Compare commits

..

No commits in common. "35ce3c39af7dd92cfa60b347851f2a8249573c41" and "bb2b8148c79e4e8d97b38329f540f9a4ce2c7607" have entirely different histories.

2 changed files with 268 additions and 150 deletions

View File

@ -6,9 +6,32 @@ import desktopBridge, {
isElectrobunDesktop
} from '../../../electrobun-bridge.js'
const electron = window.require ? window.require('electron') : null
const ipcRenderer = electron ? electron.ipcRenderer : null
// eslint-disable-next-line react-refresh/only-export-components
export function isElectron() {
return isElectrobunBridgeReady() || isElectrobunDesktop()
if (isElectrobunDesktop()) {
return true
}
if (
typeof window !== 'undefined' &&
window.process &&
window.process.type === 'renderer'
) {
return true
}
if (
typeof navigator === 'object' &&
typeof navigator.userAgent === 'string' &&
navigator.userAgent.indexOf('Electron') >= 0
) {
return true
}
return false
}
const ElectronContext = createContext()
@ -33,6 +56,7 @@ const ElectronProvider = ({ children }) => {
const [isMaximized, setIsMaximized] = useState(false)
const [isFullScreen, setIsFullScreen] = useState(false)
const [electronAvailable] = useState(isElectron())
const useElectrobun = isElectrobunBridgeReady() || isElectrobunDesktop()
const navigate = useNavigate()
const lastNavigationAtRef = useRef(0)
@ -61,34 +85,74 @@ const ElectronProvider = ({ children }) => {
}, [])
const openExternalUrl = (url) => {
if (!electronAvailable) return false
void desktopBridge.openExternalUrl(url).catch((error) => {
console.warn('[ElectronContext] Failed to open external url:', error)
})
return true
if (useElectrobun) {
void desktopBridge.openExternalUrl(url).catch((error) => {
console.warn('[ElectronContext] Failed to open external url:', error)
})
return true
}
if (electronAvailable && ipcRenderer) {
ipcRenderer.invoke('open-external-url', url)
return true
}
return false
}
const openInternalUrl = (url) => {
if (!electronAvailable) return false
void desktopBridge.openInternalUrl(url).catch((error) => {
console.warn('[ElectronContext] Failed to open internal url:', error)
})
return true
if (useElectrobun) {
void desktopBridge.openInternalUrl(url).catch((error) => {
console.warn('[ElectronContext] Failed to open internal url:', error)
})
return true
}
if (electronAvailable && ipcRenderer) {
ipcRenderer.invoke('open-internal-url', url)
return true
}
return false
}
useEffect(() => {
if (!electronAvailable) return
document.body.classList.add('electron-body')
return () => {
document.body.classList.remove('electron-body')
if (useElectrobun) {
desktopBridge.getOsInfo().then((info) => {
if (info?.platform) {
setPlatform(info.platform)
if (info.platform === 'darwin') {
document.documentElement.classList.add('macos-vibrancy')
}
}
})
desktopBridge.getWindowState().then(applyWindowState)
const unsubWindowState = desktopBridge.onMessage(
'windowState',
applyWindowState
)
const unsubNavigate = desktopBridge.onMessage('navigate', (url) => {
if (url.toLowerCase() == '/favicon.ico') {
return
}
console.log('[ElectronContext] Navigating to:', url)
navigate(url)
})
const unsubNavigationGesture = desktopBridge.onMessage(
'navigationGesture',
navigateHistory
)
return () => {
unsubWindowState()
unsubNavigate()
unsubNavigationGesture()
}
}
}, [electronAvailable])
useEffect(() => {
if (!electronAvailable) return
if (!ipcRenderer) return
desktopBridge.getOsInfo().then((info) => {
ipcRenderer.invoke('os-info').then((info) => {
if (info?.platform) {
setPlatform(info.platform)
if (info.platform === 'darwin') {
@ -97,30 +161,39 @@ const ElectronProvider = ({ children }) => {
}
})
desktopBridge.getWindowState().then(applyWindowState)
ipcRenderer.invoke('window-state').then(applyWindowState)
const unsubWindowState = desktopBridge.onMessage(
'windowState',
applyWindowState
)
const unsubNavigate = desktopBridge.onMessage('navigate', (url) => {
const windowStateHandler = (_event, state) => {
applyWindowState(state)
}
ipcRenderer.on('window-state', windowStateHandler)
const navigateHandler = (_event, url) => {
if (url.toLowerCase() == '/favicon.ico') {
return
}
console.log('[ElectronContext] Navigating to:', url)
navigate(url)
})
const unsubNavigationGesture = desktopBridge.onMessage(
'navigationGesture',
navigateHistory
)
}
ipcRenderer.on('navigate', navigateHandler)
const navigationGestureHandler = (_event, direction) => {
navigateHistory(direction)
}
ipcRenderer.on('navigation-gesture', navigationGestureHandler)
return () => {
unsubWindowState()
unsubNavigate()
unsubNavigationGesture()
ipcRenderer.removeListener('navigate', navigateHandler)
ipcRenderer.removeListener('navigation-gesture', navigationGestureHandler)
ipcRenderer.removeListener('window-state', windowStateHandler)
}
}, [applyWindowState, electronAvailable, navigate, navigateHistory])
}, [
applyWindowState,
electronAvailable,
navigate,
navigateHistory,
useElectrobun
])
useEffect(() => {
if (!electronAvailable || platform !== 'darwin') return
@ -154,74 +227,103 @@ const ElectronProvider = ({ children }) => {
}, [electronAvailable, navigateHistory, platform])
const handleWindowControl = (action) => {
if (!electronAvailable) return
void desktopBridge.windowControl(action)
if (useElectrobun) {
void desktopBridge.windowControl(action)
return
}
if (electronAvailable && ipcRenderer) {
ipcRenderer.send('window-control', action)
}
}
const getAuthSession = async () => {
if (!electronAvailable) return null
return await desktopBridge.getAuthSession()
if (useElectrobun) return await desktopBridge.getAuthSession()
if (!ipcRenderer) return null
return await ipcRenderer.invoke('auth-session-get')
}
const setAuthSession = async (session) => {
if (!electronAvailable) return false
const result = await desktopBridge.setAuthSession(session)
return result?.ok ?? false
if (useElectrobun) {
const result = await desktopBridge.setAuthSession(session)
return result?.ok ?? false
}
if (!ipcRenderer) return false
return await ipcRenderer.invoke('auth-session-set', session)
}
const clearAuthSession = async () => {
if (!electronAvailable) return false
const result = await desktopBridge.clearAuthSession()
return result?.ok ?? false
if (useElectrobun) {
const result = await desktopBridge.clearAuthSession()
return result?.ok ?? false
}
if (!ipcRenderer) return false
return await ipcRenderer.invoke('auth-session-clear')
}
const getAppSettings = useCallback(async () => {
if (!electronAvailable) return {}
return await desktopBridge.getAppSettings()
}, [electronAvailable])
if (useElectrobun) return await desktopBridge.getAppSettings()
if (!ipcRenderer) return {}
return await ipcRenderer.invoke('app-settings-get')
}, [electronAvailable, useElectrobun])
const setAppSettings = useCallback(
async (settings) => {
if (!electronAvailable) return false
const result = await desktopBridge.setAppSettings(settings)
return result?.ok ?? false
if (useElectrobun) {
const result = await desktopBridge.setAppSettings(settings)
return result?.ok ?? false
}
if (!ipcRenderer) return false
return await ipcRenderer.invoke('app-settings-set', settings)
},
[electronAvailable]
[electronAvailable, useElectrobun]
)
const startAppUpdate = useCallback(
async (update) => {
if (!electronAvailable) return false
const result = await desktopBridge.startAppUpdate(update)
return result?.ok ?? false
if (useElectrobun) {
const result = await desktopBridge.startAppUpdate(update)
return result?.ok ?? false
}
if (!ipcRenderer) return false
return await ipcRenderer.invoke('app-update-start', update)
},
[electronAvailable]
[electronAvailable, useElectrobun]
)
const checkAppUpdateResult = useCallback(async () => {
if (!electronAvailable) return null
if (!electronAvailable || !useElectrobun) return null
return await desktopBridge.checkAppUpdateResult()
}, [electronAvailable])
}, [electronAvailable, useElectrobun])
const checkDuplicateInstallations = useCallback(async () => {
if (!electronAvailable) return null
if (!electronAvailable || !useElectrobun) return null
return await desktopBridge.checkDuplicateInstallations()
}, [electronAvailable])
}, [electronAvailable, useElectrobun])
const removeDuplicateInstallations = useCallback(async () => {
if (!electronAvailable) return false
if (!electronAvailable || !useElectrobun) return false
const result = await desktopBridge.removeDuplicateInstallations()
return result?.ok ?? false
}, [electronAvailable])
}, [electronAvailable, useElectrobun])
const onDuplicateInstallationsRemoved = useCallback(
(handler) => {
if (!electronAvailable || typeof handler !== 'function') {
if (
!electronAvailable ||
!useElectrobun ||
typeof handler !== 'function'
) {
return () => {}
}
return desktopBridge.onMessage('duplicateInstallationsRemoved', handler)
},
[electronAvailable]
[electronAvailable, useElectrobun]
)
const onAppUpdateProgress = useCallback(
@ -229,9 +331,24 @@ const ElectronProvider = ({ children }) => {
if (!electronAvailable || typeof handler !== 'function') {
return () => {}
}
return desktopBridge.onMessage('appUpdateProgress', handler)
if (useElectrobun) {
return desktopBridge.onMessage('appUpdateProgress', handler)
}
if (!ipcRenderer) return () => {}
const progressHandler = (_event, progress) => {
handler(progress)
}
ipcRenderer.on('app-update-progress', progressHandler)
return () => {
ipcRenderer.removeListener('app-update-progress', progressHandler)
}
},
[electronAvailable]
[electronAvailable, useElectrobun]
)
const onCheckForUpdatesRequest = useCallback(
@ -239,9 +356,24 @@ const ElectronProvider = ({ children }) => {
if (!electronAvailable || typeof handler !== 'function') {
return () => {}
}
return desktopBridge.onMessage('checkForUpdates', handler)
if (useElectrobun) {
return desktopBridge.onMessage('checkForUpdates', handler)
}
if (!ipcRenderer) return () => {}
const checkHandler = () => {
handler()
}
ipcRenderer.on('check-for-updates', checkHandler)
return () => {
ipcRenderer.removeListener('check-for-updates', checkHandler)
}
},
[electronAvailable]
[electronAvailable, useElectrobun]
)
const getToken = async () => {
@ -257,8 +389,12 @@ const ElectronProvider = ({ children }) => {
const resizeSpotlightWindow = async (height) => {
if (!electronAvailable) return false
try {
const result = await desktopBridge.resizeSpotlightWindow(height)
return result?.ok ?? false
if (useElectrobun) {
const result = await desktopBridge.resizeSpotlightWindow(height)
return result?.ok ?? false
}
if (!ipcRenderer) return false
return await ipcRenderer.invoke('spotlight-window-resize', height)
} catch (error) {
console.warn(
'[ElectronContext] Failed to resize spotlight window:',
@ -271,22 +407,31 @@ const ElectronProvider = ({ children }) => {
const setSidebarViewMenu = useCallback(
async (sections) => {
if (!electronAvailable) return false
const result = await desktopBridge.setSidebarViewMenu(sections)
return result?.ok ?? false
if (useElectrobun) {
const result = await desktopBridge.setSidebarViewMenu(sections)
return result?.ok ?? false
}
if (!ipcRenderer) return false
return await ipcRenderer.invoke('set-sidebar-view-menu', sections)
},
[electronAvailable]
[electronAvailable, useElectrobun]
)
const getElectronVersion = useCallback(async () => {
if (!electronAvailable) return null
return await desktopBridge.getAppVersion()
}, [electronAvailable])
if (useElectrobun) return await desktopBridge.getAppVersion()
if (!ipcRenderer) return null
return await ipcRenderer.invoke('electron-version')
}, [electronAvailable, useElectrobun])
const getAppEngine = useCallback(async () => {
if (!electronAvailable) return 'native'
const engine = await desktopBridge.getAppEngine()
return engine === 'chromium' ? 'chromium' : 'native'
}, [electronAvailable])
if (useElectrobun) {
const engine = await desktopBridge.getAppEngine()
return engine === 'chromium' ? 'chromium' : 'native'
}
return 'native'
}, [electronAvailable, useElectrobun])
return (
<ElectronContext.Provider

View File

@ -126,14 +126,13 @@ export const prepareInstallerPath = async (installerPath) => {
const startWindowsInstallerProgressWatch = (
logPath,
sendProgress,
{ onInstallSuccessful, onInstallFailed, onStalled, stallTimeoutMs }
onInstallSuccessful
) => {
let installerOutput = ''
let offset = 0
let lastPercent = null
let lastMessage = null
let outcomeNotified = false
let lastActivityAt = Date.now()
let installSuccessNotified = false
const poll = async () => {
try {
@ -146,7 +145,6 @@ const startWindowsInstallerProgressWatch = (
await handle.read(buffer, 0, buffer.length, offset)
offset = stat.size
installerOutput += buffer.toString('utf8')
lastActivityAt = Date.now()
const { percent, message } =
parseWindowsInstallerProgress(installerOutput)
@ -162,14 +160,13 @@ const startWindowsInstallerProgressWatch = (
})
}
if (!outcomeNotified) {
if (isWindowsInstallFailed(installerOutput)) {
outcomeNotified = true
onInstallFailed?.(installerOutput)
} else if (isWindowsInstallSuccessful(installerOutput)) {
outcomeNotified = true
onInstallSuccessful?.(installerOutput)
}
if (
!installSuccessNotified &&
isWindowsInstallSuccessful(installerOutput) &&
!isWindowsInstallFailed(installerOutput)
) {
installSuccessNotified = true
onInstallSuccessful?.(installerOutput)
}
} finally {
await handle.close()
@ -182,18 +179,6 @@ const startWindowsInstallerProgressWatch = (
}
const intervalId = setInterval(() => {
// The installer runs detached (outside our job object), so a dead
// installer only shows up as the log going quiet before any outcome.
if (
!outcomeNotified &&
stallTimeoutMs > 0 &&
Date.now() - lastActivityAt > stallTimeoutMs
) {
outcomeNotified = true
onStalled?.(installerOutput)
return
}
poll().catch((error) => {
console.error('[app-update] installer log poll error:', error)
})
@ -264,22 +249,8 @@ export const launchWindowsInstaller = async (
const stopProgressWatch = startWindowsInstallerProgressWatch(
logPath,
sendProgress,
{
stallTimeoutMs: 3 * 60 * 1000,
onInstallSuccessful: (output) => {
settleSuccess(output)
},
onInstallFailed: (output) => {
settleFailure(getInstallErrorMessage(null, output))
},
onStalled: (output) => {
settleFailure(
getInstallErrorMessage(
new Error('The update installer stopped responding.'),
output
)
)
}
(output) => {
settleSuccess(output)
}
)
@ -287,63 +258,65 @@ export const launchWindowsInstaller = async (
return await stopProgressWatch()
}
// Silent NSIS install.
// Silent NSIS install in a detached child process (not a batch file).
// /S = silent (https://nsis.sourceforge.io/Reference/SilentInstall)
// /UPDATE = in-app update (stage into Farm Control.new; swap after exit)
// /RESTARTFC = installer waits for this process to exit, swaps folders, relaunches
// /PARENTPID = exact process to wait for (CEF may outlive the launcher)
// /LOG= = progress log (installer:% / PHASE / STATUS / COPY_TOTAL / COPY_FILE)
const installerCommandLine = [
`"${resolvedPath}"`,
// /LOG= + FARMCONTROL_INSTALL_LOG = progress log
// (installer:% / PHASE / STATUS / COPY_TOTAL / COPY_FILE)
const installerArgs = [
'/S',
'/UPDATE',
'/RESTARTFC',
`/PARENTPID=${process.pid}`,
`/LOG="${logPath}"`
].join(' ')
`/LOG=${logPath}`
]
// This process runs inside a Windows job object (CEF/launcher) that kills
// every child process when the app exits — a directly spawned installer
// (even with detached: true) inherits the job and dies mid folder-swap the
// moment the app quits. Creating the process via WMI (Win32_Process.Create)
// parents it to the WMI provider host, outside our job, so it survives.
const quoteForPowershell = (value) => `'${value.replace(/'/g, "''")}'`
const installerProcess = spawn(resolvedPath, installerArgs, {
detached: true,
env: {
...process.env,
FARMCONTROL_INSTALL_LOG: logPath
},
stdio: 'ignore',
windowsHide: true
})
const spawnerProcess = spawn(
'powershell.exe',
[
'-NoProfile',
'-NonInteractive',
'-WindowStyle',
'Hidden',
'-Command',
`$result = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${quoteForPowershell(installerCommandLine)} }; exit $result.ReturnValue`
],
{
stdio: 'ignore',
windowsHide: true
}
)
installerProcess.unref()
spawnerProcess.on('error', async (error) => {
installerProcess.on('error', async (error) => {
const output = await refreshInstallerOutput()
console.error('[app-update] installer launch error:', error)
console.error('[app-update] installer error:', error)
settleFailure(getInstallErrorMessage(error, output))
})
spawnerProcess.on('exit', async (code) => {
// PowerShell exits as soon as the installer is created; from here the
// log watcher owns success/failure. Only a non-zero code (WMI create
// failed) means the installer never started.
if (code === 0 || settled) return
installerProcess.on('exit', async (code) => {
const output = await refreshInstallerOutput()
settleFailure(
getInstallErrorMessage(
new Error(`Failed to launch the update installer (code ${code}).`),
output
await fs.unlink(logPath).catch(() => {})
if (settled) return
if (code !== 0) {
settleFailure(
getInstallErrorMessage(
new Error(`Installer exited with code ${code}.`),
output
)
)
)
return
}
if (
isWindowsInstallFailed(output) ||
!isWindowsInstallSuccessful(output)
) {
settleFailure(getInstallErrorMessage(null, output))
return
}
settleSuccess(output)
})
})
}