Skip to content

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

TypeScript

test(desktop): close stepless SDK user journey

Alfredo Lopez23621d987a98
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 64b831807..bb7007cdb 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.400",
+ "version": "0.1.401",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.400",
+ "version": "0.1.401",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 377f347ea..4099c1caa 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.400",
+ "version": "0.1.401",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/network.gateway.intent.test.ts b/control-api/test/network.gateway.intent.test.ts
index cec6ca3ac..48401737f 100644
--- a/control-api/test/network.gateway.intent.test.ts
+++ b/control-api/test/network.gateway.intent.test.ts
@@ -333,6 +333,15 @@ describe('network/gateway intent (manifest-level)', () => {
expect(gatewayConf).not.toContain('/api/v1/external/')
})
+ it('keeps the Minikube control-api Marketplace on the branch-local registry', () => {
+ const controlApiConfig = read(`${OVERLAYS}/minikube/configmaps/control-api-config.yaml`)
+
+ expect(controlApiConfig).toContain(
+ "CLERUM_REGISTRY_URL: 'http://registry-api.registry.svc.cluster.local:8085'"
+ )
+ expect(controlApiConfig).not.toContain("CLERUM_REGISTRY_URL: 'https://registry.evenfire.ai'")
+ })
+
it('keeps the stateless heartbeat route POST-only through the mcp-host gateway', () => {
const configmaps = read(`${BASE}/control-plane/configmaps.yaml`)
const gatewayConf = docContaining(yamlDocs(configmaps), 'name: nginx-workflow-approval-gateway')
@@ -356,6 +365,45 @@ describe('network/gateway intent (manifest-level)', () => {
expect(route).toContain('proxy_set_header Authorization $http_authorization;')
})
+ it('routes the Plugin Workload SDK capabilities probe through the mcp-host gateway', () => {
+ const configmaps = read(`${BASE}/control-plane/configmaps.yaml`)
+ const gatewayConf = docContaining(yamlDocs(configmaps), 'name: nginx-workflow-approval-gateway')
+ const route = locationBlock(
+ gatewayConf,
+ 'location = /api/v1/mcp-host/plugin-workload-sdk/capabilities'
+ )
+
+ expect(route).toContain('limit_except GET')
+ expect(route).toContain('proxy_pass http://control_api_upstream;')
+ expect(route).toContain('proxy_set_header Authorization $http_authorization;')
+ })
+
+ it('routes the target-aware Plugin Workload SDK promptBridge v2 endpoint through the gateway', () => {
+ const configmaps = read(`${BASE}/control-plane/configmaps.yaml`)
+ const gatewayConf = docContaining(yamlDocs(configmaps), 'name: nginx-workflow-approval-gateway')
+ const route = locationBlock(
+ gatewayConf,
+ 'location = /api/v1/mcp-host/plugin-workload-sdk/prompt-bridge/v2'
+ )
+
+ expect(route).toContain('limit_except POST')
+ expect(route).toContain('proxy_pass http://control_api_upstream;')
+ expect(route).toContain('proxy_set_header Authorization $http_authorization;')
+ })
+
+ it('routes promptBridge provider-attempt status through the mcp-host gateway', () => {
+ const configmaps = read(`${BASE}/control-plane/configmaps.yaml`)
+ const gatewayConf = docContaining(yamlDocs(configmaps), 'name: nginx-workflow-approval-gateway')
+ const route = locationBlock(
+ gatewayConf,
+ 'location ~ ^/api/v1/mcp-host/plugin-workload-sdk/provider-attempts/[^/]+/status'
+ )
+
+ expect(route).toContain('limit_except POST')
+ expect(route).toContain('proxy_pass http://control_api_upstream;')
+ expect(route).toContain('proxy_set_header Authorization $http_authorization;')
+ })
+
it('keeps governed agent-run ingest POST-only through the mcp-host gateway', () => {
const configmaps = read(`${BASE}/control-plane/configmaps.yaml`)
const gatewayConf = docContaining(yamlDocs(configmaps), 'name: nginx-workflow-approval-gateway')
diff --git a/deploy/base/control-plane/configmaps.yaml b/deploy/base/control-plane/configmaps.yaml
index f36344ec1..f026d112e 100644
--- a/deploy/base/control-plane/configmaps.yaml
+++ b/deploy/base/control-plane/configmaps.yaml
@@ -498,6 +498,30 @@ data:
# clientNotifications) to control-api through this gateway. Same RS256
# runtime access JWT that the workflow-approvals endpoints accept;
# control-api authorizes each call against the recipe grant.
+ location = /api/v1/mcp-host/plugin-workload-sdk/capabilities {
+ limit_except GET {
+ deny all;
+ }
+ proxy_pass http://control_api_upstream;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Authorization $http_authorization;
+ }
+
+ location = /api/v1/mcp-host/plugin-workload-sdk/prompt-bridge/v2 {
+ limit_except POST {
+ deny all;
+ }
+ proxy_pass http://control_api_upstream;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Authorization $http_authorization;
+ }
+
location = /api/v1/mcp-host/plugin-workload-sdk/prompt-bridge {
limit_except POST {
deny all;
@@ -566,6 +590,22 @@ data:
proxy_set_header Authorization $http_authorization;
}
+ # Provider-attempt status is part of the promptBridge audit contract.
+ # It must remain behind the same mcp-host JWT gateway as invocation
+ # status; otherwise the provider call can be authorized and issued a
+ # JIT ticket, but the runtime cannot close the attempt lease.
+ location ~ ^/api/v1/mcp-host/plugin-workload-sdk/provider-attempts/[^/]+/status$ {
+ limit_except POST {
+ deny all;
+ }
+ proxy_pass http://control_api_upstream;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Authorization $http_authorization;
+ }
+
# ── Stateless lifecycle heartbeat ──
# mcp-host pods POST D8 activity snapshots here. Same RS256 runtime
# access JWT that the workflow-approvals endpoints accept; control-api
diff --git a/deploy/overlays/minikube/configmaps/control-api-config.yaml b/deploy/overlays/minikube/configmaps/control-api-config.yaml
index 663027999..1a1d2ed1f 100644
--- a/deploy/overlays/minikube/configmaps/control-api-config.yaml
+++ b/deploy/overlays/minikube/configmaps/control-api-config.yaml
@@ -53,20 +53,13 @@ data:
WORKFLOW_APPROVAL_DEFAULT_TTL_SEC: '86400'
WORKFLOW_APPROVAL_MAX_TTL_SEC: '172800'
WORKFLOW_APPROVAL_EXPIRY_INTERVAL_MS: '60000'
- # OSS default: point at the shared registry so a self-hoster browses the
- # public catalog out of the box and can run the connect flow (register →
- # approve → claim) against it. self-hosted is the only mode that fits an OSS
- # deployment (managed = MCC-provisioned, not in this repo). Registry auth
- # turns on by itself once the connect flow completes and this deployment
- # holds machine credentials: there is no flag to set and no restart needed.
- # To run your OWN in-cluster registry instead, set CLERUM_REGISTRY_URL to
- # http://registry-api.registry.svc.cluster.local:8085. That URL is already
- # built into the allowlist, so no CLERUM_REGISTRY_URL_ALLOWLIST entry is
- # needed for it; the setting is only for any OTHER registry URL. The
- # allowlist applies to any explicitly self-hosted deployment with a registry
- # URL configured, regardless of whether auth is active, and control-api
- # refuses to start if the configured URL is not allowlisted.
- CLERUM_REGISTRY_URL: 'https://registry.evenfire.ai'
+ # Minikube owns an in-cluster registry-api deployment. Keep the control-api
+ # pointed at that service so the operator Marketplace publish/install
+ # journey stays inside the branch-owned profile; the public registry is a
+ # production/self-hosted default, not a local test dependency. This URL is
+ # already in the registry allowlist and is reachable through the explicit
+ # control-api-to-registry NetworkPolicy.
+ CLERUM_REGISTRY_URL: 'http://registry-api.registry.svc.cluster.local:8085'
REGISTRY_CONNECTION_MODE: 'self-hosted'
# The Publisher UI (Sidebar entry + /publisher route) defaults ON for every
# deploy. It only surfaces for an org-bound, non-curator deploy (the control-ui
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index ad1629d86..46b72d094 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.330",
+ "version": "0.1.331",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.330",
+ "version": "0.1.331",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index e7643c29a..b8fd69335 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.330",
+ "version": "0.1.331",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/config.ts b/desktop-app/src/config.ts
index e749daf3e..f293212a0 100644
--- a/desktop-app/src/config.ts
+++ b/desktop-app/src/config.ts
@@ -68,9 +68,20 @@ function defaultUserDataDirectoryPath(): string {
}
}
+function hasExplicitUserDataDirectory(): boolean {
+ return process.argv.some(
+ argument => argument === '--user-data-dir' || argument.startsWith('--user-data-dir=')
+ )
+}
+
try {
app?.setName?.(DEFAULT_APP_NAME)
- app?.setPath?.('userData', defaultUserDataDirectoryPath())
+ // Respect Electron's explicit user-data-dir switch. QA/E2E launches use an
+ // isolated profile so local settings and sessions cannot leak from the
+ // developer's normal Evenfire profile into a functional journey.
+ if (!hasExplicitUserDataDirectory()) {
+ app?.setPath?.('userData', defaultUserDataDirectoryPath())
+ }
} catch {
// Electron can be mocked in unit tests before the real app object is ready.
}
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index 332e712e8..c0ff26c0e 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -46,6 +46,21 @@ function isWindowVisible(win: BrowserWindow | null): boolean {
return Boolean(win && !win.isDestroyed() && win.isVisible() && !win.isMinimized())
}
+/**
+ * Chromium renderer focus is not the same thing as application focus: a
+ * WebContentsView can own the active document while the Evenfire window still
+ * owns the user's attention. Keep notification policy on the native Electron
+ * window state instead of asking the parent renderer who currently owns DOM
+ * focus.
+ */
+function isAppFocused(): boolean {
+ return BrowserWindow.getAllWindows().some(win => !win.isDestroyed() && win.isFocused())
+}
+
+function windowState(win: BrowserWindow | null): { visible: boolean; focused: boolean } {
+ return { visible: isWindowVisible(win), focused: isAppFocused() }
+}
+
/**
* GAP-D1 (spec-v2 §4.5-4): after the OS sleeps/resumes (or the screen locks and
* unlocks), open SSE sockets are typically dead but neither the tracker watchdog
@@ -65,11 +80,11 @@ function wirePowerMonitor(): void {
powerMonitor.on('unlock-screen', emit)
}
-/** Push window visibility to the renderer on every show/hide/minimize/focus change. */
+/** Push native window state to the renderer on every visibility/focus change. */
function wireWindowVisibility(win: BrowserWindow): void {
const emit = () => {
if (win.isDestroyed()) return
- win.webContents.send('window:visibility', { visible: isWindowVisible(win) })
+ win.webContents.send('window:visibility', windowState(win))
}
win.on('show', emit)
win.on('hide', emit)
@@ -77,13 +92,18 @@ function wireWindowVisibility(win: BrowserWindow): void {
win.on('restore', emit)
win.on('focus', emit)
win.on('blur', emit)
+ // A future secondary BrowserWindow can take focus without emitting a focus
+ // event on the main window. App-level events keep the main renderer's
+ // application-focus view authoritative in that case as well.
+ app.on('browser-window-focus', emit)
+ app.on('browser-window-blur', emit)
}
ipcMain.handle('window:getVisibility', event => {
// Same trusted-sender invariant as every handler in ipc.ts (defense in depth,
// even for a read-only boolean getter).
assertTrustedSender(event)
- return { visible: isWindowVisible(mainWindow) }
+ return windowState(mainWindow)
})
const DESKTOP_SETUP_PROTOCOL = 'evenfire'
const CLERUM_PROTOCOL = 'clerum'
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 378744057..c9c92bfb1 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -353,9 +353,11 @@ const clerum = Object.freeze({
},
window: {
getVisibility: () => ipcRenderer.invoke('window:getVisibility'),
- onVisibilityChange: (callback: (state: { visible: boolean }) => void) => {
- const listener = (_event: Electron.IpcRendererEvent, state: { visible: boolean }) =>
- callback(state)
+ onVisibilityChange: (callback: (state: { visible: boolean; focused: boolean }) => void) => {
+ const listener = (
+ _event: Electron.IpcRendererEvent,
+ state: { visible: boolean; focused: boolean }
+ ) => callback(state)
ipcRenderer.on('window:visibility', listener)
return () => ipcRenderer.off('window:visibility', listener)
},
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index a56efa389..3e24f3222 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -464,8 +464,10 @@ declare global {
openUrl: (url: string) => Promise<void>
}
window: {
- getVisibility: () => Promise<{ visible: boolean }>
- onVisibilityChange: (callback: (state: { visible: boolean }) => void) => () => void
+ getVisibility: () => Promise<{ visible: boolean; focused: boolean }>
+ onVisibilityChange: (
+ callback: (state: { visible: boolean; focused: boolean }) => void
+ ) => () => void
}
system: {
/** GAP-D1 (§4.5-4): OS resume / screen unlock tick — reconcile in-flight chats. */
diff --git a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
index e7ed8b1cc..cf6da5963 100644
--- a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
+++ b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
@@ -569,13 +569,18 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
.toContain('Title and body are required.')
expect(sdkInvocationCount('clientNotifications')).toBe(before)
})
- await typeEmbedded(app, webContentsId, '#message', 'Plugin Workload SDK Desktop validation.')
+ await typeEmbedded(
+ app,
+ webContentsId,
+ '#message',
+ `Plugin Workload SDK Desktop validation ${marker}.`
+ )
await expect
.poll(() => embeddedValue(app!, webContentsId, '#title'))
.toBe(`Evenfire E2E ${marker}`)
await expect
.poll(() => embeddedValue(app!, webContentsId, '#message'))
- .toBe('Plugin Workload SDK Desktop validation.')
+ .toBe(`Plugin Workload SDK Desktop validation ${marker}.`)
await activateEmbedded(app, webContentsId, '#notify')
await expect
.poll(() => embeddedText(app!, webContentsId, '#notify-out'), { timeout: 30_000 })
@@ -604,7 +609,7 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
await expect(inbox).toBeVisible({ timeout: 20_000 })
const deliveredItem = inbox
.getByTestId('notification-menu-item')
- .filter({ hasText: `Evenfire E2E ${marker}` })
+ .filter({ hasText: `Plugin Workload SDK Desktop validation ${marker}.` })
await expect(deliveredItem).toBeVisible({ timeout: 30_000 })
await expect(inbox).not.toContainText('No notifications or pending approvals right now.')
await bell.click()
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
index 02dd2c575..4f64286e6 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
@@ -155,8 +155,21 @@ export async function launchDesktopApp(testInfo: TestInfo): Promise<{
slowMo: Number.isFinite(slowMo) ? slowMo : 75,
})
+ const actualUserDataDir = await app.evaluate(({ app: electronApp }) =>
+ electronApp.getPath('userData')
+ )
+ if (path.resolve(actualUserDataDir) !== path.resolve(userDataDir)) {
+ await app.close()
+ throw new Error(
+ `Electron did not honor the isolated user-data-dir: expected ${userDataDir}, got ${actualUserDataDir}`
+ )
+ }
+
const page = await app.firstWindow()
- await page.setViewportSize({ width: 1280, height: 720 })
+ // Do not emulate a CSS viewport for native WebContentsView journeys. On a
+ // Retina display that forces renderer DPR=1 while Electron remains at
+ // scaleFactor=2, producing misleading half-sized native bounds. The window
+ // is still recorded at 1280x720 when video capture is enabled above.
await page.waitForLoadState('domcontentloaded')
return { app, page }
}
diff --git a/desktop-app/ui/src/hooks/__tests__/useBrowserWindowState.test.tsx b/desktop-app/ui/src/hooks/__tests__/useBrowserWindowState.test.tsx
new file mode 100644
index 000000000..40ca2afb1
--- /dev/null
+++ b/desktop-app/ui/src/hooks/__tests__/useBrowserWindowState.test.tsx
@@ -0,0 +1,56 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { useBrowserWindowState } from '../useBrowserWindowState'
+
+type WindowState = { visible: boolean; focused: boolean }
+
+function installWindowBridge(initialState: WindowState) {
+ let listener: ((state: WindowState) => void) | null = null
+ const getVisibility = vi.fn(async () => initialState)
+ const onVisibilityChange = vi.fn((callback: (state: WindowState) => void) => {
+ listener = callback
+ return () => {
+ listener = null
+ }
+ })
+
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { window: { getVisibility, onVisibilityChange } },
+ })
+
+ return {
+ getVisibility,
+ onVisibilityChange,
+ emit(state: WindowState) {
+ listener?.(state)
+ },
+ }
+}
+
+describe('useBrowserWindowState', () => {
+ afterEach(() => {
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('uses native application focus instead of renderer document focus', async () => {
+ const bridge = installWindowBridge({ visible: true, focused: false })
+ const { result } = renderHook(() => useBrowserWindowState())
+
+ await waitFor(() => expect(bridge.getVisibility).toHaveBeenCalledTimes(1))
+ await waitFor(() => {
+ expect(result.current.isWindowVisible).toBe(true)
+ expect(result.current.isAppFocused).toBe(false)
+ })
+
+ act(() => bridge.emit({ visible: true, focused: true }))
+ expect(result.current.isAppFocused).toBe(true)
+ })
+
+ it('keeps the existing visibility behavior when the bridge is unavailable', () => {
+ const { result } = renderHook(() => useBrowserWindowState())
+
+ expect(result.current).toEqual({ isWindowVisible: true, isAppFocused: true })
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useNotificationSettingsController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useNotificationSettingsController.test.tsx
new file mode 100644
index 000000000..e1cade9b1
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useNotificationSettingsController.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { useNotificationSettingsController } from '../useNotificationSettingsController'
+
+type WindowState = { visible: boolean; focused: boolean }
+
+function installWindowBridge(initialState: WindowState) {
+ let listener: ((state: WindowState) => void) | null = null
+ const getVisibility = vi.fn(async () => initialState)
+ const onVisibilityChange = vi.fn((callback: (state: WindowState) => void) => {
+ listener = callback
+ return () => {
+ listener = null
+ }
+ })
+ const subscribe = () => () => undefined
+
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ window: { getVisibility, onVisibilityChange },
+ notifications: {
+ onClick: subscribe,
+ onAction: subscribe,
+ onFailed: subscribe,
+ },
+ },
+ })
+
+ return {
+ getVisibility,
+ emit(state: WindowState) {
+ listener?.(state)
+ },
+ }
+}
+
+describe('useNotificationSettingsController', () => {
+ afterEach(() => {
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('re-evaluates focused delivery after native focus changes', async () => {
+ const bridge = installWindowBridge({ visible: true, focused: false })
+ const { result } = renderHook(() => useNotificationSettingsController())
+
+ await waitFor(() => expect(bridge.getVisibility).toHaveBeenCalledTimes(1))
+ await waitFor(() => {
+ expect(
+ result.current.canDeliverChatResponseNotification('inApp', { activeChatVisible: false })
+ ).toBe(false)
+ })
+
+ act(() => bridge.emit({ visible: true, focused: true }))
+
+ await waitFor(() => {
+ expect(
+ result.current.canDeliverChatResponseNotification('inApp', { activeChatVisible: false })
+ ).toBe(true)
+ })
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/useNotificationSettingsController.ts b/desktop-app/ui/src/hooks/domain/useNotificationSettingsController.ts
index 481ab97d7..fb60557ab 100644
--- a/desktop-app/ui/src/hooks/domain/useNotificationSettingsController.ts
+++ b/desktop-app/ui/src/hooks/domain/useNotificationSettingsController.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { NOTIFICATION_SETTINGS_STORAGE_KEY } from '@constants/notificationSettings'
+import { useBrowserWindowState } from '@hooks/useBrowserWindowState'
import {
sanitizeNotificationSettings,
shouldDeliverChatResponseNotification,
@@ -40,16 +41,12 @@ function readInitialNotificationSettings(): NotificationSettings {
}
}
-function isAppFocused(): boolean {
- if (typeof document === 'undefined') return true
- return document.visibilityState === 'visible' && document.hasFocus()
-}
-
export function useNotificationSettingsController() {
const [settings, setSettings] = useState<NotificationSettings>(readInitialNotificationSettings)
const [desktopNotificationPermission, setDesktopNotificationPermission] =
useState<DesktopNotificationPermission>(readDesktopNotificationPermission)
const desktopNotificationHandlersRef = useRef<Map<string, DesktopNotificationHandler>>(new Map())
+ const { isAppFocused } = useBrowserWindowState()
const runDesktopNotificationHandler = useCallback(
(handler: (() => void | Promise<void>) | undefined, warning: string) => {
@@ -243,10 +240,10 @@ export function useNotificationSettingsController() {
const canDeliverChatResponseNotification = useCallback(
(channel: 'inApp' | 'desktop', context: { activeChatVisible: boolean }) =>
shouldDeliverChatResponseNotification(settings[channel], {
- appFocused: isAppFocused(),
+ appFocused: isAppFocused,
activeChatVisible: context.activeChatVisible,
}),
- [settings]
+ [isAppFocused, settings]
)
return {
diff --git a/desktop-app/ui/src/hooks/useBrowserWindowState.ts b/desktop-app/ui/src/hooks/useBrowserWindowState.ts
index 5069e22de..ed29ef00c 100644
--- a/desktop-app/ui/src/hooks/useBrowserWindowState.ts
+++ b/desktop-app/ui/src/hooks/useBrowserWindowState.ts
@@ -1,28 +1,42 @@
import { useEffect, useState } from 'react'
+type BrowserWindowState = { visible: boolean; focused: boolean }
+
/**
- * Tracks whether the Electron window is actually on-screen (not hidden or
- * minimized), driven by main-process events (D.5b §3.4). Used by the T4 nudge to
- * honestly tell the user whether they can close the window vs. rely on an OS
- * notification — `document.visibilityState` can't detect minimize on macOS.
+ * Tracks native Electron window state (visibility and application focus),
+ * driven by main-process events (D.5b §3.4). The focus bit deliberately comes
+ * from Electron: a native WebContentsView can own Chromium document focus
+ * while the Evenfire application remains focused.
*/
-export function useBrowserWindowState(): { isWindowVisible: boolean } {
+export function useBrowserWindowState(): {
+ isWindowVisible: boolean
+ isAppFocused: boolean
+} {
const [visible, setVisible] = useState(true) // optimistic until the first IPC reply
+ const [focused, setFocused] = useState(true)
useEffect(() => {
let cancelled = false
- void window.clerum.window
+ const bridge = window.clerum?.window
+ if (!bridge) return undefined
+ void bridge
.getVisibility()
.then(state => {
- if (!cancelled) setVisible(state.visible)
+ if (!cancelled) {
+ setVisible(state.visible)
+ setFocused(state.focused ?? true)
+ }
})
.catch(() => undefined)
- const unsub = window.clerum.window.onVisibilityChange(state => setVisible(state.visible))
+ const unsub = bridge.onVisibilityChange((state: BrowserWindowState) => {
+ setVisible(state.visible)
+ setFocused(state.focused ?? true)
+ })
return () => {
cancelled = true
unsub()
}
}, [])
- return { isWindowVisible: visible }
+ return { isWindowVisible: visible, isAppFocused: focused }
}
diff --git a/scripts/e2e/e2e-plugin-workload-sdk.sh b/scripts/e2e/e2e-plugin-workload-sdk.sh
index 6d941c4c4..677151e08 100755
--- a/scripts/e2e/e2e-plugin-workload-sdk.sh
+++ b/scripts/e2e/e2e-plugin-workload-sdk.sh
@@ -39,6 +39,11 @@ export RECIPE_NS="${RECIPE_NS:-sandbox-recipes}"
source "${SCRIPT_DIR}/e2e-lib.sh"
require_safe_kube_context
+die() {
+ printf '%s\n' "Plugin Workload SDK E2E error: $*" >&2
+ exit 1
+}
+
RECIPE_NAME="e2e-plugin-workload-sdk"
WORKLOAD_ID="sdk-caller"
EVENT_TYPE="e2e.test.notification"
@@ -143,6 +148,31 @@ E2E_WAIT_CALLER_MARKER="${E2E_WAIT_CALLER_MARKER:-180}"
E2E_WAIT_CALLER_DONE="${E2E_WAIT_CALLER_DONE:-180}"
E2E_WAIT_NOTIFICATION_ROW="${E2E_WAIT_NOTIFICATION_ROW:-60}"
+# Fail closed before creating any fixture if a caller or inherited shell
+# environment asks this gate to wait for an unbounded or human-scale interval.
+# These ceilings keep a broken reconcile/provider path actionable instead of
+# leaving a T2 run apparently idle for tens of minutes.
+E2E_HARD_MAX_GATE_SECONDS=600
+E2E_HARD_MAX_PHASE_WAIT_SECONDS=180
+E2E_HARD_MAX_POLL_INTERVAL_SECONDS=5
+
+validate_bounded_seconds() {
+ local name="$1" value="$2" ceiling="$3"
+ if [[ ! "$value" =~ ^[0-9]+$ ]] || [ "$value" -le 0 ] || [ "$value" -gt "$ceiling" ]; then
+ die "${name}=${value} exceeds the fail-closed ceiling of ${ceiling}s"
+ fi
+}
+
+validate_bounded_seconds E2E_GATE_MAX_SECONDS "$E2E_GATE_MAX_SECONDS" "$E2E_HARD_MAX_GATE_SECONDS"
+validate_bounded_seconds TIMEOUT_POD "$TIMEOUT_POD" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds TIMEOUT_DELETE "$TIMEOUT_DELETE" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds TIMEOUT_DISCOVERY "$TIMEOUT_DISCOVERY" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds E2E_WAIT_STATUS_VALIDATED "$E2E_WAIT_STATUS_VALIDATED" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds E2E_WAIT_CALLER_MARKER "$E2E_WAIT_CALLER_MARKER" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds E2E_WAIT_CALLER_DONE "$E2E_WAIT_CALLER_DONE" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds E2E_WAIT_NOTIFICATION_ROW "$E2E_WAIT_NOTIFICATION_ROW" "$E2E_HARD_MAX_PHASE_WAIT_SECONDS"
+validate_bounded_seconds POLL_INTERVAL "$POLL_INTERVAL" "$E2E_HARD_MAX_POLL_INTERVAL_SECONDS"
+
require_write_confirmation() {
if [ "${E2E_PLUGIN_SDK_WRITE_CONFIRM:-}" != "1" ]; then
printf '%s\n' \
@@ -412,16 +442,6 @@ cleanup_on_exit() {
exit "$status"
}
-if [ "${1:-}" = "--cleanup-only" ]; then
- require_write_confirmation || exit 2
- cleanup_sdk_recipe
- exit $?
-fi
-
-require_write_confirmation || exit 2
-
-trap cleanup_on_exit EXIT
-
# ─── control-api admin helpers (exec curl inside the control-api pod) ─────
control_api_pod() {
@@ -616,6 +636,15 @@ restore_notification_preferences() {
psql_query "INSERT INTO user_notification_preferences (user_id,preferred_medium,channel_fallback_enabled,preferred_account_id) VALUES ('${USER_REF}'::uuid,${medium_sql},${NOTIFICATION_PREF_SNAPSHOT_FALLBACK},${account_sql}) ON CONFLICT (user_id) DO UPDATE SET preferred_medium=EXCLUDED.preferred_medium,channel_fallback_enabled=EXCLUDED.channel_fallback_enabled,preferred_account_id=EXCLUDED.preferred_account_id,updated_at=NOW();" >/dev/null 2>&1
}
+if [ "${1:-}" = "--cleanup-only" ]; then
+ require_write_confirmation || exit 2
+ cleanup_sdk_recipe
+ exit $?
+fi
+
+require_write_confirmation || exit 2
+trap cleanup_on_exit EXIT
+
is_psql_true() {
case "$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" in
t | true) return 0 ;;
@@ -1079,7 +1108,7 @@ fetch(process.env.PLUGIN_WORKLOAD_SDK_ENDPOINT + "/v1/prompt-bridge", {
idempotencyKey: "e2e-deny-target-" + process.env.E2E_PROBE_RUN_ID,
messages: [{ role: "user", content: "x" }],
}),
-}).then(async r => { const b = await r.json().catch(() => ({})); console.log(r.status + ":" + (b.error || "")); process.exit(0) })
+}).then(async r => { const b = await r.json().catch(() => ({})); console.log(r.status + ":" + (b.error || "") + ":" + (b.message || "")); process.exit(0) })
.catch(() => { console.log("ERR"); process.exit(0) })
' 2>/dev/null || true)"
if printf "%s" "$unauthorized_target" | grep -q 'target_not_allowed'; then
@@ -1146,30 +1175,37 @@ logs="$(wait_for_caller_logs_matching E2E_SDK_CLIENT_NOTIFICATION_OK "$E2E_WAIT_
if printf "%s" "$logs" | grep -q E2E_SDK_PROMPT_BRIDGE_OK; then
ok "sdk-caller promptBridge call was authorized (invocationId returned)"
else
- fail "sdk-caller promptBridge call did not succeed within ${E2E_WAIT_CALLER_MARKER}s (fixture marker missing; caller logs redacted)"
- exit 1
-fi
-
-if printf "%s" "$logs" | grep -q E2E_SDK_EXPLICIT_TARGET_OK; then
- ok "sdk-caller explicit approved targetRef was served and returned non-empty content"
-else
- fail "sdk-caller explicit approved targetRef did not return a served target/content marker"
+ markers="$(printf '%s' "$logs" | grep -E '^E2E_SDK_(PROMPT_BRIDGE|EXPLICIT_TARGET|CLIENT_NOTIFICATION|IDEMPOTENCY|QUOTA|DONE)_' || true)"
+ fail "sdk-caller promptBridge call did not succeed within ${E2E_WAIT_CALLER_MARKER}s (markers=${markers:-<none>})"
exit 1
fi
if printf "%s" "$logs" | grep -q E2E_SDK_CLIENT_NOTIFICATION_OK; then
ok "sdk-caller clientNotifications call was accepted (notificationId returned)"
else
- fail "sdk-caller clientNotifications call did not succeed within ${E2E_WAIT_CALLER_MARKER}s (fixture marker missing; caller logs redacted)"
+ markers="$(printf '%s' "$logs" | grep -E '^E2E_SDK_(PROMPT_BRIDGE|EXPLICIT_TARGET|CLIENT_NOTIFICATION|IDEMPOTENCY|QUOTA|DONE)_' || true)"
+ fail "sdk-caller clientNotifications call did not succeed within ${E2E_WAIT_CALLER_MARKER}s (markers=${markers:-<none>})"
exit 1
fi
+# The fixture intentionally exercises the approved selector after the first
+# notification, then idempotency and quota. Waiting for its terminal marker
+# gives the process time to emit those later markers instead of evaluating a
+# partial log snapshot immediately after clientNotifications succeeds.
logs="$(wait_for_caller_logs_matching E2E_SDK_DONE "$E2E_WAIT_CALLER_DONE" || true)"
if ! printf "%s" "$logs" | grep -q E2E_SDK_DONE; then
fail "sdk-caller fixture did not finish within ${E2E_WAIT_CALLER_DONE}s"
exit 1
fi
+if printf "%s" "$logs" | grep -q E2E_SDK_EXPLICIT_TARGET_OK; then
+ ok "sdk-caller explicit approved targetRef was served and returned non-empty content"
+else
+ markers="$(printf '%s' "$logs" | grep -E '^E2E_SDK_(PROMPT_BRIDGE|EXPLICIT_TARGET|CLIENT_NOTIFICATION|IDEMPOTENCY|QUOTA|DONE)_' || true)"
+ fail "sdk-caller explicit approved targetRef did not return a served target/content marker (markers=${markers:-<none>})"
+ exit 1
+fi
+
NOTIFICATION_ID="$(printf '%s' "$logs" | sed -n 's/.*E2E_SDK_CLIENT_NOTIFICATION_OK=\([^[:space:]]*\).*/\1/p' | tail -1)"
if [ -z "$NOTIFICATION_ID" ]; then
fail "could not parse notificationId from sdk-caller logs"
diff --git a/scripts/minikube/pre-gate-incremental.sh b/scripts/minikube/pre-gate-incremental.sh
index 4744ede3c..79aaf6c5d 100755
--- a/scripts/minikube/pre-gate-incremental.sh
+++ b/scripts/minikube/pre-gate-incremental.sh
@@ -28,6 +28,7 @@ incremental_is_nonruntime_path() {
case "$1" in
AGENTS.md|README.md|CONTRIBUTING.md|SECURITY.md|LICENSE|docs/*|*.md|.github/*) return 0 ;;
desktop-app/*|scripts/e2e/*|scripts/tests/*) return 0 ;;
+ tests/e2e/fixtures/workflow-plugin-sdk-e2e/*) return 1 ;;
*/test/*|*/__tests__/*|*.test.*|*.spec.*|tests/*) return 0 ;;
*) return 1 ;;
esac
@@ -55,6 +56,9 @@ incremental_classify_path() {
control-ui/*) incremental_add_target control-ui control-plane control-ui ;;
profile-ui/*) incremental_add_target profile-ui profiles profile-ui ;;
webhook-proxy/*) incremental_add_target webhook-proxy webhook-ingress webhook-proxy ;;
+ tests/e2e/fixtures/workflow-plugin-sdk-e2e/*)
+ incremental_add_target workflow-plugin-sdk-e2e sandbox-recipes workflow-plugin-sdk-e2e
+ ;;
deploy/*)
INCREMENTAL_FULL_DEPLOYMENT=true
;;
diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.sh
index 0f258a30a..a2a72a863 100755
--- a/scripts/minikube/pre-gate-sync.sh
+++ b/scripts/minikube/pre-gate-sync.sh
@@ -348,6 +348,16 @@ if [[ "${cluster_changed}" == "true" ]]; then
ensure_evenfire_registry
incremental_restart_targets
+ # nginx.conf is mounted through a subPath. Kubernetes updates the
+ # ConfigMap object but does not refresh that file in an already-running pod,
+ # so a full deployment sync must roll the gateway before any SDK probe uses
+ # the new route set.
+ if [[ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ||
+ "${FORCE_RESTART}" == "true" ]]; then
+ rollout_restart_with_retry control-plane nginx-workflow-approval-gateway
+ rollout_if_present control-plane nginx-workflow-approval-gateway
+ fi
+
rollout_if_present control-plane host-context-controller
rollout_if_present control-plane workflow-recipes
rollout_if_present control-plane control-ui
diff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.sh
index 866a9b2f7..f99f8a814 100755
--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh
+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh
@@ -91,7 +91,9 @@ fi
if incremental_contains 'control-api/*) incremental_add_target control-api control-plane control-api' &&
incremental_contains 'rpc-proxy/*) incremental_add_target rpc-proxy rpc-proxy rpc-proxy' &&
incremental_contains 'host-context-controller/*) incremental_add_target host-context-controller control-plane host-context-controller' &&
- incremental_contains 'control-ui/*) incremental_add_target control-ui control-plane control-ui'; then
+ incremental_contains 'control-ui/*) incremental_add_target control-ui control-plane control-ui' &&
+ incremental_contains 'tests/e2e/fixtures/workflow-plugin-sdk-e2e/*)' &&
+ incremental_contains 'incremental_add_target workflow-plugin-sdk-e2e sandbox-recipes workflow-plugin-sdk-e2e'; then
pass "incremental sync maps known runtime paths to their own images and deployments"
else
fail "incremental sync does not map known runtime paths precisely"
@@ -115,6 +117,15 @@ else
fail "pre-gate sync does not use the shared idempotent auth-key sync helper"
fi
+if contains 'nginx.conf is mounted through a subPath' &&
+ contains 'INCREMENTAL_FULL_DEPLOYMENT' &&
+ contains 'rollout_restart_with_retry control-plane nginx-workflow-approval-gateway' &&
+ contains 'rollout_if_present control-plane nginx-workflow-approval-gateway'; then
+ pass "pre-gate sync refreshes the subPath-mounted workflow gateway after deployment changes"
+else
+ fail "pre-gate sync can leave a stale workflow gateway after ConfigMap changes"
+fi
+
if contains 'fingerprint_dir packages/workflow-runtime-core' &&
contains 'run_if_changed packages/workflow-runtime-core "npm test && npm run build"' &&
contains 'ensure_artifact packages/workflow-runtime-core dist/index.js "npm run build"'; then
diff --git a/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh b/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
index 198a1fd9d..1d9762991 100755
--- a/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
+++ b/scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
@@ -151,4 +151,14 @@ else
pass 'admin session material is not passed as a kubectl/node process argument'
fi
+if grep -Fq 'E2E_HARD_MAX_GATE_SECONDS=600' "$SCRIPT" &&
+ grep -Fq 'E2E_HARD_MAX_PHASE_WAIT_SECONDS=180' "$SCRIPT" &&
+ grep -Fq 'E2E_HARD_MAX_POLL_INTERVAL_SECONDS=5' "$SCRIPT" &&
+ grep -Fq 'validate_bounded_seconds E2E_GATE_MAX_SECONDS' "$SCRIPT" &&
+ grep -Fq 'validate_bounded_seconds TIMEOUT_POD' "$SCRIPT"; then
+ pass 'Plugin Workload SDK E2E rejects human-scale waits before creating resources'
+else
+ fail 'Plugin Workload SDK E2E lacks fail-closed wait ceilings'
+fi
+
exit "$FAIL"
diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.json
index 7205f87da..ca012ce2e 100644
--- a/tests/e2e/fixtures/package-lock.json
+++ b/tests/e2e/fixtures/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.53",
+ "version": "1.0.54",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.53",
+ "version": "1.0.54",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.json
index dca048fa7..6fe74cf35 100644
--- a/tests/e2e/fixtures/package.json
+++ b/tests/e2e/fixtures/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.53",
+ "version": "1.0.54",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",
diff --git a/tests/e2e/fixtures/workflow-plugin-sdk-e2e/src/index.js b/tests/e2e/fixtures/workflow-plugin-sdk-e2e/src/index.js
index 4db5afae3..c063598a9 100644
--- a/tests/e2e/fixtures/workflow-plugin-sdk-e2e/src/index.js
+++ b/tests/e2e/fixtures/workflow-plugin-sdk-e2e/src/index.js
@@ -27,6 +27,10 @@ const USER_REF = process.env.E2E_SDK_USER_REF || 'e2e-test-user'
const RUN_ID = process.env.E2E_SDK_RUN_ID || String(Date.now())
const QUOTA_LIMIT = parseInt(process.env.E2E_SDK_QUOTA_LIMIT || '4', 10)
const EXPLICIT_TARGET_REF = process.env.E2E_SDK_EXPLICIT_TARGET_REF || ''
+// Every SDK request must fail closed if the server stops responding. The
+// outer shell gate also has bounded polling, but fetch itself otherwise has no
+// implicit deadline and could keep a fixture alive indefinitely.
+const SDK_REQUEST_TIMEOUT_MS = 15_000
/** Tracks the invocationId from the first promptBridge call for idempotency check. */
let firstPromptBridgeId = null
@@ -46,6 +50,7 @@ async function callSdk(path, body) {
'x-clerum-caller-ref': CALLER_REF,
},
body: JSON.stringify(body),
+ signal: AbortSignal.timeout(SDK_REQUEST_TIMEOUT_MS),
})
let parsed = null
try {