diff --git a/packages/platform/package.json b/packages/platform/package.json index 4d4b6c1bd..e3d86991d 100644 --- a/packages/platform/package.json +++ b/packages/platform/package.json @@ -33,6 +33,10 @@ "types": "./dist/plans.d.mts", "import": "./dist/plans.mjs" }, + "./ai-logging": { + "types": "./dist/ai-logging.d.mts", + "import": "./dist/ai-logging.mjs" + }, "./browser-page": { "types": "./dist/browser-page.d.mts", "import": "./dist/browser-page.mjs" diff --git a/packages/platform/src/ai-logging.ts b/packages/platform/src/ai-logging.ts new file mode 100644 index 000000000..1dcd31396 --- /dev/null +++ b/packages/platform/src/ai-logging.ts @@ -0,0 +1,288 @@ +/** + * AI Gateway logging policy shared by the platform API, proxy and installer. + * + * The API saves a project override (and plan defaults) in Postgres and publishes the + * effective mode to ROUTING KV under `aiLoggingKey(projectId)`. The proxy reads only + * that key. A missing key means `inherit`: the gateway's own `collect_logs` setting. + */ + +/** Every mode an operator can choose. `inherit` clears an override. */ +export const AI_LOGGING_MODES = ['inherit', 'off', 'metadata', 'full'] as const; +export type AiLoggingMode = (typeof AI_LOGGING_MODES)[number]; + +/** Modes that are saved and published. `inherit` is never stored: no row, no key. */ +export const PUBLISHED_AI_LOGGING_MODES = ['off', 'metadata', 'full'] as const; +export type PublishedAiLoggingMode = (typeof PUBLISHED_AI_LOGGING_MODES)[number]; + +/** Where an effective mode comes from. `gateway` means nothing is set (inherit). */ +export type AiLoggingSource = 'project' | 'plan' | 'gateway'; + +/** + * How a change between two effective modes moves logging. Only + * `off < metadata < full` has a known order: `inherit` follows the gateway setting, + * which the platform never reads, so any change to or from it is `unknown`. + */ +export type AiLoggingPublishOrder = 'same' | 'tighten' | 'loosen' | 'unknown'; + +const AI_LOGGING_KEY_PREFIX = 'ai-logging:'; + +export function isAiLoggingMode(value: unknown): value is AiLoggingMode { + return AI_LOGGING_MODES.some((mode) => mode === value); +} + +export function isPublishedAiLoggingMode(value: unknown): value is PublishedAiLoggingMode { + return PUBLISHED_AI_LOGGING_MODES.some((mode) => mode === value); +} + +/** ROUTING KV key that holds a project's published AI logging mode. */ +export function aiLoggingKey(projectId: string): string { + return `${AI_LOGGING_KEY_PREFIX}${projectId}`; +} + +/** + * Reads a published KV value: a missing key is `inherit`, a stored mode is that mode. + * Anything else, including a literal `inherit` or a mode from a newer platform, + * returns `undefined` so callers fail closed instead of logging more than intended. + */ +export function parsePublishedAiLogging(value: string | null): AiLoggingMode | undefined { + if (value === null) { + return 'inherit'; + } + return isPublishedAiLoggingMode(value) ? value : undefined; +} + +/** Effective mode: the project override, else the plan default, else inherit. */ +export function resolveAiLogging( + projectMode: AiLoggingMode | null | undefined, + planMode: AiLoggingMode | null | undefined, +): Readonly<{ mode: AiLoggingMode; source: AiLoggingSource }> { + if (projectMode && projectMode !== 'inherit') { + return { mode: projectMode, source: 'project' }; + } + if (planMode && planMode !== 'inherit') { + return { mode: planMode, source: 'plan' }; + } + return { mode: 'inherit', source: 'gateway' }; +} + +const LOGGING_RANK: Readonly> = { + off: 0, + metadata: 1, + full: 2, +}; + +/** Compares two effective modes (not saved project fields) to order a publish. */ +export function publishOrder( + previousEffective: AiLoggingMode, + nextEffective: AiLoggingMode, +): AiLoggingPublishOrder { + if (previousEffective === nextEffective) { + return 'same'; + } + if (previousEffective === 'inherit' || nextEffective === 'inherit') { + return 'unknown'; + } + return LOGGING_RANK[nextEffective] < LOGGING_RANK[previousEffective] ? 'tighten' : 'loosen'; +} + +/** + * How long after a KV write new requests are expected to follow it. KV may take up to + * 60 s (plus the proxy's 30 s `cacheTtl`) to reach other locations. A target, not a + * guarantee. + */ +export const AI_LOGGING_SETTLE_MS = 120_000; + +/** Edge cache time of the proxy's key read: KV's minimum, the same as the project token floor. */ +export const AI_LOGGING_CACHE_TTL_SECONDS = 30; + +const AI_LOGGING_CLEARED_KEY_PREFIX = 'ai-logging-cleared:'; + +/** + * ROUTING KV marker written just before `aiLoggingKey(projectId)` is removed for a + * project that now inherits. A removed key leaves no publish time behind, so readback + * reads this marker to report `pending` while other locations may still serve the old + * value. Only the API reads it (never the proxy), and it expires after the settle time. + * Its prefix does not start with the published key prefix, so key listings skip it. + */ +export function aiLoggingClearedKey(projectId: string): string { + return `${AI_LOGGING_CLEARED_KEY_PREFIX}${projectId}`; +} + +/** KV expiry of the cleared marker, in seconds (KV's minimum is 60). */ +export const AI_LOGGING_CLEARED_TTL_SECONDS: number = AI_LOGGING_SETTLE_MS / 1000; + +/** The KV value and options of a cleared marker written at `at` (ms). */ +export function aiLoggingClearedMarker(at: number): Readonly<{ + value: string; + metadata: Readonly<{ at: number }>; + expirationTtl: number; +}> { + return { value: 'inherit', metadata: { at }, expirationTtl: AI_LOGGING_CLEARED_TTL_SECONDS }; +} + +/** Reads a cleared marker's time; anything missing or malformed is `null`. */ +export function parseAiLoggingClearedAt(metadata: unknown): number | null { + if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) { + return null; + } + const { at } = metadata as Record; + return typeof at === 'number' && Number.isSafeInteger(at) ? at : null; +} + +/** ROUTING KV metadata written with every published key. `at` is the publish time in ms. */ +export type AiLoggingKeyMetadata = Readonly<{ mode: PublishedAiLoggingMode; at: number }>; + +/** Reads the metadata of a published key; anything malformed is `null` (treated as drift). */ +export function parseAiLoggingKeyMetadata(value: unknown): AiLoggingKeyMetadata | null { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return null; + } + const { mode, at } = value as Record; + if (!isPublishedAiLoggingMode(mode) || typeof at !== 'number' || !Number.isSafeInteger(at)) { + return null; + } + return { mode, at }; +} + +/** `platform_settings` key that holds plan defaults, kept apart from `plans:catalog`. */ +export const PLAN_AI_LOGGING_SETTING = 'plans:ai-logging'; + +/** + * A key for a project with no row may belong to a project whose create transaction + * has written KV but not committed yet. Cleanup leaves keys this young alone. + */ +export const AI_LOGGING_ORPHAN_GRACE_MS: number = 10 * 60_000; + +/** + * A plan-default fan-out that is still running (or stopped on an error). + * `revision` is the plan catalog revision that started it, so a page that began + * before a newer plan change cannot move the newer run's cursor. + */ +export type PlanAiLoggingPublish = Readonly<{ + revision: number; + planIds: ReadonlyArray; + includeUnknown: boolean; + cursor: string | null; + complete: boolean; + error?: string; +}>; + +export type PlanAiLoggingSettings = Readonly<{ + /** Plan ID -> default mode. A missing plan inherits. */ + modes: Readonly>; + publish: PlanAiLoggingPublish | null; +}>; + +function settingsRecord(value: unknown, name: string): Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + throw new Error(`${name} must be an object.`); + } + return value as Record; +} + +function parsePlanAiLoggingPublish(value: unknown): PlanAiLoggingPublish | null { + if (value === null || value === undefined) { + return null; + } + const input = settingsRecord(value, 'AI logging publish'); + const { revision, planIds, includeUnknown, cursor, complete, error } = input; + if ( + !Number.isSafeInteger(revision) || + !Array.isArray(planIds) || + !planIds.every((id) => typeof id === 'string') || + typeof includeUnknown !== 'boolean' || + (cursor !== null && typeof cursor !== 'string') || + typeof complete !== 'boolean' || + (error !== undefined && typeof error !== 'string') + ) { + throw new Error('Invalid AI logging publish progress.'); + } + return { + revision: revision as number, + planIds: planIds as Array, + includeUnknown, + cursor, + complete, + ...(error === undefined ? {} : { error }), + }; +} + +/** + * Reads the saved plan defaults. A missing row means every plan inherits. A mode the + * platform does not know is refused (so a bad value never loosens logging); + * `inherit` entries are dropped. Entries for plans not in the catalog stay in the + * object but are never looked up (see `planAiLogging`). + */ +export function parsePlanAiLoggingSettings(value: unknown): PlanAiLoggingSettings { + if (value === null || value === undefined) { + return { modes: {}, publish: null }; + } + const input = settingsRecord(value, 'Plan AI logging settings'); + const saved = settingsRecord(input.modes ?? {}, 'Plan AI logging modes'); + const modes: Record = {}; + for (const [planId, mode] of Object.entries(saved)) { + if (!isAiLoggingMode(mode)) { + throw new Error(`Invalid AI logging mode for plan ${planId}.`); + } + if (mode !== 'inherit') { + modes[planId] = mode; + } + } + return { modes, publish: parsePlanAiLoggingPublish(input.publish) }; +} + +/** The parts of a plan catalog the logging resolver needs. */ +export type AiLoggingPlanCatalog = Readonly<{ + defaultPlanId: string; + plans: ReadonlyArray>; +}>; + +export type PlanAiLogging = Readonly<{ + planId: string; + /** False when the account's plan ID is not in the catalog. */ + planKnown: boolean; + /** The catalog default plan, whose logging an unknown plan ID follows. */ + defaultPlanId: string; + planMode: PublishedAiLoggingMode | null; +}>; + +/** + * The plan default for an account. A plan ID that is not in the catalog takes the + * default plan's logging (unlike limits, which fall back to the built-in free plan), + * so an operator who sets `off` on every plan gets `off` for every account. + */ +export function planAiLogging( + settings: PlanAiLoggingSettings, + catalog: AiLoggingPlanCatalog, + planId: string, +): PlanAiLogging { + const planKnown = catalog.plans.some((plan) => plan.id === planId); + const lookup = planKnown ? planId : catalog.defaultPlanId; + const planMode = Object.hasOwn(settings.modes, lookup) ? settings.modes[lookup]! : null; + return { planId, planKnown, defaultPlanId: catalog.defaultPlanId, planMode }; +} + +/** Whether a running plan publish still has to reach accounts on this plan. */ +export function planPublishPending( + publish: PlanAiLoggingPublish | null, + plan: Pick, +): boolean { + if (!publish || publish.complete) { + return false; + } + return plan.planKnown ? publish.planIds.includes(plan.planId) : publish.includeUnknown; +} + +/** + * Reads a plan's `aiLogging` field from a plan change. `undefined` keeps the current + * value and `inherit` clears it. + */ +export function parsePlanAiLoggingInput(value: unknown): AiLoggingMode | undefined { + if (value === undefined) { + return undefined; + } + if (!isAiLoggingMode(value)) { + throw new Error(`aiLogging must be one of ${AI_LOGGING_MODES.join(', ')}.`); + } + return value; +} diff --git a/packages/platform/test/unit/ai-logging.test.ts b/packages/platform/test/unit/ai-logging.test.ts new file mode 100644 index 000000000..9d40fbe57 --- /dev/null +++ b/packages/platform/test/unit/ai-logging.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + AI_LOGGING_MODES, + aiLoggingKey, + isAiLoggingMode, + isPublishedAiLoggingMode, + parseAiLoggingKeyMetadata, + parsePlanAiLoggingInput, + parsePlanAiLoggingSettings, + parsePublishedAiLogging, + planAiLogging, + planPublishPending, + publishOrder, + resolveAiLogging, +} from '../../src/ai-logging.ts'; + +describe('AI logging policy', () => { + it('accepts exactly the four operator modes', () => { + expect(AI_LOGGING_MODES).toEqual(['inherit', 'off', 'metadata', 'full']); + for (const mode of AI_LOGGING_MODES) { + expect(isAiLoggingMode(mode)).toBe(true); + } + for (const value of ['OFF', ' off', '', 'none', null, undefined, 0, false, {}]) { + expect(isAiLoggingMode(value)).toBe(false); + } + }); + + it('never stores inherit', () => { + expect(isPublishedAiLoggingMode('inherit')).toBe(false); + expect(['off', 'metadata', 'full'].every(isPublishedAiLoggingMode)).toBe(true); + }); + + it('names the ROUTING key after the project', () => { + expect(aiLoggingKey('proj_000000000042')).toBe('ai-logging:proj_000000000042'); + }); + + it('reads a missing key as inherit and refuses values it does not know', () => { + expect(parsePublishedAiLogging(null)).toBe('inherit'); + expect(parsePublishedAiLogging('off')).toBe('off'); + expect(parsePublishedAiLogging('metadata')).toBe('metadata'); + expect(parsePublishedAiLogging('full')).toBe('full'); + for (const value of ['inherit', '', 'OFF', 'off ', '"off"', 'future-mode']) { + expect(parsePublishedAiLogging(value)).toBeUndefined(); + } + }); + + it('prefers the project override, then the plan default, then the gateway', () => { + expect(resolveAiLogging('full', 'off')).toEqual({ mode: 'full', source: 'project' }); + expect(resolveAiLogging('off', 'full')).toEqual({ mode: 'off', source: 'project' }); + expect(resolveAiLogging(null, 'metadata')).toEqual({ mode: 'metadata', source: 'plan' }); + expect(resolveAiLogging('inherit', 'off')).toEqual({ mode: 'off', source: 'plan' }); + expect(resolveAiLogging(undefined, 'inherit')).toEqual({ mode: 'inherit', source: 'gateway' }); + expect(resolveAiLogging(null, null)).toEqual({ mode: 'inherit', source: 'gateway' }); + }); + + it('orders known changes and treats any change with inherit as unknown', () => { + expect(publishOrder('full', 'off')).toBe('tighten'); + expect(publishOrder('full', 'metadata')).toBe('tighten'); + expect(publishOrder('metadata', 'off')).toBe('tighten'); + expect(publishOrder('off', 'metadata')).toBe('loosen'); + expect(publishOrder('off', 'full')).toBe('loosen'); + expect(publishOrder('metadata', 'full')).toBe('loosen'); + for (const mode of AI_LOGGING_MODES) { + expect(publishOrder(mode, mode)).toBe('same'); + } + for (const mode of ['off', 'metadata', 'full'] as const) { + expect(publishOrder('inherit', mode)).toBe('unknown'); + expect(publishOrder(mode, 'inherit')).toBe('unknown'); + } + }); + + it('orders by effective values, not by the saved project field', () => { + // A project override removed (`full` -> no row) while its plan says `off`. + const before = resolveAiLogging('full', 'off').mode; + const after = resolveAiLogging(null, 'off').mode; + expect(publishOrder(before, after)).toBe('tighten'); + }); + + it('reads key metadata and treats anything malformed as missing', () => { + expect(parseAiLoggingKeyMetadata({ mode: 'off', at: 1700000000000 })).toEqual({ + mode: 'off', + at: 1700000000000, + }); + for (const value of [ + null, + undefined, + 'off', + [], + { mode: 'inherit', at: 1 }, + { mode: 'off' }, + { mode: 'off', at: '1' }, + { mode: 'off', at: 1.5 }, + ]) { + expect(parseAiLoggingKeyMetadata(value)).toBeNull(); + } + }); +}); + +describe('plan AI logging defaults', () => { + const catalog = { defaultPlanId: 'free', plans: [{ id: 'free' }, { id: 'pro' }] }; + + it('reads a missing row as every plan inheriting', () => { + expect(parsePlanAiLoggingSettings(null)).toEqual({ modes: {}, publish: null }); + expect(planAiLogging(parsePlanAiLoggingSettings(null), catalog, 'pro')).toEqual({ + planId: 'pro', + planKnown: true, + defaultPlanId: 'free', + planMode: null, + }); + }); + + it('keeps known modes, drops inherit and refuses modes it does not know', () => { + const settings = parsePlanAiLoggingSettings({ + modes: { pro: 'metadata', free: 'inherit', gone: 'off' }, + publish: null, + }); + expect(settings.modes).toEqual({ pro: 'metadata', gone: 'off' }); + for (const modes of [{ pro: 'OFF' }, { pro: null }, { pro: 1 }, []]) { + expect(() => parsePlanAiLoggingSettings({ modes, publish: null })).toThrow(); + } + expect(() => parsePlanAiLoggingSettings('off')).toThrow(); + expect(() => + parsePlanAiLoggingSettings({ modes: {}, publish: { planIds: 'pro', complete: false } }), + ).toThrow(); + }); + + it('ignores entries for plans that are no longer in the catalog', () => { + const settings = parsePlanAiLoggingSettings({ modes: { gone: 'off' } }); + expect(planAiLogging(settings, catalog, 'free').planMode).toBeNull(); + expect(planAiLogging(settings, catalog, 'pro').planMode).toBeNull(); + }); + + it('gives an account on an unknown plan the logging of the default plan', () => { + const settings = parsePlanAiLoggingSettings({ modes: { free: 'off', pro: 'full' } }); + expect(planAiLogging(settings, catalog, 'legacy-x')).toEqual({ + planId: 'legacy-x', + planKnown: false, + defaultPlanId: 'free', + planMode: 'off', + }); + expect(planAiLogging(settings, catalog, 'pro').planMode).toBe('full'); + }); + + it('knows which accounts a running plan publish still has to reach', () => { + const publish = parsePlanAiLoggingSettings({ + modes: {}, + publish: { + revision: 3, + planIds: ['pro'], + includeUnknown: true, + cursor: null, + complete: false, + }, + }).publish!; + expect(planPublishPending(publish, { planId: 'pro', planKnown: true })).toBe(true); + expect(planPublishPending(publish, { planId: 'free', planKnown: true })).toBe(false); + expect(planPublishPending(publish, { planId: 'legacy-x', planKnown: false })).toBe(true); + expect( + planPublishPending({ ...publish, complete: true }, { planId: 'pro', planKnown: true }), + ).toBe(false); + expect(planPublishPending(null, { planId: 'pro', planKnown: true })).toBe(false); + }); + + it('requires the catalog revision that started a publish', () => { + const publish = { planIds: ['pro'], includeUnknown: false, cursor: null, complete: false }; + expect(() => parsePlanAiLoggingSettings({ modes: {}, publish })).toThrow(); + expect( + parsePlanAiLoggingSettings({ modes: {}, publish: { ...publish, revision: 4, error: 'x' } }) + .publish, + ).toEqual({ ...publish, revision: 4, error: 'x' }); + }); + + it('reads a plan change: omitted keeps, inherit clears, anything else is refused', () => { + expect(parsePlanAiLoggingInput(undefined)).toBeUndefined(); + for (const mode of AI_LOGGING_MODES) { + expect(parsePlanAiLoggingInput(mode)).toBe(mode); + } + for (const value of [null, '', 'OFF', 'everything', 1]) { + expect(() => parsePlanAiLoggingInput(value)).toThrow('aiLogging must be one of'); + } + }); +}); diff --git a/packages/platform/vite.config.ts b/packages/platform/vite.config.ts index d6cbc5da5..84c7423a5 100644 --- a/packages/platform/vite.config.ts +++ b/packages/platform/vite.config.ts @@ -18,6 +18,7 @@ export default defineConfig({ 'src/installer.ts', 'src/email-protocol.ts', 'src/plans.ts', + 'src/ai-logging.ts', 'src/browser-page.ts', ], format: 'esm', diff --git a/platform/packages/api/package.json b/platform/packages/api/package.json index 41406bb76..94f526930 100644 --- a/platform/packages/api/package.json +++ b/platform/packages/api/package.json @@ -10,8 +10,7 @@ "./routing": "./src/routing.ts", "./isr-store": "./src/isr-store.ts", "./usage-auth": "./src/usage-auth.ts", - "./proxy-token": "./src/proxy-token.ts", - "./ai-logging-policy": "./src/ai-logging-policy.ts" + "./proxy-token": "./src/proxy-token.ts" }, "scripts": { "db:generate": "drizzle-kit generate", diff --git a/platform/packages/api/src/admin/fate/page-data.ts b/platform/packages/api/src/admin/fate/page-data.ts index 3fdf06dc1..f3637d6fd 100644 --- a/platform/packages/api/src/admin/fate/page-data.ts +++ b/platform/packages/api/src/admin/fate/page-data.ts @@ -27,7 +27,12 @@ import type { Db } from '../../db.ts'; import type { ApiEnv } from '../../env.ts'; import { OperatorError } from '../../operator/common.ts'; import { cliVersionStats } from '../../operator/system-operations.ts'; -import { readPlanCatalog, readPlanCatalogWithAccounts, planFromCatalog } from '../../plans.ts'; +import { + initialPlanDefaultFor, + readPlanCatalog, + readPlanCatalogWithAccounts, + planFromCatalog, +} from '../../plans.ts'; import { getPlatformApiUrl, platformConnectCommand } from '../../platform-identity.ts'; import { projectUrl, projectWithUrl } from '../../project-url.ts'; import { invitations, platformLoginTests } from '../../schema.ts'; @@ -147,11 +152,17 @@ export async function loadUserDetailPage(context: AdminContext, path: string) { const { id } = detailLocation(path, '/admin/users/'); const { getOperatorUser } = await import('../../operator/tenant-service.ts'); const detail = await getOperatorUser(context, id); - const catalog = await readPlanCatalog(context.get('db')); + const { readPlanAiLoggingSettings } = await import('../../ai-logging-plans.ts'); + const { planAiLogging } = await import('../../ai-logging-policy.ts'); + const [catalog, aiLoggingSettings] = await Promise.all([ + readPlanCatalog(context.get('db'), initialPlanDefaultFor(context.env)), + readPlanAiLoggingSettings(context.get('db')), + ]); return { id: path, ...detail, limits: planFromCatalog(catalog, detail.user.plan).limits, + aiLogging: planAiLogging(aiLoggingSettings, catalog, detail.user.plan), plans: catalog.plans .filter((plan) => !plan.archived || plan.id === detail.user.plan) .map((plan) => ({ id: plan.id, name: plan.name, archived: plan.archived })), @@ -198,7 +209,7 @@ export async function loadProjectDetailPage(context: AdminContext, path: string) const { getOperatorProject } = await import('../../operator/tenant-service.ts'); const db = context.get('db'); const [detail, members, invitations, zeroTrust] = await Promise.all([ - getOperatorProject(db, id), + getOperatorProject(db, context.env, id), getProjectMembers(db, id), getPendingProjectInvitations(db, id), loadProjectZeroTrust(db, id), @@ -497,13 +508,15 @@ export async function loadPlansPage(context: AdminContext, path: string) { if (url.pathname !== home && url.pathname !== home + '/new' && !match) { throw new OperatorError(400, 'Invalid plans page request.'); } - const data = await readPlanCatalogWithAccounts( - context.get('db'), - context.env.PLATFORM_INSTALLATION_ID ? 'custom' : 'free', - ); + const initialPlanDefault = initialPlanDefaultFor(context.env); + const { readPlanAiLoggingProgress } = await import('../../ai-logging-plans.ts'); + const [data, aiLogging] = await Promise.all([ + readPlanCatalogWithAccounts(context.get('db'), initialPlanDefault), + readPlanAiLoggingProgress(context.get('db'), initialPlanDefault), + ]); const selectedPlanId = match?.[1] ?? null; if (selectedPlanId && !data.catalog.plans.some((plan) => plan.id === selectedPlanId)) { throw new OperatorError(404, 'Plan not found.'); } - return { id: path, ...data, selectedPlanId }; + return { id: path, ...data, aiLogging, selectedPlanId }; } diff --git a/platform/packages/api/src/admin/fate/page-server.ts b/platform/packages/api/src/admin/fate/page-server.ts index abdd91eb5..e16aa421d 100644 --- a/platform/packages/api/src/admin/fate/page-server.ts +++ b/platform/packages/api/src/admin/fate/page-server.ts @@ -34,6 +34,7 @@ export const plansDataView = dataView('AdminPlans')({ id: true, catalog: true, accounts: true, + aiLogging: true, selectedPlanId: true, }); export type AdminPlans = Entity; @@ -84,6 +85,7 @@ export const deploymentsPageDataView = dataView('AdminDep }); export const userDetailDataView = dataView('AdminUserDetail')({ limits: true, + aiLogging: true, plans: true, id: true, user: true, @@ -103,6 +105,7 @@ export const projectDetailDataView = dataView('AdminProject domains: true, builds: true, zeroTrust: true, + aiLogging: true, cfAccountId: true, deployUrl: true, tz: true, diff --git a/platform/packages/api/src/admin/fate/views.ts b/platform/packages/api/src/admin/fate/views.ts index 9b580e1dc..4aeb6a500 100644 --- a/platform/packages/api/src/admin/fate/views.ts +++ b/platform/packages/api/src/admin/fate/views.ts @@ -121,6 +121,7 @@ export const deploymentsPageRequest = (path: string) => export const UserDetailView = view()({ limits: true, + aiLogging: true, plans: true, id: true, user: true, @@ -140,6 +141,7 @@ export const ProjectDetailView = view()({ domains: true, builds: true, zeroTrust: true, + aiLogging: true, cfAccountId: true, deployUrl: true, tz: true, @@ -320,6 +322,7 @@ export const PlansView = view()({ id: true, catalog: true, accounts: true, + aiLogging: true, selectedPlanId: true, }); export const plansRequest = (path: string) => diff --git a/platform/packages/api/src/admin/plans.ts b/platform/packages/api/src/admin/plans.ts index 046547d04..23c01e9b3 100644 --- a/platform/packages/api/src/admin/plans.ts +++ b/platform/packages/api/src/admin/plans.ts @@ -1,4 +1,5 @@ import type { PlatformPlanCatalog } from '@void/platform/plans'; +import type { PlanAiLoggingSettings } from '../ai-logging-policy.ts'; import type { PlanCatalogAction } from '../operator/plans.ts'; export type AdminPlanPreview = { @@ -8,16 +9,26 @@ export type AdminPlanPreview = { expectedRevision: number; before: PlatformPlanCatalog; after: PlatformPlanCatalog; + /** Plan AI logging defaults before and after the change. */ + aiLoggingBefore: PlanAiLoggingSettings['modes']; + aiLoggingAfter: PlanAiLoggingSettings['modes']; affectedAccounts: number; warnings: Array; overLimitAccounts: Array<{ id: string; login: string; reasons: Array }>; usageSampleSize: number; }; +/** Progress of account updates and the AI logging publish, combined. */ export type AdminPlanProgress = { revision: number; complete: boolean; + /** Accounts plus projects written by this step; zero means it made no progress. */ processed: number; + /** Accounts whose limits were updated by this step. */ + accounts: number; + /** Projects whose AI logging setting was published by this step. */ + projects: number; + /** Changes whenever either step moves, so the page can tell it is not stuck. */ cursor: string | null; error: string | null; }; diff --git a/platform/packages/api/src/admin/react/views/PlansPage.tsx b/platform/packages/api/src/admin/react/views/PlansPage.tsx index 9f4735110..4fd7f7af7 100644 --- a/platform/packages/api/src/admin/react/views/PlansPage.tsx +++ b/platform/packages/api/src/admin/react/views/PlansPage.tsx @@ -19,6 +19,7 @@ import { import { Link } from '@void/react'; import { useEffect, useState } from 'react'; import { useRequest, useView } from 'react-fate'; +import type { AiLoggingMode, PlanAiLoggingSettings } from '../../../ai-logging-policy.ts'; import { PlansView, plansRequest } from '../../fate/views.ts'; import type { AdminPlanPreview, AdminPlanProgress } from '../../plans.ts'; import type { AdminPageProps } from '../page-utils.ts'; @@ -65,6 +66,15 @@ function limit(value: number, key?: EditablePlanLimit) { : 'Unlimited' : value.toLocaleString('en-US'); } +const aiLoggingLabels: Record = { + inherit: 'Inherit (AI Gateway setting)', + off: 'Off', + metadata: 'Metadata only', + full: 'Full (prompts and responses)', +}; +function aiLoggingMode(modes: PlanAiLoggingSettings['modes'], planId: string): AiLoggingMode { + return Object.hasOwn(modes, planId) ? modes[planId]! : 'inherit'; +} function usePlans(path: string) { const { plans: ref } = useRequest(plansRequest(path), { mode: 'stale-while-revalidate' }); const data = useView(PlansView, ref); @@ -122,8 +132,9 @@ function PlanAction({ export function PlansPage({ path, platformName, username }: AdminPageProps) { usePlanConfirmation(path); - const { catalog, accounts } = usePlans(path); + const { catalog, accounts, aiLogging } = usePlans(path); const pending = catalog.reconciliation && !catalog.reconciliation.complete; + const publishPending = aiLogging.publish && !aiLogging.publish.complete; return ( @@ -153,6 +164,20 @@ export function PlansPage({ path, platformName, username }: AdminPageProps) { )} + {!pending && publishPending && ( + +

AI logging publish pending

+

+ {aiLogging.remaining} projects still use their previous AI Gateway logging setting. + Updates continue every hour, or continue them now. +

+ {aiLogging.publish?.error &&

{aiLogging.publish.error}

} +
+ +