Skip to content

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

TypeScript

fix(desktop): secure pending app deep links

Josuéb40b5a6f487b
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index f9c943097..5b9c335ee 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -28,8 +28,15 @@ import {
getConversationOriginForNavigation,
} from '@lib/sandboxUiConversationOrigin'
import {
+ MAX_SANDBOX_UI_DEEP_LINK_RETRY_ATTEMPTS,
+ confirmPendingSandboxUiDeepLink,
+ deferPendingSandboxUiDeepLink,
enqueuePendingSandboxUiDeepLink,
+ failPendingSandboxUiDeepLink,
+ isPendingSandboxUiDeepLinkAwaitingConfirmation,
+ isPendingSandboxUiDeepLinkStale,
removePendingSandboxUiDeepLink,
+ resetPendingSandboxUiDeepLinkFailure,
shouldPurgeSandboxUiDeepLinks,
} from '@lib/sandboxUiDeepLinkState'
import { AgentsPage } from '@pages/AgentsPage'
@@ -40,7 +47,10 @@ import { ContextsPage } from '@pages/ContextsPage'
import { FilesPage } from '@pages/FilesPage'
import { McpServersPage } from '@pages/McpServersPage'
import { SandboxUiPage } from '@pages/SandboxUiPage'
-import type { SandboxUiConversationOrigin } from '@pages/SandboxUiPage.types'
+import type {
+ SandboxUiConversationOrigin,
+ SandboxUiShortcutOpenResult,
+} from '@pages/SandboxUiPage.types'
import { SettingsPage } from '@pages/SettingsPage'
import { TeamDetailsPage } from '@pages/TeamDetailsPage'
import { TeamsPage } from '@pages/TeamsPage'
@@ -49,6 +59,16 @@ import { WorkflowsPage } from '@pages/WorkflowsPage'
import type { PendingSandboxUiDeepLink, SandboxUiDeepLinkEnvelope } from '@/App.types'
import type { ActiveSandboxUiApp, NavItem, ThemeMode } from '@/uiTypes'
+type PendingSandboxUiDeepLinkLaunch = {
+ linkId: number
+ requestId: number
+ generation: number
+ originalTeamId: string
+ linkTeamId?: string
+ switchedTeam: boolean
+ conversationOrigin: SandboxUiConversationOrigin | null
+}
+
function getInitialThemeMode(): ThemeMode {
if (typeof window === 'undefined') return 'dark'
try {
@@ -151,12 +171,15 @@ export function App() {
const [pendingSandboxUiDeepLinks, setPendingSandboxUiDeepLinks] = React.useState<
PendingSandboxUiDeepLink[]
>([])
+ const [sandboxUiDeepLinkRetryTick, setSandboxUiDeepLinkRetryTick] = React.useState(0)
const contentPanelRef = React.useRef<HTMLElement | null>(null)
const activeConversationOriginRef = React.useRef<SandboxUiConversationOrigin | null>(null)
const processingSandboxUiDeepLinkIdRef = React.useRef<number | null>(null)
+ const launchingSandboxUiDeepLinkRef = React.useRef<PendingSandboxUiDeepLinkLaunch | null>(null)
const pendingSandboxUiDeepLinksRef = React.useRef<PendingSandboxUiDeepLink[]>([])
const sandboxUiDeepLinkIdentityRef = React.useRef<string | null | undefined>(undefined)
const sandboxUiDeepLinkGenerationRef = React.useRef(0)
+ const sandboxUiShortcutOpenRequestIdRef = React.useRef(0)
const bootSplashLoading = vm.booting || vm.initialExperienceLoading
const isAgentChatView =
(vm.navItem === DESKTOP_ROUTES.agents && Boolean(vm.selectedAgent)) ||
@@ -251,6 +274,7 @@ export function App() {
pendingSandboxUiDeepLinksRef.current = []
setPendingSandboxUiDeepLinks([])
processingSandboxUiDeepLinkIdRef.current = null
+ launchingSandboxUiDeepLinkRef.current = null
sandboxUiDeepLinkGenerationRef.current += 1
void window.clerum.sandboxUi.clearPendingDeepLinks().catch(error => {
console.warn('[Desktop] Could not clear stale app deep links:', error)
@@ -326,10 +350,13 @@ export function App() {
const launchSandboxUiApp = React.useCallback(
(app: ActiveSandboxUiApp, conversationOrigin: SandboxUiConversationOrigin | null) => {
+ const requestId = sandboxUiShortcutOpenRequestIdRef.current + 1
+ sandboxUiShortcutOpenRequestIdRef.current = requestId
setSandboxUiConversationOrigin(conversationOrigin)
setActiveSandboxUiApp(app)
vm.handleNavSelect(DESKTOP_ROUTES.apps)
- setSandboxUiShortcutOpenRequestId(value => value + 1)
+ setSandboxUiShortcutOpenRequestId(requestId)
+ return requestId
},
[vm.handleNavSelect]
)
@@ -360,15 +387,103 @@ export function App() {
[activeConversationOrigin, launchSandboxUiApp, sandboxUiConversationOrigin, vm.navItem]
)
+ const setPendingSandboxUiDeepLinkState = React.useCallback((next: PendingSandboxUiDeepLink[]) => {
+ pendingSandboxUiDeepLinksRef.current = next
+ setPendingSandboxUiDeepLinks(next)
+ }, [])
+
+ const clearSandboxUiDeepLinkProcessing = React.useCallback((linkId?: number) => {
+ if (linkId === undefined || processingSandboxUiDeepLinkIdRef.current === linkId) {
+ processingSandboxUiDeepLinkIdRef.current = null
+ }
+ if (linkId === undefined || launchingSandboxUiDeepLinkRef.current?.linkId === linkId) {
+ launchingSandboxUiDeepLinkRef.current = null
+ }
+ }, [])
+
+ const acknowledgeSandboxUiDeepLink = React.useCallback(
+ async (linkId: number) => {
+ const next = removePendingSandboxUiDeepLink(pendingSandboxUiDeepLinksRef.current, linkId)
+ setPendingSandboxUiDeepLinkState(next)
+ clearSandboxUiDeepLinkProcessing(linkId)
+ try {
+ await window.clerum.sandboxUi.acknowledgeDeepLink(linkId)
+ } catch (error) {
+ console.warn('[Desktop] Could not acknowledge app deep link:', error)
+ }
+ },
+ [clearSandboxUiDeepLinkProcessing, setPendingSandboxUiDeepLinkState]
+ )
+
+ const deferSandboxUiDeepLink = React.useCallback(
+ (pending: PendingSandboxUiDeepLink, message: string, tone: 'info' | 'error' = 'error') => {
+ clearSandboxUiDeepLinkProcessing(pending.link.id)
+ if ((pending.retryCount ?? 0) >= MAX_SANDBOX_UI_DEEP_LINK_RETRY_ATTEMPTS) {
+ const next = failPendingSandboxUiDeepLink(
+ pendingSandboxUiDeepLinksRef.current,
+ pending.link.id,
+ message
+ )
+ setPendingSandboxUiDeepLinkState(next)
+ vm.pushToast(`Could not open app link: ${message}`, 'error')
+ return
+ }
+ const next = deferPendingSandboxUiDeepLink(
+ pendingSandboxUiDeepLinksRef.current,
+ pending.link.id,
+ Date.now()
+ )
+ setPendingSandboxUiDeepLinkState(next)
+ vm.pushToast(message, tone)
+ },
+ [clearSandboxUiDeepLinkProcessing, setPendingSandboxUiDeepLinkState, vm.pushToast]
+ )
+
+ const restoreSandboxUiDeepLinkTeam = React.useCallback(
+ async (context: PendingSandboxUiDeepLinkLaunch) => {
+ if (
+ !context.switchedTeam ||
+ !context.originalTeamId ||
+ !context.linkTeamId ||
+ vm.getCurrentTeamId() !== context.linkTeamId ||
+ context.generation !== sandboxUiDeepLinkGenerationRef.current
+ ) {
+ return
+ }
+ try {
+ await vm.handleEnsureTeamContext({ teamId: context.originalTeamId, announce: true })
+ const origin = context.conversationOrigin
+ if (origin && (!origin.teamId || origin.teamId === context.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')
+ }
+ },
+ [vm.getCurrentTeamId, vm.handleEnsureTeamContext, vm.handleSelectChatAgent, vm.pushToast]
+ )
+
+ const closeActiveSandboxUiEmbedForHandoff = React.useCallback(async () => {
+ if (!activeSandboxUiApp) return
+ await window.clerum.sandboxUi.close()
+ handleSandboxUiClosed()
+ }, [activeSandboxUiApp, handleSandboxUiClosed])
+
React.useEffect(() => {
const enqueue = (link: SandboxUiDeepLinkEnvelope) => {
const next = enqueuePendingSandboxUiDeepLink(
pendingSandboxUiDeepLinksRef.current,
link,
- activeConversationOriginRef.current
+ activeConversationOriginRef.current,
+ sandboxUiDeepLinkIdentityRef.current ?? null
)
- pendingSandboxUiDeepLinksRef.current = next
- setPendingSandboxUiDeepLinks(next)
+ setPendingSandboxUiDeepLinkState(next)
}
const unsubscribe = window.clerum.sandboxUi.onDeepLink(enqueue)
const listGeneration = sandboxUiDeepLinkGenerationRef.current
@@ -380,7 +495,7 @@ export function App() {
})
.catch(() => undefined)
return unsubscribe
- }, [])
+ }, [setPendingSandboxUiDeepLinkState])
React.useEffect(() => {
if (
@@ -392,7 +507,24 @@ export function App() {
) {
return
}
- const pending = pendingSandboxUiDeepLinksRef.current[0]
+ const currentIdentity = vm.authenticatedPrincipalIdentity
+ if (!currentIdentity) return
+ let stalePending: PendingSandboxUiDeepLink | null = null
+ const now = Date.now()
+ const pending = pendingSandboxUiDeepLinksRef.current.find(item => {
+ if (isPendingSandboxUiDeepLinkStale(item, currentIdentity)) {
+ stalePending = item
+ return false
+ }
+ if (isPendingSandboxUiDeepLinkAwaitingConfirmation(item, currentIdentity)) return false
+ if (item.failedMessage) return false
+ if (item.nextRetryAt && item.nextRetryAt > now) return false
+ return true
+ })
+ if (stalePending) {
+ void acknowledgeSandboxUiDeepLink(stalePending.link.id)
+ return
+ }
if (!pending || processingSandboxUiDeepLinkIdRef.current !== null) return
processingSandboxUiDeepLinkIdRef.current = pending.link.id
const processingGeneration = sandboxUiDeepLinkGenerationRef.current
@@ -400,10 +532,10 @@ export function App() {
void (async () => {
const originalTeamId = vm.getCurrentTeamId()
let switchedTeam = false
- let openedApp = false
try {
if (processingGeneration !== sandboxUiDeepLinkGenerationRef.current) return
if (pending.link.teamId && pending.link.teamId !== vm.getCurrentTeamId()) {
+ await closeActiveSandboxUiEmbedForHandoff()
try {
switchedTeam = await vm.handleEnsureTeamContext({
teamId: pending.link.teamId,
@@ -426,79 +558,121 @@ export function App() {
throw new Error("You don't have access to this app in the linked team")
}
if (resolution.status === 'starting') {
- vm.pushToast(
- `${resolution.label} is still starting up. Try this link again in a moment.`,
+ const launchContext: PendingSandboxUiDeepLinkLaunch = {
+ linkId: pending.link.id,
+ requestId: 0,
+ generation: processingGeneration,
+ originalTeamId,
+ linkTeamId: pending.link.teamId,
+ switchedTeam,
+ conversationOrigin: pending.conversationOrigin,
+ }
+ await restoreSandboxUiDeepLinkTeam(launchContext)
+ deferSandboxUiDeepLink(
+ pending,
+ `${resolution.label} is still starting up. This link will retry shortly.`,
'info'
)
return
}
- launchSandboxUiApp(
+ const requestId = launchSandboxUiApp(
{
...resolution.app,
...(pending.link.path ? { routePath: pending.link.path } : {}),
},
pending.conversationOrigin ?? sandboxUiConversationOrigin
)
- openedApp = true
+ launchingSandboxUiDeepLinkRef.current = {
+ linkId: pending.link.id,
+ requestId,
+ generation: processingGeneration,
+ originalTeamId,
+ linkTeamId: pending.link.teamId,
+ switchedTeam,
+ conversationOrigin: pending.conversationOrigin,
+ }
} 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 &&
- vm.getCurrentTeamId() === pending.link.teamId &&
- 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
}
- const next = removePendingSandboxUiDeepLink(
- pendingSandboxUiDeepLinksRef.current,
- pending.link.id
- )
- pendingSandboxUiDeepLinksRef.current = next
- setPendingSandboxUiDeepLinks(next)
- processingSandboxUiDeepLinkIdRef.current = null
- try {
- await window.clerum.sandboxUi.acknowledgeDeepLink(pending.link.id)
- } catch (error) {
- console.warn('[Desktop] Could not acknowledge app deep link:', error)
- }
+ await restoreSandboxUiDeepLinkTeam({
+ linkId: pending.link.id,
+ requestId: 0,
+ generation: processingGeneration,
+ originalTeamId,
+ linkTeamId: pending.link.teamId,
+ switchedTeam,
+ conversationOrigin: pending.conversationOrigin,
+ })
+ await acknowledgeSandboxUiDeepLink(pending.link.id)
}
})()
}, [
+ acknowledgeSandboxUiDeepLink,
+ activeSandboxUiApp,
bootSplashLoading,
+ closeActiveSandboxUiEmbedForHandoff,
+ deferSandboxUiDeepLink,
launchSandboxUiApp,
pendingSandboxUiDeepLinks,
+ restoreSandboxUiDeepLinkTeam,
+ sandboxUiConversationOrigin,
+ sandboxUiDeepLinkRetryTick,
+ vm.authenticatedPrincipalIdentity,
vm.getCurrentTeamId,
vm.handleEnsureTeamContext,
- vm.handleSelectChatAgent,
vm.isAuthenticated,
vm.pushToast,
- sandboxUiConversationOrigin,
])
+ React.useEffect(() => {
+ const now = Date.now()
+ const retryAt = pendingSandboxUiDeepLinks
+ .map(item => (item.failedMessage ? undefined : item.nextRetryAt))
+ .filter((value): value is number => typeof value === 'number' && value > now)
+ .sort((left, right) => left - right)[0]
+ if (!retryAt) return
+ const timeoutId = window.setTimeout(() => {
+ setSandboxUiDeepLinkRetryTick(value => value + 1)
+ }, retryAt - now)
+ return () => window.clearTimeout(timeoutId)
+ }, [pendingSandboxUiDeepLinks, sandboxUiDeepLinkRetryTick])
+
+ const handleSandboxUiShortcutOpenResult = React.useCallback(
+ async (requestId: number, result: SandboxUiShortcutOpenResult) => {
+ const launch = launchingSandboxUiDeepLinkRef.current
+ if (!launch || launch.requestId !== requestId) return
+ if (launch.generation !== sandboxUiDeepLinkGenerationRef.current) {
+ clearSandboxUiDeepLinkProcessing(launch.linkId)
+ return
+ }
+ const pending = pendingSandboxUiDeepLinksRef.current.find(
+ item => item.link.id === launch.linkId
+ )
+ if (!pending) {
+ clearSandboxUiDeepLinkProcessing(launch.linkId)
+ return
+ }
+ if (result.status === 'mounted') {
+ await acknowledgeSandboxUiDeepLink(launch.linkId)
+ return
+ }
+ await restoreSandboxUiDeepLinkTeam(launch)
+ deferSandboxUiDeepLink(pending, result.message || 'The native app view did not mount')
+ },
+ [
+ acknowledgeSandboxUiDeepLink,
+ clearSandboxUiDeepLinkProcessing,
+ deferSandboxUiDeepLink,
+ restoreSandboxUiDeepLinkTeam,
+ ]
+ )
+
React.useEffect(() => {
const handleNewChatShortcut = (event: KeyboardEvent) => {
const isNewChatShortcut =
@@ -533,6 +707,82 @@ export function App() {
appNotificationDrawerOpen ? 'notification-drawer-open' : 'notification-drawer-closed'
}`
+ const pendingSandboxUiConfirmation = vm.authenticatedPrincipalIdentity
+ ? pendingSandboxUiDeepLinks.find(item =>
+ isPendingSandboxUiDeepLinkAwaitingConfirmation(item, vm.authenticatedPrincipalIdentity)
+ )
+ : null
+ const failedSandboxUiDeepLink = vm.authenticatedPrincipalIdentity
+ ? pendingSandboxUiDeepLinks.find(item => item.failedMessage)
+ : null
+
+ const handleConfirmSandboxUiDeepLink = React.useCallback(() => {
+ const identity = vm.authenticatedPrincipalIdentity
+ const pending = pendingSandboxUiDeepLinksRef.current.find(item =>
+ identity ? isPendingSandboxUiDeepLinkAwaitingConfirmation(item, identity) : false
+ )
+ if (!identity || !pending) return
+ const next = confirmPendingSandboxUiDeepLink(
+ pendingSandboxUiDeepLinksRef.current,
+ pending.link.id,
+ identity
+ )
+ setPendingSandboxUiDeepLinkState(next)
+ }, [setPendingSandboxUiDeepLinkState, vm.authenticatedPrincipalIdentity])
+
+ const handleDismissSandboxUiDeepLink = React.useCallback(() => {
+ const identity = vm.authenticatedPrincipalIdentity
+ const pending = pendingSandboxUiDeepLinksRef.current.find(item =>
+ identity ? isPendingSandboxUiDeepLinkAwaitingConfirmation(item, identity) : false
+ )
+ if (!pending) return
+ void acknowledgeSandboxUiDeepLink(pending.link.id)
+ }, [acknowledgeSandboxUiDeepLink, vm.authenticatedPrincipalIdentity])
+
+ const handleRetryFailedSandboxUiDeepLink = React.useCallback(() => {
+ const pending = pendingSandboxUiDeepLinksRef.current.find(item => item.failedMessage)
+ if (!pending) return
+ const next = resetPendingSandboxUiDeepLinkFailure(
+ pendingSandboxUiDeepLinksRef.current,
+ pending.link.id
+ )
+ setPendingSandboxUiDeepLinkState(next)
+ setSandboxUiDeepLinkRetryTick(value => value + 1)
+ }, [setPendingSandboxUiDeepLinkState])
+
+ const handleDismissFailedSandboxUiDeepLink = React.useCallback(() => {
+ const pending = pendingSandboxUiDeepLinksRef.current.find(item => item.failedMessage)
+ if (!pending) return
+ void acknowledgeSandboxUiDeepLink(pending.link.id)
+ }, [acknowledgeSandboxUiDeepLink])
+
+ const sandboxUiDeepLinkDialog = pendingSandboxUiConfirmation ? (
+ <ConfirmDialog
+ title="Open app link?"
+ body={<p>Open {pendingSandboxUiConfirmation.link.appRef} in this desktop session.</p>}
+ cancelLabel="Dismiss"
+ confirmLabel="Open"
+ onCancel={handleDismissSandboxUiDeepLink}
+ onConfirm={handleConfirmSandboxUiDeepLink}
+ tone="primary"
+ />
+ ) : failedSandboxUiDeepLink ? (
+ <ConfirmDialog
+ title="App link could not be opened"
+ body={
+ <p>
+ {failedSandboxUiDeepLink.failedMessage ||
+ 'The app link could not be opened in the native view.'}
+ </p>
+ }
+ cancelLabel="Dismiss"
+ confirmLabel="Retry"
+ onCancel={handleDismissFailedSandboxUiDeepLink}
+ onConfirm={handleRetryFailedSandboxUiDeepLink}
+ tone="primary"
+ />
+ ) : null
+
const authValue = React.useMemo(
() => ({
booting: vm.booting,
@@ -958,6 +1208,7 @@ export function App() {
onEmbeddedAppRemoved={handleSandboxUiRemoved}
onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
onNotify={vm.pushToast}
+ onShortcutOpenResult={handleSandboxUiShortcutOpenResult}
/>
)}
{vm.navItem === DESKTOP_ROUTES.settings && (
@@ -990,6 +1241,7 @@ export function App() {
{desktopUpdateRequiredDialog}
{environmentSetupConfirmationDialog}
{environmentSetupSuccessDialog}
+ {sandboxUiDeepLinkDialog}
</DesktopStateProvider>
</McpRuntimeProvider>
</AgentChatProviders>
diff --git a/desktop-app/ui/src/App.types.ts b/desktop-app/ui/src/App.types.ts
index ac2fc3b0a..fbf286be4 100644
--- a/desktop-app/ui/src/App.types.ts
+++ b/desktop-app/ui/src/App.types.ts
@@ -6,4 +6,9 @@ export type { SandboxUiDeepLinkEnvelope } from '@clerum/desktop-app-links'
export type PendingSandboxUiDeepLink = {
link: SandboxUiDeepLinkEnvelope
conversationOrigin: SandboxUiConversationOrigin | null
+ receivedIdentity: string | null
+ confirmedIdentity?: string | null
+ retryCount?: number
+ nextRetryAt?: number
+ failedMessage?: string
}
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index 2b2e9bd70..920cab786 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -1,11 +1,36 @@
// @vitest-environment jsdom
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, 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'
+const confirmDialogHarness = vi.hoisted(() => ({
+ props: null as null | {
+ title: string
+ onCancel: () => void
+ onConfirm: () => void
+ },
+}))
+
+const sandboxUiPageHarness = vi.hoisted(() => ({
+ props: null as null | {
+ shortcutOpenRequestId?: number
+ onEmbeddedAppOpening?: (app: {
+ appRef: string
+ label: string
+ icon?: string | null
+ defaultPath: string
+ routePath?: string
+ }) => void
+ onShortcutOpenResult?: (
+ requestId: number,
+ result: { status: 'mounted' } | { status: 'failed'; message: string }
+ ) => void | Promise<void>
+ },
+}))
+
vi.mock('@hooks/useAppController', () => ({
useAppController: vi.fn(),
}))
@@ -17,7 +42,12 @@ vi.mock('@hooks/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/ConfirmDialog', () => ({
+ ConfirmDialog: (props: { title: string; onCancel: () => void; onConfirm: () => void }) => {
+ confirmDialogHarness.props = props
+ return null
+ },
+}))
vi.mock('@components/SidebarNav', () => ({ SidebarNav: () => null }))
vi.mock('@pages/AgentsPage', () => ({ AgentsPage: () => null }))
vi.mock('@pages/AuthPage', () => ({ AuthPage: () => null }))
@@ -26,7 +56,12 @@ 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/SandboxUiPage', () => ({
+ SandboxUiPage: (props: NonNullable<typeof sandboxUiPageHarness.props>) => {
+ sandboxUiPageHarness.props = props
+ return null
+ },
+}))
vi.mock('@pages/SettingsPage', () => ({ SettingsPage: () => null }))
vi.mock('@pages/TeamDetailsPage', () => ({ TeamDetailsPage: () => null }))
vi.mock('@pages/TeamsPage', () => ({ TeamsPage: () => null }))
@@ -38,13 +73,17 @@ type AppController = ReturnType<typeof useAppController>
function makeController(overrides: Partial<AppController> = {}): AppController {
const noop = vi.fn()
let liveTeamId = String(overrides.currentTeamId || 'team-a')
+ let controller: AppController
const ensureTeamContext = vi.fn(async (target: { teamId?: string }): Promise<boolean> => {
const targetTeamId = String(target.teamId || '').trim()
if (!targetTeamId || targetTeamId === liveTeamId) return false
liveTeamId = targetTeamId
return true
})
- return {
+ const handleNavSelect = vi.fn((item: AppController['navItem']) => {
+ controller.navItem = item
+ })
+ controller = {
booting: false,
initialExperienceLoading: true,
busy: false,
@@ -96,7 +135,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
handleEnsureTeamContext: ensureTeamContext,
getCurrentTeamId: vi.fn(() => liveTeamId),
handleSelectChatAgent: vi.fn(),
- handleNavSelect: vi.fn(),
+ handleNavSelect,
pushToast: vi.fn(),
setStatus: noop,
setBooting: noop,
@@ -110,6 +149,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
setDesktopEnvironmentSetupComplete: noop,
...overrides,
} as unknown as AppController
+ return controller
}
describe('App deep-link orchestration', () => {
@@ -119,12 +159,16 @@ describe('App deep-link orchestration', () => {
const acknowledgeDeepLink = vi.fn().mockResolvedValue(undefined)
const listApps = vi.fn().mockResolvedValue({ apps: [] })
const listPendingDeepLinks = vi.fn().mockResolvedValue({ links: [] })
+ const closeSandboxUi = vi.fn().mockResolvedValue(undefined)
beforeEach(() => {
vi.clearAllMocks()
+ confirmDialogHarness.props = null
+ sandboxUiPageHarness.props = null
acknowledgeDeepLink.mockResolvedValue(undefined)
listApps.mockResolvedValue({ apps: [] })
listPendingDeepLinks.mockResolvedValue({ links: [] })
+ closeSandboxUi.mockResolvedValue(undefined)
emitDeepLink = null
currentController = makeController()
vi.mocked(useAppController).mockImplementation(() => currentController)
@@ -140,6 +184,7 @@ describe('App deep-link orchestration', () => {
listPendingDeepLinks,
clearPendingDeepLinks,
acknowledgeDeepLink,
+ close: closeSandboxUi,
onDeepLink: vi.fn((callback: (link: SandboxUiDeepLinkEnvelope) => void) => {
emitDeepLink = callback
return vi.fn()
@@ -149,6 +194,68 @@ describe('App deep-link orchestration', () => {
})
})
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ async function reportShortcutOpenResult(
+ result: { status: 'mounted' } | { status: 'failed'; message: string } = {
+ status: 'mounted',
+ }
+ ): Promise<void> {
+ await waitFor(() => {
+ expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeGreaterThan(0)
+ })
+ const props = sandboxUiPageHarness.props
+ if (!props?.shortcutOpenRequestId) throw new Error('Sandbox UI shortcut was not requested')
+ await act(async () => {
+ await props.onShortcutOpenResult?.(props.shortcutOpenRequestId, result)
+ await Promise.resolve()
+ })
+ }
+
+ it('keeps logged-out app links pending until the user confirms after login', async () => {
+ currentController = makeController({
+ initialExperienceLoading: false,
+ isAuthenticated: false,
+ authenticatedPrincipalIdentity: null,
+ me: null,
+ currentTeamId: '',
+ } as unknown as Partial<AppController>)
+ listApps.mockResolvedValue({
+ apps: [
+ {
+ appRef: 'ns/app',
+ title: 'Linked App',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ },
+ ],
+ })
+ const { rerender } = render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app' })
+ })
+
+ currentController = makeController({ initialExperienceLoading: false })
+ rerender(<App />)
+
+ await waitFor(() => expect(confirmDialogHarness.props?.title).toBe('Open app link?'))
+ expect(currentController.handleNavSelect).not.toHaveBeenCalledWith(DESKTOP_ROUTES.apps)
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
+
+ await act(async () => {
+ confirmDialogHarness.props?.onConfirm()
+ await Promise.resolve()
+ })
+ await reportShortcutOpenResult()
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ })
+
it('purges user A links synchronously before user B can process them', async () => {
const { rerender } = render(<App />)
await waitFor(() => expect(emitDeepLink).not.toBeNull())
@@ -238,6 +345,36 @@ describe('App deep-link orchestration', () => {
)
})
+ it('closes the active embed before switching teams for a failed cross-team handoff', async () => {
+ const ensureTeamContext = vi.fn(async (): Promise<boolean> => true)
+ currentController = makeController({
+ initialExperienceLoading: false,
+ navItem: DESKTOP_ROUTES.apps,
+ handleEnsureTeamContext: ensureTeamContext,
+ })
+ render(<App />)
+ await waitFor(() => expect(sandboxUiPageHarness.props).not.toBeNull())
+
+ act(() => {
+ sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
+ appRef: 'ns/current',
+ label: 'Current App',
+ defaultPath: '/',
+ })
+ })
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/missing', teamId: 'team-b' })
+ })
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(closeSandboxUi).toHaveBeenCalledOnce()
+ expect(closeSandboxUi.mock.invocationCallOrder[0]).toBeLessThan(
+ ensureTeamContext.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
+ )
+ })
+
it('lets the server authorize a linked team even when the local directory is empty', async () => {
currentController = makeController({
initialExperienceLoading: false,
@@ -263,6 +400,7 @@ describe('App deep-link orchestration', () => {
emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })
})
+ await reportShortcutOpenResult()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(currentController.handleEnsureTeamContext).toHaveBeenCalledWith({
teamId: 'team-b',
@@ -334,6 +472,7 @@ describe('App deep-link orchestration', () => {
emitDeepLink?.({ id: 1, appRef: 'ns/app' })
})
+ await reportShortcutOpenResult()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(currentController.pushToast).not.toHaveBeenCalledWith(
expect.stringContaining('bridge unavailable'),
@@ -341,4 +480,116 @@ describe('App deep-link orchestration', () => {
)
consoleWarn.mockRestore()
})
+
+ it('acks a ready app link only after the native mount succeeds', async () => {
+ currentController = makeController({ initialExperienceLoading: false })
+ listApps.mockResolvedValue({
+ apps: [
+ {
+ appRef: 'ns/app',
+ title: 'Linked App',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ },
+ ],
+ })
+ render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app' })
+ })
+
+ await waitFor(() => {
+ expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeGreaterThan(0)
+ })
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
+
+ await reportShortcutOpenResult()
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ })
+
+ it('retries a starting app link and opens it when the app becomes ready', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ currentController = makeController({ initialExperienceLoading: false })
+ let ready = false
+ listApps.mockImplementation(async () => ({
+ apps: [
+ {
+ appRef: 'ns/app',
+ title: 'Linked App',
+ defaultPath: '/',
+ ready,
+ phase: ready ? 'active' : 'deploying',
+ },
+ ],
+ }))
+ render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app' })
+ })
+
+ await waitFor(() => {
+ expect(currentController.pushToast).toHaveBeenCalledWith(
+ 'Linked App is still starting up. This link will retry shortly.',
+ 'info'
+ )
+ })
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
+
+ ready = true
+ await act(async () => {
+ vi.advanceTimersByTime(1_000)
+ await Promise.resolve()
+ })
+ await reportShortcutOpenResult()
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ })
+
+ it('keeps a failed native mount unacked and continues with later links', async () => {
+ currentController = makeController({ initialExperienceLoading: false })
+ listApps.mockResolvedValue({
+ apps: [
+ {
+ appRef: 'ns/app',
+ title: 'Linked App',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ },
+ {
+ appRef: 'ns/next',
+ title: 'Next App',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ },
+ ],
+ })
+ render(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app' })
+ })
+ await reportShortcutOpenResult({ status: 'failed', message: 'native mount failed' })
+
+ expect(acknowledgeDeepLink).not.toHaveBeenCalledWith(1)
+
+ act(() => {
+ emitDeepLink?.({ id: 2, appRef: 'ns/next' })
+ })
+ await waitFor(() => {
+ expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeGreaterThan(1)
+ })
+ await reportShortcutOpenResult()
+
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(2))
+ expect(acknowledgeDeepLink).not.toHaveBeenCalledWith(1)
+ })
})
diff --git a/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts b/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts
index b8ca59b87..47b9a8359 100644
--- a/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/sandboxUiDeepLinkState.test.ts
@@ -2,13 +2,21 @@ import { describe, expect, it } from 'vitest'
import type { PendingSandboxUiDeepLink } from '@/App.types'
import {
MAX_PENDING_SANDBOX_UI_DEEP_LINKS,
+ MAX_SANDBOX_UI_DEEP_LINK_RETRY_ATTEMPTS,
+ confirmPendingSandboxUiDeepLink,
+ deferPendingSandboxUiDeepLink,
enqueuePendingSandboxUiDeepLink,
+ failPendingSandboxUiDeepLink,
+ isPendingSandboxUiDeepLinkAwaitingConfirmation,
+ isPendingSandboxUiDeepLinkStale,
+ nextSandboxUiDeepLinkRetryDelayMs,
removePendingSandboxUiDeepLink,
+ resetPendingSandboxUiDeepLinkFailure,
shouldPurgeSandboxUiDeepLinks,
} from '../sandboxUiDeepLinkState'
describe('shouldPurgeSandboxUiDeepLinks', () => {
- it('keeps a cold-start link while the first user authenticates', () => {
+ it('keeps a cold-start link as pending user intent while the first user authenticates', () => {
expect(shouldPurgeSandboxUiDeepLinks(undefined, null)).toBe(false)
expect(shouldPurgeSandboxUiDeepLinks(null, 'user-a')).toBe(false)
})
@@ -25,17 +33,18 @@ describe('shouldPurgeSandboxUiDeepLinks', () => {
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)
+ let pending = enqueuePendingSandboxUiDeepLink([], { id: 2, appRef: 'ns/two' }, null, null)
+ pending = enqueuePendingSandboxUiDeepLink(pending, { id: 1, appRef: 'ns/one' }, null, 'user-a')
expect(pending.map(item => item.link.id)).toEqual([1, 2])
+ expect(pending.map(item => item.receivedIdentity)).toEqual(['user-a', null])
})
it('re-adds a link that arrives during its acknowledgement window', () => {
const link = { id: 1, appRef: 'ns/app' }
- let pending = enqueuePendingSandboxUiDeepLink([], link, null)
+ let pending = enqueuePendingSandboxUiDeepLink([], link, null, 'user-a')
pending = removePendingSandboxUiDeepLink(pending, link.id)
- pending = enqueuePendingSandboxUiDeepLink(pending, link, null)
+ pending = enqueuePendingSandboxUiDeepLink(pending, link, null, 'user-a')
expect(pending).toHaveLength(1)
expect(pending[0]?.link).toEqual(link)
@@ -44,10 +53,52 @@ describe('pending sandbox UI deep-link state', () => {
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)
+ pending = enqueuePendingSandboxUiDeepLink(
+ pending,
+ { id, appRef: `ns/app-${id}` },
+ null,
+ 'user-a'
+ )
}
expect(pending).toHaveLength(MAX_PENDING_SANDBOX_UI_DEEP_LINKS)
expect(pending[0]?.link.id).toBe(3)
})
+
+ it('requires post-login confirmation for links received without an identity', () => {
+ const pending = enqueuePendingSandboxUiDeepLink([], { id: 1, appRef: 'ns/app' }, null, null)
+
+ expect(isPendingSandboxUiDeepLinkAwaitingConfirmation(pending[0]!, 'user-a')).toBe(true)
+
+ const confirmed = confirmPendingSandboxUiDeepLink(pending, 1, 'user-a')
+
+ expect(isPendingSandboxUiDeepLinkAwaitingConfirmation(confirmed[0]!, 'user-a')).toBe(false)
+ expect(isPendingSandboxUiDeepLinkStale(confirmed[0]!, 'user-b')).toBe(true)
+ })
+
+ it('treats authenticated queued links as stale after an identity change', () => {
+ const pending = enqueuePendingSandboxUiDeepLink([], { id: 1, appRef: 'ns/app' }, null, 'user-a')
+
+ expect(isPendingSandboxUiDeepLinkStale(pending[0]!, 'user-a')).toBe(false)
+ expect(isPendingSandboxUiDeepLinkStale(pending[0]!, 'user-b')).toBe(true)
+ })
+
+ it('tracks bounded retry delays and explicit failed state', () => {
+ let pending = enqueuePendingSandboxUiDeepLink([], { id: 1, appRef: 'ns/app' }, null, 'user-a')
+ pending = deferPendingSandboxUiDeepLink(pending, 1, 10_000)
+
+ expect(pending[0]?.retryCount).toBe(1)
+ expect(pending[0]?.nextRetryAt).toBe(10_000 + nextSandboxUiDeepLinkRetryDelayMs(0))
+ expect(nextSandboxUiDeepLinkRetryDelayMs(MAX_SANDBOX_UI_DEEP_LINK_RETRY_ATTEMPTS + 10)).toBe(
+ 15_000
+ )
+
+ pending = failPendingSandboxUiDeepLink(pending, 1, 'native mount failed')
+ expect(pending[0]?.failedMessage).toBe('native mount failed')
+ expect(pending[0]?.nextRetryAt).toBeUndefined()
+
+ pending = resetPendingSandboxUiDeepLinkFailure(pending, 1)
+ expect(pending[0]?.failedMessage).toBeUndefined()
+ expect(pending[0]?.retryCount).toBe(0)
+ })
})
diff --git a/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts b/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts
index 9d2b28fbd..510f99627 100644
--- a/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts
+++ b/desktop-app/ui/src/lib/sandboxUiDeepLinkState.ts
@@ -2,6 +2,9 @@ import type { SandboxUiConversationOrigin } from '@pages/SandboxUiPage.types'
import type { PendingSandboxUiDeepLink, SandboxUiDeepLinkEnvelope } from '@/App.types'
export const MAX_PENDING_SANDBOX_UI_DEEP_LINKS = 20
+export const MAX_SANDBOX_UI_DEEP_LINK_RETRY_ATTEMPTS = 5
+export const SANDBOX_UI_DEEP_LINK_BASE_RETRY_DELAY_MS = 1_000
+export const SANDBOX_UI_DEEP_LINK_MAX_RETRY_DELAY_MS = 15_000
export function shouldPurgeSandboxUiDeepLinks(
previousIdentity: string | null | undefined,
@@ -9,18 +12,19 @@ export function shouldPurgeSandboxUiDeepLinks(
): boolean {
return (
previousIdentity !== undefined &&
- previousIdentity !== null &&
- previousIdentity !== currentIdentity
+ previousIdentity !== currentIdentity &&
+ !(previousIdentity === null && currentIdentity !== null)
)
}
export function enqueuePendingSandboxUiDeepLink(
current: PendingSandboxUiDeepLink[],
link: SandboxUiDeepLinkEnvelope,
- conversationOrigin: SandboxUiConversationOrigin | null
+ conversationOrigin: SandboxUiConversationOrigin | null,
+ receivedIdentity: string | null
): PendingSandboxUiDeepLink[] {
const existing = current.find(item => item.link.id === link.id)
- const next = existing ? current : [...current, { link, conversationOrigin }]
+ const next = existing ? current : [...current, { link, conversationOrigin, receivedIdentity }]
return [...next]
.sort((left, right) => left.link.id - right.link.id)
.slice(-MAX_PENDING_SANDBOX_UI_DEEP_LINKS)
@@ -32,3 +36,95 @@ export function removePendingSandboxUiDeepLink(
): PendingSandboxUiDeepLink[] {
return current.filter(item => item.link.id !== linkId)
}
+
+export function isPendingSandboxUiDeepLinkAwaitingConfirmation(
+ pending: PendingSandboxUiDeepLink,
+ currentIdentity: string | null
+): boolean {
+ if (!currentIdentity) return false
+ return pending.receivedIdentity === null && pending.confirmedIdentity !== currentIdentity
+}
+
+export function isPendingSandboxUiDeepLinkStale(
+ pending: PendingSandboxUiDeepLink,
+ currentIdentity: string | null
+): boolean {
+ if (pending.receivedIdentity !== null && pending.receivedIdentity !== currentIdentity) {
+ return true
+ }
+ return Boolean(pending.confirmedIdentity && pending.confirmedIdentity !== currentIdentity)
+}
+
+export function confirmPendingSandboxUiDeepLink(
+ current: PendingSandboxUiDeepLink[],
+ linkId: number,
+ currentIdentity: string
+): PendingSandboxUiDeepLink[] {
+ return current.map(item =>
+ item.link.id === linkId
+ ? {
+ ...item,
+ confirmedIdentity: currentIdentity,
+ failedMessage: undefined,
+ nextRetryAt: undefined,
+ }
+ : item
+ )
+}
+
+export function nextSandboxUiDeepLinkRetryDelayMs(retryCount: number): number {
+ const bounded = Math.max(0, Math.min(retryCount, MAX_SANDBOX_UI_DEEP_LINK_RETRY_ATTEMPTS - 1))
+ return Math.min(
+ SANDBOX_UI_DEEP_LINK_BASE_RETRY_DELAY_MS * 2 ** bounded,
+ SANDBOX_UI_DEEP_LINK_MAX_RETRY_DELAY_MS
+ )
+}
+
+export function deferPendingSandboxUiDeepLink(
+ current: PendingSandboxUiDeepLink[],
+ linkId: number,
+ now: number
+): PendingSandboxUiDeepLink[] {
+ return current.map(item => {
+ if (item.link.id !== linkId) return item
+ const retryCount = (item.retryCount ?? 0) + 1
+ return {
+ ...item,
+ retryCount,
+ failedMessage: undefined,
+ nextRetryAt: now + nextSandboxUiDeepLinkRetryDelayMs(retryCount - 1),
+ }
+ })
+}
+
+export function failPendingSandboxUiDeepLink(
+ current: PendingSandboxUiDeepLink[],
+ linkId: number,
+ message: string
+): PendingSandboxUiDeepLink[] {
+ return current.map(item =>
+ item.link.id === linkId
+ ? {
+ ...item,
+ failedMessage: message,
+ nextRetryAt: undefined,
+ }
+ : item
+ )
+}
+
+export function resetPendingSandboxUiDeepLinkFailure(
+ current: PendingSandboxUiDeepLink[],
+ linkId: number
+): PendingSandboxUiDeepLink[] {
+ return current.map(item =>
+ item.link.id === linkId
+ ? {
+ ...item,
+ failedMessage: undefined,
+ nextRetryAt: undefined,
+ retryCount: 0,
+ }
+ : item
+ )
+}
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 74a47f86a..56e754e26 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -9,7 +9,11 @@ import {
} from '../components/SidebarNav/icons'
import { clickableRowProps } from '../lib/clickableRowProps'
import type { SandboxUiAppListing } from '../lib/sandboxUiAppSelection.types'
-import type { SandboxUiLaunchApp, SandboxUiPageProps } from './SandboxUiPage.types'
+import type {
+ SandboxUiLaunchApp,
+ SandboxUiPageProps,
+ SandboxUiShortcutOpenResult,
+} from './SandboxUiPage.types'
type PhasePillTone = 'allowed' | 'warning' | 'denied' | 'info' | 'muted'
@@ -156,6 +160,7 @@ export function SandboxUiPage({
onEmbeddedAppRemoved,
onEmbedBoundsApplied,
onNotify,
+ onShortcutOpenResult,
}: SandboxUiPageProps = {}) {
const [apps, setApps] = useState<SandboxUiAppListing[] | null>(null)
const [error, setError] = useState<string | null>(null)
@@ -224,10 +229,14 @@ export function SandboxUiPage({
}, [onEmbeddedAppBack])
const openApp = useCallback(
- async (app: SandboxUiLaunchApp) => {
- if (app.ready === false) return
+ async (app: SandboxUiLaunchApp): Promise<SandboxUiShortcutOpenResult> => {
+ if (app.ready === false) {
+ return { status: 'failed', message: 'This app is starting up. Try again in a moment.' }
+ }
const [recipeNs, recipeName] = app.appRef.split('/', 2)
- if (!recipeNs || !recipeName) return
+ if (!recipeNs || !recipeName) {
+ return { status: 'failed', message: 'Invalid app reference' }
+ }
// Transition to 'minting' so the slot div mounts. Wait for the next
// layout commit so getBoundingClientRect() reflects the slot's real
// position (otherwise we'd be reading before React has rendered the
@@ -255,6 +264,7 @@ export function SandboxUiPage({
bounds,
})
setLaunch({ kind: 'mounted', appRef: app.appRef })
+ return { status: 'mounted' }
} catch (err) {
const { status, message } = statusFromError(err)
const userFacing =
@@ -267,6 +277,7 @@ export function SandboxUiPage({
: message
setLaunch({ kind: 'error', appRef: app.appRef, message: userFacing })
onEmbeddedAppRemoved?.()
+ return { status: 'failed', message: userFacing }
}
},
[onEmbeddedAppOpening, onEmbeddedAppRemoved]
@@ -338,8 +349,10 @@ export function SandboxUiPage({
if (shortcutOpenRequestId === lastShortcutOpenRequestIdRef.current) return
lastShortcutOpenRequestIdRef.current = shortcutOpenRequestId
if (shortcutOpenRequestId <= 0 || !shortcutApp) return
- void openApp(shortcutApp)
- }, [openApp, shortcutApp, shortcutOpenRequestId])
+ void openApp(shortcutApp).then(result => {
+ void onShortcutOpenResult?.(shortcutOpenRequestId, result)
+ })
+ }, [onShortcutOpenResult, openApp, shortcutApp, shortcutOpenRequestId])
// Track bounds while mounted; also during 'minting' so onOpen can read
// the slot's rect AFTER the layout pass that renders the slot div.
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.types.ts b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
index a120c8672..d1a632803 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.types.ts
+++ b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
@@ -11,6 +11,10 @@ export type SandboxUiLaunchApp = ActiveSandboxUiApp & {
ready?: boolean
}
+export type SandboxUiShortcutOpenResult =
+ | { status: 'mounted' }
+ | { status: 'failed'; message: string }
+
export type SandboxUiPageProps = {
boundsRefreshKey?: string | number
conversationOrigin?: SandboxUiConversationOrigin | null
@@ -26,4 +30,8 @@ export type SandboxUiPageProps = {
onEmbeddedAppRemoved?: () => void
onEmbedBoundsApplied?: () => void
onNotify?: (message: string, tone: Tone) => void
+ onShortcutOpenResult?: (
+ requestId: number,
+ result: SandboxUiShortcutOpenResult
+ ) => void | Promise<void>
}
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
index 603ca052d..c0ff013d6 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
@@ -168,6 +168,7 @@ describe('SandboxUiPage', () => {
sandboxUi.listApps.mockResolvedValueOnce({ apps: [] })
sandboxUi.open.mockResolvedValueOnce(undefined)
const onEmbeddedAppOpening = vi.fn()
+ const onShortcutOpenResult = vi.fn()
render(
<SandboxUiPage
@@ -179,6 +180,7 @@ describe('SandboxUiPage', () => {
}}
shortcutOpenRequestId={1}
onEmbeddedAppOpening={onEmbeddedAppOpening}
+ onShortcutOpenResult={onShortcutOpenResult}
/>
)
@@ -203,6 +205,34 @@ describe('SandboxUiPage', () => {
defaultPath: '/',
routePath: '/tasks/task-42',
})
+ await waitFor(() => {
+ expect(onShortcutOpenResult).toHaveBeenCalledWith(1, { status: 'mounted' })
+ })
+ })
+
+ it('reports a failed deep-linked shortcut open without acknowledging success', async () => {
+ sandboxUi.listApps.mockResolvedValueOnce({ apps: [] })
+ sandboxUi.open.mockRejectedValueOnce(new Error('native mount failed'))
+ const onShortcutOpenResult = vi.fn()
+
+ render(
+ <SandboxUiPage
+ shortcutApp={{
+ appRef: 'sandbox-recipes/task-board',
+ label: 'Agentic Task Board',
+ defaultPath: '/',
+ }}
+ shortcutOpenRequestId={1}
+ onShortcutOpenResult={onShortcutOpenResult}
+ />
+ )
+
+ await waitFor(() => {
+ expect(onShortcutOpenResult).toHaveBeenCalledWith(1, {
+ status: 'failed',
+ message: 'native mount failed',
+ })
+ })
})
it('returns to the originating conversation from an app', async () => {