Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: harden desktop app deep-link recovery
Josué6da9c60cda47
diff --git a/.dockerignore b/.dockerignoreindex 00931dd92..6b8f22d12 100644--- a/.dockerignore+++ b/.dockerignore@@ -28,6 +28,7 @@ kubeconfig***/dist**/.next**/coverage+**/.test-dist**/*.log.DS_Store**/.DS_Storediff --git a/desktop-app/forge.config.js b/desktop-app/forge.config.jsindex a444476b8..dfe64da6d 100644--- a/desktop-app/forge.config.js+++ b/desktop-app/forge.config.js@@ -4,11 +4,17 @@ const os = require('node:os')const path = require('node:path')const { FusesPlugin } = require('@electron-forge/plugin-fuses')const { FuseV1Options, FuseVersion } = require('@electron/fuses')+const {+ CLERUM_OAUTH_PROTOCOL,+ SANDBOX_UI_DEEP_LINK_PROTOCOL,+} = require('@clerum/desktop-app-links')const desktopLicense = require('./package.json').licenseconst defaultAppleBundleId = 'ai.evenfire.desktop'const assetsDirectory = path.resolve(__dirname, 'assets')const adaptiveIconDocument = path.join(assetsDirectory, 'adaptive-icon.icon')+const evenfireProtocol = SANDBOX_UI_DEEP_LINK_PROTOCOL.replace(/:$/, '')+const clerumProtocol = CLERUM_OAUTH_PROTOCOL.replace(/:$/, '')function compileMacAdaptiveIcon(buildPath, _electronVersion, platform, _arch, callback) {if (platform !== 'darwin') {@@ -151,11 +157,11 @@ module.exports = {protocols: [{name: 'Evenfire',- schemes: ['evenfire'],+ schemes: [evenfireProtocol],},{name: 'Clerum OAuth callback',- schemes: ['clerum'],+ schemes: [clerumProtocol],},],...(osxSign ? { osxSign } : {}),@@ -205,7 +211,7 @@ module.exports = {bin: 'Evenfire',categories: ['Utility'],icon: path.join(assetsDirectory, 'icon.png'),- mimeType: ['x-scheme-handler/evenfire', 'x-scheme-handler/clerum'],+ mimeType: [`x-scheme-handler/${evenfireProtocol}`, `x-scheme-handler/${clerumProtocol}`],},},},@@ -221,7 +227,7 @@ module.exports = {license: desktopLicense,categories: ['Utility'],icon: path.join(assetsDirectory, 'icon.png'),- mimeType: ['x-scheme-handler/evenfire', 'x-scheme-handler/clerum'],+ mimeType: [`x-scheme-handler/${evenfireProtocol}`, `x-scheme-handler/${clerumProtocol}`],},},},diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex a382e0e4f..6b07b5ac8 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.329",+ "version": "0.1.330","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.329",+ "version": "0.1.330","license": "MPL-2.0","dependencies": {"@clerum/desktop-app-links": "file:../packages/desktop-app-links",@@ -49,7 +49,7 @@},"../packages/desktop-app-links": {"name": "@clerum/desktop-app-links",- "version": "0.1.0"+ "version": "0.1.1"},"node_modules/@adobe/css-tools": {"version": "4.4.4",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 90d1a44bb..7441c979c 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.329",+ "version": "0.1.330","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts b/desktop-app/src/__tests__/appService.sandboxUiApps.test.tsindex baa4bbc02..81644311c 100644--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts@@ -245,4 +245,73 @@ describe('AppService profile UI link authority', () => {'Cannot resolve a shareable Profile UI link')})++ it('omits the path when the active app is still on its default route', async () => {+ const service = makeService() as unknown as {+ me: { id: string; email: string }+ memberRegistrationServiceClient: { getInvitationProfile: ReturnType<typeof vi.fn> }+ createSandboxUiDeepLink: (teamId?: string) => Promise<{ url: string }>+ }+ service.me = { id: 'user-1', email: '[email protected]' }+ service.memberRegistrationServiceClient = {+ getInvitationProfile: vi.fn().mockResolvedValue({+ profileUiBaseUrl: 'https://profile.tenant.example',+ }),+ }+ mockGetActiveSandboxUiLocation.mockReturnValue({+ recipeNs: 'sandbox-recipes',+ recipeName: 'task-board',+ })++ await expect(service.createSandboxUiDeepLink('team-1')).resolves.toEqual({+ url: 'https://profile.tenant.example/open/apps/sandbox-recipes/task-board' + '?team=team-1',+ })+ })++ it('fails visibly when a successful profile lookup omits the Profile UI URL', async () => {+ const service = makeService() as unknown as {+ me: { id: string; email: string }+ memberRegistrationServiceClient: { getInvitationProfile: ReturnType<typeof vi.fn> }+ createSandboxUiDeepLink: () => Promise<{ url: string }>+ }+ service.me = { id: 'user-1', email: '[email protected]' }+ service.memberRegistrationServiceClient = {+ getInvitationProfile: vi.fn().mockResolvedValue({ profileUiBaseUrl: '' }),+ }+ mockGetActiveSandboxUiLocation.mockReturnValue({+ recipeNs: 'sandbox-recipes',+ recipeName: 'task-board',+ path: '/',+ })++ await expect(service.createSandboxUiDeepLink()).rejects.toThrow(+ 'the invitation profile did not provide a Profile UI URL'+ )+ await expect(service.createSandboxUiDeepLink()).rejects.toThrow(+ 'the invitation profile did not provide a Profile UI URL'+ )+ expect(service.memberRegistrationServiceClient.getInvitationProfile).toHaveBeenCalledTimes(2)+ })++ it('surfaces an invalid active app URL instead of copying its initial route', async () => {+ const service = makeService() as unknown as {+ me: { id: string; email: string }+ memberRegistrationServiceClient: { getInvitationProfile: ReturnType<typeof vi.fn> }+ createSandboxUiDeepLink: () => Promise<{ url: string }>+ }+ service.me = { id: 'user-1', email: '[email protected]' }+ service.memberRegistrationServiceClient = {+ getInvitationProfile: vi.fn().mockResolvedValue({+ profileUiBaseUrl: 'https://profile.tenant.example',+ }),+ }+ mockGetActiveSandboxUiLocation.mockImplementation(() => {+ throw new Error('Cannot read the current app route')+ })++ await expect(service.createSandboxUiDeepLink()).rejects.toThrow(+ 'Cannot read the current app route'+ )+ expect(service.memberRegistrationServiceClient.getInvitationProfile).not.toHaveBeenCalled()+ })})diff --git a/desktop-app/src/__tests__/forgeConfig.test.ts b/desktop-app/src/__tests__/forgeConfig.test.tsindex 3bf5514d2..d6442bd2e 100644--- a/desktop-app/src/__tests__/forgeConfig.test.ts+++ b/desktop-app/src/__tests__/forgeConfig.test.ts@@ -1,7 +1,12 @@import { describe, expect, it } from 'vitest'+import { CLERUM_OAUTH_PROTOCOL, SANDBOX_UI_DEEP_LINK_PROTOCOL } from '@clerum/desktop-app-links'const forgeConfig = require('../../forge.config.js') as {- packagerConfig?: { asar?: boolean; derefSymlinks?: boolean }+ packagerConfig?: {+ asar?: boolean+ derefSymlinks?: boolean+ protocols?: Array<{ schemes?: string[] }>+ }}describe('Electron Forge packaging', () => {@@ -11,4 +16,17 @@ describe('Electron Forge packaging', () => {derefSymlinks: true,})})++ it('registers the protocol schemes from the shared desktop-link contract', () => {+ expect(forgeConfig.packagerConfig?.protocols).toEqual([+ {+ name: 'Evenfire',+ schemes: [SANDBOX_UI_DEEP_LINK_PROTOCOL.replace(/:$/, '')],+ },+ {+ name: 'Clerum OAuth callback',+ schemes: [CLERUM_OAUTH_PROTOCOL.replace(/:$/, '')],+ },+ ])+ })})diff --git a/desktop-app/src/__tests__/mainWindowCoordinator.test.ts b/desktop-app/src/__tests__/mainWindowCoordinator.test.tsindex 5560dc9a8..bceaa3dc5 100644--- a/desktop-app/src/__tests__/mainWindowCoordinator.test.ts+++ b/desktop-app/src/__tests__/mainWindowCoordinator.test.ts@@ -1,5 +1,8 @@import { describe, expect, it, vi } from 'vitest'-import { createMainWindowCoordinator } from '../mainWindowCoordinator.js'+import {+ createMainWindowCoordinator,+ createRetryableInitializer,+} from '../mainWindowCoordinator.js'type TestWindow = {isDestroyed: () => boolean@@ -70,4 +73,38 @@ describe('main window coordinator', () => {expect(focusWindow).toHaveBeenCalledTimes(2)})++ it('retries window creation after a failed load', async () => {+ let currentWindow: TestWindow | null = null+ const createWindow = vi+ .fn<() => Promise<void>>()+ .mockRejectedValueOnce(new Error('renderer load failed'))+ .mockImplementationOnce(async () => {+ currentWindow = { isDestroyed: () => false }+ })+ const coordinator = createMainWindowCoordinator<TestWindow>({+ createWindow,+ focusWindow: vi.fn(),+ getWindow: () => currentWindow,+ })++ await expect(coordinator.ensureWindow()).rejects.toThrow('renderer load failed')+ await expect(coordinator.ensureWindow()).resolves.toBeUndefined()+ expect(createWindow).toHaveBeenCalledTimes(2)+ })+})++describe('retryable initializer', () => {+ it('retries failures and never repeats a successful initialization', async () => {+ const initialize = vi+ .fn<() => Promise<void>>()+ .mockRejectedValueOnce(new Error('session restore failed'))+ .mockResolvedValue(undefined)+ const initializer = createRetryableInitializer(initialize)++ await expect(initializer.ensureInitialized()).rejects.toThrow('session restore failed')+ await expect(initializer.ensureInitialized()).resolves.toBeUndefined()+ await expect(initializer.ensureInitialized()).resolves.toBeUndefined()+ expect(initialize).toHaveBeenCalledTimes(2)+ })})diff --git a/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts b/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.tsindex 757296990..29856ad24 100644--- a/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts@@ -27,12 +27,12 @@ describe('SandboxUiDeepLinkQueue', () => {expect(queue.list().map(item => item.appRef)).toEqual(['ns/two', 'ns/three'])})- it('moves a repeated unacknowledged target to the newest queue position', () => {+ it('keeps a repeated unacknowledged target in its original FIFO position', () => {const queue = new SandboxUiDeepLinkQueue(3)const first = queue.enqueue({ appRef: 'ns/one' })queue.enqueue({ appRef: 'ns/two' })expect(queue.enqueue({ appRef: 'ns/one' })).toEqual(first)- expect(queue.list().map(item => item.appRef)).toEqual(['ns/two', 'ns/one'])+ expect(queue.list().map(item => item.appRef)).toEqual(['ns/one', 'ns/two'])})})diff --git a/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts b/desktop-app/src/__tests__/sandboxUiDeepLinks.test.tsindex a6cf7f865..a50972a22 100644--- a/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts@@ -8,17 +8,17 @@ import {} from '../sandboxUiDeepLinks.js'describe('sandbox UI deep links', () => {- it('round-trips an app route, query, fragment, and team', () => {+ it('round-trips an app SPA pathname and team', () => {const url = buildSandboxUiDeepLink({recipeNs: 'sandbox-recipes',recipeName: 'agentic-task-board',- path: '/boards/product/tasks/task-42?view=detail#activity',+ path: '/boards/product/tasks/task-42',teamId: 'team-123',})expect(parseSandboxUiDeepLink(url)).toEqual({appRef: 'sandbox-recipes/agentic-task-board',- path: '/boards/product/tasks/task-42?view=detail#activity',+ path: '/boards/product/tasks/task-42',teamId: 'team-123',})})@@ -28,22 +28,22 @@ describe('sandbox UI deep links', () => {buildSandboxUiWebLink('https://profile.example.com', {recipeNs: 'sandbox-recipes',recipeName: 'agentic-task-board',- path: '/tasks/task-42?view=detail#activity',+ path: '/tasks/task-42',teamId: 'team-123',})).toBe('https://profile.example.com/open/apps/sandbox-recipes/agentic-task-board' +- '?path=%2Ftasks%2Ftask-42%3Fview%3Ddetail%23activity&team=team-123'+ '?path=%2Ftasks%2Ftask-42&team=team-123')})- it('preserves a profile UI base-path prefix', () => {- expect(+ it('rejects a Profile UI base URL with a non-root path', () => {+ expect(() =>buildSandboxUiWebLink('https://tenant.example.com/profile/', {recipeNs: 'sandbox-recipes',recipeName: 'agentic-task-board',})- ).toBe('https://tenant.example.com/profile/open/apps/sandbox-recipes/agentic-task-board')+ ).toThrow('Cannot create a shareable link')})it('keeps an omitted path optional so the recipe default route wins', () => {@@ -93,13 +93,23 @@ describe('sandbox UI deep links', () => {'evenfire://app/sandbox-recipes/agentic-task-board?path=%2Fsafe%2F%252e%252e%2Fadmin')).toBeNull()+ expect(+ parseSandboxUiDeepLink(+ 'evenfire://app/sandbox-recipes/agentic-task-board?path=%2Ftasks%3Ftoken%3Dsecret'+ )+ ).toBeNull()+ expect(+ parseSandboxUiDeepLink(+ 'evenfire://app/sandbox-recipes/agentic-task-board?path=%2Ftasks%23secret'+ )+ ).toBeNull()expect(parseSandboxUiDeepLink('evenfire://app/sandbox-recipes/agentic-task-board/')).toBeNull()expect(parseSandboxUiDeepLink('evenfire://app:444/sandbox-recipes/agentic-task-board')).toBeNull()})- it('extracts the current route without copying a potentially sensitive fragment', () => {+ it('extracts only the current pathname without copying query or fragment state', () => {expect(extractSandboxUiViewRoute({currentUrl:@@ -109,7 +119,13 @@ describe('sandbox UI deep links', () => {recipeNs: 'sandbox-recipes',recipeName: 'agentic-task-board',})- ).toBe('/tasks/task-42?panel=comments')+ ).toBe('/tasks/task-42')+ })++ it('accepts the deep-link host case-insensitively', () => {+ expect(parseSandboxUiDeepLink('evenfire://APP/sandbox-recipes/agentic-task-board')).toEqual({+ appRef: 'sandbox-recipes/agentic-task-board',+ })})it('does not extract routes from another origin or recipe', () => {diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.tsindex 1250efdc0..0523ddc56 100644--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts@@ -9,6 +9,7 @@ import {partitionFor,reloadSandboxUiWebContents,resolveSandboxUiDefaultPath,+ resolveSandboxUiSharePath,} from '../sandboxUiDriver.js'describe('applySandboxUiClientRoute', () => {@@ -40,7 +41,7 @@ describe('applySandboxUiClientRoute', () => {})describe('canApplySandboxUiClientRoute', () => {- const allowedNavigationPrefix = 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/'+ const allowedNavigationPrefix = 'https://rpc.example/api/v1/sandbox-ui/ns/app/view'it('waits through a 503 interstitial before handing off the client route', () => {expect(@@ -57,8 +58,8 @@ describe('canApplySandboxUiClientRoute', () => {expect(canApplySandboxUiClientRoute({allowedNavigationPrefix,- currentUrl: `${allowedNavigationPrefix}a%20b`,- navigatedUrl: `${allowedNavigationPrefix}index.html`,+ currentUrl: `${allowedNavigationPrefix}/a%20b`,+ navigatedUrl: `${allowedNavigationPrefix}/index.html`,httpResponseCode: 200,})).toBe(true)@@ -78,11 +79,35 @@ describe('sandbox UI route normalization', () => {expect(isSandboxUiNavigationWithinPrefix('https://rpc.example/api/v1/sandbox-ui/ns/app/view/a%20b',- 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/'+ 'https://rpc.example/api/v1/sandbox-ui/ns/app/view')).toBe(true)})+ it('omits the default route and rejects an unreadable active app URL when sharing', () => {+ const input = {+ currentUrl: 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/tasks',+ rpcProxyOrigin: 'https://rpc.example',+ recipeNs: 'ns',+ recipeName: 'app',+ defaultPath: '/tasks',+ }+ expect(resolveSandboxUiSharePath(input)).toBeUndefined()+ expect(() =>+ resolveSandboxUiSharePath({+ ...input,+ currentUrl: 'https://outside.example/api/v1/sandbox-ui/ns/app/view/tasks',+ })+ ).toThrow('Cannot read the current app route')+ })++ it('treats the bare view endpoint and nested routes as the same boundary', () => {+ const prefix = 'https://rpc.example/api/v1/sandbox-ui/ns/app/view'+ expect(isSandboxUiNavigationWithinPrefix(prefix, prefix)).toBe(true)+ expect(isSandboxUiNavigationWithinPrefix(`${prefix}/tasks`, prefix)).toBe(true)+ expect(isSandboxUiNavigationWithinPrefix(`${prefix}-other`, prefix)).toBe(false)+ })+it('uses valid defaults and warns before falling back from an invalid default', () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)expect(resolveSandboxUiDefaultPath('/accounts')).toBe('/accounts')diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 9dc359919..ac92e2930 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -730,8 +730,13 @@ export class AppService {try {const activation =await this.memberRegistrationServiceClient.getInvitationProfile(normalizedEmail)- const profileUiBaseUrl =- String(activation.profileUiBaseUrl || '').trim() || config.desktopProfileUiBaseUrl+ const profileUiBaseUrl = String(activation.profileUiBaseUrl || '').trim()+ if (!profileUiBaseUrl) {+ if (!fallbackOnLookupError) {+ throw new Error('the invitation profile did not provide a Profile UI URL')+ }+ return config.desktopProfileUiBaseUrl+ }this.profileUiBaseUrlCache = { key: cacheKey, value: profileUiBaseUrl }return profileUiBaseUrl} catch (error) {diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.tsindex d331f69b3..4fc77f26b 100644--- a/desktop-app/src/main.ts+++ b/desktop-app/src/main.ts@@ -3,10 +3,11 @@ 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 { createMainWindowCoordinator, createRetryableInitializer } from './mainWindowCoordinator.js'import { collectInitialProtocolUrls } from './protocolLaunchArgs.js'import { SandboxUiDeepLinkQueue } from './sandboxUiDeepLinkQueue.js'import {+ CLERUM_OAUTH_PROTOCOL,SANDBOX_UI_DEEP_LINK_HOST,SANDBOX_UI_DEEP_LINK_PROTOCOL,parseSandboxUiDeepLink,@@ -27,9 +28,18 @@ process.stderr?.on?.('error', () => {})let mainWindow: BrowserWindow | null = nullconst appService = new AppService()const pendingEvenfireUrls: string[] = []+const MAX_PENDING_EVENFIRE_URLS = 20const sandboxUiDeepLinkQueue = new SandboxUiDeepLinkQueue()let mainWindowLifecycleReady = falselet mainWindowRendererReady = false+const appServiceInitializer = createRetryableInitializer(() => appService.initialize())++function enqueuePendingEvenfireUrl(rawUrl: string): void {+ pendingEvenfireUrls.push(rawUrl)+ if (pendingEvenfireUrls.length > MAX_PENDING_EVENFIRE_URLS) {+ pendingEvenfireUrls.shift()+ }+}function systemIconAssetsDirectory(): string {return app.isPackaged ? process.resourcesPath : path.join(__dirname, '../assets')@@ -121,7 +131,7 @@ ipcMain.handle('sandboxUi:acknowledgeDeepLink', (event, payload: { id?: unknownsandboxUiDeepLinkQueue.acknowledge(id)})const DESKTOP_SETUP_PROTOCOL = SANDBOX_UI_DEEP_LINK_PROTOCOL.replace(/:$/, '')-const CLERUM_PROTOCOL = 'clerum'+const CLERUM_PROTOCOL = CLERUM_OAUTH_PROTOCOL.replace(/:$/, '')function focusMainWindow(): void {if (!mainWindow || mainWindow.isDestroyed()) return@@ -183,12 +193,13 @@ function handleEvenfireUrl(rawUrl: string): void {return}- if (parsed.hostname === SANDBOX_UI_DEEP_LINK_HOST) {+ const hostname = parsed.hostname.toLowerCase()+ if (hostname === SANDBOX_UI_DEEP_LINK_HOST) {if (!handleSandboxUiDeepLink(rawUrl)) requestMainWindow()return}- if (parsed.hostname === 'logout') {+ if (hostname === 'logout') {void appService.logout().finally(() => {if (mainWindow && !mainWindow.isDestroyed()) {if (mainWindow.isMinimized()) mainWindow.restore()@@ -200,7 +211,7 @@ function handleEvenfireUrl(rawUrl: string): void {return}- if (parsed.hostname === 'desktop-environment') {+ if (hostname === 'desktop-environment') {const externalRestApiBaseUrl = parsed.searchParams.get('externalRestApiBaseUrl') || ''const appName =parsed.searchParams.get('tenantName') || parsed.searchParams.get('appName') || ''@@ -213,13 +224,13 @@ function handleEvenfireUrl(rawUrl: string): void {appName,})} else {- pendingEvenfireUrls.push(rawUrl)+ enqueuePendingEvenfireUrl(rawUrl)requestMainWindow()}return}- if (parsed.hostname !== 'desktop-setup') return+ if (hostname !== 'desktop-setup') returnconst email = parsed.searchParams.get('email') || ''const authorizationToken = parsed.searchParams.get('authorizationToken') || ''@@ -229,17 +240,15 @@ function handleEvenfireUrl(rawUrl: string): void {focusMainWindow()mainWindow.webContents.send('auth:desktopSetupToken', { email, authorizationToken })} else {- pendingEvenfireUrls.push(rawUrl)+ enqueuePendingEvenfireUrl(rawUrl)requestMainWindow()}}function drainPendingEvenfireUrls(): void {if (!mainWindowRendererReady) return- while (pendingEvenfireUrls.length > 0) {- const pendingUrl = pendingEvenfireUrls.shift()- if (pendingUrl) handleEvenfireUrl(pendingUrl)- }+ const pendingBatch = pendingEvenfireUrls.splice(0)+ pendingBatch.forEach(handleEvenfireUrl)}/**@@ -259,7 +268,7 @@ function handleClerumUrl(rawUrl: string): void {return}if (parsed.protocol !== `${CLERUM_PROTOCOL}:`) return- if (parsed.hostname !== 'oauth-completed') return+ if (parsed.hostname.toLowerCase() !== 'oauth-completed') returnconst oauthClientId = parsed.searchParams.get('clientId') || ''const provider = parsed.searchParams.get('provider') || ''@@ -297,6 +306,14 @@ app.on('open-url', (event, rawUrl) => {})async function createWindow(): Promise<void> {+ try {+ // Initialization is process-scoped. A failed attempt remains retryable when+ // the user recreates the window, while a successful attempt is never repeated.+ await appServiceInitializer.ensureInitialized()+ } catch (error) {+ console.error('[Desktop] Could not initialize the desktop session:', error)+ }+const devUrl = String(process.env.EVENFIRE_RENDERER_URL || '').trim()const window = new BrowserWindow({@@ -338,11 +355,20 @@ async function createWindow(): Promise<void> {}})- if (devUrl) {- await window.loadURL(devUrl)- } else {- const htmlPath = path.join(__dirname, '../ui-dist/index.html')- await window.loadFile(htmlPath)+ try {+ if (devUrl) {+ await window.loadURL(devUrl)+ } else {+ const htmlPath = path.join(__dirname, '../ui-dist/index.html')+ await window.loadFile(htmlPath)+ }+ } catch (error) {+ if (mainWindow === window) {+ mainWindow = null+ mainWindowRendererReady = false+ }+ if (!window.isDestroyed()) window.destroy()+ throw error}// Open maximized by default; users can manually resize afterward.window.maximize()@@ -361,31 +387,22 @@ if (gotSingleInstanceLock) {.then(async () => {wireAdaptiveSystemIcon()registerIpcHandlers(appService)- // Window creation must remain recoverable even if session restoration fails.mainWindowLifecycleReady = true- try {- // 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()- } catch (error) {- console.error('[Desktop] Could not initialize the desktop session:', error)- }+ wirePowerMonitor()+ app.on('activate', () => {+ if (BrowserWindow.getAllWindows().length === 0) {+ requestMainWindow()+ }+ })// Collect startup argv once. The renderer-ready handshake drains queued// Evenfire URLs after its listeners are installed; rescanning argv would// dispatch setup links twice on Windows/Linux.const initialProtocolUrls = collectInitialProtocolUrls(process.argv)- pendingEvenfireUrls.push(...initialProtocolUrls.evenfireUrls)+ initialProtocolUrls.evenfireUrls.forEach(enqueuePendingEvenfireUrl)await mainWindowCoordinator.ensureWindow()if (process.platform !== 'darwin') {initialProtocolUrls.clerumUrls.forEach(handleClerumUrl)}- wirePowerMonitor()-- app.on('activate', async () => {- if (BrowserWindow.getAllWindows().length === 0) {- await mainWindowCoordinator.ensureWindow()- }- })}).catch(error => {mainWindowLifecycleReady = app.isReady()diff --git a/desktop-app/src/mainWindowCoordinator.ts b/desktop-app/src/mainWindowCoordinator.tsindex 83dce9545..bcd6e8b7b 100644--- a/desktop-app/src/mainWindowCoordinator.ts+++ b/desktop-app/src/mainWindowCoordinator.ts@@ -32,3 +32,24 @@ export function createMainWindowCoordinator<TWindow extends MainWindowHandle>(return { ensureWindow }}++export function createRetryableInitializer(initialize: () => Promise<unknown>) {+ let initialized = false+ let initializationPromise: Promise<void> | null = null++ const ensureInitialized = async (): Promise<void> => {+ if (initialized) return+ if (!initializationPromise) {+ initializationPromise = initialize()+ .then(() => {+ initialized = true+ })+ .finally(() => {+ initializationPromise = null+ })+ }+ await initializationPromise+ }++ return { ensureInitialized }+}diff --git a/desktop-app/src/protocolLaunchArgs.ts b/desktop-app/src/protocolLaunchArgs.tsindex 3914abea3..8f9e6da5b 100644--- a/desktop-app/src/protocolLaunchArgs.ts+++ b/desktop-app/src/protocolLaunchArgs.ts@@ -1,3 +1,5 @@+import { CLERUM_OAUTH_PROTOCOL, SANDBOX_UI_DEEP_LINK_PROTOCOL } from '@clerum/desktop-app-links'+export type InitialProtocolUrls = {evenfireUrls: string[]clerumUrls: string[]@@ -5,7 +7,9 @@ export type InitialProtocolUrls = {export function collectInitialProtocolUrls(argv: string[]): InitialProtocolUrls {return {- evenfireUrls: [...new Set(argv.filter(argument => argument.startsWith('evenfire:')))],- clerumUrls: [...new Set(argv.filter(argument => argument.startsWith('clerum:')))],+ evenfireUrls: [+ ...new Set(argv.filter(argument => argument.startsWith(SANDBOX_UI_DEEP_LINK_PROTOCOL))),+ ],+ clerumUrls: [...new Set(argv.filter(argument => argument.startsWith(CLERUM_OAUTH_PROTOCOL)))],}}diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex d01ecb18d..4127edb02 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -1,3 +1,4 @@+import type { SandboxUiApp } from './rpcProxyClient.js'import type { SandboxUiDeepLinkEnvelope } from './sandboxUiDeepLinks.js'import {AccessCatalog,@@ -534,16 +535,7 @@ declare global {}sandboxUi: {listApps: () => Promise<{- apps: Array<{- appRef: string- title?: string- description?: string- icon?: string- defaultPath: string- ready: boolean- phase: string | null- updatedAt: string | null- }>+ apps: SandboxUiApp[]}>mintSession: (recipeNs: string, recipeName: string) => Promise<{ setCookie: string }>open: (args: {diff --git a/desktop-app/src/sandboxUiDeepLinkQueue.ts b/desktop-app/src/sandboxUiDeepLinkQueue.tsindex a9cc18bc5..3e63b67d0 100644--- a/desktop-app/src/sandboxUiDeepLinkQueue.ts+++ b/desktop-app/src/sandboxUiDeepLinkQueue.ts@@ -16,9 +16,7 @@ export class SandboxUiDeepLinkQueue {sandboxUiDeepLinkTargetsEqual(item, target))if (existingIndex >= 0) {- const [existing] = this.pending.splice(existingIndex, 1)- this.pending.push(existing!)- return existing!+ return this.pending[existingIndex]!}const envelope = { id: (this.sequence += 1), ...target }this.pending.push(envelope)diff --git a/desktop-app/src/sandboxUiDeepLinks.ts b/desktop-app/src/sandboxUiDeepLinks.tsindex 199d50671..932bc5daf 100644--- a/desktop-app/src/sandboxUiDeepLinks.ts+++ b/desktop-app/src/sandboxUiDeepLinks.ts@@ -1,6 +1,7 @@import { normalizeSandboxUiRoute } from '@clerum/desktop-app-links'export {+ CLERUM_OAUTH_PROTOCOL,SANDBOX_UI_DEEP_LINK_HOST,SANDBOX_UI_DEEP_LINK_PROTOCOL,SANDBOX_UI_WEB_LINK_PATH,@@ -40,7 +41,7 @@ export function extractSandboxUiViewRoute(input: SandboxUiViewRouteInput): strinif (current.pathname !== prefix && !current.pathname.startsWith(`${prefix}/`)) return nullconst pathname = current.pathname.slice(prefix.length) || '/'- // Fragments commonly contain ephemeral OAuth/access tokens and never reach- // the server. Do not copy them into a public Profile UI handoff URL.- return normalizeSandboxUiRoute(`${pathname}${current.search}`) ?? null+ // Shared app links carry only an SPA pathname. Queries and fragments can hold+ // OAuth codes or other ephemeral state and must not leave the local embed.+ return normalizeSandboxUiRoute(pathname) ?? null}diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.tsindex c1a8add24..41ace47b6 100644--- a/desktop-app/src/sandboxUiDriver.ts+++ b/desktop-app/src/sandboxUiDriver.ts@@ -94,7 +94,7 @@ type ActiveView = {view: WebContentsViewrecipeNs: stringrecipeName: string- initialPath: string+ defaultPath: stringpartition: stringparentWindow: BrowserWindowrpcProxyOrigin: string@@ -120,23 +120,36 @@ export function getActiveSandboxUi(): {export function getActiveSandboxUiLocation(): {recipeNs: stringrecipeName: string- path: string+ path?: string} | null {if (!active) return nullif (active.view.webContents.isDestroyed()) return null- const currentPath = extractSandboxUiViewRoute({+ const path = resolveSandboxUiSharePath({currentUrl: active.view.webContents.getURL(),rpcProxyOrigin: active.rpcProxyOrigin,recipeNs: active.recipeNs,recipeName: active.recipeName,+ defaultPath: active.defaultPath,})return {recipeNs: active.recipeNs,recipeName: active.recipeName,- path: currentPath ?? active.initialPath,+ ...(path ? { path } : {}),}}+export function resolveSandboxUiSharePath(input: {+ currentUrl: string+ rpcProxyOrigin: string+ recipeNs: string+ recipeName: string+ defaultPath: string+}): string | undefined {+ const currentPath = extractSandboxUiViewRoute(input)+ if (currentPath === null) throw new Error('Cannot read the current app route')+ return currentPath === input.defaultPath ? undefined : currentPath+}+export function partitionFor(envKey: string, recipeNs: string, recipeName: string): string {// Per-(environment, recipe) partition — Chromium isolates storage (cookies,// IndexedDB, localStorage, service workers) by partition. `envKey` (spec §5.2)@@ -288,7 +301,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidconst clientRoutePath = normalizeSandboxUiRoute(routePath || '')const allowedNavigationPrefix =`${proxyOriginUrl}/api/v1/sandbox-ui/` +- `${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view/`+ `${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view`// Install the session cookie BEFORE creating the view so the very first// navigation request carries it. The proxy enforces the recipe binding@@ -355,7 +368,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<voidview,recipeNs,recipeName,- initialPath: clientRoutePath || viewPath,+ defaultPath: viewPath,partition,parentWindow,rpcProxyOrigin: proxyOriginUrl,@@ -476,12 +489,6 @@ export async function applySandboxUiClientRoute(if (new URL(previousUrl).href === targetUrl) return true;window.history.replaceState(window.history.state, '', targetUrl);window.dispatchEvent(new PopStateEvent('popstate', { state: window.history.state }));- if (new URL(previousUrl).hash !== new URL(targetUrl).hash) {- window.dispatchEvent(new HashChangeEvent('hashchange', {- oldURL: previousUrl,- newURL: targetUrl,- }));- }return new URL(window.location.href).href === targetUrl;})()`))@@ -501,7 +508,13 @@ export function isSandboxUiNavigationWithinPrefix(allowedNavigationPrefix: string): boolean {try {- return new URL(navigationUrl).href.startsWith(new URL(allowedNavigationPrefix).href)+ const navigation = new URL(navigationUrl)+ const allowed = new URL(allowedNavigationPrefix)+ return (+ navigation.origin === allowed.origin &&+ (navigation.pathname === allowed.pathname ||+ navigation.pathname.startsWith(`${allowed.pathname}/`))+ )} catch {return false}diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsxindex 9eba8d708..f9c943097 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -278,26 +278,39 @@ export function App() {const handleSandboxUiBackToConversation = React.useCallback(async () => {if (!sandboxUiConversationOrigin) returnconst origin = sandboxUiConversationOrigin+ let refreshWarning: string | null = nulltry {- if (origin.teamId && origin.teamId !== vm.currentTeamId) {+ if (origin.teamId && origin.teamId !== vm.getCurrentTeamId()) {await vm.handleEnsureTeamContext({ teamId: origin.teamId })}- setActiveSandboxUiApp(null)- setSandboxUiConversationOrigin(null)- setHeaderShellOverlayOpen(false)- setSidebarSettingsMenuOpen(false)- vm.handleSelectChatAgent(origin.agentName, {- selectLatest: false,- chatId: origin.chatId,- title: origin.title,- })} catch (err) {const message = err instanceof Error ? err.message : String(err)- vm.pushToast(`Could not return to the conversation: ${message}`, 'error')+ if (!origin.teamId || vm.getCurrentTeamId() !== origin.teamId) {+ vm.pushToast(`Could not return to the conversation: ${message}`, 'error')+ throw err+ }+ // The authoritative switch completed but its follow-up refresh failed.+ // Keep the page aligned with the live team and surface the refresh problem.+ refreshWarning = message+ }+ setActiveSandboxUiApp(null)+ setSandboxUiConversationOrigin(null)+ setHeaderShellOverlayOpen(false)+ setSidebarSettingsMenuOpen(false)+ vm.handleSelectChatAgent(origin.agentName, {+ selectLatest: false,+ chatId: origin.chatId,+ title: origin.title,+ })+ if (refreshWarning) {+ vm.pushToast(+ `Returned to the conversation, but team data did not refresh: ${refreshWarning}`,+ 'warn'+ )}}, [sandboxUiConversationOrigin,- vm.currentTeamId,+ vm.getCurrentTeamId,vm.handleEnsureTeamContext,vm.handleSelectChatAgent,vm.pushToast,@@ -380,29 +393,28 @@ export function App() {return}const pending = pendingSandboxUiDeepLinksRef.current[0]- if (- pending?.link.teamId &&- pending.link.teamId !== vm.currentTeamId &&- !vm.teamDirectoryHydrated- ) {- return- }if (!pending || processingSandboxUiDeepLinkIdRef.current !== null) returnprocessingSandboxUiDeepLinkIdRef.current = pending.link.idconst processingGeneration = sandboxUiDeepLinkGenerationRef.currentvoid (async () => {- const originalTeamId = vm.currentTeamId+ const originalTeamId = vm.getCurrentTeamId()let switchedTeam = falselet openedApp = falsetry {if (processingGeneration !== sandboxUiDeepLinkGenerationRef.current) return- if (pending.link.teamId && pending.link.teamId !== vm.currentTeamId) {- if (!vm.availableTeamIds.includes(pending.link.teamId)) {- throw new Error("You don't have access to the linked team")+ if (pending.link.teamId && pending.link.teamId !== vm.getCurrentTeamId()) {+ try {+ switchedTeam = await vm.handleEnsureTeamContext({+ teamId: pending.link.teamId,+ announce: true,+ })+ } catch (error) {+ switchedTeam =+ originalTeamId !== pending.link.teamId &&+ vm.getCurrentTeamId() === pending.link.teamId+ throw error}- await vm.handleEnsureTeamContext({ teamId: pending.link.teamId, announce: true })- switchedTeam = true}if (processingGeneration !== sandboxUiDeepLinkGenerationRef.current) returnconst result = await window.clerum.sandboxUi.listApps()@@ -436,6 +448,7 @@ export function App() {!openedApp &&switchedTeam &&originalTeamId &&+ vm.getCurrentTeamId() === pending.link.teamId &&processingGeneration === sandboxUiDeepLinkGenerationRef.current) {try {@@ -478,13 +491,11 @@ export function App() {bootSplashLoading,launchSandboxUiApp,pendingSandboxUiDeepLinks,- vm.availableTeamIds,- vm.currentTeamId,+ vm.getCurrentTeamId,vm.handleEnsureTeamContext,vm.handleSelectChatAgent,vm.isAuthenticated,vm.pushToast,- vm.teamDirectoryHydrated,sandboxUiConversationOrigin,])diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsxindex b0fd18372..2b2e9bd70 100644--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx@@ -37,6 +37,13 @@ type AppController = ReturnType<typeof useAppController>function makeController(overrides: Partial<AppController> = {}): AppController {const noop = vi.fn()+ let liveTeamId = String(overrides.currentTeamId || 'team-a')+ const ensureTeamContext = vi.fn(async (target: { teamId?: string }): Promise<boolean> => {+ const targetTeamId = String(target.teamId || '').trim()+ if (!targetTeamId || targetTeamId === liveTeamId) return false+ liveTeamId = targetTeamId+ return true+ })return {booting: false,initialExperienceLoading: true,@@ -86,7 +93,8 @@ function makeController(overrides: Partial<AppController> = {}): AppController {showRuntimeConfigSelector: false,runtimeConfigMissing: false,authTransitioning: false,- handleEnsureTeamContext: vi.fn(),+ handleEnsureTeamContext: ensureTeamContext,+ getCurrentTeamId: vi.fn(() => liveTeamId),handleSelectChatAgent: vi.fn(),handleNavSelect: vi.fn(),pushToast: vi.fn(),@@ -230,6 +238,78 @@ describe('App deep-link orchestration', () => {)})+ it('lets the server authorize a linked team even when the local directory is empty', async () => {+ currentController = makeController({+ initialExperienceLoading: false,+ availableTeamIds: [],+ teamDirectoryHydrated: false,+ })+ listApps.mockResolvedValue({+ apps: [+ {+ appRef: 'ns/app',+ title: 'App',+ defaultPath: '/',+ ready: true,+ phase: 'active',+ updatedAt: null,+ },+ ],+ })+ render(<App />)+ await waitFor(() => expect(emitDeepLink).not.toBeNull())++ act(() => {+ emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })+ })++ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))+ expect(currentController.handleEnsureTeamContext).toHaveBeenCalledWith({+ teamId: 'team-b',+ announce: true,+ })+ expect(currentController.pushToast).not.toHaveBeenCalledWith(+ expect.stringContaining("don't have access to the linked team"),+ 'error'+ )+ })++ it('does not roll back a team the user selected while a linked app was loading', async () => {+ let liveTeamId = 'team-a'+ const ensureTeamContext = vi.fn(async ({ teamId }: { teamId?: string }) => {+ if (!teamId || teamId === liveTeamId) return false+ liveTeamId = teamId+ return true+ })+ let resolveApps!: (value: { apps: [] }) => void+ listApps.mockResolvedValueOnce({ apps: [] }).mockImplementationOnce(+ () =>+ new Promise(resolve => {+ resolveApps = resolve+ })+ )+ currentController = makeController({+ initialExperienceLoading: false,+ handleEnsureTeamContext: ensureTeamContext,+ getCurrentTeamId: () => liveTeamId,+ })+ render(<App />)+ await waitFor(() => expect(emitDeepLink).not.toBeNull())++ act(() => {+ emitDeepLink?.({ id: 1, appRef: 'ns/missing', teamId: 'team-b' })+ })+ await waitFor(() => expect(ensureTeamContext).toHaveBeenCalledTimes(1))+ liveTeamId = 'team-c'+ await act(async () => {+ resolveApps({ apps: [] })+ })+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))++ expect(ensureTeamContext).toHaveBeenCalledTimes(1)+ expect(liveTeamId).toBe('team-c')+ })+it('contains a synchronously throwing acknowledgement bridge', async () => {const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)currentController = makeController({ initialExperienceLoading: false })diff --git a/desktop-app/ui/src/global.d.ts b/desktop-app/ui/src/global.d.tsindex b163ddef6..e2be24b80 100644--- a/desktop-app/ui/src/global.d.ts+++ b/desktop-app/ui/src/global.d.ts@@ -6,17 +6,6 @@declare global {const __DESKTOP_APP_VERSION__: string-- interface SandboxUiApp {- appRef: string- title?: string- description?: string- icon?: string- defaultPath: string- ready: boolean- phase: string | null- updatedAt: string | null- }}/**diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex e58aca56f..32574b52a 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -529,22 +529,26 @@ export function useAppController() {)const ensureTeamContext = useCallback(- async (target: { teamId?: string; announce?: boolean }) => {+ async (target: { teamId?: string; announce?: boolean }): Promise<boolean> => {const targetTeamId = String(target.teamId || '').trim()- if (!targetTeamId) return+ if (!targetTeamId) return falseconst queuedSwitch = notificationTeamContextQueueRef.current.then(async () => {const activeTeamId = currentTeamIdRef.current- if (targetTeamId === activeTeamId) return+ if (targetTeamId === activeTeamId) return false- chat.clearActiveChat()await switchTeamForWorkspace(targetTeamId, { announce: target.announce ?? false })+ return true})- notificationTeamContextQueueRef.current = queuedSwitch.catch(() => undefined)- await queuedSwitch+ notificationTeamContextQueueRef.current = queuedSwitch.then(+ () => undefined,+ () => undefined+ )+ return queuedSwitch},- [chat.clearActiveChat, switchTeamForWorkspace]+ [switchTeamForWorkspace])+ const getCurrentTeamId = useCallback(() => currentTeamIdRef.current, [])const decideApprovalNotificationTarget = useCallback(async (target: AgentApprovalNotificationTarget) => {@@ -1095,6 +1099,7 @@ export function useAppController() {handleOpenAgentWorkspace,handleSelectChatAgent,handleEnsureTeamContext: ensureTeamContext,+ getCurrentTeamId,handleBackToAgents: nav.handleBackToAgents,handleOpenContextDetails: nav.handleOpenContextDetails,handleBackToContexts: nav.handleBackToContexts,diff --git a/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts b/desktop-app/ui/src/lib/sandboxUiAppSelection.types.tsindex 2707811b9..346799d8c 100644--- a/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts+++ b/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts@@ -1,15 +1,7 @@import type { ActiveSandboxUiApp } from '@/uiTypes'+import type { SandboxUiApp } from '../../../src/rpcProxyClient'-export type SandboxUiAppListing = {- appRef: string- title?: string- description?: string- icon?: string- defaultPath: string- ready: boolean- phase?: string | null- updatedAt?: string | null-}+export type SandboxUiAppListing = SandboxUiAppexport type SandboxUiDeepLinkAppResolution =| { status: 'ready'; app: ActiveSandboxUiApp }diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsxindex f47100b1c..74a47f86a 100644--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx@@ -303,8 +303,13 @@ export function SandboxUiPage({const handleBackToConversation = useCallback(async () => {if (!conversationOrigin || !onBackToConversation) return- await onBackToConversation()- await closeEmbed()+ try {+ await onBackToConversation()+ await closeEmbed()+ } catch {+ // The owner keeps the embedded app open and reports the failed team or+ // conversation transition without leaving the two views inconsistent.+ }}, [closeEmbed, conversationOrigin, onBackToConversation])// In-place hard-reload of the embedded app — fetches freshly-arriveddiff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsxindex 8e3aebfcd..603ca052d 100644--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx@@ -175,7 +175,7 @@ describe('SandboxUiPage', () => {appRef: 'sandbox-recipes/task-board',label: 'Agentic Task Board',defaultPath: '/',- routePath: '/tasks/task-42?panel=details',+ routePath: '/tasks/task-42',}}shortcutOpenRequestId={1}onEmbeddedAppOpening={onEmbeddedAppOpening}@@ -187,7 +187,7 @@ describe('SandboxUiPage', () => {recipeNs: 'sandbox-recipes',recipeName: 'task-board',defaultPath: '/',- routePath: '/tasks/task-42?panel=details',+ routePath: '/tasks/task-42',bounds: {x: 16,y: 12,@@ -201,7 +201,7 @@ describe('SandboxUiPage', () => {appRef: 'sandbox-recipes/task-board',label: 'Agentic Task Board',defaultPath: '/',- routePath: '/tasks/task-42?panel=details',+ routePath: '/tasks/task-42',})})@@ -242,6 +242,42 @@ describe('SandboxUiPage', () => {})})+ it('keeps the app mounted when returning to the conversation fails', async () => {+ sandboxUi.listApps.mockResolvedValueOnce({+ apps: [+ {+ appRef: 'sandbox-recipes/sales-crm',+ title: "Andy's Sales CRM",+ defaultPath: '/',+ ready: true,+ phase: 'active',+ updatedAt: null,+ },+ ],+ })+ sandboxUi.open.mockResolvedValueOnce(undefined)+ const onBackToConversation = vi.fn().mockRejectedValue(new Error('team switch failed'))++ render(+ <SandboxUiPage+ conversationOrigin={{+ agentName: 'sales-agent',+ chatId: 'chat-123',+ title: 'Quarterly planning',+ teamId: 'team-b',+ }}+ onBackToConversation={onBackToConversation}+ />+ )++ fireEvent.click(await screen.findByRole('button', { name: "Open Andy's Sales CRM" }))+ fireEvent.click(await screen.findByRole('button', { name: 'Back to Quarterly planning' }))++ await waitFor(() => expect(onBackToConversation).toHaveBeenCalledOnce())+ expect(sandboxUi.close).not.toHaveBeenCalled()+ expect(screen.getByRole('button', { name: 'Back to apps' })).toBeTruthy()+ })+it('keeps the conversation origin during Strict Mode effect replay', async () => {sandboxUi.listApps.mockResolvedValue({apps: [diff --git a/packages/desktop-app-links/README.md b/packages/desktop-app-links/README.mdnew file mode 100644index 000000000..4ef44e3b5--- /dev/null+++ b/packages/desktop-app-links/README.md@@ -0,0 +1,18 @@+# Desktop app link contract++Evenfire app links identify an accessible Sandbox UI app and may restore a client-side route:++```text+evenfire://app/<recipe-namespace>/<recipe-name>?path=/tasks/42&team=<team-id>+```++The optional `path` is an SPA pathname. The desktop first loads the recipe's configured default+server route, then applies `path` with the browser history API after the app is ready. A shared link+must not depend on the server serving that nested pathname directly.++Queries and fragments are intentionally excluded because they can contain OAuth codes, access+tokens, or other ephemeral browser state. Apps that need durable shared state should encode a+non-sensitive identifier in the pathname and fetch the corresponding data after opening.++Browser handoff links require a root-mounted HTTP(S) Profile UI and use `/open/apps/...`. A Profile+UI deployed below a path prefix is not compatible with this contract.diff --git a/packages/desktop-app-links/index.cjs b/packages/desktop-app-links/index.cjsindex 326808ef7..b51177135 100644--- a/packages/desktop-app-links/index.cjs+++ b/packages/desktop-app-links/index.cjs@@ -2,6 +2,7 @@const SANDBOX_UI_DEEP_LINK_HOST = 'app'const SANDBOX_UI_DEEP_LINK_PROTOCOL = 'evenfire:'+const CLERUM_OAUTH_PROTOCOL = 'clerum:'const SANDBOX_UI_WEB_LINK_PATH = '/open/apps'const MAX_APP_SEGMENT_LENGTH = 253const MAX_APP_ROUTE_LENGTH = 4096@@ -12,11 +13,7 @@ const DOT_SEGMENT_PATTERN = /^(?:\.|%2e){1,2}$/ifunction isValidAppSegment(value) {return (- value.length > 0 &&- value.length <= MAX_APP_SEGMENT_LENGTH &&- APP_SEGMENT_PATTERN.test(value) &&- value !== '.' &&- value !== '..'+ value.length > 0 && value.length <= MAX_APP_SEGMENT_LENGTH && APP_SEGMENT_PATTERN.test(value))}@@ -35,12 +32,13 @@ function normalizeSandboxUiRoute(rawPath) {!routePath.startsWith('/') ||routePath.startsWith('//') ||routePath.includes('\\') ||+ routePath.includes('?') ||+ routePath.includes('#') ||/[\u0000-\u001f\u007f]/.test(routePath)) {return null}- const pathname = routePath.split(/[?#]/, 1)[0]- if (pathname.split('/').some(segment => DOT_SEGMENT_PATTERN.test(segment))) return null+ if (routePath.split('/').some(segment => DOT_SEGMENT_PATTERN.test(segment))) return nullreturn routePath}@@ -84,11 +82,13 @@ function buildSandboxUiWebLink(profileUiBaseUrl, parts) {if (!['http:', 'https:'].includes(baseUrl.protocol) || baseUrl.username || baseUrl.password) {throw new Error('Cannot create a shareable link for this desktop environment')}+ if (baseUrl.pathname !== '/' || baseUrl.search) {+ throw new Error('Cannot create a shareable link for this desktop environment')+ }baseUrl.hash = ''- const basePath = baseUrl.pathname.replace(/\/+$/, '')baseUrl.pathname =- `${basePath}${SANDBOX_UI_WEB_LINK_PATH}/${encodeURIComponent(valid.recipeNs)}/` ++ `${SANDBOX_UI_WEB_LINK_PATH}/${encodeURIComponent(valid.recipeNs)}/` +encodeURIComponent(valid.recipeName)const search = new URLSearchParams()if (valid.path) search.set('path', valid.path)@@ -106,11 +106,14 @@ function parseSandboxUiDeepLink(rawUrl) {}if (parsed.protocol !== SANDBOX_UI_DEEP_LINK_PROTOCOL ||- parsed.hostname !== SANDBOX_UI_DEEP_LINK_HOST ||+ parsed.hostname.toLowerCase() !== SANDBOX_UI_DEEP_LINK_HOST ||parsed.port) {return null}+ // The canonical app target has exactly two path segments. Reject a trailing+ // slash explicitly so producers and consumers cannot disagree on identity.+ if (parsed.pathname.endsWith('/')) return nullconst segments = parsed.pathname.split('/')if (segments.length !== 3 || segments[0] !== '' || !segments[1] || !segments[2]) return null@@ -145,6 +148,7 @@ function sandboxUiDeepLinkTargetsEqual(left, right) {}module.exports = {+ CLERUM_OAUTH_PROTOCOL,SANDBOX_UI_DEEP_LINK_HOST,SANDBOX_UI_DEEP_LINK_PROTOCOL,SANDBOX_UI_WEB_LINK_PATH,diff --git a/packages/desktop-app-links/index.d.ts b/packages/desktop-app-links/index.d.tsindex 308af40bf..8b943e351 100644--- a/packages/desktop-app-links/index.d.ts+++ b/packages/desktop-app-links/index.d.ts@@ -1,3 +1,4 @@+export declare const CLERUM_OAUTH_PROTOCOL: 'clerum:'export declare const SANDBOX_UI_DEEP_LINK_HOST: 'app'export declare const SANDBOX_UI_DEEP_LINK_PROTOCOL: 'evenfire:'export declare const SANDBOX_UI_WEB_LINK_PATH: '/open/apps'@@ -15,6 +16,7 @@ export type SandboxUiDeepLinkEnvelope = SandboxUiDeepLinkTarget & {export type SandboxUiDeepLinkParts = {recipeNs: stringrecipeName: string+ /** Optional client-side SPA pathname. Query strings and fragments are not shared. */path?: stringteamId?: string}diff --git a/packages/desktop-app-links/index.test.cjs b/packages/desktop-app-links/index.test.cjsindex fda4dca2d..9fb3c5a6c 100644--- a/packages/desktop-app-links/index.test.cjs+++ b/packages/desktop-app-links/index.test.cjs@@ -6,7 +6,7 @@ const path = require('node:path')const test = require('node:test')const links = require('./index.cjs')-test('runtime exports stay aligned with the declaration file', () => {+test('runtime exports and constant values stay aligned with the declaration file', () => {const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')const declaredRuntimeExports = Array.from(declarations.matchAll(/export (?:declare )?(?:const|function)\s+([A-Za-z0-9_]+)/g),@@ -14,6 +14,18 @@ test('runtime exports stay aligned with the declaration file', () => {).sort()assert.deepEqual(Object.keys(links).sort(), declaredRuntimeExports)+ assert.equal(links.CLERUM_OAUTH_PROTOCOL, 'clerum:')+ assert.equal(links.SANDBOX_UI_DEEP_LINK_PROTOCOL, 'evenfire:')+ assert.equal(links.SANDBOX_UI_DEEP_LINK_HOST, 'app')+ assert.equal(links.SANDBOX_UI_WEB_LINK_PATH, '/open/apps')+ assert.match(+ declarations,+ /buildSandboxUiWebLink\(\s*profileUiBaseUrl: string,\s*parts: SandboxUiDeepLinkParts\s*\): string/+ )+ assert.match(+ declarations,+ /parseSandboxUiDeepLink\(rawUrl: string\): SandboxUiDeepLinkTarget \| null/+ )})test('web and desktop links use the same canonical route contract', () => {@@ -35,3 +47,53 @@ test('web and desktop links use the same canonical route contract', () => {teamId: 'team-1',})})++test('shared app links carry only client-side pathnames', () => {+ for (const pathValue of [+ '/tasks?authorization=secret',+ '/tasks#access-token',+ '//outside.example',+ '/safe/../admin',+ '/safe/%2e%2e/admin',+ '/safe\\admin',+ ]) {+ assert.throws(+ () =>+ links.buildSandboxUiDeepLink({+ recipeNs: 'sandbox-recipes',+ recipeName: 'task-board',+ path: pathValue,+ }),+ /Cannot create a deep link/+ )+ }+})++test('parser accepts a case-insensitive host and rejects non-canonical targets', () => {+ assert.deepEqual(links.parseSandboxUiDeepLink('evenfire://APP/sandbox-recipes/task-board'), {+ appRef: 'sandbox-recipes/task-board',+ })+ for (const rawUrl of [+ 'evenfire://app/sandbox-recipes/task-board/',+ 'evenfire://app:444/sandbox-recipes/task-board',+ 'evenfire://app/sandbox-recipes/task-board?team=other%2Fteam',+ 'https://profile.example/open/apps/sandbox-recipes/task-board',+ ]) {+ assert.equal(links.parseSandboxUiDeepLink(rawUrl), null)+ }+})++test('web handoffs require a root-mounted HTTP(S) Profile UI', () => {+ const parts = { recipeNs: 'sandbox-recipes', recipeName: 'task-board' }+ for (const baseUrl of [+ 'https://profile.example/settings',+ 'https://profile.example/?token=secret',+ 'https://user:[email protected]/',+ 'javascript:alert(1)',+ ]) {+ assert.throws(+ () => links.buildSandboxUiWebLink(baseUrl, parts),+ /Cannot create a shareable link/+ )+ }+})diff --git a/packages/desktop-app-links/package-lock.json b/packages/desktop-app-links/package-lock.jsonindex c8ca7704f..024ea9312 100644--- a/packages/desktop-app-links/package-lock.json+++ b/packages/desktop-app-links/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/desktop-app-links",- "version": "0.1.1",+ "version": "0.1.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/desktop-app-links",- "version": "0.1.1"+ "version": "0.1.2"}}}diff --git a/packages/desktop-app-links/package.json b/packages/desktop-app-links/package.jsonindex 016bf64fa..c077fa626 100644--- a/packages/desktop-app-links/package.json+++ b/packages/desktop-app-links/package.json@@ -1,6 +1,6 @@{"name": "@clerum/desktop-app-links",- "version": "0.1.1",+ "version": "0.1.2","private": true,"type": "commonjs","main": "index.cjs",diff --git a/profile-ui/app/constants/routes.ts b/profile-ui/app/constants/routes.tsindex 83efd5f86..619ada2c3 100644--- a/profile-ui/app/constants/routes.ts+++ b/profile-ui/app/constants/routes.ts@@ -1,5 +1,3 @@-import { SANDBOX_UI_WEB_LINK_PATH } from '@clerum/desktop-app-links'-type QueryValue = boolean | number | string | null | undefinedtype ProfileRouteQuery = Record<string, QueryValue>@@ -28,7 +26,7 @@ export const PROFILE_ROUTES = {forgotPassword: (query?: ProfileRouteQuery) => withQuery('/forgot-password', query),invitation: (token: string) => `/invitations/${segment(token)}`,openDesktopApp: (recipeNs: string, recipeName: string) =>- `${SANDBOX_UI_WEB_LINK_PATH}/${segment(recipeNs)}/${segment(recipeName)}`,+ `/open/apps/${segment(recipeNs)}/${segment(recipeName)}`,members: {root: '/members',invite: '/members/invite',diff --git a/profile-ui/lib/desktopAppLinks.ts b/profile-ui/lib/desktopAppLinks.tsindex 41db9f555..cf5424740 100644--- a/profile-ui/lib/desktopAppLinks.ts+++ b/profile-ui/lib/desktopAppLinks.ts@@ -64,7 +64,6 @@ export function buildEvenfireDesktopAppRedirectDocument(<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 app in Evenfire</title><style nonce="${nonce}">:root {diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex c219203e7..cadcdf18a 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.109",+ "version": "0.1.110","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.109",+ "version": "0.1.110","dependencies": {"@clerum/desktop-app-links": "file:../packages/desktop-app-links","next": "16.2.11",@@ -22,7 +22,7 @@},"../packages/desktop-app-links": {"name": "@clerum/desktop-app-links",- "version": "0.1.0"+ "version": "0.1.1"},"node_modules/@clerum/desktop-app-links": {"resolved": "../packages/desktop-app-links",diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex d5ce6c1de..6df5c7a3f 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.109",+ "version": "0.1.110","private": true,"scripts": {"dev": "next dev",diff --git a/profile-ui/test/desktopAppLinks.test.ts b/profile-ui/test/desktopAppLinks.test.tsindex bf9bc8a21..5c4672c42 100644--- a/profile-ui/test/desktopAppLinks.test.ts+++ b/profile-ui/test/desktopAppLinks.test.ts@@ -6,16 +6,15 @@ import {buildEvenfireDesktopAppRedirectDocument,} from '../lib/desktopAppLinks'-test('buildEvenfireDesktopAppLink preserves a nested app route and team', () => {+test('buildEvenfireDesktopAppLink preserves a nested app pathname and team', () => {assert.equal(buildEvenfireDesktopAppLink({recipeNs: 'sandbox-recipes',recipeName: 'agentic-task-board',- path: '/tasks/task-42?view=detail#activity',+ path: '/tasks/task-42',teamId: 'team-123',}),- 'evenfire://app/sandbox-recipes/agentic-task-board' +- '?path=%2Ftasks%2Ftask-42%3Fview%3Ddetail%23activity&team=team-123'+ 'evenfire://app/sandbox-recipes/agentic-task-board' + '?path=%2Ftasks%2Ftask-42&team=team-123')})@@ -28,6 +27,14 @@ test('buildEvenfireDesktopAppLink rejects unsafe routes', () => {}),null)+ assert.equal(+ buildEvenfireDesktopAppLink({+ recipeNs: 'sandbox-recipes',+ recipeName: 'agentic-task-board',+ path: '/tasks?authorization=secret',+ }),+ null+ )assert.equal(buildEvenfireDesktopAppLink({recipeNs: 'sandbox-recipes',@@ -54,7 +61,7 @@ test('buildEvenfireDesktopAppRedirectDocument creates an unauthenticated protococonst scriptNonce = 'dGVzdC1ub25jZQ=='const document = buildEvenfireDesktopAppRedirectDocument(deepLink, scriptNonce)- assert.match(document, /http-equiv="refresh"/)+ assert.doesNotMatch(document, /http-equiv="refresh"/)assert.match(document, /window\.location\.replace/)assert.match(document, new RegExp(`<script nonce="${scriptNonce}">`))assert.match(document, /evenfire:\/\/app\/sandbox-recipes\/agentic-task-board/)diff --git a/profile-ui/test/desktopAppRoute.test.ts b/profile-ui/test/desktopAppRoute.test.tsindex f0d5d0bd4..2fa81461c 100644--- a/profile-ui/test/desktopAppRoute.test.ts+++ b/profile-ui/test/desktopAppRoute.test.ts@@ -29,3 +29,12 @@ test('desktop app handoff rejects dot-segment routes with hardened error headersassert.equal(response.headers.get('referrer-policy'), 'no-referrer')assert.equal(response.headers.get('x-content-type-options'), 'nosniff')})++test('desktop app handoff rejects query or fragment data inside the shared app path', async () => {+ const response = await GET(+ new Request('https://profile.example/open/apps/ns/app?path=%2Ftasks%3Fauthorization%3Dsecret'),+ routeContext+ )++ assert.equal(response.status, 400)+})diff --git a/profile-ui/test/invitations.test.ts b/profile-ui/test/invitations.test.tsindex 7a71db0c6..6be4e5a75 100644--- a/profile-ui/test/invitations.test.ts+++ b/profile-ui/test/invitations.test.ts@@ -1,9 +1,6 @@import assert from 'node:assert/strict'import test from 'node:test'import { buildInvitationHeading, formatRemaining, resolveInvitationToken } from '../lib/invitations'-import './approvalChannels.test'-import './profileSettings.test'-import './routes.test'test('formatRemaining returns a human-readable duration', () => {const now = Date.parse('2026-04-20T12:00:00.000Z')diff --git a/profile-ui/test/routes.test.ts b/profile-ui/test/routes.test.tsindex 5d217d304..2d12fdc0a 100644--- a/profile-ui/test/routes.test.ts+++ b/profile-ui/test/routes.test.ts@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'import fs from 'node:fs'import path from 'node:path'import test from 'node:test'+import { SANDBOX_UI_WEB_LINK_PATH } from '@clerum/desktop-app-links'import { PROFILE_ROUTES } from '../app/constants/routes'function collectRoutePaths(value: unknown): string[] {@@ -47,3 +48,10 @@ test('PROFILE_ROUTES resolve to App Router pages or route handlers', () => {assert.deepEqual(unresolved, [])})++test('desktop app route stays aligned with the shared handoff contract', () => {+ assert.equal(+ PROFILE_ROUTES.openDesktopApp('sandbox-recipes', 'task-board'),+ `${SANDBOX_UI_WEB_LINK_PATH}/sandbox-recipes/task-board`+ )+})diff --git a/scripts/prettier/paths.mjs b/scripts/prettier/paths.mjsindex 79a7d6a35..7aaf2c08b 100644--- a/scripts/prettier/paths.mjs+++ b/scripts/prettier/paths.mjs@@ -8,7 +8,6 @@ export const projectRoots = ['mcp-host','mcp-proxy','mcp-servers',- 'packages/desktop-app-links','packages/workflow-sdk','profile-ui','rpc-proxy',