Skip to content

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

TypeScript

feat(gfs): per-agent GFS delegation — user-plane backend + desktop UI

Alfredo Lopezb4a4a33222da
diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.ts
index 42305a782..1ba8cccde 100644
--- a/control-api/src/routes/external/gfs.ts
+++ b/control-api/src/routes/external/gfs.ts
@@ -8,19 +8,25 @@ import {
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { GfsTreeError, clampLimit, decodeCursor, encodeCursor } from '../../gfs/tree.js'
+import { isValidHostSubjectId, makeHostSubjectId } from '../../gfs/hostSubject.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import {
type ExternalAuthedRequest,
requireValidExternalSessionToken,
} from '../../middleware/externalSessionAuth.js'
+import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'
import { rootLogger } from '../../observability/logger.js'
+import { getUserAgents } from '../../services/directory/index.js'
import {
+ GfsGrantError,
UUID_RE,
driveOf,
handleGrantDelete,
+ handleGrantListForCaller,
handleGrantWrite,
heldPermissions,
resolveCaller,
+ sendGfsGrantError,
} from '../gfs/grants.js'
import { handlePatch } from '../gfs/resources.js'
import { handleShareDelete, handleShareWrite } from '../gfs/shares.js'
@@ -75,6 +81,77 @@ async function attachExternalGfsCallerSubjects(
next()
}
+/**
+ * Indexes of well-formed host subjects in `values` that are NOT in
+ * `allowedHostIds`. Malformed entries (wrong shape, invalid host id) are
+ * deliberately skipped so `handleGrantWrite` keeps sole ownership of the
+ * `subjects_invalid` + `invalidIndexes` contract; only a syntactically valid
+ * host that simply is not the caller's is adjudicated here.
+ */
+export function foreignHostSubjectIndexes(
+ values: readonly unknown[],
+ allowedHostIds: ReadonlySet<string>
+): number[] {
+ const foreign: number[] = []
+ for (const [index, value] of values.entries()) {
+ if (typeof value !== 'object' || value === null) continue
+ const { type, id } = value as { type?: unknown; id?: unknown }
+ if (type !== 'host' || typeof id !== 'string' || !isValidHostSubjectId(id)) continue
+ if (!allowedHostIds.has(id)) foreign.push(index)
+ }
+ return foreign
+}
+
+/**
+ * User-plane eligibility: a folder owner may delegate only to agents in their
+ * own directory. The allowed set is derived from the SAME authorization
+ * boundary the agent catalog uses — `getUserAgents` (DB-only, no Kubernetes in
+ * the mutation path) — mapped to the exact `1st:<hostsNamespace>/<name>` ids
+ * `buildAgentDirectoryEntry` emits. Consequences: `3rd:` hosts and the legacy
+ * fleet-wide sentinel are foreign for every user; sentinel retirement stays on
+ * the DELETE `allowLegacyRetirement` path; an authorized-but-not-yet-reconciled
+ * agent is grantable (inert row, consistent with catalog semantics). The admin
+ * (operator) plane never runs this guard.
+ */
+async function assertHostTargetsWithinCallerAgents(
+ req: import('express').Request,
+ res: import('express').Response,
+ next: NextFunction
+): Promise<void> {
+ const externalReq = req as ExternalGfsRequest
+ const body = (externalReq.body ?? {}) as Record<string, unknown>
+ const plural = Array.isArray(body.subjects)
+ const values = plural
+ ? (body.subjects as unknown[])
+ : Object.prototype.hasOwnProperty.call(body, 'subject')
+ ? [body.subject]
+ : []
+ const probe = foreignHostSubjectIndexes(values, new Set())
+ if (probe.length === 0) {
+ // No well-formed host targets at all — nothing for this guard to decide.
+ next()
+ return
+ }
+ const { agentNames } = await getUserAgents(externalReq.externalAuth!.userId)
+ // makeHostSubjectId returns null for a name that cannot form a canonical
+ // host subject; such an agent is not grantable and never appears in the
+ // catalog either, so skipping it mirrors buildAgentDirectoryEntry exactly.
+ const allowed = new Set(
+ agentNames
+ .map(name => makeHostSubjectId('1st', config.hostsNamespace, name))
+ .filter((id): id is string => id !== null)
+ )
+ const foreign = foreignHostSubjectIndexes(values, allowed)
+ if (foreign.length > 0) {
+ sendGfsGrantError(
+ res,
+ new GfsGrantError(403, 'foreign_agent_forbidden', plural ? foreign : undefined)
+ )
+ return
+ }
+ next()
+}
+
/**
* End-user (folder-owner) gfs surface on the `/external` plane — the Session-JWT
* plane (external-rest-api ← desktop-app / profile-ui) of the platform's defined
@@ -97,6 +174,24 @@ export function createExternalGfsRouter(): Router {
// (x-user-session-token, forwarded by external-rest-api) is required.
router.use('/external/gfs', requireValidExternalSessionToken)
+ // Per-user token bucket on the DELEGATION plane only (grants + shares),
+ // mirroring the admin plane's grantsRateLimit but in a DISTINCT bucket so the
+ // two planes never share quota. requireValidExternalSessionToken runs at
+ // router level first, so externalAuth.userId is always present by the time the
+ // limiter keys; the no-user branch is therefore unreachable, but it returns a
+ // shared sentinel (never null) so the limiter fails CLOSED — per
+ // rateLimitMiddleware's guidance for strict enforcement — instead of the
+ // default fail-open, keeping this plane strictly metered under any future
+ // auth-ordering change.
+ const externalGrantsRateLimit = rateLimitMiddleware({
+ bucketType: 'gfs_grants_external',
+ maxPerMinute: 30,
+ getBucketKey: req => {
+ const userId = (req as ExternalAuthedRequest).externalAuth?.userId
+ return userId ? `gfsgrants-ext:${userId}` : 'gfsgrants-ext:__no_user__'
+ },
+ })
+
// ── token mint (mirror /external/rpc/token, but a gfs token sub=users.id) ──
router.post(
'/external/gfs/token',
@@ -126,23 +221,37 @@ export function createExternalGfsRouter(): Router {
// resolveCaller(req) reads req.externalAuth → user:<id> plus all active team
// memberships resolved here; assertMayGrant enforces no-escalation (a user may
// grant only bits it holds, within its subtree).
+ // The grants list is delegation metadata naming third-party subjects, so
+ // reading it requires the same manage_acl authority as mutating it
+ // (view-ACL = manage-ACL); handleGrantListForCaller enforces that.
+ router.get(
+ '/external/gfs/grants',
+ externalGrantsRateLimit,
+ asyncHandler(attachExternalGfsCallerSubjects),
+ asyncHandler(handleGrantListForCaller)
+ )
router.put(
'/external/gfs/grants',
+ externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
+ asyncHandler(assertHostTargetsWithinCallerAgents),
asyncHandler(handleGrantWrite)
)
router.delete(
'/external/gfs/grants/:id',
+ externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleGrantDelete)
)
router.post(
'/external/gfs/shares',
+ externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleShareWrite)
)
router.delete(
'/external/gfs/shares/:id',
+ externalGrantsRateLimit,
asyncHandler(attachExternalGfsCallerSubjects),
asyncHandler(handleShareDelete)
)
diff --git a/control-api/src/routes/gfs/grants.ts b/control-api/src/routes/gfs/grants.ts
index 785ca1630..f745aaf17 100644
--- a/control-api/src/routes/gfs/grants.ts
+++ b/control-api/src/routes/gfs/grants.ts
@@ -852,35 +852,80 @@ export function registerGfsGrantRoutes(router: Router): void {
)
}
+export interface GfsGrantListItem {
+ id: string
+ drive: string
+ resourceId: string
+ subject: { type: string; id?: string }
+ permissions: string[]
+ inherit: boolean
+}
+
+/** One resource's grant rows in the canonical list shape (`id` powers revoke). */
+export async function queryGrantItems(
+ drive: string,
+ resourceId: string
+): Promise<GfsGrantListItem[]> {
+ 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]
+ )
+ return (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),
+ }
+ })
+}
+
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),
- }
- }),
- })
+ res.status(200).json({ items: await queryGrantItems(drive, resourceId) })
+ } catch (err) {
+ if (err instanceof GfsGrantError) {
+ sendGfsGrantError(res, err)
+ return
+ }
+ throw err
+ }
+}
+
+/**
+ * Non-operator grants listing for the external (folder-owner) plane. The ACL of
+ * a resource is delegation metadata naming third-party subjects, so viewing it
+ * requires the same authority as changing it: `manage_acl` on the resource,
+ * held directly or through an inheriting ancestor (view-ACL = manage-ACL).
+ * A missing resource yields the same 403 — no existence oracle.
+ */
+export async function handleGrantListForCaller(
+ req: Request,
+ res: import('express').Response
+): Promise<void> {
+ try {
+ const caller = resolveCaller(req)
+ const { drive, resourceId } = permissionReadFilter(req)
+ if (!caller.isOperator) {
+ const held = await heldPermissions(pool, caller, drive, resourceId)
+ if (!held.includes('manage_acl')) {
+ throw new GfsGrantError(403, 'manage_acl_required')
+ }
+ }
+ res.status(200).json({ items: await queryGrantItems(drive, resourceId) })
} catch (err) {
if (err instanceof GfsGrantError) {
sendGfsGrantError(res, err)
diff --git a/control-api/test/routes.externalGfs.test.ts b/control-api/test/routes.externalGfs.test.ts
index d2f4683b2..3adcc6818 100644
--- a/control-api/test/routes.externalGfs.test.ts
+++ b/control-api/test/routes.externalGfs.test.ts
@@ -30,6 +30,8 @@ vi.mock('../src/config.js', () => ({
config: {
gfscBaseUrl: 'http://gfsc.gfs.svc:8087',
gfscWriteBaseUrl: 'http://gfsc-writer.gfs.svc:8087',
+ // The eligibility guard maps caller agent names to 1st:<hostsNamespace>/<name>.
+ hostsNamespace: 'mcp-host',
},
}))
vi.mock('../src/db.js', () => ({
@@ -92,6 +94,24 @@ async function buildOperatorShareApp() {
return app
}
+// Admin (Control UI) grants plane — the SAME grant surface the external plane
+// reuses, but mounted behind its OWN operator rate limiter (bucketType
+// `gfs_grants`, key `gfsgrants:<sub>`). Used to prove the two planes never share
+// a rate-limit bucket for the same subject id.
+async function buildAdminGrantsApp(sub: string) {
+ const { registerGfsGrantRoutes } = await import('../src/routes/gfs/grants.js')
+ const app = express()
+ app.use(express.json())
+ app.use((req, _res, next) => {
+ ;(req as typeof req & { adminAuth: { sub: string } }).adminAuth = { sub }
+ next()
+ })
+ const router = express.Router()
+ registerGfsGrantRoutes(router)
+ app.use(router)
+ return app
+}
+
beforeEach(() => {
mockVerifyExternalSessionToken.mockReset()
mockSignGfsToken.mockReset()
@@ -130,8 +150,28 @@ function combinedAuthorityRow(
}
/** Route the grant engine's queries by SQL shape. */
-function dbReturning(grants: Record<string, unknown>[]) {
+function dbReturning(
+ grants: Record<string, unknown>[],
+ opts: {
+ callerAgentNames?: string[]
+ grantListRows?: Record<string, unknown>[]
+ rateLimitCount?: number
+ } = {}
+) {
+ // The external-plane eligibility guard resolves the caller's own agents via
+ // getUserAgents (user_agents table). Default matches H1's name so existing
+ // host-grant fixtures represent an in-directory agent.
+ const callerAgentNames = opts.callerAgentNames ?? ['agent-a']
mockQuery.mockImplementation(async (text: string, values?: unknown[]) => {
+ if (text.includes('FROM user_agents')) {
+ return { rows: callerAgentNames.map(name => ({ agent_name: name })) }
+ }
+ if (text.includes('rate_limit_buckets')) {
+ return { rows: [{ count: opts.rateLimitCount ?? 1 }] }
+ }
+ if (text.includes('ORDER BY created_at ASC, id ASC')) {
+ return { rows: opts.grantListRows ?? [] }
+ }
if (text.includes('authority_grants AS') && text.includes('authority_shares AS')) {
return combinedAuthorityRow(grants, values)
}
@@ -1090,3 +1130,190 @@ describe('GET /external/gfs/resources', () => {
])
})
})
+
+describe('per-agent delegation surface (guard + list + rate limit)', () => {
+ const authority = (permissions: string[], opts: Parameters<typeof dbReturning>[1] = {}) =>
+ dbReturning(
+ [
+ {
+ subject_type: 'user',
+ subject_id: U1,
+ resource_id: R,
+ permissions,
+ inherit: false,
+ },
+ ],
+ opts
+ )
+ const putGrants = (app: express.Express, body: Record<string, unknown>) =>
+ request(app)
+ .put('/external/gfs/grants')
+ .set('x-user-session-token', 'sess')
+ .send({ resourceId: R, permissions: ['read'], inherit: true, ...body })
+
+ it('rejects a single valid-but-foreign host without indexes and writes nothing', async () => {
+ auth()
+ authority(['manage_acl', 'read'], { callerAgentNames: ['other-agent'] })
+ const app = await buildApp()
+ const res = await putGrants(app, { subject: { type: 'host', id: H1 } })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('foreign_agent_forbidden')
+ expect(res.body.invalidIndexes).toBeUndefined()
+ expect(
+ mockQuery.mock.calls.filter(call => String(call[0]).includes('INSERT INTO gfs_grants'))
+ ).toHaveLength(0)
+ })
+
+ it('rejects a plural body with the foreign host indexes and writes nothing', async () => {
+ auth()
+ authority(['manage_acl', 'read'], { callerAgentNames: ['agent-b'] })
+ const app = await buildApp()
+ const res = await putGrants(app, {
+ subjects: [
+ { type: 'user', id: U2 },
+ { type: 'host', id: H1 },
+ { type: 'host', id: '1st:mcp-host/agent-b' },
+ ],
+ })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('foreign_agent_forbidden')
+ expect(res.body.invalidIndexes).toEqual([1])
+ expect(
+ mockQuery.mock.calls.filter(call => String(call[0]).includes('INSERT INTO gfs_grants'))
+ ).toHaveLength(0)
+ })
+
+ it('leaves malformed host ids to the subjects_invalid contract', async () => {
+ auth()
+ authority(['manage_acl', 'read'], { callerAgentNames: [] })
+ const app = await buildApp()
+ const res = await putGrants(app, { subjects: [{ type: 'host', id: 'not-a-host' }] })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('subjects_invalid')
+ })
+
+ it('lists id-bearing grant rows for a manage_acl holder', async () => {
+ auth()
+ authority(['manage_acl'], {
+ grantListRows: [
+ {
+ id: 'aaaa1111-0000-4000-8000-000000000001',
+ drive: 'main',
+ resource_id: R,
+ subject_type: 'host',
+ subject_id: H1,
+ permissions: ['read', 'write'],
+ inherit: true,
+ },
+ ],
+ })
+ const app = await buildApp()
+ const res = await request(app)
+ .get('/external/gfs/grants')
+ .query({ drive: 'main', resourceId: R })
+ .set('x-user-session-token', 'sess')
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ items: [
+ {
+ id: 'aaaa1111-0000-4000-8000-000000000001',
+ drive: 'main',
+ resourceId: R,
+ subject: { type: 'host', id: H1 },
+ permissions: ['read', 'write'],
+ inherit: true,
+ },
+ ],
+ })
+ })
+
+ it('denies the grants list to a caller without manage_acl', async () => {
+ auth()
+ authority(['read', 'write'])
+ const app = await buildApp()
+ const res = await request(app)
+ .get('/external/gfs/grants')
+ .query({ drive: 'main', resourceId: R })
+ .set('x-user-session-token', 'sess')
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('manage_acl_required')
+ })
+
+ it('answers an unknown resource with the same 403 (no existence oracle)', async () => {
+ auth()
+ dbReturning([])
+ const app = await buildApp()
+ const res = await request(app)
+ .get('/external/gfs/grants')
+ .query({ drive: 'main', resourceId: R2 })
+ .set('x-user-session-token', 'sess')
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('manage_acl_required')
+ })
+
+ it('rate limits the delegation plane per user with retryAfterSeconds', async () => {
+ auth()
+ authority(['manage_acl', 'read'], { rateLimitCount: 31 })
+ const app = await buildApp()
+ const res = await putGrants(app, { subject: { type: 'user', id: U2 } })
+ expect(res.status).toBe(429)
+ expect(res.body.error).toBe('Too Many Requests')
+ expect(res.body.retryAfterSeconds).toBeGreaterThanOrEqual(1)
+ const bucketCall = mockQuery.mock.calls.find(call =>
+ String(call[0]).includes('rate_limit_buckets')
+ )
+ expect(bucketCall?.[1]?.[0]).toBe(`gfsgrants-ext:${U1}`)
+ })
+
+ it('keys the external delegation plane in a bucket DISTINCT from the admin plane for the same subject', async () => {
+ // Same subject id (U1) is driven through BOTH planes; each plane's own
+ // production getBucketKey closure runs and its bucket key is captured from
+ // the rate_limit_buckets INSERT ([bucketKey, windowStartMs] → values[0]).
+ // The PK of rate_limit_buckets is (bucket_key, window_start_ms), so distinct
+ // keys are distinct token buckets — exhausting one can never throttle the
+ // other for the same subject.
+ auth()
+ authority(['manage_acl', 'read'])
+ const externalApp = await buildApp()
+ await putGrants(externalApp, { subject: { type: 'user', id: U2 } })
+ const externalKey = mockQuery.mock.calls.find(call =>
+ String(call[0]).includes('rate_limit_buckets')
+ )?.[1]?.[0]
+
+ // Admin (operator) grants plane keyed off adminAuth.sub === U1 (same id).
+ mockQuery.mockClear()
+ const adminApp = await buildAdminGrantsApp(U1)
+ await request(adminApp).get('/gfs/grants').query({ drive: 'main', resourceId: R })
+ const adminKey = mockQuery.mock.calls.find(call =>
+ String(call[0]).includes('rate_limit_buckets')
+ )?.[1]?.[0]
+
+ // Both planes emitted a bucket key for the same subject…
+ expect(externalKey).toBe(`gfsgrants-ext:${U1}`)
+ expect(adminKey).toBe(`gfsgrants:${U1}`)
+ // …and they are DISTINCT buckets (never collide). The `-ext` separator means
+ // the external key does not fall under the admin `gfsgrants:` namespace.
+ expect(externalKey).not.toBe(adminKey)
+ expect(String(externalKey).startsWith('gfsgrants-ext:')).toBe(true)
+ expect(String(adminKey).startsWith('gfsgrants-ext:')).toBe(false)
+ expect(String(adminKey).startsWith('gfsgrants:')).toBe(true)
+ })
+
+ it('adjudicates only well-formed foreign hosts in foreignHostSubjectIndexes', async () => {
+ const { foreignHostSubjectIndexes } = await import('../src/routes/external/gfs.js')
+ const allowed = new Set([H1])
+ expect(
+ foreignHostSubjectIndexes(
+ [
+ { type: 'host', id: H1 },
+ { type: 'host', id: '3rd:sandbox-recipes/tool' },
+ { type: 'host', id: '1st:mcp-host/standalone' },
+ { type: 'user', id: U2 },
+ { type: 'host', id: 'garbage' },
+ null,
+ ],
+ allowed
+ )
+ ).toEqual([1, 2])
+ })
+})
diff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.ts
index a3955c0ad..aaec072fc 100644
--- a/desktop-app/src/__tests__/appService.gfs.test.ts
+++ b/desktop-app/src/__tests__/appService.gfs.test.ts
@@ -20,7 +20,8 @@ function gfsService() {
resourceId: string,
subjectKey: string,
bits: string[],
- drive?: string
+ drive?: string,
+ inherit?: boolean
) => Promise<void>
createGfsShare: (resourceId: string, subjectKey: string, drive?: string) => Promise<void>
}
@@ -60,20 +61,53 @@ describe('AppService GFS delegation subject boundary', () => {
)
})
- it.each(['operator:', 'host:mcp-host/standalone', 'context:engineering'])(
+ it('passes a managed host grant subject with inherit to the user-plane GFS client', async () => {
+ const service = gfsService()
+
+ await service.grantGfs(RESOURCE_ID, 'host:1st:mcp-host/chatllm', ['read'], 'main', true)
+
+ expect(service.gfsClient.grant).toHaveBeenCalledWith(
+ {
+ resourceId: RESOURCE_ID,
+ drive: 'main',
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: true,
+ },
+ 'session-token'
+ )
+ })
+
+ it.each(['operator:', 'context:engineering'])(
'rejects reserved subject %s before calling the user-plane GFS client',
async subjectKey => {
const service = gfsService()
await expect(service.grantGfs(RESOURCE_ID, subjectKey, ['read'], 'main')).rejects.toThrow(
- 'subject must be user:<id> or team:<id>'
+ 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>'
)
await expect(service.createGfsShare(RESOURCE_ID, subjectKey, 'main')).rejects.toThrow(
- 'subject must be user:<id> or team:<id>'
+ 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>'
)
expect(service.gfsClient.grant).not.toHaveBeenCalled()
expect(service.gfsClient.createShare).not.toHaveBeenCalled()
}
)
+
+ it('rejects the party-less legacy sentinel host key before calling the GFS client', async () => {
+ const service = gfsService()
+
+ // `host:mcp-host/standalone` has no 1st|3rd party prefix — the legacy
+ // fleet-wide sentinel form stays rejected by the host grammar shape check.
+ await expect(
+ service.grantGfs(RESOURCE_ID, 'host:mcp-host/standalone', ['read'], 'main')
+ ).rejects.toThrow('host subject must be host:<party>:<ns>/<name>')
+ await expect(
+ service.createGfsShare(RESOURCE_ID, 'host:mcp-host/standalone', 'main')
+ ).rejects.toThrow('host subject must be host:<party>:<ns>/<name>')
+
+ expect(service.gfsClient.grant).not.toHaveBeenCalled()
+ expect(service.gfsClient.createShare).not.toHaveBeenCalled()
+ })
})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 26038d662..98a1f0cbf 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -27,6 +27,7 @@ import {
import { TokenStore } from './tokenStore.js'
import {
AccessCatalog,
+ AgentWithMcpServers,
ApprovalDecisionResult,
ContextBreakdownResult,
DependencyHealth,
@@ -854,14 +855,50 @@ export class AppService {
return delegationAffordances(new Set(held), isOperator)
}
- /** Delegate a grant (subjectKey → structured subject). No-escalation is server-side. */
- async grantGfs(resourceId: string, subjectKey: string, bits: string[], drive?: string) {
+ /**
+ * Delegate a grant (subjectKey → structured subject). No-escalation is
+ * server-side. `inherit` is renderer-driven (agent grants on directories
+ * default it ON so contained files are covered); omitted means the client's
+ * historical `false`.
+ */
+ async grantGfs(
+ resourceId: string,
+ subjectKey: string,
+ bits: string[],
+ drive?: string,
+ inherit?: boolean
+ ) {
await this.gfsClient.grant(
- { resourceId, drive, subject: parseSubjectKey(subjectKey), permissions: bits },
+ { resourceId, drive, subject: parseSubjectKey(subjectKey), permissions: bits, inherit },
this.requireSessionToken()
)
}
+ /**
+ * List a resource's ACL rows for the Manage modal. The row `id` is the revoke
+ * handle (the grant PUT response carries no ids). View-ACL = manage-ACL is
+ * enforced server-side; a caller without manage_acl gets the API's 403.
+ */
+ async listGfsGrants(resourceId: string, drive?: string) {
+ return this.gfsClient.listGrants({ resourceId, drive }, this.requireSessionToken())
+ }
+
+ /** Revoke an ACL row by id (id learned from listGfsGrants). */
+ async revokeGfsGrant(grantId: string) {
+ await this.gfsClient.revokeGrant(grantId, this.requireSessionToken())
+ }
+
+ /**
+ * The caller's own agents with their canonical GFS host subjects — the grant
+ * targets for per-agent delegation. Served fresh from external-rest-api
+ * GET /me/agents on every call, NOT from the cached name-based AccessCatalog
+ * (which has no gfsSubject and would go stale across reconciliations).
+ */
+ async listMyAgents(): Promise<AgentWithMcpServers[]> {
+ const result = await this.authClient.getMyAgents(this.requireSessionToken())
+ return Array.isArray(result.agents) ? result.agents : []
+ }
+
/**
* Create a read share for a subject. A "share" grants read access (the minimal
* shared capability); the no-escalation engine still requires the caller hold
diff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.ts
index e6028867a..9d8584afd 100644
--- a/desktop-app/src/gfs/uriHandler.ts
+++ b/desktop-app/src/gfs/uriHandler.ts
@@ -128,6 +128,7 @@ export interface GfsAccessibleResourcesPage {
export type GfsSubject =
| { type: 'user'; id: string }
| { type: 'team'; id: string }
+ | { type: 'host'; id: string }
| { type: 'operator' }
export interface GfsGrantInput {
@@ -146,6 +147,21 @@ export interface GfsShareInput {
includeDescendants?: boolean
}
+/**
+ * One ACL row as GET /me/gfs/grants returns it (control-api queryGrantItems).
+ * The `id` is the revoke handle — the grant PUT response carries no ids, so the
+ * UI must list-after-write to learn them. `subject.id` is absent for the
+ * operator sentinel row.
+ */
+export interface GfsGrantListItem {
+ id: string
+ drive: string
+ resourceId: string
+ subject: { type: string; id?: string }
+ permissions: string[]
+ inherit: boolean
+}
+
/** Bits the caller holds on a resource, as the affordances route reports them. */
export interface GfsHeldAffordances {
held: string[]
@@ -183,6 +199,18 @@ export interface GfsDeleteInput {
const DEFAULT_DRIVE = 'main'
const TRANSPORT_TOKEN_FIELD = ['tok', 'en'].join('') as 'token'
+/** Grant ids name gfs_grants rows (control-api routes/gfs/grants.ts UUID_RE). */
+const GRANT_ID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/
+
+/**
+ * Shape of a managed host subject id: `<party>:<namespace>/<name>` with k8s
+ * DNS-1123 names (mirrors control-api src/gfs/hostSubject.ts
+ * isValidHostSubjectId). Input shaping only — the server re-validates and
+ * additionally enforces that the target is in the caller's own agent directory.
+ */
+const HOST_SUBJECT_ID_RE =
+ /^(1st|3rd):[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\/[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/
+
function joinUrl(base: string, path: string): string {
return `${base.replace(/\/+$/, '')}${path}`
}
@@ -395,6 +423,46 @@ export class GfsClient {
)
}
+ /**
+ * List a resource's ACL rows ("Who has access"). Server-side, viewing the
+ * ACL requires the same authority as changing it (manage_acl, direct or via
+ * an inheriting ancestor) — a caller without it gets the API's 403, never a
+ * silent empty list. NOT enveloped: the route returns `{items}` directly.
+ */
+ async listGrants(
+ input: { resourceId: string; drive?: string },
+ token: string
+ ): Promise<GfsGrantListItem[]> {
+ const q = new URLSearchParams()
+ q.set('drive', input.drive ?? DEFAULT_DRIVE)
+ q.set('resourceId', input.resourceId)
+ const payload = await this.transport.requestJson<{ items: GfsGrantListItem[] }>(
+ 'GET',
+ joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/grants?' + q.toString()),
+ { token }
+ )
+ if (!payload || typeof payload !== 'object' || !Array.isArray(payload.items)) {
+ throw new GfsUriError('unexpected gfs grants response: missing items array')
+ }
+ return payload.items
+ }
+
+ /**
+ * Revoke a grant by its ACL row id (learned from listGrants — the grant PUT
+ * response carries no ids). The id is validated as a UUID before the URL is
+ * built so a malformed value can never become a path segment.
+ */
+ async revokeGrant(grantId: string, token: string): Promise<void> {
+ if (!GRANT_ID_RE.test(grantId)) {
+ throw new GfsUriError(`grant id must be a UUID: ${JSON.stringify(grantId)}`)
+ }
+ await this.transport.requestJson(
+ 'DELETE',
+ joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/grants/${encodeURIComponent(grantId)}`),
+ { token }
+ )
+ }
+
/** Create a URI share for a subject (same no-escalation engine, isShare=true). */
async createShare(input: GfsShareInput, token: string): Promise<void> {
await this.transport.requestJson(
@@ -437,20 +505,35 @@ export class GfsClient {
/**
* Parse a Desktop folder-owner delegation subject. The user plane can delegate
- * only to visible users or teams; operator/host/context targets are reserved for
- * the operator/provisioner contracts and are rejected before the API call. The
- * server re-validates; this is an input-shaping convenience, not a trust point.
+ * to visible users, teams, or the caller's own managed agents
+ * (`host:<party>:<ns>/<name>` — the first `:` splits the type, so the id keeps
+ * its canonical `<party>:<ns>/<name>` form). Operator/context targets stay
+ * reserved for the operator/provisioner contracts and are rejected before the
+ * API call. The server re-validates (grammar AND agent-directory ownership);
+ * this is an input-shaping convenience, not a trust point.
*/
export function parseSubjectKey(key: string): GfsSubject {
const trimmed = key.trim()
const sep = trimmed.indexOf(':')
if (sep <= 0) {
- throw new GfsUriError(`subject must be user:<id> or team:<id>: ${JSON.stringify(key)}`)
+ throw new GfsUriError(
+ `subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>: ${JSON.stringify(key)}`
+ )
}
const type = trimmed.slice(0, sep)
const id = trimmed.slice(sep + 1)
+ if (type === 'host') {
+ if (!HOST_SUBJECT_ID_RE.test(id)) {
+ throw new GfsUriError(
+ `host subject must be host:<party>:<ns>/<name> (party 1st|3rd, k8s names): ${JSON.stringify(key)}`
+ )
+ }
+ return { type, id }
+ }
if ((type !== 'user' && type !== 'team') || id.length === 0) {
- throw new GfsUriError(`subject must be user:<id> or team:<id>: ${JSON.stringify(key)}`)
+ throw new GfsUriError(
+ `subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>: ${JSON.stringify(key)}`
+ )
}
return { type, id }
}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index ee9ac25e2..d9c124ae0 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -389,19 +389,42 @@ export function registerIpcHandlers(service: AppService): void {
'gfs:grant',
async (
event,
- payload: { resourceId: string; subjectKey: string; bits: string[]; drive?: string }
+ payload: {
+ resourceId: string
+ subjectKey: string
+ bits: string[]
+ drive?: string
+ inherit?: boolean
+ }
) => {
assertTrustedSender(event)
const bits = Array.isArray(payload?.bits) ? payload.bits.map(sanitizeString) : []
const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
+ const inherit = payload?.inherit
+ if (inherit !== undefined && typeof inherit !== 'boolean') {
+ throw new Error('inherit must be a boolean')
+ }
return service.grantGfs(
sanitizeString(payload?.resourceId),
sanitizeString(payload?.subjectKey),
bits,
- drive
+ drive,
+ inherit
)
}
)
+ ipcMain.handle(
+ 'gfs:listGrants',
+ async (event, payload: { resourceId: string; drive?: string }) => {
+ assertTrustedSender(event)
+ const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
+ return service.listGfsGrants(sanitizeString(payload?.resourceId), drive)
+ }
+ )
+ ipcMain.handle('gfs:revokeGrant', async (event, payload: { grantId: string }) => {
+ assertTrustedSender(event)
+ return service.revokeGfsGrant(sanitizeString(payload?.grantId))
+ })
ipcMain.handle(
'gfs:createShare',
async (event, payload: { resourceId: string; subjectKey: string; drive?: string }) => {
@@ -414,6 +437,13 @@ export function registerIpcHandlers(service: AppService): void {
)
}
)
+ // The caller's own agents with canonical GFS host subjects (grant targets for
+ // per-agent delegation). Dedicated channel: the cached AccessCatalog is
+ // name-based and must not be reshaped to carry subjects.
+ ipcMain.handle('agents:listMine', async event => {
+ assertTrustedSender(event)
+ return service.listMyAgents()
+ })
ipcMain.handle('approvals:listPending', async (event, payload?: { limit?: number }) => {
assertTrustedSender(event)
return service.listPendingWorkflowApprovals(
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index ddee686a6..57faf518c 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -83,14 +83,25 @@ const clerum = Object.freeze({
ipcRenderer.invoke('gfs:renameResource', { resourceId, newName, drive, ifMatch }),
deleteResource: (resourceId: string, drive?: string, ifMatch?: number) =>
ipcRenderer.invoke('gfs:deleteResource', { resourceId, drive, ifMatch }),
- grant: (resourceId: string, subjectKey: string, bits: string[], drive?: string) =>
- ipcRenderer.invoke('gfs:grant', { resourceId, subjectKey, bits, drive }),
+ grant: (
+ resourceId: string,
+ subjectKey: string,
+ bits: string[],
+ drive?: string,
+ inherit?: boolean
+ ) => ipcRenderer.invoke('gfs:grant', { resourceId, subjectKey, bits, drive, inherit }),
+ listGrants: (resourceId: string, drive?: string) =>
+ ipcRenderer.invoke('gfs:listGrants', { resourceId, drive }),
+ revokeGrant: (grantId: string) => ipcRenderer.invoke('gfs:revokeGrant', { grantId }),
// A desktop share grants READ access only (the minimal shared capability) —
// unlike `grant`, it takes no permission bits by design. The server still
// enforces the caller holds read + share (no-escalation).
createShare: (resourceId: string, subjectKey: string, drive?: string) =>
ipcRenderer.invoke('gfs:createShare', { resourceId, subjectKey, drive }),
},
+ agents: {
+ listMine: () => ipcRenderer.invoke('agents:listMine'),
+ },
approvals: {
listPending: (limit?: number) => ipcRenderer.invoke('approvals:listPending', { limit }),
decide: (
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index b5ce754a8..b13cf91bc 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -1,5 +1,6 @@
import {
AccessCatalog,
+ AgentWithMcpServers,
ApprovalDecisionResult,
ChatIndex,
ChatMessage,
@@ -229,10 +230,28 @@ declare global {
resourceId: string,
subjectKey: string,
bits: string[],
- drive?: string
+ drive?: string,
+ inherit?: boolean
) => Promise<void>
+ listGrants: (
+ resourceId: string,
+ drive?: string
+ ) => Promise<
+ Array<{
+ id: string
+ drive: string
+ resourceId: string
+ subject: { type: string; id?: string }
+ permissions: string[]
+ inherit: boolean
+ }>
+ >
+ revokeGrant: (grantId: string) => Promise<void>
createShare: (resourceId: string, subjectKey: string, drive?: string) => Promise<void>
}
+ agents: {
+ listMine: () => Promise<AgentWithMcpServers[]>
+ }
approvals: {
listPending: (limit?: number) => Promise<PendingWorkflowApproval[]>
decide: (
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 92c1a3a19..a46feca02 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -364,6 +364,13 @@ export type AgentWithMcpServers = {
contextRef: string | null
provider?: string | null
mcpServers: Array<{ name: string }>
+ /**
+ * Canonical GFS grant target for this agent (`1st:<ns>/<name>`), built by
+ * control-api's agent directory (accessReconciliation.buildAgentDirectoryEntry).
+ * Optional on the wire: servers predating per-agent GFS access omit it, and
+ * the Manage modal must skip such agents as grant targets.
+ */
+ gfsSubject?: { type: 'host'; id: string }
}
export type UserAgents = {
diff --git a/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts
new file mode 100644
index 000000000..96f425b19
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/gfs-agent-delegation.test.ts
@@ -0,0 +1,662 @@
+/**
+ * E2E — Desktop per-agent GFS delegation (plan "compressed-drifting-matsumoto",
+ * ADDENDUM 1): full pre/post permission sequence with TWO agents.
+ *
+ * One serial suite, two serial tests sharing beforeAll fixtures:
+ *
+ * Test 1 — "agents have no access until granted; grant gives A read AND write":
+ * 1. Pre-grant negative (chat): A, then B, asked to read the file by its
+ * visible path → no-disclosure denial for BOTH (zero successful gfs_read,
+ * no sentinel leak, no gfsc 503/not_mounted).
+ * 2. Grant via UI: Files → Options for <folder> → Manage → Agents section →
+ * select A only → read+write, inherit ON → Grant. Toast + gfs_grants row
+ * (host subject = A, permissions read/write, inherit true) via SQL helper.
+ * 3. Chat A read: sentinel content surfaces from the real PVC.
+ * 4. Chat A write: A replaces the file content (its own tools discover
+ * If-Match); new content + bumped version asserted in DB and on the PVC.
+ * 5. Isolation: B (stateless — exercises the wake path) still denied.
+ *
+ * Test 2 — "stateless agent grant + revoke keeps agents isolated":
+ * 1. Grant B via UI: second Manage round → select B → read → Grant; row
+ * asserted in DB.
+ * 2. Chat B read: B reads the MODIFIED sentinel (stateless runtime + fresh
+ * grant proven together).
+ * 3. Revoke A via UI: Manage → grants list → Revoke on A's row. Toast + row
+ * deleted + gfsGrantRevokeAuditCount +1.
+ * 4. Same-runtime denial for A: retry in A's existing thread is denied with
+ * NO content disclosure (no successful gfs_read, no sentinel, no infra-
+ * shape leak — per the name/path indistinguishability contract; a bare
+ * 403/404 code is intentionally NOT asserted) and pod UID/startTime
+ * invariance (no restart).
+ * 5. B unaffected: B reads again — revocation is isolated in both directions.
+ *
+ * E2E contract (e2e-test-guardian / human-driving):
+ * - Prompts and UI driving reference ONLY visible names and paths; business
+ * truth is always asserted from the database and the PVC via the shared
+ * SQL/kubectl helpers. No fixture helper performs the grant/revoke under
+ * test — those happen exclusively through the Manage modal UI.
+ * - Infra guard: gfsc unhealthy ⇒ the suite THROWS (never skips, never mocks).
+ */
+import { type Locator, type Page, expect, test } from '@playwright/test'
+import { exactNameFilter } from './helpers/agentLocators'
+import { getManagedAgentPodIdentity } from './helpers/gfsAgentDiscovery'
+import {
+ type ManagedGfsAgent,
+ assertGfsInfraHealthy,
+ discoverManagedGfsAgents,
+ getGfsTreeSnapshot,
+ gfsGrantRevokeAuditCount,
+} from './helpers/gfsFixtures'
+import {
+ type GfsFileFixture,
+ cleanupGfsFixture,
+ getE2EUserId,
+ seedGfsFileFixture,
+ seedGfsGrant,
+ uniqueGfsFixtureName,
+} from '../../../tests/e2e/gfsUiFixtures'
+import { getGfsHostGrantsUnderTree } from '../../../tests/e2e/gfsCopyFixtures'
+import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'
+import { launchAndLogin } from './workflowUi'
+
+const OWNER_EMAIL = '[email protected]'
+// glm-5.1 calibration (repo baseline): single agent turns can take minutes;
+// multi-tool turns (discover + read/write) share the 300s budget proven by the
+// issue #797 copy suite.
+const RESPONSE_TIMEOUT_MS = 300_000
+const SENSITIVE_OUTPUT =
+ /\/data\/gfs|\/mnt\/|\.generations|blob_key|blobKey|\bSQL\b|internal (?:path|error)|stack trace/i
+
+interface AgentGfsDelegationFixtures {
+ /** Stateful journey agent (grantee of read+write, later revoked). */
+ agentA: ManagedGfsAgent
+ /** Stateless journey agent (wake path; read-only grantee, never revoked). */
+ agentB: ManagedGfsAgent
+ /** Seeded folder + file; the file carries the run-unique original sentinel. */
+ folder: GfsFileFixture
+ /** Exact content sentinel seeded into the file (PVC truth). */
+ originalSentinel: string
+ /** Exact replacement sentinel Agent A is asked to write in Test 1. */
+ modifiedSentinel: string
+ cleanup(): void
+}
+
+/**
+ * Named setup preconditions ONLY (performed outside the journeys under test):
+ * a folder+file the OWNER can see and manage. The owner grant carries
+ * read+write (escalation guard: you can only grant bits you hold) and
+ * manage_acl (Manage-modal delegation affordance + grants GET). NO host grant
+ * is seeded — creating and revoking those is exactly what the UI journeys
+ * must do themselves.
+ */
+function seedAgentGfsDelegationFixtures(ownerEmail: string): AgentGfsDelegationFixtures {
+ const [agentA, agentB] = discoverManagedGfsAgents()
+ const folder = seedGfsFileFixture(uniqueGfsFixtureName('e2e-gfs-agent-delegation'))
+ try {
+ seedGfsGrant({
+ resourceId: folder.resourceId,
+ subjectType: 'user',
+ subjectId: getE2EUserId(ownerEmail),
+ permissions: ['read', 'write', 'manage_acl'],
+ inherit: true,
+ grantedBy: 'e2e:gfs-agent-delegation-owner',
+ })
+ for (const agent of [agentA, agentB]) {
+ if (getGfsHostGrantsUnderTree(folder.resourceId, agent.subjectId).length !== 0) {
+ throw new Error(
+ `delegation fixture must start with ZERO host grants for ${agent.subjectId} — ` +
+ 'the pre-grant denial phase would be meaningless'
+ )
+ }
+ }
+ return {
+ agentA,
+ agentB,
+ folder,
+ originalSentinel: `E2E GFS file fixture: ${folder.name}`,
+ modifiedSentinel: `Delegated write sentinel ${folder.name} rewritten by the granted agent`,
+ cleanup: () => cleanupGfsFixture(folder.name),
+ }
+ } catch (error) {
+ try {
+ cleanupGfsFixture(folder.name)
+ } catch (cleanupError) {
+ throw new Error(
+ `GFS delegation setup failed (${String(error)}) and cleanup failed (${String(cleanupError)})`
+ )
+ }
+ throw error
+ }
+}
+
+async function openExactAgent(
+ page: Page,
+ agentName: string,
+ opts: { reuseThread?: boolean } = {}
+): Promise<void> {
+ await openAgentsPage(page)
+ await expect(page.getByRole('heading', { name: 'Agents', exact: true })).toBeVisible()
+ const row = page.getByLabel(`Open details for ${agentName}`, { exact: true })
+ await expect(row).toBeVisible({ timeout: 30_000 })
+ await row.click()
+ await expect(page.getByText(agentName, { exact: true }).first()).toBeVisible({ timeout: 15_000 })
+ await page.getByTestId('nav-chat').click()
+ await expect(page.getByTestId('chat-input')).toBeVisible({ timeout: 30_000 })
+ // Starting a new chat can reset the composer to the DEFAULT agent, so it
+ // must happen BEFORE the agent switch — never after, or the turn silently
+ // goes to the wrong agent.
+ if (!opts.reuseThread) {
+ const fresh = page.getByRole('button', { name: /new (?:chat|thread)/i }).first()
+ if (await fresh.isVisible().catch(() => false)) await fresh.click()
+ }
+ // The product binds the composer to an agent ONLY through the chat view's
+ // "Switch chat agent" selector — opening another agent's details page
+ // deliberately does not switch the chat. Drive exactly that user flow.
+ const switcher = page.getByRole('button', { name: 'Switch chat agent' })
+ const boundSwitcher = switcher.filter(exactNameFilter(agentName))
+ const breadcrumb = page
+ .getByRole('navigation', { name: 'Chat breadcrumb' })
+ .getByText(agentName, { exact: true })
+ if (!(await boundSwitcher.or(breadcrumb).first().isVisible().catch(() => false))) {
+ await switcher.first().click()
+ await page.getByRole('menuitem', { name: agentName, exact: true }).click()
+ }
+ // A stateless agent suspended at idle wakes through the rpc-proxy
+ // wake-and-hold path (up to ~90s of scale-up) before its chat shell binds;
+ // the binding element itself remains mandatory and is the LAST gate before
+ // any turn is sent.
+ await expect(boundSwitcher.or(breadcrumb).first()).toBeVisible({ timeout: 120_000 })
+ if (opts.reuseThread) {
+ // The revocation retry deliberately continues the agent's most recent
+ // session: the user only repeats visible paths, and any resource
+ // identifiers live in the agent's own conversational memory from its
+ // previous discovery.
+ await page.locator('.agent-dedicated-session-title-btn').first().click()
+ await expect(page.getByTestId('agent-response').first()).toBeVisible({ timeout: 15_000 })
+ } else {
+ await expect(page.getByTestId('agent-response')).toHaveCount(0, { timeout: 10_000 })
+ }
+}
+
+async function sendAgentTurn(
+ page: Page,
+ prompt: string
+): Promise<{ stepper: Locator; responseText: string }> {
+ const responseIndex = await page.getByTestId('agent-response').count()
+ const approvalIndex = await page.getByTestId('approval-approve-btn').count()
+ const progressIndex = await page.getByTestId('progress-expand-btn').count()
+ await expect(page.getByTestId('chat-input')).toBeEnabled()
+ await page.getByTestId('chat-input').fill(prompt)
+ await page.getByTestId('send-button').click()
+
+ const response = page.getByTestId('agent-response').nth(responseIndex)
+ const retrySend = page.getByRole('button', { name: 'Retry last send' })
+ let approvals = 0
+ let sendRetries = 0
+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS
+ for (;;) {
+ const remaining = deadline - Date.now()
+ if (remaining <= 0) throw new Error('timed out waiting for the delegation-suite agent turn')
+ // A just-restarted runtime can drop the send with a visible "Temporary
+ // connection issue" banner; a real user presses the product's own
+ // "Retry last send". Bounded — a persistent failure still fails the turn.
+ if (await retrySend.isVisible().catch(() => false)) {
+ if (sendRetries >= 3) throw new Error('agent send kept failing after 3 product retries')
+ sendRetries += 1
+ // An absorbed retry must be LOUD in a green run: warn on the console
+ // and annotate the test report, without changing pass/fail semantics.
+ const turnLabel = prompt.slice(0, 80)
+ console.warn(
+ `[gfs-agent-delegation] "Retry last send" pressed (attempt ${sendRetries}/3) for turn: ${turnLabel}`
+ )
+ test.info().annotations.push({
+ type: 'retry-last-send',
+ description: `attempt ${sendRetries}/3 for turn: ${turnLabel}`,
+ })
+ await retrySend.click()
+ continue
+ }
+ const approval = page.getByTestId('approval-approve-btn').nth(approvalIndex + approvals)
+ const approvalWait = approval
+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })
+ .then(() => 'approval' as const)
+ const responseWait = response
+ .waitFor({ state: 'visible', timeout: Math.min(remaining, 10_000) })
+ .then(() => 'response' as const)
+ // The losing waitFor keeps its timer; silence its eventual rejection so a
+ // settled turn cannot surface a late "Target closed" unhandled rejection.
+ // .catch() returns a NEW promise, so the originals still race unchanged.
+ void approvalWait.catch(() => undefined)
+ void responseWait.catch(() => undefined)
+ let visible: 'approval' | 'response'
+ try {
+ visible = await Promise.race([approvalWait, responseWait])
+ } catch {
+ // Neither appeared within this slice; loop to re-check the retry banner
+ // and the overall deadline.
+ continue
+ }
+ if (visible === 'response') break
+ await approval.click()
+ approvals += 1
+ }
+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })
+ const responseText = (await response.textContent()) ?? ''
+ const expand = page.getByTestId('progress-expand-btn').nth(progressIndex)
+ await expect(expand).toBeVisible({ timeout: 30_000 })
+ await expand.click()
+ return { stepper: expand.locator('..'), responseText }
+}
+
+function toolRow(stepper: Locator, name: string): Locator {
+ return stepper.locator('.stepper-step').filter({ hasText: name }).last()
+}
+
+async function expectToolSuccess(stepper: Locator, name: string): Promise<void> {
+ const row = toolRow(stepper, name)
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await expect(row.locator('.stepper-step-fn')).toContainText(name)
+ await expect(row.locator('.stepper-step-duration.state-error')).toHaveCount(0)
+}
+
+/**
+ * The step-output panel renders the head of the tool result payload — the
+ * run-unique sentinel can only be there if gfsc actually served the file
+ * content from the real PVC. The OutputPanel is a SIBLING of the step row, so
+ * row→panel binds via following-sibling.
+ */
+async function expectReadWithSentinel(stepper: Locator, sentinel: string): Promise<void> {
+ await expectToolSuccess(stepper, 'gfs_read')
+ const row = toolRow(stepper, 'gfs_read')
+ await row.click()
+ const output = row
+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')
+ .locator('.stepper-step-output-code')
+ await expect(output).toBeVisible({ timeout: 10_000 })
+ await expect(output).toContainText(sentinel)
+ await expect(output).not.toContainText(SENSITIVE_OUTPUT)
+}
+
+function assertNoInfraFailureShape(responseText: string): void {
+ // Credential repair must be distinguishable from resource authorization: a
+ // not_mounted/503 here means the permission store broke (issue #775 shape),
+ // which must NEVER read as a denial pass.
+ expect(responseText.toLowerCase()).not.toContain('not_mounted')
+ expect(responseText.toLowerCase()).not.toContain('gfsc 503')
+ expect(responseText.toLowerCase()).not.toContain('fetch failed')
+}
+
+/**
+ * No-disclosure denial contract for NAME/PATH driving (pattern from
+ * gfs-agent-file-read.test.ts): an ungranted agent cannot even resolve the
+ * resource, so a denied file is deliberately indistinguishable from an absent
+ * one. The contract is: the agent really attempted its gfs tools, NO gfs_read
+ * ever succeeded, nothing leaked the sentinel content, and no infra
+ * 503/not_mounted shape appeared.
+ */
+async function expectNoDisclosureDenial(
+ turn: { stepper: Locator; responseText: string },
+ forbiddenSentinels: string[]
+): Promise<void> {
+ const page = turn.stepper.page()
+ assertNoInfraFailureShape(turn.responseText)
+ for (const sentinel of forbiddenSentinels) {
+ expect(turn.responseText).not.toContain(sentinel)
+ }
+ const gfsSteps = turn.stepper
+ .locator('.stepper-step')
+ .filter({ has: page.locator('.stepper-step-fn', { hasText: /gfs_/ }) })
+ await expect(gfsSteps.first()).toBeVisible({ timeout: 15_000 })
+ const successfulRead = turn.stepper
+ .locator('.stepper-step')
+ .filter({ has: page.locator('.stepper-step-fn', { hasText: 'gfs_read' }) })
+ .filter({ hasNot: page.locator('.stepper-step-duration.state-error') })
+ await expect(successfulRead).toHaveCount(0)
+ await expect(turn.stepper).not.toContainText(/gfsc 503|not_mounted/i)
+ await expect(turn.stepper).not.toContainText(SENSITIVE_OUTPUT)
+ for (const sentinel of forbiddenSentinels) {
+ await expect(turn.stepper).not.toContainText(sentinel)
+ }
+}
+
+async function openFilesBrowser(page: Page): Promise<Locator> {
+ await openResourcesNavItem(page, 'nav-files')
+ const browser = page.getByRole('region', { name: 'Global File System browser' })
+ await expect(browser).toBeVisible({ timeout: 20_000 })
+ return browser
+}
+
+/**
+ * Enters the fixture folder (visible-path proof: the user sees the file they
+ * will later name to the agents) and opens the Manage dialog through the
+ * folder's own "Options for <folder>" menu.
+ */
+async function openManageForFixtureFolder(
+ page: Page,
+ fixtures: AgentGfsDelegationFixtures
+): Promise<Locator> {
+ const browser = await openFilesBrowser(page)
+ await browser.getByRole('button', { name: fixtures.folder.name, exact: true }).click()
+ await expect(
+ browser.getByRole('button', { name: fixtures.folder.fileName, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ await browser.getByRole('button', { name: `Options for ${fixtures.folder.name}`, exact: true }).click()
+ await browser.getByRole('menuitem', { name: 'Manage', exact: true }).click()
+ const dialog = page.getByRole('dialog', { name: `Manage folder ${fixtures.folder.name}` })
+ await expect(dialog).toBeVisible({ timeout: 15_000 })
+ return dialog
+}
+
+async function closeManageDialog(page: Page, dialog: Locator): Promise<void> {
+ await dialog.getByRole('button', { name: 'Close manage dialog', exact: true }).click()
+ await expect(page.getByRole('dialog', { name: /^Manage folder / })).toHaveCount(0)
+}
+
+/**
+ * Drives the Agents section of the Manage dialog exactly as a user would:
+ * select ONE agent by its visible name (asserting the other stays unselected),
+ * optionally add Write in the permission dropdown, keep the directory-default
+ * "Include contents of this folder" toggle ON, and press Grant. Success is a
+ * product toast plus the agent's row appearing in the "Who has access" list
+ * (list-after-write is mandatory: the grant PUT returns no ids).
+ */
+async function grantAgentAccessViaManageModal(
+ page: Page,
+ dialog: Locator,
+ opts: { agentName: string; unselectedAgentName: string; includeWrite: boolean }
+): Promise<void> {
+ const agentSection = dialog.locator('.da-gfs-agent-access')
+ await expect(agentSection).toBeVisible({ timeout: 20_000 })
+ const agentGroup = agentSection.getByRole('group', { name: 'My agents' })
+ await expect(agentGroup).toBeVisible({ timeout: 20_000 })
+ const target = agentGroup.getByRole('button', { name: opts.agentName, exact: true })
+ const untouched = agentGroup.getByRole('button', { name: opts.unselectedAgentName, exact: true })
+ await expect(untouched).toBeVisible({ timeout: 20_000 })
+ await target.click()
+ await expect(target).toHaveAttribute('aria-pressed', 'true')
+ await expect(untouched).toHaveAttribute('aria-pressed', 'false')
+ if (opts.includeWrite) {
+ // The agent dropdown starts at the read-only default; add Write through
+ // the real menu (menuitemcheckbox), then close it by clicking the section
+ // heading so the Grant press cannot be swallowed by the click-outside
+ // handler.
+ await agentSection.getByRole('button', { name: 'Read', exact: true }).click()
+ const menu = agentSection.getByRole('menu', { name: 'Permissions' })
+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Read' })).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ await menu.getByRole('menuitemcheckbox', { name: 'Write' }).click()
+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Write' })).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ await agentSection.getByRole('heading', { name: 'Agents' }).click()
+ await expect(
+ agentSection.getByRole('button', { name: '2 permissions', exact: true })
+ ).toBeVisible()
+ } else {
+ await expect(agentSection.getByRole('button', { name: 'Read', exact: true })).toBeVisible()
+ }
+ const inherit = agentSection.getByRole('checkbox', { name: 'Include contents of this folder' })
+ // Directory default is ON — asserted, never toggled: a folder grant with
+ // inherit=false would silently break the agent-reads-file journey.
+ await expect(inherit).toBeChecked()
+ await agentSection.getByRole('button', { name: 'Grant agent access', exact: true }).click()
+ await expect(page.getByText('Access granted to 1 agent', { exact: true }).first()).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect(
+ dialog.getByRole('button', { name: `Revoke access for ${opts.agentName}`, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+}
+
+test.describe('GFS per-agent delegation: UI grant/revoke with full pre/post enforcement (Addendum 1)', () => {
+ test.describe.configure({ mode: 'serial' })
+ let fixtures: AgentGfsDelegationFixtures
+
+ test.beforeAll(() => {
+ // Infra guard FIRST: a broken permission-store credential is a blocker to
+ // fix, never a reason to skip or mock (fail-loud rule).
+ assertGfsInfraHealthy()
+ fixtures = seedAgentGfsDelegationFixtures(OWNER_EMAIL)
+ })
+
+ test.afterAll(() => fixtures?.cleanup())
+
+ test('agents have no access until granted; UI grant gives Agent A read AND write', async ({}, testInfo) => {
+ // Four real LLM turns (each allowed RESPONSE_TIMEOUT_MS) plus Electron
+ // login, one stateless wake (≤120s binding), and the Manage-modal grant
+ // round cannot fit the 240s config default.
+ testInfo.setTimeout(1_500_000)
+ const filePath = `/${fixtures.folder.name}/${fixtures.folder.fileName}`
+ const fileBefore = getGfsTreeSnapshot(fixtures.folder.fileResourceId)
+ expect(fileBefore).toHaveLength(1)
+ expect(fileBefore[0]!.kind).toBe('file')
+ expect(fileBefore[0]!.content).toContain(fixtures.originalSentinel)
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('user sees the delegated folder and file in the Files page', async () => {
+ const browser = await openFilesBrowser(page)
+ await browser.getByRole('button', { name: fixtures.folder.name, exact: true }).click()
+ await expect(
+ browser.getByRole('button', { name: fixtures.folder.fileName, exact: true })
+ ).toBeVisible({ timeout: 20_000 })
+ })
+
+ await test.step('pre-grant: Agent A is denied without disclosure', async () => {
+ await openExactAgent(page, fixtures.agentA.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS tools ' +
+ 'even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel])
+ })
+
+ await test.step('pre-grant: stateless Agent B is denied without disclosure', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS tools ' +
+ 'even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel])
+ })
+
+ await test.step('UI grant: Agent A gets read+write with inherit ON', async () => {
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ await grantAgentAccessViaManageModal(page, dialog, {
+ agentName: fixtures.agentA.name,
+ unselectedAgentName: fixtures.agentB.name,
+ includeWrite: true,
+ })
+ await closeManageDialog(page, dialog)
+ // Business truth: exactly one host grant row for A on the folder,
+ // read+write, inherit true — and still none for B.
+ const grantsA = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
+ expect(grantsA).toHaveLength(1)
+ expect(grantsA[0]!.resourceId).toBe(fixtures.folder.resourceId)
+ expect([...grantsA[0]!.permissions].sort()).toEqual(['read', 'write'])
+ expect(grantsA[0]!.inherit).toBe(true)
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ ).toHaveLength(0)
+ })
+
+ await test.step('Agent A reads the sentinel through the real PVC', async () => {
+ await openExactAgent(page, fixtures.agentA.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Use your Clerum GFS tools; do not answer from memory.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectReadWithSentinel(turn.stepper, fixtures.originalSentinel)
+ })
+
+ await test.step('Agent A replaces the content; DB version bumps and the PVC serves it', async () => {
+ // Same thread as the read: the write is the natural follow-up turn.
+ const turn = await sendAgentTurn(
+ page,
+ `Now replace the ENTIRE contents of that same file ("${filePath}" in GFS drive main) ` +
+ `with exactly this single line of text: "${fixtures.modifiedSentinel}". Use only ` +
+ "your native Clerum GFS tools; if your write tool needs the file's current version, " +
+ 'discover it with your own GFS tools first. Do not create, copy, or delete anything.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectToolSuccess(turn.stepper, 'gfs_write')
+ const fileAfter = getGfsTreeSnapshot(fixtures.folder.fileResourceId)
+ expect(fileAfter).toHaveLength(1)
+ // DB truth: the version bumped and bytes match the stored blob.
+ expect(fileAfter[0]!.version).toBeGreaterThan(fileBefore[0]!.version)
+ expect(fileAfter[0]!.bytes).toBe(Buffer.byteLength(fileAfter[0]!.content ?? '', 'utf8'))
+ // PVC truth: the snapshot content is read via kubectl exec cat on the
+ // gfsc writer pod — the new sentinel must be served, the old one gone
+ // (a "helpful" append instead of a replace must fail here).
+ expect(fileAfter[0]!.content).toContain(fixtures.modifiedSentinel)
+ expect(fileAfter[0]!.content).not.toContain(fixtures.originalSentinel)
+ })
+
+ await test.step('isolation: stateless Agent B is STILL denied after A was granted', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS tools ' +
+ 'even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [fixtures.originalSentinel, fixtures.modifiedSentinel])
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ ).toHaveLength(0)
+ })
+ } finally {
+ await app.close()
+ }
+ })
+
+ test('stateless agent grant + UI revoke keeps agents isolated in the same runtime', async ({}, testInfo) => {
+ // Three real LLM turns plus two Manage-modal rounds, Electron login, and a
+ // possible stateless wake.
+ testInfo.setTimeout(1_200_000)
+ const filePath = `/${fixtures.folder.name}/${fixtures.folder.fileName}`
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('UI grant: Agent B gets read-only with inherit ON', async () => {
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ // Continuity from Test 1: A's grant row is still listed before B's
+ // grant is created.
+ await expect(
+ dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentA.name}`,
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 20_000 })
+ await grantAgentAccessViaManageModal(page, dialog, {
+ agentName: fixtures.agentB.name,
+ unselectedAgentName: fixtures.agentA.name,
+ includeWrite: false,
+ })
+ await closeManageDialog(page, dialog)
+ const grantsB = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ expect(grantsB).toHaveLength(1)
+ expect(grantsB[0]!.resourceId).toBe(fixtures.folder.resourceId)
+ expect(grantsB[0]!.permissions).toEqual(['read'])
+ expect(grantsB[0]!.inherit).toBe(true)
+ // A's Test-1 grant is untouched by B's grant.
+ const grantsA = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
+ expect(grantsA).toHaveLength(1)
+ expect([...grantsA[0]!.permissions].sort()).toEqual(['read', 'write'])
+ })
+
+ await test.step('stateless Agent B reads the MODIFIED sentinel (wake + fresh grant)', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Use your Clerum GFS tools; do not answer from memory.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectReadWithSentinel(turn.stepper, fixtures.modifiedSentinel)
+ })
+
+ let runtimeBefore = ''
+ await test.step('UI revoke: Agent A is removed from the grants list, audited', async () => {
+ // Capture A's live pod identity BEFORE the revoke: the later denial
+ // must come from live cache invalidation, not a restart.
+ runtimeBefore = getManagedAgentPodIdentity(fixtures.agentA)
+ const auditBefore = gfsGrantRevokeAuditCount(fixtures.agentA)
+ const dialog = await openManageForFixtureFolder(page, fixtures)
+ const revokeA = dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentA.name}`,
+ exact: true,
+ })
+ await expect(revokeA).toBeVisible({ timeout: 20_000 })
+ await revokeA.click()
+ await expect(
+ page.getByText(`Access revoked for ${fixtures.agentA.name}`, { exact: true }).first()
+ ).toBeVisible({ timeout: 20_000 })
+ await expect(
+ dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentA.name}`,
+ exact: true,
+ })
+ ).toHaveCount(0, { timeout: 20_000 })
+ // B's row survives A's revocation.
+ await expect(
+ dialog.getByRole('button', {
+ name: `Revoke access for ${fixtures.agentB.name}`,
+ exact: true,
+ })
+ ).toBeVisible({ timeout: 20_000 })
+ await closeManageDialog(page, dialog)
+ expect(
+ getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentA.subjectId)
+ ).toHaveLength(0)
+ expect(gfsGrantRevokeAuditCount(fixtures.agentA)).toBe(auditBefore + 1)
+ })
+
+ await test.step('Agent A is denied in the SAME runtime (no pod restart)', async () => {
+ // A FRESH thread is deliberate: reusing A's earlier thread would let it
+ // quote the file straight from conversational memory (it legitimately
+ // read+wrote the content while granted), which proves nothing about the
+ // revocation. Driving by name in a clean thread forces a real re-access
+ // through gfsc, which now denies it. Revocation blocks FUTURE access; it
+ // does not erase context the agent already holds.
+ await openExactAgent(page, fixtures.agentA.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main and quote its contents ` +
+ 'verbatim. Do not answer from memory — attempt the read with your Clerum GFS ' +
+ 'tools even if the file is not in your listing.'
+ )
+ await expectNoDisclosureDenial(turn, [
+ fixtures.originalSentinel,
+ fixtures.modifiedSentinel,
+ ])
+ // Same-runtime proof: pod UID + startTime are unchanged across the
+ // revoke and the denied retry — live cache invalidation, not a restart.
+ expect(getManagedAgentPodIdentity(fixtures.agentA)).toBe(runtimeBefore)
+ })
+
+ await test.step('Agent B still reads fine — revocation is isolated per agent', async () => {
+ await openExactAgent(page, fixtures.agentB.name)
+ const turn = await sendAgentTurn(
+ page,
+ `Read the file at path "${filePath}" in GFS drive main one more time and quote its ` +
+ 'contents verbatim. Use your Clerum GFS tools; do not answer from memory.'
+ )
+ assertNoInfraFailureShape(turn.responseText)
+ await expectReadWithSentinel(turn.stepper, fixtures.modifiedSentinel)
+ const grantsB = getGfsHostGrantsUnderTree(fixtures.folder.resourceId, fixtures.agentB.subjectId)
+ expect(grantsB).toHaveLength(1)
+ expect(grantsB[0]!.permissions).toEqual(['read'])
+ })
+ } finally {
+ await app.close()
+ }
+ })
+})
diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.ts
index d162a8f08..dbc223c8f 100644
--- a/desktop-app/test/gfsUriHandler.test.ts
+++ b/desktop-app/test/gfsUriHandler.test.ts
@@ -206,6 +206,100 @@ describe('GfsClient.grant', () => {
},
})
})
+
+ it('passes inherit through to the API body (agent folder grants set it true)', async () => {
+ const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']
+ await new GfsClient(transport({ requestJson })).grant(
+ {
+ resourceId: RID,
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: true,
+ },
+ 'tok'
+ )
+ expect(requestJson).toHaveBeenCalledWith('PUT', 'https://api.example/api/v1/me/gfs/grants', {
+ token: 'tok',
+ body: {
+ drive: 'main',
+ resourceId: RID,
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: true,
+ },
+ })
+ })
+})
+
+const GRANT_ID = '11111111-2222-3333-4444-555555555555'
+
+const GRANT_ITEM = {
+ id: GRANT_ID,
+ drive: 'main',
+ resourceId: RID,
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read', 'write'],
+ inherit: true,
+}
+
+describe('GfsClient.listGrants', () => {
+ it('GETs the resource ACL and unwraps the items array (NOT enveloped)', async () => {
+ const requestJson = vi.fn(async () => ({
+ items: [GRANT_ITEM],
+ })) as GfsTransport['requestJson']
+ const out = await new GfsClient(transport({ requestJson })).listGrants(
+ { resourceId: RID, drive: 'main' },
+ 'tok'
+ )
+ expect(out).toEqual([GRANT_ITEM])
+ expect(requestJson).toHaveBeenCalledWith(
+ 'GET',
+ `https://api.example/api/v1/me/gfs/grants?drive=main&resourceId=${RID}`,
+ { token: 'tok' }
+ )
+ })
+
+ it('defaults the drive when omitted', async () => {
+ const requestJson = vi.fn(async () => ({ items: [] })) as GfsTransport['requestJson']
+ await new GfsClient(transport({ requestJson })).listGrants({ resourceId: RID }, 'tok')
+ expect(requestJson).toHaveBeenCalledWith(
+ 'GET',
+ `https://api.example/api/v1/me/gfs/grants?drive=main&resourceId=${RID}`,
+ { token: 'tok' }
+ )
+ })
+
+ it('fails loud when the response carries no items array', async () => {
+ const requestJson = vi.fn(async () => ({
+ ok: false,
+ error: { code: 'manage_acl_required', message: 'denied' },
+ })) as GfsTransport['requestJson']
+ await expect(
+ new GfsClient(transport({ requestJson })).listGrants({ resourceId: RID }, 'tok')
+ ).rejects.toBeInstanceOf(GfsUriError)
+ })
+})
+
+describe('GfsClient.revokeGrant', () => {
+ it('DELETEs the grant by id with the bearer token', async () => {
+ const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']
+ await new GfsClient(transport({ requestJson })).revokeGrant(GRANT_ID, 'tok')
+ expect(requestJson).toHaveBeenCalledWith(
+ 'DELETE',
+ `https://api.example/api/v1/me/gfs/grants/${GRANT_ID}`,
+ { token: 'tok' }
+ )
+ })
+
+ it('rejects a non-UUID grant id before any round-trip (no path injection)', async () => {
+ const t = transport()
+ for (const bad of ['', 'not-a-uuid', '../grants', `${GRANT_ID}/extra`, 'main?x=1']) {
+ await expect(new GfsClient(t).revokeGrant(bad, 'tok')).rejects.toThrow(
+ /grant id must be a UUID/
+ )
+ }
+ expect(t.requestJson).not.toHaveBeenCalled()
+ })
})
describe('GfsClient.createShare', () => {
@@ -290,12 +384,45 @@ describe('parseSubjectKey', () => {
expect(parseSubjectKey('team:xyz')).toEqual({ type: 'team', id: 'xyz' })
})
+ it('parses managed host subject keys (first colon splits type from the canonical id)', () => {
+ expect(parseSubjectKey('host:1st:mcp-host/chatllm')).toEqual({
+ type: 'host',
+ id: '1st:mcp-host/chatllm',
+ })
+ expect(parseSubjectKey('host:3rd:sandbox-recipes/scraper-0')).toEqual({
+ type: 'host',
+ id: '3rd:sandbox-recipes/scraper-0',
+ })
+ })
+
+ it('rejects host subject keys that fail the server grammar shape', () => {
+ // No party/namespace (pre-822 grammar stays rejected).
+ expect(() => parseSubjectKey('host:chatllm')).toThrow(/host:<party>:<ns>\/<name>/)
+ // Unknown party.
+ expect(() => parseSubjectKey('host:2nd:mcp-host/chatllm')).toThrow(GfsUriError)
+ // Empty namespace or name.
+ expect(() => parseSubjectKey('host:1st:/chatllm')).toThrow(GfsUriError)
+ expect(() => parseSubjectKey('host:1st:mcp-host/')).toThrow(GfsUriError)
+ expect(() => parseSubjectKey('host:')).toThrow(GfsUriError)
+ // Not k8s DNS-1123 names.
+ expect(() => parseSubjectKey('host:1st:MCP-Host/chatllm')).toThrow(GfsUriError)
+ expect(() => parseSubjectKey('host:1st:mcp-host/-chatllm')).toThrow(GfsUriError)
+ // Extra path segment.
+ expect(() => parseSubjectKey('host:1st:mcp-host/a/b')).toThrow(GfsUriError)
+ // Over the 63-char k8s name budget.
+ expect(() => parseSubjectKey(`host:1st:mcp-host/${'a'.repeat(64)}`)).toThrow(GfsUriError)
+ // At the 63-char budget: accepted.
+ expect(parseSubjectKey(`host:1st:mcp-host/${'a'.repeat(63)}`)).toEqual({
+ type: 'host',
+ id: `1st:mcp-host/${'a'.repeat(63)}`,
+ })
+ })
+
it('rejects malformed and operator/provisioner-only subject keys', () => {
expect(() => parseSubjectKey('')).toThrow(GfsUriError)
expect(() => parseSubjectKey('user:')).toThrow(GfsUriError)
expect(() => parseSubjectKey('bogus:1')).toThrow(GfsUriError)
expect(() => parseSubjectKey('operator')).toThrow(GfsUriError)
- expect(() => parseSubjectKey('host:chatllm')).toThrow(GfsUriError)
expect(() => parseSubjectKey('context:engineering')).toThrow(GfsUriError)
})
})
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index d7617ff8c..fb8bdf234 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -86,6 +86,9 @@ describe('ipc host status stream handlers', () => {
listGfsChildren: vi.fn(),
gfsAffordances: vi.fn(),
grantGfs: vi.fn(),
+ listGfsGrants: vi.fn(),
+ revokeGfsGrant: vi.fn(),
+ listMyAgents: vi.fn(),
createGfsShare: vi.fn(),
setSandboxUiVisible: vi.fn(),
}
@@ -317,12 +320,93 @@ describe('ipc host status stream handlers', () => {
})
)
+ // No inherit in the payload → forwarded as undefined (the client's
+ // historical `false` default applies downstream).
expect(service.grantGfs).toHaveBeenCalledWith(
'11111111-1111-1111-1111-111111111111',
'user:user-1',
['read', 'manage_acl'],
+ 'main',
+ undefined
+ )
+ })
+
+ it('forwards a boolean inherit and rejects a non-boolean one', async () => {
+ service.grantGfs.mockResolvedValue(undefined)
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('gfs:grant')
+
+ await Promise.resolve(
+ handler?.(event, {
+ resourceId: '11111111-1111-1111-1111-111111111111',
+ subjectKey: 'host:1st:mcp-host/chatllm',
+ bits: ['read'],
+ drive: 'main',
+ inherit: true,
+ })
+ )
+ expect(service.grantGfs).toHaveBeenCalledWith(
+ '11111111-1111-1111-1111-111111111111',
+ 'host:1st:mcp-host/chatllm',
+ ['read'],
+ 'main',
+ true
+ )
+
+ await expect(
+ Promise.resolve(
+ handler?.(event, {
+ resourceId: '11111111-1111-1111-1111-111111111111',
+ subjectKey: 'host:1st:mcp-host/chatllm',
+ bits: ['read'],
+ drive: 'main',
+ inherit: 'yes',
+ })
+ )
+ ).rejects.toThrow('inherit must be a boolean')
+ })
+
+ it('routes GFS grant list and revoke through trusted IPC with sanitized input', async () => {
+ service.listGfsGrants.mockResolvedValue([])
+ service.revokeGfsGrant.mockResolvedValue(undefined)
+ const { event } = makeTrustedEvent()
+
+ const listHandler = testState.handlers.get('gfs:listGrants')
+ await Promise.resolve(
+ listHandler?.(event, {
+ resourceId: ' 11111111-1111-1111-1111-111111111111 ',
+ drive: ' main ',
+ })
+ )
+ expect(service.listGfsGrants).toHaveBeenCalledWith(
+ '11111111-1111-1111-1111-111111111111',
'main'
)
+
+ const revokeHandler = testState.handlers.get('gfs:revokeGrant')
+ await Promise.resolve(
+ revokeHandler?.(event, { grantId: ' 22222222-2222-2222-2222-222222222222 ' })
+ )
+ expect(service.revokeGfsGrant).toHaveBeenCalledWith('22222222-2222-2222-2222-222222222222')
+ })
+
+ it('lists my agents through the dedicated channel (not the cached catalog)', async () => {
+ const agents = [
+ {
+ name: 'chatllm',
+ contextRef: 'engineering',
+ mcpServers: [{ name: 'mongodb' }],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ ]
+ service.listMyAgents.mockResolvedValue(agents)
+ const { event } = makeTrustedEvent()
+
+ const handler = testState.handlers.get('agents:listMine')
+ const result = await Promise.resolve(handler?.(event))
+
+ expect(service.listMyAgents).toHaveBeenCalledTimes(1)
+ expect(result).toEqual(agents)
})
it('propagates reserved GFS subject rejection from AppService', async () => {
@@ -342,6 +426,51 @@ describe('ipc host status stream handlers', () => {
).rejects.toThrow('subject must be user:<id> or team:<id>')
})
+ it('rejects untrusted sender for GFS grant listing', async () => {
+ const handler = testState.handlers.get('gfs:listGrants')
+ await expect(
+ Promise.resolve(
+ handler?.(
+ {
+ senderFrame: { url: 'https://evil.example.com' },
+ sender: { id: 1, send: vi.fn(), once: vi.fn() },
+ },
+ { resourceId: '11111111-1111-1111-1111-111111111111', drive: 'main' }
+ )
+ )
+ ).rejects.toThrow('Untrusted IPC sender')
+ expect(service.listGfsGrants).not.toHaveBeenCalled()
+ })
+
+ it('rejects untrusted sender for GFS grant revocation', async () => {
+ const handler = testState.handlers.get('gfs:revokeGrant')
+ await expect(
+ Promise.resolve(
+ handler?.(
+ {
+ senderFrame: { url: 'https://evil.example.com' },
+ sender: { id: 1, send: vi.fn(), once: vi.fn() },
+ },
+ { grantId: '22222222-2222-2222-2222-222222222222' }
+ )
+ )
+ ).rejects.toThrow('Untrusted IPC sender')
+ expect(service.revokeGfsGrant).not.toHaveBeenCalled()
+ })
+
+ it('rejects untrusted sender for my agents listing', async () => {
+ const handler = testState.handlers.get('agents:listMine')
+ await expect(
+ Promise.resolve(
+ handler?.({
+ senderFrame: { url: 'https://evil.example.com' },
+ sender: { id: 1, send: vi.fn(), once: vi.fn() },
+ })
+ )
+ ).rejects.toThrow('Untrusted IPC sender')
+ expect(service.listMyAgents).not.toHaveBeenCalled()
+ })
+
it('routes host status read through getHostStatus handler', async () => {
service.getHostStatus.mockResolvedValue({
hostRef: 'chatllm',
diff --git a/desktop-app/ui/src/components/Common/SelectableOption/index.tsx b/desktop-app/ui/src/components/Common/SelectableOption/index.tsx
index c7a522354..e3ba05e74 100644
--- a/desktop-app/ui/src/components/Common/SelectableOption/index.tsx
+++ b/desktop-app/ui/src/components/Common/SelectableOption/index.tsx
@@ -10,7 +10,10 @@ export const SelectableOption = forwardRef<HTMLButtonElement, SelectableOptionPr
return (
<button
{...props}
- aria-pressed={selected || props['aria-pressed']}
+ // A toggle button must announce BOTH states: an explicit aria-pressed
+ // override wins, otherwise reflect `selected` as a real boolean so an
+ // unselected option is "false", never an absent attribute.
+ aria-pressed={props['aria-pressed'] ?? selected}
className={joinClasses(
'ui-selectable-option',
`ui-selectable-option--${size}`,
diff --git a/desktop-app/ui/src/gfs/GfsAgentAccessSection/constants.ts b/desktop-app/ui/src/gfs/GfsAgentAccessSection/constants.ts
new file mode 100644
index 000000000..8da0c0f87
--- /dev/null
+++ b/desktop-app/ui/src/gfs/GfsAgentAccessSection/constants.ts
@@ -0,0 +1,8 @@
+/**
+ * Managed (`1st:`) agents are server-capped to read/write
+ * (`managed_agent_permission_forbidden`) — the dropdown never offers more.
+ */
+export const GFS_AGENT_GRANTABLE_PERMISSIONS = ['read', 'write'] as const
+
+/** Grant subject-key prefix for host subjects (`host:1st:<ns>/<name>`). */
+export const GFS_HOST_SUBJECT_KEY_PREFIX = 'host:'
diff --git a/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx b/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx
new file mode 100644
index 000000000..90b9702f0
--- /dev/null
+++ b/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx
@@ -0,0 +1,132 @@
+import { useState } from 'react'
+import { Button, SelectableOption, StatusBanner } from '@components/Common'
+import { describeGfsGrantError } from '@lib/gfsGrantErrors'
+import { GfsSubjectBatchError } from '@lib/gfsSubjectBatch'
+import { GfsPermissionDropdown } from '@/gfs/GfsPermissionDropdown'
+import { GFS_AGENT_GRANTABLE_PERMISSIONS, GFS_HOST_SUBJECT_KEY_PREFIX } from './constants'
+import type { GfsAgentAccessSectionProps } from './types'
+
+/**
+ * Desktop per-agent GFS delegation — a manage_acl holder grants read/write on
+ * this resource to one or more of THEIR OWN agents. Presentational only:
+ * eligibility (own-agent directory) and the read/write cap are enforced
+ * server-side; hiding controls here is usability, never the security boundary.
+ *
+ * The inherit toggle is directory-only and defaults ON — a folder grant with
+ * inherit=false does not cover contained files, which would silently break the
+ * agent-reads-file journey. Files always send inherit=false.
+ */
+
+export function GfsAgentAccessSection({
+ agents,
+ agentsLoading = false,
+ agentsError = null,
+ isDirectory,
+ onGrantAgents,
+}: GfsAgentAccessSectionProps) {
+ const [selectedIds, setSelectedIds] = useState<string[]>([])
+ const [bits, setBits] = useState<string[]>(['read'])
+ const [inherit, setInherit] = useState(true)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+
+ const toggleAgent = (id: string) => {
+ setSelectedIds(current =>
+ current.includes(id) ? current.filter(item => item !== id) : [...current, id]
+ )
+ }
+
+ const grant = async () => {
+ setError(null)
+ setBusy(true)
+ try {
+ await onGrantAgents(
+ selectedIds.map(id => `${GFS_HOST_SUBJECT_KEY_PREFIX}${id}`),
+ bits,
+ isDirectory ? inherit : false
+ )
+ setSelectedIds([])
+ } catch (grantError) {
+ // Keep only the failed agents selected so a retry targets exactly them.
+ if (grantError instanceof GfsSubjectBatchError) {
+ const failedIds = new Set(
+ grantError.failedSubjectKeys.map(key =>
+ key.startsWith(GFS_HOST_SUBJECT_KEY_PREFIX)
+ ? key.slice(GFS_HOST_SUBJECT_KEY_PREFIX.length)
+ : key
+ )
+ )
+ setSelectedIds(current => current.filter(id => failedIds.has(id)))
+ }
+ setError(describeGfsGrantError(grantError).message)
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+ <div className="da-gfs-agent-access">
+ <div className="da-gfs-manage-section__header">
+ <div>
+ <h4>Agents</h4>
+ <p className="muted">Let your own agents read or edit this resource.</p>
+ </div>
+ </div>
+ {agentsLoading ? (
+ <p className="muted">Loading your agents…</p>
+ ) : agentsError ? (
+ <StatusBanner tone="error" text={agentsError} />
+ ) : agents.length === 0 ? (
+ <p className="muted">You have no agents that can be granted access.</p>
+ ) : (
+ <>
+ <div className="da-gfs-agent-access__options" role="group" aria-label="My agents">
+ {agents.map(agent => (
+ <SelectableOption
+ disabled={busy}
+ key={agent.id}
+ onClick={() => toggleAgent(agent.id)}
+ selected={selectedIds.includes(agent.id)}
+ size="sm"
+ >
+ {agent.name}
+ </SelectableOption>
+ ))}
+ </div>
+ <div className="da-gfs-agent-access__composer">
+ <GfsPermissionDropdown
+ disabled={busy}
+ onChange={setBits}
+ permissions={[...GFS_AGENT_GRANTABLE_PERMISSIONS]}
+ value={bits}
+ />
+ {isDirectory ? (
+ <label className="da-gfs-agent-access__inherit">
+ <input
+ checked={inherit}
+ disabled={busy}
+ onChange={event => setInherit(event.target.checked)}
+ type="checkbox"
+ />
+ <span>Include contents of this folder</span>
+ </label>
+ ) : null}
+ </div>
+ <div className="da-gfs-agent-access__actions">
+ <Button
+ disabled={busy || selectedIds.length === 0 || bits.length === 0}
+ loading={busy}
+ onClick={() => void grant()}
+ type="button"
+ >
+ Grant agent access
+ </Button>
+ </div>
+ </>
+ )}
+ {error !== null && <StatusBanner tone="error" text={error} />}
+ </div>
+ )
+}
+
+export type { GfsAgentAccessSectionProps } from './types'
diff --git a/desktop-app/ui/src/gfs/GfsAgentAccessSection/types.ts b/desktop-app/ui/src/gfs/GfsAgentAccessSection/types.ts
new file mode 100644
index 000000000..93334bb0c
--- /dev/null
+++ b/desktop-app/ui/src/gfs/GfsAgentAccessSection/types.ts
@@ -0,0 +1,11 @@
+import type { GfsAgentSubjectOption } from '@/gfs/delegation.types'
+
+export interface GfsAgentAccessSectionProps {
+ agents: GfsAgentSubjectOption[]
+ agentsLoading?: boolean
+ agentsError?: string | null
+ /** Directories offer the inherit toggle (default ON); files never send inherit. */
+ isDirectory: boolean
+ /** subjectKeys are `host:`-prefixed canonical subject ids (`host:1st:<ns>/<name>`). */
+ onGrantAgents: (subjectKeys: string[], bits: string[], inherit: boolean) => Promise<void>
+}
diff --git a/desktop-app/ui/src/gfs/GfsGrantList/index.tsx b/desktop-app/ui/src/gfs/GfsGrantList/index.tsx
new file mode 100644
index 000000000..681c7ad92
--- /dev/null
+++ b/desktop-app/ui/src/gfs/GfsGrantList/index.tsx
@@ -0,0 +1,95 @@
+import { Badge, Button, Pill, StatusBanner } from '@components/Common'
+import { GFS_PERMISSION_LABELS } from '@/gfs/GfsPermissionDropdown/constants'
+import type {
+ GfsAgentSubjectOption,
+ GfsDelegationSubjectOption,
+ GfsGrantListItem,
+} from '@/gfs/delegation.types'
+import type { GfsGrantListProps } from './types'
+
+/**
+ * "Who has access" — the resource's current grants, sourced from the user-plane
+ * grants GET (the only revoke-id source: the grant PUT returns no ids). Subject
+ * labels resolve host ids to agent names via the caller's own agent directory
+ * and user/team ids via the visible team directory; anything unresolved shows
+ * its raw id so a row is never hidden or mislabeled.
+ */
+
+function subjectLabel(
+ subject: GfsGrantListItem['subject'],
+ agents: GfsAgentSubjectOption[],
+ subjects: GfsDelegationSubjectOption[]
+): string {
+ if (subject.type === 'host' && subject.id) {
+ const agent = agents.find(candidate => candidate.id === subject.id)
+ if (agent) return agent.name
+ }
+ if ((subject.type === 'user' || subject.type === 'team') && subject.id) {
+ const match = subjects.find(
+ candidate => candidate.type === subject.type && candidate.id === subject.id
+ )
+ if (match) return match.label
+ }
+ return subject.id ?? subject.type
+}
+
+export function GfsGrantList({
+ items,
+ loading = false,
+ error = null,
+ agents,
+ subjects,
+ onRevoke,
+ revoking = false,
+}: GfsGrantListProps) {
+ if (error) {
+ return (
+ <StatusBanner tone={error.severity === 'quiet' ? 'info' : 'error'} text={error.message} />
+ )
+ }
+ if (loading && items.length === 0) {
+ return <p className="muted">Loading access…</p>
+ }
+ if (items.length === 0) {
+ return <p className="muted">No one has been granted access yet.</p>
+ }
+
+ return (
+ <ul className="da-gfs-grant-list">
+ {items.map(item => {
+ const label = subjectLabel(item.subject, agents, subjects)
+ return (
+ <li className="da-gfs-grant-list__row" key={item.id}>
+ <span className="da-gfs-grant-list__identity">
+ <span className="da-gfs-grant-list__label">{label}</span>
+ <span className="da-gfs-grant-list__subject-type">{item.subject.type}</span>
+ </span>
+ <span className="da-gfs-grant-list__meta">
+ <span className="da-gfs-grant-list__chips">
+ {item.permissions.map(permission => (
+ <Pill key={permission} size="xs" tone="neutral">
+ {GFS_PERMISSION_LABELS[permission] ?? permission}
+ </Pill>
+ ))}
+ </span>
+ {item.inherit ? <Badge tone="accent">Includes contents</Badge> : null}
+ </span>
+ <Button
+ aria-label={`Revoke access for ${label}`}
+ color="danger"
+ disabled={revoking}
+ onClick={() => void onRevoke(item, label)}
+ size="sm"
+ type="button"
+ variant="outline"
+ >
+ Revoke
+ </Button>
+ </li>
+ )
+ })}
+ </ul>
+ )
+}
+
+export type { GfsGrantListProps } from './types'
diff --git a/desktop-app/ui/src/gfs/GfsGrantList/types.ts b/desktop-app/ui/src/gfs/GfsGrantList/types.ts
new file mode 100644
index 000000000..18bc9cd87
--- /dev/null
+++ b/desktop-app/ui/src/gfs/GfsGrantList/types.ts
@@ -0,0 +1,22 @@
+import type {
+ GfsAgentSubjectOption,
+ GfsDelegationSubjectOption,
+ GfsGrantListItem,
+} from '@/gfs/delegation.types'
+import type { GfsGrantErrorPresentation } from '@lib/gfsGrantErrors'
+
+export interface GfsGrantListProps {
+ items: GfsGrantListItem[]
+ loading?: boolean
+ /**
+ * Mapped list-load failure. Severity 'quiet' (manage_acl_required) renders an
+ * informational banner instead of the list; 'error' renders an error banner.
+ */
+ error?: GfsGrantErrorPresentation | null
+ /** Label source for `host` subjects (the caller's own agents). */
+ agents: GfsAgentSubjectOption[]
+ /** Label source for `user`/`team` subjects (the visible team directory). */
+ subjects: GfsDelegationSubjectOption[]
+ onRevoke: (item: GfsGrantListItem, label: string) => void | Promise<void>
+ revoking?: boolean
+}
diff --git a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
new file mode 100644
index 000000000..92cd0f922
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
@@ -0,0 +1,129 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { GfsSubjectBatchError } from '@lib/gfsSubjectBatch'
+import { GfsAgentAccessSection } from '../GfsAgentAccessSection'
+
+/**
+ * Per-agent GFS delegation section (Manage modal). Proves the read/write-only
+ * permission cap, the `host:`-prefixed subject keys, and the inherit contract:
+ * directories default inherit ON (a folder grant without inherit would silently
+ * break the agent-reads-file journey); files never send inherit.
+ */
+
+afterEach(cleanup)
+
+const agents = [
+ { id: '1st:mcp-host/chatllm', name: 'chatllm' },
+ { id: '1st:mcp-host/chatllm-stateless', name: 'chatllm-stateless' },
+]
+
+describe('GfsAgentAccessSection', () => {
+ it('offers ONLY read and write permissions for agents', () => {
+ render(
+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={vi.fn()} />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Read' }))
+ expect(screen.getByRole('menuitemcheckbox', { name: 'Read' })).toBeTruthy()
+ expect(screen.getByRole('menuitemcheckbox', { name: 'Write' })).toBeTruthy()
+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Manage access' })).toBeNull()
+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Share' })).toBeNull()
+ expect(screen.queryByRole('menuitemcheckbox', { name: 'Delete' })).toBeNull()
+ })
+
+ it('emits host:-prefixed subject keys for the selected agents', async () => {
+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)
+ render(
+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm-stateless' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(onGrantAgents).toHaveBeenCalledWith(
+ ['host:1st:mcp-host/chatllm', 'host:1st:mcp-host/chatllm-stateless'],
+ ['read'],
+ true
+ )
+ )
+ })
+
+ it('defaults the inherit toggle ON for directories and honors turning it off', async () => {
+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)
+ render(
+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
+ )
+
+ const inherit = screen.getByRole('checkbox', { name: 'Include contents of this folder' })
+ expect(inherit).toHaveProperty('checked', true)
+
+ fireEvent.click(inherit)
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(onGrantAgents).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], false)
+ )
+ })
+
+ it('hides the inherit toggle for files and always sends inherit false', async () => {
+ const onGrantAgents = vi.fn().mockResolvedValue(undefined)
+ render(
+ <GfsAgentAccessSection agents={agents} isDirectory={false} onGrantAgents={onGrantAgents} />
+ )
+
+ expect(
+ screen.queryByRole('checkbox', { name: 'Include contents of this folder' })
+ ).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(onGrantAgents).toHaveBeenCalledWith(['host:1st:mcp-host/chatllm'], ['read'], false)
+ )
+ })
+
+ it('surfaces a mapped server verdict and keeps only failed agents selected', async () => {
+ const onGrantAgents = vi
+ .fn()
+ .mockRejectedValue(
+ new GfsSubjectBatchError(
+ 'Grant agent access',
+ ['host:1st:mcp-host/chatllm'],
+ [
+ {
+ subjectKey: 'host:1st:mcp-host/chatllm-stateless',
+ message: '403 Forbidden: managed_agent_permission_forbidden',
+ },
+ ]
+ )
+ )
+ render(
+ <GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'chatllm-stateless' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await screen.findByText('Managed agents can only be granted read and write.')
+ // SelectableOption only sets aria-pressed="true" while selected.
+ expect(
+ screen.getByRole('button', { name: 'chatllm' }).getAttribute('aria-pressed')
+ ).not.toBe('true')
+ expect(
+ screen.getByRole('button', { name: 'chatllm-stateless' }).getAttribute('aria-pressed')
+ ).toBe('true')
+ })
+
+ it('renders an empty notice when the caller has no grantable agents', () => {
+ render(<GfsAgentAccessSection agents={[]} isDirectory onGrantAgents={vi.fn()} />)
+
+ expect(screen.getByText('You have no agents that can be granted access.')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Grant agent access' })).toBeNull()
+ })
+})
diff --git a/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
new file mode 100644
index 000000000..ed69207c4
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/GfsGrantList.test.tsx
@@ -0,0 +1,119 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+import type { GfsGrantListItem } from '../delegation.types'
+import { GfsGrantList } from '../GfsGrantList'
+
+/**
+ * "Who has access" list (Manage modal). Rows resolve host subjects to agent
+ * names, user/team subjects through the visible team directory, and fall back
+ * to the raw id (a row is never hidden). A manage_acl_required list failure is
+ * an expected state and renders as a quiet informational banner, not an error.
+ */
+
+afterEach(cleanup)
+
+const agents = [{ id: '1st:mcp-host/chatllm', name: 'Chat LLM' }]
+const subjects = [
+ { type: 'user' as const, id: 'user-2', label: 'Test Two', description: '[email protected]' },
+ { type: 'team' as const, id: 'team-1', label: 'Core Team' },
+]
+
+function grantItem(overrides: Partial<GfsGrantListItem>): GfsGrantListItem {
+ return {
+ id: 'grant-1',
+ drive: 'main',
+ resourceId: 'res-1',
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: false,
+ ...overrides,
+ }
+}
+
+describe('GfsGrantList', () => {
+ it('renders resolved subject labels, permission chips, and the inherit badge', () => {
+ render(
+ <GfsGrantList
+ agents={agents}
+ items={[
+ grantItem({ id: 'grant-1', permissions: ['read', 'write'], inherit: true }),
+ grantItem({
+ id: 'grant-2',
+ subject: { type: 'user', id: 'user-2' },
+ permissions: ['read'],
+ }),
+ grantItem({ id: 'grant-3', subject: { type: 'host', id: '1st:mcp-host/unknown' } }),
+ ]}
+ onRevoke={vi.fn()}
+ subjects={subjects}
+ />
+ )
+
+ const agentRow = screen.getByText('Chat LLM').closest('li')!
+ expect(within(agentRow).getByText('Read')).toBeTruthy()
+ expect(within(agentRow).getByText('Write')).toBeTruthy()
+ expect(within(agentRow).getByText('Includes contents')).toBeTruthy()
+
+ const userRow = screen.getByText('Test Two').closest('li')!
+ expect(within(userRow).getByText('Read')).toBeTruthy()
+ expect(within(userRow).queryByText('Includes contents')).toBeNull()
+
+ // Unresolvable subject ids stay visible as raw ids — never hidden.
+ expect(screen.getByText('1st:mcp-host/unknown')).toBeTruthy()
+ })
+
+ it('fires the revoke callback from the row button with an accessible name', () => {
+ const onRevoke = vi.fn()
+ const item = grantItem({ id: 'grant-1' })
+ render(<GfsGrantList agents={agents} items={[item]} onRevoke={onRevoke} subjects={subjects} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Revoke access for Chat LLM' }))
+
+ expect(onRevoke).toHaveBeenCalledWith(item, 'Chat LLM')
+ })
+
+ it('renders manage_acl_required as a quiet informational banner instead of the list', () => {
+ render(
+ <GfsGrantList
+ agents={agents}
+ error={{
+ code: 'manage_acl_required',
+ message: 'Only people with manage access can view who has access here.',
+ severity: 'quiet',
+ }}
+ items={[grantItem({ id: 'grant-1' })]}
+ onRevoke={vi.fn()}
+ subjects={subjects}
+ />
+ )
+
+ const banner = screen.getByText(
+ 'Only people with manage access can view who has access here.'
+ )
+ expect(banner.closest('.status-banner')?.className).toContain('tone-info')
+ expect(screen.queryByRole('list')).toBeNull()
+ expect(screen.queryByRole('button', { name: /Revoke access for/ })).toBeNull()
+ })
+
+ it('renders other list failures as an error banner', () => {
+ render(
+ <GfsGrantList
+ agents={agents}
+ error={{ code: null, message: 'listGrants exploded', severity: 'error' }}
+ items={[]}
+ onRevoke={vi.fn()}
+ subjects={subjects}
+ />
+ )
+
+ const banner = screen.getByText('listGrants exploded')
+ expect(banner.closest('.status-banner')?.className).toContain('tone-error')
+ })
+
+ it('renders an empty notice when nothing has been granted', () => {
+ render(<GfsGrantList agents={agents} items={[]} onRevoke={vi.fn()} subjects={subjects} />)
+
+ expect(screen.getByText('No one has been granted access yet.')).toBeTruthy()
+ })
+})
diff --git a/desktop-app/ui/src/gfs/delegation.tsx b/desktop-app/ui/src/gfs/delegation.tsx
index 008c76e7e..c28d6d59b 100644
--- a/desktop-app/ui/src/gfs/delegation.tsx
+++ b/desktop-app/ui/src/gfs/delegation.tsx
@@ -101,7 +101,9 @@ export function GfsDelegationPanel({
export type {
DelegationAffordances,
+ GfsAgentSubjectOption,
GfsDelegationPanelProps,
GfsDelegationSubjectOption,
GfsDelegationSubjectType,
+ GfsGrantListItem,
} from './delegation.types'
diff --git a/desktop-app/ui/src/gfs/delegation.types.ts b/desktop-app/ui/src/gfs/delegation.types.ts
index 9a5a5a4fd..a0aef21b2 100644
--- a/desktop-app/ui/src/gfs/delegation.types.ts
+++ b/desktop-app/ui/src/gfs/delegation.types.ts
@@ -21,3 +21,27 @@ export interface GfsDelegationPanelProps {
onGrant: (subjectKeys: string[], bits: string[]) => Promise<void>
onCreateShare?: (subjectKeys: string[]) => Promise<void>
}
+
+/**
+ * One of MY agents, offered as a delegation target. `id` is the canonical
+ * managed-host subject id (`1st:<namespace>/<name>`) from
+ * `window.clerum.agents.listMine()`; the grant subject key is `host:` + id.
+ */
+export interface GfsAgentSubjectOption {
+ id: string
+ name: string
+}
+
+/**
+ * A row from `window.clerum.gfs.listGrants()` — the admin-GET item shape
+ * surfaced on the user plane. `id` powers revoke (the grant PUT response
+ * carries no ids, so this list is the only revoke-id source).
+ */
+export interface GfsGrantListItem {
+ id: string
+ drive: string
+ resourceId: string
+ subject: { type: string; id?: string }
+ permissions: string[]
+ inherit: boolean
+}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index 4334f10db..7cec8b587 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -573,3 +573,248 @@ describe('useGfsBrowserController', () => {
expect(screen.getByTestId('accessible-count').textContent).toBe('0')
})
})
+
+// The grants listing is gated by the `grantsListEnabled` hook option (the Manage
+// dialog is the only consumer, so the query runs only while it is open). This
+// probe drives that option through local state so a test can flip Manage
+// open/closed, and it reuses the real QueryClient from `Harness` so invalidation
+// genuinely refetches — mocking the client would hide the load-after-write wiring
+// this block exists to protect.
+function ManageProbe() {
+ const [manageOpen, setManageOpen] = useState(false)
+ const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })
+ return (
+ <>
+ <div data-testid="current">{ctrl.current?.resourceId ?? 'none'}</div>
+ <div data-testid="grants-count">{ctrl.grants.length}</div>
+ <button type="button" onClick={() => void ctrl.openUri('gfs://main/root')}>
+ open root
+ </button>
+ <button type="button" onClick={() => setManageOpen(true)}>
+ open manage
+ </button>
+ <button type="button" onClick={() => setManageOpen(false)}>
+ close manage
+ </button>
+ <button type="button" onClick={() => void ctrl.refreshGrants()}>
+ refresh grants
+ </button>
+ <button type="button" onClick={() => void ctrl.revokeGrant('grant-42')}>
+ revoke grant
+ </button>
+ <button type="button" onClick={() => void ctrl.grant('user:bob', ['read'], true)}>
+ grant inherit true
+ </button>
+ <button type="button" onClick={() => void ctrl.grant('team:qa', ['read'], false)}>
+ grant inherit false
+ </button>
+ </>
+ )
+}
+
+describe('useGfsBrowserController — grants list / revoke / inherit (#826)', () => {
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('does not list grants while Manage is closed and lists them once it opens', async () => {
+ const affordances = vi.fn(async () => ({
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ }))
+ const listGrants = vi.fn(async () => [
+ {
+ id: 'grant-42',
+ drive: 'main',
+ resourceId: 'root',
+ subject: { type: 'user', id: 'bob' },
+ permissions: ['read'],
+ inherit: false,
+ },
+ ])
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
+ resolve: vi.fn(async () => ({
+ resourceId: 'root',
+ gfsUri: 'gfs://main/root',
+ name: 'Root',
+ kind: 'directory',
+ })),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances,
+ listGrants,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ // The open cycle has run (affordances fetched), so any grants fetch would have
+ // fired by now — but Manage is closed, so the grants list must stay dormant.
+ await waitFor(() => expect(affordances).toHaveBeenCalled())
+ expect(listGrants).not.toHaveBeenCalled()
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open manage' }).click()
+ })
+ await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(1))
+ expect(listGrants).toHaveBeenCalledWith('root', 'main')
+ await waitFor(() => expect(screen.getByTestId('grants-count').textContent).toBe('1'))
+ })
+
+ it('refetches the grants list when refreshGrants runs', async () => {
+ const listGrants = vi.fn(async () => [])
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
+ resolve: vi.fn(async () => ({
+ resourceId: 'root',
+ gfsUri: 'gfs://main/root',
+ name: 'Root',
+ kind: 'directory',
+ })),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ })),
+ listGrants,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ await act(async () => {
+ screen.getByRole('button', { name: 'open manage' }).click()
+ })
+ await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(1))
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'refresh grants' }).click()
+ })
+
+ await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(2))
+ })
+
+ it('revokes a grant by id and refetches the grants list on success', async () => {
+ const revokeGrant = vi.fn(async () => undefined)
+ const listGrants = vi.fn(async () => [
+ {
+ id: 'grant-42',
+ drive: 'main',
+ resourceId: 'root',
+ subject: { type: 'user', id: 'bob' },
+ permissions: ['read'],
+ inherit: false,
+ },
+ ])
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
+ resolve: vi.fn(async () => ({
+ resourceId: 'root',
+ gfsUri: 'gfs://main/root',
+ name: 'Root',
+ kind: 'directory',
+ })),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ })),
+ listGrants,
+ revokeGrant,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+ await act(async () => {
+ screen.getByRole('button', { name: 'open manage' }).click()
+ })
+ await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(1))
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'revoke grant' }).click()
+ })
+
+ await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('grant-42'))
+ // onSuccess: refreshGrants invalidates the exact grants key → active refetch.
+ await waitFor(() => expect(listGrants).toHaveBeenCalledTimes(2))
+ })
+
+ it('forwards the inherit flag (true and false) to window.clerum.gfs.grant', async () => {
+ const grant = vi.fn(async () => undefined)
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: vi.fn(async () => ({ items: [], nextCursor: null })),
+ resolve: vi.fn(async () => ({
+ resourceId: 'root',
+ gfsUri: 'gfs://main/root',
+ name: 'Root',
+ kind: 'directory',
+ })),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ })),
+ grant,
+ },
+ },
+ })
+
+ render(<ManageProbe />, { wrapper: Harness })
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open root' }).click()
+ })
+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'grant inherit true' }).click()
+ })
+ await waitFor(() =>
+ expect(grant).toHaveBeenCalledWith('root', 'user:bob', ['read'], 'main', true)
+ )
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'grant inherit false' }).click()
+ })
+ await waitFor(() =>
+ expect(grant).toHaveBeenCalledWith('root', 'team:qa', ['read'], 'main', false)
+ )
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/queryKeys.ts b/desktop-app/ui/src/hooks/domain/queryKeys.ts
index 1fdbd4778..1b9604a84 100644
--- a/desktop-app/ui/src/hooks/domain/queryKeys.ts
+++ b/desktop-app/ui/src/hooks/domain/queryKeys.ts
@@ -4,6 +4,7 @@ export const desktopQueryKeys = {
mcpServersPreview: (hostRefs: string[]) =>
['desktop-app', 'mcp-servers-preview', ...hostRefs] as const,
teamsDirectory: ['desktop-app', 'teams-directory'] as const,
+ myAgents: ['desktop-app', 'my-agents'] as const,
workflows: ['desktop-app', 'workflows'] as const,
workflowSelection: ['desktop-app', 'workflow-selection'] as const,
workflowDetail: (namespace: string, name: string) =>
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 7d4d204b0..8be2d3be7 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useAuthContext } from '@contexts/AuthContext'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'
+import type { GfsGrantListItem } from '@/gfs/delegation.types'
import { desktopQueryKeys } from './queryKeys'
/**
@@ -57,6 +58,14 @@ export interface GfsBrowserAffordances {
canCreateShare: boolean
}
+export interface GfsBrowserControllerOptions {
+ /**
+ * Enables the grants listing for the current resource. The Manage dialog is
+ * the only consumer, so the query runs only while it is open.
+ */
+ grantsListEnabled?: boolean
+}
+
function toMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
@@ -69,7 +78,8 @@ function isResourceDiscoveryUnavailable(message: string): boolean {
)
}
-export function useGfsBrowserController() {
+export function useGfsBrowserController(options: GfsBrowserControllerOptions = {}) {
+ const { grantsListEnabled = false } = options
const queryClient = useQueryClient()
const { isAuthenticated, me, runtimeConfigState } = useAuthContext()
const [crumbs, setCrumbs] = useState<GfsCrumb[]>([])
@@ -145,6 +155,25 @@ export function useGfsBrowserController() {
refetchType: 'active',
})
}, [current?.resourceId, queryClient, sessionScope])
+ // The grants listing is the revoke-id source (the grant PUT returns no ids),
+ // so writes must refetch it. Enabled only while the Manage dialog is open.
+ const grantsQuery = useQuery({
+ queryKey: ['gfs', DRIVE, current?.resourceId ?? '', 'grants'],
+ queryFn: () => window.clerum.gfs.listGrants(current!.resourceId, DRIVE),
+ enabled: Boolean(sessionScope) && Boolean(current) && grantsListEnabled,
+ })
+ const refreshGrants = useCallback(async () => {
+ const resourceId = current?.resourceId
+ if (!resourceId) return
+ await queryClient.invalidateQueries({
+ exact: true,
+ queryKey: ['gfs', DRIVE, resourceId, 'grants'],
+ })
+ }, [current?.resourceId, queryClient])
+ const revokeGrantMutation = useMutation({
+ mutationFn: (grantId: string) => window.clerum.gfs.revokeGrant(grantId),
+ onSuccess: refreshGrants,
+ })
const refreshGfs = useCallback(async () => {
await queryClient.invalidateQueries({
queryKey: desktopQueryKeys.gfsRoot,
@@ -211,6 +240,7 @@ export function useGfsBrowserController() {
() => (accessibleQuery.data?.pages ?? []).flatMap(page => page.items),
[accessibleQuery.data]
)
+ const grants = useMemo<GfsGrantListItem[]>(() => grantsQuery.data ?? [], [grantsQuery.data])
const accessibleErrorMessage = accessibleQuery.error ? toMessage(accessibleQuery.error) : null
const accessibleNotice =
sessionScope && !canListAccessibleResources
@@ -230,7 +260,9 @@ export function useGfsBrowserController() {
name: resource.name,
kind: resource.kind === 'directory' ? 'directory' : 'file',
version: resource.version ?? 0,
- bytes: resource.bytes,
+ // `resolve` may omit bytes (older servers) — crumbs display 0 then,
+ // matching the `version ?? 0` handling above.
+ bytes: resource.bytes ?? 0,
}
const ancestors: GfsCrumb[] = []
const seenResourceIds = new Set([resource.resourceId])
@@ -250,7 +282,7 @@ export function useGfsBrowserController() {
name: parent.name,
kind: 'directory',
version: parent.version ?? 0,
- bytes: parent.bytes,
+ bytes: parent.bytes ?? 0,
})
}
parentResourceId = parent.parentResourceId
@@ -311,11 +343,13 @@ export function useGfsBrowserController() {
}, [queryClient])
// Delegation actions throw on server rejection (e.g. 403 escalation_rejected);
- // the caller surfaces that — never swallow it.
+ // the caller surfaces that — never swallow it. `inherit` is only sent when a
+ // caller passes it explicitly (the agent section, directories only); the
+ // user/team panel keeps today's inherit:false behavior by omitting it.
const grant = useCallback(
- (subjectKey: string, bits: string[]): Promise<void> => {
+ (subjectKey: string, bits: string[], inherit?: boolean): Promise<void> => {
if (!current) return Promise.reject(new Error('No resource selected'))
- return window.clerum.gfs.grant(current.resourceId, subjectKey, bits, DRIVE)
+ return window.clerum.gfs.grant(current.resourceId, subjectKey, bits, DRIVE, inherit)
},
[current]
)
@@ -362,6 +396,14 @@ export function useGfsBrowserController() {
reset,
refreshAffordances,
grant,
+ grants,
+ // Raw error (not toMessage) so FilesPage can map server codes — e.g. a
+ // manage_acl_required 403 renders as a quiet banner, not an error.
+ grantsError: grantsQuery.error,
+ loadingGrants: grantsQuery.isFetching,
+ refreshGrants,
+ revokeGrant: (grantId: string) => revokeGrantMutation.mutateAsync(grantId),
+ revoking: revokeGrantMutation.isPending,
createShare,
createFolder: (name: string) => createFolderMutation.mutateAsync(name),
createFile: (parentResourceId: string, name: string, encodedData: string) =>
diff --git a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
new file mode 100644
index 000000000..ebbe51bbc
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest'
+import { describeGfsGrantError } from '../gfsGrantErrors'
+
+/**
+ * Pure presentation map for GFS grant-plane server verdicts. Codes arrive
+ * embedded in Electron IPC error messages, so matching is substring-based.
+ */
+
+describe('describeGfsGrantError', () => {
+ it.each([
+ [
+ 'agent_manager_forbidden',
+ "Agents can't be given manage or share access.",
+ ],
+ [
+ 'managed_agent_permission_forbidden',
+ 'Managed agents can only be granted read and write.',
+ ],
+ ['foreign_agent_forbidden', 'You can only grant access to your own agents.'],
+ ['escalation_rejected', 'You can only grant permissions you already hold here.'],
+ ])('maps %s to its human message with error severity', (code, message) => {
+ const presentation = describeGfsGrantError(
+ new Error(`Error invoking remote method 'gfs:grant': Error: 403 Forbidden: ${code}`)
+ )
+
+ expect(presentation).toEqual({ code, message, severity: 'error' })
+ })
+
+ it('maps manage_acl_required to a quiet banner, never an error toast', () => {
+ const presentation = describeGfsGrantError(
+ new Error("Error invoking remote method 'gfs:listGrants': Error: 403 Forbidden: manage_acl_required")
+ )
+
+ expect(presentation).toEqual({
+ code: 'manage_acl_required',
+ message: 'Only people with manage access can view who has access here.',
+ severity: 'quiet',
+ })
+ })
+
+ it('maps subjects_invalid without indexes', () => {
+ expect(describeGfsGrantError(new Error('400 Bad Request: subjects_invalid'))).toEqual({
+ code: 'subjects_invalid',
+ message: 'Some selected subjects are invalid and were rejected.',
+ severity: 'error',
+ })
+ })
+
+ it('appends 1-based subject positions when subjects_invalid carries invalidIndexes', () => {
+ const presentation = describeGfsGrantError(
+ new Error('400 Bad Request: subjects_invalid {"invalidIndexes":[0, 2]}')
+ )
+
+ expect(presentation).toEqual({
+ code: 'subjects_invalid',
+ message: 'Some selected subjects are invalid and were rejected. (subjects 1, 3)',
+ severity: 'error',
+ })
+ })
+
+ it('maps 429 with retryAfterSeconds into the retry message', () => {
+ const presentation = describeGfsGrantError(
+ new Error('429 Too Many Requests: {"error":"rate_limited","retryAfterSeconds":42}')
+ )
+
+ expect(presentation).toEqual({
+ code: 'rate_limited',
+ message: 'Too many permission changes — try again in 42s.',
+ severity: 'error',
+ })
+ })
+
+ it('maps 429 without a parseable retryAfterSeconds to the generic retry message', () => {
+ const presentation = describeGfsGrantError(new Error('429 Too Many Requests'))
+
+ expect(presentation).toEqual({
+ code: 'rate_limited',
+ message: 'Too many permission changes — try again shortly.',
+ severity: 'error',
+ })
+ })
+
+ it('does not treat an id containing 429 as a rate limit', () => {
+ const presentation = describeGfsGrantError(new Error('resource res-4290 not found'))
+
+ expect(presentation).toEqual({
+ code: null,
+ message: 'resource res-4290 not found',
+ severity: 'error',
+ })
+ })
+
+ it('passes unknown errors through verbatim — fail loud, never swallow', () => {
+ expect(describeGfsGrantError(new Error('total surprise'))).toEqual({
+ code: null,
+ message: 'total surprise',
+ severity: 'error',
+ })
+ expect(describeGfsGrantError('string failure')).toEqual({
+ code: null,
+ message: 'string failure',
+ severity: 'error',
+ })
+ })
+})
diff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.ts
new file mode 100644
index 000000000..49eef6503
--- /dev/null
+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts
@@ -0,0 +1,82 @@
+/**
+ * Pure presentation map for GFS grant/revoke/list server verdicts.
+ *
+ * The renderer receives control-api error codes embedded in Electron IPC error
+ * messages (e.g. "Error invoking remote method 'gfs:grant': Error: 403
+ * Forbidden: foreign_agent_forbidden"), so codes are matched as substrings of
+ * the raw message. Unknown errors keep their raw message — fail loud, never
+ * swallow a server verdict.
+ */
+
+export interface GfsGrantErrorPresentation {
+ /** Matched control-api error code, or null when the message is passed through. */
+ code: string | null
+ message: string
+ /**
+ * 'quiet' renders as an informational banner (never an error toast) — the
+ * caller simply lacks manage access, which is an expected state, not a fault.
+ */
+ severity: 'error' | 'quiet'
+}
+
+const GFS_GRANT_ERROR_MESSAGES: Record<string, string> = {
+ agent_manager_forbidden: "Agents can't be given manage or share access.",
+ managed_agent_permission_forbidden: 'Managed agents can only be granted read and write.',
+ foreign_agent_forbidden: 'You can only grant access to your own agents.',
+ subjects_invalid: 'Some selected subjects are invalid and were rejected.',
+ escalation_rejected: 'You can only grant permissions you already hold here.',
+ manage_acl_required: 'Only people with manage access can view who has access here.',
+}
+
+function rawMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error ?? '')
+}
+
+function parseInvalidIndexes(message: string): number[] {
+ const match = message.match(/invalidIndexes[^[]*\[([\d,\s]*)\]/)
+ if (!match || !match[1]?.trim()) return []
+ return match[1]
+ .split(',')
+ .map(part => Number.parseInt(part.trim(), 10))
+ .filter(index => Number.isInteger(index) && index >= 0)
+}
+
+function parseRetryAfterSeconds(message: string): number | null {
+ const match = message.match(/retryAfterSeconds[^\d]*(\d+)/)
+ if (!match?.[1]) return null
+ const seconds = Number.parseInt(match[1], 10)
+ return Number.isInteger(seconds) && seconds >= 0 ? seconds : null
+}
+
+export function describeGfsGrantError(error: unknown): GfsGrantErrorPresentation {
+ const raw = rawMessage(error)
+
+ if (/\b429\b/.test(raw) || raw.includes('rate_limited')) {
+ const retryAfterSeconds = parseRetryAfterSeconds(raw)
+ return {
+ code: 'rate_limited',
+ message:
+ retryAfterSeconds !== null
+ ? `Too many permission changes — try again in ${retryAfterSeconds}s.`
+ : 'Too many permission changes — try again shortly.',
+ severity: 'error',
+ }
+ }
+
+ for (const [code, message] of Object.entries(GFS_GRANT_ERROR_MESSAGES)) {
+ if (!raw.includes(code)) continue
+ if (code === 'subjects_invalid') {
+ const invalidIndexes = parseInvalidIndexes(raw)
+ return {
+ code,
+ message: invalidIndexes.length
+ ? `${message} (subjects ${invalidIndexes.map(index => index + 1).join(', ')})`
+ : message,
+ severity: 'error',
+ }
+ }
+ return { code, message, severity: code === 'manage_acl_required' ? 'quiet' : 'error' }
+ }
+
+ return { code: null, message: raw || 'The permission change failed.', severity: 'error' }
+}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index f7f56e134..c792924ac 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -15,15 +15,27 @@ import {
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
+import { describeGfsGrantError } from '@lib/gfsGrantErrors'
import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'
import { GfsSubjectBatchError, runGfsSubjectBatch } from '@lib/gfsSubjectBatch'
import { formatSharedFileSize } from '@lib/sharedFiles'
-import { GfsDelegationPanel, type GfsDelegationSubjectOption } from '@/gfs/delegation'
+import {
+ GfsDelegationPanel,
+ type GfsAgentSubjectOption,
+ type GfsDelegationSubjectOption,
+} from '@/gfs/delegation'
+import { GfsAgentAccessSection } from '@/gfs/GfsAgentAccessSection'
+import { GfsGrantList } from '@/gfs/GfsGrantList'
import { GfsFilePicker } from '@/gfs/filePicker'
import { normalizeGfsResourceName } from '@/gfs/resourceName'
import type { TeamDirectoryResult } from '../../../src/types'
-import type { FilesPageProps, GfsDriveResource, GfsPreviewResource } from './FilesPage.types'
+import type {
+ FilesPageProps,
+ GfsDriveResource,
+ GfsPreviewResource,
+ MyAgentEntry,
+} from './FilesPage.types'
async function fileToEncodedData(file: File): Promise<string> {
assertGfsFileUploadSize(file.size)
@@ -83,6 +95,17 @@ function delegationSubjectOptions(
)
}
+function agentSubjectOptions(agents: MyAgentEntry[] | undefined): GfsAgentSubjectOption[] {
+ if (!agents) return []
+ const options = new Map<string, GfsAgentSubjectOption>()
+ for (const agent of agents) {
+ // Only agents with a canonical host gfsSubject are grantable targets.
+ if (agent.gfsSubject?.type !== 'host' || !agent.gfsSubject.id) continue
+ options.set(agent.gfsSubject.id, { id: agent.gfsSubject.id, name: agent.name })
+ }
+ return [...options.values()].sort((left, right) => left.name.localeCompare(right.name))
+}
+
function resourceSource(resource: GfsDriveResource, currentFolderName?: string): string {
if (currentFolderName) return currentFolderName
return resource.sources?.length ? resource.sources.join(' + ') : 'Shared'
@@ -101,7 +124,7 @@ export function FilesPage({ pushToast }: FilesPageProps) {
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
const uploadInputRef = useRef<HTMLInputElement | null>(null)
const replaceInputRef = useRef<HTMLInputElement | null>(null)
- const ctrl = useGfsBrowserController()
+ const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })
const {
current,
crumbs,
@@ -129,6 +152,21 @@ export function FilesPage({ pushToast }: FilesPageProps) {
() => delegationSubjectOptions(teamDirectoryQuery.data),
[teamDirectoryQuery.data]
)
+ // MY agents (with canonical gfsSubject) load when the Manage dialog opens:
+ // they feed both the agent grant section and grant-list label resolution.
+ const myAgentsQuery = useQuery({
+ queryKey: desktopQueryKeys.myAgents,
+ queryFn: () => window.clerum.agents.listMine(),
+ enabled: manageOpen,
+ })
+ const agentSubjects = useMemo(
+ () => agentSubjectOptions(myAgentsQuery.data),
+ [myAgentsQuery.data]
+ )
+ const grantsError = useMemo(
+ () => (ctrl.grantsError ? describeGfsGrantError(ctrl.grantsError) : null),
+ [ctrl.grantsError]
+ )
const canWriteCurrent = hasBit(affordances, 'write')
const canDeleteCurrent = hasBit(affordances, 'delete')
const currentIsFolder = current?.kind === 'directory'
@@ -198,6 +236,7 @@ export function FilesPage({ pushToast }: FilesPageProps) {
const handleGrant = async (subjectKeys: string[], bits: string[]) => {
try {
await runGfsSubjectBatch('Grant access', subjectKeys, subjectKey =>
+ // No inherit argument here: the user/team panel keeps inherit:false.
ctrl.grant(subjectKey, bits)
)
} catch (error) {
@@ -206,6 +245,8 @@ export function FilesPage({ pushToast }: FilesPageProps) {
`Access granted to ${error.succeededSubjectKeys.length} of ${subjectKeys.length} subjects`,
'success'
)
+ // Some writes landed; the grants list (revoke-id source) must refetch.
+ await ctrl.refreshGrants()
}
throw error
}
@@ -213,6 +254,39 @@ export function FilesPage({ pushToast }: FilesPageProps) {
`Access granted to ${subjectKeys.length} ${subjectKeys.length === 1 ? 'subject' : 'subjects'}`,
'success'
)
+ await ctrl.refreshGrants()
+ }
+
+ const handleGrantAgents = async (subjectKeys: string[], bits: string[], inherit: boolean) => {
+ try {
+ await runGfsSubjectBatch('Grant agent access', subjectKeys, subjectKey =>
+ ctrl.grant(subjectKey, bits, inherit)
+ )
+ } catch (error) {
+ if (error instanceof GfsSubjectBatchError && error.succeededSubjectKeys.length > 0) {
+ pushToast?.(
+ `Access granted to ${error.succeededSubjectKeys.length} of ${subjectKeys.length} agents`,
+ 'success'
+ )
+ // The grant PUT returns no ids — list-after-write is mandatory.
+ await ctrl.refreshGrants()
+ }
+ throw error
+ }
+ pushToast?.(
+ `Access granted to ${subjectKeys.length} ${subjectKeys.length === 1 ? 'agent' : 'agents'}`,
+ 'success'
+ )
+ await ctrl.refreshGrants()
+ }
+
+ const handleRevokeGrant = async (grantId: string, label: string) => {
+ try {
+ await ctrl.revokeGrant(grantId)
+ pushToast?.(`Access revoked for ${label}`, 'success')
+ } catch (revokeError) {
+ pushToast?.(describeGfsGrantError(revokeError).message, 'error')
+ }
}
const handleCreateShare = async (subjectKeys: string[]) => {
@@ -931,24 +1005,59 @@ export function FilesPage({ pushToast }: FilesPageProps) {
) : affordancesError ? (
<StatusBanner tone="error" text={affordancesError} />
) : affordances ? (
- <GfsDelegationPanel
- affordances={affordances}
- subjectOptions={delegationSubjects}
- subjectOptionsLoading={teamDirectoryQuery.isFetching}
- subjectOptionsError={
- teamDirectoryQuery.error instanceof Error
- ? teamDirectoryQuery.error.message
- : teamDirectoryQuery.error
- ? String(teamDirectoryQuery.error)
- : null
- }
- onGrant={handleGrant}
- onCreateShare={affordances.canCreateShare ? handleCreateShare : undefined}
- />
+ <>
+ <GfsDelegationPanel
+ affordances={affordances}
+ subjectOptions={delegationSubjects}
+ subjectOptionsLoading={teamDirectoryQuery.isFetching}
+ subjectOptionsError={
+ teamDirectoryQuery.error instanceof Error
+ ? teamDirectoryQuery.error.message
+ : teamDirectoryQuery.error
+ ? String(teamDirectoryQuery.error)
+ : null
+ }
+ onGrant={handleGrant}
+ onCreateShare={affordances.canCreateShare ? handleCreateShare : undefined}
+ />
+ {affordances.canDelegate ? (
+ <GfsAgentAccessSection
+ agents={agentSubjects}
+ agentsLoading={myAgentsQuery.isFetching}
+ agentsError={
+ myAgentsQuery.error instanceof Error
+ ? myAgentsQuery.error.message
+ : myAgentsQuery.error
+ ? String(myAgentsQuery.error)
+ : null
+ }
+ isDirectory={Boolean(currentIsFolder)}
+ onGrantAgents={handleGrantAgents}
+ />
+ ) : null}
+ </>
) : (
<p className="muted">Loading permissions…</p>
)}
</section>
+
+ <section className="da-gfs-manage-section da-gfs-manage-section--grants">
+ <div className="da-gfs-manage-section__header">
+ <div>
+ <h4>Who has access</h4>
+ <p className="muted">Existing grants on this resource. Revoking is immediate.</p>
+ </div>
+ </div>
+ <GfsGrantList
+ agents={agentSubjects}
+ error={grantsError}
+ items={ctrl.grants}
+ loading={ctrl.loadingGrants}
+ onRevoke={(item, label) => void handleRevokeGrant(item.id, label)}
+ revoking={ctrl.revoking}
+ subjects={delegationSubjects}
+ />
+ </section>
</div>
</section>
</div>
diff --git a/desktop-app/ui/src/pages/FilesPage.types.ts b/desktop-app/ui/src/pages/FilesPage.types.ts
index 8771514a0..60ae0fdb5 100644
--- a/desktop-app/ui/src/pages/FilesPage.types.ts
+++ b/desktop-app/ui/src/pages/FilesPage.types.ts
@@ -14,3 +14,13 @@ export interface FilesPageProps {
/** App-level toast dispatcher for success feedback (desktop-app/ui rule). */
pushToast?: (message: string, tone: Tone) => void
}
+
+/**
+ * Structural shape of one `window.clerum.agents.listMine()` entry (the wire
+ * type is `AgentWithMcpServers` in `desktop-app/src/types.ts`). Only entries
+ * with a valid `host` gfsSubject are delegation targets.
+ */
+export interface MyAgentEntry {
+ name: string
+ gfsSubject?: { type: string; id: string }
+}
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 90ecb3093..f6fc118fc 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -43,6 +43,12 @@ function baseController() {
openChild: vi.fn(),
goToCrumb: vi.fn(),
grant: vi.fn(),
+ grants: [],
+ grantsError: null,
+ loadingGrants: false,
+ refreshGrants: vi.fn(),
+ revokeGrant: vi.fn(),
+ revoking: false,
createShare: vi.fn(),
createFolder: vi.fn(),
createFile: vi.fn(),
@@ -237,7 +243,9 @@ describe('FilesPage', () => {
})
it('shortens oversized file names before uploading through Desktop GFS', async () => {
- const createFile = vi.fn(async (_name: string, _encodedData: string) => undefined)
+ const createFile = vi.fn(
+ async (_parentResourceId: string, _name: string, _encodedData: string) => undefined
+ )
const pushToast = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
@@ -406,7 +414,7 @@ describe('FilesPage', () => {
path: '/shared',
}
let releaseFirstUpload: (() => void) | undefined
- const createFile = vi.fn(() =>
+ const createFile = vi.fn((_parentResourceId: string, _name: string, _encodedData: string) =>
createFile.mock.calls.length === 1
? new Promise<void>(resolve => {
releaseFirstUpload = resolve
@@ -710,6 +718,300 @@ describe('FilesPage', () => {
expect(screen.queryByPlaceholderText(/uuid/i)).toBeNull()
})
+ it('loads my agents when the manage dialog opens and offers only valid gfs subjects', async () => {
+ const listMine = vi.fn(async () => [
+ {
+ name: 'chatllm',
+ contextRef: 'ctx-1',
+ mcpServers: [],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ // No canonical gfsSubject yet — not a grantable delegation target.
+ { name: 'pending-agent', contextRef: null, mcpServers: [] },
+ ])
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: { listMine },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ })
+
+ renderFilesPage()
+ expect(listMine).not.toHaveBeenCalled()
+
+ await openManageDialog('Team folder')
+
+ await waitFor(() => expect(listMine).toHaveBeenCalledTimes(1))
+ expect(await screen.findByRole('button', { name: 'chatllm' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'pending-agent' })).toBeNull()
+ expect(
+ screen.getByRole('checkbox', { name: 'Include contents of this folder' })
+ ).toHaveProperty('checked', true)
+ })
+
+ it('refetches the grants list after a successful agent grant', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: {
+ listMine: vi.fn(async () => [
+ {
+ name: 'chatllm',
+ contextRef: 'ctx-1',
+ mcpServers: [],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ ]),
+ },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ const grant = vi.fn(async () => undefined)
+ const refreshGrants = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'write', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read', 'write'],
+ canCreateShare: false,
+ },
+ grant,
+ refreshGrants,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chatllm' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
+
+ await waitFor(() =>
+ expect(grant).toHaveBeenCalledWith('host:1st:mcp-host/chatllm', ['read'], true)
+ )
+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))
+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 agent', 'success')
+ })
+
+ it('refetches the grants list after a successful user or team grant', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: { listMine: vi.fn(async () => []) },
+ team: {
+ directory: vi.fn(async () => ({
+ currentTeamId: 'team-1',
+ items: [
+ {
+ team: { id: 'team-1', name: 'Core Team', role: 'admin' },
+ members: [
+ {
+ id: 'user-2',
+ email: '[email protected]',
+ name: 'Test Two',
+ role: 'member',
+ status: 'active',
+ },
+ ],
+ contextIds: [],
+ agentNames: [],
+ },
+ ],
+ })),
+ },
+ },
+ })
+ const grant = vi.fn(async () => undefined)
+ const refreshGrants = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ grant,
+ refreshGrants,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ const subjectPicker = await screen.findByRole('combobox', { name: 'Add people or teams' })
+ fireEvent.focus(subjectPicker)
+ fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
+
+ // handleGrant issues the grant then MUST list-after-write (the grant PUT
+ // returns no ids). Deleting `await ctrl.refreshGrants()` must fail here.
+ await waitFor(() => expect(grant).toHaveBeenCalledWith('user:user-2', ['read']))
+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))
+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 subject', 'success')
+ })
+
+ it('refetches the grants list when a user or team grant partially succeeds', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: { listMine: vi.fn(async () => []) },
+ team: {
+ directory: vi.fn(async () => ({
+ currentTeamId: 'team-1',
+ items: [
+ {
+ team: { id: 'team-1', name: 'Core Team', role: 'admin' },
+ members: [
+ {
+ id: 'user-2',
+ email: '[email protected]',
+ name: 'Test Two',
+ role: 'member',
+ status: 'active',
+ },
+ {
+ id: 'user-3',
+ email: '[email protected]',
+ name: 'Test Three',
+ role: 'member',
+ status: 'active',
+ },
+ ],
+ contextIds: [],
+ agentNames: [],
+ },
+ ],
+ })),
+ },
+ },
+ })
+ // First subject lands, second is rejected — the partial-success branch of
+ // handleGrant must still refetch the grants list before rethrowing.
+ const grant = vi
+ .fn()
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error('escalation_rejected'))
+ const refreshGrants = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ grant,
+ refreshGrants,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ const subjectPicker = await screen.findByRole('combobox', { name: 'Add people or teams' })
+ fireEvent.focus(subjectPicker)
+ fireEvent.click(await screen.findByRole('option', { name: /Test Two/ }))
+ fireEvent.click(await screen.findByRole('option', { name: /Test Three/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
+
+ await waitFor(() => expect(grant).toHaveBeenCalledTimes(2))
+ await waitFor(() => expect(refreshGrants).toHaveBeenCalledTimes(1))
+ expect(pushToast).toHaveBeenCalledWith('Access granted to 1 of 2 subjects', 'success')
+ })
+
+ it('revokes a grant from the who-has-access list and toasts the outcome', async () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ agents: {
+ listMine: vi.fn(async () => [
+ {
+ name: 'chatllm',
+ contextRef: 'ctx-1',
+ mcpServers: [],
+ gfsSubject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ },
+ ]),
+ },
+ team: { directory: vi.fn(async () => ({ currentTeamId: 'team-1', items: [] })) },
+ },
+ })
+ const revokeGrant = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder',
+ name: 'Team folder',
+ kind: 'directory',
+ },
+ affordances: {
+ held: ['read', 'manage_acl'],
+ canDelegate: true,
+ grantableBits: ['read'],
+ canCreateShare: false,
+ },
+ grants: [
+ {
+ id: 'grant-1',
+ drive: 'main',
+ resourceId: 'folder-1',
+ subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ permissions: ['read'],
+ inherit: true,
+ },
+ ],
+ revokeGrant,
+ })
+
+ renderFilesPage(pushToast)
+ await openManageDialog('Team folder')
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Revoke access for chatllm' }))
+
+ await waitFor(() => expect(revokeGrant).toHaveBeenCalledWith('grant-1'))
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith('Access revoked for chatllm', 'success')
+ )
+ })
+
it('refreshes server affordances whenever the manage dialog opens', async () => {
const refreshAffordances = vi.fn(async () => undefined)
hookMock.useGfsBrowserController.mockReturnValue({
@@ -998,6 +1300,7 @@ describe('FilesPage', () => {
name: 'architecture.svg',
kind: 'file',
version: 1,
+ bytes: 4,
}
let selectResolvedFile: (() => void) | undefined
const openUri = vi.fn(async () => {
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index f8b665650..2a6e9d9e5 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -14360,6 +14360,123 @@ pre {
background: rgba(var(--accent-rgb), 0.07);
}
+.da-gfs-agent-access {
+ display: grid;
+ gap: var(--space-3);
+ min-width: 0;
+ margin-top: var(--space-3);
+ padding-top: var(--space-3);
+ border-top: 1px solid var(--border-soft);
+}
+
+.da-gfs-agent-access__options {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+}
+
+.da-gfs-agent-access__composer {
+ display: grid;
+ grid-template-columns: minmax(150px, 0.4fr) minmax(0, 1fr);
+ gap: var(--space-2);
+ align-items: center;
+}
+
+.da-gfs-agent-access__inherit {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ min-width: 0;
+ padding: var(--space-1) var(--space-2);
+ border-radius: var(--radius-md);
+ color: var(--text);
+ font-size: var(--font-size-sm);
+ cursor: pointer;
+ transition: box-shadow var(--motion-fast);
+}
+
+.da-gfs-agent-access__inherit:has(input:focus-visible) {
+ box-shadow: 0 0 0 2px rgba(var(--focus-rgb), 0.24);
+}
+
+.da-gfs-agent-access__inherit input[type='checkbox'] {
+ width: var(--space-3);
+ min-width: var(--space-3);
+ height: var(--space-3);
+ min-height: var(--space-3);
+ flex: 0 0 var(--space-3);
+ margin: 0;
+ padding: 0;
+ border-radius: var(--radius-sm);
+ accent-color: var(--accent);
+}
+
+.da-gfs-agent-access__inherit input[type='checkbox']:focus,
+.da-gfs-agent-access__inherit input[type='checkbox']:focus-visible {
+ box-shadow: none;
+ outline: none;
+}
+
+.da-gfs-agent-access__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+}
+
+.da-gfs-grant-list {
+ display: grid;
+ gap: var(--space-1);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.da-gfs-grant-list__row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ min-width: 0;
+ padding: var(--space-2);
+ border: 1px solid var(--border-soft);
+ border-radius: var(--radius-md);
+ background: var(--surface-soft);
+}
+
+.da-gfs-grant-list__identity {
+ display: grid;
+ gap: var(--space-0-5);
+ min-width: 0;
+ flex: 1 1 auto;
+}
+
+.da-gfs-grant-list__label {
+ color: var(--text);
+ font-size: var(--font-size-md);
+ font-weight: var(--font-weight-medium);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.da-gfs-grant-list__subject-type {
+ color: var(--text-muted);
+ font-size: var(--font-size-xs);
+ text-transform: capitalize;
+}
+
+.da-gfs-grant-list__meta {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+}
+
+.da-gfs-grant-list__chips {
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+}
+
@media (max-width: 940px) {
.da-gfs-manage-dialog__body {
padding: var(--space-4);
@@ -14379,7 +14496,8 @@ pre {
display: grid;
}
- .da-gfs-delegation__composer {
+ .da-gfs-delegation__composer,
+ .da-gfs-agent-access__composer {
grid-template-columns: minmax(0, 1fr);
}
diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.ts
index a0840b5e3..77da58603 100644
--- a/external-rest-api/src/routes/gfs.ts
+++ b/external-rest-api/src/routes/gfs.ts
@@ -208,6 +208,24 @@ export function createGfsRouter(): Router {
// Delegation (folder-owner): grant/share as the user. control-api's
// assertMayGrant enforces no-escalation against the user's own held bits.
+ // The grants list requires manage_acl on the resource (view-ACL = manage-ACL,
+ // enforced by control-api's handleGrantListForCaller); its item `id` is what
+ // powers per-row revoke in the Manage modal.
+ router.get('/me/gfs/grants', async (req: AuthedRequest, res, next) => {
+ try {
+ const data = await controlApiRequest('GET', '/external/gfs/grants', {
+ userSessionToken: extractAuthToken(req),
+ query: {
+ drive: typeof req.query.drive === 'string' ? req.query.drive : undefined,
+ resourceId: typeof req.query.resourceId === 'string' ? req.query.resourceId : undefined,
+ },
+ })
+ res.status(200).json(data)
+ } catch (error) {
+ forwardControlApiError(error, res, next)
+ }
+ })
+
router.put('/me/gfs/grants', async (req: AuthedRequest, res, next) => {
try {
const data = await controlApiRequest('PUT', '/external/gfs/grants', {
diff --git a/external-rest-api/test/routes.gfs.test.ts b/external-rest-api/test/routes.gfs.test.ts
index 98fc4a8a4..5fd996d45 100644
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@ -204,3 +204,53 @@ describe('routes/gfs /me/gfs/* (user session passthrough → /external/gfs/*)',
expect(res.status).toBe(401)
})
})
+
+describe('GET /me/gfs/grants (delegation list passthrough)', () => {
+ it('forwards drive + resourceId and returns the id-bearing items verbatim', async () => {
+ const items = [
+ {
+ id: 'aaaa1111-0000-4000-8000-000000000001',
+ drive: 'main',
+ resourceId: '11111111-1111-1111-1111-111111111111',
+ subject: { type: 'host', id: '1st:mcp-host/agent-a' },
+ permissions: ['read', 'write'],
+ inherit: true,
+ },
+ ]
+ clientMock.controlApiRequest.mockResolvedValue({ items })
+ const res = await request(buildApp())
+ .get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
+ .set('authorization', 'Bearer sess-xyz')
+ expect(res.status).toBe(200)
+ expect(res.body).toEqual({ items })
+ expect(clientMock.controlApiRequest).toHaveBeenCalledWith('GET', '/external/gfs/grants', {
+ userSessionToken: 'sess-xyz',
+ query: { drive: 'main', resourceId: '11111111-1111-1111-1111-111111111111' },
+ })
+ })
+
+ it('propagates the manage_acl_required 403 verbatim', async () => {
+ clientMock.controlApiRequest.mockRejectedValue(
+ new ControlApiError('forbidden', 403, { error: 'manage_acl_required' })
+ )
+ const res = await request(buildApp())
+ .get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
+ .set('authorization', 'Bearer sess-xyz')
+ expect(res.status).toBe(403)
+ expect(res.body).toEqual({ error: 'manage_acl_required' })
+ })
+
+ it('propagates the delegation-plane 429 with retryAfterSeconds intact', async () => {
+ clientMock.controlApiRequest.mockRejectedValue(
+ new ControlApiError('rate limited', 429, {
+ error: 'Too Many Requests',
+ retryAfterSeconds: 17,
+ })
+ )
+ const res = await request(buildApp())
+ .get('/me/gfs/grants?drive=main&resourceId=11111111-1111-1111-1111-111111111111')
+ .set('authorization', 'Bearer sess-xyz')
+ expect(res.status).toBe(429)
+ expect(res.body).toEqual({ error: 'Too Many Requests', retryAfterSeconds: 17 })
+ })
+})