The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the update gate's marker judgement never spawns synchronously
Teknium19027b1c7574
diff --git a/apps/desktop/electron/update-marker-async-probe.test.ts b/apps/desktop/electron/update-marker-async-probe.test.tsnew file mode 100644index 00000000000..082dc2b7641--- /dev/null+++ b/apps/desktop/electron/update-marker-async-probe.test.ts@@ -0,0 +1,75 @@+/**+ * Review 5411222842: the update gate judges a marker on Electron's main+ * thread every poll while one exists, so its creation-time and process-state+ * probes must never spawn synchronously (`execFileSync` ps / getconf /+ * powershell blocked the UI for up to 5 s / 15 s). They go through async+ * `execFile`; the synchronous variants stay for the module-init repair lock.+ */++import assert from 'node:assert/strict'+import type * as ChildProcess from 'node:child_process'++import { afterAll, afterEach, beforeAll, test, vi } from 'vitest'++import { hostJudgeEnv, processCreateTime, psCreateTime } from './update-marker'+import { cleanupMarkerFixtures, liveOwner } from './update-marker.test-helpers'++const syncSpawns = vi.hoisted(() => [] as string[])++vi.mock('node:child_process', async importOriginal => {+ const actual = await importOriginal<typeof ChildProcess>()++ return {+ ...actual,+ execFileSync: ((file: string, ...rest: unknown[]) => {+ syncSpawns.push(file)++ return (actual.execFileSync as (...args: unknown[]) => unknown)(file, ...rest)+ }) as typeof actual.execFileSync+ }+})++let owner: Awaited<ReturnType<typeof liveOwner>>++beforeAll(async () => {+ owner = await liveOwner()+})++afterAll(() => {+ owner.kill()+ cleanupMarkerFixtures()+})++afterEach(() => {+ syncSpawns.length = 0+})++function asPlatform<T>(platform: NodeJS.Platform, run: () => Promise<T>): Promise<T> {+ const original = Object.getOwnPropertyDescriptor(process, 'platform')!+ Object.defineProperty(process, 'platform', { ...original, value: platform })++ return run().finally(() => Object.defineProperty(process, 'platform', original))+}++test.skipIf(process.platform !== 'linux')('the Linux creation-time probe never spawns synchronously', async () => {+ const ct = await processCreateTime(owner.pid)++ assert.ok(ct !== null && Math.abs(ct - Date.now() / 1000) < 600, `ct ${ct}`)+ assert.deepEqual(syncSpawns, [])+})++// macOS reads `ps`; procps on Linux prints the same columns, so the darwin+// branch runs here against a real `ps`.+test.skipIf(process.platform === 'win32')('the macOS probes ask ps without blocking the main thread', async () => {+ const reference = psCreateTime(owner.pid)+ syncSpawns.length = 0++ const [ct, alive] = await asPlatform('darwin', async () => [+ await processCreateTime(owner.pid),+ await hostJudgeEnv().isAlive(owner.pid)+ ])++ assert.ok(ct !== null && reference !== null && Math.abs(ct - reference) <= 1, `async ${ct}, sync ${reference}`)+ assert.equal(alive, true)+ assert.deepEqual(syncSpawns, [], 'no execFileSync on the judgement path')+})diff --git a/apps/desktop/electron/update-marker-judge.ts b/apps/desktop/electron/update-marker-judge.tsindex ed6b8eeaae6..10356031d69 100644--- a/apps/desktop/electron/update-marker-judge.ts+++ b/apps/desktop/electron/update-marker-judge.ts@@ -127,7 +127,7 @@ export interface JudgeEnv {/** Our own creation time (unix seconds); null when unreadable. */ourCt: () => number | null | Promise<number | null>/** Alive and not a zombie. Never called for our own pid. */- isAlive: (pid: number) => boolean+ isAlive: (pid: number) => boolean | Promise<boolean>/** Creation time of a live pid; null when unreadable. Only called when the marker recorded one. */createTime: (pid: number) => number | null | Promise<number | null>/** Unix seconds. */diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.tsindex 31c478ff991..59f55660d21 100644--- a/apps/desktop/electron/update-marker.ts+++ b/apps/desktop/electron/update-marker.ts@@ -119,19 +119,57 @@ export function posixProcessState(pid: number): string | null {return null}+/**+ * `posixProcessState` for the update gate's async judgement: macOS asks `ps`+ * without blocking the main thread (Linux reads /proc, no spawn).+ */+export async function posixProcessStateAsync(pid: number): Promise<string | null> {+ if (process.platform !== 'darwin') {+ return posixProcessState(pid)+ }++ const out = await execFileText('ps', ['-o', 'stat=', '-p', String(pid)], { timeout: 5000 })++ return out?.trim().charAt(0) || null+}++/** Async `execFile` stdout, or null on any failure (spawn, exit, timeout). */+function execFileText(+ file: string,+ args: string[],+ options: { env?: NodeJS.ProcessEnv; timeout: number }+): Promise<string | null> {+ return new Promise(resolve => {+ execFile(file, args, { encoding: 'utf8', windowsHide: true, ...options }, (error, stdout) =>+ resolve(error ? null : String(stdout))+ ).stdin?.end()+ })+}+function isZombieState(state: string | null | undefined): boolean {return Boolean(state && state.toUpperCase().startsWith('Z'))}let linuxClockTicks: number | null = null+/** The async path's CLK_TCK: `getconf` once, off the main thread. */+async function linuxClockTicksAsync(): Promise<number> {+ if (linuxClockTicks === null) {+ linuxClockTicks = Number((await execFileText('getconf', ['CLK_TCK'], { timeout: 2000 }))?.trim()) || 100+ }++ return linuxClockTicks+}+function linuxCreateTime(pid: number): number | null {try {const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')+const fields = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)+// Field 22 of /proc/<pid>/stat (starttime, clock ticks since boot) is index// 19 once pid and comm are stripped.const ticks = Number(fields[19])@@ -163,20 +201,32 @@ function linuxCreateTime(pid: number): number | null {*/export function psCreateTime(pid: number): number | null {try {- const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {- encoding: 'utf8',- env: { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' },- timeout: 5000- }).trim()-- const ms = out ? Date.parse(`${out.replace(/\s+/g, ' ')} GMT`) : NaN-- return Number.isFinite(ms) ? ms / 1000 : null+ return parsePsLstart(execFileSync('ps', psLstartArgs(pid), { encoding: 'utf8', env: psLstartEnv(), timeout: 5000 }))} catch {return null}}+/** {@link psCreateTime} without blocking the main thread (the update gate's probe). */+async function psCreateTimeAsync(pid: number): Promise<number | null> {+ return parsePsLstart(await execFileText('ps', psLstartArgs(pid), { env: psLstartEnv(), timeout: 5000 }))+}++function psLstartArgs(pid: number): string[] {+ return ['-o', 'lstart=', '-p', String(pid)]+}++function psLstartEnv(): NodeJS.ProcessEnv {+ return { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC0' }+}++function parsePsLstart(stdout: string | null): number | null {+ const out = String(stdout ?? '').trim()+ const ms = out ? Date.parse(`${out.replace(/\s+/g, ' ')} GMT`) : NaN++ return Number.isFinite(ms) ? ms / 1000 : null+}+/*** Windows creation time through CIM (A1): `Win32_Process.CreationDate` is read* with limited query rights, so it answers for SYSTEM, elevated and other-user@@ -216,18 +266,27 @@ export async function processCreateTime(pid: number): Promise<number | null> {return null}- if (process.platform !== 'win32' || (pid === process.pid && ownCreateTime() !== null)) {- return processCreateTimeSync(pid)+ // Never a synchronous spawn here (it runs on the main thread while a marker+ // exists): Linux reads /proc, macOS and Windows ask ps / CIM asynchronously.+ if (process.platform === 'linux') {+ await linuxClockTicksAsync()++ return linuxCreateTime(pid)}- return new Promise(resolve => {- execFile(- 'powershell.exe',- windowsCreateTimeCommand(pid),- { encoding: 'utf8', timeout: 15_000, windowsHide: true },- (error, stdout) => resolve(error ? null : dotnetTicksToUnix(stdout))- ).stdin?.end()- })+ if (process.platform === 'darwin') {+ return psCreateTimeAsync(pid)+ }++ if (process.platform !== 'win32') {+ return null+ }++ const own = pid === process.pid ? ownCreateTime() : null++ return (+ own ?? dotnetTicksToUnix(await execFileText('powershell.exe', windowsCreateTimeCommand(pid), { timeout: 15_000 }))+ )}/**@@ -323,7 +382,7 @@ export interface MarkerProbeDeps {kill?: typeof process.kill/** Milliseconds since the epoch. */now?: () => number- processState?: (pid: number) => string | null+ processState?: (pid: number) => string | null | Promise<string | null>createTime?: CreateTimeProbe/** The pid judged as "us" (A7 rule 4); default this process. */ownPid?: number@@ -337,7 +396,8 @@ export function hostJudgeEnv(deps: MarkerProbeDeps = {}): JudgeEnv {return {ourPid,ourCt: () => createTime(ourPid),- isAlive: pid => isPidAlive(pid, deps.kill) && !isZombieState((deps.processState || posixProcessState)(pid)),+ isAlive: async pid =>+ isPidAlive(pid, deps.kill) && !isZombieState(await (deps.processState || posixProcessStateAsync)(pid)),createTime,nowS: (deps.now || Date.now)() / 1000}