Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
55 changes: 55 additions & 0 deletions config/packaged-runtime-node-modules.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const requireFromProject = createRequire(join(projectDir, 'package.json'))
const PACKAGED_RUNTIME_PACKAGE_ROOTS = [
'@electron-toolkit/utils',
'@linear/sdk',
'@parcel/watcher',
'electron-updater',
'node-pty',
'posthog-node',
Expand All @@ -24,6 +25,11 @@ const NODE_PTY_PREBUILD_PREFIX_BY_PLATFORM = {
linux: 'linux-',
win32: 'win32-'
}
const PARCEL_WATCHER_PLATFORM_PREFIX_BY_PLATFORM = {
darwin: 'watcher-darwin',
linux: 'watcher-linux',
win32: 'watcher-win32'
}
const TYPE_DECLARATION_ARTIFACT_RE = /\.d\.(?:c|m)?ts(?:\.map)?$/
const VERSIONED_ONNXRUNTIME_DYLIB_RE = /^libonnxruntime\.\d[\d.]*\.dylib$/

Expand Down Expand Up @@ -99,6 +105,26 @@ function collectPackagedRuntimePackages() {
visit(packageName)
}

// Why: @parcel/watcher loads its native .node addon from a platform-specific
// optionalDependency (e.g. @parcel/watcher-linux-x64-glibc) that the
// dependencies graph above never reaches. Include the ones installed for the
// build's supported architectures; afterPack pruning trims non-target
// platforms. Without this the packaged main bundle's import of
// '@parcel/watcher' resolves at runtime but throws loading its binary.
const parcelWatcherDir = packages.get('@parcel/watcher')
if (parcelWatcherDir) {
const parcelWatcherPackage = JSON.parse(
readFileSync(join(parcelWatcherDir, 'package.json'), 'utf8')
)
for (const optionalName of Object.keys(parcelWatcherPackage.optionalDependencies ?? {})) {
try {
visit(optionalName)
} catch {
// Optional platform subpackage is not installed for this build; skip it.
}
}
}

return [...packages.entries()].sort(([left], [right]) => left.localeCompare(right))
}

Expand Down Expand Up @@ -184,6 +210,33 @@ function prunePackagedNodePty(resourcesDir, electronPlatformName) {
}
}

function prunePackagedParcelWatcher(resourcesDir, electronPlatformName) {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
if (!existsSync(parcelDir)) {
return
}

// Why: we package every installed @parcel/watcher-<platform> optional
// subpackage (supportedArchitectures fetches all), but each build only needs
// its own platform's binary. Keep the core package and the matching platform
// subpackages; drop the rest so a Linux serve doesn't ship macOS/Windows .node.
const keepPrefix = PARCEL_WATCHER_PLATFORM_PREFIX_BY_PLATFORM[electronPlatformName]
for (const entry of readdirSync(parcelDir, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === 'watcher') {
continue
}
// Why: only ever prune the watcher's own platform subpackages. Guards against
// nuking an unrelated @parcel/* runtime dep if one is added to the roots later.
if (!entry.name.startsWith('watcher-')) {
continue
}
if (keepPrefix && entry.name.startsWith(keepPrefix)) {
continue
}
rmSync(join(parcelDir, entry.name), { recursive: true, force: true })
}
}

function prunePackagedRuntimeTypeDeclarations(resourcesDir) {
const nodeModulesDir = join(resourcesDir, 'node_modules')
if (!existsSync(nodeModulesDir)) {
Expand Down Expand Up @@ -225,6 +278,7 @@ function prunePackagedZodSources(resourcesDir) {

function prunePackagedRuntimeNodeModules(resourcesDir, electronPlatformName) {
prunePackagedNodePty(resourcesDir, electronPlatformName)
prunePackagedParcelWatcher(resourcesDir, electronPlatformName)
prunePackagedRuntimeTypeDeclarations(resourcesDir)
prunePackagedSherpaOnnx(resourcesDir, electronPlatformName)
prunePackagedZodSources(resourcesDir)
Expand All @@ -248,6 +302,7 @@ module.exports = {
isPackagedExternalSpecifier,
packageNameFromSpecifier,
prunePackagedNodePty,
prunePackagedParcelWatcher,
prunePackagedRuntimeNodeModules,
prunePackagedSherpaOnnx,
prunePackagedRuntimeTypeDeclarations,
Expand Down
61 changes: 61 additions & 0 deletions config/scripts/electron-builder-config.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ const require = createRequire(import.meta.url)
const electronBuilderConfig = require('../electron-builder.config.cjs')
const electronBuilderNativeRebuild = require('./electron-builder-native-rebuild.cjs')
const {
createPackagedRuntimeNodeModuleResources,
findAsarEntry,
prunePackagedNodePty,
prunePackagedParcelWatcher,
prunePackagedSherpaOnnx,
prunePackagedRuntimeTypeDeclarations,
prunePackagedZodSources,
Expand Down Expand Up @@ -141,6 +143,65 @@ describe('electron-builder config', () => {
}
})

it('includes @parcel/watcher in the packaged runtime closure', () => {
// Why: the main process imports '@parcel/watcher' for filesystem change
// events; if it is absent from the packaged closure the serve host silently
// stops propagating file changes to clients (regression guard for #4851).
const packaged = createPackagedRuntimeNodeModuleResources()
const packagedTargets = packaged.map((resource) => resource.to)
expect(packagedTargets).toContain(join('node_modules', '@parcel', 'watcher'))
expect(
packagedTargets.some((target) =>
target.startsWith(join('node_modules', '@parcel', 'watcher-'))
)
).toBe(true)
})

it('prunes non-target @parcel/watcher platform subpackages from packaged runtime resources', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-parcel-watcher-prune-'))
try {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
await mkdir(join(parcelDir, 'watcher'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-darwin-arm64'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-darwin-x64'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-linux-x64-glibc'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-linux-arm64-glibc'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-win32-x64'), { recursive: true })

prunePackagedParcelWatcher(resourcesDir, 'linux')

await expect(readdir(parcelDir).then((entries) => entries.sort())).resolves.toEqual([
'watcher',
'watcher-linux-arm64-glibc',
'watcher-linux-x64-glibc'
])
} finally {
await rm(resourcesDir, { recursive: true, force: true })
}
})

it('leaves unrelated @parcel/* runtime deps untouched when pruning the watcher', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-parcel-watcher-prune-unrelated-'))
try {
const parcelDir = join(resourcesDir, 'node_modules', '@parcel')
await mkdir(join(parcelDir, 'watcher'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-darwin-arm64'), { recursive: true })
await mkdir(join(parcelDir, 'watcher-linux-x64-glibc'), { recursive: true })
// A hypothetical future @parcel/* runtime dep that is NOT a watcher subpackage.
await mkdir(join(parcelDir, 'transformer-js'), { recursive: true })

prunePackagedParcelWatcher(resourcesDir, 'linux')

await expect(readdir(parcelDir).then((entries) => entries.sort())).resolves.toEqual([
'transformer-js',
'watcher',
'watcher-linux-x64-glibc'
])
} finally {
await rm(resourcesDir, { recursive: true, force: true })
}
})

it('prunes type declaration artifacts from packaged runtime node_modules', async () => {
const resourcesDir = await mkdtemp(join(tmpdir(), 'orca-runtime-type-prune-'))
try {
Expand Down
117 changes: 117 additions & 0 deletions src/main/ipc/filesystem-watcher-real.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Real (unmocked) @parcel/watcher integration test.
*
* Why: every other filesystem-watcher test mocks '@parcel/watcher', so the
* suite stays green even when the native module is absent from the packaged
* runtime — the exact failure behind the directory tree not auto-refreshing
* (#4684; root cause #4851). A mocked subscribe() always "exists", so those
* tests cannot see a missing-from-bundle watcher. This test loads the real
* watcher, subscribes to a temp directory, mutates a file, and asserts a
* 'fs:changed' event actually fires end-to-end. Only 'electron' is mocked
* (it cannot load under vitest); the watcher itself is real.
*
* On a Linux host isWslPath() is always false, so a native /tmp path routes to
* createWatcher() -> real @parcel/watcher (not the inotifywait WSL fallback).
*/
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const { handleMock } = vi.hoisted(() => ({ handleMock: vi.fn() }))

vi.mock('electron', () => ({
ipcMain: { handle: handleMock }
}))

import { closeAllWatchers, registerFilesystemWatcherHandlers } from './filesystem-watcher'

type HandlerMap = Record<string, (_event: unknown, args: unknown) => Promise<unknown> | unknown>

type FsChangedCall = { worktreePath: string; events: { kind: string; absolutePath: string }[] }

// Why: real inotify + the 150ms trailing debounce means the event arrives
// asynchronously after the file write; poll rather than assume a fixed delay.
async function waitFor(predicate: () => boolean, timeoutMs = 8_000, stepMs = 50): Promise<void> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (predicate()) {
return
}
await new Promise((resolve) => setTimeout(resolve, stepMs))
}
throw new Error('waitFor: condition not met within timeout')
}

describe('filesystem-watcher real @parcel/watcher integration', () => {
const handlers: HandlerMap = {}
let tempDir: string | null = null

beforeEach(async () => {
handleMock.mockReset()
for (const key of Object.keys(handlers)) {
delete handlers[key]
}
handleMock.mockImplementation((channel: string, handler: HandlerMap[string]) => {
handlers[channel] = handler
})
registerFilesystemWatcherHandlers()
await closeAllWatchers()
})

afterEach(async () => {
await closeAllWatchers()
if (tempDir) {
await rm(tempDir, { recursive: true, force: true })
tempDir = null
}
vi.clearAllMocks()
})

// Why: a clear, separate failure mode — if the native addon is missing from
// the bundle the watcher silently no-ops (doInstallLocalWatcher swallows the
// import error), so the wiring assertion below would time out with a vague
// message. This makes "addon absent" distinct from "wiring broken".
it('loads the real @parcel/watcher native addon', async () => {
const watcher = await import('@parcel/watcher')
expect(typeof watcher.subscribe).toBe('function')
})

it.runIf(process.platform !== 'win32')(
'emits fs:changed for a file created in a watched directory',
async () => {
tempDir = await mkdtemp(join(tmpdir(), 'orca-fswatch-real-'))
const sendMock = vi.fn()
const sender = {
isDestroyed: () => false,
send: sendMock,
once: vi.fn(),
id: 1
}

// Subscribe resolves only after the native watcher is installed.
await handlers['fs:watchWorktree']({ sender }, { worktreePath: tempDir })

const createdFile = join(tempDir, 'new-file.txt')
await writeFile(createdFile, 'hello')

await waitFor(() =>
sendMock.mock.calls.some(
([channel, payload]) =>
channel === 'fs:changed' &&
(payload as FsChangedCall).events.some((event) => event.absolutePath === createdFile)
)
)

const changed = sendMock.mock.calls.find(([channel]) => channel === 'fs:changed')
expect(changed).toBeDefined()
const payload = changed![1] as FsChangedCall
const event = payload.events.find((entry) => entry.absolutePath === createdFile)
expect(event).toBeDefined()
expect(['create', 'update']).toContain(event!.kind)

await handlers['fs:unwatchWorktree']({ sender: { id: 1 } }, { worktreePath: tempDir })
},
15_000
)
})