Skip to content

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

TypeScript

feat(gfs-ui): bulk subjects[] grant + surface invalidIndexes/retryAfterSeconds

Alfredo Lopez70739aa0d7b1
diff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.ts
index aaec072fc..7670eaa97 100644
--- a/desktop-app/src/__tests__/appService.gfs.test.ts
+++ b/desktop-app/src/__tests__/appService.gfs.test.ts
@@ -18,12 +18,12 @@ function gfsService() {
}
grantGfs: (
resourceId: string,
- subjectKey: string,
+ subjectKeys: string[],
bits: string[],
drive?: string,
inherit?: boolean
) => Promise<void>
- createGfsShare: (resourceId: string, subjectKey: string, drive?: string) => Promise<void>
+ createGfsShare: (resourceId: string, subjectKeys: string[], drive?: string) => Promise<void>
}
service.sessionToken = 'session-token'
service.gfsClient = {
@@ -34,26 +34,34 @@ function gfsService() {
}
describe('AppService GFS delegation subject boundary', () => {
- it('passes only user/team grant subjects to the user-plane GFS client', async () => {
+ it('passes only user/team grant subjects as ONE bulk subjects[] array', async () => {
const service = gfsService()
- await service.grantGfs(RESOURCE_ID, 'user:user-1', ['read'], 'main')
- await service.createGfsShare(RESOURCE_ID, 'team:team-1', 'main')
+ await service.grantGfs(RESOURCE_ID, ['user:user-1', 'team:team-2'], ['read'], 'main')
+ await service.createGfsShare(RESOURCE_ID, ['team:team-1', 'user:user-9'], 'main')
+ expect(service.gfsClient.grant).toHaveBeenCalledTimes(1)
expect(service.gfsClient.grant).toHaveBeenCalledWith(
{
resourceId: RESOURCE_ID,
drive: 'main',
- subject: { type: 'user', id: 'user-1' },
+ subjects: [
+ { type: 'user', id: 'user-1' },
+ { type: 'team', id: 'team-2' },
+ ],
permissions: ['read'],
},
'session-token'
)
+ expect(service.gfsClient.createShare).toHaveBeenCalledTimes(1)
expect(service.gfsClient.createShare).toHaveBeenCalledWith(
{
resourceId: RESOURCE_ID,
drive: 'main',
- subject: { type: 'team', id: 'team-1' },
+ subjects: [
+ { type: 'team', id: 'team-1' },
+ { type: 'user', id: 'user-9' },
+ ],
permissions: ['read'],
includeDescendants: true,
},
@@ -64,13 +72,13 @@ describe('AppService GFS delegation subject boundary', () => {
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)
+ 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' },
+ subjects: [{ type: 'host', id: '1st:mcp-host/chatllm' }],
permissions: ['read'],
inherit: true,
},
@@ -83,10 +91,10 @@ describe('AppService GFS delegation subject boundary', () => {
async subjectKey => {
const service = gfsService()
- await expect(service.grantGfs(RESOURCE_ID, subjectKey, ['read'], 'main')).rejects.toThrow(
- 'subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>'
- )
- await expect(service.createGfsShare(RESOURCE_ID, subjectKey, 'main')).rejects.toThrow(
+ await expect(
+ service.grantGfs(RESOURCE_ID, [subjectKey], ['read'], 'main')
+ ).rejects.toThrow('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>, team:<id>, or host:<party>:<ns>/<name>'
)
@@ -95,16 +103,27 @@ describe('AppService GFS delegation subject boundary', () => {
}
)
+ it('fails the whole bulk grant when ANY subject key in the array is reserved', async () => {
+ const service = gfsService()
+
+ // A single bad key must reject before any round-trip — never a partial write.
+ await expect(
+ service.grantGfs(RESOURCE_ID, ['user:user-1', 'operator:'], ['read'], 'main')
+ ).rejects.toThrow('subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>')
+
+ expect(service.gfsClient.grant).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')
+ 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')
+ 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()
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 98a1f0cbf..9e3e6d3f4 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -856,20 +856,23 @@ export class AppService {
}
/**
- * 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`.
+ * Delegate a grant to one or more subjects (each subjectKey → structured
+ * subject) in a single atomic bulk PUT. 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,
+ subjectKeys: string[],
bits: string[],
drive?: string,
inherit?: boolean
) {
+ // One atomic bulk PUT for every selected subject (server caps at 100). Each
+ // key is parsed to its structured subject up front, so a single malformed
+ // key fails the whole call before any round-trip — never a partial write.
await this.gfsClient.grant(
- { resourceId, drive, subject: parseSubjectKey(subjectKey), permissions: bits, inherit },
+ { resourceId, drive, subjects: subjectKeys.map(parseSubjectKey), permissions: bits, inherit },
this.requireSessionToken()
)
}
@@ -904,12 +907,12 @@ export class AppService {
* shared capability); the no-escalation engine still requires the caller hold
* read + share. includeDescendants so a folder share covers its subtree.
*/
- async createGfsShare(resourceId: string, subjectKey: string, drive?: string) {
+ async createGfsShare(resourceId: string, subjectKeys: string[], drive?: string) {
await this.gfsClient.createShare(
{
resourceId,
drive,
- subject: parseSubjectKey(subjectKey),
+ subjects: subjectKeys.map(parseSubjectKey),
permissions: ['read'],
includeDescendants: true,
},
diff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.ts
index 9d8584afd..d463f1d13 100644
--- a/desktop-app/src/gfs/uriHandler.ts
+++ b/desktop-app/src/gfs/uriHandler.ts
@@ -134,7 +134,13 @@ export type GfsSubject =
export interface GfsGrantInput {
resourceId: string
drive?: string
- subject: GfsSubject
+ /**
+ * One or more grant subjects, sent as the server's bulk `subjects[]` array (up
+ * to 100) in a single atomic PUT. control-api rejects the whole request if any
+ * element is invalid (400 `subjects_invalid` + `invalidIndexes`), so there is
+ * no partial-success outcome — all subjects are granted or none are.
+ */
+ subjects: GfsSubject[]
permissions: string[]
inherit?: boolean
}
@@ -142,7 +148,8 @@ export interface GfsGrantInput {
export interface GfsShareInput {
resourceId: string
drive?: string
- subject: GfsSubject
+ /** One or more share subjects, sent as the bulk `subjects[]` array (atomic). */
+ subjects: GfsSubject[]
permissions: string[]
includeDescendants?: boolean
}
@@ -407,20 +414,24 @@ export class GfsClient {
* API error here); the UI affordances only HIDE controls the caller can't use.
*/
async grant(input: GfsGrantInput, token: string): Promise<void> {
- await this.transport.requestJson(
- 'PUT',
- joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/grants'),
- {
- token,
- body: {
- drive: input.drive ?? DEFAULT_DRIVE,
- resourceId: input.resourceId,
- subject: input.subject,
- permissions: input.permissions,
- inherit: input.inherit ?? false,
- },
- }
- )
+ try {
+ await this.transport.requestJson(
+ 'PUT',
+ joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/grants'),
+ {
+ token,
+ body: {
+ drive: input.drive ?? DEFAULT_DRIVE,
+ resourceId: input.resourceId,
+ subjects: input.subjects,
+ permissions: input.permissions,
+ inherit: input.inherit ?? false,
+ },
+ }
+ )
+ } catch (error) {
+ throw surfaceGfsGrantError(error)
+ }
}
/**
@@ -436,11 +447,16 @@ export class GfsClient {
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 }
- )
+ let payload: { items: GfsGrantListItem[] }
+ try {
+ payload = await this.transport.requestJson<{ items: GfsGrantListItem[] }>(
+ 'GET',
+ joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/grants?' + q.toString()),
+ { token }
+ )
+ } catch (error) {
+ throw surfaceGfsGrantError(error)
+ }
if (!payload || typeof payload !== 'object' || !Array.isArray(payload.items)) {
throw new GfsUriError('unexpected gfs grants response: missing items array')
}
@@ -463,22 +479,26 @@ export class GfsClient {
)
}
- /** Create a URI share for a subject (same no-escalation engine, isShare=true). */
+ /** Create a URI share for subjects (same no-escalation engine, isShare=true). */
async createShare(input: GfsShareInput, token: string): Promise<void> {
- await this.transport.requestJson(
- 'POST',
- joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/shares'),
- {
- token,
- body: {
- drive: input.drive ?? DEFAULT_DRIVE,
- resourceId: input.resourceId,
- subject: input.subject,
- permissions: input.permissions,
- includeDescendants: input.includeDescendants ?? false,
- },
- }
- )
+ try {
+ await this.transport.requestJson(
+ 'POST',
+ joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/shares'),
+ {
+ token,
+ body: {
+ drive: input.drive ?? DEFAULT_DRIVE,
+ resourceId: input.resourceId,
+ subjects: input.subjects,
+ permissions: input.permissions,
+ includeDescendants: input.includeDescendants ?? false,
+ },
+ }
+ )
+ } catch (error) {
+ throw surfaceGfsGrantError(error)
+ }
}
async createResource(input: GfsCreateInput, session: string): Promise<GfsResourceView> {
return createGfsResource(this.transport, input, session)
@@ -537,3 +557,80 @@ export function parseSubjectKey(key: string): GfsSubject {
}
return { type, id }
}
+
+/**
+ * The structured verdict fields a bulk grant/share/list failure can carry.
+ * control-api reports them as SEPARATE response-body fields — `invalidIndexes`
+ * on a 400/403 (routes/gfs/grants.ts sendGfsGrantError) and `retryAfterSeconds`
+ * on a 429 (middleware/rateLimitMiddleware.ts) — not inside the human message.
+ */
+interface GfsGrantErrorFields {
+ invalidIndexes?: number[]
+ retryAfterSeconds?: number
+}
+
+/**
+ * Pull `invalidIndexes` / `retryAfterSeconds` out of an error response body.
+ *
+ * The body is an OPTIONAL, best-effort supplement: many failures (network,
+ * upstream proxy, plain-text errors) are not JSON, in which case there are
+ * simply no structured fields and the caller re-throws the ORIGINAL error
+ * untouched. This never swallows a failure — `surfaceGfsGrantError` always
+ * re-throws.
+ */
+function parseGfsGrantErrorFields(bodyText: string): GfsGrantErrorFields {
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(bodyText)
+ } catch {
+ return {}
+ }
+ if (!parsed || typeof parsed !== 'object') return {}
+ const record = parsed as { invalidIndexes?: unknown; retryAfterSeconds?: unknown }
+ const fields: GfsGrantErrorFields = {}
+ if (Array.isArray(record.invalidIndexes)) {
+ const indexes = record.invalidIndexes.filter(
+ (value): value is number => Number.isInteger(value) && (value as number) >= 0
+ )
+ if (indexes.length > 0) fields.invalidIndexes = indexes
+ }
+ if (Number.isInteger(record.retryAfterSeconds) && (record.retryAfterSeconds as number) >= 0) {
+ fields.retryAfterSeconds = record.retryAfterSeconds as number
+ }
+ return fields
+}
+
+/**
+ * Re-throw a grant/share/list failure with the server's structured verdict
+ * fields embedded in the message.
+ *
+ * The transport (httpClient) throws an `ApiError` that stashes the raw response
+ * body on `.bodyText`, but ONLY the `Error.message` survives the Electron IPC
+ * boundary on the way to the renderer — `.bodyText` is dropped. So a bulk
+ * `subjects_invalid` (which subject failed) or a 429 (`retryAfterSeconds`) would
+ * be invisible to `gfsGrantErrors.ts` in production. We append those fields to
+ * the message in the exact shape that module's regexes parse (`invalidIndexes=[…]`,
+ * `retryAfterSeconds=…`), keeping the original message — and therefore the server
+ * error CODE (`subjects_invalid`, `foreign_agent_forbidden`, `429`, …) — intact.
+ *
+ * When there is nothing structured to surface, the ORIGINAL error propagates
+ * unchanged (fail loud; never swallow the server's verdict).
+ */
+function surfaceGfsGrantError(error: unknown): unknown {
+ const bodyText =
+ error &&
+ typeof error === 'object' &&
+ typeof (error as { bodyText?: unknown }).bodyText === 'string'
+ ? (error as { bodyText: string }).bodyText
+ : ''
+ if (!bodyText) return error
+ const fields = parseGfsGrantErrorFields(bodyText)
+ const parts: string[] = []
+ if (fields.invalidIndexes) parts.push(`invalidIndexes=[${fields.invalidIndexes.join(',')}]`)
+ if (fields.retryAfterSeconds !== undefined) {
+ parts.push(`retryAfterSeconds=${fields.retryAfterSeconds}`)
+ }
+ if (parts.length === 0) return error
+ const baseMessage = error instanceof Error ? error.message : String(error ?? '')
+ return new GfsUriError(`${baseMessage} ${parts.join(' ')}`)
+}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index d9c124ae0..70a911a01 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -17,6 +17,18 @@ function sanitizeString(input: unknown): string {
return String(input || '').trim()
}
+/**
+ * Sanitize a bulk subject-key array (grant/share to many subjects in one call).
+ * Fails loud on a non-array or empty payload rather than silently no-op'ing — an
+ * empty selection is a renderer bug, and the server re-validates the 1..100 bound.
+ */
+function sanitizeSubjectKeys(input: unknown): string[] {
+ if (!Array.isArray(input) || input.length === 0) {
+ throw new Error('subjectKeys must be a non-empty array')
+ }
+ return input.map(sanitizeString)
+}
+
function sanitizeOptionalInteger(input: unknown): number | undefined {
if (input === undefined || input === null || input === '') return undefined
const value = Number(input)
@@ -391,7 +403,7 @@ export function registerIpcHandlers(service: AppService): void {
event,
payload: {
resourceId: string
- subjectKey: string
+ subjectKeys: string[]
bits: string[]
drive?: string
inherit?: boolean
@@ -406,7 +418,7 @@ export function registerIpcHandlers(service: AppService): void {
}
return service.grantGfs(
sanitizeString(payload?.resourceId),
- sanitizeString(payload?.subjectKey),
+ sanitizeSubjectKeys(payload?.subjectKeys),
bits,
drive,
inherit
@@ -427,12 +439,12 @@ export function registerIpcHandlers(service: AppService): void {
})
ipcMain.handle(
'gfs:createShare',
- async (event, payload: { resourceId: string; subjectKey: string; drive?: string }) => {
+ async (event, payload: { resourceId: string; subjectKeys: string[]; drive?: string }) => {
assertTrustedSender(event)
const drive = payload?.drive ? sanitizeString(payload.drive) : undefined
return service.createGfsShare(
sanitizeString(payload?.resourceId),
- sanitizeString(payload?.subjectKey),
+ sanitizeSubjectKeys(payload?.subjectKeys),
drive
)
}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 57faf518c..378744057 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -85,19 +85,19 @@ const clerum = Object.freeze({
ipcRenderer.invoke('gfs:deleteResource', { resourceId, drive, ifMatch }),
grant: (
resourceId: string,
- subjectKey: string,
+ subjectKeys: string[],
bits: string[],
drive?: string,
inherit?: boolean
- ) => ipcRenderer.invoke('gfs:grant', { resourceId, subjectKey, bits, drive, inherit }),
+ ) => ipcRenderer.invoke('gfs:grant', { resourceId, subjectKeys, 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 }),
+ createShare: (resourceId: string, subjectKeys: string[], drive?: string) =>
+ ipcRenderer.invoke('gfs:createShare', { resourceId, subjectKeys, drive }),
},
agents: {
listMine: () => ipcRenderer.invoke('agents:listMine'),
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index b13cf91bc..a56efa389 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -228,7 +228,7 @@ declare global {
) => Promise<{ deleted: boolean; resourceId: string }>
grant: (
resourceId: string,
- subjectKey: string,
+ subjectKeys: string[],
bits: string[],
drive?: string,
inherit?: boolean
@@ -247,7 +247,7 @@ declare global {
}>
>
revokeGrant: (grantId: string) => Promise<void>
- createShare: (resourceId: string, subjectKey: string, drive?: string) => Promise<void>
+ createShare: (resourceId: string, subjectKeys: string[], drive?: string) => Promise<void>
}
agents: {
listMine: () => Promise<AgentWithMcpServers[]>
diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.ts
index dbc223c8f..dac8fbd92 100644
--- a/desktop-app/test/gfsUriHandler.test.ts
+++ b/desktop-app/test/gfsUriHandler.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
+import { ApiError } from '../src/httpClient.js'
import {
GfsClient,
type GfsTransport,
@@ -189,18 +190,29 @@ describe('GfsClient.affordances', () => {
})
describe('GfsClient.grant', () => {
- it('PUTs the grant with the structured subject + permissions', async () => {
+ it('PUTs ONE bulk request with the subjects[] array + permissions', async () => {
const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']
await new GfsClient(transport({ requestJson })).grant(
- { resourceId: RID, subject: { type: 'user', id: 'u2' }, permissions: ['read', 'write'] },
+ {
+ resourceId: RID,
+ subjects: [
+ { type: 'user', id: 'u2' },
+ { type: 'team', id: 't1' },
+ ],
+ permissions: ['read', 'write'],
+ },
'tok'
)
+ expect(requestJson).toHaveBeenCalledTimes(1)
expect(requestJson).toHaveBeenCalledWith('PUT', 'https://api.example/api/v1/me/gfs/grants', {
token: 'tok',
body: {
drive: 'main',
resourceId: RID,
- subject: { type: 'user', id: 'u2' },
+ subjects: [
+ { type: 'user', id: 'u2' },
+ { type: 'team', id: 't1' },
+ ],
permissions: ['read', 'write'],
inherit: false,
},
@@ -212,7 +224,7 @@ describe('GfsClient.grant', () => {
await new GfsClient(transport({ requestJson })).grant(
{
resourceId: RID,
- subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ subjects: [{ type: 'host', id: '1st:mcp-host/chatllm' }],
permissions: ['read'],
inherit: true,
},
@@ -223,12 +235,58 @@ describe('GfsClient.grant', () => {
body: {
drive: 'main',
resourceId: RID,
- subject: { type: 'host', id: '1st:mcp-host/chatllm' },
+ subjects: [{ type: 'host', id: '1st:mcp-host/chatllm' }],
permissions: ['read'],
inherit: true,
},
})
})
+
+ // FIX B — the server reports `invalidIndexes` (subjects_invalid / foreign_agent)
+ // and `retryAfterSeconds` (429) as SEPARATE response-body fields. httpClient
+ // stashes the raw body on ApiError.bodyText, but only `.message` survives the
+ // Electron IPC boundary. GfsClient re-throws with those fields appended in the
+ // exact shape gfsGrantErrors.ts (renderer) parses, so they reach the user.
+ it('embeds invalidIndexes from the error body into the thrown message', async () => {
+ const requestJson = vi.fn(async () => {
+ throw new ApiError(
+ '400 Bad Request: subjects_invalid',
+ 400,
+ JSON.stringify({ error: 'subjects_invalid', invalidIndexes: [0, 2] })
+ )
+ }) as GfsTransport['requestJson']
+ await expect(
+ new GfsClient(transport({ requestJson })).grant(
+ {
+ resourceId: RID,
+ subjects: [
+ { type: 'user', id: 'u2' },
+ { type: 'user', id: 'u3' },
+ { type: 'team', id: 't1' },
+ ],
+ permissions: ['read'],
+ },
+ 'tok'
+ )
+ ).rejects.toThrow(/subjects_invalid invalidIndexes=\[0,2\]/)
+ })
+
+ it('leaves the original error untouched when the body carries no structured fields', async () => {
+ const original = new ApiError(
+ '403 Forbidden: escalation_rejected',
+ 403,
+ JSON.stringify({ error: 'escalation_rejected' })
+ )
+ const requestJson = vi.fn(async () => {
+ throw original
+ }) as GfsTransport['requestJson']
+ await expect(
+ new GfsClient(transport({ requestJson })).grant(
+ { resourceId: RID, subjects: [{ type: 'user', id: 'u2' }], permissions: ['read'] },
+ 'tok'
+ )
+ ).rejects.toBe(original)
+ })
})
const GRANT_ID = '11111111-2222-3333-4444-555555555555'
@@ -278,6 +336,19 @@ describe('GfsClient.listGrants', () => {
new GfsClient(transport({ requestJson })).listGrants({ resourceId: RID }, 'tok')
).rejects.toBeInstanceOf(GfsUriError)
})
+
+ it('embeds retryAfterSeconds from a 429 body so the retry hint reaches the renderer', async () => {
+ const requestJson = vi.fn(async () => {
+ throw new ApiError(
+ '429 Too Many Requests: Too Many Requests',
+ 429,
+ JSON.stringify({ error: 'Too Many Requests', retryAfterSeconds: 45 })
+ )
+ }) as GfsTransport['requestJson']
+ await expect(
+ new GfsClient(transport({ requestJson })).listGrants({ resourceId: RID }, 'tok')
+ ).rejects.toThrow(/429 .*retryAfterSeconds=45/)
+ })
})
describe('GfsClient.revokeGrant', () => {
@@ -303,18 +374,29 @@ describe('GfsClient.revokeGrant', () => {
})
describe('GfsClient.createShare', () => {
- it('POSTs a read share covering descendants', async () => {
+ it('POSTs ONE bulk read share for the subjects[] array', async () => {
const requestJson = vi.fn(async () => ({ ok: true })) as GfsTransport['requestJson']
await new GfsClient(transport({ requestJson })).createShare(
- { resourceId: RID, subject: { type: 'team', id: 't1' }, permissions: ['read'] },
+ {
+ resourceId: RID,
+ subjects: [
+ { type: 'team', id: 't1' },
+ { type: 'user', id: 'u2' },
+ ],
+ permissions: ['read'],
+ },
'tok'
)
+ expect(requestJson).toHaveBeenCalledTimes(1)
expect(requestJson).toHaveBeenCalledWith('POST', 'https://api.example/api/v1/me/gfs/shares', {
token: 'tok',
body: {
drive: 'main',
resourceId: RID,
- subject: { type: 'team', id: 't1' },
+ subjects: [
+ { type: 'team', id: 't1' },
+ { type: 'user', id: 'u2' },
+ ],
permissions: ['read'],
includeDescendants: false,
},
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index fb8bdf234..24f516e82 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -314,23 +314,41 @@ describe('ipc host status stream handlers', () => {
await Promise.resolve(
handler?.(event, {
resourceId: ' 11111111-1111-1111-1111-111111111111 ',
- subjectKey: ' user:user-1 ',
+ subjectKeys: [' user:user-1 ', ' team:team-2 '],
bits: [' read ', ' manage_acl '],
drive: ' main ',
})
)
- // No inherit in the payload → forwarded as undefined (the client's
- // historical `false` default applies downstream).
+ // The bulk subjects[] array is sanitized element-wise. 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',
+ ['user:user-1', 'team:team-2'],
['read', 'manage_acl'],
'main',
undefined
)
})
+ it('rejects an empty or non-array subjectKeys payload before calling AppService', async () => {
+ const { event } = makeTrustedEvent()
+ const handler = testState.handlers.get('gfs:grant')
+
+ await expect(
+ Promise.resolve(
+ handler?.(event, {
+ resourceId: '11111111-1111-1111-1111-111111111111',
+ subjectKeys: [],
+ bits: ['read'],
+ drive: 'main',
+ })
+ )
+ ).rejects.toThrow('subjectKeys must be a non-empty array')
+ expect(service.grantGfs).not.toHaveBeenCalled()
+ })
+
it('forwards a boolean inherit and rejects a non-boolean one', async () => {
service.grantGfs.mockResolvedValue(undefined)
const { event } = makeTrustedEvent()
@@ -339,7 +357,7 @@ describe('ipc host status stream handlers', () => {
await Promise.resolve(
handler?.(event, {
resourceId: '11111111-1111-1111-1111-111111111111',
- subjectKey: 'host:1st:mcp-host/chatllm',
+ subjectKeys: ['host:1st:mcp-host/chatllm'],
bits: ['read'],
drive: 'main',
inherit: true,
@@ -347,7 +365,7 @@ describe('ipc host status stream handlers', () => {
)
expect(service.grantGfs).toHaveBeenCalledWith(
'11111111-1111-1111-1111-111111111111',
- 'host:1st:mcp-host/chatllm',
+ ['host:1st:mcp-host/chatllm'],
['read'],
'main',
true
@@ -357,7 +375,7 @@ describe('ipc host status stream handlers', () => {
Promise.resolve(
handler?.(event, {
resourceId: '11111111-1111-1111-1111-111111111111',
- subjectKey: 'host:1st:mcp-host/chatllm',
+ subjectKeys: ['host:1st:mcp-host/chatllm'],
bits: ['read'],
drive: 'main',
inherit: 'yes',
@@ -418,7 +436,7 @@ describe('ipc host status stream handlers', () => {
Promise.resolve(
handler?.(event, {
resourceId: '11111111-1111-1111-1111-111111111111',
- subjectKey: 'host:mcp-host/standalone',
+ subjectKeys: ['host:mcp-host/standalone'],
bits: ['read'],
drive: 'main',
})
diff --git a/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx b/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx
index 90b9702f0..6d4e56248 100644
--- a/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx
+++ b/desktop-app/ui/src/gfs/GfsAgentAccessSection/index.tsx
@@ -1,7 +1,6 @@
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'
@@ -47,17 +46,9 @@ export function GfsAgentAccessSection({
)
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)))
- }
+ // The bulk grant is atomic — a failure means NONE of the selected agents
+ // were granted, so keep the whole selection for a retry. Surface the mapped
+ // server verdict (e.g. managed_agent_permission_forbidden) — never swallow.
setError(describeGfsGrantError(grantError).message)
} finally {
setBusy(false)
diff --git a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
index 92cd0f922..172f82176 100644
--- a/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/GfsAgentAccessSection.test.tsx
@@ -1,7 +1,6 @@
// @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'
/**
@@ -87,21 +86,12 @@ describe('GfsAgentAccessSection', () => {
)
})
- it('surfaces a mapped server verdict and keeps only failed agents selected', async () => {
+ it('surfaces a mapped server verdict and keeps ALL selected agents on an atomic failure', async () => {
+ // The bulk grant is all-or-nothing: a rejection means NO agent was granted,
+ // so every selected agent stays selected for a retry (no partial-success).
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',
- },
- ]
- )
- )
+ .mockRejectedValue(new Error('403 Forbidden: managed_agent_permission_forbidden'))
render(
<GfsAgentAccessSection agents={agents} isDirectory onGrantAgents={onGrantAgents} />
)
@@ -111,10 +101,16 @@ describe('GfsAgentAccessSection', () => {
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(onGrantAgents).toHaveBeenCalledTimes(1)
+ expect(onGrantAgents).toHaveBeenCalledWith(
+ ['host:1st:mcp-host/chatllm', 'host:1st:mcp-host/chatllm-stateless'],
+ ['read'],
+ true
+ )
+ // SelectableOption only sets aria-pressed="true" while selected — both stay.
expect(
screen.getByRole('button', { name: 'chatllm' }).getAttribute('aria-pressed')
- ).not.toBe('true')
+ ).toBe('true')
expect(
screen.getByRole('button', { name: 'chatllm-stateless' }).getAttribute('aria-pressed')
).toBe('true')
diff --git a/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx b/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx
index aa131b6e3..632caaed0 100644
--- a/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx
+++ b/desktop-app/ui/src/gfs/__tests__/delegation.test.tsx
@@ -1,7 +1,6 @@
// @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 { GfsDelegationPanel } from '../delegation'
/**
@@ -68,8 +67,8 @@ describe('GfsDelegationPanel', () => {
expect(screen.getByRole('button', { name: 'Create share' })).toBeTruthy()
})
- it('surfaces a server no-escalation rejection (fail-loud, not swallowed)', async () => {
- const onGrant = vi.fn().mockRejectedValue(new Error('escalation_rejected'))
+ it('surfaces a server no-escalation rejection mapped to its human message (fail-loud)', async () => {
+ const onGrant = vi.fn().mockRejectedValue(new Error('403 Forbidden: escalation_rejected'))
render(
<GfsDelegationPanel
affordances={{ canDelegate: true, grantableBits: ['read'], canCreateShare: false }}
@@ -83,7 +82,8 @@ describe('GfsDelegationPanel', () => {
fireEvent.click(screen.getByRole('option', { name: /Delegate User/ }))
fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
- const alert = await screen.findByText(/escalation_rejected/)
+ // The panel maps the server code via describeGfsGrantError — never the raw code.
+ const alert = await screen.findByText('You can only grant permissions you already hold here.')
expect(alert).toBeTruthy()
})
@@ -124,16 +124,10 @@ describe('GfsDelegationPanel', () => {
expect(screen.queryByText('Context')).toBeNull()
})
- it('retains only failed subjects when a batch partially succeeds', async () => {
- const onGrant = vi
- .fn()
- .mockRejectedValue(
- new GfsSubjectBatchError(
- 'Grant access',
- ['user:successful'],
- [{ subjectKey: 'team:blocked', message: 'escalation_rejected' }]
- )
- )
+ it('keeps the whole selection when the atomic bulk grant is rejected', async () => {
+ // The bulk grant is all-or-nothing: a rejection means NOTHING landed, so
+ // every selected subject stays selected for a retry (no partial-success).
+ const onGrant = vi.fn().mockRejectedValue(new Error('400 Bad Request: subjects_invalid'))
render(
<GfsDelegationPanel
affordances={{ canDelegate: true, grantableBits: ['read'], canCreateShare: false }}
@@ -151,8 +145,10 @@ describe('GfsDelegationPanel', () => {
fireEvent.click(screen.getByRole('option', { name: /Blocked Team/ }))
fireEvent.click(screen.getByRole('button', { name: 'Grant access' }))
- await screen.findByText(/team:blocked \(escalation_rejected\)/)
- expect(screen.queryByRole('button', { name: 'Remove Successful User' })).toBeNull()
+ await screen.findByText('Some selected subjects are invalid and were rejected.')
+ expect(onGrant).toHaveBeenCalledTimes(1)
+ expect(onGrant).toHaveBeenCalledWith(['user:successful', 'team:blocked'], ['read'])
+ expect(screen.getByRole('button', { name: 'Remove Successful User' })).toBeTruthy()
expect(screen.getByRole('button', { name: 'Remove Blocked Team' })).toBeTruthy()
})
})
diff --git a/desktop-app/ui/src/gfs/delegation.tsx b/desktop-app/ui/src/gfs/delegation.tsx
index c28d6d59b..68654b452 100644
--- a/desktop-app/ui/src/gfs/delegation.tsx
+++ b/desktop-app/ui/src/gfs/delegation.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { Button, StatusBanner } from '@components/Common'
-import { GfsSubjectBatchError } from '@lib/gfsSubjectBatch'
+import { describeGfsGrantError } from '@lib/gfsGrantErrors'
import { GfsPermissionDropdown } from '@/gfs/GfsPermissionDropdown'
import { GfsSubjectPicker } from '@/gfs/GfsSubjectPicker'
import type { GfsDelegationPanelProps } from './delegation.types'
@@ -48,9 +48,11 @@ export function GfsDelegationPanel({
await action()
setSubjectKeys([])
} catch (e) {
- // Surface the server's verdict (e.g. escalation_rejected) — never swallow.
- if (e instanceof GfsSubjectBatchError) setSubjectKeys(e.failedSubjectKeys)
- setError(e instanceof Error ? e.message : String(e))
+ // The bulk grant/share is atomic — a failure means NONE of the subjects
+ // landed, so keep the whole selection for a retry. Surface the server's
+ // verdict (escalation_rejected, subjects_invalid with 1-based positions, a
+ // rate-limit retry, …) via the shared presentation map — never swallow it.
+ setError(describeGfsGrantError(e).message)
} finally {
setBusy(false)
}
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 7cec8b587..f1bee87e7 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -602,10 +602,10 @@ function ManageProbe() {
<button type="button" onClick={() => void ctrl.revokeGrant('grant-42')}>
revoke grant
</button>
- <button type="button" onClick={() => void ctrl.grant('user:bob', ['read'], true)}>
+ <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)}>
+ <button type="button" onClick={() => void ctrl.grant(['team:qa'], ['read'], false)}>
grant inherit false
</button>
</>
@@ -807,14 +807,14 @@ describe('useGfsBrowserController — grants list / revoke / inherit (#826)', ()
screen.getByRole('button', { name: 'grant inherit true' }).click()
})
await waitFor(() =>
- expect(grant).toHaveBeenCalledWith('root', 'user:bob', ['read'], 'main', true)
+ 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)
+ expect(grant).toHaveBeenCalledWith('root', ['team:qa'], ['read'], 'main', false)
)
})
})
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 8be2d3be7..442fb210b 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -347,17 +347,17 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// 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[], inherit?: boolean): Promise<void> => {
+ (subjectKeys: 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, inherit)
+ return window.clerum.gfs.grant(current.resourceId, subjectKeys, bits, DRIVE, inherit)
},
[current]
)
const createShare = useCallback(
- (subjectKey: string): Promise<void> => {
+ (subjectKeys: string[]): Promise<void> => {
if (!current) return Promise.reject(new Error('No resource selected'))
- return window.clerum.gfs.createShare(current.resourceId, subjectKey, DRIVE)
+ return window.clerum.gfs.createShare(current.resourceId, subjectKeys, DRIVE)
},
[current]
)
diff --git a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
index ebbe51bbc..f2df6c2e8 100644
--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
@@ -4,6 +4,12 @@ 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.
+ *
+ * `invalidIndexes` / `retryAfterSeconds` are SEPARATE response-body fields on the
+ * server; the desktop main process (uriHandler surfaceGfsGrantError) appends them
+ * to the error message as `invalidIndexes=[…]` / `retryAfterSeconds=…` BEFORE the
+ * IPC boundary drops `ApiError.bodyText`. These cases feed that real production
+ * message shape — not a JSON blob the wire never carries.
*/
describe('describeGfsGrantError', () => {
@@ -47,8 +53,12 @@ describe('describeGfsGrantError', () => {
})
it('appends 1-based subject positions when subjects_invalid carries invalidIndexes', () => {
+ // The exact message the main process now produces: the ApiError message with
+ // the appended `invalidIndexes=[…]` the server sent as a separate body field.
const presentation = describeGfsGrantError(
- new Error('400 Bad Request: subjects_invalid {"invalidIndexes":[0, 2]}')
+ new Error(
+ "Error invoking remote method 'gfs:grant': Error: 400 Bad Request: subjects_invalid invalidIndexes=[0,2]"
+ )
)
expect(presentation).toEqual({
@@ -59,8 +69,12 @@ describe('describeGfsGrantError', () => {
})
it('maps 429 with retryAfterSeconds into the retry message', () => {
+ // rate-limit body is `{ error: 'Too Many Requests', retryAfterSeconds }`; the
+ // main process appends `retryAfterSeconds=…` from the dropped body field.
const presentation = describeGfsGrantError(
- new Error('429 Too Many Requests: {"error":"rate_limited","retryAfterSeconds":42}')
+ new Error(
+ "Error invoking remote method 'gfs:grant': Error: 429 Too Many Requests: Too Many Requests retryAfterSeconds=42"
+ )
)
expect(presentation).toEqual({
diff --git a/desktop-app/ui/src/lib/__tests__/gfsSubjectBatch.test.ts b/desktop-app/ui/src/lib/__tests__/gfsSubjectBatch.test.ts
deleted file mode 100644
index 0b8c57765..000000000
--- a/desktop-app/ui/src/lib/__tests__/gfsSubjectBatch.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-import { GfsSubjectBatchError, runGfsSubjectBatch } from '@lib/gfsSubjectBatch'
-
-describe('runGfsSubjectBatch', () => {
- it('reports per-subject outcomes without stopping after the first failure', async () => {
- const action = vi.fn(async (subjectKey: string) => {
- if (subjectKey === 'team:blocked') throw new Error('escalation_rejected')
- })
-
- const error = await runGfsSubjectBatch(
- 'Grant access',
- ['user:ok', 'team:blocked', 'user:also-ok'],
- action
- ).catch(caught => caught)
-
- expect(action).toHaveBeenCalledTimes(3)
- expect(error).toBeInstanceOf(GfsSubjectBatchError)
- expect(error.failedSubjectKeys).toEqual(['team:blocked'])
- expect(error.succeededSubjectKeys).toEqual(['user:ok', 'user:also-ok'])
- expect(error.message).toContain('team:blocked (escalation_rejected)')
- expect(error.message).toContain('Succeeded: user:ok, user:also-ok')
- })
-})
diff --git a/desktop-app/ui/src/lib/gfsSubjectBatch.ts b/desktop-app/ui/src/lib/gfsSubjectBatch.ts
deleted file mode 100644
index 3f14a5900..000000000
--- a/desktop-app/ui/src/lib/gfsSubjectBatch.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-export class GfsSubjectBatchError extends Error {
- readonly failedSubjectKeys: string[]
- readonly succeededSubjectKeys: string[]
-
- constructor(
- actionLabel: string,
- succeededSubjectKeys: string[],
- failures: Array<{ subjectKey: string; message: string }>
- ) {
- const failedSummary = failures
- .map(failure => `${failure.subjectKey} (${failure.message})`)
- .join(', ')
- const succeededSummary = succeededSubjectKeys.length
- ? ` Succeeded: ${succeededSubjectKeys.join(', ')}.`
- : ''
- super(`${actionLabel} failed for ${failedSummary}.${succeededSummary}`)
- this.name = 'GfsSubjectBatchError'
- this.failedSubjectKeys = failures.map(failure => failure.subjectKey)
- this.succeededSubjectKeys = succeededSubjectKeys
- }
-}
-
-export async function runGfsSubjectBatch(
- actionLabel: string,
- subjectKeys: string[],
- action: (subjectKey: string) => Promise<void>
-): Promise<string[]> {
- const succeededSubjectKeys: string[] = []
- const failures: Array<{ subjectKey: string; message: string }> = []
-
- for (const subjectKey of subjectKeys) {
- try {
- await action(subjectKey)
- succeededSubjectKeys.push(subjectKey)
- } catch (error) {
- failures.push({
- subjectKey,
- message: error instanceof Error ? error.message : String(error),
- })
- }
- }
-
- if (failures.length > 0) {
- throw new GfsSubjectBatchError(actionLabel, succeededSubjectKeys, failures)
- }
- return succeededSubjectKeys
-}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index c792924ac..8e75585ae 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -18,7 +18,6 @@ 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,
@@ -233,46 +232,23 @@ export function FilesPage({ pushToast }: FilesPageProps) {
return () => window.removeEventListener('keydown', handleKeyDown)
}, [manageOpen, openLinkOpen])
+ // One atomic bulk grant for every selected subject — the server grants all or
+ // none (a `subjects_invalid` rejects the whole request), so there is no
+ // partial-success outcome. A failure propagates to the panel's catch, which
+ // maps the server verdict via describeGfsGrantError. No inherit argument here:
+ // the user/team panel keeps inherit:false.
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) {
- if (error instanceof GfsSubjectBatchError && error.succeededSubjectKeys.length > 0) {
- pushToast?.(
- `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
- }
+ await ctrl.grant(subjectKeys, bits)
pushToast?.(
`Access granted to ${subjectKeys.length} ${subjectKeys.length === 1 ? 'subject' : 'subjects'}`,
'success'
)
+ // The grant PUT returns no ids — list-after-write is the revoke-id source.
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
- }
+ await ctrl.grant(subjectKeys, bits, inherit)
pushToast?.(
`Access granted to ${subjectKeys.length} ${subjectKeys.length === 1 ? 'agent' : 'agents'}`,
'success'
@@ -290,19 +266,7 @@ export function FilesPage({ pushToast }: FilesPageProps) {
}
const handleCreateShare = async (subjectKeys: string[]) => {
- try {
- await runGfsSubjectBatch('Create share', subjectKeys, subjectKey =>
- ctrl.createShare(subjectKey)
- )
- } catch (error) {
- if (error instanceof GfsSubjectBatchError && error.succeededSubjectKeys.length > 0) {
- pushToast?.(
- `${error.succeededSubjectKeys.length} of ${subjectKeys.length} shares created`,
- 'success'
- )
- }
- throw error
- }
+ await ctrl.createShare(subjectKeys)
pushToast?.(
`${subjectKeys.length} ${subjectKeys.length === 1 ? 'share' : 'shares'} created`,
'success'
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index f6fc118fc..5ef32fb7d 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -810,7 +810,7 @@ describe('FilesPage', () => {
fireEvent.click(screen.getByRole('button', { name: 'Grant agent access' }))
await waitFor(() =>
- expect(grant).toHaveBeenCalledWith('host:1st:mcp-host/chatllm', ['read'], true)
+ 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')
@@ -875,12 +875,12 @@ describe('FilesPage', () => {
// 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(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 () => {
+ it('issues ONE atomic bulk grant and does not refetch or toast when it is rejected', async () => {
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
@@ -915,12 +915,9 @@ describe('FilesPage', () => {
},
},
})
- // 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'))
+ // The bulk grant is atomic: the whole request is rejected, so NOTHING landed.
+ // No success toast, and no list-after-write (there is nothing new to reveal).
+ const grant = vi.fn().mockRejectedValue(new Error('400 Bad Request: subjects_invalid'))
const refreshGrants = vi.fn(async () => undefined)
const pushToast = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
@@ -950,9 +947,17 @@ describe('FilesPage', () => {
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')
+ await waitFor(() =>
+ expect(grant).toHaveBeenCalledWith(['user:user-2', 'user:user-3'], ['read'])
+ )
+ expect(grant).toHaveBeenCalledTimes(1)
+ // The panel maps the verdict; no partial-success toast, no list-after-write.
+ await screen.findByText('Some selected subjects are invalid and were rejected.')
+ expect(refreshGrants).not.toHaveBeenCalled()
+ expect(pushToast).not.toHaveBeenCalledWith(
+ expect.stringContaining('Access granted'),
+ 'success'
+ )
})
it('revokes a grant from the who-has-access list and toasts the outcome', async () => {