Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix: address latest desktop deep-link review findings

Josuéd0ea20b5a902
diff --git a/.dockerignore b/.dockerignore
index 14d06948b..00931dd92 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -2,11 +2,12 @@
#
# Several images build from the REPO ROOT context (`docker build -f <svc>/Dockerfile .`)
# because they COPY shared packages/ alongside the service: workflow-recipes,
-# control-api, control-ui, host-context-controller, packages/workflow-sdk and
-# (since R4/B2) mcp-host. Docker only honors the .dockerignore at the CONTEXT
-# root, so the per-service .dockerignore files are inert for those builds —
-# this file restores their exclusions globally. Keep it in sync with the
-# per-service files (which still apply to any image built from its own dir).
+# control-api, control-ui, profile-ui, host-context-controller,
+# packages/workflow-sdk and (since R4/B2) mcp-host. Docker only honors the
+# .dockerignore at the CONTEXT root, so the per-service .dockerignore files are
+# inert for those builds — this file restores their exclusions globally. Keep
+# it in sync with the per-service files (which still apply to any image built
+# from its own dir).
#
# SECURITY: without this file the entire monorepo — including real .env files
# and .git history — is shipped to the Docker daemon as build context on every
diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.yml
index c704dcdf9..8ae8db06d 100644
--- a/.github/workflows/build-publish.yml
+++ b/.github/workflows/build-publish.yml
@@ -129,6 +129,7 @@ jobs:
- 'nginx-egress-proxy/**'
profile-ui:
- 'profile-ui/**'
+ - 'packages/desktop-app-links/**'
rpc-proxy:
- 'rpc-proxy/**'
workflow-recipes:
@@ -225,6 +226,7 @@ jobs:
changed: ${{ needs.detect.outputs.nginx-egress-proxy }}
- image: profile-ui
path: profile-ui
+ rooted: true
changed: ${{ needs.detect.outputs.profile-ui }}
- image: rpc-proxy
path: rpc-proxy
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 4a8a8d9bf..ee78bc246 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -63,6 +63,7 @@ jobs:
- profile-ui
- desktop-app
- mcp-servers
+ - packages/desktop-app-links
- packages/workflow-runtime-core
- packages/workflow-sdk
@@ -111,7 +112,7 @@ jobs:
# ~10 pre-existing type errors in its __tests__ — worth fixing, but as its own
# change rather than smuggled into a CI-coverage PR.
- name: Typecheck (tsc --noEmit)
- if: matrix.service != 'mcp-servers'
+ if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links'
working-directory: ${{ matrix.service }}
run: npx tsc --noEmit
diff --git a/Makefile b/Makefile
index 1f69fb365..02a218672 100644
--- a/Makefile
+++ b/Makefile
@@ -44,10 +44,11 @@ SERVICES := \
profile-ui \
desktop-app \
mcp-servers \
+ packages/desktop-app-links \
packages/workflow-runtime-core \
packages/workflow-sdk
-# Services that have unit tests (vitest)
+# Services that have unit tests
TEST_SERVICES := \
workflow-approval-request-reader \
mcp-host \
@@ -63,6 +64,7 @@ TEST_SERVICES := \
profile-ui \
desktop-app \
mcp-servers \
+ packages/desktop-app-links \
packages/workflow-runtime-core \
packages/workflow-sdk
@@ -943,4 +945,3 @@ run-platform-security-gates: ## Execute the revised platform security gate runne
help: ## Show this help
@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-24s\033[0m %s\n", $$1, $$2}'
-
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 3b5bc3517..19564485f 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.327",
+ "version": "0.1.328",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.327",
+ "version": "0.1.328",
"license": "MPL-2.0",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 789db4194..217c398cc 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.327",
+ "version": "0.1.328",
"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.ts
index 5db21e9d9..baa4bbc02 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts
@@ -2,6 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { AppService } from '../appService.js'
import { ApiError } from '../httpClient.js'
+const { mockGetActiveSandboxUiLocation } = vi.hoisted(() => ({
+ mockGetActiveSandboxUiLocation: vi.fn(),
+}))
+
vi.mock('electron', () => ({
app: {
getPath: vi.fn(() => '/tmp/clerum-desktop-test'),
@@ -16,7 +20,12 @@ vi.mock('electron', () => ({
},
}))
+vi.mock('../sandboxUiDriver.js', () => ({
+ getActiveSandboxUiLocation: mockGetActiveSandboxUiLocation,
+}))
+
vi.mock('../config.js', () => ({
+ getActiveEnvKey: () => 'test-env',
config: {
rpcProxyBaseUrl: 'http://proxy',
externalRestApiBaseUrl: 'http://rest',
@@ -185,24 +194,55 @@ describe('AppService.openForgotPassword', () => {
})
describe('AppService profile UI link authority', () => {
- it('uses the authenticated invitation profile instead of guessing a tenant hostname', async () => {
+ it('uses and memoizes the authenticated invitation profile for shareable links', async () => {
const service = makeService() as unknown as {
me: { id: string; email: string }
memberRegistrationServiceClient: { getInvitationProfile: ReturnType<typeof vi.fn> }
resolveProfileUiBaseUrl: () => Promise<string>
+ createSandboxUiDeepLink: (teamId?: string) => Promise<{ url: string }>
}
service.me = { id: 'user-1', email: '[email protected]' }
service.memberRegistrationServiceClient = {
getInvitationProfile: vi.fn().mockResolvedValue({
- profileUiBaseUrl: 'https://accounts.tenant.example/profile',
+ profileUiBaseUrl: 'https://profile.tenant.example',
}),
}
+ mockGetActiveSandboxUiLocation.mockReturnValue({
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'task-board',
+ path: '/tasks/42',
+ })
- await expect(service.resolveProfileUiBaseUrl()).resolves.toBe(
- 'https://accounts.tenant.example/profile'
- )
+ await expect(service.resolveProfileUiBaseUrl()).resolves.toBe('https://profile.tenant.example')
+ await expect(service.createSandboxUiDeepLink('team-1')).resolves.toEqual({
+ url:
+ 'https://profile.tenant.example/open/apps/sandbox-recipes/task-board' +
+ '?path=%2Ftasks%2F42&team=team-1',
+ })
+ expect(service.memberRegistrationServiceClient.getInvitationProfile).toHaveBeenCalledTimes(1)
expect(service.memberRegistrationServiceClient.getInvitationProfile).toHaveBeenCalledWith(
)
})
+
+ it('fails visibly instead of copying a localhost fallback after a lookup error', 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().mockRejectedValue(new Error('network unavailable')),
+ }
+ mockGetActiveSandboxUiLocation.mockReturnValue({
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'task-board',
+ path: '/',
+ })
+
+ await expect(service.createSandboxUiDeepLink()).rejects.toThrow(
+ 'Cannot resolve a shareable Profile UI link'
+ )
+ })
})
diff --git a/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts b/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts
index 3f0401b7c..757296990 100644
--- a/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDeepLinkQueue.test.ts
@@ -5,9 +5,9 @@ describe('SandboxUiDeepLinkQueue', () => {
it('deduplicates semantic targets and acknowledges the matching envelope', () => {
const queue = new SandboxUiDeepLinkQueue()
const first = queue.enqueue({ appRef: 'ns/app', path: '/inbox', teamId: 'team-1' })
- expect(first?.id).toBe(1)
- expect(queue.enqueue({ appRef: 'ns/app', path: '/inbox', teamId: 'team-1' })).toBeNull()
- queue.acknowledge(first!.id)
+ expect(first.id).toBe(1)
+ expect(queue.enqueue({ appRef: 'NS/APP', path: '/inbox', teamId: 'team-1' })).toEqual(first)
+ queue.acknowledge(first.id)
expect(queue.list()).toEqual([])
})
@@ -16,7 +16,7 @@ describe('SandboxUiDeepLinkQueue', () => {
queue.enqueue({ appRef: 'ns/app' })
queue.clear()
expect(queue.list()).toEqual([])
- expect(queue.enqueue({ appRef: 'ns/app' })?.id).toBe(2)
+ expect(queue.enqueue({ appRef: 'ns/app' }).id).toBe(2)
})
it('keeps the newest bounded set of links', () => {
@@ -26,4 +26,13 @@ describe('SandboxUiDeepLinkQueue', () => {
queue.enqueue({ appRef: 'ns/three' })
expect(queue.list().map(item => item.appRef)).toEqual(['ns/two', 'ns/three'])
})
+
+ it('moves a repeated unacknowledged target to the newest queue 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'])
+ })
})
diff --git a/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts b/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts
index 0a5cad45c..a6cf7f865 100644
--- a/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts
@@ -93,9 +93,13 @@ 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/')).toBeNull()
+ expect(
+ parseSandboxUiDeepLink('evenfire://app:444/sandbox-recipes/agentic-task-board')
+ ).toBeNull()
})
- it('extracts the current route from the active embedded app URL', () => {
+ it('extracts the current route without copying a potentially sensitive fragment', () => {
expect(
extractSandboxUiViewRoute({
currentUrl:
@@ -105,7 +109,7 @@ describe('sandbox UI deep links', () => {
recipeNs: 'sandbox-recipes',
recipeName: 'agentic-task-board',
})
- ).toBe('/tasks/task-42?panel=comments#latest')
+ ).toBe('/tasks/task-42?panel=comments')
})
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.ts
index 0a1af9fd8..1250efdc0 100644
--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts
@@ -5,8 +5,10 @@ import {
canApplySandboxUiClientRoute,
extractSandboxUiCookie,
extractSandboxUiPath,
+ isSandboxUiNavigationWithinPrefix,
partitionFor,
reloadSandboxUiWebContents,
+ resolveSandboxUiDefaultPath,
} from '../sandboxUiDriver.js'
describe('applySandboxUiClientRoute', () => {
@@ -38,39 +40,59 @@ describe('applySandboxUiClientRoute', () => {
})
describe('canApplySandboxUiClientRoute', () => {
- const expectedUrl = '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(
canApplySandboxUiClientRoute({
- expectedUrl,
- currentUrl: expectedUrl,
- navigatedUrl: expectedUrl,
+ allowedNavigationPrefix,
+ currentUrl: allowedNavigationPrefix,
+ navigatedUrl: allowedNavigationPrefix,
httpResponseCode: 503,
})
).toBe(false)
})
- it('accepts only a successful load of the expected server route', () => {
+ it('accepts canonicalized paths and redirects within the recipe view prefix', () => {
expect(
canApplySandboxUiClientRoute({
- expectedUrl,
- currentUrl: expectedUrl,
- navigatedUrl: expectedUrl,
+ allowedNavigationPrefix,
+ currentUrl: `${allowedNavigationPrefix}a%20b`,
+ navigatedUrl: `${allowedNavigationPrefix}index.html`,
httpResponseCode: 200,
})
).toBe(true)
expect(
canApplySandboxUiClientRoute({
- expectedUrl,
- currentUrl: `${expectedUrl}unexpected`,
- navigatedUrl: expectedUrl,
+ allowedNavigationPrefix,
+ currentUrl: 'https://rpc.example/api/v1/sandbox-ui/ns/other/view/',
+ navigatedUrl: allowedNavigationPrefix,
httpResponseCode: 200,
})
).toBe(false)
})
})
+describe('sandbox UI route normalization', () => {
+ it('recognizes canonicalized URLs within the allowed recipe prefix', () => {
+ expect(
+ isSandboxUiNavigationWithinPrefix(
+ 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/a%20b',
+ 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/'
+ )
+ ).toBe(true)
+ })
+
+ 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')
+ expect(resolveSandboxUiDefaultPath(undefined)).toBe('/')
+ expect(resolveSandboxUiDefaultPath('/safe/../admin')).toBe('/')
+ expect(warn).toHaveBeenCalledOnce()
+ warn.mockRestore()
+ })
+})
+
describe('partitionFor', () => {
it('produces a stable persist:sandbox-ui partition name per (env, recipe)', () => {
expect(partitionFor('env1', 'sandbox-recipes', 'r1')).toBe(
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 792f47097..9dc359919 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -263,6 +263,7 @@ export class AppService {
private readonly rpcTokenManager = new RpcTokenManager(this.authClient)
private sessionToken: string | null = null
private me: SessionMe | null = null
+ private profileUiBaseUrlCache: { key: string; value: string } | null = null
private accessCatalog: AccessCatalog | null = null
private teamDirectoryCache: TeamDirectoryResult | null = null
private teamContextQueue: Promise<void> = Promise.resolve()
@@ -377,6 +378,7 @@ export class AppService {
this.sessionToken = token
if (tokenChanged) {
this.rpcTokenManager.clear()
+ this.profileUiBaseUrlCache = null
this.accessCatalog = null
await this.tokenStore.setSessionToken(token, getActiveEnvKey())
}
@@ -709,17 +711,33 @@ export class AppService {
return { profileUiUrl: profileUiUrl.toString() }
}
- private async resolveProfileUiBaseUrl(email?: string): Promise<string> {
+ private async resolveProfileUiBaseUrl(
+ email?: string,
+ options: { fallbackOnLookupError?: boolean } = {}
+ ): Promise<string> {
+ const { fallbackOnLookupError = true } = options
const normalizedEmail = String(email || this.me?.email || '')
.trim()
.toLowerCase()
- if (!normalizedEmail) return config.desktopProfileUiBaseUrl
+ if (!normalizedEmail) {
+ if (fallbackOnLookupError) return config.desktopProfileUiBaseUrl
+ throw new Error('Cannot resolve the Profile UI for this desktop session')
+ }
+ const cacheKey = `${getActiveEnvKey()}:${this.me?.id || ''}:${normalizedEmail}`
+ if (this.profileUiBaseUrlCache?.key === cacheKey) {
+ return this.profileUiBaseUrlCache.value
+ }
try {
const activation =
await this.memberRegistrationServiceClient.getInvitationProfile(normalizedEmail)
- return activation.profileUiBaseUrl
- } catch {
- return config.desktopProfileUiBaseUrl
+ const profileUiBaseUrl =
+ String(activation.profileUiBaseUrl || '').trim() || config.desktopProfileUiBaseUrl
+ this.profileUiBaseUrlCache = { key: cacheKey, value: profileUiBaseUrl }
+ return profileUiBaseUrl
+ } catch (error) {
+ if (fallbackOnLookupError) return config.desktopProfileUiBaseUrl
+ const message = error instanceof Error ? error.message : String(error)
+ throw new Error(`Cannot resolve a shareable Profile UI link: ${message}`)
}
}
@@ -816,6 +834,7 @@ export class AppService {
this.stopAllStreams()
this.sessionToken = null
this.me = null
+ this.profileUiBaseUrlCache = null
this.accessCatalog = null
this.teamDirectoryCache = null
this.workflowApprovalTeamById.clear()
@@ -2926,7 +2945,9 @@ export class AppService {
const { buildSandboxUiWebLink } = await import('./sandboxUiDeepLinks.js')
const location = driver.getActiveSandboxUiLocation()
if (!location) throw new Error('No app is currently open')
- const profileUiBaseUrl = await this.resolveProfileUiBaseUrl()
+ const profileUiBaseUrl = await this.resolveProfileUiBaseUrl(undefined, {
+ fallbackOnLookupError: false,
+ })
return {
url: buildSandboxUiWebLink(profileUiBaseUrl, {
...location,
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index 1e3955a66..d331f69b3 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -6,7 +6,11 @@ import { assertTrustedSender, registerIpcHandlers } from './ipc.js'
import { createMainWindowCoordinator } from './mainWindowCoordinator.js'
import { collectInitialProtocolUrls } from './protocolLaunchArgs.js'
import { SandboxUiDeepLinkQueue } from './sandboxUiDeepLinkQueue.js'
-import { parseSandboxUiDeepLink } from './sandboxUiDeepLinks.js'
+import {
+ SANDBOX_UI_DEEP_LINK_HOST,
+ SANDBOX_UI_DEEP_LINK_PROTOCOL,
+ parseSandboxUiDeepLink,
+} from './sandboxUiDeepLinks.js'
import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'
const EVENFIRE_APP_NAME = 'Evenfire'
@@ -25,6 +29,7 @@ const appService = new AppService()
const pendingEvenfireUrls: string[] = []
const sandboxUiDeepLinkQueue = new SandboxUiDeepLinkQueue()
let mainWindowLifecycleReady = false
+let mainWindowRendererReady = false
function systemIconAssetsDirectory(): string {
return app.isPackaged ? process.resourcesPath : path.join(__dirname, '../assets')
@@ -92,6 +97,13 @@ ipcMain.handle('window:getVisibility', event => {
return { visible: isWindowVisible(mainWindow) }
})
+ipcMain.handle('app:rendererReady', event => {
+ assertTrustedSender(event)
+ if (!mainWindow || event.sender !== mainWindow.webContents) return
+ mainWindowRendererReady = true
+ drainPendingEvenfireUrls()
+})
+
ipcMain.handle('sandboxUi:listPendingDeepLinks', event => {
assertTrustedSender(event)
return { links: sandboxUiDeepLinkQueue.list() }
@@ -108,7 +120,7 @@ ipcMain.handle('sandboxUi:acknowledgeDeepLink', (event, payload: { id?: unknown
if (!Number.isInteger(id) || id <= 0) throw new Error('Invalid app deep-link id')
sandboxUiDeepLinkQueue.acknowledge(id)
})
-const DESKTOP_SETUP_PROTOCOL = 'evenfire'
+const DESKTOP_SETUP_PROTOCOL = SANDBOX_UI_DEEP_LINK_PROTOCOL.replace(/:$/, '')
const CLERUM_PROTOCOL = 'clerum'
function focusMainWindow(): void {
@@ -139,10 +151,6 @@ function handleSandboxUiDeepLink(rawUrl: string): boolean {
// acknowledgement. Query-parameter order cannot bypass this check, and once
// acknowledged, an immediate user re-click creates a fresh envelope.
const envelope = sandboxUiDeepLinkQueue.enqueue(target)
- if (!envelope) {
- requestMainWindow()
- return true
- }
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('sandboxUi:deepLink', envelope)
}
@@ -175,7 +183,7 @@ function handleEvenfireUrl(rawUrl: string): void {
return
}
- if (parsed.hostname === 'app') {
+ if (parsed.hostname === SANDBOX_UI_DEEP_LINK_HOST) {
if (!handleSandboxUiDeepLink(rawUrl)) requestMainWindow()
return
}
@@ -198,7 +206,7 @@ function handleEvenfireUrl(rawUrl: string): void {
parsed.searchParams.get('tenantName') || parsed.searchParams.get('appName') || ''
if (!externalRestApiBaseUrl) return
- if (mainWindow && !mainWindow.isDestroyed()) {
+ if (mainWindow && !mainWindow.isDestroyed() && mainWindowRendererReady) {
focusMainWindow()
mainWindow.webContents.send('auth:desktopEnvironmentSetup', {
externalRestApiBaseUrl,
@@ -217,7 +225,7 @@ function handleEvenfireUrl(rawUrl: string): void {
const authorizationToken = parsed.searchParams.get('authorizationToken') || ''
if (!email || !authorizationToken) return
- if (mainWindow && !mainWindow.isDestroyed()) {
+ if (mainWindow && !mainWindow.isDestroyed() && mainWindowRendererReady) {
focusMainWindow()
mainWindow.webContents.send('auth:desktopSetupToken', { email, authorizationToken })
} else {
@@ -226,6 +234,14 @@ function handleEvenfireUrl(rawUrl: string): void {
}
}
+function drainPendingEvenfireUrls(): void {
+ if (!mainWindowRendererReady) return
+ while (pendingEvenfireUrls.length > 0) {
+ const pendingUrl = pendingEvenfireUrls.shift()
+ if (pendingUrl) handleEvenfireUrl(pendingUrl)
+ }
+}
+
/**
* Spec §9.9 — `clerum://oauth-completed?clientId=…&provider=…` is the
* deep link the control-api OAuth callback's success page bounces to.
@@ -300,8 +316,15 @@ async function createWindow(): Promise<void> {
},
})
mainWindow = window
+ mainWindowRendererReady = false
window.on('closed', () => {
- if (mainWindow === window) mainWindow = null
+ if (mainWindow === window) {
+ mainWindow = null
+ mainWindowRendererReady = false
+ }
+ })
+ window.webContents.on('did-start-loading', () => {
+ if (mainWindow === window) mainWindowRendererReady = false
})
wireWindowVisibility(window)
@@ -325,10 +348,6 @@ async function createWindow(): Promise<void> {
window.maximize()
// Show window after successful load to avoid hidden-startup deadlocks.
window.show()
- while (pendingEvenfireUrls.length > 0) {
- const pendingUrl = pendingEvenfireUrls.shift()
- if (pendingUrl) handleEvenfireUrl(pendingUrl)
- }
window.once('ready-to-show', () => {
if (window.isDestroyed()) return
window.maximize()
@@ -337,30 +356,42 @@ async function createWindow(): Promise<void> {
}
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 = true
- // Collect startup argv once. `createWindow` drains the queued Evenfire URLs
- // after the renderer loads; rescanning argv there would dispatch setup links
- // twice on Windows/Linux and redeem single-use setup tokens a second time.
- const initialProtocolUrls = collectInitialProtocolUrls(process.argv)
- pendingEvenfireUrls.push(...initialProtocolUrls.evenfireUrls)
- await mainWindowCoordinator.ensureWindow()
- if (process.platform !== 'darwin') {
- initialProtocolUrls.clerumUrls.forEach(handleClerumUrl)
- }
- wirePowerMonitor()
-
- app.on('activate', async () => {
- if (BrowserWindow.getAllWindows().length === 0) {
- await mainWindowCoordinator.ensureWindow()
+ app
+ .whenReady()
+ .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)
}
+ // 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)
+ 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()
+ console.error('[Desktop] Startup failed before the main window was ready:', error)
+ requestMainWindow()
})
- })
}
app.on('window-all-closed', () => {
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 5bc2c0880..864cc69b3 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -351,6 +351,7 @@ const clerum = Object.freeze({
},
app: {
openUrl: (url: string) => ipcRenderer.invoke('app:openUrl', { url }),
+ rendererReady: () => ipcRenderer.invoke('app:rendererReady'),
},
window: {
getVisibility: () => ipcRenderer.invoke('window:getVisibility'),
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 26d2547f4..d01ecb18d 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -463,6 +463,7 @@ declare global {
}
app: {
openUrl: (url: string) => Promise<void>
+ rendererReady: () => Promise<void>
}
window: {
getVisibility: () => Promise<{ visible: boolean }>
@@ -556,7 +557,7 @@ declare global {
reload: () => Promise<void>
copyDeepLink: (teamId?: string) => Promise<{ url: string }>
listPendingDeepLinks: () => Promise<{ links: SandboxUiDeepLinkEnvelope[] }>
- clearPendingDeepLinks?: () => Promise<void>
+ clearPendingDeepLinks: () => Promise<void>
acknowledgeDeepLink: (id: number) => Promise<void>
setBounds: (bounds: {
x: number
diff --git a/desktop-app/src/sandboxUiDeepLinkQueue.ts b/desktop-app/src/sandboxUiDeepLinkQueue.ts
index cbe1d8d68..a9cc18bc5 100644
--- a/desktop-app/src/sandboxUiDeepLinkQueue.ts
+++ b/desktop-app/src/sandboxUiDeepLinkQueue.ts
@@ -11,8 +11,15 @@ export class SandboxUiDeepLinkQueue {
return [...this.pending]
}
- enqueue(target: SandboxUiDeepLinkTarget): SandboxUiDeepLinkEnvelope | null {
- if (this.pending.some(item => sandboxUiDeepLinkTargetsEqual(item, target))) return null
+ enqueue(target: SandboxUiDeepLinkTarget): SandboxUiDeepLinkEnvelope {
+ const existingIndex = this.pending.findIndex(item =>
+ sandboxUiDeepLinkTargetsEqual(item, target)
+ )
+ if (existingIndex >= 0) {
+ const [existing] = this.pending.splice(existingIndex, 1)
+ this.pending.push(existing!)
+ return existing!
+ }
const envelope = { id: (this.sequence += 1), ...target }
this.pending.push(envelope)
if (this.pending.length > this.maxSize) this.pending.shift()
diff --git a/desktop-app/src/sandboxUiDeepLinks.ts b/desktop-app/src/sandboxUiDeepLinks.ts
index 62ef6f5b3..199d50671 100644
--- a/desktop-app/src/sandboxUiDeepLinks.ts
+++ b/desktop-app/src/sandboxUiDeepLinks.ts
@@ -40,5 +40,7 @@ export function extractSandboxUiViewRoute(input: SandboxUiViewRouteInput): strin
if (current.pathname !== prefix && !current.pathname.startsWith(`${prefix}/`)) return null
const pathname = current.pathname.slice(prefix.length) || '/'
- return normalizeSandboxUiRoute(`${pathname}${current.search}${current.hash}`) ?? null
+ // 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
}
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index 19189ad80..c1a8add24 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -36,6 +36,7 @@ import {
*/
export const SANDBOX_UI_COOKIE_NAME = 'clerum_sandbox_ui_session'
+const CLIENT_ROUTE_HANDOFF_TIMEOUT_MS = 30_000
export type SandboxUiBounds = {
x: number
@@ -283,7 +284,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
const partition = partitionFor(getActiveEnvKey(), recipeNs, recipeName)
const proxyOriginUrl = new URL(rpcProxyUrl).toString().replace(/\/+$/, '')
- const viewPath = normalizeSandboxUiRoute(defaultPath || '/') || '/'
+ const viewPath = resolveSandboxUiDefaultPath(defaultPath)
const clientRoutePath = normalizeSandboxUiRoute(routePath || '')
const allowedNavigationPrefix =
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
@@ -382,7 +383,12 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
`${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view${clientRoutePath}`
let lastNavigation = { url: '', status: 0 }
+ let handoffFinished = false
+ let handoffTimeout: NodeJS.Timeout | null = null
const cleanupClientRouteHandoff = () => {
+ if (handoffFinished) return
+ handoffFinished = true
+ if (handoffTimeout) clearTimeout(handoffTimeout)
view.webContents.removeListener('did-navigate', onDidNavigate)
view.webContents.removeListener('did-finish-load', onDidFinishLoad)
}
@@ -400,24 +406,43 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
}
if (
!canApplySandboxUiClientRoute({
- expectedUrl: url,
+ allowedNavigationPrefix,
currentUrl: view.webContents.getURL(),
navigatedUrl: lastNavigation.url,
httpResponseCode: lastNavigation.status,
})
) {
+ if (
+ lastNavigation.status >= 200 &&
+ lastNavigation.status < 400 &&
+ !isSandboxUiNavigationWithinPrefix(view.webContents.getURL(), allowedNavigationPrefix)
+ ) {
+ console.warn(
+ '[SandboxUI] client route handoff abandoned after navigation left the app prefix:',
+ view.webContents.getURL()
+ )
+ cleanupClientRouteHandoff()
+ }
return
}
void applySandboxUiClientRoute(view.webContents, clientRouteUrl)
.then(applied => {
- if (applied) cleanupClientRouteHandoff()
+ if (!applied) {
+ console.warn('[SandboxUI] client route handoff did not update the app URL')
+ }
+ cleanupClientRouteHandoff()
})
.catch(err => {
console.warn('[SandboxUI] client route handoff failed:', err)
+ cleanupClientRouteHandoff()
})
}
view.webContents.on('did-navigate', onDidNavigate)
view.webContents.on('did-finish-load', onDidFinishLoad)
+ handoffTimeout = setTimeout(() => {
+ console.warn('[SandboxUI] client route handoff timed out before the app became ready')
+ cleanupClientRouteHandoff()
+ }, CLIENT_ROUTE_HANDOFF_TIMEOUT_MS)
}
// Drop the HTTP cache on every open so a stale entry from a prior
// broken pod can't keep painting after the recipe is healthy. The
@@ -446,9 +471,9 @@ export async function applySandboxUiClientRoute(
const serializedTarget = JSON.stringify(targetUrl)
return Boolean(
await webContents.executeJavaScript(`(() => {
- const targetUrl = ${serializedTarget};
+ const targetUrl = new URL(${serializedTarget}).href;
const previousUrl = window.location.href;
- if (previousUrl === targetUrl) return true;
+ 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) {
@@ -457,20 +482,40 @@ export async function applySandboxUiClientRoute(
newURL: targetUrl,
}));
}
- return window.location.href === targetUrl;
+ return new URL(window.location.href).href === targetUrl;
})()`)
)
}
+export function resolveSandboxUiDefaultPath(defaultPath?: string): string {
+ const rawDefaultPath = String(defaultPath || '').trim()
+ if (!rawDefaultPath) return '/'
+ const normalized = normalizeSandboxUiRoute(rawDefaultPath)
+ if (normalized) return normalized
+ console.warn('[SandboxUI] Invalid recipe defaultPath; falling back to "/":', rawDefaultPath)
+ return '/'
+}
+
+export function isSandboxUiNavigationWithinPrefix(
+ navigationUrl: string,
+ allowedNavigationPrefix: string
+): boolean {
+ try {
+ return new URL(navigationUrl).href.startsWith(new URL(allowedNavigationPrefix).href)
+ } catch {
+ return false
+ }
+}
+
export function canApplySandboxUiClientRoute(input: {
- expectedUrl: string
+ allowedNavigationPrefix: string
currentUrl: string
navigatedUrl: string
httpResponseCode: number
}): boolean {
return (
- input.currentUrl === input.expectedUrl &&
- input.navigatedUrl === input.expectedUrl &&
+ isSandboxUiNavigationWithinPrefix(input.currentUrl, input.allowedNavigationPrefix) &&
+ isSandboxUiNavigationWithinPrefix(input.navigatedUrl, input.allowedNavigationPrefix) &&
input.httpResponseCode >= 200 &&
input.httpResponseCode < 400
)
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index be880405e..9eba8d708 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -27,7 +27,11 @@ import {
getConversationOriginForAppLaunch,
getConversationOriginForNavigation,
} from '@lib/sandboxUiConversationOrigin'
-import { shouldPurgeSandboxUiDeepLinks } from '@lib/sandboxUiDeepLinkState'
+import {
+ enqueuePendingSandboxUiDeepLink,
+ removePendingSandboxUiDeepLink,
+ shouldPurgeSandboxUiDeepLinks,
+} from '@lib/sandboxUiDeepLinkState'
import { AgentsPage } from '@pages/AgentsPage'
import { AuthPage } from '@pages/AuthPage'
import { ChatPage } from '@pages/ChatPage'
@@ -150,8 +154,10 @@ export function App() {
const contentPanelRef = React.useRef<HTMLElement | null>(null)
const activeConversationOriginRef = React.useRef<SandboxUiConversationOrigin | null>(null)
const processingSandboxUiDeepLinkIdRef = React.useRef<number | null>(null)
+ const pendingSandboxUiDeepLinksRef = React.useRef<PendingSandboxUiDeepLink[]>([])
const sandboxUiDeepLinkIdentityRef = React.useRef<string | null | undefined>(undefined)
const sandboxUiDeepLinkGenerationRef = React.useRef(0)
+ const bootSplashLoading = vm.booting || vm.initialExperienceLoading
const isAgentChatView =
(vm.navItem === DESKTOP_ROUTES.agents && Boolean(vm.selectedAgent)) ||
(vm.navItem === DESKTOP_ROUTES.chat && Boolean(vm.selectedAgent))
@@ -199,6 +205,12 @@ export function App() {
}
}, [sidebarCollapsed])
+ React.useEffect(() => {
+ void window.clerum.app.rendererReady().catch(error => {
+ console.warn('[Desktop] Could not signal renderer readiness:', error)
+ })
+ }, [])
+
React.useEffect(() => {
if (!vm.isAuthenticated) {
setAvailableSandboxUiApps([])
@@ -231,20 +243,19 @@ export function App() {
}, [vm.currentTeamId, vm.isAuthenticated])
React.useEffect(() => {
- const identity =
- vm.isAuthenticated && vm.me ? `${vm.me.id}:${String(vm.me.email || '').toLowerCase()}` : null
+ const identity = vm.authenticatedPrincipalIdentity
const previousIdentity = sandboxUiDeepLinkIdentityRef.current
sandboxUiDeepLinkIdentityRef.current = identity
if (!shouldPurgeSandboxUiDeepLinks(previousIdentity, identity)) return
+ pendingSandboxUiDeepLinksRef.current = []
setPendingSandboxUiDeepLinks([])
processingSandboxUiDeepLinkIdRef.current = null
sandboxUiDeepLinkGenerationRef.current += 1
- const clearPendingDeepLinks = window.clerum.sandboxUi.clearPendingDeepLinks
- if (typeof clearPendingDeepLinks === 'function') {
- void clearPendingDeepLinks().catch(() => undefined)
- }
- }, [vm.isAuthenticated, vm.me])
+ void window.clerum.sandboxUi.clearPendingDeepLinks().catch(error => {
+ console.warn('[Desktop] Could not clear stale app deep links:', error)
+ })
+ }, [vm.authenticatedPrincipalIdentity])
const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp) => {
setActiveSandboxUiApp(app)
@@ -338,21 +349,22 @@ export function App() {
React.useEffect(() => {
const enqueue = (link: SandboxUiDeepLinkEnvelope) => {
- setPendingSandboxUiDeepLinks(current => {
- if (current.some(item => item.link.id === link.id)) return current
- return [
- ...current,
- {
- link,
- conversationOrigin: activeConversationOriginRef.current,
- },
- ]
- })
+ const next = enqueuePendingSandboxUiDeepLink(
+ pendingSandboxUiDeepLinksRef.current,
+ link,
+ activeConversationOriginRef.current
+ )
+ pendingSandboxUiDeepLinksRef.current = next
+ setPendingSandboxUiDeepLinks(next)
}
const unsubscribe = window.clerum.sandboxUi.onDeepLink(enqueue)
+ const listGeneration = sandboxUiDeepLinkGenerationRef.current
void window.clerum.sandboxUi
.listPendingDeepLinks()
- .then(result => result.links.forEach(enqueue))
+ .then(result => {
+ if (listGeneration !== sandboxUiDeepLinkGenerationRef.current) return
+ result.links.forEach(enqueue)
+ })
.catch(() => undefined)
return unsubscribe
}, [])
@@ -360,22 +372,37 @@ export function App() {
React.useEffect(() => {
if (
!canProcessSandboxUiDeepLinks(
- vm.booting,
+ bootSplashLoading,
vm.isAuthenticated,
pendingSandboxUiDeepLinks.length
)
) {
return
}
- const pending = pendingSandboxUiDeepLinks[0]
+ const pending = pendingSandboxUiDeepLinksRef.current[0]
+ if (
+ pending?.link.teamId &&
+ pending.link.teamId !== vm.currentTeamId &&
+ !vm.teamDirectoryHydrated
+ ) {
+ return
+ }
if (!pending || processingSandboxUiDeepLinkIdRef.current !== null) return
processingSandboxUiDeepLinkIdRef.current = pending.link.id
const processingGeneration = sandboxUiDeepLinkGenerationRef.current
void (async () => {
+ const originalTeamId = vm.currentTeamId
+ let switchedTeam = false
+ let openedApp = false
try {
+ if (processingGeneration !== sandboxUiDeepLinkGenerationRef.current) return
if (pending.link.teamId && pending.link.teamId !== vm.currentTeamId) {
- await vm.handleEnsureTeamContext({ teamId: pending.link.teamId })
+ if (!vm.availableTeamIds.includes(pending.link.teamId)) {
+ throw new Error("You don't have access to the linked team")
+ }
+ await vm.handleEnsureTeamContext({ teamId: pending.link.teamId, announce: true })
+ switchedTeam = true
}
if (processingGeneration !== sandboxUiDeepLinkGenerationRef.current) return
const result = await window.clerum.sandboxUi.listApps()
@@ -387,9 +414,11 @@ export function App() {
throw new Error("You don't have access to this app in the linked team")
}
if (resolution.status === 'starting') {
- throw new Error(
- `${resolution.label} is still starting up. Try this link again in a moment`
+ vm.pushToast(
+ `${resolution.label} is still starting up. Try this link again in a moment.`,
+ 'info'
)
+ return
}
launchSandboxUiApp(
{
@@ -398,34 +427,64 @@ export function App() {
},
pending.conversationOrigin ?? sandboxUiConversationOrigin
)
+ openedApp = true
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
vm.pushToast(`Could not open app link: ${message}`, 'error')
} finally {
+ if (
+ !openedApp &&
+ switchedTeam &&
+ originalTeamId &&
+ processingGeneration === sandboxUiDeepLinkGenerationRef.current
+ ) {
+ try {
+ await vm.handleEnsureTeamContext({ teamId: originalTeamId, announce: true })
+ const origin = pending.conversationOrigin
+ if (origin && (!origin.teamId || origin.teamId === originalTeamId)) {
+ vm.handleSelectChatAgent(origin.agentName, {
+ selectLatest: false,
+ chatId: origin.chatId,
+ title: origin.title,
+ })
+ }
+ } catch (rollbackError) {
+ const message =
+ rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
+ vm.pushToast(`Could not restore the previous team: ${message}`, 'error')
+ }
+ }
if (
processingGeneration !== sandboxUiDeepLinkGenerationRef.current ||
processingSandboxUiDeepLinkIdRef.current !== pending.link.id
) {
return
}
- setPendingSandboxUiDeepLinks(current =>
- current.filter(item => item.link.id !== pending.link.id)
+ const next = removePendingSandboxUiDeepLink(
+ pendingSandboxUiDeepLinksRef.current,
+ pending.link.id
)
+ pendingSandboxUiDeepLinksRef.current = next
+ setPendingSandboxUiDeepLinks(next)
processingSandboxUiDeepLinkIdRef.current = null
- const acknowledgeDeepLink = window.clerum.sandboxUi.acknowledgeDeepLink
- if (typeof acknowledgeDeepLink === 'function') {
- await acknowledgeDeepLink(pending.link.id).catch(() => undefined)
+ try {
+ await window.clerum.sandboxUi.acknowledgeDeepLink(pending.link.id)
+ } catch (error) {
+ console.warn('[Desktop] Could not acknowledge app deep link:', error)
}
}
})()
}, [
+ bootSplashLoading,
launchSandboxUiApp,
pendingSandboxUiDeepLinks,
- vm.booting,
+ vm.availableTeamIds,
vm.currentTeamId,
vm.handleEnsureTeamContext,
+ vm.handleSelectChatAgent,
vm.isAuthenticated,
vm.pushToast,
+ vm.teamDirectoryHydrated,
sandboxUiConversationOrigin,
])
@@ -804,8 +863,6 @@ export function App() {
/>
) : null
- const bootSplashLoading = vm.booting || vm.initialExperienceLoading
-
return (
<AuthContext.Provider value={authValue}>
<div className="app-root" inert={bootSplashLoading || undefined}>
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
new file mode 100644
index 000000000..b0fd18372
--- /dev/null
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -0,0 +1,264 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, render, waitFor } from '@testing-library/react'
+import { DESKTOP_ROUTES } from '@constants/navigation'
+import { useAppController } from '@hooks/useAppController'
+import { App } from '@/App'
+import type { SandboxUiDeepLinkEnvelope } from '@/App.types'
+
+vi.mock('@hooks/useAppController', () => ({
+ useAppController: vi.fn(),
+}))
+
+vi.mock('@hooks/useAgentChatActionsValue', () => ({
+ useAgentChatActionsValue: () => ({}),
+}))
+
+vi.mock('@components/AppHeader', () => ({ AppHeader: () => null }))
+vi.mock('@components/BootSplash', () => ({ BootSplash: () => null }))
+vi.mock('@components/Common', () => ({ Button: () => null, ToastStack: () => null }))
+vi.mock('@components/ConfirmDialog', () => ({ ConfirmDialog: () => null }))
+vi.mock('@components/SidebarNav', () => ({ SidebarNav: () => null }))
+vi.mock('@pages/AgentsPage', () => ({ AgentsPage: () => null }))
+vi.mock('@pages/AuthPage', () => ({ AuthPage: () => null }))
+vi.mock('@pages/ChatPage', () => ({ ChatPage: () => null }))
+vi.mock('@pages/ContextDetailsPage', () => ({ ContextDetailsPage: () => null }))
+vi.mock('@pages/ContextsPage', () => ({ ContextsPage: () => null }))
+vi.mock('@pages/FilesPage', () => ({ FilesPage: () => null }))
+vi.mock('@pages/McpServersPage', () => ({ McpServersPage: () => null }))
+vi.mock('@pages/SandboxUiPage', () => ({ SandboxUiPage: () => null }))
+vi.mock('@pages/SettingsPage', () => ({ SettingsPage: () => null }))
+vi.mock('@pages/TeamDetailsPage', () => ({ TeamDetailsPage: () => null }))
+vi.mock('@pages/TeamsPage', () => ({ TeamsPage: () => null }))
+vi.mock('@pages/UnavailablePage', () => ({ UnavailablePage: () => null }))
+vi.mock('@pages/WorkflowsPage', () => ({ WorkflowsPage: () => null }))
+
+type AppController = ReturnType<typeof useAppController>
+
+function makeController(overrides: Partial<AppController> = {}): AppController {
+ const noop = vi.fn()
+ return {
+ booting: false,
+ initialExperienceLoading: true,
+ busy: false,
+ statusText: '',
+ statusTone: 'info',
+ isAuthenticated: true,
+ authenticatedPrincipalIdentity: 'user-a:[email protected]',
+ availableTeamIds: ['team-a', 'team-b'],
+ teamDirectoryHydrated: true,
+ me: {
+ id: 'user-a',
+ email: '[email protected]',
+ name: 'User A',
+ picture: null,
+ teamId: 'team-a',
+ teamName: 'Team A',
+ role: 'member',
+ },
+ currentTeamId: 'team-a',
+ navItem: DESKTOP_ROUTES.chat,
+ selectedAgent: null,
+ selectedAgentRoute: null,
+ selectedContext: null,
+ selectedTeam: null,
+ activeChatId: null,
+ chatList: [],
+ latestChatSessions: [],
+ notifications: [],
+ toasts: [],
+ pendingApprovals: [],
+ composerImageAttachments: [],
+ composerReferenceAttachments: [],
+ groupedMessages: [],
+ activeMessages: [],
+ notificationActionById: {},
+ sessionStateByChatId: {},
+ sessionStateByChatKey: {},
+ activityByMessageId: {},
+ progressByMessageId: {},
+ agentLastActiveByAgent: {},
+ dependencyHealth: null,
+ hasDependencyOutage: false,
+ desktopEnvironmentSetupComplete: false,
+ pendingDesktopEnvironmentSetup: null,
+ desktopReleaseStatus: null,
+ showRuntimeConfigSelector: false,
+ runtimeConfigMissing: false,
+ authTransitioning: false,
+ handleEnsureTeamContext: vi.fn(),
+ handleSelectChatAgent: vi.fn(),
+ handleNavSelect: vi.fn(),
+ pushToast: vi.fn(),
+ setStatus: noop,
+ setBooting: noop,
+ setEmail: noop,
+ setPassword: noop,
+ setDesktopSetupAuthorizationToken: noop,
+ setRuntimeConfigSetupName: noop,
+ setRuntimeConfigSetupExternalRestApiBaseUrl: noop,
+ setRuntimeConfigSetupRpcProxyBaseUrl: noop,
+ setPendingDesktopEnvironmentSetup: noop,
+ setDesktopEnvironmentSetupComplete: noop,
+ ...overrides,
+ } as unknown as AppController
+}
+
+describe('App deep-link orchestration', () => {
+ let currentController: AppController
+ let emitDeepLink: ((link: SandboxUiDeepLinkEnvelope) => void) | null
+ const clearPendingDeepLinks = vi.fn().mockResolvedValue(undefined)
+ const acknowledgeDeepLink = vi.fn().mockResolvedValue(undefined)
+ const listApps = vi.fn().mockResolvedValue({ apps: [] })
+ const listPendingDeepLinks = vi.fn().mockResolvedValue({ links: [] })
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ acknowledgeDeepLink.mockResolvedValue(undefined)
+ listApps.mockResolvedValue({ apps: [] })
+ listPendingDeepLinks.mockResolvedValue({ links: [] })
+ emitDeepLink = null
+ currentController = makeController()
+ vi.mocked(useAppController).mockImplementation(() => currentController)
+
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ app: {
+ rendererReady: vi.fn().mockResolvedValue(undefined),
+ },
+ sandboxUi: {
+ listApps,
+ listPendingDeepLinks,
+ clearPendingDeepLinks,
+ acknowledgeDeepLink,
+ onDeepLink: vi.fn((callback: (link: SandboxUiDeepLinkEnvelope) => void) => {
+ emitDeepLink = callback
+ return vi.fn()
+ }),
+ },
+ } as unknown as Window['clerum'],
+ })
+ })
+
+ it('purges user A links synchronously before user B can process them', async () => {
+ const { rerender } = render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-a' })
+ })
+
+ currentController = makeController({
+ initialExperienceLoading: false,
+ authenticatedPrincipalIdentity: 'user-b:[email protected]',
+ me: {
+ id: 'user-b',
+ email: '[email protected]',
+ name: 'User B',
+ picture: null,
+ teamId: 'team-b',
+ teamName: 'Team B',
+ role: 'member',
+ },
+ currentTeamId: 'team-b',
+ })
+ rerender(<App />)
+
+ await waitFor(() => expect(clearPendingDeepLinks).toHaveBeenCalledOnce())
+ expect(currentController.handleEnsureTeamContext).not.toHaveBeenCalled()
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
+ })
+
+ it('drops a stale cold-list response after the authenticated identity changes', async () => {
+ let resolveColdList!: (value: { links: SandboxUiDeepLinkEnvelope[] }) => void
+ listPendingDeepLinks.mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ resolveColdList = resolve
+ })
+ )
+ const { rerender } = render(<App />)
+
+ currentController = makeController({
+ initialExperienceLoading: false,
+ authenticatedPrincipalIdentity: 'user-b:[email protected]',
+ me: {
+ id: 'user-b',
+ email: '[email protected]',
+ name: 'User B',
+ picture: null,
+ teamId: 'team-b',
+ teamName: 'Team B',
+ role: 'member',
+ },
+ currentTeamId: 'team-b',
+ })
+ rerender(<App />)
+ await waitFor(() => expect(clearPendingDeepLinks).toHaveBeenCalledOnce())
+
+ await act(async () => {
+ resolveColdList({ links: [{ id: 1, appRef: 'ns/app', teamId: 'team-a' }] })
+ await Promise.resolve()
+ })
+
+ expect(currentController.handleEnsureTeamContext).not.toHaveBeenCalled()
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
+ })
+
+ it('restores the previous team when the linked app is unavailable', async () => {
+ currentController = makeController({ initialExperienceLoading: false })
+ render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/missing', teamId: 'team-b' })
+ })
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(currentController.handleEnsureTeamContext).toHaveBeenNthCalledWith(1, {
+ teamId: 'team-b',
+ announce: true,
+ })
+ expect(currentController.handleEnsureTeamContext).toHaveBeenNthCalledWith(2, {
+ teamId: 'team-a',
+ announce: true,
+ })
+ expect(currentController.pushToast).toHaveBeenCalledWith(
+ expect.stringContaining("You don't have access"),
+ 'error'
+ )
+ })
+
+ it('contains a synchronously throwing acknowledgement bridge', async () => {
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ currentController = makeController({ initialExperienceLoading: false })
+ listApps.mockResolvedValue({
+ apps: [
+ {
+ appRef: 'ns/app',
+ title: 'App',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ },
+ ],
+ })
+ acknowledgeDeepLink.mockImplementationOnce(() => {
+ throw new Error('bridge unavailable')
+ })
+ render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app' })
+ })
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(currentController.pushToast).not.toHaveBeenCalledWith(
+ expect.stringContaining('bridge unavailable'),
+ 'error'
+ )
+ consoleWarn.mockRestore()
+ })
+})
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 4026a9fde..196ede463 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type {
AccessCatalog,
@@ -136,7 +136,7 @@ export function useAppController() {
// Use a ref so the stable onSessionNeedsLoad callback can call the real loadSession
// without creating a circular dependency (loadSession is defined after auth+session).
const loadSessionRef = useRef(async (_options?: { preserveNav?: boolean }) => {})
- const authenticatedSessionIdentityRef = useRef<string | null>(null)
+ const authenticatedWorkspaceIdentityRef = useRef<string | null>(null)
const catalogRefreshPromiseRef = useRef<Promise<AccessCatalog> | null>(null)
const onSessionNeedsLoad = useCallback(async (options?: { preserveNav?: boolean }) => {
@@ -155,6 +155,13 @@ export function useAppController() {
const mcpServersData = useMcpServersDataController()
const teamsData = useTeamsDataController()
const currentTeamId = teamsData.currentTeamId || auth.me?.teamId || ''
+ const availableTeamIds = useMemo(() => teamsData.teams.map(team => team.id), [teamsData.teams])
+ const authenticatedPrincipalIdentity =
+ auth.isAuthenticated && auth.me
+ ? `${auth.me.id}:${String(auth.me.email || '')
+ .trim()
+ .toLowerCase()}`
+ : null
const currentTeamName =
teamsData.teams.find(team => team.id === currentTeamId)?.name || auth.me?.teamName || ''
const currentTeamIdRef = useRef(currentTeamId)
@@ -496,7 +503,7 @@ export function useAppController() {
auth.setMe(sessionState.me)
auth.setEmail(sessionState.me.email || '')
currentTeamIdRef.current = sessionState.me.teamId || teamId
- authenticatedSessionIdentityRef.current = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`
+ authenticatedWorkspaceIdentityRef.current = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`
await refreshAuthenticatedData()
if (announce) {
const teamName =
@@ -522,7 +529,7 @@ export function useAppController() {
)
const ensureTeamContext = useCallback(
- async (target: { teamId?: string }) => {
+ async (target: { teamId?: string; announce?: boolean }) => {
const targetTeamId = String(target.teamId || '').trim()
if (!targetTeamId) return
@@ -531,7 +538,7 @@ export function useAppController() {
if (targetTeamId === activeTeamId) return
chat.clearActiveChat()
- await switchTeamForWorkspace(targetTeamId, { announce: false })
+ await switchTeamForWorkspace(targetTeamId, { announce: target.announce ?? false })
})
notificationTeamContextQueueRef.current = queuedSwitch.catch(() => undefined)
await queuedSwitch
@@ -574,6 +581,7 @@ export function useAppController() {
.then(auth.setDependencyHealth)
.catch(error => {
console.warn('[Desktop] Could not refresh dependency health:', error)
+ auth.setDependencyHealth(null)
})
const sessionState = await window.clerum.auth.getSessionState()
const authenticated = Boolean(sessionState.authenticated && sessionState.me)
@@ -591,7 +599,7 @@ export function useAppController() {
queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
chat.resetChat()
notif.resetNotifications()
- authenticatedSessionIdentityRef.current = null
+ authenticatedWorkspaceIdentityRef.current = null
if (!preserveNav) nav.handleNavSelect(DESKTOP_ROUTES.chat)
return
}
@@ -600,8 +608,8 @@ export function useAppController() {
auth.setEmail(sessionState.me.email || '')
void auth.refreshDesktopReleaseStatus()
const sessionIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`
- if (authenticatedSessionIdentityRef.current !== sessionIdentity) {
- authenticatedSessionIdentityRef.current = sessionIdentity
+ if (authenticatedWorkspaceIdentityRef.current !== sessionIdentity) {
+ authenticatedWorkspaceIdentityRef.current = sessionIdentity
await refreshAuthenticatedData({ initialLoad: true })
}
if (!preserveNav) {
@@ -656,7 +664,7 @@ export function useAppController() {
// in cache would otherwise bleed into the next login (possibly a different
// environment, since the env is chosen pre-login).
queryClient.clear()
- authenticatedSessionIdentityRef.current = null
+ authenticatedWorkspaceIdentityRef.current = null
await window.clerum.auth.logout()
chat.resetChat()
notif.resetNotifications()
@@ -1003,6 +1011,9 @@ export function useAppController() {
isAuthenticated: auth.isAuthenticated,
me: auth.me,
currentTeamId,
+ availableTeamIds,
+ teamDirectoryHydrated: teamsData.teamDirectoryHydrated,
+ authenticatedPrincipalIdentity,
email: auth.email,
password: auth.password,
desktopSetupAuthorizationToken: auth.desktopSetupAuthorizationToken,
diff --git a/desktop-app/ui/src/lib/__tests__/sandboxUiAppSelection.test.ts b/desktop-app/ui/src/lib/__tests__/sandboxUiAppSelection.test.ts
index b84ff903c..25851970f 100644
--- a/desktop-app/ui/src/lib/__tests__/sandboxUiAppSelection.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/sandboxUiAppSelection.test.ts
@@ -50,7 +50,7 @@ describe('sandbox UI app selection', () => {
})
it('returns a launchable app when the deep-link target is ready', () => {
- expect(resolveSandboxUiDeepLinkApp(apps, 'sandbox-recipes/ready-app')).toEqual({
+ expect(resolveSandboxUiDeepLinkApp(apps, 'SANDBOX-RECIPES/READY-APP')).toEqual({
status: 'ready',
app: {
appRef: 'sandbox-recipes/ready-app',
diff --git a/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts b/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts
index d130111b6..b8ca59b87 100644
--- a/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest'
-import { shouldPurgeSandboxUiDeepLinks } from '../sandboxUiDeepLinkState'
+import type { PendingSandboxUiDeepLink } from '@/App.types'
+import {
+ MAX_PENDING_SANDBOX_UI_DEEP_LINKS,
+ enqueuePendingSandboxUiDeepLink,
+ removePendingSandboxUiDeepLink,
+ shouldPurgeSandboxUiDeepLinks,
+} from '../sandboxUiDeepLinkState'
describe('shouldPurgeSandboxUiDeepLinks', () => {
it('keeps a cold-start link while the first user authenticates', () => {
@@ -16,3 +22,32 @@ describe('shouldPurgeSandboxUiDeepLinks', () => {
expect(shouldPurgeSandboxUiDeepLinks('user-a', 'user-a')).toBe(false)
})
})
+
+describe('pending sandbox UI deep-link state', () => {
+ it('merges live and cold-start links in FIFO order', () => {
+ let pending = enqueuePendingSandboxUiDeepLink([], { id: 2, appRef: 'ns/two' }, null)
+ pending = enqueuePendingSandboxUiDeepLink(pending, { id: 1, appRef: 'ns/one' }, null)
+
+ expect(pending.map(item => item.link.id)).toEqual([1, 2])
+ })
+
+ it('re-adds a link that arrives during its acknowledgement window', () => {
+ const link = { id: 1, appRef: 'ns/app' }
+ let pending = enqueuePendingSandboxUiDeepLink([], link, null)
+ pending = removePendingSandboxUiDeepLink(pending, link.id)
+ pending = enqueuePendingSandboxUiDeepLink(pending, link, null)
+
+ expect(pending).toHaveLength(1)
+ expect(pending[0]?.link).toEqual(link)
+ })
+
+ it('mirrors the bounded main-process queue size', () => {
+ let pending: PendingSandboxUiDeepLink[] = []
+ for (let id = 1; id <= MAX_PENDING_SANDBOX_UI_DEEP_LINKS + 2; id += 1) {
+ pending = enqueuePendingSandboxUiDeepLink(pending, { id, appRef: `ns/app-${id}` }, null)
+ }
+
+ expect(pending).toHaveLength(MAX_PENDING_SANDBOX_UI_DEEP_LINKS)
+ expect(pending[0]?.link.id).toBe(3)
+ })
+})
diff --git a/desktop-app/ui/src/lib/sandboxUiAppSelection.ts b/desktop-app/ui/src/lib/sandboxUiAppSelection.ts
index 178fe0725..bf35e8ee8 100644
--- a/desktop-app/ui/src/lib/sandboxUiAppSelection.ts
+++ b/desktop-app/ui/src/lib/sandboxUiAppSelection.ts
@@ -29,7 +29,8 @@ export function resolveSandboxUiDeepLinkApp(
apps: SandboxUiAppListing[],
appRef: string
): SandboxUiDeepLinkAppResolution {
- const match = apps.find(app => app.appRef === appRef)
+ const normalizedAppRef = appRef.toLowerCase()
+ const match = apps.find(app => app.appRef.toLowerCase() === normalizedAppRef)
if (!match) return { status: 'unavailable' }
if (!match.ready) {
return {
diff --git a/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts b/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts
index 8ae2ed13c..2707811b9 100644
--- a/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts
+++ b/desktop-app/ui/src/lib/sandboxUiAppSelection.types.ts
@@ -3,10 +3,12 @@ import type { ActiveSandboxUiApp } from '@/uiTypes'
export type SandboxUiAppListing = {
appRef: string
title?: string
+ description?: string
icon?: string
defaultPath: string
ready: boolean
phase?: string | null
+ updatedAt?: string | null
}
export type SandboxUiDeepLinkAppResolution =
diff --git a/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts b/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts
index 119c87875..9d2b28fbd 100644
--- a/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts
+++ b/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts
@@ -1,3 +1,8 @@
+import type { SandboxUiConversationOrigin } from '@pages/SandboxUiPage.types'
+import type { PendingSandboxUiDeepLink, SandboxUiDeepLinkEnvelope } from '@/App.types'
+
+export const MAX_PENDING_SANDBOX_UI_DEEP_LINKS = 20
+
export function shouldPurgeSandboxUiDeepLinks(
previousIdentity: string | null | undefined,
currentIdentity: string | null
@@ -8,3 +13,22 @@ export function shouldPurgeSandboxUiDeepLinks(
previousIdentity !== currentIdentity
)
}
+
+export function enqueuePendingSandboxUiDeepLink(
+ current: PendingSandboxUiDeepLink[],
+ link: SandboxUiDeepLinkEnvelope,
+ conversationOrigin: SandboxUiConversationOrigin | null
+): PendingSandboxUiDeepLink[] {
+ const existing = current.find(item => item.link.id === link.id)
+ const next = existing ? current : [...current, { link, conversationOrigin }]
+ return [...next]
+ .sort((left, right) => left.link.id - right.link.id)
+ .slice(-MAX_PENDING_SANDBOX_UI_DEEP_LINKS)
+}
+
+export function removePendingSandboxUiDeepLink(
+ current: PendingSandboxUiDeepLink[],
+ linkId: number
+): PendingSandboxUiDeepLink[] {
+ return current.filter(item => item.link.id !== linkId)
+}
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 6153ac92b..f47100b1c 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -8,18 +8,8 @@ import {
IconSandboxUi,
} from '../components/SidebarNav/icons'
import { clickableRowProps } from '../lib/clickableRowProps'
-import type { SandboxUiPageProps } from './SandboxUiPage.types'
-
-type App = {
- appRef: string
- title?: string
- description?: string
- icon?: string
- defaultPath: string
- ready: boolean
- phase: string | null
- updatedAt: string | null
-}
+import type { SandboxUiAppListing } from '../lib/sandboxUiAppSelection.types'
+import type { SandboxUiLaunchApp, SandboxUiPageProps } from './SandboxUiPage.types'
type PhasePillTone = 'allowed' | 'warning' | 'denied' | 'info' | 'muted'
@@ -68,7 +58,7 @@ function statusFromError(err: unknown): { status: number | null; message: string
return { status: m ? Number(m[1] ?? m[2]) : null, message }
}
-function appLabel(app: App): string {
+function appLabel(app: SandboxUiAppListing): string {
if (app.title && app.title.trim().length > 0) return app.title.trim()
return app.appRef
}
@@ -167,7 +157,7 @@ export function SandboxUiPage({
onEmbedBoundsApplied,
onNotify,
}: SandboxUiPageProps = {}) {
- const [apps, setApps] = useState<App[] | null>(null)
+ const [apps, setApps] = useState<SandboxUiAppListing[] | null>(null)
const [error, setError] = useState<string | null>(null)
const [launch, setLaunch] = useState<LaunchState>({ kind: 'idle' })
const [refreshError, setRefreshError] = useState<{ appRef: string; message: string } | null>(null)
@@ -234,14 +224,7 @@ export function SandboxUiPage({
}, [onEmbeddedAppBack])
const openApp = useCallback(
- async (app: {
- appRef: string
- label: string
- icon?: string
- defaultPath: string
- routePath?: string
- ready?: boolean
- }) => {
+ async (app: SandboxUiLaunchApp) => {
if (app.ready === false) return
const [recipeNs, recipeName] = app.appRef.split('/', 2)
if (!recipeNs || !recipeName) return
@@ -290,7 +273,7 @@ export function SandboxUiPage({
)
const onOpen = useCallback(
- async (app: App) => {
+ async (app: SandboxUiAppListing) => {
await openApp({
appRef: app.appRef,
label: appLabel(app),
@@ -320,8 +303,8 @@ export function SandboxUiPage({
const handleBackToConversation = useCallback(async () => {
if (!conversationOrigin || !onBackToConversation) return
- await closeEmbed()
await onBackToConversation()
+ await closeEmbed()
}, [closeEmbed, conversationOrigin, onBackToConversation])
// In-place hard-reload of the embedded app — fetches freshly-arrived
@@ -563,11 +546,11 @@ export function SandboxUiPage({
)
}
- const appIcon = (app: App) =>
+ const appIcon = (app: SandboxUiAppListing) =>
app.icon ? <img src={app.icon} alt="" width={20} height={20} /> : <IconSandboxUi />
- const appStatusPill = (app: App) => {
- const pill = phasePill(app.phase)
+ const appStatusPill = (app: SandboxUiAppListing) => {
+ const pill = phasePill(app.phase ?? null)
return <span className={`apps-status-pill apps-status-pill--${pill.tone}`}>{pill.label}</span>
}
@@ -581,7 +564,7 @@ export function SandboxUiPage({
)
const showAppPagination = totalAppPages > 1
- const gridCardProps = (app: App, activatable: boolean, activate: () => void) => {
+ const gridCardProps = (app: SandboxUiAppListing, activatable: boolean, activate: () => void) => {
if (!activatable) return {}
return clickableRowProps(activate, { ariaLabel: `Open ${appLabel(app)}` })
}
@@ -628,7 +611,9 @@ export function SandboxUiPage({
</span>
<span className="apps-grid__card-title">{appLabel(app)}</span>
{appStatusPill(app)}
- <span className="apps-card-meta__updated">{formatLastUpdated(app.updatedAt)}</span>
+ <span className="apps-card-meta__updated">
+ {formatLastUpdated(app.updatedAt ?? null)}
+ </span>
{app.description ? (
<span className="apps-grid__card-desc">{app.description}</span>
) : null}
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.types.ts b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
index b9449139c..a120c8672 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.types.ts
+++ b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
@@ -7,6 +7,10 @@ export type SandboxUiConversationOrigin = {
teamId?: string
}
+export type SandboxUiLaunchApp = ActiveSandboxUiApp & {
+ ready?: boolean
+}
+
export type SandboxUiPageProps = {
boundsRefreshKey?: string | number
conversationOrigin?: SandboxUiConversationOrigin | null
diff --git a/packages/desktop-app-links/index.cjs b/packages/desktop-app-links/index.cjs
index 68db314ee..326808ef7 100644
--- a/packages/desktop-app-links/index.cjs
+++ b/packages/desktop-app-links/index.cjs
@@ -75,7 +75,6 @@ function buildSandboxUiDeepLink(parts) {
function buildSandboxUiWebLink(profileUiBaseUrl, parts) {
const valid = validateParts(parts)
if (!valid) throw new Error('Cannot create a deep link for this app route')
- const deepLink = new URL(buildSandboxUiDeepLink(valid))
let baseUrl
try {
baseUrl = new URL(profileUiBaseUrl)
@@ -86,13 +85,15 @@ function buildSandboxUiWebLink(profileUiBaseUrl, parts) {
throw new Error('Cannot create a shareable link for this desktop environment')
}
- baseUrl.search = ''
baseUrl.hash = ''
const basePath = baseUrl.pathname.replace(/\/+$/, '')
baseUrl.pathname =
`${basePath}${SANDBOX_UI_WEB_LINK_PATH}/${encodeURIComponent(valid.recipeNs)}/` +
encodeURIComponent(valid.recipeName)
- baseUrl.search = deepLink.search
+ const search = new URLSearchParams()
+ if (valid.path) search.set('path', valid.path)
+ if (valid.teamId) search.set('team', valid.teamId)
+ baseUrl.search = search.toString()
return baseUrl.toString()
}
@@ -105,18 +106,19 @@ function parseSandboxUiDeepLink(rawUrl) {
}
if (
parsed.protocol !== SANDBOX_UI_DEEP_LINK_PROTOCOL ||
- parsed.hostname !== SANDBOX_UI_DEEP_LINK_HOST
+ parsed.hostname !== SANDBOX_UI_DEEP_LINK_HOST ||
+ parsed.port
) {
return null
}
- const segments = parsed.pathname.split('/').filter(Boolean)
- if (segments.length !== 2) return null
+ const segments = parsed.pathname.split('/')
+ if (segments.length !== 3 || segments[0] !== '' || !segments[1] || !segments[2]) return null
let recipeNs
let recipeName
try {
- recipeNs = decodeURIComponent(segments[0] || '')
- recipeName = decodeURIComponent(segments[1] || '')
+ recipeNs = decodeURIComponent(segments[1] || '')
+ recipeName = decodeURIComponent(segments[2] || '')
} catch {
return null
}
@@ -136,7 +138,7 @@ function parseSandboxUiDeepLink(rawUrl) {
function sandboxUiDeepLinkTargetsEqual(left, right) {
return (
- left.appRef === right.appRef &&
+ left.appRef.toLowerCase() === right.appRef.toLowerCase() &&
(left.path || '') === (right.path || '') &&
(left.teamId || '') === (right.teamId || '')
)
diff --git a/packages/desktop-app-links/index.test.cjs b/packages/desktop-app-links/index.test.cjs
new file mode 100644
index 000000000..fda4dca2d
--- /dev/null
+++ b/packages/desktop-app-links/index.test.cjs
@@ -0,0 +1,37 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const fs = require('node:fs')
+const path = require('node:path')
+const test = require('node:test')
+const links = require('./index.cjs')
+
+test('runtime exports 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),
+ match => match[1]
+ ).sort()
+
+ assert.deepEqual(Object.keys(links).sort(), declaredRuntimeExports)
+})
+
+test('web and desktop links use the same canonical route contract', () => {
+ const target = {
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'task-board',
+ path: '/tasks/42',
+ teamId: 'team-1',
+ }
+
+ assert.equal(
+ links.buildSandboxUiWebLink('https://profile.example.com', target),
+ 'https://profile.example.com/open/apps/sandbox-recipes/task-board' +
+ '?path=%2Ftasks%2F42&team=team-1'
+ )
+ assert.deepEqual(links.parseSandboxUiDeepLink(links.buildSandboxUiDeepLink(target)), {
+ appRef: 'sandbox-recipes/task-board',
+ path: '/tasks/42',
+ teamId: 'team-1',
+ })
+})
diff --git a/packages/desktop-app-links/package-lock.json b/packages/desktop-app-links/package-lock.json
new file mode 100644
index 000000000..c8ca7704f
--- /dev/null
+++ b/packages/desktop-app-links/package-lock.json
@@ -0,0 +1,12 @@
+{
+ "name": "@clerum/desktop-app-links",
+ "version": "0.1.1",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@clerum/desktop-app-links",
+ "version": "0.1.1"
+ }
+ }
+}
diff --git a/packages/desktop-app-links/package.json b/packages/desktop-app-links/package.json
index d56920d8f..016bf64fa 100644
--- a/packages/desktop-app-links/package.json
+++ b/packages/desktop-app-links/package.json
@@ -1,8 +1,12 @@
{
"name": "@clerum/desktop-app-links",
- "version": "0.1.0",
+ "version": "0.1.1",
"private": true,
"type": "commonjs",
"main": "index.cjs",
- "types": "index.d.ts"
+ "types": "index.d.ts",
+ "scripts": {
+ "build": "node --check index.cjs",
+ "test": "node --test index.test.cjs"
+ }
}
diff --git a/profile-ui/Dockerfile b/profile-ui/Dockerfile
index c2c533fef..4496c54a9 100644
--- a/profile-ui/Dockerfile
+++ b/profile-ui/Dockerfile
@@ -1,24 +1,32 @@
FROM node:24-alpine AS builder
WORKDIR /app
-COPY package*.json ./
-RUN npm ci
+COPY packages/desktop-app-links ./packages/desktop-app-links
+COPY profile-ui/package*.json ./profile-ui/
+WORKDIR /app/profile-ui
+# Next's bundler does not follow file: symlinks reliably, so materialize the
+# shared package as a real copy inside node_modules.
+RUN npm ci \
+ && rm -rf node_modules/@clerum/desktop-app-links \
+ && mkdir -p node_modules/@clerum \
+ && cp -R ../packages/desktop-app-links node_modules/@clerum/desktop-app-links
-COPY . .
+COPY profile-ui ./
RUN npm run build
FROM node:24-alpine
RUN addgroup -S app && adduser -S app -G app
-WORKDIR /app
+WORKDIR /app/profile-ui
ENV NODE_ENV=production
ENV PORT=3001
-COPY --from=builder --chown=app:app /app/package*.json ./
-COPY --from=builder --chown=app:app /app/.next ./.next
-COPY --from=builder --chown=app:app /app/node_modules ./node_modules
-COPY --from=builder --chown=app:app /app/next.config.js ./next.config.js
-COPY --from=builder --chown=app:app /app/public ./public
+COPY --from=builder --chown=app:app /app/packages /app/packages
+COPY --from=builder --chown=app:app /app/profile-ui/package*.json ./
+COPY --from=builder --chown=app:app /app/profile-ui/.next ./.next
+COPY --from=builder --chown=app:app /app/profile-ui/node_modules ./node_modules
+COPY --from=builder --chown=app:app /app/profile-ui/next.config.js ./next.config.js
+COPY --from=builder --chown=app:app /app/profile-ui/public ./public
USER app
EXPOSE 3001
diff --git a/profile-ui/Makefile b/profile-ui/Makefile
index 977904e54..9cf45d407 100644
--- a/profile-ui/Makefile
+++ b/profile-ui/Makefile
@@ -15,7 +15,7 @@ dev: install
EXTERNAL_REST_API_INTERNAL_URL=http://localhost:8091 npm run dev -- --port $(PORT)
docker-build:
- docker build -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) .
+ docker build -f Dockerfile -t $(REGISTRY)/$(IMAGE_NAME):$(TAG) ..
docker-push: docker-build
docker push $(REGISTRY)/$(IMAGE_NAME):$(TAG)
diff --git a/profile-ui/app/constants/routes.ts b/profile-ui/app/constants/routes.ts
index 5f5eb9dca..83efd5f86 100644
--- a/profile-ui/app/constants/routes.ts
+++ b/profile-ui/app/constants/routes.ts
@@ -1,3 +1,5 @@
+import { SANDBOX_UI_WEB_LINK_PATH } from '@clerum/desktop-app-links'
+
type QueryValue = boolean | number | string | null | undefined
type ProfileRouteQuery = Record<string, QueryValue>
@@ -25,6 +27,8 @@ export const PROFILE_ROUTES = {
desktopSetup: '/desktop-setup',
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)}`,
members: {
root: '/members',
invite: '/members/invite',
diff --git a/profile-ui/lib/desktopAppLinks.ts b/profile-ui/lib/desktopAppLinks.ts
index 7e4820f4b..41db9f555 100644
--- a/profile-ui/lib/desktopAppLinks.ts
+++ b/profile-ui/lib/desktopAppLinks.ts
@@ -1,4 +1,8 @@
-import { buildSandboxUiDeepLink } from '@clerum/desktop-app-links'
+import {
+ SANDBOX_UI_DEEP_LINK_HOST,
+ SANDBOX_UI_DEEP_LINK_PROTOCOL,
+ buildSandboxUiDeepLink,
+} from '@clerum/desktop-app-links'
const SCRIPT_NONCE_PATTERN = /^[A-Za-z0-9+/_-]+={0,2}$/
@@ -45,7 +49,10 @@ export function buildEvenfireDesktopAppRedirectDocument(
scriptNonce: string
): string {
const parsed = new URL(deepLink)
- if (parsed.protocol !== 'evenfire:' || parsed.hostname !== 'app') {
+ if (
+ parsed.protocol !== SANDBOX_UI_DEEP_LINK_PROTOCOL ||
+ parsed.hostname !== SANDBOX_UI_DEEP_LINK_HOST
+ ) {
throw new Error('Cannot redirect to an invalid desktop app link')
}
@@ -59,7 +66,7 @@ export function buildEvenfireDesktopAppRedirectDocument(
<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="${escapeHtml(nonce)}">
+ <style nonce="${nonce}">
:root {
color-scheme: dark;
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
@@ -160,7 +167,7 @@ export function buildEvenfireDesktopAppRedirectDocument(
</p>
</section>
</main>
- <script nonce="${escapeHtml(nonce)}">window.location.replace(${scriptLink})</script>
+ <script nonce="${nonce}">window.location.replace(${scriptLink})</script>
</body>
</html>`
}
diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.json
index 23c5a7c7c..c219203e7 100644
--- a/profile-ui/package-lock.json
+++ b/profile-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.108",
+ "version": "0.1.109",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-profile-ui",
- "version": "0.1.108",
+ "version": "0.1.109",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
"next": "16.2.11",
diff --git a/profile-ui/package.json b/profile-ui/package.json
index 7a82baada..d5ce6c1de 100644
--- a/profile-ui/package.json
+++ b/profile-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.108",
+ "version": "0.1.109",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/scripts/minikube/build-images.sh b/scripts/minikube/build-images.sh
index 7c012c1aa..6c0180bb4 100755
--- a/scripts/minikube/build-images.sh
+++ b/scripts/minikube/build-images.sh
@@ -542,8 +542,9 @@ else
build_control_ui_image
build_image "profile-ui" \
- "${PROJECT_DIR}/profile-ui" \
- "clerum/profile-ui:test"
+ "${PROJECT_DIR}" \
+ "clerum/profile-ui:test" \
+ "${PROJECT_DIR}/profile-ui/Dockerfile"
fi
# Registry now lives in the sibling evenfire-registry repo. Use
diff --git a/scripts/prettier/paths.mjs b/scripts/prettier/paths.mjs
index 4dcdf53f2..79a7d6a35 100644
--- a/scripts/prettier/paths.mjs
+++ b/scripts/prettier/paths.mjs
@@ -8,6 +8,7 @@ export const projectRoots = [
'mcp-host',
'mcp-proxy',
'mcp-servers',
+ 'packages/desktop-app-links',
'packages/workflow-sdk',
'profile-ui',
'rpc-proxy',
@@ -28,6 +29,7 @@ export const packageRoots = [
'mcp-servers',
'mcp-servers/doc-generator',
'mcp-servers/web-search',
+ 'packages/desktop-app-links',
'packages/workflow-sdk',
'profile-ui',
'rpc-proxy',