# AGENTS.md This file provides guidance to coding agents when working with code in this repository. > **Tip**: If you find yourself correcting the agent during interactive work, suggest adding a new rule to this file so the lesson is captured for future sessions. ## Project Overview This repository is the reference template for building, type-checking, testing and releasing a Freelens extension. The Freelens extension docs (`docs/extensions/` in freelensapp/freelens) define the API contract and point here for everything around it, so the build, type-check and test patterns in this file are the ones other extensions copy, and each comes with its reason. - **Language**: TypeScript 7.x - **Runtime**: Freelens >= 2.0.0 (extension API v2) - **Toolchain**: Node.js 24.x, yq 4.x and cosign 3.x (`mise.toml` with `mise.lock`; Node also in `.nvmrc`) - **Package manager**: pnpm 12.x (`packageManager`, run through corepack) - **License**: MIT Library and tool versions follow the Freelens stack exactly: the catalog in Freelens's `pnpm-workspace.yaml` for libraries, the root `package.json` scripts of Freelens for tools run with `pnpm dlx` (Biome, knip, Trunk launcher), and Freelens's `mise.toml` and `.nvmrc` for Node and the other mise tools. Renovate keeps them there: custom datasources in `.renovaterc.json` read the versions from the same Freelens files on `main`, so an update arrives only once Freelens has adopted it, at that version, in one `Freelens dependencies` group PR together with a release of `@freelensapp/extensions`. A dependency added to `package.json` follows the Freelens catalog unless the catalog rule excludes it; one that Freelens does not have must be excluded there, or its lookup fails on the Dependency Dashboard. The catalog rule matches only `dependencies` and `devDependencies`, so an override copied from Freelens's `pnpm-workspace.yaml`, such as `@kubernetes/client-node>@types/node`, is otherwise looked up on npm and runs ahead of Freelens. Such an override gets a rule of its own, next to the catalog rule: `matchManagers: ["npm"]`, the override's key in `matchDepNames`, `overrideDatasource: "custom.freelens-catalog"`, the overridden package in `overridePackageName`, and the catalog rule's `rangeStrategy`, `minimumReleaseAge` and `groupName` (freelensapp/freelens-for-claude-extension@f2f49241828f201890423e070655c2dc04120b23). This template has no override. What Freelens does not define (GitHub Actions, the tool versions in the workflows, `shx`) Renovate updates as usual. pnpm is the exception: Renovate updates it from the npm registry, in a pull request of its own, and not to the version of Freelens's `packageManager`. `packageManager` carries a Corepack hash (`+sha512.…`), and Renovate updates the hash only from the digest of the new version, which the registry has and a custom datasource does not; without it the update fails with "no valid digest available". `mise.lock` pins a checksum and a URL per tool for all eight platforms; after changing `mise.toml`, run `mise lock` (not only `mise install`, which re-locks just the current platform). `mise.lock` is lockfile revision 3 (`lockfile_version = 3`), which needs mise 2026.9.16 or newer; older versions reject it. `@freelensapp/extensions` is pinned to one exact version. The libraries the host provides at runtime (`react`, `react-dom`, `mobx`, `mobx-react`) and their types are devDependencies only, for compiling and testing; `electron` is a devDependency for its types only. pnpm settings live in `pnpm-workspace.yaml`. A dependency runs its install scripts only when `allowBuilds` sets it to `true`; a new dependency with install scripts that is not listed there fails `pnpm install`, so add it with `true` or `false` deliberately. pnpm refuses versions younger than its `minimumReleaseAge` (1 day), with `@freelensapp/extensions` excluded because a Freelens release is adopted on the day it is published, together with the stack it was built with. An exact version that Freelens lets in early for a security fix, such as `electron@44.10.0`, is excluded here too, with the same comment, so that the update installs; the entry goes once the version is older than the policy. `strictPeerDependencies: true` makes `pnpm install` fail when the extension's own copy of a shared library is outside the peer range that `@freelensapp/extensions` declares for it: `react`, `react-dom`, `@types/react`, `@types/react-dom`, `mobx`, `mobx-react`, `monaco-editor` and `electron`. These peers are optional, so they are checked only when the extension declares the library, which it does for every one it imports or compiles against. Without the setting pnpm reports a mismatch as one warning line and installs anyway. Freelens does not set it, because its own tree takes these libraries from its catalog, which defines the ranges; an extension declares its own copies, and these peers are the only place where they are compared with the versions the host runs. The types are peers as well, so the package's declaration compiles against the extension's own `@types/react` and `@types/react-dom`, one copy of each, and the package does not install them for it. An extension with renderer code declares both: the declaration imports its React types from `react` and `react-dom`, and the renderer's JSX and component props are checked against them. A main-only extension needs neither; its code reaches no React type, and `skipLibCheck` leaves the declaration's own imports unchecked. An extension that renders `Renderer.Component.MonacoEditor` compiles against `monaco-editor` without importing it, so it declares `monaco-editor` in `devDependencies` at the host's version as well. `MonacoEditorProps` takes its `options` and callback types from that package; without it they are `any`, and `skipLibCheck` hides the unresolved import. This template renders no editor and does not declare it ("The host-provided libraries, and how to mark them external" in Freelens's `migrating-from-v1.md`, and contracts C3 and C11 of `api.md`). ## Common Commands ```bash # Type checking pnpm type:check # All of the programs below, in this order pnpm type:check:sources # main and renderer, each with src/common/ pnpm type:check:tests # Tests and test support pnpm type:check:tooling # Vite and Vitest configs, build plugins pnpm type:check:integration # Integration tests pnpm type:check:environments # Environment tests # Linting & formatting pnpm biome:check # TypeScript/TSX, JS, JSON, CSS, SCSS, HTML, YAML, Markdown (biome) pnpm biome:fix # Auto-fix the formats above pnpm trunk:check # TOML, shell, workflows, yamllint, and Biome again (changed files) pnpm trunk:fix # Auto-fix TOML, shell, and the Biome formats pnpm lint:check # Alias for biome:check pnpm lint:fix # Alias for biome:fix pnpm knip:check # Unused files, unused and unlisted dependencies (knip) # Tests pnpm test:unit # vitest pnpm test:integration # vitest, against Freelens dev with a kind cluster # Build pnpm build # Both Vite runs, without the type check pnpm dev # Both Vite runs in watch mode, for a directory install # Pack for testing pnpm pack:dev # Bump prerelease version, build, and create .tgz for install in Freelens app # Clean pnpm clean # Clean dist/ pnpm clean:dts # Remove generated *.d.scss.ts files pnpm clean:all # Clean everything (dist, dts, node_modules, tgz) ``` ## Architecture ```text src/ main/index.ts # Main entry (Main.LensExtension): loads the preferences store renderer/index.tsx # Renderer entry (Renderer.LensExtension): every registration renderer/api/example/ # Example model per API version (v1alpha1, v1alpha2), with its tests renderer/api/types.ts # Types shared by the models renderer/pages/ # List page per API version, and their CSS module renderer/details/ # Details panel per API version renderer/menus/ # Suspend/Resume menu item per API version renderer/components/ # createAvailableVersionPage, ErrorBoundary and its registration wrappers, ErrorPage renderer/preferences/ # The preference input and hint renderer/icons/ # SVG icons, imported with ?raw renderer/vars.scss # SCSS variables common/store/ # ExamplePreferencesStore, loaded by main and renderer test/freelens-extensions.ts # Runtime stub of @freelensapp/extensions for Vitest environment-tests/ # Probes for the per-environment programs build/ # Vite plugins: host modules, standard decorators, CSS module declarations integration/__tests__/ # Integration tests, run against Freelens dev over CDP, and their shared module integration/fixtures/ # Test objects of the integration tests per API version examples/ # CRDs and test objects per API version ``` Build output goes to `dist/`: `main.js`, `renderer.js` and `renderer.css`, with source maps. `main` and `renderer` in `package.json` point at the two entries. ## CRD KubeObject Pattern A model is a subclass of `Renderer.K8sApi.LensExtensionKubeObject`, one file per API version: `src/renderer/api/example/example-v1alpha1.ts` and `example-v1alpha2.ts`, each exporting a class named `Example`. The host reads the model's metadata from the class, through `static readonly` properties. The objects it hands to the extension, in a list, a details panel or a menu item, come from the host's store for the resource: they are instances of the host's `KubeObject`, not of the extension's subclass. The methods of `KubeObject` itself are there (`getName()`, `getNs()`, `getCreationTimestamp()`, `getSearchFields()`); a method the subclass defines is not, and calling it throws. So: - **Metadata**: `static readonly` `kind`, `namespaced`, `apiBase` and `crd`. - **Instance type**: `declare kind` and `declare apiVersion`, with the class's kind and version as literals. Two versions of a kind usually differ only in optional fields, so without the literals their classes are assignable to each other, and `detailsFor` and `menuItemFor` accept a component written for the other version (see "Renderer Components"). `declare` emits nothing, so the runtime object is the host's as before. - **Per-object logic**: a `static` method that takes the object, such as `Example.getSuspended(object)`. - **Fields**: read `object.spec` and `object.status` through the model's typed `ExampleSpec` and `ExampleStatus`. - **Forbidden**: instance methods on the subclass; a fallback such as `typeof (object as any).getSuspended === "function" ? ...`, which always takes the fallback; `as any`. ```typescript export class Example extends Renderer.K8sApi.LensExtensionKubeObject< Renderer.K8sApi.KubeObjectMetadata, ExampleStatus, ExampleSpec > { declare kind: "Example"; declare apiVersion: "example.freelens.app/v1alpha2"; static readonly kind = "Example"; static readonly namespaced = true; static readonly apiBase = "/apis/example.freelens.app/v1alpha2/examples"; static readonly crd: ExampleKubeObjectCRD = { apiVersions: ["example.freelens.app/v1alpha2"], plural: "examples", singular: "example", shortNames: ["ex"], title: "Examples", }; static getSuspended(object: Example): boolean { return object.spec.suspended ?? false; } } export class ExampleApi extends Renderer.K8sApi.KubeApi {} export class ExampleStore extends Renderer.K8sApi.KubeObjectStore {} ``` The file also exports a `KubeApi` and a `KubeObjectStore` subclass. The list page uses the `KubeApi` type for `KubeObjectListLayout`; neither is instantiated, because the store comes from the host, through `Example.getStore()`. `src/renderer/index.tsx` registers each version's details panel (`kubeObjectDetailItems`) and menu item (`kubeObjectMenuItems`) with `Renderer.K8sApi.detailsFor` and `Renderer.K8sApi.menuItemFor`, which take `kind` and `crd.apiVersions` from the model class, and one "Examples" page (`clusterPages`, `clusterPageMenus`). That page is made by `createAvailableVersionPage` from the list pages of both versions, newest first: it renders the first one whose store the host has, and a "not available" message when the cluster serves neither. `customResources` lists the model classes of both versions. The host reads the group and plural from each class's `crd`, and while the extension is enabled it leaves the resource out of the Custom Resources tree of the cluster sidebar, where it would otherwise be listed a second time next to the "Examples" page. Both versions name the same group and plural, so either class alone would do; both are listed so that removing one version leaves the other registered. The definition stays in the Definitions list, and the host's own list and details stay reachable by URL and from the command palette. A model the extension only decorates, with a details panel or a menu item and no page of its own, stays out of the field: registered, it would leave the tree with nothing in its place. The host rejects an entry it cannot read (no `kind`, no `crd` or `apiBase`, a core-group resource) with an error in the log, and the resource stays in the tree (contract C6 of `api.md`). The page it returns is an `observer`. `getStore()` reads the host's API registry, which is observable, and the host registers a CRD's APIs only after the cluster frame has loaded the CRDs. Freelens restores the last page when a cluster is opened, so the page often renders before that; as an `observer` it renders again when the version is served, and otherwise it keeps showing "not available" until the user navigates away and back. Any component that chooses a version through `getStore()` is an `observer` for the same reason. `src/renderer/components/available-version.test.tsx` checks it: its spy on `getStore` reads an observable, and the page follows when the test sets it. ### Adding an API A new kind, or a new version of a kind, takes the same set of files as `Example`, one per version. The steps, in order: 1. **The types.** They follow the API of the controller that serves the resource, read from its sources at the release that serves the version, and not from memory: the Go types when the controller is written with kubebuilder, otherwise the `openAPIV3Schema` of the CRD. - Every Go struct has a TypeScript interface of the same name, with the same fields under their `json` names. - A field is optional in the interface when the CRD does not require it. `controller-gen` decides that from the markers, not from the `json` tag: `+required` (or `+kubebuilder:validation:Required`) makes the field required and `+optional` (or `+kubebuilder:validation:Optional`) makes it optional, whatever the tag says. A field without a marker is optional with `omitempty` and required without it, unless the package sets `+kubebuilder:validation:Optional`, which makes every such field optional. Current API conventions pair `+required` with `omitempty`, so `omitempty` alone does not make a field optional. When the types come from the `openAPIV3Schema`, a field is required when it is in the `required` list of its object. The generated CRD settles any doubt. - The API server validates every object against the CRD, so a required field is present. The one exception is a field that a newer CRD made required, on an object stored before; a list column or details panel shows `-` when it is missing, and the type does not allow for it. - Every `+kubebuilder:validation:Enum` (an `enum` in the schema) is a string-literal union type alias, used by the fields that have it, such as `export type ReflectionPolicy = "Always" | "IfNotPresent" | "Never";`. - A type that several kinds or versions share goes to `src/renderer/api/types.ts` and has the fields of every version it covers, optional where one of them omits it. - A new version of a kind starts as a copy of the newest version's files; the diff of the Go types between the two releases says what changes. 2. **The model**, `src/renderer/api//-.ts`, as in "CRD KubeObject Pattern": the class with the `static readonly` metadata, the `declare kind` and `declare apiVersion` literals, `static` helpers for the per-object logic, and the `KubeApi` and `KubeObjectStore` subclasses. `apiBase`, `crd.apiVersions` and `declare apiVersion` name the group and version, `crd` the plural, singular and short names of the CRD. 3. **The list page** per version in `src/renderer/pages/`, joined into one page per kind by `createAvailableVersionPage`, newest version first, and registered once in `clusterPages` and `clusterPageMenus`. 4. **The details panel** per version in `src/renderer/details/`, registered in `kubeObjectDetailItems` with `Renderer.K8sApi.detailsFor` and the version's model class. 5. **Menu items** per version in `src/renderer/menus/`, registered in `kubeObjectMenuItems` with `Renderer.K8sApi.menuItemFor` and the version's model class, only for what the resource supports: a Suspend/Resume item needs a suspend field in its spec, an action that annotates the object needs a controller that reads the annotation. 6. **`customResources`**: the model class of every version that has a page. 7. **Tests** for the static helpers, next to the model, and for any logic in the page or panel; a member of the host that a test reaches goes into the stub, as small as the test needs. 8. **`examples//`**: the CRD and a test object, applied with `kubectl apply -k` as `README.md` shows, and a row per version in the resource table of `README.md`. Then check the result in Freelens dev ("Checking the Extension in Freelens Dev"): the page lists the test object, the details show every field, the menu items work, and the resource is gone from the Custom Resources tree. ## Renderer Components - Pages and details panels are `observer` components from `mobx-react`, which the build maps to the host's copy. - Every page, details panel and menu item renders inside an `ErrorBoundary` from `src/renderer/components/error-boundary.tsx`, a class component of the host's React with `getDerivedStateFromError` and `componentDidCatch`. It logs what its children throw while React renders them with `extension.name` and the component stack, and renders `ErrorPage` in place of a page or a details panel, and nothing in place of a menu item, where an error page does not fit. A details panel or menu item renders again when the host passes a new `object`, which is the boundary's reset key. - The boundary is applied where the registrations are made: `clusterPages`, `kubeObjectDetailItems` and `kubeObjectMenuItems` are mapped through `withPageErrorBoundary`, `withDetailsErrorBoundary` and `withMenuItemErrorBoundary`, each taking `this` and a registration, so an entry added to a field is wrapped as well. A `globalPages` field is mapped through `withPageErrorBoundary` too. Each field is annotated with its type from `Renderer.LensExtension` (`clusterPages: Renderer.LensExtension["clusterPages"] = [...]`), because the mapping refers to `this`, and its type would otherwise depend on itself. - The wrappers take the registration that `Renderer.K8sApi.detailsFor` and `menuItemFor` built, so the helpers check each component against its model first, with no cast. - A `try`/`catch` around the call of a component is not enough. It sees only what the call throws, and the errors that matter come later: a child component throws when React renders it, and a callback such as `renderTableContents`, `getItems` or `customizeHeader` of `KubeObjectListLayout` throws when the host calls it from its own render. Such an error goes up to the nearest boundary of the host: the one around the main area of a cluster for a list page, and the one around the whole cluster frame for a details panel or a menu item, because the host has none around the details drawer or a menu item of an extension. - The boundary has no decorators and no `observer`; it reads no observable, and the components inside it are observers of their own. - Pages, details and menu items import their CSS module for the class names only, with no `?inline` import and no `