Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
49 changes: 49 additions & 0 deletions .github/workflows/macos-updater-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: macOS updater regression tests

on:
pull_request:
paths:
- '.github/workflows/macos-updater-tests.yml'
- 'src/main/macos-update-running-instances*'
- 'src/main/updater*'
- 'src/main/updater/**'
- 'src/main/startup/main-process-quit*'
- 'src/main/window/main-window-state-lifecycle*'
- 'src/main/window/dashboard-popout-window*'
- 'src/shared/child-process/**'
- 'src/shared/update-status-types.ts'
- 'pnpm-lock.yaml'
workflow_dispatch:

permissions:
contents: read

concurrency:
group: macos-updater-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
updater:
runs-on: macos-15
timeout-minutes: 20
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: ./.github/actions/install-node-dependencies
with:
native-runtime: node
- name: Exercise native application registry and update shutdown
env:
ORCA_BACKGROUND_LAUNCH: '1'
run: >-
pnpm exec vitest run --config config/vitest.config.ts
src/main/macos-update-running-instances.test.ts
src/main/macos-update-running-instances.integration.test.ts
src/main/updater.mac-install.test.ts
src/main/updater.headless-serve-install.test.ts
src/main/updater-mac-quit-guard.test.ts
src/main/startup/desktop-startup-ordering.test.ts
src/main/startup/main-process-quit-update-veto.test.ts
src/main/window/main-window-state-lifecycle.test.ts
src/main/window/dashboard-popout-window.test.ts
97 changes: 97 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,97 @@
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { runProcess, spawnProcess } from '../shared/child-process/run-process'
import { getMacUpdateRunningInstances } from './macos-update-running-instances'

const APPLICATION_SOURCE = `
#import <AppKit/AppKit.h>
#import <unistd.h>
int main(int argc, const char *argv[]) {
if (argc > 1) { sleep(30); return 0; }
@autoreleasepool {
NSApplication *app = [NSApplication sharedApplication];
[app setActivationPolicy:NSApplicationActivationPolicyProhibited];
[app run];
}
return 0;
}
`

it.runIf(process.platform === 'darwin')(
'matches ShipIt with registered sibling apps, excluding same-executable workers and other bundle copies',
async () => {
const root = mkdtempSync(path.join(tmpdir(), 'orca-update-instances-'))
const bundle = path.join(root, 'Orca Test.app')
const executable = path.join(bundle, 'Contents', 'MacOS', 'Orca Test')
mkdirSync(path.dirname(executable), { recursive: true })
const sourcePath = path.join(root, 'application.m')
writeFileSync(sourcePath, APPLICATION_SOURCE)
writeFileSync(
path.join(bundle, 'Contents', 'Info.plist'),
`<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>
<key>CFBundleIdentifier</key><string>com.stablyai.${path.basename(root)}</string>
<key>CFBundleExecutable</key><string>Orca Test</string>
<key>CFBundlePackageType</key><string>APPL</string>
</dict></plist>`
)
const children: ReturnType<typeof spawnProcess>[] = []
const closed: Promise<unknown>[] = []
try {
const compilation = await runProcess({
program: '/usr/bin/clang',
args: ['-framework', 'AppKit', sourcePath, '-o', executable],
timeoutMs: 15_000
})
expect(compilation.code, compilation.stderr).toBe(0)
const otherBundle = path.join(root, 'Other Orca.app')
cpSync(bundle, otherBundle, { recursive: true })
for (const [program, args] of [
[executable, []],
[executable, []],
[executable, ['--worker']],
[path.join(otherBundle, 'Contents', 'MacOS', 'Orca Test'), []]
] satisfies [string, string[]][]) {
const child = spawnProcess({
program,
args,
env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' }
})
children.push(child)
closed.push(once(child, 'close'))
}
const [self, sibling, worker, otherCopy] = children
await vi.waitFor(
async () => {
expect(self.pid).toBeTypeOf('number')
expect(sibling.pid).toBeTypeOf('number')
expect(await getMacUpdateRunningInstances(executable, self.pid)).toEqual([sibling.pid])
expect(
await getMacUpdateRunningInstances(
path.join(otherBundle, 'Contents', 'MacOS', 'Orca Test'),
0
)
).toEqual([otherCopy.pid])
const workerListing = await runProcess({
program: '/bin/ps',
args: ['-p', String(worker.pid), '-ww', '-o', 'comm=']
})
expect(workerListing.stdout.trim()).toBe(executable)
},
{ timeout: 5000 }
)
sibling.kill('SIGTERM')
await closed[1]
expect(await getMacUpdateRunningInstances(executable, self.pid)).toEqual([])
} finally {
for (const child of children) {
child.kill('SIGTERM')
}
await Promise.all(closed)
rmSync(root, { recursive: true, force: true })
}
},
25_000
)
106 changes: 106 additions & 0 deletions src/main/macos-update-running-instances.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
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('excludes the current process from the native registry result', () => {
expect(parseMacUpdateRunningInstances('[100,101,102]\n', 100)).toEqual([101, 102])
expect(parseMacUpdateRunningInstances('[]\n', 100)).toEqual([])
})

it.each([
'not JSON',
'',
'{}',
'null',
'[0]',
'[-1]',
'[1.5]',
'["101"]',
'[null]',
'[9007199254740992]'
])('rejects invalid registry output: %s', (listing) => {
expect(() => parseMacUpdateRunningInstances(listing, 100)).toThrow()
})

it.runIf(process.platform === 'darwin')(
'passes the bundle path as an argument rather than executable script',
async () => {
const unusualExecutable = '/Applications/Orca "Test" $HOME.app/Contents/MacOS/Orca Test'
runProcessMock.mockResolvedValue({ code: 0, stdout: '[]', timedOut: false })
await expect(getMacUpdateRunningInstances(unusualExecutable)).resolves.toEqual([])
expect(runProcessMock).toHaveBeenCalledWith(
expect.objectContaining({
args: [
'-l',
'JavaScript',
'-e',
expect.not.stringContaining('$HOME'),
'/Applications/Orca "Test" $HOME.app'
]
})
)
}
)

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 the bounded native application registry query and preserves paths with spaces',
async () => {
runProcessMock.mockResolvedValue({
code: 0,
stdout: '[100,101]\n',
timedOut: false
})
expect(await getMacUpdateRunningInstances(executable, 100)).toEqual([101])
expect(runProcessMock).toHaveBeenCalledWith(
expect.objectContaining({
program: '/usr/bin/osascript',
args: [
'-l',
'JavaScript',
'-e',
expect.stringContaining('runningApplicationsWithBundleIdentifier'),
'/Applications/Orca Test.app'
],
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')
})
})
53 changes: 53 additions & 0 deletions src/main/macos-update-running-instances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import path from 'node:path'
import { runProcess } from '../shared/child-process/run-process'

const RUNNING_INSTANCES_SCRIPT = `function run(argv) {
ObjC.import('AppKit');
const bundle = $.NSBundle.bundleWithPath(argv[0]);
const identifier = ObjC.unwrap(bundle.bundleIdentifier);
if (typeof identifier !== 'string' || !identifier) throw new Error('Missing bundle identifier');
const target = $.NSURL.fileURLWithPath(argv[0]).URLByStandardizingPath;
const apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(identifier);
const pids = [];
for (let i = 0; i < apps.count; i++) {
const app = apps.objectAtIndex(i);
if (app.bundleURL && app.bundleURL.URLByStandardizingPath.isEqual(target)) {
pids.push(Number(app.processIdentifier));
}
}
return JSON.stringify(pids);
}`

/** 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 bundlePath = path.dirname(path.dirname(path.dirname(executable)))
// Match ShipIt's registry query; run-as-node workers share the executable but do not block it.
const result = await runProcess({
program: '/usr/bin/osascript',
args: ['-l', 'JavaScript', '-e', RUNNING_INSTANCES_SCRIPT, bundlePath],
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, currentPid)
}

export function parseMacUpdateRunningInstances(listing: string, currentPid: number): number[] {
const pids: unknown = JSON.parse(listing)
if (
!Array.isArray(pids) ||
!pids.every((pid: unknown) => typeof pid === 'number' && Number.isSafeInteger(pid) && pid > 0)
) {
throw new Error('Invalid macOS application listing')
}
return pids.filter((pid: number) => pid !== currentPid)
}
4 changes: 4 additions & 0 deletions src/main/startup/desktop-startup-ordering.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ describe('startup ordering', () => {
expect(beforeQuitStart).toBeGreaterThanOrEqual(0)
expect(willQuitStart).toBeGreaterThan(beforeQuitStart)
expect(windowAllClosedStart).toBeGreaterThan(willQuitStart)
expect(beforeQuit.indexOf('event.defaultPrevented')).toBeGreaterThanOrEqual(0)
expect(beforeQuit.indexOf('event.defaultPrevented')).toBeLessThan(
beforeQuit.indexOf('state.isQuitting = true')
)
expect(beforeQuit).not.toContain('unsubscribeSystemResumeBroadcast')
expect(commitIndex).toBeGreaterThanOrEqual(0)
expect(disposeIndex).toBeGreaterThan(commitIndex)
Expand Down
Loading
Loading