Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/main/macos-update-running-instances.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'
import { once } from 'node:events'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { expect, it, vi } from 'vitest'
import { spawnProcess } from '../shared/child-process/run-process'
import { getMacUpdateRunningInstances } from './macos-update-running-instances'

it.runIf(process.platform === 'darwin')(
'detects real sibling processes with spaces in the bundle path and clears after they exit',
async () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-update-instances-'))
const executable = path.join(root, 'Orca Test.app', 'Contents', 'MacOS', 'Orca Test')
mkdirSync(path.dirname(executable), { recursive: true })
copyFileSync('/bin/sleep', executable)
const self = spawnProcess({ program: executable, args: ['30'] })
const sibling = spawnProcess({ program: executable, args: ['30'] })
const selfClosed = once(self, 'close')
const siblingClosed = once(sibling, 'close')
try {
expect(self.pid).toBeTypeOf('number')
expect(sibling.pid).toBeTypeOf('number')
await vi.waitFor(async () => {
expect(await getMacUpdateRunningInstances(executable, self.pid)).toEqual([sibling.pid])
})
sibling.kill('SIGTERM')
await siblingClosed
expect(await getMacUpdateRunningInstances(executable, self.pid)).toEqual([])
} finally {
self.kill('SIGTERM')
sibling.kill('SIGTERM')
await Promise.all([selfClosed, siblingClosed])
rmSync(root, { recursive: true, force: true })
}
}
)
83 changes: 83 additions & 0 deletions src/main/macos-update-running-instances.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
getMacUpdateRunningInstances,
parseMacUpdateRunningInstances
} from './macos-update-running-instances'

const { runProcessMock } = vi.hoisted(() => ({ runProcessMock: vi.fn() }))
vi.mock('../shared/child-process/run-process', () => ({ runProcess: runProcessMock }))

const executable = '/Applications/Orca Test.app/Contents/MacOS/Orca Test'

describe('macOS update running instances', () => {
beforeEach(() => {
runProcessMock.mockReset()
})

it('finds sibling main processes while excluding self, helpers, unrelated commands and other app copies', () => {
expect(
parseMacUpdateRunningInstances(
[
` 100 ${executable}`,
` 101 ${executable}`,
` 102 ${executable}`,
' 103 /Applications/Orca Test.app/Contents/Frameworks/Orca Helper.app/Contents/MacOS/Orca Helper',
' 104 /tmp/Orca Test.app/Contents/MacOS/Orca Test',
` 105 /bin/zsh -c ${executable}`,
' 106 /usr/bin/login',
''
].join('\n'),
executable,
100
)
).toEqual([101, 102])
})

it('rejects malformed process output instead of assuming no blockers', () => {
expect(() => parseMacUpdateRunningInstances('not a process row', executable, 100)).toThrow()
})

it('skips development runtimes without probing the host', async () => {
expect(await getMacUpdateRunningInstances('/usr/local/bin/node')).toEqual([])
expect(runProcessMock).not.toHaveBeenCalled()
})

it.each(['linux', 'win32'])('does not probe on %s', async (platform) => {
vi.stubGlobal('process', { ...process, platform })
try {
expect(await getMacUpdateRunningInstances(executable)).toEqual([])
expect(runProcessMock).not.toHaveBeenCalled()
} finally {
vi.unstubAllGlobals()
}
})

it.runIf(process.platform === 'darwin')(
'uses a bounded same-user process query and preserves paths with spaces',
async () => {
runProcessMock.mockResolvedValue({
code: 0,
stdout: `100 ${executable}\n101 ${executable}\n`,
timedOut: false
})
expect(await getMacUpdateRunningInstances(executable, 100)).toEqual([101])
expect(runProcessMock).toHaveBeenCalledWith(
expect.objectContaining({
program: '/bin/ps',
args: ['-U', String(process.getuid?.()), '-ww', '-o', 'pid=,comm='],
timeoutMs: 5000,
killOnOutputLimit: true
})
)
}
)

it.runIf(process.platform === 'darwin').each([
{ code: 1, timedOut: false },
{ code: null, timedOut: true },
{ code: 0, timedOut: false, outputTruncated: true }
])('fails closed for incomplete query results: %j', async (result) => {
runProcessMock.mockResolvedValue({ stdout: '', ...result })
await expect(getMacUpdateRunningInstances(executable)).rejects.toThrow('Could not check')
})
})
45 changes: 45 additions & 0 deletions src/main/macos-update-running-instances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import path from 'node:path'
import { runProcess } from '../shared/child-process/run-process'

/** Squirrel waits for every main application process from the target bundle. */
export async function getMacUpdateRunningInstances(
executable = process.execPath,
currentPid = process.pid
): Promise<number[]> {
if (process.platform !== 'darwin' || !executable.includes('.app/Contents/MacOS/')) {
return []
}
const result = await runProcess({
program: '/bin/ps',
args: ['-U', String(process.getuid?.()), '-ww', '-o', 'pid=,comm='],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
timeoutMs: 5_000,
maxOutputBytes: 2 * 1024 * 1024,
killOnOutputLimit: true
})
if (result.code !== 0 || result.timedOut || result.outputTruncated) {
throw new Error('Could not check running Orca instances')
}
return parseMacUpdateRunningInstances(result.stdout, executable, currentPid)
}

export function parseMacUpdateRunningInstances(
listing: string,
executable: string,
currentPid: number
): number[] {
const pids: number[] = []
for (const line of listing.split('\n')) {
if (!line.trim()) {
continue
}
const row = /^\s*(\d+)\s+(.+)$/.exec(line)
if (!row) {
throw new Error('Invalid macOS process listing')
}
const pid = Number(row[1])
if (pid !== currentPid && path.normalize(row[2]) === path.normalize(executable)) {
pids.push(pid)
}
}
return pids
}
20 changes: 20 additions & 0 deletions src/main/updater-mac-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,23 @@ export function registerMacUpdaterEvents({
recordUpdaterLifecycle('macos_before_quit_guard_bypassed')
return
}
if (macInstallPreflightInProgress) {
event.preventDefault()
return
}
if (isMacQuitAndInstallInFlight()) {
return
}
// Squirrel also installs on ordinary quit; use the same checks as Update & Restart.
if (
process.platform === 'darwin' &&
isMacInstallerReady() &&
hasInstallableDownloadedVersion()
) {
event.preventDefault()
void performQuitAndInstall()
return
}
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
if (
deferMacQuitUntilInstallerReady(
getCurrentStatus(),
Expand All @@ -63,6 +77,11 @@ export function registerMacUpdaterEvents({

/** Whether Squirrel.Mac has finished downloading the update from the localhost proxy. */
let squirrelReady = false
let macInstallPreflightInProgress = false

export function setMacInstallPreflightInProgress(value: boolean): void {
macInstallPreflightInProgress = value
}
/** Remembers a user/app quit request that arrived before Squirrel.Mac had a
* staged update ready to apply. Without this handoff, quitting during the
* localhost-proxy phase exits back into the old app and the update is lost. */
Expand All @@ -83,6 +102,7 @@ function clearPendingInstallTimeout(): void {
}

export function resetMacInstallState(): void {
macInstallPreflightInProgress = false
installRequestedAfterSquirrelReady = false
quitAndInstallInFlight = false
bypassMacInstallGuardOnce = false
Expand Down
119 changes: 118 additions & 1 deletion src/main/updater.mac-install.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const {
autoUpdaterMock,
shellMock,
isMock,
killAllPtyMock
killAllPtyMock,
getMacUpdateRunningInstancesMock
} = vi.hoisted(() => {
const appEventHandlers = new Map<string, ((...args: unknown[]) => void)[]>()
const eventHandlers = new Map<string, ((...args: unknown[]) => void)[]>()
Expand Down Expand Up @@ -80,6 +81,7 @@ const {
openExternal: vi.fn()
},
isMock: { dev: false },
getMacUpdateRunningInstancesMock: vi.fn(async (): Promise<number[]> => []),
killAllPtyMock: vi.fn()
}
})
Expand Down Expand Up @@ -118,8 +120,25 @@ vi.mock('./updater-nudge', () => ({
shouldApplyNudge: vi.fn().mockReturnValue(false)
}))

vi.mock('./macos-update-running-instances', () => ({
getMacUpdateRunningInstances: getMacUpdateRunningInstancesMock
}))

warmUpdaterModule()

async function prepareStagedMacUpdate(downloadUpdate: () => void): Promise<void> {
await vi.waitFor(() => expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1))
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-available', { version: '1.0.61' })
await vi.advanceTimersByTimeAsync(0)
downloadUpdate()
autoUpdaterMock.emit('update-downloaded', { version: '1.0.61' })
const nativeReady = nativeUpdaterMock.on.mock.calls.find(
([event]) => event === 'update-downloaded'
)?.[1]
nativeReady?.()
}

describe('updater mac install handoff', () => {
beforeEach(() => {
vi.resetModules()
Expand All @@ -134,6 +153,7 @@ describe('updater mac install handoff', () => {
appMock.isPackaged = true
isMock.dev = false
killAllPtyMock.mockReset()
getMacUpdateRunningInstancesMock.mockReset().mockResolvedValue([])
autoUpdaterMock.downloadUpdate.mockResolvedValue([])
vi.unstubAllGlobals()
vi.useRealTimers()
Expand Down Expand Up @@ -312,4 +332,101 @@ describe('updater mac install handoff', () => {
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
}
)

it.runIf(process.platform === 'darwin')(
'keeps the app and terminals open when another bundle instance blocks installation, then allows retry',
async () => {
vi.useFakeTimers()
const send = vi.fn()
const onBeforeQuit = vi.fn()
autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined)
const { setupAutoUpdater, downloadUpdate, quitAndInstall, isQuittingForUpdate } =
await loadUpdaterModule()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The updater only reads webContents.send from this window fixture.
setupAutoUpdater({ webContents: { send } } as never, { onBeforeQuit })
await prepareStagedMacUpdate(downloadUpdate)
getMacUpdateRunningInstancesMock.mockResolvedValue([9654, 10718])

quitAndInstall()
await vi.advanceTimersByTimeAsync(1000)

expect(onBeforeQuit).not.toHaveBeenCalled()
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
expect(killAllPtyMock).not.toHaveBeenCalled()
expect(isQuittingForUpdate()).toBe(false)
expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted')
expect(send).toHaveBeenCalledWith(
'updater:status',
expect.objectContaining({
state: 'error',
message: expect.stringContaining('9654, 10718')
})
)

getMacUpdateRunningInstancesMock.mockResolvedValue([])
quitAndInstall()
await vi.advanceTimersByTimeAsync(1000)
expect(onBeforeQuit).toHaveBeenCalledTimes(1)
expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1)
}
)

it.runIf(process.platform === 'darwin')(
'keeps the app open when process enumeration fails',
async () => {
vi.useFakeTimers()
const send = vi.fn()
const onBeforeQuit = vi.fn()
autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined)
const { setupAutoUpdater, downloadUpdate, quitAndInstall, isQuittingForUpdate } =
await loadUpdaterModule()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The updater only reads webContents.send from this window fixture.
setupAutoUpdater({ webContents: { send } } as never, { onBeforeQuit })
await prepareStagedMacUpdate(downloadUpdate)
getMacUpdateRunningInstancesMock.mockRejectedValue(new Error('probe failed'))
quitAndInstall()
await vi.advanceTimersByTimeAsync(1000)
expect(onBeforeQuit).not.toHaveBeenCalled()
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
expect(isQuittingForUpdate()).toBe(false)
expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted')
expect(send).toHaveBeenCalledWith(
'updater:status',
expect.objectContaining({
state: 'error',
message: expect.stringContaining('Could not check')
})
)
}
)

it.runIf(process.platform === 'darwin')(
'checks other instances on a normal quit with a staged update and blocks duplicate quits during the check',
async () => {
vi.useFakeTimers()
const onBeforeQuit = vi.fn()
autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined)
const { setupAutoUpdater, downloadUpdate } = await loadUpdaterModule()
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The updater only reads webContents.send from this window fixture.
setupAutoUpdater({ webContents: { send: vi.fn() } } as never, { onBeforeQuit })
await prepareStagedMacUpdate(downloadUpdate)

let finishProbe: (pids: number[]) => void = () => {}
getMacUpdateRunningInstancesMock.mockImplementation(
() =>
new Promise((resolve) => {
finishProbe = resolve
})
)
const preventDefault = vi.fn()
appMock.emit('before-quit', { preventDefault })
appMock.emit('before-quit', { preventDefault })
expect(preventDefault).toHaveBeenCalledTimes(2)
expect(getMacUpdateRunningInstancesMock).toHaveBeenCalledTimes(1)
finishProbe([9654])
await vi.advanceTimersByTimeAsync(0)
expect(onBeforeQuit).not.toHaveBeenCalled()
expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled()
}
)
})
Loading
Loading