test: remove low-value telemetry and updater test variants (#43274)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-16 14:13:13 -08:00
committed by GitHub
co-authored by OrcaWin
parent c5733d7367
commit fc0e3fbebe
9 changed files with 4 additions and 1127 deletions
@@ -2923,7 +2923,6 @@
"src/main/startup/login-shell-environment.test.ts": 103,
"src/main/startup/main-process-quit-pending-writer.test.ts": 328,
"src/main/startup/main-process-quit-update-veto.test.ts": 1714,
"src/main/startup/main-process-ready-activation-failure.test.ts": 313,
"src/main/startup/main-process-ready-persistence-cleanup.test.ts": 164,
"src/main/startup/profile-state-recovery-preflight.test.ts": 696,
"src/main/startup/profile-state-save-delay.test.ts": 45,
@@ -2948,7 +2947,6 @@
"src/main/telemetry/client-lifecycle.test.ts": 206,
"src/main/telemetry/consent.test.ts": 48,
"src/main/telemetry/plugin-install-telemetry.test.ts": 282,
"src/main/telemetry/wsl-usage-reporter.test.ts": 407,
"src/main/pty/history/terminal-history-gc-fs-call-count.test.ts": 157,
"src/main/pty/history/terminal-history-gc.test.ts": 824,
"src/main/pty/history/terminal-history-tombstone-retry.test.ts": 715,
@@ -2975,7 +2973,6 @@
"src/main/updater/updater.check-preflight.test.ts": 2878,
"src/main/updater/updater.check-settlement.test.ts": 2439,
"src/main/updater/updater.headless-serve-install.test.ts": 1744,
"src/main/updater/updater.install-failure-cause.test.ts": 1595,
"src/main/updater/updater.linux-externally-managed.test.ts": 1056,
"src/main/updater/mac-install/updater.mac-install.test.ts": 879,
"src/main/updater/updater.prerelease-fallback.test.ts": 2731,
@@ -1,118 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { MainProcessRuntimeLaunchOptions } from './runtime-startup/main-process-runtime-launch'
const phases = vi.hoisted(() => ({
foundation: vi.fn<() => Promise<void>>(),
runtimeServices: vi.fn<() => Promise<void>>(),
menu: vi.fn<() => Promise<void>>(),
launch: vi.fn<(options: MainProcessRuntimeLaunchOptions) => Promise<void>>()
}))
vi.mock('./main-process-ready-foundation', () => ({
initializeReadyFoundation: phases.foundation
}))
vi.mock('./main-process-ready-runtime', () => ({
initializeReadyRuntimeServices: phases.runtimeServices
}))
vi.mock('./main-window/main-process-i18n-menu', () => ({
initializeMainProcessI18nAndMenu: phases.menu
}))
vi.mock('./runtime-startup/main-process-runtime-launch', () => ({
initializeMainProcessRuntimeLaunch: phases.launch
}))
const { initializeMainProcessReady } = await import('./main-process-ready')
const { mainProcessState: state } = await import('./main-process-state')
const { createServeDesktopActivationGate } = await import('./serve-launch/serve-desktop-activation')
const activateWindow = vi.fn()
const launchOptions: MainProcessRuntimeLaunchOptions = {
openMainWindow: vi.fn<MainProcessRuntimeLaunchOptions['openMainWindow']>(),
handleMacAppActivation: vi.fn()
}
describe('desktop activation after ready-phase failures', () => {
beforeEach(() => {
vi.resetAllMocks()
phases.foundation.mockResolvedValue(undefined)
phases.runtimeServices.mockResolvedValue(undefined)
phases.menu.mockResolvedValue(undefined)
phases.launch.mockResolvedValue(undefined)
state.isServeMode = false
state.desktopActivationGate = createServeDesktopActivationGate({
initialState: 'initializing',
activateWindow
})
})
afterEach(() => {
state.desktopActivationGate = null
state.isServeMode = false
})
it.each(['foundation', 'runtimeServices'] as const)(
'disables desktop activation after %s fails',
async (phase) => {
const error = new Error(`${phase} failed`)
phases[phase].mockRejectedValueOnce(error)
state.desktopActivationGate?.requestActivation()
await expect(initializeMainProcessReady(launchOptions)).rejects.toBe(error)
expect(activateWindow).not.toHaveBeenCalled()
expect(state.desktopActivationGate).toBeNull()
expect(phases.launch).not.toHaveBeenCalled()
state.desktopActivationGate?.requestActivation()
expect(activateWindow).not.toHaveBeenCalled()
}
)
it('keeps activations held when menu failure leaves window creation still pending', async () => {
const error = new Error('menu failed')
let finishLaunch = (): void => {
throw new Error('launch has not started')
}
phases.menu.mockRejectedValueOnce(error)
phases.launch.mockImplementationOnce(
(options) =>
new Promise<void>((resolve) => {
finishLaunch = () => {
options.openMainWindow()
resolve()
}
})
)
state.desktopActivationGate?.requestActivation()
const ready = initializeMainProcessReady(launchOptions)
const rejected = expect(ready).rejects.toBe(error)
await vi.waitFor(() => expect(phases.launch).toHaveBeenCalledOnce())
expect(state.desktopActivationGate?.getState()).toBe('initializing')
expect(activateWindow).not.toHaveBeenCalled()
expect(launchOptions.openMainWindow).not.toHaveBeenCalled()
finishLaunch()
expect(launchOptions.openMainWindow).toHaveBeenCalledTimes(1)
expect(state.desktopActivationGate?.getState()).toBe('ready')
expect(activateWindow).toHaveBeenCalledTimes(1)
await rejected
expect(state.desktopActivationGate).toBeNull()
})
it('does not replay pending activations when window creation throws', async () => {
const error = new Error('window creation failed')
vi.mocked(launchOptions.openMainWindow).mockImplementationOnce(() => {
throw error
})
phases.launch.mockImplementationOnce(async (options) => {
options.openMainWindow()
})
state.desktopActivationGate?.requestActivation()
await expect(initializeMainProcessReady(launchOptions)).rejects.toBe(error)
expect(state.desktopActivationGate).toBeNull()
expect(activateWindow).not.toHaveBeenCalled()
expect(launchOptions.openMainWindow).toHaveBeenCalledTimes(1)
})
})
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { persistBannerAcknowledgeWithoutEmitting, setOptIn } from './client'
import {
BASE_COMMON,
cleanupTelemetryClientTest,
setupTelemetryClientTest,
type MockPostHog,
@@ -21,26 +20,6 @@ describe('setOptIn()', () => {
cleanupTelemetryClientTest(state.envStash)
})
// Capture enqueues asynchronously; opt-out evidence must reach the SDK before optOut discards it.
it('waits for telemetry_opted_out to enqueue before posthog.optOut()', async () => {
const order: string[] = []
mock.capture.mockImplementation((message: { event?: string; uuid?: string }) => {
order.push('capture called')
queueMicrotask(() => {
order.push('sdk enqueue')
mock.emitForTests('capture', {
event: message.event,
uuid: message.uuid
})
})
})
mock.optOut.mockImplementation(async () => {
order.push('optOut')
})
await setOptIn('settings', false)
expect(order).toEqual(['capture called', 'sdk enqueue', 'optOut'])
})
it('keeps the SDK opted out and sends no consent events while DO_NOT_TRACK overrides', async () => {
process.env.DO_NOT_TRACK = '1'
@@ -51,71 +30,4 @@ describe('setOptIn()', () => {
expect(mock.optIn).not.toHaveBeenCalled()
expect(mock.capture).not.toHaveBeenCalled()
})
it('fires app_opened and telemetry_opted_in after the SDK enables settings opt-in', async () => {
state.settings.telemetry!.optedIn = false
const order: string[] = []
mock.optIn.mockImplementation(async () => order.push('optIn'))
mock.capture.mockImplementation((message: { event?: string }) => {
order.push(`capture:${message.event}`)
})
await setOptIn('settings', true)
expect(order).toEqual(['optIn', 'capture:app_opened', 'capture:telemetry_opted_in'])
expect(state.store.updateSettings).toHaveBeenCalledWith(
{ telemetry: expect.objectContaining({ optedIn: true }) },
{ notifyListeners: true }
)
})
it('fires app_opened once after pending-banner opt-in enables the SDK', async () => {
state.settings.telemetry = {
optedIn: null,
installId: BASE_COMMON.install_id,
existedBeforeTelemetryRelease: true
}
const order: string[] = []
mock.optIn.mockImplementation(async () => order.push('optIn'))
mock.capture.mockImplementation((message: { event?: string }) => {
order.push(`capture:${message.event}`)
})
await setOptIn('settings', true)
expect(order).toEqual(['optIn', 'capture:app_opened', 'capture:telemetry_opted_in'])
})
})
describe('persistBannerAcknowledgeWithoutEmitting()', () => {
let state: TelemetryClientTestState
let mock: MockPostHog
beforeEach(() => {
state = setupTelemetryClientTest({
optedIn: null,
installId: BASE_COMMON.install_id,
existedBeforeTelemetryRelease: true
})
mock = state.mock
})
afterEach(() => {
cleanupTelemetryClientTest(state.envStash)
})
it('fires app_opened after re-enabling the SDK and does not emit telemetry_opted_in', async () => {
const order: string[] = []
mock.optIn.mockImplementation(async () => order.push('optIn'))
mock.capture.mockImplementation((message: { event?: string }) => {
order.push(`capture:${message.event}`)
})
await persistBannerAcknowledgeWithoutEmitting()
expect(order).toEqual(['optIn', 'capture:app_opened'])
expect(state.settings.telemetry?.optedIn).toBe(true)
expect(state.store.updateSettings).toHaveBeenCalledWith(
{ telemetry: expect.objectContaining({ optedIn: true }) },
{ notifyListeners: true }
)
})
})
@@ -33,22 +33,6 @@ describe('prompt event sampling', () => {
vi.useRealTimers()
})
it('uses the same sampling boundary for hooks and renderer prompt sources', () => {
const random = vi.spyOn(Math, 'random')
for (const launch_source of ['unknown', 'sidebar', 'diff_notes_send'] as const) {
random.mockReturnValue(0.01)
expect(track('agent_prompt_sent', { ...prompt, launch_source })).toBe(false)
random.mockReturnValue(0.0099)
expect(track('agent_prompt_sent', { ...prompt, launch_source })).toBe(true)
}
expect(state.mock.capture).toHaveBeenCalledTimes(3)
for (const [message] of state.mock.capture.mock.calls) {
expect(message.properties.sample_rate).toBe(0.01)
expect(message.properties.$process_person_profile).toBe(false)
}
})
it('still enforces consent and rejects raw prompt text on selected events', () => {
vi.spyOn(Math, 'random').mockReturnValue(0)
state.settings.telemetry!.optedIn = false
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { eventSchemas } from '../../shared/telemetry/telemetry-event-registry'
import { pluginTelemetryCatalog, trackPluginInstalled } from './plugin-install-telemetry'
import { trackPluginInstalled } from './plugin-install-telemetry'
const telemetry = vi.hoisted(() => ({ track: vi.fn() }))
vi.mock('./client', () => telemetry)
@@ -10,18 +9,6 @@ beforeEach(() => {
})
describe('plugin install telemetry', () => {
it('names only the official and community catalogs', () => {
expect(pluginTelemetryCatalog('https://github.com/stablyai/orca-plugins.git')).toBe('official')
expect(pluginTelemetryCatalog('git@github.com:stablyai/orca-plugins.git')).toBe('official')
expect(pluginTelemetryCatalog('https://github.com/stablyai/orca-community-plugins')).toBe(
'community'
)
expect(pluginTelemetryCatalog('https://github.com/acme/private-plugins.git')).toBeNull()
expect(
pluginTelemetryCatalog('https://gitlab.example.com/stablyai/orca-plugins.git')
).toBeNull()
})
it('sends nothing for a private catalog install', () => {
trackPluginInstalled({
marketplaceUrl: 'https://github.com/acme/private-plugins.git',
@@ -32,40 +19,4 @@ describe('plugin install telemetry', () => {
})
expect(telemetry.track).not.toHaveBeenCalled()
})
it('never lets a telemetry failure escape', () => {
telemetry.track.mockImplementation(() => {
throw new Error('boom')
})
expect(() =>
trackPluginInstalled({
marketplaceUrl: 'https://github.com/stablyai/orca-plugins.git',
plugin_key: 'acme.notes',
version: '1.0.0',
kind: 'install',
trigger: 'catalog'
})
).not.toThrow()
expect(telemetry.track).toHaveBeenCalledOnce()
})
it('schemas reject anything but a plugin key and enums', () => {
const valid = {
plugin_key: 'acme.notes',
version: '1.2.0-beta.1',
catalog: 'official',
kind: 'install',
trigger: 'catalog'
}
expect(eventSchemas.plugin_installed.safeParse(valid).success).toBe(true)
for (const bad of [
{ ...valid, plugin_key: '/Users/me/dev-plugin' },
{ ...valid, plugin_key: 'notes' },
{ ...valid, catalog: 'dev' },
{ ...valid, version: '1.0.0 /tmp' },
{ ...valid, path: '/Users/me' }
]) {
expect(eventSchemas.plugin_installed.safeParse(bad).success).toBe(false)
}
})
})
@@ -1,202 +0,0 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const trackMock = vi.hoisted(() => vi.fn(() => true))
vi.mock('./client', () => ({
track: trackMock,
isTelemetryEnabled: () => true
}))
import {
collectWslProjects,
countWindowsDriveReposWithWslWorktrees,
WSL_USAGE_SNAPSHOT_INTERVAL_MS,
WslUsageReporter,
type WslUsageStore
} from './wsl-usage-reporter'
import type { WslUsageSnapshotInput } from './wsl-usage-snapshot'
const input: WslUsageSnapshotInput = {
registeredDistroCount: 1,
userDistros: [{ version: 2, state: 'running' }],
wslPackageVersion: '2.4.13',
wslAvailableCached: true,
projects: [],
windowsDriveReposWithWslWorktrees: 0,
wslHostsGateOpen: false
}
const store: WslUsageStore = {
getRepos: () => [],
getProjects: () => [],
getSettings: () => ({})
}
describe('WslUsageReporter', () => {
let dir: string
let now: number
const gather = vi.fn(async () => input)
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'wsl-usage-'))
now = 1_000_000_000_000
trackMock.mockClear()
trackMock.mockReturnValue(true)
gather.mockClear()
})
afterEach(() => rmSync(dir, { recursive: true, force: true }))
function reporter(overrides: Partial<ConstructorParameters<typeof WslUsageReporter>[2]> = {}) {
return new WslUsageReporter(store, dir, {
platform: 'win32',
now: () => now,
telemetryEnabled: () => true,
gather,
...overrides
})
}
it('sends once, then not again within a day, across restarts', async () => {
expect(await reporter().reportIfDue()).toBe(true)
expect(trackMock).toHaveBeenCalledWith('wsl_usage_snapshot', expect.any(Object))
const stamp: unknown = JSON.parse(readFileSync(join(dir, 'wsl-usage-telemetry.json'), 'utf8'))
expect(stamp).toEqual({ lastSentAt: now })
now += WSL_USAGE_SNAPSHOT_INTERVAL_MS - 1
expect(await reporter().reportIfDue()).toBe(false)
expect(gather).toHaveBeenCalledTimes(1)
now += 1
expect(await reporter().reportIfDue()).toBe(true)
expect(gather).toHaveBeenCalledTimes(2)
})
it('does not regather an hour after a failed gather', async () => {
gather.mockRejectedValueOnce(new Error('store unavailable'))
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const instance = reporter()
expect(await instance.reportIfDue()).toBe(false)
now += 60 * 60 * 1000
expect(await instance.reportIfDue()).toBe(false)
expect(gather).toHaveBeenCalledTimes(1)
warn.mockRestore()
})
it('treats a stamp from the future as due', async () => {
writeFileSync(join(dir, 'wsl-usage-telemetry.json'), JSON.stringify({ lastSentAt: now + 1e9 }))
expect(await reporter().reportIfDue()).toBe(true)
})
it('stamps a dropped send so the gather is not repaid hourly', async () => {
trackMock.mockReturnValue(false)
const instance = reporter()
expect(await instance.reportIfDue()).toBe(false)
now += 60 * 60 * 1000
expect(await instance.reportIfDue()).toBe(false)
expect(gather).toHaveBeenCalledTimes(1)
})
it('treats a corrupt stamp as never sent', async () => {
writeFileSync(join(dir, 'wsl-usage-telemetry.json'), 'not json')
expect(await reporter().reportIfDue()).toBe(true)
})
})
describe('collectWslProjects', () => {
const wslStore: WslUsageStore = {
getRepos: () => [
{
id: 'a',
path: '\\\\wsl$\\Ubuntu\\home\\me\\a',
displayName: 'a',
badgeColor: '',
addedAt: 0
},
{
id: 'c',
path: '/mnt/d/src/c',
displayName: 'c',
badgeColor: '',
addedAt: 0,
kind: 'folder',
executionHostId: 'runtime:env-1'
}
],
getProjects: () => [],
getSettings: () => ({})
}
it('skips WSL-host projects while the gate is closed, without reading environments', () => {
const readHostDistros = vi.fn(() => new Map([['env-1', 'Debian']]))
expect(collectWslProjects(wslStore, false, readHostDistros, 'Ubuntu')).toEqual([
{ location: 'distro_fs', kind: 'git', distro: 'Ubuntu' }
])
expect(readHostDistros).not.toHaveBeenCalled()
})
it('counts a WSL-host project on a Windows drive when the gate is open', () => {
const projects = collectWslProjects(wslStore, true, () => new Map([['env-1', 'Debian']]), null)
expect(projects).toContainEqual({ location: 'windows_drive', kind: 'folder', distro: 'Debian' })
})
})
describe('countWindowsDriveReposWithWslWorktrees', () => {
let root: string
const originalPlatform = process.platform
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'orca-wsl-usage-links-'))
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
})
afterEach(() => {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
rmSync(root, { recursive: true, force: true })
})
function repoWithLinks(id: string, links: string[]) {
const path = join(root, id)
links.forEach((link, index) => {
mkdirSync(join(path, '.git', 'worktrees', `w${index}`), { recursive: true })
writeFileSync(join(path, '.git', 'worktrees', `w${index}`, 'gitdir'), `${link}\n`)
})
mkdirSync(join(path, '.git'), { recursive: true })
return { id, path, displayName: id, badgeColor: '', addedAt: 0 }
}
it('counts Windows-drive WSL repos with a worktree WSL Git made, reading files only', async () => {
const repos = [
repoWithLinks('mixed', ['C:/src/mixed-a/.git', '/mnt/c/src/mixed-b/.git']),
repoWithLinks('native', ['C:/src/native-a/.git']),
repoWithLinks('none', []),
repoWithLinks('share', ['//server/share/app-feature/.git'])
]
const countStore: WslUsageStore = {
getRepos: () => repos,
getProjects: () => [
{
id: 'p',
displayName: 'p',
badgeColor: '',
sourceRepoIds: repos.map((repo) => repo.id),
createdAt: 0,
updatedAt: 0,
localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' }
}
],
getSettings: () => ({})
}
await expect(countWindowsDriveReposWithWslWorktrees(countStore)).resolves.toBe(1)
})
it('ignores repos that run on Windows', async () => {
const repos = [repoWithLinks('mixed', ['/mnt/c/src/mixed-b/.git'])]
await expect(
countWindowsDriveReposWithWslWorktrees({
getRepos: () => repos,
getProjects: () => [],
getSettings: () => ({ localWindowsRuntimeDefault: { kind: 'windows-host' } })
})
).resolves.toBe(0)
})
})
-71
View File
@@ -1,5 +1,4 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { UpdateStatus } from '../../shared/updater/update-status-types'
import type { registerAutoUpdaterHandlers } from './updater-events'
const {
@@ -178,43 +177,6 @@ describe('registerAutoUpdaterHandlers linux package artifact tracking', () => {
expect(getArtifact()).toBeNull()
})
it('keeps manual-install recovery when a later check finds no newer release', async () => {
const { emit, context, getArtifact } = await register()
emit('update-downloaded', downloadedEvent())
// Clear the initial download status so only the recheck can satisfy the assertion.
vi.mocked(context.sendStatus).mockClear()
emit('update-not-available')
expect(getArtifact()).toEqual(expect.objectContaining({ version: '1.0.61' }))
expect(context.sendStatus).toHaveBeenLastCalledWith({
state: 'error',
message: 'Quit Orca before running the system package install command.',
messageCode: 'linuxPackageManualInstall',
recovery: {
kind: 'linux-package-install',
packageType: 'deb',
reason: 'manual-install-required',
version: '1.0.61'
}
})
})
it('clears recovery when a newer update takes over before no-update settles', async () => {
const { emit, context, getArtifact } = await register()
emit('update-downloaded', downloadedEvent())
emit('update-available', { version: '1.0.62' })
emit('update-not-available')
expect(getArtifact()).toBeNull()
expect(context.sendStatus).toHaveBeenLastCalledWith({
state: 'not-available',
userInitiated: undefined
})
})
it.each([
['idle', { state: 'idle' }],
['not-available', { state: 'not-available' }],
@@ -247,37 +209,4 @@ describe('registerAutoUpdaterHandlers linux package artifact tracking', () => {
expect(getArtifact()).toBeNull()
expect(context.sendStatus).not.toHaveBeenCalled()
})
// Management can change after download; retained manual-install recovery must survive the recheck.
it.each([false, true])(
'keeps manual-install recovery through a same-version recheck (externallyManaged=%s)',
async (externallyManaged) => {
isExternallyManagedLinuxInstallMock.mockReturnValue(externallyManaged)
let status: UpdateStatus = { state: 'downloading', percent: 100, version: '1.0.61' }
const { emit, context, getArtifact } = await register({
getCurrentStatus: vi.fn(() => status)
})
emit('update-downloaded', downloadedEvent())
// Clear the download status so waitFor must observe a new recheck result.
vi.mocked(context.sendStatus).mockClear()
status = { state: 'checking' }
emit('update-available', { version: '1.0.61' })
expect(getArtifact()).toEqual(expect.objectContaining({ version: '1.0.61', path: DEB_PATH }))
await vi.waitFor(() =>
expect(context.sendStatus).toHaveBeenLastCalledWith({
state: 'error',
message: 'Quit Orca before running the system package install command.',
messageCode: 'linuxPackageManualInstall',
recovery: {
kind: 'linux-package-install',
packageType: 'deb',
reason: 'manual-install-required',
version: '1.0.61'
}
})
)
}
)
})
@@ -3,16 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { loadUpdaterModule, warmUpdaterModule } from './testing/updater-test-module-loader'
import { updaterMainWindow } from './testing/updater-test-main-window'
const {
appMock,
autoUpdaterMock,
fetchNewerReleaseTagsMock,
chooseLocalBuildMock,
closeLocalBuildFeedMock,
moduleFactories,
resetUpdaterMocks
} = await vi.hoisted(async () =>
(await import('./testing/updater-test-harness')).createUpdaterMocks()
const { appMock, autoUpdaterMock, moduleFactories, resetUpdaterMocks } = await vi.hoisted(
async () => (await import('./testing/updater-test-harness')).createUpdaterMocks()
)
vi.mock('electron', () => moduleFactories.electron())
@@ -36,14 +28,12 @@ vi.mock('./releases/updater-release-readiness', async (importOriginal) => ({
vi.mock('../local-builds/local-build-switch', () => moduleFactories.localBuildSwitch())
vi.mock('../local-builds/local-build-feed-server', () => moduleFactories.localBuildFeedServer())
// Matches updater/updater-state.ts.
const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000
warmUpdaterModule()
describe('updater', () => {
beforeEach(() => {
resetUpdaterMocks()
vi.useFakeTimers({ now: 0 })
})
// Signed Windows builds verify publisherName; refuse unsigned dev jumps before downloading.
@@ -71,328 +61,4 @@ describe('updater', () => {
platformSpy.mockRestore()
}
})
it.runIf(process.platform === 'darwin')(
'allows a validated local build to downgrade through the normal updater lifecycle',
async () => {
chooseLocalBuildMock.mockResolvedValue({
version: '0.9.0-local.1',
manifestContent: 'version: 0.9.0-local.1',
artifacts: new Map()
})
autoUpdaterMock.checkForUpdates.mockImplementation(() => {
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-available', { version: '0.9.0-local.1' })
return Promise.resolve(undefined)
})
const send = vi.fn()
const { setupAutoUpdater, checkForUpdatesFromMenu } = await loadUpdaterModule()
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
checkForUpdatesFromMenu({ localBuild: true })
await vi.waitFor(() => {
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1)
})
expect(autoUpdaterMock.allowDowngrade).toBe(true)
expect(autoUpdaterMock.disableDifferentialDownload).toBe(true)
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'http://127.0.0.1:1234/token/'
})
await vi.waitFor(() => {
expect(send).toHaveBeenCalledWith(
'updater:status',
expect.objectContaining({
state: 'available',
version: '0.9.0-local.1',
source: 'local'
})
)
})
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'http://127.0.0.1:1234/token/'
})
expect(autoUpdaterMock.allowDowngrade).toBe(true)
autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined)
checkForUpdatesFromMenu()
await vi.waitFor(() => {
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2)
})
expect(closeLocalBuildFeedMock).toHaveBeenCalledTimes(1)
expect(autoUpdaterMock.allowDowngrade).toBe(false)
expect(autoUpdaterMock.disableDifferentialDownload).toBe(false)
}
)
it.runIf(process.platform === 'darwin')(
'restores ordinary release checks after a local build is unavailable',
async () => {
chooseLocalBuildMock.mockResolvedValue({
version: '0.9.0-local.1',
manifestContent: 'version: 0.9.0-local.1',
artifacts: new Map()
})
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => {
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-not-available')
return Promise.resolve(undefined)
})
const send = vi.fn()
const { setupAutoUpdater, checkForUpdates, checkForUpdatesFromMenu } =
await loadUpdaterModule()
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
checkForUpdatesFromMenu({ localBuild: true })
await vi.waitFor(() => {
expect(closeLocalBuildFeedMock).toHaveBeenCalledTimes(1)
})
expect(send).toHaveBeenCalledWith('updater:status', {
state: 'not-available',
userInitiated: true,
source: 'local'
})
expect(autoUpdaterMock.allowDowngrade).toBe(false)
expect(autoUpdaterMock.disableDifferentialDownload).toBe(false)
checkForUpdates()
await vi.waitFor(() => {
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2)
})
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'https://github.com/stablyai/orca/releases/download/v1.0.51'
})
}
)
it.runIf(process.platform === 'darwin')(
'restores ordinary release checks after a local updater failure',
async () => {
chooseLocalBuildMock.mockResolvedValue({
version: '0.9.0-local.1',
manifestContent: 'version: 0.9.0-local.1',
artifacts: new Map()
})
autoUpdaterMock.checkForUpdates.mockRejectedValueOnce(new Error('local feed failed'))
const send = vi.fn()
const { setupAutoUpdater, checkForUpdates, checkForUpdatesFromMenu } =
await loadUpdaterModule()
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
checkForUpdatesFromMenu({ localBuild: true })
await vi.waitFor(() => {
expect(send).toHaveBeenCalledWith('updater:status', {
state: 'error',
message: 'local feed failed',
userInitiated: true,
source: 'local'
})
})
expect(closeLocalBuildFeedMock).toHaveBeenCalledTimes(1)
expect(autoUpdaterMock.allowDowngrade).toBe(false)
expect(autoUpdaterMock.disableDifferentialDownload).toBe(false)
checkForUpdates()
await vi.waitFor(() => {
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2)
})
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'https://github.com/stablyai/orca/releases/download/v1.0.51'
})
}
)
it.runIf(process.platform === 'darwin')(
'keeps the automatic check chain alive across a local build session',
async () => {
vi.useFakeTimers()
chooseLocalBuildMock.mockResolvedValue({
version: '0.9.0-local.1',
manifestContent: 'version: 0.9.0-local.1',
artifacts: new Map()
})
autoUpdaterMock.checkForUpdates.mockImplementation(() => {
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-available', { version: '0.9.0-local.1' })
return Promise.resolve(undefined)
})
autoUpdaterMock.downloadUpdate.mockRejectedValue(new Error('local download failed'))
const send = vi.fn()
const { setupAutoUpdater, checkForUpdatesFromMenu, downloadUpdate } =
await loadUpdaterModule()
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
checkForUpdatesFromMenu({ localBuild: true })
await vi.advanceTimersByTimeAsync(0)
expect(send).toHaveBeenCalledWith(
'updater:status',
expect.objectContaining({ state: 'available', source: 'local' })
)
// This window observes only its owning module's attempts, excluding stale sibling timers.
autoUpdaterMock.checkForUpdates.mockReset().mockImplementation(() => {
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-not-available')
return Promise.resolve(undefined)
})
send.mockClear()
await vi.advanceTimersByTimeAsync(AUTO_UPDATE_CHECK_INTERVAL_MS)
expect(send).not.toHaveBeenCalledWith('updater:status', { state: 'not-available' })
downloadUpdate()
await vi.advanceTimersByTimeAsync(0)
expect(autoUpdaterMock.allowDowngrade).toBe(false)
send.mockClear()
await vi.advanceTimersByTimeAsync(AUTO_UPDATE_CHECK_INTERVAL_MS)
expect(send).toHaveBeenCalledWith('updater:status', { state: 'not-available' })
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'https://github.com/stablyai/orca/releases/download/v1.0.51'
})
}
)
it.runIf(process.platform === 'darwin')(
'restores release checks when an offered local build is dismissed',
async () => {
chooseLocalBuildMock.mockResolvedValue({
version: '0.9.0-local.1',
manifestContent: 'version: 0.9.0-local.1',
artifacts: new Map()
})
autoUpdaterMock.checkForUpdates.mockImplementation(() => {
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-available', { version: '0.9.0-local.1' })
return Promise.resolve(undefined)
})
const send = vi.fn()
const { setupAutoUpdater, checkForUpdates, checkForUpdatesFromMenu, dismissAvailableUpdate } =
await loadUpdaterModule()
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
checkForUpdatesFromMenu({ localBuild: true })
await vi.waitFor(() => {
expect(send).toHaveBeenCalledWith(
'updater:status',
expect.objectContaining({ state: 'available', source: 'local' })
)
})
dismissAvailableUpdate()
expect(closeLocalBuildFeedMock).toHaveBeenCalledTimes(1)
expect(autoUpdaterMock.allowDowngrade).toBe(false)
expect(autoUpdaterMock.disableDifferentialDownload).toBe(false)
expect(send).toHaveBeenCalledWith('updater:status', { state: 'idle' })
autoUpdaterMock.checkForUpdates.mockReset().mockResolvedValue(undefined)
checkForUpdates()
await vi.waitFor(() => {
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1)
})
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'https://github.com/stablyai/orca/releases/download/v1.0.51'
})
}
)
it.runIf(process.platform === 'darwin')(
'keeps the local feed in force when a dismiss lands during a local build download',
async () => {
chooseLocalBuildMock.mockResolvedValue({
version: '0.9.0-local.1',
manifestContent: 'version: 0.9.0-local.1',
artifacts: new Map()
})
autoUpdaterMock.checkForUpdates.mockImplementation(() => {
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-available', { version: '0.9.0-local.1' })
return Promise.resolve(undefined)
})
autoUpdaterMock.downloadUpdate.mockResolvedValue(undefined)
const send = vi.fn()
const { setupAutoUpdater, checkForUpdatesFromMenu, dismissAvailableUpdate, downloadUpdate } =
await loadUpdaterModule()
setupAutoUpdater(updaterMainWindow(send), {
getLastUpdateCheckAt: () => Date.now()
})
checkForUpdatesFromMenu({ localBuild: true })
await vi.waitFor(() => {
expect(send).toHaveBeenCalledWith(
'updater:status',
expect.objectContaining({ state: 'available', source: 'local' })
)
})
downloadUpdate()
dismissAvailableUpdate()
expect(closeLocalBuildFeedMock).not.toHaveBeenCalled()
expect(autoUpdaterMock.allowDowngrade).toBe(true)
expect(autoUpdaterMock.disableDifferentialDownload).toBe(true)
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'http://127.0.0.1:1234/token/'
})
}
)
it('keeps background retries on the stable channel after a perf publishing-window miss', async () => {
vi.useFakeTimers()
appMock.getVersion.mockReturnValue('1.4.120')
fetchNewerReleaseTagsMock
.mockResolvedValueOnce({ tags: [], state: 'not-ready' })
.mockResolvedValueOnce(['v1.4.121'])
autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined)
const sendMock = vi.fn()
const mainWindow = updaterMainWindow(sendMock)
const { setupAutoUpdater, checkForUpdatesFromMenu } = await loadUpdaterModule()
setupAutoUpdater(mainWindow, { getLastUpdateCheckAt: () => Date.now() })
checkForUpdatesFromMenu({ includePerfPrerelease: true })
await vi.waitFor(() => {
expect(sendMock).toHaveBeenCalledWith('updater:status', {
state: 'error',
message: "Couldn't reach the update server. Try again in a few minutes.",
messageCode: 'updateServerUnreachable',
userInitiated: true
})
})
await vi.advanceTimersByTimeAsync(60 * 60 * 1000)
await vi.waitFor(() => {
expect(fetchNewerReleaseTagsMock).toHaveBeenNthCalledWith(2, '1.4.120', 1, {
includePrerelease: false
})
expect(autoUpdaterMock.setFeedURL).toHaveBeenLastCalledWith({
provider: 'generic',
url: 'https://github.com/stablyai/orca/releases/download/v1.4.121'
})
})
})
})
@@ -1,242 +0,0 @@
import type { getReleaseDownloadUrl } from './releases/updater-release-readiness'
import os from 'node:os'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as TracerModule from '../observability/tracer'
import type * as UpdaterModule from './updater-service'
import { loadUpdaterModule, warmUpdaterModule } from './testing/updater-test-module-loader'
import { updaterMainWindow } from './testing/updater-test-main-window'
const {
appMock,
browserWindowMock,
nativeUpdaterMock,
autoUpdaterMock,
killAllPtyMock,
recordUpdaterLifecycleMock
} = vi.hoisted(() => {
const appEventHandlers = new Map<string, ((...args: unknown[]) => void)[]>()
const eventHandlers = new Map<string, ((...args: unknown[]) => void)[]>()
const appOn = vi.fn((event: string, handler: (...args: unknown[]) => void) => {
const handlers = appEventHandlers.get(event) ?? []
handlers.push(handler)
appEventHandlers.set(event, handlers)
return appMock
})
const appPrependListener = vi.fn((event: string, handler: (...args: unknown[]) => void) => {
const handlers = appEventHandlers.get(event) ?? []
handlers.unshift(handler)
appEventHandlers.set(event, handlers)
return appMock
})
const on = vi.fn((event: string, handler: (...args: unknown[]) => void) => {
const handlers = eventHandlers.get(event) ?? []
handlers.push(handler)
eventHandlers.set(event, handlers)
return autoUpdaterMock
})
const emit = (event: string, ...args: unknown[]) => {
for (const handler of eventHandlers.get(event) ?? []) {
handler(...args)
}
}
const reset = () => {
appEventHandlers.clear()
appOn.mockClear()
appPrependListener.mockClear()
eventHandlers.clear()
on.mockClear()
autoUpdaterMock.checkForUpdates.mockReset()
autoUpdaterMock.downloadUpdate.mockReset()
autoUpdaterMock.quitAndInstall.mockReset()
autoUpdaterMock.setFeedURL.mockClear()
}
const autoUpdaterMock = {
autoDownload: false,
autoInstallOnAppQuit: false,
on,
checkForUpdates: vi.fn(),
downloadUpdate: vi.fn(),
quitAndInstall: vi.fn(),
setFeedURL: vi.fn(),
emit,
reset
}
return {
appMock: {
isPackaged: true,
getVersion: vi.fn(() => '1.4.162'),
on: appOn,
prependListener: appPrependListener,
quit: vi.fn(),
exit: vi.fn()
},
browserWindowMock: { getAllWindows: vi.fn(() => []) },
nativeUpdaterMock: { on: vi.fn() },
autoUpdaterMock,
killAllPtyMock: vi.fn(),
recordUpdaterLifecycleMock: vi.fn()
}
})
vi.mock('electron', () => ({
app: appMock,
BrowserWindow: browserWindowMock,
autoUpdater: nativeUpdaterMock,
powerMonitor: { on: vi.fn() },
shell: { openExternal: vi.fn() },
net: { fetch: vi.fn() }
}))
vi.mock('electron-updater', () => ({ autoUpdater: autoUpdaterMock }))
vi.mock('./releases/updater-prerelease-feed', () => ({
fetchNewerReleaseTagsWithReadiness: vi
.fn()
.mockResolvedValue({ tags: ['v1.4.241'], state: 'ready' }),
getReleaseDownloadUrl: (tag: string) =>
`https://github.com/stablyai/orca/releases/download/${tag}`
}))
vi.mock('./releases/updater-release-readiness', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getReleaseDownloadUrl: (
await vi.importMock<{
getReleaseDownloadUrl: typeof getReleaseDownloadUrl
}>('./releases/updater-prerelease-feed')
).getReleaseDownloadUrl
}))
vi.mock('./electron-updater-loader', () => ({
loadElectronAutoUpdater: () => autoUpdaterMock
}))
vi.mock('../ipc/pty/kill-all', () => ({ killAllPty: killAllPtyMock }))
vi.mock('./releases/updater-changelog', () => ({
fetchChangelog: vi.fn().mockResolvedValue(null)
}))
vi.mock('./nudges/nudge-campaign', () => ({
fetchNudge: vi.fn().mockResolvedValue(null),
shouldApplyNudge: vi.fn().mockReturnValue(false)
}))
vi.mock('./updater-lifecycle-diagnostics', () => ({
recordUpdaterLifecycle: recordUpdaterLifecycleMock
}))
vi.mock('./linux-package/linux-update-package-type', () => ({
getLinuxPackageType: () => 'non-root',
getLinuxRootPackageType: () => null,
isExternallyManagedLinuxInstall: () => false
}))
type CapturedSpan = {
readonly name: string
readonly exit: { readonly _tag: string; readonly cause?: string }
}
const originalPlatform = process.platform
let spans: CapturedSpan[]
let tracer: typeof TracerModule | null = null
function capturingSink(): TracerModule.TracerSink {
return {
push(record) {
spans.push(record as CapturedSpan)
},
flush() {
/* no-op */
},
close() {
/* no-op */
}
}
}
async function reachDownloaded(): Promise<typeof UpdaterModule> {
const mainWindow = updaterMainWindow(vi.fn())
autoUpdaterMock.checkForUpdates.mockResolvedValue(undefined)
// Install the sink on the fresh tracer instance the updater will import.
tracer = await import('../observability/tracer')
tracer.setActiveSink(capturingSink())
const updater = await loadUpdaterModule()
updater.setupAutoUpdater(mainWindow)
await vi.advanceTimersByTimeAsync(0)
await vi.waitFor(() => {
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1)
})
autoUpdaterMock.emit('checking-for-update')
autoUpdaterMock.emit('update-available', { version: '1.4.163' })
await vi.advanceTimersByTimeAsync(0)
autoUpdaterMock.downloadUpdate.mockResolvedValue([])
updater.downloadUpdate()
autoUpdaterMock.emit('update-downloaded', { version: '1.4.163' })
expect(updater.getUpdateStatus().state).toBe('downloaded')
return updater
}
warmUpdaterModule()
// DebUpdater can emit install errors synchronously; preserve their cause through recovery.
describe('quitAndInstall failure carries the updater cause', () => {
beforeEach(() => {
vi.resetModules()
autoUpdaterMock.reset()
nativeUpdaterMock.on.mockReset()
browserWindowMock.getAllWindows.mockReset()
browserWindowMock.getAllWindows.mockReturnValue([])
appMock.getVersion.mockReset()
appMock.getVersion.mockReturnValue('1.4.162')
appMock.quit.mockReset()
appMock.isPackaged = true
killAllPtyMock.mockReset()
recordUpdaterLifecycleMock.mockReset()
Object.defineProperty(process, 'platform', {
value: 'linux',
configurable: true
})
vi.useFakeTimers()
spans = []
})
afterEach(() => {
vi.clearAllTimers()
vi.useRealTimers()
Object.defineProperty(process, 'platform', {
value: originalPlatform,
configurable: true
})
tracer?._resetTracerForTests()
tracer = null
})
it('redacts the cause the same way the retained-package card does', async () => {
const { quitAndInstall, getUpdateStatus } = await reachDownloaded()
const home = os.homedir()
const escape = String.fromCharCode(27)
autoUpdaterMock.quitAndInstall.mockImplementation(() => {
autoUpdaterMock.emit(
'error',
new Error(`${escape}[31mdpkg -i '${home}/.cache/orca-updater/pending/orca.deb'${escape}[0m`)
)
})
quitAndInstall()
await vi.advanceTimersByTimeAsync(100)
await vi.waitFor(() => {
expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1)
})
const status = getUpdateStatus()
const message = status.state === 'error' ? status.message : ''
expect(message).not.toContain(home)
expect(message).not.toContain(escape)
expect(message).toContain("<home>/.cache/orca-updater/pending/orca.deb'")
})
})