Skip to content

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

TypeScript

feat: add desktop app deep links

Josué72cdbe3205db
diff --git a/desktop-app/forge.config.js b/desktop-app/forge.config.js
index f2b0950a9..2876a1ed8 100644
--- a/desktop-app/forge.config.js
+++ b/desktop-app/forge.config.js
@@ -144,6 +144,16 @@ module.exports = {
afterCopyExtraResources: [compileMacAdaptiveIcon],
appBundleId: process.env.APPLE_BUNDLE_ID || defaultAppleBundleId,
appCategoryType: 'public.app-category.productivity',
+ protocols: [
+ {
+ name: 'Evenfire',
+ schemes: ['evenfire'],
+ },
+ {
+ name: 'Clerum OAuth callback',
+ schemes: ['clerum'],
+ },
+ ],
...(osxSign ? { osxSign } : {}),
...(osxNotarize ? { osxNotarize } : {}),
},
@@ -191,6 +201,7 @@ module.exports = {
bin: 'Evenfire',
categories: ['Utility'],
icon: path.join(assetsDirectory, 'icon.png'),
+ mimeType: ['x-scheme-handler/evenfire', 'x-scheme-handler/clerum'],
},
},
},
@@ -206,6 +217,7 @@ module.exports = {
license: desktopLicense,
categories: ['Utility'],
icon: path.join(assetsDirectory, 'icon.png'),
+ mimeType: ['x-scheme-handler/evenfire', 'x-scheme-handler/clerum'],
},
},
},
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index f5fad84ae..35e07cd19 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.313",
+ "version": "0.1.314",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.313",
+ "version": "0.1.314",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index ba540b0c3..3c04f428a 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.313",
+ "version": "0.1.314",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts b/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts
new file mode 100644
index 000000000..2b28812ce
--- /dev/null
+++ b/desktop-app/src/__tests__/sandboxUiDeepLinks.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest'
+import {
+ buildSandboxUiDeepLink,
+ extractSandboxUiViewRoute,
+ parseSandboxUiDeepLink,
+} from '../sandboxUiDeepLinks.js'
+
+describe('sandbox UI deep links', () => {
+ it('round-trips an app route, query, fragment, and team', () => {
+ const url = buildSandboxUiDeepLink({
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'agentic-task-board',
+ path: '/boards/product/tasks/task-42?view=detail#activity',
+ teamId: 'team-123',
+ })
+
+ expect(parseSandboxUiDeepLink(url)).toEqual({
+ appRef: 'sandbox-recipes/agentic-task-board',
+ path: '/boards/product/tasks/task-42?view=detail#activity',
+ teamId: 'team-123',
+ })
+ })
+
+ it('rejects malformed app routes and unrelated evenfire links', () => {
+ expect(parseSandboxUiDeepLink('evenfire://[email protected]')).toBeNull()
+ expect(
+ parseSandboxUiDeepLink(
+ 'evenfire://app/sandbox-recipes/agentic-task-board?path=https%3A%2F%2Fevil.example'
+ )
+ ).toBeNull()
+ expect(
+ parseSandboxUiDeepLink(
+ 'evenfire://app/sandbox-recipes/agentic-task-board?path=%2F%2Fevil.example'
+ )
+ ).toBeNull()
+ expect(
+ parseSandboxUiDeepLink('evenfire://app/sandbox-recipes/agentic-task-board?team=team%2Fother')
+ ).toBeNull()
+ expect(parseSandboxUiDeepLink('https://example.com/app')).toBeNull()
+ })
+
+ it('extracts the current route from the active embedded app URL', () => {
+ expect(
+ extractSandboxUiViewRoute({
+ currentUrl:
+ 'https://rpc.example/api/v1/sandbox-ui/sandbox-recipes/' +
+ 'agentic-task-board/view/tasks/task-42?panel=comments#latest',
+ rpcProxyOrigin: 'https://rpc.example/',
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'agentic-task-board',
+ })
+ ).toBe('/tasks/task-42?panel=comments#latest')
+ })
+
+ it('does not extract routes from another origin or recipe', () => {
+ expect(
+ extractSandboxUiViewRoute({
+ currentUrl:
+ 'https://other.example/api/v1/sandbox-ui/sandbox-recipes/' +
+ 'agentic-task-board/view/tasks/task-42',
+ rpcProxyOrigin: 'https://rpc.example',
+ recipeNs: 'sandbox-recipes',
+ recipeName: 'agentic-task-board',
+ })
+ ).toBeNull()
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index c12948519..3f005546d 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -2830,6 +2830,19 @@ export class AppService {
await driver.unmountSandboxUiView()
}
+ async createSandboxUiDeepLink(teamId?: string): Promise<{ url: string }> {
+ const driver = await import('./sandboxUiDriver.js')
+ const { buildSandboxUiDeepLink } = await import('./sandboxUiDeepLinks.js')
+ const location = driver.getActiveSandboxUiLocation()
+ if (!location) throw new Error('No app is currently open')
+ return {
+ url: buildSandboxUiDeepLink({
+ ...location,
+ teamId: String(teamId || '').trim() || undefined,
+ }),
+ }
+ }
+
// In-place hard-reload of the active embed (user-initiated "Refresh"). The
// session cookie is still valid, so this only reloads page content — it does
// NOT re-mint the session or cancel the refresh timer. No-op when nothing is
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index ee9ac25e2..6f2616b7d 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -1,4 +1,12 @@
-import { BrowserWindow, IpcMainInvokeEvent, Notification, app, dialog, ipcMain } from 'electron'
+import {
+ BrowserWindow,
+ IpcMainInvokeEvent,
+ Notification,
+ app,
+ clipboard,
+ dialog,
+ ipcMain,
+} from 'electron'
import { randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import path from 'node:path'
@@ -1333,6 +1341,14 @@ export function registerIpcHandlers(service: AppService): void {
await service.reloadSandboxUi()
})
+ ipcMain.handle('sandboxUi:copyDeepLink', async (event, payload: { teamId?: unknown }) => {
+ assertTrustedSender(event)
+ const teamId = sanitizeString(payload?.teamId)
+ const result = await service.createSandboxUiDeepLink(teamId || undefined)
+ clipboard.writeText(result.url)
+ return result
+ })
+
ipcMain.handle('sandboxUi:setBounds', async (event, payload: { bounds: unknown }) => {
assertTrustedSender(event)
const bounds = parseBounds(payload?.bounds)
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index 332e712e8..5ce7115d0 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -3,6 +3,7 @@ import path from 'node:path'
import { AppService } from './appService.js'
import { config } from './config.js'
import { assertTrustedSender, registerIpcHandlers } from './ipc.js'
+import { type SandboxUiDeepLinkEnvelope, parseSandboxUiDeepLink } from './sandboxUiDeepLinks.js'
import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'
const EVENFIRE_APP_NAME = 'Evenfire'
@@ -19,6 +20,9 @@ process.stderr?.on?.('error', () => {})
let mainWindow: BrowserWindow | null = null
const appService = new AppService()
const pendingEvenfireUrls: string[] = []
+const pendingSandboxUiDeepLinks: SandboxUiDeepLinkEnvelope[] = []
+let sandboxUiDeepLinkSequence = 0
+let lastSandboxUiDeepLink: { rawUrl: string; receivedAt: number } | null = null
function systemIconAssetsDirectory(): string {
return app.isPackaged ? process.resourcesPath : path.join(__dirname, '../assets')
@@ -85,9 +89,53 @@ ipcMain.handle('window:getVisibility', event => {
assertTrustedSender(event)
return { visible: isWindowVisible(mainWindow) }
})
+
+ipcMain.handle('sandboxUi:listPendingDeepLinks', event => {
+ assertTrustedSender(event)
+ return { links: [...pendingSandboxUiDeepLinks] }
+})
+
+ipcMain.handle('sandboxUi:acknowledgeDeepLink', (event, payload: { id?: unknown }) => {
+ assertTrustedSender(event)
+ const id = Number(payload?.id)
+ if (!Number.isInteger(id) || id <= 0) throw new Error('Invalid app deep-link id')
+ const index = pendingSandboxUiDeepLinks.findIndex(link => link.id === id)
+ if (index >= 0) pendingSandboxUiDeepLinks.splice(index, 1)
+})
const DESKTOP_SETUP_PROTOCOL = 'evenfire'
const CLERUM_PROTOCOL = 'clerum'
+function focusMainWindow(): void {
+ if (!mainWindow || mainWindow.isDestroyed()) return
+ if (mainWindow.isMinimized()) mainWindow.restore()
+ mainWindow.show()
+ mainWindow.focus()
+}
+
+function handleSandboxUiDeepLink(rawUrl: string): boolean {
+ const target = parseSandboxUiDeepLink(rawUrl)
+ if (!target) return false
+
+ const now = Date.now()
+ if (lastSandboxUiDeepLink?.rawUrl === rawUrl && now - lastSandboxUiDeepLink.receivedAt < 1_000) {
+ focusMainWindow()
+ return true
+ }
+ lastSandboxUiDeepLink = { rawUrl, receivedAt: now }
+
+ const envelope: SandboxUiDeepLinkEnvelope = {
+ id: (sandboxUiDeepLinkSequence += 1),
+ ...target,
+ }
+ pendingSandboxUiDeepLinks.push(envelope)
+ if (pendingSandboxUiDeepLinks.length > 20) pendingSandboxUiDeepLinks.shift()
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.webContents.send('sandboxUi:deepLink', envelope)
+ }
+ focusMainWindow()
+ return true
+}
+
function registerCustomProtocols(): void {
// In dev mode (`electron .`), Electron needs the explicit execPath +
// script-path argument vector to relaunch correctly when the OS hands a
@@ -113,6 +161,11 @@ function handleEvenfireUrl(rawUrl: string): void {
return
}
+ if (parsed.hostname === 'app') {
+ handleSandboxUiDeepLink(rawUrl)
+ return
+ }
+
if (parsed.hostname === 'logout') {
void appService.logout().finally(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
@@ -205,11 +258,7 @@ if (!gotSingleInstanceLock) {
if (desktopSetupLink) handleEvenfireUrl(desktopSetupLink)
const clerumLink = argv.find(arg => arg.startsWith(`${CLERUM_PROTOCOL}://`))
if (clerumLink) handleClerumUrl(clerumLink)
- if (mainWindow && !mainWindow.isDestroyed()) {
- if (mainWindow.isMinimized()) mainWindow.restore()
- mainWindow.show()
- mainWindow.focus()
- }
+ focusMainWindow()
})
}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index ddee686a6..acb731f15 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -410,10 +410,24 @@ const clerum = Object.freeze({
}) => ipcRenderer.invoke('sandboxUi:open', args),
close: () => ipcRenderer.invoke('sandboxUi:close'),
reload: () => ipcRenderer.invoke('sandboxUi:reload'),
+ copyDeepLink: (teamId?: string) => ipcRenderer.invoke('sandboxUi:copyDeepLink', { teamId }),
+ listPendingDeepLinks: () => ipcRenderer.invoke('sandboxUi:listPendingDeepLinks'),
+ acknowledgeDeepLink: (id: number) =>
+ ipcRenderer.invoke('sandboxUi:acknowledgeDeepLink', { id }),
setBounds: (bounds: { x: number; y: number; width: number; height: number; dpr?: number }) =>
ipcRenderer.invoke('sandboxUi:setBounds', { bounds }),
setVisible: (visible: boolean) => ipcRenderer.invoke('sandboxUi:setVisible', { visible }),
capturePreview: () => ipcRenderer.invoke('sandboxUi:capturePreview'),
+ onDeepLink: (
+ callback: (args: { id: number; appRef: string; path: string; teamId?: string }) => void
+ ) => {
+ const listener = (
+ _event: unknown,
+ args: { id: number; appRef: string; path: string; teamId?: string }
+ ) => callback(args)
+ ipcRenderer.on('sandboxUi:deepLink', listener)
+ return () => ipcRenderer.off('sandboxUi:deepLink', listener)
+ },
onClosed: (callback: (args: { appRef: string }) => void) => {
const listener = (_event: unknown, args: { appRef: string }) => callback(args)
ipcRenderer.on('sandboxUi:closed', listener)
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index b5ce754a8..323a7ebbc 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -1,3 +1,4 @@
+import type { SandboxUiDeepLinkEnvelope } from './sandboxUiDeepLinks.js'
import {
AccessCatalog,
ApprovalDecisionResult,
@@ -533,6 +534,9 @@ declare global {
}) => Promise<void>
close: () => Promise<void>
reload: () => Promise<void>
+ copyDeepLink: (teamId?: string) => Promise<{ url: string }>
+ listPendingDeepLinks: () => Promise<{ links: SandboxUiDeepLinkEnvelope[] }>
+ acknowledgeDeepLink: (id: number) => Promise<void>
setBounds: (bounds: {
x: number
y: number
@@ -542,6 +546,7 @@ declare global {
}) => Promise<void>
setVisible: (visible: boolean) => Promise<void>
capturePreview: () => Promise<string | null>
+ onDeepLink: (callback: (args: SandboxUiDeepLinkEnvelope) => void) => () => void
onClosed: (callback: (args: { appRef: string }) => void) => () => void
onRefreshError: (
callback: (args: { appRef: string; message: string }) => void
diff --git a/desktop-app/src/sandboxUiDeepLinks.ts b/desktop-app/src/sandboxUiDeepLinks.ts
new file mode 100644
index 000000000..a54665228
--- /dev/null
+++ b/desktop-app/src/sandboxUiDeepLinks.ts
@@ -0,0 +1,135 @@
+export const SANDBOX_UI_DEEP_LINK_HOST = 'app'
+export const SANDBOX_UI_DEEP_LINK_PROTOCOL = 'evenfire:'
+
+const MAX_APP_SEGMENT_LENGTH = 253
+const MAX_APP_ROUTE_LENGTH = 4096
+const MAX_TEAM_ID_LENGTH = 255
+const APP_SEGMENT_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/
+const TEAM_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/
+
+export type SandboxUiDeepLinkTarget = {
+ appRef: string
+ path: string
+ teamId?: string
+}
+
+export type SandboxUiDeepLinkEnvelope = SandboxUiDeepLinkTarget & {
+ id: number
+}
+
+type SandboxUiDeepLinkParts = {
+ recipeNs: string
+ recipeName: string
+ path: string
+ teamId?: string
+}
+
+type SandboxUiViewRouteInput = {
+ currentUrl: string
+ rpcProxyOrigin: string
+ recipeNs: string
+ recipeName: string
+}
+
+function isValidAppSegment(value: string): boolean {
+ return (
+ value.length > 0 && value.length <= MAX_APP_SEGMENT_LENGTH && APP_SEGMENT_PATTERN.test(value)
+ )
+}
+
+function normalizeTeamId(rawTeamId: string | undefined): string | null {
+ const teamId = String(rawTeamId || '').trim()
+ if (!teamId) return ''
+ if (teamId.length > MAX_TEAM_ID_LENGTH || !TEAM_ID_PATTERN.test(teamId)) return null
+ return teamId
+}
+
+export function normalizeSandboxUiRoute(rawPath: string): string | null {
+ const path = String(rawPath || '').trim()
+ if (
+ !path ||
+ path.length > MAX_APP_ROUTE_LENGTH ||
+ !path.startsWith('/') ||
+ path.startsWith('//') ||
+ path.includes('\\')
+ ) {
+ return null
+ }
+ if (/[\u0000-\u001f\u007f]/.test(path)) return null
+ return path
+}
+
+export function buildSandboxUiDeepLink(parts: SandboxUiDeepLinkParts): string {
+ const recipeNs = String(parts.recipeNs || '').trim()
+ const recipeName = String(parts.recipeName || '').trim()
+ const path = normalizeSandboxUiRoute(parts.path)
+ const teamId = normalizeTeamId(parts.teamId)
+ if (!isValidAppSegment(recipeNs) || !isValidAppSegment(recipeName) || !path || teamId === null) {
+ throw new Error('Cannot create a deep link for this app route')
+ }
+
+ const url = new URL(
+ `${SANDBOX_UI_DEEP_LINK_PROTOCOL}//${SANDBOX_UI_DEEP_LINK_HOST}/` +
+ `${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}`
+ )
+ url.searchParams.set('path', path)
+ if (teamId) url.searchParams.set('team', teamId)
+ return url.toString()
+}
+
+export function parseSandboxUiDeepLink(rawUrl: string): SandboxUiDeepLinkTarget | null {
+ let parsed: URL
+ try {
+ parsed = new URL(rawUrl)
+ } catch {
+ return null
+ }
+ if (
+ parsed.protocol !== SANDBOX_UI_DEEP_LINK_PROTOCOL ||
+ parsed.hostname !== SANDBOX_UI_DEEP_LINK_HOST
+ ) {
+ return null
+ }
+
+ const segments = parsed.pathname.split('/').filter(Boolean)
+ if (segments.length !== 2) return null
+ let recipeNs: string
+ let recipeName: string
+ try {
+ recipeNs = decodeURIComponent(segments[0] || '')
+ recipeName = decodeURIComponent(segments[1] || '')
+ } catch {
+ return null
+ }
+ if (!isValidAppSegment(recipeNs) || !isValidAppSegment(recipeName)) return null
+
+ const path = normalizeSandboxUiRoute(parsed.searchParams.get('path') || '/')
+ if (!path) return null
+ const teamId = normalizeTeamId(parsed.searchParams.get('team') || undefined)
+ if (teamId === null) return null
+ return {
+ appRef: `${recipeNs}/${recipeName}`,
+ path,
+ ...(teamId ? { teamId } : {}),
+ }
+}
+
+export function extractSandboxUiViewRoute(input: SandboxUiViewRouteInput): string | null {
+ let current: URL
+ let proxy: URL
+ try {
+ current = new URL(input.currentUrl)
+ proxy = new URL(input.rpcProxyOrigin)
+ } catch {
+ return null
+ }
+ if (current.origin !== proxy.origin) return null
+
+ const prefix =
+ `/api/v1/sandbox-ui/${encodeURIComponent(input.recipeNs)}/` +
+ `${encodeURIComponent(input.recipeName)}/view`
+ if (current.pathname !== prefix && !current.pathname.startsWith(`${prefix}/`)) return null
+
+ const pathname = current.pathname.slice(prefix.length) || '/'
+ return normalizeSandboxUiRoute(`${pathname}${current.search}${current.hash}`)
+}
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index d6cd80416..1b1cf892c 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -1,6 +1,7 @@
import { BrowserWindow, WebContentsView, session } from 'electron'
import path from 'node:path'
import { getActiveEnvKey } from './config.js'
+import { extractSandboxUiViewRoute } from './sandboxUiDeepLinks.js'
import { touchSandboxUiPartition } from './sandboxUiPartitionGc.js'
import {
applySandboxUiNavigationPolicies,
@@ -91,6 +92,7 @@ type ActiveView = {
view: WebContentsView
recipeNs: string
recipeName: string
+ initialPath: string
partition: string
parentWindow: BrowserWindow
rpcProxyOrigin: string
@@ -113,6 +115,25 @@ export function getActiveSandboxUi(): {
}
}
+export function getActiveSandboxUiLocation(): {
+ recipeNs: string
+ recipeName: string
+ path: string
+} | null {
+ if (!active) return null
+ const currentPath = extractSandboxUiViewRoute({
+ currentUrl: active.view.webContents.getURL(),
+ rpcProxyOrigin: active.rpcProxyOrigin,
+ recipeNs: active.recipeNs,
+ recipeName: active.recipeName,
+ })
+ return {
+ recipeNs: active.recipeNs,
+ recipeName: active.recipeName,
+ path: currentPath ?? active.initialPath,
+ }
+}
+
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)
@@ -259,6 +280,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
const partition = partitionFor(getActiveEnvKey(), recipeNs, recipeName)
const proxyOriginUrl = new URL(rpcProxyUrl).toString().replace(/\/+$/, '')
+ const viewPath = defaultPath && defaultPath.startsWith('/') ? defaultPath : '/'
const allowedNavigationPrefix =
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
`${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view/`
@@ -328,6 +350,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
view,
recipeNs,
recipeName,
+ initialPath: viewPath,
partition,
parentWindow,
rpcProxyOrigin: proxyOriginUrl,
@@ -347,7 +370,6 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
console.warn('[SandboxUI] touchSandboxUiPartition failed:', err)
})
- const viewPath = defaultPath && defaultPath.startsWith('/') ? defaultPath : '/'
const url =
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
`${encodeURIComponent(recipeNs)}/${encodeURIComponent(recipeName)}/view${viewPath}`
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 0178b9e78..25e788609 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -32,6 +32,7 @@ import { TeamDetailsPage } from '@pages/TeamDetailsPage'
import { TeamsPage } from '@pages/TeamsPage'
import { UnavailablePage } from '@pages/UnavailablePage'
import { WorkflowsPage } from '@pages/WorkflowsPage'
+import type { PendingSandboxUiDeepLink, SandboxUiDeepLinkEnvelope } from '@/App.types'
import type { ActiveSandboxUiApp, ThemeMode } from '@/uiTypes'
function getInitialThemeMode(): ThemeMode {
@@ -152,7 +153,12 @@ export function App() {
[]
)
const [sandboxUiShortcutOpenRequestId, setSandboxUiShortcutOpenRequestId] = React.useState(0)
+ const [pendingSandboxUiDeepLinks, setPendingSandboxUiDeepLinks] = React.useState<
+ PendingSandboxUiDeepLink[]
+ >([])
const contentPanelRef = React.useRef<HTMLElement | null>(null)
+ const activeConversationOriginRef = React.useRef<SandboxUiConversationOrigin | null>(null)
+ const processingSandboxUiDeepLinkIdRef = React.useRef<number | null>(null)
const isAgentChatView =
(vm.navItem === DESKTOP_ROUTES.agents && Boolean(vm.selectedAgent)) ||
(vm.navItem === DESKTOP_ROUTES.chat && Boolean(vm.selectedAgent))
@@ -171,8 +177,17 @@ export function App() {
agentName: vm.selectedAgent,
chatId: vm.activeChatId,
title: conversation?.title.trim() || 'Conversation',
+ teamId: vm.currentTeamId || undefined,
}
- }, [vm.activeChatId, vm.chatList, vm.latestChatSessions, vm.navItem, vm.selectedAgent])
+ }, [
+ vm.activeChatId,
+ vm.chatList,
+ vm.currentTeamId,
+ vm.latestChatSessions,
+ vm.navItem,
+ vm.selectedAgent,
+ ])
+ activeConversationOriginRef.current = activeConversationOrigin
React.useEffect(() => {
document.documentElement.setAttribute('data-theme', themeMode)
@@ -194,6 +209,13 @@ export function App() {
React.useEffect(() => {
if (!vm.isAuthenticated) {
setAvailableSandboxUiApps([])
+ setActiveSandboxUiApp(null)
+ setSandboxUiConversationOrigin(null)
+ setPendingSandboxUiDeepLinks(current =>
+ current.map(item =>
+ item.conversationOrigin ? { ...item, conversationOrigin: null } : item
+ )
+ )
return
}
@@ -218,7 +240,7 @@ export function App() {
window.removeEventListener('focus', refreshKeepingCurrentList)
window.clearInterval(intervalId)
}
- }, [vm.isAuthenticated])
+ }, [vm.currentTeamId, vm.isAuthenticated])
const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp) => {
setActiveSandboxUiApp(app)
@@ -238,19 +260,33 @@ export function App() {
setSidebarSettingsMenuOpen(false)
}, [])
- const handleSandboxUiBackToConversation = React.useCallback(() => {
+ const handleSandboxUiBackToConversation = React.useCallback(async () => {
if (!sandboxUiConversationOrigin) return
const origin = sandboxUiConversationOrigin
- setActiveSandboxUiApp(null)
- setSandboxUiConversationOrigin(null)
- setHeaderShellOverlayOpen(false)
- setSidebarSettingsMenuOpen(false)
- vm.handleSelectChatAgent(origin.agentName, {
- selectLatest: false,
- chatId: origin.chatId,
- title: origin.title,
- })
- }, [sandboxUiConversationOrigin, vm.handleSelectChatAgent])
+ try {
+ if (origin.teamId && origin.teamId !== vm.currentTeamId) {
+ 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')
+ }
+ }, [
+ sandboxUiConversationOrigin,
+ vm.currentTeamId,
+ vm.handleEnsureTeamContext,
+ vm.handleSelectChatAgent,
+ vm.pushToast,
+ ])
React.useEffect(() => {
setNotificationDrawerReady(false)
@@ -260,16 +296,89 @@ export function App() {
if (appNotificationDrawerOpen) setNotificationDrawerReady(true)
}, [appNotificationDrawerOpen])
- const handleOpenSandboxUiApp = React.useCallback(
- (app: ActiveSandboxUiApp) => {
- setSandboxUiConversationOrigin(activeConversationOrigin)
+ const launchSandboxUiApp = React.useCallback(
+ (app: ActiveSandboxUiApp, conversationOrigin: SandboxUiConversationOrigin | null) => {
+ setSandboxUiConversationOrigin(conversationOrigin)
setActiveSandboxUiApp(app)
vm.handleNavSelect(DESKTOP_ROUTES.apps)
setSandboxUiShortcutOpenRequestId(value => value + 1)
},
- [activeConversationOrigin, vm.handleNavSelect]
+ [vm.handleNavSelect]
+ )
+
+ const handleOpenSandboxUiApp = React.useCallback(
+ (app: ActiveSandboxUiApp) => {
+ launchSandboxUiApp(app, activeConversationOrigin)
+ },
+ [activeConversationOrigin, launchSandboxUiApp]
)
+ 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 unsubscribe = window.clerum.sandboxUi.onDeepLink(enqueue)
+ void window.clerum.sandboxUi
+ .listPendingDeepLinks()
+ .then(result => result.links.forEach(enqueue))
+ .catch(() => undefined)
+ return unsubscribe
+ }, [])
+
+ React.useEffect(() => {
+ if (!vm.isAuthenticated || pendingSandboxUiDeepLinks.length === 0) return
+ const pending = pendingSandboxUiDeepLinks[0]
+ if (!pending || processingSandboxUiDeepLinkIdRef.current !== null) return
+ processingSandboxUiDeepLinkIdRef.current = pending.link.id
+
+ void (async () => {
+ try {
+ if (pending.link.teamId && pending.link.teamId !== vm.currentTeamId) {
+ await vm.handleEnsureTeamContext({ teamId: pending.link.teamId })
+ }
+ const result = await window.clerum.sandboxUi.listApps()
+ const availableApps = toActiveSandboxUiApps(result.apps)
+ setAvailableSandboxUiApps(availableApps)
+ const app = availableApps.find(candidate => candidate.appRef === pending.link.appRef)
+ if (!app) {
+ throw new Error("You don't have access to this app in the linked team")
+ }
+ launchSandboxUiApp(
+ {
+ ...app,
+ defaultPath: pending.link.path,
+ },
+ pending.conversationOrigin
+ )
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ vm.pushToast(`Could not open app link: ${message}`, 'error')
+ } finally {
+ await window.clerum.sandboxUi.acknowledgeDeepLink(pending.link.id).catch(() => undefined)
+ setPendingSandboxUiDeepLinks(current =>
+ current.filter(item => item.link.id !== pending.link.id)
+ )
+ processingSandboxUiDeepLinkIdRef.current = null
+ }
+ })()
+ }, [
+ launchSandboxUiApp,
+ pendingSandboxUiDeepLinks,
+ vm.currentTeamId,
+ vm.handleEnsureTeamContext,
+ vm.isAuthenticated,
+ vm.pushToast,
+ ])
+
React.useEffect(() => {
const handleNewChatShortcut = (event: KeyboardEvent) => {
const isNewChatShortcut =
@@ -719,6 +828,7 @@ export function App() {
<SandboxUiPage
boundsRefreshKey={sandboxUiBoundsRefreshKey}
conversationOrigin={sandboxUiConversationOrigin}
+ currentTeamId={vm.currentTeamId}
headerShellOverlayOpen={headerShellOverlayOpen}
sidebarShellOverlayOpen={sidebarSettingsMenuOpen}
toastShellOverlayOpen={vm.toasts.length > 0}
@@ -729,6 +839,7 @@ export function App() {
onEmbeddedAppBack={handleSandboxUiClosed}
onEmbeddedAppRemoved={handleSandboxUiRemoved}
onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
+ onNotify={vm.pushToast}
/>
)}
{vm.navItem === DESKTOP_ROUTES.settings && (
diff --git a/desktop-app/ui/src/App.types.ts b/desktop-app/ui/src/App.types.ts
new file mode 100644
index 000000000..80bbf63de
--- /dev/null
+++ b/desktop-app/ui/src/App.types.ts
@@ -0,0 +1,13 @@
+import type { SandboxUiConversationOrigin } from '@pages/SandboxUiPage.types'
+
+export type SandboxUiDeepLinkEnvelope = {
+ id: number
+ appRef: string
+ path: string
+ teamId?: string
+}
+
+export type PendingSandboxUiDeepLink = {
+ link: SandboxUiDeepLinkEnvelope
+ conversationOrigin: SandboxUiConversationOrigin | null
+}
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index e18a88de2..46384ad8f 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -521,7 +521,7 @@ export function useAppController() {
]
)
- const ensureNotificationTeamContext = useCallback(
+ const ensureTeamContext = useCallback(
async (target: { teamId?: string }) => {
const targetTeamId = String(target.teamId || '').trim()
if (!targetTeamId) return
@@ -777,7 +777,7 @@ export function useAppController() {
try {
if (requiresTeamSwitch) {
- await ensureNotificationTeamContext({ teamId: targetTeamId })
+ await ensureTeamContext({ teamId: targetTeamId })
}
if (targetChatId && !requiresTeamSwitch && nav.selectedAgent === targetAgent) {
@@ -803,7 +803,7 @@ export function useAppController() {
[
chat.setPendingChatSelection,
chat.switchToChat,
- ensureNotificationTeamContext,
+ ensureTeamContext,
fullSetStatus,
nav.selectedAgent,
nav.setNavItem,
@@ -818,7 +818,7 @@ export function useAppController() {
const target = notification.workflow
if (!target) return
try {
- await ensureNotificationTeamContext({ teamId: notification.teamId })
+ await ensureTeamContext({ teamId: notification.teamId })
nav.setNavItem(DESKTOP_ROUTES.plugins)
const fallbackWorkflow = {
@@ -880,7 +880,7 @@ export function useAppController() {
)
}
},
- [ensureNotificationTeamContext, fullSetStatus, nav.setNavItem, queryClient]
+ [ensureTeamContext, fullSetStatus, nav.setNavItem, queryClient]
)
const openSdkNotificationTarget = useCallback(
@@ -998,6 +998,7 @@ export function useAppController() {
statusTone,
isAuthenticated: auth.isAuthenticated,
me: auth.me,
+ currentTeamId,
email: auth.email,
password: auth.password,
desktopSetupAuthorizationToken: auth.desktopSetupAuthorizationToken,
@@ -1049,6 +1050,7 @@ export function useAppController() {
handleNavSelect,
handleOpenAgentWorkspace,
handleSelectChatAgent,
+ handleEnsureTeamContext: ensureTeamContext,
handleBackToAgents: nav.handleBackToAgents,
handleOpenContextDetails: nav.handleOpenContextDetails,
handleBackToContexts: nav.handleBackToContexts,
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 1cff8c6d9..a12b03236 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -1,6 +1,12 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Button, StatusBanner } from '@components/Common'
-import { IconChat, IconClose, IconRefresh, IconSandboxUi } from '../components/SidebarNav/icons'
+import {
+ IconChat,
+ IconClose,
+ IconCopy,
+ IconRefresh,
+ IconSandboxUi,
+} from '../components/SidebarNav/icons'
import { clickableRowProps } from '../lib/clickableRowProps'
import type { SandboxUiPageProps } from './SandboxUiPage.types'
@@ -147,6 +153,7 @@ const APP_PAGE_SIZE = 6
export function SandboxUiPage({
boundsRefreshKey = 0,
conversationOrigin = null,
+ currentTeamId = '',
headerShellOverlayOpen = false,
sidebarShellOverlayOpen = false,
toastShellOverlayOpen = false,
@@ -157,6 +164,7 @@ export function SandboxUiPage({
onEmbeddedAppBack,
onEmbeddedAppRemoved,
onEmbedBoundsApplied,
+ onNotify,
}: SandboxUiPageProps = {}) {
const [apps, setApps] = useState<App[] | null>(null)
const [error, setError] = useState<string | null>(null)
@@ -302,7 +310,7 @@ export function SandboxUiPage({
const handleBackToConversation = useCallback(async () => {
if (!conversationOrigin || !onBackToConversation) return
await closeEmbed()
- onBackToConversation()
+ await onBackToConversation()
}, [closeEmbed, conversationOrigin, onBackToConversation])
// In-place hard-reload of the embedded app — fetches freshly-arrived
@@ -312,6 +320,16 @@ export function SandboxUiPage({
void window.clerum.sandboxUi.reload()
}, [])
+ const onCopyDeepLink = useCallback(async () => {
+ try {
+ await window.clerum.sandboxUi.copyDeepLink(currentTeamId || undefined)
+ onNotify?.('App link copied to clipboard.', 'success')
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ onNotify?.(`Could not copy app link: ${message}`, 'error')
+ }
+ }, [currentTeamId, onNotify])
+
const onRemoveApp = useCallback(async () => {
await closeEmbed()
onEmbeddedAppRemoved?.()
@@ -419,18 +437,32 @@ export function SandboxUiPage({
<span>Back to apps</span>
</Button>
{launch.kind === 'mounted' && (
- <Button
- color="neutral"
- variant="soft"
- size="sm"
- className="sandbox-ui-refresh-btn"
- aria-label="Refresh"
- title="Refresh app content"
- onClick={onRefresh}
- >
- <IconRefresh />
- <span>Refresh</span>
- </Button>
+ <>
+ <Button
+ color="neutral"
+ variant="soft"
+ size="sm"
+ className="sandbox-ui-refresh-btn"
+ aria-label="Refresh"
+ title="Refresh app content"
+ onClick={onRefresh}
+ >
+ <IconRefresh />
+ <span>Refresh</span>
+ </Button>
+ <Button
+ color="neutral"
+ variant="soft"
+ size="sm"
+ className="sandbox-ui-copy-link-btn"
+ aria-label="Copy current app link"
+ title="Copy current app link"
+ onClick={() => void onCopyDeepLink()}
+ >
+ <IconCopy />
+ <span>Copy URL</span>
+ </Button>
+ </>
)}
</div>
{showRefreshBanner && (
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.types.ts b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
index addeabc44..b9449139c 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.types.ts
+++ b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
@@ -1,22 +1,25 @@
-import type { ActiveSandboxUiApp } from '@/uiTypes'
+import type { ActiveSandboxUiApp, Tone } from '@/uiTypes'
export type SandboxUiConversationOrigin = {
agentName: string
chatId: string
title: string
+ teamId?: string
}
export type SandboxUiPageProps = {
boundsRefreshKey?: string | number
conversationOrigin?: SandboxUiConversationOrigin | null
+ currentTeamId?: string
headerShellOverlayOpen?: boolean
sidebarShellOverlayOpen?: boolean
toastShellOverlayOpen?: boolean
shortcutApp?: ActiveSandboxUiApp | null
shortcutOpenRequestId?: number
- onBackToConversation?: () => void
+ onBackToConversation?: () => void | Promise<void>
onEmbeddedAppOpening?: (app: ActiveSandboxUiApp) => void
onEmbeddedAppBack?: () => void
onEmbeddedAppRemoved?: () => void
onEmbedBoundsApplied?: () => void
+ onNotify?: (message: string, tone: Tone) => void
}
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
index 6a4a53d16..9a60b4591 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
@@ -9,6 +9,7 @@ const sandboxUi = {
open: vi.fn(),
close: vi.fn(),
reload: vi.fn(),
+ copyDeepLink: vi.fn(),
setBounds: vi.fn(),
setVisible: vi.fn(),
capturePreview: vi.fn(),
@@ -147,7 +148,7 @@ describe('SandboxUiPage', () => {
})
})
expect(await screen.findByRole('button', { name: 'Back to apps' })).toBeTruthy()
- expect(screen.queryByRole('button', { name: /^Back to .+ planning$/ })).toBeNull()
+ expect(screen.getAllByRole('button', { name: /^Back to / })).toHaveLength(1)
})
it('returns to the originating conversation from an app', async () => {
@@ -187,6 +188,36 @@ describe('SandboxUiPage', () => {
})
})
+ it('copies a deep link for the current app route and active team', async () => {
+ sandboxUi.listApps.mockResolvedValueOnce({
+ apps: [
+ {
+ appRef: 'sandbox-recipes/sales-crm',
+ title: "Andy's Sales CRM",
+ defaultPath: '/accounts',
+ ready: true,
+ phase: 'active',
+ updatedAt: null,
+ },
+ ],
+ })
+ sandboxUi.open.mockResolvedValueOnce(undefined)
+ sandboxUi.copyDeepLink.mockResolvedValueOnce({
+ url: 'evenfire://app/sandbox-recipes/sales-crm?path=%2Faccounts&team=team-123',
+ })
+ const onNotify = vi.fn()
+
+ render(<SandboxUiPage currentTeamId="team-123" onNotify={onNotify} />)
+
+ fireEvent.click(await screen.findByRole('button', { name: "Open Andy's Sales CRM" }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Copy current app link' }))
+
+ await waitFor(() => {
+ expect(sandboxUi.copyDeepLink).toHaveBeenCalledWith('team-123')
+ expect(onNotify).toHaveBeenCalledWith('App link copied to clipboard.', 'success')
+ })
+ })
+
it('reports when resized embedded app bounds are applied', async () => {
sandboxUi.listApps.mockResolvedValueOnce({
apps: [
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index f8b665650..b5ae38e95 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -12259,6 +12259,7 @@ pre {
.sandbox-ui-conversation-btn,
.sandbox-ui-close-btn,
+.sandbox-ui-copy-link-btn,
.sandbox-ui-refresh-btn {
display: inline-flex;
align-items: center;
@@ -12282,6 +12283,7 @@ pre {
.sandbox-ui-conversation-btn svg,
.sandbox-ui-close-btn svg,
+.sandbox-ui-copy-link-btn svg,
.sandbox-ui-refresh-btn svg {
width: 16px;
height: 16px;