The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
merge: integrate upstream desktop features through PM preparation
ethernet4efb36f81eb8
diff --cc apps/desktop/electron/main.tsindex ebdfed9a28b,156a4559840..95e9fa17db0--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -316,14 -302,9 +317,15 @@@ importimport { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'import { fetchLocalMedia } from './media-range'+import type { GatedDownloadAuth } from './native-auth-decisions'+ import { createMinimizeToTray } from './minimize-to-tray'-import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'-import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'+import {+ oauthSessionIsLive,+ resolveGatedDownloadAuth,+ resolveJsonBody,+ resolveOauthRestAuth,+ resolveReadinessProbeAuth+} from './native-auth-decisions'import {nativeRefreshUrl,type NativeTokenSet,diff --cc apps/desktop/scripts/before-pack.mjsindex 2a04e0312f9,4063687b1c0..d7e5fe84d4d--- a/apps/desktop/scripts/before-pack.mjs+++ b/apps/desktop/scripts/before-pack.mjs@@@ -52,9 -60,9 +52,10 @@@import { existsSync, rmSync, renameSync } from 'node:fs'import path from 'node:path'import { Arch } from 'electron-builder'-import { removeDirSync, stageNodePty, stageGetWindows } from './stage-native-deps.mjs'-import { buildHudModifierMonitor } from './build-hud-modifier-monitor.mjs'+import { copyNativeInputs } from './prepared-native-deps.mjs'++import { removeDirSync } from './stage-native-deps.mjs'+/** @param {string | null | undefined} appOutDir @returns {boolean} */export function cleanStaleAppOutDir(appOutDir) {if (!appOutDir || typeof appOutDir !== 'string') {return falsediff --cc apps/desktop/scripts/build-command-screenshot-monitor.mjsindex a77a35a2c0d,a77a35a2c0d..e14d44022f1--- a/apps/desktop/scripts/build-command-screenshot-monitor.mjs+++ b/apps/desktop/scripts/build-command-screenshot-monitor.mjs@@@ -11,7 -11,7 +11,8 @@@ const root = resolve(dirname(script), '// `platform` is injectable so tests can exercise both branches without// redefining process.platform.export function buildCommandScreenshotMonitor({-- distDir = resolve(root, 'dist'),++ source = resolve(root, '../..'),++ distDir = resolve(source, 'apps/desktop/dist'),platform = process.platform,} = {}) {if (platform !== 'darwin') return null@@@ -28,7 -28,7 +29,7 @@@'clang', '-arch', 'arm64', '-arch', 'x86_64', '-mmacosx-version-min=11.0','-fobjc-arc', '-fblocks', '-O2', '-Wall', '-Wextra','-framework', 'Cocoa', '-framework', 'CoreGraphics',-- resolve(root, 'electron/native/command-screenshot-monitor.m'), '-o', staging,++ resolve(source, 'apps/desktop/electron/native/command-screenshot-monitor.m'), '-o', staging,], { stdio: 'inherit', timeout: 120_000 })chmodSync(staging, 0o755)renameSync(staging, output)diff --cc apps/desktop/scripts/build-hud-modifier-monitor.mjsindex 00000000000,57242ed2fb4..556b5ffb3b9mode 000000,100644..100644--- a/apps/desktop/scripts/build-hud-modifier-monitor.mjs+++ b/apps/desktop/scripts/build-hud-modifier-monitor.mjs@@@ -1,0 -1,97 +1,98 @@@+ #!/usr/bin/env node+ // Optional, host-native helper. No compiler or development headers at runtime.+ import { execFileSync } from 'node:child_process'+ import { chmodSync, mkdirSync, renameSync, rmSync } from 'node:fs'+ import { dirname, resolve } from 'node:path'+ import { fileURLToPath } from 'node:url'++ const script = fileURLToPath(import.meta.url)+ const root = resolve(dirname(script), '..')++ export function hudModifierBinaryRelativePath(platform = process.platform, arch = process.arch) {+ return `native/${platform}-${platform === 'darwin' ? 'universal' : arch}/hud-modifier-monitor${platform === 'win32' ? '.exe' : ''}`+ }++ export function buildHudModifierMonitor({- distDir = resolve(root, 'dist'),++ source = resolve(root, '../..'),++ distDir = resolve(source, 'apps/desktop/dist'),+ platform = process.platform,+ arch = process.arch+ } = {}) {+ // Cross-packaging must not ship a host binary under the target's name. The+ // capability stays unavailable unless that target was built on its own host.+ if (platform !== process.platform || (platform !== 'darwin' && arch !== process.arch)) {+ console.warn(`[hud-modifier] ${platform}-${arch} needs a native build; modifier tap unavailable for this target`)+ return null+ }+ if (!['darwin', 'linux', 'win32'].includes(platform)) return null+ const output = resolve(distDir, hudModifierBinaryRelativePath(platform, arch))+ const staging = `${output}.${process.pid}.tmp${platform === 'win32' ? '.exe' : ''}`- const source = name => resolve(root, 'electron/native', name)++ const nativeSource = name => resolve(source, 'apps/desktop/electron/native', name)+ mkdirSync(dirname(output), { recursive: true })+ try {+ if (platform === 'darwin') {+ execFileSync(+ 'xcrun',+ [+ '--sdk',+ 'macosx',+ 'clang',+ '-arch',+ 'arm64',+ '-arch',+ 'x86_64',+ '-mmacosx-version-min=11.0',+ '-fobjc-arc',+ '-fblocks',+ '-O2',+ '-Wall',+ '-Wextra',+ '-framework',+ 'Cocoa',+ '-framework',+ 'CoreGraphics',- source('hud-modifier-monitor.m'),++ nativeSource('hud-modifier-monitor.m'),+ '-o',+ staging+ ],+ { stdio: 'pipe', timeout: 120_000 }+ )+ } else {+ const windows = platform === 'win32'+ execFileSync(+ process.env.CC || (windows ? 'clang' : 'cc'),+ [+ '-std=gnu11',+ '-O2',+ '-Wall',+ '-Wextra',- source(windows ? 'hud-modifier-monitor-win.c' : 'hud-modifier-monitor-x11.c'),++ nativeSource(windows ? 'hud-modifier-monitor-win.c' : 'hud-modifier-monitor-x11.c'),+ '-o',+ staging,+ ...(windows ? ['-luser32'] : ['-lX11', '-lXi'])+ ],+ { stdio: 'pipe', timeout: 120_000 }+ )+ }+ chmodSync(staging, 0o755)+ renameSync(staging, output)+ console.log(`built ${output}`)+ return output+ } catch (error) {+ rmSync(output, { force: true }) // Never keep a stale helper after a failed rebuild.+ if (platform === 'darwin') throw error // The existing macOS build already requires Xcode.+ const prerequisite = platform === 'linux' ? 'a C compiler, libx11-dev and libxi-dev' : 'Clang and the Windows SDK'+ console.warn(`[hud-modifier] unavailable: native build needs ${prerequisite}; desktop packaging continues`)+ console.warn(String(error.stderr || error.message))+ return null+ } finally {+ rmSync(staging, { force: true })+ }+ }++ if (process.argv[1] && resolve(process.argv[1]) === script) {+ const args = process.argv.slice(2)+ if (args.length && (args.length !== 2 || args[0] !== '--out-dir'))+ throw new Error('Usage: build-hud-modifier-monitor.mjs [--out-dir PATH]')+ buildHudModifierMonitor(args.length ? { distDir: resolve(args[1]) } : {})+ }diff --cc apps/desktop/scripts/prepared-native-deps.mjsindex feec7ffc131,00000000000..f0648b0b8c9mode 100644,000000..100644--- a/apps/desktop/scripts/prepared-native-deps.mjs+++ b/apps/desktop/scripts/prepared-native-deps.mjs@@@ -1,55 -1,0 +1,75 @@@+import fs from 'node:fs'+import path from 'node:path'+import { createHash } from 'node:crypto'+import { fileDigest, treeDigest, preparationRequired } from './prepared-packaging.mjs'++/** @typedef {{ source: string, nativeDeps: string, platform?: string, arch?: string, nativeToolchain?: string }} NativeSelection */+/** @param {string} source @returns {string} */+function nativeIdentity(source) {+ return createHash('sha256').update(JSON.stringify([+ fileDigest(path.join(source, 'package-lock.json')),+ fileDigest(path.join(source, 'apps/desktop/package.json')),+ fileDigest(path.join(import.meta.dirname, 'stage-native-deps.mjs')),+ fileDigest(path.join(import.meta.dirname, 'prepared-native-deps.mjs')),++ ...['build-command-screenshot-monitor.mjs', 'build-hud-modifier-monitor.mjs']++ .map(name => fileDigest(path.join(import.meta.dirname, name))),++ ...['command-screenshot-monitor.m', 'hud-modifier-gesture.h', 'hud-modifier-monitor.m',++ 'hud-modifier-monitor-win.c', 'hud-modifier-monitor-x11.c']++ .map(name => fileDigest(path.join(source, 'apps/desktop/electron/native', name))),+ ])).digest('hex')+}++/**+ * The sidecar stays outside node_modules so it never ships in the application.+ * @param {{ source: string, out: string, platform: string, arch: string, nativeToolchain?: string }} inputs+ * @returns {void}+ */+export function recordNativeInputs({ source, out, platform, arch, nativeToolchain }) {+ fs.writeFileSync(`${out}.prepared.json`, JSON.stringify({+ schema: 1, source: fs.realpathSync(source), out: fs.realpathSync(out),+ platform, arch, nativeToolchain, identity: nativeIdentity(source), digest: treeDigest(out),+ }) + '\n')+}++/** @param {NativeSelection} inputs @returns {string} */+export function readNativeInputs({ source, nativeDeps, platform = process.platform, arch = process.arch, nativeToolchain }) {+ try {+ const record = JSON.parse(fs.readFileSync(`${nativeDeps}.prepared.json`, 'utf8'))+ if (record.schema !== 1 || record.source !== fs.realpathSync(source) || record.out !== fs.realpathSync(nativeDeps) ||+ record.platform !== platform || record.arch !== arch ||+ (nativeToolchain !== undefined && record.nativeToolchain !== nativeToolchain) ||+ record.identity !== nativeIdentity(source) || record.digest !== treeDigest(nativeDeps)) {+ throw preparationRequired('Stale or foreign native inputs')+ }+ if (!fs.statSync(path.join(nativeDeps, 'node-pty/package.json')).isFile()) throw preparationRequired('Missing prepared node-pty')+ return record.out+ } catch (error) {+ throw preparationRequired(`Cannot consume native inputs: ${error instanceof Error ? error.message : String(error)}`)+ }+}++/** @param {NativeSelection & { out: string }} inputs @returns {void} */+export function copyNativeInputs({ out, ...inputs }) {- const nativeDeps = readNativeInputs(inputs)++ copyNativeTree({ nativeDeps: readNativeInputs(inputs), out })++}++++/** Copy admitted modules and executable resources without rebuilding either.++ * @param {{ nativeDeps: string, out: string }} inputs out is the product's node_modules.++ * @returns {void}++ */++export function copyNativeTree({ nativeDeps, out }) {++ nativeDeps = fs.realpathSync(nativeDeps)+ const destination = path.resolve(out)- if (destination === nativeDeps || destination.startsWith(nativeDeps + path.sep) || nativeDeps.startsWith(destination + path.sep)) {- throw preparationRequired('Native input and product directories overlap')++ const helpers = path.join(path.dirname(destination), 'native')++ for (const target of [destination, helpers]) {++ if (target === nativeDeps || target.startsWith(nativeDeps + path.sep) || nativeDeps.startsWith(target + path.sep)) {++ throw preparationRequired('Native input and product directories overlap')++ }+ }+ fs.rmSync(destination, { recursive: true, force: true })- fs.cpSync(nativeDeps, destination, { recursive: true, dereference: true })++ fs.rmSync(helpers, { recursive: true, force: true })++ const preparedHelpers = path.join(nativeDeps, 'native')++ fs.cpSync(nativeDeps, destination, { recursive: true, dereference: true,++ filter: file => file !== preparedHelpers })++ if (fs.existsSync(preparedHelpers)) fs.cpSync(preparedHelpers, helpers, { recursive: true, dereference: true })+}diff --cc apps/desktop/scripts/prepared-native-deps.test.mjsindex e54a43283c2,00000000000..6ae7595477bmode 100644,000000..100644--- a/apps/desktop/scripts/prepared-native-deps.test.mjs+++ b/apps/desktop/scripts/prepared-native-deps.test.mjs@@@ -1,44 -1,0 +1,69 @@@+import assert from 'node:assert/strict'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { test } from 'vitest'+import * as native from './prepared-native-deps.mjs'+import beforePack from './before-pack.mjs'++test('beforePack refuses absent native preparation rather than staging from npm', async () => {+ const source = fs.mkdtempSync(path.join(os.tmpdir(), 'native-hook-'))+ try {+ await assert.rejects(beforePack({ appOutDir: '', electronPlatformName: 'linux', arch: 1,+ packager: { projectDir: path.join(source, 'apps/desktop') } }), /run preparation again/)+ } finally {+ fs.rmSync(source, { recursive: true, force: true })+ }+})+- test('native consumption copies admitted inputs and rejects a different target or changed binding', () => {++test('native consumption copies admitted modules and helpers, rejecting changed sources, targets or bytes', async () => {+ const source = fs.mkdtempSync(path.join(os.tmpdir(), 'prepared-native-'))+ try {- const out = path.join(source, 'native')++ const app = path.join(source, 'apps/desktop')++ const out = path.join(app, 'build/native-deps')+ fs.mkdirSync(path.join(out, 'node-pty'), { recursive: true })- fs.mkdirSync(path.join(source, 'apps/desktop'), { recursive: true })++ fs.cpSync(path.join(import.meta.dirname, '../electron/native'), path.join(app, 'electron/native'), { recursive: true })+ fs.writeFileSync(path.join(source, 'package-lock.json'), '{}')- fs.writeFileSync(path.join(source, 'apps/desktop/package.json'), '{}')++ fs.writeFileSync(path.join(app, 'package.json'), '{}')+ fs.writeFileSync(path.join(out, 'node-pty/package.json'), '{}')+ const binding = path.join(out, 'node-pty/pty.node')+ fs.writeFileSync(binding, 'native fixture')- native.recordNativeInputs({ source, out, platform: 'linux', arch: 'x64', nativeToolchain: 'compiler-a' })- assert.equal(native.readNativeInputs({ source, nativeDeps: out, platform: 'linux', arch: 'x64', nativeToolchain: 'compiler-a' }), out)- assert.throws(() => native.readNativeInputs({ source, nativeDeps: out, platform: 'linux', arch: 'x64', nativeToolchain: 'compiler-b' }), /run preparation again/)- const destination = path.join(source, 'product/node_modules')- native.copyNativeInputs({ source, nativeDeps: out, out: destination, platform: 'linux', arch: 'x64' })++ const helper = 'native/linux-x64/hud-modifier-monitor'++ fs.mkdirSync(path.dirname(path.join(out, helper)), { recursive: true })++ fs.writeFileSync(path.join(out, helper), 'helper fixture', { mode: 0o755 })++ const selection = { source, nativeDeps: out, platform: 'linux', arch: 'x64', nativeToolchain: 'compiler-a' }++ const record = () => native.recordNativeInputs({ ...selection, out })++ record()++ assert.equal(native.readNativeInputs(selection), out)++ assert.throws(() => native.readNativeInputs({ ...selection, nativeToolchain: 'compiler-b' }), /run preparation again/)++ await beforePack({ appOutDir: '', electronPlatformName: 'linux', arch: 1, packager: { projectDir: app } })++ const destination = path.join(app, 'dist/node_modules')++ const copiedHelper = path.join(app, 'dist', helper)++ assert.equal(fs.readFileSync(copiedHelper, 'utf8'), 'helper fixture')++ assert.equal(fs.existsSync(path.join(destination, 'native')), false)++ if (process.platform !== 'win32') assert.equal(fs.statSync(copiedHelper).mode & 0o777, 0o755)+ fs.writeFileSync(path.join(destination, 'node-pty/pty.node'), 'product mutation')+ assert.equal(fs.readFileSync(binding, 'utf8'), 'native fixture')- assert.throws(() => native.readNativeInputs({ source, nativeDeps: out, platform: 'linux', arch: 'arm64' }), /run preparation again/)++ assert.throws(() => native.readNativeInputs({ ...selection, arch: 'arm64' }), /run preparation again/)++ const header = path.join(app, 'electron/native/hud-modifier-gesture.h')++ const originalHeader = fs.readFileSync(header)++ fs.appendFileSync(header, '\n/* changed gesture */\n')++ assert.throws(() => native.readNativeInputs(selection), /run preparation again/)++ fs.writeFileSync(header, originalHeader)++ assert.equal(native.readNativeInputs(selection), out)++ fs.writeFileSync(path.join(out, helper), 'corrupt helper')++ assert.throws(() => native.copyNativeInputs({ ...selection, out: destination }), /run preparation again/)++ assert.equal(fs.readFileSync(copiedHelper, 'utf8'), 'helper fixture')++ fs.writeFileSync(path.join(out, helper), 'helper fixture')+ fs.writeFileSync(binding, 'corrupt')- assert.throws(() => native.copyNativeInputs({ source, nativeDeps: out, out: destination, platform: 'linux', arch: 'x64' }), /run preparation again/)++ assert.throws(() => native.copyNativeInputs({ ...selection, out: destination }), /run preparation again/)+ assert.equal(fs.readFileSync(path.join(destination, 'node-pty/pty.node'), 'utf8'), 'product mutation')++ // A subsequent admitted preparation without optional helpers removes old ones.++ fs.rmSync(path.join(out, 'native'), { recursive: true })++ record()++ native.copyNativeInputs({ ...selection, out: destination })++ assert.equal(fs.existsSync(path.join(app, 'dist/native')), false)+ } finally {+ fs.rmSync(source, { recursive: true, force: true })+ }+})diff --cc apps/desktop/scripts/stage-native-deps.mjsindex bb56593f51a,e6c1282f510..b843222850d--- a/apps/desktop/scripts/stage-native-deps.mjs+++ b/apps/desktop/scripts/stage-native-deps.mjs@@@ -3,12 -3,11 +3,11 @@@//// Usage:// node scripts/stage-native-deps.mjs # host platform/arch-// node scripts/stage-native-deps.mjs win32 arm64 # explicit target+// node scripts/stage-native-deps.mjs --platform win32 --arch arm64+// node scripts/stage-native-deps.mjs --source REPO --out NATIVE_NODE_MODULES//--// Also exported as `stageNodePty({ platform, arch })` for use from--// before-pack.mjs, where electron-builder gives you the real per-target--// platform/arch during multi-arch builds.++// Preparation owns acquisition and helper compilation. beforePack only copies++// the admitted per-target tree.import { createRequire } from 'node:module'import { fileURLToPath } from 'node:url'@@@ -28,9 -26,6 +27,11 @@@ import} from 'node:fs'import { spawnSync } from 'node:child_process'import { isMain } from './utils.mjs'+import { recordNativeInputs } from './prepared-native-deps.mjs'++import { buildCommandScreenshotMonitor } from './build-command-screenshot-monitor.mjs'++import { buildHudModifierMonitor } from './build-hud-modifier-monitor.mjs'+import { parseArgs } from 'node:util'+import { productOutput, withProduct, workspaceTool } from '../../../scripts/build/frontend-common.mjs'const here = dirname(fileURLToPath(import.meta.url))const projectRoot = resolve(here, '..')@@@ -726,27 -718,9 +727,29 @@@ export function stageGetWindowsreturn stageGetWindowsInto(srcRoot, destRoot, { platform, arch, install })}-// Allow direct CLI invocation: node scripts/stage-native-deps.mjs [platform] [arch]+/**+ * Preparation may rebuild/download native bindings; compilation only consumes them.+ * @param {{ source: string, out: string, platform?: string, arch?: string, nativeToolchain?: string }} inputs+ * @returns {Promise<{out: string}>}+ */+export async function prepareDesktopNativeDependencies({ source, out, platform = process.platform, arch = process.arch, nativeToolchain }) {+ ;({ source, out } = productOutput(source, out, ['node_modules', 'apps/desktop/node_modules', 'apps/desktop/src', 'apps/desktop/electron']))+ rmSync(`${out}.prepared.json`, { force: true })+ await withProduct(out, async product => {+ stageNodePty({ source, out: product, platform, arch })+ stageGetWindows({ source, out: product, platform, arch })++ buildCommandScreenshotMonitor({ source, distDir: product, platform })++ buildHudModifierMonitor({ source, distDir: product, platform, arch })+ }, { source })+ recordNativeInputs({ source, out, platform, arch, nativeToolchain })+ return { out }+}+if (isMain(import.meta.url)) {- const [platform, arch] = process.argv.slice(2)- stageNodePty({ platform, arch })- stageGetWindows({ platform, arch })+ const { values } = parseArgs({ options: {+ source: { type: 'string', default: resolve(projectRoot, '../..') },+ out: { type: 'string' }, platform: { type: 'string', default: process.platform }, arch: { type: 'string', default: process.arch },+ 'native-toolchain': { type: 'string' },+ } })+ await prepareDesktopNativeDependencies({ ...values, nativeToolchain: values['native-toolchain'], out: values.out || join(values.source, 'apps/desktop/build/native-deps') })}diff --cc apps/desktop/src/global.d.tsindex 394b7157967,f0e1fa45a47..f1456f11938--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -2,10 -2,9 +2,11 @@@ import type { GatewayWsUrlResult } froimport type { TranslucencyState } from '@hermes/shared/translucency'import type { ScreenshotApi } from '../electron/command-screenshot-types'+import type { MachineProfile } from '../electron/machine-profile'+ import type { HudModifierApi } from '../electron/hud-modifier-types'import type { HermesNotification } from '../electron/notification-types'import type { PoolLimits } from '../electron/pool-limits'+import type { GrowRequest } from '../electron/window-growth'import type { WakeIndicatorState } from './lib/wake-indicator'import type {diff --cc apps/desktop/src/i18n/ar.tsindex ae205771d04,6973d3e2fb0..b6cad52cd26--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@@ -850,10 -843,47 +850,15 @@@ export const ar = defineLocale('عندما يحدّث Hermes نفسه من التطبيق دون موجه طرفية، احتفظ بتعديلات المصدر المحلية أو تجاهلها.'},about: {- heading: 'حول Hermes',- version: value => `الإصدار ${value}`,- versionUnavailable: 'الإصدار غير متاح',- bundleOutOfSync: 'إصدار التطبيق قديم',- bundleOutOfSyncDesc:- 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',- bundleOutOfSyncAction: 'الحصول على المثبّت',- bundleSwapPending: 'أعد التشغيل لإكمال التحديث',- bundleSwapPendingDesc:- 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',- bundleSwapPendingAction: 'إعادة تشغيل Hermes',updates: 'التحديثات',- checkNow: 'التحقق الآن',- checking: 'جار التحقق...',- seeWhatsNew: 'عرض الجديد',- updateNow: 'تحديث الآن',- releaseNotes: 'ملاحظات الإصدار',- onLatest: 'أنت على أحدث إصدار',- installing: 'جار التثبيت...',- cantUpdate: 'تعذر التحديث',- cantReach: 'تعذر الوصول لخدمة التحديث',- tapCheck: 'اضغط للتحقق من التحديثات.',- updateReady: count => `${count} تحديث متاح`,- updateReadyUnknown: 'تحديث جديد جاهز.',- lastChecked: age => `آخر تحقق ${age}`,- justNowSuffix: 'الآن',- automaticUpdates: 'التحديثات التلقائية',- automaticUpdatesDesc: 'اسمح لـ Hermes بالتحقق من التحديثات وتثبيتها.',- branchCommit: (branch, commit) => `${branch} عند ${commit}`,- never: 'أبدا',- justNow: 'الآن',- minAgo: count => `قبل ${count} دقيقة`,- hoursAgo: count => `قبل ${count} ساعة`,- daysAgo: count => `قبل ${count} يوم`},+config: {+ minimizeToTrayTitle: 'التصغير إلى علبة النظام',+ minimizeToTrayDesc:+ 'إخفاء النوافذ المصغّرة في علبة النظام (شريط القوائم على macOS) مع استمرار Hermes في العمل. يظل سلوك الإغلاق وAlt+F4 وCmd+Q كما هو. معطّل افتراضيًا ويُطبّق على هذا الجهاز فقط.',+ minimizeToTrayUnavailable:+ 'علبة النظام غير متاحة. ستُصغّر النوافذ وتُغلق كالمعتاد. أوقف هذا الخيار ثم فعّله لإعادة المحاولة.',none: 'لا شيء',noneParen: '(لا شيء)',notSet: 'غير مضبوط',diff --cc apps/desktop/src/i18n/en.tsindex 61b337d54c1,d08f9ca65a0..416fab2b1dd--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@@ -970,9 -959,48 +970,14 @@@ export const en: Translations =driverHealth: 'Driver health'},about: {- heading: 'Hermes Desktop',- version: value => `Version ${value}`,- versionUnavailable: 'Version unavailable',- bundleOutOfSync: 'App build out of date',- bundleOutOfSyncDesc:- 'The Hermes runtime was updated, but the desktop app itself is still an older build — new interface features (like Bot Mode) will be missing until it updates. Run the update below to rebuild the app. If that doesn\u2019t clear this warning, reinstall from the latest desktop installer.',- bundleOutOfSyncAction: 'Get the installer',- bundleSwapPending: 'Restart to finish the update',- bundleSwapPendingDesc:- 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',- bundleSwapPendingAction: 'Restart Hermes',updates: 'Updates',- checkNow: 'Check now',- checking: 'Checking…',- seeWhatsNew: "See what's new",- updateNow: 'Update now',- releaseNotes: 'Release notes',- onLatest: "You're on the latest version.",- installing: 'An update is currently installing.',- cantUpdate: "This build can't update itself from inside the app.",- cantReach: "We couldn't reach the update server.",- tapCheck: 'Tap "Check now" to look for updates.',- updateReady: count => `A new update is ready (${count} change${count === 1 ? '' : 's'} included).`,- updateReadyUnknown: 'A new update is ready.',- lastChecked: age => `Last checked ${age}`,- justNowSuffix: ' · just now',- automaticUpdates: 'Automatic updates',- automaticUpdatesDesc:- 'Hermes checks for updates automatically in the background and lets you know when one is ready.',- branchCommit: (branch, commit) => `Branch ${branch} · Commit ${commit}`,- never: 'never',- justNow: 'just now',- minAgo: count => `${count} min ago`,- hoursAgo: count => `${count} hours ago`,- daysAgo: count => `${count} days ago`},config: {+ minimizeToTrayTitle: 'Minimize to tray',+ minimizeToTrayDesc:+ 'Hide minimized windows in the system tray (menu bar on macOS) while Hermes keeps running. Close, Alt+F4, and Cmd+Q keep their normal behavior. Off by default; applies only to this device.',+ minimizeToTrayUnavailable:+ 'The system tray is unavailable. Windows will minimize and close normally. Turn this off and on to retry.',none: 'None',noneParen: '(none)',builtinOnly: 'Built-in only',diff --cc apps/desktop/src/i18n/ja.tsindex f062c3b7441,cccba8ce753..63e73e64697--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@@ -931,9 -924,47 +931,14 @@@ export const ja = defineLocale(}}),about: {- heading: 'Hermes Desktop',- version: value => `バージョン ${value}`,- versionUnavailable: 'バージョンを取得できません',- bundleOutOfSync: 'アプリのビルドが古くなっています',- bundleOutOfSyncDesc:- 'Hermes ランタイムは更新されましたが、デスクトップアプリ自体は古いビルドのままです。アプリを更新するまで、新しいインターフェース機能(Bot Mode など)は表示されません。下の更新を実行してアプリを再ビルドしてください。それでもこの警告が消えない場合は、最新のデスクトップインストーラーから再インストールしてください。',- bundleOutOfSyncAction: 'インストーラーを入手',- bundleSwapPending: '再起動して更新を完了',- bundleSwapPendingDesc:- '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',- bundleSwapPendingAction: 'Hermes を再起動',updates: '更新',- checkNow: '今すぐ確認',- checking: '確認中…',- seeWhatsNew: '新機能を見る',- updateNow: '今すぐ更新',- releaseNotes: 'リリースノート',- onLatest: '最新バージョンです。',- installing: '更新をインストール中です。',- cantUpdate: 'このビルドはアプリ内から更新できません。',- cantReach: '更新サーバーに接続できませんでした。',- tapCheck: '更新を探すには「今すぐ確認」を押してください。',- updateReady: count => `新しい更新の準備ができました (${count} 件の変更を含みます)。`,- updateReadyUnknown: '新しい更新の準備ができました。',- lastChecked: age => `前回確認: ${age}`,- justNowSuffix: ' · たった今',- automaticUpdates: '自動更新',- automaticUpdatesDesc: 'Hermes はバックグラウンドで自動的に更新を確認し、利用可能になったら通知します。',- branchCommit: (branch, commit) => `ブランチ ${branch} · コミット ${commit}`,- never: '未確認',- justNow: 'たった今',- minAgo: count => `${count} 分前`,- hoursAgo: count => `${count} 時間前`,- daysAgo: count => `${count} 日前`},config: {+ minimizeToTrayTitle: 'トレイに最小化',+ minimizeToTrayDesc:+ '最小化したウィンドウをシステムトレイ(macOS ではメニューバー)に隠し、Hermes を実行し続けます。閉じる、Alt+F4、Cmd+Q の動作は変わりません。初期設定はオフで、このデバイスにのみ適用されます。',+ minimizeToTrayUnavailable:+ 'システムトレイを利用できないため、通常どおり最小化・終了します。再試行するには一度オフにしてからオンにしてください。',none: 'なし',noneParen: '(なし)',builtinOnly: '内蔵のみ',diff --cc apps/desktop/src/i18n/ru.tsindex a7ec6f02ab2,79e41ad338d..94126f35b44--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@@ -1013,9 -1012,44 +1013,14 @@@ export const ru = defineLocale(}}),about: {- heading: 'Hermes Desktop',- version: value => `Версия ${value}`,- versionUnavailable: 'Версия недоступна',- bundleOutOfSync: 'Сборка приложения устарела',- bundleOutOfSyncDesc:- 'Рантайм Hermes обновлён, но само приложение — ещё старая сборка: новые функции интерфейса (например, Bot Mode) не появятся до обновления. Запустите обновление ниже, чтобы пересобрать приложение. Если предупреждение не исчезнет, переустановите с последнего установщика.',- bundleOutOfSyncAction: 'Скачать установщик',updates: 'Обновления',- checkNow: 'Проверить сейчас',- checking: 'Проверка…',- seeWhatsNew: 'Смотреть, что нового',- updateNow: 'Обновить сейчас',- releaseNotes: 'Заметки о выпуске',- onLatest: 'У вас последняя версия.',- installing: 'Сейчас устанавливается обновление.',- cantUpdate: 'Эта сборка не может обновляться изнутри приложения.',- cantReach: 'Не удалось связаться с сервером обновлений.',- tapCheck: 'Нажмите «Проверить сейчас», чтобы найти обновления.',- updateReady: count =>- `Готово новое обновление (включено ${count} ${RU_PLURAL(count, 'изменение', 'изменения', 'изменений')}).`,- updateReadyUnknown: 'Готово новое обновление.',- lastChecked: age => `Проверено ${age}`,- justNowSuffix: ' · только что',- automaticUpdates: 'Автоматические обновления',- automaticUpdatesDesc: 'Hermes автоматически проверяет обновления в фоне и сообщает, когда они готовы.',- branchCommit: (branch, commit) => `Ветка ${branch} · Коммит ${commit}`,- never: 'никогда',- justNow: 'только что',- minAgo: count => `${count} ${RU_NOUN(count, 'минуту', 'минуты', 'минут')} назад`,- hoursAgo: count => `${count} ${RU_NOUN(count, 'час', 'часа', 'часов')} назад`,- daysAgo: count => `${count} ${RU_NOUN(count, 'день', 'дня', 'дней')} назад`},config: {+ minimizeToTrayTitle: 'Сворачивать в трей',+ minimizeToTrayDesc:+ 'Скрывает свёрнутые окна в системном трее (строке меню macOS), пока Hermes продолжает работать. Закрытие, Alt+F4 и Cmd+Q работают как обычно. По умолчанию выключено; действует только на этом устройстве.',+ minimizeToTrayUnavailable:+ 'Системный трей недоступен. Окна будут сворачиваться и закрываться как обычно. Выключите и снова включите настройку, чтобы повторить попытку.',none: 'Нет',noneParen: '(нет)',builtinOnly: 'Только встроенные',diff --cc apps/desktop/src/i18n/types.tsindex 2bee181c1eb,6344f981775..2b0a92da3fd--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@@ -791,9 -781,43 +791,12 @@@ export interface TranslationsdriverHealth: string}about: {- heading: string- version: (value: string) => string- versionUnavailable: string- bundleOutOfSync: string- bundleOutOfSyncDesc: string- bundleOutOfSyncAction: string- bundleSwapPending: string- bundleSwapPendingDesc: string- bundleSwapPendingAction: stringupdates: string- checkNow: string- checking: string- seeWhatsNew: string- updateNow: string- releaseNotes: string- onLatest: string- installing: string- cantUpdate: string- cantReach: string- tapCheck: string- updateReady: (count: number) => string- updateReadyUnknown: string- lastChecked: (age: string) => string- justNowSuffix: string- automaticUpdates: string- automaticUpdatesDesc: string- branchCommit: (branch: string, commit: string) => string- never: string- justNow: string- minAgo: (count: number) => string- hoursAgo: (count: number) => string- daysAgo: (count: number) => string}config: {+ minimizeToTrayTitle: string+ minimizeToTrayDesc: string+ minimizeToTrayUnavailable: stringnone: stringnoneParen: stringbuiltinOnly: stringdiff --cc apps/desktop/src/i18n/zh-hant.tsindex 532349f027d,44bf30c6468..1515a92ca4c--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@@ -969,9 -962,46 +969,13 @@@ export const zhHant = defineLocale(driverHealth: '驅動程式健康狀態'},about: {- heading: 'Hermes Desktop',- version: value => `版本 ${value}`,- versionUnavailable: '版本不可用',- bundleOutOfSync: '應用程式建置版本過舊',- bundleOutOfSyncDesc:- 'Hermes 執行環境已更新,但桌面應用程式本身仍是舊建置——在應用程式更新之前,新的介面功能(如 Bot Mode)不會顯示。請執行下方的更新以重新建置應用程式。如果此警告仍未消除,請從最新的桌面安裝程式重新安裝。',- bundleOutOfSyncAction: '取得安裝程式',- bundleSwapPending: '重新啟動以完成更新',- bundleSwapPendingDesc:- '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',- bundleSwapPendingAction: '重新啟動 Hermes',updates: '更新',- checkNow: '立即檢查',- checking: '檢查中…',- seeWhatsNew: '查看新增內容',- updateNow: '立即更新',- releaseNotes: '發行說明',- onLatest: '你已是最新版本。',- installing: '正在安裝更新。',- cantUpdate: '此版本無法從應用程式內自行更新。',- cantReach: '無法連線到更新伺服器。',- tapCheck: '點選「立即檢查」以尋找更新。',- updateReady: count => `新更新已就緒(包含 ${count} 項變更)。`,- updateReadyUnknown: '新更新已就緒。',- lastChecked: age => `上次檢查:${age}`,- justNowSuffix: ' · 剛剛',- automaticUpdates: '自動更新',- automaticUpdatesDesc: 'Hermes 會在背景自動檢查更新,並在有可用更新時通知你。',- branchCommit: (branch, commit) => `分支 ${branch} · 提交 ${commit}`,- never: '從未',- justNow: '剛剛',- minAgo: count => `${count} 分鐘前`,- hoursAgo: count => `${count} 小時前`,- daysAgo: count => `${count} 天前`},config: {+ minimizeToTrayTitle: '最小化至系統匣',+ minimizeToTrayDesc:+ '將最小化的視窗隱藏至系統匣(macOS 上為選單列),讓 Hermes 繼續執行。關閉視窗、Alt+F4 和 Cmd+Q 的行為不變。預設關閉,僅適用於此裝置。',+ minimizeToTrayUnavailable: '系統匣無法使用。視窗將正常最小化和關閉。關閉此選項後重新開啟即可重試。',none: '無',noneParen: '(無)',builtinOnly: '僅內建',diff --cc apps/desktop/src/i18n/zh.tsindex e10a62d137a,457981e64d2..b8f5ffc12da--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@@ -1183,9 -1173,45 +1183,13 @@@ export const zh = defineLocale(driverHealth: '驱动健康状态'},about: {- heading: 'Hermes Desktop',- version: value => `版本 ${value}`,- versionUnavailable: '版本不可用',- bundleOutOfSync: '应用构建版本过旧',- bundleOutOfSyncDesc:- 'Hermes 运行时已更新,但桌面应用本身仍是旧构建——在应用更新之前,新的界面功能(如 Bot Mode)不会显示。请运行下方的更新以重新构建应用。如果此警告仍未消除,请从最新的桌面安装程序重新安装。',- bundleOutOfSyncAction: '获取安装程序',- bundleSwapPending: '重启以完成更新',- bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',- bundleSwapPendingAction: '重启 Hermes',updates: '更新',- checkNow: '立即检查',- checking: '检查中…',- seeWhatsNew: '查看新增内容',- updateNow: '立即更新',- releaseNotes: '发行说明',- onLatest: '你已是最新版本。',- installing: '正在安装更新。',- cantUpdate: '此版本无法在应用内自我更新。',- cantReach: '无法连接更新服务器。',- tapCheck: '点击"立即检查"以查找更新。',- updateReady: count => `已准备好新更新 (包含 ${count} 项更改)。`,- updateReadyUnknown: '新更新已就绪。',- lastChecked: age => `上次检查:${age}`,- justNowSuffix: ' · 刚刚',- automaticUpdates: '自动更新',- automaticUpdatesDesc: 'Hermes 会在后台自动检查更新,并在有可用更新时通知你。',- branchCommit: (branch, commit) => `分支 ${branch} · 提交 ${commit}`,- never: '从未',- justNow: '刚刚',- minAgo: count => `${count} 分钟前`,- hoursAgo: count => `${count} 小时前`,- daysAgo: count => `${count} 天前`},config: {+ minimizeToTrayTitle: '最小化到托盘',+ minimizeToTrayDesc:+ '将最小化的窗口隐藏到系统托盘(macOS 上为菜单栏),Hermes 继续运行。关闭窗口、Alt+F4 和 Cmd+Q 的行为不变。默认关闭,仅适用于此设备。',+ minimizeToTrayUnavailable: '系统托盘不可用。窗口将正常最小化和关闭。关闭此选项后重新开启即可重试。',none: '无',noneParen: '(无)',builtinOnly: '仅内置',diff --cc scripts/build/desktop.mjsindex 9b0aaa06340,00000000000..96a0b5251b9mode 100644,000000..100644--- a/scripts/build/desktop.mjs+++ b/scripts/build/desktop.mjs@@@ -1,76 -1,0 +1,77 @@@+#!/usr/bin/env node+import { execFileSync } from 'node:child_process'+import { cpSync, existsSync, readdirSync } from 'node:fs'+import { dirname, join, relative, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { bundleElectronMain } from '../../apps/desktop/scripts/bundle-electron-main.mjs'+import { checkDistBuilt } from '../../apps/desktop/scripts/assert-dist-built.mjs'+import { classifyNativeBinary } from '../../apps/desktop/scripts/stage-native-deps.mjs'++import { copyNativeTree } from '../../apps/desktop/scripts/prepared-native-deps.mjs'+import { frontendArgs, isMain, productOutput, withProduct, workspaceTool } from './frontend-common.mjs'+import { recordProduct, buildInputs } from './freshness.mjs'++function validateNativeTree(nativeDeps, platform) {+ const pty = join(nativeDeps, 'node-pty')+ if (!existsSync(join(pty, 'package.json'))) throw new Error(`Missing prepared node-pty: ${pty}`)+ const bindings = readdirSync(pty, { recursive: true }).filter(name => name.endsWith('.node'))+ if (!bindings.length) throw new Error(`Prepared node-pty has no native binding: ${pty}`)+ for (const binding of bindings) {+ if (classifyNativeBinary(join(pty, binding)) !== platform) {+ throw new Error(`Prepared node-pty binding does not match ${platform}: ${binding}`)+ }+ }+ if (platform === 'darwin' && !existsSync(join(nativeDeps, 'get-windows/main'))) {+ throw new Error('Prepared get-windows is missing its macOS helper')+ }+}++/** Pure desktop compilation. out is the dist directory, not the source app. */+export async function buildDesktop({ source, out, icons, stamp, nativeDeps, typecheck = false, platform = process.platform }) {+ if (!icons || !stamp || !nativeDeps) throw new Error('icons, stamp and nativeDeps are required prepared inputs')+ const app = 'apps/desktop'+ ;({ source, out } = productOutput(source, out, [+ // Source children can be symlinks outside the checkout. Protect their+ // canonical paths, but leave generated dist/build trees to productOutput.+ ...readdirSync(join(resolve(source), app)).filter(name => !['dist', 'build'].includes(name)).map(name => `${app}/${name}`),+ `${app}/scripts`, 'scripts/build', 'package.json', 'package-lock.json',+ 'apps/shared', 'node_modules',+ ...[join(resolve(icons), app, 'public'), stamp, nativeDeps].map(input => relative(resolve(source), resolve(input))),+ ]))+ const publicIcons = join(resolve(icons), app, 'public')+ if (!existsSync(join(publicIcons, 'apple-touch-icon.png'))) throw new Error(`Missing desktop icon: ${join(publicIcons, 'apple-touch-icon.png')}`)+ validateNativeTree(resolve(nativeDeps), platform)+ const inputs = buildInputs(source, 'desktop', { icons: publicIcons, stamp, nativeDeps })+ await withProduct(out, async (product, scratch) => {+ const publicDir = join(scratch, 'public')+ const sourcePublic = join(source, app, 'public')+ if (existsSync(sourcePublic)) cpSync(sourcePublic, publicDir, { recursive: true })+ cpSync(publicIcons, publicDir, { recursive: true })+ if (typecheck) {+ const ts = workspaceTool(source, app, 'typescript')+ execFileSync(process.execPath, [join(dirname(ts), 'tsc.js'), '-p', join(source, app, 'tsconfig.json'),+ '--noEmit', '--incremental', '--tsBuildInfoFile', join(scratch, 'renderer.tsbuildinfo')], { cwd: join(source, app), stdio: 'inherit' })+ }+ const { build } = await import(pathToFileURL(workspaceTool(source, app, 'vite')).href)+ await build({+ root: join(source, app),+ configLoader: 'runner',+ publicDir,+ cacheDir: join(scratch, 'vite-cache'),+ build: { outDir: product, emptyOutDir: true },+ })+ await bundleElectronMain({ source, out: product, stamp })- cpSync(resolve(nativeDeps), join(product, 'node_modules'), { recursive: true, dereference: true })++ copyNativeTree({ nativeDeps, out: join(product, 'node_modules') })+ const result = checkDistBuilt(product)+ if (!result.ok) throw new Error(result.error)+ recordProduct({ source, product: 'desktop', out: product, inputs })+ }, { source })+ return { out }+}++if (isMain(import.meta.url)) {+ const args = frontendArgs(process.argv.slice(2), {+ icons: { type: 'string' }, stamp: { type: 'string' }, 'native-deps': { type: 'string' },+ typecheck: { type: 'boolean' }, platform: { type: 'string' },+ })+ await buildDesktop({ ...args, nativeDeps: args['native-deps'] })+}diff --cc scripts/build/freshness.mjsindex 50524b539f1,00000000000..0f970daef17mode 100644,000000..100644--- a/scripts/build/freshness.mjs+++ b/scripts/build/freshness.mjs@@@ -1,105 -1,0 +1,105 @@@+// Product receipts belong to the compilers, not PM dependency receipts or profiles.+import { createHash } from 'node:crypto'+import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { parseArgs } from 'node:util'+import { isMain } from './frontend-common.mjs'++const receiptName = 'hermes-build.json'+const workspaces = { tui: 'ui-tui', web: 'web', desktop: 'apps/desktop' }+const generated = new Set(['node_modules', 'dist', 'build', 'release', '.cache', '.git', 'coverage', 'test-results', 'playwright-report'])++// buildTui bundles these source roots (including the Ink source alias), not+// the workspaces' documentation, test runners or other product recipes.+const tuiInputs = [+ ...['ui-tui', 'ui-tui/packages/hermes-ink', 'apps/shared'].flatMap(root => [+ `${root}/src`, `${root}/package.json`, `${root}/tsconfig.json`,+ ]),+ 'tsconfig.json', 'package.json', 'package-lock.json', '.npmrc', 'pm/lock.json',+ 'scripts/build/tui.mjs', 'scripts/build/frontend-common.mjs', 'scripts/build/freshness.mjs',+]++function treeHash(root, inputs, skip, contents = () => true) {+ const hash = createHash('sha256')+ function visit(name) {+ if (skip(name)) return+ const file = join(root, name)+ hash.update(name.replaceAll('\\', '/')).update('\0')+ if (!existsSync(file)) { hash.update('missing\0'); return }+ if (statSync(file).isDirectory()) {+ hash.update('directory\0')+ for (const child of readdirSync(file).sort()) visit(`${name}/${child}`)+ } else {+ hash.update(contents(name) ? readFileSync(file) : 'file').update('\0')+ }+ }+ for (const input of inputs) visit(input)+ return hash.digest('hex')+}++export function sourceHash(source, product) {+ const workspace = workspaces[product]+ if (!workspace) throw new Error(`Unknown frontend product: ${product}`)+ return treeHash(source, product === 'tui' ? tuiInputs : [+ workspace, 'apps/shared', 'package.json', 'package-lock.json', '.npmrc', 'pm/lock.json',+ 'scripts/build',+ 'scripts/generate-icons.mjs', 'scripts/generate_icons.py',+ 'assets', 'pyproject.toml', 'uv.lock', 'install-stamp.json',+ ], name => {+ // Build scripts are inputs; workspace build directories are outputs.+ const parts = name.split('/')+ return (!name.startsWith('scripts/') && parts.some(part => generated.has(part)))+ || (product === 'tui' && (parts.includes('__tests__') || /\.(test|spec)(-d)?\.[cm]?[jt]sx?$/.test(name)))+ || parts.some(part => part.startsWith('.dist-') || part.startsWith('.staging-') || part === '__pycache__')+ || name.endsWith('.tsbuildinfo') || name.endsWith('.pyc')+ })+}++function outputHash(out) {+ // Native binaries can be signed after compilation. Their ABI validation is+ // owned by native preparation; renderer/main/preload bytes must stay intact.+ return treeHash(out, readdirSync(out).sort(), name => name === receiptName || name === '.hermes-product',- name => !name.split('/').includes('node_modules'))++ name => !name.split('/').includes('node_modules') && !name.startsWith('native/'))+}++export function buildInputs(source, product, prepared = {}) {+ return {+ sourceHash: sourceHash(source, product),+ prepared: Object.entries(prepared).sort().map(([name, path]) => ({+ name, path: resolve(path), hash: treeHash(resolve(path), ['.'], () => false),+ })),+ }+}++function preparedPaths(inputs) {+ return Object.fromEntries(inputs.prepared.map(({ name, path }) => [name, path]))+}++export function recordProduct({ source, product, out, inputs }) {+ if (JSON.stringify(buildInputs(source, product, preparedPaths(inputs))) !== JSON.stringify(inputs)) {+ throw new Error('Build inputs changed during compilation; retry the build')+ }+ writeFileSync(join(out, receiptName), JSON.stringify({+ schema: 1, product, platform: process.platform, arch: process.arch, node: process.versions.node,+ inputs, outputHash: outputHash(out),+ }) + '\n')+}++export function productCurrent({ source, product, out, prepared }) {+ try {+ const saved = JSON.parse(readFileSync(join(out, receiptName), 'utf8'))+ return saved.schema === 1 && saved.product === product+ && saved.platform === process.platform && saved.arch === process.arch+ && saved.node === process.versions.node+ && JSON.stringify(saved.inputs) === JSON.stringify(buildInputs(source, product, prepared ?? preparedPaths(saved.inputs)))+ && saved.outputHash === outputHash(out)+ } catch { return false }+}++if (isMain(import.meta.url)) {+ const { values } = parseArgs({ options: {+ source: { type: 'string' }, product: { type: 'string' }, out: { type: 'string' },+ } })+ if (!values.source || !values.product || !values.out) throw new Error('--source, --product and --out are required')+ console.log(JSON.stringify(productCurrent(values)))+}diff --cc scripts/ci/desktop_build_cache.pyindex e80612ee08a,00000000000..c71f0a15218mode 100644,000000..100644--- a/scripts/ci/desktop_build_cache.py+++ b/scripts/ci/desktop_build_cache.py@@@ -1,126 -1,0 +1,133 @@@+"""Describe the desktop dependency snapshot using only the runner's stdlib.++Actions transports provider directories directly, including npm's existing+receipt. Restored bytes are candidates: preparation must still admit them.+This module never provisions tools or certifies a cache hit as prepared.+"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import platform+import re+import sys++if __package__ in (None, ""):+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from scripts.ci.setup_toolchain import current_target, file_commands+++CACHE_DOMAINS = ("tools", "python/runtime", "python/build", "npm/_cacache", "native", "packager")+_INPUT_FILES = (+ "package-lock.json", "pyproject.toml", "uv.lock", "pm/lock.json", "pm/pyproject.toml", "pm/uv.lock",+ "scripts/ci/desktop_build_cache.py", "scripts/ci/setup_toolchain.py",+ "scripts/bundles/desktop_prepare.py", "scripts/bundles/desktop_toolchain.py",+ "scripts/bundles/desktop_inputs.py", "scripts/bundles/native.py", "scripts/bundles/native_prepared.py",+ "scripts/bundles/native_build.py",+ "scripts/build/node-deps.mjs", "scripts/build/icon_environment.py",+ "scripts/build/windows_deps.py", "scripts/windows-build-deps.ps1",+ "apps/desktop/scripts/stage-native-deps.mjs", "apps/desktop/scripts/prepare-packaging-tools.mjs",++ "apps/desktop/scripts/build-command-screenshot-monitor.mjs",++ "apps/desktop/scripts/build-hud-modifier-monitor.mjs",++ "apps/desktop/electron/native/command-screenshot-monitor.m",++ "apps/desktop/electron/native/hud-modifier-gesture.h",++ "apps/desktop/electron/native/hud-modifier-monitor.m",++ "apps/desktop/electron/native/hud-modifier-monitor-win.c",++ "apps/desktop/electron/native/hud-modifier-monitor-x11.c",+ "apps/desktop/scripts/windows-bundle-tools.mjs", "apps/desktop/scripts/prepared-native-deps.mjs",+ "apps/desktop/scripts/prepared-packaging.mjs", "apps/desktop/scripts/prepare-dmgbuild.mjs",+ "apps/desktop/scripts/prepare_dmgbuild.py", "apps/desktop/scripts/probe-prepared-native.mjs",+)+++def _input_digest(source: Path, lock: dict) -> str:+ # A coarse lookup hint, not a second receipt or dependency resolver. Owner+ # admission remains necessary even when this digest matches exactly.+ files: set[str] = set(_INPUT_FILES)+ files.update(str(path.relative_to(source)) for path in (source / "pm").glob("*.py"))+ files.update(str(Path(path) / "package.json") for path in lock["packages"]+ if "node_modules" not in path.split("/"))+ digest = hashlib.sha256()+ for name in sorted(files):+ path = source / name+ digest.update(name.encode() + b"\0")+ digest.update(path.read_bytes() if path.is_file() else b"<missing>")+ digest.update(b"\0")+ return digest.hexdigest()+++def _workspace_path(source: Path, name: str) -> None:+ if (not isinstance(name, str) or not name or+ any(char in name for char in "\\:*?[]!\r\n\0") or+ PurePosixPath(name).is_absolute() or+ any(part in ("", ".", "..", "node_modules") for part in name.split("/"))):+ raise ValueError(f"invalid locked workspace path: {name!r}")+ path = source / name+ if not path.resolve().is_relative_to(source) or not (path / "package.json").is_file():+ raise ValueError(f"missing or foreign locked workspace: {name!r}")+++def _cache_path(path: Path) -> str:+ if any(char in str(path) for char in "*?[]!\r\n\0") or path.resolve() != path:+ raise ValueError(f"unsafe cache path: {path}")+ return str(path)+++def describe_cache(source: Path, cache: Path, producer: str, *, work: Path | None = None) -> dict:+ source, cache = source.resolve(), cache.resolve()+ if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}", producer):+ raise ValueError("producer must be a nonempty cache namespace")+ if os.environ.get("HERMES_HOME") and cache.is_relative_to(Path(os.environ["HERMES_HOME"]).resolve()):+ raise ValueError("cache must be separate from HERMES_HOME")+ payload_only = producer == "payload-test"+ lock = {"packages": {}} if payload_only else json.loads(+ (source / "package-lock.json").read_text(encoding="utf-8-sig"))+ # Match the Node owner's locked layout without needing Node before restore.+ workspaces = sorted({entry["resolved"] for entry in lock["packages"].values() if entry.get("link")})+ for workspace in set(workspaces) | {name for name in lock["packages"] if name and "node_modules" not in name.split("/")}:+ _workspace_path(source, workspace)+ domains = ("tools", "python/runtime", "native") if payload_only else CACHE_DOMAINS+ paths = [_cache_path(cache / domain) for domain in domains]+ if not payload_only:+ paths += [_cache_path(source / workspace / "node_modules") for workspace in ["", *workspaces]]+ private_roots = {"source": source, "work": work,+ "HERMES_HOME": Path(os.environ["HERMES_HOME"]) if os.environ.get("HERMES_HOME") else None}+ for name, private in private_roots.items():+ if private is not None and any(private.resolve().is_relative_to(Path(path)) for path in paths):+ raise ValueError(f"{name} must be outside every reusable cache path")+ target = current_target()+ host = hashlib.sha256(json.dumps([+ platform.platform(), os.environ.get("ImageOS", ""), os.environ.get("ImageVersion", ""),+ ]).encode()).hexdigest()[:16]+ prefix = f"desktop-inputs-v1-{producer}-{target}-{host}-"+ input_prefix = f"{prefix}{_input_digest(source, lock)}-"+ run = "-".join(os.environ.get(name, default) for name, default in (+ ("GITHUB_RUN_ID", "local"), ("GITHUB_RUN_ATTEMPT", "1"), ("GITHUB_JOB", "desktop"),+ ))+ return {"target": target, "paths": paths, "restore_keys": [input_prefix, prefix],+ "key": input_prefix + run}+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("phase", choices=["describe"])+ parser.add_argument("--source", type=Path, required=True)+ parser.add_argument("--cache", type=Path, required=True)+ parser.add_argument("--work", type=Path)+ parser.add_argument("--producer", required=True)+ args = parser.parse_args()+ description = describe_cache(args.source, args.cache, args.producer, work=args.work)+ if os.environ.get("GITHUB_OUTPUT"):+ file_commands("GITHUB_OUTPUT", {+ "cache-key": description["key"], "cache-paths": json.dumps(description["paths"]),+ "input-prefix": description["restore_keys"][0], "restore-prefix": description["restore_keys"][1],+ })+ print(json.dumps(description))+++if __name__ == "__main__":+ main()diff --cc tests-js/desktop-builder.test.mjsindex a06003b0562,00000000000..80e28aebe51mode 100644,000000..100644--- a/tests-js/desktop-builder.test.mjs+++ b/tests-js/desktop-builder.test.mjs@@@ -1,199 -1,0 +1,207 @@@+import { execFileSync } from 'node:child_process'+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterEach, expect, test } from 'vitest'+import { stageGetWindows, stageNodePtyInto } from '../apps/desktop/scripts/stage-native-deps.mjs'++const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const roots = []++test('desktop development composition reuses prepared icon pixels instead of provisioning them again', async () => {+ const { buildSourceDesktop } = await import('../apps/desktop/scripts/build.mjs')+ const input = fixture()+ put(join(input.icons, 'apps/desktop/assets/icon.ico'), 'prepared packaging icon')+ const commands = []+ buildSourceDesktop({ source: input.source, icons: input.icons,+ generate: () => { throw new Error('prepared icons must not regenerate') },+ run: (command, args) => commands.push([command, ...args]),+ })+ expect(readFileSync(join(input.source, 'apps/desktop/assets/icon.ico'), 'utf8')).toBe('prepared packaging icon')+ const compile = commands.find(command => command.some(arg => arg.endsWith('/scripts/build/desktop.mjs')))+ expect(compile[compile.indexOf('--icons') + 1]).toBe(input.icons)+})+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })+function put(path, text) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text) }+function fixture() {+ const root = mkdtempSync(join(tmpdir(), 'desktop build with spaces-'))+ roots.push(root)+ const source = join(root, 'source')+ const app = join(source, 'apps/desktop')+ put(join(app, 'package.json'), '{"type":"module"}')+ put(join(app, 'vite.config.mjs'), 'export default { base: "./", build: { minify: false } }')+ put(join(app, 'index.html'), '<html><div id="app"></div><script type="module" src="/src/index.js"></script></html>')+ put(join(app, 'src/index.js'), 'document.getElementById("app").textContent = "built renderer"')+ put(join(app, 'electron/main.ts'), 'console.log(JSON.stringify({ stamp: __HERMES_INSTALL_STAMP__, identity: __HERMES_PRODUCT_IDENTITY__ }))')+ put(join(app, 'electron/preload.ts'), 'globalThis.fixturePreload = "compiled preload"')+ put(join(app, 'electron/preview-guest-preload-entry.ts'), 'globalThis.fixtureGuestPreload = "compiled guest preload"')+ cpSync(join(repo, 'apps/desktop/product-identity.cjs'), join(app, 'product-identity.cjs'))++ cpSync(join(repo, 'apps/desktop/electron/native'), join(app, 'electron/native'), { recursive: true })+ // product-identity.cjs resolves the channel request through the in-tree+ // packaging helper (and its content-types table) by relative path.+ for (const helper of ['scripts/msix-shared.mjs', 'scripts/release-content-types.json']) {+ cpSync(join(repo, helper), join(source, helper))+ }+ symlinkSync(join(repo, 'node_modules'), join(app, 'node_modules'), 'junction')+ const icons = join(root, 'icons')+ put(join(icons, 'apps/desktop/public/apple-touch-icon.png'), 'fresh icon')+ put(join(app, 'public/apple-touch-icon.png'), 'stale icon')+ const nativeDeps = join(root, 'native')+ // The native input is the real host binding, not a fake compiler/dependency.+ stageNodePtyInto(join(repo, 'node_modules/node-pty'), join(nativeDeps, 'node-pty'))+ stageGetWindows({ source: repo, out: nativeDeps })++ put(join(nativeDeps, 'native/helper-fixture'), 'prepared executable resource')+ const stamp = join(root, 'install-stamp.json')+ put(stamp, JSON.stringify({ schemaVersion: 1, payload: 'light', updateMechanism: 'external', commit: 'a'.repeat(40), tag: 'v1.2.3' }))+ return { source, out: join(root, 'result'), icons, nativeDeps, stamp }+}+function files(root, dir = root) {+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {+ const path = join(dir, entry.name)+ if (entry.isDirectory()) return files(root, path)+ return entry.isFile() ? [[path.slice(root.length), readFileSync(path).toString('base64')]] : []+ })+}++test('desktop compiler consumes explicit immutable inputs, replaces variants, and preserves the last product on failure', async () => {+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')+ const input = fixture()+ const before = files(input.source)+ await buildDesktop(input)+ const { productCurrent } = await import('../scripts/build/freshness.mjs')+ expect(productCurrent({ ...input, product: 'desktop' })).toBe(true)+ for (const file of [join(input.icons, 'apps/desktop/public/apple-touch-icon.png'), input.stamp,- join(input.nativeDeps, 'node-pty/package.json')]) {++ join(input.nativeDeps, 'node-pty/package.json'), join(input.nativeDeps, 'native/helper-fixture')]) {+ const original = readFileSync(file)+ put(file, 'changed prepared input')+ expect(productCurrent({ ...input, product: 'desktop' }), file).toBe(false)+ writeFileSync(file, original)+ expect(productCurrent({ ...input, product: 'desktop' })).toBe(true)+ }+ put(join(input.source, 'apps/shared/src/client.ts'), 'export const shared = true')+ expect(productCurrent({ ...input, product: 'desktop' })).toBe(false)+ rmSync(join(input.source, 'apps/shared'), { recursive: true })+ expect(productCurrent({ ...input, product: 'desktop' })).toBe(true)+ expect(files(input.source)).toEqual(before)+ expect(readFileSync(join(input.out, 'apple-touch-icon.png'), 'utf8')).toBe('fresh icon')+ expect(existsSync(join(input.out, 'assets'))).toBe(true)+ expect(existsSync(join(input.out, 'electron-preload.js'))).toBe(true)++ expect(readFileSync(join(input.out, 'native/helper-fixture'), 'utf8')).toBe('prepared executable resource')++ expect(existsSync(join(input.out, 'node_modules/native'))).toBe(false)++ put(join(input.out, 'native/helper-fixture'), 'signed resource')++ expect(productCurrent({ ...input, product: 'desktop' })).toBe(true)++ rmSync(join(input.out, 'native/helper-fixture'))++ expect(productCurrent({ ...input, product: 'desktop' })).toBe(false)+ expect(files(join(input.out, 'node_modules/node-pty')).some(([name]) => name.endsWith('.node'))).toBe(true)+ const run = () => JSON.parse(execFileSync(process.execPath, [join(input.out, 'electron-main.mjs')], { cwd: tmpdir(), encoding: 'utf8' }))+ expect(run().identity.light).toBe(true)+ put(input.stamp, JSON.stringify({ schemaVersion: 1, payload: 'bundled', updateMechanism: 'microsoft-store', commit: 'b'.repeat(40), tag: null }))+ // Ambient variant/tag must not override explicit stamp inputs or cached CJS identity.+ execFileSync(process.execPath, [join(repo, 'scripts/build/desktop.mjs'), ...Object.entries(input).flatMap(([key, value]) => [`--${key === 'nativeDeps' ? 'native-deps' : key}`, value])], {+ cwd: tmpdir(), env: { ...process.env, PATH: '', HERMES_DESKTOP_VARIANT: 'light', HERMES_PAYLOAD_TAG: 'v1.0.0-canary.20260911' }, stdio: 'pipe',+ })+ expect(run().identity.store).toBe(true)+ expect(run().identity.light).toBe(false)+ expect(run().stamp.commit).toBe('b'.repeat(40))+ const built = files(input.out)+ put(join(input.source, 'apps/desktop/electron/main.ts'), 'THIS IS NOT TYPESCRIPT !!!')+ await expect(buildDesktop(input)).rejects.toThrow()+ expect(files(input.out)).toEqual(built)+ expect(files(input.source).some(([name]) => name.includes('.vite') || name.endsWith('tsbuildinfo'))).toBe(false)+}, 60000)++test('desktop output cannot overlap a source directory symlinked outside the checkout', async () => {+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')+ const root = mkdtempSync(join(tmpdir(), 'desktop symlinked source-'))+ roots.push(root)+ const source = join(root, 'source')+ const externalSource = join(root, 'external-source')+ mkdirSync(join(source, 'apps/desktop'), { recursive: true })+ put(join(externalSource, 'index.js'), 'source must not change')+ symlinkSync(externalSource, join(source, 'apps/desktop/src'), 'junction')+ const out = join(externalSource, 'product')+ const before = files(root)++ // Missing prepared inputs must not hide a failure to reject source overlap.+ await expect(buildDesktop({ source, out,+ icons: join(root, 'icons'), stamp: join(root, 'stamp.json'), nativeDeps: join(root, 'native'),+ })).rejects.toThrow(/Output must not overlap build inputs/)+ expect(files(root)).toEqual(before)+ expect(readdirSync(externalSource)).toEqual(['index.js'])+ expect(existsSync(out)).toBe(false)+})++test('in-tree desktop products rebuild after build exists without replacing prepared inputs', async () => {+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')+ const { productCurrent } = await import('../scripts/build/freshness.mjs')+ const input = fixture()+ input.out = join(input.source, 'apps/desktop/build/products/desktop')+ await buildDesktop(input)+ put(join(input.source, 'apps/desktop/src/index.js'), 'document.getElementById("app").textContent = "warm rebuild"')+ await buildDesktop(input)+ expect(productCurrent({ ...input, product: 'desktop' })).toBe(true)+ const assets = files(join(input.out, 'assets')).map(([, bytes]) => Buffer.from(bytes, 'base64').toString()).join('')+ expect(assets).toContain('warm rebuild')++ // The generated-path allowance never overrides an explicitly prepared input,+ // even when that input itself is an earlier builder-owned product.+ const built = files(input.out)+ for (const prepared of [+ { stamp: join(input.out, 'hermes-build.json') },+ { nativeDeps: join(input.out, 'node_modules') },+ { icons: input.out },+ ]) {+ await expect(buildDesktop({ ...input, ...prepared })).rejects.toThrow(/overlap/)+ expect(files(input.out)).toEqual(built)+ }+}, 30000)++test('a prepared input changing during desktop compilation cannot publish a current receipt', async () => {+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')+ const input = fixture()+ await buildDesktop(input)+ const previous = files(input.out)+ const changedStamp = { ...JSON.parse(readFileSync(input.stamp, 'utf8')), commit: 'c'.repeat(40) }+ put(join(input.source, 'apps/desktop/vite.config.mjs'), `+ import { writeFileSync } from 'node:fs';+ export default { plugins: [{ name: 'change-prepared-input', buildStart() {+ writeFileSync(${JSON.stringify(input.stamp)}, ${JSON.stringify(JSON.stringify(changedStamp))})+ }}] }+ `)+ await expect(buildDesktop(input)).rejects.toThrow(/inputs changed/)+ expect(files(input.out)).toEqual(previous)+}, 30000)++test('native preparation stages the selected source into an explicit tree before compilation', async () => {+ const { prepareDesktopNativeDependencies } = await import('../apps/desktop/scripts/stage-native-deps.mjs')+ const input = fixture()+ cpSync(join(repo, 'package-lock.json'), join(input.source, 'package-lock.json'))+ const nativeOut = join(dirname(input.out), 'prepared-native')+ await prepareDesktopNativeDependencies({ source: input.source, out: nativeOut })+ expect(existsSync(join(nativeOut, 'node-pty/package.json'))).toBe(true)+ expect(files(join(nativeOut, 'node-pty')).some(([name]) => name.endsWith('.node'))).toBe(true)+ expect(existsSync(join(input.source, 'apps/desktop/dist'))).toBe(false)+})++test('typecheck uses scratch state and incomplete prepared inputs fail before publication', async () => {+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')+ const input = fixture()+ put(join(input.source, 'apps/desktop/tsconfig.json'), JSON.stringify({ compilerOptions: { composite: true, skipLibCheck: true, types: [] }, include: ['src/*.ts'] }))+ put(join(input.source, 'apps/desktop/src/typed.ts'), 'export const value: string = "valid"')+ await buildDesktop({ ...input, typecheck: true })+ const built = files(input.out)+ expect(files(input.source).some(([name]) => name.endsWith('.tsbuildinfo') || name.endsWith('typed.js'))).toBe(false)+ put(join(input.source, 'apps/desktop/src/typed.ts'), 'export const value: string = 123')+ await expect(buildDesktop({ ...input, typecheck: true })).rejects.toThrow()+ expect(files(input.out)).toEqual(built)+ rmSync(join(input.icons, 'apps/desktop/public/apple-touch-icon.png'))+ await expect(buildDesktop(input)).rejects.toThrow(/icon/i)+ expect(files(input.out)).toEqual(built)+ await expect(buildDesktop({ ...input, out: join(input.source, 'apps/desktop/scripts') })).rejects.toThrow(/Output/)+ put(join(input.icons, 'apps/desktop/public/apple-touch-icon.png'), 'fresh icon')+ rmSync(join(input.nativeDeps, 'node-pty/build'), { recursive: true, force: true })+ rmSync(join(input.nativeDeps, 'node-pty/prebuilds'), { recursive: true, force: true })+ await expect(buildDesktop(input)).rejects.toThrow(/native binding/)+ expect(files(input.out)).toEqual(built)+}, 30000)