Skip to content

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

TypeScript

fix(hcc): skip no-op PDB replaces and treat empty env or NP slices as absent (#673)

ALFREDO J LOPEZ H (alfredolopez80.eth)0c7aca0eda60
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index f6145e1a7..aa84e757f 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -9,7 +9,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.8.1',
externalRestApiVersion: '0.1.82',
- rpcProxyVersion: '0.1.77',
+ rpcProxyVersion: '0.1.80',
desktopVersion: '0.8.1',
minimumDesktopVersion: '0.1.252',
}
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 0958b59f3..ac10a721e 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.333",
+ "version": "0.1.336",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.333",
+ "version": "0.1.336",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 5e0eb67c3..921d081c5 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.333",
+ "version": "0.1.336",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts b/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
index 231feb436..0ff56b873 100644
--- a/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
+++ b/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
@@ -18,6 +18,7 @@ import {
preserveDeploymentAnnotations,
} from '../utils'
import { RECORDED_APPSV1_DEPLOYMENT, asApiserverDeployment } from './asApiserverDeployment'
+import liveCodexCert from './fixtures/629/codex-cert.deployment.json'
import {
cloneAndMutateLeaf,
collectLeafPaths,
@@ -413,4 +414,50 @@ describe('deploymentMatchesDesired', () => {
) as k8s.V1Deployment
expectSweepDetectsLiveOnlySpecLeaves(desired, asApiserverDeployment(desired))
})
+
+ it('T1: empty env value is equivalent to an omitted value', () => {
+ const live = sparseDeployment()
+ live.spec!.template.spec!.containers[0].env = [{ name: 'CLERUM_LLM_SECRET_REF' }]
+ const desiredEmpty = structuredClone(live)
+ desiredEmpty.spec!.template.spec!.containers[0].env = [
+ { name: 'CLERUM_LLM_SECRET_REF', value: '' },
+ ]
+ expect(live.spec?.template.spec?.containers[0].env?.[0]).not.toHaveProperty('value')
+ expect(deploymentMatchesDesired(desiredEmpty, live)).toBe(true)
+ })
+
+ it('T1: a real env value is not equivalent to an omitted value', () => {
+ const live = sparseDeployment()
+ live.spec!.template.spec!.containers[0].env = [{ name: 'CLERUM_LLM_SECRET_REF' }]
+ const desiredSet = structuredClone(live)
+ desiredSet.spec!.template.spec!.containers[0].env = [
+ { name: 'CLERUM_LLM_SECRET_REF', value: 'x' },
+ ]
+ expect(deploymentMatchesDesired(desiredSet, live)).toBe(false)
+ })
+
+ it('T1: empty env value is not equivalent to a valueFrom secret ref', () => {
+ const live = sparseDeployment()
+ live.spec!.template.spec!.containers[0].env = [
+ { name: 'CLERUM_LLM_SECRET_REF', valueFrom: { secretKeyRef: { name: 's', key: 'k' } } },
+ ]
+ const desiredEmpty = structuredClone(live)
+ desiredEmpty.spec!.template.spec!.containers[0].env = [
+ { name: 'CLERUM_LLM_SECRET_REF', value: '' },
+ ]
+ expect(deploymentMatchesDesired(desiredEmpty, live)).toBe(false)
+ expect(deploymentMatchesDesired(live, desiredEmpty)).toBe(false)
+ })
+
+ it('T1: 629 fixture env without value matches empty value', () => {
+ const live = liveCodexCert as k8s.V1Deployment
+ const liveEnv = live.spec?.template.spec?.containers[0].env?.[0]
+ expect(liveEnv?.name).toBe('CLERUM_LLM_SECRET_REF')
+ expect(liveEnv).not.toHaveProperty('value')
+ const desiredEmpty = structuredClone(live)
+ desiredEmpty.spec!.template.spec!.containers[0].env = [
+ { name: 'CLERUM_LLM_SECRET_REF', value: '' },
+ ]
+ expect(deploymentMatchesDesired(desiredEmpty, live)).toBe(true)
+ })
})
diff --git a/host-context-controller/src/__tests__/fixtures/629/codex-cert.deployment.json b/host-context-controller/src/__tests__/fixtures/629/codex-cert.deployment.json
new file mode 100644
index 000000000..2ca1fc3b5
--- /dev/null
+++ b/host-context-controller/src/__tests__/fixtures/629/codex-cert.deployment.json
@@ -0,0 +1,39 @@
+{
+ "apiVersion": "apps/v1",
+ "kind": "Deployment",
+ "metadata": {
+ "name": "codex-cert",
+ "namespace": "mcp-host",
+ "labels": {
+ "app": "synthetic-host"
+ }
+ },
+ "spec": {
+ "replicas": 1,
+ "selector": {
+ "matchLabels": {
+ "app": "synthetic-host"
+ }
+ },
+ "template": {
+ "metadata": {
+ "labels": {
+ "app": "synthetic-host"
+ }
+ },
+ "spec": {
+ "containers": [
+ {
+ "name": "host",
+ "image": "registry.example.com/mcp-host:synthetic",
+ "env": [
+ {
+ "name": "CLERUM_LLM_SECRET_REF"
+ }
+ ]
+ }
+ ]
+ }
+ }
+ }
+}
diff --git a/host-context-controller/src/__tests__/fixtures/629/gfsc-writer-pdb.json b/host-context-controller/src/__tests__/fixtures/629/gfsc-writer-pdb.json
new file mode 100644
index 000000000..68ba30e2d
--- /dev/null
+++ b/host-context-controller/src/__tests__/fixtures/629/gfsc-writer-pdb.json
@@ -0,0 +1,22 @@
+{
+ "apiVersion": "policy/v1",
+ "kind": "PodDisruptionBudget",
+ "metadata": {
+ "generation": 1,
+ "labels": {
+ "clerum.io/globalfilesystem": "gfs",
+ "clerum.io/managed-by": "host-context-controller"
+ },
+ "name": "gfsc-writer-pdb",
+ "namespace": "gfs"
+ },
+ "spec": {
+ "minAvailable": 1,
+ "selector": {
+ "matchLabels": {
+ "app": "gfs-controller",
+ "clerum.io/gfsc-role": "writer"
+ }
+ }
+ }
+}
diff --git a/host-context-controller/src/__tests__/fixtures/629/np-llmhook-8204baab199521b5.json b/host-context-controller/src/__tests__/fixtures/629/np-llmhook-8204baab199521b5.json
new file mode 100644
index 000000000..46c525e76
--- /dev/null
+++ b/host-context-controller/src/__tests__/fixtures/629/np-llmhook-8204baab199521b5.json
@@ -0,0 +1,24 @@
+{
+ "apiVersion": "networking.k8s.io/v1",
+ "kind": "NetworkPolicy",
+ "metadata": {
+ "annotations": {
+ "clerum.io/llmhook-members": "tool-policy-hook"
+ },
+ "labels": {
+ "app": "llmhook-8204baab199521b5",
+ "clerum.io/hook-pod-key": "8204baab199521b5",
+ "clerum.io/managed-by": "host-context-controller"
+ },
+ "name": "llmhook-8204baab199521b5",
+ "namespace": "llm-hooks"
+ },
+ "spec": {
+ "podSelector": {
+ "matchLabels": {
+ "clerum.io/hook-pod-key": "8204baab199521b5"
+ }
+ },
+ "policyTypes": ["Ingress"]
+ }
+}
diff --git a/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts b/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts
index 916a07b2a..80acddd4b 100644
--- a/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts
@@ -203,6 +203,51 @@ describe('LlmHook NetworkPolicy no-op gate', () => {
expect(body.spec?.ingress).toEqual(desired.spec?.ingress)
})
+ it('T6: hook with no referencing hosts skips replace when live omits empty ingress', async () => {
+ const hook = makeImageHook()
+ const podKey = computePodKey(hook)!
+ const desiredEmpty = (reconciler as any).buildNetworkPolicy(
+ podKey,
+ [hook],
+ []
+ ) as k8s.V1NetworkPolicy
+ expect(desiredEmpty.spec?.ingress).toEqual([])
+ const live = structuredClone(desiredEmpty)
+ delete live.spec!.ingress
+ live.metadata = { ...live.metadata, resourceVersion: '3' }
+ networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(live)
+
+ await (reconciler as any).ensureNetworkPolicy(podKey, [hook], [])
+ expect(networkingApi.readNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(networkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(networkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('T6: adding a referencing Host still replaces the live policy', async () => {
+ const hook = makeImageHook()
+ const podKey = computePodKey(hook)!
+ const desiredEmpty = (reconciler as any).buildNetworkPolicy(
+ podKey,
+ [hook],
+ []
+ ) as k8s.V1NetworkPolicy
+ const live = structuredClone(desiredEmpty)
+ delete live.spec!.ingress
+ live.metadata = { ...live.metadata, resourceVersion: '3' }
+ const host = makeHost(hook.name)
+ hosts.set(host.name, host)
+ const desiredWithHost = (reconciler as any).buildNetworkPolicy(
+ podKey,
+ [hook],
+ []
+ ) as k8s.V1NetworkPolicy
+ expect(desiredWithHost.spec?.ingress?.length).toBeGreaterThan(0)
+ networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(live)
+ await (reconciler as any).ensureNetworkPolicy(podKey, [hook], [])
+ expect(networkingApi.readNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(networkingApi.replaceNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ })
+
it('propagates GET 403 without creating or replacing a policy', async () => {
const error = { code: 403 }
networkingApi.readNamespacedNetworkPolicy.mockRejectedValue(error)
diff --git a/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts b/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts
index 9f8de91cf..dd90ac3cf 100644
--- a/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts
+++ b/host-context-controller/src/__tests__/networkPolicyMatchesDesired.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
import { networkPolicyMatchesDesired } from '../utils'
import { RECORDED_NETWORKPOLICY, asApiserverNetworkPolicy } from './asApiserverNetworkPolicy'
+import liveLlmhookNp from './fixtures/629/np-llmhook-8204baab199521b5.json'
function desiredPolicy(overrides: Partial<k8s.V1NetworkPolicy> = {}): k8s.V1NetworkPolicy {
return {
@@ -212,12 +213,98 @@ describe('networkPolicyMatchesDesired', () => {
}
})
- it('CMP-NP-13: empty egress array vs omitted fails open to write', () => {
+ it('CMP-NP-13: empty egress array is equivalent to an omitted egress field', () => {
const omitted = desiredPolicy()
const emptyEgress: k8s.V1NetworkPolicy = {
...omitted,
spec: { ...omitted.spec, egress: [] },
}
- expect(networkPolicyMatchesDesired(emptyEgress, asApiserverNetworkPolicy(omitted))).toBe(false)
+ expect(networkPolicyMatchesDesired(emptyEgress, asApiserverNetworkPolicy(omitted))).toBe(true)
+ })
+
+ it('T2: empty ingress matches an omitted ingress field', () => {
+ const selector = { matchLabels: { app: 'np' } }
+ const live: k8s.V1NetworkPolicy = {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'np' } },
+ spec: { podSelector: selector, policyTypes: ['Ingress'] },
+ }
+ const emptyIngress: k8s.V1NetworkPolicy = {
+ ...live,
+ spec: { podSelector: selector, policyTypes: ['Ingress'], ingress: [] },
+ }
+ expect(live.spec).not.toHaveProperty('ingress')
+ expect(networkPolicyMatchesDesired(emptyIngress, live)).toBe(true)
+ })
+
+ it('T2: a non-empty ingress slice does not match an omitted ingress field', () => {
+ const selector = { matchLabels: { app: 'np' } }
+ const live: k8s.V1NetworkPolicy = {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'np' } },
+ spec: { podSelector: selector, policyTypes: ['Ingress'] },
+ }
+ const withRule: k8s.V1NetworkPolicy = {
+ ...live,
+ spec: {
+ podSelector: selector,
+ policyTypes: ['Ingress'],
+ // Witness is occupancy: a present ingress array is not omitempty-equivalent
+ // to an omitted field. The client-node type names this field `_from`
+ // (reserved word). The matcher JSON-compares clones and does not run
+ // ObjectSerializer, so the key stays `_from`.
+ ingress: [{ _from: [{ podSelector: { matchLabels: { app: 'peer' } } }] }],
+ },
+ }
+ expect(networkPolicyMatchesDesired(withRule, live)).toBe(false)
+ })
+
+ it('T2: distinct ingress from rules do not match', () => {
+ const selector = { matchLabels: { app: 'np' } }
+ const peer: k8s.V1NetworkPolicy = {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'np' } },
+ spec: {
+ podSelector: selector,
+ policyTypes: ['Ingress'],
+ ingress: [{ _from: [{ podSelector: { matchLabels: { app: 'peer' } } }] }],
+ },
+ }
+ const other: k8s.V1NetworkPolicy = {
+ ...peer,
+ spec: {
+ ...peer.spec!,
+ ingress: [{ _from: [{ podSelector: { matchLabels: { app: 'other' } } }] }],
+ },
+ }
+ expect(networkPolicyMatchesDesired(peer, other)).toBe(false)
+ })
+
+ it('T2: empty egress with derived policyTypes matches an omitted egress field', () => {
+ const selector = { matchLabels: { app: 'np' } }
+ const live: k8s.V1NetworkPolicy = {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: { name: 'np', namespace: 'ns', labels: { app: 'np' } },
+ spec: { podSelector: selector, policyTypes: ['Ingress'] },
+ }
+ const emptyEgressDerived: k8s.V1NetworkPolicy = {
+ ...live,
+ spec: { podSelector: selector, egress: [] },
+ }
+ expect(networkPolicyMatchesDesired(emptyEgressDerived, live)).toBe(true)
+ })
+
+ it('T2: 629 fixture without ingress matches empty ingress', () => {
+ const live = liveLlmhookNp as k8s.V1NetworkPolicy
+ expect(live.spec).not.toHaveProperty('ingress')
+ const emptyIngress: k8s.V1NetworkPolicy = {
+ ...live,
+ spec: { ...live.spec, policyTypes: live.spec?.policyTypes ?? ['Ingress'], ingress: [] },
+ }
+ expect(networkPolicyMatchesDesired(emptyIngress, live)).toBe(true)
})
})
diff --git a/host-context-controller/src/hostReconciler.readFirst.test.ts b/host-context-controller/src/hostReconciler.readFirst.test.ts
index 5270b45a6..01095d665 100644
--- a/host-context-controller/src/hostReconciler.readFirst.test.ts
+++ b/host-context-controller/src/hostReconciler.readFirst.test.ts
@@ -15,7 +15,7 @@ import {
} from '../test/__fixtures__/testMocks'
import { asApiserverService } from './__tests__/asApiserverService'
import { HostReconciler } from './hostReconciler'
-import { CREATE_KINDS, createsTotal } from './metrics'
+import { CREATE_KINDS, createsTotal, writeSkipsTotal } from './metrics'
import type { HostCRD } from './types'
const host: HostCRD = {
@@ -266,6 +266,61 @@ describe('Host read-first Service and Deployment contracts', () => {
expect(await count('Deployment', 'skipped')).toBe(0)
})
+ function hostWithoutSecretRef(): HostCRD {
+ return {
+ name: 'codex-cert',
+ namespace: 'mcp-host',
+ uid: 'host-uid-nosecret',
+ spec: { host: 'codex-cert', contextRef: 'context' },
+ }
+ }
+
+ function liveHostDeploymentWithoutSecretValue(
+ reconciler: HostReconciler,
+ hostNoSecret: HostCRD
+ ): k8s.V1Deployment {
+ const desired = reconciler.buildDeployment(hostNoSecret, [], 'runtime-revision')
+ const liveEqual = structuredClone(desired)
+ const liveSecret = liveEqual.spec?.template.spec?.containers
+ .flatMap(container => container.env ?? [])
+ .find(env => env.name === 'CLERUM_LLM_SECRET_REF')
+ if (!liveSecret) {
+ throw new Error('expected CLERUM_LLM_SECRET_REF on the built Host Deployment')
+ }
+ delete liveSecret.value
+ liveEqual.metadata = { ...liveEqual.metadata, resourceVersion: '11' }
+ return liveEqual
+ }
+
+ it('T5: Host without secretRef skips replace when live omits empty value', async () => {
+ const { apps, reconciler } = fixture()
+ const hostNoSecret = hostWithoutSecretRef()
+ const desired = reconciler.buildDeployment(hostNoSecret, [], 'runtime-revision')
+ const secretEnv = desired.spec?.template.spec?.containers
+ .flatMap(container => container.env ?? [])
+ .find(env => env.name === 'CLERUM_LLM_SECRET_REF')
+ expect(secretEnv).toEqual({ name: 'CLERUM_LLM_SECRET_REF', value: '' })
+ const liveEqual = liveHostDeploymentWithoutSecretValue(reconciler, hostNoSecret)
+ writeSkipsTotal.reset()
+ apps.readNamespacedDeployment.mockResolvedValue(liveEqual)
+ await (reconciler as any).ensureDeployment(hostNoSecret, [], 'runtime-revision')
+ expect(apps.readNamespacedDeployment).toHaveBeenCalledTimes(1)
+ expect(apps.replaceNamespacedDeployment).not.toHaveBeenCalled()
+ expect(apps.createNamespacedDeployment).not.toHaveBeenCalled()
+ })
+
+ it('T5: Host without secretRef still replaces when the live image differs', async () => {
+ const { apps, reconciler } = fixture()
+ const hostNoSecret = hostWithoutSecretRef()
+ const liveDrift = liveHostDeploymentWithoutSecretValue(reconciler, hostNoSecret)
+ liveDrift.spec!.template.spec!.containers[0].image = 'registry.example.com/mcp-host:other'
+ liveDrift.metadata = { ...liveDrift.metadata, resourceVersion: '12' }
+ apps.readNamespacedDeployment.mockResolvedValue(liveDrift)
+ await (reconciler as any).ensureDeployment(hostNoSecret, [], 'runtime-revision')
+ expect(apps.readNamespacedDeployment).toHaveBeenCalledTimes(1)
+ expect(apps.replaceNamespacedDeployment).toHaveBeenCalledTimes(1)
+ })
+
it('counts a Host Service create race as conflict and never as skipped', async () => {
const { core, reconciler } = fixture()
core.readNamespacedService.mockRejectedValueOnce({ code: 404 })
diff --git a/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts b/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts
index b8253cda8..6dc85e953 100644
--- a/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts
+++ b/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts
@@ -1,6 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
-import { createsTotal, existenceReadsTotal } from '../metrics'
+import livePdbFixture from '../__tests__/fixtures/629/gfsc-writer-pdb.json'
+import { createsTotal, existenceReadsTotal, writeSkipsTotal } from '../metrics'
+import { podDisruptionBudgetMatchesDesired } from '../utils'
import { K8sGfsApi } from './gfsK8sApi'
const namespace = 'mcp-host'
@@ -48,7 +50,7 @@ const cases = [
},
{
kind: 'PodDisruptionBudget',
- updates: true,
+ updates: false,
body: {
kind: 'PodDisruptionBudget',
metadata,
@@ -100,6 +102,7 @@ async function count(metric: typeof createsTotal, kind: string, outcome: string)
beforeEach(() => {
createsTotal.reset()
existenceReadsTotal.reset()
+ writeSkipsTotal.reset()
})
describe.each(cases)('K8sGfsApi $kind read-first', resource => {
@@ -255,3 +258,90 @@ describe.each(cases.filter(resource => resource.updates))(
})
}
)
+
+describe('K8sGfsApi PodDisruptionBudget no-op gate (T4)', () => {
+ const namespace = 'gfs'
+ const desired = livePdbFixture as k8s.V1PodDisruptionBudget
+
+ async function skipCount() {
+ return (
+ (await writeSkipsTotal.get()).values.find(row => row.labels.kind === 'PodDisruptionBudget')
+ ?.value ?? 0
+ )
+ }
+
+ it('T4: skips replace when the live PDB matches', async () => {
+ const equal = harness('PodDisruptionBudget')
+ equal.read.mockImplementation(async () => {
+ equal.events.push('GET')
+ return {
+ ...desired,
+ status: {
+ currentHealthy: 1,
+ desiredHealthy: 1,
+ disruptionsAllowed: 0,
+ expectedPods: 1,
+ },
+ metadata: {
+ ...desired.metadata,
+ resourceVersion: '1',
+ uid: 'pdb-uid',
+ creationTimestamp: new Date('2026-01-01T00:00:00Z'),
+ managedFields: [{ manager: 'kube-apiserver', operation: 'Update' }],
+ },
+ }
+ })
+ await equal.api.applyPodDisruptionBudget(desired, namespace)
+ expect(equal.read).toHaveBeenCalledTimes(1)
+ expect(equal.replace).toHaveBeenCalledTimes(0)
+ expect(await skipCount()).toBe(1)
+ })
+
+ it('T4: retries a drifted PDB PUT after 409 using a fresh resourceVersion', async () => {
+ const h = harness('PodDisruptionBudget')
+ let version = 0
+ h.read.mockImplementation(async () => {
+ h.events.push('GET')
+ return {
+ ...desired,
+ metadata: { ...desired.metadata, resourceVersion: String(++version) },
+ spec: { ...desired.spec, minAvailable: 2 },
+ }
+ })
+ h.replace.mockImplementationOnce(async ({ body }) => {
+ h.events.push(`PUT:${body.metadata?.resourceVersion}`)
+ throw { code: 409 }
+ })
+ await h.api.applyPodDisruptionBudget(desired, namespace)
+ expect(h.events).toEqual(['GET', 'PUT:1', 'GET', 'PUT:2'])
+ expect(h.replace).toHaveBeenCalledTimes(2)
+ expect(h.create).not.toHaveBeenCalled()
+ })
+
+ it('T4: writes when minAvailable differs', async () => {
+ const drifted = harness('PodDisruptionBudget')
+ const live = {
+ ...desired,
+ metadata: { ...desired.metadata, resourceVersion: '7' },
+ spec: { ...desired.spec, minAvailable: 2 },
+ }
+ drifted.read.mockImplementation(async () => {
+ drifted.events.push('GET')
+ return live
+ })
+ await drifted.api.applyPodDisruptionBudget(desired, namespace)
+ expect(drifted.read).toHaveBeenCalledTimes(1)
+ expect(drifted.replace).toHaveBeenCalledTimes(1)
+ const replaced = drifted.replace.mock.calls[0][0].body as k8s.V1PodDisruptionBudget
+ expect(replaced.spec?.minAvailable).toBe(1)
+ expect(await skipCount()).toBe(0)
+ })
+
+ it('T4: a live unhealthyPodEvictionPolicy is drift', () => {
+ const live = {
+ ...desired,
+ spec: { ...desired.spec, unhealthyPodEvictionPolicy: 'AlwaysAllow' as const },
+ }
+ expect(podDisruptionBudgetMatchesDesired(desired, live)).toBe(false)
+ })
+})
diff --git a/host-context-controller/src/k8s/gfsK8sApi.ts b/host-context-controller/src/k8s/gfsK8sApi.ts
index 6eed0f49e..681ec5a1b 100644
--- a/host-context-controller/src/k8s/gfsK8sApi.ts
+++ b/host-context-controller/src/k8s/gfsK8sApi.ts
@@ -8,6 +8,8 @@ import {
getErrorCode,
observeCreate,
observeExistenceRead,
+ podDisruptionBudgetMatchesDesired,
+ preserveObjectAnnotations,
replaceWithConflictRetry,
} from '../utils'
import { GFS_TEMPLATE_HASH_ANNOTATION } from './gfsFactory'
@@ -144,6 +146,8 @@ export class K8sGfsApi implements GfsK8sApi {
description: `pod disruption budget "${name}" in ${namespace}`,
logPrefix: LOG,
body: pdb,
+ mergeExisting: preserveObjectAnnotations,
+ isUpToDate: podDisruptionBudgetMatchesDesired,
read,
replace: body =>
this.policyApi.replaceNamespacedPodDisruptionBudget({ name, namespace, body }),
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index 6f3f001fc..2b1989900 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -310,6 +310,34 @@ export function preserveServiceAssignedFields<
}
}
+/**
+ * True when the desired PodDisruptionBudget is equivalent to the live object.
+ * policy/v1 does not default-fill spec fields on this object, so comparison is
+ * the whole PDB after stripping server-owned metadata. Labels, finalizers, and
+ * ownerReferences are compared in full (mergeExisting keeps annotations only).
+ * Doubt or a malformed object returns false (fail-open-to-write).
+ */
+export function podDisruptionBudgetMatchesDesired(
+ desired: k8s.V1PodDisruptionBudget | undefined,
+ existing: k8s.V1PodDisruptionBudget | undefined
+): boolean {
+ try {
+ if (!desired?.spec || !existing?.spec) return false
+ return (
+ JSON.stringify(normalizePodDisruptionBudgetForComparison(desired)) ===
+ JSON.stringify(normalizePodDisruptionBudgetForComparison(existing))
+ )
+ } catch {
+ return false
+ }
+}
+
+function normalizePodDisruptionBudgetForComparison(pdb: k8s.V1PodDisruptionBudget): unknown {
+ const normalized = structuredClone(pdb)
+ stripServerOwnedMetadata(normalized)
+ return canonicalizeValue(normalized)
+}
+
/**
* True when the merged desired Service is equivalent to the live object, so a
* replace would be a no-op. Canonicalize first: the apiserver default-fills
@@ -438,6 +466,9 @@ function normalizeNetworkPolicyForComparison(policy: k8s.V1NetworkPolicy): unkno
if (port.protocol === 'TCP') delete port.protocol
}
}
+ // Empty slices persist the same as an omitted field for the apiserver.
+ if (spec.ingress?.length === 0) delete spec.ingress
+ if (spec.egress?.length === 0) delete spec.egress
}
return canonicalizeValue(normalized)
@@ -544,6 +575,7 @@ export function normalizeContainerDefaults(container: k8s.V1Container): void {
if (probe.httpGet?.scheme === 'HTTP') delete probe.httpGet.scheme
}
for (const env of container.env ?? []) {
+ if (env.value === '') delete env.value
if (env.valueFrom?.fieldRef?.apiVersion === 'v1') {
delete env.valueFrom.fieldRef.apiVersion
}
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 13318c48c..61f4fc42d 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.77",
+ "version": "0.1.80",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.77",
+ "version": "0.1.80",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 23471ba1e..17d1d6dd8 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.77",
+ "version": "0.1.80",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/__tests__/model-selection.test.ts b/rpc-proxy/src/__tests__/model-selection.test.ts
index 1ec712d29..0c643d96c 100644
--- a/rpc-proxy/src/__tests__/model-selection.test.ts
+++ b/rpc-proxy/src/__tests__/model-selection.test.ts
@@ -45,6 +45,8 @@ function makeApp() {
return app
}
+const originalFetch = globalThis.fetch
+
describe('GET /rpc/hosts/:hostRef/models — passthrough to mcp-host', () => {
beforeEach(() => {
authTokenMock.verifyRpcToken.mockReturnValue(READ_CLAIMS)
@@ -52,7 +54,9 @@ describe('GET /rpc/hosts/:hostRef/models — passthrough to mcp-host', () => {
})
afterEach(() => {
- vi.restoreAllMocks()
+ authTokenMock.verifyRpcToken.mockReset()
+ serviceMock.resolveHostConnectionForUser.mockReset()
+ globalThis.fetch = originalFetch
})
it('forwards to mcp-host and returns the upstream body verbatim', async () => {
@@ -142,7 +146,9 @@ describe('POST /rpc/hosts/:hostRef/model — set per-session model', () => {
})
afterEach(() => {
- vi.restoreAllMocks()
+ authTokenMock.verifyRpcToken.mockReset()
+ serviceMock.resolveHostConnectionForUser.mockReset()
+ globalThis.fetch = originalFetch
})
it('forwards the body to mcp-host and returns the upstream response', async () => {
diff --git a/rpc-proxy/src/__tests__/sender-assignment.test.ts b/rpc-proxy/src/__tests__/sender-assignment.test.ts
index 4b596ba76..7f347e5aa 100644
--- a/rpc-proxy/src/__tests__/sender-assignment.test.ts
+++ b/rpc-proxy/src/__tests__/sender-assignment.test.ts
@@ -44,6 +44,8 @@ function makeApp() {
return app
}
+const originalFetch = globalThis.fetch
+
describe('POST /rpc/hosts/:hostRef/messages — sender assignment invariant', () => {
beforeEach(() => {
authTokenMock.verifyRpcToken.mockReturnValue(VALID_CLAIMS)
@@ -53,6 +55,7 @@ describe('POST /rpc/hosts/:hostRef/messages — sender assignment invariant', ()
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forces host messages onto the authenticated rpc envelope', async () => {
@@ -154,6 +157,7 @@ describe('POST /rpc/hosts/:hostRef/approvals/approve — userId identity invaria
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forwards userId = auth.sub regardless of client-supplied userId', async () => {
@@ -191,6 +195,7 @@ describe('POST /rpc/hosts/:hostRef/approvals/deny — userId identity invariant'
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forwards userId = auth.sub regardless of client-supplied userId', async () => {
diff --git a/rpc-proxy/src/__tests__/session-rename-passthrough.test.ts b/rpc-proxy/src/__tests__/session-rename-passthrough.test.ts
index 7cf28b42e..c1d28c348 100644
--- a/rpc-proxy/src/__tests__/session-rename-passthrough.test.ts
+++ b/rpc-proxy/src/__tests__/session-rename-passthrough.test.ts
@@ -48,6 +48,8 @@ function makeApp() {
return app
}
+const originalFetch = globalThis.fetch
+
describe('PATCH /rpc/hosts/:hostRef/sessions/:agent/:chatId/name — rename passthrough', () => {
beforeEach(() => {
authTokenMock.verifyRpcToken.mockReturnValue(VALID_CLAIMS)
@@ -56,6 +58,7 @@ describe('PATCH /rpc/hosts/:hostRef/sessions/:agent/:chatId/name — rename pass
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forwards PATCH to mcp-host with :agent and :chatId in the path and body verbatim', async () => {
diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
index 8fb5e616c..21ce230b3 100644
--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
@@ -44,6 +44,8 @@ function makeApp() {
return app
}
+const originalFetch = globalThis.fetch
+
describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {
beforeEach(() => {
authTokenMock.verifyRpcToken.mockReturnValue(VALID_CLAIMS)
@@ -52,6 +54,7 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forwards to mcp-host and returns the upstream body verbatim', async () => {
@@ -183,6 +186,7 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrou
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forwards to mcp-host with :agent and :chatId in the path', async () => {
@@ -356,6 +360,7 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/context-breakdown —
afterEach(() => {
vi.restoreAllMocks()
+ globalThis.fetch = originalFetch
})
it('forwards to mcp-host with :agent and :chatId in the path', async () => {
diff --git a/rpc-proxy/src/routes/rpcHostActivityStream.ts b/rpc-proxy/src/routes/rpcHostActivityStream.ts
index 4877bcc2c..ce1264b05 100644
--- a/rpc-proxy/src/routes/rpcHostActivityStream.ts
+++ b/rpc-proxy/src/routes/rpcHostActivityStream.ts
@@ -13,6 +13,17 @@ const activeStreamCountsByUserHost = new Map<string, number>()
const activeStreams = new Set<string>()
let streamCounter = 0
+/** Clears in-process stream counters. Tests must call this; production never does. */
+export function resetHostActivityStreamRuntimeForTests(): void {
+ if (process.env.VITEST !== 'true' && process.env.NODE_ENV !== 'test') {
+ throw new Error('resetHostActivityStreamRuntimeForTests is test-only')
+ }
+ activeStreamCountsByUser.clear()
+ activeStreamCountsByUserHost.clear()
+ activeStreams.clear()
+ streamCounter = 0
+}
+
function nextStreamId(): string {
streamCounter += 1
return `activity-stream-${Date.now()}-${streamCounter}`
diff --git a/rpc-proxy/src/routes/rpcHostStatusStream.ts b/rpc-proxy/src/routes/rpcHostStatusStream.ts
index bc806e144..d3fd70544 100644
--- a/rpc-proxy/src/routes/rpcHostStatusStream.ts
+++ b/rpc-proxy/src/routes/rpcHostStatusStream.ts
@@ -55,6 +55,17 @@ function sanitizedStreamErrorMessage(): string {
return 'Status temporarily unavailable'
}
+/** Clears in-process stream counters. Tests must call this; production never does. */
+export function resetHostStatusStreamRuntimeForTests(): void {
+ if (process.env.VITEST !== 'true' && process.env.NODE_ENV !== 'test') {
+ throw new Error('resetHostStatusStreamRuntimeForTests is test-only')
+ }
+ activeStreamCountsByUser.clear()
+ activeStreamCountsByUserHost.clear()
+ activeStreams.clear()
+ streamCounter = 0
+}
+
export function createRpcHostStatusStreamRouter(): Router {
const router = Router()
diff --git a/rpc-proxy/test/routes.rpcHostActivityStream.test.ts b/rpc-proxy/test/routes.rpcHostActivityStream.test.ts
index ebfb87eb1..347b38f15 100644
--- a/rpc-proxy/test/routes.rpcHostActivityStream.test.ts
+++ b/rpc-proxy/test/routes.rpcHostActivityStream.test.ts
@@ -1,20 +1,22 @@
-import express from "express";
-import request from "supertest";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import {
+ createRpcHostActivityStreamRouter,
+ resetHostActivityStreamRuntimeForTests,
+} from '../src/routes/rpcHostActivityStream.js'
const authTokenMock = vi.hoisted(() => ({
- verifyRpcToken: vi.fn()
-}));
+ verifyRpcToken: vi.fn(),
+}))
const serviceMock = vi.hoisted(() => ({
- resolveHostConnectionForUser: vi.fn()
-}));
+ resolveHostConnectionForUser: vi.fn(),
+}))
-vi.mock("../src/authToken.js", () => authTokenMock);
-vi.mock("../src/services/mcpProxyService.js", () => serviceMock);
-
-import { config } from "../src/config.js";
-import { createRpcHostActivityStreamRouter } from "../src/routes/rpcHostActivityStream.js";
+vi.mock('../src/authToken.js', () => authTokenMock)
+vi.mock('../src/services/mcpProxyService.js', () => serviceMock)
const defaultConfig = {
activityStreamMaxConcurrent: config.activityStreamMaxConcurrent,
@@ -22,148 +24,164 @@ const defaultConfig = {
activityStreamMaxPerUserHost: config.activityStreamMaxPerUserHost,
activityStreamMaxLifetimeMs: config.activityStreamMaxLifetimeMs,
activityStreamKeepaliveMs: config.activityStreamKeepaliveMs,
- activityStreamIdleTimeoutMs: config.activityStreamIdleTimeoutMs
-};
+ activityStreamIdleTimeoutMs: config.activityStreamIdleTimeoutMs,
+}
function makeApp() {
- const app = express();
- app.use(createRpcHostActivityStreamRouter());
- return app;
+ const app = express()
+ app.use(createRpcHostActivityStreamRouter())
+ return app
}
-describe("routes/rpcHostActivityStream", () => {
+describe('routes/rpcHostActivityStream', () => {
beforeEach(() => {
- authTokenMock.verifyRpcToken.mockReset();
- serviceMock.resolveHostConnectionForUser.mockReset();
- Object.assign(config, defaultConfig);
- vi.restoreAllMocks();
- });
+ resetHostActivityStreamRuntimeForTests()
+ authTokenMock.verifyRpcToken.mockReset()
+ serviceMock.resolveHostConnectionForUser.mockReset()
+ Object.assign(config, defaultConfig)
+ vi.restoreAllMocks()
+ })
- it("returns 401 without token", async () => {
- const app = makeApp();
- await request(app).get("/rpc/hosts/agent2/activity/stream").expect(401);
- });
+ it('returns 401 without token', async () => {
+ const app = makeApp()
+ await request(app).get('/rpc/hosts/agent2/activity/stream').expect(401)
+ })
- it("returns 403 without host:activity:read scope", async () => {
+ it('returns 403 without host:activity:read scope', async () => {
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:status:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:status:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
- const app = makeApp();
- await request(app).get("/rpc/hosts/agent2/activity/stream").set("authorization", "Bearer token").expect(403);
- });
+ exp: 9999999999,
+ })
+ const app = makeApp()
+ await request(app)
+ .get('/rpc/hosts/agent2/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(403)
+ })
- it("returns 403 for unauthorized host", async () => {
+ it('returns 403 for unauthorized host', async () => {
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:activity:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:activity:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
- serviceMock.resolveHostConnectionForUser.mockResolvedValue(null);
- const app = makeApp();
- await request(app).get("/rpc/hosts/nope/activity/stream").set("authorization", "Bearer token").expect(403);
- });
+ exp: 9999999999,
+ })
+ serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)
+ const app = makeApp()
+ await request(app)
+ .get('/rpc/hosts/nope/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(403)
+ })
- it("returns 429 when stream limits are exceeded", async () => {
- config.activityStreamMaxConcurrent = 0;
+ it('returns 429 when stream limits are exceeded', async () => {
+ config.activityStreamMaxConcurrent = 0
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:activity:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:activity:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
+ exp: 9999999999,
+ })
serviceMock.resolveHostConnectionForUser.mockResolvedValue({
- name: "agent2",
- url: "http://host.local",
- headers: {}
- });
- const app = makeApp();
- await request(app).get("/rpc/hosts/agent2/activity/stream").set("authorization", "Bearer token").expect(429);
- });
+ name: 'agent2',
+ url: 'http://host.local',
+ headers: {},
+ })
+ const app = makeApp()
+ await request(app)
+ .get('/rpc/hosts/agent2/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(429)
+ })
- it("emits only allowed event names and sanitizes upstream errors", async () => {
- config.activityStreamMaxLifetimeMs = 25;
- config.activityStreamKeepaliveMs = 5;
- config.activityStreamIdleTimeoutMs = 100;
+ it('emits only allowed event names and sanitizes upstream errors', async () => {
+ config.activityStreamMaxLifetimeMs = 25
+ config.activityStreamKeepaliveMs = 5
+ config.activityStreamIdleTimeoutMs = 100
authTokenMock.verifyRpcToken.mockReturnValue({
- sub: "user-1",
- typ: "user",
- teamId: "team-1",
- scopes: ["host:activity:read"],
- hostRefs: ["agent2"],
- jti: "j1",
+ sub: 'user-1',
+ typ: 'user',
+ teamId: 'team-1',
+ scopes: ['host:activity:read'],
+ hostRefs: ['agent2'],
+ jti: 'j1',
iat: 1,
- exp: 9999999999
- });
+ exp: 9999999999,
+ })
serviceMock.resolveHostConnectionForUser.mockResolvedValue({
- name: "agent2",
- url: "http://host.local",
- headers: {}
- });
+ name: 'agent2',
+ url: 'http://host.local',
+ headers: {},
+ })
const streamPayload = [
- "event: open",
- `data: ${JSON.stringify({ hostRef: "agent2", observedAt: new Date().toISOString() })}`,
- "",
- "event: activity",
+ 'event: open',
+ `data: ${JSON.stringify({ hostRef: 'agent2', observedAt: new Date().toISOString() })}`,
+ '',
+ 'event: activity',
`data: ${JSON.stringify({
- version: "1.0",
- eventId: "evt_1",
- hostRef: "agent2",
+ version: '1.0',
+ eventId: 'evt_1',
+ hostRef: 'agent2',
ts: new Date().toISOString(),
- type: "task.started",
- title: "started",
- severity: "info",
+ type: 'task.started',
+ title: 'started',
+ severity: 'info',
meta: {},
- redactions: []
+ redactions: [],
})}`,
- "",
- "event: message",
- `data: ${JSON.stringify({ should: "be ignored" })}`,
- "",
- "event: error",
- `data: ${JSON.stringify({ message: "http://internal.local/secret-token" })}`,
- "",
- "event: closed",
- `data: ${JSON.stringify({ reason: "done" })}`,
- ""
- ].join("\n");
+ '',
+ 'event: message',
+ `data: ${JSON.stringify({ should: 'be ignored' })}`,
+ '',
+ 'event: error',
+ `data: ${JSON.stringify({ message: 'http://internal.local/secret-token' })}`,
+ '',
+ 'event: closed',
+ `data: ${JSON.stringify({ reason: 'done' })}`,
+ '',
+ ].join('\n')
- vi.spyOn(globalThis, "fetch").mockResolvedValue(
- new Response(new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(streamPayload));
- controller.close();
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(streamPayload))
+ controller.close()
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
}
- }), {
- status: 200,
- headers: { "content-type": "text/event-stream" }
- })
- );
+ )
+ )
- const app = makeApp();
- const response = await request(app).get("/rpc/hosts/agent2/activity/stream").set("authorization", "Bearer token").expect(200);
- expect(response.text).toContain("event: open");
- expect(response.text).toContain("event: activity");
- expect(response.text).toContain("event: error");
- expect(response.text).toContain("Activity temporarily unavailable");
- expect(response.text).toContain("event: closed");
- expect(response.text).not.toContain("event: message");
- expect(response.text).not.toContain("internal.local");
- expect(response.text).not.toContain("secret-token");
- });
-});
+ const app = makeApp()
+ const response = await request(app)
+ .get('/rpc/hosts/agent2/activity/stream')
+ .set('authorization', 'Bearer token')
+ .expect(200)
+ expect(response.text).toContain('event: open')
+ expect(response.text).toContain('event: activity')
+ expect(response.text).toContain('event: error')
+ expect(response.text).toContain('Activity temporarily unavailable')
+ expect(response.text).toContain('event: closed')
+ expect(response.text).not.toContain('event: message')
+ expect(response.text).not.toContain('internal.local')
+ expect(response.text).not.toContain('secret-token')
+ })
+})
diff --git a/rpc-proxy/test/routes.rpcHostStatusStream.test.ts b/rpc-proxy/test/routes.rpcHostStatusStream.test.ts
index 331408639..ee0daf362 100644
--- a/rpc-proxy/test/routes.rpcHostStatusStream.test.ts
+++ b/rpc-proxy/test/routes.rpcHostStatusStream.test.ts
@@ -2,7 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
import { config } from '../src/config.js'
-import { createRpcHostStatusStreamRouter } from '../src/routes/rpcHostStatusStream.js'
+import {
+ createRpcHostStatusStreamRouter,
+ resetHostStatusStreamRuntimeForTests,
+} from '../src/routes/rpcHostStatusStream.js'
const authTokenMock = vi.hoisted(() => ({
verifyRpcToken: vi.fn(),
@@ -42,6 +45,7 @@ const defaultStreamConfig = {
describe('routes/rpcHostStatusStream', () => {
beforeEach(() => {
+ resetHostStatusStreamRuntimeForTests()
authTokenMock.verifyRpcToken.mockReset()
serviceMock.resolveHostConnectionForUser.mockReset()
serviceMock.forwardHostStatus.mockReset()