Skip to content

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

TypeScript

chore(oss): refresh dev → public sync (dev@db43d12) — post-#820 back-port convergence

Jose Ramirezf6abe0c8b3e1
diff --git a/channel-reader/makefile b/channel-reader/makefile
index 6038ead75..61bc8ae27 100644
--- a/channel-reader/makefile
+++ b/channel-reader/makefile
@@ -1,6 +1,6 @@
.PHONY: dev build install clean docker-build docker-push docker-push-cross docker-login
-REGISTRY ?= us-central1-docker.pkg.dev/your-gcp-project/clerum
+REGISTRY ?= us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum
IMAGE_NAME ?= channel-reader
TAG ?= $(shell git describe --tags --always 2>/dev/null || echo "latest")
TELEGRAM_BOT_TOKEN ?= # fill this in for local development
diff --git a/channel-reader/package-lock.json b/channel-reader/package-lock.json
index 1f07b9e2f..eeefc3394 100644
--- a/channel-reader/package-lock.json
+++ b/channel-reader/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-channel-reader",
- "version": "0.1.78",
+ "version": "0.1.79",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-channel-reader",
- "version": "0.1.78",
+ "version": "0.1.79",
"license": "MIT",
"dependencies": {
"@kubernetes/client-node": "^1.0.0",
diff --git a/channel-reader/package.json b/channel-reader/package.json
index d45492c59..b75fa33cf 100644
--- a/channel-reader/package.json
+++ b/channel-reader/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-channel-reader",
- "version": "0.1.78",
+ "version": "0.1.79",
"description": "Watches CommunicationChannel CRDs and fetches messages from Telegram, Email, and Slack",
"main": "dist/main.js",
"engines": {
diff --git a/charts/clerum-crds/crds/wrc-trigger-rbac.yaml b/charts/clerum-crds/crds/wrc-trigger-rbac.yaml
deleted file mode 100644
index 9e60f8d21..000000000
--- a/charts/clerum-crds/crds/wrc-trigger-rbac.yaml
+++ /dev/null
@@ -1,40 +0,0 @@
----
-apiVersion: v1
-kind: ServiceAccount
-metadata:
- name: wrc-trigger-sa
- namespace: control-plane
- labels:
- clerum.io/managed-by: clerum-wrc
- clerum.io/component: scheduling-trigger
----
-apiVersion: rbac.authorization.k8s.io/v1
-kind: ClusterRole
-metadata:
- name: wrc-trigger-role
- labels:
- clerum.io/managed-by: clerum-wrc
-rules:
- # Allow CronJob trigger container to POST to WRC service
- - apiGroups: [""]
- resources: ["services/proxy"]
- verbs: ["create"]
- # Allow token introspection for authentication
- - apiGroups: ["authentication.k8s.io"]
- resources: ["tokenreviews"]
- verbs: ["create"]
----
-apiVersion: rbac.authorization.k8s.io/v1
-kind: ClusterRoleBinding
-metadata:
- name: wrc-trigger-binding
- labels:
- clerum.io/managed-by: clerum-wrc
-subjects:
- - kind: ServiceAccount
- name: wrc-trigger-sa
- namespace: control-plane
-roleRef:
- kind: ClusterRole
- name: wrc-trigger-role
- apiGroup: rbac.authorization.k8s.io
diff --git a/charts/clerum-crds/examples/airtable-mcp-deployment-recipe.yaml b/charts/clerum-crds/examples/airtable-mcp-deployment-recipe.yaml
index 4dc2b638b..b777d6a81 100644
--- a/charts/clerum-crds/examples/airtable-mcp-deployment-recipe.yaml
+++ b/charts/clerum-crds/examples/airtable-mcp-deployment-recipe.yaml
@@ -26,7 +26,7 @@ spec:
workloads:
- id: airtable-mcp
type: deployment
- image: us-central1-docker.pkg.dev/your-gcp-project/clerum/airtable-mcp-server:latest
+ image: us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/airtable-mcp-server:latest
imagePullSecrets:
- clerum # GCP Artifact Registry secret
replicas: 1
diff --git a/control-api/Makefile b/control-api/Makefile
index 74378d558..25c894f91 100644
--- a/control-api/Makefile
+++ b/control-api/Makefile
@@ -1,6 +1,6 @@
.PHONY: install build docker-build docker-push
-REGISTRY ?= us-central1-docker.pkg.dev/your-gcp-project/clerum
+REGISTRY ?= us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum
IMAGE_NAME ?= control-api
TAG ?= $(shell git describe --tags --always 2>/dev/null || echo "latest")
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 7d6d171e9..2596070c1 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.361",
+ "version": "0.1.364",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.361",
+ "version": "0.1.364",
"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 2da951f40..d065b2406 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.361",
+ "version": "0.1.364",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.ts
index 95d9e873d..72ec9a41c 100644
--- a/control-api/src/routes/admin/registry.ts
+++ b/control-api/src/routes/admin/registry.ts
@@ -127,7 +127,8 @@ type SecretSnapshot = {
}
type CredentialPayloadValidation =
- { ok: true; secretData: Record<string, string> } | { ok: false; body: Record<string, unknown> }
+ | { ok: true; secretData: Record<string, string> }
+ | { ok: false; body: Record<string, unknown> }
function looksLikeCredentialPlaceholder(value: string): boolean {
const normalized = value.trim().toLowerCase()
@@ -1075,7 +1076,9 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
}
const transport = (entry.transport ?? 'streamableHttp') as
- 'streamableHttp' | 'sse' | 'stdio'
+ | 'streamableHttp'
+ | 'sse'
+ | 'stdio'
const port = (meta?.port as number | undefined) ?? 3000
const secretName = `${serverName}-credentials`
@@ -2397,7 +2400,9 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {
const limit = toPageNum(req.query.limit)
const offset = toPageNum(req.query.offset)
const raw = (await listOrgEntries(ctx.orgName, { limit, offset })) as
- { data?: unknown[]; entries?: unknown[]; meta?: unknown } | null | undefined
+ | { data?: unknown[]; entries?: unknown[]; meta?: unknown }
+ | null
+ | undefined
const data = raw?.data ?? raw?.entries ?? []
res.status(200).json(raw?.meta !== undefined ? { data, meta: raw.meta } : { data })
} catch (err) {
diff --git a/control-api/src/routes/gfs/grants.ts b/control-api/src/routes/gfs/grants.ts
index d0aab7194..bf4a1c069 100644
--- a/control-api/src/routes/gfs/grants.ts
+++ b/control-api/src/routes/gfs/grants.ts
@@ -51,7 +51,8 @@ export function subjectKey(subject: GfsSubject): string {
export class GfsGrantError extends Error {
constructor(
readonly status: number,
- readonly code: string
+ readonly code: string,
+ readonly invalidIndexes?: readonly number[]
) {
super(code)
this.name = 'GfsGrantError'
@@ -234,6 +235,106 @@ export async function assertMayGrant(
target: GfsSubject,
opts: { isShare: boolean }
): Promise<void> {
+ await assertMayGrantBatch(db, caller, drive, resourceId, permissions, [target], opts)
+}
+
+interface GrantAuthoritySnapshot {
+ ancestors: Set<string>
+ grants: GrantRow[]
+ shares: ShareRow[]
+}
+
+async function loadGrantAuthority(
+ db: GrantsDb,
+ caller: GfsCaller,
+ drive: string,
+ resourceId: string
+): Promise<GrantAuthoritySnapshot | null> {
+ if (caller.isOperator) return null
+ const { types, ids } = subjectColumns(caller.subjects)
+ const result = await db.query(
+ `WITH RECURSIVE chain AS (
+ SELECT resource_id, parent_resource_id, 0 AS depth
+ FROM gfs_resources
+ WHERE drive = $1 AND resource_id = $2::uuid AND deleted_at IS NULL
+ UNION ALL
+ SELECT r.resource_id, r.parent_resource_id, c.depth + 1
+ FROM gfs_resources r
+ JOIN chain c ON r.resource_id = c.parent_resource_id
+ WHERE r.drive = $1 AND r.deleted_at IS NULL
+ ),
+ requested_subjects(subject_type, subject_id) AS (
+ SELECT * FROM unnest($3::text[], $4::text[])
+ ),
+ authority_grants AS (
+ SELECT g.subject_type, g.subject_id, g.resource_id, g.permissions, g.inherit
+ FROM gfs_grants g
+ JOIN requested_subjects s
+ ON s.subject_type = g.subject_type AND s.subject_id = g.subject_id
+ WHERE g.drive = $1
+ ),
+ authority_shares AS (
+ SELECT s0.subject_type, s0.subject_id, s0.resource_id, s0.permissions,
+ s0.include_descendants
+ FROM gfs_shares s0
+ JOIN requested_subjects s
+ ON s.subject_type = s0.subject_type AND s.subject_id = s0.subject_id
+ WHERE s0.drive = $1
+ )
+ SELECT
+ COALESCE(
+ (SELECT jsonb_agg(c.resource_id ORDER BY c.depth ASC) FROM chain c),
+ '[]'::jsonb
+ ) AS ancestors,
+ COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'subject_type', g.subject_type,
+ 'subject_id', g.subject_id,
+ 'resource_id', g.resource_id,
+ 'permissions', g.permissions,
+ 'inherit', g.inherit
+ )) FROM authority_grants g),
+ '[]'::jsonb
+ ) AS grants,
+ COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'subject_type', s.subject_type,
+ 'subject_id', s.subject_id,
+ 'resource_id', s.resource_id,
+ 'permissions', s.permissions,
+ 'include_descendants', s.include_descendants
+ )) FROM authority_shares s),
+ '[]'::jsonb
+ ) AS shares`,
+ [drive, resourceId, types, ids]
+ )
+ const row = (result.rows[0] ?? {}) as Record<string, unknown>
+ const ancestorList = Array.isArray(row.ancestors) ? row.ancestors.map(String) : []
+ const grantRows = Array.isArray(row.grants) ? (row.grants as Record<string, unknown>[]) : []
+ const shareRows = Array.isArray(row.shares) ? (row.shares as Record<string, unknown>[]) : []
+ return {
+ ancestors: new Set(ancestorList),
+ grants: grantRows.map(grant => ({
+ subjectKey: `${String(grant.subject_type)}:${String(grant.subject_id ?? '')}`,
+ resourceId: String(grant.resource_id),
+ permissions: (grant.permissions as string[]) ?? [],
+ inherit: Boolean(grant.inherit),
+ })),
+ shares: shareRows.map(share => ({
+ subjectKey: `${String(share.subject_type)}:${String(share.subject_id ?? '')}`,
+ resourceId: String(share.resource_id),
+ permissions: (share.permissions as string[]) ?? [],
+ includeDescendants: Boolean(share.include_descendants),
+ })),
+ }
+}
+
+function assertTargetPolicy(
+ caller: GfsCaller,
+ permissions: readonly GfsPermission[],
+ target: GfsSubject,
+ opts: { isShare: boolean }
+): void {
// Agent (host) restriction (spec §Delegation): manage_acl/share are never
// grantable to a host by a folder owner — only the operator can. `share` as a
// share-grant is for users/teams only, never a host.
@@ -251,36 +352,54 @@ export async function assertMayGrant(
if (!caller.isOperator && target.type === 'operator') {
throw new GfsGrantError(403, 'operator_grant_forbidden')
}
+}
+function assertAuthorityMayGrant(
+ snapshot: GrantAuthoritySnapshot | null,
+ caller: GfsCaller,
+ resourceId: string,
+ permissions: readonly GfsPermission[],
+ opts: { isShare: boolean }
+): void {
// Operator is the intrinsic root of trust — may grant any bit anywhere.
if (caller.isOperator) return
- const ancestorList = await ancestorsOf(db, drive, resourceId)
- if (ancestorList.length === 0) {
+ if (!snapshot || snapshot.ancestors.size === 0) {
throw new GfsGrantError(403, opts.isShare ? 'not_sharer' : 'not_manager')
}
- const ancestors = new Set(ancestorList)
- const [grants, shares] = await Promise.all([
- loadGrants(db, drive, caller.subjects),
- loadShares(db, drive, caller.subjects),
- ])
// Subtree confinement: the grantor must hold the authority bit on R (or an
// inheriting ancestor) — `manage_acl` to write a folder grant, `share` to
// write a URI share (spec §Permission bits). Holding it on R via the inherit
// rule is exactly "R is within the grantor's subtree".
const authorityBit: GfsPermission = opts.isShare ? 'share' : 'manage_acl'
- if (!holds(authorityBit, resourceId, ancestors, grants, shares)) {
+ if (!holds(authorityBit, resourceId, snapshot.ancestors, snapshot.grants, snapshot.shares)) {
throw new GfsGrantError(403, opts.isShare ? 'not_sharer' : 'not_manager')
}
// No-escalation: the grantor may only hand out bits it itself holds.
for (const p of permissions) {
- if (!holds(p, resourceId, ancestors, grants, shares)) {
+ if (!holds(p, resourceId, snapshot.ancestors, snapshot.grants, snapshot.shares)) {
throw new GfsGrantError(403, 'escalation_rejected')
}
}
}
+export async function assertMayGrantBatch(
+ db: GrantsDb,
+ caller: GfsCaller,
+ drive: string,
+ resourceId: string,
+ permissions: readonly GfsPermission[],
+ targets: readonly GfsSubject[],
+ opts: { isShare: boolean }
+): Promise<void> {
+ for (const target of targets) {
+ assertTargetPolicy(caller, permissions, target, opts)
+ }
+ const snapshot = await loadGrantAuthority(db, caller, drive, resourceId)
+ assertAuthorityMayGrant(snapshot, caller, resourceId, permissions, opts)
+}
+
/**
* Plain access check: does `caller` hold `op` on `resourceId`? (Used by the
* move/rename write path — P2-S05.) Operator is intrinsic; otherwise the same
@@ -399,14 +518,70 @@ export function parseSubject(value: unknown): GfsSubject {
if ((type === 'user' || type === 'team') && !UUID_RE.test(id)) {
throw new GfsGrantError(400, 'subject_invalid')
}
+ const canonicalId = type === 'user' || type === 'team' ? id.toLowerCase() : id
// host ids are canonical provisioner principals: 1st/3rd party plus a
// Kubernetes namespace/name pair. Do not accept free-form host strings here:
// grants written with a shape the token minter never issues become an inert
// second source of truth and can mask security-review drift.
- if (type === 'host' && !isValidHostSubjectId(id)) {
+ if (type === 'host' && !isValidHostSubjectId(canonicalId)) {
throw new GfsGrantError(400, 'subject_invalid')
}
- return { type: type as GfsSubjectType, id }
+ return { type: type as GfsSubjectType, id: canonicalId }
+}
+
+export function assertMutationSubjectTransport(body: Record<string, unknown>): void {
+ const hasSubject = Object.prototype.hasOwnProperty.call(body, 'subject')
+ const hasSubjects = Object.prototype.hasOwnProperty.call(body, 'subjects')
+ if (hasSubject === hasSubjects) {
+ throw new GfsGrantError(400, 'subjects_invalid')
+ }
+}
+
+export function normalizeMutationSubjects(
+ body: Record<string, unknown>,
+ opts: { isShare: boolean }
+): GfsSubject[] {
+ assertMutationSubjectTransport(body)
+ const hasSubject = Object.prototype.hasOwnProperty.call(body, 'subject')
+ if (hasSubject) return [parseSubject(body.subject)]
+
+ if (!Array.isArray(body.subjects) || body.subjects.length < 1 || body.subjects.length > 100) {
+ throw new GfsGrantError(400, 'subjects_invalid')
+ }
+
+ const normalized: GfsSubject[] = []
+ const seen = new Set<string>()
+ const invalidIndexes: number[] = []
+ for (const [index, value] of body.subjects.entries()) {
+ try {
+ const subject = parseSubject(value)
+ const pluralTypeAllowed = opts.isShare
+ ? subject.type === 'user' || subject.type === 'team'
+ : subject.type === 'user' || subject.type === 'team' || subject.type === 'host'
+ const key = subjectKey(subject)
+ if (!pluralTypeAllowed || seen.has(key)) {
+ invalidIndexes.push(index)
+ continue
+ }
+ seen.add(key)
+ normalized.push(subject)
+ } catch (error) {
+ if (!(error instanceof GfsGrantError)) throw error
+ invalidIndexes.push(index)
+ }
+ }
+ if (invalidIndexes.length > 0) {
+ throw new GfsGrantError(400, 'subjects_invalid', invalidIndexes)
+ }
+ return normalized
+}
+
+export function sendGfsGrantError(res: import('express').Response, error: GfsGrantError): void {
+ res.status(error.status).json({
+ error: error.code,
+ message: error.message,
+ ...(error.invalidIndexes ? { invalidIndexes: error.invalidIndexes } : {}),
+ })
}
export function parsePermissions(value: unknown): GfsPermission[] {
@@ -426,6 +601,14 @@ export function driveOf(value: unknown): string {
return typeof value === 'string' && value.length > 0 ? value : DEFAULT_DRIVE
}
+export function permissionReadFilter(req: Request): { drive: string; resourceId: string } {
+ const drive = typeof req.query.drive === 'string' ? req.query.drive : ''
+ const resourceId = typeof req.query.resourceId === 'string' ? req.query.resourceId : ''
+ if (!drive) throw new GfsGrantError(400, 'drive_required')
+ if (!UUID_RE.test(resourceId)) throw new GfsGrantError(400, 'resource_invalid')
+ return { drive, resourceId }
+}
+
export function requestIdOf(req: Request): string | undefined {
const id = (req as { correlationId?: string }).correlationId
return typeof id === 'string' && id.length > 0 ? id : undefined
@@ -479,40 +662,182 @@ export async function appendGfsPermissionEvent(
outcome: 'committed' | 'rejected'
auditId: string | null
}
+): Promise<void> {
+ await appendGfsPermissionEvents(db, {
+ ...params,
+ subjects: [params.subject],
+ auditIds: [params.auditId],
+ })
+}
+
+export async function appendGfsPermissionEvents(
+ db: DbClient,
+ params: {
+ req: Request
+ caller: GfsCaller
+ subjects: readonly GfsSubject[]
+ permissions: readonly string[]
+ drive: string
+ resourceId: string
+ mutation: 'grant' | 'share'
+ action: 'grant' | 'revoke'
+ outcome: 'committed' | 'rejected'
+ auditIds: readonly (string | null)[]
+ }
): Promise<void> {
const operator = permissionEventOperator(params.req, params.caller)
await appendControlApiPermissionEventsInTransaction(db, {
operatorSub: operator.sub,
operatorKind: operator.kind,
requestId: requestIdOf(params.req) ?? null,
- changes: [
- {
- action: params.action,
- resourceClass: params.mutation === 'grant' ? 'gfs_folder_grant' : 'gfs_share',
- resourceRef: `gfs://${params.drive}/${params.resourceId}`,
- subject: permissionEventSubject(params.subject),
- sourceAuditRef: params.auditId ? `gfs_audit:${params.auditId}` : null,
- status:
- params.outcome === 'rejected'
- ? `${params.mutation}_${params.action}_rejected`
- : `${params.mutation}_${params.action === 'grant' ? 'configured' : 'revoked'}`,
- detailRef: permissionsDetailRef(params.permissions),
- count: new Set(params.permissions).size,
- outcome: params.outcome,
- authorizationDecision: params.outcome === 'rejected' ? 'deny' : 'allow',
- },
- ],
+ changes: params.subjects.map((subject, index) => ({
+ action: params.action,
+ resourceClass: params.mutation === 'grant' ? 'gfs_folder_grant' : 'gfs_share',
+ resourceRef: `gfs://${params.drive}/${params.resourceId}`,
+ subject: permissionEventSubject(subject),
+ sourceAuditRef: params.auditIds[index] ? `gfs_audit:${params.auditIds[index]}` : null,
+ status:
+ params.outcome === 'rejected'
+ ? `${params.mutation}_${params.action}_rejected`
+ : `${params.mutation}_${params.action === 'grant' ? 'configured' : 'revoked'}`,
+ detailRef: permissionsDetailRef(params.permissions),
+ count: new Set(params.permissions).size,
+ outcome: params.outcome,
+ authorizationDecision: params.outcome === 'rejected' ? 'deny' : 'allow',
+ })),
})
}
+export async function writeGfsGrantBatchInTransaction(
+ db: DbClient,
+ params: {
+ req: Request
+ caller: GfsCaller
+ drive: string
+ resourceId: string
+ subjects: readonly GfsSubject[]
+ permissions: readonly GfsPermission[]
+ inherit: boolean
+ }
+): Promise<{ error: GfsGrantError | null }> {
+ const auditIds: Array<string | null> = []
+ let outcome: 'allowed' | 'denied' = 'allowed'
+ let policyError: GfsGrantError | null = null
+ try {
+ await assertMayGrantBatch(
+ db,
+ params.caller,
+ params.drive,
+ params.resourceId,
+ params.permissions,
+ params.subjects,
+ { isShare: false }
+ )
+ } catch (error) {
+ if (!(error instanceof GfsGrantError)) throw error
+ outcome = 'denied'
+ policyError = error
+ }
+
+ if (!policyError) {
+ const types = params.subjects.map(subject => subject.type)
+ const ids = params.subjects.map(subject => subject.id ?? '')
+ await db.query(
+ `INSERT INTO gfs_grants
+ (drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by)
+ SELECT $1, $2::uuid, input.subject_type, input.subject_id, $5::text[], $6, $7
+ FROM unnest($3::text[], $4::text[]) AS input(subject_type, subject_id)
+ ON CONFLICT (drive, resource_id, subject_type, subject_id)
+ DO UPDATE SET permissions = EXCLUDED.permissions, inherit = EXCLUDED.inherit,
+ granted_by = EXCLUDED.granted_by, updated_at = now()`,
+ [
+ params.drive,
+ params.resourceId,
+ types,
+ ids,
+ params.permissions,
+ params.inherit,
+ params.caller.actorKey,
+ ]
+ )
+ }
+
+ for (const subject of params.subjects) {
+ auditIds.push(
+ await auditMutation(db, {
+ actorKey: params.caller.actorKey,
+ targetKey: subjectKey(subject),
+ op: `grant.put[${params.permissions.join(',')}]`,
+ drive: params.drive,
+ resourceId: params.resourceId,
+ outcome,
+ requestId: requestIdOf(params.req),
+ sourceIp: params.req.ip,
+ })
+ )
+ }
+ await appendGfsPermissionEvents(db, {
+ req: params.req,
+ caller: params.caller,
+ subjects: params.subjects,
+ permissions: params.permissions,
+ drive: params.drive,
+ resourceId: params.resourceId,
+ mutation: 'grant',
+ action: 'grant',
+ outcome: policyError ? 'rejected' : 'committed',
+ auditIds,
+ })
+ return { error: policyError }
+}
+
export function registerGfsGrantRoutes(router: Router): void {
// Operator (Control UI) seeds Layer-1/2 folder grants. The no-escalation
// engine (assertMayGrant) is caller-agnostic; the Profile/Desktop folder-owner
// delegation surface (external user session) wires onto it when that UI lands.
+ router.get('/gfs/grants', requireAuthForControlUI, asyncHandler(handleGrantRead))
router.put('/gfs/grants', requireAuthForControlUI, asyncHandler(handleGrantWrite))
router.delete('/gfs/grants/:id', requireAuthForControlUI, asyncHandler(handleGrantDelete))
}
+export async function handleGrantRead(
+ req: Request,
+ res: import('express').Response
+): Promise<void> {
+ try {
+ const { drive, resourceId } = permissionReadFilter(req)
+ const result = await pool.query(
+ `SELECT id, drive, resource_id, subject_type, subject_id, permissions, inherit
+ FROM gfs_grants
+ WHERE drive = $1 AND resource_id = $2::uuid
+ ORDER BY created_at ASC, id ASC`,
+ [drive, resourceId]
+ )
+ res.status(200).json({
+ items: (result.rows as Record<string, unknown>[]).map(row => {
+ const subjectId = String(row.subject_id ?? '')
+ return {
+ id: String(row.id),
+ drive: String(row.drive),
+ resourceId: String(row.resource_id),
+ subject: {
+ type: String(row.subject_type),
+ ...(subjectId ? { id: subjectId } : {}),
+ },
+ permissions: Array.isArray(row.permissions) ? row.permissions.map(String) : [],
+ inherit: Boolean(row.inherit),
+ }
+ }),
+ })
+ } catch (err) {
+ if (err instanceof GfsGrantError) {
+ sendGfsGrantError(res, err)
+ return
+ }
+ throw err
+ }
+}
+
export async function handleGrantWrite(
req: Request,
res: import('express').Response
@@ -522,85 +847,32 @@ export async function handleGrantWrite(
const body = (req.body ?? {}) as Record<string, unknown>
const drive = driveOf(body.drive)
const resourceId = String(body.resourceId ?? '')
+ assertMutationSubjectTransport(body)
if (!UUID_RE.test(resourceId)) {
- res.status(400).json({ error: 'resource_invalid' })
- return
+ throw new GfsGrantError(400, 'resource_invalid')
}
- const subject = parseSubject(body.subject)
+ const subjects = normalizeMutationSubjects(body, { isShare: false })
const permissions = parsePermissions(body.permissions)
const inherit = Boolean(body.inherit)
- const result = await withTransaction(async db => {
- try {
- await assertMayGrant(db, caller, drive, resourceId, permissions, subject, {
- isShare: false,
- })
- } catch (error) {
- if (!(error instanceof GfsGrantError)) throw error
- const auditId = await auditMutation(db, {
- actorKey: caller.actorKey,
- targetKey: subjectKey(subject),
- op: `grant.put[${permissions.join(',')}]`,
- drive,
- resourceId,
- outcome: 'denied',
- requestId: requestIdOf(req),
- sourceIp: req.ip,
- })
- await appendGfsPermissionEvent(db, {
- req,
- caller,
- subject,
- permissions,
- drive,
- resourceId,
- mutation: 'grant',
- action: 'grant',
- outcome: 'rejected',
- auditId,
- })
- return { error }
- }
-
- await db.query(
- `INSERT INTO gfs_grants (drive, resource_id, subject_type, subject_id, permissions, inherit, granted_by)
- VALUES ($1, $2::uuid, $3, $4, $5, $6, $7)
- ON CONFLICT (drive, resource_id, subject_type, subject_id)
- DO UPDATE SET permissions = EXCLUDED.permissions, inherit = EXCLUDED.inherit,
- granted_by = EXCLUDED.granted_by, updated_at = now()`,
- [drive, resourceId, subject.type, subject.id ?? '', permissions, inherit, caller.actorKey]
- )
- const auditId = await auditMutation(db, {
- actorKey: caller.actorKey,
- targetKey: subjectKey(subject),
- op: `grant.put[${permissions.join(',')}]`,
- drive,
- resourceId,
- outcome: 'allowed',
- requestId: requestIdOf(req),
- sourceIp: req.ip,
- })
- await appendGfsPermissionEvent(db, {
+ const result = await withTransaction(db =>
+ writeGfsGrantBatchInTransaction(db, {
req,
caller,
- subject,
- permissions,
drive,
resourceId,
- mutation: 'grant',
- action: 'grant',
- outcome: 'committed',
- auditId,
+ subjects,
+ permissions,
+ inherit,
})
- return { error: null }
- })
+ )
if (result.error) {
- res.status(result.error.status).json({ error: result.error.code })
+ sendGfsGrantError(res, result.error)
return
}
- res.status(200).json({ ok: true })
+ res.status(200).json({ ok: true, resourceId, updated: subjects, count: subjects.length })
} catch (err) {
if (err instanceof GfsGrantError) {
- res.status(err.status).json({ error: err.code })
+ sendGfsGrantError(res, err)
return
}
throw err
diff --git a/control-api/src/routes/gfs/shares.ts b/control-api/src/routes/gfs/shares.ts
index 4eb9f76d8..905708f38 100644
--- a/control-api/src/routes/gfs/shares.ts
+++ b/control-api/src/routes/gfs/shares.ts
@@ -1,20 +1,26 @@
import type { Request, Response, Router } from 'express'
-import { withTransaction } from '../../db.js'
+import { pool, withTransaction } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { requireAuthForControlUI } from '../../middleware/controlUIAuth.js'
import {
GfsGrantError,
type GfsPermission,
+ type GfsSubject,
type GfsSubjectType,
UUID_RE,
appendGfsPermissionEvent,
+ appendGfsPermissionEvents,
assertMayGrant,
+ assertMayGrantBatch,
+ assertMutationSubjectTransport,
auditMutation,
driveOf,
+ normalizeMutationSubjects,
parsePermissions,
- parseSubject,
+ permissionReadFilter,
requestIdOf,
resolveCaller,
+ sendGfsGrantError,
subjectKey,
} from './grants.js'
@@ -28,105 +34,163 @@ import {
*/
export function registerGfsShareRoutes(router: Router): void {
+ router.get('/gfs/shares', requireAuthForControlUI, asyncHandler(handleShareRead))
router.post('/gfs/shares', requireAuthForControlUI, asyncHandler(handleShareWrite))
router.delete('/gfs/shares/:id', requireAuthForControlUI, asyncHandler(handleShareDelete))
}
+export async function handleShareRead(req: Request, res: Response): Promise<void> {
+ try {
+ const { drive, resourceId } = permissionReadFilter(req)
+ const result = await pool.query(
+ `SELECT id, drive, resource_id, subject_type, subject_id, permissions, include_descendants
+ FROM gfs_shares
+ WHERE drive = $1 AND resource_id = $2::uuid
+ ORDER BY created_at ASC, id ASC`,
+ [drive, resourceId]
+ )
+ res.status(200).json({
+ items: (result.rows as Record<string, unknown>[]).map(row => {
+ const subjectId = String(row.subject_id ?? '')
+ return {
+ id: String(row.id),
+ drive: String(row.drive),
+ resourceId: String(row.resource_id),
+ subject: {
+ type: String(row.subject_type),
+ ...(subjectId ? { id: subjectId } : {}),
+ },
+ permissions: Array.isArray(row.permissions) ? row.permissions.map(String) : [],
+ includeDescendants: Boolean(row.include_descendants),
+ }
+ }),
+ })
+ } catch (err) {
+ if (err instanceof GfsGrantError) {
+ sendGfsGrantError(res, err)
+ return
+ }
+ throw err
+ }
+}
+
+export async function writeGfsShareBatchInTransaction(
+ db: import('../../db.js').DbClient,
+ params: {
+ req: Request
+ caller: ReturnType<typeof resolveCaller>
+ drive: string
+ resourceId: string
+ subjects: readonly GfsSubject[]
+ permissions: readonly GfsPermission[]
+ includeDescendants: boolean
+ }
+): Promise<{ error: GfsGrantError | null }> {
+ const auditIds: Array<string | null> = []
+ let outcome: 'allowed' | 'denied' = 'allowed'
+ let policyError: GfsGrantError | null = null
+ try {
+ await assertMayGrantBatch(
+ db,
+ params.caller,
+ params.drive,
+ params.resourceId,
+ params.permissions,
+ params.subjects,
+ { isShare: true }
+ )
+ } catch (error) {
+ if (!(error instanceof GfsGrantError)) throw error
+ outcome = 'denied'
+ policyError = error
+ }
+
+ if (!policyError) {
+ const types = params.subjects.map(subject => subject.type)
+ const ids = params.subjects.map(subject => subject.id ?? '')
+ await db.query(
+ `INSERT INTO gfs_shares
+ (drive, resource_id, subject_type, subject_id, permissions, include_descendants, created_by)
+ SELECT $1, $2::uuid, input.subject_type, input.subject_id, $5::text[], $6, $7
+ FROM unnest($3::text[], $4::text[]) AS input(subject_type, subject_id)
+ ON CONFLICT (drive, resource_id, subject_type, subject_id)
+ DO UPDATE SET permissions = EXCLUDED.permissions,
+ include_descendants = EXCLUDED.include_descendants,
+ created_by = EXCLUDED.created_by`,
+ [
+ params.drive,
+ params.resourceId,
+ types,
+ ids,
+ params.permissions,
+ params.includeDescendants,
+ params.caller.actorKey,
+ ]
+ )
+ }
+
+ for (const subject of params.subjects) {
+ auditIds.push(
+ await auditMutation(db, {
+ actorKey: params.caller.actorKey,
+ targetKey: subjectKey(subject),
+ op: `share.create[${params.permissions.join(',')}]`,
+ drive: params.drive,
+ resourceId: params.resourceId,
+ outcome,
+ requestId: requestIdOf(params.req),
+ sourceIp: params.req.ip,
+ })
+ )
+ }
+ await appendGfsPermissionEvents(db, {
+ req: params.req,
+ caller: params.caller,
+ subjects: params.subjects,
+ permissions: params.permissions,
+ drive: params.drive,
+ resourceId: params.resourceId,
+ mutation: 'share',
+ action: 'grant',
+ outcome: policyError ? 'rejected' : 'committed',
+ auditIds,
+ })
+ return { error: policyError }
+}
+
export async function handleShareWrite(req: Request, res: Response): Promise<void> {
try {
const caller = resolveCaller(req)
const body = (req.body ?? {}) as Record<string, unknown>
const drive = driveOf(body.drive)
const resourceId = String(body.resourceId ?? '')
+ assertMutationSubjectTransport(body)
if (!UUID_RE.test(resourceId)) {
- res.status(400).json({ error: 'resource_invalid' })
- return
+ throw new GfsGrantError(400, 'resource_invalid')
}
- const subject = parseSubject(body.subject)
+ const subjects = normalizeMutationSubjects(body, { isShare: true })
const permissions = parsePermissions(body.permissions)
const includeDescendants = Boolean(body.includeDescendants)
- const result = await withTransaction(async db => {
- try {
- await assertMayGrant(db, caller, drive, resourceId, permissions, subject, {
- isShare: true,
- })
- } catch (error) {
- if (!(error instanceof GfsGrantError)) throw error
- const auditId = await auditMutation(db, {
- actorKey: caller.actorKey,
- targetKey: subjectKey(subject),
- op: `share.create[${permissions.join(',')}]`,
- drive,
- resourceId,
- outcome: 'denied',
- requestId: requestIdOf(req),
- sourceIp: req.ip,
- })
- await appendGfsPermissionEvent(db, {
- req,
- caller,
- subject,
- permissions,
- drive,
- resourceId,
- mutation: 'share',
- action: 'grant',
- outcome: 'rejected',
- auditId,
- })
- return { error }
- }
-
- await db.query(
- `INSERT INTO gfs_shares (drive, resource_id, subject_type, subject_id, permissions, include_descendants, created_by)
- VALUES ($1, $2::uuid, $3, $4, $5, $6, $7)
- ON CONFLICT (drive, resource_id, subject_type, subject_id)
- DO UPDATE SET permissions = EXCLUDED.permissions,
- include_descendants = EXCLUDED.include_descendants,
- created_by = EXCLUDED.created_by`,
- [
- drive,
- resourceId,
- subject.type,
- subject.id ?? '',
- permissions,
- includeDescendants,
- caller.actorKey,
- ]
- )
- const auditId = await auditMutation(db, {
- actorKey: caller.actorKey,
- targetKey: subjectKey(subject),
- op: `share.create[${permissions.join(',')}]`,
- drive,
- resourceId,
- outcome: 'allowed',
- requestId: requestIdOf(req),
- sourceIp: req.ip,
- })
- await appendGfsPermissionEvent(db, {
+ const result = await withTransaction(db =>
+ writeGfsShareBatchInTransaction(db, {
req,
caller,
- subject,
- permissions,
drive,
resourceId,
- mutation: 'share',
- action: 'grant',
- outcome: 'committed',
- auditId,
+ subjects,
+ permissions,
+ includeDescendants,
})
- return { error: null }
- })
+ )
if (result.error) {
- res.status(result.error.status).json({ error: result.error.code })
+ sendGfsGrantError(res, result.error)
return
}
- res.status(200).json({ ok: true })
+ res.status(200).json({ ok: true, resourceId, updated: subjects, count: subjects.length })
} catch (err) {
if (err instanceof GfsGrantError) {
- res.status(err.status).json({ error: err.code })
+ sendGfsGrantError(res, err)
return
}
throw err
diff --git a/control-api/src/routes/mcp-host/workflows/read.routes.ts b/control-api/src/routes/mcp-host/workflows/read.routes.ts
index 63dd8e515..06ed81f15 100644
--- a/control-api/src/routes/mcp-host/workflows/read.routes.ts
+++ b/control-api/src/routes/mcp-host/workflows/read.routes.ts
@@ -9,6 +9,7 @@ import {
resolveEffectiveWorkflowTriggerTarget,
} from '../../../services/workflows/effectiveWorkflowTargetsService.js'
import type { RuntimeWorkflowStatusDto } from '../../../services/workflows/types.js'
+import { getConversationScopedWorkflowHealth } from '../../../services/workflows/workflowConversationRunReadService.js'
import {
WORKFLOW_RECIPE_PLURAL,
type WorkflowApprovalTarget,
@@ -31,6 +32,7 @@ import {
getLatestWorkflowRunWithApprovalTarget,
getProviderScopedWorkflowRun,
getWorkflowHealth,
+ mapDbRun,
} from '../../../services/workflows/workflowRunReadService.js'
import {
requireMcpHostControlScope,
@@ -106,6 +108,22 @@ function parseConversationIdQuery(req: Request, res: Response): string | null {
return rawConversationId
}
+function parseOptionalConversationIdQuery(req: Request, res: Response): string | null | undefined {
+ const rawConversationId =
+ typeof req.query.workflowConversationId === 'string'
+ ? req.query.workflowConversationId.trim()
+ : ''
+ if (!rawConversationId) return undefined
+ const isValidTeamsConversationId =
+ rawConversationId.length <= TEAMS_CONVERSATION_ID_MAX_LENGTH &&
+ TEAMS_CONVERSATION_ID_RE.test(rawConversationId)
+ if (!CONVERSATION_ID_RE.test(rawConversationId) && !isValidTeamsConversationId) {
+ res.status(400).json({ error: 'Invalid workflowConversationId format' })
+ return null
+ }
+ return rawConversationId
+}
+
function canIncludeRunSummary(
caller: ReturnType<typeof requireMcpHostControlWorkflowCaller>,
recipeNamespace: string,
@@ -329,16 +347,34 @@ export function createMcpHostWorkflowReadRoutes(gateway: K8sGateway): Router {
}
const { recipeNamespace: ns, recipeName: name } = readableRef
+ const sharedApprovalTarget =
+ isSharedMcpHostControlCaller(caller) && hasApprovalTargetContext(approvalTarget)
+ const conversationId = sharedApprovalTarget
+ ? parseOptionalConversationIdQuery(req, res)
+ : undefined
+ if (conversationId === null) return
+
try {
const resource = (await gateway.getResource(WORKFLOW_RECIPE_PLURAL, name, ns)) as Record<
string,
unknown
>
+ let latestRun = null
+ if (canIncludeRunSummary(caller, ns, name, approvalTarget)) {
+ latestRun = await getLatestRun(ns, name)
+ } else if (sharedApprovalTarget && conversationId) {
+ const scopedHealth = await getConversationScopedWorkflowHealth({
+ caller,
+ recipeNamespace: ns,
+ recipeName: name,
+ approvalTarget,
+ conversationId,
+ })
+ latestRun = scopedHealth.lastRun ? mapDbRun(scopedHealth.lastRun) : null
+ }
const dto: RuntimeWorkflowStatusDto = {
...mapRuntimeWorkflow(resource),
- latestRun: canIncludeRunSummary(caller, ns, name, approvalTarget)
- ? await getLatestRun(ns, name)
- : null,
+ latestRun,
}
res.json(dto)
} catch (err) {
@@ -377,21 +413,43 @@ export function createMcpHostWorkflowReadRoutes(gateway: K8sGateway): Router {
}
const { recipeNamespace: ns, recipeName: name } = readableRef
+ const sharedApprovalTarget =
+ isSharedMcpHostControlCaller(caller) && hasApprovalTargetContext(approvalTarget)
+ const conversationId = sharedApprovalTarget
+ ? parseOptionalConversationIdQuery(req, res)
+ : undefined
+ if (conversationId === null) return
+
try {
const resource = (await gateway.getResource(WORKFLOW_RECIPE_PLURAL, name, ns)) as Record<
string,
unknown
>
const status = asRecord(resource.status) ?? {}
- const { activeRuns, lastRun } = canIncludeRunSummary(caller, ns, name, approvalTarget)
- ? await getWorkflowHealth(ns, name)
- : { activeRuns: null, lastRun: null }
+ let runHealth: { activeRuns: number | null; lastRun: ReturnType<typeof mapDbRun> | null }
+ if (canIncludeRunSummary(caller, ns, name, approvalTarget)) {
+ runHealth = await getWorkflowHealth(ns, name)
+ } else if (sharedApprovalTarget && conversationId) {
+ const scopedHealth = await getConversationScopedWorkflowHealth({
+ caller,
+ recipeNamespace: ns,
+ recipeName: name,
+ approvalTarget,
+ conversationId,
+ })
+ runHealth = {
+ activeRuns: scopedHealth.activeRuns,
+ lastRun: scopedHealth.lastRun ? mapDbRun(scopedHealth.lastRun) : null,
+ }
+ } else {
+ runHealth = { activeRuns: null, lastRun: null }
+ }
res.json({
recipe: `${ns}/${name}`,
phase: status.phase ?? 'Unknown',
workflowPhase: asRecord(status.workflowExecution)?.phase ?? null,
- activeRuns,
- lastRun,
+ activeRuns: runHealth.activeRuns,
+ lastRun: runHealth.lastRun,
})
} catch (err) {
if (err instanceof K8sNotFoundError) {
diff --git a/control-api/src/services/userApprovalRequestService.ts b/control-api/src/services/userApprovalRequestService.ts
index 0dd740dbb..3bd421eae 100644
--- a/control-api/src/services/userApprovalRequestService.ts
+++ b/control-api/src/services/userApprovalRequestService.ts
@@ -17,6 +17,7 @@ import {
import { ApprovalPromptHistoryService } from './tracing/approvalPromptHistoryService.js'
import { enqueueWorkflowApprovalTraceProjection } from './tracing/workflowApprovalTraceProjector.js'
import type { WorkflowRunActorType, WorkflowRunRow } from './workflowRunService.js'
+import type { TriggerAllowedActor } from './workflows/types.js'
import {
type WorkflowTriggerGrantResult,
resolveWorkflowTriggerGrant,
@@ -1270,15 +1271,18 @@ export async function assertApprovalTriggerBinding(params: {
recipeNamespace: string
recipeName: string
callerKey: string
-}): Promise<void> {
+}): Promise<{ requestedActor: TriggerAllowedActor }> {
const existing = await pool.query(
`SELECT war.status,
wati.trigger_namespace AS "triggerNamespace",
wati.trigger_name AS "triggerName",
- wati.trigger_caller_key AS "triggerCaller"
+ wati.trigger_caller_key AS "triggerCaller",
+ watri.actor_type AS "actorType"
FROM workflow_approval_requests war
LEFT JOIN workflow_approval_trigger_intents wati
ON wati.approval_request_id = war.id
+ LEFT JOIN workflow_approval_trigger_run_intents watri
+ ON watri.approval_request_id = war.id
WHERE war.id = $1
LIMIT 1`,
[params.approvalRequestId]
@@ -1296,6 +1300,7 @@ export async function assertApprovalTriggerBinding(params: {
triggerNamespace?: string | null
triggerName?: string | null
triggerCaller?: string | null
+ actorType?: WorkflowRunActorType | null
}
if (
@@ -1311,6 +1316,17 @@ export async function assertApprovalTriggerBinding(params: {
row.status
)
}
+
+ switch (row.actorType ?? null) {
+ case 'user':
+ case 'admin':
+ return { requestedActor: 'user' }
+ case 'scheduled':
+ return { requestedActor: 'scheduled' }
+ case 'autonomous':
+ case null:
+ return { requestedActor: 'autonomous' }
+ }
}
export async function expirePendingRequests(): Promise<number> {
diff --git a/control-api/src/services/workflows/workflowConversationRunReadService.ts b/control-api/src/services/workflows/workflowConversationRunReadService.ts
new file mode 100644
index 000000000..600d03c79
--- /dev/null
+++ b/control-api/src/services/workflows/workflowConversationRunReadService.ts
@@ -0,0 +1,67 @@
+import { type DbClient, pool } from '../../db.js'
+import { getMcpHostCallerKey } from '../../utils/auth/mcpHostJwtToken.js'
+import type { WorkflowRunRow } from '../workflowRunService.js'
+import type { WorkflowRouteCaller } from './types.js'
+import type { WorkflowApprovalTarget } from './workflowRecipeAccessService.js'
+
+export type ConversationScopedWorkflowHealth = {
+ activeRuns: number
+ lastRun: WorkflowRunRow | null
+}
+
+/**
+ * Reads run health through the same approval target, trigger caller, and
+ * conversation boundary used by authenticated workflow artifact reads.
+ */
+export async function getConversationScopedWorkflowHealth(params: {
+ caller: Extract<WorkflowRouteCaller, { kind: 'mcp-host-control' }>
+ recipeNamespace: string
+ recipeName: string
+ approvalTarget: WorkflowApprovalTarget
+ conversationId: string
+ db?: DbClient
+}): Promise<ConversationScopedWorkflowHealth> {
+ const { caller, recipeNamespace, recipeName, approvalTarget, conversationId, db = pool } = params
+ const callerKey = getMcpHostCallerKey(caller.claims)
+ const result = await db.query(
+ `WITH scoped_runs AS (
+ SELECT wr.*
+ FROM workflow_runs wr
+ JOIN workflow_approval_requests war
+ ON war.id = wr.approval_request_id
+ JOIN workflow_approval_trigger_intents wati
+ ON wati.approval_request_id = war.id
+ WHERE (
+ (wr.recipe_namespace = $1 AND wr.recipe_name = $2)
+ OR (wr.child_recipe_namespace = $1 AND wr.child_recipe_name = $2)
+ )
+ AND (
+ ($3::uuid IS NOT NULL AND war.target_user_id = $3::uuid)
+ OR ($4::uuid IS NOT NULL AND war.target_team_id = $4::uuid)
+ )
+ AND wati.trigger_namespace = wr.recipe_namespace
+ AND wati.trigger_name = wr.recipe_name
+ AND wati.trigger_caller_key = $5
+ AND war.payload->'metadata'->'workflowTrigger'->>'conversationId' = $6
+ )
+ SELECT scoped_runs.*,
+ (COUNT(*) FILTER (
+ WHERE scoped_runs.phase IN ('Pending', 'Running')
+ ) OVER ())::int AS "activeRuns"
+ FROM scoped_runs
+ ORDER BY scoped_runs.created_at DESC,
+ scoped_runs.started_at DESC NULLS LAST
+ LIMIT 1`,
+ [
+ recipeNamespace,
+ recipeName,
+ approvalTarget.targetUserId ?? null,
+ approvalTarget.targetTeamId ?? null,
+ callerKey,
+ conversationId,
+ ]
+ )
+
+ const row = result.rows[0] as (WorkflowRunRow & { activeRuns: number }) | undefined
+ return row ? { activeRuns: row.activeRuns, lastRun: row } : { activeRuns: 0, lastRun: null }
+}
diff --git a/control-api/src/services/workflows/workflowTriggerService.ts b/control-api/src/services/workflows/workflowTriggerService.ts
index c27c2642e..6b364beef 100644
--- a/control-api/src/services/workflows/workflowTriggerService.ts
+++ b/control-api/src/services/workflows/workflowTriggerService.ts
@@ -111,6 +111,7 @@ type WorkflowTriggerResult =
type McpHostApprovalTriggerContext = {
approvalRequestId: string
callerKey: string
+ requestedActor: TriggerAllowedActor
}
type WorkflowTriggerRecipeValidation = {
@@ -236,12 +237,13 @@ export async function triggerWorkflow(params: {
})
}
try {
- await assertApprovalTriggerBinding({
+ const approvalBinding = await assertApprovalTriggerBinding({
approvalRequestId,
recipeNamespace: ns,
recipeName: name,
callerKey,
})
+ mcpHostApprovalContext = { approvalRequestId, callerKey, ...approvalBinding }
} catch (err) {
if (err instanceof ApprovalConsumeError) {
throw new WorkflowTriggerHttpError(
@@ -251,7 +253,6 @@ export async function triggerWorkflow(params: {
}
throw err
}
- mcpHostApprovalContext = { approvalRequestId, callerKey }
}
let userSessionGrant: WorkflowTriggerGrantResult | null = null
@@ -288,7 +289,7 @@ export async function triggerWorkflow(params: {
? 'admin'
: 'user'
const triggerSource = caller.kind === 'mcp-host-control' ? 'autonomous' : 'onDemand'
- const requestedActor = getTriggerActorForCaller(caller)
+ const requestedActor = mcpHostApprovalContext?.requestedActor ?? getTriggerActorForCaller(caller)
const triggerRecipe = await validateWorkflowTriggerRecipeForActor({
gateway,
recipeNamespace: ns,
diff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.ts
index 9d03ed213..15115ce21 100644
--- a/control-api/test/db.realPostgresMigration.integration.test.ts
+++ b/control-api/test/db.realPostgresMigration.integration.test.ts
@@ -1,11 +1,16 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import express from 'express'
+import express, { type Request as ExpressRequest } from 'express'
import { randomBytes, randomUUID } from 'node:crypto'
import { Pool, type PoolClient } from 'pg'
import request from 'supertest'
import { config } from '../src/config.js'
import type { K8sGateway } from '../src/k8s.js'
-import { auditMutation } from '../src/routes/gfs/grants.js'
+import {
+ type GfsSubject,
+ auditMutation,
+ writeGfsGrantBatchInTransaction,
+} from '../src/routes/gfs/grants.js'
+import { writeGfsShareBatchInTransaction } from '../src/routes/gfs/shares.js'
import { createRpcAccessUsersRouter } from '../src/routes/rpc-access/users.js'
import { getCurrentTeam, getTeamAgents, getUserAgents } from '../src/services/directory/index.js'
import { runWithAdministrativeRequestContext } from '../src/services/tracing/adminOperationContext.js'
@@ -1512,6 +1517,242 @@ describeRealPostgres('control-api real Postgres migrations', () => {
expect(stored.rows).toEqual([{ sequence_no: auditId, subject: 'host:1st:mcp-host/chatllm' }])
})
+ it('commits GFS grant/share batches atomically and invalidates only after commit', async () => {
+ const operator = await dbPool.query<{ id: string }>(
+ `SELECT id::text FROM control_admin_users
+ WHERE status = 'active' ORDER BY created_at, id LIMIT 1`
+ )
+ const operatorId = operator.rows[0]!.id
+ const shareUserId = randomUUID()
+ const shareTeamId = randomUUID()
+ await dbPool.query(
+ `INSERT INTO users (id, email, name) VALUES ($1, $2, 'Issue 792 Share User')`,
+ [shareUserId, `issue792-share-${shareUserId}@example.test`]
+ )
+ await dbPool.query(`INSERT INTO teams (id, name) VALUES ($1, 'Issue 792 Share Team')`, [
+ shareTeamId,
+ ])
+ const listener = await dbPool.connect()
+ const notifications: string[] = []
+ listener.on('notification', message => {
+ if (message.channel === 'gfs_perm_invalidate') notifications.push(message.channel)
+ })
+ await listener.query('LISTEN gfs_perm_invalidate')
+
+ type BatchCase = {
+ kind: 'grant' | 'share'
+ table: 'gfs_grants' | 'gfs_shares'
+ targets: readonly GfsSubject[]
+ write: (
+ client: PoolClient,
+ params: { req: ExpressRequest; drive: string; resourceId: string }
+ ) => Promise<{ error: unknown }>
+ }
+ const caller = {
+ isOperator: true,
+ subjects: new Set(['operator:']),
+ actorKey: 'operator:',
+ }
+ const cases: BatchCase[] = [
+ {
+ kind: 'grant',
+ table: 'gfs_grants',
+ targets: Array.from({ length: 3 }, () => ({
+ type: 'host' as const,
+ id: `1st:mcp-host/bulk-${randomUUID()}`,
+ })),
+ write: (client, params) =>
+ writeGfsGrantBatchInTransaction(client, {
+ ...params,
+ caller,
+ subjects: cases[0]!.targets,
+ permissions: ['read'],
+ inherit: false,
+ }),
+ },
+ {
+ kind: 'share',
+ table: 'gfs_shares',
+ targets: [
+ { type: 'user', id: shareUserId },
+ { type: 'team', id: shareTeamId },
+ ],
+ write: (client, params) =>
+ writeGfsShareBatchInTransaction(client, {
+ ...params,
+ caller,
+ subjects: cases[1]!.targets,
+ permissions: ['read'],
+ includeDescendants: true,
+ }),
+ },
+ ]
+ const createResource = async (drive: string): Promise<string> => {
+ const resourceId = randomUUID()
+ await dbPool.query(
+ `INSERT INTO gfs_resources (resource_id, drive, name, kind, path_cache)
+ VALUES ($1, $2, '/', 'directory', '/')`,
+ [resourceId, drive]
+ )
+ return resourceId
+ }
+ const runBatch = async (
+ batchCase: BatchCase,
+ resourceId: string,
+ drive: string,
+ requestId: string,
+ beforeCommit?: (client: PoolClient) => Promise<void>
+ ): Promise<void> => {
+ const client = await dbPool.connect()
+ try {
+ await client.query('BEGIN')
+ const req = {
+ adminAuth: { sub: operatorId },
+ correlationId: requestId,
+ ip: '127.0.0.1',
+ } as unknown as ExpressRequest
+ const result = await batchCase.write(client, {
+ req,
+ drive,
+ resourceId,
+ })
+ expect(result.error).toBeNull()
+ await beforeCommit?.(client)
+ await client.query('COMMIT')
+ } catch (error) {
+ await client.query('ROLLBACK')
+ throw error
+ } finally {
+ client.release()
+ }
+ }
+ const counts = async (
+ batchCase: BatchCase,
+ resourceId: string,
+ requestId: string
+ ): Promise<{ mutations: string; audits: string; events: string }> => {
+ const result = await dbPool.query<{ mutations: string; audits: string; events: string }>(
+ `SELECT
+ (SELECT COUNT(*)::text FROM ${batchCase.table}
+ WHERE resource_id = $1::uuid) AS mutations,
+ (SELECT COUNT(*)::text FROM gfs_audit WHERE request_id = $2) AS audits,
+ (SELECT COUNT(*)::text FROM administrative_events WHERE request_id = $2) AS events`,
+ [resourceId, requestId]
+ )
+ return result.rows[0]!
+ }
+ const settleListener = async (): Promise<void> => {
+ await listener.query('SELECT 1')
+ await new Promise<void>(resolve => setImmediate(resolve))
+ }
+ const waitForInvalidationCount = async (count: number): Promise<void> => {
+ if (notifications.length >= count) return
+ await new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ listener.off('notification', onNotification)
+ reject(new Error('timed out waiting for GFS invalidation'))
+ }, 2_000)
+ const onNotification = (): void => {
+ if (notifications.length < count) return
+ clearTimeout(timeout)
+ listener.off('notification', onNotification)
+ resolve()
+ }
+ listener.on('notification', onNotification)
+ })
+ }
+
+ try {
+ let committedNotificationCount = 0
+ for (const batchCase of cases) {
+ const targetCount = String(batchCase.targets.length)
+ const committedDrive = `issue792-${batchCase.kind}-commit-${randomUUID()}`
+ const committedResourceId = await createResource(committedDrive)
+ const committedRequestId = `issue792-${batchCase.kind}-commit-${randomUUID()}`
+ await runBatch(
+ batchCase,
+ committedResourceId,
+ committedDrive,
+ committedRequestId,
+ async client => {
+ const inside = await client.query<{
+ mutations: string
+ audits: string
+ events: string
+ }>(
+ `SELECT
+ (SELECT COUNT(*)::text FROM ${batchCase.table}
+ WHERE resource_id = $1::uuid) AS mutations,
+ (SELECT COUNT(*)::text FROM gfs_audit WHERE request_id = $2) AS audits,
+ (SELECT COUNT(*)::text FROM administrative_events
+ WHERE request_id = $2) AS events`,
+ [committedResourceId, committedRequestId]
+ )
+ expect(inside.rows[0]).toEqual({
+ mutations: targetCount,
+ audits: targetCount,
+ events: targetCount,
+ })
+ expect(notifications).toHaveLength(committedNotificationCount)
+ }
+ )
+ committedNotificationCount += 1
+ await waitForInvalidationCount(committedNotificationCount)
+ expect(await counts(batchCase, committedResourceId, committedRequestId)).toEqual({
+ mutations: targetCount,
+ audits: targetCount,
+ events: targetCount,
+ })
+ expect(notifications).toHaveLength(committedNotificationCount)
+
+ for (const failure of [
+ { stage: 'audit', table: 'gfs_audit' },
+ { stage: 'event', table: 'administrative_events' },
+ ] as const) {
+ const requestId = `issue792-${batchCase.kind}-${failure.stage}-failure-${randomUUID()}`
+ const functionName = `issue792_fail_${batchCase.kind}_${failure.stage}`
+ const triggerName = `${functionName}_trigger`
+ await dbPool.query(
+ `CREATE OR REPLACE FUNCTION ${functionName}() RETURNS trigger
+ LANGUAGE plpgsql AS $$
+ BEGIN
+ IF NEW.request_id = '${requestId}' THEN
+ RAISE EXCEPTION
+ 'injected issue 792 ${batchCase.kind} ${failure.stage} failure';
+ END IF;
+ RETURN NEW;
+ END;
+ $$;
+ CREATE TRIGGER ${triggerName} BEFORE INSERT ON ${failure.table}
+ FOR EACH ROW EXECUTE FUNCTION ${functionName}();`
+ )
+ const drive = `issue792-${batchCase.kind}-${failure.stage}-${randomUUID()}`
+ const resourceId = await createResource(drive)
+ try {
+ await expect(runBatch(batchCase, resourceId, drive, requestId)).rejects.toThrow(
+ `injected issue 792 ${batchCase.kind} ${failure.stage} failure`
+ )
+ } finally {
+ await dbPool.query(
+ `DROP TRIGGER IF EXISTS ${triggerName} ON ${failure.table};
+ DROP FUNCTION IF EXISTS ${functionName}();`
+ )
+ }
+ await settleListener()
+ expect(await counts(batchCase, resourceId, requestId)).toEqual({
+ mutations: '0',
+ audits: '0',
+ events: '0',
+ })
+ expect(notifications).toHaveLength(committedNotificationCount)
+ }
+ }
+ } finally {
+ await listener.query('UNLISTEN gfs_perm_invalidate')
+ listener.release()
+ }
+ }, 60_000)
+
it('resolves host intent tenant attribution from the canonical event stream', async () => {
const operationId = randomUUID()
const eventId = randomUUID()
diff --git a/control-api/test/delegation.test.ts b/control-api/test/delegation.test.ts
index ffaaf99ed..eb3e466dd 100644
--- a/control-api/test/delegation.test.ts
+++ b/control-api/test/delegation.test.ts
@@ -74,6 +74,21 @@ function mockDb(opts?: { teams?: Record<string, string[]>; grants?: GrantRow[] }
const userId = String(values?.[0] ?? '')
return { rows: (teams[userId] ?? []).map(team_id => ({ team_id })) }
}
+ if (text.includes('authority_grants AS') && text.includes('authority_shares AS')) {
+ const rid = String(values?.[1] ?? '')
+ const subjectTypes = (values?.[2] as string[]) ?? []
+ const subjectIds = (values?.[3] as string[]) ?? []
+ const wanted = new Set(subjectTypes.map((type, i) => `${type}:${subjectIds[i] ?? ''}`))
+ return {
+ rows: [
+ {
+ ancestors: ANCESTORS[rid] ?? [],
+ grants: grants.filter(g => wanted.has(`${g.subject_type}:${g.subject_id ?? ''}`)),
+ shares: [],
+ },
+ ],
+ }
+ }
if (text.includes('WITH RECURSIVE chain')) {
const rid = String(values?.[1] ?? '')
return { rows: (ANCESTORS[rid] ?? []).map(resource_id => ({ resource_id })) }
diff --git a/control-api/test/gfsGrants.test.ts b/control-api/test/gfsGrants.test.ts
index 4b9d4d976..728e658ad 100644
--- a/control-api/test/gfsGrants.test.ts
+++ b/control-api/test/gfsGrants.test.ts
@@ -4,7 +4,9 @@ import {
type GfsPermission,
type GrantsDb,
assertMayGrant,
+ assertMayGrantBatch,
auditMutation,
+ normalizeMutationSubjects,
subjectKey,
} from '../src/routes/gfs/grants.js'
@@ -38,6 +40,10 @@ interface AuditRow {
outcome: string
rowHash: string
}
+interface QueryCall {
+ text: string
+ values?: unknown[]
+}
function mockDb(opts: {
ancestors?: Record<string, string[]>
@@ -45,13 +51,46 @@ function mockDb(opts: {
shares?: MockShare[]
audit?: AuditRow[]
auditSql?: string[]
+ queries?: QueryCall[]
+ rejectConcurrentQueries?: boolean
}): GrantsDb {
+ let queryInFlight = false
return {
async query(text: string, values?: unknown[]) {
+ if (opts.rejectConcurrentQueries && queryInFlight) {
+ throw new Error('concurrent transaction query')
+ }
+ queryInFlight = true
+ await Promise.resolve()
+ opts.queries?.push({ text, values })
+ const complete = <T>(result: T): T => {
+ queryInFlight = false
+ return result
+ }
+ if (text.includes('authority_grants AS') && text.includes('authority_shares AS')) {
+ const rid = String(values?.[1] ?? '')
+ const chain = opts.ancestors?.[rid] ?? []
+ const subjectTypes = (values?.[2] as string[]) ?? []
+ const subjectIds = (values?.[3] as string[]) ?? []
+ const wanted = new Set(subjectTypes.map((type, i) => `${type}:${subjectIds[i] ?? ''}`))
+ return complete({
+ rows: [
+ {
+ ancestors: chain,
+ grants: (opts.grants ?? []).filter(grant =>
+ wanted.has(`${grant.subject_type}:${grant.subject_id ?? ''}`)
+ ),
+ shares: (opts.shares ?? []).filter(share =>
+ wanted.has(`${share.subject_type}:${share.subject_id ?? ''}`)
+ ),
+ },
+ ],
+ })
+ }
if (text.includes('WITH RECURSIVE chain')) {
const rid = String(values?.[1] ?? '')
const chain = opts.ancestors?.[rid] ?? []
- return { rows: chain.map(resource_id => ({ resource_id })) }
+ return complete({ rows: chain.map(resource_id => ({ resource_id })) })
}
if (text.includes('FROM gfs_grants')) {
// Faithfully model the real SQL subject filter on subject_type +
@@ -59,21 +98,21 @@ function mockDb(opts: {
const subjectTypes = (values?.[1] as string[]) ?? []
const subjectIds = (values?.[2] as string[]) ?? []
const wanted = new Set(subjectTypes.map((type, i) => `${type}:${subjectIds[i] ?? ''}`))
- return {
+ return complete({
rows: (opts.grants ?? []).filter(g =>
wanted.has(`${g.subject_type}:${g.subject_id ?? ''}`)
),
- }
+ })
}
if (text.includes('FROM gfs_shares')) {
const subjectTypes = (values?.[1] as string[]) ?? []
const subjectIds = (values?.[2] as string[]) ?? []
const wanted = new Set(subjectTypes.map((type, i) => `${type}:${subjectIds[i] ?? ''}`))
- return {
+ return complete({
rows: (opts.shares ?? []).filter(s =>
wanted.has(`${s.subject_type}:${s.subject_id ?? ''}`)
),
- }
+ })
}
if (text.includes('INSERT INTO gfs_audit')) {
opts.auditSql?.push(text)
@@ -86,9 +125,9 @@ function mockDb(opts: {
outcome: String(v[4]),
rowHash: String(v[7]),
})
- return { rows: [], rowCount: 1 }
+ return complete({ rows: [], rowCount: 1 })
}
- return { rows: [] }
+ return complete({ rows: [] })
},
}
}
@@ -96,6 +135,12 @@ function mockDb(opts: {
const R = '11111111-1111-1111-1111-111111111111'
const PARENT = '22222222-2222-2222-2222-222222222222'
const OTHER = '33333333-3333-3333-3333-333333333333'
+const USER_ID = '44444444-4444-4444-8444-444444444444'
+const TEAM_ID = '55555555-5555-4555-8555-555555555555'
+
+function indexedUuid(index: number): string {
+ return `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`
+}
const operator: GfsCaller = {
isOperator: true,
@@ -108,6 +153,260 @@ function user(id: string): GfsCaller {
const perms = (...p: GfsPermission[]): GfsPermission[] => p
+describe('normalizeMutationSubjects — singular/plural grant transport', () => {
+ it('requires exactly one own property named subject or subjects', () => {
+ for (const body of [
+ {},
+ { subject: { type: 'user', id: USER_ID }, subjects: [] },
+ { subject: undefined, subjects: [{ type: 'user', id: USER_ID }] },
+ ]) {
+ expect(() => normalizeMutationSubjects(body, { isShare: false })).toThrowError(
+ expect.objectContaining({
+ status: 400,
+ code: 'subjects_invalid',
+ })
+ )
+ }
+ })
+
+ it('preserves every currently accepted singular grant subject type', () => {
+ const singularSubjects = [
+ { type: 'operator' },
+ { type: 'user', id: USER_ID },
+ { type: 'team', id: TEAM_ID },
+ { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'context', id: 'sandbox-recipes' },
+ ] as const
+
+ for (const subject of singularSubjects) {
+ expect(normalizeMutationSubjects({ subject }, { isShare: false })).toEqual([subject])
+ }
+ })
+
+ it('accepts the inclusive 1-100 plural bounds', () => {
+ expect(
+ normalizeMutationSubjects(
+ { subjects: [{ type: 'user', id: indexedUuid(1) }] },
+ { isShare: false }
+ )
+ ).toHaveLength(1)
+
+ expect(
+ normalizeMutationSubjects(
+ {
+ subjects: Array.from({ length: 100 }, (_, index) => ({
+ type: 'user',
+ id: indexedUuid(index + 1),
+ })),
+ },
+ { isShare: false }
+ )
+ ).toHaveLength(100)
+ })
+
+ it.each([
+ { label: 'non-array', subjects: 'user' },
+ { label: 'empty', subjects: [] },
+ {
+ label: 'oversized',
+ subjects: Array.from({ length: 101 }, (_, index) => ({
+ type: 'user',
+ id: indexedUuid(index + 1),
+ })),
+ },
+ ])('rejects a $label plural collection', ({ subjects }) => {
+ expect(() => normalizeMutationSubjects({ subjects }, { isShare: false })).toThrowError(
+ expect.objectContaining({ status: 400, code: 'subjects_invalid' })
+ )
+ })
+
+ it('normalizes canonical user, team, first-party host, and third-party host targets in order', () => {
+ const subjects = [
+ { type: 'user', id: USER_ID },
+ { type: 'team', id: TEAM_ID },
+ { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'host', id: '3rd:sandbox-recipes/daily-report' },
+ ]
+
+ expect(normalizeMutationSubjects({ subjects }, { isShare: false })).toEqual(subjects)
+ })
+
+ it('canonicalizes uppercase user and team UUIDs before returning normalized subjects', () => {
+ expect(
+ normalizeMutationSubjects(
+ {
+ subjects: [
+ { type: 'user', id: USER_ID.toUpperCase() },
+ { type: 'team', id: TEAM_ID.toUpperCase() },
+ ],
+ },
+ { isShare: false }
+ )
+ ).toEqual([
+ { type: 'user', id: USER_ID },
+ { type: 'team', id: TEAM_ID },
+ ])
+ })
+
+ it('rejects a later mixed-case UUID duplicate by its stable plural index', () => {
+ expect(() =>
+ normalizeMutationSubjects(
+ {
+ subjects: [
+ { type: 'user', id: USER_ID },
+ { type: 'user', id: USER_ID.toUpperCase() },
+ ],
+ },
+ { isShare: false }
+ )
+ ).toThrowError(
+ expect.objectContaining({
+ status: 400,
+ code: 'subjects_invalid',
+ invalidIndexes: [1],
+ })
+ )
+ })
+
+ it.each([
+ ['user only', [{ type: 'user', id: USER_ID }]],
+ ['team only', [{ type: 'team', id: TEAM_ID }]],
+ ['host only', [{ type: 'host', id: '1st:mcp-host/standalone' }]],
+ [
+ 'user and team',
+ [
+ { type: 'user', id: USER_ID },
+ { type: 'team', id: TEAM_ID },
+ ],
+ ],
+ [
+ 'user and host',
+ [
+ { type: 'user', id: USER_ID },
+ { type: 'host', id: '1st:mcp-host/standalone' },
+ ],
+ ],
+ [
+ 'team and host',
+ [
+ { type: 'team', id: TEAM_ID },
+ { type: 'host', id: '3rd:sandbox-recipes/daily-report' },
+ ],
+ ],
+ ])('accepts the grant matrix for %s', (_label, subjects) => {
+ expect(normalizeMutationSubjects({ subjects }, { isShare: false })).toEqual(subjects)
+ })
+
+ it('rejects malformed, singular-only, and later duplicate plural entries with stable indexes', () => {
+ expect(() =>
+ normalizeMutationSubjects(
+ {
+ subjects: [
+ { type: 'user', id: USER_ID },
+ { type: 'host', id: 'not-canonical' },
+ { type: 'team', id: TEAM_ID },
+ { type: 'user', id: USER_ID },
+ { type: 'context', id: 'sandbox-recipes' },
+ { type: 'operator' },
+ ],
+ },
+ { isShare: false }
+ )
+ ).toThrowError(
+ expect.objectContaining({
+ status: 400,
+ code: 'subjects_invalid',
+ invalidIndexes: [1, 3, 4, 5],
+ })
+ )
+ })
+})
+
+describe('assertMayGrantBatch — common grant authorization', () => {
+ it('loads one authority snapshot statement with the caller subjects in stable order', async () => {
+ const queries: QueryCall[] = []
+ const db = mockDb({
+ queries,
+ rejectConcurrentQueries: true,
+ ancestors: { [R]: [R, PARENT] },
+ grants: [
+ {
+ subject_type: 'user',
+ subject_id: 'owner',
+ resource_id: R,
+ permissions: ['read', 'manage_acl'],
+ inherit: true,
+ },
+ ],
+ shares: [
+ {
+ subject_type: 'team',
+ subject_id: 'owners',
+ resource_id: R,
+ permissions: ['write'],
+ include_descendants: false,
+ },
+ ],
+ })
+ const owner: GfsCaller = {
+ isOperator: false,
+ subjects: new Set(['user:owner', 'team:owners']),
+ actorKey: 'user:owner',
+ }
+ const targets = [
+ { type: 'user', id: USER_ID },
+ { type: 'team', id: TEAM_ID },
+ { type: 'host', id: '1st:mcp-host/standalone' },
+ ] as const
+
+ await expect(
+ assertMayGrantBatch(db, owner, 'main', R, perms('read', 'write'), targets, {
+ isShare: false,
+ })
+ ).resolves.toBeUndefined()
+
+ expect(queries).toHaveLength(1)
+ expect(queries[0]?.text).toContain('WITH RECURSIVE chain AS')
+ expect(queries[0]?.text).toContain('requested_subjects(subject_type, subject_id)')
+ expect(queries[0]?.text).toContain('FROM gfs_grants')
+ expect(queries[0]?.text).toContain('FROM gfs_shares')
+ expect(queries[0]?.values).toEqual(['main', R, ['user', 'team'], ['owner', 'owners']])
+ })
+
+ it('keeps the existing operator host policy intact for bulk API grants', async () => {
+ const db = mockDb({})
+ await expect(
+ assertMayGrantBatch(
+ db,
+ operator,
+ 'main',
+ R,
+ perms('read', 'write', 'delete', 'manage_acl', 'share'),
+ [
+ { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'host', id: '3rd:sandbox-recipes/daily-report' },
+ ],
+ { isShare: false }
+ )
+ ).resolves.toBeUndefined()
+ })
+
+ it('keeps the existing caller-dependent host restriction intact', async () => {
+ const db = mockDb({})
+ await expect(
+ assertMayGrantBatch(
+ db,
+ user('owner'),
+ 'main',
+ R,
+ perms('manage_acl'),
+ [{ type: 'host', id: '1st:mcp-host/standalone' }],
+ { isShare: false }
+ )
+ ).rejects.toMatchObject({ status: 403, code: 'agent_manager_forbidden' })
+ })
+})
+
describe('assertMayGrant — operator intrinsic authority', () => {
it('lets the operator grant any bit without a stored grant', async () => {
const db = mockDb({})
diff --git a/control-api/test/gfsPermissionReadRoutes.test.ts b/control-api/test/gfsPermissionReadRoutes.test.ts
new file mode 100644
index 000000000..2a164b1ff
--- /dev/null
+++ b/control-api/test/gfsPermissionReadRoutes.test.ts
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+
+const mockQuery = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockQuery(...args) },
+ withTransaction: vi.fn(),
+}))
+
+vi.mock('../src/middleware/controlUIAuth.js', () => ({
+ requireAuthForControlUI: (
+ req: express.Request,
+ res: express.Response,
+ next: express.NextFunction
+ ) => {
+ if (req.header('x-test-auth') !== 'operator') {
+ res.status(401).json({ error: 'Unauthorized' })
+ return
+ }
+ next()
+ },
+}))
+
+vi.mock('../src/services/tracing/controlApiPermissionEvents.js', () => ({
+ appendControlApiPermissionEventsInTransaction: vi.fn(),
+}))
+
+const RESOURCE_ID = '11111111-1111-4111-8111-111111111111'
+
+async function buildApp() {
+ const [{ registerGfsGrantRoutes }, { registerGfsShareRoutes }] = await Promise.all([
+ import('../src/routes/gfs/grants.js'),
+ import('../src/routes/gfs/shares.js'),
+ ])
+ const router = express.Router()
+ registerGfsGrantRoutes(router)
+ registerGfsShareRoutes(router)
+ const app = express()
+ app.use(express.json())
+ app.use(router)
+ return app
+}
+
+describe('Control UI GFS permission read routes', () => {
+ beforeEach(() => mockQuery.mockReset())
+
+ it.each(['/gfs/grants', '/gfs/shares'])('requires Control UI auth for GET %s', async path => {
+ const response = await request(await buildApp())
+ .get(path)
+ .query({
+ drive: 'main',
+ resourceId: RESOURCE_ID,
+ })
+
+ expect(response.status).toBe(401)
+ expect(response.body).toEqual({ error: 'Unauthorized' })
+ expect(mockQuery).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['/gfs/grants', {}, 'drive_required'],
+ ['/gfs/shares', { drive: 'main' }, 'resource_invalid'],
+ ['/gfs/grants', { drive: 'main', resourceId: 'not-a-uuid' }, 'resource_invalid'],
+ ])('rejects an incomplete or invalid filter on %s', async (path, query, error) => {
+ const response = await request(await buildApp())
+ .get(path)
+ .set('x-test-auth', 'operator')
+ .query(query)
+
+ expect(response.status).toBe(400)
+ expect(response.body).toMatchObject({ error })
+ expect(mockQuery).not.toHaveBeenCalled()
+ })
+
+ it('lists only grants for the requested drive and resource', async () => {
+ mockQuery.mockResolvedValue({
+ rows: [
+ {
+ id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ drive: 'main',
+ resource_id: RESOURCE_ID,
+ subject_type: 'host',
+ subject_id: '1st:mcp-host/standalone',
+ permissions: ['read', 'write'],
+ inherit: true,
+ },
+ ],
+ })
+
+ const response = await request(await buildApp())
+ .get('/gfs/grants')
+ .set('x-test-auth', 'operator')
+ .query({ drive: 'main', resourceId: RESOURCE_ID })
+
+ expect(response.status).toBe(200)
+ expect(response.body).toEqual({
+ items: [
+ {
+ id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ drive: 'main',
+ resourceId: RESOURCE_ID,
+ subject: { type: 'host', id: '1st:mcp-host/standalone' },
+ permissions: ['read', 'write'],
+ inherit: true,
+ },
+ ],
+ })
+ expect(String(mockQuery.mock.calls[0]?.[0])).toContain(
+ 'WHERE drive = $1 AND resource_id = $2::uuid'
+ )
+ expect(mockQuery.mock.calls[0]?.[1]).toEqual(['main', RESOURCE_ID])
+ })
+
+ it('lists only shares for the requested drive and resource', async () => {
+ mockQuery.mockResolvedValue({
+ rows: [
+ {
+ id: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
+ drive: 'archive',
+ resource_id: RESOURCE_ID,
+ subject_type: 'operator',
+ subject_id: '',
+ permissions: ['read'],
+ include_descendants: false,
+ },
+ ],
+ })
+
+ const response = await request(await buildApp())
+ .get('/gfs/shares')
+ .set('x-test-auth', 'operator')
+ .query({ drive: 'archive', resourceId: RESOURCE_ID })
+
+ expect(response.status).toBe(200)
+ expect(response.body).toEqual({
+ items: [
+ {
+ id: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
+ drive: 'archive',
+ resourceId: RESOURCE_ID,
+ subject: { type: 'operator' },
+ permissions: ['read'],
+ includeDescendants: false,
+ },
+ ],
+ })
+ expect(String(mockQuery.mock.calls[0]?.[0])).toContain(
+ 'WHERE drive = $1 AND resource_id = $2::uuid'
+ )
+ expect(mockQuery.mock.calls[0]?.[1]).toEqual(['archive', RESOURCE_ID])
+ })
+})
diff --git a/control-api/test/registryImagePullSecret.test.ts b/control-api/test/registryImagePullSecret.test.ts
index 66c255fc6..788845a88 100644
--- a/control-api/test/registryImagePullSecret.test.ts
+++ b/control-api/test/registryImagePullSecret.test.ts
@@ -41,7 +41,7 @@ describe('imageRefHost', () => {
})
it('parses a GCP Artifact Registry host', () => {
expect(
- imageRefHost('us-central1-docker.pkg.dev/your-gcp-project/clerum/airtable-mcp:latest')
+ imageRefHost('us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/airtable-mcp:latest')
).toBe('us-central1-docker.pkg.dev')
})
it('parses a host that carries an explicit port', () => {
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index 72921c258..76a8b29fe 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -14,6 +14,7 @@ const mockVerifyExternalSessionToken = vi.fn()
const mockSignGfsToken = vi.hoisted(() => vi.fn())
const mockQuery = vi.hoisted(() => vi.fn())
const mockAppendPermissionEvents = vi.hoisted(() => vi.fn())
+const mockWithTransaction = vi.hoisted(() => vi.fn())
vi.mock('../src/utils/auth/externalSessionAuthToken.js', () => ({
verifyExternalSessionToken: (...a: unknown[]) => mockVerifyExternalSessionToken(...a),
@@ -33,8 +34,7 @@ vi.mock('../src/config.js', () => ({
}))
vi.mock('../src/db.js', () => ({
pool: { query: (...a: unknown[]) => mockQuery(...a) },
- withTransaction: async (work: (db: { query: typeof mockQuery }) => Promise<unknown>) =>
- work({ query: mockQuery }),
+ withTransaction: (...a: unknown[]) => mockWithTransaction(...a),
}))
vi.mock('../src/services/tracing/controlApiPermissionEvents.js', () => ({
appendControlApiPermissionEventsInTransaction: (...a: unknown[]) =>
@@ -53,6 +53,8 @@ const U1 = '11111111-aaaa-4aaa-8aaa-111111111111'
const U2 = '22222222-bbbb-4bbb-8bbb-222222222222'
const T1 = '33333333-cccc-4ccc-8ccc-333333333333'
const T2 = '44444444-dddd-4ddd-8ddd-444444444444'
+const H1 = '1st:mcp-host/standalone'
+const CORRELATION_ID = '55555555-eeee-4eee-8eee-555555555555'
const SESSION = {
userId: U1,
@@ -66,17 +68,40 @@ const R_RID = R.replace(/-/g, '')
async function buildApp() {
const { createExternalGfsRouter } = await import('../src/routes/external/gfs.js')
+ const { correlationIdMiddleware } = await import('../src/middleware/correlationId.js')
const app = express()
app.use(express.json())
+ app.use(correlationIdMiddleware)
app.use(createExternalGfsRouter())
return app
}
+async function buildOperatorShareApp() {
+ const { registerGfsShareRoutes } = await import('../src/routes/gfs/shares.js')
+ const app = express()
+ app.use(express.json())
+ app.use((req, _res, next) => {
+ ;(req as typeof req & { adminAuth: { sub: string } }).adminAuth = {
+ sub: 'operator-share-test',
+ }
+ next()
+ })
+ const router = express.Router()
+ registerGfsShareRoutes(router)
+ app.use(router)
+ return app
+}
+
beforeEach(() => {
mockVerifyExternalSessionToken.mockReset()
mockSignGfsToken.mockReset()
mockQuery.mockReset()
mockAppendPermissionEvents.mockReset()
+ mockWithTransaction.mockReset()
+ mockWithTransaction.mockImplementation(
+ async (work: (db: { query: typeof mockQuery }) => Promise<unknown>) =>
+ work({ query: mockQuery })
+ )
mockAppendPermissionEvents.mockResolvedValue(null)
mockSignGfsToken.mockReturnValue({ token: 'gfs-user-token', expiresInSeconds: 300 })
})
@@ -84,9 +109,32 @@ afterEach(() => vi.unstubAllGlobals())
const auth = () => mockVerifyExternalSessionToken.mockReturnValue(SESSION)
+function combinedAuthorityRow(
+ grants: Record<string, unknown>[],
+ values?: unknown[]
+): { rows: Array<{ ancestors: string[]; grants: Record<string, unknown>[]; shares: never[] }> } {
+ const subjectTypes = (values?.[2] as string[]) ?? []
+ const subjectIds = (values?.[3] as string[]) ?? []
+ const wanted = new Set(subjectTypes.map((type, i) => `${type}:${subjectIds[i] ?? ''}`))
+ return {
+ rows: [
+ {
+ ancestors: [String(values?.[1])],
+ grants: grants.filter(grant =>
+ wanted.has(`${String(grant.subject_type)}:${String(grant.subject_id ?? '')}`)
+ ),
+ shares: [],
+ },
+ ],
+ }
+}
+
/** Route the grant engine's queries by SQL shape. */
function dbReturning(grants: Record<string, unknown>[]) {
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
+ if (text.includes('authority_grants AS') && text.includes('authority_shares AS')) {
+ return combinedAuthorityRow(grants, values)
+ }
if (text.includes('WITH RECURSIVE chain'))
return { rows: [{ resource_id: String(values?.[1]) }] }
if (text.includes('FROM gfs_grants')) {
@@ -201,24 +249,29 @@ describe('PUT /external/gfs/grants (user delegation via existing engine)', () =>
it('honors grants held through any active team, not only the session teamId', async () => {
auth()
+ const teamGrants = [
+ {
+ subject_type: 'team',
+ subject_id: T2,
+ resource_id: R,
+ permissions: ['manage_acl', 'read'],
+ inherit: false,
+ },
+ ]
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
if (text.includes('FROM team_members')) return { rows: [{ team_id: T2 }] }
+ if (text.includes('authority_grants AS') && text.includes('authority_shares AS')) {
+ return combinedAuthorityRow(teamGrants, values)
+ }
if (text.includes('WITH RECURSIVE chain'))
return { rows: [{ resource_id: String(values?.[1]) }] }
if (text.includes('FROM gfs_grants')) {
const subjectTypes = (values?.[1] as string[]) ?? []
const subjectIds = (values?.[2] as string[]) ?? []
const wanted = new Set(subjectTypes.map((type, i) => `${type}:${subjectIds[i] ?? ''}`))
- const rows = [
- {
- subject_type: 'team',
- subject_id: T2,
- resource_id: R,
- permissions: ['manage_acl', 'read'],
- inherit: false,
- },
- ]
- return { rows: rows.filter(row => wanted.has(`${row.subject_type}:${row.subject_id}`)) }
+ return {
+ rows: teamGrants.filter(row => wanted.has(`${row.subject_type}:${row.subject_id}`)),
+ }
}
if (text.includes('FROM gfs_shares')) return { rows: [] }
if (text.includes('INSERT INTO gfs_grants')) return { rows: [] }
@@ -339,6 +392,12 @@ describe('POST /external/gfs/shares (user delegation via existing engine)', () =
})
expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ ok: true,
+ resourceId: R,
+ updated: [{ type: 'user', id: U2 }],
+ count: 1,
+ })
expect(
mockQuery.mock.calls.some(call => String(call[0]).includes('INSERT INTO gfs_shares'))
).toBe(true)
@@ -356,6 +415,449 @@ describe('POST /external/gfs/shares (user delegation via existing engine)', () =
})
)
})
+
+ it.each([
+ ['operator', { type: 'operator' }],
+ ['context', { type: 'context', id: 'run-context' }],
+ ])('preserves singular %s shares for an operator caller', async (_label, subject) => {
+ dbReturning([])
+ const app = await buildOperatorShareApp()
+
+ const res = await request(app)
+ .post('/gfs/shares')
+ .send({
+ resourceId: R,
+ subject,
+ permissions: ['read'],
+ includeDescendants: false,
+ })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({ ok: true, resourceId: R, updated: [subject], count: 1 })
+ const mutations = mockQuery.mock.calls.filter(call =>
+ String(call[0]).includes('INSERT INTO gfs_shares')
+ )
+ expect(mutations).toHaveLength(1)
+ expect(mutations[0]?.[1]?.[2]).toEqual([subject.type])
+ expect(mutations[0]?.[1]?.[3]).toEqual(['id' in subject ? subject.id : ''])
+ })
+
+ it('preserves the singular host share rejection for an operator caller', async () => {
+ dbReturning([])
+ const app = await buildOperatorShareApp()
+
+ const res = await request(app)
+ .post('/gfs/shares')
+ .send({
+ resourceId: R,
+ subject: { type: 'host', id: H1 },
+ permissions: ['read'],
+ includeDescendants: false,
+ })
+
+ expect(res.status).toBe(403)
+ expect(res.body).toEqual({
+ error: 'share_to_agent_forbidden',
+ message: 'share_to_agent_forbidden',
+ })
+ expect(
+ mockQuery.mock.calls.some(call => String(call[0]).includes('INSERT INTO gfs_shares'))
+ ).toBe(false)
+ expect(mockAppendPermissionEvents).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ operatorSub: 'operator-share-test',
+ operatorKind: 'control_admin',
+ changes: [
+ expect.objectContaining({
+ outcome: 'rejected',
+ authorizationDecision: 'deny',
+ subject: { kind: 'service', id: `host:${H1}`, principalKind: 'host' },
+ }),
+ ],
+ })
+ )
+ })
+})
+
+describe('authenticated bulk grant/share transport', () => {
+ const authority = (permissions: string[]) =>
+ dbReturning([
+ {
+ subject_type: 'user',
+ subject_id: U1,
+ resource_id: R,
+ permissions,
+ inherit: false,
+ },
+ ])
+
+ it('keeps singular grant responses compatible with the ordered result envelope', async () => {
+ auth()
+ authority(['manage_acl', 'read'])
+ const app = await buildApp()
+
+ const res = await request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: R,
+ subject: { type: 'user', id: U2 },
+ permissions: ['read'],
+ inherit: false,
+ })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ ok: true,
+ resourceId: R,
+ updated: [{ type: 'user', id: U2 }],
+ count: 1,
+ })
+ })
+
+ it('bulk grants user, team, and canonical host subjects in input order with one mutation', async () => {
+ auth()
+ authority(['manage_acl', 'read'])
+ const app = await buildApp()
+ const subjects = [
+ { type: 'user', id: U2 },
+ { type: 'team', id: T2 },
+ { type: 'host', id: H1 },
+ ]
+
+ const res = await request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .set('x-correlation-id', CORRELATION_ID)
+ .send({ resourceId: R, subjects, permissions: ['read'], inherit: true })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({ ok: true, resourceId: R, updated: subjects, count: 3 })
+ const mutations = mockQuery.mock.calls.filter(call =>
+ String(call[0]).includes('INSERT INTO gfs_grants')
+ )
+ expect(mutations).toHaveLength(1)
+
+ const audits = mockQuery.mock.calls.filter(call =>
+ String(call[0]).includes('INSERT INTO gfs_audit')
+ )
+ expect(audits.map(call => call[1]?.[0])).toEqual([`user:${U2}`, `team:${T2}`, `host:${H1}`])
+ expect(audits.map(call => call[1]?.[6])).toEqual([
+ CORRELATION_ID,
+ CORRELATION_ID,
+ CORRELATION_ID,
+ ])
+ expect(mockAppendPermissionEvents).toHaveBeenCalledTimes(1)
+ expect(mockAppendPermissionEvents).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ requestId: CORRELATION_ID,
+ changes: [
+ expect.objectContaining({ subject: { kind: 'user', id: U2 }, outcome: 'committed' }),
+ expect.objectContaining({ subject: { kind: 'team', id: T2 }, outcome: 'committed' }),
+ expect.objectContaining({
+ subject: { kind: 'service', id: `host:${H1}`, principalKind: 'host' },
+ outcome: 'committed',
+ }),
+ ],
+ })
+ )
+ })
+
+ it('bulk shares user and team subjects in input order with one mutation', async () => {
+ auth()
+ authority(['share', 'read'])
+ const app = await buildApp()
+ const subjects = [
+ { type: 'team', id: T2 },
+ { type: 'user', id: U2 },
+ ]
+
+ const res = await request(app)
+ .post('/external/gfs/shares')
+ .set('x-user-session-token', 'sess')
+ .send({ resourceId: R, subjects, permissions: ['read'], includeDescendants: true })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({ ok: true, resourceId: R, updated: subjects, count: 2 })
+ expect(
+ mockQuery.mock.calls.filter(call => String(call[0]).includes('INSERT INTO gfs_shares'))
+ ).toHaveLength(1)
+ expect(mockAppendPermissionEvents).toHaveBeenCalledTimes(1)
+ expect(mockAppendPermissionEvents.mock.calls[0]?.[1]?.changes).toHaveLength(2)
+ })
+
+ it.each([
+ ['grant', 'put', '/external/gfs/grants', 'INSERT INTO gfs_grants', ['manage_acl', 'read']],
+ ['share', 'post', '/external/gfs/shares', 'INSERT INTO gfs_shares', ['share', 'read']],
+ ] as const)(
+ 'canonicalizes uppercase UUID subjects throughout a successful %s mutation',
+ async (_label, method, path, mutationSql, heldPermissions) => {
+ auth()
+ authority([...heldPermissions])
+ const app = await buildApp()
+
+ const res = await request(app)
+ [method](path)
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: R,
+ subjects: [
+ { type: 'user', id: U2.toUpperCase() },
+ { type: 'team', id: T2.toUpperCase() },
+ ],
+ permissions: ['read'],
+ })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ ok: true,
+ resourceId: R,
+ updated: [
+ { type: 'user', id: U2 },
+ { type: 'team', id: T2 },
+ ],
+ count: 2,
+ })
+ const mutation = mockQuery.mock.calls.find(call => String(call[0]).includes(mutationSql))
+ expect(mutation?.[1]?.[3]).toEqual([U2, T2])
+ const audits = mockQuery.mock.calls.filter(call =>
+ String(call[0]).includes('INSERT INTO gfs_audit')
+ )
+ expect(audits.map(call => call[1]?.[0])).toEqual([`user:${U2}`, `team:${T2}`])
+ }
+ )
+
+ it.each([
+ ['grant', 'put', '/external/gfs/grants', 'INSERT INTO gfs_grants', ['manage_acl', 'read']],
+ ['share', 'post', '/external/gfs/shares', 'INSERT INTO gfs_shares', ['share', 'read']],
+ ] as const)(
+ 'rejects a mixed-case duplicate %s batch with the common structured error',
+ async (_label, method, path, mutationSql, heldPermissions) => {
+ auth()
+ authority([...heldPermissions])
+ const app = await buildApp()
+
+ const res = await request(app)
+ [method](path)
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: R,
+ subjects: [
+ { type: 'user', id: U2 },
+ { type: 'user', id: U2.toUpperCase() },
+ ],
+ permissions: ['read'],
+ })
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({
+ error: 'subjects_invalid',
+ message: 'subjects_invalid',
+ invalidIndexes: [1],
+ })
+ expect(mockQuery.mock.calls.some(call => String(call[0]).includes(mutationSql))).toBe(false)
+ expect(mockAppendPermissionEvents).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ ['grant with neither field', 'put', '/external/gfs/grants', {}],
+ [
+ 'grant with both fields',
+ 'put',
+ '/external/gfs/grants',
+ { subject: { type: 'user', id: U2 }, subjects: [{ type: 'team', id: T2 }] },
+ ],
+ ['share with neither field', 'post', '/external/gfs/shares', {}],
+ [
+ 'share with both fields',
+ 'post',
+ '/external/gfs/shares',
+ { subject: { type: 'user', id: U2 }, subjects: [{ type: 'team', id: T2 }] },
+ ],
+ ] as const)(
+ 'gives subject transport precedence for %s even when resourceId is invalid',
+ async (_label, method, path, subjectFields) => {
+ auth()
+ mockQuery.mockResolvedValue({ rows: [] })
+ const app = await buildApp()
+
+ const res = await request(app)
+ [method](path)
+ .set('x-user-session-token', 'sess')
+ .send({ resourceId: 'not-a-uuid', ...subjectFields, permissions: ['read'] })
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'subjects_invalid', message: 'subjects_invalid' })
+ expect(
+ mockQuery.mock.calls.some(call => /INSERT INTO gfs_(?:grants|shares)/.test(String(call[0])))
+ ).toBe(false)
+ expect(mockAppendPermissionEvents).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ ['grant', 'put', '/external/gfs/grants'],
+ ['share', 'post', '/external/gfs/shares'],
+ ] as const)(
+ 'serializes an invalid resource consistently for %s writes',
+ async (_label, method, path) => {
+ auth()
+ mockQuery.mockResolvedValue({ rows: [] })
+ const app = await buildApp()
+
+ const res = await request(app)
+ [method](path)
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: 'not-a-uuid',
+ subject: { type: 'user', id: U2 },
+ permissions: ['read'],
+ })
+
+ expect(res.status).toBe(400)
+ expect(res.body).toEqual({ error: 'resource_invalid', message: 'resource_invalid' })
+ expect(
+ mockQuery.mock.calls.some(call => /INSERT INTO gfs_(?:grants|shares)/.test(String(call[0])))
+ ).toBe(false)
+ expect(mockAppendPermissionEvents).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ ['operator', { type: 'operator' }],
+ ['context', { type: 'context', id: 'run-context' }],
+ ])('rejects plural %s grants before mutation', async (_label, unsupported) => {
+ auth()
+ authority(['manage_acl', 'read'])
+ const app = await buildApp()
+
+ const res = await request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: R,
+ subjects: [{ type: 'user', id: U2 }, unsupported],
+ permissions: ['read'],
+ })
+
+ expect(res.status).toBe(400)
+ expect(res.body).toMatchObject({ error: 'subjects_invalid', invalidIndexes: [1] })
+ expect(
+ mockQuery.mock.calls.some(call => String(call[0]).includes('INSERT INTO gfs_grants'))
+ ).toBe(false)
+ expect(mockAppendPermissionEvents).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['host', { type: 'host', id: H1 }],
+ ['operator', { type: 'operator' }],
+ ['context', { type: 'context', id: 'run-context' }],
+ ])('rejects a %s in plural shares before mutation', async (_label, unsupported) => {
+ auth()
+ authority(['share', 'read'])
+ const app = await buildApp()
+
+ const res = await request(app)
+ .post('/external/gfs/shares')
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: R,
+ subjects: [{ type: 'user', id: U2 }, unsupported],
+ permissions: ['read'],
+ })
+
+ expect(res.status).toBe(400)
+ expect(res.body).toMatchObject({ error: 'subjects_invalid', invalidIndexes: [1] })
+ expect(
+ mockQuery.mock.calls.some(call => String(call[0]).includes('INSERT INTO gfs_shares'))
+ ).toBe(false)
+ expect(mockAppendPermissionEvents).not.toHaveBeenCalled()
+ })
+
+ it('denies an entire mixed grant batch without mutation and records correlated denial evidence', async () => {
+ auth()
+ authority(['manage_acl'])
+ const app = await buildApp()
+
+ const res = await request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .set('x-correlation-id', CORRELATION_ID)
+ .send({
+ resourceId: R,
+ subjects: [
+ { type: 'user', id: U2 },
+ { type: 'host', id: H1 },
+ ],
+ permissions: ['manage_acl'],
+ })
+
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('agent_manager_forbidden')
+ expect(
+ mockQuery.mock.calls.some(call => String(call[0]).includes('INSERT INTO gfs_grants'))
+ ).toBe(false)
+ const audits = mockQuery.mock.calls.filter(call =>
+ String(call[0]).includes('INSERT INTO gfs_audit')
+ )
+ expect(audits.map(call => [call[1]?.[0], call[1]?.[4], call[1]?.[6]])).toEqual([
+ [`user:${U2}`, 'denied', CORRELATION_ID],
+ [`host:${H1}`, 'denied', CORRELATION_ID],
+ ])
+ expect(mockAppendPermissionEvents).toHaveBeenCalledTimes(1)
+ expect(mockAppendPermissionEvents.mock.calls[0]?.[1]?.changes).toEqual([
+ expect.objectContaining({ outcome: 'rejected', authorizationDecision: 'deny' }),
+ expect.objectContaining({ outcome: 'rejected', authorizationDecision: 'deny' }),
+ ])
+ })
+
+ it('does not publish staged mutation or audit effects when event persistence fails', async () => {
+ auth()
+ authority(['manage_acl', 'read'])
+ const attempted: string[] = []
+ const committed: string[] = []
+ mockWithTransaction.mockImplementation(
+ async (
+ work: (db: {
+ query: (text: string, values?: unknown[]) => Promise<{ rows: unknown[] }>
+ }) => Promise<unknown>
+ ) => {
+ const staged: string[] = []
+ const result = await work({
+ query: async (text: string, values?: unknown[]) => {
+ if (text.includes('INSERT INTO gfs_grants')) staged.push('grant')
+ if (text.includes('INSERT INTO gfs_audit')) staged.push('audit')
+ attempted.push(...staged.slice(attempted.length))
+ return mockQuery(text, values)
+ },
+ })
+ committed.push(...staged)
+ return result
+ }
+ )
+ mockAppendPermissionEvents.mockRejectedValueOnce(new Error('permission event write failed'))
+ const app = await buildApp()
+
+ const res = await request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .send({
+ resourceId: R,
+ subjects: [
+ { type: 'user', id: U2 },
+ { type: 'team', id: T2 },
+ ],
+ permissions: ['read'],
+ })
+
+ expect(res.status).toBe(500)
+ expect(attempted).toContain('grant')
+ expect(attempted).toContain('audit')
+ expect(committed).toEqual([])
+ })
})
describe('GET /external/gfs/resources/:id/affordances', () => {
diff --git a/control-api/test/routes.mcp-host.workflows.test.ts b/control-api/test/routes.mcp-host.workflows.test.ts
index 3cef09f95..52fd88e43 100644
--- a/control-api/test/routes.mcp-host.workflows.test.ts
+++ b/control-api/test/routes.mcp-host.workflows.test.ts
@@ -175,15 +175,18 @@ function makeRunRow(overrides: Record<string, unknown> = {}) {
function mockTypedApprovalBinding(
triggerName = 'test-recipe',
- triggerCaller = 'sandbox-recipes/test-recipe'
+ triggerCaller = 'sandbox-recipes/test-recipe',
+ actorType: 'user' | 'admin' | 'autonomous' | 'scheduled' | null = null,
+ status: 'approved' | 'consumed' = 'approved'
) {
mockPoolQuery.mockResolvedValueOnce({
rows: [
{
- status: 'approved',
+ status,
triggerNamespace: 'sandbox-recipes',
triggerName,
triggerCaller,
+ actorType,
},
],
rowCount: 1,
@@ -363,6 +366,183 @@ describe('routes/mcp-host/workflows', () => {
expect(mockListRunsByRecipe).not.toHaveBeenCalled()
})
+ it('returns only conversation-scoped status and health for a shared mcp-host', async () => {
+ const targetUserId = '00000000-0000-4000-8000-000000000001'
+ const succeededRun = makeRunRow({
+ run_id: 'conversation-run',
+ phase: 'Succeeded',
+ actor_type: 'user',
+ actor_id: targetUserId,
+ completed_at: '2026-05-03T00:02:00.000Z',
+ activeRuns: 2,
+ })
+ mockPoolQuery.mockImplementation((sql: string) => {
+ if (String(sql).includes('WITH scoped_runs AS')) {
+ return Promise.resolve({ rows: [succeededRun], rowCount: 1 })
+ }
+ return Promise.resolve({
+ rows: [{ recipe_namespace: 'sandbox-recipes', recipe_name: 'test-recipe' }],
+ rowCount: 1,
+ })
+ })
+
+ const app = makeApp()
+ const detail = await request(app)
+ .get(
+ `/workflows/sandbox-recipes/test-recipe?targetUserId=${targetUserId}&workflowConversationId=thread-1`
+ )
+ .set('Authorization', 'Bearer shared-host-control-token')
+ const health = await request(app)
+ .get(
+ `/workflows/sandbox-recipes/test-recipe/health?targetUserId=${targetUserId}&workflowConversationId=thread-1`
+ )
+ .set('Authorization', 'Bearer shared-host-control-token')
+
+ expect(detail.status).toBe(200)
+ expect(detail.body.latestRun).toMatchObject({ id: 'conversation-run', phase: 'Succeeded' })
+ expect(health.status).toBe(200)
+ expect(health.body).toMatchObject({
+ activeRuns: 2,
+ lastRun: { id: 'conversation-run', phase: 'Succeeded' },
+ })
+ const scopedQueries = mockPoolQuery.mock.calls.filter(call =>
+ String(call[0]).includes('WITH scoped_runs AS')
+ )
+ expect(scopedQueries).toHaveLength(2)
+ for (const [sql, values] of scopedQueries) {
+ expect(String(sql)).toContain("phase IN ('Pending', 'Running')")
+ expect(sql).toContain("workflowTrigger'->>'conversationId' = $6")
+ expect(values).toEqual([
+ 'sandbox-recipes',
+ 'test-recipe',
+ targetUserId,
+ null,
+ 'chatllm',
+ 'thread-1',
+ ])
+ }
+ expect(mockListRunsByRecipe).not.toHaveBeenCalled()
+ })
+
+ it('keeps shared-host run summaries null when conversation context is missing', async () => {
+ const targetUserId = '00000000-0000-4000-8000-000000000001'
+ mockPoolQuery.mockResolvedValue({
+ rows: [{ recipe_namespace: 'sandbox-recipes', recipe_name: 'test-recipe' }],
+ rowCount: 1,
+ })
+
+ const app = makeApp()
+ const detail = await request(app)
+ .get(`/workflows/sandbox-recipes/test-recipe?targetUserId=${targetUserId}`)
+ .set('Authorization', 'Bearer shared-host-control-token')
+ const health = await request(app)
+ .get(`/workflows/sandbox-recipes/test-recipe/health?targetUserId=${targetUserId}`)
+ .set('Authorization', 'Bearer shared-host-control-token')
+
+ expect(detail.status).toBe(200)
+ expect(detail.body.latestRun).toBeNull()
+ expect(health.status).toBe(200)
+ expect(health.body.activeRuns).toBeNull()
+ expect(health.body.lastRun).toBeNull()
+ expect(
+ mockPoolQuery.mock.calls.some(call => String(call[0]).includes('WITH scoped_runs AS'))
+ ).toBe(false)
+ })
+
+ it('does not leak a shared-host run from another conversation', async () => {
+ const targetUserId = '00000000-0000-4000-8000-000000000001'
+ mockPoolQuery.mockImplementation((sql: string) => {
+ if (String(sql).includes('WITH scoped_runs AS')) {
+ return Promise.resolve({ rows: [], rowCount: 0 })
+ }
+ return Promise.resolve({
+ rows: [{ recipe_namespace: 'sandbox-recipes', recipe_name: 'test-recipe' }],
+ rowCount: 1,
+ })
+ })
+
+ const app = makeApp()
+ const detail = await request(app)
+ .get(
+ `/workflows/sandbox-recipes/test-recipe?targetUserId=${targetUserId}&workflowConversationId=wrong-thread`
+ )
+ .set('Authorization', 'Bearer shared-host-control-token')
+ const health = await request(app)
+ .get(
+ `/workflows/sandbox-recipes/test-recipe/health?targetUserId=${targetUserId}&workflowConversationId=wrong-thread`
+ )
+ .set('Authorization', 'Bearer shared-host-control-token')
+
+ expect(detail.status).toBe(200)
+ expect(detail.body.latestRun).toBeNull()
+ expect(JSON.stringify(detail.body)).not.toContain('conversation-run')
+ expect(health.status).toBe(200)
+ expect(health.body).toMatchObject({ activeRuns: 0, lastRun: null })
+ expect(JSON.stringify(health.body)).not.toContain('conversation-run')
+ const scopedQueries = mockPoolQuery.mock.calls.filter(call =>
+ String(call[0]).includes('WITH scoped_runs AS')
+ )
+ expect(scopedQueries).toHaveLength(2)
+ expect(scopedQueries.every(call => call[1]?.[5] === 'wrong-thread')).toBe(true)
+ })
+
+ it.each([
+ '/workflows/sandbox-recipes/test-recipe',
+ '/workflows/sandbox-recipes/test-recipe/health',
+ ])('rejects malformed shared-host conversation context on %s', async route => {
+ const targetUserId = '00000000-0000-4000-8000-000000000001'
+ mockPoolQuery.mockResolvedValue({
+ rows: [{ recipe_namespace: 'sandbox-recipes', recipe_name: 'test-recipe' }],
+ rowCount: 1,
+ })
+
+ const response = await request(makeApp())
+ .get(`${route}?targetUserId=${targetUserId}&workflowConversationId=bad/../thread`)
+ .set('Authorization', 'Bearer shared-host-control-token')
+
+ expect(response.status).toBe(400)
+ expect(response.body).toEqual({ error: 'Invalid workflowConversationId format' })
+ expect(
+ mockPoolQuery.mock.calls.some(call => String(call[0]).includes('WITH scoped_runs AS'))
+ ).toBe(false)
+ })
+
+ it.each([
+ '/workflows/sandbox-recipes/test-recipe',
+ '/workflows/sandbox-recipes/test-recipe/health',
+ ])('accepts a maximum-length Teams conversation ID on %s', async route => {
+ const targetUserId = '00000000-0000-4000-8000-000000000001'
+ const teamsConversationId = `19:${'A'.repeat(509)}`
+ const succeededRun = makeRunRow({
+ run_id: 'teams-conversation-run',
+ phase: 'Succeeded',
+ actor_type: 'user',
+ actor_id: targetUserId,
+ completed_at: '2026-05-03T00:02:00.000Z',
+ activeRuns: 0,
+ })
+ mockPoolQuery.mockImplementation((sql: string) => {
+ if (String(sql).includes('WITH scoped_runs AS')) {
+ return Promise.resolve({ rows: [succeededRun], rowCount: 1 })
+ }
+ return Promise.resolve({
+ rows: [{ recipe_namespace: 'sandbox-recipes', recipe_name: 'test-recipe' }],
+ rowCount: 1,
+ })
+ })
+
+ const response = await request(makeApp())
+ .get(`${route}?targetUserId=${targetUserId}&workflowConversationId=${teamsConversationId}`)
+ .set('Authorization', 'Bearer shared-host-control-token')
+
+ expect(teamsConversationId).toHaveLength(512)
+ expect(response.status).toBe(200)
+ const scopedQuery = mockPoolQuery.mock.calls.find(call =>
+ String(call[0]).includes('WITH scoped_runs AS')
+ )
+ expect(scopedQuery?.[1]?.[5]).toBe(teamsConversationId)
+ })
+
it('does not let a sandbox caller read a cross-target workflow without explicit approval target context', async () => {
const res = await request(makeApp())
.get('/workflows/sandbox-recipes/test-recipe')
@@ -1729,6 +1909,50 @@ describe('routes/mcp-host/workflows', () => {
expect(mockCreateWorkflowRun).not.toHaveBeenCalled()
})
+ it('returns an existing user run when the consumed approval recipe only allows user actors', async () => {
+ const approvalRequestId = '00000000-0000-4000-8000-000000000123'
+ mockTypedApprovalBinding(
+ 'test-recipe',
+ 'sandbox-recipes/workflow-caller-alpha',
+ 'user',
+ 'consumed'
+ )
+ mockCreateApprovedWorkflowRun.mockResolvedValueOnce({
+ row: makeRunRow({
+ run_id: 'existing-user-run',
+ actor_type: 'user',
+ trigger_source: 'onDemand',
+ idempotency_key: 'idem-user-retry',
+ approval_request_id: approvalRequestId,
+ }),
+ created: false,
+ })
+
+ const res = await request(
+ makeApp(
+ ['test-recipe'],
+ {},
+ {
+ 'test-recipe': {
+ triggers: { onDemand: { requiresApproval: true, allowedActors: ['user'] } },
+ },
+ }
+ )
+ )
+ .post('/workflows/sandbox-recipes/test-recipe/trigger')
+ .set('Authorization', 'Bearer workflow-caller-alpha-token')
+ .set('Idempotency-Key', 'idem-user-retry')
+ .send({ approvalRequestId })
+
+ expect(res.status).toBe(200)
+ expect(res.body).toMatchObject({
+ id: 'existing-user-run',
+ actor: { type: 'user-session' },
+ })
+ expect(mockCreateApprovedWorkflowRun).toHaveBeenCalledTimes(1)
+ expect(mockCreateWorkflowRun).not.toHaveBeenCalled()
+ })
+
it('rejects sandbox mcp-host caller trigger before workflow preflight when approval binding mismatches', async () => {
const approvalRequestId = '00000000-0000-4000-8000-000000000123'
mockPoolQuery.mockResolvedValueOnce({
diff --git a/control-api/test/services.userApprovalRequestService.test.ts b/control-api/test/services.userApprovalRequestService.test.ts
index ceb47185b..96db9eb13 100644
--- a/control-api/test/services.userApprovalRequestService.test.ts
+++ b/control-api/test/services.userApprovalRequestService.test.ts
@@ -282,32 +282,56 @@ describe('userApprovalRequestService', () => {
})
describe('assertApprovalTriggerBinding', () => {
- it('accepts a matching typed trigger intent without reading JSON metadata', async () => {
- mockedQuery.mockResolvedValueOnce({
- rows: [
- {
- status: 'approved',
- triggerNamespace: 'sandbox-recipes',
- triggerName: 'target',
- triggerCaller: 'sandbox-recipes/caller',
- },
- ],
- rowCount: 1,
- } as any)
-
- await expect(
- assertApprovalTriggerBinding({
- approvalRequestId: 'approval-1',
- recipeNamespace: 'sandbox-recipes',
- recipeName: 'target',
- callerKey: 'sandbox-recipes/caller',
- })
- ).resolves.toBeUndefined()
+ it.each([
+ { actorType: 'user', requestedActor: 'user', approvalRequestId: 'approval-user' },
+ { actorType: 'admin', requestedActor: 'user', approvalRequestId: 'approval-admin' },
+ {
+ actorType: 'autonomous',
+ requestedActor: 'autonomous',
+ approvalRequestId: 'approval-autonomous',
+ },
+ {
+ actorType: 'scheduled',
+ requestedActor: 'scheduled',
+ approvalRequestId: 'approval-scheduled',
+ },
+ {
+ actorType: null,
+ requestedActor: 'autonomous',
+ approvalRequestId: 'approval-legacy',
+ },
+ ] as const)(
+ 'maps persisted actor type $actorType to $requestedActor',
+ async ({ actorType, requestedActor, approvalRequestId }) => {
+ mockedQuery.mockResolvedValueOnce({
+ rows: [
+ {
+ status: 'approved',
+ triggerNamespace: 'sandbox-recipes',
+ triggerName: 'target',
+ triggerCaller: 'sandbox-recipes/caller',
+ actorType,
+ },
+ ],
+ rowCount: 1,
+ } as any)
- const sql = String(mockedQuery.mock.calls[0]?.[0])
- expect(sql).toContain('LEFT JOIN workflow_approval_trigger_intents')
- expect(sql).not.toContain("payload->'metadata'->'workflowTrigger'")
- })
+ await expect(
+ assertApprovalTriggerBinding({
+ approvalRequestId,
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'target',
+ callerKey: 'sandbox-recipes/caller',
+ })
+ ).resolves.toEqual({ requestedActor })
+
+ const sql = String(mockedQuery.mock.calls[0]?.[0])
+ expect(sql).toContain('LEFT JOIN workflow_approval_trigger_intents')
+ expect(sql).toContain('LEFT JOIN workflow_approval_trigger_run_intents')
+ expect(sql).toContain('watri.actor_type AS "actorType"')
+ expect(sql).not.toContain("payload->'metadata'->'workflowTrigger'")
+ }
+ )
it.each([
'chatllm',
@@ -333,7 +357,7 @@ describe('userApprovalRequestService', () => {
recipeName: 'target',
callerKey,
})
- ).resolves.toBeUndefined()
+ ).resolves.toEqual({ requestedActor: 'autonomous' })
})
it('rejects a trigger preflight when the typed caller or target recipe mismatches', async () => {
diff --git a/control-api/test/services.workflowConversationRunReadService.test.ts b/control-api/test/services.workflowConversationRunReadService.test.ts
new file mode 100644
index 000000000..c1d5d50e4
--- /dev/null
+++ b/control-api/test/services.workflowConversationRunReadService.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from 'vitest'
+import { getConversationScopedWorkflowHealth } from '../src/services/workflows/workflowConversationRunReadService.js'
+
+const caller = {
+ kind: 'mcp-host-control' as const,
+ claims: {
+ sub: 'mcp-host/standalone',
+ hostRefs: ['chatllm'],
+ scopes: ['workflow:read'],
+ },
+}
+
+describe('workflowConversationRunReadService', () => {
+ it('counts every active run and returns the latest run inside the exact conversation scope', async () => {
+ const query = vi.fn().mockResolvedValue({
+ rows: [
+ {
+ run_id: '00000000-0000-4000-8000-000000000123',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'gfs-grant-e2e-plugin',
+ phase: 'Succeeded',
+ activeRuns: 2,
+ },
+ ],
+ rowCount: 1,
+ })
+
+ const result = await getConversationScopedWorkflowHealth({
+ caller: caller as never,
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'gfs-grant-e2e-plugin',
+ approvalTarget: { targetUserId: '00000000-0000-4000-8000-000000000001' },
+ conversationId: 'thread-1',
+ db: { query } as never,
+ })
+
+ expect(result.activeRuns).toBe(2)
+ expect(result.lastRun).toMatchObject({ phase: 'Succeeded' })
+ const [sql, params] = query.mock.calls[0]
+ expect(String(sql)).toContain('COUNT(*) FILTER')
+ expect(String(sql)).toContain("phase IN ('Pending', 'Running')")
+ expect(String(sql)).toContain('trigger_caller_key = $5')
+ expect(String(sql)).toContain("'conversationId' = $6")
+ expect(params).toEqual([
+ 'sandbox-recipes',
+ 'gfs-grant-e2e-plugin',
+ '00000000-0000-4000-8000-000000000001',
+ null,
+ 'chatllm',
+ 'thread-1',
+ ])
+ })
+
+ it('returns no run and zero active runs when the exact conversation has no match', async () => {
+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })
+
+ await expect(
+ getConversationScopedWorkflowHealth({
+ caller: caller as never,
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'gfs-grant-e2e-plugin',
+ approvalTarget: { targetTeamId: '00000000-0000-4000-8000-0000000000aa' },
+ conversationId: 'other-thread',
+ db: { query } as never,
+ })
+ ).resolves.toEqual({ activeRuns: 0, lastRun: null })
+ })
+})
diff --git a/control-ui/Dockerfile b/control-ui/Dockerfile
index a664ed1aa..4c5733ba3 100644
--- a/control-ui/Dockerfile
+++ b/control-ui/Dockerfile
@@ -20,6 +20,8 @@ RUN npm ci \
&& rm -rf node_modules/@clerum/llm-providers \
&& cp -R ../packages/llm-providers node_modules/@clerum/llm-providers
+# Next type-checks the Playwright config, which imports this shared loader.
+COPY scripts/qa-recorder /app/scripts/qa-recorder
COPY control-ui ./
RUN npm run build
diff --git a/control-ui/Dockerfile.dockerignore b/control-ui/Dockerfile.dockerignore
index e13d28c29..311a6b203 100644
--- a/control-ui/Dockerfile.dockerignore
+++ b/control-ui/Dockerfile.dockerignore
@@ -2,6 +2,9 @@
!packages/
!packages/workflow-recipe-capability-policy/
!packages/workflow-recipe-capability-policy/**
+!scripts/
+!scripts/qa-recorder/
+!scripts/qa-recorder/loadEnv.ts
!control-ui/
!control-ui/package.json
!control-ui/package-lock.json
@@ -9,6 +12,7 @@
!control-ui/next.config.js
!control-ui/next-env.d.ts
!control-ui/global.d.ts
+!control-ui/playwright.qa-recorder.config.ts
!control-ui/app/
!control-ui/app/**
!control-ui/components/
diff --git a/control-ui/Makefile b/control-ui/Makefile
index a791b54d5..98f019f5b 100644
--- a/control-ui/Makefile
+++ b/control-ui/Makefile
@@ -1,6 +1,6 @@
.PHONY: install build docker-build docker-push
-REGISTRY ?= us-central1-docker.pkg.dev/your-gcp-project/clerum
+REGISTRY ?= us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum
IMAGE_NAME ?= control-ui
TAG ?= $(shell git describe --tags --always 2>/dev/null || echo "latest")
CONTROL_API_INTERNAL_URL ?= http://control-api.control-plane.svc.cluster.local:8090
diff --git a/control-ui/app/constants/createFlowLoading.ts b/control-ui/app/constants/createFlowLoading.ts
index a09d20f84..a5069cd21 100644
--- a/control-ui/app/constants/createFlowLoading.ts
+++ b/control-ui/app/constants/createFlowLoading.ts
@@ -61,7 +61,7 @@ export const CREATE_FLOW_LOADING = {
iconKey: 'shared-files',
title: 'Create SharedFileSystem',
subtitle: 'Provision workspace storage that Contexts can mount read-only into agent pods.',
- backLabel: 'Back to shared files',
+ backLabel: 'Back to Agent Files',
steps: ['Storage', 'Access', 'Folders'],
stepFlowClassName: 'cu-create-step-flow--3',
},
diff --git a/control-ui/app/constants/gfsGrantSubjects.ts b/control-ui/app/constants/gfsGrantSubjects.ts
index d5d4b070a..47638f0af 100644
--- a/control-ui/app/constants/gfsGrantSubjects.ts
+++ b/control-ui/app/constants/gfsGrantSubjects.ts
@@ -1,10 +1,6 @@
-export const GFS_FIRST_PARTY_HOST_SUBJECT_ID = '1st:mcp-host/standalone'
-export const GFS_FIRST_PARTY_HOST_OPTION_VALUE = `host:${GFS_FIRST_PARTY_HOST_SUBJECT_ID}`
+export const GFS_MAX_BULK_SUBJECTS = 100
export const GFS_GRANT_SUBJECT_TYPE_OPTIONS = [
- { value: 'user', label: 'User' },
- { value: 'team', label: 'Team' },
+ { value: 'subjects', label: 'Subjects' },
{ value: 'operator', label: 'Operator' },
- { value: 'firstPartyAgent', label: 'First-party agent' },
- { value: 'workflowPlugin', label: 'Workflow / plugin' },
] as const
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.ts
index 53bbaa480..70bf942d5 100644
--- a/control-ui/app/constants/routes.ts
+++ b/control-ui/app/constants/routes.ts
@@ -60,7 +60,7 @@ export const CONTROL_ROUTES = {
new: (query?: ControlRouteQuery) => withQuery('/external-channels/new', query),
edit: (name: string) => `/external-channels/${segment(name)}/edit`,
},
- globalFiles: '/global-files',
+ globalFileSystem: '/global-file-system',
llmModels: {
root: '/llm-models',
discovery: '/llm-models/discovery',
@@ -80,11 +80,11 @@ export const CONTROL_ROUTES = {
editEntry: (name: string, version: string) =>
`/marketplace/entries/${segment(name)}/${segment(version)}/edit`,
},
- outputs: {
- base: '/outputs',
- root: '/outputs/recipe-artifacts',
- recipeArtifacts: '/outputs/recipe-artifacts',
- desktopAppArtifacts: '/outputs/desktop-app-artifacts',
+ agentOutputs: {
+ base: '/agent-outputs',
+ root: '/agent-outputs/recipe-artifacts',
+ recipeArtifacts: '/agent-outputs/recipe-artifacts',
+ desktopAppArtifacts: '/agent-outputs/desktop-app-artifacts',
},
plugins: {
root: '/plugins',
@@ -117,10 +117,10 @@ export const CONTROL_ROUTES = {
ui: '/settings/ui',
withFocus: (focus: string) => withQuery('/settings', { focus }),
},
- sharedFiles: {
- root: '/shared-files',
- new: '/shared-files/new',
- detail: (name: string) => `/shared-files/${segment(name)}`,
+ agentFiles: {
+ root: '/agent-files',
+ new: '/agent-files/new',
+ detail: (name: string) => `/agent-files/${segment(name)}`,
},
traces: {
root: '/traces',
diff --git a/control-ui/app/contexts/[name]/[tab]/page.tsx b/control-ui/app/contexts/[name]/[tab]/page.tsx
index abbacd236..92f47551d 100644
--- a/control-ui/app/contexts/[name]/[tab]/page.tsx
+++ b/control-ui/app/contexts/[name]/[tab]/page.tsx
@@ -5,7 +5,7 @@ interface ContextTabPageProps {
params: Promise<{ tab: string }>
}
-const CONTEXT_DETAIL_TABS = ['connectors', 'shared-files', 'agents', 'teams', 'members']
+const CONTEXT_DETAIL_TABS = ['connectors', 'agent-files', 'agents', 'teams', 'members']
export default async function ContextTabPage({ params }: ContextTabPageProps) {
const { tab } = await params
diff --git a/control-ui/app/contexts/[name]/page.tsx b/control-ui/app/contexts/[name]/page.tsx
index f2a48d8fe..0ea79a8ca 100644
--- a/control-ui/app/contexts/[name]/page.tsx
+++ b/control-ui/app/contexts/[name]/page.tsx
@@ -43,12 +43,12 @@ import {
updateContext,
} from '../../../lib/api'
-type ContextTab = 'connectors' | 'shared-files' | 'agents' | 'teams' | 'members'
-const CONTEXT_TABS: ContextTab[] = ['connectors', 'shared-files', 'agents', 'teams', 'members']
+type ContextTab = 'connectors' | 'agent-files' | 'agents' | 'teams' | 'members'
+const CONTEXT_TABS: ContextTab[] = ['connectors', 'agent-files', 'agents', 'teams', 'members']
const TAB_LABELS: Record<ContextTab, string> = {
connectors: 'Connectors',
- 'shared-files': 'Shared Files',
+ 'agent-files': 'Agent Files',
agents: 'Agents',
teams: 'Teams',
members: 'Members',
@@ -881,7 +881,7 @@ export default function ContextDetailsPage() {
</>
)}
- {activeTab === 'shared-files' && (
+ {activeTab === 'agent-files' && (
<>
{sharedFileSystemsDraft.length === 0 ? (
<div className="cu-empty">No SharedFileSystems attached.</div>
@@ -897,7 +897,7 @@ export default function ContextDetailsPage() {
<td>
<a
className="cu-link"
- href={CONTROL_ROUTES.sharedFiles.detail(ref.name)}
+ href={CONTROL_ROUTES.agentFiles.detail(ref.name)}
style={{
display: 'inline-flex',
alignItems: 'center',
diff --git a/control-ui/app/cost/layout.tsx b/control-ui/app/cost/layout.tsx
index 832232ff4..7b2229b40 100644
--- a/control-ui/app/cost/layout.tsx
+++ b/control-ui/app/cost/layout.tsx
@@ -3,21 +3,20 @@
import React from 'react'
import { useSelectedLayoutSegments } from 'next/navigation'
import { CostShell } from '@components/CostShell'
-import type { CostSegment } from '@components/CostShell/types'
-const SECTION_SEGMENTS: readonly CostSegment[] = ['usage', 'llm-prices', 'token-budgets']
+const SECTION_SEGMENTS = ['usage', 'llm-prices', 'token-budgets'] as const
export default function CostLayout({ children }: { children: React.ReactNode }) {
const segments = useSelectedLayoutSegments()
const [firstSegment] = segments
- const activeSegment = SECTION_SEGMENTS.find(segment => segment === firstSegment)
+ const isSectionRoot = SECTION_SEGMENTS.some(segment => segment === firstSegment)
// Section-root list pages (/cost/usage, /cost/llm-prices, /cost/token-budgets)
- // share the tab shell. Deeper create/edit routes own their own create shell,
+ // share the auth and dashboard shell. Deeper create/edit routes own their own create shell,
// so render them untouched.
- if (segments.length > 1 || !activeSegment) {
+ if (segments.length > 1 || !isSectionRoot) {
return <>{children}</>
}
- return <CostShell activeSegment={activeSegment}>{children}</CostShell>
+ return <CostShell>{children}</CostShell>
}
diff --git a/control-ui/app/gfs/page.tsx b/control-ui/app/gfs/page.tsx
index b4a3a61bb..2c6d3ea02 100644
--- a/control-ui/app/gfs/page.tsx
+++ b/control-ui/app/gfs/page.tsx
@@ -6,7 +6,7 @@ import { GfsBrowser } from '@components/GfsBrowser'
/**
* Operator Global File System browser + delegation. Canonical App Router path
- * (/gfs) — no ?tab= or ad-hoc query keys for routing (project UI rule).
+ * (/global-file-system) — no ?tab= or ad-hoc query keys for routing (project UI rule).
* Auth-gated like every other operator route section.
*/
export default function GfsPage() {
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index 913e60e81..66a0029da 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -692,6 +692,162 @@ body.cu-body {
background: radial-gradient(125% 125% at 50% 90%, var(--cu-bg) 40%, var(--cu-auth-bg-edge) 100%);
}
+.cu-loading-screen {
+ --cu-loading-card-max-width: 26.25rem;
+ --cu-loading-mark-size: 2.75rem;
+ --cu-loading-progress-width: 12.5rem;
+
+ min-height: 100vh;
+ width: 100%;
+ display: grid;
+ place-items: center;
+ padding: calc(var(--cu-space-5) * 2);
+ background: var(--cu-app-radial-left), var(--cu-app-radial-right), var(--cu-bg);
+}
+
+.cu-loading-screen__surface {
+ width: min(var(--cu-loading-card-max-width), 94vw);
+ display: grid;
+ place-items: center;
+ gap: var(--cu-space-4);
+ padding: calc(var(--cu-space-5) * 2) calc(var(--cu-space-4) * 2);
+ border: 1px solid var(--cu-border);
+ border-radius: var(--cu-radius);
+ background: var(--cu-surface);
+ box-shadow: var(--cu-shadow);
+ text-align: center;
+ animation: cu-loading-screen-in 420ms ease both;
+}
+
+.cu-loading-screen__brand {
+ display: inline-flex;
+ align-items: center;
+ gap: calc(var(--cu-space-2) + var(--cu-space-1));
+ opacity: 0;
+ animation: cu-loading-brand-in 600ms cubic-bezier(0.2, 0.8, 0.25, 1) both;
+}
+
+.cu-loading-screen__mark {
+ width: var(--cu-loading-mark-size);
+ height: var(--cu-loading-mark-size);
+ flex: 0 0 auto;
+ object-fit: contain;
+}
+
+.cu-loading-screen__brand-copy {
+ min-width: 0;
+ display: grid;
+ gap: 0.125rem;
+ text-align: left;
+}
+
+.cu-loading-screen__title {
+ color: var(--cu-text);
+ font-size: 1.125rem;
+ font-weight: 700;
+ line-height: 1.2;
+}
+
+.cu-loading-screen__subtitle {
+ color: var(--cu-text-muted);
+ font-size: 0.6875rem;
+ font-weight: 700;
+ line-height: 1.15;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ white-space: nowrap;
+}
+
+.cu-loading-screen__progress {
+ position: relative;
+ width: var(--cu-loading-progress-width);
+ height: 0.1875rem;
+ overflow: hidden;
+ border-radius: var(--cu-radius);
+ background: rgba(var(--cu-edge-rgb), 0.3);
+ opacity: 0;
+ animation: cu-loading-fade-in 360ms ease 300ms both;
+}
+
+.cu-loading-screen__progress::after {
+ content: '';
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 45%;
+ border-radius: inherit;
+ background: linear-gradient(
+ 90deg,
+ rgba(var(--cu-accent-rgb), 0),
+ rgba(var(--cu-accent-rgb), 0.9),
+ var(--cu-accent-hover)
+ );
+ animation: cu-loading-progress-sweep 1.4s cubic-bezier(0.45, 0, 0.15, 1) infinite;
+}
+
+.cu-loading-screen__status {
+ margin: 0;
+ color: var(--cu-text-soft);
+ font-size: 0.75rem;
+ opacity: 0;
+ animation: cu-loading-fade-in 360ms ease 300ms both;
+}
+
+@keyframes cu-loading-screen-in {
+ from {
+ opacity: 0;
+ transform: translateY(0.375rem);
+ }
+
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes cu-loading-brand-in {
+ from {
+ opacity: 0;
+ transform: scale(0.92);
+ }
+
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+@keyframes cu-loading-fade-in {
+ from {
+ opacity: 0;
+ }
+
+ to {
+ opacity: 1;
+ }
+}
+
+@keyframes cu-loading-progress-sweep {
+ from {
+ transform: translateX(-110%);
+ }
+
+ to {
+ transform: translateX(322%);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .cu-loading-screen__surface,
+ .cu-loading-screen__brand,
+ .cu-loading-screen__progress,
+ .cu-loading-screen__status,
+ .cu-loading-screen__progress::after {
+ animation: none;
+ opacity: 1;
+ transform: none;
+ }
+}
+
.cu-muted {
color: var(--cu-text-soft);
margin: 0;
@@ -10272,6 +10428,81 @@ button.cu-gfs-tree__button:focus-visible,
gap: var(--cu-space-2);
}
+.cu-gfs-existing-access {
+ display: grid;
+ gap: var(--cu-space-2);
+ padding: var(--cu-space-3) 0;
+ border-top: 1px solid var(--cu-border);
+ border-bottom: 1px solid var(--cu-border);
+}
+
+.cu-gfs-existing-access__header h3,
+.cu-gfs-existing-access__header p,
+.cu-gfs-existing-access__empty,
+.cu-gfs-existing-access__error p {
+ margin: 0;
+}
+
+.cu-gfs-existing-access__header h3 {
+ color: var(--cu-text);
+ font-size: 0.875rem;
+ font-weight: 600;
+}
+
+.cu-gfs-existing-access__header p,
+.cu-gfs-existing-access__empty {
+ color: var(--cu-text-soft);
+ font-size: 0.75rem;
+}
+
+.cu-gfs-existing-access__list {
+ display: grid;
+ gap: var(--cu-space-2);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.cu-gfs-existing-access__item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--cu-space-3);
+ padding: var(--cu-space-2);
+ border: 1px solid var(--cu-border);
+ border-radius: var(--cu-radius-sm);
+ background: var(--cu-bg-elevated);
+}
+
+.cu-gfs-existing-access__copy {
+ min-width: 0;
+ display: grid;
+ gap: var(--cu-space-1);
+}
+
+.cu-gfs-existing-access__subject,
+.cu-gfs-existing-access__detail {
+ overflow-wrap: anywhere;
+}
+
+.cu-gfs-existing-access__subject {
+ color: var(--cu-text);
+ font-size: 0.8125rem;
+ font-weight: 600;
+}
+
+.cu-gfs-existing-access__detail {
+ color: var(--cu-text-soft);
+ font-size: 0.75rem;
+}
+
+.cu-gfs-existing-access__error {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--cu-space-2);
+}
+
@media (max-width: 780px) {
.cu-gfs-panel__toolbar,
.cu-gfs-panel__actions {
diff --git a/control-ui/app/loading.tsx b/control-ui/app/loading.tsx
new file mode 100644
index 000000000..81085949c
--- /dev/null
+++ b/control-ui/app/loading.tsx
@@ -0,0 +1,5 @@
+import { LoadingScreen } from '@components/LoadingScreen'
+
+export default function Loading() {
+ return <LoadingScreen />
+}
diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsx
index 11ce259cc..3ee79be3a 100644
--- a/control-ui/app/mcp-servers/page.tsx
+++ b/control-ui/app/mcp-servers/page.tsx
@@ -2,6 +2,7 @@
import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
+import { LoadingScreen } from '@components/LoadingScreen'
import { CONTROL_ROUTES } from '@constants/routes'
import { useAuth } from '../../components/AuthContext'
import { useConfirmDialog } from '../../components/ConfirmDialog'
@@ -203,15 +204,7 @@ export default function McpServersPage() {
}, [authState.isLoading, authState.isLoggedIn, router])
if (authState.isLoading) {
- return (
- <div className="cu-app-layout">
- <main className="cu-main">
- <div className="cu-card">
- <div className="cu-card__body">Loading...</div>
- </div>
- </main>
- </div>
- )
+ return <LoadingScreen />
}
if (!authState.isLoggedIn) {
diff --git a/control-ui/app/outputs/page.tsx b/control-ui/app/outputs/page.tsx
index 51507f06c..0257ac443 100644
--- a/control-ui/app/outputs/page.tsx
+++ b/control-ui/app/outputs/page.tsx
@@ -133,7 +133,7 @@ function OutputsPageContent() {
title={
<>
<IconOutputs />
- {isRefreshing ? 'Outputs' : `Outputs (${visibleOutputsCount})`}
+ {isRefreshing ? 'Agent Outputs' : `Agent Outputs (${visibleOutputsCount})`}
</>
}
subtitle="Browse generated artifacts from workflows and chat sessions."
@@ -142,8 +142,8 @@ function OutputsPageContent() {
<SectionSearchInput
value={searchQuery}
onChange={setSearchQuery}
- placeholder="Search outputs"
- ariaLabel="Search outputs"
+ placeholder="Search agent outputs"
+ ariaLabel="Search agent outputs"
disabled={isRefreshing}
/>
<button
@@ -171,13 +171,13 @@ function OutputsPageContent() {
) : null}
<TabBar<OutputsTab>
- ariaLabel="Output sections"
+ ariaLabel="Agent output sections"
activeValue={activeTab}
className="cu-tabs--flush-top"
options={[
{
value: 'workflow',
- href: CONTROL_ROUTES.outputs.recipeArtifacts,
+ href: CONTROL_ROUTES.agentOutputs.recipeArtifacts,
label:
activeTab === 'workflow'
? `Recipe Artifacts (${filteredWorkflowOutputs.length})`
@@ -185,7 +185,7 @@ function OutputsPageContent() {
},
{
value: 'desktop',
- href: CONTROL_ROUTES.outputs.desktopAppArtifacts,
+ href: CONTROL_ROUTES.agentOutputs.desktopAppArtifacts,
label:
activeTab === 'desktop'
? `Desktop App Artifacts (${filteredChatArtifacts.length})`
diff --git a/control-ui/app/page.tsx b/control-ui/app/page.tsx
index c98e76b02..06b60d9e9 100644
--- a/control-ui/app/page.tsx
+++ b/control-ui/app/page.tsx
@@ -4,6 +4,7 @@ import React, { useEffect, useMemo, useState } from 'react'
import Image from 'next/image'
import { useRouter, useSearchParams } from 'next/navigation'
import { useAuth } from '@components/AuthContext'
+import { LoadingScreen } from '@components/LoadingScreen'
import { CONTROL_ROUTES } from '@constants/routes'
import { requestControlAdminPasswordReset } from '@lib/api'
import { sanitizeControlUiReturnPath } from '@lib/authRedirect'
@@ -68,13 +69,7 @@ function PageContent() {
}
if (authState.isLoading || authState.isLoggedIn) {
- return (
- <main className="cu-app cu-app--auth">
- <div className="cu-card cu-card--auth">
- <div className="cu-card__body">Loading...</div>
- </div>
- </main>
- )
+ return <LoadingScreen />
}
return (
@@ -195,15 +190,7 @@ function PageContent() {
export default function Page() {
return (
- <React.Suspense
- fallback={
- <main className="cu-app cu-app--auth">
- <div className="cu-card cu-card--auth">
- <div className="cu-card__body">Loading...</div>
- </div>
- </main>
- }
- >
+ <React.Suspense fallback={<LoadingScreen />}>
<PageContent />
</React.Suspense>
)
diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsx
index 5eab4b0ab..7a556e24a 100644
--- a/control-ui/app/plugin-workload-sdk/page.tsx
+++ b/control-ui/app/plugin-workload-sdk/page.tsx
@@ -5,6 +5,7 @@ import { useRouter } from 'next/navigation'
import { useAuth } from '@components/AuthContext'
import { useConfirmDialog } from '@components/ConfirmDialog'
import { DashboardLayout } from '@components/DashboardLayout'
+import { LoadingScreen } from '@components/LoadingScreen'
import { SectionSearchInput } from '@components/SectionSearchInput'
import { SelectionDropdown } from '@components/SelectionDropdown'
import { IconPluginSdk } from '@components/Sidebar/icons'
@@ -260,15 +261,7 @@ export default function PluginWorkloadSdkPage() {
}
if (authState.isLoading) {
- return (
- <div className="cu-app-layout">
- <main className="cu-main">
- <div className="cu-card">
- <div className="cu-card__body">Loading…</div>
- </div>
- </main>
- </div>
- )
+ return <LoadingScreen />
}
if (!authState.isLoggedIn) return null
diff --git a/control-ui/app/registry/entries/[name]/[version]/page.tsx b/control-ui/app/registry/entries/[name]/[version]/page.tsx
index 6cdcc4b29..8e7fc0fd3 100644
--- a/control-ui/app/registry/entries/[name]/[version]/page.tsx
+++ b/control-ui/app/registry/entries/[name]/[version]/page.tsx
@@ -7,6 +7,7 @@ import { useConfirmDialog } from '@components/ConfirmDialog'
import { CreateFlowPanel } from '@components/CreateFlowPanel'
import { CreatePageHeader } from '@components/CreatePageHeader'
import { DashboardLayout } from '@components/DashboardLayout'
+import { LoadingScreen } from '@components/LoadingScreen'
import { RegistryEntryDetailSkeleton } from '@components/RegistryEntryDetailSkeleton'
import { IconStore } from '@components/Sidebar/icons'
import { useToast } from '@components/Toast'
@@ -111,17 +112,7 @@ function RegistryEntryActionsMenu({
export default function RegistryEntryDetailPage() {
return (
- <Suspense
- fallback={
- <div className="cu-app-layout">
- <main className="cu-main cu-detail-layout">
- <div className="cu-card">
- <div className="cu-card__body">Loading…</div>
- </div>
- </main>
- </div>
- }
- >
+ <Suspense fallback={<LoadingScreen />}>
<RegistryEntryDetailContent />
</Suspense>
)
diff --git a/control-ui/app/shared-filesystems/[name]/page.tsx b/control-ui/app/shared-filesystems/[name]/page.tsx
index 8e0884b6a..73e8cc4e9 100644
--- a/control-ui/app/shared-filesystems/[name]/page.tsx
+++ b/control-ui/app/shared-filesystems/[name]/page.tsx
@@ -337,9 +337,9 @@ export default function SharedFileSystemDetailsPage() {
header={
<CreatePageHeader
icon={<IconFolder />}
- title={sfsName || 'Shared Files'}
- backLabel="Back to Shared Files"
- onBack={() => router.push(CONTROL_ROUTES.sharedFiles.root)}
+ title={sfsName || 'Agent Files'}
+ backLabel="Back to Agent Files"
+ onBack={() => router.push(CONTROL_ROUTES.agentFiles.root)}
/>
}
>
@@ -402,8 +402,8 @@ export default function SharedFileSystemDetailsPage() {
<CreatePageHeader
icon={<IconFolder />}
title={sfsName}
- backLabel="Back to Shared Files"
- onBack={() => router.push(CONTROL_ROUTES.sharedFiles.root)}
+ backLabel="Back to Agent Files"
+ onBack={() => router.push(CONTROL_ROUTES.agentFiles.root)}
/>
}
>
diff --git a/control-ui/app/shared-filesystems/new/page.tsx b/control-ui/app/shared-filesystems/new/page.tsx
index fad1d1a38..04c274900 100644
--- a/control-ui/app/shared-filesystems/new/page.tsx
+++ b/control-ui/app/shared-filesystems/new/page.tsx
@@ -135,7 +135,7 @@ export default function CreateSharedFileSystemPage() {
try {
await createSharedFileSystem(input)
showToast(`Shared filesystem "${normalizedName}" created.`, { tone: 'success' })
- router.push(CONTROL_ROUTES.sharedFiles.root)
+ router.push(CONTROL_ROUTES.agentFiles.root)
} catch (createError) {
setError(
createError instanceof Error ? createError.message : 'Failed to create SharedFileSystem'
@@ -154,8 +154,8 @@ export default function CreateSharedFileSystemPage() {
icon={<IconSharedFiles />}
title="Create SharedFileSystem"
subtitle="Provision workspace storage that Contexts can mount read-only into agent pods."
- backLabel="Back to shared files"
- onBack={() => router.push(CONTROL_ROUTES.sharedFiles.root)}
+ backLabel="Back to Agent Files"
+ onBack={() => router.push(CONTROL_ROUTES.agentFiles.root)}
backDisabled={saving}
/>
}
@@ -339,7 +339,7 @@ export default function CreateSharedFileSystemPage() {
variant="ghost"
size="sm"
onClick={() =>
- step === 0 ? router.push(CONTROL_ROUTES.sharedFiles.root) : setStep(step - 1)
+ step === 0 ? router.push(CONTROL_ROUTES.agentFiles.root) : setStep(step - 1)
}
disabled={saving}
>
diff --git a/control-ui/app/shared-filesystems/page.tsx b/control-ui/app/shared-filesystems/page.tsx
index 9692f94f6..597e55b2a 100644
--- a/control-ui/app/shared-filesystems/page.tsx
+++ b/control-ui/app/shared-filesystems/page.tsx
@@ -37,7 +37,7 @@ const DELETE_REFRESH_ATTEMPTS = 6
/**
* Lists every SharedFileSystem CRD (always in mcp-host namespace in v1) and
* surfaces the status reported by HCC's sharedFileSystemReconciler. Clicking
- * a row drills into the per-SFS file browser at /shared-filesystems/[name].
+ * a row drills into the per-SFS file browser at the canonical Agent Files detail route.
*
* Admin can create + delete SharedFileSystems from this view; HCC reconciles
* PVC + init Job + workspace-files-controller Deployment + Service +
@@ -160,7 +160,7 @@ export default function SharedFileSystemsPage() {
title={
<>
<IconSharedFiles />
- Shared Files
+ Agent Files
</>
}
subtitle="Workspace volumes that Contexts can mount read-only into agent pods."
@@ -202,7 +202,7 @@ export default function SharedFileSystemsPage() {
title={
<>
<IconSharedFiles />
- {isInitialLoad ? 'Shared Files' : `Shared Files (${filteredItems.length})`}
+ {isInitialLoad ? 'Agent Files' : `Agent Files (${filteredItems.length})`}
</>
}
subtitle="Workspace volumes that Contexts can mount read-only into agent pods."
@@ -211,8 +211,8 @@ export default function SharedFileSystemsPage() {
<SectionSearchInput
value={searchQuery}
onChange={setSearchQuery}
- placeholder="Search shared files"
- ariaLabel="Search shared files"
+ placeholder="Search agent files"
+ ariaLabel="Search agent files"
disabled={isInitialLoad}
/>
<button
@@ -220,14 +220,14 @@ export default function SharedFileSystemsPage() {
className="cu-btn cu-btn--icon cu-btn--toolbar"
onClick={() => void load()}
disabled={loading || isInitialLoad}
- aria-label={loading ? 'Refreshing shared files' : 'Refresh shared files'}
+ aria-label={loading ? 'Refreshing agent files' : 'Refresh agent files'}
>
<IconRefresh className={loading ? 'cu-spin' : undefined} width={18} height={18} />
</button>
<button
type="button"
className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => router.push(CONTROL_ROUTES.sharedFiles.new)}
+ onClick={() => router.push(CONTROL_ROUTES.agentFiles.new)}
disabled={isInitialLoad}
>
New
@@ -279,14 +279,14 @@ export default function SharedFileSystemsPage() {
className="cu-table__row cu-table__row--clickable"
onClick={() => {
if (!isDeleting) {
- router.push(CONTROL_ROUTES.sharedFiles.detail(name))
+ router.push(CONTROL_ROUTES.agentFiles.detail(name))
}
}}
onKeyDown={e => {
if (isDeleting) return
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
- router.push(CONTROL_ROUTES.sharedFiles.detail(name))
+ router.push(CONTROL_ROUTES.agentFiles.detail(name))
}
}}
tabIndex={0}
diff --git a/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx b/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx
index 5814672c8..e0c0d49db 100644
--- a/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx
+++ b/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx
@@ -8,6 +8,7 @@ import { CreateFlowSkeleton } from '@components/CreateFlowSkeleton'
import { CreatePageHeader } from '@components/CreatePageHeader'
import { DashboardLayout } from '@components/DashboardLayout'
import { DetailPageShell } from '@components/DetailPageShell'
+import { LoadingScreen } from '@components/LoadingScreen'
import { RecipeEditor } from '@components/RecipeEditor'
import { RecipeIntegrationsPanel } from '@components/RecipeIntegrationsPanel'
import { RecipeSecretsPanel } from '@components/RecipeSecretsPanel'
@@ -297,17 +298,7 @@ export const dynamic = 'force-dynamic'
export default function WorkflowRecipeDetailPage() {
return (
- <Suspense
- fallback={
- <div className="cu-app-layout">
- <main className="cu-main cu-detail-layout">
- <div className="cu-card">
- <div className="cu-card__body">Loading…</div>
- </div>
- </main>
- </div>
- }
- >
+ <Suspense fallback={<LoadingScreen />}>
<WorkflowRecipeDetailContent />
</Suspense>
)
diff --git a/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx b/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx
index 6a5d0ac27..95c07baeb 100644
--- a/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx
+++ b/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx
@@ -6,6 +6,7 @@ import { useParams, useRouter } from 'next/navigation'
import { AuthGate } from '@components/AuthGate'
import { CreatePageHeader } from '@components/CreatePageHeader'
import { DashboardLayout } from '@components/DashboardLayout'
+import { LoadingScreen } from '@components/LoadingScreen'
import { RecipeStatusContent } from '@components/RecipeStatusContent'
import { IconWorkflow } from '@components/Sidebar/icons'
import { CONTROL_ROUTES } from '@constants/routes'
@@ -15,17 +16,7 @@ export const dynamic = 'force-dynamic'
export default function WorkflowRunDetailPage() {
return (
- <Suspense
- fallback={
- <div className="cu-app-layout">
- <main className="cu-main cu-detail-layout">
- <div className="cu-card">
- <div className="cu-card__body">Loading…</div>
- </div>
- </main>
- </div>
- }
- >
+ <Suspense fallback={<LoadingScreen />}>
<WorkflowRunDetailContent />
</Suspense>
)
diff --git a/control-ui/app/workflow-recipes/page.tsx b/control-ui/app/workflow-recipes/page.tsx
index 2ffa58506..b9a94dd45 100644
--- a/control-ui/app/workflow-recipes/page.tsx
+++ b/control-ui/app/workflow-recipes/page.tsx
@@ -6,6 +6,7 @@ import { useAuth } from '@components/AuthContext'
import { CreateFlowSkeleton } from '@components/CreateFlowSkeleton'
import { CreatePageHeader } from '@components/CreatePageHeader'
import { DashboardLayout } from '@components/DashboardLayout'
+import { LoadingScreen } from '@components/LoadingScreen'
import { RecipeEditor } from '@components/RecipeEditor'
import { RecipesTab } from '@components/RecipesTab'
import { IconWorkflow } from '@components/Sidebar/icons'
@@ -19,17 +20,7 @@ export const dynamic = 'force-dynamic'
export default function WorkflowRecipesPage() {
return (
- <Suspense
- fallback={
- <div className="cu-app-layout">
- <main className="cu-main">
- <div className="cu-card">
- <div className="cu-card__body">Loading…</div>
- </div>
- </main>
- </div>
- }
- >
+ <Suspense fallback={<LoadingScreen />}>
<WorkflowRecipesPageContent />
</Suspense>
)
@@ -90,15 +81,7 @@ function WorkflowRecipesPageContent() {
}, [installerStarting])
if (authState.isLoading) {
- return (
- <div className="cu-app-layout">
- <main className="cu-main">
- <div className="cu-card">
- <div className="cu-card__body">Loading…</div>
- </div>
- </main>
- </div>
- )
+ return <LoadingScreen />
}
if (!authState.isLoggedIn) {
diff --git a/control-ui/components/AuthGate/index.tsx b/control-ui/components/AuthGate/index.tsx
index b3ba255f1..b8808a512 100644
--- a/control-ui/components/AuthGate/index.tsx
+++ b/control-ui/components/AuthGate/index.tsx
@@ -3,6 +3,7 @@
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useAuth } from '@components/AuthContext'
+import { LoadingScreen } from '@components/LoadingScreen'
import { buildControlUiLoginPath, getCurrentControlUiPath } from '@lib/authRedirect'
import type { AuthGateProps } from './types'
@@ -17,15 +18,7 @@ export function AuthGate({ children }: AuthGateProps) {
}, [authState.isLoading, authState.isLoggedIn, router])
if (authState.isLoading) {
- return (
- <div className="cu-app-layout">
- <main className="cu-main">
- <div className="cu-card">
- <div className="cu-card__body">Loading...</div>
- </div>
- </main>
- </div>
- )
+ return <LoadingScreen />
}
if (!authState.isLoggedIn) {
diff --git a/control-ui/components/CostShell/constants.ts b/control-ui/components/CostShell/constants.ts
deleted file mode 100644
index ebc5c1e63..000000000
--- a/control-ui/components/CostShell/constants.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { TabBarOption } from '@components/TabBar/types'
-import type { CostSegment } from './types'
-
-export const COST_TABS: TabBarOption<CostSegment>[] = [
- { value: 'usage', href: '/cost/usage', label: 'Usage' },
- { value: 'llm-prices', href: '/cost/llm-prices', label: 'LLM Prices' },
- { value: 'token-budgets', href: '/cost/token-budgets', label: 'Token Budgets' },
-]
diff --git a/control-ui/components/CostShell/index.tsx b/control-ui/components/CostShell/index.tsx
index 5aae82a5c..d36ca988b 100644
--- a/control-ui/components/CostShell/index.tsx
+++ b/control-ui/components/CostShell/index.tsx
@@ -1,29 +1,15 @@
-'use client'
-
import React from 'react'
import { AuthGate } from '@components/AuthGate'
import { DashboardLayout } from '@components/DashboardLayout'
-import { TabBar } from '@components/TabBar'
-import { COST_TABS } from './constants'
-import type { CostSegment, CostShellProps } from './types'
+import type { CostShellProps } from './types'
-// Shared shell for the Cost & Usage section: sidebar + in-page tab navigation
-// (Usage / LLM Prices / Token Budgets), driven by the active route segment.
-// The section-root list pages render only their content; this shell owns the
-// auth gate, dashboard chrome, and tab bar so every tab stays consistent.
-export function CostShell({ activeSegment, children }: CostShellProps) {
+// Shared shell for Cost & Usage list routes. Child-route navigation lives in
+// the expandable sidebar group, so this shell owns only auth and page chrome.
+export function CostShell({ children }: CostShellProps) {
return (
<AuthGate>
<DashboardLayout>
- <div className="cu-cost-layout">
- <TabBar<CostSegment>
- ariaLabel="Cost and usage sections"
- activeValue={activeSegment}
- className="cu-tabs--flush"
- options={COST_TABS}
- />
- {children}
- </div>
+ <div className="cu-cost-layout">{children}</div>
</DashboardLayout>
</AuthGate>
)
diff --git a/control-ui/components/CostShell/types.ts b/control-ui/components/CostShell/types.ts
index 0c6f65d0b..0543ad8e0 100644
--- a/control-ui/components/CostShell/types.ts
+++ b/control-ui/components/CostShell/types.ts
@@ -1,8 +1,5 @@
import type { ReactNode } from 'react'
-export type CostSegment = 'usage' | 'llm-prices' | 'token-budgets'
-
export type CostShellProps = {
- activeSegment: CostSegment
children: ReactNode
}
diff --git a/control-ui/components/DashboardLayout.tsx b/control-ui/components/DashboardLayout.tsx
index 67f2d8362..0f37f63e9 100644
--- a/control-ui/components/DashboardLayout.tsx
+++ b/control-ui/components/DashboardLayout.tsx
@@ -31,17 +31,17 @@ export function DashboardLayout({ children, isDetailPage = false }: DashboardLay
if (isControlRouteSection(pathname, CONTROL_ROUTES.plugins.root)) {
return 'workflow-recipes'
}
- if (isControlRouteSection(pathname, CONTROL_ROUTES.outputs.base)) {
- return 'files'
+ if (isControlRouteSection(pathname, CONTROL_ROUTES.agentOutputs.base)) {
+ return 'directories'
}
if (isControlRouteSection(pathname, CONTROL_ROUTES.connectors.root)) {
return 'mcp-servers'
}
- if (isControlRouteSection(pathname, CONTROL_ROUTES.sharedFiles.root)) {
- return 'files'
+ if (isControlRouteSection(pathname, CONTROL_ROUTES.agentFiles.root)) {
+ return 'directories'
}
- if (isControlRouteSection(pathname, CONTROL_ROUTES.globalFiles)) {
- return 'files'
+ if (isControlRouteSection(pathname, CONTROL_ROUTES.globalFileSystem)) {
+ return 'directories'
}
if (isControlRouteSection(pathname, CONTROL_ROUTES.externalChannels.root)) {
return 'communication-channels'
diff --git a/control-ui/components/GfsGrantPanel.tsx b/control-ui/components/GfsGrantPanel.tsx
index 47261a060..ddb2cc7a5 100644
--- a/control-ui/components/GfsGrantPanel.tsx
+++ b/control-ui/components/GfsGrantPanel.tsx
@@ -1,42 +1,57 @@
'use client'
-import { useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useConfirmDialog } from '@components/ConfirmDialog'
import { GfsPermissionDropdown } from '@components/GfsPermissionDropdown'
import { GfsSubjectPicker } from '@components/GfsSubjectPicker'
import type { SelectionDropdownOption } from '@components/SelectionDropdown/types'
import { useToast } from '@components/Toast'
+import { IconTrash } from '@components/icons'
import { Button, CheckboxField } from '@components/ui'
+import { GFS_MAX_BULK_SUBJECTS } from '@constants/gfsGrantSubjects'
import {
type AdminUser,
+ type GfsBulkShareSubjectInput,
+ type GfsGrantError,
type HostResource,
type TeamListItem,
type WorkflowRecipeResource,
+ deleteGfsGrant,
+ deleteGfsShare,
getAdminTeams,
getAdminUsers,
+ getGfsGrants,
+ getGfsShares,
getHosts,
getRecipes,
+ postGfsShare,
putGfsGrant,
} from '@lib/api'
-import type { GfsGrantPanelProps, GfsGrantSubjectType } from './GfsGrantPanel.types'
-import { buildGfsGrantSubjectOptions, toGfsSubjectInput } from './gfsGrantSubjectOptions'
+import type { GfsExistingAccessItem, GfsGrantPanelProps } from './GfsGrantPanel.types'
+import {
+ buildGfsBulkSubjectOptions,
+ summarizeGfsBulkSubjectTypes,
+ toGfsBulkSubjectInputs,
+} from './gfsGrantSubjectOptions'
/**
* P4-S07 — Operator delegation panel for the Global File System. The operator
- * (Control UI / Admin-JWT plane) seeds Layer-1/2 grants on a selected resource.
- * Reuses the existing grant write API (PUT /api/v1/gfs/grants) — no new
- * authority. The no-escalation / authority engine runs server-side; this panel
- * surfaces the machine error code (e.g. escalation_rejected) on rejection.
- * Composes the shared `components/ui` primitives per the control-ui frontend
- * rules.
+ * (Control UI / Admin-JWT plane) seeds Layer-1/2 grants and creates URI shares
+ * on a selected resource. Bulk actions accept users, teams, and canonical host
+ * subjects; the intrinsic operator remains a singular request. The existing
+ * server-side authority and no-escalation policies remain authoritative.
*/
const PERMISSION_BITS = ['read', 'write', 'delete', 'manage_acl', 'share'] as const
+const HOST_PERMISSION_BITS = ['read', 'write'] as const
+const OPERATOR_VALUE = 'operator'
const DRIVE = 'main'
-type GrantSubjectSelection = {
- option: SelectionDropdownOption & { id: string; badge: string }
- subjectType: GfsGrantSubjectType
+const OPERATOR_OPTION: SelectionDropdownOption = {
+ value: OPERATOR_VALUE,
+ label: 'Operator',
+ description: 'Intrinsic cluster operator',
+ badge: 'Operator',
}
export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Element {
@@ -48,13 +63,58 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
const [recipes, setRecipes] = useState<WorkflowRecipeResource[]>([])
const [directoryLoading, setDirectoryLoading] = useState(true)
const [directoryError, setDirectoryError] = useState('')
- const [subjectValue, setSubjectValue] = useState('')
+ const [selectedValues, setSelectedValues] = useState<string[]>([])
+ const [selectionError, setSelectionError] = useState('')
const [bits, setBits] = useState<string[]>([])
const [includeDescendants, setIncludeDescendants] = useState(resource.kind === 'directory')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
+ const [existingAccess, setExistingAccess] = useState<GfsExistingAccessItem[]>([])
+ const [existingAccessLoading, setExistingAccessLoading] = useState(true)
+ const [existingAccessError, setExistingAccessError] = useState('')
+ const existingAccessRequest = useRef(0)
+ const existingAccessController = useRef<AbortController | null>(null)
const canIncludeDescendants = resource.kind === 'directory'
+ const loadExistingAccess = useCallback(async () => {
+ existingAccessController.current?.abort()
+ const requestId = ++existingAccessRequest.current
+ const controller = new AbortController()
+ existingAccessController.current = controller
+ setExistingAccessLoading(true)
+ setExistingAccessError('')
+ try {
+ const [grantResult, shareResult] = await Promise.all([
+ getGfsGrants(resource.resourceId, DRIVE, controller.signal),
+ getGfsShares(resource.resourceId, DRIVE, controller.signal),
+ ])
+ if (requestId !== existingAccessRequest.current) return
+ setExistingAccess([
+ ...grantResult.items.map(item => ({ ...item, kind: 'grant' as const })),
+ ...shareResult.items.map(item => ({ ...item, kind: 'share' as const })),
+ ])
+ } catch (caught) {
+ if (requestId !== existingAccessRequest.current) return
+ setExistingAccessError(
+ caught instanceof Error ? caught.message : 'Failed to load existing access'
+ )
+ } finally {
+ if (requestId === existingAccessRequest.current) {
+ existingAccessController.current = null
+ setExistingAccessLoading(false)
+ }
+ }
+ }, [resource.resourceId])
+
+ useEffect(() => {
+ void loadExistingAccess()
+ return () => {
+ existingAccessController.current?.abort()
+ existingAccessController.current = null
+ existingAccessRequest.current += 1
+ }
+ }, [loadExistingAccess])
+
useEffect(() => {
let active = true
@@ -101,79 +161,175 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
setIncludeDescendants(resource.kind === 'directory')
}, [resource.kind, resource.resourceId])
- const subjectSelections = useMemo<GrantSubjectSelection[]>(() => {
- const selections: GrantSubjectSelection[] = []
- const addOptions = (subjectType: GfsGrantSubjectType) => {
- const options = buildGfsGrantSubjectOptions({
- subjectType,
- users,
- teams,
- hosts,
- recipes,
- })
- selections.push(...options.map(option => ({ option, subjectType })))
+ const bulkSubjectOptions = useMemo(
+ () => buildGfsBulkSubjectOptions({ users, teams, hosts, recipes }),
+ [hosts, recipes, teams, users]
+ )
+ const subjectOptions = useMemo<SelectionDropdownOption[]>(
+ () => [...bulkSubjectOptions, OPERATOR_OPTION],
+ [bulkSubjectOptions]
+ )
+ const operatorSelected = selectedValues.includes(OPERATOR_VALUE)
+ const selectedBulkOptions = useMemo(
+ () =>
+ selectedValues
+ .map(value => bulkSubjectOptions.find(option => option.value === value))
+ .filter(option => option !== undefined),
+ [bulkSubjectOptions, selectedValues]
+ )
+ const selectedSubjects = useMemo(
+ () => toGfsBulkSubjectInputs(selectedBulkOptions),
+ [selectedBulkOptions]
+ )
+ const hasHost = selectedSubjects.some(subject => subject.type === 'host')
+ const visiblePermissionBits = hasHost ? HOST_PERMISSION_BITS : PERMISSION_BITS
+ const subjectValid = operatorSelected || selectedSubjects.length > 0
+ const canCreateShare =
+ operatorSelected || selectedSubjects.every(subject => subject.type !== 'host')
+ const canSubmit = subjectValid && bits.length > 0 && !busy
+
+ function changeSelectedSubjects(nextValues: string[]) {
+ const addingOperator = nextValues.includes(OPERATOR_VALUE) && !operatorSelected
+ if (addingOperator) {
+ setSelectedValues([OPERATOR_VALUE])
+ setSelectionError('')
+ return
}
- addOptions('user')
- addOptions('team')
- addOptions('firstPartyAgent')
- addOptions('workflowPlugin')
- selections.push({
- subjectType: 'operator',
- option: {
- value: 'operator',
- id: '',
- label: 'Operator',
- description: 'Intrinsic cluster operator',
- badge: 'Operator',
- },
- })
- return selections
- }, [hosts, recipes, teams, users])
- const subjectOptions = subjectSelections.map(selection => selection.option)
- const selectedSelection =
- subjectSelections.find(selection => selection.option.value === subjectValue) ?? null
- const canSubmit = selectedSelection !== null && bits.length > 0 && !busy
-
- function subjectLabel(): string {
- if (!selectedSelection) return 'the selected subject'
- if (selectedSelection.subjectType === 'operator') return 'operator'
- return `${selectedSelection.option.badge.toLowerCase()} ${selectedSelection.option.label}`
+ const bulkValues = nextValues.filter(value => value !== OPERATOR_VALUE)
+ if (bulkValues.length > GFS_MAX_BULK_SUBJECTS) {
+ setSelectionError(`You can select up to ${GFS_MAX_BULK_SUBJECTS} subjects.`)
+ return
+ }
+
+ const nextOptions = bulkValues
+ .map(value => bulkSubjectOptions.find(option => option.value === value))
+ .filter(option => option !== undefined)
+ if (nextOptions.some(option => option.subject.type === 'host')) {
+ setBits(current =>
+ current.filter(bit => HOST_PERMISSION_BITS.includes(bit as 'read' | 'write'))
+ )
+ }
+ setSelectionError('')
+ setSelectedValues(bulkValues)
+ }
+
+ function confirmationMessage(kind: 'grant' | 'share'): string {
+ const action = kind === 'grant' ? 'Grant' : 'Share with'
+ const recipients = operatorSelected
+ ? '1 operator'
+ : `${selectedSubjects.length} subjects (${summarizeGfsBulkSubjectTypes(selectedSubjects)})`
+ const scope = includeDescendants ? 'resource and descendants' : 'resource only'
+ return `${action} ${recipients} [${bits.join(', ')}] on "${resource.name}". Scope: ${scope}.`
}
- async function submit() {
+ async function submit(kind: 'grant' | 'share') {
setError('')
- if (!selectedSelection || bits.length === 0) {
+ if (!subjectValid || bits.length === 0) {
setError('subject_and_permissions_required')
return
}
- const grantSelection = selectedSelection
const confirmed = await confirm({
- title: 'Grant access?',
- message: `Give ${subjectLabel()} [${bits.join(', ')}] on "${resource.name}"?`,
- confirmLabel: 'Grant',
+ title: kind === 'grant' ? 'Grant access?' : 'Create share?',
+ message: confirmationMessage(kind),
+ confirmLabel: kind === 'grant' ? 'Grant' : 'Create share',
})
if (!confirmed) return
setBusy(true)
try {
- const body = {
- drive: DRIVE,
- resourceId: resource.resourceId,
- subject: toGfsSubjectInput(grantSelection.subjectType, grantSelection.option),
- permissions: bits,
+ if (operatorSelected) {
+ const body = {
+ drive: DRIVE,
+ resourceId: resource.resourceId,
+ subject: { type: 'operator' as const },
+ permissions: bits,
+ }
+ if (kind === 'grant') await putGfsGrant({ ...body, inherit: includeDescendants })
+ else await postGfsShare({ ...body, includeDescendants })
+ } else {
+ const body = {
+ drive: DRIVE,
+ resourceId: resource.resourceId,
+ subjects: selectedSubjects,
+ permissions: bits,
+ }
+ if (kind === 'grant') {
+ await putGfsGrant({ ...body, inherit: includeDescendants })
+ } else {
+ const shareSubjects = selectedSubjects.filter(
+ (subject): subject is GfsBulkShareSubjectInput => subject.type !== 'host'
+ )
+ if (shareSubjects.length !== selectedSubjects.length) throw new Error('subjects_invalid')
+ await postGfsShare({ ...body, subjects: shareSubjects, includeDescendants })
+ }
}
- await putGfsGrant({ ...body, inherit: includeDescendants })
- showToast('Grant saved.', { tone: 'success' })
- // Reset the whole form — leaving the subject populated risks a mis-targeted
- // second grant on the next click.
+ showToast(kind === 'grant' ? 'Grant saved.' : 'Share created.', { tone: 'success' })
+ await loadExistingAccess()
setBits([])
- setSubjectValue('')
+ setSelectedValues([])
+ setSelectionError('')
setIncludeDescendants(resource.kind === 'directory')
} catch (e) {
- // Surface the machine code (e.g. escalation_rejected, resource_invalid)
- // so the operator sees the precise verdict — never swallow it.
- const code = (e as { code?: string }).code
- setError(code || (e instanceof Error ? e.message : String(e)))
+ const grantError = e as GfsGrantError
+ const verdict = grantError.code
+ ? grantError.serverMessage && grantError.serverMessage !== grantError.code
+ ? `${grantError.code}: ${grantError.serverMessage}`
+ : grantError.code
+ : e instanceof Error
+ ? e.message
+ : String(e)
+ const invalidIndexes = grantError.invalidIndexes
+ setError(
+ invalidIndexes && invalidIndexes.length > 0
+ ? `${verdict} (invalid indexes: ${invalidIndexes.join(', ')})`
+ : verdict
+ )
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ function subjectLabel(item: GfsExistingAccessItem): string {
+ if (item.subject.type === 'operator') return 'Operator'
+ const option = bulkSubjectOptions.find(
+ candidate =>
+ candidate.subject.type === item.subject.type && candidate.subject.id === item.subject.id
+ )
+ if (option) return option.label
+ const typeLabel =
+ item.subject.type === 'host'
+ ? 'Agent or workflow'
+ : item.subject.type.charAt(0).toUpperCase() + item.subject.type.slice(1)
+ return item.subject.id ? `${typeLabel} · ${item.subject.id}` : typeLabel
+ }
+
+ async function revokeAccess(item: GfsExistingAccessItem) {
+ const label = subjectLabel(item)
+ const confirmed = await confirm({
+ title: 'Remove access?',
+ message: `Remove ${item.kind} access for ${label} from "${resource.name}"?`,
+ confirmLabel: 'Remove access',
+ tone: 'danger',
+ })
+ if (!confirmed) return
+ setBusy(true)
+ setError('')
+ try {
+ if (item.kind === 'grant') await deleteGfsGrant(item.id)
+ else await deleteGfsShare(item.id)
+ showToast('Access removed.', { tone: 'success' })
+ await loadExistingAccess()
+ } catch (caught) {
+ const accessError = caught as GfsGrantError
+ if (
+ accessError.status === 404 &&
+ (accessError.code === 'grant_not_found' || accessError.code === 'share_not_found')
+ ) {
+ showToast('Access was already removed.', { tone: 'success' })
+ await loadExistingAccess()
+ return
+ }
+ setError(caught instanceof Error ? caught.message : 'Failed to remove access')
} finally {
setBusy(false)
}
@@ -185,22 +341,85 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
<GfsSubjectPicker
disabled={busy}
loading={directoryLoading}
- onChange={setSubjectValue}
+ onChange={changeSelectedSubjects}
options={subjectOptions}
- value={subjectValue}
+ value={selectedValues}
/>
<GfsPermissionDropdown
disabled={busy}
onChange={setBits}
- permissions={PERMISSION_BITS}
+ permissions={visiblePermissionBits}
value={bits}
/>
</div>
+ {selectionError ? (
+ <p role="alert" className="cu-field__error">
+ {selectionError}
+ </p>
+ ) : null}
{directoryError ? (
<p role="alert" className="cu-field__error">
{directoryError}
</p>
) : null}
+ {hasHost ? (
+ <p className="cu-field__hint">
+ Host selections are limited to read and write in Control UI. Incompatible permissions were
+ removed.
+ </p>
+ ) : null}
+ <section className="cu-gfs-existing-access" aria-label="Existing access">
+ <div className="cu-gfs-existing-access__header">
+ <h3>Existing access</h3>
+ <p>Direct grants and shares configured on this resource.</p>
+ </div>
+ {existingAccessLoading ? (
+ <p className="cu-gfs-existing-access__empty" role="status">
+ Loading existing access…
+ </p>
+ ) : existingAccessError ? (
+ <div className="cu-gfs-existing-access__error">
+ <p role="alert" className="cu-field__error">
+ {existingAccessError}
+ </p>
+ <Button size="sm" disabled={busy} onClick={() => void loadExistingAccess()}>
+ Retry
+ </Button>
+ </div>
+ ) : existingAccess.length === 0 ? (
+ <p className="cu-gfs-existing-access__empty">No direct access configured.</p>
+ ) : (
+ <ul className="cu-gfs-existing-access__list">
+ {existingAccess.map(item => {
+ const label = subjectLabel(item)
+ const coversDescendants =
+ item.kind === 'grant' ? item.inherit : item.includeDescendants
+ return (
+ <li className="cu-gfs-existing-access__item" key={`${item.kind}:${item.id}`}>
+ <div className="cu-gfs-existing-access__copy">
+ <span className="cu-gfs-existing-access__subject">{label}</span>
+ <span className="cu-gfs-existing-access__detail">
+ {item.kind === 'grant' ? 'Grant' : 'Share'} · {item.permissions.join(', ')} ·{' '}
+ {coversDescendants ? 'resource and descendants' : 'resource only'}
+ </span>
+ </div>
+ <Button
+ aria-label={`Remove ${item.kind} access for ${label}`}
+ title={`Remove ${item.kind} access for ${label}`}
+ variant="danger"
+ size="sm"
+ disabled={busy}
+ onClick={() => void revokeAccess(item)}
+ >
+ <IconTrash width={15} height={15} />
+ Remove
+ </Button>
+ </li>
+ )
+ })}
+ </ul>
+ )}
+ </section>
{canIncludeDescendants ? (
<CheckboxField
className="cu-gfs-grant__scope"
@@ -212,9 +431,12 @@ export function GfsGrantPanel({ resource }: GfsGrantPanelProps): React.JSX.Eleme
/>
) : null}
<div className="cu-gfs-grant__actions">
- <Button variant="primary" disabled={!canSubmit} onClick={() => submit()}>
+ <Button variant="primary" disabled={!canSubmit} onClick={() => submit('grant')}>
Grant access
</Button>
+ <Button disabled={!canSubmit || !canCreateShare} onClick={() => submit('share')}>
+ Create share
+ </Button>
</div>
{error ? (
<p role="alert" className="cu-field__error">
diff --git a/control-ui/components/GfsGrantPanel.types.ts b/control-ui/components/GfsGrantPanel.types.ts
index 03d33ca4b..1e5a69b00 100644
--- a/control-ui/components/GfsGrantPanel.types.ts
+++ b/control-ui/components/GfsGrantPanel.types.ts
@@ -1,3 +1,5 @@
+import type { GfsBulkGrantSubjectInput, GfsGrantListItem, GfsShareListItem } from '@lib/api'
+
export type GfsGrantSubjectType =
| 'user'
| 'team'
@@ -5,12 +7,17 @@ export type GfsGrantSubjectType =
| 'firstPartyAgent'
| 'workflowPlugin'
+export type GfsGrantMode = 'subjects' | 'operator'
+
+export type GfsBulkSubjectInput = GfsBulkGrantSubjectInput
+
export type GfsGrantSubjectOption = {
value: string
id: string
label: string
description?: string
badge: string
+ subject: GfsBulkSubjectInput
}
export type GfsGrantResource = {
@@ -23,3 +30,7 @@ export type GfsGrantResource = {
export interface GfsGrantPanelProps {
resource: GfsGrantResource
}
+
+export type GfsExistingAccessItem =
+ | ({ kind: 'grant' } & GfsGrantListItem)
+ | ({ kind: 'share' } & GfsShareListItem)
diff --git a/control-ui/components/GfsSubjectPicker/index.tsx b/control-ui/components/GfsSubjectPicker/index.tsx
index 2b6a1b3ba..eb9c1f30a 100644
--- a/control-ui/components/GfsSubjectPicker/index.tsx
+++ b/control-ui/components/GfsSubjectPicker/index.tsx
@@ -27,14 +27,18 @@ export function GfsSubjectPicker({
const [query, setQuery] = useState('')
const rootRef = useRef<HTMLDivElement | null>(null)
const selected = useMemo(
- () => options.find(option => option.value === value) ?? null,
+ () => value.map(item => options.find(option => option.value === item)).filter(Boolean),
[options, value]
)
const availableOptions = useMemo(
- () => options.filter(option => option.value !== value && optionMatches(option, query)),
+ () => options.filter(option => !value.includes(option.value) && optionMatches(option, query)),
[options, query, value]
)
+ function focusInput() {
+ rootRef.current?.querySelector<HTMLInputElement>('.cu-gfs-subject-picker__input')?.focus()
+ }
+
useEffect(() => {
if (!open) return
@@ -59,15 +63,15 @@ export function GfsSubjectPicker({
}, [disabled])
function selectSubject(option: SelectionDropdownOption) {
- onChange(option.value)
+ onChange([...value, option.value])
setQuery('')
- setOpen(false)
+ focusInput()
}
- function clearSubject() {
- onChange('')
+ function clearSubject(subjectValue: string) {
+ onChange(value.filter(item => item !== subjectValue))
setQuery('')
- rootRef.current?.querySelector<HTMLInputElement>('.cu-gfs-subject-picker__input')?.focus()
+ focusInput()
}
return (
@@ -76,27 +80,29 @@ export function GfsSubjectPicker({
aria-label="Grant subject"
className={`cu-gfs-subject-picker__field${open ? ' is-open' : ''}`}
>
- {selected ? (
- <span className="cu-gfs-subject-picker__chip">
- <span
- className={`cu-gfs-subject-picker__avatar cu-gfs-subject-picker__avatar--${selected.badge?.toLowerCase()}`}
- aria-hidden="true"
- >
- {selected.label.charAt(0).toUpperCase()}
+ {selected.map(subject =>
+ subject ? (
+ <span className="cu-gfs-subject-picker__chip" key={subject.value}>
+ <span
+ className={`cu-gfs-subject-picker__avatar cu-gfs-subject-picker__avatar--${subject.badge?.toLowerCase()}`}
+ aria-hidden="true"
+ >
+ {subject.label.charAt(0).toUpperCase()}
+ </span>
+ <span className="cu-gfs-subject-picker__chip-label">{subject.label}</span>
+ <Button
+ aria-label={`Remove ${subject.label}`}
+ className="cu-gfs-subject-picker__chip-remove"
+ disabled={disabled}
+ onClick={() => clearSubject(subject.value)}
+ size="sm"
+ variant="ghost"
+ >
+ <IconX width={12} height={12} />
+ </Button>
</span>
- <span className="cu-gfs-subject-picker__chip-label">{selected.label}</span>
- <Button
- aria-label={`Remove ${selected.label}`}
- className="cu-gfs-subject-picker__chip-remove"
- disabled={disabled}
- onClick={clearSubject}
- size="sm"
- variant="ghost"
- >
- <IconX width={12} height={12} />
- </Button>
- </span>
- ) : null}
+ ) : null
+ )}
<TextInput
aria-autocomplete="list"
aria-controls="cu-gfs-subject-options"
@@ -110,7 +116,7 @@ export function GfsSubjectPicker({
setOpen(true)
}}
onFocus={() => setOpen(true)}
- placeholder={selected ? '' : SUBJECT_PICKER_LABEL}
+ placeholder={selected.length > 0 ? '' : SUBJECT_PICKER_LABEL}
role="combobox"
value={query}
/>
@@ -119,7 +125,7 @@ export function GfsSubjectPicker({
{open ? (
<div
aria-label="Available grant subjects"
- aria-multiselectable="false"
+ aria-multiselectable="true"
className="cu-gfs-subject-picker__menu"
id="cu-gfs-subject-options"
role="listbox"
@@ -128,8 +134,8 @@ export function GfsSubjectPicker({
<span className="cu-gfs-subject-picker__empty">Loading subjects…</span>
) : availableOptions.length === 0 ? (
<span className="cu-gfs-subject-picker__empty">
- {options.length === 1 && selected
- ? 'The available subject is selected.'
+ {options.length > 0 && selected.length === options.length
+ ? 'All available subjects are selected.'
: 'No subjects found.'}
</span>
) : (
diff --git a/control-ui/components/GfsSubjectPicker/types.ts b/control-ui/components/GfsSubjectPicker/types.ts
index 0af89ece8..48fb42b9a 100644
--- a/control-ui/components/GfsSubjectPicker/types.ts
+++ b/control-ui/components/GfsSubjectPicker/types.ts
@@ -3,7 +3,7 @@ import type { SelectionDropdownOption } from '@components/SelectionDropdown/type
export interface GfsSubjectPickerProps {
disabled?: boolean
loading?: boolean
- onChange: (next: string) => void
+ onChange: (next: string[]) => void
options: SelectionDropdownOption[]
- value: string
+ value: string[]
}
diff --git a/control-ui/components/LoadingScreen/index.tsx b/control-ui/components/LoadingScreen/index.tsx
new file mode 100644
index 000000000..31eb9af17
--- /dev/null
+++ b/control-ui/components/LoadingScreen/index.tsx
@@ -0,0 +1,32 @@
+import Image from 'next/image'
+
+export function LoadingScreen() {
+ return (
+ <main className="cu-loading-screen">
+ <section
+ className="cu-loading-screen__surface"
+ role="status"
+ aria-label="Loading Control UI"
+ aria-live="polite"
+ >
+ <div className="cu-loading-screen__brand">
+ <Image
+ className="cu-loading-screen__mark"
+ src="/brand/logo.svg"
+ alt=""
+ width={44}
+ height={44}
+ aria-hidden="true"
+ priority
+ />
+ <span className="cu-loading-screen__brand-copy">
+ <span className="cu-loading-screen__title">Evenfire</span>
+ <span className="cu-loading-screen__subtitle">Control UI</span>
+ </span>
+ </div>
+ <div className="cu-loading-screen__progress" aria-hidden="true" />
+ <p className="cu-loading-screen__status">Loading session…</p>
+ </section>
+ </main>
+ )
+}
diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsx
index 623989c4c..e479fa2ed 100644
--- a/control-ui/components/RecipeEditor.tsx
+++ b/control-ui/components/RecipeEditor.tsx
@@ -197,7 +197,7 @@ const TEMPLATES: RecipeTemplate[] = [
{
id: 'mongodb-mcp',
type: 'deployment',
- image: 'us-central1-docker.pkg.dev/your-gcp-project/clerum/mcp-mongodb:latest',
+ image: 'us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/mcp-mongodb:latest',
port: 3000,
transport: { type: 'streamableHttp' },
envSecret: {
diff --git a/control-ui/components/Sidebar/constants.tsx b/control-ui/components/Sidebar/constants.tsx
index a24595dc6..67713bfaf 100644
--- a/control-ui/components/Sidebar/constants.tsx
+++ b/control-ui/components/Sidebar/constants.tsx
@@ -1,9 +1,9 @@
+import { IconPaperclip } from '@components/icons'
import { CONTROL_ROUTES } from '@constants/routes'
import {
IconAdministrativeTrace,
IconBroadcast,
IconCable,
- IconFolder,
IconGroupWork,
IconInfrastructureTrace,
IconKey,
@@ -57,30 +57,34 @@ export const SIDEBAR_TABS: Record<SidebarTab, SidebarItem> = {
},
],
},
- 'communication-channels': {
- label: 'External Channels',
- href: CONTROL_ROUTES.externalChannels.root,
- icon: <IconBroadcast />,
- },
- files: {
- label: 'Files',
- href: CONTROL_ROUTES.globalFiles,
- icon: <IconFolder />,
+ directories: {
+ label: 'Directories',
+ href: CONTROL_ROUTES.agentFiles.root,
+ icon: <IconPaperclip />,
children: [
- { label: 'Global Files', href: CONTROL_ROUTES.globalFiles, icon: <IconFolder /> },
{
- label: 'Outputs',
- href: CONTROL_ROUTES.outputs.root,
+ label: 'Agent Files',
+ href: CONTROL_ROUTES.agentFiles.root,
+ icon: <IconSharedFiles />,
+ },
+ {
+ label: 'Agent Outputs',
+ href: CONTROL_ROUTES.agentOutputs.root,
icon: <IconOutputs />,
- matchPath: CONTROL_ROUTES.outputs.base,
+ matchPath: CONTROL_ROUTES.agentOutputs.base,
},
{
- label: 'Shared Files',
- href: CONTROL_ROUTES.sharedFiles.root,
- icon: <IconSharedFiles />,
+ label: 'Global File System',
+ href: CONTROL_ROUTES.globalFileSystem,
+ icon: <IconPaperclip />,
},
],
},
+ 'communication-channels': {
+ label: 'External Channels',
+ href: CONTROL_ROUTES.externalChannels.root,
+ icon: <IconBroadcast />,
+ },
'llm-models': {
label: 'LLM Models',
href: CONTROL_ROUTES.llmModels.root,
@@ -116,26 +120,26 @@ export const SIDEBAR_TABS: Record<SidebarTab, SidebarItem> = {
icon: <IconWorkflow />,
hidden: true,
children: [
- {
- label: 'Dashboard',
- href: CONTROL_ROUTES.traces.operations,
- icon: <IconTraceDashboard />,
- },
- {
- label: 'Run replay',
- href: CONTROL_ROUTES.traces.root,
- icon: <IconRunReplay />,
- },
{
label: 'Administrative',
href: CONTROL_ROUTES.traces.administrative,
icon: <IconAdministrativeTrace />,
},
+ {
+ label: 'Dashboard',
+ href: CONTROL_ROUTES.traces.operations,
+ icon: <IconTraceDashboard />,
+ },
{
label: 'Infrastructure',
href: CONTROL_ROUTES.traces.infrastructure,
icon: <IconInfrastructureTrace />,
},
+ {
+ label: 'Run replay',
+ href: CONTROL_ROUTES.traces.root,
+ icon: <IconRunReplay />,
+ },
],
},
'profile-admin': {
diff --git a/control-ui/components/Sidebar/types.ts b/control-ui/components/Sidebar/types.ts
index f02ebbd23..d79b48224 100644
--- a/control-ui/components/Sidebar/types.ts
+++ b/control-ui/components/Sidebar/types.ts
@@ -4,7 +4,7 @@ export type SidebarTab =
| 'hosts'
| 'contexts'
| 'mcp-servers'
- | 'files'
+ | 'directories'
| 'communication-channels'
| 'llm-secrets'
| 'llm-models'
diff --git a/control-ui/components/__tests__/CostSection.test.tsx b/control-ui/components/__tests__/CostSection.test.tsx
index b0873a7ee..7952a3523 100644
--- a/control-ui/components/__tests__/CostSection.test.tsx
+++ b/control-ui/components/__tests__/CostSection.test.tsx
@@ -2,13 +2,13 @@ import type React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import CostLayout from '../../app/cost/layout'
-import { COST_TABS } from '../CostShell/constants'
-import type { CostSegment } from '../CostShell/types'
import { DashboardLayout } from '../DashboardLayout'
import { Sidebar } from '../Sidebar'
-import { TabBar } from '../TabBar'
-const navigationState = vi.hoisted(() => ({ pathname: '/cost/usage', segments: [] as string[] }))
+const navigationState = vi.hoisted(() => ({
+ pathname: '/cost-and-usage/usage',
+ segments: [] as string[],
+}))
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
@@ -22,38 +22,10 @@ vi.mock('../AuthContext', () => ({
afterEach(() => {
cleanup()
- navigationState.pathname = '/cost/usage'
+ navigationState.pathname = '/cost-and-usage/usage'
navigationState.segments = []
})
-describe('Cost & Usage tab bar', () => {
- it('exposes the three tabs in order pointing at their segment routes', () => {
- expect(COST_TABS.map(tab => [tab.value, tab.href, tab.label])).toEqual([
- ['usage', '/cost/usage', 'Usage'],
- ['llm-prices', '/cost/llm-prices', 'LLM Prices'],
- ['token-budgets', '/cost/token-budgets', 'Token Budgets'],
- ])
- })
-
- it('marks only the active tab as selected, by segment', () => {
- render(
- <TabBar<CostSegment>
- ariaLabel="Cost and usage sections"
- activeValue="llm-prices"
- options={COST_TABS}
- />
- )
- const active = screen.getByRole('tab', { name: 'LLM Prices' })
- expect(active).toHaveAttribute('data-active', 'true')
- expect(active).toHaveAttribute('aria-current', 'page')
- expect(screen.getByRole('tab', { name: 'Usage' })).toHaveAttribute('data-active', 'false')
- expect(screen.getByRole('tab', { name: 'Token Budgets' })).toHaveAttribute(
- 'data-active',
- 'false'
- )
- })
-})
-
describe('CostLayout segment gating', () => {
function renderLayoutForSegments(segments: string[]) {
navigationState.segments = segments
@@ -65,13 +37,10 @@ describe('CostLayout segment gating', () => {
}
it.each([['usage'], ['llm-prices'], ['token-budgets']])(
- 'wraps the %s list root in the shared tab shell',
+ 'wraps the %s list root without rendering duplicate section tabs',
segment => {
renderLayoutForSegments([segment])
- // Tab shell present with all three tabs, plus the section content.
- expect(screen.getByRole('tab', { name: 'Usage' })).toBeInTheDocument()
- expect(screen.getByRole('tab', { name: 'LLM Prices' })).toBeInTheDocument()
- expect(screen.getByRole('tab', { name: 'Token Budgets' })).toBeInTheDocument()
+ expect(screen.queryByRole('tab')).toBeNull()
expect(screen.getByText('section content')).toBeInTheDocument()
}
)
@@ -100,28 +69,52 @@ describe('Cost & Usage sidebar entry', () => {
)
}
- it('renders a single consolidated entry pointing at /cost/usage', () => {
+ it('renders one expandable group with canonical child routes', () => {
render(<Sidebar currentTab="cost" />)
- const link = screen.getByRole('link', { name: /Cost & Usage/ })
- expect(link).toHaveAttribute('href', '/cost/usage')
- // The old split entries are gone.
- expect(screen.queryByRole('link', { name: /^Usage$/ })).toBeNull()
- expect(screen.queryByRole('link', { name: /LLM Prices/ })).toBeNull()
- expect(screen.queryByRole('link', { name: /Token Budgets/ })).toBeNull()
+ const group = screen.getByRole('button', { name: /Cost & Usage/ })
+ expect(group).toHaveAttribute('aria-expanded', 'true')
+ expect(screen.getByRole('link', { name: /^Usage$/ })).toHaveAttribute(
+ 'href',
+ '/cost-and-usage/usage'
+ )
+ expect(screen.getByRole('link', { name: /LLM Prices/ })).toHaveAttribute(
+ 'href',
+ '/cost-and-usage/llm-prices'
+ )
+ expect(screen.getByRole('link', { name: /Token Budgets/ })).toHaveAttribute(
+ 'href',
+ '/cost-and-usage/token-budgets'
+ )
})
- it.each(['/cost/usage', '/cost/llm-prices', '/cost/token-budgets/abc/edit'])(
- 'stays active for any /cost/* route (%s)',
- pathname => {
- renderLayoutAt(pathname)
- const link = screen.getByRole('link', { name: /Cost & Usage/ })
- expect(link).toHaveAttribute('aria-current', 'page')
- }
- )
+ it.each([
+ '/cost-and-usage/usage',
+ '/cost-and-usage/llm-prices',
+ '/cost-and-usage/token-budgets/abc/edit',
+ ])('stays active for any /cost/* route (%s)', pathname => {
+ renderLayoutAt(pathname)
+ const group = screen.getByRole('button', { name: /Cost & Usage/ })
+ expect(group).toHaveAttribute('data-active', 'true')
+ expect(group).toHaveAttribute('aria-expanded', 'true')
+ })
+
+ it.each([
+ ['/cost-and-usage/usage', 'Usage'],
+ ['/cost-and-usage/llm-prices/new', 'LLM Prices'],
+ ['/cost-and-usage/token-budgets/abc/edit', 'Token Budgets'],
+ ])('marks the matching child route as current for %s', (pathname, label) => {
+ navigationState.pathname = pathname
+ render(<Sidebar currentTab="cost" />)
+
+ const child = screen.getByRole('link', { name: label })
+ expect(child).toHaveAttribute('data-active', 'true')
+ expect(child).toHaveAttribute('aria-current', 'page')
+ })
it('is not active on unrelated routes', () => {
- renderLayoutAt('/hosts')
- const link = screen.getByRole('link', { name: /Cost & Usage/ })
- expect(link).not.toHaveAttribute('aria-current', 'page')
+ renderLayoutAt('/agents')
+ const group = screen.getByRole('button', { name: /Cost & Usage/ })
+ expect(group).toHaveAttribute('data-active', 'false')
+ expect(group).toHaveAttribute('aria-expanded', 'false')
})
})
diff --git a/control-ui/components/__tests__/CreateSharedFileSystemPage.test.tsx b/control-ui/components/__tests__/CreateSharedFileSystemPage.test.tsx
index 6518b5f44..02185bfb4 100644
--- a/control-ui/components/__tests__/CreateSharedFileSystemPage.test.tsx
+++ b/control-ui/components/__tests__/CreateSharedFileSystemPage.test.tsx
@@ -78,6 +78,6 @@ describe('CreateSharedFileSystemPage', () => {
retainOnDelete: true,
})
})
- expect(mockPush).toHaveBeenCalledWith('/shared-files')
+ expect(mockPush).toHaveBeenCalledWith('/agent-files')
})
})
diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsx
index ef4d39119..328cef138 100644
--- a/control-ui/components/__tests__/GfsBrowser.test.tsx
+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx
@@ -8,6 +8,8 @@ import {
apiSend,
getAdminTeams,
getAdminUsers,
+ getGfsGrants,
+ getGfsShares,
getHosts,
getRecipes,
gfsDownload,
@@ -23,6 +25,8 @@ vi.mock('@lib/api', () => ({
apiSend: vi.fn(),
getAdminTeams: vi.fn(),
getAdminUsers: vi.fn(),
+ getGfsGrants: vi.fn(),
+ getGfsShares: vi.fn(),
getHosts: vi.fn(),
getRecipes: vi.fn(),
gfsDownload: vi.fn(),
@@ -35,6 +39,8 @@ const mockApiGet = apiGet as unknown as ReturnType<typeof vi.fn>
const mockApiSend = apiSend as unknown as ReturnType<typeof vi.fn>
const mockGetAdminUsers = vi.mocked(getAdminUsers)
const mockGetAdminTeams = vi.mocked(getAdminTeams)
+const mockGetGfsGrants = vi.mocked(getGfsGrants)
+const mockGetGfsShares = vi.mocked(getGfsShares)
const mockGetHosts = vi.mocked(getHosts)
const mockGetRecipes = vi.mocked(getRecipes)
const mockPutGfsGrant = putGfsGrant as unknown as ReturnType<typeof vi.fn>
@@ -91,6 +97,8 @@ describe('GfsBrowser', () => {
mockApiSend.mockReset()
mockGetAdminUsers.mockReset()
mockGetAdminTeams.mockReset()
+ mockGetGfsGrants.mockReset()
+ mockGetGfsShares.mockReset()
mockGetHosts.mockReset()
mockGetRecipes.mockReset()
mockPutGfsGrant.mockReset()
@@ -126,6 +134,8 @@ describe('GfsBrowser', () => {
mockGetRecipes.mockResolvedValue({
items: [{ metadata: { namespace: 'sandbox-recipes', name: 'sandbox-ui-hello' } }],
})
+ mockGetGfsGrants.mockResolvedValue({ items: [] })
+ mockGetGfsShares.mockResolvedValue({ items: [] })
})
it('loads the root tree and renders directories + files', async () => {
@@ -665,7 +675,7 @@ describe('GfsBrowser', () => {
expect(alert.textContent).toContain('boom')
})
- it('operator grants access on a selected resource (confirmed) with the correct body', async () => {
+ it('grants access to a selected bulk subject with the correct body', async () => {
mockApiGet.mockResolvedValueOnce({ items: [child('report.md', 'file', 2)], nextCursor: null })
mockPutGfsGrant.mockResolvedValueOnce({ ok: true })
renderBrowser()
@@ -700,7 +710,7 @@ describe('GfsBrowser', () => {
expect(mockPutGfsGrant).toHaveBeenCalledWith({
drive: 'main',
resourceId: 'id-2',
- subject: { type: 'user', id: '11111111-1111-1111-1111-111111111111' },
+ subjects: [{ type: 'user', id: '11111111-1111-1111-1111-111111111111' }],
permissions: ['read'],
inherit: false,
})
@@ -722,7 +732,7 @@ describe('GfsBrowser', () => {
expect(screen.getByRole('button', { name: 'Grant access' })).not.toBeDisabled()
})
- it('includes descendants for directory grants while keeping share creation hidden', async () => {
+ it('includes descendants for directory grants and exposes share creation', async () => {
mockApiGet.mockResolvedValueOnce({
items: [child('team-folder', 'directory', 2)],
nextCursor: null,
@@ -735,7 +745,7 @@ describe('GfsBrowser', () => {
await waitFor(() => expect(mockGetAdminUsers).toHaveBeenCalledWith(''))
expect(await screen.findByRole('checkbox', { name: /Include descendants/ })).toBeChecked()
expect(screen.getByText('Apply this grant or share to the full folder tree.')).toBeTruthy()
- expect(screen.queryByRole('button', { name: 'Create share' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Create share' })).toBeDisabled()
await openSubjectPicker()
fireEvent.click(await screen.findByRole('option', { name: 'Ada Lovelace' }))
selectPermission('Read')
@@ -776,7 +786,7 @@ describe('GfsBrowser', () => {
await waitFor(() =>
expect(mockPutGfsGrant).toHaveBeenCalledWith(
expect.objectContaining({
- subject: { type: 'team', id: '22222222-2222-2222-2222-222222222222' },
+ subjects: [{ type: 'team', id: '22222222-2222-2222-2222-222222222222' }],
})
)
)
diff --git a/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx b/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx
new file mode 100644
index 000000000..9c36fd784
--- /dev/null
+++ b/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx
@@ -0,0 +1,493 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import {
+ type GfsMutationResponse,
+ type GfsSubjectInput,
+ deleteGfsGrant,
+ deleteGfsShare,
+ getAdminTeams,
+ getAdminUsers,
+ getGfsGrants,
+ getGfsShares,
+ getHosts,
+ getRecipes,
+ postGfsShare,
+ putGfsGrant,
+} from '@lib/api'
+import { GfsGrantPanel } from '../GfsGrantPanel'
+import { ToastProvider } from '../Toast'
+
+vi.mock('@lib/api', () => ({
+ getAdminTeams: vi.fn(),
+ getAdminUsers: vi.fn(),
+ getHosts: vi.fn(),
+ getRecipes: vi.fn(),
+ getGfsGrants: vi.fn(),
+ getGfsShares: vi.fn(),
+ deleteGfsGrant: vi.fn(),
+ deleteGfsShare: vi.fn(),
+ postGfsShare: vi.fn(),
+ putGfsGrant: vi.fn(),
+}))
+
+const mockGetAdminUsers = vi.mocked(getAdminUsers)
+const mockGetAdminTeams = vi.mocked(getAdminTeams)
+const mockGetHosts = vi.mocked(getHosts)
+const mockGetRecipes = vi.mocked(getRecipes)
+const mockGetGfsGrants = vi.mocked(getGfsGrants)
+const mockGetGfsShares = vi.mocked(getGfsShares)
+const mockDeleteGfsGrant = vi.mocked(deleteGfsGrant)
+const mockDeleteGfsShare = vi.mocked(deleteGfsShare)
+const mockPostGfsShare = vi.mocked(postGfsShare)
+const mockPutGfsGrant = vi.mocked(putGfsGrant)
+
+const resource = {
+ resourceId: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ name: 'report.md',
+ gfsUri: 'gfs://main/report',
+ kind: 'file',
+}
+
+const userSubject = { type: 'user', id: '11111111-1111-1111-1111-111111111111' } as const
+const teamSubject = { type: 'team', id: '22222222-2222-2222-2222-222222222222' } as const
+const statefulHostSubject = { type: 'host', id: '1st:mcp-host/chatllm' } as const
+const statelessHostSubject = { type: 'host', id: '1st:mcp-host/chatllm-stateless' } as const
+const workflowHostSubject = {
+ type: 'host',
+ id: '3rd:sandbox-recipes/sandbox-ui-hello',
+} as const
+const operatorSubject = { type: 'operator' } as const
+
+function successfulMutation(...updated: GfsSubjectInput[]): GfsMutationResponse {
+ return { ok: true, resourceId: resource.resourceId, updated, count: updated.length }
+}
+
+function renderPanel() {
+ return render(
+ <ToastProvider>
+ <GfsGrantPanel resource={resource} />
+ </ToastProvider>
+ )
+}
+
+async function openSubjectPicker() {
+ const input = await screen.findByRole('combobox', {
+ name: 'Add people, teams, agents, or workflows',
+ })
+ fireEvent.mouseDown(input)
+ fireEvent.focus(input)
+ return screen.findByRole('listbox', { name: 'Available grant subjects' })
+}
+
+async function chooseSubjects(...names: string[]) {
+ await openSubjectPicker()
+ for (const name of names) fireEvent.click(screen.getByRole('option', { name }))
+}
+
+function openPermissionMenu() {
+ let menu = screen.queryByRole('menu', { name: 'Permissions' })
+ if (!menu) {
+ const trigger = document.querySelector<HTMLButtonElement>(
+ '.cu-gfs-permission-dropdown__trigger'
+ )
+ if (!trigger) throw new Error('permission trigger missing')
+ fireEvent.click(trigger)
+ menu = screen.getByRole('menu', { name: 'Permissions' })
+ }
+ return menu
+}
+
+function selectPermission(name: string) {
+ fireEvent.click(within(openPermissionMenu()).getByRole('menuitemcheckbox', { name }))
+}
+
+async function submit(action: 'Grant access' | 'Create share') {
+ fireEvent.click(screen.getByRole('button', { name: action }))
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: action === 'Grant access' ? 'Grant' : action })
+ )
+}
+
+describe('GfsGrantPanel bulk access', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetAdminUsers.mockResolvedValue({
+ items: [
+ {
+ id: '11111111-1111-1111-1111-111111111111',
+ email: '[email protected]',
+ name: 'Ada Lovelace',
+ displayName: 'Ada Lovelace',
+ picture: null,
+ activeTeamCount: 1,
+ },
+ ],
+ })
+ mockGetAdminTeams.mockResolvedValue({
+ items: [{ id: '22222222-2222-2222-2222-222222222222', name: 'Research', memberCount: 2 }],
+ })
+ mockGetHosts.mockResolvedValue({
+ items: [
+ { metadata: { namespace: 'mcp-host', name: 'chatllm' } },
+ {
+ metadata: { namespace: 'mcp-host', name: 'chatllm-stateless' },
+ spec: { lifecycle: { stateless: true } },
+ },
+ ],
+ })
+ mockGetRecipes.mockResolvedValue({
+ items: [{ metadata: { namespace: 'sandbox-recipes', name: 'sandbox-ui-hello' } }],
+ })
+ mockGetGfsGrants.mockResolvedValue({ items: [] })
+ mockGetGfsShares.mockResolvedValue({ items: [] })
+ mockDeleteGfsGrant.mockResolvedValue(undefined)
+ mockDeleteGfsShare.mockResolvedValue(undefined)
+ })
+
+ it('loads direct access on mount and revokes the selected persisted row', async () => {
+ mockGetGfsGrants
+ .mockResolvedValueOnce({
+ items: [
+ {
+ id: '33333333-3333-3333-3333-333333333333',
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subject: userSubject,
+ permissions: ['read', 'write'],
+ inherit: false,
+ },
+ ],
+ })
+ .mockResolvedValueOnce({ items: [] })
+ renderPanel()
+
+ const existing = await screen.findByRole('region', { name: 'Existing access' })
+ expect(within(existing).getByText('Ada Lovelace')).toBeTruthy()
+ expect(within(existing).getByText('Grant · read, write · resource only')).toBeTruthy()
+
+ fireEvent.click(
+ within(existing).getByRole('button', { name: 'Remove grant access for Ada Lovelace' })
+ )
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Remove access' }))
+
+ await waitFor(() =>
+ expect(mockDeleteGfsGrant).toHaveBeenCalledWith('33333333-3333-3333-3333-333333333333')
+ )
+ await waitFor(() =>
+ expect(within(existing).getByText('No direct access configured.')).toBeTruthy()
+ )
+ expect(mockGetGfsGrants).toHaveBeenCalledTimes(2)
+ expect(mockGetGfsShares).toHaveBeenCalledTimes(2)
+ })
+
+ it('self-heals a row that another admin already revoked without hiding other errors', async () => {
+ mockGetGfsGrants
+ .mockResolvedValueOnce({
+ items: [
+ {
+ id: '55555555-5555-5555-5555-555555555555',
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subject: userSubject,
+ permissions: ['read'],
+ inherit: false,
+ },
+ ],
+ })
+ .mockResolvedValueOnce({ items: [] })
+ mockDeleteGfsGrant.mockRejectedValueOnce(
+ Object.assign(new Error('404 grant_not_found'), {
+ status: 404,
+ code: 'grant_not_found',
+ })
+ )
+ renderPanel()
+ const existing = await screen.findByRole('region', { name: 'Existing access' })
+ fireEvent.click(
+ within(existing).getByRole('button', { name: 'Remove grant access for Ada Lovelace' })
+ )
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Remove access' }))
+
+ expect(await screen.findByText('Access was already removed.')).toBeTruthy()
+ await waitFor(() =>
+ expect(within(existing).getByText('No direct access configured.')).toBeTruthy()
+ )
+ expect(screen.queryByRole('alert')).toBeNull()
+ expect(mockGetGfsGrants).toHaveBeenCalledTimes(2)
+ })
+
+ it('surfaces a non-idempotent revoke failure and keeps the persisted row visible', async () => {
+ mockGetGfsGrants.mockResolvedValue({
+ items: [
+ {
+ id: '66666666-6666-6666-6666-666666666666',
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subject: userSubject,
+ permissions: ['read'],
+ inherit: false,
+ },
+ ],
+ })
+ mockDeleteGfsGrant.mockRejectedValueOnce(
+ Object.assign(new Error('403 not_manager'), {
+ status: 403,
+ code: 'not_manager',
+ })
+ )
+ renderPanel()
+ const existing = await screen.findByRole('region', { name: 'Existing access' })
+ fireEvent.click(
+ within(existing).getByRole('button', { name: 'Remove grant access for Ada Lovelace' })
+ )
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Remove access' }))
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('403 not_manager')
+ expect(within(existing).getByText('Ada Lovelace')).toBeTruthy()
+ expect(screen.queryByText('Access was already removed.')).toBeNull()
+ expect(mockGetGfsGrants).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the newest post-mutation hydration when the initial request resolves late', async () => {
+ let resolveInitialGrants!: (value: Awaited<ReturnType<typeof getGfsGrants>>) => void
+ const initialGrants = new Promise<Awaited<ReturnType<typeof getGfsGrants>>>(resolve => {
+ resolveInitialGrants = resolve
+ })
+ mockGetGfsGrants.mockReturnValueOnce(initialGrants).mockResolvedValueOnce({
+ items: [
+ {
+ id: '44444444-4444-4444-4444-444444444444',
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subject: userSubject,
+ permissions: ['read'],
+ inherit: false,
+ },
+ ],
+ })
+ mockPutGfsGrant.mockResolvedValue(successfulMutation(userSubject))
+ renderPanel()
+ await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(1))
+ const initialSignal = mockGetGfsGrants.mock.calls[0][2]
+ await chooseSubjects('Ada Lovelace')
+ selectPermission('Read')
+ await submit('Grant access')
+
+ const existing = await screen.findByRole('region', { name: 'Existing access' })
+ expect(await within(existing).findByText('Grant · read · resource only')).toBeTruthy()
+ expect(initialSignal?.aborted).toBe(true)
+ resolveInitialGrants({ items: [] })
+
+ await waitFor(() =>
+ expect(within(existing).getByText('Grant · read · resource only')).toBeTruthy()
+ )
+ expect(within(existing).queryByText('No direct access configured.')).toBeNull()
+ })
+
+ it('aborts the active access hydration when the panel unmounts', async () => {
+ mockGetGfsGrants.mockReturnValueOnce(new Promise(() => undefined))
+ const panel = renderPanel()
+ await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(1))
+ const signal = mockGetGfsGrants.mock.calls[0][2]
+
+ panel.unmount()
+
+ expect(signal?.aborted).toBe(true)
+ })
+
+ it('offers users, teams, canonical hosts, and singular operator without contexts', async () => {
+ renderPanel()
+ const listbox = await openSubjectPicker()
+
+ expect(within(listbox).getByRole('option', { name: 'Ada Lovelace' })).toBeTruthy()
+ expect(within(listbox).getByRole('option', { name: 'Research' })).toBeTruthy()
+ expect(within(listbox).getByRole('option', { name: 'chatllm (Stateful)' })).toBeTruthy()
+ expect(
+ within(listbox).getByRole('option', { name: 'chatllm-stateless (Stateless)' })
+ ).toBeTruthy()
+ expect(within(listbox).queryByRole('option', { name: 'First-party agent runtime' })).toBeNull()
+ expect(within(listbox).getByRole('option', { name: 'sandbox-ui-hello' })).toBeTruthy()
+ expect(within(listbox).getByRole('option', { name: 'Operator' })).toBeTruthy()
+ expect(within(listbox).queryByRole('option', { name: /context/i })).toBeNull()
+ })
+
+ it('submits one ordered mixed bulk grant and enforces the host UI permission matrix', async () => {
+ mockPutGfsGrant.mockResolvedValue(
+ successfulMutation(
+ userSubject,
+ teamSubject,
+ statefulHostSubject,
+ statelessHostSubject,
+ workflowHostSubject
+ )
+ )
+ renderPanel()
+ await chooseSubjects('Ada Lovelace', 'Research')
+ selectPermission('Read')
+ selectPermission('Delete')
+ await chooseSubjects('chatllm (Stateful)', 'chatllm-stateless (Stateless)', 'sandbox-ui-hello')
+
+ const permissions = openPermissionMenu()
+ expect(within(permissions).getByRole('menuitemcheckbox', { name: 'Read' })).toBeChecked()
+ expect(within(permissions).getByRole('menuitemcheckbox', { name: 'Write' })).not.toBeChecked()
+ expect(within(permissions).queryByRole('menuitemcheckbox', { name: 'Delete' })).toBeNull()
+ expect(within(permissions).queryByRole('menuitemcheckbox', { name: 'Share' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Create share' })).toBeDisabled()
+
+ await submit('Grant access')
+
+ await waitFor(() =>
+ expect(mockPutGfsGrant).toHaveBeenCalledWith({
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subjects: [
+ { type: 'user', id: '11111111-1111-1111-1111-111111111111' },
+ { type: 'team', id: '22222222-2222-2222-2222-222222222222' },
+ { type: 'host', id: '1st:mcp-host/chatllm' },
+ { type: 'host', id: '1st:mcp-host/chatllm-stateless' },
+ { type: 'host', id: '3rd:sandbox-recipes/sandbox-ui-hello' },
+ ],
+ permissions: ['read'],
+ inherit: false,
+ })
+ )
+ await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(2))
+ })
+
+ it('creates one bulk share for user and team subjects', async () => {
+ mockPostGfsShare.mockResolvedValue(successfulMutation(userSubject, teamSubject))
+ renderPanel()
+ await chooseSubjects('Ada Lovelace', 'Research')
+ selectPermission('Read')
+ await submit('Create share')
+
+ await waitFor(() =>
+ expect(mockPostGfsShare).toHaveBeenCalledWith({
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subjects: [
+ { type: 'user', id: '11111111-1111-1111-1111-111111111111' },
+ { type: 'team', id: '22222222-2222-2222-2222-222222222222' },
+ ],
+ permissions: ['read'],
+ includeDescendants: false,
+ })
+ )
+ })
+
+ it('keeps operator singular and prevents mixing it with bulk subjects', async () => {
+ mockPutGfsGrant.mockResolvedValue(successfulMutation(operatorSubject))
+ renderPanel()
+ await chooseSubjects('Ada Lovelace', 'Operator')
+
+ expect(screen.queryByRole('button', { name: 'Remove Ada Lovelace' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Remove Operator' })).toBeTruthy()
+ selectPermission('Read')
+ await submit('Grant access')
+
+ await waitFor(() =>
+ expect(mockPutGfsGrant).toHaveBeenCalledWith({
+ drive: 'main',
+ resourceId: resource.resourceId,
+ subject: { type: 'operator' },
+ permissions: ['read'],
+ inherit: false,
+ })
+ )
+ })
+
+ it('preserves the form after rejection and resets it only after success', async () => {
+ mockPutGfsGrant
+ .mockRejectedValueOnce(
+ Object.assign(new Error('403 escalation_rejected'), {
+ code: 'escalation_rejected',
+ serverMessage: 'Requested permissions exceed operator authority.',
+ invalidIndexes: [1],
+ })
+ )
+ .mockResolvedValueOnce(successfulMutation(userSubject, teamSubject))
+ renderPanel()
+ await chooseSubjects('Ada Lovelace', 'Research')
+ selectPermission('Write')
+ await submit('Grant access')
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'escalation_rejected: Requested permissions exceed operator authority. (invalid indexes: 1)'
+ )
+ expect(screen.getByRole('button', { name: 'Remove Ada Lovelace' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Remove Research' })).toBeTruthy()
+ expect(document.querySelector('.cu-gfs-permission-dropdown__trigger')).toHaveTextContent(
+ 'Write'
+ )
+
+ await submit('Grant access')
+ await waitFor(() => expect(mockPutGfsGrant).toHaveBeenCalledTimes(2))
+ expect(screen.queryByRole('button', { name: 'Remove Ada Lovelace' })).toBeNull()
+ expect(document.querySelector('.cu-gfs-permission-dropdown__trigger')).toHaveTextContent(
+ 'Permissions'
+ )
+ })
+
+ it('does not duplicate the machine code when the server message matches it', async () => {
+ mockPutGfsGrant.mockRejectedValue(
+ Object.assign(new Error('400 subjects_invalid'), {
+ code: 'subjects_invalid',
+ serverMessage: 'subjects_invalid',
+ })
+ )
+ renderPanel()
+ await chooseSubjects('Ada Lovelace')
+ selectPermission('Read')
+ await submit('Grant access')
+
+ const alert = await screen.findByRole('alert')
+ expect(alert).toHaveTextContent('subjects_invalid')
+ expect(alert).not.toHaveTextContent('subjects_invalid: subjects_invalid')
+ })
+
+ it('does not restore incompatible permissions after the final host is removed', async () => {
+ renderPanel()
+ await chooseSubjects('Ada Lovelace')
+ selectPermission('Delete')
+ await chooseSubjects('chatllm (Stateful)')
+
+ expect(
+ within(openPermissionMenu()).queryByRole('menuitemcheckbox', { name: 'Delete' })
+ ).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Remove chatllm (Stateful)' }))
+
+ expect(
+ within(openPermissionMenu()).getByRole('menuitemcheckbox', { name: 'Delete' })
+ ).not.toBeChecked()
+ selectPermission('Read')
+ expect(screen.getByRole('button', { name: 'Create share' })).toBeEnabled()
+ })
+
+ it('caps the UI selection at 100 subjects', async () => {
+ mockGetAdminUsers.mockResolvedValue({
+ items: Array.from({ length: 101 }, (_, index) => ({
+ id: `10000000-0000-0000-0000-${String(index).padStart(12, '0')}`,
+ email: `user-${index + 1}@example.test`,
+ name: `Bulk User ${String(index + 1).padStart(3, '0')}`,
+ displayName: `Bulk User ${String(index + 1).padStart(3, '0')}`,
+ picture: null,
+ activeTeamCount: 0,
+ })),
+ })
+ renderPanel()
+ const listbox = await openSubjectPicker()
+ for (let index = 1; index <= 101; index += 1) {
+ const option = listbox.querySelector<HTMLButtonElement>('[role="option"]')
+ expect(option).not.toBeNull()
+ fireEvent.click(option!)
+ }
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('You can select up to 100 subjects.')
+ expect(screen.getAllByRole('button', { name: /^Remove Bulk User/ })).toHaveLength(100)
+ expect(screen.queryByRole('button', { name: 'Remove Bulk User 101' })).toBeNull()
+ }, 15_000)
+})
diff --git a/control-ui/components/__tests__/GfsSubjectPicker.test.tsx b/control-ui/components/__tests__/GfsSubjectPicker.test.tsx
new file mode 100644
index 000000000..033d516a9
--- /dev/null
+++ b/control-ui/components/__tests__/GfsSubjectPicker.test.tsx
@@ -0,0 +1,41 @@
+import { useState } from 'react'
+import { describe, expect, it } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { GfsSubjectPicker } from '../GfsSubjectPicker'
+
+const options = [
+ { value: 'user:ada', label: 'Ada Lovelace', badge: 'User' },
+ { value: 'team:research', label: 'Research', badge: 'Team' },
+ { value: 'host:first-party', label: 'First-party agent runtime', badge: 'Agent' },
+]
+
+function ControlledSubjectPicker() {
+ const [value, setValue] = useState<string[]>([])
+ return <GfsSubjectPicker onChange={setValue} options={options} value={value} />
+}
+
+describe('GfsSubjectPicker', () => {
+ it('returns focus to the combobox after each keyboard selection in a multi-select flow', async () => {
+ const user = userEvent.setup({ delay: null })
+ render(<ControlledSubjectPicker />)
+
+ const combobox = screen.getByRole('combobox', {
+ name: 'Add people, teams, agents, or workflows',
+ })
+ await user.tab()
+ expect(combobox).toHaveFocus()
+
+ await user.tab()
+ expect(screen.getByRole('option', { name: 'Ada Lovelace' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(combobox).toHaveFocus()
+ expect(screen.getByRole('button', { name: 'Remove Ada Lovelace' })).toBeTruthy()
+
+ await user.tab()
+ expect(screen.getByRole('option', { name: 'Research' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(combobox).toHaveFocus()
+ expect(screen.getByRole('button', { name: 'Remove Research' })).toBeTruthy()
+ })
+})
diff --git a/control-ui/components/__tests__/LoadingScreen.test.tsx b/control-ui/components/__tests__/LoadingScreen.test.tsx
new file mode 100644
index 000000000..087626f9c
--- /dev/null
+++ b/control-ui/components/__tests__/LoadingScreen.test.tsx
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import { LoadingScreen } from '../LoadingScreen'
+
+describe('LoadingScreen', () => {
+ it('renders the centered branded Control UI loading state', () => {
+ const { container } = render(<LoadingScreen />)
+
+ expect(screen.getByRole('status', { name: 'Loading Control UI' })).toBeInTheDocument()
+ expect(screen.getByText('Evenfire')).toBeInTheDocument()
+ expect(screen.getByText('Control UI')).toBeInTheDocument()
+ expect(screen.getByText('Loading session…')).toBeInTheDocument()
+ expect(container.querySelector('.cu-loading-screen__mark')).toHaveAttribute(
+ 'src',
+ '/brand/logo.svg'
+ )
+ })
+})
diff --git a/control-ui/components/__tests__/OutputsPage.test.tsx b/control-ui/components/__tests__/OutputsPage.test.tsx
index 0df384ecb..4faf8817f 100644
--- a/control-ui/components/__tests__/OutputsPage.test.tsx
+++ b/control-ui/components/__tests__/OutputsPage.test.tsx
@@ -26,7 +26,7 @@ vi.mock('../../components/DashboardLayout', () => ({
}))
vi.mock('../../components/SectionSearchInput', () => ({
- SectionSearchInput: () => <input aria-label="Search outputs" />,
+ SectionSearchInput: () => <input aria-label="Search agent outputs" />,
}))
vi.mock('../../components/Sidebar/icons', () => ({
@@ -80,6 +80,7 @@ describe('OutputsPage', () => {
const { container } = render(<OutputsPage />)
+ expect(screen.getByText('Agent Outputs')).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: 'File' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: 'Recipe' })).toBeInTheDocument()
expect(screen.queryByText(/No workflow artifacts found/)).not.toBeInTheDocument()
diff --git a/control-ui/components/__tests__/RegistryCatalog.test.tsx b/control-ui/components/__tests__/RegistryCatalog.test.tsx
index 8b97fbaac..4881521eb 100644
--- a/control-ui/components/__tests__/RegistryCatalog.test.tsx
+++ b/control-ui/components/__tests__/RegistryCatalog.test.tsx
@@ -195,11 +195,12 @@ describe('RegistryCatalog expansion and actions', () => {
render(<RegistryCatalog />)
const row = (await screen.findByText('brave-search')).closest('tr')!
- expect(screen.queryByText('Main category')).not.toBeInTheDocument()
+ expect(screen.queryByText('local / streamableHttp')).not.toBeInTheDocument()
fireEvent.click(row)
- expect(screen.getByText('Main category')).toBeInTheDocument()
expect(screen.getByText('Type')).toBeInTheDocument()
+ const detailRow = screen.getByText('Type').closest('tr')!
+ expect(within(detailRow).getAllByText('search')).toHaveLength(2)
expect(screen.getByText('HIGH')).toBeInTheDocument()
expect(screen.getByText('verified')).toBeInTheDocument()
expect(screen.getByText('web')).toBeInTheDocument()
diff --git a/control-ui/components/__tests__/Sidebar.test.tsx b/control-ui/components/__tests__/Sidebar.test.tsx
index 4d87fa134..90baa7293 100644
--- a/control-ui/components/__tests__/Sidebar.test.tsx
+++ b/control-ui/components/__tests__/Sidebar.test.tsx
@@ -102,16 +102,16 @@ describe('Sidebar publisher gating', () => {
})
it.each([
- ['/global-files', 'Global Files', '/global-files'],
- ['/outputs/recipe-artifacts', 'Outputs', '/outputs/recipe-artifacts'],
- ['/outputs/desktop-app-artifacts', 'Outputs', '/outputs/recipe-artifacts'],
- ['/shared-files/example', 'Shared Files', '/shared-files'],
- ])('selects the matching Files child for %s', (pathname, label, href) => {
+ ['/agent-files/example', 'Agent Files', '/agent-files'],
+ ['/agent-outputs/recipe-artifacts', 'Agent Outputs', '/agent-outputs/recipe-artifacts'],
+ ['/agent-outputs/desktop-app-artifacts', 'Agent Outputs', '/agent-outputs/recipe-artifacts'],
+ ['/global-file-system', 'Global File System', '/global-file-system'],
+ ])('selects the matching Directories child for %s', (pathname, label, href) => {
vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })
navigationState.pathname = pathname
- render(<Sidebar currentTab="files" />)
+ render(<Sidebar currentTab="directories" />)
- const group = screen.getByRole('button', { name: 'Files' })
+ const group = screen.getByRole('button', { name: 'Directories' })
expect(group).toHaveAttribute('aria-expanded', 'true')
expect(group).toHaveAttribute('data-active', 'true')
const child = screen.getByRole('link', { name: label })
@@ -121,20 +121,39 @@ describe('Sidebar publisher gating', () => {
it('renders a thin icon for every visible child route', () => {
vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })
- render(<Sidebar currentTab="files" />)
+ render(<Sidebar currentTab="directories" />)
- for (const label of ['Global Files', 'Outputs', 'Shared Files']) {
+ for (const label of ['Agent Files', 'Agent Outputs', 'Global File System']) {
const child = screen.getByRole('link', { name: label })
expect(child.querySelector('.cu-sidebar__subitem-icon svg')).toBeInTheDocument()
}
})
+ it('uses the shared Desktop paperclip glyph for Global File System', () => {
+ vi.mocked(hook.usePublishScope).mockReturnValue({ scope: null, loading: false, error: false })
+ navigationState.pathname = '/global-file-system'
+ render(<Sidebar currentTab="directories" />)
+
+ const globalFileSystem = screen.getByRole('link', { name: 'Global File System' })
+ expect(globalFileSystem.querySelector('path')).toHaveAttribute(
+ 'd',
+ 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48'
+ )
+ })
+
it('defines an icon for every sidebar child route, including hidden groups', () => {
for (const item of Object.values(SIDEBAR_TABS)) {
expect(item.children?.every(child => Boolean(child.icon)) ?? true).toBe(true)
}
})
+ it('sorts every sidebar group by the displayed child label', () => {
+ for (const item of Object.values(SIDEBAR_TABS)) {
+ const labels = item.children?.map(child => child.label) ?? []
+ expect(labels).toEqual([...labels].sort((first, second) => first.localeCompare(second)))
+ }
+ })
+
it('selects hidden Trace children by their nested routes', () => {
expect(
activeSidebarChildHref('/traces/infrastructure/event-id', SIDEBAR_TABS.traces.children ?? [])
diff --git a/control-ui/components/__tests__/gfsGrantSubjectOptions.test.ts b/control-ui/components/__tests__/gfsGrantSubjectOptions.test.ts
index 8d3b6c4f3..0d4f56e13 100644
--- a/control-ui/components/__tests__/gfsGrantSubjectOptions.test.ts
+++ b/control-ui/components/__tests__/gfsGrantSubjectOptions.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest'
+import type { WorkflowRecipeResource } from '@lib/api'
import { buildGfsGrantSubjectOptions, toGfsSubjectInput } from '../gfsGrantSubjectOptions'
describe('gfsGrantSubjectOptions', () => {
@@ -13,7 +14,13 @@ describe('gfsGrantSubjectOptions', () => {
},
]
const teams = [{ id: '22222222-2222-2222-2222-222222222222', name: 'Research', memberCount: 2 }]
- const hosts = [{ metadata: { name: 'chatllm' } }]
+ const hosts = [
+ { metadata: { namespace: 'mcp-host', name: 'chatllm' } },
+ {
+ metadata: { namespace: 'mcp-host', name: 'chatllm-stateless' },
+ spec: { lifecycle: { stateless: true } },
+ },
+ ]
const recipes = [{ metadata: { namespace: 'sandbox-recipes', name: 'daily-report' } }]
it('keeps subject type selection separate from filtered subject options', () => {
@@ -38,14 +45,14 @@ describe('gfsGrantSubjectOptions', () => {
])
})
- it('maps first-party agents and workflow plugins to canonical host subjects', () => {
+ it('maps each first-party agent and workflow plugin to an independent canonical host subject', () => {
const firstParty = buildGfsGrantSubjectOptions({
subjectType: 'firstPartyAgent',
users,
teams,
hosts,
recipes,
- })[0]
+ })
const workflow = buildGfsGrantSubjectOptions({
subjectType: 'workflowPlugin',
users,
@@ -54,9 +61,26 @@ describe('gfsGrantSubjectOptions', () => {
recipes,
})[0]
- expect(toGfsSubjectInput('firstPartyAgent', firstParty)).toEqual({
+ expect(firstParty).toEqual([
+ expect.objectContaining({
+ value: 'host:1st:mcp-host/chatllm',
+ id: '1st:mcp-host/chatllm',
+ label: 'chatllm (Stateful)',
+ }),
+ expect.objectContaining({
+ value: 'host:1st:mcp-host/chatllm-stateless',
+ id: '1st:mcp-host/chatllm-stateless',
+ label: 'chatllm-stateless (Stateless)',
+ }),
+ ])
+ expect(firstParty.map(option => option.id)).not.toContain('1st:mcp-host/standalone')
+ expect(toGfsSubjectInput('firstPartyAgent', firstParty[0])).toEqual({
+ type: 'host',
+ id: '1st:mcp-host/chatllm',
+ })
+ expect(toGfsSubjectInput('firstPartyAgent', firstParty[1])).toEqual({
type: 'host',
- id: '1st:mcp-host/standalone',
+ id: '1st:mcp-host/chatllm-stateless',
})
expect(toGfsSubjectInput('workflowPlugin', workflow)).toEqual({
type: 'host',
@@ -64,4 +88,86 @@ describe('gfsGrantSubjectOptions', () => {
})
expect(toGfsSubjectInput('operator', null)).toEqual({ type: 'operator' })
})
+
+ it('omits first-party hosts without an exact namespace and name instead of synthesizing identities', () => {
+ const firstParty = buildGfsGrantSubjectOptions({
+ subjectType: 'firstPartyAgent',
+ users,
+ teams,
+ hosts: [
+ { metadata: { namespace: 'mcp-host', name: 'chatllm' } },
+ { metadata: { namespace: '', name: 'chatllm' } },
+ { metadata: { namespace: ' ', name: 'chatllm' } },
+ { metadata: { name: 'chatllm' } },
+ { metadata: { namespace: 'mcp-host', name: '' } },
+ { metadata: { namespace: 'mcp-host', name: ' ' } },
+ { metadata: { namespace: 'mcp-host' } },
+ {},
+ ],
+ recipes,
+ })
+
+ expect(firstParty.map(option => option.id)).toEqual(['1st:mcp-host/chatllm'])
+ expect(firstParty).not.toContainEqual(
+ expect.objectContaining({ id: '1st:mcp-host/standalone' })
+ )
+ })
+
+ it('omits workflows without an exact namespace and name instead of creating colliding fallbacks', () => {
+ const malformedRecipes = [
+ { metadata: { namespace: 'sandbox-recipes', name: 'daily-report' } },
+ { metadata: { namespace: '', name: 'daily-report' } },
+ { metadata: { namespace: ' ', name: 'daily-report' } },
+ { metadata: { name: 'daily-report' } },
+ { metadata: { namespace: 'sandbox-recipes', name: '' } },
+ { metadata: { namespace: 'sandbox-recipes', name: ' ' } },
+ { metadata: { namespace: 'sandbox-recipes' } },
+ {},
+ ] as unknown as WorkflowRecipeResource[]
+ const workflow = buildGfsGrantSubjectOptions({
+ subjectType: 'workflowPlugin',
+ users,
+ teams,
+ hosts,
+ recipes: malformedRecipes,
+ })
+
+ expect(workflow.map(option => option.id)).toEqual(['3rd:sandbox-recipes/daily-report'])
+ expect(workflow).not.toContainEqual(
+ expect.objectContaining({ id: '3rd:sandbox-recipes/unnamed-recipe' })
+ )
+ })
+
+ it('keeps same-named hosts and workflows in different exact namespaces collision-free', () => {
+ const firstParty = buildGfsGrantSubjectOptions({
+ subjectType: 'firstPartyAgent',
+ users,
+ teams,
+ hosts: [
+ { metadata: { namespace: 'mcp-host', name: 'runtime' } },
+ { metadata: { namespace: 'mcp-host-canary', name: 'runtime' } },
+ ],
+ recipes,
+ })
+ const workflow = buildGfsGrantSubjectOptions({
+ subjectType: 'workflowPlugin',
+ users,
+ teams,
+ hosts,
+ recipes: [
+ { metadata: { namespace: 'sandbox-recipes', name: 'runtime' } },
+ { metadata: { namespace: 'sandbox-recipes-canary', name: 'runtime' } },
+ ],
+ })
+
+ expect(firstParty.map(option => option.id)).toEqual([
+ '1st:mcp-host/runtime',
+ '1st:mcp-host-canary/runtime',
+ ])
+ expect(workflow.map(option => option.id)).toEqual([
+ '3rd:sandbox-recipes/runtime',
+ '3rd:sandbox-recipes-canary/runtime',
+ ])
+ expect(new Set([...firstParty, ...workflow].map(option => option.id)).size).toBe(4)
+ })
})
diff --git a/control-ui/components/gfsGrantSubjectOptions.ts b/control-ui/components/gfsGrantSubjectOptions.ts
index 3113085ea..e579fdeaf 100644
--- a/control-ui/components/gfsGrantSubjectOptions.ts
+++ b/control-ui/components/gfsGrantSubjectOptions.ts
@@ -1,7 +1,3 @@
-import {
- GFS_FIRST_PARTY_HOST_OPTION_VALUE,
- GFS_FIRST_PARTY_HOST_SUBJECT_ID,
-} from '@constants/gfsGrantSubjects'
import type {
AdminUser,
GfsSubjectInput,
@@ -9,7 +5,11 @@ import type {
TeamListItem,
WorkflowRecipeResource,
} from '@lib/api'
-import type { GfsGrantSubjectOption, GfsGrantSubjectType } from './GfsGrantPanel.types'
+import type {
+ GfsBulkSubjectInput,
+ GfsGrantSubjectOption,
+ GfsGrantSubjectType,
+} from './GfsGrantPanel.types'
function userLabel(user: AdminUser): string {
return user.displayName || user.name || user.email
@@ -19,16 +19,8 @@ function teamLabel(team: TeamListItem): string {
return team.name || team.id
}
-function hostName(host: HostResource): string {
- return host.metadata?.name ?? 'unnamed-host'
-}
-
-function recipeName(recipe: WorkflowRecipeResource): string {
- return recipe.metadata?.name ?? 'unnamed-recipe'
-}
-
-function recipeNamespace(recipe: WorkflowRecipeResource): string {
- return recipe.metadata?.namespace ?? 'sandbox-recipes'
+function hostLifecycleLabel(host: HostResource): 'Stateful' | 'Stateless' {
+ return host.spec?.lifecycle?.stateless === true ? 'Stateless' : 'Stateful'
}
export function gfsGrantSubjectFieldLabel(subjectType: GfsGrantSubjectType): string {
@@ -65,6 +57,7 @@ export function buildGfsGrantSubjectOptions(input: {
label: userLabel(user),
description: user.email,
badge: 'User',
+ subject: { type: 'user', id: user.id },
}))
}
if (input.subjectType === 'team') {
@@ -74,43 +67,78 @@ export function buildGfsGrantSubjectOptions(input: {
label: teamLabel(team),
description: `${team.memberCount} ${team.memberCount === 1 ? 'member' : 'members'}`,
badge: 'Team',
+ subject: { type: 'team', id: team.id },
}))
}
if (input.subjectType === 'firstPartyAgent') {
- return [
- {
- value: GFS_FIRST_PARTY_HOST_OPTION_VALUE,
- id: GFS_FIRST_PARTY_HOST_SUBJECT_ID,
- label: 'First-party agent runtime',
- description:
- input.hosts.length > 0
- ? `${input.hosts.length} active ${
- input.hosts.length === 1 ? 'agent' : 'agents'
- } share this runtime subject: ${input.hosts
- .map(hostName)
- .slice(0, 3)
- .join(', ')}${input.hosts.length > 3 ? ', ...' : ''}`
- : 'Shared runtime subject for HCC-provisioned first-party agents.',
- badge: 'Agent',
- },
- ]
+ return input.hosts.flatMap(host => {
+ const name = host.metadata?.name?.trim()
+ const namespace = host.metadata?.namespace?.trim()
+ if (!namespace || !name) return []
+ const lifecycle = hostLifecycleLabel(host)
+ const id = `1st:${namespace}/${name}`
+ return [
+ {
+ value: `host:${id}`,
+ id,
+ label: `${name} (${lifecycle})`,
+ description: `${namespace} · ${lifecycle.toLowerCase()} first-party MCP host`,
+ badge: 'Agent',
+ subject: { type: 'host', id },
+ },
+ ]
+ })
}
if (input.subjectType === 'workflowPlugin') {
- return input.recipes.map(recipe => {
- const namespace = recipeNamespace(recipe)
- const name = recipeName(recipe)
- return {
- value: `host:3rd:${namespace}/${name}`,
- id: `3rd:${namespace}/${name}`,
- label: name,
- description: namespace,
- badge: 'Workflow',
- }
+ return input.recipes.flatMap(recipe => {
+ const namespace = recipe.metadata?.namespace?.trim()
+ const name = recipe.metadata?.name?.trim()
+ if (!namespace || !name) return []
+ const id = `3rd:${namespace}/${name}`
+ return [
+ {
+ value: `host:${id}`,
+ id,
+ label: name,
+ description: namespace,
+ badge: 'Workflow',
+ subject: { type: 'host', id },
+ },
+ ]
})
}
return []
}
+export function buildGfsBulkSubjectOptions(input: {
+ users: AdminUser[]
+ teams: TeamListItem[]
+ hosts: HostResource[]
+ recipes: WorkflowRecipeResource[]
+}): GfsGrantSubjectOption[] {
+ return [
+ ...buildGfsGrantSubjectOptions({ ...input, subjectType: 'user' }),
+ ...buildGfsGrantSubjectOptions({ ...input, subjectType: 'team' }),
+ ...buildGfsGrantSubjectOptions({ ...input, subjectType: 'firstPartyAgent' }),
+ ...buildGfsGrantSubjectOptions({ ...input, subjectType: 'workflowPlugin' }),
+ ]
+}
+
+export function toGfsBulkSubjectInputs(options: GfsGrantSubjectOption[]): GfsBulkSubjectInput[] {
+ return options.map(option => option.subject)
+}
+
+export function summarizeGfsBulkSubjectTypes(subjects: GfsBulkSubjectInput[]): string {
+ const counts = subjects.reduce(
+ (summary, subject) => ({ ...summary, [subject.type]: summary[subject.type] + 1 }),
+ { user: 0, team: 0, host: 0 }
+ )
+ return (['user', 'team', 'host'] as const)
+ .filter(type => counts[type] > 0)
+ .map(type => `${counts[type]} ${type}${counts[type] === 1 ? '' : 's'}`)
+ .join(', ')
+}
+
export function toGfsSubjectInput(
subjectType: GfsGrantSubjectType,
selectedSubject: GfsGrantSubjectOption | null
diff --git a/control-ui/e2e/artifact-full-flow.spec.ts b/control-ui/e2e/artifact-full-flow.spec.ts
index c1adce0b4..b550d53e2 100644
--- a/control-ui/e2e/artifact-full-flow.spec.ts
+++ b/control-ui/e2e/artifact-full-flow.spec.ts
@@ -6,7 +6,7 @@
* 2. Wait for workflow completion
* 3. Download artifact from the run-scoped recipe status view
* 4. Delete per-file via ✕ button — verify removal + CRD update
- * 5. Navigate to /outputs — verify page loads and shows recipe data
+ * 5. Navigate to /agent-outputs — verify page loads and shows recipe data
* 6. Re-deploy → generate → Clear All via bulk delete
*
* Uses the local glm-4.7 model mapping available in the minikube E2E profile.
@@ -545,17 +545,17 @@ test.describe('Artifact Full Flow E2E', () => {
console.log(' [PASS] Per-file delete works, API confirms 404')
})
- test('4. /outputs page loads and shows recipe', async ({ page }) => {
+ test('4. /agent-outputs page loads and shows recipe', async ({ page }) => {
await login(page)
- // Navigate to /outputs
- await page.goto(`${BASE_UI}/outputs`)
+ // Navigate to the canonical Agent Outputs route.
+ await page.goto(`${BASE_UI}/agent-outputs`)
// The page should show the recipe name (even if artifacts are deleted,
// the regex fallback on step output may still detect filenames)
await expect(page.locator('text=Recipe Artifacts')).toBeVisible({ timeout: 10_000 })
- console.log(' [PASS] /outputs page loads correctly')
+ console.log(' [PASS] /agent-outputs page loads correctly')
})
test('5. re-deploy + bulk delete via Clear All', async ({ page }) => {
diff --git a/control-ui/e2e/clerum-dev-smoke.spec.ts b/control-ui/e2e/clerum-dev-smoke.spec.ts
index 4fb18f37a..e2dc71ed2 100644
--- a/control-ui/e2e/clerum-dev-smoke.spec.ts
+++ b/control-ui/e2e/clerum-dev-smoke.spec.ts
@@ -32,7 +32,7 @@ const BASE_UI = process.env.CONTROL_UI_URL || 'http://localhost:3000'
const ADMIN_USER = process.env.ADMIN_USER || 'admin'
const ADMIN_PASS = process.env.ADMIN_PASS || 'changeme123!'
const K8S_CONTEXT =
- process.env.KUBECONTEXT || process.env.CONTEXT || 'gke_your-gcp-project_us-central1-a_example-dev'
+ process.env.KUBECONTEXT || process.env.CONTEXT || 'gke_${GCP_PROJECT}_us-central1-a_example-dev'
const EXPECTED_GFS_STORAGE_CLASS = process.env.GFS_STORAGE_CLASS || 'standard-rwo'
// Minimum entries we expect the registry to serve. The registry base seed is
@@ -168,8 +168,8 @@ test.describe('example-dev — cluster smoke', () => {
test('S7. GFS — sidebar navigation loads through Control UI proxy and live cluster resources exist', async () => {
await login(page)
await page.goto(BASE_UI)
- const globalFilesLink = page.getByRole('link', { name: /Global Files/i })
- await expect(globalFilesLink).toBeVisible()
+ const globalFileSystemLink = page.getByRole('link', { name: /Global File System/i })
+ await expect(globalFileSystemLink).toBeVisible()
const treeResponse = page.waitForResponse(
response =>
@@ -177,8 +177,8 @@ test.describe('example-dev — cluster smoke', () => {
response.request().method() === 'GET'
)
- await globalFilesLink.click()
- await expect(page).toHaveURL(/\/gfs$/)
+ await globalFileSystemLink.click()
+ await expect(page).toHaveURL(/\/global-file-system$/)
await expect(page.getByRole('heading', { name: 'Global File System' })).toBeVisible()
await expect(page.getByText('Drive', { exact: true })).toBeVisible()
await expect(page.getByText('main', { exact: true }).first()).toBeVisible()
diff --git a/control-ui/e2e/gfs-operator-journey.spec.ts b/control-ui/e2e/gfs-operator-journey.spec.ts
index 05e48741d..d3c83d52d 100644
--- a/control-ui/e2e/gfs-operator-journey.spec.ts
+++ b/control-ui/e2e/gfs-operator-journey.spec.ts
@@ -1,84 +1,41 @@
/**
* E2E - GFS operator journey
*
- * The setup creates only an isolated GFS fixture. The grant behavior under test
- * is performed through the Control UI: visible login, sidebar navigation,
- * resource selection, confirmation, and persisted grant proof.
+ * Setup creates isolated fixtures. Grant behavior is exercised through visible
+ * Control UI login, navigation, resource selection, confirmation, and persisted
+ * business signals.
*/
-import { type Locator, type Page, expect, test } from '@playwright/test'
+import { expect, test } from '@playwright/test'
import {
- cleanupE2EUserTeam,
+ assertGfsFixtureCleaned,
cleanupGfsFixture,
- cleanupGfsWorkflowRecipeFixture,
- getE2EUserId,
- getGfsChildResourceSummary,
- getGfsGrantSummary,
- seedE2EUserTeam,
seedGfsDirectoryFixture,
- seedGfsWorkflowRecipeFixture,
uniqueGfsFixtureName,
} from '../../tests/e2e/gfsUiFixtures'
-import { E2E_TEST_EMAIL } from '../../tests/e2e/testUser'
-import { GFS_RESOURCE_NAME_MAX_LENGTH, normalizeGfsResourceName } from '../lib/gfsResourceName'
-
-const BASE_UI = process.env.CONTROL_UI_URL || 'http://localhost:3000'
-const ADMIN_USER = process.env.ADMIN_USER || 'admin'
-const ADMIN_PASS = process.env.ADMIN_PASS || 'changeme123!'
-
-async function loginControlUi(page: Page): Promise<void> {
- await page.goto(BASE_UI)
- await expect(page.getByRole('button', { name: 'Sign in' })).toBeVisible({ timeout: 15_000 })
- await page.getByLabel('Username or email').fill(ADMIN_USER)
- await page.getByLabel('Password').fill(ADMIN_PASS)
- await page.getByRole('button', { name: 'Sign in' }).last().click()
- await expect(page.getByRole('navigation', { name: 'Main sections' })).toBeVisible({
- timeout: 20_000,
- })
- await dismissAccountAlert(page)
-}
-
-async function dismissAccountAlert(page: Page): Promise<void> {
- const remindLater = page.getByRole('button', { name: 'Remind me later' })
- if (await remindLater.isVisible({ timeout: 3_000 }).catch(() => false)) {
- await remindLater.click()
- await expect(remindLater).toBeHidden({ timeout: 10_000 })
- }
-}
-
-async function expectCopyButtonWritesClipboard(
- page: Page,
- button: Locator,
- expectedUri: string
-): Promise<void> {
- await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], {
- origin: new URL(BASE_UI).origin,
- })
- await expect(button).toHaveAttribute('title', expectedUri)
- await button.click()
- await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(expectedUri)
-}
+import { exerciseGfsBulkOperatorJourney } from './support/gfs-bulk-operator-journey.test'
+import { loginControlUi, openGlobalFileSystemFromSidebar } from './support/gfs-control-ui-session'
test.describe('GFS operator journey', () => {
- test.setTimeout(180_000)
+ test.setTimeout(600_000)
- test('authenticated operator reaches Global Files without a 401 logout redirect', async ({
+ test('authenticated operator reaches Global File System without a 401 logout redirect', async ({
page,
}) => {
- const fixture = seedGfsDirectoryFixture(uniqueGfsFixtureName('e2e-gfs-auth'))
+ const fixtureName = uniqueGfsFixtureName('e2e-gfs-auth')
try {
+ const fixture = seedGfsDirectoryFixture(fixtureName)
await test.step('operator logs in through the visible Control UI form', async () => {
await loginControlUi(page)
})
- await test.step('operator opens Global Files from the sidebar and the GFS tree request is authorized', async () => {
+ await test.step('operator opens Global File System from the sidebar and the GFS tree request is authorized', async () => {
const treeResponsePromise = page.waitForResponse(
response =>
response.request().method() === 'GET' &&
response.url().includes('/control-api/api/v1/gfs/tree')
)
-
- await page.getByRole('link', { name: /Global Files/i }).click()
+ await openGlobalFileSystemFromSidebar(page)
const treeResponse = await treeResponsePromise
expect(treeResponse.status(), `${treeResponse.url()} ${await treeResponse.text()}`).toBe(
200
@@ -86,9 +43,9 @@ test.describe('GFS operator journey', () => {
})
await test.step('operator remains on the GFS page with the seeded folder visible', async () => {
- await expect(page).toHaveURL(/\/gfs(?:$|\?)/, { timeout: 15_000 })
+ await expect(page).toHaveURL(/\/global-file-system(?:$|\?)/, { timeout: 15_000 })
await expect(page).not.toHaveURL(/\?next=%2Fgfs/)
- await expect(page.getByRole('heading', { name: 'Global File System' })).toBeVisible()
+ await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()
await expect(
page
.getByRole('list', { name: 'Current folder resources' })
@@ -97,7 +54,8 @@ test.describe('GFS operator journey', () => {
await expect(page.getByRole('button', { name: 'Sign in' })).toHaveCount(0)
})
} finally {
- cleanupGfsFixture(fixture.name)
+ cleanupGfsFixture(fixtureName)
+ assertGfsFixtureCleaned(fixtureName)
}
})
@@ -109,414 +67,6 @@ test.describe('GFS operator journey', () => {
browserName === 'firefox',
'Full CRUD and delegation coverage runs in Chromium; Firefox runs the focused GFS auth-boundary journey.'
)
-
- const fixture = seedGfsDirectoryFixture(uniqueGfsFixtureName('e2e-gfs-operator'))
- const targetUserId = getE2EUserId()
- const targetTeam = seedE2EUserTeam(E2E_TEST_EMAIL, uniqueGfsFixtureName('e2e-gfs-team'))
- const workflowRecipe = seedGfsWorkflowRecipeFixture(uniqueGfsFixtureName('e2e-gfs-workflow'))
- const grantPanel = () =>
- page.locator('.cu-form-section').filter({
- has: page.getByRole('heading', {
- name: `Manage access \u2014 ${fixture.name}`,
- exact: true,
- }),
- })
- const folderRow = (name: string) =>
- page
- .getByRole('list', { name: 'Current folder resources' })
- .getByRole('listitem')
- .filter({ has: page.getByRole('button', { name, exact: true }) })
- .first()
-
- try {
- await test.step('operator logs in and navigates to Global Files through the sidebar', async () => {
- await loginControlUi(page)
- await page.getByRole('link', { name: /Global Files/i }).click()
- await expect(page).toHaveURL(/\/gfs(?:$|\?)/, { timeout: 15_000 })
- await expect(page.getByRole('heading', { name: 'Global File System' })).toBeVisible()
- await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()
- })
-
- await test.step('operator opens the grant panel for the seeded folder', async () => {
- const row = folderRow(fixture.name)
- await expect(row).toBeVisible({ timeout: 20_000 })
- await expectCopyButtonWritesClipboard(
- page,
- row.getByRole('button', { name: `Copy GFS link for ${fixture.name}` }),
- fixture.uri
- )
- await row.getByRole('button', { name: 'Manage access' }).click()
- await expect(
- page.getByRole('heading', { name: `Manage access \u2014 ${fixture.name}`, exact: true })
- ).toBeVisible()
- })
-
- await test.step('operator creates, uploads, renames, replaces, and deletes resources from the folder UI', async () => {
- await page.getByRole('button', { name: 'Close' }).click()
- await folderRow(fixture.name)
- .getByRole('button', { name: fixture.name, exact: true })
- .click()
- const currentResources = page.getByRole('list', { name: 'Current folder resources' })
- await expect(
- currentResources.getByRole('button', { name: fixture.childName, exact: true })
- ).toBeVisible({ timeout: 20_000 })
-
- const createdFolderRaw = `${uniqueGfsFixtureName('e2e-gfs-operator-created')}-${'very-long-'.repeat(24)}child`
- const createdFolder = await normalizeGfsResourceName(createdFolderRaw)
- expect(createdFolderRaw.length).toBeGreaterThan(GFS_RESOURCE_NAME_MAX_LENGTH)
- expect(createdFolder).toHaveLength(GFS_RESOURCE_NAME_MAX_LENGTH)
- const createResponsePromise = page.waitForResponse(
- response =>
- response.request().method() === 'POST' &&
- response.url().includes('/gfs/proxy/v1/resources/') &&
- response.url().includes('/children')
- )
- page.once('dialog', dialog => dialog.accept(createdFolderRaw))
- await page.getByRole('button', { name: 'New folder' }).click()
- const createResponse = await createResponsePromise
- expect(
- createResponse.status(),
- `${createResponse.url()} ${await createResponse.text()}`
- ).toBe(201)
- await expect(page.getByText('Folder created.').last()).toBeVisible({ timeout: 15_000 })
- await expect
- .poll(
- () =>
- getGfsChildResourceSummary({
- parentResourceId: fixture.resourceId,
- name: createdFolder,
- }),
- {
- timeout: 15_000,
- intervals: [250, 500, 1_000],
- }
- )
- .toMatchObject({ name: createdFolder, kind: 'directory', deleted: false })
- await expect(
- currentResources.getByRole('button', { name: createdFolder, exact: true })
- ).toBeVisible({ timeout: 15_000 })
-
- const uploadRawName = `${uniqueGfsFixtureName('e2e-gfs-operator-upload')}-${'very-long-'.repeat(24)}report.txt`
- const uploadName = await normalizeGfsResourceName(uploadRawName)
- expect(uploadRawName.length).toBeGreaterThan(GFS_RESOURCE_NAME_MAX_LENGTH)
- expect(uploadName).toHaveLength(GFS_RESOURCE_NAME_MAX_LENGTH)
- await page.locator('label:has-text("Upload file") input[type="file"]').setInputFiles({
- name: uploadRawName,
- mimeType: 'text/plain',
- buffer: Buffer.from('operator upload v1', 'utf8'),
- })
- await expect(page.getByText('File uploaded.').last()).toBeVisible({ timeout: 15_000 })
- await expect
- .poll(
- () =>
- getGfsChildResourceSummary({
- parentResourceId: fixture.resourceId,
- name: uploadName,
- }),
- {
- timeout: 15_000,
- intervals: [250, 500, 1_000],
- }
- )
- .toMatchObject({ name: uploadName, kind: 'file', bytes: 18, deleted: false })
-
- const rawRenamedName = uploadName.replace('.txt', '-renamed.txt')
- const renamedName = await normalizeGfsResourceName(rawRenamedName)
- const uploadRow = currentResources
- .getByRole('listitem')
- .filter({ hasText: uploadName })
- .first()
- await expect(uploadRow).toBeVisible({ timeout: 15_000 })
- page.once('dialog', dialog => dialog.accept(rawRenamedName))
- await uploadRow.getByRole('button', { name: 'Rename' }).click()
- await expect(page.getByText('Resource renamed.').last()).toBeVisible({ timeout: 15_000 })
- await expect
- .poll(
- () =>
- getGfsChildResourceSummary({
- parentResourceId: fixture.resourceId,
- name: renamedName,
- }),
- {
- timeout: 15_000,
- intervals: [250, 500, 1_000],
- }
- )
- .toMatchObject({ name: renamedName, kind: 'file', deleted: false })
-
- const renamedRow = currentResources
- .getByRole('listitem')
- .filter({ hasText: renamedName })
- .first()
- await renamedRow.locator('label:has-text("Replace") input[type="file"]').setInputFiles({
- name: renamedName,
- mimeType: 'text/plain',
- buffer: Buffer.from('operator upload v2 extended', 'utf8'),
- })
- await expect(page.getByText('File replaced.').last()).toBeVisible({ timeout: 15_000 })
- await expect
- .poll(
- () =>
- getGfsChildResourceSummary({
- parentResourceId: fixture.resourceId,
- name: renamedName,
- }),
- {
- timeout: 15_000,
- intervals: [250, 500, 1_000],
- }
- )
- .toMatchObject({ bytes: 27, deleted: false })
-
- page.once('dialog', dialog => dialog.accept())
- await currentResources
- .getByRole('listitem')
- .filter({ hasText: renamedName })
- .first()
- .getByRole('button', { name: 'Delete' })
- .click()
- await expect(page.getByText('Resource deleted.').last()).toBeVisible({ timeout: 15_000 })
- await expect
- .poll(
- () =>
- getGfsChildResourceSummary({
- parentResourceId: fixture.resourceId,
- name: renamedName,
- }),
- {
- timeout: 15_000,
- intervals: [250, 500, 1_000],
- }
- )
- .toMatchObject({ deleted: true })
- await expect(
- currentResources.getByRole('listitem').filter({ hasText: renamedName })
- ).toHaveCount(0)
-
- await page.getByRole('button', { name: 'Back' }).click()
- await expect(folderRow(fixture.name)).toBeVisible({
- timeout: 20_000,
- })
- await folderRow(fixture.name).getByRole('button', { name: 'Manage access' }).click()
- await expect(
- page.getByRole('heading', { name: `Manage access \u2014 ${fixture.name}`, exact: true })
- ).toBeVisible()
- })
-
- await test.step('operator grants read/manage_acl to the seeded user through the form', async () => {
- const panel = grantPanel()
- await expect(panel).toBeVisible()
- await expect(panel.getByLabel('Subject ID')).toHaveCount(0)
- const subjectType = panel.getByLabel('Subject type')
- await expect(subjectType).toBeVisible()
- await subjectType.selectOption('user')
- await expect(panel.getByRole('checkbox', { name: 'Include descendants' })).toBeChecked()
- const subjectPicker = panel.getByRole('button', { name: 'User', exact: true })
- await expect(subjectPicker).toContainText('Choose a user')
- await subjectPicker.click()
- await page.getByLabel('Search users...').fill(E2E_TEST_EMAIL)
- const seededUserOption = page
- .locator('.cu-selection-dropdown__option')
- .filter({ hasText: E2E_TEST_EMAIL })
- .first()
- await expect(seededUserOption).toBeVisible({ timeout: 15_000 })
- await seededUserOption.click()
- await panel.getByRole('checkbox', { name: 'read' }).check()
- await panel.getByRole('checkbox', { name: 'manage_acl' }).check()
- await panel.getByRole('button', { name: 'Grant', exact: true }).click()
- const dialog = page.getByRole('alertdialog')
- await expect(dialog).toContainText('Grant access?')
- await dialog.getByRole('button', { name: 'Grant' }).click()
- await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
-
- await expect
- .poll(
- () =>
- getGfsGrantSummary({
- resourceId: fixture.resourceId,
- subjectType: 'user',
- subjectId: targetUserId,
- }),
- { timeout: 15_000, intervals: [250, 500, 1_000] }
- )
- .toMatchObject({
- permissions: ['read', 'manage_acl'],
- inherit: true,
- grantedBy: 'operator:',
- })
- })
-
- await test.step('operator grants read access to a team subject through the same picker', async () => {
- const panel = grantPanel()
- const subjectType = panel.getByLabel('Subject type')
- await subjectType.selectOption('team')
- const subjectPicker = panel.getByRole('button', { name: 'Team', exact: true })
- await expect(subjectPicker).toContainText('Choose a team')
- await subjectPicker.click()
- await page.getByLabel('Search teams...').fill(targetTeam.name)
- const seededTeamOption = page
- .locator('.cu-selection-dropdown__option')
- .filter({ hasText: targetTeam.name })
- .first()
- await expect(seededTeamOption).toBeVisible({ timeout: 15_000 })
- await seededTeamOption.click()
- await expect(subjectPicker).toContainText(targetTeam.name)
- await panel.getByRole('checkbox', { name: 'read' }).check()
- await panel.getByRole('button', { name: 'Grant', exact: true }).click()
- const dialog = page.getByRole('alertdialog')
- await expect(dialog).toContainText('Grant access?')
- await dialog.getByRole('button', { name: 'Grant' }).click()
- await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
-
- await expect
- .poll(
- () =>
- getGfsGrantSummary({
- resourceId: fixture.resourceId,
- subjectType: 'team',
- subjectId: targetTeam.id,
- }),
- { timeout: 15_000, intervals: [250, 500, 1_000] }
- )
- .toMatchObject({
- permissions: ['read'],
- inherit: true,
- grantedBy: 'operator:',
- })
- })
-
- await test.step('operator can seed the intrinsic operator subject from Control UI only', async () => {
- const panel = grantPanel()
- const subjectType = panel.getByLabel('Subject type')
- await subjectType.selectOption('operator')
- await expect(panel.getByText('The intrinsic cluster operator subject')).toBeVisible()
- await expect(panel.getByRole('button', { name: 'User', exact: true })).toHaveCount(0)
- await panel.getByRole('checkbox', { name: 'read' }).check()
- await panel.getByRole('button', { name: 'Grant', exact: true }).click()
- const dialog = page.getByRole('alertdialog')
- await expect(dialog).toContainText('Grant access?')
- await dialog.getByRole('button', { name: 'Grant' }).click()
- await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
-
- await expect
- .poll(
- () =>
- getGfsGrantSummary({
- resourceId: fixture.resourceId,
- subjectType: 'operator',
- }),
- { timeout: 15_000, intervals: [250, 500, 1_000] }
- )
- .toMatchObject({
- permissions: ['read'],
- inherit: true,
- grantedBy: 'operator:',
- })
- })
-
- await test.step('operator grants first-party agent runtime access without free-form host ids', async () => {
- const panel = grantPanel()
- const subjectType = panel.getByLabel('Subject type')
- await subjectType.selectOption('firstPartyAgent')
- const subjectPicker = panel.getByRole('button', { name: 'First-party agent', exact: true })
- await expect(subjectPicker).toContainText('Choose a first-party agent')
- await subjectPicker.click()
- const option = page
- .locator('.cu-selection-dropdown__option')
- .filter({ hasText: 'First-party agent runtime' })
- .first()
- await expect(option).toBeVisible({ timeout: 15_000 })
- await option.click()
- await expect(subjectPicker).toContainText('First-party agent runtime')
- await expect(
- panel.getByRole('button', { name: 'Create share', exact: true })
- ).toBeDisabled()
- await panel.getByRole('checkbox', { name: 'read' }).check()
- await panel.getByRole('checkbox', { name: 'write' }).check()
- await panel.getByRole('button', { name: 'Grant', exact: true }).click()
- const dialog = page.getByRole('alertdialog')
- await expect(dialog).toContainText('Grant access?')
- await dialog.getByRole('button', { name: 'Grant' }).click()
- await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
-
- await expect
- .poll(
- () =>
- getGfsGrantSummary({
- resourceId: fixture.resourceId,
- subjectType: 'host',
- subjectId: '1st:mcp-host/standalone',
- }),
- { timeout: 15_000, intervals: [250, 500, 1_000] }
- )
- .toMatchObject({
- permissions: ['read', 'write'],
- inherit: true,
- grantedBy: 'operator:',
- })
- })
-
- await test.step('operator grants workflow/plugin access from the recipe dropdown', async () => {
- const panel = grantPanel()
- const subjectType = panel.getByLabel('Subject type')
- await subjectType.selectOption('workflowPlugin')
- const subjectPicker = panel.getByRole('button', { name: 'Workflow / plugin', exact: true })
- await expect(subjectPicker).toContainText('Choose a workflow / plugin')
- await subjectPicker.click()
- await page.getByLabel('Search workflows or plugins...').fill(workflowRecipe.name)
- const option = page
- .locator('.cu-selection-dropdown__option')
- .filter({ hasText: workflowRecipe.name })
- .first()
- await expect(option).toBeVisible({ timeout: 20_000 })
- await option.click()
- await expect(subjectPicker).toContainText(workflowRecipe.name)
- await expect(
- panel.getByRole('button', { name: 'Create share', exact: true })
- ).toBeDisabled()
- await panel.getByRole('checkbox', { name: 'read' }).check()
- await panel.getByRole('checkbox', { name: 'write' }).check()
- await panel.getByRole('button', { name: 'Grant', exact: true }).click()
- const dialog = page.getByRole('alertdialog')
- await expect(dialog).toContainText('Grant access?')
- await dialog.getByRole('button', { name: 'Grant' }).click()
- await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
-
- await expect
- .poll(
- () =>
- getGfsGrantSummary({
- resourceId: fixture.resourceId,
- subjectType: 'host',
- subjectId: workflowRecipe.subjectId,
- }),
- { timeout: 15_000, intervals: [250, 500, 1_000] }
- )
- .toMatchObject({
- permissions: ['read', 'write'],
- inherit: true,
- grantedBy: 'operator:',
- })
- })
-
- await test.step('operator cannot submit without visible subject and permissions', async () => {
- const panel = grantPanel()
- await expect(panel.getByLabel('Subject ID')).toHaveCount(0)
- const subjectType = panel.getByLabel('Subject type')
- await expect(subjectType).toBeVisible()
- await subjectType.selectOption('user')
- await expect(panel.getByRole('button', { name: 'Grant', exact: true })).toBeDisabled()
- const subjectPicker = panel.getByRole('button', { name: 'User', exact: true })
- await expect(subjectPicker).toContainText('Choose a user')
- await subjectPicker.click()
- await page.getByLabel('Search users...').fill('not-a-uuid')
- await expect(page.getByText('No matching user options.')).toBeVisible()
- await expect(panel.getByRole('button', { name: 'Grant', exact: true })).toBeDisabled()
- })
- } finally {
- cleanupGfsWorkflowRecipeFixture(workflowRecipe.name)
- cleanupGfsFixture(fixture.name)
- cleanupE2EUserTeam(targetTeam.id)
- }
+ await exerciseGfsBulkOperatorJourney(page)
})
})
diff --git a/control-ui/e2e/gfs-runtime-grants.spec.ts b/control-ui/e2e/gfs-runtime-grants.spec.ts
new file mode 100644
index 000000000..67f73555e
--- /dev/null
+++ b/control-ui/e2e/gfs-runtime-grants.spec.ts
@@ -0,0 +1,172 @@
+import { expect, test } from '@playwright/test'
+import {
+ assertGfsFixtureCleaned,
+ cleanupGfsFixture,
+ cleanupGfsWorkflowRecipeFixture,
+ getGfsGrantSummary,
+ seedGfsFileFixture,
+ seedGfsWorkflowRecipeCloneFixture,
+ uniqueGfsFixtureName,
+} from '../../tests/e2e/gfsUiFixtures'
+import { openGfsFilePanel } from './support/gfs-control-ui-session'
+import {
+ type FirstPartyHostKey,
+ exerciseGfsFirstPartyEffectiveGrantJourney,
+} from './support/gfs-first-party-effective-grants.test'
+import { cleanupNormalGfsPluginRun } from './support/gfs-normal-workflow-cleanup.test'
+import {
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+ startNormalGfsPluginRun,
+} from './support/gfs-normal-workflow-run.test'
+import { expectNormalGfsPluginRunHeld } from './support/gfs-normal-workflow-state.test'
+import { exerciseGfsPluginEffectiveGrantJourney } from './support/gfs-plugin-effective-grants.test'
+
+test.describe('GFS runtime grant enforcement', () => {
+ test('normal WorkflowRecipe run-scoped mcp-host preserves read, write, and combined grants', async ({
+ browserName,
+ page,
+ }) => {
+ test.skip(
+ browserName === 'firefox',
+ 'The normal WorkflowRecipe run-scoped mcp-host journey runs once in Chromium.'
+ )
+ test.setTimeout(600_000)
+
+ const fixtureName = uniqueGfsFixtureName('e2e-gfs-plugin-grant')
+ const unrelatedRecipeName = uniqueGfsFixtureName('e2e-gfs-plugin-isolation')
+ const subjectId = `3rd:${GFS_PLUGIN_NAMESPACE}/${GFS_PLUGIN_RECIPE}`
+ const unrelatedSubjectId = `3rd:${GFS_PLUGIN_NAMESPACE}/${unrelatedRecipeName}`
+ let fixture: ReturnType<typeof seedGfsFileFixture> | undefined
+ let childName: string | undefined
+ let runId: string | undefined
+ let unrelatedChildName: string | undefined
+ let unrelatedRunId: string | undefined
+
+ try {
+ fixture = seedGfsFileFixture(fixtureName)
+ seedGfsWorkflowRecipeCloneFixture(unrelatedRecipeName, GFS_PLUGIN_RECIPE)
+ const { pod, unrelatedPod } =
+ await test.step('operator visibly starts two plugins with independent run-scoped mcp-hosts', async () => {
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId,
+ })
+ ).toBeNull()
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId: unrelatedSubjectId,
+ })
+ ).toBeNull()
+ const grantedRun = await startNormalGfsPluginRun(page, progress => {
+ runId = progress.runId
+ childName = progress.childName
+ })
+ const unrelatedRun = await startNormalGfsPluginRun(
+ page,
+ progress => {
+ unrelatedRunId = progress.runId
+ unrelatedChildName = progress.childName
+ },
+ unrelatedRecipeName
+ )
+ return { pod: grantedRun.pod, unrelatedPod: unrelatedRun.pod }
+ })
+ const panel =
+ await test.step('operator reaches the isolated file through visible Control UI navigation', () =>
+ openGfsFilePanel(page, fixture))
+
+ await exerciseGfsPluginEffectiveGrantJourney({
+ fileResourceId: fixture.fileResourceId,
+ fileUri: fixture.fileUri,
+ initialContent: `E2E GFS file fixture: ${fixture.name}\n`,
+ page,
+ panel,
+ pod,
+ unrelatedPod,
+ updatedContent: `normal third-party workflow updated ${fixture.fileName}`,
+ })
+
+ await test.step('workflow remains approval-held with zero delayed LLM or tool execution', () => {
+ expect(runId).toBeTruthy()
+ expect(childName).toBeTruthy()
+ expectNormalGfsPluginRunHeld(runId!, childName!)
+ expect(unrelatedRunId).toBeTruthy()
+ expect(unrelatedChildName).toBeTruthy()
+ expectNormalGfsPluginRunHeld(unrelatedRunId!, unrelatedChildName!, unrelatedRecipeName)
+ })
+ } finally {
+ try {
+ try {
+ await cleanupNormalGfsPluginRun(runId, childName)
+ } finally {
+ await cleanupNormalGfsPluginRun(unrelatedRunId, unrelatedChildName, unrelatedRecipeName)
+ }
+ } finally {
+ cleanupGfsWorkflowRecipeFixture(unrelatedRecipeName)
+ cleanupGfsFixture(fixtureName)
+ assertGfsFixtureCleaned(fixtureName)
+ if (fixture) {
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId,
+ })
+ ).toBeNull()
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId: unrelatedSubjectId,
+ })
+ ).toBeNull()
+ }
+ }
+ }
+ })
+
+ for (const targetHost of [
+ 'stateful',
+ 'stateless',
+ ] as const satisfies readonly FirstPartyHostKey[]) {
+ test(`first-party ${targetHost} Host consumes grants through its independent runtime identity`, async ({
+ browserName,
+ page,
+ }) => {
+ test.skip(
+ browserName === 'firefox',
+ 'The effective in-cluster first-party Host isolation journey runs once in Chromium.'
+ )
+ test.setTimeout(600_000)
+
+ const fixtureName = uniqueGfsFixtureName(`e2e-gfs-first-party-${targetHost}-grant`)
+ let fixture: ReturnType<typeof seedGfsFileFixture> | undefined
+ try {
+ fixture = seedGfsFileFixture(fixtureName)
+ const panel =
+ await test.step('operator reaches the isolated file through visible Control UI navigation', () =>
+ openGfsFilePanel(page, fixture))
+ await exerciseGfsFirstPartyEffectiveGrantJourney({ fixture, page, panel, targetHost })
+ } finally {
+ cleanupGfsFixture(fixtureName)
+ assertGfsFixtureCleaned(fixtureName)
+ if (fixture) {
+ for (const subjectId of ['1st:mcp-host/chatllm', '1st:mcp-host/chatllm-stateless']) {
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId,
+ })
+ ).toBeNull()
+ }
+ }
+ }
+ })
+ }
+})
diff --git a/control-ui/e2e/qa-recorder-agent-create.spec.ts b/control-ui/e2e/qa-recorder-agent-create.spec.ts
new file mode 100644
index 000000000..e8e9d99c6
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-agent-create.spec.ts
@@ -0,0 +1,140 @@
+import { type Page, expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ type NamedResource,
+ adminCredentials,
+ api,
+ assertAllowedTarget,
+ loginThroughUi,
+ requireRecorderConfirm,
+ requiredValue,
+ resourceName,
+ screenshotAndLog,
+ uniqueE2EName,
+} from './qa-recorder-helpers'
+
+function wizardActions(page: Page) {
+ return page.locator('.cu-create-actions')
+}
+
+async function clickWizardNext(page: Page): Promise<void> {
+ const next = wizardActions(page).getByRole('button', { name: 'Next', exact: true })
+ await expect(next).toBeEnabled()
+ await next.click()
+}
+
+async function requireLlmSecret(
+ request: import('@playwright/test').APIRequestContext
+): Promise<string> {
+ const configured = requiredValue('E2E_AGENT_SECRET_NAME', [process.env.E2E_AGENT_SECRET_NAME])
+ const { status, data } = await api<{ items?: NamedResource[] }>(
+ request,
+ 'GET',
+ '/api/v1/admin/secrets'
+ )
+ if (status !== 200) {
+ throw new Error(`Unable to list LLM secrets before agent creation: HTTP ${status}.`)
+ }
+ const secretNames = (data.items ?? []).map(resourceName).filter(Boolean)
+ if (!secretNames.includes(configured)) {
+ throw new Error(
+ `E2E_AGENT_SECRET_NAME="${configured}" was not found. Choose an explicit disposable-environment secret.`
+ )
+ }
+ return configured
+}
+
+async function cleanupAgentFlowResources(
+ request: import('@playwright/test').APIRequestContext,
+ names: { agentName: string; contextName: string }
+): Promise<void> {
+ await api(request, 'DELETE', `/api/v1/admin/hosts/${encodeURIComponent(names.agentName)}`)
+ await api(request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(names.contextName)}`)
+}
+
+async function waitForAgent(
+ request: import('@playwright/test').APIRequestContext,
+ agentName: string
+): Promise<Record<string, unknown>> {
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ const { status, data } = await api<Record<string, unknown>>(
+ request,
+ 'GET',
+ `/api/v1/admin/hosts/${encodeURIComponent(agentName)}`
+ )
+ if (status === 200) return data
+ await new Promise(resolve => setTimeout(resolve, 500))
+ }
+ throw new Error(`Created agent "${agentName}" did not become visible through Control API.`)
+}
+
+test.describe('optional QA recorder: Control UI agent creation', () => {
+ test('records login and the complete create-agent journey', async ({ page }, testInfo) => {
+ requireRecorderConfirm(
+ 'QA_RECORDER_CONFIRM_MUTATIONS',
+ 'This journey creates and deletes local agent resources.'
+ )
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ const agentName = uniqueE2EName('qa-recorder-agent')
+ const contextName = `${agentName}-ctx`.slice(0, 63).replace(/-$/, '')
+ const memberLabel = process.env.E2E_AGENT_ACCESS_LABEL?.trim()
+
+ try {
+ await loginThroughUi(page, credentials)
+ const sessionRequest = page.request
+ const secretName = await requireLlmSecret(sessionRequest)
+ await cleanupAgentFlowResources(sessionRequest, { agentName, contextName })
+
+ await page.getByRole('link', { name: 'Agents', exact: true }).click()
+ await expect(page).toHaveURL(/\/(?:hosts|agents)$/)
+
+ const createAgent = page.getByRole('button', { name: 'Create agent', exact: true })
+ await expect(createAgent).toBeEnabled()
+ await createAgent.click()
+ await expect(page).toHaveURL(/\/(?:hosts|agents)\/new$/)
+ await expect(page.getByRole('heading', { name: 'Create agent', exact: true })).toBeVisible()
+
+ await page.getByPlaceholder('agent-name').fill(agentName)
+ await clickWizardNext(page)
+
+ await page.getByLabel(/create new context/i).check()
+ await page.getByPlaceholder('context-name').fill(contextName)
+ await clickWizardNext(page)
+
+ await expect(page.getByText('Model & credentials', { exact: true })).toBeVisible()
+ await page.getByLabel(/Reuse an existing Secret/i).check()
+ await page.getByRole('button', { name: /select secret/i }).click()
+ const secretOption = page.locator('.cu-agent-select__option').filter({ hasText: secretName })
+ await expect(secretOption.first()).toBeVisible()
+ await secretOption.first().click()
+ await clickWizardNext(page)
+
+ await expect(page.getByTestId('wizard-users-list')).toBeVisible()
+ if (memberLabel) {
+ await page.getByPlaceholder('Search members...').fill(memberLabel)
+ const memberOption = page.getByRole('option', { name: memberLabel, exact: true })
+ await expect(memberOption).toBeVisible()
+ await memberOption.click()
+ }
+ await clickWizardNext(page)
+
+ const skipChannels = page.getByRole('button', { name: /skip channel setup/i })
+ await expect(skipChannels).toBeEnabled()
+ await skipChannels.click()
+
+ await expect(page).toHaveURL(/\/(?:hosts|agents)$/)
+ const created = await waitForAgent(sessionRequest, agentName)
+ expect((created.metadata as { name?: string } | undefined)?.name).toBe(agentName)
+ expect((created.spec as { contextRef?: string } | undefined)?.contextRef).toBe(contextName)
+ expect((created.spec as { secretRef?: string } | undefined)?.secretRef).toBe(secretName)
+
+ await screenshotAndLog(page, testInfo, 'control-create-agent-complete')
+ } finally {
+ await cleanupAgentFlowResources(page.request, { agentName, contextName })
+ }
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-agents.spec.ts b/control-ui/e2e/qa-recorder-agents.spec.ts
new file mode 100644
index 000000000..6165d46c6
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-agents.spec.ts
@@ -0,0 +1,80 @@
+// control-ui/e2e/qa-recorder-agents.spec.ts
+//
+// Optional QA recorder journey for the Control UI Agents (Hosts) inventory.
+// Read-only: navigates the sidebar 'Agents' destination, asserts the hosts list
+// shell renders, and — when at least one host row is present — opens the detail
+// page and asserts the detail shell plus the tablist. Falls back to the empty
+// state when no agents exist. Uses the shared helpers from
+// qa-recorder-helpers.ts and the built-in `page` fixture (the headful Chromium
+// + video recording are managed by playwright.qa-recorder.config.ts).
+//
+// Contract: docs/testing/optional-playwright-qa-recorder.md ("Extending the recorder").
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+test.describe('optional QA recorder: Control UI agents', () => {
+ test('optional QA recorder: Control UI agents journey', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // Navigate via the sidebar 'Agents' destination (routes to /agents, which
+ // next.config rewrites to the /hosts page — so assert page CONTENT, not URL).
+ await page.getByRole('link', { name: 'Agents', exact: true }).click()
+
+ // List shell: HostTable's TablePanelHeader subtitle is a stable marker that
+ // renders regardless of row count (initial load, populated, or empty).
+ await expect(
+ page.getByText('Manage available agents and their host mappings.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // Wait for either a clickable host row or the empty state. HostTable renders
+ // exactly one of these branches (never both), so .or() is safe here. During
+ // initial load neither matches (skeleton rows use a different class).
+ const rowOrEmpty = page
+ .locator('tr.cu-table__row--clickable')
+ .or(page.getByText('No agents found.', { exact: true }))
+ await expect(rowOrEmpty.first()).toBeVisible({ timeout: 20_000 })
+
+ const rowCount = await page.locator('tr.cu-table__row--clickable').count()
+ if (rowCount > 0) {
+ const firstRow = page.locator('tr.cu-table__row--clickable').first()
+ const ariaLabel = (await firstRow.getAttribute('aria-label')) || ''
+ const hostName = ariaLabel.replace(/^Open agent\s+/i, '').trim()
+
+ // Open the detail page via the row's name link button.
+ if (hostName) {
+ await firstRow.getByRole('button', { name: hostName, exact: true }).click()
+ await expect(
+ page.getByRole('heading', { name: `Agent: ${hostName}`, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ } else {
+ await firstRow.click()
+ await expect(page.getByRole('heading', { name: /^Agent:/ })).toBeVisible({
+ timeout: 20_000,
+ })
+ }
+
+ // Detail shell: the tablist and at least one tab heading render.
+ await expect(page.getByRole('tablist', { name: 'Agent sections' })).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(page.getByRole('tab', { name: 'Overview', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+ } else {
+ await expect(page.getByText('No agents found.', { exact: true })).toBeVisible()
+ }
+
+ await screenshotAndLog(page, testInfo, 'control-ui-agents')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-connectors.spec.ts b/control-ui/e2e/qa-recorder-connectors.spec.ts
new file mode 100644
index 000000000..cec2c2758
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-connectors.spec.ts
@@ -0,0 +1,55 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only Control UI QA recorder journey for the Connectors inventory.
+//
+// The sidebar 'Connectors' link (components/Sidebar/constants.tsx) targets
+// CONTROL_ROUTES.connectors.root (`/connectors`). There is no app/connectors
+// page — next.config.js rewrites `/connectors` -> `/mcp-servers`, so the browser
+// URL stays `/connectors` while app/mcp-servers/page.tsx renders <McpServerTable>.
+// We assert the page shell (TablePanelHeader subtitle + panel title), which
+// renders identically for the loading, populated, and empty states, then
+// best-effort expand the first connector row when one is present.
+
+test.describe('optional QA recorder: Control UI connectors journey', () => {
+ test('records login and the connectors inventory page', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ await page.getByRole('link', { name: 'Connectors', exact: true }).click()
+
+ // The rewrite keeps the URL on /connectors; assert it landed.
+ await expect(page).toHaveURL(/\/connectors\/?$/, { timeout: 20_000 })
+
+ // Shell proof: the TablePanelHeader subtitle is unique and renders regardless of
+ // whether the inventory is loading, populated, or empty.
+ await expect(
+ page.getByText('Browse connector deployments and context bindings.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // Panel title is "Connectors" while loading/empty, or "Connectors (N)" once populated.
+ await expect(page.locator('.cu-panel-title').filter({ hasText: /^Connectors/ })).toBeVisible()
+
+ // Best-effort: if at least one connector row rendered, expand the first one to
+ // exercise the detail panel. Guarded so the journey still passes on an empty inventory.
+ const expandFirst = page.getByRole('button', { name: /^Expand connector / }).first()
+ if (await expandFirst.isVisible({ timeout: 2_000 }).catch(() => false)) {
+ await expandFirst.click()
+ await expect(page.locator('.cu-connector-detail').first()).toBeVisible({
+ timeout: 10_000,
+ })
+ }
+
+ await screenshotAndLog(page, testInfo, 'control-ui-connectors')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-contexts.spec.ts b/control-ui/e2e/qa-recorder-contexts.spec.ts
new file mode 100644
index 000000000..f0cea2824
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-contexts.spec.ts
@@ -0,0 +1,96 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ type NamedResource,
+ adminCredentials,
+ api,
+ assertAllowedTarget,
+ loginThroughUi,
+ resourceName,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+test.describe('optional QA recorder: Control UI contexts journey', () => {
+ test('optional QA recorder: Control UI contexts list journey', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ await page.getByRole('link', { name: 'Contexts', exact: true }).click()
+ await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
+
+ // List shell (TablePanelHeader subtitle) renders regardless of row count.
+ await expect(
+ page.getByText('Group connectors into reusable access scopes.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // The title span reads "Contexts" during initial load and "Contexts (N)" once loaded;
+ // either is a valid shell. Prefer a single concrete selector to avoid strict-mode matches.
+ await expect(page.getByPlaceholder('Search contexts')).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'control-ui-contexts')
+ })
+
+ test('optional QA recorder: Control UI context detail and tab journey', async ({
+ page,
+ }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // Read the inventory through the Control UI proxy (admin session cookie) so the
+ // detail step only runs when a real context exists. Resilient to empty environments.
+ const { status, data } = await api<{ items?: NamedResource[] }>(
+ page.request,
+ 'GET',
+ '/api/v1/admin/contexts'
+ )
+ const contextNames = status === 200 ? (data.items ?? []).map(resourceName).filter(Boolean) : []
+ test.skip(
+ contextNames.length === 0,
+ 'No contexts available in this environment; skipping context detail journey.'
+ )
+ const contextName = contextNames[0]
+
+ await page.getByRole('link', { name: 'Contexts', exact: true }).click()
+ await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
+ await expect(
+ page.getByText('Group connectors into reusable access scopes.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // Open the detail for a known context. onView routes to the connectors tab.
+ await page.getByRole('row', { name: `Open context ${contextName}`, exact: true }).click()
+
+ // Detail shell (CreatePageHeader): the <h2> title is the context name and the
+ // subtitle is stable copy that renders once the context has loaded.
+ await expect(page).toHaveURL(new RegExp(`/contexts/.+`), { timeout: 20_000 })
+ await expect(page.getByRole('heading', { name: contextName, exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(
+ page.getByText('Review details, manage connectors, agents, teams, and members.', {
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'control-ui-context-detail')
+
+ // Exercise a tab switch (Connectors is the default landing tab). Clicking the
+ // Agents tab navigates to /contexts/<name>/agents and renders its panel shell.
+ const agentsTab = page.getByRole('tab', { name: 'Agents', exact: true })
+ await expect(agentsTab).toBeVisible({ timeout: 20_000 })
+ await agentsTab.click()
+ await expect(page).toHaveURL(/\/contexts\/.+\/agents$/, { timeout: 20_000 })
+ await expect(agentsTab).toHaveAttribute('aria-selected', 'true')
+ await expect(page.getByText('Agents using this context.', { exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ await screenshotAndLog(page, testInfo, 'control-ui-context-detail-agents')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-cost-usage.spec.ts b/control-ui/e2e/qa-recorder-cost-usage.spec.ts
new file mode 100644
index 000000000..725d499e1
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-cost-usage.spec.ts
@@ -0,0 +1,78 @@
+// control-ui/e2e/qa-recorder-cost-usage.spec.ts
+//
+// Optional headful QA recorder journey for the Control UI "Cost & Usage" ->
+// "Usage" dashboard. Read-only: navigates through the sidebar, asserts the
+// dashboard shell renders, and exercises one filter change to prove the
+// dashboard is wired up. Creates no cluster resources.
+//
+// Contract: docs/testing/optional-playwright-qa-recorder.md ("Extending the
+// recorder"). The headful Chromium, viewport, slowMo, and video recording are
+// all managed by playwright.qa-recorder.config.ts via the built-in `page`
+// fixture — this spec never launches a browser itself.
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+test.describe('optional QA recorder: Control UI cost and usage journey', () => {
+ test('optional QA recorder: Control UI cost and usage dashboard journey', async ({
+ page,
+ }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // "Cost & Usage" is an expandable sidebar group rendered as a <button>
+ // (its children — LLM Prices, Token Budgets, Usage — only enter the DOM
+ // when the group is expanded). After login we land on /agents, so the
+ // group starts collapsed; expand it, guarding on aria-expanded so this
+ // stays resilient if the group is already open.
+ const costToggle = page.getByRole('button', { name: 'Cost & Usage', exact: true })
+ await expect(costToggle).toBeVisible({ timeout: 20_000 })
+ if ((await costToggle.getAttribute('aria-expanded')) !== 'true') {
+ await costToggle.click()
+ }
+
+ const usageLink = page.getByRole('link', { name: 'Usage', exact: true })
+ await expect(usageLink).toBeVisible({ timeout: 20_000 })
+ await usageLink.click()
+
+ // The sidebar href is the canonical /cost-and-usage/usage (next.config.js
+ // rewrites it to /cost/usage internally; the browser URL stays canonical),
+ // so toHaveURL is safe and confirmed from the source.
+ await expect(page).toHaveURL(/\/cost-and-usage\/usage/, { timeout: 20_000 })
+
+ // Assert the dashboard shell. The TablePanelHeader title and subtitle
+ // render immediately, regardless of how much usage data exists or whether
+ // the chart is still loading — this is the resilient shell assertion.
+ await expect(page.locator('.cu-panel-title').filter({ hasText: 'LLM Usage' })).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(
+ page.getByText('Track token usage and request volume across LLM activity.')
+ ).toBeVisible()
+
+ // Dashboard chrome that always renders: the range + breakdown filters and
+ // the time-series panel title. We intentionally do not assert on the chart
+ // body or the "No usage in the selected range." empty state, since both
+ // depend on live usage data.
+ await expect(page.locator('#usage-range')).toBeVisible()
+ await expect(page.locator('#usage-groupby')).toBeVisible()
+ await expect(page.getByText('Tokens over time', { exact: true })).toBeVisible()
+
+ // Read-only filter change to show the dashboard is interactive. Selecting
+ // by <option> value (not human label text) keeps this resilient to label
+ // copy changes.
+ await page.locator('#usage-range').selectOption('7d')
+ await expect(page.locator('#usage-range')).toHaveValue('7d')
+
+ await screenshotAndLog(page, testInfo, 'control-ui-cost-usage')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-external-channels.spec.ts b/control-ui/e2e/qa-recorder-external-channels.spec.ts
new file mode 100644
index 000000000..29e85aaeb
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-external-channels.spec.ts
@@ -0,0 +1,46 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only inventory/navigation journey: open the External Channels page from
+// the sidebar and assert the channels shell renders. The sidebar label
+// 'External Channels' links to CONTROL_ROUTES.externalChannels.root
+// ('/external-channels'); next.config.js transparently rewrites that to the
+// 'communication-channels' app route, so the browser URL stays
+// '/external-channels'. The page shell (TablePanelHeader title + subtitle)
+// renders for every state (loading skeleton, empty 'No resources found.', or a
+// populated Telegram/Slack/Teams table), so those headings are the resilient
+// assertions rather than table contents.
+test.describe('optional QA recorder: Control UI external channels journey', () => {
+ test('optional QA recorder: Control UI external channels (telegram/email/slack) journey', async ({
+ page,
+ }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ await page.getByRole('link', { name: 'External Channels', exact: true }).click()
+
+ // The canonical public URL is '/external-channels' (confirmed via the
+ // next.config.js rewrite); assert it landed there.
+ await expect(page).toHaveURL(/\/external-channels$/, { timeout: 20_000 })
+
+ // Page shell: the TablePanelHeader title (rendered in '.cu-panel-title')
+ // reads 'Communication channels' while loading/empty and
+ // 'Communication channels (N)' once the list resolves. The subtitle is
+ // stable regardless of data volume.
+ const panelTitle = page.locator('.cu-panel-title')
+ await expect(panelTitle).toContainText('Communication channels', { timeout: 20_000 })
+ await expect(page.getByText('Route channel messages to the selected agent.')).toBeVisible()
+
+ await screenshotAndLog(page, testInfo, 'control-ui-external-channels')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-helpers.ts b/control-ui/e2e/qa-recorder-helpers.ts
new file mode 100644
index 000000000..0d9e25006
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-helpers.ts
@@ -0,0 +1,165 @@
+// control-ui/e2e/qa-recorder-helpers.ts
+//
+// Shared primitives for the optional Control UI QA recorder journeys.
+//
+// Contract: see docs/testing/optional-playwright-qa-recorder.md ("Extending the
+// recorder"). The Control UI recorder drives a headful Chromium managed by
+// playwright.qa-recorder.config.ts (the `page` fixture), so these helpers only
+// cover shared plumbing: admin credentials, UI login, the Control API proxy,
+// the loopback target guard, opt-in confirmations, and named screenshot/video
+// proof capture. Journey-specific interactions stay inside their own specs.
+import { type APIRequestContext, type Page, type TestInfo, expect } from '@playwright/test'
+
+export const CONTROL_UI_URL = process.env.CONTROL_UI_URL || 'http://127.0.0.1:3000'
+export const CONTROL_API_URL = process.env.CONTROL_API_URL || 'http://127.0.0.1:8090'
+const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1'])
+
+export type ApiResult<T = Record<string, unknown>> = {
+ data: T
+ status: number
+}
+
+export type NamedResource = {
+ metadata?: { name?: string; namespace?: string }
+ name?: string
+}
+
+/** Require an explicit opt-in confirmation variable before a journey that writes/mutates. */
+export function requireRecorderConfirm(flag: string, description: string): void {
+ if (process.env[flag] !== '1') {
+ throw new Error(
+ `${description} Set ${flag}=1 in .env.qa-recorder to run this recorder journey.`
+ )
+ }
+}
+
+/** Refuse non-loopback targets unless the operator explicitly allowed a remote QA env. */
+export function assertAllowedTarget(label: string, rawUrl: string): void {
+ let url: URL
+ try {
+ url = new URL(rawUrl)
+ } catch {
+ throw new Error(`${label} must be an absolute URL; received "${rawUrl}".`)
+ }
+ if (!LOOPBACK_HOSTS.has(url.hostname) && process.env.QA_RECORDER_ALLOW_REMOTE !== '1') {
+ throw new Error(
+ `${label} targets non-local host "${url.hostname}". Set QA_RECORDER_ALLOW_REMOTE=1 only when that environment is intentionally disposable.`
+ )
+ }
+ if (LOOPBACK_HOSTS.has(url.hostname) && process.env.QA_RECORDER_ALLOW_REMOTE !== '1') {
+ void assertControlUiUp(rawUrl, label)
+ }
+}
+
+async function assertControlUiUp(baseUrl: string, label: string): Promise<void> {
+ try {
+ const res = await fetch(baseUrl, { redirect: 'manual' })
+ // 200 (app) or 3xx (auth redirect) both prove the UI is reachable.
+ if (res.status >= 500) throw new Error(`HTTP ${res.status}`)
+ } catch (err) {
+ throw new Error(
+ `[qa-recorder] ${label} not reachable at ${baseUrl}: ${(err as Error).message}. Is the control-ui dev server running on :3000?`
+ )
+ }
+}
+
+export function requiredValue(label: string, candidates: Array<string | undefined>): string {
+ const value = candidates.find(candidate => candidate?.trim())?.trim()
+ if (!value) throw new Error(`${label} is required for this recorder journey.`)
+ return value
+}
+
+export function adminCredentials(): { username: string; password: string } {
+ return {
+ username: requiredValue('ADMIN_USER', [
+ process.env.E2E_ADMIN_USER,
+ process.env.ADMIN_USER,
+ process.env.ADMIN_USERNAME,
+ ]),
+ password: requiredValue('an admin password', [
+ process.env.E2E_ADMIN_PASSWORD,
+ process.env.ADMIN_PASSWORD,
+ process.env.ADMIN_PASS,
+ process.env.TEST_ADMIN_PASSWORD,
+ ]),
+ }
+}
+
+/** Unique lowercase k8s-name-safe identifier for temporary resources. */
+export function uniqueE2EName(base: string): string {
+ // Date.now()/Math.random() are fine here — this runs at test runtime in Node,
+ // not inside a Workflow script.
+ return `${base}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`
+ .toLowerCase()
+ .replace(/[^a-z0-9-]/g, '-')
+ .slice(0, 63)
+ .replace(/-$/, '')
+}
+
+/**
+ * Call Control API through the Control UI proxy (`/control-api/*`) using the
+ * browser session's cookies. Pass `page.request` so the admin auth set by
+ * loginThroughUi is reused.
+ */
+export async function api<T = Record<string, unknown>>(
+ request: APIRequestContext,
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE',
+ pathName: string,
+ body?: unknown
+): Promise<ApiResult<T>> {
+ const response = await request.fetch(`${CONTROL_UI_URL}/control-api${pathName}`, {
+ method,
+ headers: {
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
+ },
+ data: body,
+ })
+ const text = await response.text()
+ let data = {} as T
+ try {
+ data = text ? (JSON.parse(text) as T) : ({} as T)
+ } catch {
+ data = { raw: text } as T
+ }
+ return { status: response.status(), data }
+}
+
+export function resourceName(item: NamedResource): string {
+ return String(item.name || item.metadata?.name || '').trim()
+}
+
+/** Sign in through the real Control UI. Dismisses the "Remind me later" notice if present. */
+export async function loginThroughUi(
+ page: Page,
+ credentials: { username: string; password: string }
+): Promise<void> {
+ await page.goto(CONTROL_UI_URL)
+ await expect(page.getByRole('button', { name: /^Sign in$/ })).toBeVisible({
+ timeout: 20_000,
+ })
+ await page.getByLabel('Username or email').fill(credentials.username)
+ await page.getByLabel('Password').fill(credentials.password)
+ await page.getByRole('button', { name: /^Sign in$/ }).click()
+ await expect(page.getByRole('navigation', { name: 'Main sections' })).toBeVisible({
+ // Next dev compiles routes on first hit; allow headroom for the authed
+ // shell to appear after a slow compile or control-api round-trip.
+ timeout: 60_000,
+ })
+
+ const remindLater = page.getByRole('button', { name: 'Remind me later' })
+ if (await remindLater.isVisible({ timeout: 3_000 }).catch(() => false)) {
+ await remindLater.click()
+ }
+}
+
+/** Take a full-page PNG proof and log its path. The PNG stem is also the key used to group the test's video later. */
+export async function screenshotAndLog(
+ page: Page,
+ testInfo: TestInfo,
+ name: string
+): Promise<void> {
+ const screenshotPath = testInfo.outputPath(`${name}.png`)
+ await page.screenshot({ path: screenshotPath, fullPage: true })
+ // eslint-disable-next-line no-console
+ console.log(`[qa-recorder] Control UI screenshot: ${screenshotPath}`)
+}
diff --git a/control-ui/e2e/qa-recorder-llm-models.spec.ts b/control-ui/e2e/qa-recorder-llm-models.spec.ts
new file mode 100644
index 000000000..41fa6550e
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-llm-models.spec.ts
@@ -0,0 +1,47 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Optional QA recorder journey: LLM Models catalog + Secrets management pages.
+// Read-only — only asserts the two inventory pages render their shells after
+// sign-in. No model/secret is created, edited, or deleted.
+
+test.describe('optional QA recorder: Control UI LLM models and secrets', () => {
+ test('records the LLM models catalog and secrets pages', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ const mainNav = page.getByRole('navigation', { name: 'Main sections' })
+
+ // (1) LLM Models catalog. The sidebar entry may be a direct link or an
+ // expandable group (button -> 'Catalog' child); click the label, then follow
+ // the Catalog child link if it appears. Assert the canonical URL and that the
+ // models table rendered (the 'Context window' column header is a stable shell
+ // marker that renders regardless of row count).
+ await mainNav.getByText('LLM Models', { exact: true }).click()
+ const catalogLink = mainNav.getByRole('link', { name: 'Catalog', exact: true })
+ if (await catalogLink.isVisible().catch(() => false)) {
+ await catalogLink.click()
+ }
+ await expect(page).toHaveURL(/\/llm-models/, { timeout: 20_000 })
+ await expect(page.getByText('Context window').first()).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-llm-models')
+
+ // (2) Secrets management (LLM scope). 'Secrets' is a direct sidebar link to
+ // /secrets/llm. Assert the canonical URL and that the page loaded within the
+ // authenticated shell (the 'Main sections' nav persists).
+ await mainNav.getByRole('link', { name: 'Secrets', exact: true }).click()
+ await expect(page).toHaveURL(/\/secrets\/(llm|mcp|recipe)/, { timeout: 20_000 })
+ await expect(mainNav).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-secrets')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-login.spec.ts b/control-ui/e2e/qa-recorder-login.spec.ts
new file mode 100644
index 000000000..a1113e8ea
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-login.spec.ts
@@ -0,0 +1,59 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: it never creates or mutates cluster resources, so no
+// requireRecorderConfirm(...) gate is required. Every test still guards the
+// loopback/reachability contract for both the UI and the Control API proxy.
+test.describe('optional QA recorder: Control UI login and authenticated shell journey', () => {
+ test('sign-in page renders before authentication', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ // Fresh page, no loginThroughUi: assert the unauthenticated sign-in form.
+ await page.goto(CONTROL_UI_URL)
+
+ const signInButton = page.getByRole('button', { name: /^Sign in$/ })
+ await expect(signInButton).toBeVisible({ timeout: 20_000 })
+
+ const usernameField = page.getByLabel('Username or email')
+ await expect(usernameField).toBeVisible({ timeout: 20_000 })
+
+ const passwordField = page.getByLabel('Password')
+ await expect(passwordField).toBeVisible({ timeout: 20_000 })
+
+ // The submit button stays disabled until both fields are non-empty; here we
+ // only assert it renders, not that it is enabled.
+ await expect(signInButton).toBeVisible()
+
+ await screenshotAndLog(page, testInfo, 'control-login-form')
+ })
+
+ test('signing in reveals the authenticated shell', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+
+ // loginThroughUi fills Username/Password, clicks Sign in, and waits for the
+ // 'Main sections' navigation to mount. It also dismisses "Remind me later".
+ await loginThroughUi(page, credentials)
+
+ await expect(page.getByRole('navigation', { name: 'Main sections' })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // The 'Agents' sidebar link is the primary authenticated destination; it
+ // renders inside the Main sections nav regardless of cluster inventory.
+ const agentsLink = page.getByRole('link', { name: 'Agents', exact: true })
+ await expect(agentsLink).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'control-authenticated-shell')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-marketplace.spec.ts b/control-ui/e2e/qa-recorder-marketplace.spec.ts
new file mode 100644
index 000000000..4dbc822c1
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-marketplace.spec.ts
@@ -0,0 +1,77 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only inventory/navigation journey for the Marketplace (registry catalog)
+// and Plugins (installed workflow recipes) shells. The sidebar 'Marketplace'
+// link (href /marketplace/connectors) is rewritten transparently to the
+// /registry page (RegistryCatalog); 'Plugins' (href /plugins) is rewritten to
+// /workflow-recipes (RecipesTab). Both rewrites keep the source URL in the
+// address bar, so toHaveURL asserts the canonical sidebar href.
+//
+// Each page renders a TablePanelHeader whose title is a plain <span> (not a
+// heading role), so the shell is asserted via the header subtitle (unique,
+// unconditional text) plus a stable header control, which render regardless of
+// data volume or empty/loading/error state.
+
+test.describe('optional QA recorder: Control UI marketplace and plugins journey', () => {
+ test('marketplace catalog shell renders for connectors', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ await page.getByRole('link', { name: 'Marketplace', exact: true }).click()
+ await expect(page).toHaveURL(/\/marketplace\/connectors$/)
+
+ // Shell proof: the TablePanelHeader subtitle renders regardless of catalog
+ // size, filters, or empty state.
+ await expect(
+ page.getByText('Discover and install connectors and plugins from the Marketplace.')
+ ).toBeVisible({ timeout: 20_000 })
+
+ // The Marketplace entry-type tablist (Connectors / Plugins) is part of the
+ // shell. Scope to the named tablist so the locator is unambiguous.
+ const entryTabs = page.getByRole('tablist', { name: 'Marketplace entry types' })
+ await expect(entryTabs.getByRole('tab', { name: 'Connectors', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(entryTabs.getByRole('tab', { name: 'Plugins', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ await screenshotAndLog(page, testInfo, 'control-ui-marketplace')
+ })
+
+ test('plugins catalog shell renders', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ await page.getByRole('link', { name: 'Plugins', exact: true }).click()
+ await expect(page).toHaveURL(/\/plugins$/)
+
+ // Shell proof: the RecipesTab header subtitle renders whether or not any
+ // plugin is installed (the empty state shows beneath it).
+ await expect(
+ page.getByText('Select a plugin to view status, run history, and actions.')
+ ).toBeVisible({ timeout: 20_000 })
+
+ // The header CTAs are always present on the Plugins shell (disabled only
+ // during the very first load), so they are reliable shell markers.
+ await expect(page.getByRole('button', { name: 'Install Plugin', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ await screenshotAndLog(page, testInfo, 'control-ui-plugins')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-navigation.spec.ts b/control-ui/e2e/qa-recorder-navigation.spec.ts
new file mode 100644
index 000000000..84894e6b7
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-navigation.spec.ts
@@ -0,0 +1,105 @@
+// control-ui/e2e/qa-recorder-navigation.spec.ts
+//
+// Optional QA recorder journey that walks the Control UI sidebar's main
+// destinations in turn and asserts each destination's page shell renders.
+// Read-only: no cluster resources are created or mutated. Uses the shared
+// helpers from qa-recorder-helpers.ts and the built-in `page` fixture (the
+// headful Chromium + video recording are managed by
+// playwright.qa-recorder.config.ts).
+//
+// Contract: docs/testing/optional-playwright-qa-recorder.md ("Extending the recorder").
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+test.describe('optional QA recorder: Control UI navigation', () => {
+ test('optional QA recorder: Control UI navigation journey', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // The sidebar's primary nav region. 'Settings' lives in the footer outside
+ // this region, so it is targeted with a global locator below.
+ const mainNav = page.getByRole('navigation', { name: 'Main sections' })
+
+ // 1) Agents — sidebar href is /agents, which next.config rewrites to the
+ // /hosts page (the browser URL is not stable across rewrites), so assert
+ // page CONTENT (HostTable's TablePanelHeader subtitle), not the URL.
+ await mainNav.getByRole('link', { name: 'Agents', exact: true }).click()
+ await expect(
+ page.getByText('Manage available agents and their host mappings.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-agents')
+
+ // 2) Contexts — /contexts is a real App Router segment; URL is stable.
+ await mainNav.getByRole('link', { name: 'Contexts', exact: true }).click()
+ await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
+ await expect(
+ page.getByText('Group connectors into reusable access scopes.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-contexts')
+
+ // 3) Connectors — sidebar href is /connectors (rewritten from /mcp-servers);
+ // the browser URL stays /connectors.
+ await mainNav.getByRole('link', { name: 'Connectors', exact: true }).click()
+ await expect(page).toHaveURL(/\/connectors\/?$/, { timeout: 20_000 })
+ await expect(
+ page.getByText('Browse connector deployments and context bindings.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-connectors')
+
+ // 4) External Channels — sidebar href is /external-channels (rewritten from
+ // /communication-channels); the browser URL stays /external-channels.
+ await mainNav.getByRole('link', { name: 'External Channels', exact: true }).click()
+ await expect(page).toHaveURL(/\/external-channels$/, { timeout: 20_000 })
+ await expect(
+ page.getByText('Route channel messages to the selected agent.', { exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-external-channels')
+
+ // 5) LLM Models — this is an expandable sidebar GROUP rendered as a <button>
+ // (not a link), so clicking it only toggles its subnav. Expand the group,
+ // then follow the 'Catalog' child link (href = CONTROL_ROUTES.llmModels.root
+ // = /llm-models) into the model catalog page. Scope to the sidebar nav so
+ // the 'Catalog' match is unambiguous.
+ await mainNav.getByRole('button', { name: 'LLM Models', exact: true }).click()
+ await mainNav.getByRole('link', { name: 'Catalog', exact: true }).click()
+ await expect(page).toHaveURL(/\/llm-models/, { timeout: 20_000 })
+ // The subtitle is long; anchor on a unique leading substring.
+ await expect(
+ page.getByText('Operator-declared allowlist of usable models per provider')
+ ).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-llm-models')
+
+ // 6) Users & Teams — sidebar href is /users-and-teams/users (rewritten from
+ // /profile-admin/users); the browser URL stays /users-and-teams/users.
+ await mainNav.getByRole('link', { name: 'Users & Teams', exact: true }).click()
+ await expect(page).toHaveURL(/\/users-and-teams\/users$/, { timeout: 20_000 })
+ await expect(
+ page.getByText(
+ 'Members and teams grant Desktop App access. Admins grant Control UI access.',
+ { exact: true }
+ )
+ ).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-users-teams')
+
+ // 7) Settings — rendered in the sidebar FOOTER (outside 'Main sections').
+ // Sidebar href is /settings/ui (rewritten from /settings); the browser
+ // URL stays /settings/ui. Target the link globally since it is not in the
+ // mainNav region.
+ await page.getByRole('link', { name: 'Settings', exact: true }).click()
+ await expect(page).toHaveURL(/\/settings\/ui/, { timeout: 20_000 })
+ await expect(page.getByText('Manage your Control UI admin account and theme.')).toBeVisible({
+ timeout: 20_000,
+ })
+ await screenshotAndLog(page, testInfo, 'control-ui-navigation-settings')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-settings.spec.ts b/control-ui/e2e/qa-recorder-settings.spec.ts
new file mode 100644
index 000000000..a55aaa514
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-settings.spec.ts
@@ -0,0 +1,39 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: sign in, open the Settings page from the sidebar, and
+// assert the page shell renders. No setting is changed.
+test.describe('optional QA recorder: Control UI settings journey', () => {
+ test('records login and the read-only settings page journey', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // The sidebar 'Settings' link points at /settings/ui (CONTROL_ROUTES.settings.ui).
+ // next.config.js rewrites /settings/ui -> /settings transparently, so the
+ // browser URL stays /settings/ui while the app/settings/page.tsx shell renders.
+ await page.getByRole('link', { name: 'Settings', exact: true }).click()
+ await expect(page).toHaveURL(/\/settings\/ui/, { timeout: 20_000 })
+
+ // Assert the settings page shell. TablePanelHeader renders the title in a
+ // <span> (not a heading), so anchor on the unique subtitle + section titles,
+ // which render regardless of the account data loading/empty/error state.
+ await expect(page.getByText('Manage your Control UI admin account and theme.')).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(page.getByText('Account info', { exact: true })).toBeVisible()
+ await expect(page.getByText('Appearance', { exact: true })).toBeVisible()
+ await expect(page.getByRole('radiogroup', { name: 'Theme' })).toBeVisible()
+
+ await screenshotAndLog(page, testInfo, 'control-ui-settings')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-traces.spec.ts b/control-ui/e2e/qa-recorder-traces.spec.ts
new file mode 100644
index 000000000..5aa037cce
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-traces.spec.ts
@@ -0,0 +1,101 @@
+import { expect, test } from '@playwright/test'
+import { CONTROL_ROUTES } from '../app/constants/routes'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: it never creates or mutates cluster resources, so no
+// requireRecorderConfirm(...) gate is required. Every test still guards the
+// loopback/reachability contract for both the UI and the Control API proxy.
+test.describe('optional QA recorder: Control UI traces journey', () => {
+ test('records the Traces dashboard (operations) shell after sign-in', async ({
+ page,
+ }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // The 'Traces' sidebar group is marked hidden in the canonical sidebar
+ // config (components/Sidebar/constants.tsx), so it is not rendered in the
+ // left nav. Navigate directly to the operations (Dashboard) route via its
+ // builder from app/constants/routes.ts.
+ await page.goto(`${CONTROL_UI_URL}${CONTROL_ROUTES.traces.operations}`)
+
+ // The TablePanelHeader shell renders regardless of data state
+ // (initialLoading / unavailable / populated), so the panel title is the
+ // stable shell assertion. The title is a <span class="cu-panel-title">,
+ // not a heading role, so match it via the class filter used elsewhere.
+ const dashboardTitle = page
+ .locator('.cu-panel-title')
+ .filter({ hasText: /^Tracing dashboard$/ })
+ await expect(dashboardTitle).toBeVisible({ timeout: 20_000 })
+
+ await expect(
+ page.getByText('Current control-api ingestion health and effective limits.', {
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'control-ui-traces')
+ })
+
+ test('records the traces dashboard state (loading, unavailable, or populated)', async ({
+ page,
+ }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ await page.goto(`${CONTROL_UI_URL}${CONTROL_ROUTES.traces.operations}`)
+
+ // Wait for the shell to mount before asserting the body state.
+ await expect(
+ page.locator('.cu-panel-title').filter({ hasText: /^Tracing dashboard$/ })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // The body is one of three exclusive states (see TracingOperations/index.tsx):
+ // 1. initialLoading -> "Loading tracing health…"
+ // 2. unavailable -> "Tracing health unavailable" (role="alert")
+ // 3. snapshot -> the cu-trace-ops-body with charts/limits/errors
+ // To avoid strict-mode violations from overlapping matches, assert that
+ // exactly one of these state markers is present (.first() guards against
+ // any duplicate renders).
+ const loadingState = page.getByText('Loading tracing health…', { exact: true })
+ const unavailableState = page.getByText('Tracing health unavailable', { exact: true })
+ const bodyState = page.locator('.cu-trace-ops-body')
+
+ await expect
+ .poll(
+ async () => {
+ const [loading, unavailable, body] = await Promise.all([
+ loadingState.count(),
+ unavailableState.count(),
+ bodyState.count(),
+ ])
+ return loading + unavailable + body
+ },
+ { timeout: 20_000 }
+ )
+ .toBeGreaterThanOrEqual(1)
+
+ // Best-effort: if the body is populated, exercise the Refresh CTA in the
+ // panel header to confirm the action wiring stays inert over read-only
+ // inventory. Skipped silently when the body has not loaded yet.
+ if ((await bodyState.count()) > 0) {
+ const refresh = page.getByRole('button', { name: 'Refresh tracing health', exact: true })
+ await expect(refresh).toBeEnabled({ timeout: 10_000 })
+ await refresh.click()
+ }
+
+ await screenshotAndLog(page, testInfo, 'control-ui-traces-state')
+ })
+})
diff --git a/control-ui/e2e/qa-recorder-users-teams.spec.ts b/control-ui/e2e/qa-recorder-users-teams.spec.ts
new file mode 100644
index 000000000..846c195db
--- /dev/null
+++ b/control-ui/e2e/qa-recorder-users-teams.spec.ts
@@ -0,0 +1,56 @@
+import { expect, test } from '@playwright/test'
+import {
+ CONTROL_API_URL,
+ CONTROL_UI_URL,
+ adminCredentials,
+ assertAllowedTarget,
+ loginThroughUi,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only inventory/navigation journey for the Control UI Users & Teams
+// directory. It signs in through the real UI, opens the members (users)
+// directory from the sidebar, then switches to the teams list via the in-page
+// tab navigation, asserting each page shell renders. It tolerates empty,
+// loading, and error states by anchoring on the TablePanelHeader tablist and
+// the per-tab primary CTA, both of which render regardless of data volume.
+
+test.describe('optional QA recorder: Control UI users and teams journey', () => {
+ test('records the users and teams directory navigation', async ({ page }, testInfo) => {
+ assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
+ assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
+
+ const credentials = adminCredentials()
+ await loginThroughUi(page, credentials)
+
+ // Open the Users & Teams directory from the sidebar. The sidebar entry links
+ // to the canonical /users-and-teams/users route (rewritten internally to
+ // /profile-admin/users); the browser URL stays /users-and-teams/users.
+ await page.getByRole('link', { name: 'Users & Teams', exact: true }).click()
+ await expect(page).toHaveURL(/\/users-and-teams\/users$/, { timeout: 20_000 })
+
+ // Page shell: the Users & Teams tablist is unique to this page and renders
+ // even while the member list is loading or empty.
+ const sectionTabs = page.getByRole('tablist', { name: 'Users and teams sections' })
+ await expect(sectionTabs).toBeVisible({ timeout: 20_000 })
+ // The "Create member" CTA only renders on the members (users) tab.
+ await expect(page.getByRole('button', { name: 'Create member', exact: true })).toBeVisible()
+
+ // Switch to the teams list using the in-page tab navigation. While the
+ // members tab is active the Teams tab is always labeled exactly "Teams"
+ // (the count is only appended to the active tab). It is rendered as a
+ // disabled button during initial load, so wait for it to become an enabled
+ // link before clicking.
+ const teamsTab = page.getByRole('tab', { name: 'Teams', exact: true })
+ await expect(teamsTab).toBeEnabled({ timeout: 20_000 })
+ await teamsTab.click()
+ await expect(page).toHaveURL(/\/users-and-teams\/teams$/, { timeout: 20_000 })
+
+ // Teams page shell: the same tablist is present, and the "Create team" CTA
+ // only renders on the teams tab.
+ await expect(sectionTabs).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByRole('button', { name: 'Create team', exact: true })).toBeVisible()
+
+ await screenshotAndLog(page, testInfo, 'control-ui-users-teams')
+ })
+})
diff --git a/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts b/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts
new file mode 100644
index 000000000..80f27dcc2
--- /dev/null
+++ b/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts
@@ -0,0 +1,315 @@
+import { type Page, expect, test } from '@playwright/test'
+import {
+ assertGfsFixtureCleaned,
+ cleanupE2EUserTeamByName,
+ cleanupGfsFixture,
+ cleanupGfsWorkflowRecipeFixture,
+ firstDataLine,
+ getE2EUserId,
+ getGfsGrantSummary,
+ kubectlOut,
+ runControlPostgresSql,
+ seedE2EUserTeam,
+ seedGfsDirectoryFixture,
+ seedGfsWorkflowRecipeFixture,
+ sqlLiteral,
+ uniqueGfsFixtureName,
+} from '../../../tests/e2e/gfsUiFixtures'
+import { E2E_TEST_EMAIL, E2E_TEST_NAME } from '../../../tests/e2e/testUser'
+import { exerciseGfsBulkShareJourney } from './gfs-bulk-share-journey.test'
+import {
+ CONTROL_UI_BASE_URL,
+ loginControlUi,
+ openGlobalFileSystemFromSidebar,
+} from './gfs-control-ui-session'
+import { exerciseGfsPerHostIsolationJourney } from './gfs-per-host-isolation-journey.test'
+import { exerciseGfsResourceCrudJourney } from './gfs-resource-crud-journey.test'
+
+const SUBJECT_PICKER_LABEL = 'Add people, teams, agents, or workflows'
+
+async function chooseGrantSubject(
+ panel: ReturnType<Page['getByRole']>,
+ search: string,
+ optionName: string
+): Promise<void> {
+ const input = panel.getByRole('combobox', { name: SUBJECT_PICKER_LABEL })
+ await input.fill(search)
+ const option = panel.getByRole('option', { name: optionName, exact: true })
+ await expect(option).toBeVisible({ timeout: 20_000 })
+ await option.click()
+}
+
+async function choosePermission(
+ panel: ReturnType<Page['getByRole']>,
+ permissionName: string
+): Promise<void> {
+ const menu = panel.getByRole('menu', { name: 'Permissions' })
+ if (!(await menu.isVisible().catch(() => false))) {
+ await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
+ }
+ await menu.getByRole('menuitemcheckbox', { name: permissionName, exact: true }).click()
+}
+
+export async function exerciseGfsBulkOperatorJourney(page: Page): Promise<void> {
+ const targetUserId = getE2EUserId()
+ const fixtureName = uniqueGfsFixtureName('e2e-gfs-operator')
+ const teamName = uniqueGfsFixtureName('e2e-gfs-team')
+ const workflowName = uniqueGfsFixtureName('e2e-gfs-workflow')
+
+ try {
+ const fixture = seedGfsDirectoryFixture(fixtureName)
+ const targetTeam = seedE2EUserTeam(E2E_TEST_EMAIL, teamName)
+ const workflowRecipe = seedGfsWorkflowRecipeFixture(workflowName)
+ const grantPanel = () =>
+ page.getByRole('dialog', { name: `Manage folder ${fixture.name}`, exact: true })
+ const folderRow = (name: string) =>
+ page
+ .getByRole('list', { name: 'Current folder resources' })
+ .getByRole('listitem')
+ .filter({ has: page.getByRole('button', { name, exact: true }) })
+ .first()
+
+ await test.step('operator logs in and navigates to Global File System through the sidebar', async () => {
+ await loginControlUi(page)
+ await openGlobalFileSystemFromSidebar(page)
+ await expect(page).toHaveURL(/\/global-file-system(?:$|\?)/, { timeout: 15_000 })
+ await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()
+ })
+
+ await exerciseGfsResourceCrudJourney({
+ baseUi: CONTROL_UI_BASE_URL,
+ fixture,
+ folderRow,
+ page,
+ })
+ await test.step('operator selects a mixed user, team, and per-runtime host batch through the visible picker', async () => {
+ const panel = grantPanel()
+ await expect(panel).toBeVisible()
+ await expect(panel.getByLabel('Subject ID')).toHaveCount(0)
+ await expect(panel.getByRole('checkbox', { name: 'Include descendants' })).toBeChecked()
+
+ await chooseGrantSubject(panel, E2E_TEST_EMAIL, E2E_TEST_NAME)
+ await chooseGrantSubject(panel, targetTeam.name, targetTeam.name)
+ const selectedSubjects = panel.getByLabel('Grant subject', { exact: true })
+ await expect(selectedSubjects).toContainText(E2E_TEST_NAME)
+ await expect(selectedSubjects).toContainText(targetTeam.name)
+
+ await choosePermission(panel, 'Manage access')
+ await choosePermission(panel, 'Share')
+ await chooseGrantSubject(panel, 'chatllm', 'chatllm (Stateful)')
+ await chooseGrantSubject(panel, 'chatllm-stateless', 'chatllm-stateless (Stateless)')
+ await expect(selectedSubjects).toContainText('chatllm (Stateful)')
+ await expect(selectedSubjects).toContainText('chatllm-stateless (Stateless)')
+ await expect(panel.getByText(/host selections are limited to read and write/i)).toBeVisible()
+
+ await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
+ const permissionMenu = panel.getByRole('menu', { name: 'Permissions' })
+ await expect(
+ permissionMenu.getByRole('menuitemcheckbox', { name: 'Manage access' })
+ ).toHaveCount(0)
+ await expect(permissionMenu.getByRole('menuitemcheckbox', { name: 'Share' })).toHaveCount(0)
+ await expect(permissionMenu.getByRole('menuitemcheckbox', { name: 'Delete' })).toHaveCount(0)
+ await expect(panel.getByRole('button', { name: 'Create share', exact: true })).toBeDisabled()
+
+ await chooseGrantSubject(panel, workflowRecipe.name, workflowRecipe.name)
+ await expect(selectedSubjects).toContainText(workflowRecipe.name)
+ await expect(selectedSubjects.getByRole('button', { name: /^Remove / })).toHaveCount(5)
+ await choosePermission(panel, 'Read')
+ await choosePermission(panel, 'Write')
+ })
+
+ await test.step('operator confirms one atomic bulk grant and sees persisted access', async () => {
+ const panel = grantPanel()
+ const grantResponsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'PUT' &&
+ response.url().includes('/control-api/api/v1/gfs/grants')
+ )
+ await panel.getByRole('button', { name: 'Grant access', exact: true }).click()
+ const dialog = page.getByRole('alertdialog')
+ await expect(dialog).toContainText('Grant access?')
+ await expect(dialog).toContainText(fixture.name)
+ await expect(dialog).toContainText(/5 subjects/i)
+ await expect(dialog).toContainText(/read, write/)
+ await dialog.getByRole('button', { name: 'Grant' }).click()
+ const grantResponse = await grantResponsePromise
+ expect(grantResponse.status(), `${grantResponse.url()} ${await grantResponse.text()}`).toBe(
+ 200
+ )
+
+ const submittedBody = grantResponse.request().postDataJSON() as {
+ subject?: unknown
+ subjects?: Array<{ type: string; id?: string }>
+ permissions?: string[]
+ }
+ const expectedSubjects = [
+ { type: 'user', id: targetUserId },
+ { type: 'team', id: targetTeam.id },
+ { type: 'host', id: '1st:mcp-host/chatllm' },
+ { type: 'host', id: '1st:mcp-host/chatllm-stateless' },
+ { type: 'host', id: workflowRecipe.subjectId },
+ ] as const
+ expect(submittedBody.subject).toBeUndefined()
+ expect(submittedBody.subjects).toEqual(expectedSubjects)
+ expect(submittedBody.permissions).toEqual(['read', 'write'])
+ await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
+
+ for (const subject of expectedSubjects) {
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: subject.type,
+ subjectId: subject.id,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({
+ permissions: ['read', 'write'],
+ inherit: true,
+ grantedBy: 'operator:',
+ })
+ }
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId: '1st:mcp-host/standalone',
+ })
+ ).toBeNull()
+ })
+
+ await test.step('closing and reopening the modal rehydrates persisted access and allows revocation', async () => {
+ const panel = grantPanel()
+ await panel.getByRole('button', { name: 'Close manage dialog' }).click()
+ await expect(panel).toHaveCount(0)
+
+ await page.reload()
+ await expect(page).toHaveURL(/\/global-file-system(?:$|\?)/, { timeout: 15_000 })
+ await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()
+ const row = folderRow(fixture.name)
+ await expect(row).toBeVisible({ timeout: 20_000 })
+ await row.getByRole('button', { name: `Actions for ${fixture.name}` }).click()
+ await page.getByRole('menuitem', { name: 'Manage access' }).click()
+ const reopenedPanel = grantPanel()
+ await expect(reopenedPanel).toBeVisible()
+ const existingAccess = reopenedPanel.getByRole('region', { name: 'Existing access' })
+ await expect(existingAccess.getByText(E2E_TEST_NAME, { exact: true })).toBeVisible()
+ await expect(existingAccess.getByText(targetTeam.name, { exact: true })).toBeVisible()
+ await expect(existingAccess.getByText('chatllm (Stateful)', { exact: true })).toBeVisible()
+ await expect(
+ existingAccess.getByText('chatllm-stateless (Stateless)', { exact: true })
+ ).toBeVisible()
+ await expect(existingAccess.getByText(workflowRecipe.name, { exact: true })).toBeVisible()
+ await expect(
+ existingAccess.getByText('Grant · read, write · resource and descendants')
+ ).toHaveCount(5)
+
+ const revokeResponsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'DELETE' &&
+ response.url().includes('/control-api/api/v1/gfs/grants/')
+ )
+ await existingAccess
+ .getByRole('button', { name: `Remove grant access for ${E2E_TEST_NAME}` })
+ .click()
+ const confirmation = page.getByRole('alertdialog')
+ await expect(confirmation).toContainText('Remove access?')
+ await confirmation.getByRole('button', { name: 'Remove access' }).click()
+ const revokeResponse = await revokeResponsePromise
+ expect(
+ revokeResponse.status(),
+ `${revokeResponse.url()} ${await revokeResponse.text()}`
+ ).toBe(200)
+ await expect(page.getByText('Access removed.').last()).toBeVisible({ timeout: 15_000 })
+ await expect(existingAccess.getByText(E2E_TEST_NAME, { exact: true })).toHaveCount(0)
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'user',
+ subjectId: targetUserId,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toBeNull()
+ })
+
+ await exerciseGfsPerHostIsolationJourney({
+ fixture,
+ page,
+ unchangedHostSubjectIds: ['1st:mcp-host/chatllm-stateless', workflowRecipe.subjectId],
+ })
+ await exerciseGfsBulkShareJourney({
+ fixture,
+ page,
+ targetTeam,
+ targetUserEmail: E2E_TEST_EMAIL,
+ targetUserId,
+ })
+
+ await test.step('operator remains a distinct singular grant target', async () => {
+ const panel = grantPanel()
+ await chooseGrantSubject(panel, 'Operator', 'Operator')
+ await expect(panel.getByRole('button', { name: 'Remove Operator' })).toBeVisible()
+ await choosePermission(panel, 'Read')
+ await panel.getByRole('button', { name: 'Grant access', exact: true }).click()
+ const dialog = page.getByRole('alertdialog')
+ await expect(dialog).toContainText('Grant access?')
+ await expect(dialog).toContainText(/operator/i)
+ await dialog.getByRole('button', { name: 'Grant' }).click()
+ await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'operator',
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ permissions: ['read'], inherit: true, grantedBy: 'operator:' })
+ })
+
+ await test.step('operator cannot submit without visible subject and permissions', async () => {
+ const panel = grantPanel()
+ await expect(panel.getByLabel('Subject ID')).toHaveCount(0)
+ await expect(panel.getByRole('button', { name: 'Grant access', exact: true })).toBeDisabled()
+ await panel.getByRole('combobox', { name: SUBJECT_PICKER_LABEL }).fill('not-a-uuid')
+ await expect(panel.getByText('No subjects found.')).toBeVisible()
+ await expect(panel.getByRole('button', { name: 'Grant access', exact: true })).toBeDisabled()
+ })
+ } finally {
+ try {
+ cleanupGfsWorkflowRecipeFixture(workflowName)
+ expect(
+ kubectlOut([
+ '-n',
+ 'sandbox-recipes',
+ 'get',
+ 'workflowrecipe',
+ workflowName,
+ '--ignore-not-found=true',
+ '-o',
+ 'name',
+ ]).trim()
+ ).toBe('')
+ } finally {
+ try {
+ cleanupGfsFixture(fixtureName)
+ assertGfsFixtureCleaned(fixtureName)
+ } finally {
+ cleanupE2EUserTeamByName(teamName)
+ expect(
+ firstDataLine(
+ runControlPostgresSql(
+ `SELECT COUNT(*)::text FROM teams WHERE name = ${sqlLiteral(teamName)};`
+ )
+ )
+ ).toBe('0')
+ }
+ }
+ }
+}
diff --git a/control-ui/e2e/support/gfs-bulk-share-journey.test.ts b/control-ui/e2e/support/gfs-bulk-share-journey.test.ts
new file mode 100644
index 000000000..a4afb3018
--- /dev/null
+++ b/control-ui/e2e/support/gfs-bulk-share-journey.test.ts
@@ -0,0 +1,79 @@
+import { type Page, expect, test } from '@playwright/test'
+import { getGfsShareSummary } from '../../../tests/e2e/gfsUiFixtures'
+
+type BulkShareJourneyInput = {
+ fixture: { name: string; resourceId: string }
+ page: Page
+ targetTeam: { id: string; name: string }
+ targetUserEmail: string
+ targetUserId: string
+}
+
+export async function exerciseGfsBulkShareJourney({
+ fixture,
+ page,
+ targetTeam,
+ targetUserEmail,
+ targetUserId,
+}: BulkShareJourneyInput): Promise<void> {
+ await test.step('operator creates one persisted user/team bulk share through the visible UI', async () => {
+ const panel = page.getByRole('dialog', {
+ name: `Manage folder ${fixture.name}`,
+ exact: true,
+ })
+ const subjectSearch = panel.getByRole('combobox', {
+ name: 'Add people, teams, agents, or workflows',
+ })
+ await expect(subjectSearch).toBeVisible()
+ await subjectSearch.fill(targetUserEmail)
+ await panel.getByRole('option').filter({ hasText: targetUserEmail }).first().click()
+ await subjectSearch.fill(targetTeam.name)
+ await panel.getByRole('option', { name: targetTeam.name, exact: true }).click()
+
+ await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
+ await panel.getByRole('menuitemcheckbox', { name: 'Read', exact: true }).click()
+ const shareResponsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'POST' &&
+ response.url().includes('/control-api/api/v1/gfs/shares')
+ )
+ await panel.getByRole('button', { name: 'Create share', exact: true }).click()
+ const confirmation = page.getByRole('alertdialog')
+ await expect(confirmation).toContainText('Create share?')
+ await expect(confirmation).toContainText(/2 subjects/i)
+ await expect(confirmation).toContainText(/read/)
+ await confirmation.getByRole('button', { name: 'Create share' }).click()
+
+ const shareResponse = await shareResponsePromise
+ expect(shareResponse.status(), `${shareResponse.url()} ${await shareResponse.text()}`).toBe(200)
+ const submittedBody = shareResponse.request().postDataJSON() as {
+ subject?: unknown
+ subjects?: Array<{ type: string; id?: string }>
+ permissions?: string[]
+ }
+ expect(submittedBody.subject).toBeUndefined()
+ expect(submittedBody.subjects).toEqual([
+ { type: 'user', id: targetUserId },
+ { type: 'team', id: targetTeam.id },
+ ])
+ expect(submittedBody.permissions).toEqual(['read'])
+ await expect(page.getByText('Share created.').last()).toBeVisible({ timeout: 15_000 })
+
+ for (const subject of [
+ { type: 'user' as const, id: targetUserId },
+ { type: 'team' as const, id: targetTeam.id },
+ ]) {
+ await expect
+ .poll(
+ () =>
+ getGfsShareSummary({
+ resourceId: fixture.resourceId,
+ subjectType: subject.type,
+ subjectId: subject.id,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ permissions: ['read'], includeDescendants: true, createdBy: 'operator:' })
+ }
+ })
+}
diff --git a/control-ui/e2e/support/gfs-control-ui-session.ts b/control-ui/e2e/support/gfs-control-ui-session.ts
new file mode 100644
index 000000000..759ffe6d4
--- /dev/null
+++ b/control-ui/e2e/support/gfs-control-ui-session.ts
@@ -0,0 +1,103 @@
+import { type Locator, type Page, expect } from '@playwright/test'
+
+export const CONTROL_UI_BASE_URL =
+ process.env.CONTROL_UI_BASE_URL || process.env.CONTROL_UI_URL || 'http://localhost:3000'
+
+function localAdminCredentials(): { password: string; username: string } {
+ const url = new URL(CONTROL_UI_BASE_URL)
+ const isLocal = url.hostname === '127.0.0.1' || url.hostname === 'localhost'
+ const password =
+ process.env.E2E_ADMIN_PASSWORD ||
+ process.env.ADMIN_PASSWORD ||
+ process.env.ADMIN_PASS ||
+ process.env.TEST_ADMIN_PASSWORD ||
+ (isLocal ? 'changeme123!' : '')
+ const username =
+ process.env.E2E_ADMIN_USERNAME ||
+ process.env.ADMIN_USER ||
+ process.env.ADMIN_USERNAME ||
+ process.env.TEST_ADMIN_USERNAME ||
+ (isLocal ? 'admin' : '')
+ if (!password || !username) {
+ throw new Error(
+ 'Control UI E2E credentials are required for non-local URLs; set E2E_ADMIN_PASSWORD and E2E_ADMIN_USERNAME'
+ )
+ }
+ return { password, username }
+}
+
+export async function loginControlUi(page: Page): Promise<void> {
+ const credentials = localAdminCredentials()
+ await page.goto(CONTROL_UI_BASE_URL)
+ const signIn = page.getByRole('button', { name: 'Sign in' })
+ const navigation = page.getByRole('navigation', { name: 'Main sections' })
+ const entryState = await Promise.race([
+ signIn
+ .last()
+ .waitFor({ state: 'visible', timeout: 60_000 })
+ .then(() => 'login' as const),
+ navigation.waitFor({ state: 'visible', timeout: 60_000 }).then(() => 'authenticated' as const),
+ ])
+ if (entryState === 'login') {
+ await expect(page.getByLabel('Username or email')).toBeVisible()
+ await page.getByLabel('Username or email').fill(credentials.username)
+ await expect(page.getByLabel('Password')).toBeVisible()
+ await page.getByLabel('Password').fill(credentials.password)
+ await expect(signIn.last()).toBeEnabled({ timeout: 10_000 })
+ await signIn.last().click()
+ }
+ await expect(navigation).toBeVisible({ timeout: 20_000 })
+ const sessionCookie = (await page.context().cookies()).find(
+ cookie => cookie.name === 'control_ui_admin_session'
+ )
+ expect(sessionCookie).toBeDefined()
+ expect(sessionCookie?.httpOnly).toBe(true)
+ await expect
+ .poll(() => page.evaluate(() => window.localStorage.getItem('controlUiAdminToken')))
+ .toBeNull()
+
+ const remindLater = page.getByRole('button', { name: 'Remind me later' })
+ if (await remindLater.isVisible({ timeout: 3_000 }).catch(() => false)) {
+ await remindLater.click()
+ await expect(remindLater).toBeHidden({ timeout: 10_000 })
+ }
+}
+
+export async function openGlobalFileSystemFromSidebar(page: Page): Promise<void> {
+ const directoriesSection = page.getByRole('button', { name: 'Directories', exact: true })
+ await expect(directoriesSection).toBeVisible()
+ await directoriesSection.click()
+ const globalFileSystem = page.getByRole('link', {
+ name: 'Global File System',
+ exact: true,
+ })
+ await expect(globalFileSystem).toBeVisible()
+ await globalFileSystem.click()
+}
+
+export async function openGfsFilePanel(
+ page: Page,
+ fixture: { fileName: string; name: string }
+): Promise<Locator> {
+ await loginControlUi(page)
+ await openGlobalFileSystemFromSidebar(page)
+ await expect(page).toHaveURL(/\/global-file-system(?:$|\?)/, { timeout: 15_000 })
+ await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()
+ const resources = page.getByRole('list', { name: 'Current folder resources' })
+ await resources.getByRole('button', { name: fixture.name, exact: true }).click()
+ const actions = resources.getByRole('button', {
+ name: `Actions for ${fixture.fileName}`,
+ exact: true,
+ })
+ await expect(actions).toBeVisible({ timeout: 20_000 })
+ await actions.click()
+ const manageAccess = resources.getByRole('menuitem', { name: 'Manage access', exact: true })
+ await expect(manageAccess).toBeVisible()
+ await manageAccess.click()
+ const panel = page.getByRole('dialog', {
+ name: `Manage file ${fixture.fileName}`,
+ exact: true,
+ })
+ await expect(panel).toBeVisible()
+ return panel
+}
diff --git a/control-ui/e2e/support/gfs-first-party-effective-grants.test.ts b/control-ui/e2e/support/gfs-first-party-effective-grants.test.ts
new file mode 100644
index 000000000..9cf6553aa
--- /dev/null
+++ b/control-ui/e2e/support/gfs-first-party-effective-grants.test.ts
@@ -0,0 +1,365 @@
+import { type Locator, type Page, expect, test } from '@playwright/test'
+import {
+ type GfsFileFixture,
+ getGfsGrantSummary,
+ kubectlOut,
+} from '../../../tests/e2e/gfsUiFixtures'
+
+const HOST_NAMESPACE = 'mcp-host'
+const STATEFUL_HOST_NAME = 'chatllm'
+const STATEFUL_HOST_LABEL = 'chatllm (Stateful)'
+const STATELESS_HOST_NAME = 'chatllm-stateless'
+const STATELESS_HOST_LABEL = 'chatllm-stateless (Stateless)'
+const SUBJECT_PICKER_LABEL = 'Add people, teams, agents, or workflows'
+const FIRST_PARTY_HOSTS = {
+ stateful: {
+ hostName: STATEFUL_HOST_NAME,
+ label: STATEFUL_HOST_LABEL,
+ subjectId: '1st:mcp-host/chatllm',
+ },
+ stateless: {
+ hostName: STATELESS_HOST_NAME,
+ label: STATELESS_HOST_LABEL,
+ subjectId: '1st:mcp-host/chatllm-stateless',
+ },
+} as const
+
+export type FirstPartyHostKey = keyof typeof FIRST_PARTY_HOSTS
+
+type GfsToolName = 'clerum__gfs_read' | 'clerum__gfs_stat' | 'clerum__gfs_write'
+type GfsToolOutput = { content: string; is_error: boolean }
+type GfsResourceEnvelope = { ok: boolean; data: { version: number } }
+type FirstPartyHostRuntime = { hostName: string; podName: string }
+type PodList = {
+ items: Array<{
+ metadata?: { deletionTimestamp?: string; name?: string }
+ status?: { conditions?: Array<{ status?: string; type?: string }> }
+ }>
+}
+type JourneyInput = {
+ fixture: Pick<GfsFileFixture, 'fileResourceId' | 'name'>
+ page: Page
+ panel: Locator
+ targetHost: FirstPartyHostKey
+}
+
+function readyFirstPartyHostPod(hostName: string): string {
+ const selector = [
+ `app=${hostName}`,
+ `clerum.io/host=${hostName}`,
+ 'clerum.io/managed-by=host-context-controller',
+ ].join(',')
+ const deadline = Date.now() + 30_000
+ do {
+ try {
+ kubectlOut(
+ ['-n', HOST_NAMESPACE, 'wait', '--for=create', 'pod', '-l', selector, '--timeout=5s'],
+ 7_000
+ )
+ kubectlOut(
+ [
+ '-n',
+ HOST_NAMESPACE,
+ 'wait',
+ '--for=condition=Ready',
+ 'pod',
+ '-l',
+ selector,
+ '--timeout=5s',
+ ],
+ 7_000
+ )
+ } catch {
+ // The bounded wait is the poll interval; inspect only converged Ready pods below.
+ }
+ const pods = JSON.parse(
+ kubectlOut(['-n', HOST_NAMESPACE, 'get', 'pod', '-l', selector, '-o', 'json'], 10_000)
+ ) as PodList
+ const ready = pods.items.filter(
+ pod =>
+ !pod.metadata?.deletionTimestamp &&
+ pod.status?.conditions?.some(
+ condition => condition.type === 'Ready' && condition.status === 'True'
+ )
+ )
+ if (ready.length === 1 && ready[0]?.metadata?.name) return ready[0].metadata.name
+ } while (Date.now() < deadline)
+ throw new Error(
+ `first-party Host ${HOST_NAMESPACE}/${hostName} did not converge to one non-terminating Ready pod`
+ )
+}
+
+function runGfsTool(
+ runtime: FirstPartyHostRuntime,
+ toolName: GfsToolName,
+ args: Record<string, unknown>
+): GfsToolOutput {
+ const script = `
+const { config } = require('./dist/config.js');
+const { NativeToolRegistry } = require('./dist/core/tools/nativeToolRegistry.js');
+const registry = new NativeToolRegistry(config.nativeTool, 'gfs-first-party-effective-grants-e2e');
+const registeredNames = registry.listDefinitions().map(definition => definition.name);
+if (!registeredNames.includes('clerum__gfs_read') || !registeredNames.includes('clerum__gfs_write')) {
+ throw new Error('NativeToolRegistry did not register the GFS tools');
+}
+const tool = registry.get(process.argv[1]);
+if (!tool) throw new Error('requested GFS tool is unavailable');
+tool.execute(JSON.parse(process.argv[2])).then(result => {
+ process.stdout.write(JSON.stringify(result));
+}).catch(error => {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+});
+`
+ const output = kubectlOut(
+ [
+ '-n',
+ HOST_NAMESPACE,
+ 'exec',
+ runtime.podName,
+ '-c',
+ 'mcp-host',
+ '--',
+ 'node',
+ '-e',
+ script,
+ toolName,
+ JSON.stringify(args),
+ ],
+ 20_000
+ ).trim()
+ const result = JSON.parse(output.split('\n').filter(Boolean).at(-1) ?? '') as GfsToolOutput
+ if (typeof result.is_error !== 'boolean' || typeof result.content !== 'string') {
+ throw new Error(
+ `first-party Host ${runtime.hostName} returned an invalid result for ${toolName}`
+ )
+ }
+ return result
+}
+
+function parseEnvelope(result: GfsToolOutput): GfsResourceEnvelope {
+ expect(result.is_error, result.content).toBe(false)
+ const envelope = JSON.parse(result.content) as GfsResourceEnvelope
+ expect(envelope).toMatchObject({ ok: true, data: { version: expect.any(Number) } })
+ return envelope
+}
+
+function expectDenied(result: GfsToolOutput): void {
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(/gfsc 403/i)
+}
+
+function expectReadWriteDenied(
+ runtime: FirstPartyHostRuntime,
+ resourceId: string,
+ content: string,
+ ifMatch: number
+): void {
+ expectDenied(runGfsTool(runtime, 'clerum__gfs_read', { drive: 'main', resourceId }))
+ expectDenied(
+ runGfsTool(runtime, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId,
+ content,
+ ifMatch,
+ })
+ )
+}
+
+async function chooseHost(panel: Locator, targetHost: FirstPartyHostKey): Promise<void> {
+ const host = FIRST_PARTY_HOSTS[targetHost]
+ const input = panel.getByRole('combobox', { name: SUBJECT_PICKER_LABEL })
+ await expect(input).toBeVisible()
+ await input.fill(host.hostName)
+ const option = panel.getByRole('option', { name: host.label, exact: true })
+ await expect(option).toBeVisible({ timeout: 20_000 })
+ await option.click()
+ const selected = panel.getByLabel('Grant subject', { exact: true })
+ await expect(selected.getByRole('button', { name: `Remove ${host.label}` })).toBeVisible()
+ await expect(selected.getByRole('button', { name: /^Remove / })).toHaveCount(1)
+}
+
+async function choosePermissions(
+ panel: Locator,
+ permissionNames: Array<'Read' | 'Write'>
+): Promise<void> {
+ await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
+ const menu = panel.getByRole('menu', { name: 'Permissions' })
+ await expect(menu).toBeVisible()
+ for (const permissionName of permissionNames) {
+ const checkbox = menu.getByRole('menuitemcheckbox', { name: permissionName, exact: true })
+ await checkbox.click()
+ await expect(checkbox).toHaveAttribute('aria-checked', 'true')
+ }
+}
+
+async function submitGrant(
+ page: Page,
+ panel: Locator,
+ permissions: Array<'read' | 'write'>,
+ resourceId: string,
+ targetHost: FirstPartyHostKey
+): Promise<void> {
+ const target = FIRST_PARTY_HOSTS[targetHost]
+ const other = FIRST_PARTY_HOSTS[targetHost === 'stateful' ? 'stateless' : 'stateful']
+ const responsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'PUT' &&
+ response.url().includes('/control-api/api/v1/gfs/grants')
+ )
+ await panel.getByRole('button', { name: 'Grant access', exact: true }).click()
+ const confirmation = page.getByRole('alertdialog')
+ await expect(confirmation).toContainText('Grant access?')
+ await expect(confirmation).toContainText(/1 subject/i)
+ for (const permission of permissions) {
+ await expect(confirmation).toContainText(new RegExp(permission, 'i'))
+ }
+ await confirmation.getByRole('button', { name: 'Grant', exact: true }).click()
+
+ const response = await responsePromise
+ expect(response.status(), `${response.url()} ${await response.text()}`).toBe(200)
+ const body = response.request().postDataJSON() as {
+ resourceId?: string
+ subject?: unknown
+ subjects?: Array<{ type: string; id: string }>
+ permissions?: string[]
+ }
+ expect(body).toMatchObject({
+ resourceId,
+ subjects: [{ type: 'host', id: target.subjectId }],
+ permissions,
+ })
+ expect(body.subject).toBeUndefined()
+ await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId,
+ subjectType: 'host',
+ subjectId: target.subjectId,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ permissions, grantedBy: 'operator:' })
+ expect(
+ getGfsGrantSummary({
+ resourceId,
+ subjectType: 'host',
+ subjectId: other.subjectId,
+ })
+ ).toBeNull()
+}
+
+export async function exerciseGfsFirstPartyEffectiveGrantJourney({
+ fixture,
+ page,
+ panel,
+ targetHost,
+}: JourneyInput): Promise<void> {
+ const resourceId = fixture.fileResourceId
+ const initialContent = `E2E GFS file fixture: ${fixture.name}\n`
+ const rejectedContent = `first-party rejected update for ${fixture.name}`
+ const runtimes =
+ await test.step('resolve each concrete first-party Host runtime once', async () => ({
+ stateful: {
+ hostName: STATEFUL_HOST_NAME,
+ podName: readyFirstPartyHostPod(STATEFUL_HOST_NAME),
+ },
+ stateless: {
+ hostName: STATELESS_HOST_NAME,
+ podName: readyFirstPartyHostPod(STATELESS_HOST_NAME),
+ },
+ }))
+ const targetRuntime = runtimes[targetHost]
+ const otherRuntime = runtimes[targetHost === 'stateful' ? 'stateless' : 'stateful']
+ const target = FIRST_PARTY_HOSTS[targetHost]
+
+ await test.step('both concrete first-party Hosts are denied before any grant exists', async () => {
+ for (const host of Object.values(FIRST_PARTY_HOSTS)) {
+ expect(
+ getGfsGrantSummary({ resourceId, subjectType: 'host', subjectId: host.subjectId })
+ ).toBeNull()
+ }
+ expectReadWriteDenied(runtimes.stateful, resourceId, rejectedContent, 1)
+ expectReadWriteDenied(runtimes.stateless, resourceId, rejectedContent, 1)
+ })
+
+ await test.step(`operator grants read only to ${target.hostName} through the visible Control UI`, async () => {
+ await chooseHost(panel, targetHost)
+ await choosePermissions(panel, ['Read'])
+ await submitGrant(page, panel, ['read'], resourceId, targetHost)
+ })
+
+ let currentVersion = 0
+ await test.step(`read-only enables ${target.hostName} read but not write and remains isolated`, async () => {
+ expect(
+ runGfsTool(targetRuntime, 'clerum__gfs_read', { drive: 'main', resourceId })
+ ).toMatchObject({ content: initialContent, is_error: false })
+ currentVersion = parseEnvelope(
+ runGfsTool(targetRuntime, 'clerum__gfs_stat', { drive: 'main', resourceId })
+ ).data.version
+ expectDenied(
+ runGfsTool(targetRuntime, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId,
+ content: rejectedContent,
+ ifMatch: currentVersion,
+ })
+ )
+ expectReadWriteDenied(otherRuntime, resourceId, rejectedContent, currentVersion)
+ })
+
+ await test.step(`operator replaces the ${target.hostName} grant with write only through the UI`, async () => {
+ await chooseHost(panel, targetHost)
+ await choosePermissions(panel, ['Write'])
+ await submitGrant(page, panel, ['write'], resourceId, targetHost)
+ })
+
+ const writeOnlyContent = `first-party write-only update for ${fixture.name}`
+ await test.step(`write-only enables ${target.hostName} write but not read and remains isolated`, async () => {
+ expectDenied(runGfsTool(targetRuntime, 'clerum__gfs_read', { drive: 'main', resourceId }))
+ const write = parseEnvelope(
+ runGfsTool(targetRuntime, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId,
+ content: writeOnlyContent,
+ ifMatch: currentVersion,
+ })
+ )
+ expect(write.data.version).toBe(currentVersion + 1)
+ currentVersion = write.data.version
+ expectReadWriteDenied(otherRuntime, resourceId, writeOnlyContent, currentVersion)
+ })
+
+ await test.step(`operator upgrades the ${target.hostName} grant to read and write through the UI`, async () => {
+ await chooseHost(panel, targetHost)
+ await choosePermissions(panel, ['Read', 'Write'])
+ await submitGrant(page, panel, ['read', 'write'], resourceId, targetHost)
+ })
+
+ const readWriteContent = `first-party read-write update for ${fixture.name}`
+ await test.step('combined grant preserves read-back, versioned write, and host isolation', async () => {
+ expect(
+ runGfsTool(targetRuntime, 'clerum__gfs_read', { drive: 'main', resourceId })
+ ).toMatchObject({ content: writeOnlyContent, is_error: false })
+ const write = parseEnvelope(
+ runGfsTool(targetRuntime, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId,
+ content: readWriteContent,
+ ifMatch: currentVersion,
+ })
+ )
+ expect(write.data.version).toBe(currentVersion + 1)
+ currentVersion = write.data.version
+ expect(
+ runGfsTool(targetRuntime, 'clerum__gfs_read', { drive: 'main', resourceId })
+ ).toMatchObject({ content: readWriteContent, is_error: false })
+ expect(
+ parseEnvelope(runGfsTool(targetRuntime, 'clerum__gfs_stat', { drive: 'main', resourceId }))
+ .data.version
+ ).toBe(currentVersion)
+ expectReadWriteDenied(otherRuntime, resourceId, readWriteContent, currentVersion)
+ })
+}
diff --git a/control-ui/e2e/support/gfs-normal-workflow-cleanup.test.ts b/control-ui/e2e/support/gfs-normal-workflow-cleanup.test.ts
new file mode 100644
index 000000000..9a7f58e1e
--- /dev/null
+++ b/control-ui/e2e/support/gfs-normal-workflow-cleanup.test.ts
@@ -0,0 +1,205 @@
+import { expect } from '@playwright/test'
+import {
+ UUID_RE,
+ firstDataLine,
+ kubectlOut,
+ runControlPostgresSql,
+ sqlLiteral,
+} from '../../../tests/e2e/gfsUiFixtures'
+import {
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+ type WorkflowRecipeResource,
+} from './gfs-normal-workflow-run.test'
+
+// Covers one 25s Kubernetes delete, a late-child observation allowance, and
+// the required 10s quiet window within the enclosing 600s journey budget.
+const CLEANUP_TIMEOUT_MS = 75_000
+const LATE_CHILD_QUIET_WINDOW_MS = 10_000
+
+function workflowRecipeOrUndefined(name: string): WorkflowRecipeResource | undefined {
+ const raw = kubectlOut([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ name,
+ '--ignore-not-found=true',
+ '-o',
+ 'json',
+ ]).trim()
+ return raw ? (JSON.parse(raw) as WorkflowRecipeResource) : undefined
+}
+
+function isVerifiedRunChild(
+ child: WorkflowRecipeResource,
+ input: { childName: string; parentName: string; parentUid: string; runId: string }
+): boolean {
+ const owners = child.metadata?.ownerReferences ?? []
+ const owner = owners[0]
+ return (
+ child.metadata?.name === input.childName &&
+ child.metadata?.namespace === GFS_PLUGIN_NAMESPACE &&
+ child.metadata?.labels?.['clerum.io/workflow-run-id'] === input.runId &&
+ child.metadata?.labels?.['clerum.io/parent-recipe'] === input.parentName &&
+ owners.length === 1 &&
+ owner?.controller === true &&
+ owner.apiVersion === 'clerum.io/v1alpha1' &&
+ owner.kind === 'WorkflowRecipe' &&
+ owner.name === input.parentName &&
+ owner.uid === input.parentUid
+ )
+}
+
+function namesByLabel(namespace: string, resources: string, selector: string): string[] {
+ return kubectlOut(['-n', namespace, 'get', resources, '-l', selector, '-o', 'name'])
+ .split('\n')
+ .map(value => value.trim())
+ .filter(Boolean)
+ .sort()
+}
+
+function runChildNames(runId: string): string[] {
+ return namesByLabel(GFS_PLUGIN_NAMESPACE, 'workflowrecipe', `clerum.io/workflow-run-id=${runId}`)
+}
+
+function deleteVerifiedRunChildren(
+ runId: string,
+ candidateNames: string[],
+ recipeName: string
+): { deleted: number; names: string[] } {
+ const parent = workflowRecipeOrUndefined(recipeName)
+ const parentUid = parent?.metadata?.uid ?? ''
+ const discoveredNames = runChildNames(runId).map(name => name.slice(name.indexOf('/') + 1))
+ const names = [...new Set([...candidateNames, ...discoveredNames])]
+ let deleted = 0
+ for (const childName of names) {
+ if (childName === recipeName) {
+ throw new Error(`Refusing to clean parent WorkflowRecipe for run ${runId}`)
+ }
+ const child = workflowRecipeOrUndefined(childName)
+ if (!child) continue
+ if (
+ !parentUid ||
+ !isVerifiedRunChild(child, { childName, parentName: recipeName, parentUid, runId })
+ ) {
+ throw new Error(
+ `Refusing to delete unverified workflow child ${GFS_PLUGIN_NAMESPACE}/${childName} for run ${runId}`
+ )
+ }
+ kubectlOut(
+ [
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'delete',
+ 'workflowrecipe',
+ childName,
+ '--wait=true',
+ '--timeout=25s',
+ ],
+ CLEANUP_TIMEOUT_MS
+ )
+ deleted += 1
+ }
+ return { deleted, names }
+}
+
+function leakedRuntimeResources(candidateNames: string[], runId: string) {
+ const childNames = runChildNames(runId).map(name => name.slice(name.indexOf('/') + 1))
+ const names = [...new Set([...candidateNames, ...childNames])]
+ const sandboxResources = names.flatMap(name =>
+ namesByLabel(
+ GFS_PLUGIN_NAMESPACE,
+ 'pod,service,secret,networkpolicy,configmap,persistentvolumeclaim',
+ `clerum.io/recipe=${name}`
+ )
+ )
+ const transportResources = names.flatMap(name =>
+ namesByLabel(
+ 'mcp-server',
+ 'mcpserver,context,service,deployment,secret',
+ `clerum.io/recipe=${name}`
+ )
+ )
+ return {
+ childRecipes: runChildNames(runId),
+ sandboxResources: [...new Set(sandboxResources)].sort(),
+ transportResources: [...new Set(transportResources)].sort(),
+ }
+}
+
+export async function cleanupNormalGfsPluginRun(
+ runId: string | undefined,
+ observedChildName: string | undefined,
+ recipeName = GFS_PLUGIN_RECIPE
+): Promise<void> {
+ if (!runId || !UUID_RE.test(runId)) return
+
+ const persistedChildName = firstDataLine(
+ runControlPostgresSql(`
+ UPDATE workflow_runs
+ SET phase = 'Canceled', completed_at = COALESCE(completed_at, now()), updated_at = now()
+ WHERE run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(recipeName)}
+ RETURNING child_recipe_name;
+ `)
+ )
+ let candidates = [...new Set([observedChildName, persistedChildName].filter(Boolean))] as string[]
+
+ let lastChildActivityAt = Date.now()
+ await expect
+ .poll(
+ () => {
+ const cleanup = deleteVerifiedRunChildren(runId, candidates, recipeName)
+ candidates = cleanup.names
+ if (cleanup.deleted > 0) lastChildActivityAt = Date.now()
+ return {
+ ...leakedRuntimeResources(candidates, runId),
+ quietWindowElapsed: Date.now() - lastChildActivityAt >= LATE_CHILD_QUIET_WINDOW_MS,
+ }
+ },
+ {
+ timeout: CLEANUP_TIMEOUT_MS,
+ intervals: [500, 1_000, 2_000],
+ message: `workflow run ${runId} should stop creating children after cancellation`,
+ }
+ )
+ .toEqual({
+ childRecipes: [],
+ sandboxResources: [],
+ transportResources: [],
+ quietWindowElapsed: true,
+ })
+
+ runControlPostgresSql(`
+ DELETE FROM workflow_approval_requests
+ WHERE bound_workflow_run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(recipeName)};
+ DELETE FROM workflow_runs
+ WHERE run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(recipeName)};
+ `)
+
+ expect(leakedRuntimeResources(candidates, runId)).toEqual({
+ childRecipes: [],
+ sandboxResources: [],
+ transportResources: [],
+ })
+
+ expect(
+ firstDataLine(
+ runControlPostgresSql(`
+ SELECT
+ (SELECT COUNT(*) FROM workflow_approval_requests
+ WHERE bound_workflow_run_id = ${sqlLiteral(runId)}::uuid)::text || '|' ||
+ (SELECT COUNT(*) FROM workflow_run_steps
+ WHERE run_id = ${sqlLiteral(runId)}::uuid)::text || '|' ||
+ (SELECT COUNT(*) FROM workflow_runs
+ WHERE run_id = ${sqlLiteral(runId)}::uuid)::text;
+ `)
+ )
+ ).toBe('0|0|0')
+}
diff --git a/control-ui/e2e/support/gfs-normal-workflow-constants.ts b/control-ui/e2e/support/gfs-normal-workflow-constants.ts
new file mode 100644
index 000000000..f2d2a165b
--- /dev/null
+++ b/control-ui/e2e/support/gfs-normal-workflow-constants.ts
@@ -0,0 +1,5 @@
+export const GFS_PLUGIN_NAMESPACE = 'sandbox-recipes'
+export const GFS_PLUGIN_RECIPE = 'gfs-grant-e2e-plugin'
+
+export const EXPECTED_HELD_STATE =
+ 'pending|approval-held-gfs-read|Running|true|true|true|true|true|0'
diff --git a/control-ui/e2e/support/gfs-normal-workflow-run.test.ts b/control-ui/e2e/support/gfs-normal-workflow-run.test.ts
new file mode 100644
index 000000000..acc0edacb
--- /dev/null
+++ b/control-ui/e2e/support/gfs-normal-workflow-run.test.ts
@@ -0,0 +1,355 @@
+import { type Page, expect } from '@playwright/test'
+import { UUID_RE, kubectlOut } from '../../../tests/e2e/gfsUiFixtures'
+import { loginControlUi } from './gfs-control-ui-session'
+import {
+ EXPECTED_HELD_STATE,
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+} from './gfs-normal-workflow-constants'
+import {
+ normalGfsPluginRunDiagnostic,
+ normalGfsPluginRunState,
+} from './gfs-normal-workflow-state.test'
+
+export { GFS_PLUGIN_NAMESPACE, GFS_PLUGIN_RECIPE }
+const CONTROL_API_DIAGNOSTIC_URL =
+ process.env.CONTROL_API_BASE_URL ||
+ process.env.E2E_CONTROL_API_URL ||
+ process.env.CONTROL_API_URL ||
+ 'http://localhost:8090'
+const CHILD_TIMEOUT_MS = 45_000
+const MCP_HOST_TIMEOUT_MS = 60_000
+const COORDINATOR_TIMEOUT_MS = 90_000
+const APPROVAL_TIMEOUT_MS = 30_000
+const BROWSER_REQUEST_TIMEOUT_MS = 10_000
+type WorkflowRun = {
+ id?: string
+ phase?: string
+ executionRef?: { namespace?: string; name?: string } | null
+}
+
+export type NormalGfsPluginRunProgress = {
+ runId: string
+ childName?: string
+}
+
+export type WorkflowRecipeResource = {
+ metadata?: {
+ name?: string
+ namespace?: string
+ uid?: string
+ deletionTimestamp?: string
+ labels?: Record<string, string>
+ ownerReferences?: Array<{
+ apiVersion?: string
+ blockOwnerDeletion?: boolean
+ controller?: boolean
+ kind?: string
+ name?: string
+ uid?: string
+ }>
+ }
+ spec?: {
+ agent?: unknown
+ gfs?: { mounts?: Array<{ drive?: string; scopes?: string[]; target?: string }> }
+ pluginWorkloadSdk?: unknown
+ steps?: Array<{ id?: string; requiresApproval?: unknown }>
+ }
+}
+
+type PodList = {
+ items?: Array<{
+ metadata?: { name?: string; deletionTimestamp?: string }
+ status?: { conditions?: Array<{ type?: string; status?: string }> }
+ }>
+}
+
+function kubectlJson<T>(args: string[], timeout = 20_000): T {
+ return JSON.parse(kubectlOut([...args, '-o', 'json'], timeout)) as T
+}
+
+function workflowPodState(
+ recipeName: string,
+ component: 'workflow-coordinator' | 'workflow-mcp-host'
+): { names: string[]; ready: boolean } {
+ const pods = kubectlJson<PodList>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'pod',
+ '-l',
+ `clerum.io/recipe=${recipeName},clerum.io/component=${component}`,
+ ])
+ const items = pods.items ?? []
+ return {
+ names: items.map(item => item.metadata?.name ?? '').filter(Boolean),
+ ready:
+ items.length === 1 &&
+ !items[0]?.metadata?.deletionTimestamp &&
+ items[0]?.status?.conditions?.some(
+ condition => condition.type === 'Ready' && condition.status === 'True'
+ ) === true,
+ }
+}
+
+function mcpHostPodState(recipeName: string): { names: string[]; ready: boolean } {
+ return workflowPodState(recipeName, 'workflow-mcp-host')
+}
+
+function expectNormalParent(recipeName: string): void {
+ const parent = kubectlJson<WorkflowRecipeResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ recipeName,
+ ])
+ expect(parent.metadata?.namespace).toBe(GFS_PLUGIN_NAMESPACE)
+ expect(parent.metadata?.name).toBe(recipeName)
+ expect(parent.metadata?.uid).toBeTruthy()
+ expect(parent.spec?.pluginWorkloadSdk).toBeUndefined()
+ expect(parent.spec?.agent).toBeTruthy()
+ expect(parent.spec?.steps).toHaveLength(4)
+ expect(parent.spec?.steps?.[0]?.id).toBe('approval-held-gfs-read')
+ expect(parent.spec?.steps?.[0]?.requiresApproval).toBeTruthy()
+ expect(parent.spec?.gfs?.mounts).toEqual([
+ {
+ drive: 'main',
+ target: 'e2e/gfs-grant-e2e-plugin',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ])
+ expect(mcpHostPodState(recipeName).names).toEqual([])
+}
+async function adminRequest<T>(page: Page, path: string): Promise<{ body: T; status: number }> {
+ const result = await page.evaluate(
+ async request => {
+ const controller = new AbortController()
+ const timer = window.setTimeout(() => controller.abort(), request.timeoutMs)
+ try {
+ const response = await fetch(request.path, {
+ method: 'GET',
+ credentials: 'same-origin',
+ signal: controller.signal,
+ })
+ const text = await response.text()
+ let responseBody: unknown
+ try {
+ responseBody = JSON.parse(text)
+ } catch {
+ responseBody = { raw: text }
+ }
+ return {
+ body: responseBody,
+ requestOrigin: window.location.origin,
+ responseOrigin: new URL(response.url).origin,
+ status: response.status,
+ text,
+ }
+ } finally {
+ window.clearTimeout(timer)
+ }
+ },
+ { path, timeoutMs: BROWSER_REQUEST_TIMEOUT_MS }
+ )
+ expect(result.responseOrigin).toBe(result.requestOrigin)
+ if (result.status < 200 || result.status >= 300) {
+ throw new Error(
+ `GET ${path} returned ${result.status}: ${result.text} ` +
+ `(configured control API: ${CONTROL_API_DIAGNOSTIC_URL})`
+ )
+ }
+ return { body: result.body as T, status: result.status }
+}
+async function triggerRun(page: Page, recipeName: string): Promise<string> {
+ await loginControlUi(page)
+ const pluginsNavigation = page.getByRole('link', { name: 'Plugins', exact: true })
+ await expect(pluginsNavigation).toBeVisible({ timeout: 20_000 })
+ await pluginsNavigation.click()
+ await expect(page).toHaveURL(/\/plugins(?:$|\?)/, { timeout: 20_000 })
+
+ const search = page.getByRole('searchbox', { name: 'Search plugins', exact: true })
+ await expect(search).toBeVisible({ timeout: 20_000 })
+ await search.fill(recipeName)
+ const recipeLink = page.getByRole('link', { name: `Open ${recipeName}` })
+ await expect(recipeLink).toBeVisible({ timeout: 20_000 })
+ await recipeLink.click()
+ await expect(page).toHaveURL(
+ new RegExp(`/plugins/${GFS_PLUGIN_NAMESPACE}/${recipeName}/workloads(?:\\?|$)`),
+ { timeout: 20_000 }
+ )
+ await expect(page.getByRole('heading', { name: recipeName })).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(page.getByText(/Loading recipe/)).toBeHidden({ timeout: 120_000 })
+
+ const runsTab = page.getByRole('tab', { name: /Runs/ })
+ await expect(runsTab).toBeVisible({ timeout: 20_000 })
+ const runButton = page.getByRole('button', { name: 'Run…', exact: true })
+ await expect(runButton).toBeVisible({ timeout: 20_000 })
+ await expect(runButton).toBeEnabled({ timeout: 120_000 })
+ await runButton.click()
+
+ const dialog = page.getByRole('dialog', {
+ name: new RegExp(`Run\\s+${recipeName}\\s+as operator`),
+ })
+ await expect(dialog).toBeVisible({ timeout: 20_000 })
+ const triggerResponse = page.waitForResponse(
+ response =>
+ response.request().method() === 'POST' &&
+ response
+ .url()
+ .includes(
+ `/control-api/api/v1/admin/workflows/${GFS_PLUGIN_NAMESPACE}/${recipeName}/trigger`
+ )
+ )
+ const submitRun = dialog.getByRole('button', { name: 'Run as operator' })
+ await expect(submitRun).toBeEnabled({ timeout: 20_000 })
+ await submitRun.click()
+ const response = await triggerResponse
+ expect(response.status()).toBe(201)
+ const body = (await response.json()) as WorkflowRun
+ expect(body.id).toMatch(UUID_RE)
+ await expect(dialog).toBeHidden({ timeout: 30_000 })
+ await runsTab.click()
+ await expect(page).toHaveURL(
+ new RegExp(`/plugins/${GFS_PLUGIN_NAMESPACE}/${recipeName}/runs(?:\\?|$)`),
+ { timeout: 20_000 }
+ )
+ await expect(page.getByRole('link', { name: `Open run ${body.id!.slice(0, 8)}` })).toBeVisible({
+ timeout: 60_000,
+ })
+ return body.id!
+}
+
+async function waitForChild(page: Page, runId: string, recipeName: string): Promise<string> {
+ let childName = ''
+ await expect
+ .poll(
+ async () => {
+ const response = await adminRequest<WorkflowRun>(
+ page,
+ `/control-api/api/v1/admin/workflows/${GFS_PLUGIN_NAMESPACE}/${recipeName}/runs/${runId}`
+ )
+ expect(['Pending', 'Running']).toContain(response.body.phase)
+ expect(response.body.executionRef?.namespace ?? GFS_PLUGIN_NAMESPACE).toBe(
+ GFS_PLUGIN_NAMESPACE
+ )
+ childName = response.body.executionRef?.name ?? ''
+ return childName || null
+ },
+ {
+ timeout: CHILD_TIMEOUT_MS,
+ intervals: [500, 1_000, 2_000],
+ message: `workflow run ${runId} should receive its child executionRef`,
+ }
+ )
+ .not.toBeNull()
+ return childName
+}
+
+function expectChildContract(childName: string, runId: string, recipeName: string): void {
+ const parent = kubectlJson<WorkflowRecipeResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ recipeName,
+ ])
+ const child = kubectlJson<WorkflowRecipeResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ childName,
+ ])
+ expect(parent.metadata?.uid).toBeTruthy()
+ expect(child.metadata?.name).toBe(childName)
+ expect(child.metadata?.namespace).toBe(GFS_PLUGIN_NAMESPACE)
+ expect(child.metadata?.labels?.['clerum.io/parent-recipe']).toBe(recipeName)
+ expect(child.metadata?.labels?.['clerum.io/workflow-run-id']).toBe(runId)
+ expect(child.metadata?.ownerReferences).toHaveLength(1)
+ expect(child.metadata?.ownerReferences).toEqual([
+ expect.objectContaining({
+ apiVersion: 'clerum.io/v1alpha1',
+ blockOwnerDeletion: true,
+ controller: true,
+ kind: 'WorkflowRecipe',
+ name: recipeName,
+ uid: parent.metadata!.uid,
+ }),
+ ])
+ expect(child.spec?.gfs?.mounts).toEqual([
+ {
+ drive: 'main',
+ target: 'e2e/gfs-grant-e2e-plugin',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ])
+}
+
+async function waitForMcpHostAndApproval(
+ childName: string,
+ runId: string,
+ recipeName: string
+): Promise<string> {
+ const expectedPod = `${childName}-mcp-host`
+ await expect
+ .poll(() => mcpHostPodState(childName), {
+ timeout: MCP_HOST_TIMEOUT_MS,
+ intervals: [1_000, 2_000, 5_000],
+ message: `workflow run ${runId} should create one Ready child-labeled mcp-host`,
+ })
+ .toEqual({ names: [expectedPod], ready: true })
+ expect(mcpHostPodState(recipeName).names).toEqual([])
+
+ await expect
+ .poll(() => workflowPodState(childName, 'workflow-coordinator'), {
+ timeout: COORDINATOR_TIMEOUT_MS,
+ intervals: [1_000, 2_000, 5_000],
+ message: `workflow run ${runId} should create one Ready child-labeled coordinator`,
+ })
+ .toEqual({ names: [`${childName}-coordinator`], ready: true })
+
+ try {
+ await expect
+ .poll(() => normalGfsPluginRunState(runId, childName, recipeName), {
+ timeout: APPROVAL_TIMEOUT_MS,
+ intervals: [500, 1_000, 2_000],
+ message: `workflow run ${runId} should stop before LLM or tool execution`,
+ })
+ .toBe(EXPECTED_HELD_STATE)
+ } catch (error) {
+ let coordinatorLogs = '<coordinator pod already unavailable>'
+ try {
+ coordinatorLogs = kubectlOut(
+ ['-n', GFS_PLUGIN_NAMESPACE, 'logs', `${childName}-coordinator`, '--tail=200'],
+ 20_000
+ )
+ } catch {
+ // The reconciler removes a terminal coordinator quickly; the durable DB
+ // diagnostic below remains authoritative when pod logs are already gone.
+ }
+ throw new Error(
+ `${error instanceof Error ? error.message : String(error)}\n` +
+ `Persisted run diagnostic:\n${normalGfsPluginRunDiagnostic(runId, childName, recipeName)}\n` +
+ `Coordinator logs for ${childName}:\n${coordinatorLogs}`
+ )
+ }
+ return expectedPod
+}
+
+export async function startNormalGfsPluginRun(
+ page: Page,
+ onProgress?: (progress: NormalGfsPluginRunProgress) => void,
+ recipeName = GFS_PLUGIN_RECIPE
+): Promise<{ childName: string; pod: string; runId: string }> {
+ expectNormalParent(recipeName)
+ const runId = await triggerRun(page, recipeName)
+ onProgress?.({ runId })
+ const childName = await waitForChild(page, runId, recipeName)
+ onProgress?.({ runId, childName })
+ expectChildContract(childName, runId, recipeName)
+ const pod = await waitForMcpHostAndApproval(childName, runId, recipeName)
+ return { childName, pod, runId }
+}
diff --git a/control-ui/e2e/support/gfs-normal-workflow-state.test.ts b/control-ui/e2e/support/gfs-normal-workflow-state.test.ts
new file mode 100644
index 000000000..0aae335c4
--- /dev/null
+++ b/control-ui/e2e/support/gfs-normal-workflow-state.test.ts
@@ -0,0 +1,87 @@
+import { expect } from '@playwright/test'
+import { firstDataLine, runControlPostgresSql, sqlLiteral } from '../../../tests/e2e/gfsUiFixtures'
+import {
+ EXPECTED_HELD_STATE,
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+} from './gfs-normal-workflow-constants'
+
+export function normalGfsPluginRunState(
+ runId: string,
+ childName: string,
+ recipeName = GFS_PLUGIN_RECIPE
+): string {
+ return firstDataLine(
+ runControlPostgresSql(`
+ SELECT approval.status || '|' || step.step_id || '|' || step.phase || '|' ||
+ (step.started_at IS NOT NULL)::text || '|' ||
+ (step.completed_at IS NULL)::text || '|' ||
+ (step.output IS NULL)::text || '|' ||
+ (step.tools_called IS NULL)::text || '|' ||
+ (step.error IS NULL)::text || '|' ||
+ (SELECT COUNT(*)::text FROM agent_run_events event
+ WHERE event.run_id = step.run_id
+ AND event.event_type IN ('llm_call', 'tool_call'))
+ FROM workflow_approval_requests approval
+ JOIN workflow_run_steps step
+ ON step.run_id = approval.bound_workflow_run_id
+ AND step.step_id = approval.bound_workflow_step_id
+ JOIN workflow_runs run
+ ON run.run_id = step.run_id
+ AND run.recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND run.recipe_name = ${sqlLiteral(recipeName)}
+ AND run.child_recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND run.child_recipe_name = ${sqlLiteral(childName)}
+ WHERE approval.bound_workflow_run_id = ${sqlLiteral(runId)}::uuid
+ AND approval.recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND approval.recipe_name = ${sqlLiteral(recipeName)}
+ ORDER BY approval.requested_at DESC LIMIT 1;
+ `)
+ )
+}
+
+export function normalGfsPluginRunDiagnostic(
+ runId: string,
+ childName: string,
+ recipeName = GFS_PLUGIN_RECIPE
+): string {
+ return runControlPostgresSql(`
+ SELECT json_build_object(
+ 'runPhase', run.phase,
+ 'childRecipeName', run.child_recipe_name,
+ 'stepId', step.step_id,
+ 'stepPhase', step.phase,
+ 'stepError', step.error,
+ 'approvalStatus', approval.status,
+ 'approvalRecipeName', approval.recipe_name,
+ 'llmOrToolEvents', (
+ SELECT COUNT(*)
+ FROM agent_run_events event
+ WHERE event.run_id = run.run_id
+ AND event.event_type IN ('llm_call', 'tool_call')
+ )
+ )::text
+ FROM workflow_runs run
+ LEFT JOIN workflow_run_steps step
+ ON step.run_id = run.run_id
+ AND step.step_id = 'approval-held-gfs-read'
+ LEFT JOIN workflow_approval_requests approval
+ ON approval.bound_workflow_run_id = run.run_id
+ AND approval.bound_workflow_step_id = step.step_id
+ AND approval.recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND approval.recipe_name = ${sqlLiteral(recipeName)}
+ WHERE run.run_id = ${sqlLiteral(runId)}::uuid
+ AND run.recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND run.recipe_name = ${sqlLiteral(recipeName)}
+ AND run.child_recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND run.child_recipe_name = ${sqlLiteral(childName)};
+ `).trim()
+}
+
+export function expectNormalGfsPluginRunHeld(
+ runId: string,
+ childName: string,
+ recipeName = GFS_PLUGIN_RECIPE
+): void {
+ expect(normalGfsPluginRunState(runId, childName, recipeName)).toBe(EXPECTED_HELD_STATE)
+}
diff --git a/control-ui/e2e/support/gfs-per-host-isolation-journey.test.ts b/control-ui/e2e/support/gfs-per-host-isolation-journey.test.ts
new file mode 100644
index 000000000..324d711f4
--- /dev/null
+++ b/control-ui/e2e/support/gfs-per-host-isolation-journey.test.ts
@@ -0,0 +1,95 @@
+import { type Page, expect, test } from '@playwright/test'
+import { getGfsGrantSummary } from '../../../tests/e2e/gfsUiFixtures'
+
+type PerHostIsolationJourneyInput = {
+ fixture: { name: string; resourceId: string }
+ page: Page
+ unchangedHostSubjectIds: string[]
+}
+
+const SUBJECT_PICKER_LABEL = 'Add people, teams, agents, or workflows'
+const TARGET_HOST_SEARCH = 'chatllm'
+const TARGET_HOST_LABEL = 'chatllm (Stateful)'
+const TARGET_HOST_SUBJECT_ID = '1st:mcp-host/chatllm'
+
+export async function exerciseGfsPerHostIsolationJourney({
+ fixture,
+ page,
+ unchangedHostSubjectIds,
+}: PerHostIsolationJourneyInput): Promise<void> {
+ await test.step('operator updates one first-party host without changing the other host grants', async () => {
+ const panel = page.getByRole('dialog', {
+ name: `Manage folder ${fixture.name}`,
+ exact: true,
+ })
+ const subjectSearch = panel.getByRole('combobox', {
+ name: SUBJECT_PICKER_LABEL,
+ })
+ await expect(subjectSearch).toBeVisible()
+ await subjectSearch.fill(TARGET_HOST_SEARCH)
+ const targetHost = panel.getByRole('option', { name: TARGET_HOST_LABEL, exact: true })
+ await expect(targetHost).toBeVisible({ timeout: 20_000 })
+ await targetHost.click()
+
+ await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
+ await panel.getByRole('menuitemcheckbox', { name: 'Read', exact: true }).click()
+
+ const grantResponsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'PUT' &&
+ response.url().includes('/control-api/api/v1/gfs/grants')
+ )
+ await panel.getByRole('button', { name: 'Grant access', exact: true }).click()
+ const confirmation = page.getByRole('alertdialog')
+ await expect(confirmation).toContainText('Grant access?')
+ await expect(confirmation).toContainText(/1 subject/i)
+ await expect(confirmation).toContainText(/read/)
+ await confirmation.getByRole('button', { name: 'Grant' }).click()
+
+ const grantResponse = await grantResponsePromise
+ expect(grantResponse.status(), `${grantResponse.url()} ${await grantResponse.text()}`).toBe(200)
+ const submittedBody = grantResponse.request().postDataJSON() as {
+ subject?: unknown
+ subjects?: Array<{ type: string; id?: string }>
+ permissions?: string[]
+ }
+ expect(submittedBody.subject).toBeUndefined()
+ expect(submittedBody.subjects).toEqual([{ type: 'host', id: TARGET_HOST_SUBJECT_ID }])
+ expect(submittedBody.permissions).toEqual(['read'])
+ await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
+
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId: TARGET_HOST_SUBJECT_ID,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({
+ permissions: ['read'],
+ inherit: true,
+ grantedBy: 'operator:',
+ })
+
+ for (const subjectId of unchangedHostSubjectIds) {
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({
+ permissions: ['read', 'write'],
+ inherit: true,
+ grantedBy: 'operator:',
+ })
+ }
+ })
+}
diff --git a/control-ui/e2e/support/gfs-plugin-effective-grants.test.ts b/control-ui/e2e/support/gfs-plugin-effective-grants.test.ts
new file mode 100644
index 000000000..735225320
--- /dev/null
+++ b/control-ui/e2e/support/gfs-plugin-effective-grants.test.ts
@@ -0,0 +1,265 @@
+import { type Locator, type Page, expect, test } from '@playwright/test'
+import { getGfsGrantSummary, kubectlOut } from '../../../tests/e2e/gfsUiFixtures'
+
+const RECIPE_NAMESPACE = 'sandbox-recipes'
+const RECIPE_NAME = 'gfs-grant-e2e-plugin'
+const RECIPE_SUBJECT_ID = `3rd:${RECIPE_NAMESPACE}/${RECIPE_NAME}`
+const SUBJECT_PICKER_LABEL = 'Add people, teams, agents, or workflows'
+
+type GfsToolName = 'clerum__gfs_read' | 'clerum__gfs_stat' | 'clerum__gfs_write'
+type GfsToolOutput = { content: string; is_error: boolean }
+type GfsResourceEnvelope = { ok: boolean; data: { gfsUri: string; version: number } }
+type PluginGrantJourneyInput = {
+ fileResourceId: string
+ fileUri: string
+ initialContent: string
+ page: Page
+ panel: Locator
+ pod: string
+ unrelatedPod: string
+ updatedContent: string
+}
+
+function runGfsTool(
+ pod: string,
+ toolName: GfsToolName,
+ args: Record<string, unknown>
+): GfsToolOutput {
+ const script = `
+const { config } = require('./dist/config.js');
+const { NativeToolRegistry } = require('./dist/core/tools/nativeToolRegistry.js');
+const registry = new NativeToolRegistry(config.nativeTool, 'gfs-grant-e2e');
+const registeredNames = registry.listDefinitions().map(definition => definition.name);
+if (!registeredNames.includes('clerum__gfs_read') || !registeredNames.includes('clerum__gfs_write')) {
+ throw new Error('NativeToolRegistry did not register the GFS tools');
+}
+const tool = registry.get(process.argv[1]);
+if (!tool) throw new Error('requested GFS tool is unavailable');
+tool.execute(JSON.parse(process.argv[2])).then(result => {
+ process.stdout.write(JSON.stringify(result));
+}).catch(error => {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+});
+`
+ const output = kubectlOut(
+ [
+ '-n',
+ RECIPE_NAMESPACE,
+ 'exec',
+ pod,
+ '-c',
+ 'mcp-host',
+ '--',
+ 'node',
+ '-e',
+ script,
+ toolName,
+ JSON.stringify(args),
+ ],
+ 30_000
+ ).trim()
+ const result = JSON.parse(output.split('\n').filter(Boolean).at(-1) ?? '') as GfsToolOutput
+ if (typeof result.is_error !== 'boolean' || typeof result.content !== 'string') {
+ throw new Error(`run-scoped recipe GFS tool returned an invalid result for ${toolName}`)
+ }
+ return result
+}
+
+function parseResourceEnvelope(result: GfsToolOutput): GfsResourceEnvelope {
+ expect(result.is_error, result.content).toBe(false)
+ const envelope = JSON.parse(result.content) as GfsResourceEnvelope
+ expect(envelope.ok).toBe(true)
+ expect(envelope.data.version).toEqual(expect.any(Number))
+ return envelope
+}
+
+function expectReadWriteDenied(
+ pod: string,
+ resourceId: string,
+ content: string,
+ ifMatch: number
+): void {
+ for (const result of [
+ runGfsTool(pod, 'clerum__gfs_read', { drive: 'main', resourceId }),
+ runGfsTool(pod, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId,
+ content,
+ ifMatch,
+ }),
+ ]) {
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(/gfsc 403/i)
+ }
+}
+
+async function chooseRecipeSubject(panel: Locator): Promise<void> {
+ const input = panel.getByRole('combobox', { name: SUBJECT_PICKER_LABEL })
+ await expect(input).toBeVisible()
+ await input.fill(RECIPE_NAME)
+ const option = panel.getByRole('option', { name: RECIPE_NAME, exact: true })
+ await expect(option).toBeVisible({ timeout: 20_000 })
+ await option.click()
+ await expect(panel.getByRole('button', { name: `Remove ${RECIPE_NAME}` })).toBeVisible()
+}
+
+async function choosePermission(panel: Locator, permissionName: 'Read' | 'Write'): Promise<void> {
+ const menu = panel.getByRole('menu', { name: 'Permissions' })
+ if (!(await menu.isVisible().catch(() => false))) {
+ await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
+ }
+ await menu.getByRole('menuitemcheckbox', { name: permissionName, exact: true }).click()
+}
+
+async function submitGrant(
+ page: Page,
+ panel: Locator,
+ permissions: Array<'read' | 'write'>,
+ resourceId: string
+): Promise<void> {
+ const responsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'PUT' &&
+ response.url().includes('/control-api/api/v1/gfs/grants')
+ )
+ await panel.getByRole('button', { name: 'Grant access', exact: true }).click()
+ const confirmation = page.getByRole('alertdialog')
+ await expect(confirmation).toContainText('Grant access?')
+ await expect(confirmation).toContainText('Grant 1 subjects (1 host)')
+ await expect(confirmation).toContainText(`[${permissions.join(', ')}]`)
+ await expect(confirmation).toContainText('Scope: resource only')
+ await confirmation.getByRole('button', { name: 'Grant', exact: true }).click()
+ const response = await responsePromise
+ expect(response.status(), `${response.url()} ${await response.text()}`).toBe(200)
+ const body = response.request().postDataJSON() as {
+ resourceId?: string
+ subject?: unknown
+ subjects?: Array<{ type: string; id: string }>
+ permissions?: string[]
+ }
+ expect(body.resourceId).toBe(resourceId)
+ expect(body.subject).toBeUndefined()
+ expect(body.subjects).toEqual([{ type: 'host', id: RECIPE_SUBJECT_ID }])
+ expect(body.permissions).toEqual(permissions)
+ await expect(page.getByText('Grant saved.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsGrantSummary({
+ resourceId,
+ subjectType: 'host',
+ subjectId: RECIPE_SUBJECT_ID,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ permissions, grantedBy: 'operator:' })
+}
+
+export async function exerciseGfsPluginEffectiveGrantJourney({
+ fileResourceId,
+ fileUri,
+ initialContent,
+ page,
+ panel,
+ pod,
+ unrelatedPod,
+ updatedContent,
+}: PluginGrantJourneyInput): Promise<void> {
+ await test.step('run-scoped tools are denied before any resource grant exists', async () => {
+ expectReadWriteDenied(pod, fileResourceId, updatedContent, 1)
+ expectReadWriteDenied(unrelatedPod, fileResourceId, updatedContent, 1)
+ })
+
+ await test.step('operator grants read only to the exact parent recipe through the UI', async () => {
+ await chooseRecipeSubject(panel)
+ await choosePermission(panel, 'Read')
+ await submitGrant(page, panel, ['read'], fileResourceId)
+ })
+
+ let currentVersion = 0
+ await test.step('read grant survives into the child runtime while write remains denied', async () => {
+ const read = runGfsTool(pod, 'clerum__gfs_read', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ })
+ expect(read).toMatchObject({ is_error: false, content: initialContent })
+ const stat = parseResourceEnvelope(
+ runGfsTool(pod, 'clerum__gfs_stat', { drive: 'main', resourceId: fileResourceId })
+ )
+ expect(stat.data.gfsUri).toBe(fileUri)
+ currentVersion = stat.data.version
+ const write = runGfsTool(pod, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ content: updatedContent,
+ ifMatch: currentVersion,
+ })
+ expect(write.is_error).toBe(true)
+ expect(write.content).toMatch(/gfsc 403/i)
+ expectReadWriteDenied(unrelatedPod, fileResourceId, updatedContent, currentVersion)
+ })
+
+ await test.step('operator replaces the grant with write only through the UI', async () => {
+ await chooseRecipeSubject(panel)
+ await choosePermission(panel, 'Write')
+ await submitGrant(page, panel, ['write'], fileResourceId)
+ })
+
+ const writeOnlyContent = `${updatedContent} (write-only)`
+ await test.step('write grant survives into the child runtime while read remains denied', async () => {
+ const read = runGfsTool(pod, 'clerum__gfs_read', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ })
+ expect(read.is_error).toBe(true)
+ expect(read.content).toMatch(/gfsc 403/i)
+ const write = parseResourceEnvelope(
+ runGfsTool(pod, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ content: writeOnlyContent,
+ ifMatch: currentVersion,
+ })
+ )
+ expect(write.data.gfsUri).toBe(fileUri)
+ expect(write.data.version).toBe(currentVersion + 1)
+ currentVersion = write.data.version
+ expectReadWriteDenied(unrelatedPod, fileResourceId, writeOnlyContent, currentVersion)
+ })
+
+ await test.step('operator upgrades the same parent recipe to read and write through the UI', async () => {
+ await chooseRecipeSubject(panel)
+ await choosePermission(panel, 'Read')
+ await choosePermission(panel, 'Write')
+ await submitGrant(page, panel, ['read', 'write'], fileResourceId)
+ })
+
+ await test.step('combined grant preserves both operations and the version contract', async () => {
+ const beforeWrite = runGfsTool(pod, 'clerum__gfs_read', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ })
+ expect(beforeWrite).toMatchObject({ is_error: false, content: writeOnlyContent })
+ const write = parseResourceEnvelope(
+ runGfsTool(pod, 'clerum__gfs_write', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ content: updatedContent,
+ ifMatch: currentVersion,
+ })
+ )
+ expect(write.data.gfsUri).toBe(fileUri)
+ expect(write.data.version).toBe(currentVersion + 1)
+ const readBack = runGfsTool(pod, 'clerum__gfs_read', {
+ drive: 'main',
+ resourceId: fileResourceId,
+ })
+ expect(readBack).toMatchObject({ is_error: false, content: updatedContent })
+ const stat = parseResourceEnvelope(
+ runGfsTool(pod, 'clerum__gfs_stat', { drive: 'main', resourceId: fileResourceId })
+ )
+ expect(stat.data.version).toBe(currentVersion + 1)
+ expectReadWriteDenied(unrelatedPod, fileResourceId, updatedContent, currentVersion + 1)
+ })
+}
diff --git a/control-ui/e2e/support/gfs-resource-crud-journey.test.ts b/control-ui/e2e/support/gfs-resource-crud-journey.test.ts
new file mode 100644
index 000000000..0e9c5a262
--- /dev/null
+++ b/control-ui/e2e/support/gfs-resource-crud-journey.test.ts
@@ -0,0 +1,190 @@
+import { type Locator, type Page, expect, test } from '@playwright/test'
+import { getGfsChildResourceSummary, uniqueGfsFixtureName } from '../../../tests/e2e/gfsUiFixtures'
+import { GFS_RESOURCE_NAME_MAX_LENGTH, normalizeGfsResourceName } from '../../lib/gfsResourceName'
+
+type GfsCrudFixture = {
+ childName: string
+ name: string
+ resourceId: string
+ uri: string
+}
+
+type GfsResourceCrudJourneyInput = {
+ baseUi: string
+ fixture: GfsCrudFixture
+ folderRow: (name: string) => Locator
+ page: Page
+}
+
+export async function exerciseGfsResourceCrudJourney({
+ baseUi,
+ fixture,
+ folderRow,
+ page,
+}: GfsResourceCrudJourneyInput): Promise<void> {
+ await test.step('operator opens the grant panel for the seeded folder', async () => {
+ const row = folderRow(fixture.name)
+ await expect(row).toBeVisible({ timeout: 20_000 })
+ const actionsButton = row.getByRole('button', { name: `Actions for ${fixture.name}` })
+ await actionsButton.click()
+ const copyButton = page.getByRole('menuitem', { name: 'Copy GFS link' })
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], {
+ origin: new URL(baseUi).origin,
+ })
+ await expect(copyButton).toHaveAttribute('title', fixture.uri)
+ await copyButton.click()
+ await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(fixture.uri)
+ await actionsButton.click()
+ await page.getByRole('menuitem', { name: 'Manage access' }).click()
+ await expect(
+ page.getByRole('dialog', { name: `Manage folder ${fixture.name}`, exact: true })
+ ).toBeVisible()
+ })
+
+ await test.step('operator creates, uploads, renames, replaces, and deletes resources from the folder UI', async () => {
+ await page.getByRole('button', { name: 'Close manage dialog' }).click()
+ await folderRow(fixture.name).getByRole('button', { name: fixture.name, exact: true }).click()
+ const currentResources = page.getByRole('list', { name: 'Current folder resources' })
+ await expect(
+ currentResources.getByRole('button', { name: fixture.childName, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+
+ const createdFolderRaw =
+ `${uniqueGfsFixtureName('e2e-gfs-operator-created')}-` + `${'very-long-'.repeat(24)}child`
+ const createdFolder = await normalizeGfsResourceName(createdFolderRaw)
+ expect(createdFolderRaw.length).toBeGreaterThan(GFS_RESOURCE_NAME_MAX_LENGTH)
+ expect(createdFolder).toHaveLength(GFS_RESOURCE_NAME_MAX_LENGTH)
+ const createResponsePromise = page.waitForResponse(
+ response =>
+ response.request().method() === 'POST' &&
+ response.url().includes('/gfs/proxy/v1/resources/') &&
+ response.url().includes('/children')
+ )
+ await page.getByRole('button', { name: 'New folder' }).click()
+ const newFolderDialog = page.getByRole('dialog', { name: 'New folder' })
+ await newFolderDialog.getByLabel('Folder name').fill(createdFolderRaw)
+ await newFolderDialog.getByRole('button', { name: 'Create folder' }).click()
+ const createResponse = await createResponsePromise
+ expect(createResponse.status(), `${createResponse.url()} ${await createResponse.text()}`).toBe(
+ 201
+ )
+ await expect(page.getByText('Folder created.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: createdFolder,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ name: createdFolder, kind: 'directory', deleted: false })
+ await expect(
+ currentResources.getByRole('button', { name: createdFolder, exact: true })
+ ).toBeVisible({ timeout: 15_000 })
+
+ const uploadName = `${uniqueGfsFixtureName('e2e-gfs-operator-upload')}-report.txt`
+ await page.getByRole('button', { name: 'Upload file' }).click()
+ const uploadDialog = page.getByRole('dialog', { name: 'Upload file' })
+ await uploadDialog.getByLabel('Choose file to upload').setInputFiles({
+ name: uploadName,
+ mimeType: 'text/plain',
+ buffer: Buffer.from('operator upload v1', 'utf8'),
+ })
+ await uploadDialog.getByRole('button', { name: 'Upload', exact: true }).click()
+ await expect(page.getByText('File uploaded.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: uploadName,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ name: uploadName, kind: 'file', bytes: 18, deleted: false })
+
+ const renamedName = uploadName.replace('.txt', '-renamed.txt')
+ const uploadRow = currentResources.getByRole('listitem').filter({ hasText: uploadName }).first()
+ await expect(uploadRow).toBeVisible({ timeout: 15_000 })
+ await uploadRow.getByRole('button', { name: `Actions for ${uploadName}` }).click()
+ await page.getByRole('menuitem', { name: 'Rename' }).click()
+ const renameForm = page.getByRole('form', { name: 'Rename resource' })
+ await renameForm.getByLabel('New name').fill(renamedName)
+ await renameForm.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(page.getByText('Resource renamed.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: renamedName,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ name: renamedName, kind: 'file', deleted: false })
+
+ const renamedRow = currentResources
+ .getByRole('listitem')
+ .filter({ hasText: renamedName })
+ .first()
+ await renamedRow.getByRole('button', { name: `Actions for ${renamedName}` }).click()
+ await page.getByLabel(`Replace ${renamedName}`).setInputFiles({
+ name: renamedName,
+ mimeType: 'text/plain',
+ buffer: Buffer.from('operator upload v2 extended', 'utf8'),
+ })
+ await expect(page.getByText('File replaced.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: renamedName,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ bytes: 27, deleted: false })
+
+ const deleteRow = currentResources
+ .getByRole('listitem')
+ .filter({ hasText: renamedName })
+ .first()
+ await deleteRow.getByRole('button', { name: `Actions for ${renamedName}` }).click()
+ await page.getByRole('menuitem', { name: 'Delete' }).click()
+ await page
+ .getByRole('alertdialog', { name: 'Delete resource' })
+ .getByRole('button', {
+ name: 'Delete',
+ exact: true,
+ })
+ .click()
+ await expect(page.getByText('Resource deleted.').last()).toBeVisible({ timeout: 15_000 })
+ await expect
+ .poll(
+ () =>
+ getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: renamedName,
+ }),
+ { timeout: 15_000, intervals: [250, 500, 1_000] }
+ )
+ .toMatchObject({ deleted: true })
+ await expect(
+ currentResources.getByRole('listitem').filter({ hasText: renamedName })
+ ).toHaveCount(0)
+
+ await page
+ .getByRole('navigation', { name: 'Breadcrumb' })
+ .getByRole('button', { name: 'main', exact: true })
+ .click()
+ await expect(folderRow(fixture.name)).toBeVisible({ timeout: 20_000 })
+ await folderRow(fixture.name)
+ .getByRole('button', { name: `Actions for ${fixture.name}` })
+ .click()
+ await page.getByRole('menuitem', { name: 'Manage access' }).click()
+ await expect(
+ page.getByRole('dialog', { name: `Manage folder ${fixture.name}`, exact: true })
+ ).toBeVisible()
+ })
+}
diff --git a/control-ui/lib/__tests__/gfsApi.test.ts b/control-ui/lib/__tests__/gfsApi.test.ts
new file mode 100644
index 000000000..e692f418e
--- /dev/null
+++ b/control-ui/lib/__tests__/gfsApi.test.ts
@@ -0,0 +1,131 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ type GfsGrantError,
+ type GfsGrantRequestBody,
+ type GfsMutationResponse,
+ deleteGfsGrant,
+ deleteGfsShare,
+ getGfsGrants,
+ getGfsShares,
+ postGfsShare,
+ putGfsGrant,
+} from '../api'
+
+const resourceId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
+
+const bulkGrantWithHost = {
+ resourceId,
+ permissions: ['read'],
+ subjects: [{ type: 'host', id: '1st:mcp-host/standalone' }],
+} satisfies GfsGrantRequestBody
+
+const singularContextResponse = {
+ ok: true,
+ resourceId,
+ updated: [{ type: 'context', id: 'run-context' }],
+ count: 1,
+} satisfies GfsMutationResponse
+
+function makeResponse(status: number, body: unknown): Response {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: 'Bad Request',
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+}
+
+let fetchMock: ReturnType<typeof vi.fn>
+
+beforeEach(() => {
+ fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+})
+
+afterEach(() => vi.unstubAllGlobals())
+
+describe('GFS mutation API contract', () => {
+ it('lists and revokes persisted access through resource-scoped endpoints', async () => {
+ fetchMock
+ .mockResolvedValueOnce(makeResponse(200, { items: [] }))
+ .mockResolvedValueOnce(makeResponse(200, { items: [] }))
+ .mockResolvedValueOnce(makeResponse(200, { ok: true }))
+ .mockResolvedValueOnce(makeResponse(200, { ok: true }))
+
+ await expect(getGfsGrants(resourceId)).resolves.toEqual({ items: [] })
+ await expect(getGfsShares(resourceId)).resolves.toEqual({ items: [] })
+ await expect(deleteGfsGrant('grant/id')).resolves.toBeUndefined()
+ await expect(deleteGfsShare('share/id')).resolves.toBeUndefined()
+
+ expect(String(fetchMock.mock.calls[0][0])).toContain(
+ `/api/v1/gfs/grants?drive=main&resourceId=${resourceId}`
+ )
+ expect(String(fetchMock.mock.calls[1][0])).toContain(
+ `/api/v1/gfs/shares?drive=main&resourceId=${resourceId}`
+ )
+ expect(String(fetchMock.mock.calls[2][0])).toContain('/api/v1/gfs/grants/grant%2Fid')
+ expect(fetchMock.mock.calls[2][1]).toMatchObject({ method: 'DELETE' })
+ expect(String(fetchMock.mock.calls[3][0])).toContain('/api/v1/gfs/shares/share%2Fid')
+ expect(fetchMock.mock.calls[3][1]).toMatchObject({ method: 'DELETE' })
+ })
+
+ it('keeps host grants and singular context responses in the client contract', () => {
+ expect(bulkGrantWithHost.subjects[0]).toEqual({
+ type: 'host',
+ id: '1st:mcp-host/standalone',
+ })
+ expect(singularContextResponse.updated[0]).toEqual({
+ type: 'context',
+ id: 'run-context',
+ })
+ })
+
+ it('preserves the stable error envelope for grants', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(400, {
+ error: 'subjects_invalid',
+ message: 'The subjects request is invalid.',
+ invalidIndexes: [1, -1, 2.5, '3'],
+ })
+ )
+
+ const error = (await putGfsGrant({
+ resourceId,
+ permissions: ['read'],
+ subjects: [{ type: 'user', id: '11111111-1111-1111-1111-111111111111' }],
+ }).catch(caught => caught)) as GfsGrantError
+
+ expect(error).toMatchObject({
+ status: 400,
+ code: 'subjects_invalid',
+ serverMessage: 'The subjects request is invalid.',
+ invalidIndexes: [1],
+ })
+ expect(error.message).toBe('400 subjects_invalid: The subjects request is invalid.')
+ })
+
+ it('does not duplicate a share error when message equals its machine code', async () => {
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(400, {
+ error: 'subjects_invalid',
+ message: 'subjects_invalid',
+ invalidIndexes: [0],
+ })
+ )
+
+ const error = (await postGfsShare({
+ resourceId,
+ permissions: ['read'],
+ subjects: [{ type: 'team', id: '22222222-2222-2222-2222-222222222222' }],
+ }).catch(caught => caught)) as GfsGrantError
+
+ expect(error).toMatchObject({
+ status: 400,
+ code: 'subjects_invalid',
+ serverMessage: 'subjects_invalid',
+ invalidIndexes: [0],
+ })
+ expect(error.message).toBe('400 subjects_invalid')
+ })
+})
diff --git a/control-ui/lib/__tests__/routeResolution.test.ts b/control-ui/lib/__tests__/routeResolution.test.ts
index d21b17f4a..d78eda995 100644
--- a/control-ui/lib/__tests__/routeResolution.test.ts
+++ b/control-ui/lib/__tests__/routeResolution.test.ts
@@ -96,4 +96,28 @@ describe('CONTROL_ROUTES App Router resolution', () => {
expect(unresolved).toEqual([])
})
+
+ it('redirects the previous directory section URLs to their canonical names', async () => {
+ const redirects = ((await nextConfig.redirects?.()) ?? []) as RouteRule[]
+
+ expect(redirects).toEqual(
+ expect.arrayContaining([
+ {
+ source: '/global-files',
+ destination: CONTROL_ROUTES.globalFileSystem,
+ permanent: true,
+ },
+ {
+ source: '/outputs',
+ destination: CONTROL_ROUTES.agentOutputs.root,
+ permanent: true,
+ },
+ {
+ source: '/shared-files',
+ destination: CONTROL_ROUTES.agentFiles.root,
+ permanent: true,
+ },
+ ])
+ )
+ })
})
diff --git a/control-ui/lib/__tests__/routes.test.ts b/control-ui/lib/__tests__/routes.test.ts
index b497d254f..de98de1d7 100644
--- a/control-ui/lib/__tests__/routes.test.ts
+++ b/control-ui/lib/__tests__/routes.test.ts
@@ -21,4 +21,10 @@ describe('CONTROL_ROUTES', () => {
expect(isControlRouteSection('/agents/example/overview', CONTROL_ROUTES.agents.root)).toBe(true)
expect(isControlRouteSection('/agents-old', CONTROL_ROUTES.agents.root)).toBe(false)
})
+
+ it('uses the canonical directory section names in public paths', () => {
+ expect(CONTROL_ROUTES.agentFiles.root).toBe('/agent-files')
+ expect(CONTROL_ROUTES.agentOutputs.root).toBe('/agent-outputs/recipe-artifacts')
+ expect(CONTROL_ROUTES.globalFileSystem).toBe('/global-file-system')
+ })
})
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 53cf6a997..b8df1b3c6 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -268,26 +268,75 @@ export async function apiSend(
// Like registryKeysRequest: unlike apiSend (friendly-remaps the message), these
// routes need the machine-readable error CODE (e.g. escalation_rejected,
// resource_invalid) so the operator panel can surface the precise verdict.
+export type GfsUserSubjectInput = { type: 'user'; id: string }
+export type GfsTeamSubjectInput = { type: 'team'; id: string }
+export type GfsHostSubjectInput = { type: 'host'; id: string }
+export type GfsOperatorSubjectInput = { type: 'operator' }
+export type GfsContextSubjectInput = { type: 'context'; id: string }
+
+export type GfsBulkGrantSubjectInput =
+ | GfsUserSubjectInput
+ | GfsTeamSubjectInput
+ | GfsHostSubjectInput
+export type GfsBulkShareSubjectInput = GfsUserSubjectInput | GfsTeamSubjectInput
export type GfsSubjectInput =
- | { type: 'user'; id: string }
- | { type: 'team'; id: string }
- | { type: 'host'; id: string }
- | { type: 'operator' }
+ | GfsBulkGrantSubjectInput
+ | GfsOperatorSubjectInput
+ | GfsContextSubjectInput
-export type GfsGrantRequestBody = {
+type GfsSubjectMutationInput<TBulkSubject extends GfsSubjectInput> =
+ | { subject: GfsSubjectInput; subjects?: never }
+ | { subject?: never; subjects: TBulkSubject[] }
+
+type GfsMutationRequestBody = {
drive?: string
resourceId: string
+ permissions: string[]
+}
+
+export type GfsGrantRequestBody = GfsMutationRequestBody &
+ GfsSubjectMutationInput<GfsBulkGrantSubjectInput> & {
+ inherit?: boolean
+ }
+
+export type GfsShareRequestBody = GfsMutationRequestBody &
+ GfsSubjectMutationInput<GfsBulkShareSubjectInput> & {
+ includeDescendants?: boolean
+ }
+
+export type GfsMutationResponse = {
+ ok: true
+ resourceId: string
+ updated: GfsSubjectInput[]
+ count: number
+}
+
+export type GfsGrantListItem = {
+ id: string
+ drive: string
+ resourceId: string
subject: GfsSubjectInput
permissions: string[]
- inherit?: boolean
+ inherit: boolean
}
-export type GfsShareRequestBody = {
- drive?: string
+export type GfsShareListItem = {
+ id: string
+ drive: string
resourceId: string
subject: GfsSubjectInput
permissions: string[]
- includeDescendants?: boolean
+ includeDescendants: boolean
+}
+
+export type GfsGrantListResponse = { items: GfsGrantListItem[] }
+export type GfsShareListResponse = { items: GfsShareListItem[] }
+
+export type GfsGrantError = Error & {
+ status?: number
+ code?: string
+ serverMessage?: string
+ invalidIndexes?: number[]
}
async function gfsMutate(
@@ -307,18 +356,34 @@ async function gfsMutate(
if (!res.ok) {
if (res.status === 401) handleUnauthorized()
let code = ''
+ let serverMessage = ''
+ let invalidIndexes: number[] | undefined
try {
- const parsed = (await res.json()) as { error?: string }
+ const parsed = (await res.json()) as {
+ error?: string
+ message?: unknown
+ invalidIndexes?: unknown
+ }
code = parsed?.error ?? ''
+ if (typeof parsed?.message === 'string') serverMessage = parsed.message
+ if (Array.isArray(parsed?.invalidIndexes)) {
+ invalidIndexes = parsed.invalidIndexes.filter(
+ (index): index is number =>
+ typeof index === 'number' && Number.isInteger(index) && index >= 0
+ )
+ }
} catch {
/* no body */
}
- const error = new Error(`${res.status} ${code || res.statusText}`) as Error & {
- status?: number
- code?: string
- }
+ const detail =
+ code && serverMessage && serverMessage !== code
+ ? `${code}: ${serverMessage}`
+ : serverMessage || code || res.statusText
+ const error = new Error(`${res.status} ${detail}`) as GfsGrantError
error.status = res.status
error.code = code
+ error.serverMessage = serverMessage
+ error.invalidIndexes = invalidIndexes
throw error
}
if (res.status === 204) return undefined
@@ -326,13 +391,47 @@ async function gfsMutate(
}
/** Operator grants a Layer-1/2 folder grant (PUT /api/v1/gfs/grants). */
-export async function putGfsGrant(body: GfsGrantRequestBody): Promise<void> {
- await gfsMutate('PUT', '/api/v1/gfs/grants', body)
+export async function putGfsGrant(body: GfsGrantRequestBody): Promise<GfsMutationResponse> {
+ return (await gfsMutate('PUT', '/api/v1/gfs/grants', body)) as GfsMutationResponse
+}
+
+/** Lists direct grants configured on one resource. Inherited effective access is not expanded. */
+export async function getGfsGrants(
+ resourceId: string,
+ drive = 'main',
+ signal?: AbortSignal
+): Promise<GfsGrantListResponse> {
+ return (await apiGet(
+ '/api/v1/gfs/grants',
+ { drive, resourceId },
+ { signal }
+ )) as GfsGrantListResponse
+}
+
+export async function deleteGfsGrant(id: string): Promise<void> {
+ await gfsMutate('DELETE', `/api/v1/gfs/grants/${encodeURIComponent(id)}`)
}
/** Operator creates a URI share (POST /api/v1/gfs/shares). */
-export async function postGfsShare(body: GfsShareRequestBody): Promise<void> {
- await gfsMutate('POST', '/api/v1/gfs/shares', body)
+export async function postGfsShare(body: GfsShareRequestBody): Promise<GfsMutationResponse> {
+ return (await gfsMutate('POST', '/api/v1/gfs/shares', body)) as GfsMutationResponse
+}
+
+/** Lists direct URI shares configured on one resource. */
+export async function getGfsShares(
+ resourceId: string,
+ drive = 'main',
+ signal?: AbortSignal
+): Promise<GfsShareListResponse> {
+ return (await apiGet(
+ '/api/v1/gfs/shares',
+ { drive, resourceId },
+ { signal }
+ )) as GfsShareListResponse
+}
+
+export async function deleteGfsShare(id: string): Promise<void> {
+ await gfsMutate('DELETE', `/api/v1/gfs/shares/${encodeURIComponent(id)}`)
}
export type AdminLoginResponse = {
@@ -1209,7 +1308,9 @@ export async function deleteMcpSecret(name: string) {
}
export type RecipeSecretOwnership =
- { kind: 'shared' } | { kind: 'owner-recipe'; recipeName: string } | { kind: 'unlabeled' }
+ | { kind: 'shared' }
+ | { kind: 'owner-recipe'; recipeName: string }
+ | { kind: 'unlabeled' }
export type RecipeSecretItem = {
name: string
@@ -1928,7 +2029,13 @@ export type WorkflowRecipePhase =
| 'rollback-failed'
export type WorkflowExecutionPhase =
- 'pending' | 'initializing' | 'running' | 'completed' | 'failed' | 'cancelled' | 'recovering'
+ | 'pending'
+ | 'initializing'
+ | 'running'
+ | 'completed'
+ | 'failed'
+ | 'cancelled'
+ | 'recovering'
export type WorkflowRecipeStatus = {
phase?: WorkflowRecipePhase
@@ -2811,7 +2918,8 @@ export async function listOrgGrants(pluginName?: string): Promise<{ grants: OrgG
export async function createOrgGrant(input: CreateOrgGrantInput): Promise<OrgGrant> {
const raw = (await registryCodedRequest('POST', '/api/v1/admin/registry/grants', input)) as
- RawOrgGrant | undefined
+ | RawOrgGrant
+ | undefined
return normalizeOrgGrant(raw ?? {})
}
@@ -3071,7 +3179,12 @@ export type PluginWorkloadSdkQuotaCounter = {
}
export type PluginWorkloadSdkInvocationStatus =
- 'in_progress' | 'complete' | 'failed' | 'provider_unavailable' | 'accepted' | 'delivered'
+ | 'in_progress'
+ | 'complete'
+ | 'failed'
+ | 'provider_unavailable'
+ | 'accepted'
+ | 'delivered'
export type PluginWorkloadSdkInvocation = {
id: string
@@ -3254,7 +3367,11 @@ export async function revokeRegistryApiKey(id: string): Promise<void> {
// There is NO rejection_reason in the contract.
export type RegistryConnectionState =
- 'disconnected' | 'pending' | 'approved' | 'rejected' | 'connected'
+ | 'disconnected'
+ | 'pending'
+ | 'approved'
+ | 'rejected'
+ | 'connected'
export type RegistryConnectionStatus = {
state: RegistryConnectionState
deploymentId?: string
diff --git a/control-ui/next.config.js b/control-ui/next.config.js
index 3b97b9c4e..9288b148f 100644
--- a/control-ui/next.config.js
+++ b/control-ui/next.config.js
@@ -11,10 +11,11 @@ const nextConfig = {
{ source: '/plugins/sdk', destination: '/plugin-workload-sdk' },
{ source: '/plugins', destination: '/workflow-recipes' },
{ source: '/plugins/:path*', destination: '/workflow-recipes/:path*' },
- { source: '/shared-files', destination: '/shared-filesystems' },
- { source: '/shared-files/:path*', destination: '/shared-filesystems/:path*' },
- { source: '/global-files', destination: '/gfs' },
- { source: '/global-files/:path*', destination: '/gfs/:path*' },
+ { source: '/agent-files', destination: '/shared-filesystems' },
+ { source: '/agent-files/:path*', destination: '/shared-filesystems/:path*' },
+ { source: '/agent-outputs/:path*', destination: '/outputs/:path*' },
+ { source: '/global-file-system', destination: '/gfs' },
+ { source: '/global-file-system/:path*', destination: '/gfs/:path*' },
{ source: '/external-channels', destination: '/communication-channels' },
{
source: '/external-channels/:path*',
@@ -45,14 +46,26 @@ const nextConfig = {
{ source: '/workflow-recipes', destination: '/plugins', permanent: true },
{ source: '/workflow-recipes/:path*', destination: '/plugins/:path*', permanent: true },
{ source: '/plugin-workload-sdk', destination: '/plugins/sdk', permanent: true },
- { source: '/shared-filesystems', destination: '/shared-files', permanent: true },
+ { source: '/shared-filesystems', destination: '/agent-files', permanent: true },
{
source: '/shared-filesystems/:path*',
- destination: '/shared-files/:path*',
+ destination: '/agent-files/:path*',
+ permanent: true,
+ },
+ { source: '/shared-files', destination: '/agent-files', permanent: true },
+ { source: '/shared-files/:path*', destination: '/agent-files/:path*', permanent: true },
+ { source: '/gfs', destination: '/global-file-system', permanent: true },
+ {
+ source: '/gfs/:path*',
+ destination: '/global-file-system/:path*',
+ permanent: true,
+ },
+ { source: '/global-files', destination: '/global-file-system', permanent: true },
+ {
+ source: '/global-files/:path*',
+ destination: '/global-file-system/:path*',
permanent: true,
},
- { source: '/gfs', destination: '/global-files', permanent: true },
- { source: '/gfs/:path*', destination: '/global-files/:path*', permanent: true },
{ source: '/communication-channels', destination: '/external-channels', permanent: true },
{
source: '/communication-channels/:path*',
@@ -72,7 +85,18 @@ const nextConfig = {
{ source: '/cost/:path*', destination: '/cost-and-usage/:path*', permanent: true },
{ source: '/marketplace', destination: '/marketplace/connectors', permanent: true },
{ source: '/cost-and-usage', destination: '/cost-and-usage/usage', permanent: true },
- { source: '/outputs', destination: '/outputs/recipe-artifacts', permanent: true },
+ {
+ source: '/agent-outputs',
+ destination: '/agent-outputs/recipe-artifacts',
+ permanent: true,
+ },
+ { source: '/outputs', destination: '/agent-outputs/recipe-artifacts', permanent: true },
+ { source: '/outputs/:path*', destination: '/agent-outputs/:path*', permanent: true },
+ {
+ source: '/contexts/:name/shared-files',
+ destination: '/contexts/:name/agent-files',
+ permanent: true,
+ },
{ source: '/secrets', destination: '/secrets/llm', permanent: true },
{ source: '/settings', destination: '/settings/ui', permanent: true },
{ source: '/traces/hosts', destination: '/traces', permanent: true },
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 5f6c0740b..9c97858f2 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.335",
+ "version": "0.1.344",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.335",
+ "version": "0.1.344",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-ui/package.json b/control-ui/package.json
index 67f29bb8b..925194420 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,11 +1,26 @@
{
"name": "clerum-control-ui",
- "version": "0.1.335",
+ "version": "0.1.344",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
"build": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next build",
"start": "next start -p 3000",
+ "qa:recorder:install": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright install chromium",
+ "qa:recorder:agent-create": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-agent-create.spec.ts",
+ "qa:recorder:login": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-login.spec.ts",
+ "qa:recorder:navigation": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-navigation.spec.ts",
+ "qa:recorder:agents": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-agents.spec.ts",
+ "qa:recorder:contexts": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-contexts.spec.ts",
+ "qa:recorder:connectors": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-connectors.spec.ts",
+ "qa:recorder:external-channels": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-external-channels.spec.ts",
+ "qa:recorder:llm-models": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-llm-models.spec.ts",
+ "qa:recorder:users-teams": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-users-teams.spec.ts",
+ "qa:recorder:cost-usage": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-cost-usage.spec.ts",
+ "qa:recorder:traces": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-traces.spec.ts",
+ "qa:recorder:settings": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-settings.spec.ts",
+ "qa:recorder:marketplace": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-marketplace.spec.ts",
+ "qa:recorder:all": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts",
"test": "vitest run",
"test:watch": "vitest"
},
diff --git a/control-ui/playwright.config.ts b/control-ui/playwright.config.ts
index 1e4c55c6f..d4b363dab 100644
--- a/control-ui/playwright.config.ts
+++ b/control-ui/playwright.config.ts
@@ -49,13 +49,13 @@ const gfsAuthCrossBrowserProjects: NonNullable<PlaywrightTestConfig['projects']>
{
name: 'chrome-gfs-auth',
testMatch: /gfs-operator-journey\.spec\.ts/,
- grep: /authenticated operator reaches Global Files/,
+ grep: /authenticated operator reaches Global File System/,
use: { channel: 'chrome' },
},
{
name: 'firefox-gfs-auth',
testMatch: /gfs-operator-journey\.spec\.ts/,
- grep: /authenticated operator reaches Global Files/,
+ grep: /authenticated operator reaches Global File System/,
use: { browserName: 'firefox' },
},
]
@@ -71,11 +71,13 @@ const gfsAuthCrossBrowserProjects: NonNullable<PlaywrightTestConfig['projects']>
// when you need html/json for CI artifacts.
export default defineConfig({
testDir: './e2e',
+ testIgnore: '**/support/**',
timeout: 300_000, // 5 min default — long-running workflow specs override via test.setTimeout()
expect: { timeout: 120_000 },
reporter: [['list']],
use: {
- baseURL: process.env.CONTROL_UI_URL || 'http://localhost:3000',
+ baseURL:
+ process.env.CONTROL_UI_BASE_URL || process.env.CONTROL_UI_URL || 'http://localhost:3000',
headless: true,
screenshot: 'only-on-failure',
trace: 'on-first-retry',
diff --git a/control-ui/playwright.qa-recorder.config.ts b/control-ui/playwright.qa-recorder.config.ts
new file mode 100644
index 000000000..d214312c5
--- /dev/null
+++ b/control-ui/playwright.qa-recorder.config.ts
@@ -0,0 +1,56 @@
+import { defineConfig } from '@playwright/test'
+import path from 'node:path'
+import { loadQaRecorderEnv } from '../scripts/qa-recorder/loadEnv'
+
+const repoRoot = path.resolve(__dirname, '..')
+loadQaRecorderEnv(repoRoot)
+
+const recorderRoot = process.env.QA_RECORDER_ROOT
+ ? path.resolve(process.env.QA_RECORDER_ROOT)
+ : path.join(repoRoot, '.local-notes', 'qa-recorder')
+const browserChannel = process.env.QA_RECORDER_BROWSER_CHANNEL?.trim()
+const slowMo = Number(process.env.QA_RECORDER_SLOW_MO_MS || 75)
+
+if (!Number.isFinite(slowMo) || slowMo < 0) {
+ throw new Error('QA_RECORDER_SLOW_MO_MS must be a non-negative number.')
+}
+
+export default defineConfig({
+ testDir: './e2e',
+ // All Control UI recorder journeys share this config. Each journey lives in
+ // its own qa-recorder-<journey>.spec.ts and is run via a namespaced
+ // qa:recorder:<journey> command (see package.json). Stays isolated from the
+ // normal Playwright/CI suite — only recorder specs match.
+ testMatch: /qa-recorder-.*\.spec\.ts/,
+ timeout: 300_000,
+ expect: { timeout: 30_000 },
+ reporter: [['list']],
+ outputDir: path.join(recorderRoot, 'runs', 'control-ui'),
+ preserveOutput: 'always',
+ retries: 0,
+ workers: 1,
+ use: {
+ baseURL: process.env.CONTROL_UI_URL || 'http://127.0.0.1:3000',
+ headless: process.env.QA_RECORDER_HEADLESS === '1',
+ screenshot: 'on',
+ trace: 'retain-on-failure',
+ video:
+ process.env.QA_RECORDER_VIDEO === '0'
+ ? 'off'
+ : {
+ mode: 'on',
+ size: { width: 1280, height: 720 },
+ },
+ viewport: { width: 1280, height: 720 },
+ },
+ projects: [
+ {
+ name: 'qa-recorder-chromium',
+ use: {
+ browserName: 'chromium',
+ ...(browserChannel ? { channel: browserChannel } : {}),
+ launchOptions: { slowMo },
+ },
+ },
+ ],
+})
diff --git a/control-ui/type-contracts/gfsApi.contract.ts b/control-ui/type-contracts/gfsApi.contract.ts
new file mode 100644
index 000000000..e426ac534
--- /dev/null
+++ b/control-ui/type-contracts/gfsApi.contract.ts
@@ -0,0 +1,12 @@
+import type { GfsBulkShareSubjectInput } from '../lib/api'
+
+type AssertNever<T extends never> = T
+
+/**
+ * Control UI bulk shares intentionally exclude host subjects. Keep this
+ * contract outside test-file paths so the production Next typecheck enforces
+ * it even though Next filters diagnostics from __tests__ and *.test.* files.
+ */
+export type GfsBulkShareMustExcludeHost = AssertNever<
+ Extract<GfsBulkShareSubjectInput, { type: 'host' }>
+>
diff --git a/deploy/base/cluster-wide/clusterrolebindings.yaml b/deploy/base/cluster-wide/clusterrolebindings.yaml
index eb98ddbe2..907c0f9ac 100644
--- a/deploy/base/cluster-wide/clusterrolebindings.yaml
+++ b/deploy/base/cluster-wide/clusterrolebindings.yaml
@@ -57,21 +57,6 @@ subjects:
namespace: control-plane
---
apiVersion: rbac.authorization.k8s.io/v1
-kind: ClusterRoleBinding
-metadata:
- name: wrc-trigger-binding
- labels:
- clerum.io/managed-by: clerum-wrc
-roleRef:
- apiGroup: rbac.authorization.k8s.io
- kind: ClusterRole
- name: wrc-trigger-role
-subjects:
-- kind: ServiceAccount
- name: wrc-trigger-sa
- namespace: control-plane
----
-apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: control-api-pod-reader
diff --git a/deploy/base/cluster-wide/clusterroles.yaml b/deploy/base/cluster-wide/clusterroles.yaml
index 15d8f43d5..bcb19f185 100644
--- a/deploy/base/cluster-wide/clusterroles.yaml
+++ b/deploy/base/cluster-wide/clusterroles.yaml
@@ -99,26 +99,6 @@ rules:
- patch
- delete
---
-apiVersion: rbac.authorization.k8s.io/v1
-kind: ClusterRole
-metadata:
- name: wrc-trigger-role
- labels:
- clerum.io/managed-by: clerum-wrc
-rules:
-- apiGroups:
- - ""
- resources:
- - services/proxy
- verbs:
- - create
-- apiGroups:
- - authentication.k8s.io
- resources:
- - tokenreviews
- verbs:
- - create
----
# control-api-pod-reader: allows control-api to exec into artifact pods
# through @kubernetes/client-node. The client opens pods/exec over WebSocket
# GET, while kubectl-compatible exec paths may use create; grant both verbs
diff --git a/deploy/base/control-plane/workflow-recipes.yaml b/deploy/base/control-plane/workflow-recipes.yaml
index 79c310538..ae854c46f 100644
--- a/deploy/base/control-plane/workflow-recipes.yaml
+++ b/deploy/base/control-plane/workflow-recipes.yaml
@@ -5,15 +5,6 @@ metadata:
name: workflow-recipes
namespace: control-plane
---
-apiVersion: v1
-kind: ServiceAccount
-metadata:
- name: wrc-trigger-sa
- namespace: control-plane
- labels:
- clerum.io/component: scheduling-trigger
- clerum.io/managed-by: clerum-wrc
----
apiVersion: apps/v1
kind: Deployment
metadata:
diff --git a/deploy/scripts/apply-inter-service-tokens.sh b/deploy/scripts/apply-inter-service-tokens.sh
index e6f1158ca..8f368cfe1 100755
--- a/deploy/scripts/apply-inter-service-tokens.sh
+++ b/deploy/scripts/apply-inter-service-tokens.sh
@@ -131,13 +131,13 @@ resolve_member_registration_hmac() {
if [ -n "$minikube_hmac" ]; then
printf '%s' "$minikube_hmac"; return
fi
- # The evenfire-member-registration sibling checkout is optional in the OSS
- # single-tenant tree (it lives in a separate repo). When it is absent,
- # generate a local dev HMAC so `make minikube-setup` continues instead of
- # aborting — member invitation / registration flows stay non-functional
- # until the sibling is deployed, per docs/deploy/minikube.md ("setup simply
- # prints a warning and continues"). The value is preserved across re-runs by
- # the existing-Secret read above.
+ # The evenfire-member-registration sibling is optional in the OSS single-tenant
+ # tree (it lives in a separate repo and is excluded from the public snapshot).
+ # When it is absent, generate a local dev HMAC so `make minikube-setup` continues
+ # instead of aborting — member invitation / registration flows stay non-functional
+ # until the sibling is deployed, per docs/deploy/minikube.md ("setup simply prints a
+ # warning and continues"). The value is preserved across re-runs by the existing-Secret
+ # read above. In the monorepo the sibling script is present, so this branch is inert.
printf '[inter-service-tokens] WARN: evenfire-member-registration sibling not found; generating a local dev member-registration HMAC (invitation/registration flows will fail until it is deployed)\n' >&2
openssl rand -hex 32; return
fi
diff --git a/deploy/scripts/validate-assembled-image-allowlist.sh b/deploy/scripts/validate-assembled-image-allowlist.sh
deleted file mode 100755
index 2ce64455d..000000000
--- a/deploy/scripts/validate-assembled-image-allowlist.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env bash
-# Renders the app-vs-config ASSEMBLED tree (public genericized base + private gcp overlay)
-# and asserts the image-allowlist envs contain the real AR/registry prefixes and NO
-# ${GCP_PROJECT}/example.com placeholders. This is the ONLY render check that catches the
-# base-genericization gap — the monorepo (non-genericized) base renders real values either way.
-set -euo pipefail
-ROOT="$(git rev-parse --show-toplevel)"
-TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
-echo "==> genericize base"
-( cd "$ROOT/scripts/oss/snapshot" && npx tsx run.ts "$TMP/dist-public" >/dev/null )
-fail=0
-for env in gcp-dev gcp-prod; do
- work="$TMP/assembled-$env/deploy"
- mkdir -p "$work/overlays"
- cp -R "$TMP/dist-public/deploy/base" "$work/base"
- cp -R "$ROOT/deploy/overlays/$env" "$work/overlays/$env"
- rendered="$(kubectl kustomize "$work/overlays/$env")"
- # -A1: control-api renders `KEY: value` (one line); the HCC env renders `- name: …` then
- # `value: …` on the NEXT line — capture both.
- prefixes="$(printf '%s\n' "$rendered" | grep -A1 -E 'ALLOWED_IMAGE_PREFIXES' || true)"
- echo "--- $env allowlist lines ---"; printf '%s\n' "$prefixes"
- if ! printf '%s\n' "$prefixes" | grep -q 'us-central1-docker.pkg.dev/your-gcp-project/clerum/'; then
- echo "::error::[$env] allowlist missing real AR prefix"; fail=1
- fi
- if printf '%s\n' "$prefixes" | grep -qE '\$\{GCP_PROJECT\}|example\.com/'; then
- echo "::error::[$env] allowlist contains a genericized placeholder"; fail=1
- fi
-done
-[ "$fail" -eq 0 ] && echo "OK: assembled allowlist render is real in gcp-dev + gcp-prod"
-exit "$fail"
diff --git a/desktop-app/assets/adaptive-icon.icon/Assets/icon.png b/desktop-app/assets/adaptive-icon.icon/Assets/icon.png
new file mode 100644
index 000000000..073ae0f6b
Binary files /dev/null and b/desktop-app/assets/adaptive-icon.icon/Assets/icon.png differ
diff --git a/desktop-app/assets/adaptive-icon.icon/icon.json b/desktop-app/assets/adaptive-icon.icon/icon.json
new file mode 100644
index 000000000..a67187cba
--- /dev/null
+++ b/desktop-app/assets/adaptive-icon.icon/icon.json
@@ -0,0 +1,44 @@
+{
+ "fill-specializations": [
+ {
+ "value": {
+ "solid": "extended-gray:1.00000,1.00000"
+ }
+ },
+ {
+ "appearance": "dark",
+ "value": {
+ "solid": "extended-gray:0.00000,1.00000"
+ }
+ }
+ ],
+ "groups": [
+ {
+ "layers": [
+ {
+ "blend-mode": "normal",
+ "fill": "automatic",
+ "glass": false,
+ "hidden": false,
+ "image-name": "icon.png",
+ "name": "Evenfire",
+ "position": {
+ "scale": 0.62,
+ "translation-in-points": [0, 0]
+ }
+ }
+ ],
+ "shadow": {
+ "kind": "neutral",
+ "opacity": 0.5
+ },
+ "translucency": {
+ "enabled": false,
+ "value": 0
+ }
+ }
+ ],
+ "supported-platforms": {
+ "squares": "shared"
+ }
+}
diff --git a/desktop-app/assets/icon-dark.png b/desktop-app/assets/icon-dark.png
new file mode 100644
index 000000000..a0aa367c0
Binary files /dev/null and b/desktop-app/assets/icon-dark.png differ
diff --git a/desktop-app/assets/icon-dark.svg b/desktop-app/assets/icon-dark.svg
new file mode 100644
index 000000000..219c407f4
--- /dev/null
+++ b/desktop-app/assets/icon-dark.svg
@@ -0,0 +1,14 @@
+<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect x="64" y="64" width="896" height="896" rx="200" fill="#000000" stroke="#262B35" stroke-width="12"/>
+ <g transform="translate(192 192) scale(3.2)">
+ <path d="M100.205 191.845L56.0735 145.864C43.7804 133.061 37.5208 116.687 37.2126 100.245C37.1784 98.4326 37.2126 96.5995 37.3291 94.7939C38.2331 79.9595 43.9996 65.3982 54.5668 53.6756C55.69 52.4173 56.8748 51.1997 58.1144 50.0098L70.209 38.4375L100.637 70.1449C108.985 78.8446 108.711 91.6958 100 100.033L71.9415 70.8014C55.6215 86.4227 55.0462 113.267 70.6952 129.565L100.863 160.999C109.211 169.699 108.924 183.515 100.205 191.859V191.845Z" fill="url(#dark-gradient)"/>
+ <path d="M99.7947 8.19922L143.92 54.1804C156.213 66.9906 162.479 83.3573 162.787 99.806C162.822 101.619 162.787 103.451 162.671 105.257C161.767 120.092 156.001 134.653 145.433 146.375C144.31 147.634 143.125 148.851 141.886 150.041L129.791 161.614L99.3631 129.906C91.0147 121.207 91.2888 108.355 100 100.018L128.059 129.25C144.379 113.628 144.954 86.7839 129.305 70.4855L99.1371 39.0517C90.7887 30.352 91.0832 16.5364 99.7947 8.19922Z" fill="url(#dark-gradient)"/>
+ </g>
+ <defs>
+ <linearGradient id="dark-gradient" x1="100" y1="-36.9" x2="100" y2="311.4" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#C3D4FD"/>
+ <stop offset="0.407055" stop-color="#4377FA"/>
+ <stop offset="1" stop-color="#163A96"/>
+ </linearGradient>
+ </defs>
+</svg>
diff --git a/desktop-app/assets/icon-light.png b/desktop-app/assets/icon-light.png
new file mode 100644
index 000000000..1ed74ec3f
Binary files /dev/null and b/desktop-app/assets/icon-light.png differ
diff --git a/desktop-app/assets/icon-light.svg b/desktop-app/assets/icon-light.svg
new file mode 100644
index 000000000..6caa40eba
--- /dev/null
+++ b/desktop-app/assets/icon-light.svg
@@ -0,0 +1,14 @@
+<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect x="64" y="64" width="896" height="896" rx="200" fill="#FFFFFF" stroke="#D9DEE8" stroke-width="12"/>
+ <g transform="translate(192 192) scale(3.2)">
+ <path d="M100.205 191.845L56.0735 145.864C43.7804 133.061 37.5208 116.687 37.2126 100.245C37.1784 98.4326 37.2126 96.5995 37.3291 94.7939C38.2331 79.9595 43.9996 65.3982 54.5668 53.6756C55.69 52.4173 56.8748 51.1997 58.1144 50.0098L70.209 38.4375L100.637 70.1449C108.985 78.8446 108.711 91.6958 100 100.033L71.9415 70.8014C55.6215 86.4227 55.0462 113.267 70.6952 129.565L100.863 160.999C109.211 169.699 108.924 183.515 100.205 191.859V191.845Z" fill="url(#light-gradient)"/>
+ <path d="M99.7947 8.19922L143.92 54.1804C156.213 66.9906 162.479 83.3573 162.787 99.806C162.822 101.619 162.787 103.451 162.671 105.257C161.767 120.092 156.001 134.653 145.433 146.375C144.31 147.634 143.125 148.851 141.886 150.041L129.791 161.614L99.3631 129.906C91.0147 121.207 91.2888 108.355 100 100.018L128.059 129.25C144.379 113.628 144.954 86.7839 129.305 70.4855L99.1371 39.0517C90.7887 30.352 91.0832 16.5364 99.7947 8.19922Z" fill="url(#light-gradient)"/>
+ </g>
+ <defs>
+ <linearGradient id="light-gradient" x1="100" y1="-36.9" x2="100" y2="311.4" gradientUnits="userSpaceOnUse">
+ <stop stop-color="#C3D4FD"/>
+ <stop offset="0.407055" stop-color="#4377FA"/>
+ <stop offset="1" stop-color="#02123C"/>
+ </linearGradient>
+ </defs>
+</svg>
diff --git a/desktop-app/assets/icon.ico b/desktop-app/assets/icon.ico
index 43481d37d..4816cb0cd 100644
Binary files a/desktop-app/assets/icon.ico and b/desktop-app/assets/icon.ico differ
diff --git a/desktop-app/forge.config.js b/desktop-app/forge.config.js
index 9e3625d23..f2b0950a9 100644
--- a/desktop-app/forge.config.js
+++ b/desktop-app/forge.config.js
@@ -1,9 +1,86 @@
-const { execSync } = require('node:child_process')
+const { execFileSync, execSync } = require('node:child_process')
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
const { FusesPlugin } = require('@electron-forge/plugin-fuses')
const { FuseV1Options, FuseVersion } = require('@electron/fuses')
const desktopLicense = require('./package.json').license
const defaultAppleBundleId = 'ai.evenfire.desktop'
+const assetsDirectory = path.resolve(__dirname, 'assets')
+const adaptiveIconDocument = path.join(assetsDirectory, 'adaptive-icon.icon')
+
+function compileMacAdaptiveIcon(buildPath, _electronVersion, platform, _arch, callback) {
+ if (platform !== 'darwin') {
+ callback()
+ return
+ }
+
+ const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'evenfire-app-icon-'))
+ const compileDirectory = path.join(temporaryDirectory, 'compiled')
+ const compileInput = path.join(temporaryDirectory, 'Icon.icon')
+ const partialInfoPath = path.join(temporaryDirectory, 'partial-info.plist')
+ const appDirectory = path.join(buildPath, 'Evenfire.app')
+ const resourcesDirectory = path.join(appDirectory, 'Contents', 'Resources')
+ const infoPlistPath = path.join(appDirectory, 'Contents', 'Info.plist')
+
+ let hookError
+ try {
+ fs.mkdirSync(compileDirectory, { recursive: true })
+ fs.cpSync(adaptiveIconDocument, compileInput, { recursive: true })
+ execFileSync(
+ 'xcrun',
+ [
+ 'actool',
+ compileInput,
+ '--compile',
+ compileDirectory,
+ '--output-format',
+ 'human-readable-text',
+ '--notices',
+ '--warnings',
+ '--platform',
+ 'macosx',
+ '--minimum-deployment-target',
+ '26.0',
+ '--app-icon',
+ 'Icon',
+ '--include-all-app-icons',
+ '--output-partial-info-plist',
+ partialInfoPath,
+ '--enable-on-demand-resources',
+ 'NO',
+ '--target-device',
+ 'mac',
+ ],
+ { stdio: 'inherit' }
+ )
+ fs.copyFileSync(
+ path.join(compileDirectory, 'Assets.car'),
+ path.join(resourcesDirectory, 'Assets.car')
+ )
+ fs.copyFileSync(
+ path.join(compileDirectory, 'Icon.icns'),
+ path.join(resourcesDirectory, 'Icon.icns')
+ )
+ execFileSync(
+ '/usr/bin/plutil',
+ ['-replace', 'CFBundleIconName', '-string', 'Icon', infoPlistPath],
+ { stdio: 'inherit' }
+ )
+ } catch (error) {
+ if (process.env.EVENFIRE_REQUIRE_ADAPTIVE_ICONS === '1') {
+ hookError = error
+ } else {
+ console.warn(
+ 'Skipping the macOS adaptive icon catalog; the compatible static icon remains available.'
+ )
+ }
+ } finally {
+ fs.rmSync(temporaryDirectory, { recursive: true, force: true })
+ }
+ callback(hookError)
+}
function resolveOsxSignConfig() {
if (process.platform !== 'darwin' || process.env.ENABLE_APPLE_CODESIGN !== '1') {
@@ -62,6 +139,9 @@ module.exports = {
executableName: 'Evenfire',
name: 'Evenfire',
icon: './assets/icon',
+ darwinDarkModeSupport: true,
+ extraResource: ['./assets/icon-light.png', './assets/icon-dark.png'],
+ afterCopyExtraResources: [compileMacAdaptiveIcon],
appBundleId: process.env.APPLE_BUNDLE_ID || defaultAppleBundleId,
appCategoryType: 'public.app-category.productivity',
...(osxSign ? { osxSign } : {}),
@@ -85,7 +165,9 @@ module.exports = {
{
name: '@electron-forge/maker-dmg',
platforms: ['darwin'],
- config: {},
+ config: {
+ icon: path.join(assetsDirectory, 'icon.icns'),
+ },
},
{
name: '@electron-forge/maker-squirrel',
@@ -95,6 +177,7 @@ module.exports = {
name: 'Evenfire',
title: 'Evenfire',
setupExe: 'EvenfireSetup.exe',
+ setupIcon: path.join(assetsDirectory, 'icon.ico'),
},
},
{
@@ -107,6 +190,7 @@ module.exports = {
genericName: 'Evenfire',
bin: 'Evenfire',
categories: ['Utility'],
+ icon: path.join(assetsDirectory, 'icon.png'),
},
},
},
@@ -121,6 +205,7 @@ module.exports = {
bin: 'Evenfire',
license: desktopLicense,
categories: ['Utility'],
+ icon: path.join(assetsDirectory, 'icon.png'),
},
},
},
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index a466ea8ed..98d7b3b4d 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.299",
+ "version": "0.1.311",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.299",
+ "version": "0.1.311",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 322c81de9..dc249bfac 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.299",
+ "version": "0.1.311",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
@@ -10,9 +10,24 @@
"build": "npm run build:main && npm run build:renderer",
"build:main": "tsc -p tsconfig.json",
"build:renderer": "vite build --config ui/vite.config.ts",
+ "icons:generate": "node ./scripts/generate-adaptive-icons.mjs",
"test": "vitest run",
"test:e2e": "vitest run --config test/e2e/vitest.config.ts",
"test:e2e:playwright": "npm run build && playwright test --config test/e2e-playwright/playwright.config.ts",
+ "qa:recorder:auth": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-auth.spec.ts",
+ "qa:recorder:navigation": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-navigation.spec.ts",
+ "qa:recorder:agents": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-agents.spec.ts",
+ "qa:recorder:connectors": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-connectors.spec.ts",
+ "qa:recorder:contexts": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-contexts.spec.ts",
+ "qa:recorder:shared-files": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-shared-files.spec.ts",
+ "qa:recorder:teams": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-teams.spec.ts",
+ "qa:recorder:plugins": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-plugins.spec.ts",
+ "qa:recorder:apps": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-apps.spec.ts",
+ "qa:recorder:settings": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-settings.spec.ts",
+ "qa:recorder:inbox-search": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-inbox-search.spec.ts",
+ "qa:recorder:chat": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-chat.spec.ts",
+ "qa:recorder:settings-chat": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts qa-recorder-settings-chat.spec.ts",
+ "qa:recorder:all": "npm run build && playwright test --config test/e2e-playwright/playwright.qa-recorder.config.ts",
"test:e2e:all": "npm run test:e2e && npm run test:e2e:playwright",
"dev": "concurrently -k \"npm:dev:renderer\" \"npm:dev:main\" \"npm:dev:app\"",
"dev:renderer": "vite --config ui/vite.config.ts",
diff --git a/desktop-app/scripts/generate-adaptive-icons.mjs b/desktop-app/scripts/generate-adaptive-icons.mjs
new file mode 100644
index 000000000..0fdb53ab2
--- /dev/null
+++ b/desktop-app/scripts/generate-adaptive-icons.mjs
@@ -0,0 +1,121 @@
+import electron from 'electron'
+import { spawnSync } from 'node:child_process'
+import fs from 'node:fs/promises'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const scriptPath = fileURLToPath(import.meta.url)
+if (typeof electron === 'string') {
+ const childEnvironment = { ...process.env }
+ delete childEnvironment.ELECTRON_RUN_AS_NODE
+ const result = spawnSync(electron, [scriptPath], {
+ env: childEnvironment,
+ stdio: 'inherit',
+ })
+ process.exit(result.status ?? 1)
+}
+
+const scriptDirectory = path.dirname(scriptPath)
+const projectDirectory = path.resolve(scriptDirectory, '..')
+const assetsDirectory = path.join(projectDirectory, 'assets')
+const iconComposerDirectory = path.join(assetsDirectory, 'adaptive-icon.icon')
+const iconComposerAssetsDirectory = path.join(iconComposerDirectory, 'Assets')
+const iconSize = 1024
+const { app, BrowserWindow, nativeImage } = electron
+
+app.disableHardwareAcceleration()
+app.on('window-all-closed', () => {})
+
+async function renderSvg(svgPath) {
+ const svg = await fs.readFile(svgPath, 'utf8')
+ const window = new BrowserWindow({
+ width: iconSize,
+ height: iconSize,
+ show: false,
+ frame: false,
+ transparent: true,
+ backgroundColor: '#00000000',
+ webPreferences: {
+ backgroundThrottling: false,
+ offscreen: true,
+ },
+ })
+
+ try {
+ await window.loadURL(`data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`)
+ const capture = await window.webContents.capturePage({
+ x: 0,
+ y: 0,
+ width: iconSize,
+ height: iconSize,
+ })
+ return capture.resize({ width: iconSize, height: iconSize, quality: 'best' })
+ } finally {
+ window.destroy()
+ }
+}
+
+function buildIco(images) {
+ const headerSize = 6
+ const entrySize = 16
+ const entriesSize = images.length * entrySize
+ const header = Buffer.alloc(headerSize + entriesSize)
+ header.writeUInt16LE(0, 0)
+ header.writeUInt16LE(1, 2)
+ header.writeUInt16LE(images.length, 4)
+
+ let imageOffset = header.length
+ for (const [index, image] of images.entries()) {
+ const entryOffset = headerSize + index * entrySize
+ header.writeUInt8(image.size === 256 ? 0 : image.size, entryOffset)
+ header.writeUInt8(image.size === 256 ? 0 : image.size, entryOffset + 1)
+ header.writeUInt8(0, entryOffset + 2)
+ header.writeUInt8(0, entryOffset + 3)
+ header.writeUInt16LE(1, entryOffset + 4)
+ header.writeUInt16LE(32, entryOffset + 6)
+ header.writeUInt32LE(image.png.length, entryOffset + 8)
+ header.writeUInt32LE(imageOffset, entryOffset + 12)
+ imageOffset += image.png.length
+ }
+
+ return Buffer.concat([header, ...images.map(image => image.png)])
+}
+
+async function writeThemeVariant(theme) {
+ const image = await renderSvg(path.join(assetsDirectory, `icon-${theme}.svg`))
+ const png = image.toPNG({ scaleFactor: 1 })
+ await fs.writeFile(path.join(assetsDirectory, `icon-${theme}.png`), png)
+}
+
+async function writeWindowsFallbackIcon() {
+ const source = nativeImage.createFromPath(path.join(assetsDirectory, 'icon.png'))
+ if (source.isEmpty()) {
+ throw new Error('Unable to load assets/icon.png for the Windows fallback icon.')
+ }
+
+ const sizes = [16, 24, 32, 48, 64, 128, 256]
+ const images = sizes.map(size => ({
+ size,
+ png: source.resize({ width: size, height: size, quality: 'best' }).toPNG(),
+ }))
+ await fs.writeFile(path.join(assetsDirectory, 'icon.ico'), buildIco(images))
+}
+
+async function main() {
+ await app.whenReady()
+ await fs.mkdir(iconComposerAssetsDirectory, { recursive: true })
+ await fs.copyFile(
+ path.join(assetsDirectory, 'icon.png'),
+ path.join(iconComposerAssetsDirectory, 'icon.png')
+ )
+ await writeThemeVariant('light')
+ await writeThemeVariant('dark')
+ await writeWindowsFallbackIcon()
+}
+
+main()
+ .then(() => app.exit(0))
+ .catch(error => {
+ console.error(error instanceof Error ? error.message : error)
+ app.exit(1)
+ })
diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.ts
index ececb9676..779e8850d 100644
--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts
+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts
@@ -3,6 +3,14 @@ import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
+// The chat store binds to the filesystem (Electron userData). Mock it so
+// passwordLogin can be asserted to bind the env-scoped store without touching
+// real directories.
+vi.mock('../chatStoreBinding.js', () => ({
+ bindChatStoreForUser: vi.fn(),
+ unbindChatStore: vi.fn(),
+}))
+
describe('AppService invitation configuration lookup', () => {
const originalConfigPath = process.env.CLERUM_DESKTOP_CONFIG_PATH
const originalExternalRestApiBaseUrl = process.env.EXTERNAL_REST_API_BASE_URL
@@ -44,10 +52,9 @@ describe('AppService invitation configuration lookup', () => {
delete process.env.PROFILE_UI_BASE_URL
vi.resetModules()
- const [{ AppService }, { config, isDesktopRuntimeConfigured }] = await Promise.all([
- import('../appService.js'),
- import('../config.js'),
- ])
+ const [{ AppService }, { config, isDesktopRuntimeConfigured, resolveEnvKey }] =
+ await Promise.all([import('../appService.js'), import('../config.js')])
+ const { bindChatStoreForUser } = await import('../chatStoreBinding.js')
const service = new AppService() as unknown as {
authClient: {
@@ -109,6 +116,12 @@ describe('AppService invitation configuration lookup', () => {
expect(service.authClient.passwordLogin).toHaveBeenCalledWith('[email protected]', 'password123')
expect(result).toMatchObject({ authenticated: true, me: { email: '[email protected]' } })
+ // The env-scoped chat store must be bound after a password login, or every
+ // chat:* IPC throws "Not authenticated" until something else re-binds.
+ expect(bindChatStoreForUser).toHaveBeenCalledWith(
+ 'user-1',
+ resolveEnvKey('https://api.example.com')
+ )
expect(config.externalRestApiBaseUrl).toBe('https://api.example.com')
expect(config.rpcProxyBaseUrl).toBe('https://rpc.example.com')
expect(config.desktopProfileUiBaseUrl).toBe('https://profile.example.com')
diff --git a/desktop-app/src/__tests__/appService.rpc.test.ts b/desktop-app/src/__tests__/appService.rpc.test.ts
index 7775f35e2..90f315ded 100644
--- a/desktop-app/src/__tests__/appService.rpc.test.ts
+++ b/desktop-app/src/__tests__/appService.rpc.test.ts
@@ -1,9 +1,24 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
import { AppService } from '../appService.js'
import { __setChatStoreBaseDirForTests } from '../chatStoreBinding.js'
import { ApiError } from '../httpClient.js'
describe('AppService.invokeHostMessage', () => {
+ let chatStoreBaseDir: string
+
+ beforeEach(async () => {
+ chatStoreBaseDir = await fs.mkdtemp(path.join(os.tmpdir(), 'clerum-app-service-rpc-'))
+ __setChatStoreBaseDirForTests(chatStoreBaseDir)
+ })
+
+ afterEach(async () => {
+ __setChatStoreBaseDirForTests(null)
+ await fs.rm(chatStoreBaseDir, { recursive: true, force: true })
+ })
+
it('forces desktop host messages onto the authenticated rpc envelope', async () => {
const service = new AppService() as any
service.sessionToken = 'session-token'
@@ -60,7 +75,6 @@ describe('AppService.invokeHostMessage', () => {
})
it('switches to a matching directory team before issuing RPC tokens for teamless sessions', async () => {
- __setChatStoreBaseDirForTests('/private/tmp/clerum-desktop-app-test-chats')
const service = new AppService() as any
service.sessionToken = 'teamless-token'
service.me = {
@@ -128,11 +142,9 @@ describe('AppService.invokeHostMessage', () => {
['host:message:invoke', 'host:task:read', 'host:wake:write'],
['pro-agent']
)
- __setChatStoreBaseDirForTests(null)
})
it('uses the teamless session when a directly granted agent needs an RPC token', async () => {
- __setChatStoreBaseDirForTests('/private/tmp/clerum-desktop-app-test-chats')
const service = new AppService() as any
service.sessionToken = 'teamless-token'
service.me = {
@@ -180,11 +192,9 @@ describe('AppService.invokeHostMessage', () => {
['pro-agent']
)
expect(service.rpcClient.invokeHostMessage).toHaveBeenCalled()
- __setChatStoreBaseDirForTests(null)
})
it('uses the access catalog response without probing host status', async () => {
- __setChatStoreBaseDirForTests('/private/tmp/clerum-desktop-app-test-chats')
const service = new AppService() as any
service.sessionToken = 'session-token'
service.me = {
@@ -233,6 +243,5 @@ describe('AppService.invokeHostMessage', () => {
expect(catalog.mcpServersByAgent).toEqual({ 'allowed-agent': [], 'denied-agent': [] })
expect(service.rpcTokenManager.clear).toHaveBeenCalledTimes(1)
expect(service.rpcClient.getHostStatus).not.toHaveBeenCalled()
- __setChatStoreBaseDirForTests(null)
})
})
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index 2070f2c7d..714ef0125 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -296,3 +296,54 @@ describe('path-segment validation', () => {
await expect(store.loadMessages('agent-1', 'a/b')).resolves.toEqual([])
})
})
+
+// ── upsertServerSessions (spec §5.3) ──────────────────────────────────────────
+
+describe('upsertServerSessions', () => {
+ it('refreshes updatedAt for an existing chat when the server is newer', async () => {
+ await store.createChat('agent-1', 'c1')
+ // Force an old updatedAt.
+ await store.saveMessages('agent-1', 'c1', [])
+ const before = (await store.listChats('agent-1')).find(c => c.id === 'c1')!
+ const newer = new Date(Date.now() + 60_000).toISOString()
+
+ const changed = await store.upsertServerSessions('agent-1', [
+ { chatId: 'c1', lastActivityAt: newer },
+ ])
+
+ expect(changed).toBe(1)
+ const after = (await store.listChats('agent-1')).find(c => c.id === 'c1')!
+ expect(new Date(after.updatedAt).getTime()).toBeGreaterThan(
+ new Date(before.updatedAt).getTime()
+ )
+ expect(after.updatedAt).toBe(newer)
+ })
+
+ it('does NOT resurrect a server-only session as a local chat (no delete-resurrection)', async () => {
+ await store.createChat('agent-1', 'c1')
+ const changed = await store.upsertServerSessions('agent-1', [
+ { chatId: 'server-only', lastActivityAt: new Date().toISOString() },
+ ])
+ expect(changed).toBe(0)
+ expect((await store.listChats('agent-1')).map(c => c.id)).toEqual(['c1'])
+ })
+
+ it('never moves a local chat backwards in time (server older is ignored)', async () => {
+ await store.createChat('agent-1', 'c1')
+ const current = (await store.listChats('agent-1')).find(c => c.id === 'c1')!
+ const older = new Date(Date.now() - 60_000).toISOString()
+
+ const changed = await store.upsertServerSessions('agent-1', [
+ { chatId: 'c1', lastActivityAt: older },
+ ])
+
+ expect(changed).toBe(0)
+ const after = (await store.listChats('agent-1')).find(c => c.id === 'c1')!
+ expect(after.updatedAt).toBe(current.updatedAt)
+ })
+
+ it('is a no-op for an empty session list', async () => {
+ await store.createChat('agent-1', 'c1')
+ expect(await store.upsertServerSessions('agent-1', [])).toBe(0)
+ })
+})
diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.ts
index 1a524e140..ba247ad4e 100644
--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts
+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts
@@ -9,6 +9,17 @@ import {
unbindChatStore,
} from '../chatStoreBinding'
+// Env keys are opaque, filesystem-safe slugs from resolveEnvKey. Any two distinct
+// strings model two distinct environments for these tests.
+const ENV_A = 'env-a-0011223344'
+const ENV_B = 'env-b-5566778899'
+
+const exists = (p: string) =>
+ fs
+ .stat(p)
+ .then(() => true)
+ .catch(() => false)
+
describe('chatStoreBinding', () => {
let tmpBase: string
@@ -27,75 +38,89 @@ describe('chatStoreBinding', () => {
expect(() => requireChatStore()).toThrow(/Not authenticated/)
})
- it('bindChatStoreForUser returns a store rooted under the user subdir', async () => {
- await bindChatStoreForUser('user-a')
+ it('roots the store under <base>/<envKey>/<userId> (spec §5.2)', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
const store = requireChatStore()
await store.createChat('agent-x', 'chat-1')
- const exists = await fs
- .stat(path.join(tmpBase, 'user-a', 'agent-x', 'index.json'))
- .then(() => true)
- .catch(() => false)
- expect(exists).toBe(true)
+ expect(await exists(path.join(tmpBase, ENV_A, 'user-a', 'agent-x', 'index.json'))).toBe(true)
+ // Never under the legacy (pre-envKey) location.
+ expect(await exists(path.join(tmpBase, 'user-a', 'agent-x', 'index.json'))).toBe(false)
})
- it('unbindChatStore makes requireChatStore throw again', async () => {
- await bindChatStoreForUser('user-a')
- unbindChatStore()
- expect(() => requireChatStore()).toThrow(/Not authenticated/)
- })
+ it('isolates the SAME user across environments (the cross-cluster bug)', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
+ await requireChatStore().createChat('agent-x', 'chat-in-a')
- it("rebinding to a different user does not touch the previous user's files", async () => {
- await bindChatStoreForUser('user-a')
- await requireChatStore().createChat('agent-x', 'chat-a')
+ await bindChatStoreForUser('user-a', ENV_B)
+ // Env B starts empty — env A's chat is invisible here.
+ expect(await requireChatStore().listChats('agent-x')).toEqual([])
+ await requireChatStore().createChat('agent-x', 'chat-in-b')
- await bindChatStoreForUser('user-b')
- await requireChatStore().createChat('agent-x', 'chat-b')
+ // Both env subtrees exist and hold only their own chat.
+ await bindChatStoreForUser('user-a', ENV_A)
+ expect((await requireChatStore().listChats('agent-x')).map(c => c.id)).toEqual(['chat-in-a'])
+ await bindChatStoreForUser('user-a', ENV_B)
+ expect((await requireChatStore().listChats('agent-x')).map(c => c.id)).toEqual(['chat-in-b'])
+ })
- const userAIndex = path.join(tmpBase, 'user-a', 'agent-x', 'index.json')
- const userBIndex = path.join(tmpBase, 'user-b', 'agent-x', 'index.json')
- expect((await fs.stat(userAIndex)).isFile()).toBe(true)
- expect((await fs.stat(userBIndex)).isFile()).toBe(true)
+ it('re-binds when the envKey changes for the same user', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
+ const storeA = requireChatStore()
+ await bindChatStoreForUser('user-a', ENV_B)
+ expect(requireChatStore()).not.toBe(storeA)
})
- it('rebinding the same userId is idempotent (no files moved or lost)', async () => {
- await bindChatStoreForUser('user-a')
+ it('unbindChatStore makes requireChatStore throw again', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
+ unbindChatStore()
+ expect(() => requireChatStore()).toThrow(/Not authenticated/)
+ })
+
+ it('rebinding the same (env, userId) is idempotent (no files moved or lost)', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
await requireChatStore().createChat('agent-x', 'chat-a')
- await bindChatStoreForUser('user-a')
+ await bindChatStoreForUser('user-a', ENV_A)
const chats = await requireChatStore().listChats('agent-x')
expect(chats.find(c => c.id === 'chat-a')).toBeDefined()
})
- it('rebinding the same userId keeps the store bound (no "Not authenticated" window)', async () => {
- await bindChatStoreForUser('user-a')
+ it('rebinding the same (env, userId) keeps the store bound (no "Not authenticated" window)', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
const firstStore = requireChatStore()
-
- // Same-user re-bind (team switch / catalog refresh) must not tear down the
- // active store: a concurrent chat IPC between unbind and rebind would
- // throw "Not authenticated" and blank the UI's session lists.
- const rebind = bindChatStoreForUser('user-a')
+ const rebind = bindChatStoreForUser('user-a', ENV_A)
expect(requireChatStore()).toBe(firstStore)
await rebind
expect(requireChatStore()).toBe(firstStore)
})
- it('coalesces concurrent binds for the same userId', async () => {
- const first = bindChatStoreForUser('user-a')
- const second = bindChatStoreForUser('user-a')
+ it('coalesces concurrent binds for the same (env, userId)', async () => {
+ const first = bindChatStoreForUser('user-a', ENV_A)
+ const second = bindChatStoreForUser('user-a', ENV_A)
await Promise.all([first, second])
const store = requireChatStore()
await store.createChat('agent-x', 'chat-1')
expect((await store.listChats('agent-x')).map(c => c.id)).toEqual(['chat-1'])
})
- // D.4 §7.1 / §5.2 — bootstrap wipes any pre-v2 (legacy) per-agent cache dir.
- describe('legacy cache wipe on bind', () => {
+ it('rejects an unsafe userId or envKey before touching the filesystem (no wipe escape)', async () => {
+ for (const bad of ['', '.', '..', '../../etc', 'a/b', 'a\\b']) {
+ await expect(bindChatStoreForUser(bad, ENV_A)).rejects.toThrow(/unsafe path segment/)
+ await expect(bindChatStoreForUser('user-a', bad)).rejects.toThrow(/unsafe path segment/)
+ }
+ expect(() => requireChatStore()).toThrow(/Not authenticated/)
+ })
+
+ // §5.2 / §7.1 — bootstrap wipes any pre-v2 (legacy schema) per-agent cache dir
+ // WITHIN the env-scoped user directory.
+ describe('legacy schema wipe on bind', () => {
async function seedAgentDir(
+ envKey: string,
userId: string,
agentRef: string,
indexContent: string | null,
chatFiles: Record<string, string> = {}
) {
- const agentDir = path.join(tmpBase, userId, agentRef)
+ const agentDir = path.join(tmpBase, envKey, userId, agentRef)
await fs.mkdir(agentDir, { recursive: true })
if (indexContent !== null) {
await fs.writeFile(path.join(agentDir, 'index.json'), indexContent)
@@ -105,36 +130,28 @@ describe('chatStoreBinding', () => {
}
}
- const exists = (p: string) =>
- fs
- .stat(p)
- .then(() => true)
- .catch(() => false)
-
it('wipes an agent dir whose index.json is v1', async () => {
const v1Index = JSON.stringify({
version: 1,
chats: [{ id: 'old' }],
lastActiveChatId: 'old',
})
- await seedAgentDir('user-legacy', 'agent-x', v1Index, { 'old.json': '{"version":1}' })
+ await seedAgentDir(ENV_A, 'user-legacy', 'agent-x', v1Index, { 'old.json': '{"version":1}' })
- await bindChatStoreForUser('user-legacy')
+ await bindChatStoreForUser('user-legacy', ENV_A)
- expect(await exists(path.join(tmpBase, 'user-legacy', 'agent-x'))).toBe(false)
- // A fresh store works and starts empty.
- const chats = await requireChatStore().listChats('agent-x')
- expect(chats).toEqual([])
+ expect(await exists(path.join(tmpBase, ENV_A, 'user-legacy', 'agent-x'))).toBe(false)
+ expect(await requireChatStore().listChats('agent-x')).toEqual([])
})
it('wipes an agent dir with a missing/unparseable index.json', async () => {
- await seedAgentDir('user-broken', 'agent-x', 'not json{', { 'c.json': '{}' })
- await seedAgentDir('user-broken', 'agent-y', null, { 'c.json': '{}' })
+ await seedAgentDir(ENV_A, 'user-broken', 'agent-x', 'not json{', { 'c.json': '{}' })
+ await seedAgentDir(ENV_A, 'user-broken', 'agent-y', null, { 'c.json': '{}' })
- await bindChatStoreForUser('user-broken')
+ await bindChatStoreForUser('user-broken', ENV_A)
- expect(await exists(path.join(tmpBase, 'user-broken', 'agent-x'))).toBe(false)
- expect(await exists(path.join(tmpBase, 'user-broken', 'agent-y'))).toBe(false)
+ expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-x'))).toBe(false)
+ expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-y'))).toBe(false)
})
it('preserves a v2 agent dir', async () => {
@@ -142,30 +159,83 @@ describe('chatStoreBinding', () => {
version: 2,
chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],
lastActiveChatId: 'keep',
- chatPanelOpen: false,
onboardingDismissed: false,
})
- await seedAgentDir('user-current', 'agent-x', v2Index)
+ await seedAgentDir(ENV_A, 'user-current', 'agent-x', v2Index)
- await bindChatStoreForUser('user-current')
+ await bindChatStoreForUser('user-current', ENV_A)
- expect(await exists(path.join(tmpBase, 'user-current', 'agent-x', 'index.json'))).toBe(true)
- const chats = await requireChatStore().listChats('agent-x')
- expect(chats.find(c => c.id === 'keep')).toBeDefined()
+ expect(await exists(path.join(tmpBase, ENV_A, 'user-current', 'agent-x', 'index.json'))).toBe(
+ true
+ )
+ expect(
+ (await requireChatStore().listChats('agent-x')).find(c => c.id === 'keep')
+ ).toBeDefined()
})
it('is a no-op when the user has no cache directory yet', async () => {
- await expect(bindChatStoreForUser('brand-new-user')).resolves.toBeUndefined()
- const chats = await requireChatStore().listChats('agent-x')
- expect(chats).toEqual([])
+ await expect(bindChatStoreForUser('brand-new-user', ENV_A)).resolves.toBeUndefined()
+ expect(await requireChatStore().listChats('agent-x')).toEqual([])
})
+ })
- it('rejects an unsafe userId before touching the filesystem (no wipe escape)', async () => {
- for (const bad of ['', '.', '..', '../../etc', 'a/b', 'a\\b']) {
- await expect(bindChatStoreForUser(bad)).rejects.toThrow(/unsafe path segment/)
- }
- // A rejected bind leaves the store unbound rather than serving a wrong dir.
- expect(() => requireChatStore()).toThrow(/Not authenticated/)
+ // §5.5 (D3) — the pre-envKey cache tree (<base>/<userId>/<agentRef>/…, no env
+ // level) is discarded once on the first bind after the update, then rebuilt
+ // from the server. Env-scoped subtrees are never touched.
+ describe('one-shot pre-envKey legacy tree wipe', () => {
+ async function seedLegacyUserDir(userId: string, agentRef: string) {
+ const agentDir = path.join(tmpBase, userId, agentRef)
+ await fs.mkdir(agentDir, { recursive: true })
+ await fs.writeFile(
+ path.join(agentDir, 'index.json'),
+ JSON.stringify({
+ version: 2,
+ chats: [],
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ })
+ )
+ }
+
+ it('drops the legacy per-user tree on first env-scoped bind', async () => {
+ await seedLegacyUserDir('user-a', 'agent-x')
+ await seedLegacyUserDir('user-b', 'agent-y')
+
+ await bindChatStoreForUser('user-a', ENV_A)
+
+ // Both legacy user dirs are gone; the env-scoped store is separate + empty.
+ expect(await exists(path.join(tmpBase, 'user-a', 'agent-x'))).toBe(false)
+ expect(await exists(path.join(tmpBase, 'user-b', 'agent-y'))).toBe(false)
+ expect(await requireChatStore().listChats('agent-x')).toEqual([])
+ })
+
+ it('runs only once — a legacy dir re-created after the marker survives', async () => {
+ await seedLegacyUserDir('user-a', 'agent-x')
+ await bindChatStoreForUser('user-a', ENV_A)
+ expect(await exists(path.join(tmpBase, 'user-a', 'agent-x'))).toBe(false)
+
+ // Simulate a stray legacy-shaped dir appearing after migration; the marker
+ // must prevent a second destructive sweep.
+ await seedLegacyUserDir('user-c', 'agent-z')
+ unbindChatStore()
+ await bindChatStoreForUser('user-a', ENV_A)
+ expect(await exists(path.join(tmpBase, 'user-c', 'agent-z'))).toBe(true)
+ })
+
+ it('never wipes an env-scoped subtree (index.json is one level deeper)', async () => {
+ // Pre-seed env A with a real chat, then bind env B for the first time.
+ await bindChatStoreForUser('user-a', ENV_A)
+ await requireChatStore().createChat('agent-x', 'chat-a')
+ unbindChatStore()
+
+ // A fresh process would re-run the one-shot if the marker were missing;
+ // simulate that by removing the marker before binding a different env.
+ await fs.rm(path.join(tmpBase, '.env-scoped'), { force: true })
+ await bindChatStoreForUser('user-a', ENV_B)
+
+ // Env A's data is untouched — it lives at depth 3, not the legacy depth 2.
+ await bindChatStoreForUser('user-a', ENV_A)
+ expect((await requireChatStore().listChats('agent-x')).map(c => c.id)).toEqual(['chat-a'])
})
})
})
diff --git a/desktop-app/src/__tests__/config.envKey.test.ts b/desktop-app/src/__tests__/config.envKey.test.ts
new file mode 100644
index 000000000..147abcfa2
--- /dev/null
+++ b/desktop-app/src/__tests__/config.envKey.test.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// resolveEnvKey is pure, but importing config.ts touches the Electron `app`
+// object at module load, so provide a minimal mock.
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn(() => '/tmp/evenfire-test-userdata'),
+ isPackaged: false,
+ isReady: vi.fn(() => true),
+ setName: vi.fn(),
+ setPath: vi.fn(),
+ },
+}))
+
+let resolveEnvKey: (url: string) => string
+
+beforeEach(async () => {
+ const mod = await import('../config.js')
+ resolveEnvKey = mod.resolveEnvKey
+})
+
+describe('resolveEnvKey (spec §5.1, D1)', () => {
+ it('is deterministic and stable across calls for the same origin', () => {
+ const a = resolveEnvKey('https://example.com')
+ const b = resolveEnvKey('https://example.com')
+ expect(a).toBe(b)
+ })
+
+ it('is filesystem/keychain-safe (no scheme separators, slashes, or colons)', () => {
+ const key = resolveEnvKey('https://example.com:8091')
+ expect(key).not.toMatch(/[/\\:]/)
+ expect(key).toMatch(/^[a-z0-9_]+-[0-9a-f]{12}$/)
+ })
+
+ it('keys distinct origins apart — dev vs prod (D1 subdomain case)', () => {
+ expect(resolveEnvKey('https://example.com')).not.toBe(resolveEnvKey('https://example.com'))
+ })
+
+ it('keys apart on scheme and port (origin includes both)', () => {
+ expect(resolveEnvKey('http://api.example.com')).not.toBe(
+ resolveEnvKey('https://api.example.com')
+ )
+ expect(resolveEnvKey('https://api.example.com:8091')).not.toBe(
+ resolveEnvKey('https://api.example.com:8092')
+ )
+ })
+
+ it('ignores path/query (same origin ⇒ same key)', () => {
+ expect(resolveEnvKey('https://api.example.com/rpc?x=1')).toBe(
+ resolveEnvKey('https://api.example.com')
+ )
+ })
+
+ it('produces a valid, stable key for the Localhost sentinel origin', () => {
+ const key = resolveEnvKey('http://127.0.0.1:8091')
+ expect(key).toMatch(/^http_127_0_0_1_8091-[0-9a-f]{12}$/)
+ expect(resolveEnvKey('http://127.0.0.1:8091')).toBe(key)
+ })
+
+ it('does not throw on an invalid URL (falls back to a stable key)', () => {
+ expect(() => resolveEnvKey('not a url')).not.toThrow()
+ expect(resolveEnvKey('not a url')).toBe(resolveEnvKey('not a url'))
+ })
+})
diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.ts
index f096001b0..0246670c9 100644
--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts
@@ -8,12 +8,22 @@ import {
} from '../sandboxUiDriver.js'
describe('partitionFor', () => {
- it('produces a stable persist:sandbox-ui partition name per recipe', () => {
- expect(partitionFor('sandbox-recipes', 'r1')).toBe('persist:sandbox-ui-sandbox-recipes-r1')
+ it('produces a stable persist:sandbox-ui partition name per (env, recipe)', () => {
+ expect(partitionFor('env1', 'sandbox-recipes', 'r1')).toBe(
+ 'persist:sandbox-ui-env1-sandbox-recipes-r1'
+ )
})
it('keeps recipe A and recipe B in distinct partitions (storage isolation)', () => {
- expect(partitionFor('sandbox-recipes', 'a')).not.toBe(partitionFor('sandbox-recipes', 'b'))
+ expect(partitionFor('env1', 'sandbox-recipes', 'a')).not.toBe(
+ partitionFor('env1', 'sandbox-recipes', 'b')
+ )
+ })
+
+ it('keeps the same recipe in distinct partitions across environments (spec §5.2)', () => {
+ expect(partitionFor('envA', 'sandbox-recipes', 'r1')).not.toBe(
+ partitionFor('envB', 'sandbox-recipes', 'r1')
+ )
})
})
diff --git a/desktop-app/src/__tests__/sandboxUiPartitionGc.test.ts b/desktop-app/src/__tests__/sandboxUiPartitionGc.test.ts
index 9d998b476..f3d856913 100644
--- a/desktop-app/src/__tests__/sandboxUiPartitionGc.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiPartitionGc.test.ts
@@ -1,17 +1,43 @@
-import { describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
import {
type GcPlanInput,
+ SANDBOX_UI_PRE_ENV_MIGRATION_MARKER,
+ isPreEnvSandboxUiPartitionDirName,
isSandboxUiPartitionDirName,
+ isSandboxUiPartitionDirNameForEnv,
+ maybeWipePreEnvSandboxUiPartitions,
partitionDirNameFor,
planSandboxUiPartitionGc,
} from '../sandboxUiPartitionGc.js'
+const clearStorageData = vi.fn(async () => {})
+vi.mock('electron', () => ({
+ app: { getPath: vi.fn(() => '/tmp/clerum-desktop-test') },
+ session: { fromPartition: vi.fn(() => ({ clearStorageData })) },
+}))
+
describe('partitionDirNameFor', () => {
- it('matches the persist:sandbox-ui-<ns>-<name> partition encoding (minus the `persist:` prefix)', () => {
- // The driver stamps `persist:sandbox-ui-${ns}-${name}` as the
+ it('matches the persist:sandbox-ui-<env>-<ns>-<name> partition encoding (minus the `persist:` prefix)', () => {
+ // The driver stamps `persist:sandbox-ui-${env}-${ns}-${name}` as the
// Electron partition; on disk, Chromium drops the `persist:`
- // prefix, so the directory name is `sandbox-ui-${ns}-${name}`.
- expect(partitionDirNameFor('sandbox-recipes', 'r1')).toBe('sandbox-ui-sandbox-recipes-r1')
+ // prefix, so the directory name is `sandbox-ui-${env}-${ns}-${name}`.
+ expect(partitionDirNameFor('env1', 'sandbox-recipes', 'r1')).toBe(
+ 'sandbox-ui-env1-sandbox-recipes-r1'
+ )
+ })
+})
+
+describe('isSandboxUiPartitionDirNameForEnv', () => {
+ it('matches only the given environment prefix (spec §5.2)', () => {
+ expect(isSandboxUiPartitionDirNameForEnv('sandbox-ui-envA-sandbox-recipes-r1', 'envA')).toBe(
+ true
+ )
+ expect(isSandboxUiPartitionDirNameForEnv('sandbox-ui-envB-sandbox-recipes-r1', 'envA')).toBe(
+ false
+ )
})
})
@@ -29,6 +55,92 @@ describe('isSandboxUiPartitionDirName', () => {
})
})
+describe('isPreEnvSandboxUiPartitionDirName', () => {
+ it('flags pre-env partitions (no envKey segment)', () => {
+ expect(isPreEnvSandboxUiPartitionDirName('sandbox-ui-sandbox-recipes-r1')).toBe(true)
+ expect(isPreEnvSandboxUiPartitionDirName('sandbox-ui-mcp-server-r1')).toBe(true)
+ })
+
+ it('does NOT flag env-scoped partitions (valid <slug>-<12hex> envKey)', () => {
+ expect(
+ isPreEnvSandboxUiPartitionDirName('sandbox-ui-localhost_8091-ab12cd34ef56-sandbox-recipes-r1')
+ ).toBe(false)
+ expect(isPreEnvSandboxUiPartitionDirName('sandbox-ui-env-0123456789ab-mcp-server-r1')).toBe(
+ false
+ )
+ })
+
+ it('ignores non-sandbox-ui dirs and the bare prefix', () => {
+ expect(isPreEnvSandboxUiPartitionDirName('default')).toBe(false)
+ expect(isPreEnvSandboxUiPartitionDirName('sandbox-ui-')).toBe(false)
+ })
+})
+
+describe('maybeWipePreEnvSandboxUiPartitions', () => {
+ let userDataDir: string
+ let partitionsRoot: string
+ const legacyDir = 'sandbox-ui-sandbox-recipes-r1'
+ const envDir = 'sandbox-ui-localhost_8091-ab12cd34ef56-sandbox-recipes-r1'
+
+ beforeEach(async () => {
+ clearStorageData.mockClear()
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'sandbox-ui-gc-'))
+ partitionsRoot = path.join(userDataDir, 'Partitions')
+ await fs.mkdir(path.join(partitionsRoot, legacyDir), { recursive: true })
+ await fs.writeFile(path.join(partitionsRoot, legacyDir, 'Cookies'), 'x')
+ await fs.mkdir(path.join(partitionsRoot, envDir), { recursive: true })
+ await fs.writeFile(path.join(partitionsRoot, envDir, 'Cookies'), 'y')
+ await fs.mkdir(path.join(partitionsRoot, 'default'), { recursive: true })
+ })
+
+ afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+ })
+
+ const exists = async (p: string) =>
+ fs
+ .access(p)
+ .then(() => true)
+ .catch(() => false)
+
+ it('(a) wipes the pre-env legacy partition', async () => {
+ const wiped = await maybeWipePreEnvSandboxUiPartitions(userDataDir)
+ expect(wiped).toEqual([legacyDir])
+ expect(await exists(path.join(partitionsRoot, legacyDir))).toBe(false)
+ expect(clearStorageData).toHaveBeenCalledTimes(1)
+ })
+
+ it('(b) leaves valid env-scoped partitions and unrelated dirs intact', async () => {
+ await maybeWipePreEnvSandboxUiPartitions(userDataDir)
+ expect(await exists(path.join(partitionsRoot, envDir))).toBe(true)
+ expect(await exists(path.join(partitionsRoot, 'default'))).toBe(true)
+ })
+
+ it('(c) marker prevents a second run from re-scanning/wiping', async () => {
+ await maybeWipePreEnvSandboxUiPartitions(userDataDir)
+ expect(await exists(path.join(userDataDir, SANDBOX_UI_PRE_ENV_MIGRATION_MARKER))).toBe(true)
+
+ // Re-create a legacy dir; the marker must keep the second pass a no-op.
+ await fs.mkdir(path.join(partitionsRoot, legacyDir), { recursive: true })
+ clearStorageData.mockClear()
+ const wiped = await maybeWipePreEnvSandboxUiPartitions(userDataDir)
+ expect(wiped).toEqual([])
+ expect(await exists(path.join(partitionsRoot, legacyDir))).toBe(true)
+ expect(clearStorageData).not.toHaveBeenCalled()
+ })
+
+ it('returns [] with no marker when the Partitions dir does not exist', async () => {
+ const fresh = await fs.mkdtemp(path.join(os.tmpdir(), 'sandbox-ui-gc-fresh-'))
+ try {
+ const wiped = await maybeWipePreEnvSandboxUiPartitions(fresh)
+ expect(wiped).toEqual([])
+ expect(await exists(path.join(fresh, SANDBOX_UI_PRE_ENV_MIGRATION_MARKER))).toBe(false)
+ } finally {
+ await fs.rm(fresh, { recursive: true, force: true })
+ }
+ })
+})
+
describe('planSandboxUiPartitionGc', () => {
function input(overrides: Partial<GcPlanInput>): GcPlanInput {
return {
diff --git a/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts b/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts
new file mode 100644
index 000000000..8ac4febc4
--- /dev/null
+++ b/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+// Pure-fallback platform: keytar import fails AND safeStorage is unavailable, so
+// the token round-trips through the per-env PLAIN-TEXT file. This locks the
+// regression where the per-env plain file was written but never read back
+// (silent logout on every restart).
+vi.mock('keytar', () => {
+ throw new Error('keytar unavailable on this platform')
+})
+
+let userDataDir = ''
+
+vi.mock('electron', () => ({
+ app: { isReady: vi.fn(() => true), getPath: vi.fn(() => userDataDir) },
+ safeStorage: { isEncryptionAvailable: vi.fn(() => false) },
+}))
+
+const ENV_A = 'env_a-000000000000'
+const ENV_B = 'env_b-111111111111'
+
+let TokenStore: typeof import('../tokenStore.js').TokenStore
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'evenfire-plainfallback-'))
+ TokenStore = (await import('../tokenStore.js')).TokenStore
+})
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+describe('TokenStore plain-text fallback (no keytar, no safeStorage)', () => {
+ it('reads back a token it wrote to the per-env plain-text file (restart survival)', async () => {
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+ // A fresh instance models a restart — no in-memory state carried over.
+ expect(await new TokenStore().getSessionToken(ENV_A)).toBe('tok-a')
+ // On disk under the env-scoped plain-text filename.
+ expect(
+ await fs
+ .access(path.join(userDataDir, `session-token-${ENV_A}.json`))
+ .then(() => true)
+ .catch(() => false)
+ ).toBe(true)
+ })
+
+ it('does not leak the plain-text token across environments', async () => {
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+ expect(await store.getSessionToken(ENV_B)).toBeNull()
+ })
+
+ it('clear removes the per-env plain-text file', async () => {
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+ await store.clearSessionToken(ENV_A)
+ expect(await store.getSessionToken(ENV_A)).toBeNull()
+ })
+})
diff --git a/desktop-app/src/__tests__/tokenStore.test.ts b/desktop-app/src/__tests__/tokenStore.test.ts
new file mode 100644
index 000000000..6ca10143d
--- /dev/null
+++ b/desktop-app/src/__tests__/tokenStore.test.ts
@@ -0,0 +1,109 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// In-memory keychain backing the mocked keytar module. Keyed by service:account
+// so per-environment account isolation is directly observable.
+const keychain = new Map<string, string>()
+const keyOf = (service: string, account: string) => `${service}::${account}`
+
+vi.mock('keytar', () => ({
+ getPassword: vi.fn(async (service: string, account: string) =>
+ keychain.has(keyOf(service, account)) ? keychain.get(keyOf(service, account))! : null
+ ),
+ setPassword: vi.fn(async (service: string, account: string, password: string) => {
+ keychain.set(keyOf(service, account), password)
+ }),
+ deletePassword: vi.fn(async (service: string, account: string) =>
+ keychain.delete(keyOf(service, account))
+ ),
+}))
+
+// app.isReady()=false + safeStorage unavailable ⇒ the keytar path is the only
+// active store, which is exactly what we want to assert per-env isolation on.
+vi.mock('electron', () => ({
+ app: { isReady: vi.fn(() => false), getPath: vi.fn(() => '/tmp/evenfire-test') },
+ safeStorage: { isEncryptionAvailable: vi.fn(() => false) },
+}))
+
+const SERVICE = 'Evenfire'
+const LEGACY_ACCOUNT = 'session-token'
+// Realistic env keys: `resolveEnvKey` emits `<slug>-<12 hex>` where the slug is
+// `[a-z0-9_]+` (non-alphanumerics collapsed to `_`), so the ONLY `-` is the
+// hash separator.
+const ENV_A = 'env_a-000000000000'
+const ENV_B = 'env_b-111111111111'
+
+let TokenStore: typeof import('../tokenStore.js').TokenStore
+
+beforeEach(async () => {
+ keychain.clear()
+ TokenStore = (await import('../tokenStore.js')).TokenStore
+})
+
+describe('TokenStore per-environment slots (spec §5.2)', () => {
+ it('stores and reads a token under the env-scoped account', async () => {
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+ expect(await store.getSessionToken(ENV_A)).toBe('tok-a')
+ // Physically stored under the namespaced account, never the global one.
+ expect(keychain.get(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A}`))).toBe('tok-a')
+ expect(keychain.has(keyOf(SERVICE, LEGACY_ACCOUNT))).toBe(false)
+ })
+
+ it('does not leak env A token into env B', async () => {
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+ expect(await store.getSessionToken(ENV_B)).toBeNull()
+
+ await store.setSessionToken('tok-b', ENV_B)
+ expect(await store.getSessionToken(ENV_A)).toBe('tok-a')
+ expect(await store.getSessionToken(ENV_B)).toBe('tok-b')
+ })
+
+ it('clear only removes the active env slot (other env token survives)', async () => {
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+ await store.setSessionToken('tok-b', ENV_B)
+
+ await store.clearSessionToken(ENV_A)
+ expect(await store.getSessionToken(ENV_A)).toBeNull()
+ expect(await store.getSessionToken(ENV_B)).toBe('tok-b')
+ })
+
+ it('migrates a legacy global-slot token into the active env slot, then deletes it', async () => {
+ // Simulate a pre-per-env install: token in the single global account.
+ keychain.set(keyOf(SERVICE, LEGACY_ACCOUNT), 'legacy-tok')
+ const store = new TokenStore()
+
+ const migrated = await store.getSessionToken(ENV_A)
+ expect(migrated).toBe('legacy-tok')
+ // Copied into the env slot and removed from the legacy slot (no cross-env reuse).
+ expect(keychain.get(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A}`))).toBe('legacy-tok')
+ expect(keychain.has(keyOf(SERVICE, LEGACY_ACCOUNT))).toBe(false)
+
+ // A second env no longer sees the (now-consumed) legacy token.
+ expect(await store.getSessionToken(ENV_B)).toBeNull()
+ })
+
+ it('clear removes the legacy global slot too (defense against later migration)', async () => {
+ keychain.set(keyOf(SERVICE, LEGACY_ACCOUNT), 'legacy-tok')
+ const store = new TokenStore()
+ await store.setSessionToken('tok-a', ENV_A)
+
+ await store.clearSessionToken(ENV_A)
+ expect(keychain.has(keyOf(SERVICE, LEGACY_ACCOUNT))).toBe(false)
+ })
+
+ it('rejects a malformed envKey before it reaches account/file names', async () => {
+ const store = new TokenStore()
+ // Path-separator, traversal, wrong shape, and empty are all refused up front
+ // so an attacker-controlled value can never build a keychain account or
+ // on-disk filename.
+ for (const bad of ['../etc', 'env_a/000000000000', 'env_a', 'ENV_A-000000000000', '']) {
+ await expect(store.setSessionToken('tok', bad)).rejects.toThrow(/Invalid envKey/)
+ await expect(store.getSessionToken(bad)).rejects.toThrow(/Invalid envKey/)
+ await expect(store.clearSessionToken(bad)).rejects.toThrow(/Invalid envKey/)
+ }
+ // Nothing was written for any rejected key.
+ expect(keychain.size).toBe(0)
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 82fb03d11..c12948519 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -6,6 +6,7 @@ import {
clearDesktopRuntimeConfigSelection,
config,
deleteDesktopRuntimeConfigOption,
+ getActiveEnvKey,
getDesktopRuntimeConfigState,
hydrateDesktopRuntimeConfig,
isDesktopRuntimeConfigured,
@@ -332,7 +333,7 @@ export class AppService {
if (tokenChanged) {
this.rpcTokenManager.clear()
this.accessCatalog = null
- await this.tokenStore.setSessionToken(token)
+ await this.tokenStore.setSessionToken(token, getActiveEnvKey())
}
if (options.refreshMe) {
try {
@@ -341,7 +342,7 @@ export class AppService {
unbindChatStore()
throw error
}
- await bindChatStoreForUser(this.me.id)
+ await bindChatStoreForUser(this.me.id, getActiveEnvKey())
this.updateCachedCurrentTeam(this.me.teamId)
}
}
@@ -349,7 +350,7 @@ export class AppService {
private async getCurrentSessionTeamId(token: string): Promise<string> {
if (this.me?.teamId) return this.me.teamId
this.me = await this.authClient.getMe(token)
- await bindChatStoreForUser(this.me.id)
+ await bindChatStoreForUser(this.me.id, getActiveEnvKey())
this.updateCachedCurrentTeam(this.me.teamId)
return this.me.teamId || ''
}
@@ -465,13 +466,13 @@ export class AppService {
async initialize(): Promise<SessionState> {
hydrateDesktopRuntimeConfig()
- this.sessionToken = await this.tokenStore.getSessionToken()
+ this.sessionToken = await this.tokenStore.getSessionToken(getActiveEnvKey())
if (!this.sessionToken) {
return { authenticated: false, me: null }
}
try {
this.me = await this.authClient.getMe(this.sessionToken)
- await bindChatStoreForUser(this.me.id)
+ await bindChatStoreForUser(this.me.id, getActiveEnvKey())
this.accessCatalog = null
this.teamDirectoryCache = null
this.workflowApprovalTeamById.clear()
@@ -493,6 +494,7 @@ export class AppService {
const { runSandboxUiPartitionGc } = await import('./sandboxUiPartitionGc.js')
const result = await runSandboxUiPartitionGc({
userDataDir: app.getPath('userData'),
+ envKey: getActiveEnvKey(),
listAccessibleApps: () => this.listSandboxUiApps(),
})
if (result.wiped.length || result.evicted.length) {
@@ -510,12 +512,13 @@ export class AppService {
const result = await this.authClient.passwordLogin(email, password)
this.sessionToken = result.token
this.me = result.me
+ await bindChatStoreForUser(result.me.id, getActiveEnvKey())
this.accessCatalog = null
this.teamDirectoryCache = null
this.workflowApprovalTeamById.clear()
this.workflowTeamByKey.clear()
this.rpcTokenManager.clear()
- await this.tokenStore.setSessionToken(result.token)
+ await this.tokenStore.setSessionToken(result.token, getActiveEnvKey())
return { authenticated: true, me: result.me }
}
@@ -578,13 +581,13 @@ export class AppService {
const result = await this.authClient.googleLogin(idToken)
this.sessionToken = result.token
this.me = result.me
- await bindChatStoreForUser(result.me.id)
+ await bindChatStoreForUser(result.me.id, getActiveEnvKey())
this.accessCatalog = null
this.teamDirectoryCache = null
this.workflowApprovalTeamById.clear()
this.workflowTeamByKey.clear()
this.rpcTokenManager.clear()
- await this.tokenStore.setSessionToken(result.token)
+ await this.tokenStore.setSessionToken(result.token, getActiveEnvKey())
return { authenticated: true, me: result.me }
}
@@ -768,7 +771,7 @@ export class AppService {
this.workflowApprovalTeamById.clear()
this.workflowTeamByKey.clear()
this.rpcTokenManager.clear()
- await this.tokenStore.clearSessionToken()
+ await this.tokenStore.clearSessionToken(getActiveEnvKey())
unbindChatStore()
}
@@ -1312,7 +1315,7 @@ export class AppService {
const token = this.requireSessionToken()
const me = this.me ?? (await this.authClient.getMe(token))
this.me = me
- await bindChatStoreForUser(me.id)
+ await bindChatStoreForUser(me.id, getActiveEnvKey())
const currentTeamId = String(me.teamId || '').trim()
const [userContexts, userAgents, teamContexts, teamAgents] = await Promise.all([
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index d8d792196..1a5db8347 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -243,6 +243,43 @@ export class ChatStore {
})
}
+ /**
+ * Reconcile the local index against the server's session listing (spec §5.3).
+ * The mcp-host is the source of truth; this refreshes `updatedAt` for chats
+ * ALREADY tracked locally so the persisted sidebar order/freshness survives a
+ * cold start without a server round-trip.
+ *
+ * Deliberately does NOT create entries for server-only sessions: the sidebar's
+ * in-memory merge (`useChatListController`) already surfaces those, and a local
+ * `deleteChat` doesn't remove the server session — eagerly re-persisting it
+ * would resurrect a chat the user just deleted. Titles are never touched (the
+ * server has none; the client derives them on open). Returns the count of
+ * entries reconciled.
+ */
+ async upsertServerSessions(
+ agentRef: string,
+ sessions: Array<{ chatId: string; lastActivityAt?: string }>
+ ): Promise<number> {
+ if (!sessions.length) return 0
+ return this.serializeIndex(agentRef, async () => {
+ const index = await this.getIndex(agentRef)
+ const byId = new Map(index.chats.map(chat => [chat.id, chat]))
+ let changed = 0
+ for (const session of sessions) {
+ const chat = byId.get(session.chatId)
+ if (!chat) continue // server-only session — do not resurrect a local delete
+ const lastActivityAt = session.lastActivityAt
+ if (!lastActivityAt) continue
+ if (new Date(lastActivityAt).getTime() > new Date(chat.updatedAt).getTime()) {
+ chat.updatedAt = lastActivityAt
+ changed += 1
+ }
+ }
+ if (changed > 0) await this.saveIndex(agentRef, index)
+ return changed
+ })
+ }
+
/** Clear the unread-terminal flag (D.5), e.g. when the user opens the chat. */
async clearUnreadTerminal(agentRef: string, chatId: string): Promise<void> {
return this.serializeIndex(agentRef, async () => {
diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.ts
index 2ec67f4ce..15a96f197 100644
--- a/desktop-app/src/chatStoreBinding.ts
+++ b/desktop-app/src/chatStoreBinding.ts
@@ -17,47 +17,61 @@ function currentBaseDir(): string {
let activeChatStore: ChatStore | null = null
let activeUserId: string | null = null
-let bindInFlight: { userId: string; promise: Promise<void> } | null = null
+let activeEnvKey: string | null = null
+let bindInFlight: { key: string; promise: Promise<void> } | null = null
+
+/** Marker file (per base dir) that records the pre-`envKey` legacy wipe ran. */
+const PRE_ENV_MIGRATION_MARKER = '.env-scoped'
/**
- * Reject a `userId` that isn't a single safe path segment. It roots both the
- * store and the destructive bootstrap wipe (`fs.rm` recursive), and it comes
- * from the auth server's `me.id` — an empty/`.`/`..`/separator-bearing value
- * could make the wipe escape the user's subdir or target the whole base dir.
+ * Reject a segment that isn't a single safe path component. It roots both the
+ * store and the destructive bootstrap wipe (`fs.rm` recursive): `userId` comes
+ * from the auth server's `me.id` and `envKey` from the runtime config — an
+ * empty/`.`/`..`/separator-bearing value could make the wipe escape its subdir
+ * or target the whole base dir.
*/
-function assertSafeUserId(userId: string): void {
- if (!userId || userId === '.' || userId === '..' || /[/\\\0]/.test(userId)) {
- throw new Error('Invalid userId: unsafe path segment')
+function assertSafeSegment(label: string, value: string): void {
+ if (!value || value === '.' || value === '..' || /[/\\\0]/.test(value)) {
+ throw new Error(`Invalid ${label}: unsafe path segment`)
}
}
/**
- * Bind the chat store to a user's directory, wiping any legacy (pre-v2) cache
- * first. The desktop is a cache of the server (post-Hermes spec §7.1): a v1
- * directory has per-message data without `task_id` and a different reconcile
- * model, so the first launch after deploy drops it wholesale and lets the
- * server re-hydrate. Safe because the server is the source of truth.
+ * Bind the chat store to a `(envKey, user)` directory (spec §5.2). The path is
+ * namespaced by environment — `<base>/<envKey>/<userId>/…` — so switching
+ * clusters never surfaces or reconciles another environment's chats (the
+ * cross-cluster 404-eviction bug). Wipes any legacy (pre-v2) per-agent cache
+ * first; the desktop is a cache of the server (spec §3.5, §7.1), so a stale
+ * directory is dropped and re-hydrated from the source of truth.
*/
-export async function bindChatStoreForUser(userId: string): Promise<void> {
- assertSafeUserId(userId)
- // Re-binding the same user is a no-op. Team switches and access-catalog
+export async function bindChatStoreForUser(userId: string, envKey: string): Promise<void> {
+ assertSafeSegment('userId', userId)
+ assertSafeSegment('envKey', envKey)
+ // Re-binding the same (env, user) is a no-op. Team switches and access-catalog
// refreshes re-call this with an unchanged `me.id`; tearing the store down
// just to rebuild it opens a window where every concurrent chat IPC fails
// with "Not authenticated" (seen as an empty "Latest sessions" at boot).
- if (activeChatStore && activeUserId === userId) return
- if (bindInFlight?.userId === userId) return bindInFlight.promise
+ if (activeChatStore && activeUserId === userId && activeEnvKey === envKey) return
+ const bindKey = `${envKey}::${userId}`
+ if (bindInFlight?.key === bindKey) return bindInFlight.promise
const promise = (async () => {
// bind is async (it awaits a directory wipe); until it completes,
// requireChatStore must not keep serving the previous user's store.
activeChatStore = null
activeUserId = null
- const userDir = join(currentBaseDir(), userId)
+ activeEnvKey = null
+ const baseDir = currentBaseDir()
+ // One-shot: drop the pre-`envKey` cache tree (no env level) before rooting
+ // the env-scoped store. Safe to discard — the server rebuilds it (spec §5.5).
+ await maybeWipePreEnvLegacyCache(baseDir)
+ const userDir = join(baseDir, envKey, userId)
await maybeWipeLegacyCache(userDir)
activeChatStore = new ChatStore(userDir)
activeUserId = userId
+ activeEnvKey = envKey
})()
- bindInFlight = { userId, promise }
+ bindInFlight = { key: bindKey, promise }
try {
await promise
} finally {
@@ -65,6 +79,82 @@ export async function bindChatStoreForUser(userId: string): Promise<void> {
}
}
+/**
+ * One-shot wipe of the pre-`envKey` cache layout (spec §5.5, D3). Before this
+ * feature the tree was `<base>/<userId>/<agentRef>/index.json`; it is now
+ * `<base>/<envKey>/<userId>/<agentRef>/index.json`. Legacy user dirs are
+ * indistinguishable from env dirs by name, but not by SHAPE: a legacy `<userId>`
+ * dir has `index.json` at depth 2 (`<userId>/<agentRef>/index.json`), whereas an
+ * env dir only ever has it at depth 3 (`<envKey>/<userId>/<agentRef>/index.json`).
+ * So any top-level dir with an `index.json` in one of its children is legacy and
+ * is dropped.
+ * Guarded by a marker file so it runs exactly once (the first launch after the
+ * update, before any env dir exists); it never touches env-scoped subtrees.
+ */
+async function maybeWipePreEnvLegacyCache(baseDir: string): Promise<void> {
+ const markerPath = join(baseDir, PRE_ENV_MIGRATION_MARKER)
+ try {
+ await fs.access(markerPath)
+ return // already migrated
+ } catch {
+ // marker absent → run the one-shot below
+ }
+
+ let entries
+ try {
+ entries = await fs.readdir(baseDir, { withFileTypes: true })
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
+ // Fresh install — nothing legacy to wipe. Create the base + marker so the
+ // scan never runs again.
+ await fs.mkdir(baseDir, { recursive: true })
+ await writeMigrationMarker(markerPath)
+ return
+ }
+ throw err
+ }
+
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue
+ const topDir = join(baseDir, entry.name)
+ if (await looksLikeLegacyUserDir(topDir)) {
+ console.warn(`[chatStore] Wiping pre-envKey legacy cache dir "${entry.name}"`)
+ await fs.rm(topDir, { recursive: true, force: true })
+ }
+ }
+
+ await writeMigrationMarker(markerPath)
+}
+
+/** A top-level dir is a legacy user dir iff any child holds `index.json`. */
+async function looksLikeLegacyUserDir(topDir: string): Promise<boolean> {
+ let children
+ try {
+ children = await fs.readdir(topDir, { withFileTypes: true })
+ } catch {
+ return false
+ }
+ for (const child of children) {
+ if (!child.isDirectory()) continue
+ try {
+ await fs.access(join(topDir, child.name, 'index.json'))
+ return true
+ } catch {
+ // no index.json under this child — keep scanning siblings
+ }
+ }
+ return false
+}
+
+async function writeMigrationMarker(markerPath: string): Promise<void> {
+ try {
+ await fs.writeFile(markerPath, new Date().toISOString(), { mode: 0o600 })
+ } catch (err) {
+ // Non-fatal: worst case the one-shot scan reruns next launch (idempotent).
+ console.warn('[chatStore] Failed to persist pre-envKey migration marker:', err)
+ }
+}
+
/**
* Scan a user's per-agent chat directories and remove any whose `index.json`
* is missing or not at the current schema version. Idempotent and best-effort
@@ -104,6 +194,7 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {
export function unbindChatStore(): void {
activeChatStore = null
activeUserId = null
+ activeEnvKey = null
}
export function requireChatStore(): ChatStore {
diff --git a/desktop-app/src/config.ts b/desktop-app/src/config.ts
index a52a67266..e749daf3e 100644
--- a/desktop-app/src/config.ts
+++ b/desktop-app/src/config.ts
@@ -1,4 +1,5 @@
import { app } from 'electron'
+import { createHash } from 'node:crypto'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import os from 'node:os'
@@ -647,6 +648,42 @@ export async function saveDesktopRuntimeConfig(next: DesktopRuntimeConfig): Prom
await persistProfilesIndex(storedProfiles, activeRuntimeOptionId)
}
+/**
+ * Derive the environment namespacing key from a runtime config's external-rest-api
+ * base URL (spec §5.1, D1). Semantically "one environment = one external-rest-api
+ * origin": `new URL(url).origin` includes scheme + host + port, so
+ * `https://api.dev…` and `https://api.prod…` (or `:8091` vs `:8092`) key apart
+ * automatically, and `rpcProxyBaseUrl` is deliberately NOT mixed in.
+ *
+ * The raw origin is not filesystem/keychain-safe (it carries `://`, `:`), so we
+ * emit a stable, collision-resistant slug: a lowercase `scheme_host_port`
+ * fragment for human debuggability, suffixed with a 12-hex sha256 of the origin
+ * so distinct origins can never collide even when the slug is truncated. Purely a
+ * function of the origin ⇒ deterministic and stable across restarts.
+ */
+export function resolveEnvKey(externalRestApiBaseUrl: string): string {
+ const raw = String(externalRestApiBaseUrl || '').trim()
+ let origin: string
+ try {
+ origin = new URL(raw).origin
+ } catch {
+ origin = raw || 'unknown'
+ }
+ const slug = origin
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_')
+ .replace(/^_+|_+$/g, '')
+ .slice(0, 48)
+ const hash = createHash('sha256').update(origin).digest('hex').slice(0, 12)
+ return `${slug || 'env'}-${hash}`
+}
+
+/** Env key for the CURRENTLY active runtime config (main-process surfaces). */
+export function getActiveEnvKey(): string {
+ hydrateDesktopRuntimeConfig()
+ return resolveEnvKey(config.externalRestApiBaseUrl)
+}
+
export function getDesktopRuntimeConfigState(): DesktopRuntimeConfigState {
hydrateDesktopRuntimeConfig()
const current = currentRuntimeConfig()
@@ -666,6 +703,7 @@ export function getDesktopRuntimeConfigState(): DesktopRuntimeConfigState {
isLocalhost,
selectorVisible,
activeOptionId,
+ envKey: resolveEnvKey(current.externalRestApiBaseUrl),
storagePath: process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim() || runtimeConfigDirectoryPath(),
options,
}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 9c3e6cd92..ee9ac25e2 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -1079,6 +1079,31 @@ export function registerIpcHandlers(service: AppService): void {
}
)
+ ipcMain.handle(
+ 'chat:reconcileSessions',
+ async (
+ event,
+ payload: {
+ agentRef: string
+ sessions?: Array<{ chatId?: unknown; lastActivityAt?: unknown }>
+ }
+ ) => {
+ assertTrustedSender(event)
+ const agentRef = sanitizeString(payload?.agentRef)
+ if (!agentRef) throw new Error('agentRef is required')
+ const sessions = Array.isArray(payload?.sessions)
+ ? payload.sessions
+ .map(session => ({
+ chatId: sanitizeString(session?.chatId),
+ lastActivityAt:
+ typeof session?.lastActivityAt === 'string' ? session.lastActivityAt : undefined,
+ }))
+ .filter(session => Boolean(session.chatId))
+ : []
+ return requireChatStore().upsertServerSessions(agentRef, sessions)
+ }
+ )
+
ipcMain.handle('chat:getIndex', async (event, payload: { agentRef: string }) => {
assertTrustedSender(event)
const agentRef = sanitizeString(payload?.agentRef)
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index 35cb94dab..332e712e8 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -1,8 +1,9 @@
-import { BrowserWindow, app, ipcMain, powerMonitor } from 'electron'
+import { BrowserWindow, app, ipcMain, nativeTheme, powerMonitor } from 'electron'
import path from 'node:path'
import { AppService } from './appService.js'
import { config } from './config.js'
import { assertTrustedSender, registerIpcHandlers } from './ipc.js'
+import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'
const EVENFIRE_APP_NAME = 'Evenfire'
const EVENFIRE_APP_ID = 'ai.evenfire.desktop'
@@ -19,6 +20,26 @@ let mainWindow: BrowserWindow | null = null
const appService = new AppService()
const pendingEvenfireUrls: string[] = []
+function systemIconAssetsDirectory(): string {
+ return app.isPackaged ? process.resourcesPath : path.join(__dirname, '../assets')
+}
+
+function wireAdaptiveSystemIcon(): void {
+ installAdaptiveSystemIcon({
+ assetsDirectory: systemIconAssetsDirectory(),
+ getAllWindows: () => BrowserWindow.getAllWindows(),
+ onThemeUpdated: listener => {
+ nativeTheme.on('updated', listener)
+ },
+ onWindowCreated: listener => {
+ app.on('browser-window-created', (_event, window) => listener(window))
+ },
+ platform: process.platform,
+ setDockIcon: app.dock ? icon => app.dock?.setIcon(icon) : undefined,
+ shouldUseDarkColors: () => nativeTheme.shouldUseDarkColors,
+ })
+}
+
/** True when the window is actually on-screen (not hidden/minimized). Drives the
* D.5b T4 nudge copy — `document.visibilityState` doesn't detect minimize on macOS. */
function isWindowVisible(win: BrowserWindow | null): boolean {
@@ -213,7 +234,7 @@ async function createWindow(): Promise<void> {
config.appName === EVENFIRE_APP_NAME
? EVENFIRE_APP_NAME
: `${EVENFIRE_APP_NAME} — ${config.appName}`,
- icon: path.join(__dirname, '../assets/icon.png'),
+ icon: resolveSystemIconPath(systemIconAssetsDirectory(), nativeTheme.shouldUseDarkColors),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
@@ -255,6 +276,7 @@ async function createWindow(): Promise<void> {
if (gotSingleInstanceLock) {
app.whenReady().then(async () => {
+ wireAdaptiveSystemIcon()
registerIpcHandlers(appService)
for (const arg of process.argv) {
if (arg.startsWith(`${DESKTOP_SETUP_PROTOCOL}://`)) {
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index bcce054d9..ddee686a6 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -391,6 +391,10 @@ const clerum = Object.freeze({
setLastActive: (agentRef: string, chatId: string) =>
ipcRenderer.invoke('chat:setLastActive', { agentRef, chatId }),
getIndex: (agentRef: string) => ipcRenderer.invoke('chat:getIndex', { agentRef }),
+ reconcileServerSessions: (
+ agentRef: string,
+ sessions: Array<{ chatId: string; lastActivityAt?: string }>
+ ) => ipcRenderer.invoke('chat:reconcileSessions', { agentRef, sessions }),
dismissOnboarding: (agentRef: string) =>
ipcRenderer.invoke('chat:dismissOnboarding', { agentRef }),
},
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index f7a626655..b5ce754a8 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -503,6 +503,10 @@ declare global {
getLastActive: (agentRef: string) => Promise<string | null>
setLastActive: (agentRef: string, chatId: string) => Promise<void>
getIndex: (agentRef: string) => Promise<ChatIndex>
+ reconcileServerSessions: (
+ agentRef: string,
+ sessions: Array<{ chatId: string; lastActivityAt?: string }>
+ ) => Promise<number>
dismissOnboarding: (agentRef: string) => Promise<void>
markUnreadTerminal: (agentRef: string, chatId: string) => Promise<void>
clearUnreadTerminal: (agentRef: string, chatId: string) => Promise<void>
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index 562a2bec3..d6cd80416 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -1,5 +1,6 @@
import { BrowserWindow, WebContentsView, session } from 'electron'
import path from 'node:path'
+import { getActiveEnvKey } from './config.js'
import { touchSandboxUiPartition } from './sandboxUiPartitionGc.js'
import {
applySandboxUiNavigationPolicies,
@@ -112,12 +113,14 @@ export function getActiveSandboxUi(): {
}
}
-export function partitionFor(recipeNs: string, recipeName: string): string {
- // Per-recipe partition — Chromium isolates storage (cookies, IndexedDB,
- // localStorage, service workers) by partition. The launch-time GC pass
- // walks all `persist:sandbox-ui-*` partitions and wipes the ones the user
- // no longer has ACL for.
- return `persist:sandbox-ui-${recipeNs}-${recipeName}`
+export function partitionFor(envKey: string, recipeNs: string, recipeName: string): string {
+ // Per-(environment, recipe) partition — Chromium isolates storage (cookies,
+ // IndexedDB, localStorage, service workers) by partition. `envKey` (spec §5.2)
+ // scopes it so the same recipe ns/name in two clusters never shares KasmVNC
+ // cookies/storage. The launch-time GC pass walks the current env's
+ // `persist:sandbox-ui-${envKey}-*` partitions and wipes the ones the user no
+ // longer has ACL for; other environments' partitions are left untouched.
+ return `persist:sandbox-ui-${envKey}-${recipeNs}-${recipeName}`
}
/**
@@ -254,7 +257,7 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
// within the ACL window.
await teardownActive('replaced')
- const partition = partitionFor(recipeNs, recipeName)
+ const partition = partitionFor(getActiveEnvKey(), recipeNs, recipeName)
const proxyOriginUrl = new URL(rpcProxyUrl).toString().replace(/\/+$/, '')
const allowedNavigationPrefix =
`${proxyOriginUrl}/api/v1/sandbox-ui/` +
diff --git a/desktop-app/src/sandboxUiPartitionGc.ts b/desktop-app/src/sandboxUiPartitionGc.ts
index 3059a33a0..c291a4e3a 100644
--- a/desktop-app/src/sandboxUiPartitionGc.ts
+++ b/desktop-app/src/sandboxUiPartitionGc.ts
@@ -9,12 +9,16 @@ import path from 'node:path'
* mounted) so it can safely rm partition data without racing the
* Electron Session that owns it.
*
- * 1. Enumerate `userData/Partitions/sandbox-ui-*` directories on disk.
+ * 1. Enumerate `userData/Partitions/sandbox-ui-${envKey}-*` directories on
+ * disk (the ACTIVE environment only — spec §5.2).
* 2. Fetch the user's current sandbox-ui ACL via `GET /apps`.
- * 3. Wipe every on-disk partition whose recipe isn't in the ACL.
+ * 3. Wipe every on-disk partition (in this env) whose recipe isn't in the ACL.
* 4. If remaining ACL-aligned partitions sum to > 1 GiB, evict the
* oldest by `lastAccessAt` until total is back under cap.
*
+ * The size cap is applied PER ENVIRONMENT since GC is env-scoped; total
+ * sandbox-ui storage across N environments can reach up to N × the cap.
+ *
* `lastAccessAt` is tracked per `appRef` in a JSON file under userData
* and updated by `touchSandboxUiPartition` whenever the driver mounts
* a view.
@@ -24,6 +28,24 @@ export const SANDBOX_UI_PARTITION_PREFIX = 'sandbox-ui-'
export const SANDBOX_UI_MAX_TOTAL_BYTES = 1024 * 1024 * 1024
export const SANDBOX_UI_STATE_FILENAME = 'sandbox-ui-partition-state.json'
+/**
+ * Marker file (under userData) recording that the one-shot pre-`envKey`
+ * partition wipe ran. Mirrors ChatStore's `.env-scoped` marker
+ * (`chatStoreBinding.ts`) so the destructive scan happens exactly once.
+ */
+export const SANDBOX_UI_PRE_ENV_MIGRATION_MARKER = '.sandbox-ui-env-scoped'
+
+/**
+ * Leading segment of an env-scoped partition, right after the `sandbox-ui-`
+ * prefix. An env partition is `sandbox-ui-<envKey>-<ns>-<name>` where
+ * `envKey = <slug>-<12 hex>` (see `resolveEnvKey` in `config.ts`: slug is
+ * `[a-z0-9_]+`, hash is 12 hex). So a valid env partition's remainder starts
+ * with `<slug>-<12hex>-`; a pre-env partition (`sandbox-ui-<ns>-<name>`) does
+ * not. The trailing `-` matters: it rules out a legacy `<name>` that is itself
+ * exactly 12 hex from being read as an envKey.
+ */
+const ENV_KEY_LEADING_SEGMENT_RE = /^[a-z0-9_]+-[0-9a-f]{12}-/
+
export type SandboxUiPartitionState = {
lastAccessAt: Record<string, number>
}
@@ -32,10 +54,15 @@ export function emptySandboxUiPartitionState(): SandboxUiPartitionState {
return { lastAccessAt: {} }
}
-export function partitionDirNameFor(recipeNs: string, recipeName: string): string {
- return `${SANDBOX_UI_PARTITION_PREFIX}${recipeNs}-${recipeName}`
+export function partitionDirNameFor(envKey: string, recipeNs: string, recipeName: string): string {
+ return `${SANDBOX_UI_PARTITION_PREFIX}${envKey}-${recipeNs}-${recipeName}`
}
+/**
+ * True when `dirName` is a sandbox-ui partition of any vintage (env-scoped or
+ * the pre-env layout). The base predicate — reused by
+ * `isPreEnvSandboxUiPartitionDirName` to gate the one-shot legacy wipe.
+ */
export function isSandboxUiPartitionDirName(dirName: string): boolean {
return (
dirName.startsWith(SANDBOX_UI_PARTITION_PREFIX) &&
@@ -43,6 +70,31 @@ export function isSandboxUiPartitionDirName(dirName: string): boolean {
)
}
+/**
+ * True when `dirName` is a sandbox-ui partition created BEFORE env-scoping
+ * (`sandbox-ui-<ns>-<name>`, no `<envKey>-` segment). These no longer match any
+ * environment's GC scan (`isSandboxUiPartitionDirNameForEnv`, §5.2) — new mounts
+ * use `sandbox-ui-<envKey>-…` — so their now-dead KasmVNC cookies would leak on
+ * disk forever and never count against the LRU cap. Detected by the ABSENCE of a
+ * valid leading envKey segment. Best-effort heuristic (same class as ChatStore's
+ * shape check): a legacy `<name>` shaped exactly like `<12hex>-…` is left alone,
+ * leaking at most that one dir.
+ */
+export function isPreEnvSandboxUiPartitionDirName(dirName: string): boolean {
+ if (!isSandboxUiPartitionDirName(dirName)) return false
+ const rest = dirName.slice(SANDBOX_UI_PARTITION_PREFIX.length)
+ return !ENV_KEY_LEADING_SEGMENT_RE.test(rest)
+}
+
+/**
+ * True when `dirName` is a sandbox-ui partition for `envKey` (spec §5.2). GC is
+ * scoped to the CURRENT environment: other environments' partitions must be
+ * neither wiped nor counted against this env's LRU cap.
+ */
+export function isSandboxUiPartitionDirNameForEnv(dirName: string, envKey: string): boolean {
+ return dirName.startsWith(`${SANDBOX_UI_PARTITION_PREFIX}${envKey}-`)
+}
+
export type GcPlan = {
/** Dirs to wipe because their recipe isn't in the ACL. */
wipe: string[]
@@ -194,10 +246,73 @@ async function clearAndRemovePartition(dirName: string, partitionsRoot: string):
}
}
+// ─── One-shot pre-envKey legacy wipe ─────────────────────────────
+
+async function writePreEnvMigrationMarker(markerPath: string): Promise<void> {
+ try {
+ await fs.mkdir(path.dirname(markerPath), { recursive: true })
+ await fs.writeFile(markerPath, new Date().toISOString(), { mode: 0o600 })
+ } catch (err) {
+ // Non-fatal: worst case the one-shot scan reruns next launch (idempotent).
+ console.warn('[SandboxUI] Failed to persist pre-envKey partition marker:', err)
+ }
+}
+
+/**
+ * One-shot wipe of the pre-`envKey` partition layout (spec §5.2). Before this
+ * feature partitions were `sandbox-ui-<ns>-<name>`; they are now
+ * `sandbox-ui-<envKey>-<ns>-<name>`. The env-scoped GC below only matches the
+ * new naming, so old partitions would otherwise leak forever. This scans the
+ * partitions root ONCE (marker-guarded, like ChatStore's `.env-scoped` wipe),
+ * env-independently, and removes every dir that is a sandbox-ui partition
+ * WITHOUT a valid envKey segment. Returns the wiped dir names (for logging).
+ */
+export async function maybeWipePreEnvSandboxUiPartitions(userDataDir: string): Promise<string[]> {
+ const partitionsRoot = path.join(userDataDir, 'Partitions')
+ const markerPath = path.join(userDataDir, SANDBOX_UI_PRE_ENV_MIGRATION_MARKER)
+
+ try {
+ await fs.access(markerPath)
+ return [] // already migrated
+ } catch {
+ // marker absent → run the one-shot below
+ }
+
+ let entries: import('node:fs').Dirent[]
+ try {
+ entries = await fs.readdir(partitionsRoot, { withFileTypes: true })
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
+ // No Partitions dir yet (fresh install / nothing ever mounted). Nothing
+ // legacy to wipe and nowhere stable to drop the marker; the next launch
+ // reruns this cheaply once the dir exists.
+ return []
+ }
+ throw err
+ }
+
+ const wiped: string[] = []
+ for (const entry of entries) {
+ // Names come from readdir of partitionsRoot ⇒ single path components (no
+ // separators), so `clearAndRemovePartition`'s join can't escape the root.
+ if (!entry.isDirectory()) continue
+ if (!isPreEnvSandboxUiPartitionDirName(entry.name)) continue
+ console.warn(`[SandboxUI] Wiping pre-envKey legacy partition "${entry.name}"`)
+ await clearAndRemovePartition(entry.name, partitionsRoot)
+ wiped.push(entry.name)
+ }
+
+ await writePreEnvMigrationMarker(markerPath)
+ return wiped
+}
+
// ─── Orchestrator ────────────────────────────────────────────────
export type RunSandboxUiPartitionGcArgs = {
userDataDir: string
+ /** Namespacing key of the ACTIVE environment (spec §5.2). GC only touches
+ * this env's `sandbox-ui-${envKey}-*` partitions. */
+ envKey: string
/** Returns the user's current sandbox-ui ACL. The orchestrator only
* needs `appRef`. Failure here aborts GC for this launch (better to
* keep stale data than to wipe a partition the user still has). */
@@ -218,11 +333,19 @@ export async function runSandboxUiPartitionGc(
const stateFilePath = path.join(args.userDataDir, SANDBOX_UI_STATE_FILENAME)
const maxTotalBytes = args.maxTotalBytes ?? SANDBOX_UI_MAX_TOTAL_BYTES
+ // One-shot, env-independent cleanup of pre-`envKey` partitions. Runs before
+ // the env-scoped scan below (which by design only matches this env's
+ // `sandbox-ui-${envKey}-*` dirs) so legacy partitions can't leak forever.
+ await maybeWipePreEnvSandboxUiPartitions(args.userDataDir)
+
let diskDirs: string[]
try {
const entries = await fs.readdir(partitionsRoot, { withFileTypes: true })
+ // Scope to the ACTIVE env only — other environments' partitions are left
+ // intact (they GC when their env is active). Prevents an env switch from
+ // wiping another cluster's KasmVNC storage (spec §5.2).
diskDirs = entries
- .filter(e => e.isDirectory() && isSandboxUiPartitionDirName(e.name))
+ .filter(e => e.isDirectory() && isSandboxUiPartitionDirNameForEnv(e.name, args.envKey))
.map(e => e.name)
} catch {
// userData/Partitions doesn't exist yet — nothing to GC.
@@ -239,7 +362,9 @@ export async function runSandboxUiPartitionGc(
aclEntries = []
for (const a of result.apps) {
const [ns, name] = a.appRef.split('/', 2)
- if (ns && name) aclEntries.push({ appRef: a.appRef, dirName: partitionDirNameFor(ns, name) })
+ if (ns && name) {
+ aclEntries.push({ appRef: a.appRef, dirName: partitionDirNameFor(args.envKey, ns, name) })
+ }
}
} catch (err) {
console.warn('[SandboxUI] partition GC: failed to fetch ACL, skipping:', err)
@@ -274,15 +399,23 @@ export async function runSandboxUiPartitionGc(
delete state.lastAccessAt[appRef]
}
- // Drop lastAccessAt entries for appRefs that no longer have an ACL
- // mapping — we'd never use them again.
+ // Drop lastAccessAt entries for appRefs that lost ACL access AND have no
+ // surviving on-disk partition in THIS env. Scoped to the active env so an
+ // env switch doesn't discard another cluster's LRU timestamps (self-healing
+ // metadata regardless — the next mount re-touches it).
+ const envDiskDirSet = new Set(diskDirs)
for (const appRef of Object.keys(state.lastAccessAt)) {
const [ns, name] = appRef.split('/', 2)
if (!ns || !name) {
delete state.lastAccessAt[appRef]
continue
}
- if (!aclDirSet.has(partitionDirNameFor(ns, name))) {
+ const dirName = partitionDirNameFor(args.envKey, ns, name)
+ // Prune only timestamps this pass just invalidated: the recipe had a
+ // current-env partition on disk that is NOT in the current ACL (so it was
+ // wiped above). An appRef with no current-env dir belongs to another env —
+ // leave its timestamp for that env's own GC pass.
+ if (envDiskDirSet.has(dirName) && !aclDirSet.has(dirName)) {
delete state.lastAccessAt[appRef]
}
}
diff --git a/desktop-app/src/systemIcon.test.ts b/desktop-app/src/systemIcon.test.ts
new file mode 100644
index 000000000..eead65ea8
--- /dev/null
+++ b/desktop-app/src/systemIcon.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it, vi } from 'vitest'
+import path from 'node:path'
+import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'
+
+describe('systemIcon', () => {
+ it('resolves the matching light and dark assets', () => {
+ expect(path.basename(resolveSystemIconPath('/icons', false))).toBe('icon-light.png')
+ expect(path.basename(resolveSystemIconPath('/icons', true))).toBe('icon-dark.png')
+ })
+
+ it('updates existing and newly created Windows and Linux windows', () => {
+ let darkMode = false
+ let themeUpdated: (() => void) | undefined
+ let windowCreated:
+ | ((window: { isDestroyed(): boolean; setIcon(icon: string): void }) => void)
+ | undefined
+ const firstWindow = { isDestroyed: () => false, setIcon: vi.fn() }
+ const secondWindow = { isDestroyed: () => false, setIcon: vi.fn() }
+
+ installAdaptiveSystemIcon({
+ assetsDirectory: '/icons',
+ getAllWindows: () => [firstWindow],
+ onThemeUpdated: listener => {
+ themeUpdated = listener
+ },
+ onWindowCreated: listener => {
+ windowCreated = listener
+ },
+ platform: 'win32',
+ shouldUseDarkColors: () => darkMode,
+ })
+
+ expect(path.basename(firstWindow.setIcon.mock.calls[0]?.[0] ?? '')).toBe('icon-light.png')
+
+ darkMode = true
+ themeUpdated?.()
+ windowCreated?.(secondWindow)
+
+ expect(path.basename(firstWindow.setIcon.mock.calls[1]?.[0] ?? '')).toBe('icon-dark.png')
+ expect(path.basename(secondWindow.setIcon.mock.calls[0]?.[0] ?? '')).toBe('icon-dark.png')
+ })
+
+ it('updates the macOS Dock without applying unsupported window icons', () => {
+ const setDockIcon = vi.fn()
+ const setWindowIcon = vi.fn()
+
+ installAdaptiveSystemIcon({
+ assetsDirectory: '/icons',
+ getAllWindows: () => [{ isDestroyed: () => false, setIcon: setWindowIcon }],
+ onThemeUpdated: () => {},
+ onWindowCreated: () => {},
+ platform: 'darwin',
+ setDockIcon,
+ shouldUseDarkColors: () => true,
+ })
+
+ expect(path.basename(setDockIcon.mock.calls[0]?.[0] ?? '')).toBe('icon-dark.png')
+ expect(setWindowIcon).not.toHaveBeenCalled()
+ })
+
+ it('does not update destroyed windows', () => {
+ const setIcon = vi.fn()
+
+ installAdaptiveSystemIcon({
+ assetsDirectory: '/icons',
+ getAllWindows: () => [{ isDestroyed: () => true, setIcon }],
+ onThemeUpdated: () => {},
+ onWindowCreated: () => {},
+ platform: 'linux',
+ shouldUseDarkColors: () => false,
+ })
+
+ expect(setIcon).not.toHaveBeenCalled()
+ })
+})
diff --git a/desktop-app/src/systemIcon.ts b/desktop-app/src/systemIcon.ts
new file mode 100644
index 000000000..eaed9f3ee
--- /dev/null
+++ b/desktop-app/src/systemIcon.ts
@@ -0,0 +1,52 @@
+import path from 'node:path'
+
+export type SystemIconWindow = {
+ isDestroyed(): boolean
+ setIcon(icon: string): void
+}
+
+export type AdaptiveSystemIconOptions = {
+ assetsDirectory: string
+ getAllWindows(): SystemIconWindow[]
+ onThemeUpdated(listener: () => void): void
+ onWindowCreated(listener: (window: SystemIconWindow) => void): void
+ platform: NodeJS.Platform
+ setDockIcon?(icon: string): void
+ shouldUseDarkColors(): boolean
+}
+
+export function resolveSystemIconPath(assetsDirectory: string, darkMode: boolean): string {
+ return path.join(assetsDirectory, darkMode ? 'icon-dark.png' : 'icon-light.png')
+}
+
+export function installAdaptiveSystemIcon(options: AdaptiveSystemIconOptions): void {
+ const supportsWindowIcons = options.platform === 'win32' || options.platform === 'linux'
+ const supportsDockIcon = options.platform === 'darwin' && Boolean(options.setDockIcon)
+
+ const iconPath = () =>
+ resolveSystemIconPath(options.assetsDirectory, options.shouldUseDarkColors())
+
+ const applyToWindow = (window: SystemIconWindow) => {
+ if (supportsWindowIcons && !window.isDestroyed()) {
+ window.setIcon(iconPath())
+ }
+ }
+
+ const apply = () => {
+ if (supportsDockIcon) {
+ options.setDockIcon?.(iconPath())
+ return
+ }
+ if (supportsWindowIcons) {
+ options.getAllWindows().forEach(applyToWindow)
+ }
+ }
+
+ if (supportsWindowIcons) {
+ options.onWindowCreated(applyToWindow)
+ }
+ if (supportsWindowIcons || supportsDockIcon) {
+ options.onThemeUpdated(apply)
+ apply()
+ }
+}
diff --git a/desktop-app/src/tokenStore.ts b/desktop-app/src/tokenStore.ts
index a522a848c..d78199899 100644
--- a/desktop-app/src/tokenStore.ts
+++ b/desktop-app/src/tokenStore.ts
@@ -4,7 +4,39 @@ import os from 'node:os'
import path from 'node:path'
const SERVICE = 'Evenfire'
-const ACCOUNT = 'session-token'
+/**
+ * Legacy single global slot (pre per-environment scoping). Read once for a
+ * best-effort migration into the active environment's slot, then deleted.
+ */
+const LEGACY_ACCOUNT = 'session-token'
+
+/**
+ * Exact shape emitted by `resolveEnvKey` (config.ts): a `[a-z0-9_]` slug, a
+ * `-` separator, and a 12-hex sha256 suffix. Every call site feeds `envKey`
+ * straight into keychain account names and on-disk file names, so validate the
+ * shape before interpolating — defense in depth mirroring the
+ * `assertSafeSegment` guard in chatStore/chatStoreBinding. Today all callers
+ * pass sanitized `getActiveEnvKey()` output, so a mismatch signals a bug (or a
+ * tampered value), never a normal input.
+ */
+const ENV_KEY_SHAPE = /^[a-z0-9_]+-[0-9a-f]{12}$/
+
+function assertEnvKey(envKey: string): void {
+ if (!ENV_KEY_SHAPE.test(envKey)) {
+ throw new Error('Invalid envKey: unexpected shape')
+ }
+}
+
+/**
+ * Per-environment keychain account (spec §5.2). Each environment stores/reads
+ * its OWN session token, so switching clusters never leaks env A's token into
+ * env B. `envKey` is the stable, filesystem/keychain-safe key from
+ * `resolveEnvKey`.
+ */
+function accountFor(envKey: string): string {
+ const key = String(envKey || '').trim()
+ return key ? `${LEGACY_ACCOUNT}::${key}` : LEGACY_ACCOUNT
+}
type KeytarModule = {
getPassword: (service: string, account: string) => Promise<string | null>
@@ -44,20 +76,47 @@ async function resolvedStorageBase(): Promise<string> {
return base
}
-async function encryptedFilePath(): Promise<string> {
+async function encryptedFilePath(envKey: string): Promise<string> {
+ const key = String(envKey || '').trim()
+ const name = key ? `session-token-${key}.enc` : 'session-token.enc'
+ return path.join(await resolvedStorageBase(), name)
+}
+
+/** Per-env plain-text fallback (only when neither keytar nor safeStorage exist). */
+async function plainFilePath(envKey: string): Promise<string> {
+ const key = String(envKey || '').trim()
+ const name = key ? `session-token-${key}.json` : 'session-token.json'
+ return path.join(await resolvedStorageBase(), name)
+}
+
+/** Legacy pre-per-env safeStorage file (global slot). */
+async function legacyEncryptedFilePath(): Promise<string> {
return path.join(await resolvedStorageBase(), 'session-token.enc')
}
+/** Legacy plain-text fallback file (global slot). */
async function legacyFilePath(): Promise<string> {
return path.join(await resolvedStorageBase(), 'session-token.json')
}
export class TokenStore {
- async getSessionToken(): Promise<string | null> {
+ /**
+ * Read the session token for `envKey`. Falls back keytar → safeStorage file,
+ * then does a one-time best-effort migration of the pre-per-env GLOBAL slot
+ * into this environment's slot. Migrating the legacy token is safe: it was
+ * issued for whatever environment was last active (which is the environment
+ * being restored at startup), and an env mismatch simply fails `getMe` and
+ * drops the user back to login — never a cross-env leak, since after the
+ * migration the legacy slot is deleted.
+ */
+ async getSessionToken(envKey: string): Promise<string | null> {
+ assertEnvKey(envKey)
+ const account = accountFor(envKey)
const keytar = await loadKeytar()
if (keytar) {
try {
- return await keytar.getPassword(SERVICE, ACCOUNT)
+ const stored = await keytar.getPassword(SERVICE, account)
+ if (stored) return stored
} catch {
// Packaged builds can fail keychain access depending on host policies.
// Fall back to the local encrypted store so auth flow can continue.
@@ -66,7 +125,7 @@ export class TokenStore {
if (app?.isReady() && safeStorage.isEncryptionAvailable()) {
try {
- const file = await encryptedFilePath()
+ const file = await encryptedFilePath(envKey)
const encrypted = await fs.readFile(file)
return safeStorage.decryptString(encrypted)
} catch {
@@ -74,20 +133,70 @@ export class TokenStore {
}
}
- // Legacy plain-text fallback — migrate to a better store when one is available.
+ // Pure-fallback platforms (no keytar AND no safeStorage) persist to the
+ // per-env plain-text file — read it back symmetrically before falling
+ // through to the one-time legacy-global migration.
+ try {
+ const file = await plainFilePath(envKey)
+ const raw = await fs.readFile(file, 'utf8')
+ const data = JSON.parse(raw) as { token?: unknown }
+ if (typeof data.token === 'string' && data.token) return data.token
+ } catch {
+ // No per-env plain-text token — fall through to legacy migration.
+ }
+
+ return this.migrateLegacyGlobalToken(envKey, keytar)
+ }
+
+ /**
+ * One-time migration of the legacy global slot (keytar `session-token`, then
+ * the plain-text/enc files) into this environment's slot. Returns the token
+ * if any legacy store held one, else null. The legacy source is deleted once
+ * copied so it can never be read into a second environment.
+ */
+ private async migrateLegacyGlobalToken(
+ envKey: string,
+ keytar: KeytarModule | null
+ ): Promise<string | null> {
+ // Legacy keytar global account.
+ if (keytar) {
+ try {
+ const legacy = await keytar.getPassword(SERVICE, LEGACY_ACCOUNT)
+ if (legacy) {
+ await this.setSessionToken(legacy, envKey)
+ await keytar.deletePassword(SERVICE, LEGACY_ACCOUNT).catch(() => {})
+ return legacy
+ }
+ } catch {
+ // keychain unavailable — try the file fallbacks below.
+ }
+ }
+
+ // Legacy safeStorage-encrypted global file.
+ if (app?.isReady() && safeStorage.isEncryptionAvailable()) {
+ try {
+ const file = await legacyEncryptedFilePath()
+ const encrypted = await fs.readFile(file)
+ const token = safeStorage.decryptString(encrypted)
+ if (token) {
+ await this.setSessionToken(token, envKey)
+ await fs.unlink(file).catch(() => {})
+ return token
+ }
+ } catch {
+ // no legacy encrypted file — fall through to plain-text.
+ }
+ }
+
+ // Legacy plain-text global file.
try {
const file = await legacyFilePath()
const raw = await fs.readFile(file, 'utf8')
const data = JSON.parse(raw) as { token?: unknown }
const token = typeof data.token === 'string' && data.token ? data.token : null
if (token) {
- const betterStoreAvailable =
- !!keytar || (app?.isReady() && safeStorage.isEncryptionAvailable())
- if (betterStoreAvailable) {
- await this.setSessionToken(token)
- .then(() => fs.unlink(file))
- .catch(() => {})
- }
+ await this.setSessionToken(token, envKey).catch(() => {})
+ await fs.unlink(file).catch(() => {})
}
return token
} catch {
@@ -95,11 +204,13 @@ export class TokenStore {
}
}
- async setSessionToken(token: string): Promise<void> {
+ async setSessionToken(token: string, envKey: string): Promise<void> {
+ assertEnvKey(envKey)
+ const account = accountFor(envKey)
const keytar = await loadKeytar()
if (keytar) {
try {
- await keytar.setPassword(SERVICE, ACCOUNT, token)
+ await keytar.setPassword(SERVICE, account, token)
return
} catch {
// Fall through to file storage when keychain writes fail.
@@ -107,28 +218,39 @@ export class TokenStore {
}
if (app?.isReady() && safeStorage.isEncryptionAvailable()) {
- const file = await encryptedFilePath()
+ const file = await encryptedFilePath(envKey)
await fs.writeFile(file, safeStorage.encryptString(token), { mode: 0o600 })
return
}
- const file = await legacyFilePath()
+ const file = await plainFilePath(envKey)
await fs.writeFile(file, JSON.stringify({ token }), { encoding: 'utf8', mode: 0o600 })
}
- async clearSessionToken(): Promise<void> {
+ async clearSessionToken(envKey: string): Promise<void> {
+ assertEnvKey(envKey)
+ const account = accountFor(envKey)
const keytar = await loadKeytar()
if (keytar) {
try {
- await keytar.deletePassword(SERVICE, ACCOUNT)
+ await keytar.deletePassword(SERVICE, account)
} catch {
// Continue cleaning up file-based storage even if keychain fails.
}
+ // Best-effort cleanup of the legacy global slot so it can't be migrated
+ // into another environment later.
+ await keytar.deletePassword(SERVICE, LEGACY_ACCOUNT).catch(() => {})
}
// Always clean up file-based storage regardless of keychain result,
// since prior versions may have written both stores.
await Promise.all([
- encryptedFilePath()
+ encryptedFilePath(envKey)
+ .then(file => fs.unlink(file))
+ .catch(() => {}),
+ plainFilePath(envKey)
+ .then(file => fs.unlink(file))
+ .catch(() => {}),
+ legacyEncryptedFilePath()
.then(file => fs.unlink(file))
.catch(() => {}),
legacyFilePath()
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 5c3d559a8..92c1a3a19 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -541,6 +541,14 @@ export type DesktopRuntimeConfigState = {
isLocalhost: boolean
selectorVisible: boolean
activeOptionId: string | null
+ /**
+ * Stable, filesystem-safe namespacing key for the ACTIVE environment (spec
+ * §5.1). Derived from `new URL(externalRestApiBaseUrl).origin`; every local
+ * cache surface (chat store path, session-token keychain slot, gfs session
+ * scope, sandbox partitions) is scoped by this so switching clusters never
+ * shows or reconciles another environment's data.
+ */
+ envKey: string
storagePath: string
options: DesktopRuntimeConfigOption[]
}
diff --git a/desktop-app/test/e2e-playwright/cron-execution-desktop-journey.test.ts b/desktop-app/test/e2e-playwright/cron-execution-desktop-journey.test.ts
new file mode 100644
index 000000000..aa186b99b
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/cron-execution-desktop-journey.test.ts
@@ -0,0 +1,168 @@
+import { CRON_EXEC_PROBE_INSTRUCTION } from '../../../tests/e2e/fixtures/cronExecProbeInstruction.js'
+import { getStatus, mcpHostExec } from '../../../tests/e2e/helpers.js'
+import { expect, test } from './fixtures.js'
+import {
+ enterChatllmChat,
+ expandResponseToolDetails,
+ startFreshThread,
+} from './workflowAgentChatTools.js'
+import { sendChatPromptAndApproveToolCallsUntilText } from './workflowChatMultiToolApproval.js'
+
+const RUN_DESKTOP_CRON = process.env.E2E_RUN_DESKTOP_CRON === '1'
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+test.describe.serial('Desktop cron execution regression for issue #529', () => {
+ test.skip(
+ !RUN_DESKTOP_CRON,
+ 'Set E2E_RUN_DESKTOP_CRON=1 to run the real-LLM Desktop cron journey.'
+ )
+ test.setTimeout(900_000)
+
+ test('user creates and executes the canonical cron probe through Agent Chat', async ({
+ appPage,
+ }) => {
+ const suffix = Date.now().toString(36)
+ const jobName = `e2e-desktop-cron-${suffix}`
+ const proofPath = `/tmp/${jobName}-proof.txt`
+ const instruction = CRON_EXEC_PROBE_INSTRUCTION.replaceAll('e2e-cron-exec', jobName)
+ .replaceAll('/tmp/cron-exec-proof.txt', proofPath)
+ .replace('"*/1 * * * *"', '"0 0 1 1 *"')
+
+ expect(instruction).toContain('cron_manage')
+ expect(instruction).toContain(jobName)
+ expect(instruction).toContain(proofPath)
+ expect(instruction).toContain('CRON_EXEC_OK')
+ expect(instruction).toContain('CRON_EXEC_VERIFIED')
+
+ mcpHostExec(`rm -f ${proofPath}`)
+ const baselineCronJobs = Number((await getStatus()).cronJobs ?? 0)
+ await enterChatllmChat(appPage)
+ await startFreshThread(appPage)
+ let cronMutationAttempted = false
+ let journeyError: unknown
+
+ try {
+ const response =
+ await test.step('user submits the canonical recipe instruction and approves its tool calls', () => {
+ cronMutationAttempted = true
+ return sendChatPromptAndApproveToolCallsUntilText(
+ appPage,
+ instruction,
+ [/CRON_EXEC_VERIFIED/],
+ 720_000,
+ { approvalRequired: true, requiredText: [/cron|shell/i] }
+ )
+ })
+
+ await test.step('Desktop exposes the real cron and shell execution evidence', async () => {
+ await expandResponseToolDetails(response)
+ const progress = response.getByTestId('progress-stepper').last()
+ await expect(progress).toContainText(/cron/i)
+ await expect(progress).toContainText(/shell/i)
+ const completedCron = progress
+ .locator('.stepper-step:has(.stepper-step-icon.state-completed)')
+ .filter({ hasText: /cron_manage/i })
+ const completedCronCount = await completedCron.count()
+ expect(completedCronCount).toBeGreaterThanOrEqual(2)
+ const cronOutputs: string[] = []
+ for (let index = 0; index < completedCronCount; index += 1) {
+ const row = completedCron.nth(index)
+ await row.click()
+ const output = row.locator(
+ 'xpath=following-sibling::*[1][@data-testid="step-output-panel"]'
+ )
+ await expect(output).toBeVisible()
+ cronOutputs.push(await output.textContent().then(text => text ?? ''))
+ }
+ expect(cronOutputs.some(output => output.includes(jobName))).toBe(true)
+ expect(cronOutputs.some(output => /"triggered"\s*:\s*true/i.test(output))).toBe(true)
+
+ const completedShells = progress
+ .locator('.stepper-step:has(.stepper-step-icon.state-completed)')
+ .filter({ hasText: /Shell.*shell_exec/i })
+ const completedShellCount = await completedShells.count()
+ expect(completedShellCount).toBeGreaterThanOrEqual(1)
+ const shellInputs: string[] = []
+ for (let index = 0; index < completedShellCount; index += 1) {
+ const row = completedShells.nth(index)
+ const input = row.locator(
+ 'xpath=following-sibling::*[1][@data-testid="step-input-preview"]'
+ )
+ await expect(input).toBeVisible()
+ shellInputs.push(await input.textContent().then(text => text ?? ''))
+ }
+ const proofReader = new RegExp(
+ `^(?:sleep\\s+8\\s*(?:;|&&)\\s*)?cat\\s+['"]?${escapeRegExp(proofPath)}['"]?\\s*$`
+ )
+ expect(shellInputs.every(input => proofReader.test(input.trim()))).toBe(true)
+ await expect(response).toContainText('CRON_EXEC_OK')
+ await expect(response).toContainText('CRON_EXEC_VERIFIED')
+ await expect(response).not.toContainText('CRON_EXEC_FAILED')
+ })
+
+ await test.step('the runtime confirms the unique schedule exists', async () => {
+ await expect
+ .poll(() => getStatus().then(status => Number(status.cronJobs ?? 0)), {
+ timeout: 30_000,
+ intervals: [500, 1_000, 2_000],
+ message: `cron job count should increase after creating ${jobName}`,
+ })
+ .toBe(baselineCronJobs + 1)
+ })
+
+ await test.step('the unique cron dispatch created an independent proof file', async () => {
+ await expect
+ .poll(
+ () => {
+ try {
+ return mcpHostExec(`cat ${proofPath}`).trim()
+ } catch {
+ return ''
+ }
+ },
+ {
+ timeout: 180_000,
+ intervals: [1_000, 2_000, 5_000],
+ message: `cron task ${jobName} should write its unique proof file`,
+ }
+ )
+ .toBe('CRON_EXEC_OK')
+ })
+ } catch (error) {
+ journeyError = error
+ } finally {
+ let cleanupError: unknown
+ if (cronMutationAttempted) {
+ try {
+ const cleanupResponse = await sendChatPromptAndApproveToolCallsUntilText(
+ appPage,
+ `Use cron_manage to delete the cron job named "${jobName}". If it is already absent, report that clearly.`,
+ [new RegExp(jobName), /deleted|removed|absent|not found|does not exist/i],
+ 240_000,
+ { requiredText: [/cron/i] }
+ )
+ await expect(cleanupResponse).toContainText(jobName)
+ await expect
+ .poll(() => getStatus().then(status => Number(status.cronJobs ?? 0)), {
+ timeout: 30_000,
+ intervals: [500, 1_000, 2_000],
+ message: `cron job count should return to baseline after deleting ${jobName}`,
+ })
+ .toBe(baselineCronJobs)
+ } catch (error) {
+ cleanupError = error
+ }
+ }
+ try {
+ mcpHostExec(`rm -f ${proofPath}`)
+ } catch (error) {
+ cleanupError ??= error
+ }
+ if (journeyError) throw journeyError
+ if (cleanupError) throw cleanupError
+ }
+ })
+})
diff --git a/desktop-app/test/e2e-playwright/gfs-user-journey.test.ts b/desktop-app/test/e2e-playwright/gfs-user-journey.test.ts
index d709118a2..a2dfcc846 100644
--- a/desktop-app/test/e2e-playwright/gfs-user-journey.test.ts
+++ b/desktop-app/test/e2e-playwright/gfs-user-journey.test.ts
@@ -74,8 +74,9 @@ async function loginControlUi(page: Page): Promise<void> {
async function openControlGfs(page: Page): Promise<void> {
await loginControlUi(page)
- await page.getByRole('link', { name: /Global Files/i }).click()
- await expect(page).toHaveURL(/\/gfs(?:$|\?)/, { timeout: 15_000 })
+ await page.getByRole('button', { name: 'Directories', exact: true }).click()
+ await page.getByRole('link', { name: /Global File System/i }).click()
+ await expect(page).toHaveURL(/\/global-file-system(?:$|\?)/, { timeout: 15_000 })
await expect(page.getByRole('region', { name: 'Global File System browser' })).toBeVisible()
}
diff --git a/desktop-app/test/e2e-playwright/global-setup.ts b/desktop-app/test/e2e-playwright/global-setup.ts
index 7df87a6fc..a31a0ae31 100644
--- a/desktop-app/test/e2e-playwright/global-setup.ts
+++ b/desktop-app/test/e2e-playwright/global-setup.ts
@@ -2,13 +2,13 @@ import { execFileSync } from 'node:child_process'
import { E2E_TEST_EMAIL } from '../../../tests/e2e/testUser'
const ALLOWED_CONTEXTS = new Set(
- (process.env.E2E_ALLOWED_CONTEXTS || 'clerum-test,gke_your-gcp-project_us-central1-a_example-dev')
+ (process.env.E2E_ALLOWED_CONTEXTS || 'clerum-test,gke_${GCP_PROJECT}_us-central1-a_example-dev')
.split(',')
.map(context => context.trim())
.filter(Boolean)
)
-const DEV_CONTEXT = 'gke_your-gcp-project_us-central1-a_example-dev'
-const PROD_CONTEXT = 'gke_your-gcp-project_us-central1-a_clerum'
+const DEV_CONTEXT = 'gke_${GCP_PROJECT}_us-central1-a_example-dev'
+const PROD_CONTEXT = 'gke_${GCP_PROJECT}_us-central1-a_clerum'
function isLocalhost(url: string): boolean {
return /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(url)
diff --git a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts
index 4f6d2a03f..1b404edc4 100644
--- a/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts
+++ b/desktop-app/test/e2e-playwright/helpers/gfsFixtures.ts
@@ -3,7 +3,7 @@
*
* Seeds two isolated GFS files through the shared SQL fixtures:
* - `granted`: visible to the Desktop user AND granted read to the agent
- * host sentinel — the happy path.
+ * host `chatllm` — the happy path.
* - `ungranted`: visible to the Desktop user but NOT granted to the host —
* the agent must receive a clean authorization denial (403),
* never a permission-store outage (503 not_mounted).
@@ -24,11 +24,11 @@ import {
} from '../../../../tests/e2e/gfsUiFixtures'
/**
- * Every HCC-provisioned 1st-party host shares this sentinel gfs subject —
- * the host NAME (e.g. `chatllm`) is Kubernetes-provisioning-only and never a
- * token claim (see host-context-controller/src/gfsHostBinding.ts).
+ * The Desktop agent journey runs through the concrete `chatllm` Host. GFS
+ * grants are host-specific, so `chatllm-stateless` and every other first-party
+ * Host remain independently denied unless they receive their own grant.
*/
-export const FIRST_PARTY_HOST_SUBJECT_ID = '1st:mcp-host/standalone'
+export const FIRST_PARTY_HOST_SUBJECT_ID = '1st:mcp-host/chatllm'
const GFS_NS = 'gfs'
// Pod-template labels — pods do NOT inherit the deployment-level managed-by
diff --git a/desktop-app/test/e2e-playwright/playwright.qa-recorder.config.ts b/desktop-app/test/e2e-playwright/playwright.qa-recorder.config.ts
new file mode 100644
index 000000000..8b92fdb9b
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/playwright.qa-recorder.config.ts
@@ -0,0 +1,26 @@
+import { defineConfig } from '@playwright/test'
+import path from 'node:path'
+import { loadQaRecorderEnv } from '../../../scripts/qa-recorder/loadEnv'
+
+const repoRoot = path.resolve(__dirname, '../../..')
+loadQaRecorderEnv(repoRoot)
+
+const recorderRoot = process.env.QA_RECORDER_ROOT
+ ? path.resolve(process.env.QA_RECORDER_ROOT)
+ : path.join(repoRoot, '.local-notes', 'qa-recorder')
+
+export default defineConfig({
+ testDir: '.',
+ // All Desktop App recorder journeys share this config. Each journey lives in
+ // its own qa-recorder-<journey>.spec.ts and is run via a namespaced
+ // qa:recorder:<journey> command (see package.json). This stays isolated from
+ // the normal Playwright/CI suite — only recorder specs match.
+ testMatch: /qa-recorder-.*\.spec\.ts/,
+ timeout: 240_000,
+ expect: { timeout: 30_000 },
+ retries: 0,
+ workers: 1,
+ reporter: [['list']],
+ outputDir: path.join(recorderRoot, 'runs', 'desktop-app'),
+ preserveOutput: 'always',
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts
new file mode 100644
index 000000000..1d09e286b
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts
@@ -0,0 +1,151 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ configuredHostRef,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openAgentsPage,
+ openExactAgentChat,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Optional QA recorder journey for the Desktop App agents fleet and workspace.
+//
+// Read-only throughout: it launches the real Electron window headfully with
+// video, signs in as the exact QA identity, walks the Resources -> Agents fleet,
+// lands on the chatllm agent's chat composer, and exercises the agent workspace
+// route switcher (Details / Connectors / Contexts / Activity). No chat messages
+// are sent and no confirm flag is required; every test still guards the loopback
+// targets up front. See docs/testing/optional-playwright-qa-recorder.md.
+
+test('optional QA recorder: Desktop agents journey — fleet', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ const hostRef = configuredHostRef()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openAgentsPage(page)
+
+ // The fleet renders one .agents-table-row-clickable per agent. Assert the
+ // exact chatllm fixture row is present, resilient to the chat-autoselect
+ // landing (composer visible instead) and to empty/loading states.
+ const exactAgentRow = page.locator('.agents-table-row-clickable', { hasText: hostRef }).first()
+ const composer = page.getByRole('textbox', { name: 'Agent message composer' })
+ const emptyState = page.getByText('No agents available')
+ await expect(exactAgentRow.or(composer).or(emptyState)).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-agents-fleet')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop agents journey — chat workspace', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ const hostRef = configuredHostRef()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ // Lands on the exact chatllm agent's chat composer (no first-available
+ // fallback) and asserts the Switch chat agent control reflects chatllm.
+ await openExactAgentChat(page, hostRef)
+
+ // Assert the workspace shell rendered: the chat breadcrumb is present and
+ // the composer is visible. openExactAgentChat already verifies the agent
+ // identity, so here we prove the workspace chrome (breadcrumb + composer)
+ // is mounted around it.
+ const breadcrumb = page.getByLabel('Chat breadcrumb')
+ const composer = page.getByRole('textbox', { name: 'Agent message composer' })
+ await expect(breadcrumb).toBeVisible({ timeout: 20_000 })
+ await expect(composer).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-agents-chat-workspace')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop agents journey — workspace routes', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ const hostRef = configuredHostRef()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openAgentsPage(page)
+
+ // Enter the chatllm workspace in agents-mode (Details route) by clicking its
+ // fleet row. Resilient to the auto-selected-chat landing: if the fleet did
+ // not render, the route-switching portion is skipped and we still capture a
+ // proof of whatever shell is present.
+ const exactAgentRow = page.locator('.agents-table-row-clickable', { hasText: hostRef }).first()
+ const composer = page.getByRole('textbox', { name: 'Agent message composer' })
+ const emptyState = page.getByText('No agents available')
+ await expect(exactAgentRow.or(composer).or(emptyState)).toBeVisible({ timeout: 20_000 })
+
+ if (await exactAgentRow.isVisible().catch(() => false)) {
+ await exactAgentRow.click()
+
+ // Agents-mode workspace: breadcrumb shows Agents / <agent> / <route>, and
+ // the default Details section renders its hero shell.
+ const agentBreadcrumb = page.getByLabel('Agent breadcrumb')
+ await expect(agentBreadcrumb).toBeVisible({ timeout: 20_000 })
+ await expect(agentBreadcrumb).toContainText(hostRef)
+ await expect(page.locator('section[aria-label="Agent details"]')).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // Exercise the breadcrumb route switcher (ResourceBreadcrumbSwitcher,
+ // aria-label "Switch agent section") across the workspace resource routes
+ // exposed by the agent menu, asserting each section shell renders.
+ const routes: Array<{ menuLabel: string; sectionAriaLabel: string }> = [
+ { menuLabel: 'Connectors', sectionAriaLabel: 'Agent connectors' },
+ { menuLabel: 'Contexts', sectionAriaLabel: 'Agent contexts' },
+ { menuLabel: 'Activity', sectionAriaLabel: 'Agent activity' },
+ ]
+ for (const { menuLabel, sectionAriaLabel } of routes) {
+ await page.getByRole('button', { name: 'Switch agent section' }).click()
+ await page.getByRole('menuitem', { name: menuLabel, exact: true }).click()
+ await expect(page.locator(`section[aria-label="${sectionAriaLabel}"]`).first()).toBeVisible(
+ {
+ timeout: 20_000,
+ }
+ )
+ }
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-agents-workspace-routes')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts
new file mode 100644
index 000000000..b48ae614c
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts
@@ -0,0 +1,97 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+//
+// Read-only Apps catalog + embedded session journey. No confirm flag is
+// required because this journey sends no messages, triggers no workflows, and
+// pays no provider — it only browses. The target guard still runs on every
+// test so a recorder can never accidentally hit a non-local env.
+//
+// Resilience contract: the Apps catalog may load slowly, be empty, surface a
+// load error, or hold any number of seeded apps. We hard-assert only the shell
+// (the <h2>Apps</h2> header is rendered in every SandboxUiPage branch) and a
+// broad union of catalog bodies. The embedded-session and Back steps are
+// gated on a ready app card actually being present — we never hard-assert a
+// specific app name, because none is guaranteed by the fixture set.
+//
+test('optional QA recorder: Desktop apps journey', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ // (1) Open Apps (nav-sandbox-ui) and assert the catalog shell rendered.
+ // SandboxUiPage emits <h2>Apps</h2> in its loading, empty, error, and
+ // populated branches, so the heading is the stable proof the shell mounted
+ // regardless of how much seed data is present.
+ await page.getByTestId('nav-sandbox-ui').click()
+ const appsHeading = page.getByRole('heading', { name: 'Apps', exact: true })
+ await expect(appsHeading).toBeVisible({ timeout: 20_000 })
+
+ // Resilient catalog body union: `.apps-grid` matches both the populated
+ // grid and the loading-skeleton grid (`apps-grid apps-grid--skeleton`),
+ // and the empty-state copy covers the zero-app branch. Either way the
+ // shell is rendering real content — never hard-assert a specific app name.
+ const catalogBody = page
+ .locator('.apps-grid')
+ .or(page.getByText('No available apps yet'))
+ .first()
+ await expect(catalogBody).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-apps-catalog')
+
+ // (2) If a ready app card is present, open the embedded session. A card is
+ // only activatable when the backend marked it ready, which is exactly when
+ // SandboxUiPage applies the `apps-grid__card--clickable` modifier plus
+ // role=button (via clickableRowProps). Take the first ready card — do not
+ // pin to a specific app identity.
+ const readyCard = page.locator('.apps-grid__card--clickable').first()
+ if (await readyCard.isVisible().catch(() => false)) {
+ await readyCard.click()
+
+ // The embedded app is a native WebContentsView floated above the DOM, so
+ // assert the mounted chrome OR the minting loader OR the parked preview
+ // image. The "Back to apps" button is rendered for both the `minting`
+ // and `mounted` launch states, so it is the most reliable signal that the
+ // open flow actually ran.
+ const backButton = page.getByRole('button', { name: 'Back to apps' })
+ const loadingApp = page.getByText('Loading app')
+ const embedPreview = page.getByTestId('sandbox-ui-embed-preview')
+ const mounted = backButton.or(loadingApp).or(embedPreview).first()
+ await expect(mounted).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-apps-embedded')
+
+ // (3) Back action returns to the catalog. The Back button is part of the
+ // mounted union above, so only click it when it is the visible signal —
+ // if the open surfaced an error banner instead, the catalog is already
+ // showing and there is nothing to return from.
+ if (await backButton.isVisible().catch(() => false)) {
+ await backButton.click()
+ await expect(appsHeading).toBeVisible({ timeout: 20_000 })
+ await expect(catalogBody).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'desktop-apps-back')
+ }
+ }
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts
new file mode 100644
index 000000000..54e0c110e
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts
@@ -0,0 +1,144 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Optional QA recorder journey for the Desktop App auth + runtime session surface.
+// Read-only against the UI (no chat, no workflow, no endpoint switch), so it needs
+// no confirm flag — only the loopback target guard shared by every recorder test.
+// Each test launches a fresh isolated profile, so the sign-in screen is the
+// starting state and there is no carryover between tests.
+
+test('optional QA recorder: Desktop auth and session journey — sign-in screen', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ // Wait for the boot splash / dependency + session checks to clear.
+ await expect(page.locator('.boot-overlay')).toBeHidden({ timeout: 30_000 })
+
+ const emailInput = page.locator('#email-input')
+ const passwordInput = page.locator('#password-input')
+ const signInButton = page.getByRole('button', { name: /^Sign in$/ })
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+
+ // A returning user may be auto-authenticated from a cached keyring session
+ // (keytar persists across the recorder's isolated user-data-dirs). If so, the
+ // authenticated shell is shown instead of the sign-in form; log out through
+ // the app to clear that session and reveal the real sign-in screen. This also
+ // exercises the auto-login + logout paths. email-input and the settings menu
+ // are mutually exclusive, so the .or() is strict-mode safe.
+ await expect(emailInput.or(settingsMenu)).toBeVisible({ timeout: 30_000 })
+ if (await settingsMenu.isVisible().catch(() => false)) {
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+ await page.getByTestId('logout-btn').click()
+ }
+
+ // Sign-in screen rendered with its three fixtures.
+ await expect(emailInput).toBeVisible({ timeout: 20_000 })
+ await expect(passwordInput).toBeVisible()
+ await expect(signInButton).toBeVisible()
+
+ await screenshotAndLog(page, testInfo, 'desktop-auth-signin-screen')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop auth and session journey — authenticated shell', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ // Authenticated shell proof: the chat nav item OR the composer is visible.
+ const navChat = page.getByTestId('nav-chat')
+ const composer = page.getByRole('textbox', { name: 'Agent message composer' })
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ await expect(navChat.or(composer).or(settingsMenu).first()).toBeVisible({ timeout: 20_000 })
+
+ // Reveal the footer Settings menu so the signed-in profile block renders.
+ await expect(settingsMenu).toBeVisible({ timeout: 20_000 })
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+ await expect(settingsMenu).toHaveAttribute('aria-expanded', 'true')
+
+ // The display name falls back to the email local-part when no profile name
+ // is set. Assert the local-part is shown; if a profile name is set instead,
+ // fall back to the profile email line so the exact QA identity is still proven.
+ const displayName = page.getByTestId('user-display-name')
+ await expect(displayName).toBeVisible({ timeout: 20_000 })
+ const localPart = credentials.email.split('@')[0]
+ const shown = (await displayName.textContent()) ?? ''
+ if (!shown.toLowerCase().includes(localPart.toLowerCase())) {
+ await expect(page.locator('.sidebar-settings-profile-email')).toContainText(credentials.email)
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-auth-authenticated-shell')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop auth and session journey — logout', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ // Expand the footer Settings menu to reveal the logout menu item.
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ await expect(settingsMenu).toBeVisible({ timeout: 20_000 })
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+ await expect(settingsMenu).toHaveAttribute('aria-expanded', 'true')
+
+ const logoutButton = page.getByTestId('logout-btn')
+ await expect(logoutButton).toBeVisible({ timeout: 20_000 })
+ await logoutButton.click()
+
+ // Signing out returns the user to the sign-in screen.
+ await expect(page.locator('#email-input')).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-auth-logout')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts
new file mode 100644
index 000000000..5965da400
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts
@@ -0,0 +1,78 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ configuredHostRef,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openExactAgentChat,
+ requireRecorderConfirm,
+ screenshotAndLog,
+ sendChatMessage,
+} from './qa-recorder-helpers'
+
+// Deep chat journey: composer landing, send-button enablement, real send, and
+// thread/agent-response rendering. This is the focused companion to the combined
+// settings-chat smoke (qa-recorder-settings-chat.spec.ts) — it drills into the
+// composer + thread interactions only. Sending a real message costs model
+// tokens, so the whole journey is gated behind QA_RECORDER_CONFIRM_CHAT=1.
+test('optional QA recorder: Desktop chat composer, thread, and task progress journey', async ({}, testInfo) => {
+ requireRecorderConfirm(
+ 'QA_RECORDER_CONFIRM_CHAT',
+ 'This journey sends a real chat message and may incur model cost.'
+ )
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ const hostRef = configuredHostRef()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openExactAgentChat(page, hostRef)
+
+ const composer = page.getByRole('textbox', { name: 'Agent message composer' })
+ const sendButton = page.getByTestId('send-button')
+
+ // (1) The exact agent's composer landed and is interactive.
+ await expect(composer).toBeVisible({ timeout: 20_000 })
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+
+ // Establish a known-empty draft so the disabled-while-empty assertion is
+ // deterministic regardless of any persisted draft state for this chat.
+ await composer.click()
+ await composer.fill('')
+
+ // (2) The send button is disabled while the composer is empty, then becomes
+ // enabled once the user types a draft (ComposerPanel gates the button on a
+ // non-empty trimmed draft and/or attachments).
+ await expect(sendButton).toBeVisible({ timeout: 20_000 })
+ await expect(sendButton).toBeDisabled({ timeout: 20_000 })
+ await composer.fill('Probe draft to enable the send button.')
+ await expect(sendButton).toBeEnabled({ timeout: 20_000 })
+
+ // (3) Send the real QA prompt via the shared helper — it fills the composer,
+ // clicks send, and waits for a non-empty [data-testid='agent-response'].
+ await sendChatMessage(page)
+
+ // (4) The thread surface rendered the exchange: the message-list is present
+ // and at least one assistant response bubble is visible with content.
+ await expect(page.getByTestId('message-list')).toBeVisible({ timeout: 20_000 })
+ const agentResponse = page.getByTestId('agent-response').first()
+ await expect(agentResponse).toBeVisible({ timeout: 20_000 })
+ await expect(agentResponse).not.toHaveText('')
+
+ await screenshotAndLog(page, testInfo, 'desktop-chat-composer-thread')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts
new file mode 100644
index 000000000..0fe3f21bc
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts
@@ -0,0 +1,77 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openResourcesNavItem,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: no requireRecorderConfirm flag. The loopback + health
+// guard still runs for both targets at the top of the test.
+test('optional QA recorder: Desktop connectors journey', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ // Resources -> Connectors inventory page (exact nav item, not first-available).
+ await openResourcesNavItem(page, 'nav-mcp-servers')
+
+ // (1) Page shell rendered.
+ const heading = page.getByRole('heading', { name: 'Connectors', exact: true })
+ await expect(heading).toBeVisible({ timeout: 20_000 })
+
+ // The connectors inventory lives inside the board card; scope content
+ // locators to it so transient toasts/sidebar markup cannot satisfy the
+ // resilient chain. The McpServerHealthTable testids (mcp-health-table /
+ // mcp-health-empty) are emitted by the per-agent workspace, not this page,
+ // but are kept in the .or() so the assertion stays resilient to either
+ // surface and degrades gracefully if the inventory shell changes shape.
+ const boardCard = page.locator('.mcp-servers-board-card')
+ const connectorsTable = boardCard.locator('.mcp-servers-data-table')
+ const healthTable = page.getByTestId('mcp-health-table')
+ const emptyHeading = boardCard
+ .getByRole('heading', { name: 'No connectors', exact: true })
+ .or(boardCard.getByRole('heading', { name: 'Loading', exact: true }))
+ const healthEmpty = page.getByTestId('mcp-health-empty')
+ const errorAlert = boardCard.locator('.composer-error')
+
+ await expect(
+ connectorsTable.or(healthTable).or(emptyHeading).or(healthEmpty).or(errorAlert)
+ ).toBeVisible({ timeout: 20_000 })
+
+ // (2) If the connectors table is present, assert its container rendered.
+ // Rows may be empty — we only assert the table shell, not row count.
+ if (await connectorsTable.isVisible().catch(() => false)) {
+ await expect(connectorsTable).toBeVisible()
+ }
+
+ // (3) Toggle health detail if a toggle is exposed on this surface, then
+ // assert the page did not crash. The connectors inventory renders a static
+ // table (no mcp-health-toggle); the toggle is honored opportunistically for
+ // any surface that exposes it, and is a safe no-op here.
+ const healthToggle = page.getByTestId('mcp-health-toggle')
+ if (await healthToggle.isVisible().catch(() => false)) {
+ await healthToggle.click()
+ await expect(heading).toBeVisible({ timeout: 20_000 })
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-connectors')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts
new file mode 100644
index 000000000..b4ad3452e
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts
@@ -0,0 +1,92 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openResourcesNavItem,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: Resources -> Contexts list, then a context detail.
+// No chat, no writes, no paid calls — so no confirm flag is required. The
+// loopback + health guard still runs for both targets.
+test('optional QA recorder: Desktop contexts list and detail journey', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openResourcesNavItem(page, 'nav-contexts')
+
+ // (1) Contexts list shell renders.
+ const contextsHeading = page.getByRole('heading', { name: 'Contexts', exact: true })
+ await expect(contextsHeading).toBeVisible({ timeout: 20_000 })
+ await expect(page.locator('.contexts-board-card')).toBeVisible({ timeout: 20_000 })
+
+ // Wait for the list to resolve to a known fixture row OR an explicit
+ // empty / error state. Resilient to loading, empty, and error seeds — we
+ // only hard-assert on fixture identities we know exist.
+ const devRow = page.getByRole('button', { name: 'Open context development' })
+ const moneyRow = page.getByRole('button', { name: 'Open context moneymaking' })
+ const emptyState = page.getByText('No contexts').first()
+ const errorBox = page.locator('.contexts-board-card .composer-error')
+ await expect(devRow.or(moneyRow).or(emptyState).or(errorBox).first()).toBeVisible({
+ timeout: 20_000,
+ })
+
+ await screenshotAndLog(page, testInfo, 'desktop-contexts-list')
+
+ // (2) Open a context detail using an exact known fixture (development
+ // preferred, moneymaking as a still-exact fallback). Skip-with-success when
+ // no fixture row is present — the list shell assertions above already prove
+ // the journey for empty/error seeds.
+ const targetRow = (await devRow.isVisible().catch(() => false))
+ ? devRow
+ : (await moneyRow.isVisible().catch(() => false))
+ ? moneyRow
+ : null
+
+ if (targetRow) {
+ const targetId = targetRow === devRow ? 'development' : 'moneymaking'
+ await targetRow.click()
+
+ // Detail shell + tabs nav render.
+ const tabsNav = page.locator('nav.context-tabs')
+ await expect(tabsNav).toBeVisible({ timeout: 20_000 })
+ await expect(
+ page.getByRole('heading', { name: targetId, exact: true, level: 3 })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // Default tab is Agents; its panel must render.
+ await expect(tabsNav.getByRole('button', { name: 'Agents', exact: true })).toBeVisible()
+ await expect(page.locator('.context-resource-list').first()).toBeVisible()
+
+ // Exercise the remaining detail tabs. Each renders a .context-resource-list
+ // panel (table or explicit empty state) regardless of how much is seeded.
+ for (const tabName of ['Connectors', 'Teams', 'Members', 'Agent Files']) {
+ const tab = tabsNav.getByRole('button', { name: tabName, exact: true })
+ await expect(tab).toBeVisible()
+ await tab.click()
+ await expect(page.locator('.context-resource-list').first()).toBeVisible({
+ timeout: 20_000,
+ })
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-contexts-detail')
+ }
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
new file mode 100644
index 000000000..9190fa04b
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
@@ -0,0 +1,314 @@
+// desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
+//
+// Shared primitives for the optional Desktop App QA recorder journeys.
+//
+// Contract: see docs/testing/optional-playwright-qa-recorder.md ("Extending the
+// recorder"). Every recorder journey is self-contained: it launches the real
+// Electron app headfully with video, signs in with the exact identity from
+// .env.qa-recorder, guards non-local targets, and requires an explicit opt-in
+// confirmation variable for any write, message, or paid provider call.
+//
+// These helpers hold only the genuinely shared plumbing (launch, login,
+// credentials, guards, screenshots/video finalization, and a few navigation
+// primitives reused across journeys). Journey-specific interactions stay inside
+// their own specs so each remains independently readable.
+import {
+ type ElectronApplication,
+ type Page,
+ type TestInfo,
+ _electron as electron,
+ expect,
+} from '@playwright/test'
+import fs from 'node:fs'
+import path from 'node:path'
+
+export const DESKTOP_APP_ROOT = path.resolve(__dirname, '../..')
+export const MAIN_ENTRY = path.join(DESKTOP_APP_ROOT, 'dist/main.js')
+export const EXTERNAL_REST_API_BASE_URL =
+ process.env.EXTERNAL_REST_API_BASE_URL || 'http://127.0.0.1:8091'
+export const RPC_PROXY_BASE_URL = process.env.RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094'
+const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1'])
+
+/** Require an explicit opt-in confirmation variable before a journey that writes, messages, or pays. */
+export function requireRecorderConfirm(flag: string, description: string): void {
+ if (process.env[flag] !== '1') {
+ throw new Error(
+ `${description} Set ${flag}=1 in .env.qa-recorder to run this recorder journey.`
+ )
+ }
+}
+
+/** Refuse non-loopback targets unless the operator explicitly allowed a remote QA env. */
+export function assertAllowedTarget(label: string, rawUrl: string): void {
+ let url: URL
+ try {
+ url = new URL(rawUrl)
+ } catch {
+ throw new Error(`${label} must be an absolute URL; received "${rawUrl}".`)
+ }
+ if (!LOOPBACK_HOSTS.has(url.hostname) && process.env.QA_RECORDER_ALLOW_REMOTE !== '1') {
+ throw new Error(
+ `${label} targets non-local host "${url.hostname}". Set QA_RECORDER_ALLOW_REMOTE=1 only for an intentional QA environment.`
+ )
+ }
+ if (LOOPBACK_HOSTS.has(url.hostname) && process.env.QA_RECORDER_ALLOW_REMOTE !== '1') {
+ // Target is local — assert the endpoints are healthy right now so a recorder
+ // run fails fast with a clear message instead of a slow Electron timeout.
+ void assertHealthy(rawUrl, label)
+ }
+}
+
+async function assertHealthy(baseUrl: string, label: string): Promise<void> {
+ try {
+ const res = await fetch(`${baseUrl.replace(/\/$/, '')}/health`)
+ if (res.status !== 200) {
+ throw new Error(`HTTP ${res.status}`)
+ }
+ } catch (err) {
+ throw new Error(
+ `[qa-recorder] ${label} not healthy at ${baseUrl}: ${(err as Error).message}. Are port-forwards up?`
+ )
+ }
+}
+
+function requiredValue(label: string, candidates: Array<string | undefined>): string {
+ const value = candidates.find(candidate => candidate?.trim())?.trim()
+ if (!value) throw new Error(`${label} is required for this recorder journey.`)
+ return value
+}
+
+export function desktopCredentials(): { email: string; password: string } {
+ return {
+ email: requiredValue('E2E_DEV_LOGIN_EMAIL or TEST_USER_EMAIL', [
+ process.env.E2E_DEV_LOGIN_EMAIL,
+ process.env.TEST_USER_EMAIL,
+ ]),
+ password: requiredValue('a Desktop test password', [
+ process.env.E2E_DESKTOP_PASSWORD,
+ process.env.E2E_TEST_PASSWORD,
+ process.env.ADMIN_PASSWORD,
+ ]),
+ }
+}
+
+export function configuredHostRef(): string {
+ return requiredValue('E2E_HOST_REF', [process.env.E2E_HOST_REF])
+}
+
+/**
+ * Launch the real Electron app headfully into an isolated profile, recording a
+ * 1280x720 WebM. Returns the app handle and its first window page. Caller owns
+ * closing the app (use finalizeRecording in a finally block) so the video file
+ * is finalized on disk.
+ */
+export async function launchDesktopApp(testInfo: TestInfo): Promise<{
+ app: ElectronApplication
+ page: Page
+}> {
+ if (!fs.existsSync(MAIN_ENTRY)) {
+ throw new Error(`Desktop app build missing at ${MAIN_ENTRY}. Run npm run build first.`)
+ }
+
+ const userDataDir = testInfo.outputPath('electron-user-data')
+ const videoDir = testInfo.outputPath('video')
+ fs.mkdirSync(userDataDir, { recursive: true })
+ fs.mkdirSync(videoDir, { recursive: true })
+
+ const slowMo = Number(process.env.QA_RECORDER_SLOW_MO_MS ?? 75)
+
+ const app = await electron.launch({
+ args: [`--user-data-dir=${userDataDir}`, MAIN_ENTRY],
+ env: {
+ ...process.env,
+ ELECTRON_RENDERER_URL: '',
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ CLERUM_DESKTOP_CONFIG_PATH: path.join(userDataDir, 'runtime-config.json'),
+ },
+ recordVideo:
+ process.env.QA_RECORDER_VIDEO === '0'
+ ? undefined
+ : {
+ dir: videoDir,
+ size: { width: 1280, height: 720 },
+ },
+ // Headful + human-paced actions. QA_RECORDER_HEADLESS is honored for the
+ // Control UI browser journeys; Electron always opens a real window, so this
+ // only controls action pacing here. Slow-mo is what makes the recording
+ // watchable as a genuine UI-interaction proof.
+ slowMo: Number.isFinite(slowMo) ? slowMo : 75,
+ })
+
+ const page = await app.firstWindow()
+ await page.setViewportSize({ width: 1280, height: 720 })
+ await page.waitForLoadState('domcontentloaded')
+ return { app, page }
+}
+
+/** Sign in through the real UI using the configured identity. No-ops if already authenticated. */
+export async function login(
+ page: Page,
+ credentials: { email: string; password: string }
+): Promise<void> {
+ await expect(page.locator('.boot-overlay')).toBeHidden({ timeout: 20_000 })
+
+ const emailInput = page.locator('#email-input')
+ const passwordInput = page.locator('#password-input')
+ const authenticatedShell = page
+ .getByTestId('nav-chat')
+ .or(page.getByTestId('nav-settings-menu'))
+ .or(page.getByRole('textbox', { name: 'Agent message composer' }))
+ .first()
+
+ await expect(emailInput.or(authenticatedShell)).toBeVisible({ timeout: 20_000 })
+ if (await emailInput.isVisible()) {
+ await expect(passwordInput).toBeVisible()
+ await emailInput.fill(credentials.email)
+ await passwordInput.fill(credentials.password)
+ await page.getByRole('button', { name: /^Sign in$/ }).click()
+ }
+ await expect(authenticatedShell).toBeVisible({ timeout: 20_000 })
+}
+
+/** Open the footer Settings menu -> Settings page. */
+export async function openSettings(page: Page): Promise<void> {
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ await expect(settingsMenu).toBeVisible({ timeout: 20_000 })
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+ await expect(settingsMenu).toHaveAttribute('aria-expanded', 'true')
+ await page.getByTestId('nav-settings').click()
+ await expect(page.getByRole('heading', { name: 'Settings', exact: true })).toBeVisible()
+}
+
+/** Click a Settings tab and assert its panel rendered the expected content. */
+export async function visitSettingsTab(
+ page: Page,
+ tabName: string,
+ expectedContent: string
+): Promise<void> {
+ const tab = page.getByRole('tab', { name: tabName, exact: true })
+ await expect(tab).toBeVisible()
+ await tab.click()
+ await expect(page.getByRole('tabpanel')).toContainText(expectedContent)
+}
+
+/** Expand footer Resources submenu and click one of its items by test id. */
+export async function openResourcesNavItem(page: Page, itemTestId: string): Promise<void> {
+ const item = page.getByTestId(itemTestId)
+ if (!(await item.isVisible().catch(() => false))) {
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ await expect(settingsMenu).toBeVisible({ timeout: 15_000 })
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+ await expect(settingsMenu).toHaveAttribute('aria-expanded', 'true', { timeout: 15_000 })
+
+ const resourcesMenu = page.getByTestId('nav-data-menu')
+ await expect(resourcesMenu).toBeVisible({ timeout: 15_000 })
+ if (!(await item.isVisible().catch(() => false))) {
+ await resourcesMenu.click()
+ }
+ }
+ await expect(item).toBeVisible({ timeout: 15_000 })
+ await item.click()
+}
+
+/** Open Agents (Resources -> Agents). */
+export async function openAgentsPage(page: Page): Promise<void> {
+ await openResourcesNavItem(page, 'nav-agents')
+}
+
+/**
+ * Navigate to the exact agent named by hostRef and land on its chat composer.
+ * Uses exact identity (no first-available fallback), per the recorder contract.
+ */
+export async function openExactAgentChat(page: Page, hostRef: string): Promise<void> {
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+
+ const resourcesMenu = page.getByTestId('nav-data-menu')
+ await expect(resourcesMenu).toBeVisible()
+ if ((await resourcesMenu.getAttribute('aria-expanded')) !== 'true') {
+ await resourcesMenu.click()
+ }
+
+ await page.getByTestId('nav-agents').click()
+ const chatInput = page.getByRole('textbox', { name: 'Agent message composer' })
+ const exactAgent = page.locator('.agents-table-row-clickable', { hasText: hostRef }).first()
+ const emptyState = page.getByText('No agents available')
+ await expect(chatInput.or(exactAgent).or(emptyState)).toBeVisible({ timeout: 20_000 })
+
+ if (await emptyState.isVisible().catch(() => false)) {
+ throw new Error(`No agents are available for the configured Desktop test user.`)
+ }
+ if (await exactAgent.isVisible().catch(() => false)) {
+ await exactAgent.click()
+ }
+
+ await page.getByTestId('nav-chat').click()
+ const switchAgent = page.getByRole('button', { name: /^Switch chat agent$/ })
+ await expect(switchAgent).toBeVisible({ timeout: 20_000 })
+
+ if (
+ !(await chatInput.isVisible().catch(() => false)) ||
+ !(await switchAgent
+ .getByText(hostRef, { exact: true })
+ .isVisible()
+ .catch(() => false))
+ ) {
+ await switchAgent.click()
+ await page.getByRole('menuitem', { name: hostRef, exact: true }).click()
+ }
+
+ await expect(chatInput).toBeVisible({ timeout: 20_000 })
+ await expect(switchAgent).toContainText(hostRef)
+}
+
+/** Send a chat message and wait for a non-empty assistant response. */
+export async function sendChatMessage(page: Page): Promise<void> {
+ const prompt =
+ process.env.QA_RECORDER_CHAT_PROMPT ||
+ 'Please reply with one short sentence confirming this optional QA recording.'
+ const chatInput = page.getByRole('textbox', { name: 'Agent message composer' })
+ const responseCountBefore = await page.getByTestId('agent-response').count()
+
+ await expect(chatInput).toBeEnabled()
+ await chatInput.fill(prompt)
+ const sendButton = page.getByTestId('send-button')
+ await expect(sendButton).toBeEnabled()
+ await sendButton.click()
+
+ const response = page.getByTestId('agent-response').nth(responseCountBefore)
+ await expect(response).toBeVisible({ timeout: 120_000 })
+ await expect(response).not.toHaveText('', { timeout: 120_000 })
+}
+
+/** Take a full-page PNG proof and log its path. */
+export async function screenshotAndLog(
+ page: Page,
+ testInfo: TestInfo,
+ name: string
+): Promise<void> {
+ const screenshotPath = testInfo.outputPath(`${name}.png`)
+ await page.screenshot({ path: screenshotPath, fullPage: true })
+ // eslint-disable-next-line no-console
+ console.log(`[qa-recorder] Desktop screenshot: ${screenshotPath}`)
+}
+
+/** Close Electron so the WebM recording is finalized; log the video path. Use in finally. */
+export async function finalizeRecording(
+ app: ElectronApplication | undefined,
+ page: Page | undefined
+): Promise<void> {
+ const video = page?.video()
+ await app?.close().catch(() => undefined)
+ const videoPath = await video?.path().catch(() => undefined)
+ if (videoPath && fs.existsSync(videoPath)) {
+ // eslint-disable-next-line no-console
+ console.log(`[qa-recorder] Desktop video: ${videoPath}`)
+ }
+}
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts
new file mode 100644
index 000000000..e48ae5618
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts
@@ -0,0 +1,113 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: exercises the AppHeader notification bell / inbox panel and
+// the header global search. Neither test writes, messages, pays, or
+// approves/denies anything — so no confirmation flag is required. Both still
+// assert the loopback + health guard at the top, per the recorder contract.
+//
+// Selectors below come from desktop-app/ui/src/components/AppHeader/index.tsx:
+// - notification-bell IconButton -> opens role="dialog" "Notifications and approvals"
+// - inbox rows: data-testid="notification-menu-item" and "workflow-approval-card"
+// - empty inbox: ".notification-menu-empty" ("No notifications or pending approvals right now.")
+// - global search: TextInput aria-label="Search" -> results in ".global-search-results"
+// - no results: ".search-results-empty"; loading: ".search-results-loading"
+// We deliberately do NOT click Approve/Deny (those mutate the backend).
+
+test('optional QA recorder: Desktop inbox and search journey — inbox', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ // AppHeader is rendered for every authenticated view, so the bell is
+ // always present after sign-in.
+ const bell = page!.getByTestId('notification-bell')
+ await expect(bell).toBeVisible({ timeout: 20_000 })
+
+ // Opening the inbox must not throw; assert the dialog renders.
+ await bell.click()
+ await expect(bell).toHaveAttribute('aria-expanded', 'true', { timeout: 20_000 })
+
+ const inboxDialog = page!.getByRole('dialog', { name: 'Notifications and approvals' })
+ await expect(inboxDialog).toBeVisible({ timeout: 20_000 })
+
+ // Resilient to empty / populated inbox: at least one row OR the empty
+ // state must render. We never assert a specific seeded notification and
+ // never touch the Approve/Deny buttons.
+ const inboxRow = page!.getByTestId('notification-menu-item').first()
+ const approvalCard = page!.getByTestId('workflow-approval-card').first()
+ const emptyInbox = page!.getByText('No notifications or pending approvals right now.')
+ await expect(inboxRow.or(approvalCard).or(emptyInbox)).toBeVisible({ timeout: 20_000 })
+
+ // Close the inbox cleanly so the final screenshot shows the resting shell.
+ await bell.click()
+ await expect(bell).toHaveAttribute('aria-expanded', 'false', { timeout: 20_000 })
+
+ await screenshotAndLog(page!, testInfo, 'desktop-inbox')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop inbox and search journey — global search', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ const searchInput = page!.getByRole('textbox', { name: 'Search' })
+ await expect(searchInput).toBeVisible({ timeout: 20_000 })
+
+ // Known fixture term (agent "chatllm" / context "development" exist for
+ // the QA user). Resilient: a result row OR the no-results OR the loading
+ // state must render — we only assert the panel reaches a terminal state
+ // without error, regardless of how much directory data has hydrated.
+ await searchInput.fill('chatllm')
+ const resultsPanel = page!.locator('.global-search-results')
+ await expect(resultsPanel).toBeVisible({ timeout: 20_000 })
+ const resultItem = page!.locator('.search-result-item').first()
+ const noResults = page!.locator('.search-results-empty')
+ const searchLoading = page!.locator('.search-results-loading')
+ await expect(resultItem.or(noResults).or(searchLoading)).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page!, testInfo, 'desktop-global-search-known-term')
+
+ // Nonsense term exercises the deterministic no-results branch. Accept the
+ // transient loading state too, in case the team directory is still hydrating.
+ await searchInput.fill('zzzznomatchqa')
+ await expect(resultsPanel).toBeVisible({ timeout: 20_000 })
+ await expect(noResults.or(searchLoading)).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page!, testInfo, 'desktop-global-search-no-results')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts
new file mode 100644
index 000000000..17de70fa3
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts
@@ -0,0 +1,146 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openAgentsPage,
+ openResourcesNavItem,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only global shell navigation journey. It exercises the primary sidebar,
+// the footer Settings/Resources menus, and each Resources destination page so
+// the recording proves the Desktop shell routes between its top-level views.
+// No confirm flag is required: nothing here writes, messages, or pays.
+
+test('optional QA recorder: Desktop navigation journey — primary sidebar', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+ await login(page, credentials)
+
+ // Both primary sidebar items are present. The `active` class lives on the
+ // wrapping div around the data-testid button, so assert against its parent.
+ const chatNav = page.getByTestId('nav-chat')
+ const sandboxNav = page.getByTestId('nav-sandbox-ui')
+ await expect(chatNav).toBeVisible({ timeout: 20_000 })
+ await expect(sandboxNav).toBeVisible({ timeout: 20_000 })
+
+ // Clicking Apps marks the sandbox-ui nav item active and renders the Apps shell.
+ await sandboxNav.click()
+ await expect(sandboxNav.locator('xpath=..')).toHaveClass(/active/)
+ await expect(page.getByRole('heading', { name: 'Apps', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // Clicking Chat restores the chat nav item as the active destination.
+ await chatNav.click()
+ await expect(chatNav.locator('xpath=..')).toHaveClass(/active/)
+
+ await screenshotAndLog(page, testInfo, 'desktop-nav-primary-sidebar')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop navigation journey — footer settings menu', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+ await login(page, credentials)
+
+ // Footer Settings menu opens (aria-expanded flips to true).
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ await expect(settingsMenu).toBeVisible({ timeout: 20_000 })
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click()
+ }
+ await expect(settingsMenu).toHaveAttribute('aria-expanded', 'true')
+
+ // Resources submenu expands and exposes the data-route destinations.
+ const resourcesMenu = page.getByTestId('nav-data-menu')
+ await expect(resourcesMenu).toBeVisible({ timeout: 20_000 })
+ if ((await resourcesMenu.getAttribute('aria-expanded')) !== 'true') {
+ await resourcesMenu.click()
+ }
+ await expect(resourcesMenu).toHaveAttribute('aria-expanded', 'true')
+
+ for (const itemTestId of ['nav-agents', 'nav-contexts', 'nav-teams', 'nav-mcp-servers']) {
+ await expect(page.getByTestId(itemTestId)).toBeVisible({ timeout: 20_000 })
+ }
+
+ // The Settings menu item opens the Settings page heading.
+ await page.getByTestId('nav-settings').click()
+ await expect(page.getByRole('heading', { name: 'Settings', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ await screenshotAndLog(page, testInfo, 'desktop-nav-footer-menu')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop navigation journey — resources pages', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+ await login(page, credentials)
+
+ // Agents — FleetBoard and the empty state both surface the "Agents" heading.
+ await openAgentsPage(page)
+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // Contexts page shell.
+ await openResourcesNavItem(page, 'nav-contexts')
+ await expect(page.getByRole('heading', { name: 'Contexts', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // Teams page heading reads "Members & Teams".
+ await openResourcesNavItem(page, 'nav-teams')
+ await expect(page.getByRole('heading', { name: /Members & Teams/ })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // Connectors (MCP servers) page shell.
+ await openResourcesNavItem(page, 'nav-mcp-servers')
+ await expect(page.getByRole('heading', { name: 'Connectors', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ await screenshotAndLog(page, testInfo, 'desktop-nav-resources-pages')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts
new file mode 100644
index 000000000..e8f14b4dd
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts
@@ -0,0 +1,125 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openResourcesNavItem,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts
+//
+// Optional headful QA recorder journey for the Plugins (Workflows) page.
+// Read-only inventory + detail-panel assertions always run. The trigger step is
+// gated behind QA_RECORDER_CONFIRM_MUTATIONS=1 (it creates a real workflow run
+// and may incur provider cost) and only fires when a triggerable recipe with an
+// input contract is selected. Contract: docs/testing/optional-playwright-qa-recorder.md.
+//
+// Note on selectors: WorkflowsPage renders no `workflows-page`, `workflow-row`,
+// `selected-workflow`, `run-count`, or `runs-loading` data-testids. The real
+// anchors are the `Plugins` <h2> shell, the `button.da-grid__row--clickable`
+// rows, the `Details`/`Recent Runs` headings, the `workflow-run-row` run rows,
+// the `.input-contract-form`, and the `Trigger`/`Triggering...` button.
+
+test('optional QA recorder: Desktop plugins journey', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+
+ // (1, read-only) Resources -> Plugins renders the workflows page shell. The
+ // `Plugins` heading and subtitle are present in every render branch
+ // (loading / error / empty / populated), so they are the robust shell proof.
+ await openResourcesNavItem(page, 'nav-workflows')
+ const pluginsHeading = page.getByRole('heading', { name: 'Plugins', exact: true })
+ const subtitle = page
+ .getByText('View deployed recipes. Select one to see recent runs or trigger it.')
+ .first()
+ await expect(pluginsHeading).toBeVisible({ timeout: 20_000 })
+ await expect(subtitle).toBeVisible({ timeout: 20_000 })
+
+ // Wait for the list to settle out of the loading state into either a row or
+ // the empty state. No plugin fixtures are guaranteed for the QA user, so this
+ // is first-available and must pass when the cluster has zero recipes.
+ const workflowRow = page.locator('button.da-grid__row--clickable').first()
+ const emptyRecipes = page.getByText('No recipes are deployed in this cluster.')
+ await expect(workflowRow.or(emptyRecipes)).toBeVisible({ timeout: 20_000 })
+
+ // (2, read-only) If a row is present, open its detail panel and assert the
+ // detail shell + Recent Runs section render in one of their states.
+ if (await workflowRow.isVisible().catch(() => false)) {
+ await workflowRow.click()
+
+ const detailsHeading = page.getByRole('heading', { name: 'Details', exact: true })
+ const recentRunsHeading = page.getByRole('heading', { name: 'Recent Runs', exact: true })
+ await expect(detailsHeading).toBeVisible({ timeout: 20_000 })
+ await expect(recentRunsHeading).toBeVisible({ timeout: 20_000 })
+
+ const runsLoading = page.getByText('Loading runs...')
+ const runsEmpty = page.getByText('No runs recorded yet.')
+ const runRow = page.getByTestId('workflow-run-row')
+ await expect(runsLoading.or(runsEmpty).or(runRow)).toBeVisible({ timeout: 20_000 })
+
+ // (3, OPTIONAL + gated) Only when the operator opts in via
+ // QA_RECORDER_CONFIRM_MUTATIONS=1 AND the selected recipe is triggerable
+ // AND declares an input contract. Otherwise the read-only journey above
+ // remains the proof and the test still passes.
+ if (process.env.QA_RECORDER_CONFIRM_MUTATIONS === '1') {
+ const triggerButton = page.getByRole('button', { name: /^Trigger$/ })
+ const inputForm = page.locator('.input-contract-form')
+ if (
+ (await triggerButton.isVisible().catch(() => false)) &&
+ (await inputForm.isVisible().catch(() => false))
+ ) {
+ const runCountBefore = await page.getByTestId('workflow-run-row').count()
+
+ // Fill free-text inputs with a sentinel value and numeric inputs with a
+ // valid number. Enums (<select>) and booleans (checkboxes) keep their
+ // defaults so we never send an invalid enum/required value.
+ const textFields = inputForm.locator('input[type="text"]')
+ const textCount = await textFields.count()
+ for (let i = 0; i < textCount; i++) {
+ const field = textFields.nth(i)
+ if (await field.isEnabled().catch(() => false)) {
+ await field.fill('qa-recorder')
+ }
+ }
+
+ const numberFields = inputForm.locator('input[type="number"]')
+ const numberCount = await numberFields.count()
+ for (let i = 0; i < numberCount; i++) {
+ const field = numberFields.nth(i)
+ if (await field.isEnabled().catch(() => false)) {
+ await field.fill('1')
+ }
+ }
+
+ await triggerButton.click()
+
+ // Success = the trigger was acknowledged (button flips to
+ // "Triggering...") OR a new run row appears in Recent Runs.
+ const triggering = page.getByRole('button', { name: 'Triggering...' })
+ const newRunRow = page.getByTestId('workflow-run-row').nth(runCountBefore)
+ await expect(triggering.or(newRunRow)).toBeVisible({ timeout: 60_000 })
+ }
+ }
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-plugins')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts
new file mode 100644
index 000000000..fcc2ef4f0
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts
@@ -0,0 +1,49 @@
+import { type ElectronApplication, type Page, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ configuredHostRef,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openExactAgentChat,
+ openSettings,
+ requireRecorderConfirm,
+ screenshotAndLog,
+ sendChatMessage,
+ visitSettingsTab,
+} from './qa-recorder-helpers'
+
+test('optional QA recorder: Desktop settings and chat journey', async ({}, testInfo) => {
+ requireRecorderConfirm(
+ 'QA_RECORDER_CONFIRM_CHAT',
+ 'This journey sends a real chat message and may incur model cost.'
+ )
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ const hostRef = configuredHostRef()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openSettings(page)
+ await visitSettingsTab(page, 'Appearance', 'Theme')
+ await visitSettingsTab(page, 'Notifications', 'In App Notifications')
+ await visitSettingsTab(page, 'Information', 'External REST API URL')
+ await openExactAgentChat(page, hostRef)
+ await sendChatMessage(page)
+
+ await screenshotAndLog(page, testInfo, 'desktop-settings-chat')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts
new file mode 100644
index 000000000..d06112ff2
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts
@@ -0,0 +1,174 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openSettings,
+ requireRecorderConfirm,
+ screenshotAndLog,
+ visitSettingsTab,
+} from './qa-recorder-helpers'
+
+// Optional QA recorder journey: Settings appearance, notifications, and configuration.
+//
+// Read-only by default. The only mutating step — exercising the desktop endpoint
+// switcher (which logs out) — runs exclusively when QA_RECORDER_CONFIRM_MUTATIONS=1.
+// The appearance theme toggle and the notification volume adjust are local
+// preference/audio changes (no server or paid-provider call), so they run as part
+// of the always-on read-only journey without a confirm flag.
+
+test('optional QA recorder: Desktop settings journey — appearance and notifications', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openSettings(page)
+
+ // (1) Appearance — assert the Theme panel rendered, then toggle the color mode
+ // if the radio controls are present and confirm the shell still renders.
+ await visitSettingsTab(page, 'Appearance', 'Theme')
+ await expect(page.getByRole('heading', { name: 'Theme', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ const themeRadios = page.locator('input[name="settings-theme-mode"]')
+ const themeRadioCount = await themeRadios.count()
+ if (themeRadioCount >= 2) {
+ const currentTheme = await page
+ .evaluate(() => document.documentElement.getAttribute('data-theme'))
+ .catch(() => null)
+ // THEME_MODE_OPTIONS order is [{ dark }, { light }] -> dark=index 0, light=index 1.
+ const targetIndex = currentTheme === 'dark' ? 1 : 0
+ await themeRadios.nth(targetIndex).check({ force: true })
+ await expect(page.getByTestId('nav-settings-menu')).toBeVisible({ timeout: 20_000 })
+ // Best-effort restore so the recording leaves theme prefs stable.
+ await themeRadios
+ .nth(currentTheme === 'dark' ? 0 : 1)
+ .check({ force: true })
+ .catch(() => undefined)
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-settings-appearance')
+
+ // (2) Notifications — assert the In App Notifications panel rendered, then
+ // adjust the alert volume via the number input if present and confirm no crash.
+ await visitSettingsTab(page, 'Notifications', 'In App Notifications')
+ await expect(
+ page.getByRole('heading', { name: 'In App Notifications', exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+
+ const volumeNumber = page.getByRole('spinbutton', {
+ name: 'Notification sound volume percentage',
+ })
+ if (await volumeNumber.isVisible().catch(() => false)) {
+ // fill() fires the local onChange only (no blur -> no preview sound).
+ await volumeNumber.fill('40').catch(() => undefined)
+ }
+ // Assert the alert-volume surface still renders (no crash from the adjust).
+ await expect(page.getByText('Alert volume').first()).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-settings-notifications')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
+
+test('optional QA recorder: Desktop settings journey — information and configuration', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openSettings(page)
+
+ // (3) Information / Configuration — assert the active endpoint and the app
+ // version rows are shown (read-only). No data-testid current-version exists,
+ // so assert on the rendered "External REST API URL" / "Desktop app version" rows.
+ await visitSettingsTab(page, 'Information', 'External REST API URL')
+ const panel = page.getByRole('tabpanel')
+ await expect(panel.getByText('External REST API URL')).toBeVisible({ timeout: 20_000 })
+ await expect(panel.getByText('Desktop app version')).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-settings-information')
+
+ // (4, OPTIONAL + gated) Exercise the desktop endpoint switcher surface, which
+ // logs out to the AuthPage environment selector. Runs ONLY when opted in via
+ // QA_RECORDER_CONFIRM_MUTATIONS=1; otherwise the read-only configuration view
+ // above is the whole journey. The custom-endpoint form is exercised by filling
+ // its fields and then going back — no destructive switch to an unknown host.
+ if (process.env.QA_RECORDER_CONFIRM_MUTATIONS === '1') {
+ requireRecorderConfirm(
+ 'QA_RECORDER_CONFIRM_MUTATIONS',
+ 'This step opens the desktop endpoint switcher and logs out.'
+ )
+
+ const settingsMenu = page.getByTestId('nav-settings-menu')
+ if ((await settingsMenu.getAttribute('aria-expanded')) !== 'true') {
+ await settingsMenu.click().catch(() => undefined)
+ }
+ const logoutBtn = page
+ .getByTestId('logout-btn')
+ .or(page.getByRole('button', { name: /^Logout$/ }))
+ await expect(logoutBtn).toBeVisible({ timeout: 15_000 })
+ await logoutBtn.click()
+
+ // AuthPage rendered.
+ await expect(page.locator('#email-input')).toBeVisible({ timeout: 20_000 })
+
+ // Open the environment selector (the endpoint switch surface).
+ const envToggle = page.getByRole('button', { name: 'Open environment selector' })
+ await expect(envToggle).toBeVisible({ timeout: 20_000 })
+ await envToggle.click()
+ await expect(page.locator('#auth-runtime-dock-panel')).toBeVisible({ timeout: 15_000 })
+
+ // Exercise the custom-endpoint form: add-environment, fill name + URL, then
+ // cancel. No submit -> no persisted endpoint change.
+ const addEnvBtn = page.getByRole('button', { name: 'Add environment' })
+ if (await addEnvBtn.isVisible().catch(() => false)) {
+ await addEnvBtn.click()
+ const nameInput = page.locator('#runtime-config-name-input')
+ const urlInput = page.locator('#runtime-config-external-rest-api-input')
+ if (await nameInput.isVisible().catch(() => false)) {
+ await nameInput.fill('QA recorder probe').catch(() => undefined)
+ }
+ if (await urlInput.isVisible().catch(() => false)) {
+ await urlInput.fill(EXTERNAL_REST_API_BASE_URL).catch(() => undefined)
+ }
+ await page
+ .getByRole('button', { name: /^Go back to login$/ })
+ .click()
+ .catch(() => undefined)
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-settings-endpoint-switcher')
+ } else {
+ // eslint-disable-next-line no-console
+ console.log(
+ '[qa-recorder] Endpoint switch omitted (set QA_RECORDER_CONFIRM_MUTATIONS=1 to exercise it).'
+ )
+ }
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts
new file mode 100644
index 000000000..cb64be2d3
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts
@@ -0,0 +1,115 @@
+// desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts
+//
+// Optional QA recorder journey: Desktop shared files browser.
+//
+// Read-only browse of Resources -> Files (the GFS "Shared with me" browser
+// shell rendered by FilesPage). The journey proves the shell renders, that
+// opening a directory row does not crash the page, that the breadcrumb root
+// returns to the shared root, and that the download affordance is present —
+// without ever triggering a real native save dialog. It is resilient to
+// empty/loading/error states and only hard-asserts on the shell, which always
+// exists for an authenticated user.
+//
+// Contract: docs/testing/optional-playwright-qa-recorder.md ("Extending the
+// recorder"). This journey performs NO writes, messages, or paid calls, so it
+// needs no confirmation flag — but it still guards both target URLs up front.
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openResourcesNavItem,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+test('optional QA recorder: Desktop shared files browser journey', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openResourcesNavItem(page, 'nav-files')
+
+ // (1) Shell proof — the Files page heading and the GFS browser card always
+ // render for an authenticated user, regardless of how much is shared.
+ const filesHeading = page.getByRole('heading', { name: 'Files', exact: true })
+ const browserCard = page.locator('.da-gfs-drive')
+ await expect(filesHeading).toBeVisible({ timeout: 20_000 })
+ await expect(browserCard).toBeVisible({ timeout: 20_000 })
+
+ // Resilient content check: the card shows a loading state, an empty state
+ // (root or folder), or a populated resource grid. At least one must hold.
+ const loadingFiles = page.getByText('Loading files…', { exact: true })
+ const emptyRoot = page.getByText('No shared files yet', { exact: true })
+ const emptyFolder = page.getByText('This folder is empty', { exact: true })
+ const anyRow = page.locator('.da-gfs-drive__grid .da-grid__row').first()
+ await expect(loadingFiles.or(emptyRoot).or(emptyFolder).or(anyRow)).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // The "Open GFS link" affordance lives in the card header and is always
+ // present — a stable proof that the browse/open affordances rendered.
+ await expect(page.getByRole('button', { name: 'Open GFS link', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+
+ // Download affordance: when a file row is present it exposes a Download
+ // button. We only assert its presence — we never click it, because the
+ // native save dialog is not reliably drivable in the recorder.
+ const fileRow = page
+ .locator('.da-gfs-drive__grid .da-grid__row')
+ .filter({ has: page.locator('.da-gfs-drive__type', { hasText: 'File' }) })
+ .first()
+ if (await fileRow.isVisible().catch(() => false)) {
+ await expect(fileRow.getByRole('button', { name: /Download / })).toBeVisible({
+ timeout: 20_000,
+ })
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-shared-files-root')
+
+ // (2) If a directory row is present, open it and assert no crash.
+ const folderRow = page
+ .locator('.da-gfs-drive__grid .da-grid__row')
+ .filter({ has: page.locator('.da-gfs-drive__type', { hasText: 'Folder' }) })
+ .first()
+ if (await folderRow.isVisible().catch(() => false)) {
+ await folderRow.locator('.da-gfs-list__name button').first().click()
+
+ // After navigation the card either loads, lists the folder contents, or
+ // reports the folder is empty. The shell itself stays mounted (no crash).
+ const insideLoading = page.getByText('Loading files…', { exact: true })
+ const insideEmpty = page.getByText('This folder is empty', { exact: true })
+ const insideRow = page.locator('.da-gfs-drive__grid .da-grid__row').first()
+ await expect(insideLoading.or(insideEmpty).or(insideRow)).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(filesHeading).toBeVisible({ timeout: 20_000 })
+ await expect(browserCard).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'desktop-shared-files-inside')
+
+ // (3) Navigate back via the breadcrumb root ("Shared with me") and assert
+ // the shell is still mounted.
+ await page.getByRole('button', { name: 'Shared with me', exact: true }).click()
+ await expect(filesHeading).toBeVisible({ timeout: 20_000 })
+ await expect(browserCard).toBeVisible({ timeout: 20_000 })
+ await screenshotAndLog(page, testInfo, 'desktop-shared-files-back')
+ }
+
+ await screenshotAndLog(page, testInfo, 'desktop-shared-files')
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts
new file mode 100644
index 000000000..fb763d762
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts
@@ -0,0 +1,95 @@
+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+import {
+ EXTERNAL_REST_API_BASE_URL,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ finalizeRecording,
+ launchDesktopApp,
+ login,
+ openResourcesNavItem,
+ screenshotAndLog,
+} from './qa-recorder-helpers'
+
+// Read-only journey: Resources -> Teams directory, then a team detail.
+// No chat, no writes, no paid calls — so no confirm flag is required. The
+// loopback + health guard still runs for both targets.
+test('optional QA recorder: Desktop teams journey', async ({}, testInfo) => {
+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ const credentials = desktopCredentials()
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+
+ try {
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+
+ await login(page, credentials)
+ await openResourcesNavItem(page, 'nav-teams')
+
+ // (1) Teams directory shell renders.
+ const teamsHeading = page.getByRole('heading', { name: 'Members & Teams', exact: true })
+ await expect(teamsHeading).toBeVisible({ timeout: 20_000 })
+ await expect(page.locator('.teams-board-card')).toBeVisible({ timeout: 20_000 })
+
+ // The shell is proven as soon as ANY directory state renders. Wait for a
+ // known fixture row OR an explicit empty / loading / error state. Resilient
+ // to loading, empty, and error seeds — we only hard-assert on fixture
+ // identities we know exist (dev team, The Golden Kingdom).
+ const devTeamRow = page.locator('.da-table__row--clickable', { hasText: 'dev team' })
+ const goldenRow = page.locator('.da-table__row--clickable', { hasText: 'The Golden Kingdom' })
+ const emptyState = page.getByRole('heading', { name: 'No teams', exact: true })
+ const loadingState = page.getByText('Fetching teams and members...')
+ const errorBox = page.locator('.teams-board-card .composer-error')
+ await expect(
+ devTeamRow.or(goldenRow).or(emptyState).or(loadingState).or(errorBox).first()
+ ).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-teams-directory')
+
+ // (2) Settle to a terminal state (rows / empty / error) — not the transient
+ // loading state — before deciding whether a known fixture row is present to
+ // open. Skip-with-success when no fixture row is present; the directory
+ // shell assertions above already prove the journey for empty/error seeds.
+ await expect(devTeamRow.or(goldenRow).or(emptyState).or(errorBox).first()).toBeVisible({
+ timeout: 20_000,
+ })
+
+ const targetRow = (await devTeamRow.isVisible().catch(() => false))
+ ? devTeamRow
+ : (await goldenRow.isVisible().catch(() => false))
+ ? goldenRow
+ : null
+
+ if (targetRow) {
+ const targetName = targetRow === devTeamRow ? 'dev team' : 'The Golden Kingdom'
+
+ // Click the team-name span (plain text) to avoid the member avatar
+ // buttons in the Members cell, which stop propagation.
+ await targetRow.locator('.team-list-name').click()
+
+ // Detail shell + the team's own heading render.
+ await expect(
+ page.getByRole('heading', { name: targetName, exact: true, level: 3 })
+ ).toBeVisible({ timeout: 20_000 })
+
+ // The three detail tabs render (Members / Contexts / Agents).
+ const tabsNav = page.locator('.team-tabs')
+ await expect(tabsNav).toBeVisible({ timeout: 20_000 })
+ await expect(tabsNav.getByRole('button', { name: 'Members', exact: true })).toBeVisible()
+ await expect(tabsNav.getByRole('button', { name: 'Contexts', exact: true })).toBeVisible()
+ await expect(tabsNav.getByRole('button', { name: 'Agents', exact: true })).toBeVisible()
+
+ // Default tab is Members; its panel must render (member table or an
+ // explicit "No members" empty state).
+ await expect(page.locator('.team-resource-list').first()).toBeVisible({ timeout: 20_000 })
+
+ await screenshotAndLog(page, testInfo, 'desktop-team-detail')
+ }
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/desktop-app/test/e2e-playwright/workflow-agent-chat-gfs-runtime-grants.test.ts b/desktop-app/test/e2e-playwright/workflow-agent-chat-gfs-runtime-grants.test.ts
new file mode 100644
index 000000000..378cd3c42
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/workflow-agent-chat-gfs-runtime-grants.test.ts
@@ -0,0 +1,258 @@
+import { type Page, expect, test } from '@playwright/test'
+import {
+ assertGfsFixtureCleaned,
+ cleanupGfsFixture,
+ getGfsChildResourceSummary,
+ getGfsGrantSummary,
+ seedGfsFileFixture,
+ seedGfsGrant,
+ uniqueGfsFixtureName,
+} from '../../../tests/e2e/gfsUiFixtures'
+import { cleanupGfsWorkflowRunsAfter } from './workflowAgentChatGfsCleanup'
+import {
+ expectDurableGfsGrantUsage,
+ waitForWorkflowRunSucceeded,
+ workflowRunInfraState,
+} from './workflowAgentChatGfsRunState'
+import {
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+ GFS_PLUGIN_SUBJECT_ID,
+ expectWorkflowGfsProbeResult,
+ gfsWorkflowRunsAfter,
+ listGfsWorkflowRuns,
+ waitForGfsRunScopedRuntime,
+} from './workflowAgentChatGfsRuntime'
+import {
+ approvalPromptFor,
+ approveWorkflowNotification,
+ captureE2eEvidence,
+ enterChatllmChat,
+ expandResponseToolDetails,
+ expectNoOperationalIds,
+ runWorkflowFromChat,
+ sendChatPromptWithModelRescue,
+ startFreshThread,
+ waitForWorkflowRecipeActive,
+} from './workflowAgentChatTools'
+import { sendChatPromptAndApproveToolCallsUntilText } from './workflowChatMultiToolApproval'
+import { E2E_EMAIL, launchAndLogin, loginAs, rendererListWorkflowRuns } from './workflowUi'
+
+async function waitForChatRunExecution(
+ page: Page,
+ baselineIds: ReadonlySet<string>,
+ userId: string
+): Promise<{ childName: string; runId: string }> {
+ let match: Awaited<ReturnType<typeof rendererListWorkflowRuns>>['items'][number] | undefined
+ await expect
+ .poll(
+ async () => {
+ const newRuns = gfsWorkflowRunsAfter(baselineIds)
+ if (newRuns.length !== 1 || !newRuns[0]?.childName) return null
+ const runs = await rendererListWorkflowRuns(
+ page,
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+ 20
+ )
+ match = runs.items.find(run => run.id === newRuns[0]!.runId && run.executionRef?.name)
+ return match?.executionRef?.name ?? null
+ },
+ {
+ timeout: 90_000,
+ intervals: [500, 1_000, 2_000],
+ message: `Agent Chat should create exactly one new child-backed run for ${GFS_PLUGIN_RECIPE}`,
+ }
+ )
+ .not.toBeNull()
+
+ expect(match).toBeTruthy()
+ expect(gfsWorkflowRunsAfter(baselineIds)).toHaveLength(1)
+ expect(match!.actor).toMatchObject({ type: 'user-session', userId })
+ expect(['Pending', 'Running']).toContain(match!.phase)
+ expect(match!.executionRef).toMatchObject({ namespace: GFS_PLUGIN_NAMESPACE })
+ return { childName: match!.executionRef!.name, runId: match!.id }
+}
+
+test.describe.serial('Agent Chat WorkflowRecipe GFS runtime grants', () => {
+ test('triggers the exact third-party recipe from Desktop Chat and inherits its folder read/write grant in the run-scoped mcp-host', async ({}, testInfo) => {
+ test.setTimeout(1_200_000)
+ test.info().annotations.push({
+ type: 'e2e-contract',
+ description:
+ 'The workflow must be discovered and triggered through visible Desktop Agent Chat. Its host receives one inheritable grant on the parent folder and no direct grant on the child file. The chat response is not proof by itself: the test independently binds the one new user-session run to its exact child and proves that its ordered agentic steps performed real GFS read/stat/write/read-back operations from the run-scoped mcp-host, with durable audit and final-resource validation. Direct API triggering, kubectl-exec tool shortcuts, and fleet-wide parent runtimes are forbidden.',
+ })
+
+ const fixtureName = uniqueGfsFixtureName('e2e-gfs-desktop-chat-grant')
+ let fixture: ReturnType<typeof seedGfsFileFixture> | undefined
+ let childName: string | undefined
+ let runId: string | undefined
+ let app: Awaited<ReturnType<typeof launchAndLogin>>['app'] | undefined
+ const baselineRunIds = new Set(listGfsWorkflowRuns().map(run => run.runId))
+
+ try {
+ await waitForWorkflowRecipeActive(GFS_PLUGIN_RECIPE)
+ const { userId } = await loginAs(E2E_EMAIL)
+ fixture = seedGfsFileFixture(fixtureName)
+ seedGfsGrant({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ permissions: ['read', 'write'],
+ inherit: true,
+ grantedBy: 'e2e:desktop-chat-precondition',
+ })
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ })
+ ).toMatchObject({
+ permissions: ['read', 'write'],
+ inherit: true,
+ grantedBy: 'e2e:desktop-chat-precondition',
+ })
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ })
+ ).toBeNull()
+ const initialResource = getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: fixture.fileName,
+ })
+ expect(initialResource).not.toBeNull()
+ const updatedContent = `Desktop Chat third-party workflow updated ${fixture.fileName}`
+
+ const launched = await launchAndLogin(E2E_EMAIL)
+ app = launched.app
+ const { page } = launched
+ await enterChatllmChat(page)
+ await startFreshThread(page)
+ await expect(page.getByRole('button', { name: /^Workflows$/i })).toHaveCount(0)
+ await captureE2eEvidence(page, testInfo, 'gfs-chat-ready-no-workflow-shortcut')
+
+ const listResponse = await sendChatPromptWithModelRescue(
+ page,
+ 'What workflow recipes can I run? List the exact recipe names and required business inputs.'
+ )
+ await expandResponseToolDetails(listResponse)
+ await expect(listResponse).toContainText(GFS_PLUGIN_RECIPE, { timeout: 180_000 })
+ await expectNoOperationalIds(listResponse)
+ await captureE2eEvidence(page, testInfo, 'gfs-workflow-discovered-in-chat')
+
+ const triggerResponse = await runWorkflowFromChat(
+ page,
+ GFS_PLUGIN_RECIPE,
+ [
+ `${approvalPromptFor(GFS_PLUGIN_RECIPE)} now.`,
+ 'Use the workflow recipe trigger available in this chat.',
+ 'When the approval request appears, wait for me to approve it in this app and then continue.',
+ `Pass these exact business inputs: resourceId=${fixture.fileResourceId} and updatedContent=${JSON.stringify(updatedContent)}.`,
+ 'After it starts, do not request results or approve the workflow step; leave the run active.',
+ ].join(' ')
+ )
+ await expandResponseToolDetails(triggerResponse)
+ await expect(triggerResponse).toContainText(/workflow/i, { timeout: 300_000 })
+ await expect(triggerResponse).toContainText(/approved|started|triggered|run/i, {
+ timeout: 300_000,
+ })
+ await expect(triggerResponse).not.toContainText(/workflow tool failed|broker request failed/i)
+ await expectNoOperationalIds(triggerResponse)
+ await captureE2eEvidence(page, testInfo, 'gfs-workflow-triggered-from-chat')
+
+ const execution = await waitForChatRunExecution(page, baselineRunIds, userId)
+ runId = execution.runId
+ childName = execution.childName
+ await waitForGfsRunScopedRuntime(runId, childName, {
+ resourceId: fixture.fileResourceId,
+ updatedContent,
+ })
+
+ await test.step('the user approves the held workflow step and infra waits for completion', async () => {
+ await approveWorkflowNotification(page, GFS_PLUGIN_RECIPE)
+ await waitForWorkflowRunSucceeded(runId!, childName!)
+ })
+
+ const resultResponse = await sendChatPromptAndApproveToolCallsUntilText(
+ page,
+ [
+ `Check the final status of ${GFS_PLUGIN_RECIPE}.`,
+ 'Use workflow_status for the workflow I just started from this chat.',
+ 'Tell me whether it completed successfully; do not trigger another run.',
+ ].join(' '),
+ [/Succeeded/i],
+ 420_000,
+ { requiredText: [/workflow_status/i], forbiddenText: [/workflow_trigger/i] }
+ )
+ await expandResponseToolDetails(resultResponse)
+ await expect(resultResponse).toContainText(/Succeeded|completed successfully/i)
+ await captureE2eEvidence(page, testInfo, 'gfs-workflow-completed-visible-in-chat')
+
+ expect(gfsWorkflowRunsAfter(baselineRunIds)).toEqual([
+ { childName: childName!, runId: runId! },
+ ])
+ expect(workflowRunInfraState(runId!)).toEqual({ childName: childName!, phase: 'Succeeded' })
+ await expectWorkflowGfsProbeResult({
+ childName: childName!,
+ fileResourceId: fixture.fileResourceId,
+ fileUri: fixture.fileUri,
+ initialContent: `E2E GFS file fixture: ${fixture.name}\n`,
+ runId: runId!,
+ updatedContent,
+ })
+ expectDurableGfsGrantUsage(fixture.fileUri)
+ expect(
+ getGfsChildResourceSummary({
+ parentResourceId: fixture.resourceId,
+ name: fixture.fileName,
+ })
+ ).toMatchObject({
+ bytes: Buffer.byteLength(updatedContent),
+ version: initialResource!.version + 1,
+ })
+ await captureE2eEvidence(page, testInfo, 'gfs-run-scoped-runtime-read-write-proven')
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ })
+ ).toMatchObject({ permissions: ['read', 'write'], inherit: true })
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ })
+ ).toBeNull()
+ } finally {
+ if (app) await app.close()
+ try {
+ await cleanupGfsWorkflowRunsAfter(baselineRunIds)
+ } finally {
+ cleanupGfsFixture(fixtureName)
+ assertGfsFixtureCleaned(fixtureName)
+ if (fixture) {
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.resourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ })
+ ).toBeNull()
+ expect(
+ getGfsGrantSummary({
+ resourceId: fixture.fileResourceId,
+ subjectType: 'host',
+ subjectId: GFS_PLUGIN_SUBJECT_ID,
+ })
+ ).toBeNull()
+ }
+ }
+ }
+ })
+})
diff --git a/desktop-app/test/e2e-playwright/workflowAgentChatGfsCleanup.ts b/desktop-app/test/e2e-playwright/workflowAgentChatGfsCleanup.ts
new file mode 100644
index 000000000..ab3c915a6
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/workflowAgentChatGfsCleanup.ts
@@ -0,0 +1,239 @@
+import { expect } from '@playwright/test'
+import {
+ UUID_RE,
+ firstDataLine,
+ runControlPostgresSql,
+ sqlLiteral,
+} from '../../../tests/e2e/gfsUiFixtures'
+import {
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+ gfsWorkflowRunsAfter,
+} from './workflowAgentChatGfsRuntime'
+import { kubectl } from './workflowAgentChatTools'
+
+type WorkflowRecipeMetadata = {
+ labels?: Record<string, string>
+ name?: string
+ namespace?: string
+ ownerReferences?: Array<{
+ apiVersion?: string
+ controller?: boolean
+ kind?: string
+ name?: string
+ uid?: string
+ }>
+ uid?: string
+}
+
+type WorkflowRecipeResource = { metadata?: WorkflowRecipeMetadata }
+
+// Covers one 25s Kubernetes delete, late-child observation, and the required
+// 10s quiet window within the enclosing 900s Desktop journey budget.
+const CLEANUP_TIMEOUT_MS = 75_000
+const LATE_CHILD_QUIET_WINDOW_MS = 10_000
+
+function workflowRecipeOrUndefined(name: string): WorkflowRecipeResource | undefined {
+ const raw = kubectl(
+ [
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ name,
+ '--ignore-not-found=true',
+ '-o',
+ 'json',
+ ],
+ undefined,
+ 20_000
+ ).trim()
+ return raw ? (JSON.parse(raw) as WorkflowRecipeResource) : undefined
+}
+
+function isVerifiedRunChild(
+ child: WorkflowRecipeResource,
+ input: { childName: string; parentUid: string; runId: string }
+): boolean {
+ const owners = child.metadata?.ownerReferences ?? []
+ const owner = owners[0]
+ return (
+ child.metadata?.name === input.childName &&
+ child.metadata?.namespace === GFS_PLUGIN_NAMESPACE &&
+ child.metadata?.labels?.['clerum.io/workflow-run-id'] === input.runId &&
+ child.metadata?.labels?.['clerum.io/parent-recipe'] === GFS_PLUGIN_RECIPE &&
+ owners.length === 1 &&
+ owner?.controller === true &&
+ owner.apiVersion === 'clerum.io/v1alpha1' &&
+ owner.kind === 'WorkflowRecipe' &&
+ owner.name === GFS_PLUGIN_RECIPE &&
+ owner.uid === input.parentUid
+ )
+}
+
+function namesByLabel(namespace: string, resources: string, selector: string): string[] {
+ return kubectl(
+ ['-n', namespace, 'get', resources, '-l', selector, '-o', 'name'],
+ undefined,
+ 20_000
+ )
+ .split('\n')
+ .map(value => value.trim())
+ .filter(Boolean)
+ .sort()
+}
+
+function runChildNames(runId: string): string[] {
+ return namesByLabel(GFS_PLUGIN_NAMESPACE, 'workflowrecipe', `clerum.io/workflow-run-id=${runId}`)
+}
+
+function deleteVerifiedRunChildren(
+ runId: string,
+ candidateNames: string[]
+): { deleted: number; names: string[] } {
+ const parentUid = workflowRecipeOrUndefined(GFS_PLUGIN_RECIPE)?.metadata?.uid ?? ''
+ const discoveredNames = runChildNames(runId).map(name => name.slice(name.indexOf('/') + 1))
+ const names = [...new Set([...candidateNames, ...discoveredNames])]
+ let deleted = 0
+
+ for (const childName of names) {
+ if (childName === GFS_PLUGIN_RECIPE) {
+ throw new Error(`Refusing to clean parent WorkflowRecipe for run ${runId}`)
+ }
+ const child = workflowRecipeOrUndefined(childName)
+ if (!child) continue
+ if (!parentUid || !isVerifiedRunChild(child, { childName, parentUid, runId })) {
+ throw new Error(
+ `Refusing to delete unverified workflow child ${GFS_PLUGIN_NAMESPACE}/${childName} for run ${runId}`
+ )
+ }
+ kubectl(
+ [
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'delete',
+ 'workflowrecipe',
+ childName,
+ '--wait=true',
+ '--timeout=25s',
+ ],
+ undefined,
+ CLEANUP_TIMEOUT_MS
+ )
+ deleted += 1
+ }
+ return { deleted, names }
+}
+
+function leakedRuntimeResources(candidateNames: string[], runId: string) {
+ const childNames = runChildNames(runId).map(name => name.slice(name.indexOf('/') + 1))
+ const names = [...new Set([...candidateNames, ...childNames])]
+ const sandboxResources = names.flatMap(name =>
+ namesByLabel(
+ GFS_PLUGIN_NAMESPACE,
+ 'pod,service,secret,networkpolicy,configmap,persistentvolumeclaim',
+ `clerum.io/recipe=${name}`
+ )
+ )
+ const transportResources = names.flatMap(name =>
+ namesByLabel(
+ 'mcp-server',
+ 'mcpserver,context,service,deployment,secret',
+ `clerum.io/recipe=${name}`
+ )
+ )
+ return {
+ childRecipes: runChildNames(runId),
+ sandboxResources: [...new Set(sandboxResources)].sort(),
+ transportResources: [...new Set(transportResources)].sort(),
+ }
+}
+
+async function cleanupGfsWorkflowRun(
+ runId: string,
+ observedChildName: string | undefined
+): Promise<void> {
+ if (!UUID_RE.test(runId)) return
+
+ const persistedChildName = firstDataLine(
+ runControlPostgresSql(`
+ UPDATE workflow_runs
+ SET phase = 'Canceled', completed_at = COALESCE(completed_at, now()), updated_at = now()
+ WHERE run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(GFS_PLUGIN_RECIPE)}
+ RETURNING child_recipe_name;
+ `)
+ )
+ let candidates = [...new Set([observedChildName, persistedChildName].filter(Boolean))] as string[]
+
+ let lastChildActivityAt = Date.now()
+ await expect
+ .poll(
+ () => {
+ const cleanup = deleteVerifiedRunChildren(runId, candidates)
+ candidates = cleanup.names
+ if (cleanup.deleted > 0) lastChildActivityAt = Date.now()
+ return {
+ ...leakedRuntimeResources(candidates, runId),
+ quietWindowElapsed: Date.now() - lastChildActivityAt >= LATE_CHILD_QUIET_WINDOW_MS,
+ }
+ },
+ {
+ timeout: CLEANUP_TIMEOUT_MS,
+ intervals: [500, 1_000, 2_000],
+ message: `workflow run ${runId} should stop creating children after cancellation`,
+ }
+ )
+ .toEqual({
+ childRecipes: [],
+ sandboxResources: [],
+ transportResources: [],
+ quietWindowElapsed: true,
+ })
+
+ runControlPostgresSql(`
+ DELETE FROM workflow_approval_requests
+ WHERE bound_workflow_run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(GFS_PLUGIN_RECIPE)};
+ DELETE FROM workflow_runs
+ WHERE run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(GFS_PLUGIN_RECIPE)};
+ `)
+
+ expect(leakedRuntimeResources(candidates, runId)).toEqual({
+ childRecipes: [],
+ sandboxResources: [],
+ transportResources: [],
+ })
+
+ expect(
+ firstDataLine(
+ runControlPostgresSql(`
+ SELECT
+ (SELECT COUNT(*) FROM workflow_approval_requests
+ WHERE bound_workflow_run_id = ${sqlLiteral(runId)}::uuid)::text || '|' ||
+ (SELECT COUNT(*) FROM workflow_run_steps
+ WHERE run_id = ${sqlLiteral(runId)}::uuid)::text || '|' ||
+ (SELECT COUNT(*) FROM workflow_runs
+ WHERE run_id = ${sqlLiteral(runId)}::uuid)::text;
+ `)
+ )
+ ).toBe('0|0|0')
+}
+
+export async function cleanupGfsWorkflowRunsAfter(baselineIds: ReadonlySet<string>): Promise<void> {
+ const errors: unknown[] = []
+ for (const run of gfsWorkflowRunsAfter(baselineIds)) {
+ try {
+ await cleanupGfsWorkflowRun(run.runId, run.childName || undefined)
+ } catch (error) {
+ errors.push(error)
+ }
+ }
+ if (errors.length > 0) {
+ throw new AggregateError(errors, 'failed to clean every new GFS workflow run')
+ }
+}
diff --git a/desktop-app/test/e2e-playwright/workflowAgentChatGfsRunState.ts b/desktop-app/test/e2e-playwright/workflowAgentChatGfsRunState.ts
new file mode 100644
index 000000000..298ae8566
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/workflowAgentChatGfsRunState.ts
@@ -0,0 +1,58 @@
+import { expect } from '@playwright/test'
+import {
+ firstDataLine,
+ runControlPostgresSql,
+ splitSqlRow,
+ sqlLiteral,
+} from '../../../tests/e2e/gfsUiFixtures'
+import {
+ GFS_PLUGIN_NAMESPACE,
+ GFS_PLUGIN_RECIPE,
+ GFS_PLUGIN_SUBJECT_ID,
+} from './workflowAgentChatGfsRuntime'
+
+const GFS_PLUGIN_RUNTIME_SUBJECT = `host:${GFS_PLUGIN_SUBJECT_ID}`
+
+export function workflowRunInfraState(runId: string): { childName: string; phase: string } {
+ const row = firstDataLine(
+ runControlPostgresSql(`
+ SELECT phase || '|' || coalesce(child_recipe_name, '')
+ FROM workflow_runs
+ WHERE run_id = ${sqlLiteral(runId)}::uuid
+ AND recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(GFS_PLUGIN_RECIPE)};
+ `)
+ )
+ const [phase = '', childName = ''] = splitSqlRow(row)
+ return { childName, phase }
+}
+
+export async function waitForWorkflowRunSucceeded(runId: string, childName: string): Promise<void> {
+ await expect
+ .poll(() => workflowRunInfraState(runId), {
+ timeout: 600_000,
+ intervals: [1_000, 2_000, 5_000],
+ message: `infra should observe ${runId} reach Succeeded`,
+ })
+ .toEqual({ childName, phase: 'Succeeded' })
+}
+
+export function expectDurableGfsGrantUsage(fileUri: string): void {
+ const auditRows = runControlPostgresSql(`
+ SELECT op || '|' || outcome || '|' || count(*)::text
+ FROM gfs_audit
+ WHERE subject = ${sqlLiteral(GFS_PLUGIN_RUNTIME_SUBJECT)}
+ AND gfs_uri = ${sqlLiteral(fileUri)}
+ GROUP BY op, outcome
+ ORDER BY op, outcome;
+ `)
+ .split('\n')
+ .map(line => line.trim())
+ .filter(Boolean)
+ .map(splitSqlRow)
+ const allowed = new Map(
+ auditRows.map(([op, outcome, count]) => [`${op}:${outcome}`, Number(count)])
+ )
+ expect(allowed.get('read:allow') ?? 0).toBeGreaterThanOrEqual(2)
+ expect(allowed.get('write:allow') ?? 0).toBeGreaterThanOrEqual(1)
+}
diff --git a/desktop-app/test/e2e-playwright/workflowAgentChatGfsRuntime.ts b/desktop-app/test/e2e-playwright/workflowAgentChatGfsRuntime.ts
new file mode 100644
index 000000000..0e8c93fe0
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/workflowAgentChatGfsRuntime.ts
@@ -0,0 +1,322 @@
+import { expect } from '@playwright/test'
+import {
+ firstDataLine,
+ runControlPostgresSql,
+ splitSqlRow,
+ sqlLiteral,
+} from '../../../tests/e2e/gfsUiFixtures'
+import { type WorkflowToolCall, singleSuccessfulToolCall } from './workflowAgentChatGfsToolCalls'
+import { kubectl } from './workflowAgentChatTools'
+
+export const GFS_PLUGIN_NAMESPACE = 'sandbox-recipes'
+export const GFS_PLUGIN_RECIPE = 'gfs-grant-e2e-plugin'
+export const GFS_PLUGIN_SUBJECT_ID = `3rd:${GFS_PLUGIN_NAMESPACE}/${GFS_PLUGIN_RECIPE}`
+
+type WorkflowRecipeResource = {
+ metadata?: {
+ name?: string
+ uid?: string
+ labels?: Record<string, string>
+ ownerReferences?: Array<{
+ apiVersion?: string
+ blockOwnerDeletion?: boolean
+ controller?: boolean
+ kind?: string
+ name?: string
+ uid?: string
+ }>
+ }
+ spec?: {
+ gfs?: { mounts?: Array<{ drive?: string; scopes?: string[]; target?: string }> }
+ inputs?: Record<string, unknown>
+ }
+ status?: {
+ steps?: Array<{
+ id?: string
+ phase?: string
+ toolsCalled?: Array<{
+ args?: Record<string, unknown>
+ result?: unknown
+ serverName?: string
+ toolName?: string
+ }>
+ }>
+ }
+}
+
+type ConfigMapResource = { data?: Record<string, string> }
+
+type PodList = {
+ items?: Array<{
+ metadata?: { name?: string; deletionTimestamp?: string }
+ status?: { conditions?: Array<{ type?: string; status?: string }> }
+ }>
+}
+
+export type GfsWorkflowRun = { childName: string; runId: string }
+
+function kubectlJson<T>(args: string[]): T {
+ return JSON.parse(kubectl([...args, '-o', 'json'], undefined, 20_000)) as T
+}
+
+function workflowPodState(
+ recipeName: string,
+ component: 'workflow-coordinator' | 'workflow-mcp-host'
+): { names: string[]; ready: boolean } {
+ const pods = kubectlJson<PodList>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'pod',
+ '-l',
+ `clerum.io/recipe=${recipeName},clerum.io/component=${component}`,
+ ])
+ const items = pods.items ?? []
+ return {
+ names: items.map(item => item.metadata?.name ?? '').filter(Boolean),
+ ready:
+ items.length === 1 &&
+ !items[0]?.metadata?.deletionTimestamp &&
+ items[0]?.status?.conditions?.some(
+ condition => condition.type === 'Ready' && condition.status === 'True'
+ ) === true,
+ }
+}
+
+function expectParentAndChild(
+ runId: string,
+ childName: string,
+ expectedInputs: { resourceId: string; updatedContent: string }
+): void {
+ const parent = kubectlJson<WorkflowRecipeResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ GFS_PLUGIN_RECIPE,
+ ])
+ const child = kubectlJson<WorkflowRecipeResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ childName,
+ ])
+ expect(parent.metadata?.uid).toBeTruthy()
+ expect(child.metadata?.labels).toMatchObject({
+ 'clerum.io/parent-recipe': GFS_PLUGIN_RECIPE,
+ 'clerum.io/workflow-run-id': runId,
+ })
+ expect(child.metadata?.ownerReferences).toEqual([
+ expect.objectContaining({
+ apiVersion: 'clerum.io/v1alpha1',
+ blockOwnerDeletion: true,
+ controller: true,
+ kind: 'WorkflowRecipe',
+ name: GFS_PLUGIN_RECIPE,
+ uid: parent.metadata!.uid,
+ }),
+ ])
+ expect(child.spec?.gfs?.mounts).toEqual([
+ {
+ drive: 'main',
+ target: 'e2e/gfs-grant-e2e-plugin',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ])
+ expect(child.spec?.inputs).toEqual(expectedInputs)
+ const workflowConfig = kubectlJson<ConfigMapResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'configmap',
+ `${childName}-workflow-config`,
+ ])
+ const config = JSON.parse(workflowConfig.data?.['config.json'] ?? '{}') as {
+ steps?: Array<{
+ allowedTools?: { include?: string[] }
+ dependsOn?: string[]
+ id?: string
+ maxIterations?: number
+ toolChoice?: string
+ }>
+ }
+ expect(config.steps).toEqual([
+ expect.objectContaining({
+ id: 'approval-held-gfs-read',
+ maxIterations: 3,
+ toolChoice: 'required',
+ allowedTools: { include: ['clerum__gfs_read'] },
+ }),
+ expect.objectContaining({
+ id: 'gfs-stat-probe',
+ dependsOn: ['approval-held-gfs-read'],
+ maxIterations: 3,
+ toolChoice: 'required',
+ allowedTools: { include: ['clerum__gfs_stat'] },
+ }),
+ expect.objectContaining({
+ id: 'gfs-write-probe',
+ dependsOn: ['gfs-stat-probe'],
+ maxIterations: 3,
+ toolChoice: 'required',
+ allowedTools: { include: ['clerum__gfs_write'] },
+ }),
+ expect.objectContaining({
+ id: 'read-back-gfs-probe',
+ dependsOn: ['gfs-write-probe'],
+ maxIterations: 3,
+ toolChoice: 'required',
+ allowedTools: { include: ['clerum__gfs_read'] },
+ }),
+ ])
+ expect(workflowPodState(GFS_PLUGIN_RECIPE, 'workflow-mcp-host').names).toEqual([])
+}
+
+export async function waitForGfsRunScopedRuntime(
+ runId: string,
+ childName: string,
+ expectedInputs: { resourceId: string; updatedContent: string }
+): Promise<string> {
+ expectParentAndChild(runId, childName, expectedInputs)
+ const pod = `${childName}-mcp-host`
+ await expect
+ .poll(() => workflowPodState(childName, 'workflow-mcp-host'), {
+ timeout: 60_000,
+ intervals: [1_000, 2_000, 5_000],
+ message: `run ${runId} should create exactly one Ready child mcp-host`,
+ })
+ .toEqual({ names: [pod], ready: true })
+ await expect
+ .poll(() => workflowPodState(childName, 'workflow-coordinator'), {
+ timeout: 90_000,
+ intervals: [1_000, 2_000, 5_000],
+ message: `run ${runId} should create exactly one Ready child coordinator`,
+ })
+ .toEqual({ names: [`${childName}-coordinator`], ready: true })
+ expect(workflowPodState(GFS_PLUGIN_RECIPE, 'workflow-mcp-host').names).toEqual([])
+ return pod
+}
+
+export function listGfsWorkflowRuns(): GfsWorkflowRun[] {
+ return runControlPostgresSql(`
+ SELECT run_id::text || '|' || coalesce(child_recipe_name, '')
+ FROM workflow_runs
+ WHERE recipe_namespace = ${sqlLiteral(GFS_PLUGIN_NAMESPACE)}
+ AND recipe_name = ${sqlLiteral(GFS_PLUGIN_RECIPE)}
+ ORDER BY created_at, run_id;
+ `)
+ .split('\n')
+ .map(line => line.trim())
+ .filter(Boolean)
+ .map(line => {
+ const [runId = '', childName = ''] = splitSqlRow(line)
+ return { runId, childName }
+ })
+ .filter(run => /^[0-9a-f-]{36}$/i.test(run.runId))
+}
+
+export function gfsWorkflowRunsAfter(baselineIds: ReadonlySet<string>): GfsWorkflowRun[] {
+ return listGfsWorkflowRuns().filter(run => !baselineIds.has(run.runId))
+}
+
+export async function expectWorkflowGfsProbeResult(input: {
+ childName: string
+ fileResourceId: string
+ fileUri: string
+ initialContent: string
+ runId: string
+ updatedContent: string
+}): Promise<void> {
+ const child = kubectlJson<WorkflowRecipeResource>([
+ '-n',
+ GFS_PLUGIN_NAMESPACE,
+ 'get',
+ 'workflowrecipe',
+ input.childName,
+ ])
+ const readStep = child.status?.steps?.find(step => step.id === 'approval-held-gfs-read')
+ const statStep = child.status?.steps?.find(step => step.id === 'gfs-stat-probe')
+ const writeStep = child.status?.steps?.find(step => step.id === 'gfs-write-probe')
+ const readBackStep = child.status?.steps?.find(step => step.id === 'read-back-gfs-probe')
+ expect(
+ readStep?.toolsCalled,
+ 'child WorkflowRecipe status must retain the initial read call'
+ ).toBeDefined()
+ expect(
+ statStep?.toolsCalled,
+ 'child WorkflowRecipe status must retain the stat call'
+ ).toBeDefined()
+ expect(
+ writeStep?.toolsCalled,
+ 'child WorkflowRecipe status must retain the write call'
+ ).toBeDefined()
+ expect(
+ readBackStep?.toolsCalled,
+ 'dependent read-back step must retain its real GFS read'
+ ).toBeDefined()
+ expect(readStep?.phase).toBe('completed')
+ expect(statStep?.phase).toBe('completed')
+ expect(writeStep?.phase).toBe('completed')
+ expect(readBackStep?.phase).toBe('completed')
+
+ const row = firstDataLine(
+ runControlPostgresSql(`
+ SELECT count(*)
+ FROM workflow_run_steps
+ WHERE run_id = ${sqlLiteral(input.runId)}::uuid
+ AND step_id IN (
+ 'approval-held-gfs-read',
+ 'gfs-stat-probe',
+ 'gfs-write-probe',
+ 'read-back-gfs-probe'
+ )
+ AND phase = 'Succeeded';
+ `)
+ )
+ const [succeededStepCount = ''] = splitSqlRow(row)
+ expect(succeededStepCount).toBe('4')
+ const toolCallFor = (step: typeof readStep) => {
+ return singleSuccessfulToolCall(step!.toolsCalled as WorkflowToolCall[])
+ }
+ const { rejected: rejectedReads, successful: readCall } = toolCallFor(readStep)
+ const { rejected: rejectedStats, successful: statCall } = toolCallFor(statStep)
+ const { rejected: rejectedWrites, successful: writeCall } = toolCallFor(writeStep)
+ expect(rejectedReads).toHaveLength(0)
+ expect(rejectedStats).toHaveLength(0)
+ expect(`${readCall.serverName}__${readCall.toolName}`).toBe('clerum__gfs_read')
+ expect(`${statCall.serverName}__${statCall.toolName}`).toBe('clerum__gfs_stat')
+ expect(`${writeCall.serverName}__${writeCall.toolName}`).toBe('clerum__gfs_write')
+ for (const tool of [readCall, statCall, writeCall]) {
+ expect(tool.args).toMatchObject({ drive: 'main', resourceId: input.fileResourceId })
+ }
+ expect(readCall.result?.content).toBe(input.initialContent)
+ const statEnvelope = JSON.parse(statCall.result!.content!) as {
+ ok?: boolean
+ data?: { gfsUri?: string; version?: number }
+ }
+ expect(statEnvelope).toMatchObject({ ok: true, data: { gfsUri: input.fileUri } })
+ expect(typeof statEnvelope.data?.version).toBe('number')
+ expect(writeCall.args).toMatchObject({
+ content: input.updatedContent,
+ ifMatch: statEnvelope.data!.version,
+ })
+ const writeEnvelope = JSON.parse(writeCall.result!.content!) as {
+ ok?: boolean
+ data?: { version?: number }
+ }
+ expect(writeEnvelope).toMatchObject({
+ ok: true,
+ data: { version: statEnvelope.data!.version! + 1 },
+ })
+ for (const retry of rejectedWrites) {
+ expect(`${retry.serverName}__${retry.toolName}`).toBe('clerum__gfs_write')
+ expect(retry.args).toEqual(writeCall.args)
+ expect(retry.result?.error).toContain('precondition_failed')
+ }
+ const { rejected: rejectedReadBacks, successful: readBackCall } = toolCallFor(readBackStep)
+ expect(rejectedReadBacks).toHaveLength(0)
+ expect(`${readBackCall.serverName}__${readBackCall.toolName}`).toBe('clerum__gfs_read')
+ expect(readBackCall.args).toMatchObject({ drive: 'main', resourceId: input.fileResourceId })
+ expect(readBackCall.result).toMatchObject({ success: true, content: input.updatedContent })
+}
diff --git a/desktop-app/test/e2e-playwright/workflowAgentChatGfsToolCalls.ts b/desktop-app/test/e2e-playwright/workflowAgentChatGfsToolCalls.ts
new file mode 100644
index 000000000..8f648144b
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/workflowAgentChatGfsToolCalls.ts
@@ -0,0 +1,23 @@
+export type WorkflowToolCall = {
+ args?: Record<string, unknown>
+ result?: { content?: string; error?: string; success?: boolean }
+ serverName?: string
+ toolName?: string
+}
+
+export function singleSuccessfulToolCall(calls: WorkflowToolCall[]): {
+ rejected: WorkflowToolCall[]
+ successful: WorkflowToolCall
+} {
+ const successful = calls.filter(call => call.result?.success === true)
+ const rejected = calls.filter(call => call.result?.success === false)
+
+ if (successful.length !== 1) {
+ throw new Error(`expected exactly one successful tool call, received ${successful.length}`)
+ }
+ if (successful.length + rejected.length !== calls.length) {
+ throw new Error('every recorded tool call must have an explicit success result')
+ }
+
+ return { rejected, successful: successful[0]! }
+}
diff --git a/desktop-app/test/globalSetupGuard.test.ts b/desktop-app/test/globalSetupGuard.test.ts
index bc044c281..9b4c979a8 100644
--- a/desktop-app/test/globalSetupGuard.test.ts
+++ b/desktop-app/test/globalSetupGuard.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { validateBaseUrls } from './e2e-playwright/global-setup'
-const DEV_CONTEXT = 'gke_your-gcp-project_us-central1-a_example-dev'
+const DEV_CONTEXT = 'gke_${GCP_PROJECT}_us-central1-a_example-dev'
describe('validateBaseUrls', () => {
it('requires localhost for clerum-test', () => {
diff --git a/desktop-app/test/workflowAgentChatGfsToolCalls.test.ts b/desktop-app/test/workflowAgentChatGfsToolCalls.test.ts
new file mode 100644
index 000000000..c6cd00e5c
--- /dev/null
+++ b/desktop-app/test/workflowAgentChatGfsToolCalls.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { singleSuccessfulToolCall } from './e2e-playwright/workflowAgentChatGfsToolCalls'
+
+describe('singleSuccessfulToolCall', () => {
+ const success = { result: { success: true }, toolName: 'gfs_write' }
+ const rejected = {
+ result: { error: 'precondition_failed', success: false },
+ toolName: 'gfs_write',
+ }
+
+ it('returns one successful call and preserves rejected retries', () => {
+ expect(singleSuccessfulToolCall([success, rejected])).toEqual({
+ rejected: [rejected],
+ successful: success,
+ })
+ })
+
+ it('rejects multiple successful calls', () => {
+ expect(() => singleSuccessfulToolCall([success, success])).toThrow(
+ 'expected exactly one successful tool call, received 2'
+ )
+ })
+
+ it('rejects a result without one successful call', () => {
+ expect(() => singleSuccessfulToolCall([rejected])).toThrow(
+ 'expected exactly one successful tool call, received 0'
+ )
+ })
+
+ it('rejects ambiguous tool results', () => {
+ expect(() => singleSuccessfulToolCall([success, { toolName: 'gfs_write' }])).toThrow(
+ 'every recorded tool call must have an explicit success result'
+ )
+ })
+})
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 82a69b3c2..1259d2ded 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -10,6 +10,7 @@ import {
WorkspaceActionsProvider,
} from '@contexts/index'
import { AppHeader } from '@components/AppHeader'
+import { BootSplash } from '@components/BootSplash'
import { Button, ToastStack } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
import { SidebarNav } from '@components/SidebarNav'
@@ -613,141 +614,137 @@ export function App() {
/>
) : null
- if (vm.booting) {
- return (
- <main className="auth-page">
- <section className="auth-card glass-card">
- <h1>Evenfire</h1>
- <p className="muted">Loading session...</p>
- </section>
- </main>
- )
- }
-
- if (!vm.isAuthenticated) {
- return (
- <AuthContext.Provider value={authValue}>
- {vm.hasDependencyOutage ? <UnavailablePage /> : <AuthPage />}
- {environmentSetupConfirmationDialog}
- {environmentSetupSuccessDialog}
- <ToastStack items={vm.toasts} />
- </AuthContext.Provider>
- )
- }
+ const bootSplashLoading = vm.booting || vm.initialExperienceLoading
return (
<AuthContext.Provider value={authValue}>
- <NavigationContext.Provider value={navValue}>
- <NotificationsContext.Provider value={notifValue}>
- <WorkspaceActionsProvider value={workspaceActionsValue}>
- <AgentActivityProvider value={agentActivityValue}>
- <AgentChatProviders
- actions={agentChatActionsValue}
- chatList={chatListValue}
- composerState={chatComposerStateValue}
- threadState={chatThreadStateValue}
- >
- <McpRuntimeProvider value={mcpRuntimeValue}>
- <DesktopStateProvider value={desktopStateValue}>
- <main className="app-shell">
- <SidebarNav
- navItem={
- vm.navItem === DESKTOP_ROUTES.teamDetails
- ? DESKTOP_ROUTES.teams
- : vm.navItem === DESKTOP_ROUTES.contextDetails
- ? DESKTOP_ROUTES.contexts
- : vm.navItem
- }
- activeSandboxUiApp={activeSandboxUiApp}
- availableSandboxUiApps={availableSandboxUiApps}
- collapsed={sidebarCollapsed}
- onCollapsedChange={setSidebarCollapsed}
- onOpenSandboxUiApp={handleOpenSandboxUiApp}
- onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
- onSelect={vm.handleNavSelect}
- />
- <section className="workspace-layout">
- <section
- ref={contentPanelRef}
- className={`content-panel glass-card${
- isAgentChatView ? ' content-panel--agent-chat' : ''
- }${vm.navItem === DESKTOP_ROUTES.settings ? ' content-panel--settings' : ''}${
- appNotificationDrawerOpen
- ? ' content-panel--app-notification-drawer-open'
- : ''
- }`}
- >
- <AppHeader
- notificationTrayMode={notificationTrayUsesDrawer ? 'drawer' : 'overlay'}
- notificationTrayReady={notificationDrawerReady}
- onNotificationTrayOpenChange={setHeaderNotificationTrayOpen}
- onShellOverlayOpenChange={setHeaderShellOverlayOpen}
+ <div className="app-root" inert={bootSplashLoading || undefined}>
+ {vm.isAuthenticated ? (
+ <NavigationContext.Provider value={navValue}>
+ <NotificationsContext.Provider value={notifValue}>
+ <WorkspaceActionsProvider value={workspaceActionsValue}>
+ <AgentActivityProvider value={agentActivityValue}>
+ <AgentChatProviders
+ actions={agentChatActionsValue}
+ chatList={chatListValue}
+ composerState={chatComposerStateValue}
+ threadState={chatThreadStateValue}
+ >
+ <McpRuntimeProvider value={mcpRuntimeValue}>
+ <DesktopStateProvider value={desktopStateValue}>
+ <main className="app-shell">
+ <SidebarNav
+ navItem={
+ vm.navItem === DESKTOP_ROUTES.teamDetails
+ ? DESKTOP_ROUTES.teams
+ : vm.navItem === DESKTOP_ROUTES.contextDetails
+ ? DESKTOP_ROUTES.contexts
+ : vm.navItem
+ }
+ activeSandboxUiApp={activeSandboxUiApp}
+ availableSandboxUiApps={availableSandboxUiApps}
+ collapsed={sidebarCollapsed}
+ onCollapsedChange={setSidebarCollapsed}
+ onOpenSandboxUiApp={handleOpenSandboxUiApp}
+ onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
+ onSelect={vm.handleNavSelect}
/>
- <ToastStack items={vm.toasts} />
- {vm.navItem === DESKTOP_ROUTES.chat && (
- <ChatPage scrollContainerRef={contentPanelRef} />
- )}
- {vm.navItem === DESKTOP_ROUTES.agents && (
- <AgentsPage scrollContainerRef={contentPanelRef} />
- )}
- {vm.navItem === DESKTOP_ROUTES.contexts && <ContextsPage />}
- {vm.navItem === DESKTOP_ROUTES.files && (
- <FilesPage pushToast={vm.pushToast} />
- )}
- {vm.navItem === DESKTOP_ROUTES.connectors && <McpServersPage />}
- {vm.navItem === DESKTOP_ROUTES.contextDetails && <ContextDetailsPage />}
- {vm.navItem === DESKTOP_ROUTES.plugins && <WorkflowsPage />}
- {vm.navItem === DESKTOP_ROUTES.apps && (
- <SandboxUiPage
- boundsRefreshKey={sandboxUiBoundsRefreshKey}
- headerShellOverlayOpen={headerShellOverlayOpen}
- sidebarShellOverlayOpen={sidebarSettingsMenuOpen}
- toastShellOverlayOpen={vm.toasts.length > 0}
- shortcutApp={activeSandboxUiApp}
- shortcutOpenRequestId={sandboxUiShortcutOpenRequestId}
- onEmbeddedAppOpening={handleSandboxUiOpening}
- onEmbeddedAppBack={handleSandboxUiClosed}
- onEmbeddedAppRemoved={handleSandboxUiRemoved}
- onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
- />
- )}
- {vm.navItem === DESKTOP_ROUTES.settings && (
- <SettingsPage
- notificationSettings={vm.notificationSettings}
- desktopNotificationPermission={vm.desktopNotificationPermission}
- themeMode={themeMode}
- onNotify={vm.pushToast}
- onThemeModeChange={setThemeMode}
- onNotificationSoundVolumeChange={vm.setNotificationSoundVolume}
- onPlayNotificationSoundPreview={vm.playNotificationSoundPreview}
- onSaveNotificationSettings={vm.saveNotificationSettings}
- channelNotificationPreferences={vm.channelNotificationPreferences}
- channelNotificationPreferencesLoading={
- vm.channelNotificationPreferencesLoading
- }
- channelNotificationPreferencesSaving={
- vm.channelNotificationPreferencesSaving
- }
- onSaveChannelNotificationPreferences={
- vm.saveChannelNotificationPreferences
- }
- />
- )}
- {vm.navItem === DESKTOP_ROUTES.teams && <TeamsPage />}
- {vm.navItem === DESKTOP_ROUTES.teamDetails && <TeamDetailsPage />}
- </section>
- </section>
- </main>
- {desktopUpdateRequiredDialog}
- {environmentSetupConfirmationDialog}
- {environmentSetupSuccessDialog}
- </DesktopStateProvider>
- </McpRuntimeProvider>
- </AgentChatProviders>
- </AgentActivityProvider>
- </WorkspaceActionsProvider>
- </NotificationsContext.Provider>
- </NavigationContext.Provider>
+ <section className="workspace-layout">
+ <section
+ ref={contentPanelRef}
+ className={`content-panel glass-card${
+ isAgentChatView ? ' content-panel--agent-chat' : ''
+ }${vm.navItem === DESKTOP_ROUTES.settings ? ' content-panel--settings' : ''}${
+ appNotificationDrawerOpen
+ ? ' content-panel--app-notification-drawer-open'
+ : ''
+ }`}
+ >
+ <AppHeader
+ notificationTrayMode={
+ notificationTrayUsesDrawer ? 'drawer' : 'overlay'
+ }
+ notificationTrayReady={notificationDrawerReady}
+ onNotificationTrayOpenChange={setHeaderNotificationTrayOpen}
+ onShellOverlayOpenChange={setHeaderShellOverlayOpen}
+ />
+ <ToastStack items={vm.toasts} />
+ {vm.navItem === DESKTOP_ROUTES.chat && (
+ <ChatPage scrollContainerRef={contentPanelRef} />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.agents && (
+ <AgentsPage scrollContainerRef={contentPanelRef} />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.contexts && <ContextsPage />}
+ {vm.navItem === DESKTOP_ROUTES.files && (
+ <FilesPage pushToast={vm.pushToast} />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.connectors && <McpServersPage />}
+ {vm.navItem === DESKTOP_ROUTES.contextDetails && (
+ <ContextDetailsPage />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.plugins && <WorkflowsPage />}
+ {vm.navItem === DESKTOP_ROUTES.apps && (
+ <SandboxUiPage
+ boundsRefreshKey={sandboxUiBoundsRefreshKey}
+ headerShellOverlayOpen={headerShellOverlayOpen}
+ sidebarShellOverlayOpen={sidebarSettingsMenuOpen}
+ toastShellOverlayOpen={vm.toasts.length > 0}
+ shortcutApp={activeSandboxUiApp}
+ shortcutOpenRequestId={sandboxUiShortcutOpenRequestId}
+ onEmbeddedAppOpening={handleSandboxUiOpening}
+ onEmbeddedAppBack={handleSandboxUiClosed}
+ onEmbeddedAppRemoved={handleSandboxUiRemoved}
+ onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
+ />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.settings && (
+ <SettingsPage
+ notificationSettings={vm.notificationSettings}
+ desktopNotificationPermission={vm.desktopNotificationPermission}
+ themeMode={themeMode}
+ onNotify={vm.pushToast}
+ onThemeModeChange={setThemeMode}
+ onNotificationSoundVolumeChange={vm.setNotificationSoundVolume}
+ onPlayNotificationSoundPreview={vm.playNotificationSoundPreview}
+ onSaveNotificationSettings={vm.saveNotificationSettings}
+ channelNotificationPreferences={vm.channelNotificationPreferences}
+ channelNotificationPreferencesLoading={
+ vm.channelNotificationPreferencesLoading
+ }
+ channelNotificationPreferencesSaving={
+ vm.channelNotificationPreferencesSaving
+ }
+ onSaveChannelNotificationPreferences={
+ vm.saveChannelNotificationPreferences
+ }
+ />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.teams && <TeamsPage />}
+ {vm.navItem === DESKTOP_ROUTES.teamDetails && <TeamDetailsPage />}
+ </section>
+ </section>
+ </main>
+ {desktopUpdateRequiredDialog}
+ {environmentSetupConfirmationDialog}
+ {environmentSetupSuccessDialog}
+ </DesktopStateProvider>
+ </McpRuntimeProvider>
+ </AgentChatProviders>
+ </AgentActivityProvider>
+ </WorkspaceActionsProvider>
+ </NotificationsContext.Provider>
+ </NavigationContext.Provider>
+ ) : (
+ <>
+ {vm.hasDependencyOutage ? <UnavailablePage /> : <AuthPage />}
+ {environmentSetupConfirmationDialog}
+ {environmentSetupSuccessDialog}
+ <ToastStack items={vm.toasts} />
+ </>
+ )}
+ </div>
+ <BootSplash loading={bootSplashLoading} />
</AuthContext.Provider>
)
}
diff --git a/desktop-app/ui/src/components/BootSplash/__tests__/BootSplash.test.tsx b/desktop-app/ui/src/components/BootSplash/__tests__/BootSplash.test.tsx
new file mode 100644
index 000000000..c7327db29
--- /dev/null
+++ b/desktop-app/ui/src/components/BootSplash/__tests__/BootSplash.test.tsx
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { BOOT_SPLASH_EXIT_MS, BOOT_SPLASH_MIN_DISPLAY_MS } from '@constants/bootSplash'
+import { BootSplash } from '..'
+
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('BootSplash', () => {
+ it('stays visible until the experience is ready, then exits behind an opaque backdrop', async () => {
+ vi.useFakeTimers()
+ const view = render(<BootSplash loading />)
+
+ expect(screen.getByRole('status').textContent).toContain('Loading session')
+
+ await act(() => vi.advanceTimersByTimeAsync(BOOT_SPLASH_MIN_DISPLAY_MS * 2))
+ expect(screen.getByRole('status')).toBeTruthy()
+ expect(view.container.querySelector('.boot-overlay--leaving')).toBeNull()
+
+ view.rerender(<BootSplash loading={false} />)
+ await act(() => vi.advanceTimersByTimeAsync(BOOT_SPLASH_EXIT_MS - 1))
+
+ const overlay = view.container.querySelector('.boot-overlay')
+ expect(overlay).toBeTruthy()
+ expect(overlay?.classList.contains('boot-overlay--leaving')).toBe(true)
+
+ await act(() => vi.advanceTimersByTimeAsync(1))
+ expect(view.container.querySelector('.boot-overlay')).toBeNull()
+ })
+})
diff --git a/desktop-app/ui/src/components/BootSplash/index.tsx b/desktop-app/ui/src/components/BootSplash/index.tsx
new file mode 100644
index 000000000..188ba543c
--- /dev/null
+++ b/desktop-app/ui/src/components/BootSplash/index.tsx
@@ -0,0 +1,52 @@
+import { useEffect, useRef, useState } from 'react'
+import { BOOT_SPLASH_EXIT_MS, BOOT_SPLASH_MIN_DISPLAY_MS } from '@constants/bootSplash'
+import type { BootSplashProps } from './types'
+
+/**
+ * Full-screen startup overlay. The backdrop stays opaque while the splash
+ * exits so partially hydrated workspace surfaces never show through.
+ */
+export function BootSplash({ loading }: BootSplashProps) {
+ const [leaving, setLeaving] = useState(!loading)
+ const [mounted, setMounted] = useState(loading)
+ const mountedAtRef = useRef(Date.now())
+
+ useEffect(() => {
+ if (loading) {
+ setLeaving(false)
+ setMounted(true)
+ mountedAtRef.current = Date.now()
+ return
+ }
+
+ const elapsed = Date.now() - mountedAtRef.current
+ const leaveDelay = Math.max(0, BOOT_SPLASH_MIN_DISPLAY_MS - elapsed)
+ const leaveTimer = window.setTimeout(() => setLeaving(true), leaveDelay)
+ const unmountTimer = window.setTimeout(
+ () => setMounted(false),
+ leaveDelay + BOOT_SPLASH_EXIT_MS
+ )
+ return () => {
+ window.clearTimeout(leaveTimer)
+ window.clearTimeout(unmountTimer)
+ }
+ }, [loading])
+
+ if (!mounted) return null
+
+ return (
+ <div className={`boot-overlay${leaving ? ' boot-overlay--leaving' : ''}`}>
+ <section className="boot-screen glass-card" role="status" aria-live="polite">
+ <div className="boot-brand">
+ <img className="boot-brand-mark" src="./logo.svg" alt="" aria-hidden="true" />
+ <span className="boot-brand-copy">
+ <span className="boot-brand-title">Evenfire</span>
+ <span className="boot-brand-subtitle">Desktop App</span>
+ </span>
+ </div>
+ <div className="boot-progress" aria-hidden="true" />
+ <p className="boot-status muted">Loading session…</p>
+ </section>
+ </div>
+ )
+}
diff --git a/desktop-app/ui/src/components/BootSplash/types.ts b/desktop-app/ui/src/components/BootSplash/types.ts
new file mode 100644
index 000000000..57c391e7b
--- /dev/null
+++ b/desktop-app/ui/src/components/BootSplash/types.ts
@@ -0,0 +1,3 @@
+export type BootSplashProps = {
+ loading: boolean
+}
diff --git a/desktop-app/ui/src/components/SidebarNav/index.tsx b/desktop-app/ui/src/components/SidebarNav/index.tsx
index 820279a69..91510c840 100644
--- a/desktop-app/ui/src/components/SidebarNav/index.tsx
+++ b/desktop-app/ui/src/components/SidebarNav/index.tsx
@@ -326,7 +326,7 @@ export function SidebarNav({
<React.Fragment key={item.id}>
<div
className={`nav-link nav-link--with-toggle${
- item.id === DESKTOP_ROUTES.chat ? ' nav-link--with-new-chat' : ''
+ item.id === DESKTOP_ROUTES.chat && !collapsed ? ' nav-link--with-new-chat' : ''
} ${navItem === item.id ? 'active' : ''}`}
title={collapsed ? item.label : undefined}
data-tooltip={item.label}
@@ -345,7 +345,7 @@ export function SidebarNav({
>
{item.label}
</NavItemControl>
- {item.id === DESKTOP_ROUTES.chat && (
+ {item.id === DESKTOP_ROUTES.chat && !collapsed && (
<IconButton
className="nav-link-new-chat"
label="New chat"
diff --git a/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx b/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx
index 9cd3a3fa1..92c37d2ab 100644
--- a/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx
+++ b/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx
@@ -145,9 +145,15 @@ describe('SidebarNav new-chat affordance', () => {
it('renders exactly one new-chat button (on the chat nav row)', () => {
// The chat nav item is always present in primaryItems, so the new-chat
- // affordance is always rendered — regardless of which nav item is active.
+ // affordance is rendered while expanded, regardless of which nav item is active.
const { container } = render(<SidebarNav {...baseProps({ navItem: 'sandbox-ui' })} />)
const newChatButtons = container.querySelectorAll('.nav-link-new-chat')
expect(newChatButtons.length).toBe(1)
})
+
+ it('does not render the new-chat button when the sidebar is collapsed', () => {
+ render(<SidebarNav {...baseProps({ collapsed: true })} />)
+
+ expect(screen.queryByTestId('nav-new-chat')).toBeNull()
+ })
})
diff --git a/desktop-app/ui/src/constants/bootSplash.ts b/desktop-app/ui/src/constants/bootSplash.ts
new file mode 100644
index 000000000..e10973307
--- /dev/null
+++ b/desktop-app/ui/src/constants/bootSplash.ts
@@ -0,0 +1,2 @@
+export const BOOT_SPLASH_MIN_DISPLAY_MS = 400
+export const BOOT_SPLASH_EXIT_MS = 240
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
index b23b7a133..2134a7d71 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
@@ -26,6 +26,7 @@ interface ChatMock {
getLastActive: Fn
setLastActive: Fn
getIndex: Fn
+ reconcileServerSessions: Fn
dismissOnboarding: Fn
}
@@ -84,6 +85,7 @@ export function installMockClerum(): MockClerum {
onboardingDismissed: false,
chats: [],
})),
+ reconcileServerSessions: vi.fn(async () => 0),
dismissOnboarding: vi.fn(async () => undefined),
}
diff --git a/desktop-app/ui/src/hooks/domain/useAuthController.ts b/desktop-app/ui/src/hooks/domain/useAuthController.ts
index e3bdb0f29..76d71a2b0 100644
--- a/desktop-app/ui/src/hooks/domain/useAuthController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAuthController.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { DEFAULT_TOAST_DURATION_MS } from '@constants/toasts'
+import { desktopQueryClient } from '@lib/queryClient'
import type {
DependencyHealth,
DesktopReleaseStatus,
@@ -299,6 +300,10 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
try {
setBusy(true)
const state = await window.clerum.auth.selectRuntimeConfig(optionId)
+ // Switching environment (pre-login) must not carry another env's cached
+ // queries forward (spec §5.2 P1). The env is bound to login (D4: no switch
+ // without logout), so a full clear is sufficient — no per-env query keys.
+ desktopQueryClient.clear()
setRuntimeConfigState(state)
setDesktopSetupAuthorizationToken('')
setDesktopSetupStarted(false)
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index c047e1d8d..f9cf379d6 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -145,9 +145,28 @@ export function useChatListController({
const merged = [...localChats, ...fromServerOnly].sort(byUpdatedDesc)
setChatList(merged)
+
+ // Persist server freshness into the local index (spec §5.3): keeps the
+ // durable sidebar order aligned with the source of truth. A pure tail
+ // effect that does NOT affect this render — the merge above sorts local
+ // chats by their (possibly stale) local `updatedAt`, so a chat whose
+ // server `lastActivityAt` is newer only re-sorts on the next cold start
+ // from this persisted reconcile. Best-effort: must never block or fail the
+ // load (fully swallowed).
+ try {
+ void chatStore
+ .reconcileServerSessions(
+ agentRef,
+ serverSessions.map(s => ({ chatId: s.chatId, lastActivityAt: s.lastActivityAt }))
+ )
+ .catch(() => undefined)
+ } catch {
+ // ignore — reconciliation is best-effort freshness only
+ }
+
return { index, merged }
},
- [chatStore.getIndex, chatStore.listSessions, fsm]
+ [chatStore.getIndex, chatStore.listSessions, chatStore.reconcileServerSessions, fsm]
)
const loadChatList = useCallback(
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index ffa01e768..7d4d204b0 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -71,7 +71,7 @@ function isResourceDiscoveryUnavailable(message: string): boolean {
export function useGfsBrowserController() {
const queryClient = useQueryClient()
- const { isAuthenticated, me } = useAuthContext()
+ const { isAuthenticated, me, runtimeConfigState } = useAuthContext()
const [crumbs, setCrumbs] = useState<GfsCrumb[]>([])
const [openError, setOpenError] = useState<string | null>(null)
const [resolving, setResolving] = useState(false)
@@ -79,9 +79,13 @@ export function useGfsBrowserController() {
const current = crumbs.length ? crumbs[crumbs.length - 1] : null
const currentIsDirectory = current?.kind === 'directory'
+ // Scope gfs cache/crumbs by environment too (spec §5.2): the same user/team
+ // pair addresses different resources across clusters, so an env switch must
+ // reset the browser + drop the gfs query subtree.
+ const envKey = runtimeConfigState?.envKey ?? ''
const sessionScope = useMemo(
- () => (isAuthenticated && me ? `${me.id}:${me.teamId ?? ''}` : null),
- [isAuthenticated, me]
+ () => (isAuthenticated && me ? `${envKey}:${me.id}:${me.teamId ?? ''}` : null),
+ [envKey, isAuthenticated, me]
)
const canListAccessibleResources = typeof window.clerum?.gfs?.listAccessible === 'function'
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index b5b64770b..e18a88de2 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -647,6 +647,11 @@ export function useAppController() {
teamsData.reset()
resetWorkflowsData()
queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
+ // Drop ALL cached queries on logout (spec §5.2 P1): the singleton
+ // desktopQueryClient uses staleTime:Infinity, so any env-scoped data left
+ // in cache would otherwise bleed into the next login (possibly a different
+ // environment, since the env is chosen pre-login).
+ queryClient.clear()
authenticatedSessionIdentityRef.current = null
await window.clerum.auth.logout()
chat.resetChat()
@@ -983,6 +988,11 @@ export function useAppController() {
return {
// Auth
booting: auth.booting,
+ initialExperienceLoading:
+ auth.isAuthenticated &&
+ !auth.hasDependencyOutage &&
+ agentsData.loading &&
+ !agentsData.accessCatalog,
busy: auth.busy,
statusText,
statusTone,
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index 50d40b3df..95e593c77 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -101,6 +101,11 @@ export function useChatStore() {
[]
)
const getIndex = useCallback((agentRef: string) => window.clerum.chat.getIndex(agentRef), [])
+ const reconcileServerSessions = useCallback(
+ (agentRef: string, sessions: Array<{ chatId: string; lastActivityAt?: string }>) =>
+ window.clerum.chat.reconcileServerSessions(agentRef, sessions),
+ []
+ )
const dismissOnboarding = useCallback(
(agentRef: string) => window.clerum.chat.dismissOnboarding(agentRef),
[]
@@ -175,6 +180,7 @@ export function useChatStore() {
getLastActive,
setLastActive,
getIndex,
+ reconcileServerSessions,
dismissOnboarding,
listSessions,
loadSessionMessages,
diff --git a/desktop-app/ui/src/pages/McpServersPage.tsx b/desktop-app/ui/src/pages/McpServersPage.tsx
index 2a3b451a8..d2816393b 100644
--- a/desktop-app/ui/src/pages/McpServersPage.tsx
+++ b/desktop-app/ui/src/pages/McpServersPage.tsx
@@ -88,10 +88,7 @@ export function McpServersPage() {
<section className="page">
<div className="page-header">
<h2>Connectors</h2>
- <p className="muted">
- Connectors mapped across available agents and contexts. Select an agent to open its
- connector mappings. This is a global aggregate view and not a per-context guarantee.
- </p>
+ <p className="muted">Connectors mapped across available agents and contexts.</p>
</div>
<div className="page-layout">
diff --git a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
index b4733d833..643781d9f 100644
--- a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
@@ -32,6 +32,7 @@ const makeAuthValue = (overrides: Partial<AuthContextValue> = {}): AuthContextVa
isLocalhost: false,
selectorVisible: true,
activeOptionId: null,
+ envKey: 'env-test-key',
storagePath: '/tmp/evenfire-runtime-config',
options: [],
},
@@ -87,6 +88,7 @@ describe('AuthPage', () => {
isLocalhost: false,
selectorVisible: true,
activeOptionId: null,
+ envKey: 'env-test-key',
storagePath: '/tmp/evenfire-runtime-config',
options: [],
},
@@ -137,6 +139,7 @@ describe('AuthPage', () => {
isLocalhost: false,
selectorVisible: true,
activeOptionId: null,
+ envKey: 'env-test-key',
storagePath: '/tmp/evenfire-runtime-config',
options: [],
},
diff --git a/desktop-app/ui/src/pages/__tests__/SettingsPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SettingsPage.test.tsx
index 58fee75d5..13886d8ff 100644
--- a/desktop-app/ui/src/pages/__tests__/SettingsPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SettingsPage.test.tsx
@@ -28,6 +28,7 @@ const makeAuthValue = (overrides: Partial<AuthContextValue> = {}): AuthContextVa
isLocalhost: false,
selectorVisible: true,
activeOptionId: null,
+ envKey: 'env-test-key',
storagePath: '/tmp/evenfire-runtime-config',
options: [],
},
@@ -143,6 +144,7 @@ describe('SettingsPage', () => {
isLocalhost: true,
selectorVisible: true,
activeOptionId: '__localhost__',
+ envKey: 'env-test-key',
storagePath: '/tmp/evenfire-runtime-config',
options: [
{
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 0e246b8b8..fc45c01d7 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -9,6 +9,14 @@ body,
min-height: 100%;
}
+/* Layout-transparent wrapper around the app/auth tree. It only exists so the
+ BootSplash overlay can mark the whole background subtree `inert` during the
+ startup/loading window, removing hidden controls from the tab order and
+ accessibility tree until the splash exits. */
+.app-root {
+ display: contents;
+}
+
body {
color: var(--text);
font-family:
@@ -4027,8 +4035,9 @@ h3 {
box-shadow: none;
}
-/* Details and Activity: grid rows should not stretch to fill height */
+/* Non-chat route grids should keep their content grouped at the top. */
.agent-workspace-shell .agent-workspace-panel,
+.agent-workspace-shell .agent-mcp-panel,
.agent-workspace-shell .agent-activity-dashboard {
align-content: start;
}
@@ -9743,6 +9752,163 @@ button.page-breadcrumb-link--plain-action:hover:enabled {
padding: var(--space-4);
}
+/* Boot / session-loading splash. The brand mark + copy reveal as a single
+ cohesive unit (no staggered fragmentation), with one calm shimmer bar
+ underneath signaling the load. */
+.boot-screen {
+ width: min(420px, 94vw);
+ display: grid;
+ gap: var(--space-4);
+ padding: var(--space-5) var(--space-4);
+ place-items: center;
+ text-align: center;
+ animation: boot-screen-in 420ms ease both;
+}
+
+/* Fixed overlay that carries the branded splash across the booting → ready
+ transition. Its backdrop remains opaque until unmount so incomplete
+ workspace surfaces never show through the exit animation. */
+.boot-overlay {
+ --boot-exit-duration: 240ms;
+
+ position: fixed;
+ inset: 0;
+ z-index: 9999;
+ display: grid;
+ place-items: center;
+ padding: var(--space-5);
+ background: var(--bg);
+}
+
+.boot-overlay--leaving .boot-screen {
+ animation: boot-screen-out var(--boot-exit-duration) ease forwards;
+}
+
+.boot-brand {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2-5);
+ opacity: 0;
+ animation: boot-brand-in 600ms cubic-bezier(0.2, 0.8, 0.25, 1) both;
+}
+
+.boot-brand-mark {
+ width: 44px;
+ height: 44px;
+ flex: 0 0 auto;
+ object-fit: contain;
+}
+
+.boot-brand-copy {
+ display: grid;
+ gap: 2px;
+ min-width: 0;
+ text-align: left;
+}
+
+.boot-brand-title {
+ font-size: var(--font-size-xl);
+ font-weight: var(--font-weight-bold);
+ line-height: var(--line-height-tight);
+ color: var(--text);
+}
+
+.boot-brand-subtitle {
+ font-size: var(--font-size-xs);
+ font-weight: var(--font-weight-bold);
+ line-height: 1.15;
+ color: var(--text-muted);
+ letter-spacing: var(--letter-spacing-caps);
+ text-transform: uppercase;
+ white-space: nowrap;
+}
+
+.boot-progress {
+ position: relative;
+ width: 200px;
+ height: 3px;
+ border-radius: var(--radius-xl);
+ background: rgba(var(--edge-rgb), 0.3);
+ overflow: hidden;
+ opacity: 0;
+ animation: boot-fade-in 360ms ease 0.3s both;
+}
+
+.boot-progress::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 45%;
+ height: 100%;
+ border-radius: inherit;
+ background: linear-gradient(
+ 90deg,
+ rgba(var(--accent-rgb), 0),
+ rgba(var(--accent-rgb), 0.9),
+ var(--accent-strong)
+ );
+ animation: boot-progress-sweep 1.4s cubic-bezier(0.45, 0, 0.15, 1) infinite;
+}
+
+.boot-status {
+ margin: 0;
+ font-size: var(--font-size-sm);
+ opacity: 0;
+ animation: boot-fade-in 360ms ease 0.3s both;
+}
+
+@keyframes boot-screen-in {
+ from {
+ opacity: 0;
+ transform: translateY(6px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes boot-brand-in {
+ from {
+ opacity: 0;
+ transform: scale(0.92);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+@keyframes boot-fade-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+@keyframes boot-progress-sweep {
+ 0% {
+ transform: translateX(-110%);
+ }
+ 100% {
+ transform: translateX(322%);
+ }
+}
+
+@keyframes boot-screen-out {
+ from {
+ opacity: 1;
+ transform: translateY(0);
+ }
+ to {
+ opacity: 0;
+ transform: translateY(-4px);
+ }
+}
+
.auth-form {
display: grid;
gap: var(--space-5);
@@ -12067,9 +12233,15 @@ pre {
.apps-skeleton-pill,
.chat-skeleton-line,
.chat-skeleton-send,
- .sandbox-ui-loading__mark span {
+ .sandbox-ui-loading__mark span,
+ .boot-screen,
+ .boot-brand,
+ .boot-progress,
+ .boot-status,
+ .boot-overlay--leaving .boot-screen {
animation: none;
transform: none;
+ opacity: 1;
}
}
diff --git a/docs/architecture/diagrams/mcp-delegation-phase8.html b/docs/architecture/diagrams/mcp-delegation-phase8.html
index 95afc0875..6cf5dc4a3 100644
--- a/docs/architecture/diagrams/mcp-delegation-phase8.html
+++ b/docs/architecture/diagrams/mcp-delegation-phase8.html
@@ -206,7 +206,7 @@
<rect x="70" y="610" width="490" height="70" rx="6" fill="#0f172a"/>
<rect x="70" y="610" width="490" height="70" rx="6" fill="rgba(120, 53, 15, 0.3)" stroke="#fbbf24" stroke-width="1.5"/>
<text x="315" y="632" fill="#e2e8f0" font-family="JetBrains Mono" font-size="12" font-weight="600" text-anchor="middle">Secret wf-&lt;recipe&gt;-coordinator-token</text>
- <text x="315" y="650" fill="#94a3b8" font-family="JetBrains Mono" font-size="9" text-anchor="middle">{ mcp-host-token, wrc-token, cronjob-trigger-token }</text>
+ <text x="315" y="650" fill="#94a3b8" font-family="JetBrains Mono" font-size="9" text-anchor="middle">{ mcp-host-token, wrc-token }</text>
<text x="315" y="666" fill="#fbbf24" font-family="JetBrains Mono" font-size="8" text-anchor="middle">claim recipeNamespace = sandbox-recipes ← matches CRD's actual ns</text>
<!-- ═══════════════ NAMESPACE: mcp-server ═══════════════ -->
diff --git a/docs/features/ai-recipe-builder-app-architecture.md b/docs/features/ai-recipe-builder-app-architecture.md
new file mode 100644
index 000000000..87e421dab
--- /dev/null
+++ b/docs/features/ai-recipe-builder-app-architecture.md
@@ -0,0 +1,644 @@
+# AI Recipe Builder App Architecture
+
+The AI Recipe Builder is a Clerum-native sandbox application for designing
+`WorkflowRecipe` manifests through a guided LLM conversation. It appears inside
+the Desktop App as a custom app, lets the operator talk naturally with an AI
+agent, drafts a reviewable plan, and only generates WorkflowRecipe YAML after
+the operator confirms that plan.
+
+The app is intentionally conservative. It does not install generated recipes,
+publish registry entries, or mutate Kubernetes. Its job is to help an operator
+think through the design, produce safer starter YAML, surface required setup
+steps, and leave final install/publish decisions to Control UI or Control API.
+
+## What It Is
+
+At a high level, the app is a recipe-design assistant:
+
+- It runs inside Clerum as a `WorkflowRecipe`.
+- It exposes a custom UI inside Desktop App -> Apps.
+- It has a backend API that can call an OpenAI-compatible LLM provider.
+- It chats naturally with the operator before producing YAML.
+- It separates planning from creation with an explicit `Confirm plan` button.
+- It validates generated YAML locally before showing it to the operator.
+- It emits a registry payload and setup checklist for human review.
+
+The main product idea is simple: recipe creation should feel like working with a
+technical teammate, not filling out a brittle form. The operator can describe an
+app, workflow, MCP tool, webhook integration, OAuth flow, scheduled job, or data
+service in natural language. The assistant asks clarifying questions when the
+request is vague, drafts a concrete plan when enough detail exists, and generates
+YAML only after confirmation.
+
+## Why It Is A WorkflowRecipe
+
+We kept this as a `WorkflowRecipe` instead of a standalone MCP server because
+the desired user experience is a custom UI inside the Desktop App. MCP servers
+are excellent for exposing tools to agents, but they do not by themselves provide
+a rich embedded application surface. A WorkflowRecipe can expose a sandbox UI
+while still running a backend workload with controlled secrets and egress.
+
+This gives us the better fit for this use case:
+
+- The user gets a first-class app tile in Desktop.
+- The UI can provide chat, plan review, copy buttons, generated YAML, registry
+ payloads, validation output, and theme controls.
+- The backend can hold the optional LLM secret.
+- The recipe remains permission-light and operator-approved.
+
+## Runtime Shape
+
+The deployed app has two workloads:
+
+```text
+Desktop App
+ -> sandbox-ui/ui workload
+ -> internal egress/proxy to sandbox-recipes/api workload
+ -> optional exact-host egress to LLM provider
+```
+
+The `WorkflowRecipe` custom resource lives in `sandbox-recipes`, following the
+repo invariant that all WorkflowRecipe CRDs belong there. The rendered UI
+workload runs in `sandbox-ui`, and the backend API workload runs in
+`sandbox-recipes`.
+
+The UI workload does not receive AI provider secrets. It proxies API calls to the
+backend by using `RECIPE_BUILDER_PROXY_TARGET`, which is rendered from the recipe
+template as:
+
+```yaml
+value: 'http://{{api:host}}:{{api:port}}'
+```
+
+The API workload optionally receives the `ai-recipe-builder-llm` Secret:
+
+```text
+RECIPE_BUILDER_API_KEY
+RECIPE_BUILDER_BASE_URL
+RECIPE_BUILDER_MODEL
+```
+
+If the secret is missing, the app still works in deterministic mode. In
+deterministic mode it can infer capabilities, create a conservative plan, and
+generate starter YAML without calling an external model.
+
+## User Experience
+
+The current UI is a single-page app with these primary areas:
+
+- Header with service health, configured model, and light/dark toggle.
+- Natural-language chat panel.
+- Plan review panel.
+- Generated result panel with assistant notes.
+- Capability chips.
+- Local validation status.
+- Setup checklist.
+- Registry payload preview.
+- WorkflowRecipe YAML preview and copy button.
+
+The chat behavior is intentionally staged:
+
+1. The user can chat casually or ask what the assistant is.
+2. The assistant responds naturally in LLM text mode.
+3. If the user asks for a recipe but the request is underspecified, the assistant
+ asks focused clarifying questions.
+4. Once the request is concrete, the assistant returns a structured plan.
+5. The UI shows `Confirm plan`.
+6. Only after confirmation does the backend generate YAML.
+
+This avoids the earlier bad behavior where a greeting like "hi bro" generated a
+fake recipe. A casual message is now treated as conversation, not as build
+intent.
+
+## Feature Summary
+
+The app currently supports:
+
+- Natural language LLM chat.
+- Recipe-intent detection.
+- Clarifying question mode.
+- Plan-first generation.
+- Confirm-before-YAML flow.
+- OpenAI-compatible LLM configuration.
+- Deterministic fallback when AI is disabled or unavailable.
+- Local WorkflowRecipe validation.
+- Inline secret detection guard.
+- Capability inference for UI, database, workflow, MCP, webhook, OAuth, cron,
+ and egress.
+- Generated setup checklist.
+- Generated registry payload.
+- Light and dark mode using the Desktop App visual language.
+- Embedded Desktop-safe relative API paths.
+
+## Safety Model
+
+The app is a drafting tool, not an installer.
+
+It does not receive Kubernetes write privileges. It does not apply generated
+YAML. It does not create Secrets. It does not publish to the registry. This is
+intentional.
+
+The generated output still needs operator review because a WorkflowRecipe can
+describe workloads, network access, OAuth clients, webhooks, persistent storage,
+and external integrations. The app tries to make those requirements explicit
+instead of hiding them.
+
+Safety boundaries:
+
+- WorkflowRecipe CRDs are generated for `sandbox-recipes`.
+- Secrets are referenced through `envSecret`, not inline values.
+- Public internet access is represented through explicit `egressBindings`.
+- UI workloads should not receive provider secrets.
+- Generated YAML is locally validated before display.
+- Human approval is required for install and publish.
+
+## Source Layout
+
+The app lives under:
+
+```text
+workflow-recipes/samples/ai-recipe-builder/
+ Dockerfile
+ README.md
+ recipe.yaml
+ server.js
+ public/
+ index.html
+ app.js
+ styles.css
+ test-control-api-permissions.sh
+```
+
+Supporting documentation:
+
+```text
+docs/features/ai-recipe-builder-minikube-operator-cheatsheet.md
+docs/features/ai-recipe-builder-app-architecture.md
+docs/features/control-ui-workflow-recipes-and-registry-guide.md
+```
+
+## WorkflowRecipe Definition
+
+The installable recipe is:
+
+```text
+workflow-recipes/samples/ai-recipe-builder/recipe.yaml
+```
+
+Important fields:
+
+```yaml
+apiVersion: clerum.io/v1alpha1
+kind: WorkflowRecipe
+metadata:
+ name: ai-recipe-builder
+ namespace: sandbox-recipes
+spec:
+ contextRef: context1
+ workloads:
+ - id: api
+ type: deployment
+ image: clerum/ai-recipe-builder:0.1.0
+ - id: ui
+ type: deployment
+ image: clerum/ai-recipe-builder:0.1.0
+ dependsOn: [api]
+ ui:
+ workloadRef: ui
+ port: 8080
+ title: 'AI Recipe Builder'
+```
+
+The `api` workload:
+
+- Runs in `sandbox-recipes`.
+- Hosts `/api/*`.
+- Reads the optional LLM Secret.
+- Has exact-host egress to `api.openai.com` and `api.z.ai`.
+- Performs validation and generation.
+
+The `ui` workload:
+
+- Runs in `sandbox-ui`.
+- Hosts the static HTML/CSS/JS app.
+- Does not receive AI credentials.
+- Proxies `api/*` to the backend API using `RECIPE_BUILDER_PROXY_TARGET`.
+
+Both workloads use the same image. The difference is their environment and
+namespace placement.
+
+## Docker Image
+
+The image is intentionally small:
+
+```dockerfile
+FROM node:20-alpine
+
+USER node
+WORKDIR /home/node/app
+
+COPY --chown=node:node server.js ./
+COPY --chown=node:node public ./public
+
+EXPOSE 8080
+CMD ["node", "server.js"]
+```
+
+There is no `npm install` step because the implementation uses Node built-ins and
+the runtime `fetch` available in Node 20.
+
+## Backend API
+
+The backend is:
+
+```text
+workflow-recipes/samples/ai-recipe-builder/server.js
+```
+
+It uses Node's built-in `http`, `fs`, and `path` modules. It serves static files
+and JSON API routes from the same process.
+
+### Environment Variables
+
+```text
+PORT
+RECIPE_BUILDER_API_KEY
+RECIPE_BUILDER_BASE_URL
+RECIPE_BUILDER_MODEL
+RECIPE_BUILDER_PROXY_TARGET
+```
+
+Defaults:
+
+```text
+PORT=8080
+RECIPE_BUILDER_BASE_URL=https://api.openai.com/v1
+RECIPE_BUILDER_MODEL=gpt-5.4-mini
+```
+
+When `RECIPE_BUILDER_PROXY_TARGET` is present, the process behaves as the UI
+proxy for `/api/*` calls. That is how the sandbox UI reaches the backend without
+holding secrets.
+
+### Routes
+
+```text
+GET /healthz
+GET /api/health
+POST /api/chat-plan
+POST /api/create-from-plan
+POST /api/draft
+POST /api/validate
+GET /*
+```
+
+`GET /healthz` and `GET /api/health`
+
+Returns service status, AI configuration state, proxy target, and model name.
+
+`POST /api/chat-plan`
+
+Accepts chat messages:
+
+```json
+{
+ "useAi": true,
+ "messages": [
+ { "role": "user", "content": "Build a dashboard that checks domain expiry daily" }
+ ]
+}
+```
+
+Returns one of three modes:
+
+```text
+chat casual natural-language response
+question focused clarification before planning
+plan structured plan ready for operator confirmation
+```
+
+Normal conversation uses plain LLM text mode through `callAiText`. Recipe
+planning uses structured JSON through `callAiJson`.
+
+`POST /api/create-from-plan`
+
+Accepts a confirmed plan and generates the final draft.
+
+```json
+{
+ "useAi": true,
+ "plan": {
+ "name": "domain-expiry-dashboard",
+ "objective": "Build a dashboard that checks domain expiry daily"
+ }
+}
+```
+
+Returns:
+
+- `recipeName`
+- `recipeYaml`
+- `capabilities`
+- `checklist`
+- `registryPayload`
+- `validation`
+- optional `aiUnderstood`, `aiAssumptions`, `aiNotes`, and `aiError`
+
+`POST /api/draft`
+
+Legacy direct drafting endpoint. It remains for smoke tests and backwards
+compatibility, but the UI now prefers chat -> plan -> confirm.
+
+`POST /api/validate`
+
+Runs local validation on a supplied YAML string.
+
+### Important Backend Functions
+
+```text
+inferCapabilities(prompt)
+isActionableBuildPrompt(prompt)
+buildDeterministicPlan(messages)
+normalizePlan(raw, fallbackMessages)
+generateDeterministicDraft({ prompt, recipeName })
+validateDraft(yaml)
+hasInlineSecretValue(yaml)
+callAiText(messages)
+callAiJson(messages)
+maybePlanWithAi(messages, useAi)
+maybeGenerateWithAi(input)
+```
+
+The design splits normal chat and structured planning:
+
+- `callAiText` is used for natural conversation.
+- `callAiJson` is used only where structured output is required.
+- `maybePlanWithAi` chooses chat, question, or plan mode.
+- `maybeGenerateWithAi` generates or improves WorkflowRecipe YAML.
+- deterministic helpers provide a no-AI fallback.
+
+## System Prompt Context
+
+The backend includes a compact system context derived from the WorkflowRecipe
+guide. It teaches the agent the local invariants:
+
+- WorkflowRecipe CRDs live in `sandbox-recipes`.
+- UI workloads run in `sandbox-ui`.
+- Backend workloads run in `sandbox-recipes`.
+- UI workloads should not receive secrets.
+- Secrets should be referenced through `envSecret`.
+- Provider access requires explicit egress bindings.
+- MCP transport children belong in `mcp-server` only when transport is declared.
+- Casual chat is allowed and should not become a fake recipe.
+- YAML generation happens after plan confirmation.
+
+This context is intentionally embedded in `server.js` so the deployed sample is
+self-contained. Future versions could load it from documentation or a
+versioned prompt file.
+
+## Frontend App
+
+The frontend lives in:
+
+```text
+workflow-recipes/samples/ai-recipe-builder/public/
+ index.html
+ app.js
+ styles.css
+```
+
+`index.html` defines the app shell:
+
+- hero/header
+- health chip
+- light/dark toggle
+- chat panel
+- plan panel
+- generated output panel
+
+`app.js` manages browser state:
+
+```text
+currentYaml
+currentPlan
+chatMessages
+```
+
+Important UI functions:
+
+```text
+preferredTheme()
+applyTheme(theme)
+renderChat()
+renderPlan(plan)
+renderDraft(draft)
+renderValidation(validation)
+sendMessage()
+confirmPlan()
+copyYaml()
+```
+
+The browser uses relative API paths like `api/chat-plan`, not absolute `/api/*`.
+That matters inside the Desktop embedded app because the sandbox UI may be
+served from a nested path.
+
+`styles.css` ports the Desktop App visual language into this standalone sample:
+
+- dark neutral shell
+- warm light mode
+- burnt-orange accent
+- glass-like panels
+- matching controls, chips, validation states, and code blocks
+
+The selected theme is stored in:
+
+```text
+localStorage["ai-recipe-builder.theme"]
+```
+
+## LLM Connection
+
+The app expects an OpenAI-compatible chat completions API:
+
+```text
+POST <base-url>/chat/completions
+Authorization: Bearer <api-key>
+```
+
+The local minikube setup used a ZAI-compatible endpoint:
+
+```text
+base-url=https://api.z.ai/api/coding/paas/v4
+model=glm-4.7
+```
+
+The Secret shape is:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes create secret generic ai-recipe-builder-llm \
+ --from-literal=api-key="<provider-api-key>" \
+ --from-literal=base-url="<openai-compatible-base-url>" \
+ --from-literal=model="<model-name>"
+```
+
+For ownership and Secret discovery, the local secret should be labeled:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes label secret ai-recipe-builder-llm \
+ clerum.io/owner-recipe=ai-recipe-builder --overwrite
+```
+
+Never store real keys in documentation.
+
+## Data Flow
+
+Natural chat:
+
+```text
+User message
+ -> public/app.js sendMessage()
+ -> POST api/chat-plan
+ -> ui workload proxy
+ -> api workload /api/chat-plan
+ -> callAiText()
+ -> OpenAI-compatible provider
+ -> assistant text response
+ -> chat bubble
+```
+
+Recipe plan:
+
+```text
+Concrete build request
+ -> POST api/chat-plan
+ -> maybePlanWithAi()
+ -> callAiJson()
+ -> structured plan JSON
+ -> renderPlan()
+ -> Confirm plan button
+```
+
+YAML generation:
+
+```text
+Confirm plan
+ -> POST api/create-from-plan
+ -> maybeGenerateWithAi()
+ -> generated WorkflowRecipe YAML
+ -> validateDraft()
+ -> registry payload + checklist + YAML preview
+```
+
+No generated resource is applied automatically.
+
+## Local Build And Rollout
+
+Build the image into the minikube Docker daemon:
+
+```bash
+cd /home/pal/Clerum/Code/clerum
+eval "$(minikube -p clerum-test docker-env)"
+
+docker build -t clerum/ai-recipe-builder:0.1.0 \
+ workflow-recipes/samples/ai-recipe-builder
+```
+
+Restart both workloads:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes rollout restart deploy/api
+kubectl --context=clerum-test -n sandbox-ui rollout restart deploy/ui
+
+kubectl --context=clerum-test -n sandbox-recipes rollout status deploy/api --timeout=120s
+kubectl --context=clerum-test -n sandbox-ui rollout status deploy/ui --timeout=120s
+```
+
+The UI may need a Desktop embedded-view refresh after rollout because the webview
+can keep old JavaScript in memory.
+
+## Live Debugging
+
+Check the API workload logs:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes logs deploy/api --tail=160
+```
+
+Check the Secret shape without printing secret values:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes get secret ai-recipe-builder-llm \
+ -o go-template='{{range $k,$v := .data}}{{printf "%s len=%d\n" $k (len ($v | base64decode))}}{{end}}'
+```
+
+Verify env wiring:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes get deploy api \
+ -o jsonpath='{range .spec.template.spec.containers[0].env[*]}{.name}{" secret="}{.valueFrom.secretKeyRef.name}{":"}{.valueFrom.secretKeyRef.key}{"\n"}{end}'
+```
+
+Test chat from inside the pod:
+
+```bash
+kubectl --context=clerum-test -n sandbox-recipes exec -i deploy/api -- node - <<'NODE'
+(async () => {
+ const res = await fetch('http://127.0.0.1:8080/api/chat-plan', {
+ method: 'POST',
+ headers: {'content-type':'application/json'},
+ body: JSON.stringify({
+ useAi: true,
+ messages: [
+ {role:'user', content:'hi, can you tell me who you are?'}
+ ]
+ })
+ });
+ console.log(await res.text());
+})().catch(err => {
+ console.error(err.stack || err.message);
+ process.exit(1);
+});
+NODE
+```
+
+Expected shape:
+
+```json
+{
+ "mode": "chat",
+ "assistantMessage": "..."
+}
+```
+
+## Known Limits
+
+The app is a strong v1, but it is still a drafting assistant:
+
+- It does not persist chat history across reloads.
+- It does not stream tokens.
+- It does not apply generated YAML.
+- It does not publish registry entries.
+- It does not manage provider keys.
+- It does not deeply validate every CRD field against the Kubernetes OpenAPI
+ schema.
+- It uses an embedded system prompt in `server.js` rather than a separate prompt
+ asset.
+
+## Good Future Improvements
+
+High-value next steps:
+
+- Add streaming chat responses.
+- Persist sessions locally or in a recipe-owned store.
+- Add an explicit edit-plan step before confirmation.
+- Add CRD schema-backed validation through Control API.
+- Add a registry publish draft flow.
+- Add model/provider selection when multiple shared LLM secrets exist.
+- Add generated diff views when the plan changes.
+- Add tests for chat mode, plan mode, fallback mode, and invalid YAML fallback.
+- Move the system prompt into a versioned markdown or prompt file.
+- Add a "copy install commands" panel for generated recipes.
+
+The important architectural principle should stay the same: the app can assist,
+draft, and validate, but human operators approve the resources that enter the
+cluster.
diff --git a/docs/how-to/shared-and-global-files.md b/docs/how-to/shared-and-global-files.md
index 5f464f5db..21ed98660 100644
--- a/docs/how-to/shared-and-global-files.md
+++ b/docs/how-to/shared-and-global-files.md
@@ -12,7 +12,7 @@ evenfire has two ways to give agents files, with different trust models:
### 1. Create the workspace
-Apply a `SharedFileSystem` (or use **Control UI → Shared Files → New**):
+Apply a `SharedFileSystem` (or use **Control UI → Directories → Agent Files → New**):
```yaml
apiVersion: clerum.io/v1alpha1
@@ -48,7 +48,7 @@ sees the workspace read-only at that path.
### 3. Put files in it
Humans and admins write through the workspace API: in Control UI, open the
-Shared Filesystem and upload — the request is proxied through control-api to the
+Agent Files workspace and upload — the request is proxied through control-api to the
per-SFS controller. Agents **cannot** write: their mount is read-only, so an
agent reads the files with its file tools but never mutates them.
@@ -70,7 +70,7 @@ HTTP API, and that indirection is the point:
writes) through the broker.
Create one with a `GlobalFileSystem` CRD and manage access from Control UI's
-Global Files area. For the full API, the writer/reader roles, and the
+**Directories → Global File System** area. For the full API, the writer/reader roles, and the
authorization chain, see [`gfs-controller`](../../gfs-controller/README.md) and
the [GlobalFileSystem CRD](../crds/globalfilesystem.md).
diff --git a/docs/surfaces/control-ui.md b/docs/surfaces/control-ui.md
index 9b173714d..70246b207 100644
--- a/docs/surfaces/control-ui.md
+++ b/docs/surfaces/control-ui.md
@@ -29,7 +29,7 @@ five steps live together.
can answer "whose usage is this."
![Control UI usage dashboard: stacked-area token usage over time, grouped by agent](../assets/control-ui-usage-dashboard.webp)
- *Dev cluster, demo tenant.*
+ _Dev cluster, demo tenant._
2. **Cap it** — `TokenBudgetTable` (`/cost/token-budgets`) and
`LlmPriceTable` (`/cost/llm-prices`): per-1M-token model prices (input,
@@ -61,7 +61,7 @@ five steps live together.
[Configure approvals](../how-to/configure-approvals.md).
![Control UI per-tool approval editor on a host detail page](../assets/control-ui-approval-editor.webp)
- *Dev cluster, demo tenant.*
+ _Dev cluster, demo tenant._
4. **Constrain it** — `EgressEditor` (`components/EgressEditor.tsx`, model in
`lib/egressModel.ts`): closed-by-default, exact-host, exact-CIDR/IP (where
@@ -74,7 +74,7 @@ five steps live together.
URL.
![Control UI EgressEditor on the Edit Connector page: exact-host mode with allowed domain api.airtable.com, allowed ports, and an egress summary capped at a maximum of 20](../assets/control-ui-egress-editor.webp)
- *Dev cluster, demo tenant.*
+ _Dev cluster, demo tenant._
5. **Govern what gets installed** — `RegistryCatalog`
(`components/RegistryCatalog.tsx`), at `/registry`: marketplace entries
@@ -96,7 +96,7 @@ five steps live together.
[publish](../how-to/publish-plugin-to-registry.md) under its own org.
![Control UI registry catalog at /registry showing trust levels and the install flow](../assets/control-ui-registry-install.webp)
- *Dev cluster, demo tenant.*
+ _Dev cluster, demo tenant._
## Every screen writes a CRD
@@ -107,25 +107,25 @@ CRD (registry entries, publisher credentials, users/teams, secrets, outputs,
cost records, global-file resources and grants, settings). See the
[CRD reference](../crds/README.md) for the full schema of each resource. One
caveat to the heading: the `GlobalFileSystem` CRD itself is applied out of band
-(kustomize), and the Global Files screen only manages the brokered gfs
+(kustomize), and the Global File System screen only manages the brokered gfs
resources and grants inside it — it never writes that CR.
-| Sidebar label | Route | CRD / control-api resource |
-| ------------------ | --------------------------------------------------------- | ---------------------------------------------- |
-| Agents | `/hosts` | `Host` |
-| Connectors | `/mcp-servers` | `McpServer` |
-| Plugins | `/workflow-recipes` | `WorkflowRecipe` |
-| Shared Files | `/shared-filesystems` | `SharedFileSystem` |
-| Global Files | `/gfs` | gfs resources & grants (non-CRD) |
-| Marketplace | `/registry` | registry (non-CRD) |
-| Publisher | `/publisher` | publisher (non-CRD) |
-| External Channels | `/communication-channels` | `CommunicationChannel` |
-| Users & Teams | `/profile-admin/users` | users/teams (non-CRD) |
-| Contexts | `/contexts` | `Context` |
-| Secrets | `/secrets` | secrets (non-CRD) |
-| Outputs | `/outputs` | outputs (non-CRD) |
-| Cost & Usage | `/cost/usage`, `/cost/llm-prices`, `/cost/token-budgets` | cost (non-CRD) |
-| Settings | `/settings` | settings (non-CRD) |
+| Sidebar label | Route | CRD / control-api resource |
+| ------------------ | -------------------------------------------------------------------------------------- | -------------------------------- |
+| Agent Files | `/agent-files` | `SharedFileSystem` |
+| Agent Outputs | `/agent-outputs/recipe-artifacts` | outputs (non-CRD) |
+| Agents | `/agents` | `Host` |
+| Connectors | `/connectors` | `McpServer` |
+| Contexts | `/contexts` | `Context` |
+| Cost & Usage | `/cost-and-usage/usage`, `/cost-and-usage/llm-prices`, `/cost-and-usage/token-budgets` | cost (non-CRD) |
+| External Channels | `/external-channels` | `CommunicationChannel` |
+| Global File System | `/global-file-system` | gfs resources & grants (non-CRD) |
+| Marketplace | `/marketplace/connectors` | registry (non-CRD) |
+| Plugins | `/plugins` | `WorkflowRecipe` |
+| Publisher | `/publisher` | publisher (non-CRD) |
+| Secrets | `/secrets/llm` | secrets (non-CRD) |
+| Settings | `/settings/ui` | settings (non-CRD) |
+| Users & Teams | `/users-and-teams/users` | users/teams (non-CRD) |
Secret **values are write-only from the UI**: the Secrets screen lets an
admin create or replace a value, but never displays one back.
diff --git a/docs/testing/control-ui-headful-journeys.md b/docs/testing/control-ui-headful-journeys.md
new file mode 100644
index 000000000..b7a42056e
--- /dev/null
+++ b/docs/testing/control-ui-headful-journeys.md
@@ -0,0 +1,61 @@
+# Control UI — headful journey tests
+
+Status snapshot of the optional Playwright **QA recorder** journeys for the
+Clerum Control UI (Next.js operator/admin web app). These drive a real headful
+Chromium window (recorded WebM + PNG) against a local control-ui dev server
+pointed at a `example-dev` control-api port-forward. They are separate from the CI
+Playwright suite and never run in CI by default.
+
+For the recorder contract, safety flags, and credential configuration, see
+[optional-playwright-qa-recorder.md](./optional-playwright-qa-recorder.md).
+
+## Coverage
+
+Every common Control UI operator journey has at least one headful spec. Each
+signs in with the exact admin identity from `.env.qa-recorder`, shares
+launch/login/proof plumbing in `e2e/qa-recorder-helpers.ts`, and records a WebM +
+PNG per test under `.local-notes/qa-recorder/runs/control-ui/` (git-ignored).
+
+| Journey | Spec | Tests | Confirm flag | Status |
+| --- | --- | --- | --- | --- |
+| Login & shell | `qa-recorder-login.spec.ts` | 2 — sign-in page, authenticated shell | — | ✅ |
+| Navigation | `qa-recorder-navigation.spec.ts` | 1 — sidebar across main sections | — | ✅ |
+| Agents (hosts) | `qa-recorder-agents.spec.ts` | 1 — list + detail | — | ✅ |
+| Contexts | `qa-recorder-contexts.spec.ts` | 2 — list, detail + tabs | — | ✅ |
+| Connectors | `qa-recorder-connectors.spec.ts` | 1 — inventory | — | ✅ |
+| External channels | `qa-recorder-external-channels.spec.ts` | 1 — Telegram/Email/Slack | — | ✅ |
+| LLM models & secrets | `qa-recorder-llm-models.spec.ts` | 1 — models catalog + secrets | — | ✅ |
+| Users & teams | `qa-recorder-users-teams.spec.ts` | 1 — directory | — | ✅ |
+| Cost & usage | `qa-recorder-cost-usage.spec.ts` | 1 — usage dashboard | — | ✅ |
+| Traces | `qa-recorder-traces.spec.ts` | 2 — dashboard, state | — | ✅ |
+| Settings | `qa-recorder-settings.spec.ts` | 1 — read-only settings | — | ✅ |
+| Marketplace & plugins | `qa-recorder-marketplace.spec.ts` | 2 — connectors, plugins | — | ✅ |
+| Create agent | `qa-recorder-agent-create.spec.ts` | 1 — full create wizard | `QA_RECORDER_CONFIRM_MUTATIONS` (required) | ✅ |
+
+**Totals: 13 specs, 17 tests.** Read-only journeys need no confirmation flag; every
+journey still calls the loopback reachability guard on both URLs. The only
+mutating journey (create agent) requires `QA_RECORDER_CONFIRM_MUTATIONS=1` and
+cleans up its temporary agent/context in a `finally`.
+
+## Run
+
+```bash
+cd control-ui
+npm run qa:recorder:install # one-time: recorder Chromium into .local-notes/qa-recorder/browsers
+# control-ui dev server on :3000 + control-api forward on :8090 must be up
+npm run qa:recorder:login # one journey
+npm run qa:recorder:all # all 13 specs / 17 tests
+```
+
+## Proof artifacts (local only, git-ignored)
+
+```bash
+find .local-notes/qa-recorder/runs/control-ui -name '*.webm' # WebM recordings
+find .local-notes/qa-recorder/runs/control-ui -name '*.png' # full-page screenshots
+```
+
+## Last verified
+
+2026-07-17 against `example-dev` (GKE) — 17/17 passed, exit 0, with WebM + PNG
+proof for every test. Point-in-time snapshot; re-run `npm run qa:recorder:all`
+to refresh.
diff --git a/docs/testing/desktop-headful-journeys.md b/docs/testing/desktop-headful-journeys.md
new file mode 100644
index 000000000..bc4c90932
--- /dev/null
+++ b/docs/testing/desktop-headful-journeys.md
@@ -0,0 +1,65 @@
+# Desktop App — headful journey tests
+
+Status snapshot of the optional Playwright **QA recorder** journeys for the
+Evenfire Desktop App. These drive the real Electron window headfully (visible UI,
+recorded WebM + PNG) against a live `example-dev` port-forward. They are separate
+from the CI Playwright suite and never run in CI by default.
+
+For the recorder contract, safety flags, and how to configure credentials, see
+[optional-playwright-qa-recorder.md](./optional-playwright-qa-recorder.md).
+
+## Coverage
+
+Every Desktop App user journey has at least one headful spec. Each uses the exact
+QA identity from `.env.qa-recorder` (no first-available fallback), shares launch /
+login / proof plumbing in `qa-recorder-helpers.ts`, and records a WebM + PNG per
+test under `.local-notes/qa-recorder/runs/desktop-app/` (git-ignored).
+
+| Journey | Spec | Tests | Confirm flag | Status |
+| --- | --- | --- | --- | --- |
+| Auth & session | `qa-recorder-auth.spec.ts` | 3 — sign-in screen, authenticated shell, logout | — | ✅ |
+| Navigation | `qa-recorder-navigation.spec.ts` | 3 — primary sidebar, footer settings menu, resources pages | — | ✅ |
+| Agents | `qa-recorder-agents.spec.ts` | 3 — fleet, chat workspace, workspace routes | — | ✅ |
+| Connectors | `qa-recorder-connectors.spec.ts` | 1 — MCP/connector health inventory | — | ✅ |
+| Contexts | `qa-recorder-contexts.spec.ts` | 1 — list + detail tabs | — | ✅ |
+| Shared files | `qa-recorder-shared-files.spec.ts` | 1 — filesystem + directory browser | — | ✅ |
+| Teams & members | `qa-recorder-teams.spec.ts` | 1 — directory + detail tabs | — | ✅ |
+| Plugins & workflows | `qa-recorder-plugins.spec.ts` | 1 — inventory, detail, runs/artifacts (+optional trigger) | `QA_RECORDER_CONFIRM_MUTATIONS` (trigger only) | ✅ |
+| Apps | `qa-recorder-apps.spec.ts` | 1 — catalog + embedded session | — | ✅ |
+| Settings | `qa-recorder-settings.spec.ts` | 2 — appearance/notifications, information/configuration (+optional endpoint switch) | `QA_RECORDER_CONFIRM_MUTATIONS` (switch only) | ✅ |
+| Inbox & search | `qa-recorder-inbox-search.spec.ts` | 2 — inbox, global search | — | ✅ |
+| Chat | `qa-recorder-chat.spec.ts` | 1 — composer, thread, task progress | `QA_RECORDER_CONFIRM_CHAT` (required) | ✅ |
+| Settings + chat smoke | `qa-recorder-settings-chat.spec.ts` | 1 — Settings tabs + one chat message | `QA_RECORDER_CONFIRM_CHAT` (required) | ✅ |
+
+**Totals: 13 specs, 21 tests.** Read-only journeys need no confirmation flag; every
+journey still calls the loopback health guard on both API URLs. Mutating / paid
+steps (chat message, workflow trigger, endpoint switch) run only under their
+`QA_RECORDER_CONFIRM_*` flag and are otherwise skipped — the read-only part of the
+journey always runs.
+
+## Run
+
+```bash
+cd desktop-app
+# dev Evenfire must be closed (process-wide single-instance lock)
+make gcp-dev-pf-desktop # keep control-api/external-rest/rpc-proxy forwarded
+
+npm run qa:recorder:navigation # one journey
+npm run qa:recorder:all # all 13 specs / 21 tests
+```
+
+## Proof artifacts (local only, git-ignored)
+
+```bash
+find .local-notes/qa-recorder/runs/desktop-app -name '*.webm' # WebM recordings
+find .local-notes/qa-recorder/runs/desktop-app -name '*.png' # full-page screenshots
+```
+
+Videos may contain emails, agent names, endpoint URLs, prompts, or model responses
+and must stay local unless reviewed and shared intentionally.
+
+## Last verified
+
+2026-07-17 against `example-dev` (GKE) port-forwards — 21/21 passed, exit 0, with
+WebM + PNG proof for every test. This is a point-in-time snapshot; re-run
+`npm run qa:recorder:all` to refresh.
diff --git a/docs/testing/optional-playwright-qa-recorder.md b/docs/testing/optional-playwright-qa-recorder.md
new file mode 100644
index 000000000..1aa80742d
--- /dev/null
+++ b/docs/testing/optional-playwright-qa-recorder.md
@@ -0,0 +1,443 @@
+# Optional Playwright QA recorder
+
+The QA recorder is an opt-in local workflow for recording complete Control UI
+and Desktop App journeys as WebM videos. It is deliberately separate from the
+normal unit, build, Playwright, and CI paths.
+
+Using the recorder is not required to build, test, or develop Clerum. No
+existing command invokes it, and no CI workflow installs its browser or runs
+its journeys.
+
+The recorder consumes an environment that is already running. It never starts
+Docker or minikube, builds backend images, deploys services, or invokes another
+test suite. Pointing it at an existing `example-dev` port-forward is therefore a
+Playwright/Chromium operation, not a local-stack bootstrap.
+
+## Included journeys
+
+### Control UI: create an agent
+
+The Control UI journey:
+
+1. Signs in through the real UI.
+2. Opens the canonical `/hosts` Agents route.
+3. Opens `/hosts/new` through the Create agent button.
+4. Creates a uniquely named context and agent.
+5. Selects the exact LLM secret supplied by the operator.
+6. Optionally grants the agent to an explicitly named member.
+7. Skips channel setup.
+8. Verifies the resulting resource through Control API.
+9. Deletes the temporary agent and context in a `finally` cleanup.
+
+This journey mutates the target environment temporarily. It will not run
+unless `QA_RECORDER_CONFIRM_MUTATIONS=1` is enabled in `.env.qa-recorder`.
+
+### Control UI: full headful journey suite
+
+The recorder also ships one headful spec per common Control UI operator journey
+(login, navigation, agents, contexts, connectors, external channels, LLM models
+& secrets, users & teams, cost & usage, traces, settings, marketplace). Each
+shares launch/login/proof plumbing in `e2e/qa-recorder-helpers.ts`, signs in with
+the exact admin identity from `.env.qa-recorder`, and records a WebM + PNG under
+`.local-notes/qa-recorder/runs/control-ui/`. They are read-only (no confirm flag
+needed); only the `agent-create` journey above mutates. See
+[control-ui-headful-journeys.md](./control-ui-headful-journeys.md) for the full
+status table. Run one with `npm run qa:recorder:<journey>` or all with
+`npm run qa:recorder:all`.
+
+### Desktop App: Settings and chat
+
+The Desktop journey:
+
+1. Builds and launches the actual Electron app.
+2. Signs in with an explicitly supplied test identity.
+3. Visits Appearance, Notifications, and Information in Settings.
+4. Opens the exact agent supplied through `E2E_HOST_REF`.
+5. Sends a short real chat message.
+6. Waits for a non-empty assistant response.
+7. Closes Electron so its WebM recording is finalized.
+
+This journey can create chat history and incur model-provider cost. It will not
+run unless `QA_RECORDER_CONFIRM_CHAT=1` is enabled in `.env.qa-recorder`.
+
+### Desktop App: full headful journey suite
+
+The recorder also ships one headful spec per Desktop App user journey. Each
+journey lives in its own `qa-recorder-<journey>.spec.ts`, shares the same
+launch/login/proof plumbing in `qa-recorder-helpers.ts`, uses the exact QA
+identity from `.env.qa-recorder` (no first-available fallback), and records a
+WebM + PNG under `.local-notes/qa-recorder/runs/desktop-app/`.
+
+| Journey | Spec | Notes |
+| --- | --- | --- |
+| Auth & session | `qa-recorder-auth.spec.ts` | Sign-in, authenticated shell, logout. Read-only. |
+| Navigation | `qa-recorder-navigation.spec.ts` | Sidebar, footer Settings/Resources menus, page shells. Read-only. |
+| Agents | `qa-recorder-agents.spec.ts` | Fleet, exact `chatllm` row, workspace routes. Read-only. |
+| Connectors | `qa-recorder-connectors.spec.ts` | MCP/connector health inventory. Read-only. |
+| Contexts | `qa-recorder-contexts.spec.ts` | List + detail tabs (`development`/`moneymaking`). Read-only. |
+| Shared files | `qa-recorder-shared-files.spec.ts` | Filesystem + directory browser. Read-only. |
+| Teams | `qa-recorder-teams.spec.ts` | Teams directory + detail tabs. Read-only. |
+| Plugins | `qa-recorder-plugins.spec.ts` | Inventory, detail, runs/artifacts. Trigger gated by `QA_RECORDER_CONFIRM_MUTATIONS`. |
+| Apps | `qa-recorder-apps.spec.ts` | Catalog + embedded session. Read-only. |
+| Settings | `qa-recorder-settings.spec.ts` | Appearance, notifications, configuration. Endpoint switch gated by `QA_RECORDER_CONFIRM_MUTATIONS`. |
+| Inbox & search | `qa-recorder-inbox-search.spec.ts` | Inbox, notifications, global search. Read-only. |
+| Chat | `qa-recorder-chat.spec.ts` | Composer, thread, task progress. Requires `QA_RECORDER_CONFIRM_CHAT=1`. |
+
+The combined `qa-recorder-settings-chat.spec.ts` smoke (Settings tabs + one chat
+message) is unchanged. Read-only journeys need no confirmation flag; every
+journey still calls the loopback health guard on both API URLs. Run one journey
+with its namespaced command (below) or all of them with `npm run qa:recorder:all`.
+
+## Repository isolation
+
+The recorder adds new commands; it does not alter any existing command:
+
+| Package | Optional command | Purpose |
+| ------------- | ----------------------------------- | ------------------------------------- |
+| `control-ui` | `npm run qa:recorder:install` | Download recorder-only Chromium |
+| `control-ui` | `npm run qa:recorder:agent-create` | Record the agent creation journey |
+| `control-ui` | `npm run qa:recorder:<journey>` | Record one headful journey (`login`, `navigation`, `agents`, `contexts`, `connectors`, `external-channels`, `llm-models`, `users-teams`, `cost-usage`, `traces`, `settings`, `marketplace`) |
+| `control-ui` | `npm run qa:recorder:all` | Record every Control UI recorder journey |
+| `desktop-app` | `npm run qa:recorder:settings-chat` | Build and record the Settings+Chat Electron journey |
+| `desktop-app` | `npm run qa:recorder:<journey>` | Build and record one headful journey (`auth`, `navigation`, `agents`, `connectors`, `contexts`, `shared-files`, `teams`, `plugins`, `apps`, `settings`, `inbox-search`, `chat`) |
+| `desktop-app` | `npm run qa:recorder:all` | Build and record every Desktop recorder journey |
+
+The normal `test`, `build`, `test:e2e:playwright`, and `test:e2e:all` commands
+retain their existing behavior. The dedicated configs match only their
+dedicated recorder specs, so they cannot accidentally expand into a full E2E
+suite.
+
+The implementation files that belong in Git are:
+
+```text
+.env.qa-recorder.example
+scripts/qa-recorder/loadEnv.ts
+control-ui/
+ e2e/qa-recorder-agent-create.spec.ts
+ playwright.qa-recorder.config.ts
+desktop-app/test/e2e-playwright/
+ qa-recorder-helpers.ts
+ qa-recorder-settings-chat.spec.ts
+ qa-recorder-<journey>.spec.ts # one per Desktop journey (see table above)
+ playwright.qa-recorder.config.ts
+docs/testing/optional-playwright-qa-recorder.md
+```
+
+The developer's private settings file is:
+
+```text
+.env.qa-recorder
+```
+
+It is ignored by Git. All other machine-specific state goes under:
+
+```text
+.local-notes/qa-recorder/
+ browsers/ # Control UI Chromium download
+ runs/
+ control-ui/ # Control screenshots, traces, and WebM
+ desktop-app/ # Electron profile, diagnostics, and WebM
+```
+
+`.local-notes/qa-recorder/` is explicitly ignored, and `.local-notes/` remains
+ignored as a second boundary. The repository's existing `**/test-results/`,
+`**/playwright-report/`, and browser-cache rules provide defense in depth for
+any Playwright output produced outside the configured recorder root.
+
+The root `.env.*` ignore rule excludes `.env.qa-recorder`; only
+`.env.qa-recorder.example` is explicitly tracked.
+
+Do not add an exception that force-adds recorder output. Videos may contain
+email addresses, agent names, endpoint URLs, secret names, prompts, or model
+responses and must remain local unless reviewed and shared intentionally.
+
+## Configure once
+
+From the repository root:
+
+```bash
+cp .env.qa-recorder.example .env.qa-recorder
+```
+
+Open `.env.qa-recorder` and fill in the blank credentials and fixture names.
+For the Desktop journey, the minimum settings to review are:
+
+```dotenv
+QA_RECORDER_CONFIRM_CHAT=1
+E2E_DESKTOP_PASSWORD=your-local-test-password
+E2E_HOST_REF=chatllm
+```
+
+For the Control UI journey:
+
+```dotenv
+QA_RECORDER_CONFIRM_MUTATIONS=1
+E2E_ADMIN_USER=admin
+E2E_ADMIN_PASSWORD=your-local-admin-password
+E2E_AGENT_SECRET_NAME=your-existing-secret-name
+```
+
+The example includes every supported recorder setting, including URLs,
+recording controls, browser selection, the optional member label, and the chat
+prompt. Configure both journeys in the same file or only the journey being
+used.
+
+Both dedicated Playwright configs load `.env.qa-recorder` automatically before
+loading their specs. Regular application, build, test, and CI commands do not
+load it. Existing shell environment variables take precedence over the file,
+which permits one-off overrides without making exports the normal workflow.
+
+Values may be unquoted, single-quoted, or double-quoted. Use one `KEY=value`
+entry per line; interpolation is intentionally unsupported so passwords
+containing `$` are treated literally.
+
+## Install
+
+The packages already declare `@playwright/test`; the recorder adds no new npm
+dependency and does not change either lockfile.
+
+Install normal Control UI dependencies when needed:
+
+```bash
+cd control-ui
+npm ci
+```
+
+Install Chromium into the ignored shared recorder cache:
+
+```bash
+npm run qa:recorder:install
+```
+
+The download is optional and can be large. It happens only when someone runs
+that command. It does not use Playwright's global browser cache.
+
+Install normal Desktop App dependencies when needed:
+
+```bash
+cd ../desktop-app
+npm ci
+```
+
+Do **not** run the Control UI browser-install command for Desktop. The Desktop
+recorder launches the Electron dependency already used by the application and
+records Electron's embedded Chromium.
+
+### Use an installed Chrome instead
+
+Control UI can use a locally installed Playwright-supported Chrome channel
+without downloading recorder Chromium. Set this once in `.env.qa-recorder`:
+
+```dotenv
+QA_RECORDER_BROWSER_CHANNEL=chrome
+```
+
+Then run `npm run qa:recorder:agent-create` normally from `control-ui/`. Leave
+`QA_RECORDER_BROWSER_CHANNEL` empty to use the pinned Chromium installed by
+`qa:recorder:install`.
+
+## Runtime prerequisites
+
+These are real end-to-end journeys, not mocked component tests. Before running
+them:
+
+- Start or connect to the required Clerum services using the repository's
+ normal development workflow.
+- Confirm the UI and API URLs used below are healthy.
+- Seed the intended local test user and password.
+- For Control UI, seed the exact LLM secret named by
+ `E2E_AGENT_SECRET_NAME`.
+- For Desktop, grant the test user access to the exact agent named by
+ `E2E_HOST_REF`.
+- Keep required port-forwards alive for the entire run.
+
+The recorder deliberately does not manage those prerequisites. If the target
+is a local branch-scoped profile, follow the repository E2E/minikube
+instructions in `AGENTS.md`; a browser opening does not prove that a local
+cluster is synced to the current worktree.
+
+### Straightforward `example-dev` setup
+
+When the existing GKE dev environment is the intended target, no Docker or
+local minikube profile is needed.
+
+Keep the three API port-forwards open in one terminal:
+
+```bash
+make gcp-dev-pf-desktop
+```
+
+Run the current branch's Control UI against the forwarded dev API in another:
+
+```bash
+cd control-ui
+CONTROL_API_INTERNAL_URL=http://localhost:8090 npm run dev
+```
+
+Then run either recorder command from a third terminal. This tests the current
+branch UI/Electron code against the existing dev backend. Use `localhost` for
+`CONTROL_UI_URL` when running Next locally; mixing `127.0.0.1` with a
+`localhost` dev server can trigger Next's development-origin protection.
+
+Do not also launch `make local-app` or the Desktop portion of `make local-ui`
+while recording Desktop. Evenfire enforces a single running Electron instance,
+and the recorder needs to own that instance long enough to finalize its video.
+
+## Record Control UI
+
+After configuring `.env.qa-recorder`, run from `control-ui/`:
+
+```bash
+npm run qa:recorder:agent-create
+```
+
+Local defaults:
+
+```text
+CONTROL_UI_URL=http://localhost:3000
+CONTROL_API_URL=http://localhost:8090
+```
+
+Supported credential names, in priority order:
+
+```text
+Username:
+ E2E_ADMIN_USER
+ ADMIN_USER
+ ADMIN_USERNAME
+
+Password:
+ E2E_ADMIN_PASSWORD
+ ADMIN_PASSWORD
+ ADMIN_PASS
+ TEST_ADMIN_PASSWORD
+```
+
+No password is embedded in the recorder spec.
+
+To record selecting a specific member during agent creation, set:
+
+```dotenv
+E2E_AGENT_ACCESS_LABEL=exact-visible-member-label
+```
+
+If omitted, the agent is created without a member/team grant and is still
+cleaned up after verification.
+
+## Record Desktop App
+
+After configuring `.env.qa-recorder`, run from `desktop-app/`:
+
+```bash
+npm run qa:recorder:settings-chat
+```
+
+Local defaults:
+
+```text
+EXTERNAL_REST_API_BASE_URL=http://127.0.0.1:8091
+RPC_PROXY_BASE_URL=http://127.0.0.1:8094
+```
+
+The email can also be supplied as `TEST_USER_EMAIL`. Password priority is:
+
+```text
+E2E_DESKTOP_PASSWORD
+E2E_TEST_PASSWORD
+ADMIN_PASSWORD
+```
+
+There is no personal email, default password, or “first available agent”
+fallback in the recorder.
+
+Override the short default prompt when a journey needs specific visible copy:
+
+```dotenv
+QA_RECORDER_CHAT_PROMPT="Reply with exactly: optional-recorder-ok"
+```
+
+The recorder keeps its runtime-config file and Playwright output under the
+ignored run directory. The current Electron application still enforces its
+normal process-wide single-instance lock, so close any running Evenfire window
+before starting this journey. The real chat backend may retain the sent
+conversation according to its normal behavior.
+
+## Locate recordings
+
+From the repository root:
+
+```bash
+find .local-notes/qa-recorder/runs -type f -name '*.webm' -print
+```
+
+Control UI places its video below:
+
+```text
+.local-notes/qa-recorder/runs/control-ui/
+```
+
+Desktop prints the final video path as `[qa-recorder] Desktop video: ...` and
+stores it below:
+
+```text
+.local-notes/qa-recorder/runs/desktop-app/
+```
+
+Successful runs also retain PNG screenshots in the corresponding Control UI or
+Desktop App run directory.
+
+Videos are not attached a second time to the Playwright result, avoiding the
+duplicate WebM produced by the original prototype.
+
+Playwright prepares the configured output directory for each new run. Copy a
+recording to another ignored/private location before rerunning if it must be
+retained.
+
+## Optional controls
+
+Set these in `.env.qa-recorder`:
+
+| Variable | Default | Effect |
+| ----------------------------- | --------------------------------- | ----------------------------------------------------------- |
+| `QA_RECORDER_ROOT` | `<repo>/.local-notes/qa-recorder` | Absolute or working-directory-relative runtime root |
+| `QA_RECORDER_VIDEO` | `1` | Set to `0` to exercise the journey without recording |
+| `QA_RECORDER_SLOW_MO_MS` | `75` | Control UI action delay; use `0` for normal speed |
+| `QA_RECORDER_HEADLESS` | `0` | Control UI only; set to `1` for an invisible diagnostic run |
+| `QA_RECORDER_BROWSER_CHANNEL` | unset | Control UI browser channel, such as `chrome` |
+| `QA_RECORDER_ALLOW_REMOTE` | `0` | Permit non-loopback targets after explicit review |
+
+Headful mode and video are defaults for the recorder only. They do not affect
+the repository's normal Playwright configs.
+
+## Remote-target guard
+
+Both journeys accept only `localhost`, `127.0.0.1`, or `::1` endpoints by
+default. A non-loopback URL fails before launching the journey.
+
+`QA_RECORDER_ALLOW_REMOTE=1` overrides that protection, but it does not bypass
+the mutation/chat confirmation flag. Use it only for an explicitly approved
+disposable QA environment. Never point these journeys at production.
+
+## Extending the recorder
+
+Keep future recorder work under the same contract:
+
+1. Commit specs, configs, and documentation.
+2. Add new private settings to `.env.qa-recorder.example`; never commit the
+ populated `.env.qa-recorder`.
+3. Put browser binaries, profiles, traces, screenshots, reports, and videos
+ under `.local-notes/qa-recorder/`.
+4. Add namespaced `qa:recorder:*` commands; do not change existing test
+ commands or make recorder installation a lifecycle hook.
+5. Match each config narrowly to its recorder spec.
+6. Require exact fixture identities instead of choosing the first resource.
+7. Require an explicit confirmation variable for writes, messages, or paid
+ provider calls.
+8. Guard non-local targets.
+9. Clean temporary resources with unique names and `finally`.
+10. Never add recorder execution to CI by default.
+
+This keeps the recorder useful to QA-focused developers without imposing its
+browser download, disk usage, runtime, credentials, or video handling on the
+rest of the project.
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 2d8b5a7ab..b3635ac43 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.153",
+ "version": "0.1.154",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.153",
+ "version": "0.1.154",
"license": "MIT",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 19a523030..7b0c2ee3c 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.153",
+ "version": "0.1.154",
"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__/hostReconciler.mounts.test.ts b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
index ce4a0f244..b683de416 100644
--- a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
+++ b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
@@ -30,11 +30,13 @@ vi.mock('../mcpHostRuntimeTokenIssuerClient', () => ({
}))
vi.mock('../gfsHostBinding', () => ({
- mintHostGfsToken: vi.fn().mockResolvedValue({
- token: 'gfs-runtime-value',
- expiresInSeconds: 300,
- subject: 'host:1st:mcp-host/standalone',
- }),
+ mintHostGfsToken: vi
+ .fn()
+ .mockImplementation(async ({ name, namespace }: { name: string; namespace: string }) => ({
+ token: 'gfs-runtime-value',
+ expiresInSeconds: 300,
+ subject: `host:1st:${namespace}/${name}`,
+ })),
}))
// Stand-in KubeConfig that returns a stub for every makeApiClient — buildDeployment
@@ -176,7 +178,7 @@ function runtimeSecretAnnotations(host = makeHost(), refreshBefore = '2999-01-01
'clerum.io/runtime-token-scope-hash': helper.runtimeTokenScopeHash(host),
'clerum.io/runtime-token-issuer': 'control-api',
'clerum.io/runtime-token-audience': 'workflow-approvals',
- 'clerum.io/runtime-token-schema-version': '1',
+ 'clerum.io/runtime-token-schema-version': '2',
'clerum.io/runtime-token-refresh-before': refreshBefore,
'clerum.io/gfs-token-refresh-before': '2999-01-01T00:00:00.000Z',
}
@@ -306,6 +308,48 @@ describe('HostReconciler runtime credential Secret revision', () => {
expect(coreApi.replaceNamespacedSecret).not.toHaveBeenCalled()
})
+ it('rotates and rolls a legacy fleet-wide GFS token contract', async () => {
+ const host = makeHost()
+ const legacyAnnotations = {
+ ...runtimeSecretAnnotations(host),
+ 'clerum.io/runtime-token-schema-version': '1',
+ }
+ const legacySecret = runtimeSecret(host, legacyAnnotations)
+ const helper = HostReconciler as unknown as {
+ runtimeTokenRefreshDecision: (
+ h: HostCRD,
+ secret: k8s.V1Secret,
+ nowMs: number
+ ) => { refresh: boolean; rolloutRequired: boolean; reason: string }
+ runtimeTokenSecretRevisionFromSecret: (value: k8s.V1Secret) => string | null
+ }
+ expect(helper.runtimeTokenRefreshDecision(host, legacySecret, Date.now())).toMatchObject({
+ refresh: true,
+ rolloutRequired: true,
+ reason: 'contract_changed',
+ })
+
+ const legacyRevision = helper.runtimeTokenSecretRevisionFromSecret(legacySecret)!
+ const { reconciler, coreApi } = runtimeSecretReconciler({
+ secret: legacySecret,
+ deployment: deploymentWithRevision(legacyRevision, 1),
+ })
+
+ const result = await (
+ reconciler as unknown as {
+ ensureMcpHostRuntimeTokenSecret: (h: HostCRD) => Promise<RuntimeTokenProvision>
+ }
+ ).ensureMcpHostRuntimeTokenSecret(host)
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalledTimes(1)
+ expect(coreApi.replaceNamespacedSecret).toHaveBeenCalledTimes(1)
+ expect(result.revision).not.toBe(legacyRevision)
+ expect(replacedRuntimeSecret(coreApi).metadata?.annotations).toMatchObject({
+ 'clerum.io/runtime-token-schema-version': '2',
+ 'clerum.io/runtime-token-rollout-required': 'true',
+ })
+ })
+
it('keeps a matching fresh bootstrap stable while booting, then marks it consumed when Ready', async () => {
// A fresh Secret already matches the Deployment template. Reconciles while
// that Pod is still becoming Ready must not mint again and trigger another
@@ -644,7 +688,7 @@ describe('HostReconciler runtime credential Secret revision', () => {
expect(replaceBody.metadata?.annotations).toMatchObject({
'clerum.io/runtime-token-issuer': 'control-api',
'clerum.io/runtime-token-audience': 'workflow-approvals',
- 'clerum.io/runtime-token-schema-version': '1',
+ 'clerum.io/runtime-token-schema-version': '2',
})
})
diff --git a/host-context-controller/src/gfsConfig.test.ts b/host-context-controller/src/gfsConfig.test.ts
index de9af97dd..1b0e30150 100644
--- a/host-context-controller/src/gfsConfig.test.ts
+++ b/host-context-controller/src/gfsConfig.test.ts
@@ -31,7 +31,7 @@ describe('gfsDefaultFactoryConfig', () => {
process.env.CONTEXT_MAPPER_NODELOCAL_DNS_CIDR = '203.0.113.10/32'
expect(gfsDefaultFactoryConfig().nodeLocalDnsCidr).toBe('203.0.113.10/32')
- process.env.CONTEXT_MAPPER_NODELOCAL_DNS_CIDR = '203.0.113.0/24'
+ process.env.CONTEXT_MAPPER_NODELOCAL_DNS_CIDR = '203.0.113.10/24'
expect(() => gfsDefaultFactoryConfig()).toThrow(/expected \/32 CIDR/)
})
})
diff --git a/host-context-controller/src/gfsHostBinding.test.ts b/host-context-controller/src/gfsHostBinding.test.ts
index 15bc331a0..3eaf0cfa4 100644
--- a/host-context-controller/src/gfsHostBinding.test.ts
+++ b/host-context-controller/src/gfsHostBinding.test.ts
@@ -6,32 +6,47 @@ import {
mintHostGfsToken,
} from './gfsHostBinding'
-/**
- * P3-S02 — HCC 1st-party host gfs token mint. Every Host shares the sentinel
- * binding mcp-host/standalone; read-only scope in P3; fail-loud on error.
- */
+/** P3-S02 — first-party tokens preserve the concrete Host identity. */
function okResponse(body: unknown): Response {
return { ok: true, status: 200, json: async () => body } as Response
}
+function jwt(payload: unknown): string {
+ return [
+ Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url'),
+ Buffer.from(JSON.stringify(payload)).toString('base64url'),
+ 'unverified-signature',
+ ].join('.')
+}
+
describe('mintHostGfsToken', () => {
- it('POSTs to the sentinel provisioner route with the InternalControl bearer and read scope', async () => {
+ it.each([
+ ['chatllm', 'host:1st:mcp-host/chatllm'],
+ ['chatllm-stateless', 'host:1st:mcp-host/chatllm-stateless'],
+ ])('mints an independent token for Host %s', async (name, subject) => {
+ const token = jwt({ sub: subject, scopes: ['gfs.read', 'gfs.write'] })
const fetchFn = vi.fn(async () =>
- okResponse({ token: 'tok', expiresInSeconds: 300, subject: 'host:1st:mcp-host/standalone' })
+ okResponse({ token, expiresInSeconds: 300, subject })
) as unknown as typeof fetch
- const out = await mintHostGfsToken({
- controlApiBaseUrl: 'http://control-api:8090',
- signToken: () => 'hcc-jwt',
- fetchFn,
- })
+ const out = await mintHostGfsToken(
+ { name, namespace: 'mcp-host' },
+ {
+ controlApiBaseUrl: 'http://control-api:8090',
+ signToken: () => 'hcc-jwt',
+ fetchFn,
+ }
+ )
- expect(out.subject).toBe('host:1st:mcp-host/standalone')
- expect(out.token).toBe('tok')
+ expect(out.subject).toBe(subject)
+ expect(out.token).toBe(token)
const [url, init] = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls[0]
- expect(url).toBe('http://control-api:8090/api/v1/auth/gfs/standalone/tokens')
+ expect(url).toBe(`http://control-api:8090/api/v1/auth/gfs/${name}/tokens`)
expect(init.headers.Authorization).toBe('Bearer hcc-jwt')
- expect(JSON.parse(init.body)).toEqual({ namespace: 'mcp-host', scopes: ['gfs.read'] })
+ expect(JSON.parse(init.body)).toEqual({
+ namespace: 'mcp-host',
+ scopes: ['gfs.read', 'gfs.write'],
+ })
})
it('fails loud on a non-2xx response (never silently degrades)', async () => {
@@ -39,10 +54,94 @@ describe('mintHostGfsToken', () => {
async () => ({ ok: false, status: 403 }) as Response
) as unknown as typeof fetch
await expect(
- mintHostGfsToken({ controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn })
+ mintHostGfsToken(
+ { name: 'chatllm', namespace: 'mcp-host' },
+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }
+ )
).rejects.toThrow(/403/)
})
+ it('rejects a fleet-wide subject returned for a concrete Host', async () => {
+ const fetchFn = vi.fn(async () =>
+ okResponse({
+ token: jwt({
+ sub: 'host:1st:mcp-host/standalone',
+ scopes: ['gfs.read', 'gfs.write'],
+ }),
+ expiresInSeconds: 300,
+ subject: 'host:1st:mcp-host/standalone',
+ })
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintHostGfsToken(
+ { name: 'chatllm', namespace: 'mcp-host' },
+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }
+ )
+ ).rejects.toThrow(
+ 'gfs host token subject mismatch: expected host:1st:mcp-host/chatllm, received host:1st:mcp-host/standalone'
+ )
+ })
+
+ it.each([
+ ['an opaque token', 'not-a-jwt', 'gfs host token is not a JWT'],
+ ['a malformed payload', 'header.bm90LWpzb24.signature', 'malformed JWT payload'],
+ ])('rejects %s after response metadata validation', async (_case, token, message) => {
+ const subject = 'host:1st:mcp-host/chatllm'
+ const fetchFn = vi.fn(async () =>
+ okResponse({ token, expiresInSeconds: 300, subject })
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintHostGfsToken(
+ { name: 'chatllm', namespace: 'mcp-host' },
+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }
+ )
+ ).rejects.toThrow(message)
+ })
+
+ it('rejects a JWT whose subject claim does not match the concrete Host', async () => {
+ const subject = 'host:1st:mcp-host/chatllm'
+ const fetchFn = vi.fn(async () =>
+ okResponse({
+ token: jwt({
+ sub: 'host:1st:mcp-host/other-host',
+ scopes: ['gfs.read', 'gfs.write'],
+ }),
+ expiresInSeconds: 300,
+ subject,
+ })
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintHostGfsToken(
+ { name: 'chatllm', namespace: 'mcp-host' },
+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }
+ )
+ ).rejects.toThrow(
+ 'gfs host token claim subject mismatch: expected host:1st:mcp-host/chatllm, received host:1st:mcp-host/other-host'
+ )
+ })
+
+ it.each([
+ ['missing', undefined],
+ ['read-only', ['gfs.read']],
+ ['reordered', ['gfs.write', 'gfs.read']],
+ ['expanded', ['gfs.read', 'gfs.write', 'gfs.delete']],
+ ])('rejects %s JWT scopes', async (_case, scopes) => {
+ const subject = 'host:1st:mcp-host/chatllm'
+ const fetchFn = vi.fn(async () =>
+ okResponse({ token: jwt({ sub: subject, scopes }), expiresInSeconds: 300, subject })
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintHostGfsToken(
+ { name: 'chatllm', namespace: 'mcp-host' },
+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }
+ )
+ ).rejects.toThrow('gfs host token claim scopes mismatch: expected ["gfs.read","gfs.write"]')
+ })
+
it('aborts a hung request and waits for the transport to reject', async () => {
vi.useFakeTimers()
try {
@@ -56,11 +155,14 @@ describe('mintHostGfsToken', () => {
}) as unknown as typeof fetch
let settled = false
- const request = mintHostGfsToken({
- controlApiBaseUrl: 'http://control-api:8090',
- signToken: () => 'hcc-jwt',
- fetchFn,
- })
+ const request = mintHostGfsToken(
+ { name: 'chatllm', namespace: 'mcp-host' },
+ {
+ controlApiBaseUrl: 'http://control-api:8090',
+ signToken: () => 'hcc-jwt',
+ fetchFn,
+ }
+ )
const outcome = request.then(
value => {
settled = true
diff --git a/host-context-controller/src/gfsHostBinding.ts b/host-context-controller/src/gfsHostBinding.ts
index e1ca0b856..798fc5360 100644
--- a/host-context-controller/src/gfsHostBinding.ts
+++ b/host-context-controller/src/gfsHostBinding.ts
@@ -6,11 +6,12 @@ import { signInternalControlJwt } from './utils/internalControlSigner'
* P3-S02). HCC asks control-api (the sole gfs token minter) for a host token and
* mounts it on the Host's mcp-host pod.
*
- * Every HCC-provisioned Host shares the SENTINEL binding `mcp-host/standalone` —
- * the `host.name` (e.g. chatllm) is K8s-provisioning-only (Secret name + labels),
- * NEVER a JWT claim. From control-api's auth perspective every 1st-party host is
- * the same binding class (`host:1st:mcp-host/standalone`). Read-only scope in P3
- * (agent write is P4).
+ * Each HCC-provisioned Host keeps its Kubernetes identity in the GFS subject.
+ * For example, the `mcp-host/chatllm` Host receives
+ * `host:1st:mcp-host/chatllm`; another Host is never authorized through the
+ * same binding. The token ceiling permits the Control UI's supported Host
+ * operations, read and write; resource grants still decide which concrete
+ * resources the Host may access.
*/
export interface GfsHostToken {
@@ -27,10 +28,57 @@ export interface GfsHostBindingDeps {
fetchFn?: typeof fetch
}
-const SENTINEL_NAMESPACE = 'mcp-host'
-const SENTINEL_NAME = 'standalone'
+export interface GfsFirstPartyHostRef {
+ name: string
+ namespace: string
+}
+
export const GFS_HOST_TOKEN_REQUEST_TIMEOUT_MS = 10_000
export const GFS_HOST_TOKEN_REQUEST_TIMEOUT_CODE = 'HCC_GFS_HOST_TOKEN_REQUEST_TIMEOUT'
+const GFS_HOST_TOKEN_SCOPES = ['gfs.read', 'gfs.write'] as const
+
+function validateIssuedTokenClaims(
+ token: unknown,
+ expectedSubject: string
+): asserts token is string {
+ if (typeof token !== 'string') {
+ throw new Error('gfs host token is not a JWT')
+ }
+
+ const segments = token.split('.')
+ if (segments.length !== 3 || segments.some(segment => !/^[A-Za-z0-9_-]+$/.test(segment))) {
+ throw new Error('gfs host token is not a JWT')
+ }
+
+ let claims: unknown
+ try {
+ claims = JSON.parse(Buffer.from(segments[1], 'base64url').toString('utf8'))
+ } catch {
+ throw new Error('gfs host token has a malformed JWT payload')
+ }
+
+ if (typeof claims !== 'object' || claims === null || Array.isArray(claims)) {
+ throw new Error('gfs host token has a malformed JWT payload')
+ }
+
+ const payload = claims as Record<string, unknown>
+ if (payload.sub !== expectedSubject) {
+ throw new Error(
+ `gfs host token claim subject mismatch: expected ${expectedSubject}, received ${String(payload.sub)}`
+ )
+ }
+
+ const scopes = payload.scopes
+ if (
+ !Array.isArray(scopes) ||
+ scopes.length !== GFS_HOST_TOKEN_SCOPES.length ||
+ !GFS_HOST_TOKEN_SCOPES.every((scope, index) => scopes[index] === scope)
+ ) {
+ throw new Error(
+ `gfs host token claim scopes mismatch: expected ${JSON.stringify(GFS_HOST_TOKEN_SCOPES)}`
+ )
+ }
+}
export class GfsHostTokenMintTimeoutError extends Error {
readonly code = GFS_HOST_TOKEN_REQUEST_TIMEOUT_CODE
@@ -52,11 +100,15 @@ export class GfsHostTokenMintTimeoutError extends Error {
* loud on any non-2xx — a host without a working gfs token must surface, never
* silently degrade.
*/
-export async function mintHostGfsToken(deps: GfsHostBindingDeps = {}): Promise<GfsHostToken> {
+export async function mintHostGfsToken(
+ host: GfsFirstPartyHostRef,
+ deps: GfsHostBindingDeps = {}
+): Promise<GfsHostToken> {
const baseUrl = deps.controlApiBaseUrl ?? config.controlApiBaseUrl
const sign = deps.signToken ?? signInternalControlJwt
const doFetch = deps.fetchFn ?? fetch
- const url = `${baseUrl}/api/v1/auth/gfs/${SENTINEL_NAME}/tokens`
+ const url = `${baseUrl}/api/v1/auth/gfs/${encodeURIComponent(host.name)}/tokens`
+ const expectedSubject = `host:1st:${host.namespace}/${host.name}`
const timeoutError = new GfsHostTokenMintTimeoutError(GFS_HOST_TOKEN_REQUEST_TIMEOUT_MS)
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(timeoutError), GFS_HOST_TOKEN_REQUEST_TIMEOUT_MS)
@@ -69,7 +121,10 @@ export async function mintHostGfsToken(deps: GfsHostBindingDeps = {}): Promise<G
'content-type': 'application/json',
Authorization: `Bearer ${sign()}`,
},
- body: JSON.stringify({ namespace: SENTINEL_NAMESPACE, scopes: ['gfs.read'] }),
+ body: JSON.stringify({
+ namespace: host.namespace,
+ scopes: GFS_HOST_TOKEN_SCOPES,
+ }),
signal: controller.signal,
})
if (controller.signal.aborted) throw timeoutError
@@ -78,6 +133,12 @@ export async function mintHostGfsToken(deps: GfsHostBindingDeps = {}): Promise<G
}
const body = (await response.json()) as GfsHostToken
if (controller.signal.aborted) throw timeoutError
+ if (body.subject !== expectedSubject) {
+ throw new Error(
+ `gfs host token subject mismatch: expected ${expectedSubject}, received ${body.subject}`
+ )
+ }
+ validateIssuedTokenClaims(body.token, expectedSubject)
return body
} catch (error) {
if (error instanceof GfsHostTokenMintTimeoutError) throw error
diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.ts
index f33bf20d5..af87512ae 100644
--- a/host-context-controller/src/hostReconciler.test.ts
+++ b/host-context-controller/src/hostReconciler.test.ts
@@ -44,11 +44,13 @@ vi.mock('./config', () => ({
}))
vi.mock('./gfsHostBinding', () => ({
- mintHostGfsToken: vi.fn().mockResolvedValue({
- token: 'gfs-runtime-value',
- expiresInSeconds: 300,
- subject: 'host:1st:mcp-host/standalone',
- }),
+ mintHostGfsToken: vi
+ .fn()
+ .mockImplementation(async ({ name, namespace }: { name: string; namespace: string }) => ({
+ token: 'gfs-runtime-value',
+ expiresInSeconds: 300,
+ subject: `host:1st:${namespace}/${name}`,
+ })),
}))
function makeHost(overrides: Partial<HostCRD['spec']> & { name?: string } = {}): HostCRD {
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index a5932283f..c6ca15041 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -126,7 +126,10 @@ const RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION = 'clerum.io/runtime-token-bootst
const RUNTIME_TOKEN_ROLLOUT_REQUIRED_ANNOTATION = 'clerum.io/runtime-token-rollout-required'
const RUNTIME_TOKEN_ISSUER = 'control-api'
const RUNTIME_TOKEN_AUDIENCE = 'workflow-approvals'
-const RUNTIME_TOKEN_SCHEMA_VERSION = '1'
+// v2 binds the GFS token to the concrete Host CRD instead of the historical
+// fleet-wide `mcp-host/standalone` sentinel. The version change makes existing
+// Secrets fail the contract check so HCC rotates them and rolls each Host.
+const RUNTIME_TOKEN_SCHEMA_VERSION = '2'
const RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESH = 'fresh'
const RUNTIME_TOKEN_BOOTSTRAP_STATE_CONSUMED = 'consumed'
// Deployments affected by the historical stringData/data hashing bug can carry
@@ -1082,7 +1085,7 @@ export class HostReconciler {
host.name,
this.resolveWorkflowControlScopesForHost(host, hasChannelIngress)
)
- const gfs = await mintHostGfsToken()
+ const gfs = await mintHostGfsToken({ name: host.name, namespace: host.namespace })
const body = buildMcpHostRuntimeTokenSecret(
host,
tokens.accessToken,
diff --git a/host-context-controller/test/config.k8sApiCidrs.test.ts b/host-context-controller/test/config.k8sApiCidrs.test.ts
index e8ca5766c..a74277253 100644
--- a/host-context-controller/test/config.k8sApiCidrs.test.ts
+++ b/host-context-controller/test/config.k8sApiCidrs.test.ts
@@ -13,9 +13,9 @@ describe('config.k8sApiCidrs', () => {
})
it('parses a comma-separated value', async () => {
- process.env.CONTEXT_MAPPER_K8S_API_CIDRS = '203.0.113.1/32,10.128.0.2/32'
+ process.env.CONTEXT_MAPPER_K8S_API_CIDRS = '203.0.113.10/32,203.0.113.11/32'
const { config } = await import('../src/config')
- expect(config.k8sApiCidrs).toEqual(['203.0.113.1/32', '10.128.0.2/32'])
+ expect(config.k8sApiCidrs).toEqual(['203.0.113.10/32', '203.0.113.11/32'])
})
it('crashes module load on an over-broad value (fail-closed)', async () => {
diff --git a/host-context-controller/test/hostReconciler.channelReaderIntegration.test.ts b/host-context-controller/test/hostReconciler.channelReaderIntegration.test.ts
index a839bc4bf..7f885adce 100644
--- a/host-context-controller/test/hostReconciler.channelReaderIntegration.test.ts
+++ b/host-context-controller/test/hostReconciler.channelReaderIntegration.test.ts
@@ -90,11 +90,13 @@ vi.mock('../src/mcpHostRuntimeTokenIssuerClient', () => ({
}))
vi.mock('../src/gfsHostBinding', () => ({
- mintHostGfsToken: vi.fn().mockResolvedValue({
- ['to'.concat('ken')]: 'gfs-runtime-value',
- expiresInSeconds: 300,
- subject: 'host:1st:mcp-host/standalone',
- }),
+ mintHostGfsToken: vi
+ .fn()
+ .mockImplementation(async ({ name, namespace }: { name: string; namespace: string }) => ({
+ ['to'.concat('ken')]: 'gfs-runtime-value',
+ expiresInSeconds: 300,
+ subject: `host:1st:${namespace}/${name}`,
+ })),
}))
function makeHost(overrides?: Partial<HostCRD>): HostCRD {
diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.ts
index 46fbbba17..b665f6268 100644
--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts
+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts
@@ -823,6 +823,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
expect(issueTokens).toHaveBeenCalledOnce()
expect(mintGfs).toHaveBeenCalledOnce()
+ expect(mintGfs).toHaveBeenCalledWith({ name: host.name, namespace: host.namespace })
expect(issueTokens).toHaveBeenCalledWith(
host.name,
expect.arrayContaining([
diff --git a/host-context-controller/test/hostReconciler.networkpolicy.test.ts b/host-context-controller/test/hostReconciler.networkpolicy.test.ts
index ebee2eb0e..f1de23109 100644
--- a/host-context-controller/test/hostReconciler.networkpolicy.test.ts
+++ b/host-context-controller/test/hostReconciler.networkpolicy.test.ts
@@ -79,11 +79,13 @@ vi.mock('../src/mcpHostRuntimeTokenIssuerClient', () => ({
}))
vi.mock('../src/gfsHostBinding', () => ({
- mintHostGfsToken: vi.fn().mockResolvedValue({
- ['to'.concat('ken')]: 'gfs-runtime-value',
- expiresInSeconds: 300,
- subject: 'host:1st:mcp-host/standalone',
- }),
+ mintHostGfsToken: vi
+ .fn()
+ .mockImplementation(async ({ name, namespace }: { name: string; namespace: string }) => ({
+ ['to'.concat('ken')]: 'gfs-runtime-value',
+ expiresInSeconds: 300,
+ subject: `host:1st:${namespace}/${name}`,
+ })),
}))
const HOST: HostCRD = {
diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.ts
index bea8aac69..bec0d1a74 100644
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@ -89,11 +89,13 @@ vi.mock('../src/mcpHostRuntimeTokenIssuerClient', () => ({
}))
vi.mock('../src/gfsHostBinding', () => ({
- mintHostGfsToken: vi.fn().mockResolvedValue({
- ['to'.concat('ken')]: 'gfs-runtime-value',
- expiresInSeconds: 300,
- subject: 'host:1st:mcp-host/standalone',
- }),
+ mintHostGfsToken: vi
+ .fn()
+ .mockImplementation(async ({ name, namespace }: { name: string; namespace: string }) => ({
+ ['to'.concat('ken')]: 'gfs-runtime-value',
+ expiresInSeconds: 300,
+ subject: `host:1st:${namespace}/${name}`,
+ })),
}))
function makeHost(overrides?: Partial<HostCRD>): HostCRD {
diff --git a/host-context-controller/test/k8sApiCidrs.test.ts b/host-context-controller/test/k8sApiCidrs.test.ts
index 920834646..92819e642 100644
--- a/host-context-controller/test/k8sApiCidrs.test.ts
+++ b/host-context-controller/test/k8sApiCidrs.test.ts
@@ -12,22 +12,22 @@ describe('parseK8sApiCidrs', () => {
})
it('accepts a single /32', () => {
- expect(parseK8sApiCidrs('203.0.113.1/32')).toEqual(['203.0.113.1/32'])
+ expect(parseK8sApiCidrs('203.0.113.10/32')).toEqual(['203.0.113.10/32'])
})
it('accepts two CIDRs and trims whitespace', () => {
- expect(parseK8sApiCidrs(' 203.0.113.1/32 , 10.128.0.2/32 ')).toEqual([
- '203.0.113.1/32',
- '10.128.0.2/32',
+ expect(parseK8sApiCidrs(' 203.0.113.10/32 , 203.0.113.11/32 ')).toEqual([
+ '203.0.113.10/32',
+ '203.0.113.11/32',
])
})
it('accepts the /24 boundary', () => {
- expect(parseK8sApiCidrs('10.128.0.0/24')).toEqual(['10.128.0.0/24'])
+ expect(parseK8sApiCidrs('203.0.113.11/24')).toEqual(['203.0.113.11/24'])
})
it('rejects a missing prefix', () => {
- expect(() => parseK8sApiCidrs('203.0.113.1')).toThrow(/missing prefix/)
+ expect(() => parseK8sApiCidrs('203.0.113.10')).toThrow(/missing prefix/)
})
it('rejects an invalid IP', () => {
@@ -48,7 +48,7 @@ describe('parseK8sApiCidrs', () => {
it('rejects an IPv4 prefix wider than /24', () => {
expect(() => parseK8sApiCidrs('10.0.0.0/8')).toThrow(/over-broad/)
- expect(() => parseK8sApiCidrs('10.128.0.0/23')).toThrow(/over-broad/)
+ expect(() => parseK8sApiCidrs('203.0.113.11/23')).toThrow(/over-broad/)
})
it('rejects ::/0 as over-broad', () => {
@@ -56,7 +56,7 @@ describe('parseK8sApiCidrs', () => {
})
it('throws if any entry in a list is bad (no partial accept)', () => {
- expect(() => parseK8sApiCidrs('203.0.113.1/32,0.0.0.0/0')).toThrow(/over-broad/)
+ expect(() => parseK8sApiCidrs('203.0.113.10/32,0.0.0.0/0')).toThrow(/over-broad/)
})
})
@@ -86,6 +86,6 @@ describe('parseNodeLocalDnsCidr', () => {
})
it('rejects ranges wider than a single service IP', () => {
- expect(() => parseNodeLocalDnsCidr('203.0.113.0/24')).toThrow(/expected \/32/)
+ expect(() => parseNodeLocalDnsCidr('203.0.113.10/24')).toThrow(/expected \/32/)
})
})
diff --git a/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts b/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
index 4737802dc..a06465eeb 100644
--- a/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
+++ b/host-context-controller/test/networkPolicyReconciler.k8sApiEgress.test.ts
@@ -11,7 +11,7 @@ vi.mock('../src/config', () => ({
rpcProxyNamespace: 'rpc-proxy',
runtimeNamespaces: ['mcp-server', 'rpc-proxy', 'sandbox-recipes'],
port: 8081,
- k8sApiCidrs: ['203.0.113.1/32', '10.128.0.2/32'],
+ k8sApiCidrs: ['203.0.113.10/32', '203.0.113.11/32'],
},
}))
@@ -48,7 +48,7 @@ describe('ensureK8sApiEgress', () => {
const np = k8sApiEgressFor('mcp-server')
expect(np).toBeDefined()
const blocks = np!.spec!.egress![0].to!.map(t => t.ipBlock!.cidr)
- expect(blocks).toEqual(['203.0.113.1/32', '10.128.0.2/32'])
+ expect(blocks).toEqual(['203.0.113.10/32', '203.0.113.11/32'])
})
it('applies the same CIDR set to every runtime namespace', async () => {
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index ba6796a1c..261933b80 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.205",
+ "version": "0.1.206",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.205",
+ "version": "0.1.206",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 045746bcc..c32ca00f0 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.205",
+ "version": "0.1.206",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/tools/__tests__/workflowTools.test.ts b/mcp-host/src/core/tools/__tests__/workflowTools.test.ts
index eae5860dc..4d7559b7f 100644
--- a/mcp-host/src/core/tools/__tests__/workflowTools.test.ts
+++ b/mcp-host/src/core/tools/__tests__/workflowTools.test.ts
@@ -1092,7 +1092,10 @@ describe('workflow native tools', () => {
}),
} as Response)
- const workflowCallerContext = { targetUserId: '00000000-0000-4000-8000-000000000001' }
+ const workflowCallerContext = {
+ targetUserId: '00000000-0000-4000-8000-000000000001',
+ conversationId: 'thread-1',
+ }
const statusResult = await new WorkflowStatusTool({
getEnv: env(),
workflowCallerContext,
@@ -1123,13 +1126,13 @@ describe('workflow native tools', () => {
'http://gateway:8092/api/v1/workflows/effective-targets/resolve'
)
expect(fetchMock.mock.calls[1][0]).toBe(
- 'http://gateway:8092/api/v1/workflows/sandbox-recipes/source-recipe?targetUserId=00000000-0000-4000-8000-000000000001'
+ 'http://gateway:8092/api/v1/workflows/sandbox-recipes/source-recipe?targetUserId=00000000-0000-4000-8000-000000000001&workflowConversationId=thread-1'
)
expect(fetchMock.mock.calls[2][0]).toBe(
'http://gateway:8092/api/v1/workflows/effective-targets/resolve'
)
expect(fetchMock.mock.calls[3][0]).toBe(
- 'http://gateway:8092/api/v1/workflows/sandbox-recipes/source-recipe/health?targetUserId=00000000-0000-4000-8000-000000000001'
+ 'http://gateway:8092/api/v1/workflows/sandbox-recipes/source-recipe/health?targetUserId=00000000-0000-4000-8000-000000000001&workflowConversationId=thread-1'
)
})
@@ -1169,6 +1172,7 @@ describe('workflow native tools', () => {
const workflowCallerContext = {
targetUserId: '00000000-0000-4000-8000-000000000001',
targetTeamId: '00000000-0000-4000-8000-0000000000aa',
+ conversationId: 'thread-1',
}
const statusResult = await new WorkflowStatusTool({
getEnv: env(),
@@ -1189,21 +1193,23 @@ describe('workflow native tools', () => {
expect(healthResult.is_error).toBe(false)
expect(fetchMock.mock.calls.map(call => call[0])).toEqual([
'http://gateway:8092/api/v1/workflows/effective-targets/resolve',
- 'http://gateway:8092/api/v1/workflows/sandbox-recipes/team-recipe?targetTeamId=00000000-0000-4000-8000-0000000000aa',
+ 'http://gateway:8092/api/v1/workflows/sandbox-recipes/team-recipe?targetTeamId=00000000-0000-4000-8000-0000000000aa&workflowConversationId=thread-1',
'http://gateway:8092/api/v1/workflows/effective-targets/resolve',
- 'http://gateway:8092/api/v1/workflows/sandbox-recipes/team-recipe/health?targetTeamId=00000000-0000-4000-8000-0000000000aa',
+ 'http://gateway:8092/api/v1/workflows/sandbox-recipes/team-recipe/health?targetTeamId=00000000-0000-4000-8000-0000000000aa&workflowConversationId=thread-1',
])
expect(JSON.parse(String((fetchMock.mock.calls[0][1] as RequestInit).body))).toEqual({
purpose: 'trigger',
userId: '00000000-0000-4000-8000-000000000001',
recipeNamespace: 'sandbox-recipes',
recipeName: 'team-recipe',
+ conversationId: 'thread-1',
})
expect(JSON.parse(String((fetchMock.mock.calls[2][1] as RequestInit).body))).toEqual({
purpose: 'trigger',
userId: '00000000-0000-4000-8000-000000000001',
recipeNamespace: 'sandbox-recipes',
recipeName: 'team-recipe',
+ conversationId: 'thread-1',
})
})
diff --git a/mcp-host/src/core/tools/workflowReadTools.ts b/mcp-host/src/core/tools/workflowReadTools.ts
index 1cef7e6ee..64b8ef270 100644
--- a/mcp-host/src/core/tools/workflowReadTools.ts
+++ b/mcp-host/src/core/tools/workflowReadTools.ts
@@ -275,6 +275,15 @@ function approvalTargetParamSet(
return [{ targetUserId: context.targetUserId }, { targetTeamId: context.targetTeamId }]
}
+function attachWorkflowConversation(
+ targets: Record<string, unknown>[],
+ context: WorkflowCallerContext | null
+): Record<string, unknown>[] {
+ const conversationId = context?.conversationId?.trim()
+ if (!conversationId) return targets
+ return targets.map(target => ({ ...target, workflowConversationId: conversationId }))
+}
+
function isApprovalTargetMiss(error: unknown): boolean {
if (!(error instanceof Error)) return false
return /\((403|404)\)/.test(error.message)
@@ -906,6 +915,7 @@ export class WorkflowStatusTool extends WorkflowTool {
} else {
targets = approvalTargetParamSet(params, this.workflowCallerContext)
}
+ targets = attachWorkflowConversation(targets, this.workflowCallerContext)
const result = await requestWithApprovalTargetFallback(targets, target =>
this.client.request(
appendApprovalTargetQuery(
@@ -963,6 +973,7 @@ export class WorkflowHealthTool extends WorkflowTool {
} else {
targets = approvalTargetParamSet(params, this.workflowCallerContext)
}
+ targets = attachWorkflowConversation(targets, this.workflowCallerContext)
const result = await requestWithApprovalTargetFallback(targets, target =>
this.client.request(
appendApprovalTargetQuery(
diff --git a/mcp-host/src/workflow/workflowService.gating.test.ts b/mcp-host/src/workflow/workflowService.gating.test.ts
index d844bae35..9d1b26d0e 100644
--- a/mcp-host/src/workflow/workflowService.gating.test.ts
+++ b/mcp-host/src/workflow/workflowService.gating.test.ts
@@ -3,6 +3,8 @@ import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import { config } from '../config'
+import { FinishReason } from '../core/types'
+import { createGfscClient } from '../internalTools/gfsClient'
import type { SingleTurnProvider } from '../llm'
import { getMcpHostJwtStateFilePath } from './mcpHostJwtState'
import { gateStep } from './userApprovalRequester'
@@ -12,6 +14,21 @@ vi.mock('./userApprovalRequester', () => ({
gateStep: vi.fn(),
}))
+const gfsGate = vi.hoisted(() => ({ enabled: false }))
+const gfsClient = vi.hoisted(() => ({
+ accessible: vi.fn(),
+ list: vi.fn(),
+ read: vi.fn(),
+ stat: vi.fn(),
+ resolve: vi.fn(),
+ write: vi.fn(),
+}))
+
+vi.mock('../internalTools/gfsClient', () => ({
+ hasGfsRuntimeAccess: vi.fn(() => gfsGate.enabled),
+ createGfscClient: vi.fn(() => gfsClient),
+}))
+
function makeJwt(exp: number, label: string): string {
const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url')
const payload = Buffer.from(
@@ -58,6 +75,7 @@ describe('WorkflowService approval gating', () => {
beforeEach(() => {
vi.clearAllMocks()
+ gfsGate.enabled = false
const nowSecs = Math.floor(Date.now() / 1000)
config.mcpHostRuntimeAccessToken = makeJwt(nowSecs + 600, 'initial-access')
config.mcpHostRuntimeRefreshToken = makeJwt(nowSecs + 900, 'initial-refresh')
@@ -325,10 +343,13 @@ describe('WorkflowService approval gating', () => {
describe('WorkflowService internal-tools capability gate (#592)', () => {
const originalOutputDir = process.env.CLERUM_OUTPUT_DIR
const originalMounts = process.env.CLERUM_CONTEXT_FILES_MOUNTS
+ const originalGfsScopes = process.env.MCP_HOST_GFS_SCOPES
let tempDir = ''
beforeEach(() => {
vi.clearAllMocks()
+ gfsGate.enabled = false
+ delete process.env.MCP_HOST_GFS_SCOPES
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wf-capgate-'))
process.env.CLERUM_OUTPUT_DIR = tempDir
})
@@ -338,6 +359,8 @@ describe('WorkflowService internal-tools capability gate (#592)', () => {
else process.env.CLERUM_OUTPUT_DIR = originalOutputDir
if (originalMounts === undefined) delete process.env.CLERUM_CONTEXT_FILES_MOUNTS
else process.env.CLERUM_CONTEXT_FILES_MOUNTS = originalMounts
+ if (originalGfsScopes === undefined) delete process.env.MCP_HOST_GFS_SCOPES
+ else process.env.MCP_HOST_GFS_SCOPES = originalGfsScopes
fs.rmSync(tempDir, { recursive: true, force: true })
})
@@ -346,7 +369,13 @@ describe('WorkflowService internal-tools capability gate (#592)', () => {
// getFilteredTools() returns the intersection of the REGISTERED catalog with
// the include list, so a context-files tool appears here only if
// workflowService actually registered it (i.e. the SFS gate let it through).
- async function toolNamesExposedToProvider(): Promise<string[]> {
+ async function toolNamesExposedToProvider(
+ include = [
+ 'clerum__generate_markdown',
+ 'clerum__context_files_list',
+ 'clerum__context_files_read',
+ ]
+ ): Promise<string[]> {
const provider = makeProvider()
const service = new WorkflowService('recipe-1', {
llmFactory: () => provider,
@@ -362,11 +391,7 @@ describe('WorkflowService internal-tools capability gate (#592)', () => {
stepId: 'gate-step',
instruction: 'Do the thing.',
allowedTools: {
- include: [
- 'clerum__generate_markdown',
- 'clerum__context_files_list',
- 'clerum__context_files_read',
- ],
+ include,
},
})
expect(result.status).toBe('completed')
@@ -399,4 +424,146 @@ describe('WorkflowService internal-tools capability gate (#592)', () => {
expect(names).toContain('clerum__context_files_list')
expect(names).toContain('clerum__context_files_read')
})
+
+ it('does not expose GFS tools when runtime access is absent', async () => {
+ process.env.MCP_HOST_GFS_SCOPES = 'gfs.read,gfs.write'
+ const names = await toolNamesExposedToProvider([
+ 'clerum__generate_markdown',
+ 'clerum__gfs_read',
+ 'clerum__gfs_write',
+ ])
+
+ expect(names).toContain('clerum__generate_markdown')
+ expect(names).not.toContain('clerum__gfs_read')
+ expect(names).not.toContain('clerum__gfs_write')
+ })
+
+ it('does not register or expose GFS tools without an explicit allowedTools opt-in', async () => {
+ gfsGate.enabled = true
+ process.env.MCP_HOST_GFS_SCOPES = 'gfs.read,gfs.write'
+
+ const names = await toolNamesExposedToProvider(['clerum__generate_markdown'])
+
+ expect(names).toEqual(['clerum__generate_markdown'])
+ expect(createGfscClient).not.toHaveBeenCalled()
+ })
+
+ it('exposes the existing GFS read and write tools when runtime access is present', async () => {
+ gfsGate.enabled = true
+ process.env.MCP_HOST_GFS_SCOPES = 'gfs.read,gfs.write'
+
+ const names = await toolNamesExposedToProvider([
+ 'clerum__generate_markdown',
+ 'clerum__gfs_accessible',
+ 'clerum__gfs_list',
+ 'clerum__gfs_read',
+ 'clerum__gfs_stat',
+ 'clerum__gfs_resolve',
+ 'clerum__gfs_write',
+ ])
+
+ expect(names).toEqual(
+ expect.arrayContaining([
+ 'clerum__generate_markdown',
+ 'clerum__gfs_accessible',
+ 'clerum__gfs_list',
+ 'clerum__gfs_read',
+ 'clerum__gfs_stat',
+ 'clerum__gfs_resolve',
+ 'clerum__gfs_write',
+ ])
+ )
+ })
+
+ it('does not register a GFS write tool for a read-only runtime credential', async () => {
+ gfsGate.enabled = true
+ process.env.MCP_HOST_GFS_SCOPES = 'gfs.read'
+
+ const names = await toolNamesExposedToProvider([
+ 'clerum__generate_markdown',
+ 'clerum__gfs_read',
+ 'clerum__gfs_write',
+ ])
+
+ expect(names).toContain('clerum__gfs_read')
+ expect(names).not.toContain('clerum__gfs_write')
+ })
+
+ it('dispatches workflow GFS calls through the existing gfsc client boundary', async () => {
+ gfsGate.enabled = true
+ process.env.MCP_HOST_GFS_SCOPES = 'gfs.read'
+ gfsClient.read.mockResolvedValue({ content: 'granted file content' })
+ const provider = makeProvider()
+ vi.mocked(provider.completeSingleTurnWithTools)
+ .mockResolvedValueOnce({
+ content: '',
+ tool_calls: [
+ {
+ id: 'gfs-read-1',
+ name: 'clerum__gfs_read',
+ arguments: { drive: 'main', resourceId: '0123456789abcdef0123456789abcdef' },
+ },
+ ],
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
+ finish_reason: FinishReason.ToolUse,
+ })
+ .mockResolvedValueOnce({
+ content: 'Read completed.',
+ tool_calls: [],
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
+ finish_reason: FinishReason.Stop,
+ })
+ const service = new WorkflowService('recipe-1', {
+ llmFactory: () => provider,
+ mcpClientFactory: () => {
+ throw new Error('mcp client must not be created in this GFS gate test')
+ },
+ })
+ service.configure({ provider: 'openai', apiKey: 'test-key', model: 'gpt-4o' })
+
+ const result = await service.executeStep({
+ stepId: 'gfs-read-step',
+ instruction: 'Read the granted file.',
+ allowedTools: { include: ['clerum__gfs_read'] },
+ })
+
+ expect(result.status).toBe('completed')
+ expect(result.toolsCalled).toEqual([
+ expect.objectContaining({
+ serverName: 'clerum',
+ toolName: 'gfs_read',
+ result: expect.objectContaining({ success: true }),
+ }),
+ ])
+ expect(gfsClient.read).toHaveBeenCalledWith({
+ drive: 'main',
+ resourceId: '0123456789abcdef0123456789abcdef',
+ })
+ })
+
+ it('fails closed when toolChoice is required but no allowed tool is available', async () => {
+ const provider = makeProvider()
+ const service = new WorkflowService('recipe-1', {
+ llmFactory: () => provider,
+ mcpClientFactory: () => {
+ throw new Error('mcp client must not be created in this required-tool gate test')
+ },
+ })
+ service.configure({ provider: 'openai', apiKey: 'test-key', model: 'gpt-4o' })
+
+ const result = await service.executeStep({
+ stepId: 'required-missing-tool',
+ instruction: 'Use the unavailable tool.',
+ allowedTools: { include: ['clerum__gfs_read'] },
+ toolChoice: 'required',
+ })
+
+ expect(result).toMatchObject({
+ status: 'failed',
+ error:
+ 'required-tool-unavailable: step requires a tool call but no allowed tools are available',
+ })
+ expect(provider.completeSingleTurn).not.toHaveBeenCalled()
+ expect(provider.completeSingleTurnWithTools).not.toHaveBeenCalled()
+ })
})
diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.ts
index 0396fb34e..7416b718b 100644
--- a/mcp-host/src/workflow/workflowService.ts
+++ b/mcp-host/src/workflow/workflowService.ts
@@ -12,6 +12,8 @@ import type { BudgetVerdict } from '../budget/types'
import { createGetCapabilitiesTool } from '../capabilities/getCapabilitiesTool'
import { config } from '../config'
import { FinishReason, type ToolDefinition } from '../core/types'
+import { buildGfsReadTools, buildGfsWriteTools } from '../internalTools/gfs'
+import { createGfscClient, hasGfsRuntimeAccess } from '../internalTools/gfsClient'
import { SingleTurnProvider, createLLMProvider } from '../llm'
import { type LlmProvider, descriptorFor, isLlmProvider, primarySlot } from '../llm/registryCore'
import type { ApiKeys } from '../types'
@@ -717,10 +719,38 @@ export class WorkflowService {
// a recipe (workflow) runtime never mounts a SharedFileSystem (the SFS PVC is
// in the mcp-host namespace; recipe pods run in sandbox-recipes), so they would
// be dead tools in every recipe step agent's toolset.
- router.registerInternalTools(
- [...resolveInternalTools(), createGetCapabilitiesTool(key => process.env[key])],
- getOutputDir()
+ const internalTools = [
+ ...resolveInternalTools(),
+ createGetCapabilitiesTool(key => process.env[key]),
+ ]
+ const requestedGfsToolNames = new Set(
+ (req.allowedTools?.include ?? []).filter(name => name.startsWith('clerum__gfs_'))
)
+ const gfsEnv = {
+ get: (key: string): string | undefined => process.env[key],
+ }
+ const rawGfsScopes = (process.env.MCP_HOST_GFS_SCOPES ?? '')
+ .split(',')
+ .map(scope => scope.trim())
+ .filter(Boolean)
+ const knownGfsScopes = new Set([
+ 'gfs.read',
+ 'gfs.write',
+ 'gfs.delete',
+ 'gfs.manage_acl',
+ 'gfs.share',
+ ])
+ const validGfsScopes = rawGfsScopes.every(scope => knownGfsScopes.has(scope))
+ const gfsScopes = new Set(validGfsScopes ? rawGfsScopes : [])
+ if (requestedGfsToolNames.size > 0 && gfsScopes.size > 0 && hasGfsRuntimeAccess(gfsEnv)) {
+ const gfsClient = createGfscClient(gfsEnv)
+ const scopedGfsTools = [
+ ...(gfsScopes.has('gfs.read') ? buildGfsReadTools(gfsClient) : []),
+ ...(gfsScopes.has('gfs.write') ? buildGfsWriteTools(gfsClient) : []),
+ ].filter(tool => requestedGfsToolNames.has(tool.name))
+ internalTools.push(...scopedGfsTools)
+ }
+ router.registerInternalTools(internalTools, getOutputDir())
const toolsCalled: ToolCallRecord[] = []
let totalInputTokens = 0
let totalOutputTokens = 0
@@ -880,6 +910,17 @@ export class WorkflowService {
description: t.description ?? '',
parameters: (t.inputSchema ?? {}) as Record<string, unknown>,
}))
+ if (req.toolChoice === 'required' && toolDefs.length === 0) {
+ this.revertSoulToGlobal()
+ return {
+ stepId: req.stepId,
+ status: 'failed',
+ error:
+ 'required-tool-unavailable: step requires a tool call but no allowed tools are available',
+ toolsCalled,
+ durationMs: Date.now() - startTime,
+ }
+ }
// 3. Build system prompt
const soulContent = this.soulOverrideActive ? this.stepSoulContent : this.globalSoulContent
@@ -923,7 +964,7 @@ export class WorkflowService {
const envDefault = parseInt(process.env.CLERUM_WORKFLOW_MAX_ITERATIONS ?? '50', 10)
const MAX_ITERATIONS = req.maxIterations ?? (envDefault > 0 ? envDefault : 50)
const WRAP_UP_THRESHOLD = 3 // Force wrap-up when this many iterations remain
- const requiresToolCall = req.toolChoice === 'required' && toolDefs.length > 0
+ const requiresToolCall = req.toolChoice === 'required'
for (let i = 0; i < MAX_ITERATIONS; i++) {
onProgress?.({ iteration: i + 1 })
diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.json
index 1050de0c7..cf7a9429a 100644
--- a/profile-ui/package-lock.json
+++ b/profile-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.100",
+ "version": "0.1.101",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-profile-ui",
- "version": "0.1.100",
+ "version": "0.1.101",
"dependencies": {
"next": "16.2.6",
"react": "^18.3.1",
diff --git a/profile-ui/package.json b/profile-ui/package.json
index c085451b1..8b58d506a 100644
--- a/profile-ui/package.json
+++ b/profile-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.100",
+ "version": "0.1.101",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/scripts/e2e/e2e-gke-rbac.sh b/scripts/e2e/e2e-gke-rbac.sh
index 14a4f9847..62cb734d8 100755
--- a/scripts/e2e/e2e-gke-rbac.sh
+++ b/scripts/e2e/e2e-gke-rbac.sh
@@ -46,7 +46,7 @@ echo ""
# ═════════════════════════════════════════════════════════════════════
log "Phase 1: ClusterRoles Exist"
-for role in control-api-cluster-role control-api-pod-reader wrc-trigger-role host-context-controller-role; do
+for role in control-api-cluster-role control-api-pod-reader host-context-controller-role; do
if kubectl get clusterrole "$role" >/dev/null 2>&1; then
pass "ClusterRole $role exists"
detail "$(kubectl get clusterrole "$role" -o jsonpath='{.metadata.creationTimestamp}')"
@@ -61,7 +61,7 @@ echo ""
# ═════════════════════════════════════════════════════════════════════
log "Phase 2: ClusterRoleBindings Exist"
-for binding in control-api-cluster-binding control-api-pod-reader-binding wrc-trigger-binding host-context-controller-binding; do
+for binding in control-api-cluster-binding control-api-pod-reader-binding host-context-controller-binding; do
if kubectl get clusterrolebinding "$binding" >/dev/null 2>&1; then
pass "ClusterRoleBinding $binding exists"
detail "$(kubectl get clusterrolebinding "$binding" -o jsonpath='{.roleRef.name}')"
diff --git a/scripts/e2e/e2e-gke-smoke.sh b/scripts/e2e/e2e-gke-smoke.sh
index 2ff2ab719..136b23151 100755
--- a/scripts/e2e/e2e-gke-smoke.sh
+++ b/scripts/e2e/e2e-gke-smoke.sh
@@ -259,7 +259,7 @@ echo ""
# ═════════════════════════════════════════════════════════════════════
log "Phase 7: RBAC Validation"
-for cr in control-api control-api-pod-reader wrc-trigger-role clerum-channel-reader workflow-recipes-cluster-watch; do
+for cr in control-api control-api-pod-reader clerum-channel-reader workflow-recipes-cluster-watch; do
if kubectl get clusterrole "$cr" >/dev/null 2>&1; then
pass "ClusterRole $cr exists"
else
@@ -267,7 +267,7 @@ for cr in control-api control-api-pod-reader wrc-trigger-role clerum-channel-rea
fi
done
-for crb in control-api control-api-pod-reader wrc-trigger-binding clerum-channel-reader workflow-recipes-cluster-watch; do
+for crb in control-api control-api-pod-reader clerum-channel-reader workflow-recipes-cluster-watch; do
if kubectl get clusterrolebinding "$crb" >/dev/null 2>&1; then
pass "ClusterRoleBinding $crb exists"
else
diff --git a/scripts/e2e/gfs-user-e2e-gate.sh b/scripts/e2e/gfs-user-e2e-gate.sh
index 229478485..8ad6320a7 100755
--- a/scripts/e2e/gfs-user-e2e-gate.sh
+++ b/scripts/e2e/gfs-user-e2e-gate.sh
@@ -1,41 +1,8 @@
#!/usr/bin/env bash
-# gfs USER-delegation E2E gate (plan P4-S07 / Phase E) — the end-user plane.
-#
-# Proves the Desktop/Profile delegation journey end-to-end THROUGH THE NEW
-# user-session routes, reusing the EXISTING JWT scheme (no new auth):
-# external-rest-api /api/v1/me/gfs/* → control-api /external/gfs/* (Session
-# JWT plane, service-gated) → gfsc. The user gfs token is minted by the same
-# signGfsToken as operator/host tokens (only sub=users.id).
-#
-# Flow (fail-loud at every step; never skip, never mock-to-green):
-# 1. GlobalFileSystem Ready (gfsc writer, control-api, external-rest-api pods).
-# 2. Seed a scratch root (provisioner / InternalControl JWT).
-# 3. Operator logs in with seeded admin credentials and grants the test USER
-# manage_acl+read on the scratch folder.
-# 4. User logs in via external-rest-api password-login → real session token.
-# 5. User mints a gfs token via /me/gfs/token (the new user-plane mint).
-# 6. User reads the scratch folder it was granted via /me/gfs/resources/:id/
-# children (deny-by-default: it only sees what it was granted).
-# 7. User affordances report held=[manage_acl,read], isOperator=false (the bits
-# the Desktop delegation panel renders).
-# 8. User delegates read to a 2nd subject via /me/gfs/grants — accepted, and the
-# grant row is recorded with granted_by=user:<id> (resolveCaller user path).
-# 9. No-escalation: user tries to grant `write` (a bit it does NOT hold) → 403
-# escalation_rejected (assertMayGrant enforced on the user plane).
-#
-# Scope note (no silent cap): step 8 asserts the delegation LANDS in the store
-# (the governance proof for the user-caller path). That a granted subject then
-# reads is gfsc authz, already proven by scripts/e2e/gfs-e2e-gate.sh; this gate
-# does not spin a 2nd login to avoid a second seeded identity.
-#
-# NOT a CI unit test — needs a live cluster. Run ONLY after a deploy sync on a
-# branch profile, with the test user seeded:
-# CONTEXT=clerum-test scripts/minikube/seed-test-data.sh
-#
-# Usage:
-# CONTEXT=clerum-<topic>-<sha> scripts/e2e/gfs-user-e2e-gate.sh
+# Authenticated end-user GFS gate. It fails loud, uses no mocks, and must run
+# only after deploy sync plus seed-test-data.sh on an allowed local profile.
+# Proves singular delegation compatibility and atomic bulk grant/share behavior.
set -euo pipefail
-
CONTEXT="${CONTEXT:?set CONTEXT to an allowed branch/clerum-test profile (never a prod context)}"
GFS_NS="${GFS_NS:-gfs}"
CONTROL_NS="${CONTROL_NS:-control-plane}"
@@ -46,24 +13,22 @@ CONTROL_API_PORT="${CONTROL_API_PORT:-8090}"
EXT_PORT="${EXT_PORT:-8091}"
DRIVE="${DRIVE:-main}"
TIMEOUT="${TIMEOUT:-180}"
-
TEST_USER_EMAIL="${TEST_USER_EMAIL:[email protected]}"
TEST_USER_PASSWORD="${TEST_USER_PASSWORD:-changeme123!}"
-
TAG="${GFS_E2E_TAG:-$(kubectl --context="$CONTEXT" -n "$CONTROL_NS" get ns "$CONTROL_NS" -o jsonpath='{.metadata.uid}' 2>/dev/null | cut -c1-8 || echo run)}"
-SCRATCH_NAME="user-scratch-e2e-${TAG}"
RUN_NONCE="${GFS_E2E_NONCE:-$(date +%s)}"
-# A throwaway 2nd subject the user delegates read to (no login needed — the row
-# landing is the governance proof). Stable per run.
+RUN_SUFFIX="$(printf '%s' "${TAG}-${RUN_NONCE}-$$" | shasum -a 256 | cut -c1-10)"
+SCRATCH_NAME="user-scratch-e2e-${TAG}-${RUN_SUFFIX}"
DELEGATE_USER_ID="${GFS_E2E_DELEGATE_ID:-00000000-0000-4000-8000-$(printf '%012d' "$((RUN_NONCE % 1000000000000))")}"
-
+SCRATCH_RID=""
+CREATED_SCRATCH=0
+USER_TEAM_ID=""
+CREATED_TEAM=0
kc() { kubectl --context="$CONTEXT" "$@"; }
-
pass=0
fail=0
ok() { echo " PASS: $1"; pass=$((pass + 1)); }
bad() { echo " FAIL: $1"; fail=$((fail + 1)); }
-
die() {
echo "FATAL: $1" >&2
echo "--- gfs namespace pods ---" >&2
@@ -72,7 +37,6 @@ die() {
kc -n "$PROFILES_NS" get pods -o wide 2>&1 | sed 's/^/ /' >&2 || true
exit 1
}
-
wait_ready() {
local ns="$1" sel="$2" deadline=$((SECONDS + TIMEOUT))
while ((SECONDS < deadline)); do
@@ -85,15 +49,12 @@ wait_ready() {
done
die "no Ready pod for '$sel' in ns '$ns' within ${TIMEOUT}s"
}
-
ready_pod() {
kc -n "$1" get pods -l "$2" --field-selector=status.phase=Running \
-o 'jsonpath={range .items[*]}{.metadata.name}{"\t"}{.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}' 2>/dev/null \
| awk -F'\t' '$2=="True"{print $1; exit}'
}
-
echo "== gfs USER-delegation E2E gate (context=$CONTEXT) =="
-
case "$CONTEXT" in
*prod*) die "CONTEXT '$CONTEXT' looks like production — refusing" ;;
esac
@@ -102,14 +63,10 @@ if [[ "$CONTEXT" == "clerum-test" || "$CONTEXT" =~ ^clerum-[a-z0-9][a-z0-9-]*-[0
else
die "CONTEXT '$CONTEXT' is not an allowed local/branch profile for this gate"
fi
-
-
-# ─── 1. Pods Ready ───────────────────────────────────────────────────────────
phase="$(kc -n "$GFS_NS" get globalfilesystem "$GFS_NAME" -o 'jsonpath={.status.phase}' 2>/dev/null || true)"
[[ "$phase" == "Ready" ]] && ok "GlobalFileSystem phase=Ready" || bad "GlobalFileSystem phase='$phase' (want Ready)"
wait_ready "$GFS_NS" "app=gfs-controller" && ok "gfsc pod Ready"
wait_ready "$PROFILES_NS" "app=external-rest-api" && ok "external-rest-api pod Ready"
-
GFSC_POD="$(ready_pod "$GFS_NS" "app=gfs-controller,clerum.io/gfsc-role=writer")"
[[ -n "$GFSC_POD" ]] || die "no Ready gfsc WRITER pod"
CONTROL_POD="$(ready_pod "$CONTROL_NS" "app=control-api")"
@@ -117,12 +74,8 @@ CONTROL_POD="$(ready_pod "$CONTROL_NS" "app=control-api")"
[[ -n "$CONTROL_POD" ]] || die "no Ready control-api pod"
EXT_POD="$(ready_pod "$PROFILES_NS" "app=external-rest-api")"
[[ -n "$EXT_POD" ]] || die "no Ready external-rest-api pod"
-
-# ─── helpers ─────────────────────────────────────────────────────────────────
http_status() { printf '%s' "$1" | cut -f1; }
http_body() { printf '%s' "$1" | cut -f2-; }
-
-# operator session cookie → control-api admin endpoints.
admin_http() {
kc -n "$CONTROL_NS" exec "$CONTROL_POD" -- node -e '
const [method, path, token, body] = process.argv.slice(1)
@@ -134,8 +87,6 @@ admin_http() {
.catch(e => { process.stderr.write(e.message); process.exit(1) })
' "$1" "$2" "$E2E_ADMIN_TOKEN" "${3:-}"
}
-
-# provisioner InternalControl JWT (iss=hcc), signed in-pod → control-api.
ic_http() {
kc -n "$CONTROL_NS" exec "$CONTROL_POD" -- node -e '
const jwt = require("jsonwebtoken")
@@ -152,8 +103,6 @@ ic_http() {
.catch(e => { process.stderr.write(e.message); process.exit(1) })
' "$1" "$2" "${3:-}"
}
-
-# user session: login (no Origin header in-pod → bearer token returned in body).
user_login() {
kc -n "$PROFILES_NS" exec "$EXT_POD" -- node -e '
const [email, password] = process.argv.slice(1)
@@ -165,8 +114,6 @@ user_login() {
.catch(e => { process.stderr.write(e.message); process.exit(1) })
' "$1" "$2"
}
-
-# user-plane call: external-rest-api /api/v1/me/gfs/* with the user bearer token.
user_http() {
kc -n "$PROFILES_NS" exec "$EXT_POD" -- node -e '
const [token, method, path, body] = process.argv.slice(1)
@@ -178,14 +125,63 @@ user_http() {
.catch(e => { process.stderr.write(e.message); process.exit(1) })
' "$1" "$2" "$3" "${4:-}"
}
-
psql_one() {
kc -n "$CONTROL_NS" exec deploy/control-postgres -- \
psql -v ON_ERROR_STOP=1 -U postgres -d profiles -tA -c "$1" 2>/dev/null | tr -d '[:space:]'
}
-
+fixture_uuid() { printf '00000000-0000-4000-8000-%s' "$(printf '%s' "${SCRATCH_NAME}-$1" | shasum -a 256 | cut -c1-12)"; }
+stored_subject_count() { psql_one "SELECT count(*) FROM $1 WHERE drive='$DRIVE' AND resource_id='$SCRATCH_RID' AND (subject_type || ':' || subject_id) IN ($2);"; }
+assert_bulk_success() {
+ local label="$1" response="$2" expected="$3" status body
+ status="$(http_status "$response")"
+ body="$(http_body "$response")"
+ if [[ "$status" =~ ^20 ]] && jq -e --arg rid "$SCRATCH_RID" --argjson expected "$expected" \
+ '.ok == true and .resourceId == $rid and .count == ($expected|length) and [(.updated[]|{type,id})] == $expected' >/dev/null <<<"$body"; then
+ ok "$label returned ordered updated subjects and count"
+ else die "$label response contract failed (status=$status body=$body)"; fi
+}
+assert_correlated_audit() {
+ local label="$1" subjects_sql="$2" expected_count="$3" op_prefix="${4:-grant.put}" summary
+ summary="$(psql_one "SELECT count(*) || '|' || count(DISTINCT subject) || '|' || count(DISTINCT request_id) || '|' || count(*) FILTER (WHERE request_id IS NULL) FROM gfs_audit WHERE gfs_uri='gfs://$DRIVE/$SCRATCH_RID' AND outcome='allowed' AND op LIKE '$op_prefix%' AND subject IN ($subjects_sql);")"
+ if [[ "$summary" == "$expected_count|$expected_count|1|0" ]]; then ok "$label wrote one correlated audit row per target"
+ else bad "$label audit summary='$summary' (want $expected_count|$expected_count|1|0)"; fi
+}
+assert_rejected_atomic() {
+ local table="$1" label="$2" response="$3" subjects_sql="$4" status code
+ status="$(http_status "$response")"; code="$(http_body "$response" | jq -r '.error // empty')"
+ if [[ "$status" == "400" && "$code" == "subjects_invalid" ]]; then ok "$label rejected the complete batch"
+ else bad "$label expected 400 subjects_invalid: $response"; fi
+ if [[ "$(stored_subject_count "$table" "$subjects_sql")" == "0" ]]; then ok "$label wrote no partial rows"
+ else bad "$label persisted a partial row"; fi
+}
+assert_denied_atomic() {
+ local label="$1" response="$2" subjects_sql="$3" expected="$4" status code summary
+ status="$(http_status "$response")"; code="$(http_body "$response" | jq -r '.error // empty')"
+ if [[ "$status" == "403" && "$code" == "escalation_rejected" ]]; then ok "$label returned exact escalation_rejected"
+ else bad "$label expected 403 escalation_rejected: $response"; fi
+ if [[ "$(stored_subject_count gfs_grants "$subjects_sql")" == "0" ]]; then ok "$label wrote no grant rows"
+ else bad "$label persisted a denied grant"; fi
+ summary="$(psql_one "SELECT count(*) || '|' || count(DISTINCT a.subject) || '|' || count(DISTINCT a.request_id) || '|' || count(e.event_id) FROM gfs_audit a LEFT JOIN administrative_events e ON e.source_audit_ref=('gfs_audit:' || a.sequence_no::text) AND e.request_id=a.request_id AND e.action='permission_grant' AND e.outcome='rejected' AND e.authorization_decision='deny' WHERE a.gfs_uri='gfs://$DRIVE/$SCRATCH_RID' AND a.outcome='denied' AND a.subject IN ($subjects_sql);")"
+ if [[ "$summary" == "$expected|$expected|1|$expected" ]]; then ok "$label wrote correlated denial audit/events per target"
+ else bad "$label denial evidence='$summary' (want $expected|$expected|1|$expected)"; fi
+}
+cleanup() {
+ local exit_status=$?
+ trap - EXIT
+ if [[ "$CREATED_TEAM" == "1" && -n "$USER_TEAM_ID" ]]; then
+ kc -n "$CONTROL_NS" exec deploy/control-postgres -- psql -v ON_ERROR_STOP=1 -U postgres -d profiles \
+ -c "DELETE FROM team_members WHERE team_id='$USER_TEAM_ID'::uuid; DELETE FROM teams WHERE id='$USER_TEAM_ID'::uuid AND name='e2e-gfs-issue792-$RUN_SUFFIX';" \
+ >/dev/null 2>&1 || echo "WARN: cleanup failed for owned E2E team $USER_TEAM_ID" >&2
+ fi
+ if [[ "$CREATED_SCRATCH" == "1" && -n "$SCRATCH_RID" ]]; then
+ kc -n "$CONTROL_NS" exec deploy/control-postgres -- psql -v ON_ERROR_STOP=1 -U postgres -d profiles \
+ -c "DELETE FROM gfs_shares WHERE drive='$DRIVE' AND resource_id='$SCRATCH_RID'; DELETE FROM gfs_grants WHERE drive='$DRIVE' AND resource_id='$SCRATCH_RID'; DELETE FROM gfs_resources WHERE drive='$DRIVE' AND resource_id='$SCRATCH_RID';" \
+ >/dev/null 2>&1 || echo "WARN: cleanup failed for owned scratch resource $SCRATCH_RID" >&2
+ fi
+ exit "$exit_status"
+}
+trap cleanup EXIT
CONTROL_ADMIN_USER="${CONTROL_ADMIN_USER:-admin}"
-
operator_admin_password() {
if [[ -n "${E2E_ADMIN_PASSWORD:-}" ]]; then printf '%s' "$E2E_ADMIN_PASSWORD"; return 0; fi
if [[ -n "${ADMIN_PASSWORD:-}" ]]; then printf '%s' "$ADMIN_PASSWORD"; return 0; fi
@@ -197,16 +193,13 @@ operator_admin_password() {
fi
return 1
}
-
ensure_operator_session() {
if [[ -n "${E2E_ADMIN_TOKEN:-}" ]]; then
return 0
fi
-
local admin_password login_payload login_resp login_status login_body session_cookie
admin_password="$(operator_admin_password)" || die "operator admin credential is required to acquire the Control UI session"
login_payload="$(jq -cn --arg u "$CONTROL_ADMIN_USER" --arg p "$admin_password" '{username:$u,password:$p}')"
-
login_resp="$(kc -n "$CONTROL_NS" exec -i "$CONTROL_POD" -- node -e '
let input = ""
process.stdin.setEncoding("utf8")
@@ -231,7 +224,6 @@ ensure_operator_session() {
}
})
' <<<"$login_payload")"
-
login_status="$(http_status "$login_resp")"
session_cookie="$(printf '%s' "$login_resp" | cut -f2)"
login_body="$(printf '%s' "$login_resp" | cut -f3-)"
@@ -239,60 +231,53 @@ ensure_operator_session() {
export E2E_ADMIN_TOKEN="$session_cookie"
ok "operator session obtained through seeded admin login"
}
-
ensure_operator_session
-
-# ─── 2. Seed scratch root (provisioner) ──────────────────────────────────────
resp="$(ic_http POST /api/v1/gfs/seed "{\"drive\":\"$DRIVE\",\"rootDirectories\":[\"/$SCRATCH_NAME\"]}")"
case "$(http_status "$resp")" in
- 200 | 201 | 409) ok "scratch root seeded (/$SCRATCH_NAME)" ;;
+ 200 | 201) CREATED_SCRATCH=1; ok "unique scratch root seeded (/$SCRATCH_NAME)" ;;
+ 409) die "unique scratch root unexpectedly existed before this run (/$SCRATCH_NAME)" ;;
*) die "seed /$SCRATCH_NAME failed: $resp" ;;
esac
SCRATCH_RID="$(psql_one "SELECT resource_id FROM gfs_resources WHERE drive='$DRIVE' AND name='$SCRATCH_NAME' AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1;")"
[[ -n "$SCRATCH_RID" ]] && ok "resolved scratch rid ($SCRATCH_RID)" || die "scratch dir not found after seed"
-
-# ─── 3. Operator grants the test USER manage_acl+read on the scratch folder ──
USER_ID="$(psql_one "SELECT id FROM users WHERE lower(email)=lower('$TEST_USER_EMAIL') LIMIT 1;")"
[[ -n "$USER_ID" ]] && ok "resolved test user id ($USER_ID)" \
|| die "test user '$TEST_USER_EMAIL' not found — run scripts/minikube/seed-test-data.sh first"
-
-grant_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg id "$USER_ID" \
- '{drive:$d, resourceId:$r, subject:{type:"user", id:$id}, permissions:["manage_acl","read"], inherit:true}')"
+USER_TEAM_ID="$(fixture_uuid authority-team)"
+kc -n "$CONTROL_NS" exec deploy/control-postgres -- psql -v ON_ERROR_STOP=1 -U postgres -d profiles \
+ -c "INSERT INTO teams (id, name) VALUES ('$USER_TEAM_ID'::uuid, 'e2e-gfs-issue792-$RUN_SUFFIX'); INSERT INTO team_members (team_id, user_id, role, status) VALUES ('$USER_TEAM_ID'::uuid, '$USER_ID'::uuid, 'member', 'active');" >/dev/null
+CREATED_TEAM=1
+[[ "$(psql_one "SELECT count(*) FROM team_members WHERE team_id='$USER_TEAM_ID' AND user_id='$USER_ID' AND status='active';")" == "1" ]] \
+ && ok "seeded isolated active team membership ($USER_TEAM_ID)" || die "failed to seed isolated active team membership"
+authority_subjects="$(jq -cn --arg u "$USER_ID" --arg t "$USER_TEAM_ID" '[{type:"user",id:$u},{type:"team",id:$t}]')"
+authority_keys="'user:$USER_ID','team:$USER_TEAM_ID'"
+grant_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --argjson s "$authority_subjects" \
+ '{drive:$d, resourceId:$r, subjects:$s, permissions:["manage_acl","share","read","write"], inherit:true}')"
resp="$(admin_http PUT /api/v1/gfs/grants "$grant_body")"
-[[ "$(http_status "$resp")" =~ ^20 ]] && ok "operator granted user manage_acl+read on scratch" \
- || die "operator grant to user failed: $resp"
-
-# ─── 4. User logs in (real session token) ────────────────────────────────────
+assert_bulk_success "real user/team authority bulk grant" "$resp" "$authority_subjects"
+[[ "$(stored_subject_count gfs_grants "$authority_keys")" == "2" ]] && ok "bulk authority stored real direct-user and active-team targets" || die "real user/team authority rows missing"
resp="$(user_login "$TEST_USER_EMAIL" "$TEST_USER_PASSWORD")"
[[ "$(http_status "$resp")" == "200" ]] || die "user password-login failed: $resp"
USER_TOKEN="$(http_body "$resp" | jq -r '.token')"
[[ -n "$USER_TOKEN" && "$USER_TOKEN" != "null" ]] && ok "user logged in (session token)" \
|| die "no bearer token in login response (in-pod exposure gate?): $resp"
-
-# ─── 5. User mints a gfs token via the new user-plane route ──────────────────
resp="$(user_http "$USER_TOKEN" POST /api/v1/me/gfs/token '{"scopes":["gfs.read"]}')"
[[ "$(http_status "$resp")" == "200" ]] || die "user /me/gfs/token mint failed: $resp"
[[ -n "$(http_body "$resp" | jq -r '.token // empty')" ]] && ok "user minted a gfs token (/me/gfs/token)" \
|| die "no token in user mint: $resp"
-
-# ─── 6. User reads the granted folder (deny-by-default honored) ──────────────
resp="$(user_http "$USER_TOKEN" GET "/api/v1/me/gfs/resources/$SCRATCH_RID/children?drive=$DRIVE")"
[[ "$(http_status "$resp")" == "200" ]] && ok "user listed the granted folder (/me/gfs/.../children)" \
|| bad "user children listing failed (granted read not honored?): $resp"
-
-# ─── 7. User affordances reflect the held bits (drives the Desktop panel) ─────
resp="$(user_http "$USER_TOKEN" GET "/api/v1/me/gfs/resources/$SCRATCH_RID/affordances?drive=$DRIVE")"
if [[ "$(http_status "$resp")" == "200" ]]; then
held="$(http_body "$resp" | jq -r '.held | sort | join(",")')"
isop="$(http_body "$resp" | jq -r '.isOperator')"
- [[ "$held" == "manage_acl,read" && "$isop" == "false" ]] \
- && ok "user affordances = [manage_acl,read], isOperator=false" \
+ [[ "$held" == "manage_acl,read,share,write" && "$isop" == "false" ]] \
+ && ok "direct user plus active-team membership expose only requested bulk authority" \
|| bad "unexpected affordances held='$held' isOperator='$isop': $resp"
else
bad "user affordances failed: $resp"
fi
-
-# ─── 8. User delegates read to a 2nd subject (resolveCaller user path) ────────
deleg_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg id "$DELEGATE_USER_ID" \
'{drive:$d, resourceId:$r, subject:{type:"user", id:$id}, permissions:["read"], inherit:false}')"
resp="$(user_http "$USER_TOKEN" PUT /api/v1/me/gfs/grants "$deleg_body")"
@@ -301,15 +286,57 @@ resp="$(user_http "$USER_TOKEN" PUT /api/v1/me/gfs/grants "$deleg_body")"
gb="$(psql_one "SELECT granted_by FROM gfs_grants WHERE drive='$DRIVE' AND resource_id='$SCRATCH_RID' AND subject_type='user' AND subject_id='$DELEGATE_USER_ID' ORDER BY updated_at DESC LIMIT 1;")"
[[ "$gb" == "user:$USER_ID" ]] && ok "delegation recorded with granted_by=user:<id> (caller path)" \
|| bad "expected granted_by='user:$USER_ID', got '$gb'"
-
-# ─── 9. No-escalation: user cannot grant a bit it does NOT hold (write) ──────
-esc_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg id "$DELEGATE_USER_ID" \
- '{drive:$d, resourceId:$r, subject:{type:"user", id:$id}, permissions:["write"], inherit:false}')"
+BULK_USER_ID="$(fixture_uuid grant-user)"; BULK_TEAM_ID="$(fixture_uuid grant-team)"; REJECT_USER_ID="$(fixture_uuid reject-user)"
+FIRST_HOST="1st:mcp-host/bulk-${RUN_SUFFIX}"; THIRD_HOST="3rd:sandbox-recipes/bulk-${RUN_SUFFIX}"
+grant_subjects="$(jq -cn --arg u "$BULK_USER_ID" --arg t "$BULK_TEAM_ID" --arg h1 "$FIRST_HOST" --arg h3 "$THIRD_HOST" '[{type:"user",id:$u},{type:"team",id:$t},{type:"host",id:$h1},{type:"host",id:$h3}]')"
+grant_keys="'user:$BULK_USER_ID','team:$BULK_TEAM_ID','host:$FIRST_HOST','host:$THIRD_HOST'"
+bulk_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --argjson s "$grant_subjects" '{drive:$d,resourceId:$r,subjects:$s,permissions:["read","write"],inherit:false}')"
+resp="$(user_http "$USER_TOKEN" PUT /api/v1/me/gfs/grants "$bulk_body")"
+assert_bulk_success "mixed bulk grant" "$resp" "$grant_subjects"
+if [[ "$(stored_subject_count gfs_grants "$grant_keys")" == "4" ]]; then ok "mixed bulk grant stored all targets"
+else bad "mixed bulk grant did not store exactly four targets"; fi
+assert_correlated_audit "mixed bulk grant" "$grant_keys" 4
+HOST_READ="1st:mcp-host/read-${RUN_SUFFIX}"; HOST_WRITE="3rd:sandbox-recipes/write-${RUN_SUFFIX}"
+MULTI_FIRST="1st:mcp-host/multi-${RUN_SUFFIX}"; MULTI_THIRD="3rd:sandbox-recipes/multi-${RUN_SUFFIX}"
+host_labels=("host-only read grant" "host-only write grant" "multi-host read+write grant")
+host_permissions=('["read"]' '["write"]' '["read","write"]')
+host_subject_sets=("$(jq -cn --arg h "$HOST_READ" '[{type:"host",id:$h}]')" "$(jq -cn --arg h "$HOST_WRITE" '[{type:"host",id:$h}]')" "$(jq -cn --arg h1 "$MULTI_FIRST" --arg h3 "$MULTI_THIRD" '[{type:"host",id:$h1},{type:"host",id:$h3}]')")
+host_key_sets=("'host:$HOST_READ'" "'host:$HOST_WRITE'" "'host:$MULTI_FIRST','host:$MULTI_THIRD'"); host_counts=(1 1 2)
+for host_index in 0 1 2; do
+ host_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --argjson s "${host_subject_sets[$host_index]}" --argjson p "${host_permissions[$host_index]}" '{drive:$d,resourceId:$r,subjects:$s,permissions:$p,inherit:false}')"
+ resp="$(admin_http PUT /api/v1/gfs/grants "$host_body")"; label="${host_labels[$host_index]}"; keys="${host_key_sets[$host_index]}"; expected="${host_counts[$host_index]}"
+ assert_bulk_success "$label" "$resp" "${host_subject_sets[$host_index]}"
+ if [[ "$(stored_subject_count gfs_grants "$keys")" == "$expected" ]]; then ok "$label stored all targets"; else bad "$label stored an unexpected target count"; fi
+ assert_correlated_audit "$label" "$keys" "$expected"
+done
+share_subjects="$(jq -cn --arg u "$USER_ID" --arg t "$USER_TEAM_ID" '[{type:"user",id:$u},{type:"team",id:$t}]')"
+share_keys="'user:$USER_ID','team:$USER_TEAM_ID'"
+share_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --argjson s "$share_subjects" '{drive:$d,resourceId:$r,subjects:$s,permissions:["read"],includeDescendants:false}')"
+resp="$(user_http "$USER_TOKEN" POST /api/v1/me/gfs/shares "$share_body")"
+assert_bulk_success "mixed bulk share" "$resp" "$share_subjects"
+if [[ "$(stored_subject_count gfs_shares "$share_keys")" == "2" ]]; then ok "mixed bulk share stored both targets"
+else bad "mixed bulk share did not store exactly two targets"; fi
+assert_correlated_audit "mixed bulk share" "$share_keys" 2 share.create
+reject_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg u "$REJECT_USER_ID" '{drive:$d,resourceId:$r,subjects:[{type:"user",id:$u},{type:"context",id:"bulk-context"}],permissions:["read"],inherit:false}')"
+resp="$(user_http "$USER_TOKEN" PUT /api/v1/me/gfs/grants "$reject_body")"
+assert_rejected_atomic gfs_grants "plural context grant" "$resp" "'user:$REJECT_USER_ID','context:bulk-context'"
+reject_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg u "$REJECT_USER_ID" '{drive:$d,resourceId:$r,subjects:[{type:"user",id:$u},{type:"operator"}],permissions:["read"],inherit:false}')"
+resp="$(user_http "$USER_TOKEN" PUT /api/v1/me/gfs/grants "$reject_body")"
+assert_rejected_atomic gfs_grants "plural operator grant" "$resp" "'user:$REJECT_USER_ID','operator:'"
+reject_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg u "$REJECT_USER_ID" --arg h "$FIRST_HOST" '{drive:$d,resourceId:$r,subjects:[{type:"user",id:$u},{type:"host",id:$h}],permissions:["read"],includeDescendants:false}')"
+resp="$(user_http "$USER_TOKEN" POST /api/v1/me/gfs/shares "$reject_body")"
+assert_rejected_atomic gfs_shares "plural host share" "$resp" "'user:$REJECT_USER_ID','host:$FIRST_HOST'"
+for rejected_type in context operator; do
+ rejected_subject="$(jq -cn --arg type "$rejected_type" '{type:$type} + if $type == "context" then {id:"bulk-context"} else {} end')"
+ [[ "$rejected_type" == "context" ]] && rejected_key="context:bulk-context" || rejected_key="operator:"
+ reject_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg u "$REJECT_USER_ID" --argjson invalid "$rejected_subject" '{drive:$d,resourceId:$r,subjects:[{type:"user",id:$u},$invalid],permissions:["read"],includeDescendants:false}')"
+ resp="$(admin_http POST /api/v1/gfs/shares "$reject_body")"
+ assert_rejected_atomic gfs_shares "plural $rejected_type share" "$resp" "'user:$REJECT_USER_ID','$rejected_key'"
+done
+ESCALATION_USER_ID="$(fixture_uuid escalation-user)"; ESCALATION_TEAM_ID="$(fixture_uuid escalation-team)"; escalation_keys="'user:$ESCALATION_USER_ID','team:$ESCALATION_TEAM_ID'"
+esc_body="$(jq -cn --arg d "$DRIVE" --arg r "$SCRATCH_RID" --arg u "$ESCALATION_USER_ID" --arg t "$ESCALATION_TEAM_ID" \
+ '{drive:$d,resourceId:$r,subjects:[{type:"user",id:$u},{type:"team",id:$t}],permissions:["delete"],inherit:false}')"
resp="$(user_http "$USER_TOKEN" PUT /api/v1/me/gfs/grants "$esc_body")"
-status="$(http_status "$resp")"
-code="$(http_body "$resp" | jq -r '.error // empty' 2>/dev/null || true)"
-[[ "$status" == "403" ]] && ok "no-escalation: user grant of unheld 'write' denied (403, $code)" \
- || bad "expected 403 escalation_rejected, got status=$status: $resp"
-
+assert_denied_atomic "no-escalation mixed bulk grant" "$resp" "$escalation_keys" 2
echo "== gfs USER-delegation gate: ${pass} passed, ${fail} failed =="
[[ "$fail" -eq 0 ]] || exit 1
diff --git a/scripts/e2e/seed-gfs-grant-workflow.sh b/scripts/e2e/seed-gfs-grant-workflow.sh
new file mode 100755
index 000000000..345f92ca5
--- /dev/null
+++ b/scripts/e2e/seed-gfs-grant-workflow.sh
@@ -0,0 +1,249 @@
+#!/usr/bin/env bash
+
+# Sourced by seed-e2e-data.sh after its shared configuration and helpers load.
+# This function reuses the existing authenticated recipe API and kubectl context.
+render_gfs_grant_plugin_fixture() {
+ RUBYOPT=--disable=gems ruby -ryaml -rjson -e '
+ document = YAML.safe_load(File.read(ARGV.fetch(0)), aliases: false)
+ abort "fixture must contain one YAML object" unless document.is_a?(Hash)
+ puts JSON.generate(document)
+ ' "$1"
+}
+
+normalize_gfs_grant_plugin_contract() {
+ jq -S -c \
+ '.spec
+ | (.agent.provider |= type)
+ | (.agent.model |= type)
+ | ((.steps[] | select(
+ .id == "approval-held-gfs-read"
+ or .id == "approval-held-gfs-probe"
+ )
+ | .requiresApproval.target.userId) |= type)'
+}
+
+superseded_gfs_grant_plugin_contract() {
+ normalize_gfs_grant_plugin_contract | jq -S -c \
+ '.steps = [
+ (.steps[] | select(.id == "approval-held-gfs-read")),
+ (.steps[] | select(.id == "read-back-gfs-probe"))
+ ]
+ | .steps[0].id = "approval-held-gfs-probe"
+ | .steps[0].instruction = "After the seeded user approves this E2E run, exercise the exact GFS file resource {{inputs.resourceId}} through this run-scoped host. Call clerum__gfs_read first and retain its exact content. Call clerum__gfs_stat next and retain its gfsUri and numeric version. Call clerum__gfs_write with drive \"main\", resourceId \"{{inputs.resourceId}}\", content \"{{inputs.updatedContent}}\", and ifMatch equal to the stat version. Do not claim success unless all three calls succeed. Return one concise JSON object containing resourceId, initialContent, gfsUri, statVersion, writeVersion, and updatedContent."
+ | .steps[0].allowedTools.include = [
+ "clerum__gfs_read",
+ "clerum__gfs_stat",
+ "clerum__gfs_write"
+ ]
+ | .steps[0].maxIterations = 6
+ | .steps[1].dependsOn = ["approval-held-gfs-probe"]'
+}
+
+legacy_gfs_grant_plugin_contract() {
+ normalize_gfs_grant_plugin_contract | jq -S -c \
+ 'del(.inputContract)
+ | .steps = [.steps[] | select(.id == "approval-held-gfs-read")]
+ | .steps[0] |= (
+ .id = "approval-held-gfs-probe"
+ | del(.allowedTools, .toolChoice)
+ | .instruction = "Use the mock-tools MCP server only after the seeded user approves this E2E run."
+ | .maxIterations = 5
+ )'
+}
+
+previous_gfs_grant_plugin_contract() {
+ normalize_gfs_grant_plugin_contract | jq -S -c \
+ '.steps = [.steps[] | select(.id == "approval-held-gfs-read")]
+ | .steps[0] |= (
+ .id = "approval-held-gfs-probe"
+ | .allowedTools.include = [
+ "clerum__gfs_read",
+ "clerum__gfs_stat",
+ "clerum__gfs_write"
+ ]
+ | .instruction = "After the seeded user approves this E2E run, exercise the exact GFS file resource {{inputs.resourceId}} through this run-scoped host. Call clerum__gfs_read first and retain its exact content. Call clerum__gfs_stat next and retain its gfsUri and numeric version. Call clerum__gfs_write with drive \"main\", resourceId \"{{inputs.resourceId}}\", content \"{{inputs.updatedContent}}\", and ifMatch equal to the stat version. Finally call clerum__gfs_read again and verify its exact content equals \"{{inputs.updatedContent}}\". Do not claim success unless all four calls succeed. Return one concise JSON object containing resourceId, initialContent, gfsUri, statVersion, writeVersion, updatedContent, and readBackContent."
+ | .maxIterations = 50
+ )'
+}
+
+current_previous_gfs_grant_plugin_contract() {
+ previous_gfs_grant_plugin_contract | jq -S -c \
+ '(.steps[] | select(.id == "approval-held-gfs-probe") | .maxIterations) = 5'
+}
+
+interim_gfs_grant_plugin_contract() {
+ previous_gfs_grant_plugin_contract | jq -S -c \
+ '(.steps[] | select(.id == "approval-held-gfs-probe") | .maxIterations) = 7'
+}
+
+two_iteration_gfs_grant_plugin_contract() {
+ normalize_gfs_grant_plugin_contract | jq -S -c \
+ '.steps |= map(.maxIterations = 2)'
+}
+
+seed_gfs_grant_plugin_if_enabled() {
+ local enabled="$SEED_GFS_GRANT_PLUGIN"
+ local rendered probe code desired_spec current_spec desired_contract desired_superseded_contract desired_legacy_contract desired_previous_contract desired_current_previous_contract desired_interim_contract desired_two_iteration_contract current_contract phase message trigger_ready eager_pods deadline grant_ids
+
+ if [ -z "$enabled" ]; then
+ if is_minikube_context; then enabled="true"; else enabled="false"; fi
+ fi
+ if [ "$enabled" != "true" ]; then
+ log "Skipping third-party GFS plugin seed for context $CONTEXT"
+ return 0
+ fi
+ if ! is_minikube_context; then
+ die "Refusing to seed the third-party GFS plugin outside minikube context '$CONTEXT'"
+ fi
+ case "$GFS_GRANT_PLUGIN_WAIT_SECONDS" in
+ ''|*[!0-9]*) die "E2E_GFS_GRANT_PLUGIN_WAIT_SECONDS must be a positive integer" ;;
+ esac
+ [ "$GFS_GRANT_PLUGIN_WAIT_SECONDS" -gt 0 ] \
+ || die "E2E_GFS_GRANT_PLUGIN_WAIT_SECONDS must be a positive integer"
+ [ -f "$GFS_GRANT_PLUGIN_FIXTURE" ] \
+ || die "Third-party GFS plugin fixture not found: $GFS_GRANT_PLUGIN_FIXTURE"
+ [ -n "$USER_ID" ] || die "Cannot seed the third-party GFS plugin before the E2E user exists"
+ [ -n "$GFS_GRANT_PLUGIN_MODEL_PROVIDER" ] \
+ || die "Cannot seed the third-party GFS plugin without a workflow model provider"
+ [ -n "$GFS_GRANT_PLUGIN_MODEL_NAME" ] \
+ || die "Cannot seed the third-party GFS plugin without a workflow model name"
+ printf '%s' "$USER_ID" \
+ | grep -Eq '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$' \
+ || die "Cannot seed the third-party GFS plugin with a non-UUID E2E user id"
+
+ rendered="$(render_gfs_grant_plugin_fixture "$GFS_GRANT_PLUGIN_FIXTURE" | jq \
+ --arg provider "$GFS_GRANT_PLUGIN_MODEL_PROVIDER" \
+ --arg model "$GFS_GRANT_PLUGIN_MODEL_NAME" \
+ --arg userRef "$USER_ID" \
+ '.spec.agent.provider = $provider
+ | .spec.agent.model = $model
+ | (.spec.steps[] | select(.id == "approval-held-gfs-read")
+ | .requiresApproval.target.userId) = $userRef' \
+ )"
+
+ printf '%s' "$rendered" | jq -e \
+ --arg provider "$GFS_GRANT_PLUGIN_MODEL_PROVIDER" \
+ --arg model "$GFS_GRANT_PLUGIN_MODEL_NAME" \
+ --arg userRef "$USER_ID" \
+ '.spec.agent == {provider: $provider, model: $model}
+ and (.spec.steps | length == 4)
+ and (.spec.steps[0].requiresApproval.target.userId == $userRef)
+ and (.spec.inputContract.required | sort == ["resourceId", "updatedContent"])
+ and (.spec.inputContract.properties.resourceId.type == "string")
+ and (.spec.inputContract.properties.updatedContent.type == "string")
+ and (.spec.steps[0].id == "approval-held-gfs-read")
+ and (.spec.steps[0].allowedTools.include == ["clerum__gfs_read"])
+ and (.spec.steps[0].toolChoice == "required")
+ and (.spec.steps[0].maxIterations == 3)
+ and (.spec.steps[1].id == "gfs-stat-probe")
+ and (.spec.steps[1].dependsOn == ["approval-held-gfs-read"])
+ and (.spec.steps[1].allowedTools.include == ["clerum__gfs_stat"])
+ and (.spec.steps[1].toolChoice == "required")
+ and (.spec.steps[1].maxIterations == 3)
+ and (.spec.steps[2].id == "gfs-write-probe")
+ and (.spec.steps[2].dependsOn == ["gfs-stat-probe"])
+ and (.spec.steps[2].allowedTools.include == ["clerum__gfs_write"])
+ and (.spec.steps[2].toolChoice == "required")
+ and (.spec.steps[2].maxIterations == 3)
+ and (.spec.steps[2].instruction | contains("{{gfs-stat-probe:output}}"))
+ and (.spec.steps[3].id == "read-back-gfs-probe")
+ and (.spec.steps[3].dependsOn == ["gfs-write-probe"])
+ and (.spec.steps[3].allowedTools.include == ["clerum__gfs_read"])
+ and (.spec.steps[3].toolChoice == "required")
+ and (.spec.steps[3].maxIterations == 3)
+ and (.spec.workloads | any(
+ .id == "mock-tools"
+ and .image == "clerum/mock-mcp-server:test"
+ and .transport == {type: "streamableHttp", path: "/mcp"}
+ ))
+ and (.spec.gfs.mounts | any(
+ .drive == "main"
+ and .target == "e2e/gfs-grant-e2e-plugin"
+ and (.scopes | sort == ["gfs.read", "gfs.write"])
+ ))
+ and (.spec | has("pluginWorkloadSdk") | not)
+ and (.spec | has("contextRef") | not)' >/dev/null \
+ || die "Rendered third-party GFS plugin fixture violates the standard WorkflowRecipe contract"
+ if printf '%s' "$rendered" | grep -Eq 'PLACEHOLDER_[A-Z0-9_]+'; then
+ die "Rendered third-party GFS plugin fixture still contains unresolved placeholders"
+ fi
+
+ probe="$(curl -sS -w '\n%{http_code}' \
+ "$CAPI_BASE/admin/recipes/$GFS_GRANT_PLUGIN_RECIPE_NAME" "${AUTH_CURL[@]}" || true)"
+ code="$(echo "$probe" | tail -n1)"
+ case "$code" in
+ 200)
+ desired_spec="$(printf '%s' "$rendered" | jq -S -c '.spec')"
+ current_spec="$(echo "$probe" | sed '$d' | jq -S -c '.spec')"
+ if [ "$current_spec" = "$desired_spec" ]; then
+ ok "WorkflowRecipe $GFS_GRANT_PLUGIN_RECIPE_NAME already matches the standard seed"
+ else
+ # The canonical admin recipe API intentionally strips author-supplied
+ # labels. Compare the complete spec while normalizing only the three
+ # environment-seeded values; any other drift remains fail-closed.
+ desired_contract="$(printf '%s' "$rendered" | normalize_gfs_grant_plugin_contract)"
+ desired_superseded_contract="$(printf '%s' "$rendered" | superseded_gfs_grant_plugin_contract)"
+ desired_legacy_contract="$(printf '%s' "$rendered" | legacy_gfs_grant_plugin_contract)"
+ desired_previous_contract="$(printf '%s' "$rendered" | previous_gfs_grant_plugin_contract)"
+ desired_current_previous_contract="$(printf '%s' "$rendered" | current_previous_gfs_grant_plugin_contract)"
+ desired_interim_contract="$(printf '%s' "$rendered" | interim_gfs_grant_plugin_contract)"
+ desired_two_iteration_contract="$(printf '%s' "$rendered" | two_iteration_gfs_grant_plugin_contract)"
+ current_contract="$(echo "$probe" | sed '$d' | normalize_gfs_grant_plugin_contract)"
+ if [ "$current_contract" != "$desired_contract" ] \
+ && [ "$current_contract" != "$desired_superseded_contract" ] \
+ && [ "$current_contract" != "$desired_legacy_contract" ] \
+ && [ "$current_contract" != "$desired_previous_contract" ] \
+ && [ "$current_contract" != "$desired_current_previous_contract" ] \
+ && [ "$current_contract" != "$desired_interim_contract" ] \
+ && [ "$current_contract" != "$desired_two_iteration_contract" ]; then
+ die "Refusing to replace WorkflowRecipe $GFS_GRANT_PLUGIN_RECIPE_NAME without an exact recognized E2E fixture contract"
+ fi
+ put_json "$CAPI_BASE/admin/recipes/$GFS_GRANT_PLUGIN_RECIPE_NAME" "$rendered" \
+ "PUT /admin/recipes/$GFS_GRANT_PLUGIN_RECIPE_NAME"
+ fi
+ ;;
+ 404)
+ admin_post "$CAPI_BASE/admin/recipes" "$rendered" \
+ "POST /admin/recipes ($GFS_GRANT_PLUGIN_RECIPE_NAME)"
+ ;;
+ *) die "GET /admin/recipes/$GFS_GRANT_PLUGIN_RECIPE_NAME failed with status=$code" ;;
+ esac
+
+ put_json \
+ "$CAPI_BASE/admin/workflows/$GFS_GRANT_PLUGIN_RECIPE_NS/$GFS_GRANT_PLUGIN_RECIPE_NAME/grants" \
+ "$(jq -cn --arg userId "$USER_ID" '{userIds:[$userId]}')" \
+ "PUT /admin/workflows/$GFS_GRANT_PLUGIN_RECIPE_NS/$GFS_GRANT_PLUGIN_RECIPE_NAME/grants"
+ admin_get \
+ "$CAPI_BASE/admin/workflows/$GFS_GRANT_PLUGIN_RECIPE_NS/$GFS_GRANT_PLUGIN_RECIPE_NAME/grants" \
+ "GET /admin/workflows/$GFS_GRANT_PLUGIN_RECIPE_NS/$GFS_GRANT_PLUGIN_RECIPE_NAME/grants"
+ grant_ids="$(printf '%s' "$ADMIN_GET_BODY" | jq -c '[.items[]?.id] | sort')"
+ [ "$grant_ids" = "[\"$USER_ID\"]" ] \
+ || die "Third-party GFS plugin grant seed mismatch: expected only $USER_ID, got $grant_ids"
+ ok "WorkflowRecipe $GFS_GRANT_PLUGIN_RECIPE_NAME trigger/approval grant seeded for $DEV_EMAIL"
+
+ deadline=$((SECONDS + GFS_GRANT_PLUGIN_WAIT_SECONDS))
+ phase=""; message=""; trigger_ready="false"
+ while [ "$SECONDS" -lt "$deadline" ]; do
+ admin_get "$CAPI_BASE/admin/recipes/$GFS_GRANT_PLUGIN_RECIPE_NAME" \
+ "GET /admin/recipes/$GFS_GRANT_PLUGIN_RECIPE_NAME"
+ phase="$(echo "$ADMIN_GET_BODY" | jq -r '.status.phase // empty')"
+ message="$(echo "$ADMIN_GET_BODY" | jq -r '.status.message // empty')"
+ trigger_ready="$(echo "$ADMIN_GET_BODY" | jq -r \
+ '(.spec.triggers.onDemand != null)
+ and (.status.workflowExecution == null)
+ and ((.status.message // "") | startswith("Workflow trigger infrastructure registered"))')"
+ if [ "$phase" = "active" ] && [ "$trigger_ready" = "true" ]; then break; fi
+ sleep 2
+ done
+ if [ "$phase" != "active" ] || [ "$trigger_ready" != "true" ]; then
+ die "WorkflowRecipe $GFS_GRANT_PLUGIN_RECIPE_NAME did not become trigger-ready (phase=${phase:-unknown}, message=${message:-missing})"
+ fi
+ ok "WorkflowRecipe $GFS_GRANT_PLUGIN_RECIPE_NAME is active with trigger infrastructure registered"
+
+ eager_pods="$($KC -n "$GFS_GRANT_PLUGIN_RECIPE_NS" get pods \
+ -l "clerum.io/recipe=$GFS_GRANT_PLUGIN_RECIPE_NAME,clerum.io/component=workflow-mcp-host" \
+ -o name)"
+ [ -z "$eager_pods" ] \
+ || die "Standard WorkflowRecipe $GFS_GRANT_PLUGIN_RECIPE_NAME unexpectedly created an eager parent mcp-host: $eager_pods"
+ ok "No eager parent mcp-host exists; a recipe-local host will be created only for a triggered run"
+}
diff --git a/scripts/minikube/teardown.sh b/scripts/minikube/teardown.sh
index 49d72c987..14a1f2e16 100755
--- a/scripts/minikube/teardown.sh
+++ b/scripts/minikube/teardown.sh
@@ -164,7 +164,8 @@ for ns in "${NAMESPACES[@]}"; do
done
ok "ServiceAccounts, Roles, RoleBindings deleted"
-# Cluster-scoped RBAC (Clerum-specific only)
+# Cluster-scoped RBAC (Clerum-specific only). The obsolete wrc-trigger names
+# remain here only so teardown also cleans profiles created by older releases.
for name in clerum-channel-reader control-api workflow-recipes-cluster-watch wrc-trigger-role control-api-pod-reader; do
$KC delete clusterrole "$name" 2>/dev/null || true
done
diff --git a/scripts/qa-recorder/loadEnv.ts b/scripts/qa-recorder/loadEnv.ts
new file mode 100644
index 000000000..8a7a05b6f
--- /dev/null
+++ b/scripts/qa-recorder/loadEnv.ts
@@ -0,0 +1,48 @@
+import fs from 'node:fs'
+import path from 'node:path'
+
+const QA_RECORDER_ENV_FILENAME = '.env.qa-recorder'
+const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/
+
+function parseValue(rawValue: string): string {
+ const value = rawValue.trim()
+ if (value.length < 2) return value
+
+ const first = value[0]
+ const last = value[value.length - 1]
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
+ return value.slice(1, -1)
+ }
+ return value
+}
+
+export function loadQaRecorderEnv(repoRoot: string): string | undefined {
+ const envPath = path.join(repoRoot, QA_RECORDER_ENV_FILENAME)
+ if (!fs.existsSync(envPath)) return undefined
+
+ const lines = fs
+ .readFileSync(envPath, 'utf8')
+ .replace(/^\uFEFF/, '')
+ .split(/\r?\n/)
+ for (const [index, sourceLine] of lines.entries()) {
+ const line = sourceLine.trim()
+ if (!line || line.startsWith('#')) continue
+
+ const declaration = line.startsWith('export ') ? line.slice('export '.length).trim() : line
+ const separator = declaration.indexOf('=')
+ if (separator < 1) {
+ throw new Error(`${QA_RECORDER_ENV_FILENAME}:${index + 1} must use KEY=value syntax.`)
+ }
+
+ const key = declaration.slice(0, separator).trim()
+ if (!ENV_KEY.test(key)) {
+ throw new Error(`${QA_RECORDER_ENV_FILENAME}:${index + 1} has invalid key "${key}".`)
+ }
+
+ if (process.env[key] === undefined) {
+ process.env[key] = parseValue(declaration.slice(separator + 1))
+ }
+ }
+
+ return envPath
+}
diff --git a/scripts/tests/test-lint-networkpolicies.sh b/scripts/tests/test-lint-networkpolicies.sh
index b73481924..2400d8517 100755
--- a/scripts/tests/test-lint-networkpolicies.sh
+++ b/scripts/tests/test-lint-networkpolicies.sh
@@ -62,7 +62,7 @@ write_policy "${TMP_DIR}/safe-specific.yaml" ' - ports:
protocol: TCP
to:
- ipBlock:
- cidr: 203.0.113.1/32'
+ cidr: 203.0.113.10/32'
run_lint "${TMP_DIR}/safe-specific.yaml" >/dev/null
echo "PASS: lint-networkpolicies allows explicit port plus specific destination"
diff --git a/scripts/tests/test-seed-gfs-grant-workflow.sh b/scripts/tests/test-seed-gfs-grant-workflow.sh
new file mode 100755
index 000000000..d23b296fd
--- /dev/null
+++ b/scripts/tests/test-seed-gfs-grant-workflow.sh
@@ -0,0 +1,112 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+HELPER="$ROOT_DIR/scripts/e2e/seed-gfs-grant-workflow.sh"
+FIXTURE="$ROOT_DIR/tests/e2e/fixtures/gfs-grant-e2e-plugin-recipe.yaml"
+
+bash -n "$HELPER"
+source "$HELPER"
+
+rendered="$(render_gfs_grant_plugin_fixture "$FIXTURE")"
+printf '%s' "$rendered" | jq -e '
+ .apiVersion == "clerum.io/v1alpha1"
+ and .kind == "WorkflowRecipe"
+ and .metadata.name == "gfs-grant-e2e-plugin"
+ and .metadata.namespace == "sandbox-recipes"
+ and (.spec.inputContract.required | sort == ["resourceId", "updatedContent"])
+ and (.spec.steps | length == 4)
+ and (.spec.steps[0].id == "approval-held-gfs-read")
+ and (.spec.steps[0].allowedTools.include == ["clerum__gfs_read"])
+ and (.spec.steps[0].toolChoice == "required")
+ and (.spec.steps[0].maxIterations == 3)
+ and (.spec.steps[1].id == "gfs-stat-probe")
+ and (.spec.steps[1].dependsOn == ["approval-held-gfs-read"])
+ and (.spec.steps[1].allowedTools.include == ["clerum__gfs_stat"])
+ and (.spec.steps[1].toolChoice == "required")
+ and (.spec.steps[1].maxIterations == 3)
+ and (.spec.steps[2].id == "gfs-write-probe")
+ and (.spec.steps[2].dependsOn == ["gfs-stat-probe"])
+ and (.spec.steps[2].allowedTools.include == ["clerum__gfs_write"])
+ and (.spec.steps[2].toolChoice == "required")
+ and (.spec.steps[2].maxIterations == 3)
+ and (.spec.steps[2].instruction | contains("{{gfs-stat-probe:output}}"))
+ and (.spec.steps[3].id == "read-back-gfs-probe")
+ and (.spec.steps[3].dependsOn == ["gfs-write-probe"])
+ and (.spec.steps[3].allowedTools.include == ["clerum__gfs_read"])
+ and (.spec.steps[3].toolChoice == "required")
+ and (.spec.steps[3].maxIterations == 3)
+ and (.spec.workloads | any(
+ .id == "mock-tools"
+ and .transport == {type: "streamableHttp", path: "/mcp"}
+ ))
+ and (.spec.gfs.mounts | any(
+ .drive == "main"
+ and .target == "e2e/gfs-grant-e2e-plugin"
+ and (.scopes | sort == ["gfs.read", "gfs.write"])
+ ))
+' >/dev/null
+
+current_contract="$(printf '%s' "$rendered" | normalize_gfs_grant_plugin_contract)"
+superseded_contract="$(printf '%s' "$rendered" | superseded_gfs_grant_plugin_contract)"
+legacy_contract="$(printf '%s' "$rendered" | legacy_gfs_grant_plugin_contract)"
+previous_contract="$(printf '%s' "$rendered" | previous_gfs_grant_plugin_contract)"
+current_previous_contract="$(printf '%s' "$rendered" | current_previous_gfs_grant_plugin_contract)"
+interim_contract="$(printf '%s' "$rendered" | interim_gfs_grant_plugin_contract)"
+two_iteration_contract="$(printf '%s' "$rendered" | two_iteration_gfs_grant_plugin_contract)"
+test "$current_contract" != "$legacy_contract"
+test "$current_contract" != "$superseded_contract"
+test "$current_contract" != "$previous_contract"
+test "$current_contract" != "$current_previous_contract"
+test "$current_contract" != "$interim_contract"
+test "$current_contract" != "$two_iteration_contract"
+printf '%s' "$two_iteration_contract" | jq -e '
+ (.steps | length == 4)
+ and all(.steps[]; .maxIterations == 2)
+' >/dev/null
+deployed_superseded_contract="$(printf '%s' "$superseded_contract" | jq -c '
+ .agent.provider = "seeded-provider"
+ | .agent.model = "seeded-model"
+ | .steps[0].requiresApproval.target.userId = "11111111-1111-4111-8111-111111111111"
+')"
+test "$(printf '%s' "$deployed_superseded_contract" | jq -c '{spec: .}' | normalize_gfs_grant_plugin_contract)" = "$superseded_contract"
+printf '%s' "$legacy_contract" | jq -e '
+ (has("inputContract") | not)
+ and (.steps[0].instruction == "Use the mock-tools MCP server only after the seeded user approves this E2E run.")
+ and (.steps[0] | has("allowedTools") | not)
+ and (.steps[0] | has("toolChoice") | not)
+ and (.steps[0].maxIterations == 5)
+ and (.steps | length == 1)
+' >/dev/null
+printf '%s' "$superseded_contract" | jq -e '
+ (.steps | length == 2)
+ and (.steps[0].id == "approval-held-gfs-probe")
+ and (.steps[0].allowedTools.include | sort == [
+ "clerum__gfs_read",
+ "clerum__gfs_stat",
+ "clerum__gfs_write"
+ ])
+ and (.steps[0].maxIterations == 6)
+ and (.steps[1].id == "read-back-gfs-probe")
+ and (.steps[1].dependsOn == ["approval-held-gfs-probe"])
+' >/dev/null
+printf '%s' "$previous_contract" | jq -e '
+ .steps[0].maxIterations == 50
+ and .steps[0].toolChoice == "required"
+ and (.steps | length == 1)
+ and (.inputContract.required | sort == ["resourceId", "updatedContent"])
+' >/dev/null
+printf '%s' "$current_previous_contract" | jq -e '
+ .steps[0].maxIterations == 5
+ and .steps[0].toolChoice == "required"
+ and (.steps | length == 1)
+ and (.inputContract.required | sort == ["resourceId", "updatedContent"])
+' >/dev/null
+printf '%s' "$interim_contract" | jq -e '
+ .steps[0].maxIterations == 7
+ and .steps[0].toolChoice == "required"
+ and (.steps | length == 1)
+ and (.inputContract.required | sort == ["resourceId", "updatedContent"])
+' >/dev/null
+
+echo "PASS: GFS grant WorkflowRecipe seed fixture renders through the helper contract"
diff --git a/scripts/tests/test-verify-networkpolicies.sh b/scripts/tests/test-verify-networkpolicies.sh
index 7fe670fd9..b77e514ca 100755
--- a/scripts/tests/test-verify-networkpolicies.sh
+++ b/scripts/tests/test-verify-networkpolicies.sh
@@ -16,7 +16,7 @@ if [[ "${1:-}" == "--context" ]]; then
fi
if [[ "${1:-}" == "kustomize" ]]; then
- cidr="203.0.113.1/32"
+ cidr="203.0.113.10/32"
if [[ "${mode}" == "forbidden" ]]; then
cidr="10.109.0.1/32"
fi
@@ -71,7 +71,7 @@ if [[ "${1:-}" == "get" && "${2:-}" == "networkpolicy" ]]; then
printf '{"items":[]}\n'
exit 0
fi
- cidr="203.0.113.1/32"
+ cidr="203.0.113.10/32"
if [[ "${mode}" == "drift" ]]; then
cidr="35.199.192.1/32"
fi
diff --git a/tests/e2e/fixtures/cronExecProbeInstruction.ts b/tests/e2e/fixtures/cronExecProbeInstruction.ts
new file mode 100644
index 000000000..53ba08f5d
--- /dev/null
+++ b/tests/e2e/fixtures/cronExecProbeInstruction.ts
@@ -0,0 +1,21 @@
+export const CRON_EXEC_PROBE_INSTRUCTION = [
+ 'You are validating whether SCHEDULED (cron) tasks actually execute on this',
+ 'mcp-host. Use the available tools and do these steps IN ORDER.',
+ '',
+ '1. CREATE — use the cron scheduling tool (cron_manage) to create a recurring job',
+ ' named "e2e-cron-exec" with schedule "*/1 * * * *". The job\'s task content MUST be',
+ ' EXACTLY this sentence (copy it verbatim):',
+ ' Use the shell tool to run this command: echo CRON_EXEC_OK > /tmp/cron-exec-proof.txt',
+ '',
+ '2. FIRE — use cron_manage to TRIGGER the "e2e-cron-exec" job immediately so it runs now.',
+ '',
+ '3. WAIT + VERIFY — the triggered task runs asynchronously in the background, so you',
+ ' must poll. Use the shell tool to run:',
+ ' sleep 8 ; cat /tmp/cron-exec-proof.txt',
+ ' If the file is missing or empty, repeat the same shell command (sleep 8 ; cat ...)',
+ ' up to 4 attempts total.',
+ '',
+ '4. REPORT — the FINAL line of your answer MUST be exactly one of:',
+ ' - if the file contains CRON_EXEC_OK -> CRON_EXEC_VERIFIED',
+ ' - if after all 4 attempts it is empty -> CRON_EXEC_FAILED',
+].join('\n')
diff --git a/tests/e2e/fixtures/gfs-grant-e2e-plugin-recipe.yaml b/tests/e2e/fixtures/gfs-grant-e2e-plugin-recipe.yaml
new file mode 100644
index 000000000..bb3c48459
--- /dev/null
+++ b/tests/e2e/fixtures/gfs-grant-e2e-plugin-recipe.yaml
@@ -0,0 +1,112 @@
+{
+ 'apiVersion': 'clerum.io/v1alpha1',
+ 'kind': 'WorkflowRecipe',
+ 'metadata': { 'name': 'gfs-grant-e2e-plugin', 'namespace': 'sandbox-recipes' },
+ 'spec':
+ {
+ 'description': 'Standard on-demand workflow fixture for per-recipe GFS read/write grant validation.',
+ 'triggers': { 'onDemand': { 'allowedActors': ['user'], 'requiresApproval': true } },
+ 'agent': { 'provider': 'PLACEHOLDER_MODEL_PROVIDER', 'model': 'PLACEHOLDER_MODEL_NAME' },
+ 'inputContract':
+ {
+ 'type': 'object',
+ 'required': ['resourceId', 'updatedContent'],
+ 'properties':
+ {
+ 'resourceId':
+ {
+ 'type': 'string',
+ 'description': 'GFS file resource UUID to exercise through the run-scoped host grant.',
+ },
+ 'updatedContent':
+ {
+ 'type': 'string',
+ 'description': 'Exact replacement content to write and read back.',
+ },
+ },
+ },
+ 'workloads':
+ [
+ {
+ 'id': 'mock-tools',
+ 'type': 'deployment',
+ 'image': 'clerum/mock-mcp-server:test',
+ 'port': 3000,
+ 'transport': { 'type': 'streamableHttp', 'path': '/mcp' },
+ 'healthCheck': { 'type': 'tcp', 'port': 3001 },
+ 'resources':
+ {
+ 'requests': { 'cpu': '50m', 'memory': '64Mi' },
+ 'limits': { 'cpu': '200m', 'memory': '128Mi' },
+ },
+ },
+ ],
+ 'gfs':
+ {
+ 'mounts':
+ [
+ {
+ 'drive': 'main',
+ 'target': 'e2e/gfs-grant-e2e-plugin',
+ 'scopes': ['gfs.read', 'gfs.write'],
+ },
+ ],
+ },
+ 'steps':
+ [
+ {
+ 'id': 'approval-held-gfs-read',
+ 'instruction': 'After the seeded user approves this E2E run, call clerum__gfs_read exactly once with drive "main" and resourceId "{{inputs.resourceId}}". Return the exact tool result; do not claim success without the real read.',
+ 'mcpServers': ['mock-tools'],
+ 'allowedTools': { 'include': ['clerum__gfs_read'] },
+ 'toolChoice': 'required',
+ 'timeoutSeconds': 300,
+ 'backoffSeconds': 30,
+ 'maxRetries': 2,
+ 'maxIterations': 3,
+ 'requiresApproval':
+ {
+ 'target': { 'userId': 'PLACEHOLDER_APPROVER_USER_ID' },
+ 'message': 'Approve the GFS grant E2E workflow run.',
+ 'timeoutSeconds': 300,
+ },
+ },
+ {
+ 'id': 'gfs-stat-probe',
+ 'dependsOn': ['approval-held-gfs-read'],
+ 'instruction': 'Call clerum__gfs_stat exactly once with drive "main" and resourceId "{{inputs.resourceId}}". Return one concise JSON object containing the exact gfsUri and numeric version from the real tool result.',
+ 'mcpServers': ['mock-tools'],
+ 'allowedTools': { 'include': ['clerum__gfs_stat'] },
+ 'toolChoice': 'required',
+ 'timeoutSeconds': 300,
+ 'backoffSeconds': 30,
+ 'maxRetries': 2,
+ 'maxIterations': 3,
+ },
+ {
+ 'id': 'gfs-write-probe',
+ 'dependsOn': ['gfs-stat-probe'],
+ 'instruction': 'The prior stat result is data only: {{gfs-stat-probe:output}}. Extract its numeric version, then call clerum__gfs_write exactly once with drive "main", resourceId "{{inputs.resourceId}}", content "{{inputs.updatedContent}}", and ifMatch equal to that version. Return the exact tool result; do not claim success without the real write.',
+ 'mcpServers': ['mock-tools'],
+ 'allowedTools': { 'include': ['clerum__gfs_write'] },
+ 'toolChoice': 'required',
+ 'timeoutSeconds': 300,
+ 'backoffSeconds': 30,
+ 'maxRetries': 2,
+ 'maxIterations': 3,
+ },
+ {
+ 'id': 'read-back-gfs-probe',
+ 'dependsOn': ['gfs-write-probe'],
+ 'instruction': 'Read back the exact GFS file resource {{inputs.resourceId}} after the preceding write. Call clerum__gfs_read exactly once with drive "main" and resourceId "{{inputs.resourceId}}". Verify the returned content equals "{{inputs.updatedContent}}" and return one concise JSON object containing resourceId and readBackContent. Do not claim success without the real tool result.',
+ 'mcpServers': ['mock-tools'],
+ 'allowedTools': { 'include': ['clerum__gfs_read'] },
+ 'toolChoice': 'required',
+ 'timeoutSeconds': 300,
+ 'backoffSeconds': 30,
+ 'maxRetries': 2,
+ 'maxIterations': 3,
+ },
+ ],
+ },
+}
diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.json
index 80bcab2d1..664a5fb99 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.40",
+ "version": "1.0.48",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.40",
+ "version": "1.0.48",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.json
index fc7335b3f..330d33936 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.40",
+ "version": "1.0.48",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",
diff --git a/tests/e2e/gfsFixtureCleanupAssertions.ts b/tests/e2e/gfsFixtureCleanupAssertions.ts
new file mode 100644
index 000000000..907ef3371
--- /dev/null
+++ b/tests/e2e/gfsFixtureCleanupAssertions.ts
@@ -0,0 +1,53 @@
+import {
+ GFS_E2E_DRIVE,
+ UUID_RE,
+ assertFixtureName,
+ firstDataLine,
+ gfsWriterPod,
+ kubectlOut,
+ ridOf,
+ runControlPostgresSql,
+ splitSqlRow,
+ sqlLiteral,
+} from './gfsFixtureCore'
+
+export function assertGfsFixtureCleaned(name: string): void {
+ assertFixtureName(name)
+ const row = firstDataLine(
+ runControlPostgresSql(`
+ WITH fixture_resources AS (
+ SELECT resource_id, kind, deleted_at
+ FROM gfs_resources
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)})
+ )
+ SELECT
+ COUNT(*) FILTER (WHERE deleted_at IS NULL)::text || '|' ||
+ (SELECT COUNT(*) FROM gfs_grants
+ WHERE resource_id IN (SELECT resource_id FROM fixture_resources))::text || '|' ||
+ (SELECT COUNT(*) FROM gfs_shares
+ WHERE resource_id IN (SELECT resource_id FROM fixture_resources))::text || '|' ||
+ COALESCE(array_to_string(array_agg(resource_id::text) FILTER (WHERE kind = 'file'), ','), '')
+ FROM fixture_resources;
+ `)
+ )
+ const [activeResources, grants, shares, fileIds = ''] = splitSqlRow(row)
+ if (activeResources !== '0' || grants !== '0' || shares !== '0') {
+ throw new Error(
+ `GFS fixture ${name} leaked active resources or authority rows: ${activeResources}|${grants}|${shares}`
+ )
+ }
+ for (const resourceId of fileIds.split(',').filter(value => UUID_RE.test(value))) {
+ kubectlOut([
+ '-n',
+ 'gfs',
+ 'exec',
+ gfsWriterPod(),
+ '--',
+ 'test',
+ '!',
+ '-e',
+ `/data/gfs/${ridOf(resourceId)}`,
+ ])
+ }
+}
diff --git a/tests/e2e/gfsResourceFixtures.ts b/tests/e2e/gfsResourceFixtures.ts
index fd7550729..933644345 100644
--- a/tests/e2e/gfsResourceFixtures.ts
+++ b/tests/e2e/gfsResourceFixtures.ts
@@ -152,7 +152,19 @@ export function seedGfsFileFixture(name: string): GfsFileFixture {
if (!UUID_RE.test(resourceId) || !UUID_RE.test(fileResourceId)) {
throw new Error(`failed to seed GFS file fixture ${name}: ${row}`)
}
- seedGfsBlob(fileResourceId, fileContent)
+ try {
+ seedGfsBlob(fileResourceId, fileContent)
+ } catch (error) {
+ try {
+ cleanupGfsFixture(name)
+ } catch (cleanupError) {
+ throw new AggregateError(
+ [error, cleanupError],
+ `failed to seed and roll back GFS file fixture ${name}`
+ )
+ }
+ throw error
+ }
return {
name,
fileName,
@@ -292,29 +304,41 @@ export function cleanupGfsFixture(name: string): void {
.split('\n')
.map(line => line.trim())
.filter(line => UUID_RE.test(line))
+ const cleanupErrors: unknown[] = []
for (const resourceId of resourceIds) {
- cleanupGfsBlob(resourceId)
+ try {
+ cleanupGfsBlob(resourceId)
+ } catch (error) {
+ cleanupErrors.push(error)
+ }
}
- runControlPostgresSql(`
- WITH fixture_resources AS (
- SELECT resource_id
- FROM gfs_resources
- WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
- AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)})
- )
- DELETE FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM fixture_resources);
+ try {
+ runControlPostgresSql(`
+ WITH fixture_resources AS (
+ SELECT resource_id
+ FROM gfs_resources
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)})
+ )
+ DELETE FROM gfs_grants WHERE resource_id IN (SELECT resource_id FROM fixture_resources);
- WITH fixture_resources AS (
- SELECT resource_id
- FROM gfs_resources
- WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
- AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)})
- )
- DELETE FROM gfs_shares WHERE resource_id IN (SELECT resource_id FROM fixture_resources);
+ WITH fixture_resources AS (
+ SELECT resource_id
+ FROM gfs_resources
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)})
+ )
+ DELETE FROM gfs_shares WHERE resource_id IN (SELECT resource_id FROM fixture_resources);
- UPDATE gfs_resources
- SET deleted_at = now(), updated_at = now()
- WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
- AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)});
- `)
+ UPDATE gfs_resources
+ SET deleted_at = now(), updated_at = now()
+ WHERE drive = ${sqlLiteral(GFS_E2E_DRIVE)}
+ AND (path_cache = ${sqlLiteral(`/${name}`)} OR path_cache LIKE ${sqlLiteral(`/${name}/%`)});
+ `)
+ } catch (error) {
+ cleanupErrors.push(error)
+ }
+ if (cleanupErrors.length > 0) {
+ throw new AggregateError(cleanupErrors, `failed to fully clean GFS fixture ${name}`)
+ }
}
diff --git a/tests/e2e/gfsUiFixtures.ts b/tests/e2e/gfsUiFixtures.ts
index 89e860e9c..c373fa8b3 100644
--- a/tests/e2e/gfsUiFixtures.ts
+++ b/tests/e2e/gfsUiFixtures.ts
@@ -1,4 +1,5 @@
export * from './gfsFixtureCore'
+export * from './gfsFixtureCleanupAssertions'
export * from './gfsResourceFixtures'
export * from './gfsUserTeamFixtures'
export * from './gfsWorkflowRecipeFixtures'
diff --git a/tests/e2e/gfsUserTeamFixtures.ts b/tests/e2e/gfsUserTeamFixtures.ts
index f846368df..888b47aa0 100644
--- a/tests/e2e/gfsUserTeamFixtures.ts
+++ b/tests/e2e/gfsUserTeamFixtures.ts
@@ -1,6 +1,7 @@
import {
type E2EDelegateVisibility,
UUID_RE,
+ assertFixtureName,
firstDataLine,
runControlPostgresSql,
splitSqlRow,
@@ -86,6 +87,15 @@ export function cleanupE2EUserTeam(teamId: string): void {
`)
}
+export function cleanupE2EUserTeamByName(name: string): void {
+ assertFixtureName(name)
+ runControlPostgresSql(`
+ DELETE FROM teams
+ WHERE name = ${sqlLiteral(name)}
+ AND name LIKE 'e2e-gfs-%';
+ `)
+}
+
export function addE2EUserToTeam(email: string, teamId: string): void {
if (!UUID_RE.test(teamId)) {
throw new Error(`invalid E2E team id: ${teamId}`)
diff --git a/tests/e2e/gfsWorkflowRecipeFixtures.test.ts b/tests/e2e/gfsWorkflowRecipeFixtures.test.ts
new file mode 100644
index 000000000..ee38cbe84
--- /dev/null
+++ b/tests/e2e/gfsWorkflowRecipeFixtures.test.ts
@@ -0,0 +1,103 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ cleanupGfsWorkflowRecipeFixture,
+ seedGfsWorkflowRecipeCloneFixture,
+} from './gfsWorkflowRecipeFixtures'
+
+const { kubectlOutMock, runControlPostgresSqlMock } = vi.hoisted(() => ({
+ kubectlOutMock: vi.fn(),
+ runControlPostgresSqlMock: vi.fn(),
+}))
+
+vi.mock('./gfsFixtureCore', async importOriginal => ({
+ ...(await importOriginal<typeof import('./gfsFixtureCore')>()),
+ kubectlOut: kubectlOutMock,
+ runControlPostgresSql: runControlPostgresSqlMock,
+}))
+
+describe('seedGfsWorkflowRecipeCloneFixture', () => {
+ beforeEach(() => {
+ kubectlOutMock.mockReset()
+ runControlPostgresSqlMock.mockReset()
+ })
+
+ it('clones the canonical read-only source into an E2E-scoped mutation target', () => {
+ kubectlOutMock
+ .mockReturnValueOnce(JSON.stringify({ spec: { steps: [{ id: 'probe' }] } }))
+ .mockReturnValueOnce('workflowrecipe.clerum.io/e2e-gfs-isolation created\n')
+ runControlPostgresSqlMock.mockReturnValue('1\n')
+
+ expect(seedGfsWorkflowRecipeCloneFixture('e2e-gfs-isolation', 'gfs-grant-e2e-plugin')).toEqual({
+ name: 'e2e-gfs-isolation',
+ namespace: 'sandbox-recipes',
+ subjectId: '3rd:sandbox-recipes/e2e-gfs-isolation',
+ })
+
+ expect(kubectlOutMock).toHaveBeenCalledTimes(2)
+ const applyInput = kubectlOutMock.mock.calls[1]?.[2] as string
+ expect(JSON.parse(applyInput)).toMatchObject({
+ metadata: {
+ name: 'e2e-gfs-isolation',
+ namespace: 'sandbox-recipes',
+ labels: { 'clerum.io/e2e': 'true' },
+ },
+ spec: { steps: [{ id: 'probe' }] },
+ })
+ expect(runControlPostgresSqlMock).toHaveBeenCalledOnce()
+ expect(runControlPostgresSqlMock.mock.calls[0]?.[0]).toContain(
+ "recipe_name = 'gfs-grant-e2e-plugin'"
+ )
+ expect(runControlPostgresSqlMock.mock.calls[0]?.[0]).toContain("'e2e-gfs-isolation'")
+ })
+
+ it('fails closed when the canonical source has no user grant to copy', () => {
+ kubectlOutMock
+ .mockReturnValueOnce(JSON.stringify({ spec: { steps: [{ id: 'probe' }] } }))
+ .mockReturnValueOnce('workflowrecipe.clerum.io/e2e-gfs-isolation created\n')
+ runControlPostgresSqlMock.mockReturnValue('0\n')
+
+ expect(() =>
+ seedGfsWorkflowRecipeCloneFixture('e2e-gfs-isolation', 'gfs-grant-e2e-plugin')
+ ).toThrow('has no user grant to copy')
+ })
+
+ it('removes only the exact E2E recipe grant rows and proves cleanup', () => {
+ kubectlOutMock.mockReturnValue('workflowrecipe.clerum.io/e2e-gfs-isolation deleted\n')
+ runControlPostgresSqlMock.mockReturnValueOnce('DELETE 1\n').mockReturnValueOnce('0\n')
+
+ cleanupGfsWorkflowRecipeFixture('e2e-gfs-isolation')
+
+ expect(kubectlOutMock).toHaveBeenCalledWith(
+ [
+ '-n',
+ 'sandbox-recipes',
+ 'delete',
+ 'workflowrecipe',
+ 'e2e-gfs-isolation',
+ '--ignore-not-found=true',
+ ],
+ 20_000
+ )
+ expect(runControlPostgresSqlMock).toHaveBeenCalledTimes(2)
+ for (const [sql] of runControlPostgresSqlMock.mock.calls) {
+ expect(sql).toContain("recipe_namespace = 'sandbox-recipes'")
+ expect(sql).toContain("recipe_name = 'e2e-gfs-isolation'")
+ }
+ })
+
+ it('rejects unsafe cleanup before invoking Kubernetes or SQL', () => {
+ expect(() => cleanupGfsWorkflowRecipeFixture('unsafe-recipe')).toThrow(
+ 'refusing to mutate non-E2E GFS fixture'
+ )
+ expect(kubectlOutMock).not.toHaveBeenCalled()
+ expect(runControlPostgresSqlMock).not.toHaveBeenCalled()
+ })
+
+ it('rejects an unsafe mutation target before invoking kubectl', () => {
+ expect(() =>
+ seedGfsWorkflowRecipeCloneFixture('unsafe-recipe', 'gfs-grant-e2e-plugin')
+ ).toThrow('refusing to mutate non-E2E GFS fixture')
+ expect(kubectlOutMock).not.toHaveBeenCalled()
+ expect(runControlPostgresSqlMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/tests/e2e/gfsWorkflowRecipeFixtures.ts b/tests/e2e/gfsWorkflowRecipeFixtures.ts
index bbe319d99..99602e198 100644
--- a/tests/e2e/gfsWorkflowRecipeFixtures.ts
+++ b/tests/e2e/gfsWorkflowRecipeFixtures.ts
@@ -1,4 +1,18 @@
-import { assertFixtureName, kubectlOut } from './gfsFixtureCore'
+import {
+ assertFixtureName,
+ firstDataLine,
+ kubectlOut,
+ runControlPostgresSql,
+ sqlLiteral,
+} from './gfsFixtureCore'
+
+const DNS_1123_SUBDOMAIN = /^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)*$/
+
+function assertReadonlyRecipeName(name: string): void {
+ if (name.length > 253 || !DNS_1123_SUBDOMAIN.test(name)) {
+ throw new Error(`invalid source WorkflowRecipe name "${name}"`)
+ }
+}
export interface GfsWorkflowRecipeFixture {
name: string
@@ -43,8 +57,76 @@ spec:
export function cleanupGfsWorkflowRecipeFixture(name: string): void {
assertFixtureName(name)
+ const namespace = 'sandbox-recipes'
+ kubectlOut(['-n', namespace, 'delete', 'workflowrecipe', name, '--ignore-not-found=true'], 20_000)
+ runControlPostgresSql(`
+ DELETE FROM user_workflow_triggers
+ WHERE recipe_namespace = ${sqlLiteral(namespace)}
+ AND recipe_name = ${sqlLiteral(name)};
+ `)
+ const remainingGrantCount = firstDataLine(
+ runControlPostgresSql(`
+ SELECT COUNT(*)::text
+ FROM user_workflow_triggers
+ WHERE recipe_namespace = ${sqlLiteral(namespace)}
+ AND recipe_name = ${sqlLiteral(name)};
+ `)
+ )
+ if (remainingGrantCount !== '0') {
+ throw new Error(
+ `WorkflowRecipe fixture ${namespace}/${name} retained ${remainingGrantCount || 'unknown'} user grants after cleanup`
+ )
+ }
+}
+
+export function seedGfsWorkflowRecipeCloneFixture(
+ name: string,
+ sourceName: string
+): GfsWorkflowRecipeFixture {
+ assertFixtureName(name)
+ assertReadonlyRecipeName(sourceName)
+ const namespace = 'sandbox-recipes'
+ const source = JSON.parse(
+ kubectlOut(['-n', namespace, 'get', 'workflowrecipe', sourceName, '-o', 'json'])
+ ) as { spec?: unknown }
+ if (!source.spec) {
+ throw new Error(`WorkflowRecipe ${namespace}/${sourceName} has no spec to clone`)
+ }
kubectlOut(
- ['-n', 'sandbox-recipes', 'delete', 'workflowrecipe', name, '--ignore-not-found=true'],
- 20_000
+ ['apply', '-f', '-'],
+ 30_000,
+ JSON.stringify({
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: {
+ name,
+ namespace,
+ labels: { 'clerum.io/e2e': 'true' },
+ },
+ spec: source.spec,
+ })
+ )
+ const sourceGrantCount = firstDataLine(
+ runControlPostgresSql(`
+ WITH copied AS (
+ INSERT INTO user_workflow_triggers (user_id, recipe_namespace, recipe_name)
+ SELECT user_id, ${sqlLiteral(namespace)}, ${sqlLiteral(name)}
+ FROM user_workflow_triggers
+ WHERE recipe_namespace = ${sqlLiteral(namespace)}
+ AND recipe_name = ${sqlLiteral(sourceName)}
+ ON CONFLICT DO NOTHING
+ RETURNING user_id
+ )
+ SELECT COUNT(*)::text
+ FROM user_workflow_triggers
+ WHERE recipe_namespace = ${sqlLiteral(namespace)}
+ AND recipe_name = ${sqlLiteral(sourceName)};
+ `)
)
+ if (!/^\d+$/.test(sourceGrantCount) || Number(sourceGrantCount) < 1) {
+ throw new Error(
+ `WorkflowRecipe ${namespace}/${sourceName} has no user grant to copy into ${namespace}/${name}`
+ )
+ }
+ return { name, namespace, subjectId: `3rd:${namespace}/${name}` }
}
diff --git a/tests/e2e/mcp-host/cron-probe-fixture-contract.test.ts b/tests/e2e/mcp-host/cron-probe-fixture-contract.test.ts
new file mode 100644
index 000000000..a99658ad5
--- /dev/null
+++ b/tests/e2e/mcp-host/cron-probe-fixture-contract.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { CRON_EXEC_PROBE_INSTRUCTION } from '../fixtures/cronExecProbeInstruction.js'
+
+function yamlInstructionBlock(source: string): string {
+ const lines = source.split('\n')
+ const start = lines.findIndex(line => line.trim() === 'instruction: |')
+ if (start < 0) throw new Error('WorkflowRecipe fixture has no instruction block')
+
+ const parentIndent = lines[start].length - lines[start].trimStart().length
+ const contentIndent = parentIndent + 2
+ const content: string[] = []
+ for (const line of lines.slice(start + 1)) {
+ const indent = line.length - line.trimStart().length
+ if (line.trim() && indent <= parentIndent) break
+ content.push(line.slice(Math.min(contentIndent, line.length)))
+ }
+ return content.join('\n').trim()
+}
+
+describe('CR-11 cron probe fixture contract', () => {
+ it('keeps the WorkflowRecipe instruction aligned with the shared E2E probe', () => {
+ const currentDir = path.dirname(fileURLToPath(import.meta.url))
+ const recipePath = path.resolve(currentDir, '../fixtures/cron-exec-test-recipe.yaml')
+ expect(yamlInstructionBlock(fs.readFileSync(recipePath, 'utf8'))).toBe(
+ CRON_EXEC_PROBE_INSTRUCTION
+ )
+ })
+})
diff --git a/tests/e2e/mcp-host/cron-scheduler.test.ts b/tests/e2e/mcp-host/cron-scheduler.test.ts
index b78aeded7..db3864667 100644
--- a/tests/e2e/mcp-host/cron-scheduler.test.ts
+++ b/tests/e2e/mcp-host/cron-scheduler.test.ts
@@ -42,6 +42,7 @@
* of the default deterministic minikube gate.
*/
import { afterAll, describe, expect, it } from 'vitest'
+import { CRON_EXEC_PROBE_INSTRUCTION } from '../fixtures/cronExecProbeInstruction.js'
import {
MCP_HOST_URL,
approveRequest,
@@ -204,28 +205,6 @@ function readAbsFileInContainer(absPath: string): string {
* create -> fire -> wait -> verify -> report flow autonomously so the
* LLM (not the test harness) orchestrates every step.
*/
-const CRON_EXEC_RECIPE_INSTRUCTION = [
- 'You are validating whether SCHEDULED (cron) tasks actually execute on this',
- 'mcp-host. Use the available tools and do these steps IN ORDER.',
- '',
- '1. CREATE — use the cron scheduling tool (cron_manage) to create a recurring job',
- ' named "e2e-cron-exec" with schedule "*/1 * * * *". The job\'s task content MUST be',
- ' EXACTLY this sentence (copy it verbatim):',
- ' Use the shell tool to run this command: echo CRON_EXEC_OK > /tmp/cron-exec-proof.txt',
- '',
- '2. FIRE — use cron_manage to TRIGGER the "e2e-cron-exec" job immediately so it runs now.',
- '',
- '3. WAIT + VERIFY — the triggered task runs asynchronously in the background, so you',
- ' must poll. Use the shell tool to run:',
- ' sleep 8 ; cat /tmp/cron-exec-proof.txt',
- ' If the file is missing or empty, repeat the same shell command (sleep 8 ; cat ...)',
- ' up to 4 attempts total.',
- '',
- '4. REPORT — the FINAL line of your answer MUST be exactly one of:',
- ' - if the file contains CRON_EXEC_OK -> CRON_EXEC_VERIFIED',
- ' - if after all 4 attempts it is empty -> CRON_EXEC_FAILED',
-].join('\n')
-
type CronResultEntry = {
id: string
cronJobId: string
@@ -545,7 +524,7 @@ describe.skipIf(!RUN_CRON_SCHEDULER)('Phase 1: Cron CRUD (approval disabled)', (
// Single-shot: hand the full recipe instruction to the agent and let it
// self-orchestrate every step. Long timeout: the agent polls with
// `sleep 8` up to 4 times plus multiple LLM rounds.
- const { response } = await sendWithApproval(CRON_EXEC_RECIPE_INSTRUCTION, {
+ const { response } = await sendWithApproval(CRON_EXEC_PROBE_INSTRUCTION, {
userId,
timeoutMs: 720_000,
})
diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.json
index 53b39a9db..d21ab9dc2 100644
--- a/tests/e2e/package-lock.json
+++ b/tests/e2e/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-e2e-tests",
- "version": "0.1.44",
+ "version": "0.1.50",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-e2e-tests",
- "version": "0.1.44",
+ "version": "0.1.50",
"devDependencies": {
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.0.0",
diff --git a/tests/e2e/package.json b/tests/e2e/package.json
index 842cbb500..c84fb9021 100644
--- a/tests/e2e/package.json
+++ b/tests/e2e/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-e2e-tests",
- "version": "0.1.44",
+ "version": "0.1.50",
"private": true,
"type": "module",
"scripts": {
diff --git a/webhook-gateway/Makefile b/webhook-gateway/Makefile
index fa21f57b4..52a0085d6 100644
--- a/webhook-gateway/Makefile
+++ b/webhook-gateway/Makefile
@@ -1,6 +1,6 @@
.PHONY: build clean install dev docker-build docker-push docker-push-cross test
-REGISTRY ?= us-central1-docker.pkg.dev/your-gcp-project/clerum
+REGISTRY ?= us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum
IMAGE_NAME ?= webhook-gateway
TAG ?= $(shell git describe --tags --always 2>/dev/null || echo "latest")
diff --git a/webhook-proxy/Makefile b/webhook-proxy/Makefile
index ab3b5a8cf..b4ea07156 100644
--- a/webhook-proxy/Makefile
+++ b/webhook-proxy/Makefile
@@ -1,6 +1,6 @@
.PHONY: build clean install dev docker-build docker-push docker-push-cross test
-REGISTRY ?= us-central1-docker.pkg.dev/your-gcp-project/clerum
+REGISTRY ?= us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum
IMAGE_NAME ?= webhook-proxy
TAG ?= $(shell git describe --tags --always 2>/dev/null || echo "latest")
diff --git a/workflow-recipes/Makefile b/workflow-recipes/Makefile
index 6fd608538..317cf2e79 100644
--- a/workflow-recipes/Makefile
+++ b/workflow-recipes/Makefile
@@ -48,7 +48,7 @@
.PHONY: cluster-env-check cluster-start cluster-stop cluster-delete cluster-setup cluster-setup-simple cluster-status
# Docker build (existing)
-REGISTRY ?= us-central1-docker.pkg.dev/your-gcp-project/clerum
+REGISTRY ?= us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum
IMAGE_NAME ?= workflow-recipes
TAG ?= $(shell git describe --tags --always 2>/dev/null || echo "latest")
diff --git a/workflow-recipes/README.md b/workflow-recipes/README.md
index 28e0dc06f..05652d52a 100644
--- a/workflow-recipes/README.md
+++ b/workflow-recipes/README.md
@@ -112,6 +112,7 @@ Test files are co-located with source in `src/` (e.g., `reconciler/resourceBuild
## Further Reading
- [WorkflowRecipe CRD reference](../docs/crds/workflowrecipe.md)
+- [Workflow Recipes feature hub](../docs/features/workflow-recipes.md)
## Source Layout
@@ -159,7 +160,6 @@ src/
├── modelConfigHandler.ts # Per-step model overrides
├── httpMcpHostClient.ts # mcp-host HTTP client
├── schedulingHandler.ts # Cron/trigger scheduling
- ├── triggerHandler.ts # External trigger support
├── signalStore.ts # Inter-step signal passing
├── rateLimiter.ts # LLM call rate limiting
├── historyManager.ts # Execution history
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index eace83a4b..4ef27d448 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.251",
+ "version": "0.1.252",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.251",
+ "version": "0.1.252",
"license": "MIT",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index cb575f8b1..f5635791e 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.251",
+ "version": "0.1.252",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/samples/mcp-batch-processor.yaml b/workflow-recipes/samples/mcp-batch-processor.yaml
index e0bd13e6d..38c1c97e3 100644
--- a/workflow-recipes/samples/mcp-batch-processor.yaml
+++ b/workflow-recipes/samples/mcp-batch-processor.yaml
@@ -8,7 +8,7 @@ spec:
workloads:
- id: batch-processor
type: job
- image: us-central1-docker.pkg.dev/your-gcp-project/clerum/batch-processor:latest
+ image: us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/batch-processor:latest
backoffLimit: 2
command: ['node', 'process.js']
env:
diff --git a/workflow-recipes/samples/mcp-file-browser.yaml b/workflow-recipes/samples/mcp-file-browser.yaml
index 4822e98c7..ceace3e28 100644
--- a/workflow-recipes/samples/mcp-file-browser.yaml
+++ b/workflow-recipes/samples/mcp-file-browser.yaml
@@ -9,7 +9,7 @@ spec:
workloads:
- id: file-browser
type: deployment
- image: us-central1-docker.pkg.dev/your-gcp-project/clerum/file-browser-mcp:latest
+ image: us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/file-browser-mcp:latest
port: 3000
transport:
type: streamableHttp
diff --git a/workflow-recipes/samples/mcp-health-monitor.yaml b/workflow-recipes/samples/mcp-health-monitor.yaml
index 5311ad9f0..d5f3e6ced 100644
--- a/workflow-recipes/samples/mcp-health-monitor.yaml
+++ b/workflow-recipes/samples/mcp-health-monitor.yaml
@@ -8,7 +8,7 @@ spec:
workloads:
- id: health-monitor
type: daemonset
- image: us-central1-docker.pkg.dev/your-gcp-project/clerum/health-monitor:latest
+ image: us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/health-monitor:latest
port: 9090
resources:
requests:
diff --git a/workflow-recipes/samples/prod/stdio-mcp-with-postgres.yaml b/workflow-recipes/samples/prod/stdio-mcp-with-postgres.yaml
index d62e8430b..49d86cd86 100644
--- a/workflow-recipes/samples/prod/stdio-mcp-with-postgres.yaml
+++ b/workflow-recipes/samples/prod/stdio-mcp-with-postgres.yaml
@@ -38,7 +38,7 @@ spec:
- id: pg-stdio-mcp
type: deployment
- image: us-central1-docker.pkg.dev/your-gcp-project/clerum/mock-stdio-mcp-server:prod
+ image: us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/mock-stdio-mcp-server:prod
imagePullPolicy: Always
imagePullSecrets:
- clerum
diff --git a/workflow-recipes/src/cli/backfillRecipeOwnership.cli.test.ts b/workflow-recipes/src/cli/backfillRecipeOwnership.cli.test.ts
index d04fa2454..7e6bb46d5 100644
--- a/workflow-recipes/src/cli/backfillRecipeOwnership.cli.test.ts
+++ b/workflow-recipes/src/cli/backfillRecipeOwnership.cli.test.ts
@@ -192,7 +192,7 @@ describe('issue #637 ownership backfill CLI contract', () => {
recipes: [recipe('recipe-a', 'alpha')],
namespaces: { 'mcp-server': {}, 'sandbox-ui': {}, 'sandbox-recipes': { alpha: {} } },
})
- const result = h.run(['--context', 'gke_your-gcp-project_us-central1-a_clerum', '--apply'])
+ const result = h.run(['--context', 'gke_${GCP_PROJECT}_us-central1-a_clerum', '--apply'])
expect(result.status).toBe(2)
expect(result.stderr).toContain('without CONFIRM=yes')
expect(h.read().namespaces['sandbox-recipes'].alpha).toEqual({})
diff --git a/workflow-recipes/src/cli/backfillRecipeSecretOwnership.ts b/workflow-recipes/src/cli/backfillRecipeSecretOwnership.ts
index b810ae01c..ae357f22c 100644
--- a/workflow-recipes/src/cli/backfillRecipeSecretOwnership.ts
+++ b/workflow-recipes/src/cli/backfillRecipeSecretOwnership.ts
@@ -1,10 +1,10 @@
#!/usr/bin/env node
// Issue #637 back-fill CLI — stamps `clerum.io/owner-recipe=<recipe>` on
// pre-existing recipe Secrets that predate the ownership-label model and would be
-// fail-closed-denied by the WRC reconciler (e.g. a recipe's envSecret created
-// before ownership labelling existed). The decision logic lives in the
-// unit-tested `planSecretOwnershipBackfill`; this file only does cluster I/O
-// via kubectl.
+// fail-closed-denied by the WRC reconciler (prod incident 2026-06-26: leadforge +
+// agentic-task-board plugins broke because leadforge-mcp-credentials / atb-secrets
+// were unlabeled). The decision logic lives in the unit-tested
+// `planSecretOwnershipBackfill`; this file only does cluster I/O via kubectl.
//
// DRY-RUN by default — prints the plan and exits without mutating. Pass `--apply`
// to label. Against a prod context `--apply` additionally requires CONFIRM=yes.
diff --git a/workflow-recipes/src/gfsBinding.test.ts b/workflow-recipes/src/gfsBinding.test.ts
index e22a4d672..04ca1c792 100644
--- a/workflow-recipes/src/gfsBinding.test.ts
+++ b/workflow-recipes/src/gfsBinding.test.ts
@@ -10,11 +10,28 @@ function okResponse(body: unknown): Response {
return { ok: true, status: 200, json: async () => body } as Response
}
+function jwt(payload: unknown): string {
+ const encode = (value: unknown): string =>
+ Buffer.from(JSON.stringify(value)).toString('base64url')
+ return `${encode({ alg: 'none' })}.${encode(payload)}.unverified-signature`
+}
+
+const expectedSubject = 'host:3rd:sandbox-recipes/my-recipe'
+
+function validBinding(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ token: jwt({ sub: expectedSubject, scopes: ['gfs.read'] }),
+ expiresInSeconds: 300,
+ subject: expectedSubject,
+ ...overrides,
+ }
+}
+
describe('mintRecipeHostGfsToken', () => {
- it('POSTs to the provisioner route for the recipe with the WRC bearer', async () => {
+ it('returns a token only for the exact requested recipe subject', async () => {
const fetchFn = vi.fn(async () =>
okResponse({
- token: 'tok',
+ token: jwt({ sub: expectedSubject, scopes: ['gfs.read'] }),
expiresInSeconds: 300,
subject: 'host:3rd:sandbox-recipes/my-recipe',
})
@@ -32,11 +49,31 @@ describe('mintRecipeHostGfsToken', () => {
expect(JSON.parse(init.body)).toEqual({ namespace: 'sandbox-recipes', scopes: ['gfs.read'] })
})
- it('passes explicit recipe host scopes to control-api', async () => {
+ it('fails closed when control-api returns a different recipe subject', async () => {
const fetchFn = vi.fn(async () =>
okResponse({
token: 'tok',
expiresInSeconds: 300,
+ subject: 'host:3rd:sandbox-recipes/other-recipe',
+ })
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintRecipeHostGfsToken('sandbox-recipes', 'my-recipe', {
+ controlApiBaseUrl: 'http://control-api:8090',
+ signToken: () => 'wrc-jwt',
+ fetchFn,
+ })
+ ).rejects.toThrow(
+ 'gfs recipe host token subject mismatch: expected host:3rd:sandbox-recipes/my-recipe, received host:3rd:sandbox-recipes/other-recipe'
+ )
+ })
+
+ it('passes explicit recipe host scopes to control-api', async () => {
+ const fetchFn = vi.fn(async () =>
+ okResponse({
+ token: jwt({ sub: expectedSubject, scopes: ['gfs.read', 'gfs.write'] }),
+ expiresInSeconds: 300,
subject: 'host:3rd:sandbox-recipes/my-recipe',
})
) as unknown as typeof fetch
@@ -67,4 +104,79 @@ describe('mintRecipeHostGfsToken', () => {
})
).rejects.toThrow(/403/)
})
+
+ describe('issued token claims', () => {
+ it.each([
+ ['a non-JWT token', 'opaque-token', 'not a well-formed JWT'],
+ [
+ 'a JWT with an empty signature',
+ `${jwt({}).split('.').slice(0, 2).join('.')}.`,
+ 'not a well-formed JWT',
+ ],
+ ['a JWT with invalid base64url', 'header.%%%.signature', 'not a well-formed JWT'],
+ ['a JWT with malformed JSON', 'header.bm90LWpzb24.signature', 'malformed JWT payload'],
+ ['a JWT with a non-object payload', jwt(['not-an-object']), 'malformed JWT payload'],
+ ])('fails closed for %s', async (_description, token, expectedError) => {
+ const fetchFn = vi.fn(async () =>
+ okResponse(validBinding({ token }))
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintRecipeHostGfsToken('sandbox-recipes', 'my-recipe', {
+ controlApiBaseUrl: 'http://control-api:8090',
+ signToken: () => 'wrc-jwt',
+ fetchFn,
+ })
+ ).rejects.toThrow(expectedError)
+ })
+
+ it('fails closed when the JWT subject differs from the exact response subject', async () => {
+ const fetchFn = vi.fn(async () =>
+ okResponse(
+ validBinding({
+ token: jwt({
+ sub: 'host:3rd:sandbox-recipes/other-recipe',
+ scopes: ['gfs.read'],
+ }),
+ })
+ )
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintRecipeHostGfsToken('sandbox-recipes', 'my-recipe', {
+ controlApiBaseUrl: 'http://control-api:8090',
+ signToken: () => 'wrc-jwt',
+ fetchFn,
+ })
+ ).rejects.toThrow(
+ 'gfs recipe host token claim subject mismatch: expected host:3rd:sandbox-recipes/my-recipe, received host:3rd:sandbox-recipes/other-recipe'
+ )
+ })
+
+ it.each([
+ ['missing', undefined],
+ ['not an array', 'gfs.read'],
+ ['missing requested write scope', ['gfs.read']],
+ ['extra scope', ['gfs.read', 'gfs.write', 'gfs.delete']],
+ ['different order', ['gfs.write', 'gfs.read']],
+ ['duplicate scope', ['gfs.read', 'gfs.read', 'gfs.write']],
+ ])('fails closed when JWT scopes are %s', async (_description, scopes) => {
+ const fetchFn = vi.fn(async () =>
+ okResponse(
+ validBinding({
+ token: jwt({ sub: expectedSubject, scopes }),
+ })
+ )
+ ) as unknown as typeof fetch
+
+ await expect(
+ mintRecipeHostGfsToken('sandbox-recipes', 'my-recipe', {
+ controlApiBaseUrl: 'http://control-api:8090',
+ signToken: () => 'wrc-jwt',
+ fetchFn,
+ scopes: ['gfs.read', 'gfs.write'],
+ })
+ ).rejects.toThrow('gfs recipe host token claim scopes do not exactly match requested scopes')
+ })
+ })
})
diff --git a/workflow-recipes/src/gfsBinding.ts b/workflow-recipes/src/gfsBinding.ts
index 3ba9153cd..ee6a43936 100644
--- a/workflow-recipes/src/gfsBinding.ts
+++ b/workflow-recipes/src/gfsBinding.ts
@@ -10,7 +10,8 @@ const CONTROL_API_BASE_URL =
* a 3rd-party `host` (subject `host:3rd:<recipeNs>/<recipeName>`) and requests a
* scoped gfs token from control-api. The recipe's workloads reach gfs THROUGH
* this host (brokered, gated by allowedCallers) — a workload is never a gfs
- * subject with its own token.
+ * subject with its own token. The returned subject must match that exact recipe
+ * identity; a different subject is rejected even on a successful HTTP response.
*/
export interface GfsRecipeHostToken {
@@ -27,16 +28,71 @@ export interface GfsBindingDeps {
scopes?: WorkflowRecipeGfsScope[]
}
+interface UntrustedGfsTokenClaims {
+ sub?: unknown
+ scopes?: unknown
+}
+
+function decodeUntrustedJwtPayload(token: string): UntrustedGfsTokenClaims {
+ const segments = token.split('.')
+ const payload = segments[1]
+ if (
+ segments.length !== 3 ||
+ segments.some(segment => !/^[A-Za-z0-9_-]+$/.test(segment)) ||
+ payload.length % 4 === 1
+ ) {
+ throw new Error('gfs recipe host token is not a well-formed JWT')
+ }
+
+ try {
+ const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as unknown
+ if (decoded === null || typeof decoded !== 'object' || Array.isArray(decoded)) {
+ throw new Error('payload is not an object')
+ }
+ return decoded as UntrustedGfsTokenClaims
+ } catch {
+ throw new Error('gfs recipe host token has a malformed JWT payload')
+ }
+}
+
+function validateUntrustedTokenClaims(
+ token: unknown,
+ expectedSubject: string,
+ expectedScopes: WorkflowRecipeGfsScope[]
+): asserts token is string {
+ if (typeof token !== 'string') {
+ throw new Error('gfs recipe host token is not a well-formed JWT')
+ }
+
+ // This is deliberately metadata validation only. The gfs service remains the
+ // authority that verifies the token signature when the credential is used.
+ const claims = decodeUntrustedJwtPayload(token)
+ if (claims.sub !== expectedSubject) {
+ throw new Error(
+ `gfs recipe host token claim subject mismatch: expected ${expectedSubject}, received ${String(claims.sub)}`
+ )
+ }
+ if (
+ !Array.isArray(claims.scopes) ||
+ claims.scopes.length !== expectedScopes.length ||
+ claims.scopes.some((scope, index) => scope !== expectedScopes[index])
+ ) {
+ throw new Error('gfs recipe host token claim scopes do not exactly match requested scopes')
+ }
+}
+
/**
- * Mint the 3rd-party host gfs token for a recipe's mcp-host. Read-only scope in
- * P4 baseline (publish targets add write where the recipe holds it). Fails loud
- * on any non-2xx — a recipe host without a gfs token must surface.
+ * Mint the 3rd-party host gfs token for a recipe's mcp-host. The caller derives
+ * the read/write ceiling from the recipe intent, while resource grants remain
+ * authoritative. Fails loud on any non-2xx or mismatched issued authority.
*/
export async function mintRecipeHostGfsToken(
recipeNamespace: string,
recipeName: string,
deps: GfsBindingDeps = {}
): Promise<GfsRecipeHostToken> {
+ const expectedSubject = `host:3rd:${recipeNamespace}/${recipeName}`
+ const expectedScopes: WorkflowRecipeGfsScope[] = [...(deps.scopes ?? ['gfs.read'])]
const baseUrl = deps.controlApiBaseUrl ?? CONTROL_API_BASE_URL
const sign = deps.signToken ?? signInternalControlJwt
const doFetch = deps.fetchFn ?? fetch
@@ -47,10 +103,17 @@ export async function mintRecipeHostGfsToken(
'content-type': 'application/json',
Authorization: `Bearer ${sign()}`,
},
- body: JSON.stringify({ namespace: recipeNamespace, scopes: deps.scopes ?? ['gfs.read'] }),
+ body: JSON.stringify({ namespace: recipeNamespace, scopes: expectedScopes }),
})
if (!response.ok) {
throw new Error(`gfs recipe host token mint failed: HTTP ${response.status}`)
}
- return (await response.json()) as GfsRecipeHostToken
+ const binding = (await response.json()) as GfsRecipeHostToken
+ if (binding.subject !== expectedSubject) {
+ throw new Error(
+ `gfs recipe host token subject mismatch: expected ${expectedSubject}, received ${binding.subject}`
+ )
+ }
+ validateUntrustedTokenClaims(binding.token, expectedSubject, expectedScopes)
+ return binding
}
diff --git a/workflow-recipes/src/k8sClient.test.ts b/workflow-recipes/src/k8sClient.test.ts
index 3159b6780..f36c3dec7 100644
--- a/workflow-recipes/src/k8sClient.test.ts
+++ b/workflow-recipes/src/k8sClient.test.ts
@@ -1201,6 +1201,34 @@ describe('status-only events drive DB sync (terminal + heartbeat)', () => {
return { internal, reconcile, sync }
}
+ it('does not reconcile a run child until the workflow_runs sync barrier completes', async () => {
+ let markSyncStarted!: () => void
+ let releaseSync!: () => void
+ const syncStarted = new Promise<void>(resolve => {
+ markSyncStarted = resolve
+ })
+ const syncBarrier = new Promise<void>(resolve => {
+ releaseSync = resolve
+ })
+ const child = makeRunChild()
+ const { internal, reconcile, sync } = makeInternal(child, async () => {
+ markSyncStarted()
+ await syncBarrier
+ })
+
+ const event = internal.handleRecipeEvent('ADDED', child)
+ await syncStarted
+
+ expect(sync).toHaveBeenCalledTimes(1)
+ expect(reconcile).not.toHaveBeenCalled()
+
+ releaseSync()
+ await event
+
+ expect(reconcile).toHaveBeenCalledTimes(1)
+ expect(sync.mock.invocationCallOrder[0]).toBeLessThan(reconcile.mock.invocationCallOrder[0])
+ })
+
it.each(['completed', 'failed', 'cancelled'] as const)(
'runs syncFromRecipeExecution AND reconciles a %s run-scoped status-only event',
async phase => {
diff --git a/workflow-recipes/src/mcp/server.ts b/workflow-recipes/src/mcp/server.ts
index 70a23b35b..2343e89fe 100644
--- a/workflow-recipes/src/mcp/server.ts
+++ b/workflow-recipes/src/mcp/server.ts
@@ -449,18 +449,6 @@ export class ClerumMcpServer {
res.end(JSON.stringify(result.body))
return
}
-
- // POST /api/v1/workflow/:name/trigger
- if (subPath === '/trigger') {
- // Recipe namespace travels via the token claim (signed by WRC when it
- // minted the CronJob trigger token). Callers never need to hardcode
- // sandbox vs mcp-server — whichever namespace the CRD lives in,
- // the claim says so.
- const result = await handlers.postTrigger(recipeName, claims.recipeNamespace, claims)
- res.writeHead(result.status, { 'Content-Type': 'application/json' })
- res.end(JSON.stringify(result.body))
- return
- }
}
}
diff --git a/workflow-recipes/src/reconciler/k8sErrors.test.ts b/workflow-recipes/src/reconciler/k8sErrors.test.ts
index 1813f17cf..b58302402 100644
--- a/workflow-recipes/src/reconciler/k8sErrors.test.ts
+++ b/workflow-recipes/src/reconciler/k8sErrors.test.ts
@@ -33,7 +33,7 @@ describe('isRetryableInfraError', () => {
// FetchError carries the socket code on `.code` as a string.
const err = Object.assign(
new Error(
- 'request to https://203.0.113.1/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies failed, reason: connect ETIMEDOUT 203.0.113.1:443'
+ 'request to https://203.0.113.10/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies failed, reason: connect ETIMEDOUT 203.0.113.10:443'
),
{ code: 'ETIMEDOUT', name: 'FetchError' }
)
@@ -65,14 +65,14 @@ describe('isRetryableInfraError', () => {
it('matches a wrapped error message that lost its .code', () => {
// WRC re-wraps pre-deploy failures: `new Error("Pre-deploy ... : connect ETIMEDOUT ...")`.
const wrapped = new Error(
- 'Pre-deploy Context allowlist failed for "recipe-helpdesk": request to https://203.0.113.1/... failed, reason: connect ETIMEDOUT 203.0.113.1:443'
+ 'Pre-deploy Context allowlist failed for "recipe-helpdesk": request to https://203.0.113.10/... failed, reason: connect ETIMEDOUT 203.0.113.10:443'
)
expect(isRetryableInfraError(wrapped)).toBe(true)
})
it('matches a persisted status.message string (already-latched recipe)', () => {
const persisted =
- 'FetchError: request to https://203.0.113.1/apis/apps/v1/namespaces/sandbox-recipes/deployments/x failed, reason: connect ETIMEDOUT 203.0.113.1:443'
+ 'FetchError: request to https://203.0.113.10/apis/apps/v1/namespaces/sandbox-recipes/deployments/x failed, reason: connect ETIMEDOUT 203.0.113.10:443'
expect(isRetryableInfraError(persisted)).toBe(true)
})
@@ -111,7 +111,7 @@ describe('isRetryableInfraError', () => {
})
it('DOES match the anchored transport shapes (syscall-prefixed / reason:)', () => {
- expect(isRetryableInfraError('connect ETIMEDOUT 203.0.113.1:443')).toBe(true)
+ expect(isRetryableInfraError('connect ETIMEDOUT 203.0.113.10:443')).toBe(true)
expect(isRetryableInfraError('read ECONNRESET')).toBe(true)
expect(isRetryableInfraError('getaddrinfo EAI_AGAIN registry.example.com')).toBe(true)
expect(
diff --git a/workflow-recipes/src/reconciler/k8sErrors.ts b/workflow-recipes/src/reconciler/k8sErrors.ts
index 9ce03c504..ed419c37e 100644
--- a/workflow-recipes/src/reconciler/k8sErrors.ts
+++ b/workflow-recipes/src/reconciler/k8sErrors.ts
@@ -93,7 +93,7 @@ const TRANSPORT_PREFIXED_PHRASE_RE = new RegExp(
/**
* Node renders socket errors as `<syscall> <CODE> <addr>` (e.g.
- * `connect ETIMEDOUT 203.0.113.1:443`, `read ECONNRESET`,
+ * `connect ETIMEDOUT 203.0.113.10:443`, `read ECONNRESET`,
* `getaddrinfo EAI_AGAIN host`) and node-fetch wraps them as
* `request to <url> failed, reason: connect ETIMEDOUT …`.
*
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index 16e82985b..098710e33 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -4,8 +4,9 @@ import { loadAll } from 'js-yaml'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { loadConfig } from '../config'
-import { CronJobDef, WorkflowRecipeCRD, WorkloadDef } from '../types'
+import { CronJobDef, WorkflowRecipeCRD, WorkflowRecipeGfsIntentSpec, WorkloadDef } from '../types'
import { INHERITED_PARENT_RESOURCES_ANNOTATION } from '../workflow/childRecipeFactory'
+import { buildCoordinatorGfsNetworkPolicy } from '../workflow/networkPolicyFactory'
import { isRetryableInfraError } from './k8sErrors'
import * as brokerIssuer from './oauthBrokerTokenIssuerClient'
import {
@@ -101,6 +102,8 @@ const mockNetworkingApi = {
deleteCollectionNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
}
+const mockVerifyWorkflowRunProvenance = vi.fn().mockResolvedValue('verified')
+
vi.mock('@kubernetes/client-node', () => ({
KubeConfig: vi.fn().mockImplementation(() => ({
makeApiClient: vi.fn().mockImplementation((ApiClass: unknown) => {
@@ -160,6 +163,7 @@ describe('WorkflowRecipeReconciler', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockVerifyWorkflowRunProvenance.mockResolvedValue('verified')
process.env.CLERUM_NETWORK_POLICY_ENFORCEMENT_CONFIRMED = 'true'
mockAppsApi.readNamespacedDeployment.mockReset()
mockAppsApi.readNamespacedDeployment.mockResolvedValue({
@@ -216,9 +220,19 @@ describe('WorkflowRecipeReconciler', () => {
mockNetworkingApi.createNamespacedNetworkPolicy.mockReset()
mockNetworkingApi.createNamespacedNetworkPolicy.mockResolvedValue({})
mockNetworkingApi.readNamespacedNetworkPolicy.mockReset()
- mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValue({
- metadata: { resourceVersion: '1' },
- })
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockImplementation(({ name }: { name: string }) =>
+ Promise.resolve({
+ metadata: {
+ name,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/managed-by': 'wrc',
+ 'clerum.io/recipe': name.replace(/-coordinator-to-gfs$/, ''),
+ },
+ },
+ })
+ )
mockNetworkingApi.replaceNamespacedNetworkPolicy.mockReset()
mockNetworkingApi.replaceNamespacedNetworkPolicy.mockResolvedValue({})
mockNetworkingApi.deleteNamespacedNetworkPolicy.mockReset()
@@ -226,7 +240,9 @@ describe('WorkflowRecipeReconciler', () => {
mockNetworkingApi.listNamespacedNetworkPolicy.mockReset()
mockNetworkingApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })
const kc = new k8s.KubeConfig()
- reconciler = new WorkflowRecipeReconciler(kc)
+ reconciler = new WorkflowRecipeReconciler(kc, undefined, {
+ verifyWorkflowRunProvenance: mockVerifyWorkflowRunProvenance,
+ })
})
// ─── Pipeline Tests ─────────────────────────────────────────────
@@ -3800,6 +3816,68 @@ describe('WorkflowRecipeReconciler', () => {
})
})
+ it('forwards the exact GFS read/write intent to the workflow reconciler', async () => {
+ const workflowReconcile = vi.fn().mockResolvedValue({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof workflowReconcile
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = { reconcile: workflowReconcile, validateWorkflowSpec: () => undefined }
+
+ const gfs: WorkflowRecipeGfsIntentSpec = {
+ mounts: [
+ {
+ drive: 'main',
+ target: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ],
+ }
+ const recipe = makeRecipe({
+ spec: {
+ steps: [{ id: 'read-write', run: snippetRun() }],
+ gfs,
+ },
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(workflowReconcile.mock.calls[0][3].gfs).toEqual(gfs)
+ })
+
+ it('does not synthesize GFS intent when the recipe omits it', async () => {
+ const workflowReconcile = vi.fn().mockResolvedValue({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof workflowReconcile
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = { reconcile: workflowReconcile, validateWorkflowSpec: () => undefined }
+
+ const recipe = makeRecipe({
+ spec: {
+ steps: [{ id: 'no-gfs', run: snippetRun() }],
+ },
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(workflowReconcile.mock.calls[0][3].gfs).toBeUndefined()
+ })
+
it('delegates workflow transport workloads without contextRef and waits for ExternalEgressReady', async () => {
const workflowReconcile = vi.fn().mockResolvedValue({
phase: 'deploying',
@@ -5158,6 +5236,7 @@ describe('WorkflowRecipeReconciler', () => {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
@@ -5187,6 +5266,13 @@ describe('WorkflowRecipeReconciler', () => {
recipe.spec,
'parent-recipe'
)
+ expect(mockVerifyWorkflowRunProvenance).toHaveBeenCalledWith({
+ runId: 'run-child',
+ parentNamespace: 'sandbox-recipes',
+ parentName: 'parent-recipe',
+ childNamespace: 'sandbox-recipes',
+ childName: 'child-run',
+ })
// Terminal run-scoped workflow → compute pods are freed.
expect(teardownComputePodsForTerminalRun).toHaveBeenCalledWith('child-run')
})
@@ -5422,7 +5508,7 @@ describe('WorkflowRecipeReconciler', () => {
})
})
- it('repairs active workflow credentials using the controller ownerReference scope', async () => {
+ it('repairs active normal DB-run workflow credentials using verified parent provenance', async () => {
const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
@@ -5437,8 +5523,9 @@ describe('WorkflowRecipeReconciler', () => {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
- 'clerum.io/parent-recipe': 'spoofed-parent',
+ 'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
},
ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
@@ -5466,7 +5553,8 @@ describe('WorkflowRecipeReconciler', () => {
)
})
- it('does not trust forged controller ownerReferences with mismatched UIDs', async () => {
+ it('uses the child runtime identity when the DB run does not bind the exact child', async () => {
+ mockVerifyWorkflowRunProvenance.mockResolvedValue('invalid')
const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
@@ -5481,27 +5569,26 @@ describe('WorkflowRecipeReconciler', () => {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
},
- ownerReferences: [
- {
- ...workflowRecipeOwnerRef('parent-recipe'),
- uid: 'forged-parent-uid',
- },
- ],
- },
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
},
- status: {
- phase: 'active',
- } as WorkflowRecipeCRD['status'],
+ spec: { steps: [{ id: 'research', instruction: 'run' }] },
+ status: { phase: 'active' } as WorkflowRecipeCRD['status'],
})
await reconciler.reconcile(recipe)
+ expect(mockVerifyWorkflowRunProvenance).toHaveBeenCalledWith({
+ runId: 'run-child',
+ parentNamespace: 'sandbox-recipes',
+ parentName: 'parent-recipe',
+ childNamespace: 'sandbox-recipes',
+ childName: 'child-run',
+ })
expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
'sandbox-recipes',
'child-run',
@@ -5510,50 +5597,67 @@ describe('WorkflowRecipeReconciler', () => {
)
})
- it('does not trust controller ownerReferences whose target WorkflowRecipe is missing', async () => {
+ it('requeues a Pending DB binding before creating or rotating workflow runtime resources', async () => {
+ mockVerifyWorkflowRunProvenance.mockResolvedValue('pending')
+ const ensureCoordinatorRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ const refreshRuntimeHttpEgressNetworkPolicies = vi.fn().mockResolvedValue(undefined)
+ const reconcileWorkflow = vi.fn().mockResolvedValue({ phase: 'active', message: 'unexpected' })
;(
reconciler as unknown as {
workflowReconciler: {
+ ensureCoordinatorRuntimeCredentials: typeof ensureCoordinatorRuntimeCredentials
ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ refreshRuntimeHttpEgressNetworkPolicies: typeof refreshRuntimeHttpEgressNetworkPolicies
+ reconcile: typeof reconcileWorkflow
}
}
- ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
- mockCustomApi.getNamespacedCustomObject
- .mockReset()
- .mockResolvedValueOnce({ metadata: { uid: 'uid-child' } })
- .mockRejectedValueOnce({ code: 404 })
-
+ ).workflowReconciler = {
+ ensureCoordinatorRuntimeCredentials,
+ ensureMcpHostRuntimeCredentials,
+ refreshRuntimeHttpEgressNetworkPolicies,
+ reconcile: reconcileWorkflow,
+ }
const recipe = makeRecipe({
metadata: {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
- 'clerum.io/parent-recipe': 'missing-parent',
+ 'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
},
- ownerReferences: [workflowRecipeOwnerRef('missing-parent')],
- },
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
},
+ spec: { steps: [{ id: 'research', instruction: 'run' }] },
status: {
phase: 'active',
+ message: 'Workflow running',
+ workflowExecution: { phase: 'running' },
} as WorkflowRecipeCRD['status'],
})
- await reconciler.reconcile(recipe)
+ const result = await reconciler.reconcile(recipe)
- expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'child-run',
- recipe.spec,
- 'child-run'
- )
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ })
+ expect(ensureCoordinatorRuntimeCredentials).not.toHaveBeenCalled()
+ expect(ensureMcpHostRuntimeCredentials).not.toHaveBeenCalled()
+ expect(refreshRuntimeHttpEgressNetworkPolicies).not.toHaveBeenCalled()
+ expect(reconcileWorkflow).not.toHaveBeenCalled()
+ expect(mockCoreApi.createNamespacedSecret).not.toHaveBeenCalled()
+ expect(mockCoreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- it('does not trust controller ownerReferences whose live owner is deleting', async () => {
+ it('requeues a transient DB provenance failure without downgrading to child identity', async () => {
+ mockVerifyWorkflowRunProvenance.mockRejectedValue(new Error('ECONNRESET'))
const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
@@ -5562,89 +5666,92 @@ describe('WorkflowRecipeReconciler', () => {
}
}
).workflowReconciler = { ensureMcpHostRuntimeCredentials }
- mockCustomApi.getNamespacedCustomObject.mockImplementation(({ name }: { name?: string }) =>
- Promise.resolve({
- metadata: {
- uid: liveWorkflowRecipeUid(name),
- deletionTimestamp: name === 'parent-recipe' ? '2026-05-06T00:00:00Z' : undefined,
- resourceVersion: '1',
- annotations: { 'clerum.io/network-ready': 'true' },
- labels: { 'clerum.io/recipe': 'test-recipe' },
- },
- spec: { mcpServers: [] },
- })
- )
-
const recipe = makeRecipe({
metadata: {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
},
ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
},
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
- },
+ spec: { steps: [{ id: 'research', instruction: 'run' }] },
status: {
phase: 'active',
+ message: 'Workflow running',
+ workflowExecution: { phase: 'running' },
} as WorkflowRecipeCRD['status'],
})
- await reconciler.reconcile(recipe)
+ const result = await reconciler.reconcile(recipe)
- expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'child-run',
- recipe.spec,
- 'child-run'
- )
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ })
+ expect(ensureMcpHostRuntimeCredentials).not.toHaveBeenCalled()
+ expect(mockCoreApi.createNamespacedSecret).not.toHaveBeenCalled()
+ expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'child-run-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ body: {
+ preconditions: {
+ uid: 'uid-child-run-coordinator-to-gfs',
+ resourceVersion: '1',
+ },
+ },
+ })
})
- it('does not trust WorkflowRecipe ownerReferences without a UID', async () => {
- const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
- ;(
- reconciler as unknown as {
- workflowReconciler: {
- ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
- }
- }
- ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
-
- const ownerRefWithoutUid = { ...workflowRecipeOwnerRef('parent-recipe'), uid: undefined }
+ it('does not open coordinator GFS egress while a child DB binding is Pending', async () => {
+ mockVerifyWorkflowRunProvenance.mockResolvedValue('pending')
const recipe = makeRecipe({
metadata: {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
},
- ownerReferences: [ownerRefWithoutUid],
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
},
spec: {
steps: [{ id: 'research', instruction: 'run' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'outputs' }] },
},
status: {
phase: 'active',
+ message: 'Workflow running',
+ workflowExecution: { phase: 'running' },
} as WorkflowRecipeCRD['status'],
})
- await reconciler.reconcile(recipe)
+ const result = await reconciler.reconcile(recipe)
- expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'child-run',
- recipe.spec,
- 'child-run'
- )
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ })
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- it('does not trust parent-recipe labels without a controller ownerReference', async () => {
+ it('requeues a transient owner lookup failure without downgrading to child identity', async () => {
+ mockCustomApi.getNamespacedCustomObject
+ .mockReset()
+ .mockResolvedValueOnce({ metadata: { uid: 'uid-child' } })
+ .mockRejectedValueOnce({ code: 503 })
const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
@@ -5653,336 +5760,1255 @@ describe('WorkflowRecipeReconciler', () => {
}
}
).workflowReconciler = { ensureMcpHostRuntimeCredentials }
-
const recipe = makeRecipe({
metadata: {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
labels: {
- 'clerum.io/parent-recipe': 'victim-recipe',
+ 'clerum.io/parent-recipe': 'parent-recipe',
'clerum.io/workflow-run-id': 'run-child',
},
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
},
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
- },
+ spec: { steps: [{ id: 'research', instruction: 'run' }] },
status: {
phase: 'active',
+ message: 'Workflow running',
+ workflowExecution: { phase: 'running' },
} as WorkflowRecipeCRD['status'],
})
- await reconciler.reconcile(recipe)
-
- expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'child-run',
- recipe.spec,
- 'child-run'
- )
- })
+ const result = await reconciler.reconcile(recipe)
- it('passes the ownerReference parent scope on first workflow infrastructure reconcile', async () => {
- const reconcileWorkflow = vi.fn().mockResolvedValue({
- phase: 'deploying',
- message: 'Workflow infrastructure created',
- workflowPhase: 'initializing',
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
})
- ;(
- reconciler as unknown as {
- workflowReconciler: {
- reconcile: typeof reconcileWorkflow
- validateWorkflowSpec: () => undefined
- }
- }
- ).workflowReconciler = { reconcile: reconcileWorkflow, validateWorkflowSpec: () => undefined }
+ expect(mockVerifyWorkflowRunProvenance).not.toHaveBeenCalled()
+ expect(ensureMcpHostRuntimeCredentials).not.toHaveBeenCalled()
+ expect(mockCoreApi.createNamespacedSecret).not.toHaveBeenCalled()
+ expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ })
+ it('uses the child runtime identity when the workflow run id is missing', async () => {
const recipe = makeRecipe({
metadata: {
name: 'child-run',
namespace: 'sandbox-recipes',
uid: 'uid-child',
- labels: { 'clerum.io/parent-recipe': 'spoofed-parent' },
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: { 'clerum.io/parent-recipe': 'parent-recipe' },
ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
},
+ spec: { steps: [{ id: 'research', instruction: 'run' }] },
+ status: { phase: 'active' } as WorkflowRecipeCRD['status'],
+ })
+
+ const runtimeScope = await (
+ reconciler as unknown as {
+ workflowRuntimeScopeRecipeName: (input: WorkflowRecipeCRD) => Promise<string>
+ }
+ ).workflowRuntimeScopeRecipeName(recipe)
+
+ expect(mockVerifyWorkflowRunProvenance).not.toHaveBeenCalled()
+ expect(runtimeScope).toBe('child-run')
+ })
+
+ it('keeps the verified parent identity when the live parent GFS changes after run creation', async () => {
+ mockCustomApi.getNamespacedCustomObject.mockResolvedValue({
+ metadata: { uid: 'uid-parent-recipe', resourceVersion: '1' },
spec: {
- steps: [{ id: 'research', instruction: 'run' }],
+ gfs: {
+ mounts: [
+ {
+ drive: 'main',
+ target: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
+ scopes: ['gfs.write'],
+ },
+ ],
+ },
},
- status: {
- phase: 'candidate',
- } as WorkflowRecipeCRD['status'],
})
- const result = await reconciler.reconcile(recipe)
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ gfs: {
+ mounts: [
+ {
+ drive: 'main',
+ target: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
+ scopes: ['gfs.read'],
+ },
+ ],
+ },
+ },
+ status: { phase: 'active' } as WorkflowRecipeCRD['status'],
+ })
- expect(result).toMatchObject({
- phase: 'deploying',
- message: 'Workflow infrastructure created',
- workflowPhase: 'initializing',
+ const runtimeScope = await (
+ reconciler as unknown as {
+ workflowRuntimeScopeRecipeName: (input: WorkflowRecipeCRD) => Promise<string>
+ }
+ ).workflowRuntimeScopeRecipeName(recipe)
+
+ expect(mockVerifyWorkflowRunProvenance).toHaveBeenCalledWith({
+ runId: 'run-child',
+ parentNamespace: 'sandbox-recipes',
+ parentName: 'parent-recipe',
+ childNamespace: 'sandbox-recipes',
+ childName: 'child-run',
})
- expect(reconcileWorkflow).toHaveBeenCalledWith(
- 'child-run',
- 'uid-child',
+ expect(runtimeScope).toBe('parent-recipe')
+ expect(recipe.spec.gfs?.mounts?.[0]?.scopes).toEqual(['gfs.read'])
+ })
+
+ it('does not trust forged controller ownerReferences with mismatched UIDs', async () => {
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
+ }
+ ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [
+ {
+ ...workflowRecipeOwnerRef('parent-recipe'),
+ uid: 'forged-parent-uid',
+ },
+ ],
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
'sandbox-recipes',
- expect.objectContaining({ steps: recipe.spec.steps }),
- expect.objectContaining({ workflowExecution: undefined }),
- {},
- 'parent-recipe',
- undefined,
- undefined,
- undefined,
- undefined
+ 'child-run',
+ recipe.spec,
+ 'child-run'
)
})
- it('enforces configured workflow limits before resolving step MCP servers', async () => {
- const reconcileWorkflow = vi.fn().mockResolvedValue({
- phase: 'deploying',
- message: 'Workflow infrastructure created',
- workflowPhase: 'initializing',
- })
+ it('does not trust controller ownerReferences whose target WorkflowRecipe is missing', async () => {
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
workflowReconciler: {
- reconcile: typeof reconcileWorkflow
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
}
- config: { workflowStepMcpServersMaxItems: number }
}
- ).workflowReconciler = { reconcile: reconcileWorkflow }
+ ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
+ mockCustomApi.getNamespacedCustomObject
+ .mockReset()
+ .mockResolvedValueOnce({ metadata: { uid: 'uid-child' } })
+ .mockRejectedValueOnce({ code: 404 })
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'missing-parent',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [workflowRecipeOwnerRef('missing-parent')],
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledWith({
+ group: 'clerum.io',
+ version: 'v1alpha1',
+ namespace: 'sandbox-recipes',
+ plural: 'workflowrecipes',
+ name: 'missing-parent',
+ })
+ expect(mockVerifyWorkflowRunProvenance).not.toHaveBeenCalled()
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'child-run',
+ recipe.spec,
+ 'child-run'
+ )
+ })
+
+ it('does not trust controller ownerReferences whose live owner is deleting', async () => {
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
- config: { workflowStepMcpServersMaxItems: number }
+ workflowReconciler: {
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
}
- ).config.workflowStepMcpServersMaxItems = 2
-
- const result = await reconciler.reconcile(
- makeRecipe({
- spec: {
- agent: { provider: 'zai', model: 'glm-4.7' },
- steps: [
- {
- id: 'research',
- instruction: 'run',
- mcpServers: ['srv0', 'srv1', 'srv2'],
- },
- ],
+ ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
+ mockCustomApi.getNamespacedCustomObject.mockImplementation(({ name }: { name?: string }) =>
+ Promise.resolve({
+ metadata: {
+ uid: liveWorkflowRecipeUid(name),
+ deletionTimestamp: name === 'parent-recipe' ? '2026-05-06T00:00:00Z' : undefined,
+ resourceVersion: '1',
+ annotations: { 'clerum.io/network-ready': 'true' },
+ labels: { 'clerum.io/recipe': 'test-recipe' },
},
- status: { phase: 'candidate' } as WorkflowRecipeCRD['status'],
+ spec: { mcpServers: [] },
})
)
- expect(result).toMatchObject({
- phase: 'failed',
- message: 'spec.steps[0].mcpServers must contain at most 2 items',
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
})
- expect(reconcileWorkflow).not.toHaveBeenCalled()
+
+ await reconciler.reconcile(recipe)
+
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledWith({
+ group: 'clerum.io',
+ version: 'v1alpha1',
+ namespace: 'sandbox-recipes',
+ plural: 'workflowrecipes',
+ name: 'parent-recipe',
+ })
+ expect(mockVerifyWorkflowRunProvenance).not.toHaveBeenCalled()
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'child-run',
+ recipe.spec,
+ 'child-run'
+ )
})
- it('passes workflow admin usage actor labels into the runtime reconciler', async () => {
- const reconcileWorkflow = vi.fn().mockResolvedValue({
- phase: 'deploying',
- message: 'Workflow infrastructure created',
- workflowPhase: 'initializing',
+ it('does not trust WorkflowRecipe ownerReferences without a UID', async () => {
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
+ }
+ ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
+
+ const ownerRefWithoutUid = { ...workflowRecipeOwnerRef('parent-recipe'), uid: undefined }
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ ownerReferences: [ownerRefWithoutUid],
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
})
+
+ await reconciler.reconcile(recipe)
+
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'child-run',
+ recipe.spec,
+ 'child-run'
+ )
+ })
+
+ it('does not trust parent-recipe labels without a controller ownerReference', async () => {
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
;(
reconciler as unknown as {
workflowReconciler: {
- reconcile: typeof reconcileWorkflow
- validateWorkflowSpec: () => undefined
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
}
}
- ).workflowReconciler = { reconcile: reconcileWorkflow, validateWorkflowSpec: () => undefined }
+ ).workflowReconciler = { ensureMcpHostRuntimeCredentials }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ labels: {
+ 'clerum.io/parent-recipe': 'victim-recipe',
+ 'clerum.io/workflow-run-id': 'run-child',
+ },
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'child-run',
+ recipe.spec,
+ 'child-run'
+ )
+ })
+
+ it('does not inherit a parent scope on first reconcile without DB-run metadata', async () => {
+ const reconcileWorkflow = vi.fn().mockResolvedValue({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof reconcileWorkflow
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = { reconcile: reconcileWorkflow, validateWorkflowSpec: () => undefined }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ labels: { 'clerum.io/parent-recipe': 'spoofed-parent' },
+ ownerReferences: [workflowRecipeOwnerRef('parent-recipe')],
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'candidate',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ const result = await reconciler.reconcile(recipe)
+
+ expect(result).toMatchObject({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ expect(reconcileWorkflow).toHaveBeenCalledWith(
+ 'child-run',
+ 'uid-child',
+ 'sandbox-recipes',
+ expect.objectContaining({ steps: recipe.spec.steps }),
+ expect.objectContaining({ workflowExecution: undefined }),
+ {},
+ 'child-run',
+ undefined,
+ undefined,
+ undefined,
+ undefined
+ )
+ })
+
+ it('enforces configured workflow limits before resolving step MCP servers', async () => {
+ const reconcileWorkflow = vi.fn().mockResolvedValue({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof reconcileWorkflow
+ }
+ config: { workflowStepMcpServersMaxItems: number }
+ }
+ ).workflowReconciler = { reconcile: reconcileWorkflow }
+ ;(
+ reconciler as unknown as {
+ config: { workflowStepMcpServersMaxItems: number }
+ }
+ ).config.workflowStepMcpServersMaxItems = 2
+
+ const result = await reconciler.reconcile(
+ makeRecipe({
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ steps: [
+ {
+ id: 'research',
+ instruction: 'run',
+ mcpServers: ['srv0', 'srv1', 'srv2'],
+ },
+ ],
+ },
+ status: { phase: 'candidate' } as WorkflowRecipeCRD['status'],
+ })
+ )
+
+ expect(result).toMatchObject({
+ phase: 'failed',
+ message: 'spec.steps[0].mcpServers must contain at most 2 items',
+ })
+ expect(reconcileWorkflow).not.toHaveBeenCalled()
+ })
+
+ it('passes workflow admin usage actor labels into the runtime reconciler', async () => {
+ const reconcileWorkflow = vi.fn().mockResolvedValue({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof reconcileWorkflow
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = { reconcile: reconcileWorkflow, validateWorkflowSpec: () => undefined }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'child-run',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ labels: {
+ 'clerum.io/workflow-run-id': '00000000-0000-4000-8000-000000000123',
+ 'clerum.io/workflow-team-id': 'control-plane-admin-ui',
+ 'clerum.io/workflow-actor-id': '11111111-1111-4111-8111-111111111111',
+ 'clerum.io/workflow-actor-type': 'admin',
+ },
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'candidate',
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ await reconciler.reconcile(recipe)
+
+ expect(reconcileWorkflow).toHaveBeenCalledWith(
+ 'child-run',
+ 'uid-child',
+ 'sandbox-recipes',
+ expect.objectContaining({ steps: recipe.spec.steps }),
+ expect.objectContaining({ workflowExecution: undefined }),
+ {},
+ 'child-run',
+ '00000000-0000-4000-8000-000000000123',
+ 'control-plane-admin-ui',
+ '11111111-1111-4111-8111-111111111111',
+ 'admin'
+ )
+ })
+
+ it('repairs failed parent workflows without a run id as active trigger infrastructure', async () => {
+ const reconcileWorkflow = vi.fn().mockResolvedValue({
+ phase: 'active',
+ message: 'Workflow trigger infrastructure registered (workflow-agentic)',
+ clearWorkflowExecution: true,
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof reconcileWorkflow
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = { reconcile: reconcileWorkflow, validateWorkflowSpec: () => undefined }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'e2e-parent',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-parent',
+ labels: {},
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'failed',
+ workflowExecution: { phase: 'failed' },
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ const result = await reconciler.reconcile(recipe)
+
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow trigger infrastructure registered (workflow-agentic)',
+ clearWorkflowExecution: true,
+ })
+ expect(reconcileWorkflow).toHaveBeenCalledWith(
+ 'e2e-parent',
+ 'uid-parent',
+ 'sandbox-recipes',
+ expect.objectContaining({ steps: recipe.spec.steps }),
+ expect.objectContaining({ workflowExecution: { phase: 'failed' } }),
+ {},
+ 'e2e-parent',
+ undefined,
+ undefined,
+ undefined,
+ undefined
+ )
+ })
+
+ it('marks running workflow infrastructure active before skipping reconcile', async () => {
+ const ensureCoordinatorRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ ensureCoordinatorRuntimeCredentials: typeof ensureCoordinatorRuntimeCredentials
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = {
+ ensureCoordinatorRuntimeCredentials,
+ ensureMcpHostRuntimeCredentials,
+ validateWorkflowSpec: () => undefined,
+ }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'test-recipe',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-123',
+ labels: { 'clerum.io/workflow-run-id': 'run-test' },
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'deploying',
+ workflowExecution: { phase: 'running' },
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ const result = await reconciler.reconcile(recipe)
+
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: false,
+ })
+ expect(ensureCoordinatorRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'test-recipe',
+ recipe.spec,
+ 'test-recipe'
+ )
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'test-recipe',
+ recipe.spec,
+ 'test-recipe'
+ )
+ })
+
+ it('keeps active running workflows active without another status patch', async () => {
+ const ensureCoordinatorRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ ensureCoordinatorRuntimeCredentials: typeof ensureCoordinatorRuntimeCredentials
+ ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ }
+ }
+ ).workflowReconciler = { ensureCoordinatorRuntimeCredentials, ensureMcpHostRuntimeCredentials }
+
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'test-recipe',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-123',
+ labels: { 'clerum.io/workflow-run-id': 'run-test' },
+ },
+ spec: {
+ steps: [{ id: 'research', instruction: 'run' }],
+ },
+ status: {
+ phase: 'active',
+ workflowExecution: { phase: 'running' },
+ } as WorkflowRecipeCRD['status'],
+ })
+
+ const result = await reconciler.reconcile(recipe)
+
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ })
+ expect(ensureCoordinatorRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'test-recipe',
+ recipe.spec,
+ 'test-recipe'
+ )
+ expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
+ 'sandbox-recipes',
+ 'test-recipe',
+ recipe.spec,
+ 'test-recipe'
+ )
+ })
+
+ describe('steady workflow coordinator GFS NetworkPolicy convergence', () => {
+ function stubSteadyWorkflowRuntime(): void {
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ ensureCoordinatorRuntimeCredentials: () => Promise<void>
+ ensureMcpHostRuntimeCredentials: () => Promise<void>
+ }
+ }
+ ).workflowReconciler = {
+ ensureCoordinatorRuntimeCredentials: vi.fn().mockResolvedValue(undefined),
+ ensureMcpHostRuntimeCredentials: vi.fn().mockResolvedValue(undefined),
+ }
+ }
+
+ function activeWorkflow(
+ publishTargets?: Array<{ drive: string; target: string }>
+ ): WorkflowRecipeCRD {
+ return makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ labels: { 'clerum.io/workflow-run-id': 'run-gfs-policy' },
+ },
+ spec: {
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: publishTargets ? { publishTargets } : undefined,
+ },
+ status: {
+ phase: 'active',
+ workflowExecution: { phase: 'running' },
+ } as WorkflowRecipeCRD['status'],
+ })
+ }
+
+ it('creates the exact coordinator GFS policy when publishTargets become present', async () => {
+ stubSteadyWorkflowRuntime()
+ const recipe = activeWorkflow([{ drive: 'main', target: 'published-results' }])
+
+ const result = await reconciler.reconcile(recipe)
+
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ })
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ namespace: 'sandbox-recipes',
+ body: expect.objectContaining({
+ metadata: expect.objectContaining({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ }),
+ spec: expect.objectContaining({
+ podSelector: {
+ matchLabels: {
+ 'clerum.io/recipe': 'gfs-policy-workflow',
+ 'clerum.io/component': 'workflow-coordinator',
+ },
+ },
+ egress: [
+ {
+ to: [
+ {
+ namespaceSelector: {
+ matchLabels: { 'kubernetes.io/metadata.name': 'gfs' },
+ },
+ podSelector: { matchLabels: { app: 'gfs-controller' } },
+ },
+ ],
+ ports: [{ port: 8087, protocol: 'TCP' }],
+ },
+ ],
+ }),
+ }),
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('deletes only the exact coordinator GFS policy when publishTargets become absent', async () => {
+ stubSteadyWorkflowRuntime()
+
+ const result = await reconciler.reconcile(activeWorkflow())
+
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ body: {
+ preconditions: {
+ uid: 'uid-gfs-policy-workflow-coordinator-to-gfs',
+ resourceVersion: '1',
+ },
+ },
+ })
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('tolerates an already-absent coordinator GFS policy', async () => {
+ stubSteadyWorkflowRuntime()
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 404 })
+
+ const result = await reconciler.reconcile(activeWorkflow())
+
+ expect(result).toMatchObject({
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: true,
+ })
+ expect(mockNetworkingApi.readNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('tolerates a concurrent 404 after reading the owned policy', async () => {
+ stubSteadyWorkflowRuntime()
+ mockNetworkingApi.deleteNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 404 })
+
+ const result = await reconciler.reconcile(activeWorkflow())
+
+ expect(result).toMatchObject({ phase: 'active', message: 'Workflow running' })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ })
+
+ it('surfaces non-404 reads without attempting a delete', async () => {
+ stubSteadyWorkflowRuntime()
+ const apiError = { code: 503, message: 'apiserver unavailable' }
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockRejectedValueOnce(apiError)
+
+ await expect(reconciler.reconcile(activeWorkflow())).rejects.toBe(apiError)
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('refuses to delete an owned policy without complete live identity', async () => {
+ stubSteadyWorkflowRuntime()
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ resourceVersion: '7',
+ labels: { 'clerum.io/managed-by': 'wrc', 'clerum.io/recipe': 'gfs-policy-workflow' },
+ },
+ })
+
+ await expect(reconciler.reconcile(activeWorkflow())).rejects.toThrow(
+ 'live object identity is incomplete'
+ )
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('surfaces non-404 revocation failures instead of reporting false convergence', async () => {
+ stubSteadyWorkflowRuntime()
+ const apiError = { code: 503, message: 'apiserver unavailable' }
+ mockNetworkingApi.deleteNamespacedNetworkPolicy.mockRejectedValueOnce(apiError)
+
+ await expect(reconciler.reconcile(activeWorkflow())).rejects.toBe(apiError)
+ })
+
+ it.each([
+ {
+ branch: 'awaiting-trigger',
+ recipe: () =>
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ },
+ status: { phase: 'active' },
+ }),
+ expected: {
+ phase: 'active',
+ message: 'Workflow trigger infrastructure registered',
+ skipStatusPatch: true,
+ },
+ },
+ {
+ branch: 'terminal',
+ recipe: () =>
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ labels: { 'clerum.io/workflow-run-id': 'run-gfs-policy' },
+ },
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ },
+ status: {
+ phase: 'active',
+ message: 'Workflow completed',
+ workflowExecution: { phase: 'completed' },
+ } as WorkflowRecipeCRD['status'],
+ }),
+ expected: {
+ phase: 'active',
+ message: 'Workflow completed',
+ skipStatusPatch: true,
+ },
+ },
+ {
+ branch: 'in-progress',
+ recipe: () =>
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ },
+ status: {
+ phase: 'deploying',
+ workflowExecution: { phase: 'running' },
+ } as WorkflowRecipeCRD['status'],
+ }),
+ expected: {
+ phase: 'active',
+ message: 'Workflow running',
+ skipStatusPatch: false,
+ },
+ },
+ ])('converges the absent policy without changing the $branch result', async testCase => {
+ stubSteadyWorkflowRuntime()
+ const workflowRuntime = (
+ reconciler as unknown as {
+ workflowReconciler: Record<string, unknown>
+ }
+ ).workflowReconciler
+ workflowRuntime.teardownComputePodsForTerminalRun = vi.fn().mockResolvedValue(undefined)
+
+ const result = await reconciler.reconcile(testCase.recipe())
+
+ expect(result).toMatchObject(testCase.expected)
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ body: {
+ preconditions: {
+ uid: 'uid-gfs-policy-workflow-coordinator-to-gfs',
+ resourceVersion: '1',
+ },
+ },
+ })
+ })
+
+ it.each([
+ {
+ branch: 'awaiting-trigger',
+ recipe: () =>
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ },
+ status: { phase: 'active' },
+ }),
+ },
+ {
+ branch: 'terminal',
+ recipe: () =>
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ labels: { 'clerum.io/workflow-run-id': 'run-gfs-policy' },
+ },
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ },
+ status: {
+ phase: 'active',
+ message: 'Workflow completed',
+ workflowExecution: { phase: 'completed' },
+ } as WorkflowRecipeCRD['status'],
+ }),
+ },
+ {
+ branch: 'in-progress',
+ recipe: () =>
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ agent: { provider: 'zai', model: 'glm-4.7' },
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ },
+ status: {
+ phase: 'deploying',
+ workflowExecution: { phase: 'running' },
+ } as WorkflowRecipeCRD['status'],
+ }),
+ },
+ ])('converges the present policy before returning from $branch', async testCase => {
+ stubSteadyWorkflowRuntime()
+ const workflowRuntime = (
+ reconciler as unknown as { workflowReconciler: Record<string, unknown> }
+ ).workflowReconciler
+ workflowRuntime.teardownComputePodsForTerminalRun = vi.fn().mockResolvedValue(undefined)
+
+ await reconciler.reconcile(testCase.recipe())
+
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ namespace: 'sandbox-recipes',
+ body: expect.objectContaining({
+ metadata: expect.objectContaining({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ }),
+ }),
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
- const recipe = makeRecipe({
- metadata: {
- name: 'child-run',
+ it('does not open coordinator GFS egress for a workflow rejected by preflight', async () => {
+ stubSteadyWorkflowRuntime()
+ const workflowRuntime = (
+ reconciler as unknown as { workflowReconciler: Record<string, unknown> }
+ ).workflowReconciler
+ workflowRuntime.validateWorkflowSpec = vi.fn().mockReturnValue('invalid runtime spec')
+
+ const result = await reconciler.reconcile(
+ activeWorkflow([{ drive: 'main', target: 'published-results' }])
+ )
+
+ expect(result).toMatchObject({ phase: 'active', message: 'Workflow running' })
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
namespace: 'sandbox-recipes',
- uid: 'uid-child',
- labels: {
- 'clerum.io/workflow-run-id': '00000000-0000-4000-8000-000000000123',
- 'clerum.io/workflow-team-id': 'control-plane-admin-ui',
- 'clerum.io/workflow-actor-id': '11111111-1111-4111-8111-111111111111',
- 'clerum.io/workflow-actor-type': 'admin',
+ body: {
+ preconditions: {
+ uid: 'uid-gfs-policy-workflow-coordinator-to-gfs',
+ resourceVersion: '1',
+ },
},
- },
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
- },
- status: {
- phase: 'candidate',
- } as WorkflowRecipeCRD['status'],
+ })
})
- await reconciler.reconcile(recipe)
+ it('refuses to replace a homonymous policy not owned by the exact recipe', async () => {
+ stubSteadyWorkflowRuntime()
+ mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 409 })
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ uid: 'uid-foreign-policy',
+ resourceVersion: '7',
+ labels: { 'clerum.io/managed-by': 'operator', 'clerum.io/recipe': 'other-recipe' },
+ },
+ })
- expect(reconcileWorkflow).toHaveBeenCalledWith(
- 'child-run',
- 'uid-child',
- 'sandbox-recipes',
- expect.objectContaining({ steps: recipe.spec.steps }),
- expect.objectContaining({ workflowExecution: undefined }),
- {},
- 'child-run',
- '00000000-0000-4000-8000-000000000123',
- 'control-plane-admin-ui',
- '11111111-1111-4111-8111-111111111111',
- 'admin'
- )
- })
+ await expect(
+ reconciler.reconcile(activeWorkflow([{ drive: 'main', target: 'published-results' }]))
+ ).rejects.toThrow('existing policy is not owned by WRC')
+ expect(mockNetworkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
- it('repairs failed parent workflows without a run id as active trigger infrastructure', async () => {
- const reconcileWorkflow = vi.fn().mockResolvedValue({
- phase: 'active',
- message: 'Workflow trigger infrastructure registered (workflow-agentic)',
- clearWorkflowExecution: true,
+ it('replaces the exact owned coordinator GFS policy with its live resourceVersion', async () => {
+ stubSteadyWorkflowRuntime()
+ mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 409 })
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ uid: 'uid-owned-policy',
+ resourceVersion: '7',
+ labels: { 'clerum.io/managed-by': 'wrc', 'clerum.io/recipe': 'gfs-policy-workflow' },
+ },
+ })
+
+ await reconciler.reconcile(activeWorkflow([{ drive: 'main', target: 'published-results' }]))
+
+ expect(mockNetworkingApi.replaceNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ body: expect.objectContaining({
+ metadata: expect.objectContaining({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ resourceVersion: '7',
+ }),
+ }),
+ })
})
- ;(
- reconciler as unknown as {
- workflowReconciler: {
- reconcile: typeof reconcileWorkflow
- validateWorkflowSpec: () => undefined
- }
+
+ it('does not replace an already-converged owned policy', async () => {
+ stubSteadyWorkflowRuntime()
+ const existing = buildCoordinatorGfsNetworkPolicy({
+ recipeName: 'gfs-policy-workflow',
+ sandboxNamespace: 'sandbox-recipes',
+ })
+ existing.metadata = {
+ ...existing.metadata,
+ uid: 'uid-owned-policy',
+ resourceVersion: '7',
}
- ).workflowReconciler = { reconcile: reconcileWorkflow, validateWorkflowSpec: () => undefined }
+ mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 409 })
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce(existing)
- const recipe = makeRecipe({
- metadata: {
- name: 'e2e-parent',
- namespace: 'sandbox-recipes',
- uid: 'uid-parent',
- labels: {},
- },
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
- },
- status: {
- phase: 'failed',
- workflowExecution: { phase: 'failed' },
- } as WorkflowRecipeCRD['status'],
+ const result = await reconciler.reconcile(
+ activeWorkflow([{ drive: 'main', target: 'published-results' }])
+ )
+
+ expect(result).toMatchObject({ phase: 'active', message: 'Workflow running' })
+ expect(mockNetworkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- const result = await reconciler.reconcile(recipe)
+ it('refuses to delete a homonymous policy not owned by the exact recipe', async () => {
+ stubSteadyWorkflowRuntime()
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ uid: 'uid-foreign-policy',
+ resourceVersion: '7',
+ labels: { 'clerum.io/managed-by': 'operator', 'clerum.io/recipe': 'other-recipe' },
+ },
+ })
- expect(result).toMatchObject({
- phase: 'active',
- message: 'Workflow trigger infrastructure registered (workflow-agentic)',
- clearWorkflowExecution: true,
+ await expect(reconciler.reconcile(activeWorkflow())).rejects.toThrow(
+ 'existing policy is not owned by WRC'
+ )
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- expect(reconcileWorkflow).toHaveBeenCalledWith(
- 'e2e-parent',
- 'uid-parent',
- 'sandbox-recipes',
- expect.objectContaining({ steps: recipe.spec.steps }),
- expect.objectContaining({ workflowExecution: { phase: 'failed' } }),
- {},
- 'e2e-parent',
- undefined,
- undefined,
- undefined,
- undefined
- )
- })
- it('marks running workflow infrastructure active before skipping reconcile', async () => {
- const ensureCoordinatorRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
- const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
- ;(
- reconciler as unknown as {
- workflowReconciler: {
- ensureCoordinatorRuntimeCredentials: typeof ensureCoordinatorRuntimeCredentials
- ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
- validateWorkflowSpec: () => undefined
- }
- }
- ).workflowReconciler = {
- ensureCoordinatorRuntimeCredentials,
- ensureMcpHostRuntimeCredentials,
- validateWorkflowSpec: () => undefined,
- }
+ it('revokes stale coordinator GFS egress before returning a spec limit failure', async () => {
+ const recipe = makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ steps: [
+ { id: 'duplicate', instruction: 'first' },
+ { id: 'duplicate', instruction: 'second' },
+ ],
+ },
+ status: { phase: 'active' },
+ })
- const recipe = makeRecipe({
- metadata: {
- name: 'test-recipe',
+ const result = await reconciler.reconcile(recipe)
+
+ expect(result).toMatchObject({ phase: 'failed' })
+ expect(result.message).toContain('duplicate step id "duplicate" is not allowed')
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
namespace: 'sandbox-recipes',
- uid: 'uid-123',
- labels: { 'clerum.io/workflow-run-id': 'run-test' },
- },
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
- },
- status: {
- phase: 'deploying',
- workflowExecution: { phase: 'running' },
- } as WorkflowRecipeCRD['status'],
+ body: {
+ preconditions: {
+ uid: 'uid-gfs-policy-workflow-coordinator-to-gfs',
+ resourceVersion: '1',
+ },
+ },
+ })
})
- const result = await reconciler.reconcile(recipe)
+ it('opens coordinator GFS egress once only after a successful first deploy', async () => {
+ const workflowReconcile = vi.fn().mockResolvedValue({
+ phase: 'deploying',
+ message: 'Workflow infrastructure created',
+ workflowPhase: 'initializing',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof workflowReconcile
+ validateWorkflowSpec: () => undefined
+ }
+ }
+ ).workflowReconciler = { reconcile: workflowReconcile, validateWorkflowSpec: () => undefined }
- expect(result).toMatchObject({
- phase: 'active',
- message: 'Workflow running',
- skipStatusPatch: false,
+ const result = await reconciler.reconcile(
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ },
+ status: { phase: 'candidate' },
+ })
+ )
+
+ expect(result).toMatchObject({ phase: 'deploying' })
+ expect(workflowReconcile).toHaveBeenCalledTimes(1)
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(workflowReconcile.mock.invocationCallOrder[0]).toBeLessThan(
+ mockNetworkingApi.createNamespacedNetworkPolicy.mock.invocationCallOrder[0]
+ )
})
- expect(ensureCoordinatorRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'test-recipe',
- recipe.spec,
- 'test-recipe'
- )
- expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'test-recipe',
- recipe.spec,
- 'test-recipe'
- )
- })
- it('keeps active running workflows active without another status patch', async () => {
- const ensureCoordinatorRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
- const ensureMcpHostRuntimeCredentials = vi.fn().mockResolvedValue(undefined)
- ;(
- reconciler as unknown as {
- workflowReconciler: {
- ensureCoordinatorRuntimeCredentials: typeof ensureCoordinatorRuntimeCredentials
- ensureMcpHostRuntimeCredentials: typeof ensureMcpHostRuntimeCredentials
+ it('does not open coordinator GFS egress when first deploy fails asynchronously', async () => {
+ const workflowReconcile = vi.fn().mockResolvedValue({
+ phase: 'failed',
+ message: 'snippet Secret reference is invalid',
+ workflowPhase: 'failed',
+ })
+ ;(
+ reconciler as unknown as {
+ workflowReconciler: {
+ reconcile: typeof workflowReconcile
+ validateWorkflowSpec: () => undefined
+ }
}
- }
- ).workflowReconciler = { ensureCoordinatorRuntimeCredentials, ensureMcpHostRuntimeCredentials }
+ ).workflowReconciler = { reconcile: workflowReconcile, validateWorkflowSpec: () => undefined }
- const recipe = makeRecipe({
- metadata: {
- name: 'test-recipe',
- namespace: 'sandbox-recipes',
- uid: 'uid-123',
- labels: { 'clerum.io/workflow-run-id': 'run-test' },
- },
- spec: {
- steps: [{ id: 'research', instruction: 'run' }],
- },
- status: {
- phase: 'active',
- workflowExecution: { phase: 'running' },
- } as WorkflowRecipeCRD['status'],
+ const result = await reconciler.reconcile(
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ },
+ spec: {
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ },
+ status: { phase: 'candidate' },
+ })
+ )
+
+ expect(result).toMatchObject({ phase: 'failed' })
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
})
- const result = await reconciler.reconcile(recipe)
+ it.each(['failed', 'cancelled'] as const)(
+ 'revokes coordinator GFS egress for a terminal %s workflow',
+ async workflowPhase => {
+ stubSteadyWorkflowRuntime()
+ const workflowRuntime = (
+ reconciler as unknown as { workflowReconciler: Record<string, unknown> }
+ ).workflowReconciler
+ workflowRuntime.teardownComputePodsForTerminalRun = vi.fn().mockResolvedValue(undefined)
- expect(result).toMatchObject({
- phase: 'active',
- message: 'Workflow running',
- skipStatusPatch: true,
- })
- expect(ensureCoordinatorRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'test-recipe',
- recipe.spec,
- 'test-recipe'
- )
- expect(ensureMcpHostRuntimeCredentials).toHaveBeenCalledWith(
- 'sandbox-recipes',
- 'test-recipe',
- recipe.spec,
- 'test-recipe'
+ const result = await reconciler.reconcile(
+ makeRecipe({
+ metadata: {
+ name: 'gfs-policy-workflow',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-gfs-policy',
+ labels: { 'clerum.io/workflow-run-id': 'run-gfs-policy' },
+ },
+ spec: {
+ steps: [{ id: 'publish', instruction: 'publish output' }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
+ },
+ status: {
+ phase: 'active',
+ workflowExecution: { phase: workflowPhase },
+ } as WorkflowRecipeCRD['status'],
+ })
+ )
+
+ expect(result).toMatchObject({ phase: 'failed', message: `Workflow ${workflowPhase}` })
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ }
)
})
@@ -6272,6 +7298,7 @@ describe('WorkflowRecipeReconciler', () => {
workloads: [{ id: 'api', type: 'deployment', image: 'api:latest', port: 8080 }],
resources: [{ id: 'data', type: 'pvc', size: '10Gi' }],
steps: [{ id: 'run', run: snippetRun() }],
+ gfs: { publishTargets: [{ drive: 'main', target: 'published-results' }] },
},
status: { phase: 'candidate' },
})
@@ -6290,6 +7317,7 @@ describe('WorkflowRecipeReconciler', () => {
expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
expect(mockCoreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
expect(mockCoreApi.createNamespacedService).not.toHaveBeenCalled()
+ expect(mockNetworkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
it('dryRun still validates that at least one workload or step is configured', async () => {
@@ -7828,7 +8856,7 @@ describe('WorkflowRecipeReconciler', () => {
function etimedout(): Error {
return Object.assign(
new Error(
- 'request to https://203.0.113.1/api/v1/namespaces/sandbox-recipes/services/app failed, reason: connect ETIMEDOUT 203.0.113.1:443'
+ 'request to https://203.0.113.10/api/v1/namespaces/sandbox-recipes/services/app failed, reason: connect ETIMEDOUT 203.0.113.10:443'
),
{ code: 'ETIMEDOUT', name: 'FetchError' }
)
@@ -7888,7 +8916,7 @@ describe('WorkflowRecipeReconciler', () => {
status: {
phase: 'failed',
message:
- 'FetchError: request to https://203.0.113.1/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies failed, reason: connect ETIMEDOUT 203.0.113.1:443',
+ 'FetchError: request to https://203.0.113.10/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies failed, reason: connect ETIMEDOUT 203.0.113.10:443',
workloads: [{ id: 'app', type: 'deployment', phase: 'deployed', ready: true }],
},
})
@@ -8080,11 +9108,11 @@ describe('WorkflowRecipeReconciler', () => {
it('self-heals recipes latched by the real dev API-timeout messages', async () => {
const devMessages = [
// helpdesk — pre-deploy Context allowlist fetch
- 'Error: Pre-deploy failed for WorkflowRecipe "recipe-helpdesk-v1-0-0-4549198b". WRC cannot start transport workloads until HCC can reconcile child McpServers: Error: Pre-deploy Context allowlist failed for "recipe-helpdesk-v1-0-0-4549198b": request to https://203.0.113.1/apis/clerum.io/v1alpha1/namespaces/mcp-server/contexts/context1 failed, reason: connect ETIMEDOUT 203.0.113.1:443',
+ 'Error: Pre-deploy failed for WorkflowRecipe "recipe-helpdesk-v1-0-0-4549198b". WRC cannot start transport workloads until HCC can reconcile child McpServers: Error: Pre-deploy Context allowlist failed for "recipe-helpdesk-v1-0-0-4549198b": request to https://203.0.113.10/apis/clerum.io/v1alpha1/namespaces/mcp-server/contexts/context1 failed, reason: connect ETIMEDOUT 203.0.113.10:443',
// leadforge — NetworkPolicy fetch
- 'FetchError: request to https://203.0.113.1/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies/wl-egress-recipe-leadforge-app-v1-0-0-bdb457b6-prospector-api failed, reason: connect ETIMEDOUT 203.0.113.1:443',
+ 'FetchError: request to https://203.0.113.10/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies/wl-egress-recipe-leadforge-app-v1-0-0-bdb457b6-prospector-api failed, reason: connect ETIMEDOUT 203.0.113.10:443',
// recap — NetworkPolicy list
- 'FetchError: request to https://203.0.113.1/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies failed, reason: connect ETIMEDOUT 203.0.113.1:443',
+ 'FetchError: request to https://203.0.113.10/apis/networking.k8s.io/v1/namespaces/sandbox-recipes/networkpolicies failed, reason: connect ETIMEDOUT 203.0.113.10:443',
]
for (const message of devMessages) {
const recipe = makeRecipe({
diff --git a/workflow-recipes/src/reconciler/secretOwnershipBackfill.test.ts b/workflow-recipes/src/reconciler/secretOwnershipBackfill.test.ts
index bf9bdb99c..2efde8d03 100644
--- a/workflow-recipes/src/reconciler/secretOwnershipBackfill.test.ts
+++ b/workflow-recipes/src/reconciler/secretOwnershipBackfill.test.ts
@@ -247,10 +247,10 @@ describe('mapRecipeListToBackfillRecipes', () => {
describe('isProdContext', () => {
it('flags the clerum prod context', () => {
- expect(isProdContext('gke_your-gcp-project_us-central1-a_clerum')).toBe(true)
+ expect(isProdContext('gke_${GCP_PROJECT}_us-central1-a_clerum')).toBe(true)
})
it('does NOT flag dev / test / minikube contexts', () => {
- expect(isProdContext('gke_your-gcp-project_us-central1-a_example-dev')).toBe(false)
+ expect(isProdContext('gke_${GCP_PROJECT}_us-central1-a_example-dev')).toBe(false)
expect(isProdContext('clerum-test')).toBe(false)
expect(isProdContext('minikube')).toBe(false)
})
diff --git a/workflow-recipes/src/reconciler/secretOwnershipBackfill.ts b/workflow-recipes/src/reconciler/secretOwnershipBackfill.ts
index 013fe4479..2385e894a 100644
--- a/workflow-recipes/src/reconciler/secretOwnershipBackfill.ts
+++ b/workflow-recipes/src/reconciler/secretOwnershipBackfill.ts
@@ -2,10 +2,10 @@
// pre-existing recipe Secrets that were created before the ownership-label model
// and are therefore UNLABELED. The #637 fail-closed gate denies unlabeled
// envSecret / imagePullSecrets / snippet capability Secrets at reconcile time,
-// which silently breaks any recipe whose credential Secrets predate the model
-// (e.g. leadforge-mcp-credentials). New Secrets created via control-api's
-// /admin/recipe-secrets are already labeled; only legacy / `kubectl
-// apply`-created Secrets need this.
+// which silently breaks plugins whose credential Secrets predate the model (prod
+// incident 2026-06-26: leadforge-mcp-credentials, atb-secrets). New Secrets
+// created via control-api's /admin/recipe-secrets are already labeled; only
+// legacy / `kubectl apply`-created Secrets need this.
//
// CORRECTNESS: this planner mirrors the reconciler's two authoritative rules so it
// cannot drift from enforcement:
diff --git a/workflow-recipes/src/reconciler/workflowOwnerProvenance.test.ts b/workflow-recipes/src/reconciler/workflowOwnerProvenance.test.ts
new file mode 100644
index 000000000..e67c9e889
--- /dev/null
+++ b/workflow-recipes/src/reconciler/workflowOwnerProvenance.test.ts
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import * as k8s from '@kubernetes/client-node'
+import type { WorkflowRecipeCRD } from '../types'
+import { INHERITED_PARENT_RESOURCES_ANNOTATION } from '../workflow/childRecipeFactory'
+import {
+ RuntimeScopeResolutionPendingError,
+ WorkflowRecipeReconciler,
+} from './workflowRecipeReconciler'
+
+const mockCustomApi = {
+ getNamespacedCustomObject: vi.fn(),
+}
+
+vi.mock('@kubernetes/client-node', () => ({
+ KubeConfig: vi.fn().mockImplementation(() => ({
+ makeApiClient: vi
+ .fn()
+ .mockImplementation((ApiClass: unknown) =>
+ (ApiClass as { name?: string }).name === 'CustomObjectsApi' ? mockCustomApi : {}
+ ),
+ })),
+ AppsV1Api: { name: 'AppsV1Api' },
+ BatchV1Api: { name: 'BatchV1Api' },
+ CoreV1Api: { name: 'CoreV1Api' },
+ CustomObjectsApi: { name: 'CustomObjectsApi' },
+ NetworkingV1Api: { name: 'NetworkingV1Api' },
+}))
+
+function dbRunChild(): WorkflowRecipeCRD {
+ return {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: {
+ name: 'parent-recipe-run-00000000',
+ namespace: 'sandbox-recipes',
+ uid: 'uid-child',
+ annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
+ labels: {
+ 'clerum.io/parent-recipe': 'parent-recipe',
+ 'clerum.io/workflow-run-id': '00000000-0000-4000-8000-000000000123',
+ },
+ ownerReferences: [
+ {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ name: 'parent-recipe',
+ uid: 'uid-parent-recipe',
+ controller: true,
+ blockOwnerDeletion: true,
+ },
+ ],
+ },
+ spec: { steps: [{ id: 'research', instruction: 'run' }] },
+ }
+}
+
+describe('WorkflowRecipe owner provenance', () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it('treats a non-404 owner lookup failure as retryable instead of child identity', async () => {
+ mockCustomApi.getNamespacedCustomObject.mockRejectedValueOnce({ code: 503 })
+ const verifyWorkflowRunProvenance = vi.fn().mockResolvedValue('verified')
+ const reconciler = new WorkflowRecipeReconciler(new k8s.KubeConfig(), undefined, {
+ verifyWorkflowRunProvenance,
+ })
+
+ await expect(
+ (
+ reconciler as unknown as {
+ workflowRuntimeScopeRecipeName: (recipe: WorkflowRecipeCRD) => Promise<string>
+ }
+ ).workflowRuntimeScopeRecipeName(dbRunChild())
+ ).rejects.toBeInstanceOf(RuntimeScopeResolutionPendingError)
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledWith({
+ group: 'clerum.io',
+ version: 'v1alpha1',
+ namespace: 'sandbox-recipes',
+ plural: 'workflowrecipes',
+ name: 'parent-recipe',
+ })
+ expect(verifyWorkflowRunProvenance).not.toHaveBeenCalled()
+ })
+})
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index 3fc014039..b5518ba25 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -33,11 +33,15 @@ import {
WorkflowRecipeStatus,
WorkloadDef,
} from '../types'
-import { INHERITED_PARENT_RESOURCES_ANNOTATION } from '../workflow/childRecipeFactory'
+import {
+ INHERITED_PARENT_RESOURCES_ANNOTATION,
+ buildDbRunChildName,
+} from '../workflow/childRecipeFactory'
import { HttpMcpHostClient } from '../workflow/httpMcpHostClient'
import { JwtTokenFactory } from '../workflow/jwtTokenFactory'
import { K8sSecretReaderImpl } from '../workflow/k8sSecretReaderImpl'
import { ModelConfigHandler } from '../workflow/modelConfigHandler'
+import { buildCoordinatorGfsNetworkPolicy } from '../workflow/networkPolicyFactory'
import { deriveWorkflowRuntimePlan } from '../workflow/runtimePlan'
import { validateWorkflowRecipeLimits } from '../workflow/workflowLimits'
import {
@@ -543,6 +547,69 @@ export interface WorkflowRecipeReconcilerDeps {
* left unset.
*/
secretReverseIndex?: SecretReverseIndex
+ /**
+ * Test seam for the durable DB-run provenance check used before a child
+ * WorkflowRecipe may inherit its parent's runtime identity. Production uses
+ * the authoritative `workflow_runs` row directly.
+ */
+ verifyWorkflowRunProvenance?: (expected: {
+ runId: string
+ parentNamespace: string
+ parentName: string
+ childNamespace: string
+ childName: string
+ }) => Promise<WorkflowRunProvenanceState>
+}
+
+export type WorkflowRunProvenanceState = 'verified' | 'pending' | 'invalid'
+
+export interface WorkflowRunProvenanceRow {
+ phase: string
+ recipe_namespace: string
+ recipe_name: string
+ child_recipe_namespace: string | null
+ child_recipe_name: string | null
+}
+
+export function classifyWorkflowRunProvenance(
+ row: WorkflowRunProvenanceRow | undefined,
+ expected: {
+ runId: string
+ parentNamespace: string
+ parentName: string
+ childNamespace: string
+ childName: string
+ }
+): WorkflowRunProvenanceState {
+ if (
+ !row ||
+ row.recipe_namespace !== expected.parentNamespace ||
+ row.recipe_name !== expected.parentName
+ ) {
+ return 'invalid'
+ }
+ if (
+ row.child_recipe_namespace === expected.childNamespace &&
+ row.child_recipe_name === expected.childName
+ ) {
+ return 'verified'
+ }
+ if (
+ row.phase === 'Pending' &&
+ row.child_recipe_namespace === null &&
+ row.child_recipe_name === null &&
+ expected.childName === buildDbRunChildName(expected.parentName, expected.runId)
+ ) {
+ return 'pending'
+ }
+ return 'invalid'
+}
+
+export class RuntimeScopeResolutionPendingError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options)
+ this.name = 'RuntimeScopeResolutionPendingError'
+ }
}
export class WorkflowRecipeReconciler {
@@ -556,6 +623,9 @@ export class WorkflowRecipeReconciler {
private _tokenFactory: JwtTokenFactory | null = null
private fqdnLookup: FqdnLookup
private secretReverseIndex: SecretReverseIndex | null
+ private verifyWorkflowRunProvenance: NonNullable<
+ WorkflowRecipeReconcilerDeps['verifyWorkflowRunProvenance']
+ >
constructor(kc: k8s.KubeConfig, config?: OperatorConfig, deps?: WorkflowRecipeReconcilerDeps) {
this.appsApi = kc.makeApiClient(k8s.AppsV1Api)
@@ -566,6 +636,19 @@ export class WorkflowRecipeReconciler {
this.config = config ?? loadConfig()
this.fqdnLookup = deps?.fqdnLookup ?? defaultFqdnLookup
this.secretReverseIndex = deps?.secretReverseIndex ?? null
+ this.verifyWorkflowRunProvenance =
+ deps?.verifyWorkflowRunProvenance ??
+ (async expected => {
+ const result = await getPool().query<WorkflowRunProvenanceRow>(
+ `SELECT phase, recipe_namespace, recipe_name,
+ child_recipe_namespace, child_recipe_name
+ FROM workflow_runs
+ WHERE run_id = $1
+ LIMIT 1`,
+ [expected.runId]
+ )
+ return classifyWorkflowRunProvenance(result.rows[0], expected)
+ })
}
/**
@@ -734,6 +817,7 @@ export class WorkflowRecipeReconciler {
private async workflowRuntimeScopeRecipeName(recipe: WorkflowRecipeCRD): Promise<string> {
const parentLabel = recipe.metadata.labels?.[PARENT_RECIPE_LABEL]?.trim()
+ const workflowRunId = recipe.metadata.labels?.[WORKFLOW_RUN_ID_LABEL]?.trim()
const ownerRecipe = recipe.metadata.ownerReferences?.find(
ref =>
ref.apiVersion === `${CRD_GROUP}/${CRD_VERSION}` &&
@@ -747,6 +831,18 @@ export class WorkflowRecipeReconciler {
const ownerRecipeUid = ownerRecipe?.uid?.trim()
if (ownerRecipeName && ownerRecipeUid) {
+ if (
+ !workflowRunId ||
+ !parentLabel ||
+ parentLabel !== ownerRecipeName ||
+ recipe.metadata.annotations?.[INHERITED_PARENT_RESOURCES_ANNOTATION] !== 'true'
+ ) {
+ console.warn(
+ `[WR-Reconciler] Ignoring controller ownerReference "${ownerRecipeName}" on workflow "${recipe.metadata.name}" because normal DB-run inheritance metadata is incomplete or inconsistent`
+ )
+ return recipe.metadata.name
+ }
+
const verifiedOwnerRecipeName = await this.verifyControllerOwnerRecipe(
recipe,
ownerRecipeName,
@@ -760,11 +856,38 @@ export class WorkflowRecipeReconciler {
}
return recipe.metadata.name
}
- if (parentLabel && parentLabel !== ownerRecipeName) {
+
+ try {
+ const provenance = await this.verifyWorkflowRunProvenance({
+ runId: workflowRunId,
+ parentNamespace: recipe.metadata.namespace,
+ parentName: ownerRecipeName,
+ childNamespace: recipe.metadata.namespace,
+ childName: recipe.metadata.name,
+ })
+ if (provenance === 'pending') {
+ throw new RuntimeScopeResolutionPendingError(
+ `workflow_runs binding for run "${workflowRunId}" is still pending`
+ )
+ }
+ if (provenance === 'invalid') {
+ console.warn(
+ `[WR-Reconciler] Ignoring controller ownerReference "${ownerRecipeName}" on workflow "${recipe.metadata.name}" because workflow_runs does not bind run "${workflowRunId}" to this exact parent and child`
+ )
+ return recipe.metadata.name
+ }
+ } catch (error) {
+ if (error instanceof RuntimeScopeResolutionPendingError) throw error
console.warn(
- `[WR-Reconciler] Ignoring mismatched ${PARENT_RECIPE_LABEL}="${parentLabel}" on workflow "${recipe.metadata.name}"; using controller ownerReference "${ownerRecipeName}"`
+ `[WR-Reconciler] Deferring runtime scope resolution for workflow "${recipe.metadata.name}" because DB-run provenance is temporarily unavailable:`,
+ error
+ )
+ throw new RuntimeScopeResolutionPendingError(
+ `DB-run provenance is temporarily unavailable for workflow "${recipe.metadata.name}"`,
+ { cause: error }
)
}
+
return verifiedOwnerRecipeName
}
@@ -779,11 +902,22 @@ export class WorkflowRecipeReconciler {
private async hasVerifiedInheritedParentResources(recipe: WorkflowRecipeCRD): Promise<boolean> {
if (!declaresInheritedParentResources(recipe)) return false
const parentName = recipe.metadata.labels?.[PARENT_RECIPE_LABEL]?.trim()
- return Boolean(
- parentName &&
- parentName !== recipe.metadata.name &&
- (await this.workflowRuntimeScopeRecipeName(recipe)) === parentName
+ const ownerRecipe = recipe.metadata.ownerReferences?.find(
+ ref =>
+ ref.apiVersion === `${CRD_GROUP}/${CRD_VERSION}` &&
+ ref.kind === 'WorkflowRecipe' &&
+ ref.controller === true &&
+ ref.name === parentName &&
+ typeof ref.uid === 'string' &&
+ ref.uid.trim().length > 0
+ )
+ if (!parentName || parentName === recipe.metadata.name || !ownerRecipe?.uid) return false
+ const verifiedOwner = await this.verifyControllerOwnerRecipe(
+ recipe,
+ parentName,
+ ownerRecipe.uid.trim()
)
+ return verifiedOwner === parentName
}
private workflowAwaitsTriggeredRun(recipe: WorkflowRecipeCRD): boolean {
@@ -808,7 +942,9 @@ export class WorkflowRecipeReconciler {
namespace: recipe.metadata.namespace,
plural: WORKFLOWRECIPE_PLURAL,
name: ownerRecipeName,
- })) as { metadata?: { uid?: string; deletionTimestamp?: string } }
+ })) as {
+ metadata?: { uid?: string; deletionTimestamp?: string }
+ }
const liveOwnerUid = liveOwner.metadata?.uid
if (liveOwner.metadata?.deletionTimestamp) {
@@ -833,16 +969,23 @@ export class WorkflowRecipeReconciler {
return null
}
console.warn(
- `[WR-Reconciler] Ignoring controller ownerReference "${ownerRecipeName}" on workflow "${recipe.metadata.name}" because the owner WorkflowRecipe could not be verified:`,
+ `[WR-Reconciler] Deferring runtime scope resolution for workflow "${recipe.metadata.name}" because the owner WorkflowRecipe is temporarily unavailable:`,
error
)
- return null
+ throw new RuntimeScopeResolutionPendingError(
+ `Owner WorkflowRecipe "${ownerRecipeName}" is temporarily unavailable`,
+ { cause: error }
+ )
}
}
- private async ensureSteadyWorkflowRuntimeCredentials(recipe: WorkflowRecipeCRD): Promise<void> {
+ private async ensureSteadyWorkflowRuntimeCredentials(
+ recipe: WorkflowRecipeCRD,
+ resolvedRuntimeScopeRecipeName?: string
+ ): Promise<void> {
if (!this.workflowReconciler) return
- const runtimeScopeRecipeName = await this.workflowRuntimeScopeRecipeName(recipe)
+ const runtimeScopeRecipeName =
+ resolvedRuntimeScopeRecipeName ?? (await this.workflowRuntimeScopeRecipeName(recipe))
const coordinatorRefresher = this.workflowReconciler as WorkflowReconciler & {
ensureCoordinatorRuntimeCredentials?: (
recipeNamespace: string,
@@ -1082,8 +1225,16 @@ export class WorkflowRecipeReconciler {
return this.staleRecipeResult(recipe, 'initial check')
}
+ const isWorkflow = recipe.spec.steps !== undefined && recipe.spec.steps.length > 0
+ if (isWorkflow) {
+ // Revocation must precede spec/policy validation: an invalid edit that also
+ // removes publishTargets must still close the previously opened lane.
+ await this.revokeCoordinatorGfsNetworkPolicyIfDisabled(recipe)
+ }
+
const limitError = validateWorkflowRecipeLimits(recipe.spec, this.config)
if (limitError) {
+ if (isWorkflow) await this.revokeCoordinatorGfsNetworkPolicy(recipe)
return {
phase: 'failed' as RecipePhase,
message: limitError,
@@ -1103,6 +1254,7 @@ export class WorkflowRecipeReconciler {
const policies = await listWorkflowRecipePolicies(this.customApi, ns)
const violations = enforcePolicy(recipe, policies)
if (violations.length > 0) {
+ if (isWorkflow) await this.revokeCoordinatorGfsNetworkPolicy(recipe)
const details = violations.map(v => `[${v.policy}] ${v.rule}: ${v.message}`).join('; ')
console.error(`[WR-Reconciler] Policy violation for "${name}": ${details}`)
return {
@@ -1139,11 +1291,10 @@ export class WorkflowRecipeReconciler {
// reconcile loop. This prevents the fundamental conflict between the WRC
// reconciler (which patches recipe.phase) and the coordinator (which patches
// workflowExecution.phase and steps[]) — two concurrent writers on the same CRD.
- const isWorkflow = recipe.spec.steps !== undefined && recipe.spec.steps.length > 0
-
if (isWorkflow) {
const stepLimitError = this.validateWorkflowStepLimit(recipe)
if (stepLimitError) {
+ await this.revokeCoordinatorGfsNetworkPolicy(recipe)
return {
phase: 'failed',
message: stepLimitError,
@@ -1161,6 +1312,47 @@ export class WorkflowRecipeReconciler {
const wfInProgress =
wfExecPhase === 'initializing' || wfExecPhase === 'running' || wfExecPhase === 'recovering'
+ const workflowWorkloads = recipe.spec.workloads ?? []
+ const policyPreflight = this.buildWorkflowRuntimeSpec(recipe)
+ const policyPreflightError = this.workflowReconciler?.validateWorkflowSpec?.(
+ policyPreflight.workflowRuntimeSpec
+ )
+ const coordinatorGfsPolicyCanOpen =
+ this.workflowReconciler !== undefined &&
+ !recipe.spec.dryRun &&
+ !alreadyPolicyFailed &&
+ !policyPreflight.unresolvedMcpServerMessage &&
+ !policyPreflightError
+ if ((recipe.spec.gfs?.publishTargets ?? []).length > 0 && !coordinatorGfsPolicyCanOpen) {
+ await this.revokeCoordinatorGfsNetworkPolicy(recipe)
+ }
+
+ let approvalScopeRecipeName: string
+ try {
+ // Resolve provenance before any workflow-side mutation. A pending DB
+ // binding or transient DB/Kubernetes lookup must never mint credentials
+ // or create resources under the child fallback identity.
+ approvalScopeRecipeName = await this.workflowRuntimeScopeRecipeName(recipe)
+ } catch (error) {
+ if (!(error instanceof RuntimeScopeResolutionPendingError)) throw error
+ console.warn(
+ `[WR-Reconciler] Runtime scope resolution pending for workflow "${name}"; keeping current state and requeueing:`,
+ error
+ )
+ return {
+ phase: currentPhase as RecipePhase,
+ message: recipe.status?.message ?? '',
+ workloadStatuses: (recipe.status?.workloads ?? []).map(workload => ({
+ id: workload.id,
+ phase: workload.phase,
+ ready: workload.ready ?? false,
+ message: workload.message,
+ })),
+ skipStatusPatch: true,
+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
+ }
+ }
+
if (currentPhase === 'active' && awaitsTriggeredRun && !wfExecPhase) {
// Plugin Workload SDK promptBridge recipes keep an eager mcp-host whose
// provider must be (re-)configured once it becomes Ready and after any
@@ -1169,6 +1361,9 @@ export class WorkflowRecipeReconciler {
// provider_unavailable forever. clientNotifications-only needs no provider,
// so it keeps the cheap short-circuit.
if (!recipe.spec.pluginWorkloadSdk?.promptBridge) {
+ if (coordinatorGfsPolicyCanOpen) {
+ await this.ensureCoordinatorGfsNetworkPolicyIfEnabled(recipe)
+ }
// Issue #637 — this awaiting-trigger short-circuit also returns before the
// Step 8 ownership gate, yet the recipe's envSecret/imagePullSecrets
// workloads were already deployed on the first-deploy pass. Enforce
@@ -1190,10 +1385,15 @@ export class WorkflowRecipeReconciler {
// error lives on workflowExecution.message) must NOT be re-confirmed here
// — fall through to the recovery handoff below so the run is retried.
if (wfTerminal && !awaitsTriggeredRun && !latchedByTransientError) {
+ if (wfExecPhase === 'completed' && coordinatorGfsPolicyCanOpen) {
+ await this.ensureCoordinatorGfsNetworkPolicyIfEnabled(recipe)
+ } else {
+ await this.revokeCoordinatorGfsNetworkPolicy(recipe)
+ }
const derivedPhase: RecipePhase = wfExecPhase === 'completed' ? 'active' : 'failed'
const derivedMessage = `Workflow ${wfExecPhase}`
if (wfExecPhase === 'completed') {
- await this.ensureSteadyWorkflowRuntimeCredentials(recipe)
+ await this.ensureSteadyWorkflowRuntimeCredentials(recipe, approvalScopeRecipeName)
}
// Free a terminal run's COMPUTE pods promptly (mcp-host, coordinator,
// snippet-runner, and any cross-namespace transport/MCP-server such as
@@ -1247,10 +1447,13 @@ export class WorkflowRecipeReconciler {
)
// Fall through to WorkflowReconciler.reconcile() which will create/recreate pods
} else {
+ if (coordinatorGfsPolicyCanOpen) {
+ await this.ensureCoordinatorGfsNetworkPolicyIfEnabled(recipe)
+ }
console.log(
`[WR-Reconciler] Workflow "${name}" in-progress (wf: ${wfExecPhase}) — skipping reconcile`
)
- await this.ensureSteadyWorkflowRuntimeCredentials(recipe)
+ await this.ensureSteadyWorkflowRuntimeCredentials(recipe, approvalScopeRecipeName)
// Issue #637 — same revocation enforcement as the active short-circuit
// below: a re-labeled Secret on an in-progress workflow must tear down the
// affected workload(s) even though we skip the full reconcile here.
@@ -1272,7 +1475,10 @@ export class WorkflowRecipeReconciler {
// "active" covers both completed workflow infrastructure and an already-active
// recipe whose current execution is still running.
if (currentPhase === 'active' && !awaitsTriggeredRun) {
- await this.ensureSteadyWorkflowRuntimeCredentials(recipe)
+ if (coordinatorGfsPolicyCanOpen) {
+ await this.ensureCoordinatorGfsNetworkPolicyIfEnabled(recipe)
+ }
+ await this.ensureSteadyWorkflowRuntimeCredentials(recipe, approvalScopeRecipeName)
// Issue #637 — this short-circuit runs BEFORE the Step 8 ownership gate to
// protect the coordinator 409-window. Enforce Secret-ownership revocation on
// the active workload(s) (teardown only, no redeploy) and re-seed the
@@ -1292,8 +1498,6 @@ export class WorkflowRecipeReconciler {
// Only reaches here on first deploy (candidate phase) or when no wfExecPhase yet.
// After this, the skip guards above prevent redundant reconciles.
- const workflowWorkloads = recipe.spec.workloads ?? []
-
const workflowComputedValues = recipe.spec.computed
? evaluateComputedValues(recipe.spec.computed, recipe.spec.inputs ?? {})
: undefined
@@ -1362,57 +1566,17 @@ export class WorkflowRecipeReconciler {
throw error
}
- const mcpServerNs = this.config.namespace
- const computedMcpServers = (recipe.spec.workloads ?? [])
- .filter(w => w.transport != null && w.port != null)
- .map(w => ({
- id: w.id,
- endpoint: `http://${mcpServerName(recipe.metadata.name, w.id, recipe)}.${mcpServerNs}.svc.cluster.local:${w.port!}${w.transport?.path ?? '/mcp'}`,
- }))
- const mergedMcpServersMap = new Map<string, { id: string; endpoint: string }>()
- for (const srv of (recipe.spec.mcpServers ?? []) as Array<{
- id: string
- endpoint?: string
- }>) {
- if (srv.id && srv.endpoint)
- mergedMcpServersMap.set(srv.id, { id: srv.id, endpoint: srv.endpoint })
- }
- for (const srv of computedMcpServers) mergedMcpServersMap.set(srv.id, srv)
-
- // Validate: every steps[].mcpServers[] ID must resolve to an endpoint
- for (const step of recipe.spec.steps ?? []) {
- for (const srvId of (step as { mcpServers?: string[] }).mcpServers ?? []) {
- if (!mergedMcpServersMap.has(srvId)) {
- return {
- phase: 'failed' as RecipePhase,
- message: `Step "${(step as { id: string }).id}" references MCP server "${srvId}" not found in MCP workloads or mcpServers (with endpoint)`,
- workloadStatuses: [],
- }
- }
+ // Rebuild after instance assignment because transport Service names may
+ // depend on the newly persisted workload instance mapping.
+ const { workflowRuntimeSpec, unresolvedMcpServerMessage } =
+ this.buildWorkflowRuntimeSpec(recipe)
+ if (unresolvedMcpServerMessage) {
+ return {
+ phase: 'failed' as RecipePhase,
+ message: unresolvedMcpServerMessage,
+ workloadStatuses: [],
}
}
-
- const workflowRuntimeSpec = {
- coordinatorImage: recipe.spec.coordinatorImage,
- agent: recipe.spec.agent as import('../workflow/types').AgentSpec | undefined,
- inputContract: recipe.spec.inputContract,
- steps: recipe.spec.steps! as import('../workflow/types').StepSpec[],
- mcpServers: [...mergedMcpServersMap.values()] as Array<{ id: string; endpoint: string }>,
- output: recipe.spec.output as import('../workflow/types').OutputSpec | undefined,
- runtimeEgress: recipe.spec.runtimeEgress,
- resources: recipe.spec.resources,
- // NP-04: inner reconciler needs to know which mcpServers are workload-spawned
- // (vs external McpServer CRDs) to compute the correct NetworkPolicy pod selector.
- workloads: recipe.spec.workloads,
- // Phase 5: forward scheduling/triggers so the inner reconciler can keep
- // `workflow_schedules` in sync. Without these, the DB worker never sees
- // the cron (root cause of schedules E2E Case 2 failure).
- triggers: recipe.spec.triggers,
- scheduling: recipe.spec.scheduling,
- // Plugin Workload SDK: forward so the inner reconciler can create the
- // mcp-host eagerly (always-on SDK server, independent of trigger).
- pluginWorkloadSdk: recipe.spec.pluginWorkloadSdk,
- }
const workflowPreflightError =
this.workflowReconciler.validateWorkflowSpec(workflowRuntimeSpec)
if (workflowPreflightError) {
@@ -1442,7 +1606,9 @@ export class WorkflowRecipeReconciler {
}
}
- if (!(await this.hasVerifiedInheritedParentResources(recipe))) {
+ const inheritsVerifiedParentResources =
+ approvalScopeRecipeName !== recipe.metadata.name && declaresInheritedParentResources(recipe)
+ if (!inheritsVerifiedParentResources) {
await this.ensureRecipeResources(recipe)
}
@@ -1493,7 +1659,6 @@ export class WorkflowRecipeReconciler {
console.log(
`[WR-Reconciler] Workflow "${name}" first deploy (${recipe.spec.steps!.length} steps) — creating infrastructure`
)
- const approvalScopeRecipeName = await this.workflowRuntimeScopeRecipeName(recipe)
// Recovery handoff: when this workflow was latched `failed` by a transient
// infra blip, hand the inner reconciler a `recovering` execution phase
// (preserving message/steps/conditions) so it retries infrastructure
@@ -1528,6 +1693,11 @@ export class WorkflowRecipeReconciler {
recipe.metadata.labels?.[WORKFLOW_ACTOR_ID_LABEL],
recipe.metadata.labels?.[WORKFLOW_ACTOR_TYPE_LABEL]
)
+ if (coordinatorGfsPolicyCanOpen && !result.skipStatusPatch && result.phase !== 'failed') {
+ await this.ensureCoordinatorGfsNetworkPolicyIfEnabled(recipe)
+ } else if (result.phase === 'failed' || !coordinatorGfsPolicyCanOpen) {
+ await this.revokeCoordinatorGfsNetworkPolicy(recipe)
+ }
return {
phase: result.phase as RecipePhase,
message: result.message,
@@ -4029,6 +4199,149 @@ export class WorkflowRecipeReconciler {
)
}
+ private coordinatorGfsNetworkPolicy(recipe: WorkflowRecipeCRD): k8s.V1NetworkPolicy {
+ return buildCoordinatorGfsNetworkPolicy({
+ recipeName: recipe.metadata.name,
+ sandboxNamespace: this.config.sandboxNamespace,
+ })
+ }
+
+ private buildWorkflowRuntimeSpec(recipe: WorkflowRecipeCRD) {
+ const computedMcpServers = (recipe.spec.workloads ?? [])
+ .filter(workload => workload.transport != null && workload.port != null)
+ .map(workload => ({
+ id: workload.id,
+ endpoint: `http://${mcpServerName(recipe.metadata.name, workload.id, recipe)}.${this.config.namespace}.svc.cluster.local:${workload.port!}${workload.transport?.path ?? '/mcp'}`,
+ }))
+ const mergedMcpServers = new Map<string, { id: string; endpoint: string }>()
+ for (const server of (recipe.spec.mcpServers ?? []) as Array<{
+ id: string
+ endpoint?: string
+ }>) {
+ if (server.id && server.endpoint) {
+ mergedMcpServers.set(server.id, { id: server.id, endpoint: server.endpoint })
+ }
+ }
+ for (const server of computedMcpServers) mergedMcpServers.set(server.id, server)
+
+ let unresolvedMcpServerMessage: string | undefined
+ for (const step of recipe.spec.steps ?? []) {
+ for (const serverId of (step as { mcpServers?: string[] }).mcpServers ?? []) {
+ if (!mergedMcpServers.has(serverId)) {
+ unresolvedMcpServerMessage = `Step "${step.id}" references MCP server "${serverId}" not found in MCP workloads or mcpServers (with endpoint)`
+ break
+ }
+ }
+ if (unresolvedMcpServerMessage) break
+ }
+
+ return {
+ unresolvedMcpServerMessage,
+ workflowRuntimeSpec: {
+ coordinatorImage: recipe.spec.coordinatorImage,
+ agent: recipe.spec.agent as import('../workflow/types').AgentSpec | undefined,
+ inputContract: recipe.spec.inputContract,
+ steps: recipe.spec.steps! as import('../workflow/types').StepSpec[],
+ mcpServers: [...mergedMcpServers.values()] as Array<{ id: string; endpoint: string }>,
+ output: recipe.spec.output as import('../workflow/types').OutputSpec | undefined,
+ runtimeEgress: recipe.spec.runtimeEgress,
+ resources: recipe.spec.resources,
+ gfs: recipe.spec.gfs,
+ workloads: recipe.spec.workloads,
+ triggers: recipe.spec.triggers,
+ scheduling: recipe.spec.scheduling,
+ pluginWorkloadSdk: recipe.spec.pluginWorkloadSdk,
+ },
+ }
+ }
+
+ private async ensureCoordinatorGfsNetworkPolicyIfEnabled(
+ recipe: WorkflowRecipeCRD
+ ): Promise<void> {
+ if ((recipe.spec.gfs?.publishTargets ?? []).length === 0) return
+
+ const namespace = this.config.sandboxNamespace
+ const policy = this.coordinatorGfsNetworkPolicy(recipe)
+ const name = policy.metadata!.name!
+ await this.createOrReplace(
+ () => this.networkingApi.createNamespacedNetworkPolicy({ namespace, body: policy }),
+ async () => {
+ const existing = await this.networkingApi.readNamespacedNetworkPolicy({
+ name,
+ namespace,
+ })
+ this.assertCoordinatorGfsNetworkPolicyOwnership(existing, recipe.metadata.name, namespace)
+ const desiredLabels = policy.metadata?.labels ?? {}
+ const existingLabels = existing.metadata?.labels ?? {}
+ const labelsMatch = Object.entries(desiredLabels).every(
+ ([key, value]) => existingLabels[key] === value
+ )
+ if (labelsMatch && JSON.stringify(existing.spec) === JSON.stringify(policy.spec)) {
+ return existing
+ }
+ policy.metadata!.resourceVersion = existing.metadata?.resourceVersion
+ return this.networkingApi.replaceNamespacedNetworkPolicy({
+ name,
+ namespace,
+ body: policy,
+ })
+ },
+ `NetworkPolicy "${name}" in ${namespace}`
+ )
+ }
+
+ private async revokeCoordinatorGfsNetworkPolicyIfDisabled(
+ recipe: WorkflowRecipeCRD
+ ): Promise<void> {
+ if ((recipe.spec.gfs?.publishTargets ?? []).length > 0) return
+
+ await this.revokeCoordinatorGfsNetworkPolicy(recipe)
+ }
+
+ private async revokeCoordinatorGfsNetworkPolicy(recipe: WorkflowRecipeCRD): Promise<void> {
+ const namespace = this.config.sandboxNamespace
+ const policy = this.coordinatorGfsNetworkPolicy(recipe)
+ const name = policy.metadata!.name!
+ let existing: k8s.V1NetworkPolicy
+ try {
+ existing = await this.networkingApi.readNamespacedNetworkPolicy({ name, namespace })
+ } catch (error: unknown) {
+ if (getErrorCode(error) === 404) return
+ throw error
+ }
+ this.assertCoordinatorGfsNetworkPolicyOwnership(existing, recipe.metadata.name, namespace)
+ const uid = existing.metadata?.uid
+ const resourceVersion = existing.metadata?.resourceVersion
+ if (!uid || !resourceVersion) {
+ throw new NetworkPolicyOwnershipConflictError(
+ `Refusing to delete NetworkPolicy "${name}" in ${namespace}: live object identity is incomplete`
+ )
+ }
+ await this.deleteOrThrow(
+ () =>
+ this.networkingApi.deleteNamespacedNetworkPolicy({
+ name,
+ namespace,
+ body: { preconditions: { uid, resourceVersion } },
+ }),
+ `NetworkPolicy "${name}" in ${namespace}`
+ )
+ }
+
+ private assertCoordinatorGfsNetworkPolicyOwnership(
+ existing: k8s.V1NetworkPolicy,
+ recipeName: string,
+ namespace: string
+ ): void {
+ const labels = existing.metadata?.labels ?? {}
+ if (labels['clerum.io/managed-by'] === 'wrc' && labels['clerum.io/recipe'] === recipeName) {
+ return
+ }
+ throw new NetworkPolicyOwnershipConflictError(
+ `Refusing to mutate NetworkPolicy "${recipeName}-coordinator-to-gfs" in ${namespace}: existing policy is not owned by WRC for WorkflowRecipe "${recipeName}"`
+ )
+ }
+
private async deleteWorkloadEgressIfExists(
recipeName: string,
workloadId: string,
diff --git a/workflow-recipes/src/reconciler/workflowRunProvenance.test.ts b/workflow-recipes/src/reconciler/workflowRunProvenance.test.ts
new file mode 100644
index 000000000..57a38d14b
--- /dev/null
+++ b/workflow-recipes/src/reconciler/workflowRunProvenance.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import { buildDbRunChildName } from '../workflow/childRecipeFactory'
+import {
+ type WorkflowRunProvenanceRow,
+ classifyWorkflowRunProvenance,
+} from './workflowRecipeReconciler'
+
+const expected = {
+ runId: '00000000-0000-4000-8000-000000000123',
+ parentNamespace: 'sandbox-recipes',
+ parentName: 'research-summary',
+ childNamespace: 'sandbox-recipes',
+ childName: 'research-summary-child',
+}
+
+function row(overrides: Partial<WorkflowRunProvenanceRow> = {}): WorkflowRunProvenanceRow {
+ return {
+ phase: 'Running',
+ recipe_namespace: expected.parentNamespace,
+ recipe_name: expected.parentName,
+ child_recipe_namespace: expected.childNamespace,
+ child_recipe_name: expected.childName,
+ ...overrides,
+ }
+}
+
+describe('classifyWorkflowRunProvenance', () => {
+ it('verifies only the exact durable parent and child binding', () => {
+ expect(classifyWorkflowRunProvenance(row(), expected)).toBe('verified')
+ expect(
+ classifyWorkflowRunProvenance(row({ child_recipe_name: 'different-child' }), expected)
+ ).toBe('invalid')
+ expect(classifyWorkflowRunProvenance(row({ recipe_name: 'different-parent' }), expected)).toBe(
+ 'invalid'
+ )
+ })
+
+ it('classifies an exact deterministic child with an unbound Pending row as pending', () => {
+ const pendingExpected = {
+ ...expected,
+ childName: buildDbRunChildName(expected.parentName, expected.runId),
+ }
+ expect(
+ classifyWorkflowRunProvenance(
+ row({
+ phase: 'Pending',
+ child_recipe_namespace: null,
+ child_recipe_name: null,
+ }),
+ pendingExpected
+ )
+ ).toBe('pending')
+ })
+
+ it('rejects a non-deterministic observed child even while the row is Pending', () => {
+ expect(
+ classifyWorkflowRunProvenance(
+ row({
+ phase: 'Pending',
+ child_recipe_namespace: null,
+ child_recipe_name: null,
+ }),
+ expected
+ )
+ ).toBe('invalid')
+ })
+
+ it('rejects missing rows and partially attached child bindings', () => {
+ expect(classifyWorkflowRunProvenance(undefined, expected)).toBe('invalid')
+ expect(
+ classifyWorkflowRunProvenance(
+ row({ phase: 'Pending', child_recipe_namespace: null }),
+ expected
+ )
+ ).toBe('invalid')
+ })
+})
diff --git a/workflow-recipes/src/workflow/childRecipeFactory.test.ts b/workflow-recipes/src/workflow/childRecipeFactory.test.ts
index a2c43a25c..3d47041e3 100644
--- a/workflow-recipes/src/workflow/childRecipeFactory.test.ts
+++ b/workflow-recipes/src/workflow/childRecipeFactory.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest'
+import type { WorkflowRecipeGfsIntentSpec } from '../types.js'
import { type ParentRecipe, buildChildRecipe } from './childRecipeFactory.js'
function makeParent(overrides: Partial<ParentRecipe['spec']> = {}): ParentRecipe {
@@ -63,4 +64,53 @@ describe('buildChildRecipe', () => {
expect(spec.inputs).toEqual({ db_name: 'run-db' })
expect(spec.computed).toEqual([{ name: 'db_mode', expression: "'readonly'" }])
})
+
+ it('inherits the parent GFS intent exactly into the per-run child', () => {
+ const gfs: WorkflowRecipeGfsIntentSpec = {
+ publishTargets: [{ drive: 'main', target: 'published-results' }],
+ mounts: [
+ {
+ drive: 'main',
+ target: 'shared-inputs',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ],
+ }
+
+ const child = buildChildRecipe(makeParent({ gfs }), 0)
+
+ expect((child.spec as Record<string, unknown>).gfs).toEqual(gfs)
+ })
+
+ it('omits GFS intent when the parent recipe does not declare it', () => {
+ const child = buildChildRecipe(makeParent(), 0)
+
+ expect(child.spec).not.toHaveProperty('gfs')
+ })
+
+ it('deep-copies inherited GFS intent so parent mutations cannot change a run', () => {
+ const mount = {
+ drive: 'main',
+ target: 'shared-inputs',
+ scopes: ['gfs.read', 'gfs.write'] as Array<'gfs.read' | 'gfs.write'>,
+ }
+ const gfs: WorkflowRecipeGfsIntentSpec = {
+ mounts: [mount],
+ }
+ const parent = makeParent({ gfs })
+
+ const child = buildChildRecipe(parent, 0)
+ mount.target = 'mutated-after-child-creation'
+ mount.scopes.pop()
+
+ expect((child.spec as Record<string, unknown>).gfs).toEqual({
+ mounts: [
+ {
+ drive: 'main',
+ target: 'shared-inputs',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ],
+ })
+ })
})
diff --git a/workflow-recipes/src/workflow/childRecipeFactory.ts b/workflow-recipes/src/workflow/childRecipeFactory.ts
index 2cd23e4e3..d37760d2b 100644
--- a/workflow-recipes/src/workflow/childRecipeFactory.ts
+++ b/workflow-recipes/src/workflow/childRecipeFactory.ts
@@ -10,6 +10,7 @@ import * as k8s from '@kubernetes/client-node'
import { createHash } from 'node:crypto'
import { createLogger } from '../observability/logger'
import { CRD_GROUP, CRD_VERSION, WORKFLOWRECIPE_PLURAL } from '../reconciler/crdConstants'
+import type { WorkflowRecipeGfsIntentSpec } from '../types'
// Strict allowlist: child WorkflowRecipe CRDs inherit the platform-owned
// WorkflowRecipe namespace only. Rendered MCP transport children are represented
@@ -36,6 +37,7 @@ export interface ParentRecipe {
workloads?: unknown[]
resources?: unknown[]
runtimeEgress?: Record<string, unknown>
+ gfs?: WorkflowRecipeGfsIntentSpec
output?: unknown
// scheduling intentionally NOT included in child
}
@@ -264,6 +266,7 @@ export function buildChildRecipe(
workloads: deepCopy(parent.spec.workloads),
resources: deepCopy(parent.spec.resources),
runtimeEgress: deepCopy(parent.spec.runtimeEgress),
+ ...(parent.spec.gfs ? { gfs: deepCopy(parent.spec.gfs) } : {}),
inputContract: deepCopy(parent.spec.inputContract),
computed: deepCopy(parent.spec.computed),
...(options.inputs ? { inputs: deepCopy(options.inputs) } : {}),
diff --git a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts
index d3d43d695..4a48888e4 100644
--- a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts
+++ b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.test.ts
@@ -1,53 +1,8 @@
import { describe, expect, it, vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
-import type { DbRunRow } from '../reconciler/dbRunProcessor.js'
+import type { WorkflowRecipeGfsIntentSpec } from '../types.js'
import { createDbRunChildRecipe } from './dbRunChildRecipeCreator.js'
-
-function makeRun(overrides: Partial<DbRunRow> = {}): DbRunRow {
- return {
- run_id: '00000000-0000-0000-0000-000000000123',
- recipe_namespace: 'sandbox-recipes',
- recipe_name: 'demo-parent',
- phase: 'Pending',
- team_id: null,
- usage_team_id: null,
- actor_type: 'user',
- actor_id: null,
- inputs: null,
- intermediate_parameters: null,
- output_overrides: null,
- trigger_source: 'onDemand',
- owner_instance_id: null,
- max_duration_seconds: 600,
- started_at: null,
- child_recipe_name: null,
- child_recipe_namespace: null,
- ...overrides,
- }
-}
-
-function makeParent() {
- return {
- metadata: {
- name: 'demo-parent',
- namespace: 'sandbox-recipes',
- uid: 'parent-uid-1',
- },
- spec: {
- coordinatorImage: 'clerum/workflow-custom-sdk-e2e:test',
- inputContract: {
- properties: {
- greeting: { type: 'string', default: 'hello' },
- },
- },
- steps: [{ id: 'step-1' }],
- inputs: { greeting: 'hello' },
- computed: [{ name: 'db_mode', expression: "'readonly'" }],
- resources: [{ id: 'api-key', type: 'secret', data: { token: 'redacted' } }],
- runtimeEgress: { http: { allowedHosts: ['swapi.info'] } },
- },
- }
-}
+import { makeExistingChild, makeParent, makeRun } from './dbRunChildRecipeCreator.testFixtures.js'
describe('createDbRunChildRecipe', () => {
it('creates a stable child name derived from the run id', async () => {
@@ -210,14 +165,7 @@ describe('createDbRunChildRecipe', () => {
getNamespacedCustomObject: vi
.fn()
.mockResolvedValueOnce(makeParent())
- .mockResolvedValueOnce({
- metadata: {
- name: 'demo-parent-00000000',
- labels: {
- 'clerum.io/workflow-run-id': '00000000-0000-0000-0000-000000000123',
- },
- },
- }),
+ .mockResolvedValueOnce(makeExistingChild()),
createNamespacedCustomObject: vi.fn().mockRejectedValue({ code: 409 }),
} as unknown as k8s.CustomObjectsApi
@@ -249,24 +197,71 @@ describe('createDbRunChildRecipe', () => {
expect(childSpec?.computed).toEqual([{ name: 'db_mode', expression: "'readonly'" }])
})
- it('throws if a 409 resolves to a child owned by a different run', async () => {
+ it('retains the exact parent GFS intent on a DB-run child recipe', async () => {
+ const gfs: WorkflowRecipeGfsIntentSpec = {
+ publishTargets: [{ drive: 'main', target: 'published-results' }],
+ mounts: [
+ {
+ drive: 'main',
+ target: 'shared-inputs',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ],
+ }
+ const customApi = {
+ getNamespacedCustomObject: vi.fn().mockResolvedValue(makeParent(gfs)),
+ createNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: { name: 'demo-parent-00000000' },
+ }),
+ } as unknown as k8s.CustomObjectsApi
+
+ await createDbRunChildRecipe(customApi, makeRun())
+
+ expect(
+ (customApi.createNamespacedCustomObject as unknown as ReturnType<typeof vi.fn>).mock
+ .calls[0]?.[0]?.body?.spec?.gfs
+ ).toEqual(gfs)
+ })
+
+ const expectedGfs: WorkflowRecipeGfsIntentSpec = {
+ mounts: [{ drive: 'main', target: 'shared-inputs', scopes: ['gfs.read'] }],
+ }
+ const collisionCases: Array<[string, (child: ReturnType<typeof makeExistingChild>) => void]> = [
+ [
+ 'a different run id',
+ child => void (child.metadata.labels['clerum.io/workflow-run-id'] = 'other-run'),
+ ],
+ ['the wrong owner', child => void (child.metadata.ownerReferences[0]!.name = 'other-parent')],
+ ['a stale parent UID', child => void (child.metadata.ownerReferences[0]!.uid = 'stale-uid')],
+ ['no controller owner', child => void (child.metadata.ownerReferences = [])],
+ [
+ 'the wrong parent label',
+ child => void (child.metadata.labels['clerum.io/parent-recipe'] = 'other-parent'),
+ ],
+ [
+ 'the wrong inherited-resource annotation',
+ child => void (child.metadata.annotations['clerum.io/inherited-parent-resources'] = 'false'),
+ ],
+ ['mismatched GFS intent', child => void (child.spec.gfs = { mounts: [] })],
+ ['changed steps', child => void (child.spec.steps = [{ id: 'different-step' }])],
+ ['changed coordinator image', child => void (child.spec.coordinatorImage = 'attacker/image')],
+ ['changed resources', child => void (child.spec.resources[0]!.id = 'other-resource')],
+ ['the wrong child kind', child => void (child.kind = 'ConfigMap')],
+ ]
+
+ it.each(collisionCases)('rejects a 409 collision with %s', async (_description, mutate) => {
+ const existing = makeExistingChild(expectedGfs)
+ mutate(existing)
const customApi = {
getNamespacedCustomObject: vi
.fn()
- .mockResolvedValueOnce(makeParent())
- .mockResolvedValueOnce({
- metadata: {
- name: 'demo-parent-00000000',
- labels: {
- 'clerum.io/workflow-run-id': 'ffffffff-ffff-ffff-ffff-ffffffffffff',
- },
- },
- }),
+ .mockResolvedValueOnce(makeParent(expectedGfs))
+ .mockResolvedValueOnce(existing),
createNamespacedCustomObject: vi.fn().mockRejectedValue({ code: 409 }),
} as unknown as k8s.CustomObjectsApi
await expect(createDbRunChildRecipe(customApi, makeRun())).rejects.toThrow(
- /already exists for a different workflow run/i
+ /does not match the expected workflow run child identity/i
)
})
})
diff --git a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.testFixtures.ts b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.testFixtures.ts
new file mode 100644
index 000000000..b2c88a460
--- /dev/null
+++ b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.testFixtures.ts
@@ -0,0 +1,89 @@
+import type { DbRunRow } from '../reconciler/dbRunProcessor.js'
+import type { WorkflowRecipeGfsIntentSpec } from '../types.js'
+
+const defaultedStep: Record<string, unknown> = {
+ id: 'step-1',
+ timeoutSeconds: 300,
+ backoffSeconds: 30,
+ maxRetries: 2,
+ maxIterations: 50,
+}
+
+export function makeRun(overrides: Partial<DbRunRow> = {}): DbRunRow {
+ return {
+ run_id: '00000000-0000-0000-0000-000000000123',
+ recipe_namespace: 'sandbox-recipes',
+ recipe_name: 'demo-parent',
+ phase: 'Pending',
+ team_id: null,
+ usage_team_id: null,
+ actor_type: 'user',
+ actor_id: null,
+ inputs: null,
+ intermediate_parameters: null,
+ output_overrides: null,
+ trigger_source: 'onDemand',
+ owner_instance_id: null,
+ max_duration_seconds: 600,
+ started_at: null,
+ child_recipe_name: null,
+ child_recipe_namespace: null,
+ ...overrides,
+ }
+}
+
+export function makeParent(gfs?: WorkflowRecipeGfsIntentSpec) {
+ return {
+ metadata: {
+ name: 'demo-parent',
+ namespace: 'sandbox-recipes',
+ uid: 'parent-uid-1',
+ },
+ spec: {
+ coordinatorImage: 'clerum/workflow-custom-sdk-e2e:test',
+ inputContract: { properties: { greeting: { type: 'string', default: 'hello' } } },
+ // The parent is read from Kubernetes, so CRD defaults are materialized.
+ steps: [{ ...defaultedStep }],
+ inputs: { greeting: 'hello' },
+ computed: [{ name: 'db_mode', expression: "'readonly'" }],
+ resources: [{ id: 'api-key', type: 'secret', data: { token: 'redacted' } }],
+ runtimeEgress: { http: { allowedHosts: ['swapi.info'] } },
+ ...(gfs ? { gfs } : {}),
+ },
+ }
+}
+
+export function makeExistingChild(gfs?: WorkflowRecipeGfsIntentSpec) {
+ return {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ metadata: {
+ name: 'demo-parent-00000000',
+ namespace: 'sandbox-recipes',
+ labels: {
+ 'clerum.io/workflow-run-id': '00000000-0000-0000-0000-000000000123',
+ 'clerum.io/parent-recipe': 'demo-parent',
+ },
+ annotations: { 'clerum.io/inherited-parent-resources': 'true' },
+ ownerReferences: [
+ {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ name: 'demo-parent',
+ uid: 'parent-uid-1',
+ controller: true,
+ },
+ ],
+ },
+ spec: {
+ coordinatorImage: 'clerum/workflow-custom-sdk-e2e:test',
+ steps: [{ ...defaultedStep }],
+ resources: [{ id: 'api-key', type: 'secret', data: { token: 'redacted' } }],
+ runtimeEgress: { http: { allowedHosts: ['swapi.info'] } },
+ inputContract: { properties: { greeting: { type: 'string', default: 'hello' } } },
+ computed: [{ name: 'db_mode', expression: "'readonly'" }],
+ inputs: { greeting: 'hello' },
+ ...(gfs ? { gfs } : {}),
+ },
+ }
+}
diff --git a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts
index 749801762..619c89bba 100644
--- a/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts
+++ b/workflow-recipes/src/workflow/dbRunChildRecipeCreator.ts
@@ -1,8 +1,15 @@
import * as k8s from '@kubernetes/client-node'
+import { isDeepStrictEqual } from 'node:util'
import { CRD_GROUP, CRD_VERSION, WORKFLOWRECIPE_PLURAL } from '../reconciler/crdConstants.js'
import type { ChildRecipeRef, DbRunRow } from '../reconciler/dbRunProcessor.js'
import { getErrorCode } from '../reconciler/k8sErrors.js'
-import { type ParentRecipe, buildChildRecipe, buildDbRunChildName } from './childRecipeFactory.js'
+import type { WorkflowRecipeGfsIntentSpec } from '../types.js'
+import {
+ INHERITED_PARENT_RESOURCES_ANNOTATION,
+ type ParentRecipe,
+ buildChildRecipe,
+ buildDbRunChildName,
+} from './childRecipeFactory.js'
import { WORKFLOW_TEAM_ID_LABEL } from './schedulingHandler.js'
export const RUN_ID_LABEL = 'clerum.io/workflow-run-id'
@@ -12,8 +19,27 @@ export const RUN_ACTOR_TYPE_LABEL = 'clerum.io/workflow-actor-type'
export const RUN_OUTPUT_OVERRIDES_ANNOTATION = 'clerum.io/run-output-overrides'
export const RUN_INTERMEDIATE_PARAMS_ANNOTATION = 'clerum.io/run-intermediate-parameters'
+const WORKFLOW_RECIPE_API_VERSION = `${CRD_GROUP}/${CRD_VERSION}`
+const WORKFLOW_RECIPE_KIND = 'WorkflowRecipe'
+const PARENT_RECIPE_LABEL = 'clerum.io/parent-recipe'
+
type ParentRecipeResponse = {
- metadata?: { name?: string; namespace?: string; uid?: string; labels?: Record<string, string> }
+ apiVersion?: string
+ kind?: string
+ metadata?: {
+ name?: string
+ namespace?: string
+ uid?: string
+ labels?: Record<string, string>
+ annotations?: Record<string, string>
+ ownerReferences?: Array<{
+ apiVersion?: string
+ kind?: string
+ name?: string
+ uid?: string
+ controller?: boolean
+ }>
+ }
spec?: {
contextRef?: string
security?: Record<string, unknown>
@@ -27,10 +53,42 @@ type ParentRecipeResponse = {
workloads?: unknown[]
resources?: unknown[]
runtimeEgress?: Record<string, unknown>
+ gfs?: WorkflowRecipeGfsIntentSpec
output?: unknown
}
}
+function isExpectedExistingChild(
+ existing: ParentRecipeResponse,
+ expected: {
+ name: string
+ namespace: string
+ runId: string
+ parentName: string
+ parentUid: string
+ spec: ParentRecipeResponse['spec']
+ }
+): boolean {
+ const controllerOwners =
+ existing.metadata?.ownerReferences?.filter(owner => owner.controller === true) ?? []
+ const controllerOwner = controllerOwners.length === 1 ? controllerOwners[0] : undefined
+
+ return (
+ existing.apiVersion === WORKFLOW_RECIPE_API_VERSION &&
+ existing.kind === WORKFLOW_RECIPE_KIND &&
+ existing.metadata?.name === expected.name &&
+ existing.metadata?.namespace === expected.namespace &&
+ existing.metadata?.labels?.[RUN_ID_LABEL] === expected.runId &&
+ existing.metadata?.labels?.[PARENT_RECIPE_LABEL] === expected.parentName &&
+ existing.metadata?.annotations?.[INHERITED_PARENT_RESOURCES_ANNOTATION] === 'true' &&
+ controllerOwner?.apiVersion === WORKFLOW_RECIPE_API_VERSION &&
+ controllerOwner.kind === WORKFLOW_RECIPE_KIND &&
+ controllerOwner.name === expected.parentName &&
+ controllerOwner.uid === expected.parentUid &&
+ isDeepStrictEqual(existing.spec, expected.spec)
+ )
+}
+
export async function createDbRunChildRecipe(
customApi: k8s.CustomObjectsApi,
run: DbRunRow
@@ -76,6 +134,7 @@ export async function createDbRunChildRecipe(
workloads: response.spec?.workloads,
resources: response.spec?.resources,
runtimeEgress: response.spec?.runtimeEgress,
+ gfs: response.spec?.gfs,
output: response.spec?.output,
},
}
@@ -112,6 +171,11 @@ export async function createDbRunChildRecipe(
: {}),
},
})
+ // Match the JSON representation persisted by Kubernetes: buildChildRecipe
+ // retains undefined keys in memory, while the API payload omits them.
+ const expectedChildSpec = JSON.parse(
+ JSON.stringify(childRecipe.spec)
+ ) as ParentRecipeResponse['spec']
try {
await customApi.createNamespacedCustomObject({
@@ -132,10 +196,18 @@ export async function createDbRunChildRecipe(
name: childName,
})) as ParentRecipeResponse
- const existingRunId = existing.metadata?.labels?.[RUN_ID_LABEL]
- if (existingRunId !== run.run_id) {
+ if (
+ !isExpectedExistingChild(existing, {
+ name: childName,
+ namespace: parentNamespace,
+ runId: run.run_id,
+ parentName,
+ parentUid,
+ spec: expectedChildSpec,
+ })
+ ) {
throw new Error(
- `Child recipe "${parentNamespace}/${childName}" already exists for a different workflow run`
+ `Child recipe "${parentNamespace}/${childName}" already exists but does not match the expected workflow run child identity and inherited intent`
)
}
}
diff --git a/workflow-recipes/src/workflow/jwtTokenFactory.ts b/workflow-recipes/src/workflow/jwtTokenFactory.ts
index 246b4f473..4c7a743da 100644
--- a/workflow-recipes/src/workflow/jwtTokenFactory.ts
+++ b/workflow-recipes/src/workflow/jwtTokenFactory.ts
@@ -8,13 +8,12 @@
* 4. Coordinator → mcp_host (execute) — mounted in Secret
* 5. Coordinator → WRC (status/configure_model/model_injection_request) — mounted in Secret
* 5b. Custom coordinator → WRC (reduced status/signal/health/model_injection_request) — mounted in Secret
- * 6. CronJob → WRC (trigger_write) — mounted in Secret
* */
import { SignJWT, importPKCS8 } from 'jose'
import { randomUUID } from 'node:crypto'
export type TokenAudience = 'mcp-host' | 'clerum-wrc'
-export type TokenSubject = 'coordinator' | 'custom-coordinator' | 'wrc' | 'cronjob'
+export type TokenSubject = 'coordinator' | 'custom-coordinator' | 'wrc'
export interface TokenClaims {
sub: TokenSubject
@@ -33,8 +32,6 @@ export interface TokenClaims {
/** Default TTL for rotatable runtime JWTs mounted through Kubernetes Secret volumes. */
export const DEFAULT_RUNTIME_TOKEN_TTL_SECONDS = 15 * 60
-/** Cron trigger tokens are separate from live runtime JWTs and are refreshed by WRC. */
-const CRONJOB_TRIGGER_TOKEN_EXPIRY_SECONDS = 60 * 60
/** Ephemeral artifact tokens (60s) — signed fresh per request, never stored. */
const ARTIFACT_TOKEN_EXPIRY_SECONDS = 60
@@ -137,7 +134,7 @@ export class JwtTokenFactory {
)
}
- /** Token Type 3: Coordinator → WRC (scopes: configure_model, model_injection_request, status_write, status_read, signal_read, health_read, trigger_write) */
+ /** Token Type 3: Coordinator → WRC (configure/model/status/signal/health scopes). */
async signCoordinatorToWrcToken(recipeName: string, recipeNamespace: string): Promise<string> {
return this.sign(
{
@@ -152,14 +149,13 @@ export class JwtTokenFactory {
'status_read',
'signal_read',
'health_read',
- 'trigger_write',
],
},
this.runtimeTokenTtlSeconds
)
}
- /** Token Type 3b: Custom coordinator → WRC (no trigger_write or configure_model). */
+ /** Token Type 3b: Custom coordinator → WRC (no configure_model). */
async signCustomCoordinatorToWrcToken(
recipeName: string,
recipeNamespace: string
@@ -182,20 +178,6 @@ export class JwtTokenFactory {
)
}
- /** Token Type 4: CronJob → WRC (scope: trigger_write only — least privilege for scheduled triggers) */
- async signCronJobTriggerToken(recipeName: string, recipeNamespace: string): Promise<string> {
- return this.sign(
- {
- sub: 'cronjob',
- aud: 'clerum-wrc',
- recipeName,
- recipeNamespace,
- scopes: ['trigger_write'],
- },
- CRONJOB_TRIGGER_TOKEN_EXPIRY_SECONDS
- )
- }
-
private async sign(claims: TokenClaims, ttlSeconds: number): Promise<string> {
if (!this.privateKey) {
throw new Error('JwtTokenFactory not initialized — call initialize() first')
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts b/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts
index 7663b9787..20f3acda3 100644
--- a/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
-import { type NetworkPolicyConfig, buildWorkflowNetworkPolicies } from './networkPolicyFactory'
+import {
+ type NetworkPolicyConfig,
+ buildCoordinatorGfsNetworkPolicy,
+ buildWorkflowNetworkPolicies,
+} from './networkPolicyFactory'
const baseConfig: NetworkPolicyConfig = {
recipeName: 'daily-report',
@@ -74,4 +78,48 @@ describe('workflow GFS NetworkPolicy', () => {
'gfs'
)
})
+
+ it('uses the canonical coordinator GFS policy for custom destinations', () => {
+ const policy = buildCoordinatorGfsNetworkPolicy({
+ recipeName: 'daily-report',
+ sandboxNamespace: 'sandbox-recipes',
+ gfsNamespace: 'custom-gfs',
+ gfscPort: 19087,
+ })
+
+ expect(policy).toEqual({
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name: 'daily-report-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ labels: {
+ 'clerum.io/recipe': 'daily-report',
+ 'clerum.io/managed-by': 'wrc',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: {
+ 'clerum.io/recipe': 'daily-report',
+ 'clerum.io/component': 'workflow-coordinator',
+ },
+ },
+ policyTypes: ['Egress'],
+ egress: [
+ {
+ to: [
+ {
+ namespaceSelector: {
+ matchLabels: { 'kubernetes.io/metadata.name': 'custom-gfs' },
+ },
+ podSelector: { matchLabels: { app: 'gfs-controller' } },
+ },
+ ],
+ ports: [{ port: 19087, protocol: 'TCP' }],
+ },
+ ],
+ },
+ })
+ })
})
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.ts b/workflow-recipes/src/workflow/networkPolicyFactory.ts
index d5e1079cf..bee2ec91c 100644
--- a/workflow-recipes/src/workflow/networkPolicyFactory.ts
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.ts
@@ -84,6 +84,50 @@ export interface NetworkPolicyConfig {
pluginWorkloadSdkSandboxAccess?: boolean
}
+export function buildCoordinatorGfsNetworkPolicy(
+ config: Pick<NetworkPolicyConfig, 'recipeName' | 'sandboxNamespace' | 'gfsNamespace' | 'gfscPort'>
+): k8s.V1NetworkPolicy {
+ const gfsNamespace = config.gfsNamespace ?? 'gfs'
+ const gfscPort = config.gfscPort ?? 8087
+
+ return {
+ apiVersion: 'networking.k8s.io/v1',
+ kind: 'NetworkPolicy',
+ metadata: {
+ name: `${config.recipeName}-coordinator-to-gfs`,
+ namespace: config.sandboxNamespace,
+ labels: {
+ 'clerum.io/recipe': config.recipeName,
+ 'clerum.io/managed-by': 'wrc',
+ },
+ },
+ spec: {
+ podSelector: {
+ matchLabels: {
+ 'clerum.io/recipe': config.recipeName,
+ 'clerum.io/component': 'workflow-coordinator',
+ },
+ },
+ policyTypes: ['Egress'],
+ egress: [
+ {
+ to: [
+ {
+ namespaceSelector: {
+ matchLabels: { 'kubernetes.io/metadata.name': gfsNamespace },
+ },
+ podSelector: {
+ matchLabels: { app: 'gfs-controller' },
+ },
+ },
+ ],
+ ports: [{ port: gfscPort, protocol: 'TCP' }],
+ },
+ ],
+ },
+ }
+}
+
export const PUBLIC_HTTP_EGRESS_EXCEPT_CIDRS = [
'0.0.0.0/8',
'10.0.0.0/8',
@@ -181,39 +225,7 @@ export function buildWorkflowNetworkPolicies(
snippetRunnerPublicHttpEgressRule
? { 'clerum.io/egress-class': config.snippetRunnerPublicHttpEgressClass ?? 'exact-host' }
: {}
- const coordinatorToGfs: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name: `${config.recipeName}-coordinator-to-gfs`,
- namespace: config.sandboxNamespace,
- labels: commonLabels,
- },
- spec: {
- podSelector: {
- matchLabels: {
- 'clerum.io/recipe': config.recipeName,
- 'clerum.io/component': 'workflow-coordinator',
- },
- },
- policyTypes: ['Egress'],
- egress: [
- {
- to: [
- {
- namespaceSelector: {
- matchLabels: { 'kubernetes.io/metadata.name': gfsNamespace },
- },
- podSelector: {
- matchLabels: { app: 'gfs-controller' },
- },
- },
- ],
- ports: [{ port: gfscPort, protocol: 'TCP' as const }],
- },
- ],
- },
- }
+ const coordinatorToGfs = buildCoordinatorGfsNetworkPolicy(config)
const coordinatorToWrc: k8s.V1NetworkPolicy = {
apiVersion: 'networking.k8s.io/v1',
diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.ts
index 7e146a8f1..e441336e5 100644
--- a/workflow-recipes/src/workflow/podFactory.ts
+++ b/workflow-recipes/src/workflow/podFactory.ts
@@ -6,6 +6,7 @@
import * as k8s from '@kubernetes/client-node'
import { createHash } from 'node:crypto'
import { privateWorkflowContextName } from '../reconciler/workflowContext'
+import type { WorkflowRecipeGfsScope } from '../types'
import { truncateRfc1123WithHash } from './networkPolicyFactory'
import {
PLUGIN_WORKLOAD_SDK_PORT,
@@ -539,6 +540,8 @@ export function buildCoordinatorPod(
}
export interface McpHostPodOptions {
+ /** Verified scopes derived from the WorkflowRecipe spec and used to mint the mounted GFS token. */
+ gfsScopes?: readonly WorkflowRecipeGfsScope[]
workflowOutputScope?: string
mountWorkflowOutput: boolean
/**
@@ -687,6 +690,9 @@ export function buildMcpHostPod(
name: 'MCP_HOST_RUNTIME_AUTH_STATE_DIR',
value: MCP_HOST_RUNTIME_AUTH_STATE_PATH,
},
+ ...(options.gfsScopes && options.gfsScopes.length > 0
+ ? [{ name: 'MCP_HOST_GFS_SCOPES', value: options.gfsScopes.join(',') }]
+ : []),
// Downward API namespace — defense-in-depth leg of the Plugin
// Workload SDK triple activation gate. Always injected so a
// misplaced Deployment fails the gate closed.
diff --git a/workflow-recipes/src/workflow/restEndpoints.ts b/workflow-recipes/src/workflow/restEndpoints.ts
index 88be363a4..8a513d8d4 100644
--- a/workflow-recipes/src/workflow/restEndpoints.ts
+++ b/workflow-recipes/src/workflow/restEndpoints.ts
@@ -18,7 +18,6 @@ import {
} from './resourceNames'
import { drainSignals } from './signalStore'
import { buildStatusOutputPreview } from './statusOutputPreview'
-import { handleTrigger } from './triggerHandler'
import { StepPhase, WorkflowPhase, isTerminalStepPhase, isTerminalWorkflowPhase } from './types'
import { type AuthenticatedRequest, CONTROL_API_ISSUER } from './workflowAuth'
import { workflowStatusMessage } from './workflowStatusMessage'
@@ -614,8 +613,6 @@ function validateDeclaredModelInjection(
}
// ─── Signal Store (re-exported from signalStore.ts) ─────────────────────
-// enqueueSignal + drainSignals live in signalStore.ts so that triggerHandler.ts
-// can import them without creating a circular dependency.
export { enqueueSignal, drainSignals, type WorkflowSignal } from './signalStore'
// ─── Endpoint Handlers ──────────────────────────────────────────────────
@@ -1551,32 +1548,6 @@ export function createWorkflowEndpointHandlers(
return { status: 204, body: {} }
},
- /** POST /api/v1/workflow/:name/trigger — legacy scheduled execution */
- async postTrigger(
- parentName: string,
- namespace: string,
- claims: AuthenticatedRequest['tokenClaims']
- ): Promise<{ status: number; body: Record<string, unknown> }> {
- const bindingError = validateWorkflowClaimBinding(parentName, claims)
- if (bindingError) return bindingError
- if (!claims.scopes.includes('trigger_write')) {
- return { status: 403, body: { error: 'Missing scope: trigger_write' } }
- }
- if (process.env.WRC_ENABLE_LEGACY_DIRECT_TRIGGER !== 'true') {
- return {
- status: 410,
- body: {
- error: 'Legacy direct trigger endpoint disabled; use control-api workflow broker',
- },
- }
- }
- // Coordinator tokens also carry trigger_write, so require CronJob subject.
- if (claims.sub !== 'cronjob') {
- return { status: 403, body: { error: 'Endpoint requires sub: cronjob' } }
- }
- return handleTrigger(customApi, parentName, namespace)
- },
-
// ─── Helpers ──────────────────────────────────────────────────────
/**
diff --git a/workflow-recipes/src/workflow/secretFactory.ts b/workflow-recipes/src/workflow/secretFactory.ts
index b3c2d1044..c8a99172d 100644
--- a/workflow-recipes/src/workflow/secretFactory.ts
+++ b/workflow-recipes/src/workflow/secretFactory.ts
@@ -36,8 +36,8 @@ export function buildCoordinatorTokenSecret(
// WorkflowRecipe lived in different namespaces so ownerRefs were unsafe.
// Now both live in sandbox-recipes and native GC *could* be wired back
// up, but the explicit cleanup in finalizationHandler.reconcileDelete()
- // still handles Pods, PVCs, NetworkPolicies, and trigger Secrets that
- // do not all share the same parent — so adding the ownerRef here would
+ // still handles Pods, PVCs, and NetworkPolicies that do not all share
+ // the same parent — so adding the ownerRef here would
// only cover half the cleanup surface. Left unchanged until a broader
// ownership refactor is scheduled.
},
@@ -53,37 +53,6 @@ export function buildCoordinatorTokenSecret(
}
}
-/**
- * Builds the CronJob trigger token Secret in control-plane namespace.
- *
- * This Secret CANNOT use ownerReferences because the WorkflowRecipe lives in
- * sandbox-recipes (cross-namespace ownerRefs are not enforced by K8s GC).
- * Cleanup is handled explicitly by finalizationHandler.reconcileDelete.
- */
-export function buildTriggerTokenSecret(
- recipeName: string,
- triggerToken: string,
- namespace: string
-): k8s.V1Secret {
- return {
- apiVersion: 'v1',
- kind: 'Secret',
- metadata: {
- name: `wf-${recipeName}-trigger-token`,
- namespace,
- labels: {
- 'clerum.io/recipe': recipeName,
- 'clerum.io/managed-by': 'wrc',
- 'clerum.io/component': 'trigger-token',
- },
- },
- type: 'Opaque',
- data: {
- token: Buffer.from(triggerToken).toString('base64'),
- },
- }
-}
-
/**
* Recipe-scoped Plugin Workload SDK token Secret (plan §3.6). Each allowed
* caller workload gets its own key (`caller-<workloadId>`) so the SDK server
@@ -170,7 +139,7 @@ export async function createCoordinatorTokens(
includeSnippetRunnerToken?: boolean
gfsToken?: string
} = {}
-): Promise<{ secret: k8s.V1Secret; cronJobTriggerToken: string }> {
+): Promise<k8s.V1Secret> {
const includeMcpHostToken = options.includeMcpHostToken ?? true
const mcpHostToken = includeMcpHostToken
? await tokenFactory.signCoordinatorToMcpHostToken(recipeName, namespace)
@@ -178,12 +147,10 @@ export async function createCoordinatorTokens(
const wrcToken = options.useCustomCoordinatorWrcToken
? await tokenFactory.signCustomCoordinatorToWrcToken(recipeName, namespace)
: await tokenFactory.signCoordinatorToWrcToken(recipeName, namespace)
- // Mint a minimal token for the CronJob — trigger_write scope only (least privilege).
- const cronJobTriggerToken = await tokenFactory.signCronJobTriggerToken(recipeName, namespace)
const snippetRunnerToken =
options.includeSnippetRunnerToken === true ? randomBytes(32).toString('base64url') : undefined
- const secret = buildCoordinatorTokenSecret(
+ return buildCoordinatorTokenSecret(
recipeName,
mcpHostToken,
wrcToken,
@@ -191,6 +158,4 @@ export async function createCoordinatorTokens(
snippetRunnerToken,
options.gfsToken
)
-
- return { secret, cronJobTriggerToken }
}
diff --git a/workflow-recipes/src/workflow/signalStore.ts b/workflow-recipes/src/workflow/signalStore.ts
index d2bbcd5af..3963c5312 100644
--- a/workflow-recipes/src/workflow/signalStore.ts
+++ b/workflow-recipes/src/workflow/signalStore.ts
@@ -1,10 +1,9 @@
/**
* In-memory signal store for workflow runtime signals.
*
- * Extracted from restEndpoints.ts into its own module so that
- * triggerHandler.ts can enqueue cancel signals without creating a
- * circular dependency (restEndpoints → triggerHandler → restEndpoints).
- * */
+ * Kept separate from the HTTP handlers so runtime signal state has a single
+ * owner and can be consumed by both the reconciler and REST surface.
+ */
export interface WorkflowSignal {
type: 'cancel' | 'pause' | 'resume' | 'approval'
diff --git a/workflow-recipes/src/workflow/triggerHandler.ts b/workflow-recipes/src/workflow/triggerHandler.ts
deleted file mode 100644
index caa144042..000000000
--- a/workflow-recipes/src/workflow/triggerHandler.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * Direct trigger handler for scheduled workflow executions.
- *
- * Called by the DB-backed schedule worker through
- * POST /api/v1/workflow/{parent}/trigger. It orchestrates concurrency checks,
- * child WorkflowRecipe creation, and history pruning. The canonical run row is
- * created before this handler runs; this path only materializes the child
- * execution artifact.
- */
-import * as k8s from '@kubernetes/client-node'
-import { createLogger } from '../observability/logger'
-import { CRD_GROUP, CRD_VERSION, WORKFLOWRECIPE_PLURAL } from '../reconciler/crdConstants'
-import { getErrorCode } from '../reconciler/k8sErrors'
-import { type ParentRecipe, buildChildRecipe, resolveExecutionIndex } from './childRecipeFactory'
-import { type HistoryLimits, pruneHistory } from './historyManager'
-import { checkConcurrency } from './rateLimiter'
-import { enqueueSignal } from './signalStore'
-import type { SchedulingSpec } from './types'
-
-export interface TriggerResult {
- status: number
- body: Record<string, unknown>
-}
-
-export async function handleTrigger(
- customApi: k8s.CustomObjectsApi,
- parentName: string,
- namespace: string
-): Promise<TriggerResult> {
- // 1. Fetch parent WorkflowRecipe
- let parent: Record<string, unknown>
- try {
- parent = (await customApi.getNamespacedCustomObject({
- group: CRD_GROUP,
- version: CRD_VERSION,
- namespace,
- plural: WORKFLOWRECIPE_PLURAL,
- name: parentName,
- })) as Record<string, unknown>
- } catch (err: unknown) {
- // Only treat 404 as "not found" — rethrow 5xx/network errors so the CronJob
- // Pod's restartPolicy:OnFailure can retry. Swallowing non-404 errors silently
- // drops scheduled executions on transient K8s API failures.
- if (getErrorCode(err) === 404) {
- return { status: 404, body: { error: `WorkflowRecipe '${parentName}' not found` } }
- }
- throw err
- }
-
- // 2. Verify parent has spec.scheduling
- const spec = parent.spec as Record<string, unknown> | undefined
- const scheduling = spec?.scheduling as SchedulingSpec | undefined
- if (!scheduling) {
- return { status: 400, body: { error: 'Recipe does not have spec.scheduling' } }
- }
-
- // 3. Verify not suspended
- if (scheduling.suspend) {
- return { status: 409, body: { error: 'Recipe scheduling is suspended' } }
- }
-
- // 4. Check concurrency
- const policy = scheduling.concurrencyPolicy ?? 'Forbid'
- const concurrency = await checkConcurrency(customApi, parentName, namespace, policy)
-
- if (concurrency.decision === 'skip') {
- return { status: 202, body: { skipped: true, reason: concurrency.reason } }
- }
-
- if (concurrency.decision === 'replace' && concurrency.runningChildren) {
- await Promise.allSettled(
- concurrency.runningChildren.map(async child => {
- const runningChildName = child.metadata.name
- try {
- const childStatus = (child as unknown as Record<string, unknown>).status as
- | Record<string, unknown>
- | undefined
- const existingExecution = childStatus?.workflowExecution as
- | Record<string, unknown>
- | undefined
- await customApi.patchNamespacedCustomObjectStatus(
- {
- group: CRD_GROUP,
- version: CRD_VERSION,
- namespace,
- plural: WORKFLOWRECIPE_PLURAL,
- name: runningChildName,
- body: {
- status: { workflowExecution: { ...(existingExecution ?? {}), phase: 'cancelled' } },
- },
- },
- {
- middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],
- }
- )
- } catch (patchErr) {
- createLogger('wrc', 'trigger-handler').warn('Failed to patch status of cancelled child', {
- childName: runningChildName,
- error: patchErr instanceof Error ? patchErr.message : String(patchErr),
- })
- }
- enqueueSignal(runningChildName, {
- type: 'cancel',
- requestId: `replace-policy-${Date.now()}-${runningChildName}`,
- receivedAt: new Date().toISOString(),
- })
- })
- )
- }
-
- // 5. Resolve execution index and build child
- const executionIndex = await resolveExecutionIndex(customApi, parentName, namespace)
- const metadata = parent.metadata as { name: string; namespace: string; uid: string }
- const parentRecipe: ParentRecipe = {
- metadata: { name: metadata.name, namespace: metadata.namespace, uid: metadata.uid },
- spec: spec as ParentRecipe['spec'],
- }
- const child = buildChildRecipe(parentRecipe, executionIndex)
-
- // 6. Create child CRD — handle 409 from concurrent same-second triggers
- // (resolveExecutionIndex uses second-resolution timestamps, so two simultaneous
- // triggers can produce identical child names and collide on creation).
- try {
- await customApi.createNamespacedCustomObject({
- group: CRD_GROUP,
- version: CRD_VERSION,
- namespace,
- plural: WORKFLOWRECIPE_PLURAL,
- body: child,
- })
- } catch (err: unknown) {
- if (getErrorCode(err) === 409) {
- return {
- status: 409,
- body: {
- error:
- 'Concurrent trigger conflict — a child with this execution index already exists. Retry after a moment.',
- },
- }
- }
- throw err
- }
-
- // 7. Best-effort history pruning
- const limits: HistoryLimits = {
- successfulHistoryLimit: scheduling.successfulHistoryLimit ?? 3,
- failedHistoryLimit: scheduling.failedHistoryLimit ?? 1,
- }
- try {
- await pruneHistory(customApi, parentName, namespace, limits)
- } catch {
- // Best-effort — do not fail the trigger on pruning errors
- }
-
- const childMeta = child.metadata as Record<string, unknown>
- return { status: 202, body: { childName: childMeta.name } }
-}
diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.ts
index 4adb41453..d9b5d1754 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts
@@ -148,7 +148,6 @@ describe('WorkflowReconciler.reconcileDelete — orphaned Service cleanup', () =
signCoordinatorToMcpHostToken: vi.fn().mockResolvedValue('coordinator-mcp-host-token'),
signCustomCoordinatorToWrcToken: vi.fn().mockResolvedValue('custom-coordinator-wrc-token'),
signCoordinatorToWrcToken: vi.fn().mockResolvedValue('coordinator-wrc-token'),
- signCronJobTriggerToken: vi.fn().mockResolvedValue('cronjob-trigger-token'),
}
const deps = {
@@ -303,6 +302,95 @@ describe('WorkflowReconciler.reconcileDelete — orphaned Service cleanup', () =
)
})
+ it('mints exactly read scope when a recipe mount is read-only', async () => {
+ const reconciler = new WorkflowReconciler(deps)
+
+ await reconciler.ensureMcpHostRuntimeCredentials(sandboxNamespace, 'read-mount-recipe', {
+ steps: [{ id: 'step-1', instruction: 'read mounted inputs' }],
+ gfs: {
+ mounts: [{ drive: 'main', target: 'inputs', scopes: ['gfs.read'] }],
+ },
+ })
+
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledTimes(1)
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'read-mount-recipe',
+ { scopes: ['gfs.read'] }
+ )
+ })
+
+ it('keeps the read ceiling and adds write when a recipe mount is write-only', async () => {
+ const reconciler = new WorkflowReconciler(deps)
+
+ await reconciler.ensureMcpHostRuntimeCredentials(sandboxNamespace, 'write-mount-recipe', {
+ steps: [{ id: 'step-1', instruction: 'write mounted outputs' }],
+ gfs: {
+ mounts: [{ drive: 'main', target: 'outputs', scopes: ['gfs.write'] }],
+ },
+ })
+
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledTimes(1)
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'write-mount-recipe',
+ { scopes: ['gfs.read', 'gfs.write'] }
+ )
+ })
+
+ it('orders and de-duplicates read-write mount scopes before minting', async () => {
+ const reconciler = new WorkflowReconciler(deps)
+
+ await reconciler.ensureMcpHostRuntimeCredentials(sandboxNamespace, 'read-write-mount-recipe', {
+ steps: [{ id: 'step-1', instruction: 'read and write mounted content' }],
+ gfs: {
+ mounts: [
+ {
+ drive: 'main',
+ target: 'workspace',
+ scopes: ['gfs.write', 'gfs.read', 'gfs.write'],
+ },
+ ],
+ },
+ })
+
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledTimes(1)
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'read-write-mount-recipe',
+ { scopes: ['gfs.read', 'gfs.write'] }
+ )
+ })
+
+ it('mints inherited child GFS scopes against the parent runtime identity', async () => {
+ const reconciler = new WorkflowReconciler(deps)
+
+ await reconciler.ensureMcpHostRuntimeCredentials(
+ sandboxNamespace,
+ 'child-run',
+ {
+ steps: [{ id: 'step-1', instruction: 'use the parent grant' }],
+ gfs: {
+ mounts: [
+ {
+ drive: 'main',
+ target: 'workspace',
+ scopes: ['gfs.read', 'gfs.write'],
+ },
+ ],
+ },
+ },
+ 'parent-recipe'
+ )
+
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledTimes(1)
+ expect(gfsBindingMocks.mintRecipeHostGfsToken).toHaveBeenCalledWith(
+ sandboxNamespace,
+ 'parent-recipe',
+ { scopes: ['gfs.read', 'gfs.write'] }
+ )
+ })
+
it('mints write-scoped GFS credentials when the recipe declares publish targets', async () => {
const reconciler = new WorkflowReconciler(deps)
@@ -730,6 +818,77 @@ describe('WorkflowReconciler.reconcileDelete — orphaned Service cleanup', () =
expect(podNames).not.toContain('agentic-recipe-coordinator')
})
+ it('preserves required toolChoice in the workflow config ConfigMap', async () => {
+ crashRecoveryMocks.getPodPhase.mockImplementation(async (_api, name: string) => {
+ if (name === 'tool-choice-recipe-workflow-output-anchor') return 'Running'
+ if (name === 'tool-choice-recipe-workflow-output-prepare') return 'Succeeded'
+ return undefined
+ })
+ mockMcpHostReadiness({ ready: false, phase: 'Pending' })
+ const reconciler = new WorkflowReconciler(deps)
+
+ await reconciler.reconcile(
+ 'tool-choice-recipe',
+ 'uid-tool-choice',
+ sandboxNamespace,
+ {
+ agent: { provider: 'openai', model: 'gpt-4.1' },
+ steps: [
+ {
+ id: 'use-gfs',
+ instruction: 'Use the available GFS tools',
+ toolChoice: 'required',
+ },
+ ],
+ },
+ { workflowExecution: { phase: 'initializing' } },
+ undefined,
+ 'tool-choice-recipe',
+ 'run-1'
+ )
+
+ const configMap = mockCoreApi.createNamespacedConfigMap.mock.calls
+ .map(call => call[0].body)
+ .find(body => body.metadata?.name === 'tool-choice-recipe-workflow-config')
+ const workflowConfig = JSON.parse(configMap.data['config.json'])
+
+ expect(workflowConfig.steps[0]).toMatchObject({
+ id: 'use-gfs',
+ toolChoice: 'required',
+ })
+ })
+
+ it('does not add toolChoice to workflow config steps when it is absent', async () => {
+ crashRecoveryMocks.getPodPhase.mockImplementation(async (_api, name: string) => {
+ if (name === 'default-tool-choice-recipe-workflow-output-anchor') return 'Running'
+ if (name === 'default-tool-choice-recipe-workflow-output-prepare') return 'Succeeded'
+ return undefined
+ })
+ mockMcpHostReadiness({ ready: false, phase: 'Pending' })
+ const reconciler = new WorkflowReconciler(deps)
+
+ await reconciler.reconcile(
+ 'default-tool-choice-recipe',
+ 'uid-default-tool-choice',
+ sandboxNamespace,
+ {
+ agent: { provider: 'openai', model: 'gpt-4.1' },
+ steps: [{ id: 'answer', instruction: 'Answer without a tool requirement' }],
+ },
+ { workflowExecution: { phase: 'initializing' } },
+ undefined,
+ 'default-tool-choice-recipe',
+ 'run-1'
+ )
+
+ const configMap = mockCoreApi.createNamespacedConfigMap.mock.calls
+ .map(call => call[0].body)
+ .find(body => body.metadata?.name === 'default-tool-choice-recipe-workflow-config')
+ const workflowConfig = JSON.parse(configMap.data['config.json'])
+
+ expect(workflowConfig.steps[0]).not.toHaveProperty('toolChoice')
+ })
+
it('preserves recovering while the mcp-host pod is not ready', async () => {
crashRecoveryMocks.getPodPhase.mockImplementation(async (_api, name: string) => {
if (name === 'agentic-recipe-workflow-output-anchor') return 'Running'
@@ -1263,6 +1422,26 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
expect(svcNames).toContain('wf-sdk-recipe-mcp-host')
})
+ it('leaves coordinator GFS NetworkPolicy ownership to the outer recipe reconciler', async () => {
+ const reconciler = new WorkflowReconciler(makeDeps())
+
+ await reconciler.reconcile(
+ 'sdk-recipe',
+ 'uid-sdk',
+ sandboxNamespace,
+ sdkSpec({ gfs: { publishTargets: [{ drive: 'main', target: 'outputs' }] } }),
+ { workflowExecution: { phase: 'initializing' } },
+ undefined,
+ 'sdk-recipe',
+ undefined
+ )
+
+ const npNames = mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls.map(
+ call => call[0].body.metadata.name
+ )
+ expect(npNames).not.toContain('sdk-recipe-coordinator-to-gfs')
+ })
+
it('creates eager mcp-host for SDK-only recipes without agentic steps', async () => {
const reconciler = new WorkflowReconciler(makeDeps())
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 8bdee251d..896be52a2 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -114,11 +114,7 @@ import {
deleteScheduling,
reconcileScheduling,
} from './schedulingHandler'
-import {
- buildMcpHostRuntimeTokenSecret,
- buildTriggerTokenSecret,
- createCoordinatorTokens,
-} from './secretFactory'
+import { buildMcpHostRuntimeTokenSecret, createCoordinatorTokens } from './secretFactory'
import { SNIPPET_RUN_KEYS } from './snippetRunSchema'
import {
CyclicDependencyError,
@@ -135,8 +131,6 @@ import {
} from './types'
import { validateWorkflowRecipeLimits } from './workflowLimits'
-const TRIGGER_TOKEN_NAMESPACE = 'control-plane'
-
const DEFAULT_WORKFLOW_OUTPUT_STORAGE_SIZE = '256Mi'
const WORKFLOW_OUTPUT_PVC_DELETE_WAIT_MS = 30_000
const WORKFLOW_OUTPUT_PVC_DELETE_POLL_MS = 1_000
@@ -1243,7 +1237,7 @@ export class WorkflowReconciler {
const coordinatorGfsToken = coordinatorGfsBinding ? coordinatorGfsBinding.token : undefined
// 1. Create coordinator token Secret
- const { secret: tokenSecret, cronJobTriggerToken } = await createCoordinatorTokens(
+ const tokenSecret = await createCoordinatorTokens(
recipeName,
this.deps.tokenFactory,
this.deps.config.sandboxNamespace,
@@ -1271,27 +1265,6 @@ export class WorkflowReconciler {
})
}
- // Create trigger token Secret in control-plane for CronJob access.
- // Uses a minimal-scope token (trigger_write only) — least privilege for the CronJob container.
- // Cross-namespace ownerRefs are not enforced by K8s GC; cleanup is in reconcileDelete().
- const triggerTokenSecret = buildTriggerTokenSecret(
- recipeName,
- cronJobTriggerToken,
- TRIGGER_TOKEN_NAMESPACE
- )
- const triggerSecretCreated = await this.createIfNotExists(
- () =>
- this.deps.coreApi.createNamespacedSecret({
- namespace: TRIGGER_TOKEN_NAMESPACE,
- body: triggerTokenSecret,
- }),
- `Secret "wf-${recipeName}-trigger-token" in ${TRIGGER_TOKEN_NAMESPACE}`
- )
- // Refresh stale tokens (1-hour TTL) so multi-hour schedules don't 401.
- if (!triggerSecretCreated) {
- await this.refreshTriggerTokenIfExpiring(recipeName, cronJobTriggerToken)
- }
-
if (needsMcpHost && !awaitsTriggeredRun) {
await this.ensureMcpHostSecrets(namespace, recipeName, runtimeScopeRecipeName, spec)
}
@@ -1603,6 +1576,7 @@ export class WorkflowReconciler {
runtime.pods.mcpHost!.workflowOutputSubPath,
effectiveWorkflowContextRefForSpec(recipeName, spec),
{
+ gfsScopes: coordinatorGfsScopes,
mountWorkflowOutput: runtime.pods.mcpHost!.mountWorkflowOutput,
workflowOutputScope: runtime.pods.mcpHost!.workflowOutputScope,
pluginWorkloadSdkEnabled:
@@ -2207,7 +2181,7 @@ export class WorkflowReconciler {
artifactReaderPort: 8080,
snippetRunnerPort: 8095,
includeMcpHost: false,
- includeCoordinatorGfs: workflowHasGfsPublishTargets(spec),
+ includeCoordinatorGfs: false,
includeArtifactReader: false,
includeSnippetRunner: hasSnippetHttpEgress,
coordinatorPublicHttpEgress: hasCustomCoordinatorHttpEgress,
@@ -2323,7 +2297,9 @@ export class WorkflowReconciler {
artifactReaderPort: 8080,
snippetRunnerPort: 8095,
includeMcpHost: runtime.network.includeMcpHost && mcpHostLaneLive,
- includeCoordinatorGfs: workflowHasGfsPublishTargets(spec),
+ // The outer WorkflowRecipe reconciler owns this declarative lane so it can
+ // revoke before phase short-circuits while gating creation on provenance.
+ includeCoordinatorGfs: false,
includeArtifactReader: runtime.network.includeArtifactReader && !awaitsTriggeredRun,
includeSnippetRunner: runtime.network.includeSnippetRunner && !awaitsTriggeredRun,
// Plugin Workload SDK (plan §6.1): open the SDK lane when the recipe
@@ -2937,19 +2913,6 @@ export class WorkflowReconciler {
})
),
},
- // No K8s-level schedule object to delete — `deleteScheduling()` at the
- // top of this method already cleared the `workflow_schedules` row.
- // Cross-namespace Secret (control-plane) has no ownerRef GC.
- {
- label: `Secret "wf-${recipeName}-trigger-token"`,
- run: () =>
- this.safeDelete(() =>
- this.deps.coreApi.deleteNamespacedSecret({
- name: `wf-${recipeName}-trigger-token`,
- namespace: TRIGGER_TOKEN_NAMESPACE,
- })
- ),
- },
]
// Child runs use the parent recipe's workflow output PVC, so deleting a
@@ -3753,6 +3716,7 @@ export class WorkflowReconciler {
.filter((x): x is { name: string; url: string } => x !== null),
...(s.allowedTools && { allowedTools: s.allowedTools }),
...(s.maxIterations && { maxIterations: s.maxIterations }),
+ ...(s.toolChoice !== undefined && { toolChoice: s.toolChoice }),
...(s.agent && {
agent: {
...(s.agent.provider && { provider: s.agent.provider }),
@@ -3918,41 +3882,6 @@ export class WorkflowReconciler {
}
}
- /** Replaces the trigger-token Secret if its JWT expires near the runtime refresh window. */
- private async refreshTriggerTokenIfExpiring(
- recipeName: string,
- freshToken: string
- ): Promise<void> {
- try {
- const existing = await this.deps.coreApi.readNamespacedSecret({
- name: `wf-${recipeName}-trigger-token`,
- namespace: TRIGGER_TOKEN_NAMESPACE,
- })
- const rawToken = existing.data?.['token']
- const storedToken = rawToken ? Buffer.from(rawToken, 'base64').toString('utf-8') : ''
- const exp = WorkflowReconciler.jwtExp(storedToken)
- const nowSecs = Math.floor(Date.now() / 1000)
- if (exp === 0 || exp - nowSecs < this.runtimeTokenRefreshBeforeSeconds) {
- await this.deps.coreApi.patchNamespacedSecret(
- {
- name: `wf-${recipeName}-trigger-token`,
- namespace: TRIGGER_TOKEN_NAMESPACE,
- body: { data: { token: Buffer.from(freshToken).toString('base64') } },
- },
- { middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')] }
- )
- this.log.info(
- `Refreshed trigger token for ${recipeName} (was expiring in ${exp - nowSecs}s)`
- )
- }
- } catch (err) {
- // Non-fatal: next reconcile will retry.
- this.log.error(`Failed to refresh trigger token for ${recipeName}`, {
- error: err instanceof Error ? err.message : String(err),
- })
- }
- }
-
/** Replaces coordinator JWTs in-place when either expires near the refresh window. */
private async refreshCoordinatorTokenIfExpiring(
recipeName: string,
diff --git a/workflow-recipes/test/integration/clerumRegistryClient.test.ts b/workflow-recipes/test/integration/clerumRegistryClient.test.ts
index ed0bda4a0..d731a4973 100644
--- a/workflow-recipes/test/integration/clerumRegistryClient.test.ts
+++ b/workflow-recipes/test/integration/clerumRegistryClient.test.ts
@@ -1,16 +1,17 @@
/**
* Integration tests for clerumRegistryClient against a live registry.
*
- * Requires a running registry server reachable at TEST_REGISTRY_URL
- * (any server implementing the registry contract — npm-style /:name and
- * OCI-style /api/v1/entries routes). Run locally:
+ * Run locally (boot evenfire-registry yourself first):
* docker run -d --name pg -e POSTGRES_PASSWORD=postgres -p 15432:5432 postgres:16-alpine
- * # Start your registry server (see your private deployment runbook for setup)
- * # then export the URL:
+ * cd ../evenfire-registry
+ * CLERUM_REGISTRY_DB_URL=postgres://postgres:[email protected]:15432/registry \
+ * CLERUM_REGISTRY_AUTH_ENABLED=false \
+ * PORT=18085 npm start &
+ * cd ../clerum/.claude/worktrees/feat-registry-consumer/workflow-recipes
* TEST_REGISTRY_URL=http://127.0.0.1:18085 npm test test/integration/clerumRegistryClient.test.ts
*
- * In CI: set TEST_REGISTRY_URL to point at a running registry server before
- * running this suite.
+ * In CI: the `registry-contract` job in clerum/.github/workflows/ci.yaml boots
+ * evenfire-registry as a sibling checkout and exports TEST_REGISTRY_URL.
*
* Skip when TEST_REGISTRY_URL is unset so `npm test` doesn't fail when a
* developer runs the full WRC suite without booting a registry.
diff --git a/workflow-recipes/tests/e2e/airtable-lifecycle.test.ts b/workflow-recipes/tests/e2e/airtable-lifecycle.test.ts
index 64567cb19..ad38aff89 100644
--- a/workflow-recipes/tests/e2e/airtable-lifecycle.test.ts
+++ b/workflow-recipes/tests/e2e/airtable-lifecycle.test.ts
@@ -281,7 +281,7 @@ describe('Airtable MCP Server - E2E Lifecycle', () => {
// E10.3: Pod Ready + Health check passing
// Note: In minikube without DOCR registry credentials, the image
- // us-central1-docker.pkg.dev/your-gcp-project/clerum/airtable-mcp-server:latest may fail to pull
+ // us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/airtable-mcp-server:latest may fail to pull
// (ImagePullBackOff). We attempt to wait but skip gracefully if image pull fails.
it(
'E10.3 — Pod Ready and MCP server healthy (skips if image unavailable)',
diff --git a/workflow-recipes/tests/e2e/mongodb-lifecycle.test.ts b/workflow-recipes/tests/e2e/mongodb-lifecycle.test.ts
index d0a935437..cb0caa0e1 100644
--- a/workflow-recipes/tests/e2e/mongodb-lifecycle.test.ts
+++ b/workflow-recipes/tests/e2e/mongodb-lifecycle.test.ts
@@ -43,7 +43,7 @@ const LOCAL_PORT = 18086
const MCP_REMOTE_PORT = 3000
const HEALTH_REMOTE_PORT = 3001
-// Expected MongoDB MCP tool names (from us-central1-docker.pkg.dev/your-gcp-project/clerum/mongodb-mcp-server:latest)
+// Expected MongoDB MCP tool names (from us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/mongodb-mcp-server:latest)
// Verified 2026-03-06: Server returns 15 READ-ONLY tools (no insert/update/delete)
// Actual tools: aggregate, collection-indexes, collection-schema, collection-storage-size,
// connect, count, db-stats, explain, export, find, list-collections,
diff --git a/workflow-recipes/tests/e2e/mongodb-statefulset-recipe.test.ts b/workflow-recipes/tests/e2e/mongodb-statefulset-recipe.test.ts
index c4e4c3947..3ba2c78b7 100644
--- a/workflow-recipes/tests/e2e/mongodb-statefulset-recipe.test.ts
+++ b/workflow-recipes/tests/e2e/mongodb-statefulset-recipe.test.ts
@@ -41,7 +41,7 @@ const LOCAL_PORT = 18086
const MCP_REMOTE_PORT = 3000
const HEALTH_REMOTE_PORT = 3001
-// Expected MongoDB MCP tool names (from us-central1-docker.pkg.dev/your-gcp-project/clerum/mongodb-mcp-server:latest)
+// Expected MongoDB MCP tool names (from us-central1-docker.pkg.dev/${GCP_PROJECT}/clerum/mongodb-mcp-server:latest)
// Verified 2026-03-06: Server returns 15 READ-ONLY tools (no insert/update/delete)
// Actual tools: aggregate, collection-indexes, collection-schema, collection-storage-size,
// connect, count, db-stats, explain, export, find, list-collections,
diff --git a/workflow-recipes/tests/e2e/package-lock.json b/workflow-recipes/tests/e2e/package-lock.json
index b3b227424..9567c650b 100644
--- a/workflow-recipes/tests/e2e/package-lock.json
+++ b/workflow-recipes/tests/e2e/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workflow-recipes-e2e",
- "version": "0.1.16",
+ "version": "0.1.17",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workflow-recipes-e2e",
- "version": "0.1.16",
+ "version": "0.1.17",
"devDependencies": {
"@types/node": "^20.10.0",
"typescript": "^5.3.0",
diff --git a/workflow-recipes/tests/e2e/package.json b/workflow-recipes/tests/e2e/package.json
index 95a9f6435..7785b2541 100644
--- a/workflow-recipes/tests/e2e/package.json
+++ b/workflow-recipes/tests/e2e/package.json
@@ -1,6 +1,6 @@
{
"name": "workflow-recipes-e2e",
- "version": "0.1.16",
+ "version": "0.1.17",
"private": true,
"description": "E2E tests for Workload Recipes Controller (minikube)",
"scripts": {
diff --git a/workflow-recipes/tests/unit/workflow/jwtTokenFactory.test.ts b/workflow-recipes/tests/unit/workflow/jwtTokenFactory.test.ts
index 160039fe7..e98cd0ad4 100644
--- a/workflow-recipes/tests/unit/workflow/jwtTokenFactory.test.ts
+++ b/workflow-recipes/tests/unit/workflow/jwtTokenFactory.test.ts
@@ -158,7 +158,6 @@ describe('JwtTokenFactory', () => {
'status_read',
'signal_read',
'health_read',
- 'trigger_write',
])
})
@@ -177,7 +176,6 @@ describe('JwtTokenFactory', () => {
'health_read',
])
expect(scopes).not.toContain('configure_model')
- expect(scopes).not.toContain('trigger_write')
})
// ─── Uninitialized factory rejects signing ───────────────────────────────
diff --git a/workflow-recipes/tests/unit/workflow/mcpServerRoutes.test.ts b/workflow-recipes/tests/unit/workflow/mcpServerRoutes.test.ts
new file mode 100644
index 000000000..b21c418b9
--- /dev/null
+++ b/workflow-recipes/tests/unit/workflow/mcpServerRoutes.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { exportPKCS8, exportSPKI, generateKeyPair } from 'jose'
+import type { AddressInfo } from 'node:net'
+import { ClerumMcpServer } from '../../../src/mcp/server'
+import { JwtTokenFactory } from '../../../src/workflow/jwtTokenFactory'
+import { initializePublicKey } from '../../../src/workflow/restEndpoints'
+
+describe('ClerumMcpServer workflow routes', () => {
+ let server: ClerumMcpServer | undefined
+
+ afterEach(async () => {
+ await server?.stop()
+ server = undefined
+ })
+
+ it('does not register the removed singular direct-trigger endpoint', async () => {
+ const { privateKey, publicKey } = await generateKeyPair('RS256', { extractable: true })
+ const privateKeyPem = await exportPKCS8(privateKey)
+ const publicKeyPem = await exportSPKI(publicKey)
+ const tokenFactory = new JwtTokenFactory(privateKeyPem)
+ await tokenFactory.initialize()
+ await initializePublicKey(publicKeyPem)
+ const token = await tokenFactory.signCoordinatorToWrcToken('my-recipe', 'sandbox-recipes')
+
+ const provider = {
+ getAllRecipes: vi.fn(() => []),
+ start: vi.fn(async () => undefined),
+ stop: vi.fn(async () => undefined),
+ getTokenFactory: vi.fn(() => tokenFactory),
+ getTraceReporter: vi.fn(() => null),
+ getDbRunProcessor: vi.fn(() => null),
+ }
+ const customApi = {
+ getNamespacedCustomObject: vi.fn(),
+ createNamespacedCustomObject: vi.fn(),
+ }
+
+ server = new ClerumMcpServer(
+ provider as never,
+ 0,
+ customApi as never,
+ 'control-plane',
+ undefined,
+ 'sandbox-recipes',
+ tokenFactory
+ )
+ await server.start()
+ const address = (
+ server as unknown as { httpServer: { address: () => AddressInfo | null } }
+ ).httpServer.address()
+ expect(address).not.toBeNull()
+
+ const response = await fetch(
+ `http://127.0.0.1:${address!.port}/api/v1/workflow/my-recipe/trigger`,
+ {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ },
+ body: '{}',
+ }
+ )
+
+ expect(response.status).toBe(404)
+ await expect(response.json()).resolves.toEqual({ error: 'Not found' })
+ expect(customApi.getNamespacedCustomObject).not.toHaveBeenCalled()
+ expect(customApi.createNamespacedCustomObject).not.toHaveBeenCalled()
+ })
+})
diff --git a/workflow-recipes/tests/unit/workflow/podFactory.mcpHostRuntimeEnvVars.test.ts b/workflow-recipes/tests/unit/workflow/podFactory.mcpHostRuntimeEnvVars.test.ts
index 3c5214d24..ca54e243f 100644
--- a/workflow-recipes/tests/unit/workflow/podFactory.mcpHostRuntimeEnvVars.test.ts
+++ b/workflow-recipes/tests/unit/workflow/podFactory.mcpHostRuntimeEnvVars.test.ts
@@ -148,6 +148,23 @@ describe('Pod Factory — mcpHost Runtime Env Vars', () => {
expect(volume!.emptyDir).toEqual({ sizeLimit: '16Mi' })
})
+ it('projects only the verified WorkflowRecipe GFS token scopes into the mcp-host pod', () => {
+ const scopedPod = buildMcpHostPod(
+ 'test-child-run',
+ mockAgent,
+ mockConfig,
+ 'test-recipe',
+ 'sandbox-recipes',
+ 'test-recipe-workflow-output',
+ undefined,
+ undefined,
+ { gfsScopes: ['gfs.read', 'gfs.write'], mountWorkflowOutput: false }
+ )
+
+ expect(envByName(scopedPod, 'MCP_HOST_GFS_SCOPES')?.value).toBe('gfs.read,gfs.write')
+ expect(envByName(mcpHostPod, 'MCP_HOST_GFS_SCOPES')).toBeUndefined()
+ })
+
it('mcp-host pod exposes the logical approval recipe name', () => {
const pod = buildMcpHostPod(
'test-child-run',
diff --git a/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts b/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts
index db26155b0..22af163d5 100644
--- a/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts
+++ b/workflow-recipes/tests/unit/workflow/restEndpoints.functional.test.ts
@@ -1687,47 +1687,6 @@ describe('getArtifact', () => {
})
})
-// ─── postTrigger legacy direct path ────────────────────────────────────────
-
-describe('postTrigger — legacy direct path', () => {
- const ORIGINAL_FLAG = process.env.WRC_ENABLE_LEGACY_DIRECT_TRIGGER
-
- afterEach(() => {
- if (ORIGINAL_FLAG === undefined) delete process.env.WRC_ENABLE_LEGACY_DIRECT_TRIGGER
- else process.env.WRC_ENABLE_LEGACY_DIRECT_TRIGGER = ORIGINAL_FLAG
- })
-
- it('is disabled by default so runtime triggers must use control-api broker', async () => {
- delete process.env.WRC_ENABLE_LEGACY_DIRECT_TRIGGER
- const api = makeCustomApi()
- const handlers = createWorkflowEndpointHandlers(api, 'sandbox-recipes')
-
- const result = await handlers.postTrigger(
- 'my-recipe',
- 'sandbox-recipes',
- makeClaims({ sub: 'cronjob', scopes: ['trigger_write'] })
- )
-
- expect(result.status).toBe(410)
- expect(result.body.error).toContain('control-api workflow broker')
- })
-
- it('returns precise 403 when a runtime token lacks trigger_write even if legacy trigger is disabled', async () => {
- delete process.env.WRC_ENABLE_LEGACY_DIRECT_TRIGGER
- const api = makeCustomApi()
- const handlers = createWorkflowEndpointHandlers(api, 'sandbox-recipes')
-
- const result = await handlers.postTrigger(
- 'my-recipe',
- 'sandbox-recipes',
- makeClaims({ sub: 'custom-coordinator', scopes: ['status_write', 'status_read'] })
- )
-
- expect(result.status).toBe(403)
- expect(result.body.error).toContain('trigger_write')
- })
-})
-
// ─── deleteArtifact (bulk) ─────────────────────────────────────────────────
describe('deleteArtifact — bulk artifact cleanup', () => {
diff --git a/workflow-recipes/tests/unit/workflow/triggerHandler.test.ts b/workflow-recipes/tests/unit/workflow/triggerHandler.test.ts
deleted file mode 100644
index 9956baf7e..000000000
--- a/workflow-recipes/tests/unit/workflow/triggerHandler.test.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-import { handleTrigger } from '../../../src/workflow/triggerHandler'
-
-function makeParentRecipe(overrides: Record<string, unknown> = {}) {
- return {
- metadata: { name: 'market-report', namespace: 'sandbox-recipes', uid: 'uid-123' },
- spec: {
- scheduling: {
- cron: '0 9 * * *',
- concurrencyPolicy: 'Forbid',
- successfulHistoryLimit: 3,
- failedHistoryLimit: 1,
- },
- steps: [{ id: 'fetch', instruction: 'Get data' }],
- agent: { model: 'gpt-4', provider: 'openai' },
- ...overrides,
- },
- }
-}
-
-function makeMockApi(parent: unknown | null, listItems: unknown[] = []) {
- return {
- getNamespacedCustomObject: parent
- ? vi.fn().mockResolvedValue(parent)
- : vi.fn().mockRejectedValue(Object.assign(new Error('not found'), { code: 404 })),
- listNamespacedCustomObject: vi.fn().mockResolvedValue({ items: listItems }),
- createNamespacedCustomObject: vi.fn().mockResolvedValue({}),
- patchNamespacedCustomObjectStatus: vi.fn().mockResolvedValue({}),
- deleteNamespacedCustomObject: vi.fn().mockResolvedValue({}),
- } as any
-}
-
-describe('handleTrigger', () => {
- it('returns 404 when parent not found', async () => {
- const api = makeMockApi(null)
- const result = await handleTrigger(api, 'missing', 'sandbox-recipes')
- expect(result.status).toBe(404)
- expect(result.body.error).toContain('not found')
- })
-
- it('returns 400 when parent has no scheduling', async () => {
- const parent = {
- metadata: { name: 'no-sched', namespace: 'ns', uid: 'u' },
- spec: { steps: [] },
- }
- const api = makeMockApi(parent)
- const result = await handleTrigger(api, 'no-sched', 'ns')
- expect(result.status).toBe(400)
- expect(result.body.error).toContain('spec.scheduling')
- })
-
- it('returns 409 when scheduling is suspended', async () => {
- const parent = makeParentRecipe()
- ;(parent.spec.scheduling as any).suspend = true
- const api = makeMockApi(parent)
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(409)
- expect(result.body.error).toContain('suspended')
- })
-
- it('creates child and returns 202 on proceed', async () => {
- const parent = makeParentRecipe()
- const api = makeMockApi(parent, []) // no running children
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(202)
- expect(result.body.childName).toMatch(/^market-report-\d{8}-\d{6}-\d{4}$/)
- expect(api.createNamespacedCustomObject).toHaveBeenCalledTimes(1)
- })
-
- it('returns 202 with skipped when Forbid and child running', async () => {
- const parent = makeParentRecipe()
- const runningChild = {
- metadata: { name: 'market-report-20260316-090000', namespace: 'sandbox-recipes' },
- status: { workflowExecution: { phase: 'running' } },
- }
- const api = makeMockApi(parent, [runningChild])
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(202)
- expect(result.body.skipped).toBe(true)
- expect(api.createNamespacedCustomObject).not.toHaveBeenCalled()
- })
-
- it('cancels running child on Replace policy', async () => {
- const parent = makeParentRecipe()
- ;(parent.spec.scheduling as any).concurrencyPolicy = 'Replace'
- const runningChild = {
- metadata: { name: 'market-report-old', namespace: 'sandbox-recipes' },
- status: { workflowExecution: { phase: 'running' } },
- }
- const api = makeMockApi(parent, [runningChild])
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(202)
- expect(result.body.childName).toBeDefined()
- // Should have patched running child to cancelled (now called with params + merge-patch options)
- expect(api.patchNamespacedCustomObjectStatus).toHaveBeenCalledWith(
- expect.objectContaining({
- name: 'market-report-old',
- body: expect.objectContaining({
- status: expect.objectContaining({
- workflowExecution: expect.objectContaining({ phase: 'cancelled' }),
- }),
- }),
- }),
- expect.objectContaining({ middleware: expect.any(Array) })
- )
- // And created a new child
- expect(api.createNamespacedCustomObject).toHaveBeenCalledTimes(1)
- })
-
- it('proceeds on Allow policy when below capacity', async () => {
- const parent = makeParentRecipe()
- ;(parent.spec.scheduling as any).concurrencyPolicy = 'Allow'
- const runningChild = {
- metadata: { name: 'market-report-r1', namespace: 'sandbox-recipes' },
- status: { workflowExecution: { phase: 'running' } },
- }
- const api = makeMockApi(parent, [runningChild])
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(202)
- expect(result.body.childName).toBeDefined()
- })
-
- it('does not fail when pruneHistory throws', async () => {
- const parent = makeParentRecipe()
- const api = makeMockApi(parent, [])
- // Make listNamespacedCustomObject fail on the second call (pruneHistory)
- let callCount = 0
- api.listNamespacedCustomObject = vi.fn().mockImplementation(() => {
- callCount++
- if (callCount <= 1) return Promise.resolve({ items: [] }) // resolveExecutionIndex
- throw new Error('prune fail')
- })
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(202) // Should still succeed
- })
-
- it('uses default concurrencyPolicy Forbid when not specified', async () => {
- const parent = makeParentRecipe()
- delete (parent.spec.scheduling as any).concurrencyPolicy
- const runningChild = {
- metadata: { name: 'r1', namespace: 'sandbox-recipes' },
- status: { workflowExecution: { phase: 'running' } },
- }
- const api = makeMockApi(parent, [runningChild])
- const result = await handleTrigger(api, 'market-report', 'sandbox-recipes')
- expect(result.status).toBe(202)
- expect(result.body.skipped).toBe(true) // Forbid default → skip
- })
-})
diff --git a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
index 7d1f563cb..396ab100a 100644
--- a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
@@ -97,7 +97,6 @@ function makeTokenFactory() {
signWrcArtifactToken: vi.fn().mockResolvedValue('wrc-artifact-token'),
signWrcArtifactDeleteToken: vi.fn().mockResolvedValue('wrc-artifact-delete-token'),
signCustomCoordinatorToWrcToken: vi.fn().mockResolvedValue('custom-coord-wrc-token'),
- signCronJobTriggerToken: vi.fn().mockResolvedValue('cronjob-trigger-token'),
}
}
@@ -4822,7 +4821,6 @@ describe('WorkflowReconciler — reconcile loop', () => {
// Coordinator tokens are persistent (Secret-mounted) → signed at reconcile time.
expect(tf.signCoordinatorToMcpHostToken).toHaveBeenCalled()
expect(tf.signCoordinatorToWrcToken).toHaveBeenCalled()
- expect(tf.signCronJobTriggerToken).toHaveBeenCalled()
// WRC→mcp-host configure/artifact tokens are no longer issued on reconcile —
// they are signed fresh per call by restEndpoints handlers.
expect(tf.signWrcConfigureToken).not.toHaveBeenCalled()
diff --git a/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts b/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts
index 80886a213..89e010ef0 100644
--- a/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts
+++ b/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts
@@ -75,6 +75,8 @@ const mockCustomApi = {
const mockNetworkingApi = {
createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
+ readNamespacedNetworkPolicy: vi.fn().mockRejectedValue({ code: 404 }),
+ replaceNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
deleteNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),
}
@@ -471,7 +473,9 @@ describe('Workflow Reconciler Bifurcation', () => {
message: 'Workflow trigger infrastructure registered',
skipStatusPatch: true,
})
- expect(validateWorkflowSpec).not.toHaveBeenCalled()
+ // The steady short-circuit still runs semantic preflight before deciding
+ // whether coordinator GFS egress is eligible; only the inner reconcile is skipped.
+ expect(validateWorkflowSpec).toHaveBeenCalledTimes(1)
expect(innerReconcile).not.toHaveBeenCalled()
})
@@ -598,6 +602,10 @@ describe('Workflow Reconciler Bifurcation', () => {
})
it('uses inherited child resources for templates without re-creating parent-owned resources', async () => {
+ const verifyWorkflowRunProvenance = vi.fn().mockResolvedValue('verified')
+ reconciler = new WorkflowRecipeReconciler(new k8s.KubeConfig(), undefined, {
+ verifyWorkflowRunProvenance,
+ })
const callOrder: string[] = []
mockCoreApi.createNamespacedSecret.mockImplementationOnce(async () => {
callOrder.push('secret')
@@ -640,7 +648,10 @@ describe('Workflow Reconciler Bifurcation', () => {
name: 'wf-db-run-00000000',
namespace: 'sandbox-recipes',
uid: 'uid-wf-db-run',
- labels: { 'clerum.io/parent-recipe': 'wf-db' },
+ labels: {
+ 'clerum.io/parent-recipe': 'wf-db',
+ 'clerum.io/workflow-run-id': '00000000-0000-4000-8000-000000000123',
+ },
annotations: { [INHERITED_PARENT_RESOURCES_ANNOTATION]: 'true' },
ownerReferences: [
{
@@ -685,6 +696,13 @@ describe('Workflow Reconciler Bifurcation', () => {
const result = await reconciler.reconcile(recipe)
expect(result.phase).toBe('deploying')
+ expect(verifyWorkflowRunProvenance).toHaveBeenCalledWith({
+ runId: '00000000-0000-4000-8000-000000000123',
+ parentNamespace: 'sandbox-recipes',
+ parentName: 'wf-db',
+ childNamespace: 'sandbox-recipes',
+ childName: 'wf-db-run-00000000',
+ })
expect(callOrder).toEqual(['statefulset', 'runtime'])
expect(mockCoreApi.createNamespacedSecret).not.toHaveBeenCalled()
const statefulSet = mockAppsApi.createNamespacedStatefulSet.mock.calls[0]?.[0].body
@@ -794,7 +812,9 @@ describe('Workflow Reconciler Bifurcation', () => {
expect(result.phase).toBe('failed')
expect(result.message).toBe('snippet postgres capability must declare access')
- expect(validateWorkflowSpec).toHaveBeenCalledTimes(1)
+ // Preflight runs once before GFS policy eligibility and again after instance
+ // assignment, when runtime Service names reflect the persisted mapping.
+ expect(validateWorkflowSpec).toHaveBeenCalledTimes(2)
expect(innerReconcile).not.toHaveBeenCalled()
// Two status patches reserve the name maps before preflight: workload
// instances and resource instances (issue #571). Neither creates real K8s