feat(ai): publish capabilities on the account payload

GET /api/auth/me gains ai: the state of every capability and the
provider block, resolved for the active record and masked to the
grant like moduleAccess. The authority comes from the switch the
payload already resolved, so a delegate reads not_permitted_for_record
and a guardian is limited to the operator's key.

useAiCapability is the web reader and fails closed until the payload
arrives. GET /api/feature-flags becomes a deprecated projection of the
operator switches with a Deprecation header and a link to its
successor.
This commit is contained in:
Marc-André Bombeck committed 2026-09-24 07:49:14 +02:00
1 parent 7c757520f1
commit 464522f315
8 files changed
+296 -36

No files matched your search

+42
View File
@@ -70,6 +70,7 @@ import {
sectionsOpen,
} from "@/lib/sharing/module-disclosure";
import { recordSessionForPayload } from "@/lib/sharing/record-session-fence";
import { loadAiCapabilities } from "@/lib/ai/capabilities/load";
export const dynamic = "force-dynamic";
@@ -115,12 +116,32 @@ export const GET = apiHandler(async () => {
// no switch at all, and the reason the own-record payload is untouched.
const sections = accountAccess.active?.sections ?? null;
// Who may put a model to work on that record, stated from the switch this
// payload already resolved rather than read back off the request: this is an
// actor surface, so the request carries no record authority of its own.
// One's own record is the owner's; a managed profile is its guardian's,
// limited to the operator's key; anybody else's is a delegate's, and a
// delegate starts no AI work on a record that is not theirs.
const recordKind = accountAccess.active?.recordKind ?? "self";
const aiAuthority = {
origin:
recordKind === "self"
? ("owner" as const)
: recordKind === "managed"
? ("guardian" as const)
: ("delegate" as const),
recordUserId: recordId,
actorUserId: user.id,
grantId: null,
};
const [
record,
cycleProfile,
resolvedModules,
moduleAvailability,
onboardingRow,
ai,
] = await Promise.all([
// The actor's own row is already in hand; a switched session needs the
// record's `gender`, which is the column the cycle gate derives from.
@@ -171,6 +192,19 @@ export const GET = apiHandler(async () => {
// keyed by record already, and a delegate seeing the record's own setup
// state is what makes the dashboard they are looking at coherent.
loadOnboardingRecordRow(prisma, recordId),
// v1.39 — the AI capabilities for the RECORD, resolved on the server from
// every layer that can say no: the operator's switches, the record's
// modules (masked to the grant exactly like `moduleAccess`), the
// provider-work authority, provider presence and consent. The module map
// and the operator availability it needs are the memoised reads above, so
// the extra cost is the provider presence (two point reads) and one read
// of the active consent kinds.
loadAiCapabilities({
recordId,
authority: aiAuthority,
sections,
recordKind,
}),
]);
// The masking step, and the one place the record scoping is narrowed rather
@@ -350,6 +384,14 @@ export const GET = apiHandler(async () => {
// adds a reason without moving a gate; empty states read it to say the
// honest thing rather than offering a switch the reader cannot reach.
moduleAccess,
// v1.39 — which AI capabilities this record has, and why not when it has
// none: `capabilities` maps every capability key to `{ available, reason,
// onDeviceAllowed }` (reason is the outermost layer that said no), and
// `provider` says whether a provider is configured, who manages it, and
// whether the person in front of the screen may set one up. Resolved for
// the RECORD and masked to the grant, like `modules`. Clients render from
// it and never recompute it; data never depends on it.
ai,
// v1.36.0 — account sharing, resolved. `accounts` is the switcher's menu,
// `active` is the record this session is inside (null when it is in its
// own), `canSwitch` and per-entry `canWrite` are the booleans the UI binds
@@ -145,4 +145,27 @@ describe("GET /api/feature-flags", () => {
const res = await GET(req());
expect(res.headers.get("Cache-Control")).toBe("private, max-age=60");
});
it("announces itself deprecated and names its successor", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
FIND.mockResolvedValue(null);
const res = await GET(req());
expect(res.headers.get("Deprecation")).toBe("true");
expect(res.headers.get("Link")).toBe(
'</api/auth/me>; rel="successor-version"',
);
});
it("answers every switch off when the switches cannot be read", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
FIND.mockRejectedValue(new Error("db down"));
const res = await GET(req());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { assistant: Record<string, boolean> };
};
expect(Object.values(body.data.assistant).every((v) => v === false)).toBe(
true,
);
});
});
+19 -31
View File
@@ -1,38 +1,21 @@
/**
* `GET /api/feature-flags` — operator-side assistant flag matrix.
* `GET /api/feature-flags` — the operator's assistant switches. DEPRECATED.
*
* Projects `AppSettings.assistant*Enabled` over HTTP so every client
* (web React tree + iOS native) reads the same authoritative shape.
* The answer a client needs is not the switch set but what the switches, the
* record's modules, the provider-work authority, the provider and consent add
* up to, per capability. That is `ai` on `GET /api/auth/me`, and it is what
* every client reads from this release on. This route stays a projection of
* the operator switches alone, for clients that have not moved yet, and is
* removed in the first release after the native build that reads `ai` ships:
*
* Response envelope:
* { "data": { "assistant": { "enabled", "coach", "briefing",
* "insightStatus", "documentAi" } } }
*
* {
* "data": {
* "assistant": {
* "enabled": true,
* "coach": true,
* "briefing": true,
* "insightStatus": true,
* "correlations": true
* }
* },
* "error": null
* }
* The master is applied (every sub-switch reads false when it is off), and a
* switch read that fails answers every switch off. The response carries
* `Deprecation: true` and a `Link` to its successor.
*
* - `requireActorAuth()` — any logged-in user, including one acting on
* somebody else's record. Per-request flag fetches from the iOS native
* client always arrive after auth, so the gate matches the rest of the
* read-only profile surface; the mode is argued at the call site.
* - Master kills every sub-flag in the resolver before the shape
* leaves the handler, so callers never have to compose
* `master && sub`.
* - `Cache-Control: private, max-age=60` — operator toggles flip
* rarely; a 60-second per-session cache keeps the cost off the
* hot /insights mount path while still propagating an admin
* change within a minute.
*
* Locked per `.planning/RESPONSE-TO-IOS-TEAM-2026-05-16.md` §3 R5
* and `.planning/research/v15-assistant-optional.md` Part D.
* `Cache-Control: private, max-age=60`: switches flip rarely.
*/
import type { NextRequest } from "next/server";
@@ -53,11 +36,16 @@ export const GET = apiHandler(async (_request: NextRequest) => {
// about the DEPLOYMENT, which for this purpose is the caller's side of the
// request, not the record's.
await requireActorAuth();
annotate({ action: { name: "feature-flags.read" } });
annotate({
action: { name: "feature-flags.read" },
meta: { deprecated: true },
});
const assistant = await getAssistantFlags();
const response = apiSuccess({ assistant });
response.headers.set("Cache-Control", "private, max-age=60");
response.headers.set("Deprecation", "true");
response.headers.set("Link", '</api/auth/me>; rel="successor-version"');
return response;
});