Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: make desktop deep links reliable after window close
Josué19d4889cde47
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex b48db81b8..3a237e3a5 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.317",+ "version": "0.1.318","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.317",+ "version": "0.1.318","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex e70913995..309071548 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.317",+ "version": "0.1.318","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/mainWindowCoordinator.test.ts b/desktop-app/src/__tests__/mainWindowCoordinator.test.tsnew file mode 100644index 000000000..5560dc9a8--- /dev/null+++ b/desktop-app/src/__tests__/mainWindowCoordinator.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it, vi } from 'vitest'+import { createMainWindowCoordinator } from '../mainWindowCoordinator.js'++type TestWindow = {+ isDestroyed: () => boolean+}++function deferred() {+ let resolve!: () => void+ const promise = new Promise<void>(done => {+ resolve = done+ })+ return { promise, resolve }+}++describe('main window coordinator', () => {+ it('focuses an existing live window without creating another one', async () => {+ const focusWindow = vi.fn()+ const createWindow = vi.fn(async () => undefined)+ const coordinator = createMainWindowCoordinator<TestWindow>({+ createWindow,+ focusWindow,+ getWindow: () => ({ isDestroyed: () => false }),+ })++ await coordinator.ensureWindow()++ expect(createWindow).not.toHaveBeenCalled()+ expect(focusWindow).toHaveBeenCalledOnce()+ })++ it('recreates a window after the previous window was closed', async () => {+ let currentWindow: TestWindow | null = { isDestroyed: () => true }+ const focusWindow = vi.fn()+ const createWindow = vi.fn(async () => {+ currentWindow = { isDestroyed: () => false }+ })+ const coordinator = createMainWindowCoordinator<TestWindow>({+ createWindow,+ focusWindow,+ getWindow: () => currentWindow,+ })++ await coordinator.ensureWindow()++ expect(createWindow).toHaveBeenCalledOnce()+ expect(focusWindow).toHaveBeenCalledOnce()+ })++ it('coalesces simultaneous cold-start requests into one window creation', async () => {+ let currentWindow: TestWindow | null = null+ const creation = deferred()+ const focusWindow = vi.fn()+ const createWindow = vi.fn(async () => {+ await creation.promise+ currentWindow = { isDestroyed: () => false }+ })+ const coordinator = createMainWindowCoordinator<TestWindow>({+ createWindow,+ focusWindow,+ getWindow: () => currentWindow,+ })++ const firstRequest = coordinator.ensureWindow()+ const secondRequest = coordinator.ensureWindow()+ expect(createWindow).toHaveBeenCalledOnce()++ creation.resolve()+ await Promise.all([firstRequest, secondRequest])++ expect(focusWindow).toHaveBeenCalledTimes(2)+ })+})diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.tsindex 9962464c7..2a29f269c 100644--- a/desktop-app/src/main.ts+++ b/desktop-app/src/main.ts@@ -3,6 +3,7 @@ import path from 'node:path'import { AppService } from './appService.js'import { config } from './config.js'import { assertTrustedSender, registerIpcHandlers } from './ipc.js'+import { createMainWindowCoordinator } from './mainWindowCoordinator.js'import { type SandboxUiDeepLinkEnvelope, parseSandboxUiDeepLink } from './sandboxUiDeepLinks.js'import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'@@ -23,6 +24,7 @@ const pendingEvenfireUrls: string[] = []const pendingSandboxUiDeepLinks: SandboxUiDeepLinkEnvelope[] = []let sandboxUiDeepLinkSequence = 0let lastSandboxUiDeepLink: { rawUrl: string; receivedAt: number } | null = null+let mainWindowLifecycleReady = falsefunction systemIconAssetsDirectory(): string {return app.isPackaged ? process.resourcesPath : path.join(__dirname, '../assets')@@ -112,6 +114,19 @@ function focusMainWindow(): void {mainWindow.focus()}+const mainWindowCoordinator = createMainWindowCoordinator<BrowserWindow>({+ createWindow,+ focusWindow: focusMainWindow,+ getWindow: () => mainWindow,+})++function requestMainWindow(): void {+ if (!mainWindowLifecycleReady || !app.isReady()) return+ void mainWindowCoordinator.ensureWindow().catch(error => {+ console.error('[Desktop] Could not create the main window for a deep link:', error)+ })+}+function findProtocolUrl(argv: string[], protocol: string): string | undefined {return argv.find(arg => arg.startsWith(`${protocol}://`))}@@ -122,7 +137,7 @@ function handleSandboxUiDeepLink(rawUrl: string): boolean {const now = Date.now()if (lastSandboxUiDeepLink?.rawUrl === rawUrl && now - lastSandboxUiDeepLink.receivedAt < 1_000) {- focusMainWindow()+ requestMainWindow()return true}lastSandboxUiDeepLink = { rawUrl, receivedAt: now }@@ -136,7 +151,7 @@ function handleSandboxUiDeepLink(rawUrl: string): boolean {if (mainWindow && !mainWindow.isDestroyed()) {mainWindow.webContents.send('sandboxUi:deepLink', envelope)}- focusMainWindow()+ requestMainWindow()return true}@@ -197,6 +212,7 @@ function handleEvenfireUrl(rawUrl: string): void {})} else {pendingEvenfireUrls.push(rawUrl)+ requestMainWindow()}return}@@ -213,6 +229,7 @@ function handleEvenfireUrl(rawUrl: string): void {mainWindow.webContents.send('auth:desktopSetupToken', { email, authorizationToken })} else {pendingEvenfireUrls.push(rawUrl)+ requestMainWindow()}}@@ -262,7 +279,7 @@ if (!gotSingleInstanceLock) {if (desktopSetupLink) handleEvenfireUrl(desktopSetupLink)const clerumLink = argv.find(arg => arg.startsWith(`${CLERUM_PROTOCOL}://`))if (clerumLink) handleClerumUrl(clerumLink)- focusMainWindow()+ requestMainWindow()})}@@ -276,10 +293,9 @@ app.on('open-url', (event, rawUrl) => {})async function createWindow(): Promise<void> {- await appService.initialize()const devUrl = String(process.env.EVENFIRE_RENDERER_URL || '').trim()- mainWindow = new BrowserWindow({+ const window = new BrowserWindow({width: 1240,height: 860,show: false,@@ -295,11 +311,15 @@ async function createWindow(): Promise<void> {nodeIntegration: false,},})+ mainWindow = window+ window.on('closed', () => {+ if (mainWindow === window) mainWindow = null+ })- wireWindowVisibility(mainWindow)+ wireWindowVisibility(window)- mainWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))- mainWindow.webContents.on('will-navigate', (event, url) => {+ window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))+ window.webContents.on('will-navigate', (event, url) => {const allowFile = url.startsWith('file://')const allowDev = Boolean(devUrl) && url.startsWith(devUrl)if (!allowFile && !allowDev) {@@ -308,15 +328,15 @@ async function createWindow(): Promise<void> {})if (devUrl) {- await mainWindow.loadURL(devUrl)+ await window.loadURL(devUrl)} else {const htmlPath = path.join(__dirname, '../ui-dist/index.html')- await mainWindow.loadFile(htmlPath)+ await window.loadFile(htmlPath)}// Open maximized by default; users can manually resize afterward.- mainWindow.maximize()+ window.maximize()// Show window after successful load to avoid hidden-startup deadlocks.- mainWindow.show()+ window.show()if (process.platform !== 'darwin') {const initialEvenfireUrl = findProtocolUrl(process.argv, DESKTOP_SETUP_PROTOCOL)if (initialEvenfireUrl) handleEvenfireUrl(initialEvenfireUrl)@@ -327,9 +347,10 @@ async function createWindow(): Promise<void> {const pendingUrl = pendingEvenfireUrls.shift()if (pendingUrl) handleEvenfireUrl(pendingUrl)}- mainWindow.once('ready-to-show', () => {- mainWindow?.maximize()- mainWindow?.show()+ window.once('ready-to-show', () => {+ if (window.isDestroyed()) return+ window.maximize()+ window.show()})}@@ -337,17 +358,21 @@ if (gotSingleInstanceLock) {app.whenReady().then(async () => {wireAdaptiveSystemIcon()registerIpcHandlers(appService)+ // AppService belongs to the process, not a BrowserWindow. Initialize it once+ // so recreating a closed macOS window does not repeat session network I/O.+ await appService.initialize()+ mainWindowLifecycleReady = truefor (const arg of process.argv) {if (arg.startsWith(`${DESKTOP_SETUP_PROTOCOL}://`)) {pendingEvenfireUrls.push(arg)}}- await createWindow()+ await mainWindowCoordinator.ensureWindow()wirePowerMonitor()app.on('activate', async () => {if (BrowserWindow.getAllWindows().length === 0) {- await createWindow()+ await mainWindowCoordinator.ensureWindow()}})})diff --git a/desktop-app/src/mainWindowCoordinator.ts b/desktop-app/src/mainWindowCoordinator.tsnew file mode 100644index 000000000..83dce9545--- /dev/null+++ b/desktop-app/src/mainWindowCoordinator.ts@@ -0,0 +1,34 @@+type MainWindowHandle = {+ isDestroyed: () => boolean+}++type MainWindowCoordinatorOptions<TWindow extends MainWindowHandle> = {+ createWindow: () => Promise<void>+ focusWindow: () => void+ getWindow: () => TWindow | null+}++export function createMainWindowCoordinator<TWindow extends MainWindowHandle>(+ options: MainWindowCoordinatorOptions<TWindow>+) {+ let creationPromise: Promise<void> | null = null++ const ensureWindow = async (): Promise<void> => {+ const currentWindow = options.getWindow()+ if (currentWindow && !currentWindow.isDestroyed()) {+ options.focusWindow()+ return+ }++ if (!creationPromise) {+ creationPromise = options.createWindow().finally(() => {+ creationPromise = null+ })+ }++ await creationPromise+ options.focusWindow()+ }++ return { ensureWindow }+}diff --git a/desktop-app/ui/src/hooks/__tests__/useWorkspaceController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useWorkspaceController.test.tsxindex 79629b57a..920042510 100644--- a/desktop-app/ui/src/hooks/__tests__/useWorkspaceController.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useWorkspaceController.test.tsx@@ -66,12 +66,17 @@ function createSessionState(authenticated: boolean): SessionState {}function installClerumHarness(- options: { delayAuthenticatedLoad?: boolean; passwordLoginError?: unknown } = {}+ options: {+ delayAuthenticatedLoad?: boolean+ delayHealth?: boolean+ passwordLoginError?: unknown+ } = {}) {let authenticated = falseconst teamDirectoryDeferred = createDeferred<{ items: []; currentTeamId: string }>()const catalogDeferred = createDeferred<ReturnType<typeof createCatalog>>()const approvalsDeferred = createDeferred<[]>()+ const healthDeferred = createDeferred<ReturnType<typeof createHealth>>()const getSessionState = vi.fn(async () => createSessionState(authenticated))const passwordLogin = vi.fn(async () => {@@ -111,7 +116,9 @@ function installClerumHarness(isPackaged: false,options: [],})),- getDependenciesHealth: vi.fn(async () => createHealth()),+ getDependenciesHealth: vi.fn(async () =>+ options.delayHealth ? healthDeferred.promise : createHealth()+ ),getSessionState,passwordLogin,onDesktopSetupToken: vi.fn(() => () => undefined),@@ -214,6 +221,9 @@ function installClerumHarness(passwordLogin,getSessionState,getDesktopReleaseStatus,+ resolveHealth() {+ healthDeferred.resolve(createHealth())+ },resolveAuthenticatedLoad() {teamDirectoryDeferred.resolve({ items: [], currentTeamId: '' })catalogDeferred.resolve(createCatalog())@@ -290,6 +300,17 @@ describe('useWorkspaceController', () => {delete (window as { clerum?: unknown }).clerum})+ it('restores the session without waiting for a slow dependency-health probe', async () => {+ const clerum = installClerumHarness({ delayHealth: true })++ renderControllerHarness()++ await waitFor(() => expect(clerum.getSessionState).toHaveBeenCalledOnce())+ await waitFor(() => expect(screen.getByTestId('booting').textContent).toBe('false'))++ clerum.resolveHealth()+ })+it('preserves a workflow nav selection while login session hydration finishes', async () => {const clerum = installClerumHarness({ delayAuthenticatedLoad: true })diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 46384ad8f..1abf3d90f 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -569,8 +569,10 @@ export function useAppController() {async (options: { preserveNav?: boolean } = {}) => {const { preserveNav = false } = optionstry {- const health = await window.clerum.auth.getDependenciesHealth()- auth.setDependencyHealth(health)+ void window.clerum.auth+ .getDependenciesHealth()+ .then(auth.setDependencyHealth)+ .catch(() => undefined)const sessionState = await window.clerum.auth.getSessionState()const authenticated = Boolean(sessionState.authenticated && sessionState.me)auth.setIsAuthenticated(authenticated)diff --git a/profile-ui/app/open/apps/[recipeNs]/[recipeName]/page.tsx b/profile-ui/app/open/apps/[recipeNs]/[recipeName]/page.tsxdeleted file mode 100644index 8d8168679..000000000--- a/profile-ui/app/open/apps/[recipeNs]/[recipeName]/page.tsx+++ /dev/null@@ -1,76 +0,0 @@-'use client'--import { Suspense, useEffect, useMemo, useRef } from 'react'-import { useParams, useSearchParams } from 'next/navigation'-import { Button } from '@components/Button'-import { buildEvenfireDesktopAppLink } from '@lib/desktopAppLinks'--function OpenDesktopAppContent() {- const params = useParams<{ recipeNs: string; recipeName: string }>()- const searchParams = useSearchParams()- const attemptedOpenRef = useRef(false)- const deepLink = useMemo(- () =>- buildEvenfireDesktopAppLink({- recipeNs: params.recipeNs,- recipeName: params.recipeName,- path: searchParams.get('path') || '/',- teamId: searchParams.get('team') || undefined,- }),- [params.recipeName, params.recipeNs, searchParams]- )-- useEffect(() => {- if (!deepLink || attemptedOpenRef.current) return- attemptedOpenRef.current = true- window.location.href = deepLink- }, [deepLink])-- return (- <main className="center-page">- <section className="page-card">- <div className="stack-tight">- <p className="eyebrow">Evenfire Desktop</p>- <h1 className="page-title page-title--large">Open {params.recipeName}</h1>- <p className="body-copy">- {deepLink- ? 'Evenfire should open this app automatically. Use the button if your browser asks for confirmation.'- : 'This app link is invalid or incomplete.'}- </p>- </div>-- <Button- disabled={!deepLink}- onClick={() => {- if (deepLink) window.location.href = deepLink- }}- >- Open in Evenfire- </Button>-- {deepLink ? (- <p className="body-copy">- If nothing happens, make sure the Evenfire desktop app is installed and try again.- </p>- ) : null}- </section>- </main>- )-}--export default function OpenDesktopAppPage() {- return (- <Suspense- fallback={- <main className="center-page">- <section className="page-card">- <h1 className="page-title page-title--large">Open in Evenfire</h1>- <p className="body-copy">Preparing the desktop app link...</p>- </section>- </main>- }- >- <OpenDesktopAppContent />- </Suspense>- )-}diff --git a/profile-ui/app/open/apps/[recipeNs]/[recipeName]/route.ts b/profile-ui/app/open/apps/[recipeNs]/[recipeName]/route.tsnew file mode 100644index 000000000..ee5efb425--- /dev/null+++ b/profile-ui/app/open/apps/[recipeNs]/[recipeName]/route.ts@@ -0,0 +1,41 @@+import {+ buildEvenfireDesktopAppLink,+ buildEvenfireDesktopAppRedirectDocument,+} from '@lib/desktopAppLinks'++export const dynamic = 'force-dynamic'++export async function GET(+ request: Request,+ context: { params: Promise<{ recipeNs: string; recipeName: string }> }+) {+ const params = await context.params+ const requestUrl = new URL(request.url)+ const deepLink = buildEvenfireDesktopAppLink({+ recipeNs: params.recipeNs,+ recipeName: params.recipeName,+ path: requestUrl.searchParams.get('path') || '/',+ teamId: requestUrl.searchParams.get('team') || undefined,+ })++ if (!deepLink) {+ return new Response('Invalid or incomplete Evenfire desktop app link.', {+ status: 400,+ headers: {+ 'Cache-Control': 'no-store',+ 'Content-Type': 'text/plain; charset=utf-8',+ },+ })+ }++ return new Response(buildEvenfireDesktopAppRedirectDocument(deepLink), {+ headers: {+ 'Cache-Control': 'no-store',+ 'Content-Security-Policy':+ "default-src 'none'; script-src 'unsafe-inline'; base-uri 'none'; " ++ "form-action 'none'; frame-ancestors 'none'",+ 'Content-Type': 'text/html; charset=utf-8',+ 'Referrer-Policy': 'no-referrer',+ },+ })+}diff --git a/profile-ui/lib/desktopAppLinks.ts b/profile-ui/lib/desktopAppLinks.tsindex 3169e33a0..baa52a608 100644--- a/profile-ui/lib/desktopAppLinks.ts+++ b/profile-ui/lib/desktopAppLinks.ts@@ -38,3 +38,35 @@ export function buildEvenfireDesktopAppLink(parts: {if (teamId) url.searchParams.set('team', teamId)return url.toString()}++function escapeHtml(value: string): string {+ return value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''')+}++export function buildEvenfireDesktopAppRedirectDocument(deepLink: string): string {+ const parsed = new URL(deepLink)+ if (parsed.protocol !== 'evenfire:' || parsed.hostname !== 'app') {+ throw new Error('Cannot redirect to an invalid desktop app link')+ }++ const escapedLink = escapeHtml(deepLink)+ const scriptLink = JSON.stringify(deepLink).replaceAll('<', '\\u003c')+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta http-equiv="refresh" content="0;url=${escapedLink}">+ <title>Open in Evenfire</title>+</head>+<body>+ <p>Opening Evenfire… <a href="${escapedLink}">Open the desktop app</a></p>+ <script>window.location.replace(${scriptLink})</script>+</body>+</html>`+}diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex af0f44bc8..8d63b6148 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.102",+ "version": "0.1.103","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.102",+ "version": "0.1.103","dependencies": {"next": "16.2.6","react": "^18.3.1",diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex d9f0a014e..071102856 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.102",+ "version": "0.1.103","private": true,"scripts": {"dev": "next dev",diff --git a/profile-ui/test/desktopAppLinks.test.ts b/profile-ui/test/desktopAppLinks.test.tsindex 3f9c809f9..a070b1cf7 100644--- a/profile-ui/test/desktopAppLinks.test.ts+++ b/profile-ui/test/desktopAppLinks.test.ts@@ -1,6 +1,9 @@import assert from 'node:assert/strict'import test from 'node:test'-import { buildEvenfireDesktopAppLink } from '../lib/desktopAppLinks'+import {+ buildEvenfireDesktopAppLink,+ buildEvenfireDesktopAppRedirectDocument,+} from '../lib/desktopAppLinks'test('buildEvenfireDesktopAppLink preserves a nested app route and team', () => {assert.equal(@@ -25,3 +28,21 @@ test('buildEvenfireDesktopAppLink rejects unsafe routes', () => {null)})++test('buildEvenfireDesktopAppRedirectDocument creates an unauthenticated protocol handoff', () => {+ const deepLink =+ 'evenfire://app/sandbox-recipes/agentic-task-board' + '?path=%2Ftasks%2Ftask-42&team=team-123'+ const document = buildEvenfireDesktopAppRedirectDocument(deepLink)++ assert.match(document, /http-equiv="refresh"/)+ assert.match(document, /window\.location\.replace/)+ assert.match(document, /evenfire:\/\/app\/sandbox-recipes\/agentic-task-board/)+ assert.doesNotMatch(document, /login|authenticate|authorization/i)+})++test('buildEvenfireDesktopAppRedirectDocument rejects unrelated protocols', () => {+ assert.throws(+ () => buildEvenfireDesktopAppRedirectDocument('https://example.com/app'),+ /invalid desktop app link/+ )+})diff --git a/profile-ui/test/routes.test.ts b/profile-ui/test/routes.test.tsindex 20b9a7c95..5d217d304 100644--- a/profile-ui/test/routes.test.ts+++ b/profile-ui/test/routes.test.ts@@ -18,18 +18,18 @@ function collectRoutePaths(value: unknown): string[] {function appRoutePatterns(): RegExp[] {const appDirectory = path.join(process.cwd(), 'app')- const pageFiles: string[] = []+ const routeFiles: string[] = []function visit(directory: string) {for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {const entryPath = path.join(directory, entry.name)if (entry.isDirectory()) visit(entryPath)- else if (/^page\.(?:js|jsx|ts|tsx)$/.test(entry.name)) pageFiles.push(entryPath)+ else if (/^(?:page|route)\.(?:js|jsx|ts|tsx)$/.test(entry.name)) routeFiles.push(entryPath)}}visit(appDirectory)- return pageFiles.map(file => {+ return routeFiles.map(file => {const relativeDirectory = path.relative(appDirectory, path.dirname(file))const routePath = relativeDirectory ? `/${relativeDirectory}` : '/'const pattern = routePath@@ -40,7 +40,7 @@ function appRoutePatterns(): RegExp[] {})}-test('PROFILE_ROUTES resolve to App Router pages', () => {+test('PROFILE_ROUTES resolve to App Router pages or route handlers', () => {const appRoutes = appRoutePatterns()const routePaths = [...new Set(collectRoutePaths(PROFILE_ROUTES))]const unresolved = routePaths.filter(route => !appRoutes.some(pattern => pattern.test(route)))