Skip to content

armgit / Orkas

Public Imported from GitHub
0

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

Strengthen native runtime provisioning and validation

wyt163877b53137
diff --git a/.gitignore b/.gitignore
index f3565bfb..911ef684 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,9 +12,11 @@
/resources/runtime/ffmpeg
/resources/runtime/whisper
/resources/runtime/vc
+/resources/runtime/phone-passkey/
/src/main/native/build/
/playwright-report/
/test-results/
*.pyc
__pycache__/
/userWorkSpace
+/.cache/
diff --git a/bin/native-package-gate.cjs b/bin/native-package-gate.cjs
index 1a7df0e3..55c312f0 100644
--- a/bin/native-package-gate.cjs
+++ b/bin/native-package-gate.cjs
@@ -80,11 +80,13 @@ function sharpNativeContract(platform, arch) {
id: 'sharp-binding',
candidates: mac
? [
+ `@img/sharp-darwin-${arch}/lib/sharp-darwin-${arch}-0.35.5.node`,
`@img/sharp-darwin-${arch}/lib/sharp-darwin-${arch}-0.35.4.node`,
`@img/sharp-darwin-${arch}/lib/sharp-darwin-${arch}-0.35.3.node`,
`@img/sharp-darwin-${arch}/lib/sharp-darwin-${arch}.node`,
]
: [
+ '@img/sharp-win32-x64/lib/sharp-win32-x64-0.35.5.node',
'@img/sharp-win32-x64/lib/sharp-win32-x64-0.35.4.node',
'@img/sharp-win32-x64/lib/sharp-win32-x64-0.35.3.node',
'@img/sharp-win32-x64/lib/sharp-win32-x64.node',
@@ -94,11 +96,13 @@ function sharpNativeContract(platform, arch) {
id: 'sharp-libvips-cpp',
candidates: mac
? [
+ `@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.7.dylib`,
`@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.6.dylib`,
`@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.3.dylib`,
`@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.17.3.dylib`,
]
: [
+ '@img/sharp-win32-x64/lib/libvips-cpp-8.18.7.dll',
'@img/sharp-win32-x64/lib/libvips-cpp-8.18.6.dll',
'@img/sharp-win32-x64/lib/libvips-cpp-8.18.3.dll',
'@img/sharp-win32-x64/lib/libvips-cpp-8.17.3.dll',
diff --git a/bin/packaged-entrypoint-gate.cjs b/bin/packaged-entrypoint-gate.cjs
index 1f8557f3..20e519ae 100644
--- a/bin/packaged-entrypoint-gate.cjs
+++ b/bin/packaged-entrypoint-gate.cjs
@@ -111,6 +111,7 @@ const PACKAGED_BIN_ENTRYPOINTS = Object.freeze([
// surfaces themselves. App-owned connector entrypoints load this proxy
// bootstrap so their fetch can follow the route selected by Electron main.
const PACKAGED_BIN_HELPERS = Object.freeze([
+ 'local-cli-lark-permission-contract.json',
// Shared automation schema loaded by both the packaged Orkas bridge and
// the in-process auto_tasks tool.
'auto-tasks-contract.cjs',
@@ -119,6 +120,9 @@ const PACKAGED_BIN_HELPERS = Object.freeze([
// Loaded by the retained Google Workspace bundle, never a standalone catalog transport.
'gmail-mcp-server.cjs',
'bridge-tool-input.cjs',
+ 'skill-esm-loader.cjs',
+ 'tool-input-compat.cjs',
+ 'browser-tool-contract.cjs',
'connector-discovery-contract.cjs',
// Lark CLI shortcut contract required by local-cli-mcp-server.cjs.
'local-cli-lark.cjs',
@@ -212,6 +216,7 @@ const PACKAGED_BIN_HELPERS = Object.freeze([
const DORMANT_BIN_FILES = Object.freeze([]);
const BUILD_ONLY_BIN_FILES = Object.freeze([
+ 'tool-input-compat.d.cts',
'builtin-resource-gate.cjs',
'ensure-runtime.cjs',
'native-package-gate.cjs',
@@ -241,6 +246,8 @@ const PACKAGED_JS_LOADER_FILES = Object.freeze([
// proxy-bootstrap.cjs.
const PACKAGED_MCP_RUNTIME_UNPACK_GLOBS = Object.freeze([
'node_modules/@modelcontextprotocol/sdk/**/*',
+ 'node_modules/@modelcontextprotocol/server/**/*',
+ 'node_modules/@modelcontextprotocol/core/**/*',
'node_modules/ajv/**/*',
'node_modules/ajv-formats/**/*',
'node_modules/zod/**/*',
@@ -258,6 +265,10 @@ const PACKAGED_MCP_RUNTIME_UNPACK_GLOBS = Object.freeze([
]);
const PACKAGED_MCP_RUNTIME_FILES = Object.freeze([
+ { lockPath: 'node_modules/@modelcontextprotocol/server', packageName: '@modelcontextprotocol/server', entries: ['dist/index.cjs', 'dist/stdio.cjs'] },
+ { lockPath: 'node_modules/@modelcontextprotocol/core', packageName: '@modelcontextprotocol/core', entries: ['dist/index.cjs'] },
+ { lockPath: 'node_modules/@modelcontextprotocol/server/node_modules/zod', packageName: 'zod', entries: ['index.cjs', 'v4/index.cjs'] },
+ { lockPath: 'node_modules/@modelcontextprotocol/core/node_modules/zod', packageName: 'zod', entries: ['index.cjs', 'v4/index.cjs'] },
{
lockPath: 'node_modules/@modelcontextprotocol/sdk',
packageName: '@modelcontextprotocol/sdk',
@@ -516,6 +527,28 @@ function verifyRuntimeConsumerReferences(projectRoot) {
}
}
+// Development and beforePack share the executable bridge dependency check.
+// These packages are pure JS; the same lock/version contract serves all targets.
+function verifyBridgeSdkRuntime(projectRoot) {
+ const packageLock = readJson('package-lock.json', path.join(projectRoot, 'package-lock.json'));
+ const bridgePackages = PACKAGED_MCP_RUNTIME_FILES.filter(spec =>
+ spec.lockPath.startsWith('node_modules/@modelcontextprotocol/server')
+ || spec.lockPath.startsWith('node_modules/@modelcontextprotocol/core')
+ || spec.packageName === 'zod-to-json-schema');
+ for (const spec of bridgePackages) {
+ const installed = readJson(`${spec.lockPath} package.json`, path.join(projectRoot, spec.lockPath, 'package.json'));
+ if (installed.version !== packageLockPathVersion(packageLock, spec.lockPath)) {
+ throw new Error(`[packaged-entrypoint-gate] bridge dependency ${spec.lockPath} does not match package-lock.json`);
+ }
+ }
+ const fromProject = Module.createRequire(path.join(projectRoot, 'package.json'));
+ if (typeof fromProject('@modelcontextprotocol/server').McpServer !== 'function'
+ || typeof fromProject('@modelcontextprotocol/server/stdio').serveStdio !== 'function'
+ || typeof fromProject('zod-to-json-schema').zodToJsonSchema !== 'function') {
+ throw new Error('[packaged-entrypoint-gate] bridge dependency exports are unavailable');
+ }
+}
+
function verifySourceEntrypointContract(projectRoot) {
projectRoot = path.resolve(projectRoot);
const expected = [
@@ -527,7 +560,14 @@ function verifySourceEntrypointContract(projectRoot) {
assertExactFiles('source bin directory', sourceBinFiles(projectRoot), expected);
for (const name of expected) {
- assertCommonJsSyntax(`source bin/${name}`, path.join(projectRoot, 'bin', name));
+ // Type declarations are build inputs, never executable CommonJS payloads.
+ if (BUILD_ONLY_BIN_FILES.includes(name) && name.endsWith('.d.cts')) {
+ requiredFile(`source bin/${name}`, path.join(projectRoot, 'bin', name));
+ } else if (name.endsWith('.json')) {
+ readJson(`source bin/${name}`, path.join(projectRoot, 'bin', name));
+ } else {
+ assertCommonJsSyntax(`source bin/${name}`, path.join(projectRoot, 'bin', name));
+ }
}
const packageJson = readJson('package.json', path.join(projectRoot, 'package.json'));
@@ -675,7 +715,8 @@ function verifyPackagedEntrypointPayload(pcRoot, options = {}) {
for (const name of PACKAGED_BIN_HELPERS) {
const file = path.join(binRoot, name);
requiredFile(`runtime helper bin/${name}`, file);
- assertCommonJsSyntax(`runtime helper bin/${name}`, file);
+ if (name.endsWith('.json')) readJson(`runtime helper bin/${name}`, file);
+ else assertCommonJsSyntax(`runtime helper bin/${name}`, file);
verified.push(`helper:bin/${name}`);
}
@@ -748,4 +789,5 @@ module.exports = {
verifyPackagedConnectorRuntime,
verifyPackagedEntrypointPayload,
verifySourceEntrypointContract,
+ verifyBridgeSdkRuntime,
};
diff --git a/bin/packaged-resource-gate.cjs b/bin/packaged-resource-gate.cjs
index d582e07b..64fb6f8a 100644
--- a/bin/packaged-resource-gate.cjs
+++ b/bin/packaged-resource-gate.cjs
@@ -61,114 +61,149 @@ const EMBEDDING_MODEL_CONTRACT = Object.freeze({
const MAC_LOCALIZED_METADATA_CONTRACT = Object.freeze([
Object.freeze({
- directory: 'en.lproj',
+ directory: "en.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: 'Orkas uses the microphone for voice input.',
+ NSBluetoothAlwaysUsageDescription: "Orkas uses Bluetooth to verify that your passkey phone is nearby.",
+ NSMicrophoneUsageDescription: "Orkas uses the microphone for voice input and websites you authorize.",
+ NSCameraUsageDescription: "Orkas lets websites use the camera with your permission.",
}),
}),
Object.freeze({
- directory: 'ja.lproj',
+ directory: "ja.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: 'Orkas は音声入力にマイクを使用します。',
+ NSBluetoothAlwaysUsageDescription: "Orkas は Bluetooth を使用して、パスキーを保存したスマートフォンが近くにあることを確認します。",
+ NSMicrophoneUsageDescription: "Orkas は音声入力と許可したウェブサイトでマイクを使用します。",
+ NSCameraUsageDescription: "Orkas は許可を得てウェブサイトでカメラを使用します。",
}),
}),
Object.freeze({
- directory: 'zh-Hans.lproj',
+ directory: "zh-Hans.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: 'Orkas 需要使用麦克风进行语音输入。',
+ NSBluetoothAlwaysUsageDescription: "Orkas 使用蓝牙确认保存通行密钥的手机在附近。",
+ NSMicrophoneUsageDescription: "Orkas 使用麦克风进行语音输入,并供你授权的网站使用。",
+ NSCameraUsageDescription: "Orkas 经你允许后,让网站使用摄像头。",
}),
}),
Object.freeze({
directory: "es.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas usa el micrófono para la entrada de voz.",
+ NSBluetoothAlwaysUsageDescription: "Orkas usa Bluetooth para comprobar que el teléfono con tu clave de acceso está cerca.",
+ NSMicrophoneUsageDescription: "Orkas usa el micrófono para la entrada de voz y los sitios que autorizas.",
+ NSCameraUsageDescription: "Orkas permite que los sitios usen la cámara con tu permiso.",
}),
}),
Object.freeze({
directory: "fr.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas utilise le microphone pour la saisie vocale.",
+ NSBluetoothAlwaysUsageDescription: "Orkas utilise le Bluetooth pour vérifier que le téléphone contenant votre clé d’accès est à proximité.",
+ NSMicrophoneUsageDescription: "Orkas utilise le microphone pour la saisie vocale et les sites que vous autorisez.",
+ NSCameraUsageDescription: "Orkas permet aux sites d’utiliser la caméra avec votre autorisation.",
}),
}),
Object.freeze({
directory: "ko.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas는 음성 입력에 마이크를 사용합니다.",
+ NSBluetoothAlwaysUsageDescription: "Orkas는 Bluetooth로 패스키가 저장된 휴대폰이 근처에 있는지 확인합니다.",
+ NSMicrophoneUsageDescription: "Orkas는 음성 입력과 사용자가 허용한 웹사이트에 마이크를 사용합니다.",
+ NSCameraUsageDescription: "Orkas는 사용자의 허락을 받아 웹사이트에서 카메라를 사용합니다.",
}),
}),
Object.freeze({
directory: "de.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas verwendet das Mikrofon für die Spracheingabe.",
+ NSBluetoothAlwaysUsageDescription: "Orkas verwendet Bluetooth, um zu prüfen, ob Ihr Telefon mit dem Passkey in der Nähe ist.",
+ NSMicrophoneUsageDescription: "Orkas verwendet das Mikrofon für die Spracheingabe und von Ihnen autorisierte Websites.",
+ NSCameraUsageDescription: "Orkas erlaubt Websites mit Ihrer Zustimmung den Kamerazugriff.",
}),
}),
Object.freeze({
directory: "ru.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas использует микрофон для голосового ввода.",
+ NSBluetoothAlwaysUsageDescription: "Orkas использует Bluetooth, чтобы убедиться, что телефон с ключом доступа находится рядом.",
+ NSMicrophoneUsageDescription: "Orkas использует микрофон для голосового ввода и сайтов, которым вы дали разрешение.",
+ NSCameraUsageDescription: "Orkas позволяет сайтам использовать камеру с вашего разрешения.",
}),
}),
Object.freeze({
directory: "it.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas usa il microfono per l’inserimento vocale.",
+ NSBluetoothAlwaysUsageDescription: "Orkas usa Bluetooth per verificare che il telefono con la tua passkey sia nelle vicinanze.",
+ NSMicrophoneUsageDescription: "Orkas usa il microfono per l’inserimento vocale e i siti che autorizzi.",
+ NSCameraUsageDescription: "Orkas consente ai siti di usare la fotocamera con la tua autorizzazione.",
}),
}),
Object.freeze({
directory: "hi.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas वॉइस इनपुट के लिए माइक्रोफ़ोन का उपयोग करता है।",
+ NSBluetoothAlwaysUsageDescription: "Orkas ब्लूटूथ से पुष्टि करता है कि आपकी पासकी वाला फ़ोन पास में है।",
+ NSMicrophoneUsageDescription: "Orkas वॉइस इनपुट और आपके अनुमति दिए गए वेबसाइटों के लिए माइक्रोफ़ोन का उपयोग करता है।",
+ NSCameraUsageDescription: "Orkas आपकी अनुमति से वेबसाइटों को कैमरा इस्तेमाल करने देता है।",
}),
}),
Object.freeze({
directory: "id.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas menggunakan mikrofon untuk input suara.",
+ NSBluetoothAlwaysUsageDescription: "Orkas menggunakan Bluetooth untuk memastikan ponsel dengan kunci sandi Anda berada di dekat Anda.",
+ NSMicrophoneUsageDescription: "Orkas menggunakan mikrofon untuk input suara dan situs yang Anda izinkan.",
+ NSCameraUsageDescription: "Orkas mengizinkan situs menggunakan kamera dengan izin Anda.",
}),
}),
Object.freeze({
directory: "th.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas ใช้ไมโครโฟนสำหรับการป้อนข้อมูลด้วยเสียง",
+ NSBluetoothAlwaysUsageDescription: "Orkas ใช้บลูทูธเพื่อยืนยันว่าโทรศัพท์ที่เก็บพาสคีย์อยู่ใกล้คุณ",
+ NSMicrophoneUsageDescription: "Orkas ใช้ไมโครโฟนสำหรับการป้อนข้อมูลด้วยเสียงและเว็บไซต์ที่คุณอนุญาต",
+ NSCameraUsageDescription: "Orkas ให้เว็บไซต์ใช้กล้องเมื่อคุณอนุญาต",
}),
}),
Object.freeze({
directory: "tr.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas, sesli giriş için mikrofonu kullanır.",
+ NSBluetoothAlwaysUsageDescription: "Orkas, geçiş anahtarınızın bulunduğu telefonun yakında olduğunu doğrulamak için Bluetooth kullanır.",
+ NSMicrophoneUsageDescription: "Orkas, sesli giriş ve izin verdiğiniz siteler için mikrofonu kullanır.",
+ NSCameraUsageDescription: "Orkas, izninizle sitelerin kamerayı kullanmasına olanak tanır.",
}),
}),
Object.freeze({
directory: "vi.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas sử dụng micrô để nhập liệu bằng giọng nói.",
+ NSBluetoothAlwaysUsageDescription: "Orkas dùng Bluetooth để xác nhận điện thoại lưu khóa truy cập của bạn ở gần.",
+ NSMicrophoneUsageDescription: "Orkas sử dụng micrô để nhập liệu bằng giọng nói và cho các trang web bạn cho phép.",
+ NSCameraUsageDescription: "Orkas cho phép trang web sử dụng máy ảnh khi bạn đồng ý.",
}),
}),
Object.freeze({
directory: "zh-Hant.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas 會使用麥克風進行語音輸入。",
+ NSBluetoothAlwaysUsageDescription: "Orkas 使用藍牙確認儲存通行密鑰的手機在附近。",
+ NSMicrophoneUsageDescription: "Orkas 使用麥克風進行語音輸入,並供你授權的網站使用。",
+ NSCameraUsageDescription: "Orkas 經你允許後,讓網站使用攝影機。",
}),
}),
Object.freeze({
directory: "pt-PT.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "O Orkas utiliza o microfone para a entrada de voz.",
+ NSBluetoothAlwaysUsageDescription: "O Orkas utiliza Bluetooth para confirmar que o telemóvel com a sua chave de acesso está por perto.",
+ NSMicrophoneUsageDescription: "O Orkas utiliza o microfone para a entrada de voz e os sites que autoriza.",
+ NSCameraUsageDescription: "Orkas permite que os sites usem a câmara com a sua permissão.",
}),
}),
Object.freeze({
directory: "es-419.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "Orkas usa el micrófono para la entrada de voz.",
+ NSBluetoothAlwaysUsageDescription: "Orkas usa Bluetooth para comprobar que el teléfono con tu clave de acceso está cerca.",
+ NSMicrophoneUsageDescription: "Orkas usa el micrófono para la entrada de voz y los sitios que autorizas.",
+ NSCameraUsageDescription: "Orkas permite que los sitios usen la cámara con tu permiso.",
}),
}),
Object.freeze({
directory: "ar.lproj",
values: Object.freeze({
- NSMicrophoneUsageDescription: "يستخدم Orkas الميكروفون للإدخال الصوتي.",
+ NSBluetoothAlwaysUsageDescription: "يستخدم Orkas البلوتوث للتأكد من أن الهاتف الذي يحفظ مفتاح المرور قريب منك.",
+ NSMicrophoneUsageDescription: "يستخدم Orkas الميكروفون للإدخال الصوتي والمواقع التي تسمح لها.",
+ NSCameraUsageDescription: "يسمح Orkas للمواقع باستخدام الكاميرا بإذنك.",
}),
}),
-
]);
const MAC_LOCALIZED_METADATA_FILTERS = Object.freeze(
diff --git a/bin/runtime-gate.cjs b/bin/runtime-gate.cjs
index 073c5eed..5749ea36 100644
--- a/bin/runtime-gate.cjs
+++ b/bin/runtime-gate.cjs
@@ -10,7 +10,7 @@ const path = require('node:path');
// different, but pruning, post-pack verification, release validation, and cache
// isolation must all consume these exported lists instead of copying them.
const MANIFEST_RUNTIME_KINDS = ['python', 'uv', 'node'];
-const PACKAGED_RUNTIME_KINDS = [...MANIFEST_RUNTIME_KINDS, 'ffmpeg', 'whisper', 'vc'];
+const PACKAGED_RUNTIME_KINDS = [...MANIFEST_RUNTIME_KINDS, 'ffmpeg', 'whisper', 'vc', 'phone-passkey'];
const FFMPEG_CAPABILITIES = ['libass', 'ass', 'subtitles'];
const WINDOWS_VC_RUNTIME_CONTRACT = Object.freeze({
schema: 1,
@@ -783,11 +783,39 @@ function verifyWindowsVcExtraFilesConfig(winConfig) {
return true;
}
+function verifyPhonePasskeyRuntimeDir(runtimeRoot, targetPlatform, targetArch, options = {}) {
+ if (targetPlatform !== 'darwin') throw new Error('[native-deps-gate] phone passkey helper is Mac-only');
+ const key = runtimeKey(targetPlatform, targetArch);
+ requireOnlyRuntimeDirs(runtimeRoot, 'phone-passkey', options.allowedKeys || [key]);
+ const dir = path.join(runtimeRoot, 'phone-passkey', key);
+ const marker = readJsonFile('phone passkey marker', path.join(dir, '.orkas-phone-passkey.json'));
+ if (marker.schema !== 1 || marker.protocol !== 1 || marker.platformKey !== key
+ || !/^[a-f0-9]{64}$/.test(marker.source || '')) throw new Error('[native-deps-gate] phone passkey marker mismatch');
+ const files = marker.files || {};
+ for (const name of ['orkas-phone-passkey', 'NOTICE.txt', 'webauthn-source.tar.gz', 'licenses/OpenSSL-LICENSE.txt']) {
+ if (!files[name]) throw new Error('[native-deps-gate] incomplete phone passkey runtime');
+ }
+ if (!Object.keys(files).some(name => name.startsWith('licenses/'))) throw new Error('[native-deps-gate] phone passkey licenses missing');
+ for (const [name, expected] of Object.entries(files)) {
+ if (path.isAbsolute(name) || name.split(/[\\/]/).some(part => !part || part === '..' || part === '.')) {
+ throw new Error('[native-deps-gate] invalid phone passkey runtime file');
+ }
+ const file = path.join(dir, name);
+ requiredFile('phone passkey runtime file', file);
+ const matches = expected.bytes === fs.statSync(file).size && expected.sha256 === sha256File(file);
+ if (!matches && (name !== 'orkas-phone-passkey' || !acceptSignedDarwinRuntimeMutation(file, targetPlatform, options))) {
+ throw new Error('[native-deps-gate] phone passkey runtime checksum mismatch');
+ }
+ }
+ const binary = path.join(dir, 'orkas-phone-passkey');
+ assertExecutableArch(binary, targetPlatform, targetArch, options);
+ return binary;
+}
+
function requiredRuntimeVerificationEntries(targetPlatform, targetArch) {
const key = runtimeKey(targetPlatform, targetArch);
- const kinds = targetPlatform === 'win32'
- ? PACKAGED_RUNTIME_KINDS
- : PACKAGED_RUNTIME_KINDS.filter(kind => kind !== 'vc');
+ const kinds = PACKAGED_RUNTIME_KINDS.filter(kind => (kind !== 'vc' || targetPlatform === 'win32')
+ && (kind !== 'phone-passkey' || targetPlatform === 'darwin'));
return kinds.map(kind => `runtime:${kind}:${key}`);
}
@@ -816,6 +844,10 @@ function verifyRuntimeRoot(runtimeRoot, targetPlatform, targetArch, options = {}
verified.push(`runtime:ffmpeg:${key}`);
verifyWhisperRuntimeDir(runtimeRoot, targetPlatform, targetArch, { ...options, allowedKeys });
verified.push(`runtime:whisper:${key}`);
+ if (targetPlatform === 'darwin') {
+ verifyPhonePasskeyRuntimeDir(runtimeRoot, targetPlatform, targetArch, { ...options, allowedKeys });
+ verified.push(`runtime:phone-passkey:${key}`);
+ }
if (targetPlatform === 'win32') {
verifyWindowsVcRuntimeDir(runtimeRoot, targetPlatform, targetArch, { ...options, allowedKeys });
verified.push(`runtime:vc:${key}`);
@@ -832,6 +864,7 @@ function verifyRuntimeRoot(runtimeRoot, targetPlatform, targetArch, options = {}
}
module.exports = {
+ verifyPhonePasskeyRuntimeDir,
FFMPEG_CAPABILITIES,
WHISPER_RUNTIME_CONTRACT,
WINDOWS_VC_RUNTIME_CONTRACT,
diff --git a/package-lock.json b/package-lock.json
index c9c5f4dc..88930295 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,8 +10,9 @@
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
- "@earendil-works/pi-ai": "^0.99.1",
- "@modelcontextprotocol/sdk": "^1.29.0",
+ "@earendil-works/pi-ai": "^1.2.0",
+ "@modelcontextprotocol/sdk": "^1.31.0",
+ "@modelcontextprotocol/server": "2.3.1",
"adm-zip": "^0.6.1",
"async-mutex": "^0.5.0",
"better-sqlite3": "^12.11.1",
@@ -23,12 +24,13 @@
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^6.2.108",
"quickjs-emscripten": "0.32.0",
- "sharp": "^0.35.4",
+ "sharp": "^0.35.5",
"socks-proxy-agent": "^8.0.5",
"sqlite-vec": "^0.1.9",
"tsx": "^4.21.0",
"undici": "^7.30.0",
- "zod": "^3.24.0"
+ "zod": "^3.24.0",
+ "zod-to-json-schema": "3.25.2"
},
"devDependencies": {
"@electron/asar": "3.4.1",
@@ -51,9 +53,9 @@
}
},
"node_modules/@anthropic-ai/sdk": {
- "version": "0.124.0",
- "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.124.0.tgz",
- "integrity": "sha512-cN5O8i9UVxHeOQAzj/XjshWXG8KiibJDw9OGpH2Z/eR3n/RBxdoLxDJOcfqAJWvjaMDFfHTBADU04hWRJVkDyA==",
+ "version": "0.129.0",
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz",
+ "integrity": "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==",
"license": "MIT",
"dependencies": {
"json-schema-to-ts": "^3.1.1",
@@ -619,14 +621,14 @@
}
},
"node_modules/@earendil-works/pi-ai": {
- "version": "0.99.1",
- "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-0.99.1.tgz",
- "integrity": "sha512-4nV9JKc94iPX8bwdGPc2nTuVPKIPsffhnp3WoN9NYCNqbtoOF8LhYcIs/+Sn/alroqJK/5QRu6/Z6Ck+n0hyBA==",
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.2.0.tgz",
+ "integrity": "sha512-U5/1zXqfV1on7/9sbez03tT4Ru49Lvfb4+zXSDK3DBKF5cRk6KxvAOTOY3HJ4jimlZth+rs7vbJqN6iBQAoNuQ==",
"license": "MIT",
"dependencies": {
- "@anthropic-ai/sdk": "0.124.0",
+ "@anthropic-ai/sdk": "0.129.0",
"@aws-sdk/client-bedrock-runtime": "3.1127.0",
- "@earendil-works/pi-telemetry": "^0.99.1",
+ "@earendil-works/pi-telemetry": "^1.2.0",
"@google/genai": "2.21.0",
"@smithy/node-http-handler": "4.12.1",
"http-proxy-agent": "9.1.0",
@@ -643,9 +645,9 @@
}
},
"node_modules/@earendil-works/pi-telemetry": {
- "version": "0.99.1",
- "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-0.99.1.tgz",
- "integrity": "sha512-9PBPjGk+TXRtuMianpqBbHBpYpyKusESF6rwdmgD0WTZSTUQXhcKEO0hAINRLuSwy4V7yPvXV+EVV0ONY7mbpQ==",
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.2.0.tgz",
+ "integrity": "sha512-NZ3aJE6dr7aTgzzXDe53OW7BsAsF8ZUKHPJTtnjaQcxtlagkUT0Ew8Qas0EvYQsZqR/KpF1lB+z209XBzIC7xg==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
@@ -1406,9 +1408,9 @@
}
},
"node_modules/@img/sharp-darwin-arm64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.4.tgz",
- "integrity": "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
"cpu": [
"arm64"
],
@@ -1424,13 +1426,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-darwin-arm64": "1.3.3"
+ "@img/sharp-libvips-darwin-arm64": "1.3.4"
}
},
"node_modules/@img/sharp-darwin-x64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.4.tgz",
- "integrity": "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
"cpu": [
"x64"
],
@@ -1446,20 +1448,20 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-darwin-x64": "1.3.3"
+ "@img/sharp-libvips-darwin-x64": "1.3.4"
}
},
"node_modules/@img/sharp-freebsd-wasm32": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.4.tgz",
- "integrity": "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
"license": "Apache-2.0",
"optional": true,
"os": [
"freebsd"
],
"dependencies": {
- "@img/sharp-wasm32": "0.35.4"
+ "@img/sharp-wasm32": "0.35.5"
},
"engines": {
"node": ">=20.9.0"
@@ -1469,9 +1471,9 @@
}
},
"node_modules/@img/sharp-libvips-darwin-arm64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.3.tgz",
- "integrity": "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
"cpu": [
"arm64"
],
@@ -1485,9 +1487,9 @@
}
},
"node_modules/@img/sharp-libvips-darwin-x64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.3.tgz",
- "integrity": "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
"cpu": [
"x64"
],
@@ -1501,9 +1503,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-arm": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.3.tgz",
- "integrity": "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
"cpu": [
"arm"
],
@@ -1517,9 +1519,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-arm64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.3.tgz",
- "integrity": "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
"cpu": [
"arm64"
],
@@ -1533,9 +1535,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-ppc64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.3.tgz",
- "integrity": "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
"cpu": [
"ppc64"
],
@@ -1549,9 +1551,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-riscv64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.3.tgz",
- "integrity": "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
"cpu": [
"riscv64"
],
@@ -1565,9 +1567,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-s390x": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.3.tgz",
- "integrity": "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
"cpu": [
"s390x"
],
@@ -1581,9 +1583,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.3.tgz",
- "integrity": "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
"cpu": [
"x64"
],
@@ -1597,9 +1599,9 @@
}
},
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.3.tgz",
- "integrity": "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
"cpu": [
"arm64"
],
@@ -1613,9 +1615,9 @@
}
},
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
- "version": "1.3.3",
- "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.3.tgz",
- "integrity": "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==",
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
"cpu": [
"x64"
],
@@ -1629,9 +1631,9 @@
}
},
"node_modules/@img/sharp-linux-arm": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.4.tgz",
- "integrity": "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
"cpu": [
"arm"
],
@@ -1647,13 +1649,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linux-arm": "1.3.3"
+ "@img/sharp-libvips-linux-arm": "1.3.4"
}
},
"node_modules/@img/sharp-linux-arm64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.4.tgz",
- "integrity": "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
"cpu": [
"arm64"
],
@@ -1669,13 +1671,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linux-arm64": "1.3.3"
+ "@img/sharp-libvips-linux-arm64": "1.3.4"
}
},
"node_modules/@img/sharp-linux-ppc64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.4.tgz",
- "integrity": "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
"cpu": [
"ppc64"
],
@@ -1691,13 +1693,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linux-ppc64": "1.3.3"
+ "@img/sharp-libvips-linux-ppc64": "1.3.4"
}
},
"node_modules/@img/sharp-linux-riscv64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.4.tgz",
- "integrity": "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
"cpu": [
"riscv64"
],
@@ -1713,13 +1715,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linux-riscv64": "1.3.3"
+ "@img/sharp-libvips-linux-riscv64": "1.3.4"
}
},
"node_modules/@img/sharp-linux-s390x": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.4.tgz",
- "integrity": "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
"cpu": [
"s390x"
],
@@ -1735,13 +1737,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linux-s390x": "1.3.3"
+ "@img/sharp-libvips-linux-s390x": "1.3.4"
}
},
"node_modules/@img/sharp-linux-x64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.4.tgz",
- "integrity": "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
"cpu": [
"x64"
],
@@ -1757,13 +1759,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linux-x64": "1.3.3"
+ "@img/sharp-libvips-linux-x64": "1.3.4"
}
},
"node_modules/@img/sharp-linuxmusl-arm64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.4.tgz",
- "integrity": "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
"cpu": [
"arm64"
],
@@ -1779,13 +1781,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linuxmusl-arm64": "1.3.3"
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
}
},
"node_modules/@img/sharp-linuxmusl-x64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.4.tgz",
- "integrity": "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
"cpu": [
"x64"
],
@@ -1801,13 +1803,13 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-libvips-linuxmusl-x64": "1.3.3"
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
}
},
"node_modules/@img/sharp-wasm32": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.4.tgz",
- "integrity": "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
"dependencies": {
@@ -1821,16 +1823,16 @@
}
},
"node_modules/@img/sharp-webcontainers-wasm32": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.4.tgz",
- "integrity": "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
"cpu": [
"wasm32"
],
"license": "Apache-2.0",
"optional": true,
"dependencies": {
- "@img/sharp-wasm32": "0.35.4"
+ "@img/sharp-wasm32": "0.35.5"
},
"engines": {
"node": ">=20.9.0"
@@ -1840,9 +1842,9 @@
}
},
"node_modules/@img/sharp-win32-arm64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.4.tgz",
- "integrity": "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
"cpu": [
"arm64"
],
@@ -1859,9 +1861,9 @@
}
},
"node_modules/@img/sharp-win32-ia32": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.4.tgz",
- "integrity": "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
"cpu": [
"ia32"
],
@@ -1878,9 +1880,9 @@
}
},
"node_modules/@img/sharp-win32-x64": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.4.tgz",
- "integrity": "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
"cpu": [
"x64"
],
@@ -2413,13 +2415,34 @@
"node": ">= 12.13.0"
}
},
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz",
+ "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core/node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
"node_modules/@modelcontextprotocol/sdk": {
- "version": "1.29.0",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
- "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",
+ "version": "1.31.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.31.0.tgz",
+ "integrity": "sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==",
"license": "MIT",
"dependencies": {
- "@hono/node-server": "^1.19.9",
+ "@hono/node-server": "^1.19.9 || ^2.0.5",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
"content-type": "^1.0.5",
@@ -2492,6 +2515,28 @@
"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
"license": "BSD-2-Clause"
},
+ "node_modules/@modelcontextprotocol/server": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz",
+ "integrity": "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/server/node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
"node_modules/@napi-rs/canvas": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.3.tgz",
@@ -6490,9 +6535,9 @@
}
},
"node_modules/proxy-addr": {
- "version": "2.0.7",
- "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
- "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "version": "2.0.8",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
+ "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
@@ -6500,6 +6545,10 @@
},
"engines": {
"node": ">= 0.10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
}
},
"node_modules/proxy-agent-negotiate": {
@@ -6865,9 +6914,9 @@
"license": "ISC"
},
"node_modules/sharp": {
- "version": "0.35.4",
- "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.4.tgz",
- "integrity": "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==",
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
"license": "Apache-2.0",
"dependencies": {
"@img/colour": "^1.1.0",
@@ -6881,31 +6930,31 @@
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
- "@img/sharp-darwin-arm64": "0.35.4",
- "@img/sharp-darwin-x64": "0.35.4",
- "@img/sharp-freebsd-wasm32": "0.35.4",
- "@img/sharp-libvips-darwin-arm64": "1.3.3",
- "@img/sharp-libvips-darwin-x64": "1.3.3",
- "@img/sharp-libvips-linux-arm": "1.3.3",
- "@img/sharp-libvips-linux-arm64": "1.3.3",
- "@img/sharp-libvips-linux-ppc64": "1.3.3",
- "@img/sharp-libvips-linux-riscv64": "1.3.3",
- "@img/sharp-libvips-linux-s390x": "1.3.3",
- "@img/sharp-libvips-linux-x64": "1.3.3",
- "@img/sharp-libvips-linuxmusl-arm64": "1.3.3",
- "@img/sharp-libvips-linuxmusl-x64": "1.3.3",
- "@img/sharp-linux-arm": "0.35.4",
- "@img/sharp-linux-arm64": "0.35.4",
- "@img/sharp-linux-ppc64": "0.35.4",
- "@img/sharp-linux-riscv64": "0.35.4",
- "@img/sharp-linux-s390x": "0.35.4",
- "@img/sharp-linux-x64": "0.35.4",
- "@img/sharp-linuxmusl-arm64": "0.35.4",
- "@img/sharp-linuxmusl-x64": "0.35.4",
- "@img/sharp-webcontainers-wasm32": "0.35.4",
- "@img/sharp-win32-arm64": "0.35.4",
- "@img/sharp-win32-ia32": "0.35.4",
- "@img/sharp-win32-x64": "0.35.4"
+ "@img/sharp-darwin-arm64": "0.35.5",
+ "@img/sharp-darwin-x64": "0.35.5",
+ "@img/sharp-freebsd-wasm32": "0.35.5",
+ "@img/sharp-libvips-darwin-arm64": "1.3.4",
+ "@img/sharp-libvips-darwin-x64": "1.3.4",
+ "@img/sharp-libvips-linux-arm": "1.3.4",
+ "@img/sharp-libvips-linux-arm64": "1.3.4",
+ "@img/sharp-libvips-linux-ppc64": "1.3.4",
+ "@img/sharp-libvips-linux-riscv64": "1.3.4",
+ "@img/sharp-libvips-linux-s390x": "1.3.4",
+ "@img/sharp-libvips-linux-x64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
+ "@img/sharp-linux-arm": "0.35.5",
+ "@img/sharp-linux-arm64": "0.35.5",
+ "@img/sharp-linux-ppc64": "0.35.5",
+ "@img/sharp-linux-riscv64": "0.35.5",
+ "@img/sharp-linux-s390x": "0.35.5",
+ "@img/sharp-linux-x64": "0.35.5",
+ "@img/sharp-linuxmusl-arm64": "0.35.5",
+ "@img/sharp-linuxmusl-x64": "0.35.5",
+ "@img/sharp-webcontainers-wasm32": "0.35.5",
+ "@img/sharp-win32-arm64": "0.35.5",
+ "@img/sharp-win32-ia32": "0.35.5",
+ "@img/sharp-win32-x64": "0.35.5"
},
"peerDependenciesMeta": {
"@types/node": {
@@ -7100,9 +7149,9 @@
}
},
"node_modules/source-map-js": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
- "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
@@ -7943,6 +7992,8 @@
},
"node_modules/zod-to-json-schema": {
"version": "3.25.2",
+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
"license": "ISC",
"peerDependencies": {
"zod": "^3.25.28 || ^4"
diff --git a/package.json b/package.json
index e94f5ee1..62bcd938 100644
--- a/package.json
+++ b/package.json
@@ -25,8 +25,6 @@
"test:non-model": "npm run typecheck && npm test && npm run test:e2e:typecheck && npm run test:e2e && npm run test:platform-native && npm run smoke",
"test:js": "node scripts/run-tests.mjs run",
"test:e2e": "node scripts/run-e2e.cjs test --config playwright.config.ts",
- "test:app-template-generation": "node scripts/run-e2e.cjs test --config playwright.config.ts test/e2e/app_templates_e2e_model.spec.ts",
- "test:web-app-generation": "node scripts/run-e2e.cjs test --config playwright.config.ts test/e2e/web_app_generation_e2e_model.spec.ts",
"test:e2e:debug": "node scripts/run-e2e.cjs test --config playwright.config.ts --debug",
"test:e2e:typecheck": "tsc --noEmit --project test/e2e/tsconfig.json",
"test:e2e:update": "playwright test --config playwright.config.ts --update-snapshots",
@@ -57,7 +55,8 @@
"prepack": "node scripts/ensure-dev-dependencies.cjs && node bin/officecli-policy-gate.cjs --require-host-binary",
"native:check": "node scripts/verify-native-dependencies.cjs",
"native:repair": "node scripts/verify-native-dependencies.cjs --host-only && npm install --include=optional --no-save && node bin/ensure-runtime.cjs --kind node && npm run native:check",
- "test:web-assist-input-canary": "node test/gui/run-web-assist-input-canary.mjs"
+ "test:web-assist-input-canary": "node test/gui/run-web-assist-input-canary.mjs",
+ "test:apps:e2e": "node scripts/run-e2e.cjs test --config playwright.apps.config.ts"
},
"devDependencies": {
"@electron/asar": "3.4.1",
@@ -76,8 +75,9 @@
"vitest": "^4.1.11"
},
"dependencies": {
- "@earendil-works/pi-ai": "^0.99.1",
- "@modelcontextprotocol/sdk": "^1.29.0",
+ "@earendil-works/pi-ai": "^1.2.0",
+ "@modelcontextprotocol/sdk": "^1.31.0",
+ "@modelcontextprotocol/server": "2.3.1",
"adm-zip": "^0.6.1",
"async-mutex": "^0.5.0",
"better-sqlite3": "^12.11.1",
@@ -88,13 +88,14 @@
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^6.2.108",
"quickjs-emscripten": "0.32.0",
- "sharp": "^0.35.4",
+ "sharp": "^0.35.5",
"socks-proxy-agent": "^8.0.5",
"sqlite-vec": "^0.1.9",
"tsx": "^4.21.0",
"undici": "^7.30.0",
"zod": "^3.24.0",
- "fast-xml-parser": "5.7.3"
+ "fast-xml-parser": "5.7.3",
+ "zod-to-json-schema": "3.25.2"
},
"overrides": {
"@anush008/tokenizers": "0.6.0",
@@ -128,6 +129,7 @@
"!bin/packaged-entrypoint-gate.cjs",
"!bin/packaged-resource-gate.cjs",
"!bin/runtime-gate.cjs",
+ "!bin/tool-input-compat.d.cts",
"src/main/**/*.{js,ts,mjs,md,json}",
"resources/connectors/setup/*.md",
"src/main/native/build/*.node",
@@ -140,6 +142,8 @@
"node_modules/esbuild/**/*",
"node_modules/@esbuild/**/*",
"node_modules/@modelcontextprotocol/sdk/**/*",
+ "node_modules/@modelcontextprotocol/server/**/*",
+ "node_modules/@modelcontextprotocol/core/**/*",
"node_modules/ajv/**/*",
"node_modules/ajv-formats/**/*",
"node_modules/zod/**/*",
@@ -174,6 +178,7 @@
"asar": true,
"asarUnpack": [
"bin/**/*",
+ "src/main/features/web_apps/data-worker.js",
"src/main/native/build/*.node",
"node_modules/tsx/**/*",
"node_modules/get-tsconfig/**/*",
@@ -181,6 +186,8 @@
"node_modules/esbuild/**/*",
"node_modules/@esbuild/**/*",
"node_modules/@modelcontextprotocol/sdk/**/*",
+ "node_modules/@modelcontextprotocol/server/**/*",
+ "node_modules/@modelcontextprotocol/core/**/*",
"node_modules/ajv/**/*",
"node_modules/ajv-formats/**/*",
"node_modules/zod/**/*",
@@ -299,7 +306,11 @@
}
],
"icon": "src/resources/icons/icon.icns",
- "extendInfo": {}
+ "extendInfo": {
+ "NSMicrophoneUsageDescription": "Orkas uses the microphone for websites with your permission.",
+ "NSCameraUsageDescription": "Orkas lets websites use the camera with your permission.",
+ "NSBluetoothAlwaysUsageDescription": "Orkas uses Bluetooth to verify that your passkey phone is nearby."
+ }
},
"dmg": {
"writeUpdateInfo": false
diff --git a/playwright.release-harness.config.ts b/playwright.release-harness.config.ts
new file mode 100644
index 00000000..3e4438c1
--- /dev/null
+++ b/playwright.release-harness.config.ts
@@ -0,0 +1,28 @@
+import { defineConfig } from '@playwright/test';
+import apps from './playwright.apps.config';
+
+// Reuse owning cases; adding a detail/locale/parameter case must not silently
+// expand the release gate. The cohort test checks actual Playwright discovery
+// so renamed or missing critical journeys fail before a release run.
+const criticalAppJourneys = [
+ // Creation/editing, exactly-once dispatch and recoverable task submission.
+ 'creates a separate task once with 2 existing tasks and records bounded actions',
+ 'keeps the description in the new task when sending is rejected and supports retry',
+ 'opens safely, renames, prepares an edit, persists, and deletes a saved app',
+ // Local/cloud durability and explicit, non-destructive schema migration.
+ 'web app common data survives closing and reopening while host inference remains unavailable',
+ 'author can export, cancel, and explicitly clear incompatible local data before updating',
+ 'calibration web-app-local-data-persistence alert',
+ // Real SDK wiring, application isolation and permission lifetime.
+ 'SDK app discovers, reads a selected file, generates, exports and keeps isolated state across reopening',
+ 'SDK tools discovery and execution read the real Library without redundant app consent',
+ 'isolated origin denies forged messages, foreign data and revoked SDK calls',
+ 'app approval uses Orkas UI, lasts for this use, isolates windows and honors Trusted',
+ // Publish/manage/unpublish and recovery without inventing account quota.
+ 'publish, independent metadata, remote management and quota are usable in Electron',
+ 'publication list failure 404 shows unknown quota and retry recovers',
+];
+
+export default defineConfig(apps, {
+ grep: criticalAppJourneys.map(title => new RegExp(`(?:^| )${title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`)),
+});
diff --git a/scripts/check-prompt-commit-metadata.cjs b/scripts/check-prompt-commit-metadata.cjs
index 0e65a50c..bbf5e3b7 100644
--- a/scripts/check-prompt-commit-metadata.cjs
+++ b/scripts/check-prompt-commit-metadata.cjs
@@ -11,6 +11,14 @@ const PROMPT_PATH_PATTERNS = [
/(^|\/)prompts\/.*\.(?:md|ts|js)$/,
/(^|\/)docs\/architecture\/(?:system-prompt-engineering-contract|core-agent-runtime-engineering-contract|core-agent-tool-contract-policy)\.md$/,
/(^|\/)(?:Common\/)?docs\/reviews\/REVIEW_PROCESS\.md$/,
+ // Rule documents that resident CLAUDE.md clauses require reading in full or
+ // that automation loads on every run; editing them changes model behavior.
+ /(^|\/)Common\/docs\/(?:engineering-quality|agent-authoring|test-case-design|git-delivery)\.md$/,
+ /(^|\/)Common\/docs\/evaluation\/daily-harness-evaluation\.md$/,
+ /(^|\/)Common\/docs\/reviews\/PRODUCTION_SAMPLING_PROCESS\.md$/,
+ /(^|\/)Common\/AutoFix\/AUTOFIX_PROCESS\.md$/,
+ /(^|\/)PC\/docs\/design\/PATTERNS\.md$/,
+ /(^|\/)PC\/docs\/architecture\/(?:skill-engineering-contract\.md|core-agent-tool-approvals\.json)$/,
];
const SYSTEM_PROMPT_PATH_PATTERN = /^PC\/(?:src\/main\/prompts\/.*\.(?:md|ts|js)|resources\/builtin\/system\/skills\/.*\.md)$/;
diff --git a/scripts/ensure-dev-dependencies.cjs b/scripts/ensure-dev-dependencies.cjs
index 680e6bda..2a6c8eda 100644
--- a/scripts/ensure-dev-dependencies.cjs
+++ b/scripts/ensure-dev-dependencies.cjs
@@ -2,77 +2,93 @@
'use strict';
const path = require('node:path');
-const { spawnSync } = require('node:child_process');
+const { spawn } = require('node:child_process');
const { WHISPER_RUNTIME_CONTRACT } = require('../bin/runtime-gate.cjs');
const pcRoot = path.resolve(__dirname, '..');
function run(label, script, args = []) {
- const result = spawnSync(process.execPath, [path.join(pcRoot, script), ...args], {
- cwd: pcRoot,
- env: process.env,
- stdio: 'inherit',
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [path.join(pcRoot, script), ...args], {
+ cwd: pcRoot,
+ env: process.env,
+ stdio: 'inherit',
+ });
+ let launchError;
+ child.once('error', (error) => { launchError = error; });
+ // Wait for close even after a launch error: readiness/failure must not
+ // leave a provisioning child or its inherited output behind.
+ child.once('close', (code, signal) => {
+ if (launchError) reject(launchError);
+ else if (code !== 0) reject(new Error(`${label} failed with ${signal ? `signal ${signal}` : `status ${code}`}`));
+ else resolve();
+ });
});
- if (result.error) throw result.error;
- if (result.status !== 0) throw new Error(`${label} failed with status ${result.status}`);
}
function shouldProvisionWhisper(platform = process.platform, arch = process.arch) {
return Boolean(WHISPER_RUNTIME_CONTRACT.targets[`${platform}-${arch}`]);
}
-function main() {
- run('Node bootstrap', 'scripts/verify-native-dependencies.cjs', ['--host-only']);
- console.log(`[dev-deps] preparing built-in dependencies for ${process.platform}-${process.arch}`);
+async function main() {
+ require('../bin/packaged-resource-gate.cjs').verifyXlsReaderRoot(path.join(pcRoot, 'resources', 'xls-reader'));
+ await run('Node bootstrap', 'scripts/verify-native-dependencies.cjs', ['--host-only']);
if (process.platform === 'linux') {
- run('Linux host preflight', 'scripts/verify-linux-source-dependencies.cjs', ['--host-only']);
+ await run('Linux host preflight', 'scripts/verify-linux-source-dependencies.cjs', ['--host-only']);
}
- run('notification permission addon', 'scripts/build-notification-permission-addon.cjs', [
- '--platform', process.platform,
- '--arch', process.arch,
- ]);
- run('SQLite Electron ABI', 'scripts/ensure-sqlite-electron-abi.mjs');
- run('runtime ensure', 'bin/ensure-runtime.cjs', [
- '--root', path.join(pcRoot, 'resources', 'runtime'),
- '--platform', process.platform,
- '--arch', process.arch,
- ]);
- run('embedding model', 'scripts/fetch-embedding-model.mjs');
- run('OfficeCLI', 'scripts/fetch-officecli.cjs');
- run('FFmpeg', 'scripts/fetch-ffmpeg.cjs', ['--platform', process.platform, '--arch', process.arch]);
+ require('../bin/packaged-entrypoint-gate.cjs').verifyBridgeSdkRuntime(pcRoot);
+ console.log(`[dev-deps] preparing built-in dependencies for ${process.platform}-${process.arch}`);
if (process.platform === 'win32') {
- run('Windows VC runtime', 'scripts/fetch-win-vc-runtime.cjs', [
+ await run('Windows VC runtime', 'scripts/fetch-win-vc-runtime.cjs', [
+ '--platform', process.platform,
+ '--arch', process.arch,
+ ]);
+ }
+ // Native preparation and asset preparation own disjoint output directories.
+ // Keep their dependencies ordered within two lanes, bounding child count and
+ // I/O concurrency without skipping any readiness or self-repair checks.
+ let stopped = false;
+ async function step(...args) {
+ if (stopped) return;
+ try { await run(...args); }
+ catch (error) { stopped = true; throw error; }
+ }
+ async function prepareNative() {
+ await step('notification permission addon', 'scripts/build-notification-permission-addon.cjs', [
+ '--platform', process.platform,
+ '--arch', process.arch,
+ ]);
+ await step('SQLite Electron ABI', 'scripts/ensure-sqlite-electron-abi.mjs');
+ await step('phone passkey helper', 'scripts/build-phone-passkey.cjs', ['--platform', process.platform, '--arch', process.arch]);
+ await step('runtime ensure', 'bin/ensure-runtime.cjs', [
+ '--root', path.join(pcRoot, 'resources', 'runtime'),
'--platform', process.platform,
'--arch', process.arch,
]);
+ await step('native dependencies', 'scripts/verify-native-dependencies.cjs');
}
- run('native dependencies', 'scripts/verify-native-dependencies.cjs');
- // Whisper ships pinned prebuilt CLIs for a fixed target list only. On hosts
- // without a contract target the fetch script must keep failing (packaging
- // gates rely on that strictness); here it is simply not required — speech
- // transcription degrades to an actionable error at runtime instead.
- if (shouldProvisionWhisper(process.platform, process.arch)) {
- run('Whisper', 'scripts/fetch-whisper.cjs', [
+ async function prepareAssets() {
+ await step('embedding model', 'scripts/fetch-embedding-model.mjs');
+ await step('OfficeCLI', 'scripts/fetch-officecli.cjs');
+ await step('FFmpeg', 'scripts/fetch-ffmpeg.cjs', ['--platform', process.platform, '--arch', process.arch]);
+ if (shouldProvisionWhisper()) await step('Whisper', 'scripts/fetch-whisper.cjs', [
'--platform', process.platform,
'--arch', process.arch,
]);
- } else {
- console.log(`[dev-deps] Whisper not provisioned for ${process.platform}-${process.arch}; skipping (local speech transcription unavailable)`);
}
+ const results = await Promise.allSettled([prepareNative(), prepareAssets()]);
+ const failure = results.find(result => result.status === 'rejected');
+ if (failure) throw failure.reason;
if (process.platform === 'linux') {
- run('Linux source dependencies', 'scripts/verify-linux-source-dependencies.cjs');
+ await run('Linux source dependencies', 'scripts/verify-linux-source-dependencies.cjs');
}
console.log('[dev-deps] built-in dependencies ready');
}
module.exports = Object.freeze({ shouldProvisionWhisper });
-if (require.main === module) {
- try {
- main();
- } catch (err) {
- console.error(`[dev-deps] failed: ${err.message}`);
- process.exit(1);
- }
-}
+if (require.main === module) main().catch((err) => {
+ console.error(`[dev-deps] failed: ${err.message}`);
+ process.exit(1);
+});
diff --git a/scripts/ensure-runtime-before-pack.cjs b/scripts/ensure-runtime-before-pack.cjs
index f4c9e6db..58b6bda7 100644
--- a/scripts/ensure-runtime-before-pack.cjs
+++ b/scripts/ensure-runtime-before-pack.cjs
@@ -16,7 +16,7 @@ const {
verifyXlsReaderRoot,
verifyMacLocalizedMetadataRoot,
} = require('../bin/packaged-resource-gate.cjs');
-const { verifySourceEntrypointContract } = require('../bin/packaged-entrypoint-gate.cjs');
+const { verifySourceEntrypointContract, verifyBridgeSdkRuntime } = require('../bin/packaged-entrypoint-gate.cjs');
const { verifyBuiltinExtraResourcesConfig, verifyBuiltinRoot } = require('../bin/builtin-resource-gate.cjs');
const { verifyOfficeCliRuntimePolicy } = require('../bin/officecli-policy-gate.cjs');
@@ -68,6 +68,9 @@ module.exports = async function ensureRuntimeBeforePack(context) {
verifyOfficeCliRuntimePolicy(pcRoot);
for (const targetArch of arches) {
+ const helper = spawnSync(process.execPath, [path.join(pcRoot, 'scripts', 'build-phone-passkey.cjs'),
+ '--platform', platform, '--arch', targetArch], { cwd: pcRoot, stdio: 'inherit', env: process.env });
+ if (helper.error || helper.status !== 0) throw new Error('Phone passkey runtime provisioning failed');
const addon = spawnSync(process.execPath, [
path.join(pcRoot, 'scripts', 'build-notification-permission-addon.cjs'),
'--platform', platform,
@@ -98,6 +101,7 @@ module.exports = async function ensureRuntimeBeforePack(context) {
// tree. A new runtime entrypoint or build-only helper cannot enter a package
// until it is classified in the shared closed-world contract.
verifySourceEntrypointContract(pcRoot);
+ verifyBridgeSdkRuntime(pcRoot);
const embedding = spawnSync(process.execPath, [
path.join(pcRoot, 'scripts', 'fetch-embedding-model.mjs'),
diff --git a/scripts/model-eval-log-policy.mjs b/scripts/model-eval-log-policy.mjs
index ed1774d8..1f5d12bf 100644
--- a/scripts/model-eval-log-policy.mjs
+++ b/scripts/model-eval-log-policy.mjs
@@ -5,13 +5,19 @@ const RUNTIME_LOG_RE = /^\[\d{2}:\d{2}:\d{2}\.\d{3}\]\s+\[(debug|info|warn|error
const CASE_MARKER_RE = /^\[model-eval-case\]\s+(start|end)\s+(.+)$/;
const CASE_LOG_RE = /^\[model-eval-case-log ([A-Za-z0-9_./:-]{1,240})\] (.*)$/;
const REPORT_RE = /^report=(.+)$/;
-const ELECTRON_MACOS_TASK_POLICY_WARNING_RE = /^\[\d+:\d{4}\/\d{6}\.\d+:ERROR:base\/process\/process_mac\.cc:\d+\]\s+task_policy_set\s+TASK_(?:CATEGORY|SUPPRESSION)_POLICY:\s+\(os\/kern\)\s+invalid argument\s+\(4\)$/;
+export const ELECTRON_MACOS_TASK_POLICY_WARNING_RE = /^\[\d+:\d{4}\/\d{6}\.\d+:ERROR:base\/process\/process_mac\.cc:\d+\]\s+task_policy_set\s+TASK_(?:CATEGORY|SUPPRESSION)_POLICY:\s+\(os\/kern\)\s+invalid argument\s+\(4\)$/;
+const ELECTRON_MACOS_SPELLCHECKER_WARNING_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+ Electron\[\d+:\d+\] NSSpellServer dataFromCheckingString (?:timed out|succeeded), index is \d+$/;
/** The one runtime warning whose message can span several lines: AgentRunner
* splices a slice of the failed tool's result, newlines included. */
const TOOL_ERROR_PAYLOAD_RE = /\bTool\s+\S+\s+returned error:/i;
const STDERR_CONTEXT_CONTINUATION_RE = /^(?:\s+|\[\d+\]\s|[}\]]|\(Use\s|<\/?[a-z][\w:.-]*(?:\s[^>]*)?>?\s*$)/i;
+/** A partial line held per stream until its newline arrives. A child printing
+ * one unbounded line must not grow the coordinator; the remainder is counted
+ * as a captured but never analyzed line so the coverage gate fails. */
+const MAX_PARTIAL_LINE_CHARS = 8 * 1024 * 1024;
+
/** Exact progress records emitted by bin/ensure-runtime.cjs, not evidence that
* dependency preparation succeeded; the launcher still checks its exit status. */
function isRuntimePreparationProgress(line) {
@@ -49,6 +55,8 @@ function findingDetail(code) {
return "the Electron model-evaluation runner was terminated by an operating-system signal";
case "electron-macos-task-policy-warning":
return "Chromium could not apply a non-critical macOS task policy to a child process";
+ case "electron-macos-spellchecker-warning":
+ return "the macOS spellchecking service reported a timeout or recovery requiring review";
case "unclassified-stderr":
return "unclassified stderr is treated as a process error until explicitly classified";
case "log-coverage-gap":
@@ -88,10 +96,15 @@ function aggregateFindings(findings) {
));
}
-export function createModelEvalLogCollector(phase) {
+/** `onFinding(finding, line)` lets a caller keep its own bounded, redacted
+ * signature of the analyzed line; the collector itself never retains text. */
+export function createModelEvalLogCollector(phase, { maxLineChars = MAX_PARTIAL_LINE_CHARS, onFinding } = {}) {
const state = {
phase,
buffers: { stdout: "", stderr: "" },
+ overflow: { stdout: false, stderr: false },
+ droppedBytes: 0,
+ droppedLineCount: 0,
capturedBytes: 0,
capturedLineCount: 0,
analyzedLineCount: 0,
@@ -113,9 +126,10 @@ export function createModelEvalLogCollector(phase) {
const contexts = new Map();
let context = state;
let attribution = {};
+ let currentLine;
const addFinding = (severity, code, source) => {
- state.findings.push({
+ const finding = {
severity,
code,
count: 1,
@@ -123,7 +137,9 @@ export function createModelEvalLogCollector(phase) {
...(source ? { source } : {}),
...attribution,
detail: findingDetail(code),
- });
+ };
+ state.findings.push(finding);
+ onFinding?.(finding, currentLine);
};
const analyzeLine = (stream, rawLine) => {
@@ -138,6 +154,7 @@ export function createModelEvalLogCollector(phase) {
: key ? { caseKey: key, attribution: 'legacy-marker' }
: state.activeCases.size > 1 ? { attribution: 'ambiguous' } : {};
if (framed) line = framed[2];
+ currentLine = line;
// Continuation windows belong to one case and stream, not whichever case
// happened to emit the previous process-wide warning.
const contextKey = `${stream}:${key ?? '<unattributed>'}`;
@@ -168,9 +185,15 @@ export function createModelEvalLogCollector(phase) {
if (runtime) {
context.nodeToolPayloadRemaining = 0;
context.nodeToolDiagnostic = false;
- const level = runtime[1].toLowerCase();
+ let level = runtime[1].toLowerCase();
const source = runtime[2].trim() || "unknown";
const message = runtime[3];
+ // Electron's console bridge labels Node's process-warning protocol as
+ // error. Preserve its warning classification without excusing ordinary
+ // application errors that merely mention deprecation.
+ const nodeDeprecation = level === "error" && source === "console"
+ && /^\(node:\d+\) \[DEP\d{4}\] DeprecationWarning: /.test(message);
+ if (nodeDeprecation) level = "warn";
state.classificationCounts.runtime += 1;
state.levelCounts[level] += 1;
state.sourceCounts[source] = (state.sourceCounts[source] || 0) + 1;
@@ -179,7 +202,8 @@ export function createModelEvalLogCollector(phase) {
} else if (level === "warn") {
addFinding(
"warning",
- /tool definition description exceeds soft budget/i.test(message)
+ nodeDeprecation ? "node-deprecation-warning"
+ : /tool definition description exceeds soft budget/i.test(message)
? "tool-definition-soft-budget"
: "runtime-warning",
source,
@@ -289,6 +313,14 @@ export function createModelEvalLogCollector(phase) {
addFinding("warning", "electron-macos-task-policy-warning", "electron");
return;
}
+ if (ELECTRON_MACOS_SPELLCHECKER_WARNING_RE.test(line)) {
+ state.classificationCounts.processWarning += 1;
+ state.levelCounts.warn += 1;
+ context.stderrContext = undefined;
+ context.stderrPayload = false;
+ addFinding("warning", "electron-macos-spellchecker-warning", "electron");
+ return;
+ }
if (/model-eval Electron runner failed|failed to start .*runner/i.test(line)) {
state.classificationCounts.processError += 1;
state.levelCounts.error += 1;
@@ -325,18 +357,39 @@ export function createModelEvalLogCollector(phase) {
state.classificationCounts.other += 1;
};
+ // The end of a line that exceeded the cap: captured, never analyzed.
+ const countDroppedLine = (stream) => {
+ state.overflow[stream] = false;
+ state.capturedLineCount += 1;
+ state.streamLineCounts[stream] += 1;
+ state.droppedLineCount += 1;
+ };
+
const ingest = (stream, chunk) => {
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
state.capturedBytes += Buffer.byteLength(text, "utf8");
state.buffers[stream] += text;
const lines = state.buffers[stream].split("\n");
state.buffers[stream] = lines.pop() || "";
- for (const line of lines) analyzeLine(stream, line);
+ for (const line of lines) {
+ if (state.overflow[stream]) {
+ state.droppedBytes += Buffer.byteLength(line, "utf8");
+ countDroppedLine(stream);
+ continue;
+ }
+ analyzeLine(stream, line);
+ }
+ if (state.overflow[stream] || state.buffers[stream].length > maxLineChars) {
+ state.droppedBytes += Buffer.byteLength(state.buffers[stream], "utf8");
+ state.buffers[stream] = "";
+ state.overflow[stream] = true;
+ }
};
const finish = () => {
for (const stream of ["stdout", "stderr"]) {
- if (state.buffers[stream].length) analyzeLine(stream, state.buffers[stream]);
+ if (state.overflow[stream]) countDroppedLine(stream);
+ else if (state.buffers[stream].length) analyzeLine(stream, state.buffers[stream]);
state.buffers[stream] = "";
}
const coveragePassed = state.capturedLineCount === state.analyzedLineCount;
@@ -359,6 +412,8 @@ export function createModelEvalLogCollector(phase) {
capturedBytes: state.capturedBytes,
capturedLineCount: state.capturedLineCount,
analyzedLineCount: state.analyzedLineCount,
+ droppedLineCount: state.droppedLineCount,
+ droppedBytes: state.droppedBytes,
blankLineCount: state.blankLineCount,
classificationCounts: { ...state.classificationCounts },
levelCounts: { ...state.levelCounts },
@@ -369,7 +424,7 @@ export function createModelEvalLogCollector(phase) {
};
};
- return { ingest, finish, addFinding: (...args) => { attribution = {}; addFinding(...args); } };
+ return { ingest, finish, addFinding: (...args) => { attribution = {}; currentLine = undefined; addFinding(...args); } };
}
export function mergeModelEvalLogAnalyses(analyses) {
@@ -393,6 +448,8 @@ export function mergeModelEvalLogAnalyses(analyses) {
capturedBytes: analyses.reduce((sum, item) => sum + item.capturedBytes, 0),
capturedLineCount,
analyzedLineCount,
+ droppedLineCount: analyses.reduce((sum, item) => sum + Number(item.droppedLineCount || 0), 0),
+ droppedBytes: analyses.reduce((sum, item) => sum + Number(item.droppedBytes || 0), 0),
blankLineCount: analyses.reduce((sum, item) => sum + item.blankLineCount, 0),
classificationCounts: sumObject("classificationCounts"),
levelCounts: sumObject("levelCounts"),
diff --git a/scripts/run-platform-native-tests.mjs b/scripts/run-platform-native-tests.mjs
index 6f4f1304..800fc348 100644
--- a/scripts/run-platform-native-tests.mjs
+++ b/scripts/run-platform-native-tests.mjs
@@ -20,6 +20,7 @@ if (!['win32', 'darwin', 'linux'].includes(process.platform)) {
// runs after dependency provisioning in the platform-specific Windows and
// Linux lanes because it requires downloaded FFmpeg, model, and native payloads.
const commonSuites = [
+ 'test/main/util/ensure-dev-dependencies.test.ts',
'test/main/util/verify-native-dependencies.test.ts',
'test/main/util/ensure-sqlite-electron-abi.test.ts',
'test/main/util/inspect-canary-logs.test.ts',
@@ -46,6 +47,7 @@ const commonSuites = [
'test/main/features/local_agents/base.test.ts',
'test/main/features/local_agents/spawn-command.test.ts',
'test/main/features/local_agents/version.test.ts',
+ 'test/main/features/local_agents/upgrade.test.ts',
'test/main/util/bundled-runtime.test.ts',
'test/main/util/run-skill.test.ts',
'test/main/features/packages.test.ts',
@@ -54,6 +56,8 @@ const commonSuites = [
'test/main/features/video_studio_native_qa.test.ts',
'test/main/features/video_studio_delivery.test.ts',
'test/main/paths.test.ts',
+ 'test/main/install-data-root.test.ts',
+ 'test/main/features/web_assist_passkey.test.ts',
];
const platformSuites = process.platform === 'win32'
diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs
index caaa37fe..1ff88cea 100644
--- a/scripts/run-tests.mjs
+++ b/scripts/run-tests.mjs
@@ -10,7 +10,7 @@ import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { withWindowsGitOnPath } from './test-runtime-env.mjs';
+import { withTestPython, withWindowsGitOnPath } from './test-runtime-env.mjs';
import { formatDriftReport, installedDependencyDrift } from './check-installed-dependencies.mjs';
// A merge that advanced the lockfile leaves stale packages installed, and the
@@ -25,7 +25,7 @@ const here = dirname(fileURLToPath(import.meta.url));
const require_ = createRequire(import.meta.url);
const electronBin = require_('electron');
const vitestBin = resolve(here, '..', 'node_modules', 'vitest', 'vitest.mjs');
-const testEnvironment = withWindowsGitOnPath(process.env);
+const testEnvironment = withTestPython(withWindowsGitOnPath(process.env));
// npm appends arguments to the final shell command of a compound script.
// Own the suite here so filters reach Vitest without first running every JS
diff --git a/scripts/run-windows-native-tests.mjs b/scripts/run-windows-native-tests.mjs
index 6bcad320..538fd266 100644
--- a/scripts/run-windows-native-tests.mjs
+++ b/scripts/run-windows-native-tests.mjs
@@ -1,8 +1,11 @@
#!/usr/bin/env node
import { spawnSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { withWindowsPowerShellModules } from './test-runtime-env.mjs';
if (process.platform !== 'win32') {
console.log('[windows-native-tests] skipped: Windows-only native runtime gate');
@@ -12,6 +15,7 @@ if (process.platform !== 'win32') {
const here = dirname(fileURLToPath(import.meta.url));
const runner = resolve(here, 'run-tests.mjs');
const pcRoot = resolve(here, '..');
+const require = createRequire(import.meta.url);
function run(command, args, options) {
const result = spawnSync(command, args, options);
@@ -28,13 +32,22 @@ run('powershell.exe', [
'-NodeExe', process.execPath,
], {
cwd: pcRoot,
- env: process.env,
+ env: withWindowsPowerShellModules(process.env),
stdio: 'inherit',
timeout: 5 * 60_000,
windowsHide: true,
});
-run(process.execPath, [
+// The canary tests the full bundled Node/npm/npx payload, not a standalone
+// agent-provided Node executable that need not ship npm beside itself.
+const runtimeRoot = resolve(pcRoot, 'resources', 'runtime');
+const manifest = JSON.parse(readFileSync(resolve(runtimeRoot, 'manifest.json'), 'utf8'));
+const runtimeGate = require('../bin/runtime-gate.cjs');
+const runtimeKey = runtimeGate.runtimeKey(process.platform, process.arch);
+const bundledNode = runtimeGate.verifyRuntimeDir('node', resolve(runtimeRoot, 'node', runtimeKey),
+ runtimeKey, manifest.node, manifest.node.assets[runtimeKey], process.platform, process.arch);
+
+run(bundledNode, [
resolve(pcRoot, 'test', 'windows', 'windows-local-cli.integration.mjs'),
], {
cwd: pcRoot,
diff --git a/scripts/test-runtime-env.mjs b/scripts/test-runtime-env.mjs
index bd1712eb..62b18d09 100644
--- a/scripts/test-runtime-env.mjs
+++ b/scripts/test-runtime-env.mjs
@@ -1,5 +1,38 @@
import fs from 'node:fs';
import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+/** Keep deterministic evaluator fixtures on the same project interpreter as
+ * the test suite, including direct npm test invocations. Explicit evaluator
+ * overrides remain independent of the ordinary Python suite. */
+export function withTestPython(env, repoRoot = fileURLToPath(new URL('../../', import.meta.url)), platform = process.platform) {
+ const result = { ...env };
+ const localPython = platform === 'win32'
+ ? path.join(repoRoot, 'venv', 'Scripts', 'python.exe')
+ : path.join(repoRoot, 'venv', 'bin', 'python');
+ const python = result.ORKAS_TEST_PYTHON || (fs.existsSync(localPython) ? localPython : '');
+ if (python) {
+ result.ORKAS_TEST_PYTHON = python;
+ if (!result.ORKAS_EVAL_PYTHON) result.ORKAS_EVAL_PYTHON = python;
+ }
+ return result;
+}
+
+/** PowerShell 5.1 cannot import PowerShell 7's core modules. Native Windows
+ * lanes may be launched by pwsh, so restore the installed system module root
+ * ahead of inherited user/Core paths without changing the caller environment. */
+export function withWindowsPowerShellModules(env, platform = process.platform) {
+ const result = { ...env };
+ if (platform !== 'win32') return result;
+ const systemRoot = result.SystemRoot || result.WINDIR;
+ if (!systemRoot) return result;
+ const modules = path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'Modules');
+ if (!fs.existsSync(modules)) return result;
+ const key = Object.keys(result).find(name => name.toLowerCase() === 'psmodulepath') || 'PSModulePath';
+ const inherited = String(result[key] || '').split(';').filter(Boolean);
+ result[key] = [modules, ...inherited.filter(entry => path.resolve(entry).toLowerCase() !== path.resolve(modules).toLowerCase())].join(';');
+ return result;
+}
function environmentPathKey(env) {
return Object.keys(env).find((key) => key.toLowerCase() === 'path') || 'PATH';
diff --git a/src/main/features/client_config.ts b/src/main/features/client_config.ts
index 1c0a2d9e..1a7c5b63 100644
--- a/src/main/features/client_config.ts
+++ b/src/main/features/client_config.ts
@@ -639,7 +639,7 @@ export const DEFAULT_PROVIDER_MODELS = PUBLIC_PROVIDER_MODELS;
export const DEFAULT_IMAGE_GEN_BY_PROVIDER: Readonly<Record<string, ImageGenCapability>> = {
openai: { model: 'gpt-image-2', api: 'openai', supportsEdit: true },
- google: { model: 'gemini-3.1-flash-image-preview', api: 'gemini', supportsEdit: true },
+ google: { model: 'gemini-nano-banana-2.1', api: 'gemini', supportsEdit: true },
doubao: { model: 'doubao-seedream-5-0-lite-260128', api: 'doubao', supportsEdit: true },
};
@@ -708,6 +708,8 @@ function normalizeProviderModels(value: unknown, providerId: string): ProviderMo
const description = typeof r.description === 'string' ? r.description.trim() : undefined;
if (r.description !== undefined && (!description || description.length > 500)) return null;
const recommended = r.recommended === true;
+ const hiddenFromPicker = typeof r.hiddenFromPicker === 'boolean' ? r.hiddenFromPicker : undefined;
+ if (r.hiddenFromPicker !== undefined && hiddenFromPicker === undefined) return null;
const template = typeof r.template === 'string' && r.template.trim() ? r.template.trim() : undefined;
const contextWindow = normalizePositiveInteger(r.contextWindow);
const maxTokens = normalizePositiveInteger(r.maxTokens);
@@ -726,6 +728,7 @@ function normalizeProviderModels(value: unknown, providerId: string): ProviderMo
name,
...(description ? { description } : {}),
...(recommended ? { recommended: true } : {}),
+ ...(hiddenFromPicker !== undefined ? { hiddenFromPicker } : {}),
...(includedModels ? { includedModels } : {}),
...(template ? { template } : {}),
...(contextWindow ? { contextWindow } : {}),
diff --git a/src/main/features/idle_sleep_guard.ts b/src/main/features/idle_sleep_guard.ts
new file mode 100644
index 00000000..bda11a07
--- /dev/null
+++ b/src/main/features/idle_sleep_guard.ts
@@ -0,0 +1,90 @@
+import { createLogger } from '../logger';
+
+const log = createLogger('idle-sleep-guard');
+
+/** The part of Electron's `powerSaveBlocker` this guard uses. */
+export interface PowerSaveBlockerLike {
+ start(type: 'prevent-app-suspension'): number;
+ stop(id: number): void;
+}
+
+export interface IdleSleepGuardOptions {
+ blocker: PowerSaveBlockerLike;
+ /** The bus's in-memory "work is running" signal (also used by the window
+ * close confirmation); it must stay cheap because it is polled. */
+ hasActiveWork: () => boolean;
+ intervalMs?: number;
+}
+
+export interface IdleSleepGuard {
+ /** Re-evaluate now (also runs on every interval tick). */
+ sync(): void;
+ /** Stop polling and release the blocker. Idempotent. */
+ stop(): void;
+}
+
+export const IDLE_SLEEP_GUARD_INTERVAL_MS = 10_000;
+
+/**
+ * Keep the computer out of idle sleep while Agent work runs, so a task the
+ * user started and walked away from is not frozen when the machine idles.
+ *
+ * Uses `prevent-app-suspension`: the display may still turn off, and sleep
+ * the user asks for (menu, lid, power button) still happens. The blocker is
+ * held only while `hasActiveWork()` is true and released on the first tick
+ * after the last run ends, so an idle app never keeps the machine awake.
+ */
+export function startIdleSleepGuard(opts: IdleSleepGuardOptions): IdleSleepGuard {
+ const { blocker, hasActiveWork, intervalMs = IDLE_SLEEP_GUARD_INTERVAL_MS } = opts;
+ let blockerId: number | null = null;
+ let stopped = false;
+
+ const release = (): void => {
+ if (blockerId === null) return;
+ const id = blockerId;
+ blockerId = null;
+ try {
+ blocker.stop(id);
+ log.info('idle sleep allowed: no Agent work is running');
+ } catch (err) {
+ log.warn('releasing the idle sleep blocker failed', { error: (err as Error)?.message || String(err) });
+ }
+ };
+
+ const sync = (): void => {
+ if (stopped) return;
+ let active = false;
+ try {
+ active = hasActiveWork();
+ } catch {
+ // An unreadable signal must not pin the machine awake.
+ active = false;
+ }
+ if (!active) {
+ release();
+ return;
+ }
+ if (blockerId !== null) return;
+ try {
+ blockerId = blocker.start('prevent-app-suspension');
+ log.info('preventing idle sleep while Agent work runs');
+ } catch (err) {
+ // Retried on the next tick; a failure here never affects the run itself.
+ log.warn('preventing idle sleep failed', { error: (err as Error)?.message || String(err) });
+ }
+ };
+
+ const timer = setInterval(sync, intervalMs);
+ timer.unref?.();
+ sync();
+
+ return {
+ sync,
+ stop: () => {
+ if (stopped) return;
+ stopped = true;
+ clearInterval(timer);
+ release();
+ },
+ };
+}
diff --git a/src/main/features/local_access_policy.ts b/src/main/features/local_access_policy.ts
index 87485b06..641e117f 100644
--- a/src/main/features/local_access_policy.ts
+++ b/src/main/features/local_access_policy.ts
@@ -1,3 +1,4 @@
+import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -220,6 +221,40 @@ export function sensitivePathReasons(
return [];
}
+export interface LocationOnlyRead {
+ /** Folder shown to the user: the directory read itself, else the file's parent. */
+ folder: string;
+ /** Real paths, so a link inside the folder cannot carry a grant elsewhere. */
+ realPath: string;
+ realFolder: string;
+}
+
+function realpathOr(candidate: string): string {
+ try { return fs.realpathSync.native(candidate); }
+ catch { return candidate; }
+}
+
+/** A read that is sensitive only because it lies in a broad personal location
+ * (Desktop, Documents, Downloads, Library app folders): neither the path nor
+ * what it resolves to matches an intrinsic secret pattern. Such a read may be
+ * covered by a read-only grant for its folder; anything else stays per-read. */
+export function locationOnlyRead(
+ absPath: string,
+ options: { trustedRoots?: readonly string[] } = {},
+): LocationOnlyRead | undefined {
+ const trustedRoots = options.trustedRoots ?? [];
+ const intrinsicReasons = (candidate: string) => sensitivePathReasons(candidate, 'read', { trustedRoots: [...trustedRoots, candidate] });
+ const lexical = path.resolve(absPath);
+ if (!sensitivePathReasons(lexical, 'read', { trustedRoots }).length || intrinsicReasons(lexical).length) return undefined;
+ const realPath = realpathOr(lexical);
+ if (realPath !== lexical && intrinsicReasons(realPath).length) return undefined;
+ let isDirectory = false;
+ try { isDirectory = fs.statSync(realPath).isDirectory(); }
+ catch { /* a missing path is read as a file in its parent */ }
+ const folder = isDirectory ? lexical : path.dirname(lexical);
+ return { folder, realPath, realFolder: isDirectory ? realPath : realpathOr(folder) };
+}
+
export function classifyConfiguredBashCommand(
command: string,
baseReasons: readonly LocalAccessRiskCategory[] = [],
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 26fe6543..c594506d 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -42,6 +42,7 @@
*/
import * as path from 'node:path';
+import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as os from 'node:os';
@@ -148,6 +149,11 @@ export const artifactDir = (uid: string, cid: string, artifactId: strin
// `shell.openPath`. See `features/saved_apps.ts`.
export const userSavedAppsDir = (uid: string) => path.join(userCloudRoot(uid), 'saved_apps');
export const savedAppDir = (uid: string, appId: string) => path.join(userSavedAppsDir(uid), appId);
+// Editing snapshots and publishing state are device-local, never sync manifests.
+export const userAppEditsDir = (uid: string) => path.join(userLocalRoot(uid), 'app-edits');
+export const userAppPublishingDir = (uid: string) => path.join(userLocalRoot(uid), 'app-publishing');
+// Durable saved-app delete intents; machine-private so a stopped delete finishes only where it started.
+export const userAppDeletesDir = (uid: string) => path.join(userLocalRoot(uid), 'app-deletes');
// App data in either scope is never served or copied with an immutable bundle.
export type WebAppStorageScope = 'local' | 'cloud';
@@ -179,6 +185,11 @@ export const userLocalSessionFile = (uid: string, sessionId: string) => path.j
// under the owning user's local tree, never enter cloud sync, and are isolated
// from the app renderer/default Electron session.
export const userWebAssistProfileDir = (uid: string) => path.join(userLocalRoot(uid), 'web-assist', 'profile');
+// Only reconstructible network caches may live under Electron's sandbox root.
+// Include the full profile identity so separate installs/workspaces never share a cache.
+export const userWebAssistCacheDir = (uid: string, sessionDataDir: string) => path.join(
+ sessionDataDir, 'web-assist-cache', createHash('sha256').update(userWebAssistProfileDir(uid)).digest('hex'),
+);
export const userWebAssistSessionCookiesFile = (uid: string) => path.join(userLocalRoot(uid), 'web-assist', 'session-cookies.enc');
// Curated knowledge base (the "organized" region of the historical
@@ -259,6 +270,8 @@ export const projectBindingsFile = (uid: string, pid: string) => path.join(pro
// outside the shared project's Server/COS file allowlist.
export const projectPrivateAgentFile = (uid: string, pid: string) =>
path.join(projectDir(uid, assertProjectSegment(pid)), 'agent_preferences', 'private-agents.json');
+export const projectTaskOwnerPreferencesFile = (uid: string, pid: string) =>
+ path.join(projectDir(uid, assertProjectSegment(pid)), 'agent_preferences', 'task-owners.json');
/** Guard a project id used as a single path segment for project-scoped
* instructions/memory. The pid comes from the conv index / IPC (never
* model-supplied), but these paths are written to, so reject traversal /
@@ -344,6 +357,8 @@ export const agentRuntimeStatsFile = (uid: string, agentId: string) => path.join
// itself.
export const agentMetaDir = (uid: string, agentId: string) => path.join(agentDir(uid, agentId), 'meta');
export const agentCompetenceFile = (uid: string, agentId: string) => path.join(agentMetaDir(uid, agentId), 'COMPETENCE.md');
+// Rejected reflection candidates stay machine-private and outside prompt inputs.
+export const userMetacognitionDraftsDir = (uid: string) => path.join(userLocalRoot(uid), 'metacognition-drafts');
export const agentStrategiesFile = (uid: string, agentId: string) => path.join(agentMetaDir(uid, agentId), 'LEARNING_STRATEGIES.md');
// Agent self-evolved skill store (System B — written by core-agent's SkillStore;
@@ -698,6 +713,7 @@ export const chatAttachmentDraftDir = (uid: string, cid: string) => path.jo
// overwritten versions. Recoverable deletes live in `local/recycle/`, shared
// with in-app deletes.
export const userSyncDir = (uid: string) => path.join(userLocalRoot(uid), 'sync');
+export const userSyncMetacognitionBaselinesDir = (uid: string) => path.join(userSyncDir(uid), 'metacognition-baselines');
export const userSyncIndexFile = (uid: string) => path.join(userSyncDir(uid), 'index.json');
export const userSyncStateFile = (uid: string) => path.join(userSyncDir(uid), 'state.json');
export const userSyncConflictsDir = (uid: string) => path.join(userSyncDir(uid), 'conflicts');
diff --git a/src/main/storage.ts b/src/main/storage.ts
index ec0a6e6d..b93a349a 100644
--- a/src/main/storage.ts
+++ b/src/main/storage.ts
@@ -119,7 +119,8 @@ async function renameWithRetryUsing(
}
}
-function renameWithRetry(tmp: string, filePath: string, shouldCommit?: () => boolean): Promise<boolean> {
+/** Async rename using the atomic writers' bounded Windows file-lock retries. */
+export function renameWithRetry(tmp: string, filePath: string, shouldCommit?: () => boolean): Promise<boolean> {
// A guarded publication must not yield between the ownership check and
// rename. Retry delays stay asynchronous so file locks do not block main.
return renameWithRetryUsing(tmp, filePath, shouldCommit ? fs.renameSync : fsp.rename, shouldCommit);
@@ -129,11 +130,13 @@ function renameWithRetrySyncUsing(
tmp: string,
filePath: string,
renameFn: (oldPath: string, newPath: string) => void,
-): void {
+ shouldCommit?: () => boolean,
+): boolean {
for (let attempt = 0; ; attempt++) {
+ if (shouldCommit && !shouldCommit()) return false;
try {
renameFn(tmp, filePath);
- return;
+ return true;
} catch (err) {
if (!isRetryableRenameError(err) || attempt >= RENAME_RETRY_DELAYS_MS.length) throw err;
sleepSync(RENAME_RETRY_DELAYS_MS[attempt]);
@@ -141,9 +144,25 @@ function renameWithRetrySyncUsing(
}
}
-/** Rename with retry on Windows AV/backup-tool lock errors. */
+/** Guarded small-text publication. Check and rename share one main-process
+ * critical section, including Windows retries; no event-loop yield between them. */
+export function writeTextAtomicGuardedSync(filePath: string, text: string, shouldCommit: () => boolean): boolean {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ const tmp = atomicTmpPath(filePath);
+ try {
+ fs.writeFileSync(tmp, text, 'utf8');
+ return renameWithRetrySyncUsing(tmp, filePath, fs.renameSync, shouldCommit);
+ } finally {
+ fs.rmSync(tmp, { force: true });
+ }
+}
+
+/** Rename with retry on Windows AV/backup-tool lock errors (EPERM/EACCES/
+ * EBUSY). Exported for writers that hand-roll tmp+rename with a non-default
+ * serialization (e.g. sync's compact-JSON index files) — everything else
+ * should use writeJson/writeJsonSync/writeTextAtomicSync directly. */
export function renameWithRetrySync(tmp: string, filePath: string): void {
- return renameWithRetrySyncUsing(tmp, filePath, fs.renameSync);
+ renameWithRetrySyncUsing(tmp, filePath, fs.renameSync);
}
export const __storageTestHooks = {
@@ -208,8 +227,9 @@ export function writeTextAtomicSync(
const tmp = atomicTmpPath(filePath);
// Mode is applied to the tmp file; rename carries it onto the target — used
// by secret-bearing writers (connectors.json, auth profiles) that need 0600.
- fs.writeFileSync(tmp, text, { encoding, ...(opts && opts.mode !== undefined ? { mode: opts.mode } : {}) });
try {
+ // A failed (e.g. disk-full) write must not leave a partial sibling behind.
+ fs.writeFileSync(tmp, text, { encoding, ...(opts && opts.mode !== undefined ? { mode: opts.mode } : {}) });
renameWithRetrySync(tmp, filePath);
} catch (err) {
try { fs.rmSync(tmp, { force: true }); } catch {}
@@ -524,68 +544,132 @@ export async function readJsonlWindow<T = Record<string, any>>(
projectRecord?: (record: T) => T,
after = 0,
): Promise<JsonlWindow<T>> {
- const first = Math.max(0, Math.floor(Number(startIndex) || 0));
- const wanted = Math.max(1, Math.floor(Number(limit) || 1));
let handle: fs.promises.FileHandle;
try {
handle = await fsp.open(filePath, 'r');
} catch {
return { records: [], previousCursor: null, followingCursor: null };
}
+ try {
+ return await _readJsonlWindowFrom(handle, (await handle.stat()).size, startIndex, limit, projectRecord, after);
+ } finally {
+ await handle.close();
+ }
+}
+
+/** Hand each newline-delimited line from `position` to `consume` with its
+ * byte start until it returns true. Lines are assembled from whole chunks
+ * before decoding, so UTF-8 split across reads stays intact. Returns the byte
+ * offset after the last consumed line (`size` after a final unterminated one). */
+async function _scanJsonlLines(
+ handle: fs.promises.FileHandle,
+ size: number,
+ position: number,
+ consume: (line: Buffer, lineStart: number) => boolean,
+): Promise<number> {
+ let lineSegments: Buffer[] = [];
+ let currentRecordStart = position;
+ let done = false;
+ while (position < size && !done) {
+ const bytes = Math.min(JSONL_TAIL_CHUNK_BYTES, size - position);
+ const block = Buffer.allocUnsafe(bytes);
+ const { bytesRead } = await handle.read(block, 0, bytes, position);
+ if (bytesRead <= 0) break;
+ let lineStart = 0;
+ for (let i = block.indexOf(0x0a); i >= 0 && i < bytesRead; i = block.indexOf(0x0a, i + 1)) {
+ const current = block.subarray(lineStart, i);
+ const line = lineSegments.length
+ ? _concatJsonlSegments([...lineSegments, current])
+ : current;
+ done = consume(line, currentRecordStart);
+ lineSegments = [];
+ lineStart = i + 1;
+ currentRecordStart = position + lineStart;
+ if (done) break;
+ }
+ position += bytesRead;
+ if (!done && lineStart < bytesRead) lineSegments.push(block.subarray(lineStart, bytesRead));
+ }
+ if (!done && lineSegments.length) {
+ consume(_concatJsonlSegments(lineSegments), currentRecordStart);
+ currentRecordStart = size;
+ }
+ return currentRecordStart;
+}
+async function _readJsonlWindowFrom<T>(
+ handle: fs.promises.FileHandle,
+ size: number,
+ startIndex: number,
+ limit: number,
+ projectRecord: ((record: T) => T) | undefined,
+ after: number,
+): Promise<JsonlWindow<T>> {
+ const first = Math.max(0, Math.floor(Number(startIndex) || 0));
+ const wanted = Math.max(1, Math.floor(Number(limit) || 1));
+ const records: T[] = [];
+ let recordIndex = 0;
+ let firstRecordStart = -1;
+ const position = Number.isSafeInteger(after) && after >= 0 ? Math.min(after, size) : 0;
+ const end = await _scanJsonlLines(handle, size, position, (line, recordStart) => {
+ const record = _parseJsonlRecord<T>(line.toString('utf8'));
+ if (record === undefined) return false;
+ if (recordIndex >= first && records.length < wanted) {
+ if (firstRecordStart < 0) firstRecordStart = recordStart;
+ // Project on consumption so a long search window retains only the
+ // display payload, never every raw execution trail at once.
+ records.push(projectRecord ? projectRecord(record) : record);
+ }
+ recordIndex += 1;
+ return records.length >= wanted;
+ });
+ return {
+ records,
+ previousCursor: firstRecordStart > 0 ? firstRecordStart : null,
+ followingCursor: end < size ? end : null,
+ };
+}
+
+/**
+ * Read the `limit`-aligned record page (the same page readJsonlWindow returns
+ * for `floor(index / limit) * limit`) holding the first record `matches`
+ * accepts. One forward pass parses records up to the match and keeps only
+ * the page start; the page itself is then read and projected from that byte
+ * offset on the same handle. Null when no record matches.
+ */
+export async function readJsonlWindowAtMatch<T = Record<string, any>>(
+ filePath: string,
+ matches: (record: T) => boolean,
+ limit = 10,
+ projectRecord?: (record: T) => T,
+): Promise<(JsonlWindow<T> & { start: number; index: number }) | null> {
+ const wanted = Math.max(1, Math.floor(Number(limit) || 1));
+ let handle: fs.promises.FileHandle;
+ try {
+ handle = await fsp.open(filePath, 'r');
+ } catch {
+ return null;
+ }
try {
const size = (await handle.stat()).size;
- const records: T[] = [];
let recordIndex = 0;
- let position = Number.isSafeInteger(after) && after >= 0 ? Math.min(after, size) : 0;
- let lineSegments: Buffer[] = [];
- let currentRecordStart = position;
- let firstRecordStart = -1;
- let done = false;
-
- const consumeLine = (line: Buffer, recordStart: number): boolean => {
+ let index = -1;
+ let pageStart = 0;
+ let pageStartByte = 0;
+ await _scanJsonlLines(handle, size, 0, (line, recordStart) => {
const record = _parseJsonlRecord<T>(line.toString('utf8'));
if (record === undefined) return false;
- if (recordIndex >= first && records.length < wanted) {
- if (firstRecordStart < 0) firstRecordStart = recordStart;
- // Project on consumption so a long search window retains only the
- // display payload, never every raw execution trail at once.
- records.push(projectRecord ? projectRecord(record) : record);
+ if (recordIndex % wanted === 0) {
+ pageStart = recordIndex;
+ pageStartByte = recordStart;
}
+ if (matches(record)) index = recordIndex;
recordIndex += 1;
- return records.length >= wanted;
- };
-
- while (position < size && !done) {
- const bytes = Math.min(JSONL_TAIL_CHUNK_BYTES, size - position);
- const block = Buffer.allocUnsafe(bytes);
- const { bytesRead } = await handle.read(block, 0, bytes, position);
- if (bytesRead <= 0) break;
- let lineStart = 0;
- for (let i = block.indexOf(0x0a); i >= 0 && i < bytesRead; i = block.indexOf(0x0a, i + 1)) {
- const current = block.subarray(lineStart, i);
- const line = lineSegments.length
- ? _concatJsonlSegments([...lineSegments, current])
- : current;
- done = consumeLine(line, currentRecordStart);
- lineSegments = [];
- lineStart = i + 1;
- currentRecordStart = position + lineStart;
- if (done) break;
- }
- position += bytesRead;
- if (!done && lineStart < bytesRead) lineSegments.push(block.subarray(lineStart, bytesRead));
- }
- if (!done && lineSegments.length) {
- consumeLine(_concatJsonlSegments(lineSegments), currentRecordStart);
- currentRecordStart = size;
- }
-
- return {
- records,
- previousCursor: firstRecordStart > 0 ? firstRecordStart : null,
- followingCursor: currentRecordStart < size ? currentRecordStart : null,
- };
+ return index >= 0;
+ });
+ if (index < 0) return null;
+ const window = await _readJsonlWindowFrom(handle, size, 0, wanted, projectRecord, pageStartByte);
+ return { ...window, start: pageStart, index };
} finally {
await handle.close();
}
diff --git a/src/main/util/auto-title.ts b/src/main/util/auto-title.ts
index 42610b8f..8414925d 100644
--- a/src/main/util/auto-title.ts
+++ b/src/main/util/auto-title.ts
@@ -29,9 +29,17 @@ export const EN_FILLER_RE = /^(could you|would you|can you|help me|i'?d like to|
* cap produced for an all-CJK title, so no existing title gets shorter.
*
* The budget covers the kept text; the ellipsis is appended on top, as it was
- * under the character cap.
+ * under the character cap. Raised from 50 so task lists on wide surfaces (the
+ * project task tab) show the request instead of a quarter-width stub; narrow
+ * lists keep clipping by CSS.
*/
-export const TITLE_MAX_UNITS = 50;
+export const TITLE_MAX_UNITS = 100;
+
+/** Stored conversation titles, auto or manual, are capped here rather than by
+ * the shared 60-unit name limit, so a full auto title keeps its ellipsis and
+ * a manual title may be as wide as an auto one. Projects, Agents and Skills
+ * keep the shared limit. */
+export const CONVERSATION_TITLE_MAX_UNITS = TITLE_MAX_UNITS + 1;
/** Cut `text` to the title budget by rendered width, marking the cut with an
* ellipsis. Whole grapheme clusters only, so an emoji is never halved. */
diff --git a/src/main/util/browser-proxy.ts b/src/main/util/browser-proxy.ts
index 169408df..5e833bd1 100644
--- a/src/main/util/browser-proxy.ts
+++ b/src/main/util/browser-proxy.ts
@@ -1,10 +1,16 @@
import type { ProxyConfig, Session, WebContents } from 'electron';
import { createLogger } from '../logger';
import { envProxyConfig } from './proxy-dispatcher';
+import { isIP } from 'node:net';
const log = createLogger('browser-proxy');
type Credentials = { username: string; password: string };
+export interface BrowserProxyDiagnostic {
+ browser_proxy_policy: 'system' | 'fixed_servers' | 'invalid';
+ browser_proxy_setup: 'ready' | 'pending' | 'failed';
+}
+
/** Translate launch environment policy without changing Chromium's system/PAC defaults. */
export function browserProxyConfig(env: NodeJS.ProcessEnv): {
config?: ProxyConfig;
@@ -43,6 +49,18 @@ export function browserProxyConfig(env: NodeJS.ProcessEnv): {
bypass.push('*');
continue;
}
+ // macOS system exceptions include CIDR literals, which Chromium accepts
+ // directly. Validate the literal and prefix without dropping bypass policy.
+ const cidr = /^([^/]+)\/(\d{1,3})$/u.exec(token);
+ if (cidr) {
+ const family = isIP(cidr[1]);
+ const prefix = Number(cidr[2]);
+ if (!family || prefix > (family === 4 ? 32 : 128)) {
+ throw new Error('Invalid browser proxy bypass range');
+ }
+ bypass.push(`${cidr[1]}/${prefix}`);
+ continue;
+ }
// NO_PROXY bare domains cover both the host and its subdomains. Chromium bare hosts do not.
const match = /^(\[[\da-f:]+\]|::1|(?:\*?\.)?[\w.-]+)(:\d+)?$/iu.exec(token);
if (!match) throw new Error('Unsupported browser proxy bypass rule');
@@ -67,10 +85,13 @@ export function browserProxyConfig(env: NodeJS.ProcessEnv): {
export function prepareBrowserProxy(ses: Pick<Session, 'setProxy'>, env: NodeJS.ProcessEnv = process.env): {
ready?: Promise<boolean>;
attach: (contents: WebContents) => void;
+ diagnostic: () => BrowserProxyDiagnostic;
} {
try {
const { config, credentials } = browserProxyConfig(env);
- if (!config) return { attach: () => {} };
+ if (!config) return { attach: () => {},
+ diagnostic: () => ({ browser_proxy_policy: 'system', browser_proxy_setup: 'ready' }) };
+ let setup: BrowserProxyDiagnostic['browser_proxy_setup'] = 'pending';
let timer: ReturnType<typeof setTimeout>;
const ready = Promise.race([
ses.setProxy(config).then(() => true),
@@ -80,9 +101,15 @@ export function prepareBrowserProxy(ses: Pick<Session, 'setProxy'>, env: NodeJS.
]).catch(() => {
log.warn('browser proxy setup failed; browser requests remain blocked');
return false;
- }).finally(() => clearTimeout(timer!));
+ }).finally(() => clearTimeout(timer!)).then(applied => {
+ setup = applied ? 'ready' : 'failed';
+ return applied;
+ });
return {
ready,
+ // Policy/setup observations only; system/PAC and bypass resolution are
+ // deliberately not inferred and this performs no network lookup.
+ diagnostic: () => ({ browser_proxy_policy: 'fixed_servers', browser_proxy_setup: setup }),
attach(contents) {
if (!credentials.size) return;
contents.on('login', (event, details, auth, callback) => {
@@ -99,6 +126,7 @@ export function prepareBrowserProxy(ses: Pick<Session, 'setProxy'>, env: NodeJS.
} catch {
// Never include an environment URL or upstream error: it may contain credentials.
log.warn('browser proxy configuration is invalid; browser requests remain blocked');
- return { ready: Promise.resolve(false), attach: () => {} };
+ return { ready: Promise.resolve(false), attach: () => {},
+ diagnostic: () => ({ browser_proxy_policy: 'invalid', browser_proxy_setup: 'failed' }) };
}
}
diff --git a/src/main/util/proxy-dispatcher.ts b/src/main/util/proxy-dispatcher.ts
index bf0684e3..d27c7278 100644
--- a/src/main/util/proxy-dispatcher.ts
+++ b/src/main/util/proxy-dispatcher.ts
@@ -113,6 +113,7 @@ let _fetchDelegate: FetchLike | undefined;
let _fetchRouter: FetchLike | undefined;
let _baseBinaryFetch: BinaryFetchLike | undefined;
let _binaryFetchDelegate: BinaryFetchLike | undefined;
+let _uploadRoute: ((url: URL) => Promise<ResolvedProxyRoute>) | undefined;
let _childFetchBridge: Promise<ChildFetchBridge> | undefined;
interface ChildFetchBridge {
@@ -344,6 +345,101 @@ async function electronSystemFetch(): Promise<FetchLike> {
}) as FetchLike;
}
+export type UploadProgress = (sent: number, total: number) => void;
+
+/** Bounded JSON uploads use transport byte events, never body-producer reads.
+ * Keep environment/DIRECT on Node and system proxy routes on Chromium. */
+export async function fetchUploadWithProxyPolicy(
+ url: string, init: RequestInit, onProgress: UploadProgress,
+): Promise<Response> {
+ if (typeof init.body !== 'string') throw new TypeError('upload requires a serialized body');
+ const body = Buffer.from(init.body);
+ if (_uploadRoute && !_envActive && (await _uploadRoute(new URL(url))).kind !== 'direct') {
+ return electronUpload(url, init, body, onProgress);
+ }
+ const { fetch: nodeFetch, getGlobalDispatcher } = require('undici') as typeof import('undici');
+ const base = getGlobalDispatcher();
+ let active = true;
+ const dispatcher = {
+ dispatch(options: import('undici').Dispatcher.DispatchOptions, handler: import('undici').Dispatcher.DispatchHandler) {
+ let sent = 0;
+ return base.dispatch({...options, ...(options.body ? {body: Readable.from(chunks(), {objectMode: false})} : {})}, new Proxy(handler, {
+ get(target, key) {
+ if (key === 'onBodySent') return (chunk: Uint8Array) => {
+ // The installed undici runtime supplies the chunk (its .d.ts differs).
+ sent += chunk.byteLength;
+ if (active && !init.signal?.aborted) onProgress(Math.min(sent, body.length), body.length);
+ };
+ const value = Reflect.get(target, key);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ }));
+ },
+ } as import('undici').Dispatcher;
+ // Subdivide within the same HTTP request. Socket backpressure controls pacing;
+ // no extra round trips or artificial progress timers are introduced.
+ async function* chunks() {
+ for (let offset = 0; offset < body.length; offset += 16 * 1024) yield body.subarray(offset, offset + 16 * 1024);
+ }
+ try {
+ // Retain fetch's replayable serialized body and redirect policy; split only
+ // at dispatch so 307/308 retries can obtain a fresh iterator.
+ return await nodeFetch(url, { ...init, headers: Object.fromEntries(new Headers(init.headers)), dispatcher,
+ } as Parameters<typeof nodeFetch>[1]) as unknown as Response;
+ } finally { active = false; }
+}
+
+async function electronUpload(url: string, init: RequestInit, body: Buffer, onProgress: UploadProgress): Promise<Response> {
+ const { net, session } = await import('electron');
+ return new Promise((resolve, reject) => {
+ const signal = init.signal;
+ if (signal?.aborted) { reject(signal.reason); return; }
+ const request = net.request({url, method: init.method || 'POST', session: session.defaultSession, redirect: init.redirect || 'follow'});
+ let settled = false;
+ let timer: ReturnType<typeof setInterval> | undefined;
+ const finish = (error?: unknown, response?: Response) => {
+ if (settled) return;
+ settled = true;
+ clearInterval(timer);
+ signal?.removeEventListener('abort', abort);
+ if (error) reject(error); else resolve(response!);
+ };
+ const abort = () => { finish(signal?.reason || new Error('upload aborted')); request.abort(); };
+ const report = () => {
+ if (settled || signal?.aborted) return;
+ const value = request.getUploadProgress();
+ if (value.active && value.started) onProgress(Math.min(value.current, body.length), body.length);
+ };
+ request.on('error', error => finish(normalizeElectronNetFetchError(error)));
+ request.on('abort', () => finish(new Error('upload aborted')));
+ request.on('close', () => finish(new Error('upload closed before response completed')));
+ request.on('response', response => {
+ report(); clearInterval(timer);
+ const chunks: Buffer[] = [];
+ response.on('data', (chunk: Buffer) => chunks.push(chunk));
+ response.on('error', error => finish(error));
+ response.on('aborted', () => finish(new Error('upload response aborted')));
+ response.on('end', () => {
+ if (settled) return;
+ try {
+ const headers = new Headers();
+ for (const [name, values] of Object.entries(response.headers)) {
+ for (const value of Array.isArray(values) ? values : [values]) headers.append(name, value);
+ }
+ finish(undefined, new Response([204,205,304].includes(response.statusCode) ? null : Buffer.concat(chunks),
+ {status: response.statusCode, headers}));
+ } catch (error) { finish(error); }
+ });
+ });
+ try {
+ new Headers(init.headers).forEach((value, name) => request.setHeader(name, value));
+ signal?.addEventListener('abort', abort, {once: true});
+ timer = setInterval(report, 100);
+ request.end(body);
+ } catch (error) { finish(error); request.abort(); }
+ });
+}
+
/**
* Electron's `net.fetch` materialises every response header as a WHATWG
* `Headers` value. Some object-storage providers return non-Latin-1 metadata
@@ -908,6 +1004,7 @@ export async function installSystemProxyDispatcher(
electronSystemBinaryFetch,
resolveProxy,
);
+ _uploadRoute = createProxyRouteResolver(resolveProxy);
_active = 'system:per-request';
log.info('installed per-request Electron system-proxy routing for global fetch');
return true;
@@ -937,6 +1034,7 @@ export function _resetProxyRoutingForTests(): void {
_fetchRouter = undefined;
_baseBinaryFetch = undefined;
_binaryFetchDelegate = undefined;
+ _uploadRoute = undefined;
if (_childFetchBridge) {
void _childFetchBridge.then(({ close }) => close()).catch(() => undefined);
_childFetchBridge = undefined;
diff --git a/src/main/util/retry.ts b/src/main/util/retry.ts
index 9387f3ba..01a1ee14 100644
--- a/src/main/util/retry.ts
+++ b/src/main/util/retry.ts
@@ -15,6 +15,8 @@ interface RetryOptions {
}
export interface FetchRetryOptions extends RetryOptions {
+ /** Per-call transport; shares the same retry, abort and response-body deadline. */
+ fetch?: FetchImplementation;
/** Per-attempt wall-clock timeout. Omitted by default so large downloads can opt in deliberately. */
timeoutMs?: number;
timeoutMessage?: string;
@@ -78,6 +80,7 @@ export async function retryAsync<T>(
return await fn();
} catch (err) {
lastErr = err;
+ if (opts.signal?.aborted) throw abortReason(opts.signal);
if (attempt >= retries || !isRetriable(err)) throw err;
const nextDelay = delaysMs[Math.min(attempt, delaysMs.length - 1)] ?? 0;
log.warn('request failed; retrying', {
@@ -149,11 +152,13 @@ export async function fetchAndReadWithRetry<T>(
readBody: (response: Response, signal?: AbortSignal) => Promise<T>,
opts: FetchRetryOptions = {},
): Promise<{ response: Response; body: T }> {
+ const parent = init?.signal && opts.signal ? AbortSignal.any([init.signal, opts.signal])
+ : init?.signal ?? opts.signal;
return retryAsync(label, async () => {
const timeoutMessage = opts.timeoutMessage || `${label} timed out after ${opts.timeoutMs}ms`;
- const composed = composeTimeoutSignal(init?.signal ?? undefined, opts.timeoutMs, timeoutMessage);
+ const composed = composeTimeoutSignal(parent ?? undefined, opts.timeoutMs, timeoutMessage);
try {
- const res = await (fetchImplementation || fetch)(input, { ...init, signal: composed.signal });
+ const res = await (opts.fetch || fetchImplementation || fetch)(input, { ...init, signal: composed.signal });
if (isRetriableHttpStatus(res.status)) {
throw new RetriableHttpStatusError(res.status, label);
}
@@ -165,6 +170,7 @@ export async function fetchAndReadWithRetry<T>(
composed.cleanup();
}
}, {
+ signal: parent ?? undefined,
retries: opts.retries,
delaysMs: opts.delaysMs,
isRetriable: opts.isRetriable,
diff --git a/src/main/util/three-way-text.ts b/src/main/util/three-way-text.ts
new file mode 100644
index 00000000..2f07c4d9
--- /dev/null
+++ b/src/main/util/three-way-text.ts
@@ -0,0 +1,138 @@
+/** Exact, bounded text merge. Try lines first, then words/punctuation when
+ * line edits overlap. Never normalize bytes or interpret note semantics.
+ * A shared insertion may border another edit; distinct insertions, overlapping
+ * words and delete/edit conflicts stay ambiguous. Bound total DP work. */
+type Edit = { start: number; end: number; lines: string[] };
+const MAX_CHARS = 32_768;
+const MAX_CELLS = 1_000_000;
+type Budget = { remaining: number };
+
+function edits(base: string[], next: string[], budget: Budget, trim: boolean): Edit[] | null {
+ let offset = 0;
+ if (trim) {
+ while (offset < base.length && offset < next.length && base[offset] === next[offset]) offset++;
+ let tail = 0;
+ while (tail < base.length - offset && tail < next.length - offset
+ && base[base.length - tail - 1] === next[next.length - tail - 1]) tail++;
+ base = base.slice(offset, base.length - tail);
+ next = next.slice(offset, next.length - tail);
+ }
+ const width = next.length + 1;
+ const cells = (base.length + 1) * width;
+ if (cells > MAX_CELLS || cells > budget.remaining) return null;
+ budget.remaining -= cells;
+ const table = new Uint32Array(cells);
+ for (let i = base.length - 1; i >= 0; i--) {
+ for (let j = next.length - 1; j >= 0; j--) {
+ table[i * width + j] = base[i] === next[j]
+ ? table[(i + 1) * width + j + 1] + 1
+ : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
+ }
+ }
+ const out: Edit[] = [];
+ let i = 0, j = 0;
+ while (i < base.length || j < next.length) {
+ if (i < base.length && j < next.length && base[i] === next[j]) { i++; j++; continue; }
+ const edit: Edit = { start: i, end: i, lines: [] };
+ while (i < base.length || j < next.length) {
+ if (i < base.length && j < next.length && base[i] === next[j]) break;
+ if (j < next.length && (i === base.length || table[i * width + j + 1] >= table[(i + 1) * width + j])) {
+ edit.lines.push(next[j++]);
+ } else { i++; }
+ }
+ edit.start += offset;
+ edit.end = i + offset;
+ out.push(edit);
+ }
+ return out;
+}
+
+function sameEdit(a: Edit, b: Edit): boolean {
+ return a.start === b.start && a.end === b.end && a.lines.join('') === b.lines.join('');
+}
+
+/** LCS may combine a common insertion with an adjacent replacement. Split
+ * only when the other side inserts those exact units at the same boundary. */
+function splitSharedInsertions(source: Edit[], other: Edit[]): Edit[] {
+ const insertions = new Map(other.filter(edit => edit.start === edit.end).map(edit => [edit.start, edit]));
+ return source.flatMap(original => {
+ if (original.start === original.end) return [original];
+ let edit = original;
+ const result: Edit[] = [];
+ const before = insertions.get(edit.start);
+ if (before && before.lines.length <= edit.lines.length
+ && before.lines.every((unit, i) => unit === edit.lines[i])) {
+ result.push(before);
+ edit = { ...edit, lines: edit.lines.slice(before.lines.length) };
+ }
+ const after = insertions.get(edit.end);
+ if (after && after.lines.length <= edit.lines.length
+ && after.lines.every((unit, i) => unit === edit.lines[edit.lines.length - after.lines.length + i])) {
+ result.push({ ...edit, lines: edit.lines.slice(0, -after.lines.length) }, after);
+ } else result.push(edit);
+ return result;
+ });
+}
+
+function overlaps(a: Edit, b: Edit): boolean {
+ if (a.start === a.end) return a.start >= b.start && a.start <= b.end;
+ if (b.start === b.end) return b.start >= a.start && b.start <= a.end;
+ return a.start < b.end && b.start < a.end;
+}
+
+function combine(base: string[], leftEdits: Edit[], rightEdits: Edit[]): string | null {
+ const left = splitSharedInsertions(leftEdits, rightEdits);
+ const right = splitSharedInsertions(rightEdits, left);
+ const leftInsertions = new Map(left.filter(edit => edit.start === edit.end).map(edit => [edit.start, edit]));
+ const sharedInsertions = new Set(right.filter(edit => edit.start === edit.end
+ && leftInsertions.has(edit.start) && sameEdit(leftInsertions.get(edit.start)!, edit)).map(edit => edit.start));
+ const combined = [...left];
+ for (const edit of right) {
+ let duplicate = false;
+ for (const prior of left) {
+ if (sameEdit(prior, edit)) {
+ duplicate = true; break;
+ }
+ if (overlaps(prior, edit)) {
+ const insertion = prior.start === prior.end ? prior : edit.start === edit.end ? edit : null;
+ const replacement = insertion === prior ? edit : prior;
+ if (!insertion || !sharedInsertions.has(insertion.start)
+ || (insertion.start !== replacement.start && insertion.start !== replacement.end)) return null;
+ }
+ }
+ if (!duplicate) combined.push(edit);
+ }
+ combined.sort((a, b) => a.start - b.start || a.end - b.end);
+ const output: string[] = [];
+ let position = 0;
+ for (const edit of combined) {
+ output.push(...base.slice(position, edit.start), ...edit.lines);
+ position = edit.end;
+ }
+ output.push(...base.slice(position));
+ return output.join('');
+}
+
+export function mergeThreeWayText(baseText: string, local: string, remote: string): string | null {
+ if (local === remote) return local;
+ if (baseText === local) return remote;
+ if (baseText === remote) return local;
+ if ([baseText, local, remote].some(text => text.length > MAX_CHARS)) return null;
+ const budget = { remaining: MAX_CELLS * 2 };
+ // Keep line terminators as content, including the final-newline distinction.
+ const split = (text: string) => text.match(/[^\n]*\n|[^\n]+$/g) || [];
+ const base = split(baseText);
+ const left = edits(base, split(local), budget, false);
+ const right = edits(base, split(remote), budget, false);
+ if (!left || !right) return null;
+ const merged = combine(base, left, right);
+ if (merged !== null) return merged;
+ // Whole words avoid manufacturing a third word from incompatible spelling
+ // edits. Unicode code points keep surrogate pairs intact; whitespace and
+ // punctuation remain exact units, never normalization or semantic anchors.
+ const units = (text: string) => text.match(/[\p{L}\p{N}_]+|[^\p{L}\p{N}_]/gu) || [];
+ const fineBase = units(baseText);
+ const fineLeft = edits(fineBase, units(local), budget, true);
+ const fineRight = edits(fineBase, units(remote), budget, true);
+ return fineLeft && fineRight ? combine(fineBase, fineLeft, fineRight) : null;
+}
diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.ts
index da3d8e43..247286aa 100644
--- a/src/main/util/tool-result-cap.ts
+++ b/src/main/util/tool-result-cap.ts
@@ -15,6 +15,7 @@
* Pure-function util: Node stdlib only, never imports features/ or model/.
*/
+import { appendInputReceipt } from '../../../bin/tool-input-compat.cjs';
import * as fs from 'fs';
import * as path from 'path';
import { createHash } from 'crypto';
@@ -58,6 +59,31 @@ export type ToolResultInlineLedger = {
verbatimDocumentTokens?: number;
};
+/** The estimated tokens one result may fill: the fixed per-result ceiling,
+ * the runner's per-result ceiling and what the current tool round has left.
+ * A complete document the model was told to read whole uses its own fixed
+ * ceiling instead of the ordinary one. Without a ledger (CLI bridge, direct
+ * calls) the fixed ceiling applies. Producers size their output with this so
+ * a result stays inline instead of spilling to a preview. */
+export function inlineResultTokenBudget(state: unknown, verbatimDocument = false): number {
+ const value = state && typeof state === 'object'
+ ? (state as Record<string, unknown>)[TOOL_RESULT_INLINE_LEDGER_STATE_KEY]
+ : undefined;
+ const ledger = value && typeof value === 'object'
+ ? value as Partial<ToolResultInlineLedger>
+ : undefined;
+ const skillLimit = ledger?.verbatimDocumentTokens;
+ const candidates = [verbatimDocument && Number.isFinite(skillLimit) && skillLimit! > 0
+ ? skillLimit! : DEFAULT_INLINE_RESULT_TOKENS];
+ if (!verbatimDocument && Number.isFinite(ledger?.perResultTokens)) {
+ candidates.push(Math.max(0, ledger!.perResultTokens!));
+ }
+ if (Number.isFinite(ledger?.remainingTokens)) {
+ candidates.push(Math.max(0, ledger!.remainingTokens!));
+ }
+ return Math.max(0, Math.floor(Math.min(...candidates)));
+}
+
/** Host-owned storage failure; never a request to re-execute the tool. */
export class ToolResultPersistenceError extends Error {
readonly code = 'TOOL_RESULT_PERSISTENCE_FAILED';
@@ -154,19 +180,29 @@ async function executeWithRetrievalBudget(
const ceiling = Math.min(DEFAULT_INLINE_RESULT_TOKENS, ledger?.perResultTokens ?? DEFAULT_INLINE_RESULT_TOKENS);
const reserved = Math.max(0, Math.floor(Math.min(ceiling, ledger?.remainingTokens ?? ceiling)));
if (ledger) ledger.remainingTokens -= reserved;
+ // Reserve the envelope receipt before source selection so continuation
+ // cursors describe exactly the bytes delivered. The final result keeps the
+ // same identity for the admission receipt; it must not be charged twice.
+ const inputReceipt = ctx.inputReceipt;
+ const receiptTokens = inputReceipt
+ ? estimateToolResultTokens(JSON.stringify({ result: null, ...inputReceipt })) + 4
+ : 0;
+ const sourceBudget = Math.max(0, reserved - receiptTokens);
const previousReads = ctx.state.toolResultReadLedger as { epoch: number; readKeys: Set<string> } | undefined;
- const reads = { epoch: previousReads?.epoch ?? 0, remainingTokens: reserved,
+ const reads = { epoch: previousReads?.epoch ?? 0, remainingTokens: sourceBudget,
readKeys: new Set(previousReads?.readKeys ?? []) };
- const child = { ...ctx, state: { ...ctx.state, [RETRIEVAL_OUTPUT_BUDGET_KEY]: reserved,
+ const child = { ...ctx, state: { ...ctx.state, [RETRIEVAL_OUTPUT_BUDGET_KEY]: sourceBudget,
toolResultReadLedger: reads } };
let used = 0;
try {
- let result = reserved > 0 ? await execute(child, reserved) : { content: '', isError: true };
+ let result = sourceBudget > 0 ? await execute(child, sourceBudget) : { content: '', isError: true };
+ if (inputReceipt) result = { ...result, content: appendInputReceipt(result.content, inputReceipt), appliedInputReceipt: inputReceipt };
if (ctx.signal?.aborted) throw ctx.signal.reason ?? new Error('Retrieval aborted.');
if (estimateToolResultTokens(result.content) > reserved) {
// Contract failure: do not publish partial source bytes or advance its
// cursor. In particular, never turn this receipt into a persisted ref.
- result = { content: boundedRetrievalText('Retrieval output did not fit. No source data was delivered; retry the same source with a narrower range.', reserved), isError: true };
+ result = { content: boundedRetrievalText(appendInputReceipt('Retrieval output did not fit. No source data was delivered; retry the same source with a narrower range.', inputReceipt ?? null), reserved), isError: true,
+ ...(inputReceipt ? { appliedInputReceipt: inputReceipt } : {}) };
} else if (previousReads) {
for (const key of reads.readKeys) previousReads.readKeys.add(key);
}
@@ -305,6 +341,7 @@ export function wrapToolWithCap(tool: AgentTool, opts: WrapOpts): AgentTool {
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
+ ...(tool.compatibilityInputFields ? { compatibilityInputFields: tool.compatibilityInputFields } : {}),
// Preserve the concurrency flag — without this the wrapper silently makes
// EVERY capped tool sequential (the runner's G4 partitioner keys on
// `executionMode === 'parallel'`), defeating parallel reads/search AND
diff --git a/src/main/util/window-presentation.ts b/src/main/util/window-presentation.ts
new file mode 100644
index 00000000..5f1c5eef
--- /dev/null
+++ b/src/main/util/window-presentation.ts
@@ -0,0 +1,35 @@
+interface PresentationWindow {
+ on(event: string, listener: () => void): unknown;
+ webContents: {
+ on(event: string, listener: () => void): unknown;
+ isDestroyed(): boolean;
+ send(channel: string, payload: { active: boolean }): void;
+ };
+}
+
+/** Native presentation signals complement Page Visibility: embedded views or
+ * a hidden-at-launch window can keep Chromium's document state visible.
+ * This channel changes rendering only; no task or persistence handle travels.
+ */
+export function installWindowPresentationEvents(win: PresentationWindow): void {
+ // Electron considers hidden-at-launch documents visible until a lifecycle
+ // transition. Keep that first-paint contract, including isolated E2E windows.
+ let active = true;
+ const publish = () => {
+ if (!win.webContents.isDestroyed()) {
+ win.webContents.send('conversations:window-visibility', { active });
+ }
+ };
+ const update = (value: boolean) => {
+ if (active === value) return;
+ active = value;
+ publish();
+ };
+ // Focus does not determine visibility: a user can read a streaming reply
+ // beside another app. Suspend only when the window is hidden or minimized.
+ for (const event of ['hide', 'minimize']) win.on(event, () => update(false));
+ for (const event of ['show', 'restore']) win.on(event, () => update(true));
+ // A renderer reload must recover the last native state, including a hide
+ // that happened before its push listener was ready.
+ win.webContents.on('did-finish-load', publish);
+}
diff --git a/test/fixtures/eval/ui-product-fidelity-canary.mts b/test/fixtures/eval/ui-product-fidelity-canary.mts
new file mode 100644
index 00000000..38206430
--- /dev/null
+++ b/test/fixtures/eval/ui-product-fidelity-canary.mts
@@ -0,0 +1,102 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { inspectUiProductArtifact } from '../../../eval/model-eval/regression/ui-product-fidelity.js';
+
+// Independent accepted source translation, with JS-only workflow headings and
+// equivalent minmax geometry. Labels in script text alone cannot certify it.
+const html = `<!doctype html><html><head><meta charset="utf-8"><title>Northstar</title><style>
+*{box-sizing:border-box}body{margin:0;font:13px/1.45 system-ui}.app-shell{display:grid;grid-template-columns:232px minmax(0,1fr);min-height:100vh}
+.app-sidebar{background:#10273e;color:white;padding:20px 14px}.brand{color:inherit}.app-sidebar nav{display:grid}.app-sidebar nav a{min-height:32px;color:inherit}
+.project-page{padding:28px 32px}.project-header,.section-heading{display:flex;justify-content:space-between}.eyebrow{color:#17837a}
+.project-summary,.activity{border-radius:6px;padding:16px;border:1px solid #c9d4df;margin-top:20px}.board{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px}
+.task-row{display:flex;gap:8px}.icon{width:16px;height:16px;flex-shrink:0}.task-row h3{font-size:13px}.muted{color:#607487}a:focus,button:focus{outline:2px solid #17837a;outline-offset:2px}
+</style></head><body><div class="app-shell"><aside class="app-sidebar"><a class="brand" href="#">Northstar</a><nav aria-label="Primary"><a href="#">Overview</a><a class="active" href="#">Projects</a><a href="#">Inbox</a><a href="#">Reports</a></nav><button class="account">AC · Alex Chen</button></aside>
+<main class="project-page"><header class="project-header"><div><p class="eyebrow">Projects / Operations</p><h1>Atlas migration</h1><p class="muted">Move customer workflows to the new workspace.</p></div><button class="secondary">Share</button></header>
+<section class="project-summary"><h2>Project summary</h2><dl><div><dt>Owner</dt><dd>Alex Chen</dd></div><div><dt>Due</dt><dd>Sep 18</dd></div><div><dt>Status</dt><dd>On track</dd></div></dl></section>
+<section class="board" id="board"></section>
+<section class="activity"><div class="section-heading"><h2>Recent activity</h2><button class="primary">Add update</button></div><p class="muted">Three updates this week</p></section></main></div>
+<script>const labels=['Intake','Planned','Building','Review','Done'];
+document.getElementById('board').innerHTML=labels.map(label => '<section><h3>'+label+'</h3><article class="task-row"><svg class="icon" viewBox="0 0 16 16"><path stroke="currentColor" d="M2 8h12"/></svg><div><h3>Map data</h3><p class="muted">Due Sep 12 · Alex Chen</p></div><span class="status">On track</span></article></section>').join('');</script></body></html>`;
+
+export async function main(): Promise<number> {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'uid-fidelity-canary-'));
+ const dir = path.join(root, 'ui-artifacts', 'northstar');
+ fs.mkdirSync(dir, { recursive: true });
+ const files = ['ui-artifacts/northstar/artifact.json', 'ui-artifacts/northstar/index.html'];
+ const manifest = path.join(dir, 'artifact.json');
+ const entry = path.join(dir, 'index.html');
+ fs.writeFileSync(manifest, JSON.stringify({ entry: 'index.html' }));
+ const observe = async (body: string) => {
+ fs.writeFileSync(entry, body);
+ const facts = await inspectUiProductArtifact(root, files);
+ assert.equal(facts?.rendered, true, JSON.stringify(facts));
+ return facts!;
+ };
+ try {
+ const good = await observe(html);
+ assert.equal(good.shellPreserved, true);
+ assert.equal(good.workflowBetweenRegions, true);
+ assert.equal(good.workflowColumnCount, 5);
+ assert.equal(good.sidebarWidth, 232);
+ assert.equal(good.visualSystemPreserved, true);
+ assert.equal(good.taskPatternPreserved, true);
+ // A stage count is supplementary content, not part of its workflow name.
+ const counted = html.replace("<h3>'+label+'</h3>", '<h3>\'+label+\'<span class="count">1</span></h3>');
+ assert.notEqual(counted, html);
+ const countedFacts = await observe(counted);
+ assert.equal(countedFacts.workflowColumnCount, 5);
+ assert.equal(countedFacts.workflowBetweenRegions, true);
+ assert.equal((await observe(counted.replace("'Review',", ''))).workflowColumnCount, 4);
+ const divLabels = counted.replace('<h3>\'+label+\'', '<div>\'+label+\'').replace('</span></h3>', '</span></div>');
+ const divFacts = await observe(divLabels);
+ assert.equal(divFacts.workflowColumnCount, 5);
+ assert.equal(divFacts.workflowBetweenRegions, true);
+ const flexLabels = html.replace("<h3>'+label+'</h3>", '<header><strong>\'+label+\'</strong></header>')
+ .replace('display:grid;grid-template-columns:repeat(5,minmax(0,1fr))', 'display:flex')
+ .replace('</style>', '.board>section{flex:1}</style>');
+ assert.equal((await observe(flexLabels)).workflowColumnCount, 5);
+ const inlineLabels = html.replace(/<script>[\s\S]*?<\/script>/, '')
+ .replace('<section class="board" id="board"></section>', '<p><span>Intake</span> <span>Planned</span> <span>Building</span> <span>Review</span> <span>Done</span></p>');
+ assert.equal((await observe(inlineLabels)).workflowColumnCount, 0);
+ assert.equal((await observe(html.replace('</style>', '.board{grid-template-columns:1fr}</style>'))).workflowColumnCount, 0);
+ assert.equal((await observe(divLabels.replace('</style>', '#board>section:nth-child(4)>div{visibility:hidden}</style>'))).workflowColumnCount, 4);
+ const countOnly = html.replace("<h3>'+label+'</h3>", '<h3><span class="count">\'+label+\'</span></h3>');
+ assert.equal((await observe(countOnly)).workflowColumnCount, 0);
+ const literal = html.replace(/<script>[\s\S]*?<\/script>/, '<script>const labels=["Intake","Planned","Building","Review","Done"];</script>');
+ assert.equal((await observe(literal)).workflowColumnCount, 0);
+ assert.equal((await observe(html.replace("'Review',", ''))).workflowColumnCount, 4);
+ const hidden = await observe(html.replace('</style>', '#board>section:nth-child(4){display:none}</style>'));
+ assert.equal(hidden.workflowColumnCount, 4);
+ assert.equal(hidden.workflowBetweenRegions, false);
+ const moved = html.replace('<section class="board" id="board"></section>', '')
+ .replace('</main>', '<section class="board" id="board"></section></main>');
+ assert.equal((await observe(moved)).workflowBetweenRegions, false);
+ const reordered = html.replace('</style>', '.project-page{display:flex;flex-direction:column}.board{order:2}</style>');
+ assert.equal((await observe(reordered)).workflowBetweenRegions, false);
+ assert.equal((await observe(html.replace('232px', '280px'))).visualSystemPreserved, false);
+ assert.equal((await observe(html.replaceAll('#17837a', '#12695f'))).visualSystemPreserved, false);
+ assert.equal((await observe(html.replace(/<svg class="icon"[\s\S]*?<\/svg>/, ''))).taskPatternPreserved, false);
+ assert.equal((await observe(html.replace('AC · Alex Chen', 'New account'))).shellPreserved, false);
+ // Package boundary failures must never execute an outside entry.
+ for (const unsafe of ['../index.html', '/tmp/index.html', 'nested\\index.html']) {
+ fs.writeFileSync(manifest, JSON.stringify({ entry: unsafe }));
+ assert.equal(await inspectUiProductArtifact(root, files), undefined);
+ }
+ fs.writeFileSync(manifest, JSON.stringify({ entry: 'index.html' }));
+ const project = path.join(root, 'project');
+ fs.mkdirSync(project);
+ const siblingFiles = files.map(file => `../${file}`);
+ assert.equal(await inspectUiProductArtifact(project, siblingFiles), undefined);
+ assert.equal((await inspectUiProductArtifact(project, siblingFiles, root))?.rendered, true);
+ assert.equal(await inspectUiProductArtifact(project, siblingFiles, project), undefined);
+ assert.equal(await inspectUiProductArtifact(root, [files[0]]), undefined);
+ assert.equal(await inspectUiProductArtifact(root, [...files, files[0]]), undefined);
+ const outside = path.join(root, 'outside.html');
+ fs.writeFileSync(outside, html); fs.unlinkSync(entry); fs.symlinkSync(outside, entry);
+ assert.equal(await inspectUiProductArtifact(root, files), undefined);
+ console.info('ui-product-fidelity-canary=passed rendered-cases=19 boundary-controls=8');
+ return 0;
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+}
diff --git a/test/fixtures/test-log-analysis/expected.fixture.ts b/test/fixtures/test-log-analysis/expected.fixture.ts
new file mode 100644
index 00000000..911d176a
--- /dev/null
+++ b/test/fixtures/test-log-analysis/expected.fixture.ts
@@ -0,0 +1,21 @@
+import { expect, it } from 'vitest';
+import { expectTestLog } from '../../helpers/test-log-analysis';
+
+it('passes a declared recoverable warning', () => {
+ expectTestLog({ level: 'warn', source: 'console', message: /fixture recoverable retry/ });
+ console.warn('fixture recoverable retry', { attempt: 2 });
+ expect(true).toBe(true);
+});
+
+it('passes but surfaces an undeclared warning', () => {
+ console.warn('fixture undeclared warning');
+});
+
+it('passes a declared and asserted error path', () => {
+ expectTestLog({ level: 'error', message: /fixture asserted failure/ });
+ console.error('fixture asserted failure');
+});
+
+it('accepts the structured skill-script progress protocol on stderr', () => {
+ process.stderr.write('{"type":"progress","source":"video_edit","op":"mix","status":"running","elapsed_sec":0.5}\n');
+});
diff --git a/test/fixtures/test-log-analysis/phase.fixture.ts b/test/fixtures/test-log-analysis/phase.fixture.ts
new file mode 100644
index 00000000..6282ba44
--- /dev/null
+++ b/test/fixtures/test-log-analysis/phase.fixture.ts
@@ -0,0 +1,9 @@
+import { afterAll, it } from 'vitest';
+
+process.stderr.write('fixture setup-phase noise\n');
+
+it('passes inside the case', () => {});
+
+afterAll(() => {
+ process.stderr.write('fixture cleanup-phase noise\n');
+});
diff --git a/test/fixtures/test-log-analysis/unexpected.fixture.ts b/test/fixtures/test-log-analysis/unexpected.fixture.ts
new file mode 100644
index 00000000..7361cdb8
--- /dev/null
+++ b/test/fixtures/test-log-analysis/unexpected.fixture.ts
@@ -0,0 +1,22 @@
+import { it } from 'vitest';
+import { expectTestLog } from '../../helpers/test-log-analysis';
+
+it('fails on an unexpected error', () => {
+ console.error('fixture unexpected failure token=fixture-secret-value /Users/test/private-notes.txt');
+});
+
+it('fails on unclassified stderr', () => {
+ process.stderr.write('fixture raw unexplained diagnostic\n');
+});
+
+it('rejects progress look-alikes on stderr', () => {
+ process.stderr.write('{"type":"progressive","status":"running"}\n{"type":"progress", truncated\n');
+});
+
+it('fails when a declared expected log never occurs', () => {
+ expectTestLog({ level: 'error', message: /never emitted/ });
+});
+
+it('keeps an unrelated clean case passing', () => {
+ console.log('fixture info line');
+});
diff --git a/test/fixtures/test-log-analysis/vitest.config.ts b/test/fixtures/test-log-analysis/vitest.config.ts
new file mode 100644
index 00000000..9fb1d8b6
--- /dev/null
+++ b/test/fixtures/test-log-analysis/vitest.config.ts
@@ -0,0 +1,20 @@
+// Negative-control harness for the default test log analysis. It reuses the
+// real PC Vitest config (setup tap + reporter) and only narrows the inventory.
+// ORKAS_LOG_FIXTURE_NO_TAP removes the tap to prove the reporter's coverage gate.
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from 'vitest/config';
+import base from '../../../vitest.config';
+
+const reporters = [...(base.test?.reporters as unknown[])];
+if (process.env.ORKAS_LOG_FIXTURE_JSON) reporters.push(['json', { outputFile: process.env.ORKAS_LOG_FIXTURE_JSON }]);
+
+export default defineConfig({
+ ...base,
+ test: {
+ ...base.test,
+ root: fileURLToPath(new URL('../../..', import.meta.url)),
+ include: ['test/fixtures/test-log-analysis/*.fixture.ts'],
+ setupFiles: process.env.ORKAS_LOG_FIXTURE_NO_TAP === '1' ? [] : base.test?.setupFiles,
+ reporters: reporters as never,
+ },
+});
diff --git a/test/helpers/test-log-analysis.ts b/test/helpers/test-log-analysis.ts
new file mode 100644
index 00000000..d66d29b1
--- /dev/null
+++ b/test/helpers/test-log-analysis.ts
@@ -0,0 +1,275 @@
+/**
+ * Default per-case log analysis for every Vitest file (installed by
+ * `test/setup-env.ts`; summarized by `test/log-analysis-reporter.ts`).
+ *
+ * Inside a test worker the tap observes console calls (level known at the call)
+ * and raw `process.stdout/stderr` writes (direct writes, Node warnings and
+ * Worker-thread output such as the log-delivery console mirror). Each record is
+ * classified by the shared `model-eval-log-policy.mjs` collector and attributed
+ * to the active case, or to the file's `setup` (before the first case) or
+ * `cleanup` (outside a case afterwards) phase. Console records are attributed
+ * at the call; raw writes at arrival, so a Worker-thread line delayed past its
+ * case boundary lands in the following scope.
+ *
+ * A case fails on unexpected error-level output, unclassified stderr, a log
+ * coverage gap, or a declared expectation that never occurred. Warnings are
+ * surfaced, never failed. Only bounded, redacted signatures leave the worker.
+ * Blind spot: bytes written straight to the file descriptors by child
+ * processes spawned with inherited stdio bypass this tap.
+ */
+import { formatWithOptions } from 'node:util';
+import { afterAll, afterEach, beforeEach } from 'vitest';
+import { createModelEvalLogCollector } from '../../scripts/model-eval-log-policy.mjs';
+import { sanitizeLogTextForUpload } from '../../src/main/util/log-sanitize';
+import { TEST_LOG_META_KEY } from '../log-analysis-reporter';
+
+export type TestLogLevel = 'warn' | 'error';
+export type TestLogPhase = 'case' | 'setup' | 'cleanup';
+
+/** A case's explicit statement that it asserts this output and its recovery. */
+export interface ExpectedTestLog {
+ level: TestLogLevel;
+ /** Logger scope, `console`, `stderr`, `node`, ... as classified by the policy. */
+ source?: string;
+ /** Matched against the unredacted message inside the worker only. */
+ message: RegExp;
+}
+
+export interface TestLogSignature {
+ severity: 'warning' | 'error';
+ code: string;
+ source: string;
+ phase: TestLogPhase;
+ signature: string;
+ count: number;
+ expected: boolean;
+}
+
+export interface TestLogScopeSummary {
+ phase: TestLogPhase;
+ capturedLineCount: number;
+ analyzedLineCount: number;
+ levelCounts: { debug: number; info: number; warn: number; error: number };
+ streamLineCounts: { stdout: number; stderr: number };
+ unexpectedErrorCount: number;
+ expectedCount: number;
+ unmetExpectations: number;
+ coveragePassed: boolean;
+ signatures: TestLogSignature[];
+ omittedSignatureCount: number;
+}
+
+const MAX_SIGNATURES = 20;
+const MAX_SIGNATURE_CHARS = 160;
+const RUNTIME_PREFIX_RE = /^\[\d{2}:\d{2}:\d{2}\.\d{3}\]\s+\[(?:debug|info|warn|error)\]\s+\[\s*\([^)]*\)\s*\]\s*/i;
+const ANSI_RE = /\x1b\[[0-9;]*m/g;
+const CONSOLE_LEVELS = { debug: 'debug', log: 'info', info: 'info', dir: 'info', warn: 'warn', error: 'error' } as const;
+
+/** Redacted, de-numbered message template; never the raw line. */
+export function testLogSignature(line: string | undefined): string {
+ const message = String(line ?? '').replace(RUNTIME_PREFIX_RE, '');
+ const text = sanitizeLogTextForUpload(message)
+ .replace(/<(?:abs|cloud|file-url)-path:[a-f0-9]{12}>|\d+/g, match => (match.startsWith('<') ? match : '#'))
+ .replace(/\s+/g, ' ')
+ .trim();
+ return text.length > MAX_SIGNATURE_CHARS ? `${text.slice(0, MAX_SIGNATURE_CHARS - 1)}…` : text || '<empty>';
+}
+
+interface Scope {
+ phase: TestLogPhase;
+ collector: ReturnType<typeof createModelEvalLogCollector>;
+ signatures: Map<string, TestLogSignature>;
+ omitted: number;
+ expectations: { spec: ExpectedTestLog; hits: number }[];
+ expectedCount: number;
+ unexpectedErrorCount: number;
+}
+
+interface TapState {
+ current: Scope;
+ fileExpectations: { spec: ExpectedTestLog; hits: number }[];
+ setup: Scope;
+ cleanup?: Scope;
+}
+
+const STATE_KEY = Symbol.for('orkas.test.log-analysis');
+
+function newScope(phase: TestLogPhase, expectations: Scope['expectations']): Scope {
+ const scope: Scope = {
+ phase, signatures: new Map(), omitted: 0, expectations, expectedCount: 0, unexpectedErrorCount: 0,
+ collector: undefined as never,
+ };
+ scope.collector = createModelEvalLogCollector(phase, {
+ maxLineChars: 1024 * 1024,
+ onFinding: (finding: { severity: 'warning' | 'error'; code: string; source?: string }, line?: string) => {
+ const source = finding.source || 'unknown';
+ const message = String(line ?? '').replace(RUNTIME_PREFIX_RE, '');
+ const level: TestLogLevel = finding.severity === 'error' ? 'error' : 'warn';
+ const match = scope.expectations.find(({ spec }) => spec.level === level
+ && (spec.source === undefined || spec.source === source) && spec.message.test(message));
+ if (match) { match.hits += 1; scope.expectedCount += 1; }
+ else if (finding.severity === 'error') scope.unexpectedErrorCount += 1;
+ const signature = testLogSignature(line);
+ const key = [finding.severity, finding.code, source, signature, Boolean(match)].join('\0');
+ const existing = scope.signatures.get(key);
+ if (existing) existing.count += 1;
+ else if (scope.signatures.size < MAX_SIGNATURES) {
+ scope.signatures.set(key, {
+ severity: finding.severity, code: finding.code, source, phase, signature, count: 1, expected: Boolean(match),
+ });
+ } else scope.omitted += 1;
+ },
+ });
+ return scope;
+}
+
+function summarize(scope: Scope): TestLogScopeSummary {
+ const analysis = scope.collector.finish();
+ const unmetExpectations = scope.expectations.filter(item => item.hits === 0).length;
+ return {
+ phase: scope.phase,
+ capturedLineCount: analysis.capturedLineCount,
+ analyzedLineCount: analysis.analyzedLineCount,
+ levelCounts: { debug: 0, info: 0, warn: 0, error: 0, ...analysis.levelCounts },
+ streamLineCounts: { stdout: 0, stderr: 0, ...analysis.streamLineCounts },
+ unexpectedErrorCount: scope.unexpectedErrorCount,
+ expectedCount: scope.expectedCount,
+ unmetExpectations,
+ coveragePassed: analysis.coveragePassed,
+ signatures: [...scope.signatures.values()],
+ omittedSignatureCount: scope.omitted,
+ };
+}
+
+/** Failure text names classes and redacted signatures only. */
+export function testLogFailure(summary: TestLogScopeSummary): string | null {
+ const reasons: string[] = [];
+ if (!summary.coveragePassed) reasons.push(`log coverage ${summary.analyzedLineCount}/${summary.capturedLineCount}`);
+ if (summary.unexpectedErrorCount) {
+ const shown = summary.signatures.filter(item => item.severity === 'error' && !item.expected).slice(0, 5)
+ .map(item => `${item.code} [${item.source}] x${item.count}: ${item.signature}`);
+ reasons.push(`${summary.unexpectedErrorCount} unexpected error-level/unclassified stderr record(s): ${shown.join('; ')}`);
+ }
+ if (summary.unmetExpectations) reasons.push(`${summary.unmetExpectations} declared expected log(s) did not occur`);
+ return reasons.length
+ ? `[test-log-analysis] ${summary.phase} output failed: ${reasons.join(' | ')}. Fix the cause, or assert the path and declare it with expectTestLog().`
+ : null;
+}
+
+function tapState(): TapState | undefined {
+ return (globalThis as Record<symbol, TapState | undefined>)[STATE_KEY];
+}
+
+/**
+ * Declare output that the current case (or, outside a case, this file's
+ * setup/cleanup phases) deliberately produces and asserts. Matching records are
+ * surfaced as expected instead of failing; a declaration that never matches
+ * fails, so stale declarations cannot hide later regressions.
+ */
+export function expectTestLog(spec: ExpectedTestLog): void {
+ const state = tapState();
+ if (!state) throw new Error('test log analysis is not installed');
+ const entry = { spec, hits: 0 };
+ if (state.current.phase === 'case') state.current.expectations.push(entry);
+ else state.fileExpectations.push(entry);
+}
+
+function formatConsoleRecord(level: string, args: unknown[]): string {
+ let text: string;
+ try { text = formatWithOptions({ colors: false }, ...args); } catch { text = '[unformattable console arguments]'; }
+ return `[00:00:00.000] [${level}] [(console)] ${text.replace(ANSI_RE, '').replace(/\r?\n/g, ' \\n ')}\n`;
+}
+
+/** Skill scripts report progress as one JSON object per stderr line; the
+ * product consumer (`model/core-agent/local-tools.ts` progress parser) accepts
+ * exactly `{"type":"progress",...}` lines up to 64 KiB. */
+export function isScriptProgressLine(line: string): boolean {
+ if (line.length > 64 * 1024 || !line.startsWith('{')) return false;
+ try {
+ const parsed = JSON.parse(line) as unknown;
+ return !!parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ && (parsed as Record<string, unknown>).type === 'progress';
+ } catch { return false; }
+}
+
+function installStreamTaps(state: TapState): void {
+ const ingest = (stream: 'stdout' | 'stderr', chunk: unknown, encoding?: unknown) => {
+ try {
+ let text = typeof chunk === 'string' ? chunk
+ : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding as BufferEncoding : 'utf8')
+ : String(chunk);
+ text = text.replace(ANSI_RE, '');
+ // Classify only whole-line writes; a split record stays unclassified.
+ if (stream === 'stderr' && text.endsWith('\n') && text.includes('"progress"')) {
+ text = text.slice(0, -1).split('\n').map(line => (isScriptProgressLine(line.replace(/\r$/, ''))
+ ? '[00:00:00.000] [info] [(script-progress)] progress record' : line)).join('\n') + '\n';
+ }
+ state.current.collector.ingest(stream, text);
+ } catch { /* Analysis must not break the test's own output. */ }
+ };
+ for (const stream of ['stdout', 'stderr'] as const) {
+ const target = process[stream];
+ const original = target.write;
+ target.write = function tappedWrite(this: typeof target, chunk: unknown, ...rest: unknown[]) {
+ ingest(stream, chunk, rest[0]);
+ return (original as (...args: unknown[]) => boolean).call(this, chunk, ...rest);
+ } as typeof target.write;
+ }
+ for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {
+ const original = (console as unknown as Record<string, (...args: unknown[]) => void>)[method];
+ if (typeof original !== 'function') continue;
+ const stream = level === 'warn' || level === 'error' ? 'stderr' : 'stdout';
+ (console as unknown as Record<string, unknown>)[method] = function tappedConsole(...args: unknown[]) {
+ try { state.current.collector.ingest(stream, formatConsoleRecord(level, args)); } catch { /* keep logging */ }
+ return original.apply(console, args);
+ };
+ }
+}
+
+/**
+ * Called by `test/setup-env.ts` for every test file. Stream taps install once
+ * per worker global (a reused worker keeps them); scopes and hooks are per file.
+ */
+export function installTestLogAnalysis(): void {
+ let state = tapState();
+ const fileExpectations: Scope['expectations'] = [];
+ const setup = newScope('setup', fileExpectations);
+ if (state) Object.assign(state, { current: setup, fileExpectations, setup, cleanup: undefined });
+ else {
+ state = { current: setup, fileExpectations, setup };
+ (globalThis as Record<symbol, TapState | undefined>)[STATE_KEY] = state;
+ installStreamTaps(state);
+ }
+ const fileState = state;
+
+ beforeEach(() => {
+ fileState.current = newScope('case', []);
+ });
+ afterEach(({ task }) => {
+ const scope = fileState.current;
+ fileState.cleanup ??= newScope('cleanup', fileState.fileExpectations);
+ fileState.current = fileState.cleanup;
+ if (scope.phase !== 'case') return;
+ const summary = summarize(scope);
+ (task.meta as Record<string, unknown>)[TEST_LOG_META_KEY] = summary;
+ const failure = testLogFailure(summary);
+ // A case that already failed keeps its own failure; its log findings stay
+ // in the summary without adding a second, less relevant error.
+ if (failure && !task.result?.errors?.length) throw new Error(failure);
+ });
+ // eslint-disable-next-line no-empty-pattern -- Vitest requires a destructured context.
+ afterAll(({}, suite) => {
+ const phases = [summarize(fileState.setup), ...(fileState.cleanup ? [summarize(fileState.cleanup)] : [])];
+ // File-level declarations may be satisfied in either phase.
+ const unmet = fileState.fileExpectations.filter(item => item.hits === 0).length;
+ for (const phase of phases) phase.unmetExpectations = 0;
+ phases[phases.length - 1].unmetExpectations = unmet;
+ (suite.meta as Record<string, unknown>)[TEST_LOG_META_KEY] = phases;
+ // Output after the last hook (worker teardown) has no reporting channel.
+ fileState.setup = newScope('setup', []);
+ fileState.cleanup = undefined;
+ fileState.current = fileState.setup;
+ const failures = phases.map(testLogFailure).filter(Boolean);
+ if (failures.length) throw new Error(failures.join('\n'));
+ });
+}
diff --git a/test/log-analysis-reporter.ts b/test/log-analysis-reporter.ts
new file mode 100644
index 00000000..d57791c6
--- /dev/null
+++ b/test/log-analysis-reporter.ts
@@ -0,0 +1,130 @@
+/**
+ * Default Vitest reporter half of the test log policy (Common/docs/
+ * test-case-design.md §3.1). The worker tap (`helpers/test-log-analysis.ts`)
+ * fails the owning case/file on unexpected errors; this reporter prints the
+ * attributed, redacted summary after every run and fails the run when any
+ * executed case or file lacks analysis (coverage gap), so a missing tap cannot
+ * pass silently. Printed text is bounded and built only from redacted
+ * signatures, repository-relative test files and test names.
+ */
+import { relative } from 'node:path';
+import type { Reporter, TestModule } from 'vitest/node';
+import type { TestLogScopeSummary, TestLogSignature } from './helpers/test-log-analysis';
+
+/** Task-meta key shared with the worker tap; this module must not load Vitest's runtime. */
+export const TEST_LOG_META_KEY = 'orkasLogAnalysis';
+
+const MAX_SIGNATURE_LINES = 40;
+const MAX_FILE_LINES = 30;
+const MAX_OWNERS = 3;
+
+interface Owned extends TestLogSignature { owners: string[]; ownerCount: number }
+
+export interface TestLogRunSummary {
+ status: 'PASS' | 'WARN' | 'FAIL';
+ files: number;
+ cases: number;
+ lines: number;
+ levels: { debug: number; info: number; warn: number; error: number };
+ unexpected: number;
+ expected: number;
+ unmetExpectations: number;
+ coverageGaps: string[];
+ signatures: Owned[];
+ fileLevels: { file: string; warn: number; error: number; casesWithFindings: number }[];
+ omittedSignatures: number;
+}
+
+export function summarizeTestLogs(modules: readonly TestModule[], root: string): TestLogRunSummary {
+ const summary: TestLogRunSummary = {
+ status: 'PASS', files: 0, cases: 0, lines: 0, levels: { debug: 0, info: 0, warn: 0, error: 0 },
+ unexpected: 0, expected: 0, unmetExpectations: 0, coverageGaps: [], signatures: [], fileLevels: [], omittedSignatures: 0,
+ };
+ const signatures = new Map<string, Owned>();
+ const add = (scope: TestLogScopeSummary, owner: string) => {
+ summary.lines += scope.capturedLineCount;
+ for (const level of ['debug', 'info', 'warn', 'error'] as const) summary.levels[level] += scope.levelCounts[level] || 0;
+ summary.unexpected += scope.unexpectedErrorCount;
+ summary.expected += scope.expectedCount;
+ summary.unmetExpectations += scope.unmetExpectations;
+ summary.omittedSignatures += scope.omittedSignatureCount;
+ if (!scope.coveragePassed) summary.coverageGaps.push(`${owner} (${scope.analyzedLineCount}/${scope.capturedLineCount})`);
+ for (const item of scope.signatures) {
+ const key = [item.severity, item.code, item.source, item.signature, item.expected].join('\0');
+ const existing = signatures.get(key);
+ if (!existing) signatures.set(key, { ...item, owners: [owner], ownerCount: 1 });
+ else {
+ existing.count += item.count;
+ existing.ownerCount += 1;
+ if (existing.owners.length < MAX_OWNERS) existing.owners.push(owner);
+ }
+ }
+ return (scope.levelCounts.warn || 0) + (scope.levelCounts.error || 0) + scope.unexpectedErrorCount > 0;
+ };
+ for (const module of modules) {
+ const file = relative(root, module.moduleId).replace(/\\/g, '/');
+ let executed = 0;
+ let withFindings = 0;
+ const before = { ...summary.levels };
+ for (const testCase of module.children.allTests()) {
+ const state = testCase.result().state;
+ if (state !== 'passed' && state !== 'failed') continue;
+ executed += 1;
+ const scope = testCase.meta()[TEST_LOG_META_KEY as keyof ReturnType<typeof testCase.meta>] as TestLogScopeSummary | undefined;
+ const owner = `${file} > ${testCase.fullName}`;
+ if (!scope) { summary.coverageGaps.push(`${owner} (no analysis)`); continue; }
+ if (add(scope, owner)) withFindings += 1;
+ }
+ if (!executed) continue;
+ summary.files += 1;
+ summary.cases += executed;
+ const phases = module.meta()[TEST_LOG_META_KEY as keyof ReturnType<typeof module.meta>] as TestLogScopeSummary[] | undefined;
+ if (!Array.isArray(phases)) summary.coverageGaps.push(`${file} [setup/cleanup] (no analysis)`);
+ else for (const phase of phases) add(phase, `${file} [${phase.phase}]`);
+ const warn = summary.levels.warn - before.warn;
+ const error = summary.levels.error - before.error;
+ if (warn || error) summary.fileLevels.push({ file, warn, error, casesWithFindings: withFindings });
+ }
+ summary.signatures = [...signatures.values()].sort((a, b) => (a.severity === b.severity ? b.count - a.count : a.severity === 'error' ? -1 : 1));
+ summary.status = summary.unexpected || summary.unmetExpectations || summary.coverageGaps.length ? 'FAIL'
+ : summary.signatures.length ? 'WARN' : 'PASS';
+ return summary;
+}
+
+export function formatTestLogSummary(summary: TestLogRunSummary): string {
+ const out = [`[test-log-analysis] ${summary.status} files=${summary.files} cases=${summary.cases} lines=${summary.lines}`
+ + ` debug=${summary.levels.debug} info=${summary.levels.info} warn=${summary.levels.warn} error=${summary.levels.error}`
+ + ` unexpected=${summary.unexpected} expected=${summary.expected} unmet=${summary.unmetExpectations} gaps=${summary.coverageGaps.length}`];
+ if (summary.signatures.length) {
+ out.push('[test-log-analysis] distinct signatures (severity, count, code [source], owner):');
+ for (const item of summary.signatures.slice(0, MAX_SIGNATURE_LINES)) {
+ const owners = item.owners.join(' | ') + (item.ownerCount > item.owners.length ? ` | +${item.ownerCount - item.owners.length} more` : '');
+ out.push(` ${item.severity}${item.expected ? ' (expected)' : ''} x${item.count} ${item.code} [${item.source}] ${item.signature} <- ${owners}`);
+ }
+ if (summary.signatures.length > MAX_SIGNATURE_LINES) out.push(` +${summary.signatures.length - MAX_SIGNATURE_LINES} more signatures`);
+ }
+ if (summary.omittedSignatures) out.push(`[test-log-analysis] ${summary.omittedSignatures} record(s) beyond the per-scope signature cap are counted but not listed`);
+ if (summary.fileLevels.length) {
+ out.push('[test-log-analysis] files with warn/error output:');
+ for (const item of summary.fileLevels.slice(0, MAX_FILE_LINES)) {
+ out.push(` ${item.file} warn=${item.warn} error=${item.error} cases=${item.casesWithFindings}`);
+ }
+ if (summary.fileLevels.length > MAX_FILE_LINES) out.push(` +${summary.fileLevels.length - MAX_FILE_LINES} more files`);
+ }
+ for (const gap of summary.coverageGaps.slice(0, MAX_FILE_LINES)) out.push(`[test-log-analysis] coverage gap: ${gap}`);
+ return `${out.join('\n')}\n`;
+}
+
+export class TestLogAnalysisReporter implements Reporter {
+ private root = process.cwd();
+
+ onInit(vitest: { config: { root: string } }): void {
+ this.root = vitest.config.root;
+ }
+
+ onTestRunEnd(modules: readonly TestModule[]): void {
+ const summary = summarizeTestLogs(modules, this.root);
+ process.stdout.write(formatTestLogSummary(summary));
+ if (summary.status === 'FAIL') process.exitCode = 1;
+ }
+}
diff --git a/test/main/core-regression.test.ts b/test/main/core-regression.test.ts
index 84e61d02..11376dfe 100644
--- a/test/main/core-regression.test.ts
+++ b/test/main/core-regression.test.ts
@@ -241,7 +241,7 @@ describe('PC core regression unit coverage', () => {
expect(source).toContain('========== FILE: assets/app.js ==========');
}
- expect(savedApps.deleteSavedApp(TEST_UID, saved.id).ok).toBe(true);
+ expect((await savedApps.deleteSavedApp(TEST_UID, saved.id)).ok).toBe(true);
expect(savedApps.listSavedApps(TEST_UID)).toEqual([]);
});
diff --git a/test/main/features/idle_sleep_guard.test.ts b/test/main/features/idle_sleep_guard.test.ts
new file mode 100644
index 00000000..92678e49
--- /dev/null
+++ b/test/main/features/idle_sleep_guard.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn() }));
+vi.mock('../../../src/main/logger', () => ({ createLogger: () => ({ info: mocks.info, warn: mocks.warn }) }));
+
+import {
+ IDLE_SLEEP_GUARD_INTERVAL_MS,
+ startIdleSleepGuard,
+} from '../../../src/main/features/idle_sleep_guard';
+
+function fakeBlocker() {
+ let nextId = 1;
+ const held = new Set<number>();
+ return {
+ held,
+ start: vi.fn((_type: 'prevent-app-suspension') => {
+ const id = nextId++;
+ held.add(id);
+ return id;
+ }),
+ stop: vi.fn((id: number) => { held.delete(id); }),
+ };
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('keeping the computer awake while Agent work runs', () => {
+ it('never blocks idle sleep while nothing runs', () => {
+ const blocker = fakeBlocker();
+ const guard = startIdleSleepGuard({ blocker, hasActiveWork: () => false });
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS * 5);
+ expect(blocker.start).not.toHaveBeenCalled();
+ guard.stop();
+ });
+
+ it('holds one app-suspension blocker for the whole run and releases it after the run ends', () => {
+ const blocker = fakeBlocker();
+ let active = true;
+ const guard = startIdleSleepGuard({ blocker, hasActiveWork: () => active });
+
+ expect(blocker.start).toHaveBeenCalledTimes(1);
+ expect(blocker.start).toHaveBeenCalledWith('prevent-app-suspension');
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS * 3);
+ expect(blocker.start).toHaveBeenCalledTimes(1);
+ expect(blocker.held.size).toBe(1);
+
+ active = false;
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS);
+ expect(blocker.stop).toHaveBeenCalledTimes(1);
+ expect(blocker.held.size).toBe(0);
+
+ active = true;
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS);
+ expect(blocker.start).toHaveBeenCalledTimes(2);
+ expect(blocker.held.size).toBe(1);
+ guard.stop();
+ });
+
+ it('picks up work that starts while the app is idle within one interval', () => {
+ const blocker = fakeBlocker();
+ let active = false;
+ const guard = startIdleSleepGuard({ blocker, hasActiveWork: () => active });
+ active = true;
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS - 1);
+ expect(blocker.start).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(blocker.start).toHaveBeenCalledTimes(1);
+ guard.stop();
+ });
+
+ it('releases the blocker and stops polling when the app quits', () => {
+ const blocker = fakeBlocker();
+ const hasActiveWork = vi.fn(() => true);
+ const guard = startIdleSleepGuard({ blocker, hasActiveWork });
+ guard.stop();
+ guard.stop();
+ expect(blocker.stop).toHaveBeenCalledTimes(1);
+ expect(blocker.held.size).toBe(0);
+ const checks = hasActiveWork.mock.calls.length;
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS * 5);
+ guard.sync();
+ expect(hasActiveWork).toHaveBeenCalledTimes(checks);
+ expect(blocker.start).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not keep the machine awake when the work signal cannot be read', () => {
+ const blocker = fakeBlocker();
+ let broken = false;
+ const guard = startIdleSleepGuard({
+ blocker,
+ hasActiveWork: () => {
+ if (broken) throw new Error('bus unavailable');
+ return true;
+ },
+ });
+ expect(blocker.held.size).toBe(1);
+ broken = true;
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS);
+ expect(blocker.held.size).toBe(0);
+ guard.stop();
+ });
+
+ it('retries on the next tick when the system refuses the blocker, without throwing', () => {
+ const blocker = fakeBlocker();
+ blocker.start.mockImplementationOnce(() => { throw new Error('assertion refused'); });
+ const guard = startIdleSleepGuard({ blocker, hasActiveWork: () => true });
+ expect(blocker.held.size).toBe(0);
+ expect(mocks.warn).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(IDLE_SLEEP_GUARD_INTERVAL_MS);
+ expect(blocker.start).toHaveBeenCalledTimes(2);
+ expect(blocker.held.size).toBe(1);
+ guard.stop();
+ });
+});
diff --git a/test/main/features/local_access_policy.test.ts b/test/main/features/local_access_policy.test.ts
index dd133a2a..8816f3cc 100644
--- a/test/main/features/local_access_policy.test.ts
+++ b/test/main/features/local_access_policy.test.ts
@@ -94,6 +94,45 @@ describe('local_access_policy', () => {
)).toEqual(['sensitive_path']);
});
+ it('offers a folder grant only for reads sensitive solely for their personal location', async () => {
+ const previousHome = process.env.HOME;
+ const previousUserProfile = process.env.USERPROFILE;
+ const home = path.join(tmpDir, 'home');
+ process.env.HOME = home;
+ if (process.platform === 'win32') process.env.USERPROFILE = home;
+ try {
+ const policy = await import('../../../src/main/features/local_access_policy');
+ const ads = path.join(home, 'Desktop', 'ads');
+ fs.mkdirSync(ads, { recursive: true });
+ fs.mkdirSync(path.join(home, '.ssh'), { recursive: true });
+ const image = path.join(ads, 'a.png');
+ fs.writeFileSync(image, 'png');
+ fs.writeFileSync(path.join(ads, '.env'), 'TOKEN=1');
+ fs.writeFileSync(path.join(home, '.ssh', 'config'), 'Host x');
+ fs.symlinkSync(path.join(home, '.ssh', 'config'), path.join(ads, 'notes.txt'));
+ fs.writeFileSync(path.join(tmpDir, 'plain.txt'), 'plain');
+
+ expect(policy.locationOnlyRead(image)).toEqual({
+ folder: ads, realPath: fs.realpathSync(image), realFolder: fs.realpathSync(ads),
+ });
+ // A listed directory grants itself; a file not created yet, its parent.
+ expect(policy.locationOnlyRead(ads)).toMatchObject({ folder: ads, realFolder: fs.realpathSync(ads) });
+ expect(policy.locationOnlyRead(path.join(ads, 'later.png'))).toMatchObject({ folder: ads });
+ // Intrinsic secrets, links to them, unprotected paths and trusted
+ // workspaces never carry a folder grant.
+ expect(policy.locationOnlyRead(path.join(ads, '.env'))).toBeUndefined();
+ expect(policy.locationOnlyRead(path.join(home, '.ssh', 'config'))).toBeUndefined();
+ expect(policy.locationOnlyRead(path.join(ads, 'notes.txt'))).toBeUndefined();
+ expect(policy.locationOnlyRead(path.join(tmpDir, 'plain.txt'))).toBeUndefined();
+ expect(policy.locationOnlyRead(image, { trustedRoots: [ads] })).toBeUndefined();
+ } finally {
+ if (previousHome === undefined) delete process.env.HOME;
+ else process.env.HOME = previousHome;
+ if (previousUserProfile === undefined) delete process.env.USERPROFILE;
+ else process.env.USERPROFILE = previousUserProfile;
+ }
+ });
+
it('applies server-configured sensitive paths and command patterns immediately', async () => {
const { clientConfig } = await import('../../../src/main/features/client_config');
const policy = await import('../../../src/main/features/local_access_policy');
diff --git a/test/main/i18n.test.ts b/test/main/i18n.test.ts
index ee880ea8..bc5ec413 100644
--- a/test/main/i18n.test.ts
+++ b/test/main/i18n.test.ts
@@ -230,3 +230,20 @@ describe('i18n › acceptLanguageHeader', () => {
expect(acceptLanguageHeader('pt').startsWith('pt-BR')).toBe(true);
});
});
+
+describe('stopped summary notices', () => {
+ it.each(LOCALES.map(locale => locale.code))('has local copy and interpolates the actual cap in %s', async lang => {
+ const fs = await import('node:fs');
+ const path = await import('node:path');
+ const table = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../src/main/locales', `${lang}.json`), 'utf8'));
+ for (const key of ['model.stopped_tool_limit_summary_incomplete', 'model.stopped_repeat_summary_incomplete', 'model.stopped_summary_incomplete']) {
+ expect(typeof table[key]).toBe('string');
+ expect(table[key].length).toBeGreaterThan(0);
+ const actual = t(key, { limit: 37 }, lang);
+ expect(actual).toBe(table[key].replace('{limit}', '37'));
+ expect(actual).not.toContain('{limit}');
+ if (key.includes('tool_limit')) expect(actual).toContain('37');
+ if (lang !== 'en') expect(actual).not.toBe(t(key, { limit: 37 }, 'en'));
+ }
+ });
+});
diff --git a/test/main/index-process.test.ts b/test/main/index-process.test.ts
index 1510c4cf..73b9a8a4 100644
--- a/test/main/index-process.test.ts
+++ b/test/main/index-process.test.ts
@@ -40,7 +40,9 @@ describe('main process child-process ownership', () => {
expect(relaunchBlock).toContain('windowsVerbatimArguments: resolved.windowsVerbatimArguments');
expect(relaunchBlock).toContain('env: childEnv');
expect(relaunchBlock).toContain('child.unref()');
- expect(relaunchBlock).toContain('await openLifecycleTracking?.flushQuit()');
+ expect(relaunchBlock).toContain('await prepareShutdown()');
+ expect(source).toContain('registerIpc(flushForShutdown)');
+ expect(source).toContain('const lifecycleFlush = openLifecycleTracking?.flushQuit()');
const shellLauncher = fs.readFileSync(
path.resolve(process.cwd(), 'run.sh'),
diff --git a/test/main/ipc/import-local-files.test.ts b/test/main/ipc/import-local-files.test.ts
index 417fa184..1a793e97 100644
--- a/test/main/ipc/import-local-files.test.ts
+++ b/test/main/ipc/import-local-files.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { expectTestLog } from '../../helpers/test-log-analysis';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -104,6 +105,9 @@ describe('add a user-selected local file to conversation attachments', () => {
['txt', 'text'], ['pdf', 'pdf'], ['docx', 'docx'], ['xlsx', 'spreadsheet'],
['pptx', 'presentation'], ['zip', 'archive'], ['mp4', 'video'],
])('copies an unrecorded external %s file and reuses its pending attachment on repeat', async (ext, kind) => {
+ // The two rejected reads/deletes of the original path are asserted below.
+ expectTestLog({ level: 'error', source: 'ipc', message: /^invoke produced\.readText failed \{ error: 'path is outside the user workspace'/ });
+ expectTestLog({ level: 'error', source: 'ipc', message: /^invoke workspace\.deletePath failed \{ error: 'path/ });
const fixtures: Record<string, Buffer> = {
pdf: makeMinimalPdf(['Selected document']), docx: makeMinimalDocx({ paragraphs: ['Selected document'] }),
xlsx: makeMinimalXlsx(), pptx: makeMinimalPptx(),
@@ -263,6 +267,8 @@ describe('manual attachment import boundaries', () => {
['conversations.attachments.import', { cid: CID }],
['autoTasks.attachments.import', { taskId: 'at_12345678' }],
])('rejects invalid paths and untrusted senders for %s without copying files', async (channel, target) => {
+ // Each invalid path is asserted to resolve { ok: false } below.
+ expectTestLog({ level: 'error', source: 'ipc', message: new RegExp(`^invoke ${channel.replace(/\./g, '\\.')} failed \\{`) });
const abs = sourceFile('note.md', '# note\n');
for (const invalidPath of ['', 'desktop/note.md', abs + '\0']) {
await expect(invoke(channel, { ...target, path: invalidPath })).resolves.toMatchObject({ ok: false });
@@ -275,6 +281,9 @@ describe('manual attachment import boundaries', () => {
});
it('reports missing and unsupported scheduled-task selections and allows a corrected retry', async () => {
+ // Both rejections are asserted with their error before the corrected retry.
+ expectTestLog({ level: 'error', source: 'ipc', message: /^invoke autoTasks\.attachments\.import failed \{ error: 'file not found'/ });
+ expectTestLog({ level: 'error', source: 'ipc', message: /^invoke autoTasks\.attachments\.import failed \{ error: 'unsupported/ });
const taskId = 'at_12345678';
const abs = sourceFile('brief.txt', 'restored source', 'downloads');
const unsupported = sourceFile('program.exe', 'unsupported');
diff --git a/test/main/platform-process-coverage.test.ts b/test/main/platform-process-coverage.test.ts
index 33419097..2cf01429 100644
--- a/test/main/platform-process-coverage.test.ts
+++ b/test/main/platform-process-coverage.test.ts
@@ -38,6 +38,10 @@ const PROCESS_OWNER_SUITE: Record<string, ProcessOwner> = {
suite: 'test/main/features/local_agents/base.test.ts',
evidence: 'killProcessTree',
},
+ 'src/main/features/local_agents/upgrade.ts': {
+ suite: 'test/main/features/local_agents/upgrade.test.ts',
+ evidence: 'runUpgradeCommand',
+ },
'src/main/features/local_agents/version.ts': {
suite: 'test/main/features/local_agents/version.test.ts',
evidence: 'detectVersion',
@@ -62,6 +66,10 @@ const PROCESS_OWNER_SUITE: Record<string, ProcessOwner> = {
suite: 'test/main/features/video_studio_native_qa.test.ts',
evidence: 'runVideoProcessForTest',
},
+ 'src/main/features/web_assist_passkey.ts': {
+ suite: 'test/main/features/web_assist_passkey.test.ts',
+ evidence: 'attachWebAssistPasskeys',
+ },
'src/main/model/core-agent/interactive-cli-sessions.ts': {
suite: 'test/main/model/local-tools.test.ts',
evidence: 'startInteractiveCliSession',
diff --git a/test/main/quality/dependency-security.test.ts b/test/main/quality/dependency-security.test.ts
new file mode 100644
index 00000000..1db9c70e
--- /dev/null
+++ b/test/main/quality/dependency-security.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+const proxyaddr = require('proxy-addr');
+const { SourceMapConsumer } = require('source-map-js');
+
+describe('dependency security boundaries', () => {
+ it.each(['203.0.113.9', '::ffff:203.0.113.9'])(
+ 'does not accept a forwarded identity from an untrusted peer %s', address => {
+ const request = {
+ socket: { remoteAddress: address },
+ headers: { 'x-forwarded-for': '192.0.2.10' },
+ };
+ for (const ranges of [['::ffff:10.0.0.0/8'], ['::ffff:10.0.0.0/8', '::1/128']]) {
+ expect(proxyaddr(request, proxyaddr.compile(ranges))).toBe(address);
+ }
+ },
+ );
+
+ it('preserves explicitly trusted IPv4-mapped proxy subnets', () => {
+ const request = {
+ socket: { remoteAddress: '::ffff:10.2.3.4' },
+ headers: { 'x-forwarded-for': '192.0.2.10' },
+ };
+ expect(proxyaddr(request, proxyaddr.compile('::ffff:10.0.0.0/104'))).toBe('192.0.2.10');
+ });
+
+ const leaf = { version: 3, sources: ['input.js'], names: [], mappings: 'AAAA' };
+ const indexed = (line: number, map: unknown = leaf) => ({
+ version: 3, sections: [{ offset: { line, column: 0 }, map }],
+ });
+
+ it('rejects tiny source maps that would amplify into enormous generated output', () => {
+ // Construction must reject the input before a build tool serializes it.
+ // Do not actually allocate the unbounded output on an unpatched version.
+ expect(() => new SourceMapConsumer(indexed(1_000_000_000))).toThrow();
+ expect(() => new SourceMapConsumer(indexed(6_000_000, indexed(6_000_000)))).toThrow();
+ });
+
+ it('preserves ordinary indexed source-map locations', () => {
+ const consumer = new SourceMapConsumer(indexed(2));
+ const mappings: unknown[] = [];
+ consumer.eachMapping((mapping: unknown) => mappings.push(mapping));
+ expect(mappings).toEqual([expect.objectContaining({
+ source: 'input.js', generatedLine: 3, generatedColumn: 0,
+ originalLine: 1, originalColumn: 0,
+ })]);
+ });
+});
diff --git a/test/main/quality/test-log-analysis.test.ts b/test/main/quality/test-log-analysis.test.ts
new file mode 100644
index 00000000..d7f7cefb
--- /dev/null
+++ b/test/main/quality/test-log-analysis.test.ts
@@ -0,0 +1,89 @@
+import { afterAll, describe, expect, it } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+
+// Scenario: a maintainer runs any PC Vitest entry (`npm test`, `npm run
+// test:apps`, `run-tests.mjs suite <files>`). Emitted logs must be attributed
+// to their case or setup/cleanup phase, unexpected errors and unclassified
+// stderr must fail even when assertions pass, declared output must pass but stay
+// visible, and a missing tap must fail as a coverage gap. The fixtures run
+// through the real runner and the real PC config (tap + reporter); only the
+// inventory is narrowed.
+const pcRoot = path.resolve(__dirname, '../../..');
+const node = process.env.ORKAS_TEST_NODE || process.execPath;
+const fixtureDir = 'test/fixtures/test-log-analysis';
+const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-log-analysis-'));
+
+afterAll(() => fs.rmSync(outDir, { recursive: true, force: true }));
+
+function runFixtures(files: string[], env: Record<string, string> = {}) {
+ const json = path.join(outDir, `${files.join('-').replace(/\W+/g, '_')}-${Object.keys(env).join('_')}.json`);
+ const childEnv: NodeJS.ProcessEnv = Object.fromEntries(Object.entries(process.env)
+ .filter(([key]) => !key.startsWith('VITEST')));
+ const result = spawnSync(node, ['scripts/run-tests.mjs', 'suite', '--config', `${fixtureDir}/vitest.config.ts`,
+ ...files.map(file => `${fixtureDir}/${file}`)], {
+ cwd: pcRoot, encoding: 'utf8', timeout: 90_000,
+ env: { ...childEnv, ORKAS_LOG_FIXTURE_JSON: json, NO_COLOR: '1', ...env },
+ });
+ expect(result.error).toBeUndefined();
+ // The reporter block starts at its status line and is the last stdout output.
+ const lines = result.stdout.split(/\r?\n/);
+ const start = lines.findIndex(line => /^\[test-log-analysis\] (?:PASS|WARN|FAIL) /.test(line));
+ const summary = start < 0 ? [] : lines.slice(start);
+ const report = fs.existsSync(json) ? JSON.parse(fs.readFileSync(json, 'utf8')) : { testResults: [] };
+ const cases = new Map<string, { status: string; failure: string }>();
+ for (const file of report.testResults) {
+ for (const item of file.assertionResults) cases.set(item.title, { status: item.status, failure: (item.failureMessages || []).join('\n') });
+ }
+ return { status: result.status, summary: summary.join('\n'), head: summary[0] || '', cases, stderr: result.stderr };
+}
+
+describe('default Vitest log analysis', () => {
+ it('passes declared output but surfaces it, and surfaces an undeclared warning with its owning case', () => {
+ const run = runFixtures(['expected.fixture.ts']);
+ expect(run.status).toBe(0);
+ expect([...run.cases.values()].map(item => item.status)).toEqual(['passed', 'passed', 'passed', 'passed']);
+ expect(run.head).toMatch(/^\[test-log-analysis\] WARN files=1 cases=4 .* warn=2 error=1 unexpected=0 expected=2 unmet=0 gaps=0$/);
+ expect(run.summary).not.toContain('script-progress');
+ expect(run.summary).toContain('warning (expected) x1 runtime-warning [console] fixture recoverable retry { attempt: # } <- '
+ + `${fixtureDir}/expected.fixture.ts > passes a declared recoverable warning`);
+ expect(run.summary).toContain(`warning x1 runtime-warning [console] fixture undeclared warning <- ${fixtureDir}/expected.fixture.ts > passes but surfaces an undeclared warning`);
+ expect(run.summary).toContain('error (expected) x1 runtime-error [console] fixture asserted failure');
+ }, 120_000);
+
+ it('fails the owning case for an unexpected error, unclassified stderr or an unmet declaration, without leaking raw content', () => {
+ const run = runFixtures(['unexpected.fixture.ts']);
+ expect(run.status).toBe(1);
+ expect(run.head).toMatch(/^\[test-log-analysis\] FAIL .* unexpected=4 expected=0 unmet=1 gaps=0$/);
+ expect(run.cases.get('rejects progress look-alikes on stderr')?.failure).toContain('2 unexpected error-level/unclassified stderr record(s)');
+ expect(run.cases.get('fails on an unexpected error')?.failure).toMatch(/case output failed: 1 unexpected .*runtime-error \[console\]/);
+ expect(run.cases.get('fails on unclassified stderr')?.failure).toMatch(/unclassified-stderr \[stderr\] x1: fixture raw unexplained diagnostic/);
+ expect(run.cases.get('fails when a declared expected log never occurs')?.failure).toContain('1 declared expected log(s) did not occur');
+ expect(run.cases.get('keeps an unrelated clean case passing')?.status).toBe('passed');
+ expect(run.summary).toContain(`<- ${fixtureDir}/unexpected.fixture.ts > fails on an unexpected error`);
+ // The attributed summary and the failure text carry only redacted signatures.
+ for (const text of [run.summary, run.cases.get('fails on an unexpected error')?.failure ?? '']) {
+ expect(text).not.toContain('fixture-secret-value');
+ expect(text).not.toContain('/Users/test/private-notes.txt');
+ }
+ expect(run.summary).toMatch(/token=\*\*\* <abs-path:[a-f0-9]{12}>/);
+ }, 120_000);
+
+ it('attributes stderr outside any case to the file setup and cleanup phases and fails the file', () => {
+ const run = runFixtures(['phase.fixture.ts']);
+ expect(run.status).toBe(1);
+ expect(run.cases.get('passes inside the case')?.status).toBe('passed');
+ expect(run.summary).toContain(`unclassified-stderr [stderr] fixture setup-phase noise <- ${fixtureDir}/phase.fixture.ts [setup]`);
+ expect(run.summary).toContain(`unclassified-stderr [stderr] fixture cleanup-phase noise <- ${fixtureDir}/phase.fixture.ts [cleanup]`);
+ expect(run.stderr).toContain('[test-log-analysis] setup output failed');
+ }, 120_000);
+
+ it('fails the run as a coverage gap when executed cases carry no log analysis', () => {
+ const run = runFixtures(['expected.fixture.ts'], { ORKAS_LOG_FIXTURE_NO_TAP: '1' });
+ expect(run.status).toBe(1);
+ expect(run.head).toMatch(/^\[test-log-analysis\] FAIL .* gaps=5$/);
+ expect(run.summary).toContain(`coverage gap: ${fixtureDir}/expected.fixture.ts [setup/cleanup] (no analysis)`);
+ }, 120_000);
+});
diff --git a/test/main/quality/ui-layer-contract.test.ts b/test/main/quality/ui-layer-contract.test.ts
new file mode 100644
index 00000000..452875e8
--- /dev/null
+++ b/test/main/quality/ui-layer-contract.test.ts
@@ -0,0 +1,130 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import postcss from 'postcss';
+import ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+
+const renderer = path.resolve(__dirname, '../../../src/renderer');
+
+function sourceFiles(directory: string, extension: string): string[] {
+ return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
+ if (entry.name === 'vendor') return [];
+ const full = path.join(directory, entry.name);
+ return entry.isDirectory() ? sourceFiles(full, extension) : entry.name.endsWith(extension) ? [full] : [];
+ });
+}
+
+function undeclaredInlineLayers(source: string): string[] {
+ const file = ts.createSourceFile('surface.js', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+ const findings: string[] = [];
+ function scope(node: ts.Node): ts.Node {
+ for (let parent = node.parent; parent; parent = parent.parent) {
+ if (ts.isFunctionLike(parent)) return parent;
+ }
+ return file;
+ }
+ function declared(owner: string, container: ts.Node): boolean {
+ let found = false;
+ const visit = (node: ts.Node) => {
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken
+ && [owner + '.dataset.uiOverlay', owner + '.dataset.uiLayoutChrome'].includes(node.left.getText(file))
+ && ts.isStringLiteralLike(node.right)) found = true;
+ ts.forEachChild(node, visit);
+ };
+ visit(container); return found;
+ }
+ function visit(node: ts.Node) {
+ if (ts.isStringLiteralLike(node)) findings.push(...undeclaredMarkup(node.text));
+ if (ts.isTemplateExpression(node)) findings.push(...undeclaredMarkup(
+ [node.head.text, ...node.templateSpans.map(span => span.literal.text)].join('__dynamic__'),
+ ));
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isPropertyAccessExpression(node.left)) {
+ const left = node.left;
+ const style = left.expression;
+ if (ts.isPropertyAccessExpression(style) && style.name.text === 'style') {
+ const empty = ts.isStringLiteralLike(node.right) && node.right.text === '';
+ const fixed = left.name.text === 'position' && (!ts.isStringLiteralLike(node.right)
+ || ['absolute', 'fixed'].includes(node.right.text));
+ const css = left.name.text === 'cssText' && ts.isStringLiteralLike(node.right)
+ && undeclaredLayers(`.inline { ${node.right.text} }`).length > 0;
+ if ((fixed || (!empty && left.name.text === 'zIndex') || css) && !declared(style.expression.getText(file), scope(node))) {
+ findings.push(left.getText(file));
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(file); return findings;
+}
+
+function undeclaredLayers(source: string): string[] {
+ const findings: string[] = [];
+ postcss.parse(source).walkRules(rule => {
+ const declarations = new Map(rule.nodes.filter(node => node.type === 'decl').map(node => [node.prop, node.value.trim()]));
+ if (!declarations.has('z-index') && !['absolute', 'fixed'].includes(declarations.get('position') || '')) return;
+ const kind = declarations.get('--orkas-ui-layer') || '';
+ if (!['overlay', 'chrome'].includes(kind)
+ || (kind === 'overlay' && /:(?:hover|active|focus(?:-visible|-within)?)(?![\w-])/.test(rule.selector))) findings.push(rule.selector);
+ });
+ return findings;
+}
+
+function undeclaredMarkup(source: string): string[] {
+ const findings: string[] = [];
+ for (const style of source.matchAll(/<style(?:\s[^>]*)?>([\s\S]*?)<\/style>/g)) findings.push(...undeclaredLayers(style[1]));
+ for (const tag of source.match(/<[\w:-]+(?:[^>"']|"[^"]*"|'[^']*')*>/g) || []) {
+ const style = /\sstyle\s*=\s*(["'])(.*?)\1/s.exec(tag)?.[2];
+ if (!style || undeclaredLayers(`.inline { ${style} }`).length === 0) continue;
+ const classes = /\sclass\s*=\s*(["'])(.*?)\1/s.exec(tag)?.[2].split(/\s+/) || [];
+ if (!classes.includes('ui-overlay') && !/\sdata-ui-(?:overlay|layout-chrome)(?:[\s=>])/.test(tag)) findings.push(tag);
+ }
+ return findings;
+}
+
+describe('application stacking layer ownership', () => {
+ it('requires declarations across the actual application stylesheet inventory, including new view directories', () => {
+ const findings = sourceFiles(renderer, '.css').flatMap(file => undeclaredLayers(fs.readFileSync(file, 'utf8')).map(selector => (
+ `${path.relative(renderer, file)}: ${selector}`
+ )));
+ expect(findings).toEqual([]);
+ });
+
+ it('rejects a new unnamed floating family and accepts a shared declaration without browser-specific registration', () => {
+ expect(undeclaredLayers('.new-surface { position: fixed; z-index: 5000; }')).toEqual(['.new-surface']);
+ expect(undeclaredLayers('.new-surface { position: absolute; z-index: 5000; --orkas-ui-layer: overlay; }')).toEqual([]);
+ expect(undeclaredLayers('@media (min-width: 600px) { .new-surface { position: fixed; } }')).toEqual(['.new-surface']);
+ expect(undeclaredLayers('.new-surface { position: fixed; --orkas-ui-layer: guessed; }')).toEqual(['.new-surface']);
+ expect(undeclaredLayers('.new-surface { position: absolute; }')).toEqual(['.new-surface']);
+ expect(undeclaredLayers('.new-surface:hover { position:absolute; --orkas-ui-layer:overlay; }')).toEqual(['.new-surface:hover']);
+ });
+
+ it('discovers new directories rather than inheriting a frozen filename list', () => {
+ const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'ui-layer-inventory-'));
+ try {
+ fs.mkdirSync(path.join(root, 'new-view'));
+ fs.writeFileSync(path.join(root, 'new-view', 'new.css'), '.new { position: fixed; }');
+ expect(sourceFiles(root, '.css').flatMap(file => undeclaredLayers(fs.readFileSync(file, 'utf8')))).toEqual(['.new']);
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it('requires the same public marker for direct inline floating styles across all first-party renderer scripts', () => {
+ const findings = sourceFiles(renderer, '.js').flatMap(file => undeclaredInlineLayers(fs.readFileSync(file, 'utf8')).map(selector => (
+ `${path.relative(renderer, file)}: ${selector}`
+ )));
+ expect(findings).toEqual([]);
+ expect(undeclaredInlineLayers("function open() { node.style.position = 'fixed'; node.style.zIndex = '900'; }")).toEqual(['node.style.position', 'node.style.zIndex']);
+ expect(undeclaredInlineLayers("function open() { node.dataset.uiOverlay = ''; node.style.position = 'fixed'; node.style.zIndex = '900'; }")).toEqual([]);
+ expect(undeclaredInlineLayers("function a() { node.dataset.uiOverlay = ''; } function b() { node.style.position = 'fixed'; }")).toEqual(['node.style.position']);
+ expect(undeclaredInlineLayers("node.style.position = 'absolute'")).toEqual(['node.style.position']);
+ });
+
+ it('covers static and generated inline markup so a new panel cannot bypass the stylesheet gate', () => {
+ expect(sourceFiles(renderer, '.html').flatMap(file => undeclaredMarkup(fs.readFileSync(file, 'utf8')))).toEqual([]);
+ expect(undeclaredMarkup('<section style="position:fixed;z-index:999">')).toHaveLength(1);
+ expect(undeclaredMarkup('<section class="ui-overlay" style="position:fixed;z-index:999">')).toEqual([]);
+ expect(undeclaredMarkup('<section style="position:fixed;--orkas-ui-layer:overlay">')).toEqual([]);
+ expect(undeclaredInlineLayers('node.innerHTML = `<section style="position:fixed;z-index:999">`')).toHaveLength(1);
+ expect(undeclaredInlineLayers('node.innerHTML = `<section style="position:fixed;z-index:${level}">`')).toHaveLength(1);
+ expect(undeclaredMarkup('<style>.new { position:fixed; z-index:900; }</style>')).toEqual(['.new']);
+ });
+});
diff --git a/test/main/storage.test.ts b/test/main/storage.test.ts
index 2537d92c..86f0e034 100644
--- a/test/main/storage.test.ts
+++ b/test/main/storage.test.ts
@@ -7,9 +7,9 @@ import * as path from 'node:path';
import {
nowIso, genUserId, genId12, safeId,
readJson, readJsonSync, writeJson, writeJsonSync,
- writeTextAtomicSync, appendJsonl, appendJsonlAtomic,
+ writeTextAtomicSync, writeTextAtomicGuardedSync, appendJsonl, appendJsonlAtomic,
invalidateLineCount, readJsonl, readJsonlPage, readJsonlPageWithOffsets,
- readJsonlWindow, __storageTestHooks,
+ readJsonlWindow, readJsonlWindowAtMatch, __storageTestHooks,
} from '../../src/main/storage';
let tmpDir: string;
@@ -188,6 +188,28 @@ describe('storage › JSON IO', () => {
});
describe('storage › writeTextAtomicSync', () => {
+ it('does not publish a superseded snapshot and cleans its temporary file', () => {
+ const file = path.join(tmpDir, 'guarded.md');
+ fs.writeFileSync(file, 'newer save');
+ expect(writeTextAtomicGuardedSync(file, 'old candidate', () => false)).toBe(false);
+ expect(fs.readFileSync(file, 'utf8')).toBe('newer save');
+ expect(fs.readdirSync(tmpDir)).toEqual(['guarded.md']);
+ expect(writeTextAtomicGuardedSync(file, 'accepted', () => true)).toBe(true);
+ expect(fs.readFileSync(file, 'utf8')).toBe('accepted');
+ });
+
+ it('rechecks ownership after a Windows-style sharing violation', () => {
+ let current = 'original';
+ let renames = 0;
+ const published = __storageTestHooks.renameWithRetrySyncUsing('temporary', 'target', () => {
+ renames++;
+ current = 'newer save';
+ throw eperm();
+ }, () => current === 'original');
+ expect(published).toBe(false);
+ expect(renames).toBe(1);
+ expect(current).toBe('newer save');
+ });
it('writes text atomically and removes .tmp', () => {
const p = path.join(tmpDir, 'text.md');
writeTextAtomicSync(p, '# hello\n');
@@ -305,6 +327,42 @@ describe('storage › JSONL append/read', () => {
expect(previousPage.records.map((row) => row.i)).toEqual([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
});
+ // A quoted message is located by id. The single pass must land on exactly
+ // the page the index reader returns for that record, across malformed and
+ // blank lines, CRLF endings, records spanning read chunks, a tombstoned
+ // duplicate, page boundaries and an unterminated final record.
+ it('finds the page holding the first live matching record in one pass, identical to its index page', async () => {
+ const p = path.join(tmpDir, 'quoted.jsonl');
+ const pad = '中🙂'.repeat(12_000);
+ const lines: string[] = [];
+ for (let i = 0; i < 37; i++) {
+ lines.push(JSON.stringify({ id: `m${i}`, text: i % 5 === 0 ? pad : `row ${i}` }));
+ if (i === 3) lines.push('{malformed');
+ if (i === 8) lines.push(' ');
+ }
+ lines.splice(12, 0, JSON.stringify({ id: 'm30', deleted_at: '2026-10-01T00:00:00Z' }));
+ const body = lines.join('\r\n');
+ fs.writeFileSync(p, body, 'utf8');
+ // Independent oracle: parsed-record indexes in file order.
+ const parsed = body.split('\n').map((line) => line.trim()).filter(Boolean)
+ .flatMap((line) => { try { return [JSON.parse(line)]; } catch { return []; } });
+ const live = (id: string) => (record: any) => record?.id === id && !record?.deleted_at;
+ for (const limit of [1, 7, 10]) {
+ for (const id of ['m0', 'm9', 'm10', 'm30', 'm36']) {
+ const index = parsed.findIndex(live(id));
+ const start = Math.floor(index / limit) * limit;
+ expect(await readJsonlWindowAtMatch<any>(p, live(id), limit))
+ .toEqual({ ...await readJsonlWindow<any>(p, start, limit), start, index });
+ }
+ }
+ let projected = 0;
+ const page = await readJsonlWindowAtMatch<any>(p, live('m36'), 10, (record) => { projected++; return { id: record.id }; });
+ expect(page!.records.map((record) => record.id)).toEqual(['m29', 'm30', 'm31', 'm32', 'm33', 'm34', 'm35', 'm36']);
+ expect(projected).toBe(8);
+ expect(await readJsonlWindowAtMatch<any>(p, live('missing'), 10)).toBeNull();
+ expect(await readJsonlWindowAtMatch<any>(path.join(tmpDir, 'absent.jsonl'), live('m0'), 10)).toBeNull();
+ });
+
it('continues forward at byte boundaries across large Unicode records and an unterminated tail', async () => {
const p = path.join(tmpDir, 'forward-log.jsonl');
const text = '中文🙂'.repeat(20_000);
diff --git a/test/main/util/browser-proxy.test.ts b/test/main/util/browser-proxy.test.ts
index 8a0d53f3..6ef4b6c8 100644
--- a/test/main/util/browser-proxy.test.ts
+++ b/test/main/util/browser-proxy.test.ts
@@ -13,6 +13,7 @@ describe('embedded browser launch proxy policy', () => {
const setProxy = vi.fn();
const policy = prepareBrowserProxy({ setProxy }, { NO_PROXY: 'example.com' });
expect(policy.ready).toBeUndefined();
+ expect(policy.diagnostic()).toEqual({ browser_proxy_policy: 'system', browser_proxy_setup: 'ready' });
expect(setProxy).not.toHaveBeenCalled();
});
@@ -41,16 +42,34 @@ describe('embedded browser launch proxy policy', () => {
let applied!: () => void;
const setProxy = vi.fn(() => new Promise<void>(resolve => { applied = resolve; }));
const policy = prepareBrowserProxy({ setProxy }, { HTTP_PROXY: 'http://proxy.test' });
+ expect(policy.diagnostic()).toEqual({ browser_proxy_policy: 'fixed_servers', browser_proxy_setup: 'pending' });
const released = vi.fn();
void policy.ready!.then(released);
await Promise.resolve();
expect(released).not.toHaveBeenCalled();
applied();
expect(await policy.ready).toBe(true);
+ expect(policy.diagnostic()).toEqual({ browser_proxy_policy: 'fixed_servers', browser_proxy_setup: 'ready' });
expect(released).toHaveBeenCalledWith(true);
expect(warnings).not.toHaveBeenCalled();
});
+ it('preserves system IPv4/IPv6 CIDR exceptions and the mandatory loopback bypasses', async () => {
+ const ranges = ['10.0.0.0/8', '192.168.0.0/16', '172.16.0.0/12', '2001:db8::/32', '0.0.0.0/0', '2001:db8::1/128'];
+ const setProxy = vi.fn().mockResolvedValue(undefined);
+ const policy = prepareBrowserProxy({ setProxy }, { HTTP_PROXY: 'http://proxy.test:8080', NO_PROXY: ranges.join(',') });
+ expect(await policy.ready).toBe(true);
+ expect(setProxy.mock.calls[0][0].proxyBypassRules.split(',')).toEqual([...ranges, 'localhost', '.localhost', '127.0.0.1', '[::1]', 'local', '.local']);
+ expect(setProxy.mock.calls[0][0].proxyRules).toBe('http=http://proxy.test:8080;https=http://proxy.test:8080');
+ expect(warnings).not.toHaveBeenCalled();
+ });
+
+ it.each(['999.1.1.1/8', '10.0.0.0/33', '10.0.0.0/-1', '10.0.0.0/8.0', '2001:db8::/129', 'example.com/8', '10.0.0.0/8;*', '10.0.0.0/8:80'])('retains fail-closed admission for malformed CIDR %s', async range => {
+ const setProxy = vi.fn();
+ expect(await prepareBrowserProxy({ setProxy }, { HTTP_PROXY: 'http://proxy.test', NO_PROXY: range }).ready).toBe(false);
+ expect(setProxy).not.toHaveBeenCalled();
+ });
+
it.each([
{ HTTP_PROXY: 'http://secret:[email protected]/bad-path' },
{ ALL_PROXY: 'socks5://secret:[email protected]:1080' },
@@ -71,9 +90,11 @@ describe('embedded browser launch proxy policy', () => {
vi.useFakeTimers();
const rejected = prepareBrowserProxy({ setProxy: vi.fn().mockRejectedValue(new Error('private provider error')) }, { HTTP_PROXY: 'http://proxy.test' });
expect(await rejected.ready).toBe(false);
+ expect(rejected.diagnostic()).toEqual({ browser_proxy_policy: 'fixed_servers', browser_proxy_setup: 'failed' });
const stalled = prepareBrowserProxy({ setProxy: () => new Promise(() => {}) }, { HTTP_PROXY: 'http://proxy.test' });
await vi.advanceTimersByTimeAsync(60_000);
expect(await stalled.ready).toBe(false);
+ expect(stalled.diagnostic()).toEqual({ browser_proxy_policy: 'fixed_servers', browser_proxy_setup: 'failed' });
expect(warnings.mock.calls).toEqual(Array(2).fill(['browser proxy setup failed; browser requests remain blocked']));
expect(vi.getTimerCount()).toBe(0);
});
diff --git a/test/main/util/ensure-deps.test.ts b/test/main/util/ensure-deps.test.ts
index af339920..cb963255 100644
--- a/test/main/util/ensure-deps.test.ts
+++ b/test/main/util/ensure-deps.test.ts
@@ -62,7 +62,9 @@ describe('ensure-deps package-tree health', () => {
packageName: 'electron',
});
- expect(lockedVersion).toBe('42.11.9');
+ const lock = JSON.parse(fs.readFileSync(path.resolve('package-lock.json'), 'utf8'));
+ expect(lockedVersion).toBe(lock.packages['node_modules/electron'].version);
+ expect(lockedVersion).toMatch(/^\d+\.\d+\.\d+$/);
expect(packageJson.devDependencies?.electron).toBe(lockedVersion);
});
diff --git a/test/main/util/ensure-dev-dependencies.test.ts b/test/main/util/ensure-dev-dependencies.test.ts
index 63ed4f6a..a2fd8984 100644
--- a/test/main/util/ensure-dev-dependencies.test.ts
+++ b/test/main/util/ensure-dev-dependencies.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { createRequire } from 'node:module';
+import * as fs from 'node:fs';
import * as path from 'node:path';
-
+import * as vm from 'node:vm';
+import { describe, expect, it } from 'vitest';
const { shouldProvisionWhisper } = require(
path.join(process.cwd(), 'scripts', 'ensure-dev-dependencies.cjs'),
) as {
@@ -24,3 +27,105 @@ describe('ensure-dev-dependencies.cjs', () => {
expect(shouldProvisionWhisper(platform, arch)).toBe(false);
});
});
+
+
+const entry = path.resolve('scripts/ensure-dev-dependencies.cjs');
+const requireScript = createRequire(entry);
+
+// Execute the CLI entry, preserving its actual readiness/error boundary. Only
+// provisioning children are controlled; no downloads or toolchains are needed.
+async function prepare(platform = 'darwin', fail = '', fault = 'exit') {
+ const calls: string[] = [];
+ const completed = new Set<string>();
+ const messages: string[] = [];
+ let active = 0;
+ let peak = 0;
+ let readyWhileActive = false;
+ let exitWhileActive = false;
+ let exitCode = 0;
+ let nativePrerequisites: string[] = [];
+ const result = (args: string[]) => {
+ const name = path.basename(args[0]) + (args.includes('--host-only') ? ':host' : '');
+ calls.push(name);
+ if (name === 'verify-native-dependencies.cjs') nativePrerequisites = [...completed];
+ return { name, status: name === fail ? 1 : 0 };
+ };
+ const req = (name: string) => name === 'node:child_process' ? {
+ spawn: (_node: string, args: string[]) => {
+ const record = result(args);
+ const child = new EventEmitter();
+ active++;
+ peak = Math.max(peak, active);
+ setTimeout(() => {
+ if (record.status && fault === 'spawn') child.emit('error', new Error('controlled launch failure'));
+ active--;
+ completed.add(record.name);
+ child.emit('close', record.status && fault !== 'exit' ? null : record.status,
+ record.status && fault === 'signal' ? 'SIGTERM' : null);
+ }, record.name === fail ? 0 : 5);
+ return child;
+ },
+ } : requireScript(name);
+ const module = {};
+ await vm.runInNewContext(fs.readFileSync(entry, 'utf8'), {
+ require: Object.assign(req, { main: module }), module, __dirname: path.dirname(entry),
+ process: { execPath: process.execPath, env: {}, platform, arch: platform === 'win32' ? 'x64' : 'arm64',
+ exit: (code: number) => { exitCode = code; exitWhileActive = active > 0; } },
+ console: {
+ log: (message: string) => {
+ if (message.includes('built-in dependencies ready')) readyWhileActive = active > 0;
+ messages.push(message);
+ },
+ error: (message: string) => messages.push(message),
+ },
+ });
+ return { calls, completed, messages, peak, readyWhileActive, exitWhileActive, exitCode, nativePrerequisites };
+}
+
+describe('development dependency preparation', () => {
+ it.each(['darwin', 'win32'])('overlaps independent preparation on %s and waits for every prerequisite', async platform => {
+ const run = await prepare(platform);
+ expect(run.peak).toBe(2);
+ expect(run.readyWhileActive).toBe(false);
+ expect(run.exitCode).toBe(0);
+ expect(run.nativePrerequisites).toEqual(expect.arrayContaining([
+ 'ensure-sqlite-electron-abi.mjs', 'ensure-runtime.cjs', 'build-phone-passkey.cjs',
+ ]));
+ expect(run.completed).toEqual(new Set([
+ 'verify-native-dependencies.cjs:host', 'build-notification-permission-addon.cjs',
+ 'ensure-sqlite-electron-abi.mjs', 'build-phone-passkey.cjs', 'ensure-runtime.cjs',
+ 'fetch-embedding-model.mjs', 'fetch-officecli.cjs', 'fetch-ffmpeg.cjs',
+ 'verify-native-dependencies.cjs', 'fetch-whisper.cjs',
+ ...(platform === 'win32' ? ['fetch-win-vc-runtime.cjs'] : []),
+ ]));
+ expect(run.messages.at(-1)).toContain('built-in dependencies ready');
+ });
+
+ it.each(['verify-native-dependencies.cjs:host', 'build-phone-passkey.cjs', 'verify-native-dependencies.cjs', 'fetch-embedding-model.mjs'])(
+ 'fails readiness and drains running preparation after %s fails', async fail => {
+ const run = await prepare('darwin', fail);
+ expect(run.exitCode).toBe(1);
+ expect(run.exitWhileActive).toBe(false);
+ expect(run.messages.join('\n')).not.toContain('built-in dependencies ready');
+ expect(run.messages.at(-1)).toContain('failed');
+ if (fail === 'build-phone-passkey.cjs') expect(run.calls).not.toContain('ensure-runtime.cjs');
+ if (fail === 'fetch-embedding-model.mjs') expect(run.calls).not.toContain('fetch-officecli.cjs');
+ if (fail.endsWith(':host')) expect(run.calls).toEqual([fail]);
+ },
+ );
+
+ it('blocks Windows preparation when the VC runtime cannot be prepared', async () => {
+ const run = await prepare('win32', 'fetch-win-vc-runtime.cjs');
+ expect(run.exitCode).toBe(1);
+ expect(run.calls).toEqual(['verify-native-dependencies.cjs:host', 'fetch-win-vc-runtime.cjs']);
+ expect(run.messages.join('\n')).not.toContain('built-in dependencies ready');
+ });
+
+ it.each(['spawn', 'signal'])('drains the other lane after a child %s failure', async fault => {
+ const run = await prepare('darwin', 'fetch-embedding-model.mjs', fault);
+ expect(run.exitCode).toBe(1);
+ expect(run.exitWhileActive).toBe(false);
+ expect(run.calls).not.toContain('fetch-officecli.cjs');
+ expect(run.messages.join('\n')).not.toContain('built-in dependencies ready');
+ });
+});
diff --git a/test/main/util/native-package-gate.test.ts b/test/main/util/native-package-gate.test.ts
index eaea869e..58beacca 100644
--- a/test/main/util/native-package-gate.test.ts
+++ b/test/main/util/native-package-gate.test.ts
@@ -73,7 +73,7 @@ function macFixture(arch: string): string {
const onnx = path.join(root, 'onnxruntime-node');
fs.mkdirSync(onnx, { recursive: true });
fs.writeFileSync(path.join(onnx, 'package.json'), JSON.stringify({ version: '1.21.0' }));
- // Names come from the locked Sharp 0.35.4 / libvips 1.3.3 package payloads.
+ // Names come from the locked Sharp 0.35.5 / libvips 1.3.4 package payloads.
for (const relativePath of [
`@esbuild/darwin-${arch}/bin/esbuild`,
'esbuild/bin/esbuild',
@@ -83,8 +83,8 @@ function macFixture(arch: string): string {
'better-sqlite3/build/Release/better_sqlite3.node',
`onnxruntime-node/bin/napi-v3/darwin/${arch}/onnxruntime_binding.node`,
`onnxruntime-node/bin/napi-v3/darwin/${arch}/libonnxruntime.1.21.0.dylib`,
- `@img/sharp-darwin-${arch}/lib/sharp-darwin-${arch}-0.35.4.node`,
- `@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.6.dylib`,
+ `@img/sharp-darwin-${arch}/lib/sharp-darwin-${arch}-0.35.5.node`,
+ `@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.7.dylib`,
'fsevents/fsevents.node',
]) {
const file = path.join(root, relativePath);
@@ -109,12 +109,12 @@ describe('native-package-gate', () => {
it('verifies current Windows Sharp payload and rejects a missing libvips DLL', () => {
const root = windowsFixture();
const lib = path.join(root, '@img/sharp-win32-x64/lib');
- fs.renameSync(path.join(lib, 'sharp-win32-x64-0.35.3.node'), path.join(lib, 'sharp-win32-x64-0.35.4.node'));
- fs.renameSync(path.join(lib, 'libvips-cpp-8.18.3.dll'), path.join(lib, 'libvips-cpp-8.18.6.dll'));
+ fs.renameSync(path.join(lib, 'sharp-win32-x64-0.35.3.node'), path.join(lib, 'sharp-win32-x64-0.35.5.node'));
+ fs.renameSync(path.join(lib, 'libvips-cpp-8.18.3.dll'), path.join(lib, 'libvips-cpp-8.18.7.dll'));
expect(verifyNativePackagePayload(root, 'win32', 'x64')).toEqual(
requiredNativeVerificationEntries('win32', 'x64'),
);
- fs.rmSync(path.join(lib, 'libvips-cpp-8.18.6.dll'));
+ fs.rmSync(path.join(lib, 'libvips-cpp-8.18.7.dll'));
expect(() => verifyNativePackagePayload(root, 'win32', 'x64'))
.toThrow(/expected exactly one sharp-libvips-cpp/);
});
@@ -124,7 +124,7 @@ describe('native-package-gate', () => {
expect(verifyNativePackagePayload(root, 'darwin', arch)).toEqual(
requiredNativeVerificationEntries('darwin', arch),
);
- fs.rmSync(path.join(root, `@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.6.dylib`));
+ fs.rmSync(path.join(root, `@img/sharp-libvips-darwin-${arch}/lib/libvips-cpp.8.18.7.dylib`));
expect(() => verifyNativePackagePayload(root, 'darwin', arch))
.toThrow(/expected exactly one sharp-libvips-cpp/);
});
diff --git a/test/main/util/packaged-entrypoint-gate.test.ts b/test/main/util/packaged-entrypoint-gate.test.ts
index 04543cfa..4b5ec74a 100644
--- a/test/main/util/packaged-entrypoint-gate.test.ts
+++ b/test/main/util/packaged-entrypoint-gate.test.ts
@@ -27,6 +27,7 @@ const gate = require('../../../bin/packaged-entrypoint-gate.cjs') as {
verifyPackagedConnectorRuntime(root: string): string[];
verifyPackagedEntrypointPayload(root: string, options: { projectRoot: string }): string[];
verifySourceEntrypointContract(root: string): string[];
+ verifyBridgeSdkRuntime(root: string): void;
};
let tmpDir: string;
@@ -39,7 +40,7 @@ afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
-function packagedFixture(): string {
+function packagedFixture(realHelpers = false): string {
const pcRoot = path.join(tmpDir, 'app.asar.unpacked');
const binRoot = path.join(pcRoot, 'bin');
fs.mkdirSync(binRoot, { recursive: true });
@@ -47,7 +48,11 @@ function packagedFixture(): string {
fs.copyFileSync(path.join(process.cwd(), 'bin', name), path.join(binRoot, name));
}
for (const name of gate.PACKAGED_BIN_HELPERS) {
- fs.copyFileSync(path.join(process.cwd(), 'bin', name), path.join(binRoot, name));
+ // Inventory and corruption cases use small syntax-valid helpers. The
+ // source-contract case checks shipped syntax;
+ // executable connector journeys below retain the real helper closure.
+ if (realHelpers) fs.copyFileSync(path.join(process.cwd(), 'bin', name), path.join(binRoot, name));
+ else fs.writeFileSync(path.join(binRoot, name), name.endsWith('.json') ? '{}\n' : 'module.exports = {};\n');
}
const lock = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package-lock.json'), 'utf8'));
@@ -78,7 +83,7 @@ function packagedFixture(): string {
}
function packagedRuntimeFixture(): string {
- const pcRoot = packagedFixture();
+ const pcRoot = packagedFixture(true);
for (const spec of gate.PACKAGED_MCP_RUNTIME_FILES) {
const sourceDir = path.join(process.cwd(), ...spec.lockPath.split('/'));
const packageDir = path.join(pcRoot, ...(spec.packagedPath || spec.lockPath).split('/'));
@@ -115,6 +120,31 @@ describe('packaged-entrypoint-gate', () => {
expect(gate.PACKAGED_BIN_ENTRYPOINTS).not.toContain('shopify-setup-requirements.cjs');
});
+ it('loads the bridge SDK closure outside the source tree and rejects a missing nested validator', () => {
+ const root = packagedRuntimeFixture();
+ fs.copyFileSync(path.join(process.cwd(), 'package-lock.json'), path.join(root, 'package-lock.json'));
+ expect(() => gate.verifyBridgeSdkRuntime(root)).not.toThrow();
+ fs.rmSync(path.join(root, 'node_modules', '@modelcontextprotocol', 'server', 'node_modules', 'zod'), { recursive: true });
+ const child = spawnSync(process.env.ORKAS_TEST_NODE || process.execPath, ['-e',
+ `require(${JSON.stringify(path.join(process.cwd(), 'bin', 'packaged-entrypoint-gate.cjs'))}).verifyBridgeSdkRuntime(${JSON.stringify(root)})`,
+ ], { encoding: 'utf8', timeout: 10000 });
+ expect(child.status).not.toBe(0);
+ expect(child.stderr).toContain('zod');
+ });
+
+ it('rejects malformed packaged runtime JSON without accepting it as executable JavaScript', () => {
+ const root = packagedFixture();
+ fs.writeFileSync(path.join(root, 'bin', 'local-cli-lark-permission-contract.json'), '{broken');
+ expect(() => gate.verifyPackagedEntrypointPayload(root, { projectRoot: process.cwd() })).toThrow(/invalid runtime helper/);
+ });
+
+ it('rejects a corrupted JavaScript helper after valid source files were packaged', () => {
+ const root = packagedFixture();
+ fs.writeFileSync(path.join(root, 'bin', 'browser-tool-contract.cjs'), 'module.exports = {;\n');
+ expect(() => gate.verifyPackagedEntrypointPayload(root, { projectRoot: process.cwd() }))
+ .toThrow(/invalid runtime helper.*browser-tool-contract\.cjs/);
+ });
+
it('rejects a build-only helper that is not excluded from the app', () => {
const packageJson = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'));
packageJson.build.files = packageJson.build.files.filter(
@@ -204,7 +234,7 @@ describe('packaged-entrypoint-gate', () => {
.toThrow(/missing esbuild loader lib\/main\.js/);
});
- it.each(['browser-tool-contract.cjs', 'connector-discovery-contract.cjs', 'ebay-signature.cjs', 'temu-api-contracts.cjs', 'shein-api-contracts.cjs', 'lazada-api-contracts.cjs', 'amazon-business-api.cjs', 'amazon-api-contracts.cjs', 'square-business-api.cjs', 'square-api-contracts.cjs', 'ebay-business-api.cjs', 'ebay-api-contracts.cjs', 'etsy-business-api.cjs', 'etsy-api-contracts.cjs', 'bigcommerce-business-api.cjs', 'bigcommerce-api-contracts.cjs', 'woocommerce-business-api.cjs', 'woocommerce-api-contracts.cjs', 'commercelayer-business-api.cjs', 'commercelayer-api-contracts.cjs', 'constant-contact-business-api.cjs', 'constant-contact-api-contracts.cjs', 'shopify-business-api.cjs', 'shopify-api-contracts.cjs', 'shopline-business-api.cjs', 'shopline-api-contracts.cjs', 'shoplazza-business-api.cjs', 'shoplazza-api-contracts.cjs', 'reloadly-business-api.cjs', 'reloadly-api-contracts.cjs', 'lightspeed-business-api.cjs', 'lightspeed-api-contracts.cjs', 'shopline-graphql-api.cjs', 'shopline-graphql-contracts.cjs', 'base-shop-business-api.cjs', 'base-shop-api-contracts.cjs', 'walmart-business-api.cjs', 'walmart-api-contracts.cjs', 'qoo10-business-api.cjs', 'qoo10-api-contracts.cjs', 'futureshop-business-api.cjs', 'futureshop-api-contracts.cjs', 'shopee-business-api.cjs', 'shopee-api-contracts.cjs', 'tiktok-shop-business-api.cjs', 'tiktok-shop-api-contracts.cjs', 'yahoo-shopping-business-api.cjs', 'yahoo-shopping-api-contracts.cjs', 'douyin-business-api.cjs', 'douyin-api-contracts.cjs', 'aliexpress-business-api.cjs', 'aliexpress-api-contracts.cjs', 'mercado-libre-business-api.cjs', 'mercado-libre-api-contracts.cjs', 'kuaishou-business-api.cjs', 'kuaishou-api-contracts.cjs', 'alibaba-1688-business-api.cjs', 'alibaba-1688-api-contracts.cjs', 'youzan-business-api.cjs', 'youzan-api-contracts.cjs', 'icbu-business-api.cjs', 'icbu-api-contracts.cjs', 'weimob-business-api.cjs', 'weimob-api-contracts.cjs', 'taobao-business-api.cjs', 'taobao-api-contracts.cjs', 'jd-business-api.cjs', 'jd-api-contracts.cjs'])(
+ it.each(['skill-esm-loader.cjs', 'browser-tool-contract.cjs', 'connector-discovery-contract.cjs', 'ebay-signature.cjs', 'temu-api-contracts.cjs', 'shein-api-contracts.cjs', 'lazada-api-contracts.cjs', 'amazon-business-api.cjs', 'amazon-api-contracts.cjs', 'square-business-api.cjs', 'square-api-contracts.cjs', 'ebay-business-api.cjs', 'ebay-api-contracts.cjs', 'etsy-business-api.cjs', 'etsy-api-contracts.cjs', 'bigcommerce-business-api.cjs', 'bigcommerce-api-contracts.cjs', 'woocommerce-business-api.cjs', 'woocommerce-api-contracts.cjs', 'commercelayer-business-api.cjs', 'commercelayer-api-contracts.cjs', 'constant-contact-business-api.cjs', 'constant-contact-api-contracts.cjs', 'shopify-business-api.cjs', 'shopify-api-contracts.cjs', 'shopline-business-api.cjs', 'shopline-api-contracts.cjs', 'shoplazza-business-api.cjs', 'shoplazza-api-contracts.cjs', 'reloadly-business-api.cjs', 'reloadly-api-contracts.cjs', 'lightspeed-business-api.cjs', 'lightspeed-api-contracts.cjs', 'shopline-graphql-api.cjs', 'shopline-graphql-contracts.cjs', 'base-shop-business-api.cjs', 'base-shop-api-contracts.cjs', 'walmart-business-api.cjs', 'walmart-api-contracts.cjs', 'qoo10-business-api.cjs', 'qoo10-api-contracts.cjs', 'futureshop-business-api.cjs', 'futureshop-api-contracts.cjs', 'shopee-business-api.cjs', 'shopee-api-contracts.cjs', 'tiktok-shop-business-api.cjs', 'tiktok-shop-api-contracts.cjs', 'yahoo-shopping-business-api.cjs', 'yahoo-shopping-api-contracts.cjs', 'douyin-business-api.cjs', 'douyin-api-contracts.cjs', 'aliexpress-business-api.cjs', 'aliexpress-api-contracts.cjs', 'mercado-libre-business-api.cjs', 'mercado-libre-api-contracts.cjs', 'kuaishou-business-api.cjs', 'kuaishou-api-contracts.cjs', 'alibaba-1688-business-api.cjs', 'alibaba-1688-api-contracts.cjs', 'youzan-business-api.cjs', 'youzan-api-contracts.cjs', 'icbu-business-api.cjs', 'icbu-api-contracts.cjs', 'weimob-business-api.cjs', 'weimob-api-contracts.cjs', 'taobao-business-api.cjs', 'taobao-api-contracts.cjs', 'jd-business-api.cjs', 'jd-api-contracts.cjs'])(
'blocks a package missing the runtime helper %s', (name) => {
const pcRoot = packagedFixture();
fs.rmSync(path.join(pcRoot, 'bin', name));
diff --git a/test/main/util/proxy-dispatcher.test.ts b/test/main/util/proxy-dispatcher.test.ts
index 0d33a328..506ce901 100644
--- a/test/main/util/proxy-dispatcher.test.ts
+++ b/test/main/util/proxy-dispatcher.test.ts
@@ -1,6 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import { createServer } from 'node:http';
+import { EventEmitter } from 'node:events';
+import { connect } from 'node:net';
import {
_resetProxyRoutingForTests,
activeProxy,
@@ -9,6 +11,7 @@ import {
createSystemProxyBinaryFetch,
createSystemProxyFetch,
downloadBinaryWithProxyPolicy,
+ fetchUploadWithProxyPolicy,
envProxyConfig,
envProxyAppliesToUrl,
envProxyUrl,
@@ -55,6 +58,86 @@ afterEach(() => {
});
describe('Electron system-proxy transport failures', () => {
+ it('uploads through the configured environment proxy with byte progress and no system-route lookup', async () => {
+ const {getGlobalDispatcher, setGlobalDispatcher} = await import('undici');
+ const original = getGlobalDispatcher();
+ let received = '', tunnels = 0;
+ const server = createServer((request, response) => {
+ request.setEncoding('utf8'); request.on('data', chunk => { received += chunk; });
+ request.on('end', () => response.end('ok'));
+ });
+ const proxy = createServer();
+ const listen = (value: ReturnType<typeof createServer>) => new Promise<number>(resolve => {
+ value.listen(0, '127.0.0.1', () => resolve((value.address() as import('node:net').AddressInfo).port));
+ });
+ const port = await listen(server);
+ proxy.on('connect', (_request, socket, head) => {
+ tunnels++;
+ const upstream = connect(port, '127.0.0.1', () => {
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ if(head.length)upstream.write(head);
+ socket.pipe(upstream).pipe(socket);
+ });
+ socket.on('close', () => upstream.destroy()); upstream.on('error', () => socket.destroy());
+ });
+ const proxyPort = await listen(proxy), progress: number[] = [];
+ process.env.HTTP_PROXY = `http://127.0.0.1:${proxyPort}`;
+ const resolveSystem = vi.fn(async () => 'PROXY unused:8080');
+ const body = 'x'.repeat(64 * 1024);
+ try {
+ expect(await installEnvProxyDispatcher()).toBe(true);
+ expect(await installSystemProxyDispatcher(vi.fn(), resolveSystem)).toBe(false);
+ const result = await fetchUploadWithProxyPolicy('http://upload.invalid/chunk', {
+ method: 'POST', body, signal: AbortSignal.timeout(3000),
+ }, sent => progress.push(sent));
+ expect(await result.text()).toBe('ok'); expect(received).toBe(body);
+ expect(progress.some(sent => sent > 0 && sent < body.length)).toBe(true);
+ expect(progress.at(-1)).toBe(body.length);
+ expect(tunnels).toBe(1); expect(resolveSystem).not.toHaveBeenCalled();
+ } finally {
+ const current = getGlobalDispatcher(); setGlobalDispatcher(original); await current.destroy();
+ server.closeAllConnections();
+ await Promise.all([new Promise<void>(resolve => server.close(() => resolve())), new Promise<void>(resolve => proxy.close(() => resolve()))]);
+ }
+ });
+ it.each(['success', 'abort', 'error'] as const)('tracks Chromium upload bytes and disposes polling on %s without a direct fallback', async outcome => {
+ vi.useFakeTimers();
+ const request = Object.assign(new EventEmitter(), {
+ getUploadProgress: vi.fn(() => ({active: true, started: true, current: 4, total: 8})),
+ setHeader: vi.fn(), end: vi.fn(), abort: vi.fn(),
+ });
+ const netRequest = vi.fn(() => request);
+ vi.doMock('electron', () => ({net: {request: netRequest}, session: {defaultSession: {}}}));
+ const progress = vi.fn(), controller = new AbortController();
+ let work: Promise<unknown> | undefined;
+ try {
+ await installSystemProxyDispatcher(vi.fn(), async () => 'SOCKS5 proxy.example:1080');
+ work = fetchUploadWithProxyPolicy('https://upload.example/chunk', {
+ method: 'POST', body: '12345678', headers: {user_id: 'test', session_id: 'test-session'}, signal: controller.signal,
+ }, progress).then(response => response.text(), error => error.message);
+ await vi.waitFor(() => expect(request.end).toHaveBeenCalled());
+ await vi.advanceTimersByTimeAsync(100);
+ expect(progress).toHaveBeenCalledWith(4, 8);
+ expect(request.end).toHaveBeenCalledWith(Buffer.from('12345678'));
+ expect(request.setHeader).toHaveBeenCalledWith('session_id', 'test-session');
+ if (outcome === 'success') {
+ const response = Object.assign(new EventEmitter(), {statusCode: 200, headers: {'Content-Type': ['application/json']}});
+ request.emit('response', response); response.emit('data', Buffer.from('ok')); response.emit('end');
+ expect(await work).toBe('ok');
+ } else if (outcome === 'abort') {
+ controller.abort(new Error('cancelled'));
+ expect(await work).toBe('cancelled'); expect(request.abort).toHaveBeenCalledOnce();
+ } else {
+ request.emit('error', new Error('proxy unavailable'));
+ expect(await work).toBe('proxy unavailable');
+ }
+ const count = progress.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(500);
+ expect(progress).toHaveBeenCalledTimes(count);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(netRequest).toHaveBeenCalledOnce();
+ } finally { controller.abort(); await work; vi.useRealTimers(); vi.doUnmock('electron'); }
+ });
it('keeps a message-only Chromium proxy failure in the network exhaustion category', () => {
const rejection = new Error('net::ERR_PROXY_CONNECTION_FAILED');
expect(classifyTransientNetworkError(rejection)).toBeNull();
diff --git a/test/main/util/retry.test.ts b/test/main/util/retry.test.ts
index 59b52484..1bdbd4d3 100644
--- a/test/main/util/retry.test.ts
+++ b/test/main/util/retry.test.ts
@@ -38,6 +38,29 @@ describe('retryAsync', () => {
});
describe('fetchWithRetry', () => {
+ it.each(['request', 'options'])('cancels the %s signal during HTTP backoff without another attempt', async source => {
+ vi.useFakeTimers();
+ const controller = new AbortController();
+ const fetchMock = vi.fn().mockImplementation(async () => new Response('busy', { status: 503 }));
+ vi.stubGlobal('fetch', fetchMock);
+ let failure: Error | undefined;
+ const work = fetchWithRetry('test:http-cancel', 'https://example.test/api',
+ source === 'request' ? { signal: controller.signal } : undefined,
+ { retries: 2, delaysMs: [10_000], ...(source === 'options' ? { signal: controller.signal } : {}) })
+ .catch(error => { failure = error; });
+ try {
+ await vi.advanceTimersByTimeAsync(1);
+ controller.abort(new Error('user cancelled request'));
+ await vi.advanceTimersByTimeAsync(1);
+ expect(failure?.message).toBe('user cancelled request');
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ await vi.advanceTimersByTimeAsync(30_000);
+ await work;
+ }
+ });
+
it('retries retriable HTTP status responses', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response('busy', { status: 503 }))
diff --git a/test/main/util/run-skill-packages.test.ts b/test/main/util/run-skill-packages.test.ts
index d9da4598..dde545b1 100644
--- a/test/main/util/run-skill-packages.test.ts
+++ b/test/main/util/run-skill-packages.test.ts
@@ -130,6 +130,27 @@ describe('run-skill.cjs › external packages root', () => {
expect(JSON.parse(r.stdout.trim()).marker).toBe('from-package-deps');
});
+ it('preserves package-local ESM import conditions and legacy require conditions', () => {
+ writePackageSkill('mypack', 'pkg-esm', 'pkg-esm');
+ writeRegistry({ version: 1, packages: [{ name: 'mypack', skill_roots: ['skills'], enabled: true }] });
+ const packageDir = path.join(pkgsDir(), 'mypack');
+ const scripts = path.join(packageDir, 'skills', 'pkg-esm', 'scripts');
+ const markerDir = path.join(packageDir, 'node_modules', 'pkg-marker');
+ fs.writeFileSync(path.join(markerDir, 'package.json'), JSON.stringify({
+ name: 'pkg-marker', exports: { import: './import.mjs', require: './index.js' },
+ }));
+ fs.writeFileSync(path.join(markerDir, 'import.mjs'), 'export default await Promise.resolve("from-esm-package");');
+ fs.rmSync(path.join(scripts, 'hello.js'));
+ fs.writeFileSync(path.join(scripts, 'hello.mjs'), `
+ import marker from 'pkg-marker';
+ export default async ({ args }) => ({ marker, legacy: require('pkg-marker'), args });
+ `);
+ const r = runSkill('pkg-esm', 'hello', ['two words']);
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ marker: 'from-esm-package', legacy: 'from-package-deps', args: ['two words'] });
+ });
+
it('does not resolve skills from disabled packages', () => {
writePackageSkill('mypack', 'pkg-hello', 'pkg-hello');
writeRegistry({
diff --git a/test/main/util/run-skill.test.ts b/test/main/util/run-skill.test.ts
index da20debd..9f4447ee 100644
--- a/test/main/util/run-skill.test.ts
+++ b/test/main/util/run-skill.test.ts
@@ -3,6 +3,7 @@ import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
+import { pathToFileURL } from 'node:url';
const TEST_NODE = process.env.ORKAS_TEST_NODE || process.execPath;
@@ -271,6 +272,209 @@ describe('run-skill.cjs', () => {
});
});
+ it('initializes an awaiting .mjs entry once and preserves its default-function invocation', () => {
+ writeCustomSkill('await-entry', 'await-entry', 'run');
+ const skillDir = path.join(tmpDir, 'u1', 'cloud', 'skills', 'await-entry');
+ const marker = path.join(skillDir, 'calls.txt');
+ const entry = path.join(skillDir, 'scripts', 'run.mjs');
+ fs.rmSync(path.join(skillDir, 'scripts', 'run.js'));
+ fs.writeFileSync(entry, `
+ import fs from 'node:fs';
+ await Promise.resolve();
+ fs.appendFileSync(${JSON.stringify(marker)}, 'init\\n');
+ async function dispatch({ args, skillId, skillDir }) {
+ fs.appendFileSync(${JSON.stringify(marker)}, 'dispatch\\n');
+ return { args, skillId, skillDir, url: import.meta.url };
+ }
+ if (require.main === module) await dispatch({ args: ['cli'] });
+ export default dispatch;
+ `);
+
+ const args = ['--selftest', 'two words', '中文', ''];
+ const r = runSkill('await-entry', 'run', args);
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ args, skillId: 'await-entry', skillDir, url: pathToFileURL(fs.realpathSync(entry)).href });
+ expect(fs.readFileSync(marker, 'utf8')).toBe('init\ndispatch\n');
+ });
+
+ it('awaits transitive ESM initialization without duplicating a shared dependency', () => {
+ writeCustomSkill('await-dependency', 'await-dependency', 'run');
+ const skillDir = path.join(tmpDir, 'u1', 'cloud', 'skills', 'await-dependency');
+ const scripts = path.join(skillDir, 'scripts');
+ const marker = path.join(skillDir, 'calls.txt');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.mkdirSync(path.join(scripts, 'nested'));
+ fs.writeFileSync(path.join(scripts, 'nested', 'value.cjs'), 'module.exports = "relative-resource";');
+ fs.writeFileSync(path.join(scripts, 'nested', 'ready.mjs'), `
+ import fs from 'node:fs';
+ fs.appendFileSync(${JSON.stringify(marker)}, 'init\\n');
+ export const value = await Promise.resolve(require('./value.cjs'));
+ export const directory = __dirname;
+ `);
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ import { value, directory } from './nested/ready.mjs';
+ export default async () => {
+ const again = await import('./nested/ready.mjs');
+ return { value, directory, same: value === again.value };
+ };
+ `);
+
+ const r = runSkill('await-dependency', 'run');
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ value: 'relative-resource', directory: fs.realpathSync(path.join(scripts, 'nested')), same: true });
+ expect(fs.readFileSync(marker, 'utf8')).toBe('init\n');
+ });
+
+ it('preserves legacy require and import identity for a synchronous .mjs dependency', () => {
+ writeCustomSkill('legacy-dependency', 'legacy-dependency', 'run');
+ const scripts = path.join(tmpDir, 'u1', 'cloud', 'skills', 'legacy-dependency', 'scripts');
+ const marker = path.join(scripts, 'calls.txt');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.writeFileSync(path.join(scripts, 'helper.mjs'), `
+ require('node:fs').appendFileSync(${JSON.stringify(marker)}, 'init\\n');
+ export const value = {};
+ `);
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ import { value } from './helper.mjs';
+ export default async () => ({ same: value === require('./helper.mjs').value });
+ `);
+
+ const r = runSkill('legacy-dependency', 'run');
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ same: true });
+ expect(fs.readFileSync(marker, 'utf8')).toBe('init\n');
+ });
+
+ it('does not replay initialization or call the default entry after an ESM load failure', () => {
+ writeCustomSkill('failed-initialization', 'failed-initialization', 'run');
+ const scripts = path.join(tmpDir, 'u1', 'cloud', 'skills', 'failed-initialization', 'scripts');
+ const marker = path.join(scripts, 'calls.txt');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.writeFileSync(path.join(scripts, 'ready.mjs'), `
+ import fs from 'node:fs';
+ fs.appendFileSync(${JSON.stringify(marker)}, 'init\\n');
+ await Promise.resolve();
+ throw new Error('fixture initialization failed');
+ `);
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ import './ready.mjs';
+ export default async () => {
+ require('node:fs').appendFileSync(${JSON.stringify(marker)}, 'dispatch\\n');
+ };
+ `);
+
+ const r = runSkill('failed-initialization', 'run');
+ expect(r.status).toBe(71);
+ expect(r.stdout).toBe('');
+ expect(JSON.parse(r.stderr)).toMatchObject({ ok: false, error: expect.stringContaining('fixture initialization failed') });
+ expect(fs.readFileSync(marker, 'utf8')).toBe('init\n');
+ });
+
+ it('preserves authored require bindings and resolves ESM packages from the PC fallback', () => {
+ writeCustomSkill('esm-packages', 'esm-packages', 'run');
+ const skillDir = path.join(tmpDir, 'u1', 'cloud', 'skills', 'esm-packages');
+ const scripts = path.join(skillDir, 'scripts');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ import { z } from 'zod';
+ import { createRequire } from 'node:module';
+ const require = createRequire(import.meta.url);
+ const __orkas_skill_cjs = 'authored';
+ const value = await Promise.resolve(z.string().parse('esm-ready'));
+ export default async () => ({ value, authored: __orkas_skill_cjs,
+ exists: require('node:fs').existsSync(__filename) });
+ `);
+ const r = runSkill('esm-packages', 'run');
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ value: 'esm-ready', authored: 'authored', exists: true });
+ });
+
+ it('retains CommonJS-style .mjs entries and dependency return shapes', () => {
+ writeCustomSkill('cjs-mjs', 'cjs-mjs', 'run');
+ const scripts = path.join(tmpDir, 'u1', 'cloud', 'skills', 'cjs-mjs', 'scripts');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.writeFileSync(path.join(scripts, 'helper.mjs'), `
+ globalThis.__legacyHelperLoads = (globalThis.__legacyHelperLoads || 0) + 1;
+ module.exports = () => "legacy-cjs";
+ `);
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ globalThis.__legacyEntryLoads = (globalThis.__legacyEntryLoads || 0) + 1;
+ module.exports = async ({ args }) => ({ value: require('./helper.mjs')(), args,
+ entryLoads: globalThis.__legacyEntryLoads, helperLoads: globalThis.__legacyHelperLoads });
+ `);
+ const r = runSkill('cjs-mjs', 'run', ['--selftest']);
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ value: 'legacy-cjs', args: ['--selftest'], entryLoads: 1, helperLoads: 1 });
+
+ fs.writeFileSync(path.join(scripts, 'inspect.mjs'), `
+ import helper from './helper.mjs';
+ export default async () => ({ same: helper === require('./helper.mjs'), value: helper(),
+ helperLoads: globalThis.__legacyHelperLoads });
+ `);
+ const inspected = runSkill('cjs-mjs', 'inspect');
+ expect(inspected.status, inspected.stderr).toBe(0);
+ expect(inspected.stderr).toBe('');
+ expect(JSON.parse(inspected.stdout)).toEqual({ same: true, value: 'legacy-cjs', helperLoads: 1 });
+
+ fs.writeFileSync(path.join(scripts, 'named-default.mjs'), 'exports.default = async ({ args }) => ({ args });');
+ const namedDefault = runSkill('cjs-mjs', 'named-default', ['--selftest']);
+ expect(namedDefault.status, namedDefault.stderr).toBe(0);
+ expect(namedDefault.stderr).toBe('');
+ expect(JSON.parse(namedDefault.stdout)).toEqual({ args: ['--selftest'] });
+ });
+
+ it('does not substitute the PC package for a broken package installed beside an ESM Skill', () => {
+ writeCustomSkill('broken-esm-package', 'broken-esm-package', 'run');
+ const skillDir = path.join(tmpDir, 'u1', 'cloud', 'skills', 'broken-esm-package');
+ const scripts = path.join(skillDir, 'scripts');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ const dependency = path.join(skillDir, 'node_modules', 'zod');
+ fs.mkdirSync(dependency, { recursive: true });
+ fs.writeFileSync(path.join(dependency, 'package.json'), JSON.stringify({ name: 'zod', exports: './missing.mjs' }));
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), "import { z } from 'zod'; export default async () => ({ value: z.string().parse('wrong-copy') });");
+ const r = runSkill('broken-esm-package', 'run');
+ expect(r.status).toBe(71);
+ expect(r.stdout).toBe('');
+ expect(JSON.parse(r.stderr)).toMatchObject({ ok: false, error: expect.stringContaining('missing.mjs') });
+ });
+
+ it('retains relative TypeScript dependency resolution and transformation for .mjs entries', () => {
+ writeCustomSkill('esm-ts-dependency', 'esm-ts-dependency', 'run');
+ const scripts = path.join(tmpDir, 'u1', 'cloud', 'skills', 'esm-ts-dependency', 'scripts');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.writeFileSync(path.join(scripts, 'helper.ts'), `
+ enum Mode { Ready = 'typed-ready' }
+ export const value: string = Mode.Ready;
+ `);
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ import { value } from './helper';
+ export default async () => ({ value, same: value === require('./helper.ts').value });
+ `);
+ const r = runSkill('esm-ts-dependency', 'run');
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ value: 'typed-ready', same: true });
+ });
+
+ it('does not report success when ESM initialization remains unsettled without active handles', () => {
+ writeCustomSkill('unsettled-esm', 'unsettled-esm', 'run');
+ const scripts = path.join(tmpDir, 'u1', 'cloud', 'skills', 'unsettled-esm', 'scripts');
+ fs.rmSync(path.join(scripts, 'run.js'));
+ fs.writeFileSync(path.join(scripts, 'run.mjs'), `
+ await new Promise(() => {});
+ export default async () => ({ dispatched: true });
+ `);
+ const r = runSkill('unsettled-esm', 'run');
+ expect(r.status).toBe(71);
+ expect(r.stdout).toBe('');
+ expect(r.stderr).toBe('');
+ });
+
it('does not infer failure from module-specific fields without ok false', () => {
const skillDir = path.join(tmpDir, 'u1', 'local', 'marketplace', 'skills', 'module-result');
fs.mkdirSync(path.join(skillDir, 'scripts'), { recursive: true });
diff --git a/test/main/util/run-tests.test.ts b/test/main/util/run-tests.test.ts
index a58319f6..4995e43f 100644
--- a/test/main/util/run-tests.test.ts
+++ b/test/main/util/run-tests.test.ts
@@ -36,7 +36,8 @@ function fixture() {
setTimeout(() => process.exit(12), 5000);
}
console.log('EXEC:' + JSON.stringify({ family: '${family}', args: process.argv.slice(2),
- electronNode: process.env.ELECTRON_RUN_AS_NODE, outerNode: process.env.ORKAS_TEST_NODE }));
+ electronNode: process.env.ELECTRON_RUN_AS_NODE, outerNode: process.env.ORKAS_TEST_NODE,
+ testPython: process.env.ORKAS_TEST_PYTHON, evalPython: process.env.ORKAS_EVAL_PYTHON }));
console.error('${family}-diagnostic');
if (process.env.HOLD_FAMILY !== '${family}') process.exit(Number(process.env.${family === 'js' ? 'JS' : 'RESOURCE'}_EXIT || 0));
`;
@@ -45,11 +46,30 @@ function fixture() {
return root;
}
+/** npm and direct Node launchers both use the installed npm CLI. Homebrew
+ * and other split layouts can put npm outside the outer Node's prefix. */
+function npmCli(): string | undefined {
+ const bin = path.dirname(node);
+ const candidates = [
+ process.env.npm_execpath,
+ path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
+ path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
+ ];
+ for (const directory of String(process.env.PATH || '').split(path.delimiter)) {
+ if (!directory) continue;
+ try {
+ const entry = fs.realpathSync(path.join(directory, 'npm'));
+ if (path.basename(entry) === 'npm-cli.js') candidates.push(entry);
+ } catch { /* A PATH entry need not contain npm. */ }
+ candidates.push(path.join(directory, 'node_modules', 'npm', 'bin', 'npm-cli.js'));
+ }
+ return candidates.find((candidate): candidate is string => !!candidate && fs.existsSync(candidate));
+}
+
function invoke(root: string, args: string[], env: Record<string, string> = {}) {
- const npm = process.env.npm_execpath;
- const command = npm ? node : process.platform === 'win32' ? 'npm.cmd' : 'npm';
- const commandArgs = npm ? [npm, ...args] : args;
- const result = spawnSync(command, commandArgs, {
+ const npm = npmCli();
+ if (!npm) throw new Error('No npm CLI found on PATH or beside the test Node.');
+ const result = spawnSync(node, [npm, ...args], {
cwd: root, env: { ...process.env, ...env }, encoding: 'utf8', timeout: 15_000,
});
expect(result.error).toBeUndefined();
@@ -61,6 +81,32 @@ function invoke(root: string, args: string[], env: Record<string, string> = {})
}
describe('npm test selection and outcome', () => {
+ it('runs the real npm fixture when a direct Node parent does not export npm_execpath', () => {
+ const previous = process.env.npm_execpath;
+ delete process.env.npm_execpath;
+ try {
+ const result = invoke(fixture(), ['run', 'test:js', '--', 'test/direct.test.ts']);
+ expect(result.status).toBe(0);
+ expect(result.records.map(record => [record.family, record.args])).toEqual([
+ ['js', ['run', 'test/direct.test.ts']],
+ ]);
+ } finally {
+ if (previous === undefined) delete process.env.npm_execpath;
+ else process.env.npm_execpath = previous;
+ }
+ });
+
+ it('shares the configured project Python with fixture subprocesses in both test families', () => {
+ const result = invoke(fixture(), ['test'], {
+ ORKAS_TEST_PYTHON: path.join(os.tmpdir(), 'project-python'), ORKAS_EVAL_PYTHON: '',
+ });
+ expect(result.status).toBe(0);
+ expect(result.records.map(record => [record.family, record.testPython, record.evalPython])).toEqual([
+ ['js', path.join(os.tmpdir(), 'project-python'), path.join(os.tmpdir(), 'project-python')],
+ ['resources', path.join(os.tmpdir(), 'project-python'), path.join(os.tmpdir(), 'project-python')],
+ ]);
+ });
+
it('passes targeted file/name filters intact to JS without starting the resource suite', () => {
const args = ['--run', 'test/selected case.test.ts', '--testNamePattern', 'keeps two words'];
const result = invoke(fixture(), ['test', '--', ...args]);
diff --git a/test/main/util/runtime-gate.test.ts b/test/main/util/runtime-gate.test.ts
index d54845ac..15f592f6 100644
--- a/test/main/util/runtime-gate.test.ts
+++ b/test/main/util/runtime-gate.test.ts
@@ -7,11 +7,15 @@ import * as path from 'node:path';
const require = createRequire(import.meta.url);
const {
+ verifyPhonePasskeyRuntimeDir,
+ requiredRuntimeVerificationEntries,
verifyFfmpegRuntimeDir,
verifyRuntimeRoot,
verifyWhisperRuntimeDir,
verifyWindowsVcImportClosure,
} = require('../../../bin/runtime-gate.cjs') as {
+ verifyPhonePasskeyRuntimeDir: (root: string, platform: string, arch: string, options?: Record<string, unknown>) => string;
+ requiredRuntimeVerificationEntries: (platform: string, arch: string) => string[];
verifyFfmpegRuntimeDir: (root: string, platform: string, arch: string, options?: Record<string, unknown>) => string[];
verifyRuntimeRoot: (root: string, platform: string, arch: string, options?: {
allowedKeys?: string[];
@@ -570,3 +574,48 @@ describe('runtime-gate', () => {
expect(() => verifyWindowsVcImportClosure(app, 'x64')).toThrow(/does not export __CxxFrameHandler3/);
});
});
+
+// A Mac installation must carry a verified helper and the corresponding MPL
+// source/licenses. Windows retains its native OS route and needs no helper.
+describe('phone passkey distribution contract', () => {
+ function fixture() {
+ const root = path.join(tmpDir, 'phone-runtime');
+ const dir = path.join(root, 'phone-passkey/darwin-arm64');
+ fs.mkdirSync(path.join(dir, 'licenses'), { recursive: true });
+ const files = Object.fromEntries(['orkas-phone-passkey', 'NOTICE.txt', 'webauthn-source.tar.gz', 'licenses/OpenSSL-LICENSE.txt'].map(name => {
+ const bytes = Buffer.from(`public fixture ${name}`); fs.writeFileSync(path.join(dir, name), bytes);
+ return [name, { bytes: bytes.length, sha256: crypto.createHash('sha256').update(bytes).digest('hex') }];
+ }));
+ const marker = { schema: 1, protocol: 1, platformKey: 'darwin-arm64', source: 'a'.repeat(64), files };
+ fs.writeFileSync(path.join(dir, '.orkas-phone-passkey.json'), JSON.stringify(marker));
+ return { root, dir, marker };
+ }
+ it('requires Mac helper evidence without adding a Windows runtime requirement', () => {
+ expect(requiredRuntimeVerificationEntries('darwin', 'arm64')).toContain('runtime:phone-passkey:darwin-arm64');
+ expect(requiredRuntimeVerificationEntries('win32', 'x64').some((name: string) => name.includes('phone-passkey'))).toBe(false);
+ const { root, dir } = fixture();
+ expect(verifyPhonePasskeyRuntimeDir(root, 'darwin', 'arm64', { checkArch: false })).toBe(path.join(dir, 'orkas-phone-passkey'));
+ });
+ it('blocks corrupted or incomplete distributable files and rejects path traversal in the inventory', () => {
+ const { root, dir, marker } = fixture();
+ const verify = () => verifyPhonePasskeyRuntimeDir(root, 'darwin', 'arm64', { checkArch: false });
+ fs.writeFileSync(path.join(dir, 'orkas-phone-passkey'), 'tampered');
+ expect(verify).toThrow(/checksum mismatch/);
+ fs.writeFileSync(path.join(dir, 'orkas-phone-passkey'), 'public fixture orkas-phone-passkey');
+ delete (marker.files as any)['webauthn-source.tar.gz'];
+ fs.writeFileSync(path.join(dir, '.orkas-phone-passkey.json'), JSON.stringify(marker));
+ expect(verify).toThrow(/incomplete/);
+ marker.files['webauthn-source.tar.gz'] = { bytes: 0, sha256: 'a'.repeat(64) };
+ const data = fs.readFileSync(path.join(dir, 'webauthn-source.tar.gz'));
+ marker.files['webauthn-source.tar.gz'] = { bytes: data.length, sha256: crypto.createHash('sha256').update(data).digest('hex') };
+ const opensslLicense = marker.files['licenses/OpenSSL-LICENSE.txt'];
+ delete (marker.files as any)['licenses/OpenSSL-LICENSE.txt'];
+ fs.writeFileSync(path.join(dir, '.orkas-phone-passkey.json'), JSON.stringify(marker));
+ expect(verify).toThrow(/incomplete/);
+ marker.files['licenses/OpenSSL-LICENSE.txt'] = opensslLicense;
+ // Keep the intact license/source records so traversal is the isolated failure.
+ (marker.files as any)['../outside'] = { bytes: 0, sha256: 'a'.repeat(64) };
+ fs.writeFileSync(path.join(dir, '.orkas-phone-passkey.json'), JSON.stringify(marker));
+ expect(verify).toThrow(/invalid phone passkey runtime file/);
+ });
+});
diff --git a/test/main/util/test-runtime-env.test.ts b/test/main/util/test-runtime-env.test.ts
index b64dfc76..ec50f84d 100644
--- a/test/main/util/test-runtime-env.test.ts
+++ b/test/main/util/test-runtime-env.test.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
-import { withWindowsGitOnPath } from '../../../scripts/test-runtime-env.mjs';
+import { withTestPython, withWindowsGitOnPath, withWindowsPowerShellModules } from '../../../scripts/test-runtime-env.mjs';
const temporaryRoots: string[] = [];
@@ -21,6 +21,46 @@ function temporaryRoot(): string {
}
describe('test runtime environment', () => {
+ it.each(['win32', 'darwin', 'linux'])('uses the repository virtual environment for %s fixture subprocesses', platform => {
+ const root = temporaryRoot();
+ const python = platform === 'win32'
+ ? path.join(root, 'venv', 'Scripts', 'python.exe')
+ : path.join(root, 'venv', 'bin', 'python');
+ fs.mkdirSync(path.dirname(python), { recursive: true });
+ fs.writeFileSync(python, '');
+ const caller = { PATH: 'unchanged' };
+ expect(withTestPython(caller, root, platform)).toEqual({
+ PATH: 'unchanged', ORKAS_TEST_PYTHON: python, ORKAS_EVAL_PYTHON: python,
+ });
+ expect(caller).toEqual({ PATH: 'unchanged' });
+ });
+
+ it('preserves explicit interpreter choices and leaves absent runtimes unresolved', () => {
+ const root = temporaryRoot();
+ expect(withTestPython({ ORKAS_TEST_PYTHON: 'project-python' }, root)).toEqual({
+ ORKAS_TEST_PYTHON: 'project-python', ORKAS_EVAL_PYTHON: 'project-python',
+ });
+ const explicit = { ORKAS_TEST_PYTHON: 'project-python', ORKAS_EVAL_PYTHON: 'eval-python' };
+ expect(withTestPython(explicit, root)).toEqual(explicit);
+ expect(withTestPython({ PATH: 'unchanged' }, root)).toEqual({ PATH: 'unchanged' });
+ });
+
+ it('restores Windows PowerShell system modules ahead of inherited pwsh modules without mutating the caller', () => {
+ const systemRoot = temporaryRoot();
+ const modules = path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'Modules');
+ fs.mkdirSync(modules, { recursive: true });
+ const caller = { SystemRoot: systemRoot, PSModulePath: `core-modules;${modules};user-modules` };
+ expect(withWindowsPowerShellModules(caller, 'win32').PSModulePath)
+ .toBe(`${modules};core-modules;user-modules`);
+ expect(caller.PSModulePath).toBe(`core-modules;${modules};user-modules`);
+ });
+
+ it('does not invent module roots or change non-Windows shell environments', () => {
+ const caller = { SystemRoot: temporaryRoot(), PSModulePath: 'core-modules' };
+ expect(withWindowsPowerShellModules(caller, 'win32')).toEqual(caller);
+ expect(withWindowsPowerShellModules(caller, 'darwin')).toEqual(caller);
+ });
+
it('discovers GitHub Desktop Git when Windows PATH does not expose git', () => {
const localAppData = temporaryRoot();
const older = path.join(
diff --git a/test/main/util/three-way-text.test.ts b/test/main/util/three-way-text.test.ts
new file mode 100644
index 00000000..2e3f545b
--- /dev/null
+++ b/test/main/util/three-way-text.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+import { mergeThreeWayText } from '../../../src/main/util/three-way-text';
+
+describe('exact three-way text merge', () => {
+ const base = '## Rules\nfirst\nseparator\nlast\n';
+ it('preserves independent same-section changes in either device order', () => {
+ const left = '## Rules\nlocal first\nseparator\nlast\n';
+ const right = '## Rules\nfirst\nseparator\ncloud last\n';
+ const expected = '## Rules\nlocal first\nseparator\ncloud last\n';
+ expect(mergeThreeWayText(base, left, right)).toBe(expected);
+ expect(mergeThreeWayText(base, right, left)).toBe(expected);
+ });
+ it.each([
+ ['same-line phrases', 'Use logs; keep backups.\n', 'Use traces; keep backups.\n', 'Use logs; keep snapshots.\n', 'Use traces; keep snapshots.\n'],
+ ['Chinese phrases', '排查日志;保留备份。\n', '排查链路;保留备份。\n', '排查日志;保留快照。\n', '排查链路;保留快照。\n'],
+ ['shared insertion before replacement', 'a\nb\n', 'a\nx\nb\n', 'a\nx\nB\n', 'a\nx\nB\n'],
+ ['shared insertion after replacement', 'a\nb\n', 'a\nx\nb\n', 'A\nx\nb\n', 'A\nx\nb\n'],
+ ['shared insertion and deletion', 'a\nb\nc\n', 'a\nx\nb\nc\n', 'a\nx\nc\n', 'a\nx\nc\n'],
+ ['Unicode and line endings', '👩‍💻 logs; backups\r\n', '👩‍💻 traces; backups\r\n', '👩‍💻 logs; snapshots\r\n', '👩‍💻 traces; snapshots\r\n'],
+ ])('merges %s exactly in either device order', (_name, ancestor, left, right, expected) => {
+ expect(mergeThreeWayText(ancestor, left, right)).toBe(expected);
+ expect(mergeThreeWayText(ancestor, right, left)).toBe(expected);
+ });
+ it('preserves a deletion and an unrelated addition without resurrecting deleted text', () => {
+ expect(mergeThreeWayText(base, '## Rules\nseparator\nlast\n', base + 'new\n'))
+ .toBe('## Rules\nseparator\nlast\nnew\n');
+ });
+ it.each([
+ ['opposite instructions', '## Rules\nALWAYS publish\n', '## Rules\nNEVER publish\n', '## Rules\npublish with approval\n'],
+ ['delete versus edit', 'first\nlast\n', 'first\nchanged\nlast\n', 'first\nmiddle\nlast\n'],
+ ['different insertions at one point', 'a\nleft\nb\n', 'a\nright\nb\n', 'a\nb\n'],
+ ['opposite changes to one word', 'Use ALWAYS; keep backups.\n', 'Use NEVER; keep backups.\n', 'Use MAYBE; keep backups.\n'],
+ ['different edits within one word', 'cat\n', 'bar\n', 'car\n'],
+ ['insertion at a changed boundary', 'a\nx\nb\n', 'a\nB\n', 'a\nb\n'],
+ ])('preserves ambiguity: %s', (_label, left, right, ancestor) => {
+ expect(mergeThreeWayText(ancestor, left, right)).toBeNull();
+ expect(mergeThreeWayText(ancestor, right, left)).toBeNull();
+ });
+ it('deduplicates identical concurrent edits while retaining another change', () => {
+ expect(mergeThreeWayText('a\nb\nc\nd\n', 'A\nb\nc\nd\n', 'A\nb\nc\nD\n'))
+ .toBe('A\nb\nc\nD\n');
+ });
+ it('handles empty origins, one-sided deletion and exact line endings', () => {
+ expect(mergeThreeWayText('', '', 'new')).toBe('new');
+ expect(mergeThreeWayText(base, '', base)).toBe('');
+ expect(mergeThreeWayText('a\r\nb\r\nc', 'A\r\nb\r\nc', 'a\r\nb\r\nC'))
+ .toBe('A\r\nb\r\nC');
+ });
+ it('rejects newline-heavy divergent documents within a bounded work budget', () => {
+ const original = 'x\n'.repeat(2000);
+ expect(mergeThreeWayText(original, 'left\n' + original, original + 'right\n')).toBeNull();
+ });
+ it('keeps same-line fallback bounded for punctuation-heavy notes', () => {
+ const original = Array.from({ length: 1200 }, (_, index) => `w${index};`).join('');
+ const left = original.replace('w0;', 'left0;').replace('w1199;', 'left1199;');
+ const right = original.replace('w1;', 'right1;').replace('w1198;', 'right1198;');
+ // These four word edits are independent, but their divergent spans exceed
+ // the fine-diff budget. Keep both candidates rather than unbounded work.
+ expect(mergeThreeWayText(original, left, right)).toBeNull();
+ });
+ it('gives both devices the same result with repeated lines and ambiguous alignments', () => {
+ const documents = [''];
+ for (let size = 1; size <= 4; size++) {
+ for (let bits = 0; bits < 2 ** size; bits++) {
+ documents.push(Array.from({ length: size }, (_, index) => bits & (1 << index) ? 'a\n' : 'b\n').join(''));
+ }
+ }
+ for (const ancestor of documents.slice(0, 7)) {
+ for (const left of documents) for (const right of documents) {
+ expect(mergeThreeWayText(ancestor, left, right)).toBe(mergeThreeWayText(ancestor, right, left));
+ }
+ }
+ });
+});
diff --git a/test/main/util/tool-result-cap.test.ts b/test/main/util/tool-result-cap.test.ts
index f77ccc0c..34a5a20b 100644
--- a/test/main/util/tool-result-cap.test.ts
+++ b/test/main/util/tool-result-cap.test.ts
@@ -6,6 +6,7 @@ import type { AgentTool, ToolContext, ToolResult } from '#core-agent';
import { MAX_PER_RESULT_INLINE_TOKENS, MAX_VERBATIM_DOCUMENT_INLINE_TOKENS } from '../../../src/core-agent/src/agent/context-budget';
import {
capToolResult,
+ withRetrievalBudget,
ToolResultPersistenceError,
DEFAULT_INLINE_RESULT_TOKENS,
DEFAULT_LOCAL_TOOL_RESULTS_MAX_BYTES,
@@ -15,6 +16,7 @@ import {
buildPersistedOutputMarkerFromPreview,
buildStructureOutline,
estimateToolResultTokens,
+ inlineResultTokenBudget,
maybeSpillToolResult,
persistToolResult,
sweepToolResults,
@@ -75,6 +77,41 @@ describe('tool-result-cap configuration', () => {
});
});
+describe('retrieval envelope receipt admission', () => {
+ it.each([0, 10, 300])('keeps ignored-field feedback inside a %i-token remaining budget', async budget => {
+ const dir = makeTmpDir();
+ try {
+ const ledger = { remainingTokens: budget, initialTokens: budget };
+ const reads = { epoch: 0, readKeys: new Set<string>() };
+ const ctx: ToolContext = { inputReceipt: { ignored_fields: ['future_option'] }, state: {
+ toolResultInlineLedger: ledger, toolResultReadLedger: reads,
+ } };
+ let executed = false;
+ const result = await withRetrievalBudget(ctx, async child => {
+ executed = true;
+ (child.state.toolResultReadLedger as typeof reads).readKeys.add('source:0');
+ return { content: '{"data":"source","next_cursor":6}' };
+ });
+ expect(estimateToolResultTokens(result.content)).toBeLessThanOrEqual(budget);
+ expect(ledger.remainingTokens).toBe(budget - estimateToolResultTokens(result.content));
+ expect(result.appliedInputReceipt).toBe(ctx.inputReceipt);
+ const remaining = ledger.remainingTokens;
+ expect(capToolResult('retrieval', result, ctx, { maxInlineTokens: 10_000, toolResultsDir: dir })).toBe(result);
+ expect(ledger.remainingTokens).toBe(remaining);
+ expect(fs.readdirSync(dir)).toEqual([]);
+ if (budget === 300) {
+ expect(executed).toBe(true);
+ expect(JSON.parse(result.content)).toEqual({ data: 'source', next_cursor: 6, ignored_fields: ['future_option'] });
+ expect(reads.readKeys.has('source:0')).toBe(true);
+ } else {
+ expect(executed).toBe(false);
+ expect(result.isError).toBe(true);
+ expect(reads.readKeys.size).toBe(0);
+ }
+ } finally { cleanup(dir); }
+ });
+});
+
describe('wrapToolWithCap', () => {
let dir: string;
beforeEach(() => { dir = makeTmpDir(); });
@@ -834,3 +871,30 @@ describe('sweepToolResults', () => {
expect(stats).toMatchObject({ removedStale: 0, removedForQuota: 1, retainedBytes: 24 });
});
});
+
+// Producers that size their own output (read_files pages, task browser
+// observations) share one rule, so every result fits the allowance the cap
+// will apply instead of spilling to a preview.
+describe('inline result token budget', () => {
+ const ledger = (value: Record<string, number>) => ({
+ [TOOL_RESULT_INLINE_LEDGER_STATE_KEY]: { initialTokens: 50_000, ...value },
+ });
+
+ it('takes the smallest of the fixed ceiling, the runner ceiling and what the round has left', () => {
+ expect(inlineResultTokenBudget(undefined)).toBe(DEFAULT_INLINE_RESULT_TOKENS);
+ expect(inlineResultTokenBudget({})).toBe(DEFAULT_INLINE_RESULT_TOKENS);
+ expect(inlineResultTokenBudget(ledger({ remainingTokens: 50_000 }))).toBe(DEFAULT_INLINE_RESULT_TOKENS);
+ expect(inlineResultTokenBudget(ledger({ remainingTokens: 50_000, perResultTokens: 6_000 }))).toBe(6_000);
+ expect(inlineResultTokenBudget(ledger({ remainingTokens: 2_500.7, perResultTokens: 10_000 }))).toBe(2_500);
+ expect(inlineResultTokenBudget(ledger({ remainingTokens: -40 }))).toBe(0);
+ });
+
+ it('gives a document read whole its own ceiling, still bounded by the round', () => {
+ expect(inlineResultTokenBudget(ledger({
+ remainingTokens: 50_000, perResultTokens: 6_000, verbatimDocumentTokens: 25_000,
+ }), true)).toBe(25_000);
+ expect(inlineResultTokenBudget(ledger({
+ remainingTokens: 4_000, perResultTokens: 6_000, verbatimDocumentTokens: 25_000,
+ }), true)).toBe(4_000);
+ });
+});
diff --git a/test/main/util/tool-result-save-retry.test.ts b/test/main/util/tool-result-save-retry.test.ts
index 9260094f..493a9d6a 100644
--- a/test/main/util/tool-result-save-retry.test.ts
+++ b/test/main/util/tool-result-save-retry.test.ts
@@ -12,6 +12,7 @@ import { isRetryableError } from '../../../src/core-agent/src/shared/errors';
import type { AgentTool, ToolResult } from '../../../src/core-agent/src/tools/base';
import type { CompletionResult } from '../../../src/core-agent/src/providers/base';
import type { AgentRunEvent } from '../../../src/core-agent/src/agent/types';
+import { expectTestLog } from '../../helpers/test-log-analysis';
let root: string;
beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-result-retry-')); });
@@ -161,6 +162,9 @@ async function collect(runner: AgentRunner, signal?: AbortSignal) {
describe('result storage failure through the runner', () => {
it.each([false, true])('stops queued work, preserves executed facts and protocol across reload (parallel=%s)', async parallel => {
+ // Asserted below: done.meta.error is TOOL_RESULT_PERSISTENCE_FAILED and the
+ // ledger records `first` as failed. Only the parallel executor logs it.
+ if (parallel) expectTestLog({ level: 'warn', source: 'console', message: /^\[agent-runner\] Tool first failed \(permanent\); details withheld$/ });
vi.stubEnv('ORKAS_MAX_TOOL_CONCURRENCY', '2');
const store = path.join(root, 'results');
const sessionFile = path.join(root, 'session.jsonl');
diff --git a/test/main/util/verify-native-dependencies.test.ts b/test/main/util/verify-native-dependencies.test.ts
index 39450118..f25e2240 100644
--- a/test/main/util/verify-native-dependencies.test.ts
+++ b/test/main/util/verify-native-dependencies.test.ts
@@ -2,7 +2,6 @@ import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import vm from 'node:vm';
import { afterEach, describe, expect, it, vi } from 'vitest';
const requirePackage = createRequire(path.join(process.cwd(), 'package.json'));
@@ -98,28 +97,6 @@ describe('source native dependency readiness', () => {
expect(spawn.mock.calls[0][2].timeout).toBe(PROBE_TIMEOUT_MS);
});
- it('stops development preparation before reporting readiness when the native check fails', () => {
- const calls: string[] = [];
- const output: string[] = [];
- const exit = vi.fn(() => { throw new Error('exit'); });
- const entry = path.join(process.cwd(), 'scripts/ensure-dev-dependencies.cjs');
- const module = { exports: {} };
- const req: any = (name: string) => name === 'node:child_process'
- ? { spawnSync: (_node: string, args: string[]) => {
- const script = path.basename(args[0]); calls.push(script);
- return { status: script === 'verify-native-dependencies.cjs' && !args.includes('--host-only') ? 1 : 0 };
- } } : requirePackage(name.startsWith('.') ? path.resolve(path.dirname(entry), name) : name);
- req.main = module;
- expect(() => vm.runInNewContext(fs.readFileSync(entry, 'utf8'), {
- require: req, module, __dirname: path.dirname(entry),
- process: { execPath: process.execPath, env: {}, platform: 'win32', arch: 'x64', exit },
- console: { log: (s: string) => output.push(s), error: (s: string) => output.push(s) },
- })).toThrow('exit');
- expect(calls).toContain('ensure-sqlite-electron-abi.mjs');
- expect(calls.at(-1)).toBe('verify-native-dependencies.cjs');
- expect(output.join('\n')).toContain('native dependencies failed');
- expect(output.join('\n')).not.toContain('built-in dependencies ready');
- });
it('keeps one repair command guarded before install and verified afterward', () => {
const pkg = requirePackage('./package.json');
diff --git a/test/main/util/window-presentation.test.ts b/test/main/util/window-presentation.test.ts
new file mode 100644
index 00000000..c15d32ac
--- /dev/null
+++ b/test/main/util/window-presentation.test.ts
@@ -0,0 +1,62 @@
+import { EventEmitter } from 'node:events';
+import { describe, expect, it, vi } from 'vitest';
+import { installWindowPresentationEvents } from '../../../src/main/util/window-presentation';
+
+function windowFixture() {
+ const window = new EventEmitter();
+ const contents = Object.assign(new EventEmitter(), { isDestroyed: vi.fn(() => false), send: vi.fn() });
+ const win = Object.assign(window, { webContents: contents });
+ installWindowPresentationEvents(win);
+ return { win, contents, states: () => contents.send.mock.calls.map(call => call[1]) };
+}
+
+describe('native window presentation for task transcripts', () => {
+ it.each([['hide', 'show'], ['minimize', 'restore']])(
+ 'suspends on %s and resumes on %s independently of Chromium visibility', (background, foreground) => {
+ const { win, contents, states } = windowFixture();
+ win.emit(background);
+ win.emit(background);
+ win.emit(foreground);
+ expect(states()).toEqual([{ active: false }, { active: true }]);
+ expect(contents.send.mock.calls.every(call => call[0] === 'conversations:window-visibility')).toBe(true);
+ },
+ );
+
+ it('keeps a visible unfocused transcript streaming without publishing a suspension', () => {
+ const { win, contents, states } = windowFixture();
+ contents.emit('did-finish-load');
+ win.emit('blur');
+ contents.emit('did-finish-load');
+ win.emit('focus');
+ expect(states()).toEqual([{ active: true }, { active: true }]);
+ });
+
+ it.each(['hide', 'minimize'])('does not let focus resume a transcript suspended by %s', event => {
+ const { win, contents, states } = windowFixture();
+ win.emit(event);
+ win.emit('blur');
+ win.emit('focus');
+ contents.emit('did-finish-load');
+ expect(states()).toEqual([{ active: false }, { active: false }]);
+ });
+
+ it('restores the latest background state after a renderer reload without replaying lifecycle transitions', () => {
+ const { win, contents, states } = windowFixture();
+ win.emit('hide');
+ contents.send.mockClear();
+ contents.emit('did-finish-load');
+ expect(states()).toEqual([{ active: false }]);
+ win.emit('show');
+ expect(states()).toEqual([{ active: false }, { active: true }]);
+ });
+
+ it('leaves the initial hidden-at-launch first paint available and never sends to destroyed contents', () => {
+ const { win, contents, states } = windowFixture();
+ contents.emit('did-finish-load');
+ expect(states()).toEqual([{ active: true }]);
+ contents.isDestroyed.mockReturnValue(true);
+ win.emit('hide');
+ contents.emit('did-finish-load');
+ expect(states()).toEqual([{ active: true }]);
+ });
+});
diff --git a/test/setup-env.ts b/test/setup-env.ts
index 084b2019..0aa9ef89 100644
--- a/test/setup-env.ts
+++ b/test/setup-env.ts
@@ -34,6 +34,11 @@ import * as fs from 'node:fs';
import { createRequire, syncBuiltinESMExports } from 'node:module';
import * as os from 'node:os';
import * as path from 'node:path';
+import { installTestLogAnalysis } from './helpers/test-log-analysis';
+
+// Every file's stdout/stderr and console output is classified and attributed
+// to its case or setup/cleanup phase; see ./helpers/test-log-analysis.ts.
+installTestLogAnalysis();
// Unit tests exercise logging through focused opt-in suites. Other cases reset
// modules and temp workspaces freely, so do not start a worker that can outlive
diff --git a/test/web/electron-cleanup.test.ts b/test/web/electron-cleanup.test.ts
index 969e2b53..a7c4decc 100644
--- a/test/web/electron-cleanup.test.ts
+++ b/test/web/electron-cleanup.test.ts
@@ -9,6 +9,7 @@ import { closeElectronFixture, requestElectronQuit } from '../e2e/fixtures/elect
it('defers graceful quit outside evaluation and waits for the real close event', async () => {
const app = new EventEmitter() as any;
app.windows = () => [{}];
+ app.close = vi.fn(async () => {});
let evaluating = false;
let requested = false;
let finished = false;
@@ -35,9 +36,32 @@ it('preserves quit request errors and removes the close observer', async () => {
expect(app.listenerCount('close')).toBe(0);
});
+it('releases the inspector after deferred quit so the real application can exit', async () => {
+ const app = new EventEmitter() as any;
+ app.windows = () => [{}];
+ let quit!: () => void;
+ const quitting = new Promise<void>(resolve => { quit = resolve; });
+ app.evaluate = async (callback: any) => { callback({ app: { quit } }); };
+ app.close = vi.fn(async () => { await quitting; app.emit('close'); });
+ await requestElectronQuit(app);
+ expect(app.close).toHaveBeenCalledTimes(1);
+ expect(app.listenerCount('close')).toBe(0);
+});
+
+it('preserves inspector detach failures instead of reporting graceful shutdown', async () => {
+ const app = new EventEmitter() as any;
+ const failure = new Error('inspector detach failed');
+ app.windows = () => [{}];
+ app.evaluate = async (callback: any) => { callback({ app: { quit: () => {} } }); };
+ app.close = async () => { throw failure; };
+ await expect(requestElectronQuit(app)).rejects.toBe(failure);
+ expect(app.listenerCount('close')).toBe(0);
+});
+
it('waits for real close when quitting destroys the inspector before the close event', async () => {
const app = new EventEmitter() as any;
app.windows = () => [{}];
+ app.close = vi.fn(async () => {});
app.evaluate = async () => { throw new Error('electronApplication.evaluate: Execution context was destroyed, most likely because of a navigation.'); };
let finished = false;
const completion = requestElectronQuit(app).then(() => { finished = true; });
@@ -58,9 +82,11 @@ it.skipIf(process.platform === 'darwin')('waits for natural shutdown after the f
child.signalCode = null;
app.windows = () => [];
app.process = () => child;
+ app.close = vi.fn(async () => {});
app.evaluate = vi.fn();
const completion = requestElectronQuit(app);
expect(app.evaluate).not.toHaveBeenCalled();
+ expect(app.close).toHaveBeenCalledTimes(1);
child.exitCode = 0;
child.emit('exit', 0);
await expect(completion).resolves.toBeUndefined();
@@ -128,7 +154,7 @@ function createCleanupOwner(app: any) {
ts.isClassDeclaration(node) && node.name?.text === 'OrkasTestApp');
if (!owner) throw new Error('Missing fixture owner');
const members = owner.members.filter(member =>
- member.name && ['closeCurrentApp', 'appClosePromises'].includes(member.name.getText(file)));
+ member.name && ['closeCurrentApp', 'appClosePromises', 'appTraceStops', 'stopAppTrace', 'prepareForNativeShutdown'].includes(member.name.getText(file)));
const code = ts.transpileModule(`class CleanupOwner { ${members.map(m => m.getText(file)).join('\n')} }`, {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText;
@@ -145,6 +171,7 @@ function controlledCleanupApp(closeError?: Error) {
const tracingGate = new Promise<void>(resolve => { release = resolve; });
const app = new EventEmitter() as any;
app.windows = () => [{}];
+ app.close = vi.fn(async () => {});
app.process = () => ({ exitCode: 0, signalCode: null });
const stop = vi.fn(() => tracingGate);
app.context = () => ({ tracing: { stop } });
@@ -169,6 +196,19 @@ it('shares one trace and graceful shutdown when relaunch and teardown overlap',
expect(owner.page).toBeNull();
});
+it('exports tracing before native shutdown and reuses that export during teardown', async () => {
+ const { app, stop, release } = controlledCleanupApp();
+ const owner = createCleanupOwner(app);
+ release();
+ await owner.prepareForNativeShutdown();
+ expect(stop).toHaveBeenCalledTimes(1);
+ app.context = () => { throw new Error('Native shutdown disposed the browser context'); };
+ await owner.closeCurrentApp();
+ expect(stop).toHaveBeenCalledTimes(1);
+ expect(owner.tracePaths).toEqual(['trace-1.zip']);
+ expect(app.evaluate).toHaveBeenCalledTimes(1);
+});
+
it('delivers the same cleanup failure and original cause to both overlapping callers', async () => {
const cause = new Error('injected owner close failure');
const { app, release } = controlledCleanupApp(cause);
diff --git a/vitest.config.ts b/vitest.config.ts
index d9bfbb35..33546a5c 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -1,5 +1,6 @@
import { defineConfig } from 'vitest/config';
import { cpus } from 'node:os';
+import { TestLogAnalysisReporter } from './test/log-analysis-reporter';
const logicalCpus = cpus().length || 1;
// Test files exercise real Electron workers, shell helpers, Git, SQLite,
@@ -23,8 +24,10 @@ export default defineConfig({
// the developer's real `PC/data/`. See ./test/setup-env.ts for the
// full rationale.
setupFiles: ['./test/setup-env.ts'],
- // Default reporter is a per-file dot list — keep CI output compact.
- reporters: ['default'],
+ // Default reporter is a per-file dot list — keep CI output compact. The
+ // log-analysis reporter adds the attributed log summary and fails a run
+ // whose executed cases lack analysis (Common/docs/test-case-design.md §3.1).
+ reporters: ['default', new TestLogAnalysisReporter()],
// The desktop suite exercises native modules, file IO, child processes,
// and sqlite-backed features. Leaving Vitest at the host default can
// oversubscribe local dev machines and make otherwise healthy tests trip