Skip to content

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

TypeScript
17.9 KB
Raw Blame
/**
 * Producer-backed GFS wire fixtures for renderer tests (pr-discipline T1).
 *
 * The renderer consumes `window.clerum.gfs.{listChildren,listAccessible,download}`.
 * That bridge is a pure pass-through: preload → `ipc.ts` handler →
 * `AppService.list*` → `GfsClient.*`. The ONLY shape transform along the way is
 * `GfsClient`'s envelope `unwrap`, and the ONLY serialization is Electron's
 * structured clone across the IPC boundary. So the truthful in-process producer
 * of the shape the tree/preview renders is `GfsClient` (desktop-app/src), not the
 * renderer `.d.ts`.
 *
 * A hand-written fixture typed against `window.clerum.gfs.*` (the `.d.ts`) proves
 * nothing: the `.d.ts` is a hand-maintained mirror, so a producer-contract change
 * (a renamed/dropped field, a change to `unwrap`) or an IPC-serialization change
 * would break production while such a test stayed green. These builders instead
 * run the caller-supplied resource views THROUGH the real `GfsClient` against its
 * designed transport seam ("Inject the API transport so the client is testable
 * without a real backend" — uriHandler.ts) and then through `structuredClone` to
 * model the IPC boundary. The output IS what the renderer receives in production.
 *
 * The inputs are typed as `GfsChildView` / `GfsAccessibleResource` /
 * `ResolvedGfsResource` — desktop-app's OWN declaration of the gfs-controller
 * `toView` contract (kept in lockstep with the server by those interfaces). We
 * cannot call gfs-controller (a separate service/repo) from here, so that HTTP
 * shape is asserted by those types, not by a live round-trip; the transport is
 * the honest boundary between this repo's producer and that service. Everything
 * below the transport is the real producer.
 *
 * The list* return types are the renderer boundary types
 * (`Awaited<ReturnType<typeof window.clerum.gfs.*>>`), so if the producer's
 * emitted page and the renderer `.d.ts` ever drift, this module fails to
 * typecheck — the compile-time half of the same guarantee. (download is bound to
 * the producer's own output instead; see the note on `DownloadResult` below.)
 *
 * H8 (fail-closed tests) reuses these builders — do not inline gfs wire shapes
 * in a new tree/preview test.
 */
import { createServer } from 'node:http'
import {
  type GfsAccessibleResource,
  type GfsChildView,
  GfsClient,
  type GfsGrantListItem,
  type GfsHeldAffordances,
  type GfsShareListItem,
  type GfsTransport,
  type ResolvedGfsResource,
} from '../../../../src/gfs/uriHandler.js'
import { requestJson } from '../../../../src/httpClient.js'

// listChildren/listAccessible bind cleanly to the renderer boundary types (the
// `.d.ts` the tree consumes), so a drift between the producer's emitted page and
// the renderer contract fails this module's typecheck.
type ListChildrenPage = Awaited<ReturnType<typeof window.clerum.gfs.listChildren>>
type ListAccessiblePage = Awaited<ReturnType<typeof window.clerum.gfs.listAccessible>>
// download binds to the PRODUCER's own output, not the renderer `.d.ts`: the
// `.d.ts` declares `download.resource.pathCache` as required while the producer's
// `ResolvedGfsResource` leaves it optional, so the mirror overstates the contract
// (a pre-existing `.d.ts` inaccuracy, out of scope for this fixture change). The
// tree's download consumer (`saveGfsFileToDisk`) reads only `bytes`.
type DownloadResult = Awaited<ReturnType<GfsClient['download']>>

/** A one-shot transport standing in for the gfs-controller HTTP boundary. It
 *  returns the given enveloped body for the JSON request and the given bytes for
 *  a proxy fetch — the seam `GfsClient` was built to be injected with. */
function stubTransport(jsonBody: unknown, bytes: ArrayBuffer = new ArrayBuffer(0)): GfsTransport {
  return {
    baseUrl: 'https://gfs.fixture.test',
    requestJson: async () => jsonBody as never,
    fetchBytes: async () => bytes,
  }
}

const SESSION_TOKEN = 'fixture-session-token'

/** A `GfsChildView` — the gfs-controller `toView` child shape as desktop-app
 *  declares it. Flows through the real producer below; never consumed directly. */
export function childView(
  resourceId: string,
  name: string,
  kind: 'file' | 'directory',
  overrides: Partial<GfsChildView> = {}
): GfsChildView {
  return {
    resourceId,
    rid: resourceId,
    gfsUri: `gfs://main/${resourceId}`,
    drive: 'main',
    parentResourceId: null,
    name,
    kind,
    path: `/${name}`,
    version: 1,
    bytes: 4,
    ...overrides,
  }
}

/** A `GfsAccessibleResource` — the "Shared with me" root-item shape. */
export function accessibleResource(
  resourceId: string,
  name: string,
  kind: 'file' | 'directory',
  overrides: Partial<GfsAccessibleResource> = {}
): GfsAccessibleResource {
  return {
    resourceId,
    rid: resourceId,
    gfsUri: `gfs://main/${resourceId}`,
    drive: 'main',
    parentResourceId: null,
    name,
    kind,
    path: `/${name}`,
    version: 1,
    bytes: 4,
    ...overrides,
  }
}

/** Run child views through the real `GfsClient.listChildren` (envelope unwrap)
 *  and the IPC structured-clone boundary — the exact value the renderer's
 *  `window.clerum.gfs.listChildren` resolves to in production. */
export async function listChildrenPage(
  items: GfsChildView[],
  nextCursor: string | null = null
): Promise<ListChildrenPage> {
  const client = new GfsClient(stubTransport({ ok: true, data: { items, nextCursor } }))
  const page = await client.listChildren('fixture-parent', SESSION_TOKEN, { drive: 'main' })
  return structuredClone(page)
}

/** Run accessible resources through the real `GfsClient.listAccessible`. */
export async function listAccessiblePage(
  items: GfsAccessibleResource[],
  nextCursor: string | null = null
): Promise<ListAccessiblePage> {
  const client = new GfsClient(stubTransport({ ok: true, data: { items, nextCursor } }))
  const page = await client.listAccessible(SESSION_TOKEN, { drive: 'main' })
  return structuredClone(page)
}

/** Run a resolve + byte fetch through the real `GfsClient.download` — the
 *  `{ resource, bytes }` shape the download consumer (`saveGfsFileToDisk`)
 *  reads. `bytes` survives the structured-clone IPC boundary as an ArrayBuffer. */
export async function downloadResult(
  resource: ResolvedGfsResource,
  bytes: ArrayBuffer = new ArrayBuffer(4)
): Promise<DownloadResult> {
  const client = new GfsClient(stubTransport({ ok: true, data: resource }, bytes))
  const out = await client.download(resource.gfsUri, SESSION_TOKEN)
  return structuredClone(out)
}

// The `onOpenGfsResource` payload the plugin SDK pushes across the preload
// boundary — bound to the renderer `.d.ts` callback arg, so a drift between what
// the runtime emits and what the renderer expects fails this module's typecheck.
type OpenGfsResourcePayload = Parameters<
  Parameters<typeof window.clerum.pluginSdk.onOpenGfsResource>[0]
>[0]

/**
 * The `onOpenGfsResource` wire payload as `pluginSdkRuntime.openGfsResource`
 * emits it: it resolves the URI with the user's session (the real
 * `GfsClient.resolveUri` below — envelope unwrap, the same seam `download` uses)
 * and then projects five fields onto the wire. That runtime imports `electron`
 * at module load, so it cannot be driven from a jsdom renderer test (the awkward
 * case T1 anticipates); the resolve half runs through this repo's REAL producer
 * and the runtime's projection is mirrored here in ONE place —
 * `bytes` is coerced to `null` when the resolved resource omits it, exactly as
 * the runtime does — then structured-cloned to model the IPC boundary.
 */
export async function openGfsResourcePayload(
  resource: ResolvedGfsResource
): Promise<OpenGfsResourcePayload> {
  const client = new GfsClient(stubTransport({ ok: true, data: resource }))
  const resolved = await client.resolveUri(resource.gfsUri, SESSION_TOKEN)
  return structuredClone({
    gfsUri: resolved.gfsUri ?? resource.gfsUri,
    name: resolved.name,
    kind: resolved.kind,
    bytes: typeof resolved.bytes === 'number' ? resolved.bytes : null,
    version: resolved.version,
  })
}

/**
 * The Error message `window.clerum.gfs.resolve` rejects with when a per-resource
 * read is denied (the file was unshared) — derived, not hand-written (T1).
 *
 * Unlike the success builders above, a denial cannot go through `stubTransport`:
 * that stub returns its body and lets `GfsClient.unwrap` throw a `GfsUriError`,
 * but that envelope branch is UNREACHABLE for a resolve denial in production. The
 * server returns an HTTP 403 (gfsc `envelope.ts` `toResponse` → `{ ok:false,
 * error:{ code:'forbidden', … } }`, forwarded verbatim through control-api and
 * external-rest-api since 403 ∈ its PROPAGATED set), and the desktop's REAL
 * `httpClient.requestJson` — the exact transport `appService.ts` constructs
 * `GfsClient` with — mints an `ApiError` from that non-2xx BEFORE `unwrap` ever
 * runs. Only that `ApiError.message` survives the Electron IPC boundary to the
 * renderer. So the faithful producer is the real client + real transport run
 * against a temp 403 endpoint; the only hand-modeled part is the gfsc error body,
 * the cross-service HTTP boundary this module already treats as the honest seam.
 */
export async function resolveDeniedMessage(
  gfsUri = 'gfs://main/secret',
  errorBody: { code: string; message: string } = {
    code: 'forbidden',
    message: 'not authorized to read this resource',
  },
  status = 403
): Promise<string> {
  const server = createServer((_req, res) => {
    res.writeHead(status, { 'content-type': 'application/json' })
    res.end(JSON.stringify({ ok: false, error: errorBody }))
  })
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()))
  try {
    const address = server.address()
    const port = typeof address === 'object' && address ? address.port : 0
    const client = new GfsClient({
      baseUrl: `http://127.0.0.1:${port}`,
      requestJson,
      fetchBytes: async () => new ArrayBuffer(0),
    })
    await client.resolveUri(gfsUri, SESSION_TOKEN)
    throw new Error(`expected resolve to reject with a ${status} denial`)
  } catch (error) {
    if (!(error instanceof Error)) return String(error)
    return error.message
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
  }
}

/** A `ResolvedGfsResource` for a downloadable file, for `downloadResult`. */
export function resolvedFile(
  resourceId: string,
  name: string,
  overrides: Partial<ResolvedGfsResource> = {}
): ResolvedGfsResource {
  return {
    resourceId,
    rid: resourceId,
    gfsUri: `gfs://main/${resourceId}`,
    drive: 'main',
    parentResourceId: null,
    name,
    kind: 'file',
    path: `/${name}`,
    version: 1,
    bytes: 4,
    ...overrides,
  }
}

/** A `ResolvedGfsResource` for an openable directory. */
export function resolvedDirectory(
  resourceId: string,
  name: string,
  overrides: Partial<ResolvedGfsResource> = {}
): ResolvedGfsResource {
  return {
    resourceId,
    rid: resourceId,
    gfsUri: `gfs://main/${resourceId}`,
    drive: 'main',
    parentResourceId: null,
    name,
    kind: 'directory',
    path: `/${name}`,
    version: 1,
    ...overrides,
  }
}

/** Resolve a resource through the real GfsClient and structured-clone IPC seam. */
export async function resolveResource(resource: ResolvedGfsResource): Promise<ResolvedGfsResource> {
  const client = new GfsClient(stubTransport({ ok: true, data: resource }))
  return structuredClone(await client.resolveUri(resource.gfsUri, SESSION_TOKEN))
}

/** A `GfsHeldAffordances` — the direct (NOT enveloped) affordances route body. */
export function heldAffordances(
  held: string[],
  overrides: Partial<GfsHeldAffordances> = {}
): GfsHeldAffordances {
  return { held, isOperator: false, ...overrides }
}

/**
 * Run held bits through the real `GfsClient.affordances` (the direct,
 * un-enveloped affordances route) and the IPC structured-clone boundary —
 * the value `window.clerum.gfs.affordances` resolves with in production.
 */
export async function affordancesResult(held: GfsHeldAffordances): Promise<GfsHeldAffordances> {
  const client = new GfsClient(stubTransport({ ...held }))
  return structuredClone(await client.affordances('fixture-parent', SESSION_TOKEN, 'main'))
}

/**
 * The Error message `window.clerum.gfs.affordances` rejects with when the
 * route answers a non-2xx — derived, not hand-written (T1), at the same honest
 * seam as `resolveDeniedMessage`: the real `httpClient.requestJson` mints the
 * ApiError from the HTTP status, and `GfsClient.affordances` surfaces it with
 * its vetted `httpStatus=` marker.
 */
export async function affordancesFailureMessage(
  status = 500,
  body: { code: string; message: string } = {
    code: 'internal',
    message: 'gfs controller failed',
  },
  resourceId = 'fixture-parent'
): Promise<string> {
  const server = createServer((_req, res) => {
    res.writeHead(status, { 'content-type': 'application/json' })
    res.end(JSON.stringify({ ok: false, error: body }))
  })
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()))
  try {
    const address = server.address()
    const port = typeof address === 'object' && address ? address.port : 0
    const client = new GfsClient({
      baseUrl: `http://127.0.0.1:${port}`,
      requestJson,
      fetchBytes: async () => new ArrayBuffer(0),
    })
    await client.affordances(resourceId, SESSION_TOKEN, 'main')
    throw new Error(`expected affordances to reject with a ${status} failure`)
  } catch (error) {
    if (!(error instanceof Error)) return String(error)
    return error.message
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
  }
}

/**
 * The Error message a transport-level affordances failure produces (dead
 * endpoint, real `httpClient.requestJson`) — connection refused with no HTTP
 * response, so `parseHttpStatus` must read no status from it.
 */
export async function affordancesTransportFailureMessage(): Promise<string> {
  const client = new GfsClient({
    baseUrl: 'http://127.0.0.1:9',
    requestJson,
    fetchBytes: async () => new ArrayBuffer(0),
  })
  try {
    await client.affordances('fixture-parent', SESSION_TOKEN, 'main')
    throw new Error('expected affordances to fail at the transport layer')
  } catch (error) {
    if (!(error instanceof Error)) return String(error)
    return error.message
  }
}

// ── ACL list fixtures (R1-H3 inherited-access walk) ──────────────────────────
// Appended without touching the H1/H8 helpers above; distinct names.

/**
 * Run grant rows through the real `GfsClient.listGrants` (envelope unwrap +
 * items-array validation) and the IPC structured-clone boundary — the exact
 * value `window.clerum.gfs.listGrants` resolves with in production. Bound to
 * the renderer `.d.ts` return type so producer/renderer drift fails the
 * typecheck, like the builders above.
 */
export async function grantsListPage(
  items: GfsGrantListItem[]
): Promise<Awaited<ReturnType<typeof window.clerum.gfs.listGrants>>> {
  const client = new GfsClient(stubTransport({ items }))
  return structuredClone(await client.listGrants({ resourceId: 'fixture-parent' }, SESSION_TOKEN))
}

/** Same as `grantsListPage` for the shares list. */
export async function sharesListPage(
  items: GfsShareListItem[]
): Promise<Awaited<ReturnType<typeof window.clerum.gfs.listShares>>> {
  const client = new GfsClient(stubTransport({ items }))
  return structuredClone(await client.listShares({ resourceId: 'fixture-parent' }, SESSION_TOKEN))
}

/**
 * The Error message a GfsClient read route rejects with when the server answers
 * a non-2xx — derived, not hand-written (T1), at the same honest seam as
 * `resolveDeniedMessage`/`affordancesFailureMessage`: a temp HTTP endpoint
 * returns the gfsc error envelope, the real `httpClient.requestJson` mints the
 * `ApiError`, and `surfaceGfsGrantError` appends the vetted `httpStatus=` (and
 * `retryAfterSeconds=`) markers the renderer classifies on. Generalized over
 * the invoked client method; the ACL wrappers below keep call sites readable.
 */
export async function gfsRouteFailureMessage(
  invoke: (client: GfsClient) => Promise<unknown>,
  status = 403,
  body: { code: string; message: string } = {
    code: 'forbidden',
    message: 'not authorized',
  },
  headers: Record<string, string> = {}
): Promise<string> {
  const server = createServer((_req, res) => {
    res.writeHead(status, { 'content-type': 'application/json', ...headers })
    res.end(JSON.stringify({ ok: false, error: body }))
  })
  await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()))
  try {
    const address = server.address()
    const port = typeof address === 'object' && address ? address.port : 0
    const client = new GfsClient({
      baseUrl: `http://127.0.0.1:${port}`,
      requestJson,
      fetchBytes: async () => new ArrayBuffer(0),
    })
    await invoke(client)
    throw new Error(`expected the gfs route to reject with a ${status} failure`)
  } catch (error) {
    if (!(error instanceof Error)) return String(error)
    return error.message
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()))
  }
}

/** Producer-derived grants-list rejection (default: a 403 manage_acl denial). */
export async function listGrantsFailureMessage(
  status = 403,
  body: { code: string; message: string } = {
    code: 'manage_acl_required',
    message: 'viewing the access list requires manage_acl',
  }
): Promise<string> {
  return gfsRouteFailureMessage(
    client => client.listGrants({ resourceId: 'fixture-parent' }, SESSION_TOKEN),
    status,
    body
  )
}

/** Producer-derived shares-list rejection (default: a 403 manage_acl denial). */
export async function listSharesFailureMessage(
  status = 403,
  body: { code: string; message: string } = {
    code: 'manage_acl_required',
    message: 'viewing the share list requires manage_acl',
  }
): Promise<string> {
  return gfsRouteFailureMessage(
    client => client.listShares({ resourceId: 'fixture-parent' }, SESSION_TOKEN),
    status,
    body
  )
}