AI-native design editor. Open-source Figma alternative.
feat(ai): show Cloud AI credits and explain an exhausted allowance (#1490)
Danila Poyarkovc8f6fc20a476
diff --git a/bun.lock b/bun.lockindex f80d90253..9cf511272 100644--- a/bun.lock+++ b/bun.lock@@ -109,6 +109,7 @@"@commitlint/config-conventional": "^21.2.3","@commitlint/is-ignored": "^21.2.3","@commitlint/types": "^21.2.3",+ "@electric-sql/pglite": "0.4.1","@feature-sliced/steiger-plugin": "^0.5.8","@figma/plugin-typings": "^1.140.0","@hono/node-server": "^1.19.17",@@ -150,8 +151,10 @@"fake-indexeddb": "^6.2.5","franc": "^6.2.0","hono": "^4.13.13",+ "jose": "^6.2.8","jscpd": "^4.3.0","knip": "6.20.0",+ "kysely-pglite-dialect": "1.3.1","mdast": "^3.0.0","mdast-util-from-markdown": "^2.0.3","mitata": "^1.0.34",diff --git a/changes/1362/added.md b/changes/1362/added.mdindex c0d261df9..661befbef 100644--- a/changes/1362/added.md+++ b/changes/1362/added.md@@ -1,2 +1,2 @@-- The AI assistant can use models through OpenPencil Cloud: choose **OpenPencil Cloud** as a model's provider in **Settings → AI** and the workspace whose plan pays for it, with the models and prices the server offers. When the workspace's AI credits for the month run out, the assistant says so and offers **Manage plan** where the server bills.+- The AI assistant can use models through OpenPencil Cloud: choose **OpenPencil Cloud** as a model's provider in **Settings → AI** and the workspace whose plan pays for it, with the models and prices the server offers. The chat shows how many credits the workspace has left; when they run out, it offers **Manage plan** where the server bills, and on a self-hosted server says when the allowance renews.- Self-hosted OpenPencil Cloud servers can offer AI through the AI relay, `dist-standalone/ai-relay.mjs`, which forwards requests to one OpenAI-compatible provider with your key and holds each workspace to its monthly credit allowance.diff --git a/package.json b/package.jsonindex dfd307d5f..e0c2570de 100644--- a/package.json+++ b/package.json@@ -224,6 +224,7 @@"@commitlint/config-conventional": "^21.2.3","@commitlint/is-ignored": "^21.2.3","@commitlint/types": "^21.2.3",+ "@electric-sql/pglite": "0.4.1","@feature-sliced/steiger-plugin": "^0.5.8","@figma/plugin-typings": "^1.140.0","@hono/node-server": "^1.19.17",@@ -265,8 +266,10 @@"fake-indexeddb": "^6.2.5","franc": "^6.2.0","hono": "^4.13.13",+ "jose": "^6.2.8","jscpd": "^4.3.0","knip": "6.20.0",+ "kysely-pglite-dialect": "1.3.1","mdast": "^3.0.0","mdast-util-from-markdown": "^2.0.3","mitata": "^1.0.34",diff --git a/packages/cloud/src/ai-relay/app.ts b/packages/cloud/src/ai-relay/app.tsindex ccf529ebd..985958ecd 100644--- a/packages/cloud/src/ai-relay/app.ts+++ b/packages/cloud/src/ai-relay/app.ts@@ -4,6 +4,7 @@ import {CLOUD_AI_API_PATHS,CLOUD_AI_TOKEN_AUDIENCE,parseAIUsageQuery,+ type AIError,type AIErrorCode,type AITokenClaims} from '#cloud/contract'@@ -74,8 +75,12 @@ const FORWARDED_FIELDS = [/** How long an upstream answer may take in all, streamed or not, so a stalled one cannot hold a request slot forever. */const DEFAULT_UPSTREAM_TIMEOUT_MS = 10 * 60_000-function aiError(context: Context, code: AIErrorCode) {- return context.json({ error: { code } }, AI_ERROR_STATUS[code])+function aiError(+ context: Context,+ code: AIErrorCode,+ details: Omit<AIError['error'], 'code'> = {}+) {+ return context.json({ error: { code, ...details } }, AI_ERROR_STATUS[code])}/** Counts each workspace's model requests in flight, within one process. */@@ -179,7 +184,11 @@ export function createAIRelayApp(services: AIRelayServices) {const model = models.get(request.model)if (!model) return aiError(context, 'model_not_allowed')const wallet = await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())- if (wallet.balance === 0) return aiError(context, 'insufficient_credits')+ if (wallet.balance === 0) {+ return aiError(context, 'insufficient_credits', {+ resetsAt: wallet.buckets[0]?.expiresAt ?? undefined+ })+ }const release = limiter.acquire(claims.workspaceId)if (!release) return aiError(context, 'rate_limited')@@ -232,7 +241,9 @@ export function createAIRelayApp(services: AIRelayServices) {}const settled = settle().catch(reportBackgroundError).finally(release)services.waitUntil?.(settled)- return new Response(answer, { status: upstream.status, headers })+ // The answer ends once its charge is recorded, so a wallet read after it includes the charge.+ const charged = answer.pipeThrough(new TransformStream({ flush: () => settled }))+ return new Response(charged, { status: upstream.status, headers })})}diff --git a/packages/cloud/src/contract/ai.ts b/packages/cloud/src/contract/ai.tsindex aec607a2f..3574c8bc1 100644--- a/packages/cloud/src/contract/ai.ts+++ b/packages/cloud/src/contract/ai.ts@@ -86,6 +86,10 @@ export const aiCreditBucketSchema = v.object({})export type AICreditBucket = v.InferOutput<typeof aiCreditBucketSchema>+/**+ * A service records a request's charge before the request's answer ends, so a wallet read after+ * an answer includes what it cost.+ */export const aiWalletSchema = v.object({/** Credits left to spend; `null` when the service sets no limit. */balance: v.nullable(creditsSchema),@@ -129,7 +133,12 @@ export const aiErrorCodeSchema = v.picklist([export type AIErrorCode = v.InferOutput<typeof aiErrorCodeSchema>export const aiErrorSchema = v.object({- error: v.object({ code: aiErrorCodeSchema, message: v.optional(v.string()) })+ error: v.object({+ code: aiErrorCodeSchema,+ message: v.optional(v.string()),+ /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */+ resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))+ })})export type AIError = v.InferOutput<typeof aiErrorSchema>diff --git a/packages/cloud/tests/integration/ai-relay/app.test.ts b/packages/cloud/tests/integration/ai-relay/app.test.tsindex d86ca3bf3..dd306c626 100644--- a/packages/cloud/tests/integration/ai-relay/app.test.ts+++ b/packages/cloud/tests/integration/ai-relay/app.test.ts@@ -18,6 +18,7 @@ import {} from '#cloud/contract'import { PGlite } from '@electric-sql/pglite'import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT } from 'jose'+import { InsertQueryNode, type KyselyPlugin, type QueryId } from 'kysely'import { PGliteDialect } from 'kysely-pglite-dialect'import * as v from 'valibot'@@ -60,9 +61,24 @@ function streamOf(...events: unknown[]): string {return events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n'}+/** Holds every insert's result until `gate` resolves, so a test decides when a charge is recorded. */+function holdInserts(gate: Promise<void>): KyselyPlugin {+ const inserts = new Set<QueryId>()+ return {+ transformQuery({ node, queryId }) {+ if (InsertQueryNode.is(node)) inserts.add(queryId)+ return node+ },+ async transformResult({ result, queryId }) {+ if (inserts.delete(queryId)) await gate+ return result+ }+ }+}+async function relay(upstream: (call: UpstreamCall) => Response = () => Response.json({}),- options: { upstreamTimeoutMs?: number; maxRequestBytes?: number } = {}+ options: { upstreamTimeoutMs?: number; maxRequestBytes?: number; chargeGate?: Promise<void> } = {}) {const pglite = await PGlite.create({ dataDir: 'memory://' })const database = createAIRelayDatabase(new PGliteDialect(pglite))@@ -85,7 +101,7 @@ async function relay(OPENPENCIL_AI_RELAY_UPSTREAM_KEY: 'upstream-key'}),- database,+ database: options.chargeGate ? database.withPlugin(holdInserts(options.chargeGate)) : database,keys,now: () => NOW,upstreamTimeoutMs: options.upstreamTimeoutMs,@@ -219,7 +235,11 @@ describe('AI relay', () => {expect(usage.entries).toEqual([])})- test('asks a streamed completion for usage and charges it after the stream ends', async () => {+ test('asks a streamed completion for usage and charges it before the answer ends', async () => {+ let recordCharge: (() => void) | undefined+ const charge = new Promise<void>((resolve) => {+ recordCharge = resolve+ })const context = await relay(() =>new Response(@@ -228,7 +248,8 @@ describe('AI relay', () => {{ choices: [], usage: { prompt_tokens: 1000, completion_tokens: 1000 } }),{ headers: { 'Content-Type': 'text/event-stream' } }- )+ ),+ { chargeGate: charge })const bearer = await context.token()const response = await context.complete(bearer, {@@ -239,8 +260,16 @@ describe('AI relay', () => {})expect(response.headers.get('Content-Type')).toBe('text/event-stream')expect(context.calls[0]?.body.stream_options).toEqual({ include_usage: true })- expect(await response.text()).toContain('"content":"Hi"')- await Promise.all(context.settled)+ // The answer ends only once its charge is recorded, so a wallet read after it includes it.+ let answered = false+ const text = response.text().then((body) => {+ answered = true+ return body+ })+ await Bun.sleep(50)+ expect(answered).toBe(false)+ recordCharge?.()+ expect(await text).toContain('"content":"Hi"')const wallet = await responseJSON(await context.request(CLOUD_AI_API_PATHS.wallet, bearer),aiWalletSchema@@ -262,7 +291,11 @@ describe('AI relay', () => {await Promise.all(context.settled)const exhausted = await context.complete(bearer, { model: MODEL })expect(exhausted.status).toBe(402)- expect((await responseJSON(exhausted, aiErrorSchema)).error.code).toBe('insufficient_credits')+ // It says when the allowance renews, so the editor need not guess the relay's period.+ expect((await responseJSON(exhausted, aiErrorSchema)).error).toEqual({+ code: 'insufficient_credits',+ resetsAt: '2026-11-01T00:00:00.000Z'+ })expect(context.calls).toHaveLength(1)// Another workspace, and one without an allowance, are unaffected.diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex b9cd28bd2..4f984ee5b 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -336,7 +336,9 @@ forwards completions to one upstream with one key, and keeps one usage row per sworkspace's monthly spend is the sum of its rows. It reads usage from the upstream's answer, askingstreams for it with `stream_options.include_usage`, and keeps reading after the editor disconnectsso a request is still charged. It admits a request while credits remain and charges it afterwards,-so in-flight requests can overdraw an allowance; the official service reserves credits instead. It forwards only+so in-flight requests can overdraw an allowance; the official service reserves credits instead. An+answer ends only after its charge is recorded, so the wallet the editor reads once a reply ends+includes it, and a refusal for lack of credits says when the allowance renews. It forwards onlychat completion fields, so a router's fallback or provider fields cannot run a model outside thecatalog on its key. An upstream answer has ten minutes in all, streamed or not, before the relay ends it.diff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.mdindex e70dfb304..ffbc154a9 100644--- a/packages/docs/reference/self-hosting-cloud.md+++ b/packages/docs/reference/self-hosting-cloud.md@@ -97,7 +97,7 @@ Cloud does not run models itself. It advertises an AI service and signs short-li3. Copy [`openpencil-ai-relay.example.toml`](https://github.com/open-pencil/open-pencil/blob/master/packages/cloud/deploy/openpencil-ai-relay.example.toml), set `relay.cloud_url` to Cloud's `public_url`, `allowed_origins` to the browser editors, and list the models with their credit prices.4. Start it with `OPENPENCIL_AI_RELAY_CONFIG`, `OPENPENCIL_AI_RELAY_UPSTREAM_KEY`, and `DATABASE_URL` set: `node --env-file=.env dist-standalone/ai-relay.mjs`. It listens on `PORT` (default `8788`) and can share Cloud's database, keeping its own tables and migration history.-The relay charges a request once the upstream reports its usage, and admits one while the workspace has credits left, so requests already in flight can overdraw the month's allowance by what they cost; `relay.max_concurrent_requests` bounds them. A workspace's allowance renews at the start of each UTC month. It refuses a model request larger than `relay.max_request_bytes` (16 MiB by default) before reading it all. Choose an upstream that reports token usage: a request it reports none for is logged as an error and not charged.+The relay charges a request once the upstream reports its usage, and admits one while the workspace has credits left, so requests already in flight can overdraw the month's allowance by what they cost; `relay.max_concurrent_requests` bounds them. A workspace's allowance renews at the start of each UTC month. The editor's chat shows how many credits are left, and once they run out it says when the allowance renews and asks members to contact you; with no `[billing]` table it offers nothing to buy. It refuses a model request larger than `relay.max_request_bytes` (16 MiB by default) before reading it all. Choose an upstream that reports token usage: a request it reports none for is logged as an error and not charged.diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex f8771d8b9..6dcf62528 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -154,6 +154,11 @@"cloudAICatalogFailed": "OpenPencil Cloud konnte seine Modelle nicht auflisten. Prüfe deine Verbindung und versuche es erneut.","cloudAIWorkspacesFailed": "OpenPencil Cloud konnte nicht prüfen, welche deiner Arbeitsbereiche KI enthalten. Prüfe deine Verbindung und versuche es erneut.","chatCloudCreditsExhausted": "Dieser Arbeitsbereich hat das KI-Guthaben dieses Monats verbraucht. Verwalte seinen Tarif, um mehr hinzuzufügen.",+ "chatCloudAllowanceUsed": "Dieser Arbeitsbereich hat das KI-Kontingent dieses Monats verbraucht. Bitte deine Cloud-Administration, es zu erhöhen.",+ "chatCloudAllowanceUsedUntil": "Dieser Arbeitsbereich hat das KI-Kontingent dieses Monats verbraucht. Es erneuert sich am {date}. Bitte deine Cloud-Administration, es früher zu erhöhen.",+ "connectionTestCloudCreditsExhausted": "Dieser Arbeitsbereich hat diesen Monat kein KI-Guthaben mehr.",+ "cloudCreditsLeft": "Verbleibendes Guthaben: {credits}",+ "cloudCreditsRenew": "Erneuert sich am {date}","manageCloudPlanAction": "Tarif verwalten","chatCloudUnavailable": "OpenPencil-Cloud-KI ist nicht verfügbar. Melde dich bei OpenPencil Cloud an und wähle in den Einstellungen einen Arbeitsbereich.","chatInsufficientCredit": "Das Anbieterkonto hat nicht genügend Guthaben oder Kontingent. Lade es auf und versuche es erneut.",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex ace91d329..8273c7d42 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -160,6 +160,11 @@"cloudAICatalogFailed": "OpenPencil Cloud no pudo listar sus modelos. Comprueba tu conexión e inténtalo de nuevo.","cloudAIWorkspacesFailed": "OpenPencil Cloud no pudo comprobar cuáles de tus espacios de trabajo incluyen IA. Comprueba tu conexión e inténtalo de nuevo.","chatCloudCreditsExhausted": "Este espacio de trabajo ha usado los créditos de IA de este mes. Gestiona su plan para añadir más.",+ "chatCloudAllowanceUsed": "Este espacio de trabajo ha usado la asignación de IA de este mes. Pide a la administración de tu Cloud que la aumente.",+ "chatCloudAllowanceUsedUntil": "Este espacio de trabajo ha usado la asignación de IA de este mes. Se renueva el {date}. Pide a la administración de tu Cloud que la aumente antes.",+ "connectionTestCloudCreditsExhausted": "A este espacio de trabajo no le quedan créditos de IA este mes.",+ "cloudCreditsLeft": "Créditos restantes: {credits}",+ "cloudCreditsRenew": "Se renueva el {date}","manageCloudPlanAction": "Gestionar plan","chatCloudUnavailable": "La IA de OpenPencil Cloud no está disponible. Inicia sesión en OpenPencil Cloud y elige un espacio de trabajo en Ajustes.","chatInsufficientCredit": "La cuenta del proveedor no tiene suficiente saldo o cuota. Recárgala e inténtalo de nuevo.",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 738b7a7c5..5dfa5344f 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -154,6 +154,11 @@"cloudAICatalogFailed": "OpenPencil Cloud n’a pas pu lister ses modèles. Vérifiez votre connexion et réessayez.","cloudAIWorkspacesFailed": "OpenPencil Cloud n’a pas pu vérifier lesquels de vos espaces de travail incluent l’IA. Vérifiez votre connexion et réessayez.","chatCloudCreditsExhausted": "Cet espace de travail a utilisé les crédits d’IA de ce mois. Gérez son abonnement pour en ajouter.",+ "chatCloudAllowanceUsed": "Cet espace de travail a utilisé l’allocation d’IA de ce mois. Demandez à l’administration de votre Cloud de l’augmenter.",+ "chatCloudAllowanceUsedUntil": "Cet espace de travail a utilisé l’allocation d’IA de ce mois. Elle est renouvelée le {date}. Demandez à l’administration de votre Cloud de l’augmenter d’ici là.",+ "connectionTestCloudCreditsExhausted": "Cet espace de travail n’a plus de crédits d’IA ce mois-ci.",+ "cloudCreditsLeft": "Crédits restants : {credits}",+ "cloudCreditsRenew": "Renouvelé le {date}","manageCloudPlanAction": "Gérer l’abonnement","chatCloudUnavailable": "L’IA d’OpenPencil Cloud n’est pas disponible. Connectez-vous à OpenPencil Cloud et choisissez un espace de travail dans les paramètres.","chatInsufficientCredit": "Le compte du fournisseur n’a pas assez de crédit ou de quota. Rechargez-le et réessayez.",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 53afa7d2f..cb5933812 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -160,6 +160,11 @@"cloudAICatalogFailed": "OpenPencil Cloud non è riuscito a elencare i suoi modelli. Controlla la connessione e riprova.","cloudAIWorkspacesFailed": "OpenPencil Cloud non è riuscito a verificare quali delle tue aree di lavoro includono l’IA. Controlla la connessione e riprova.","chatCloudCreditsExhausted": "Questa area di lavoro ha usato i crediti IA di questo mese. Gestisci il suo piano per aggiungerne altri.",+ "chatCloudAllowanceUsed": "Questa area di lavoro ha usato l’assegnazione IA di questo mese. Chiedi all’amministrazione del tuo Cloud di aumentarla.",+ "chatCloudAllowanceUsedUntil": "Questa area di lavoro ha usato l’assegnazione IA di questo mese. Si rinnova il {date}. Chiedi all’amministrazione del tuo Cloud di aumentarla prima.",+ "connectionTestCloudCreditsExhausted": "Questa area di lavoro non ha più crediti IA questo mese.",+ "cloudCreditsLeft": "Crediti rimanenti: {credits}",+ "cloudCreditsRenew": "Si rinnova il {date}","manageCloudPlanAction": "Gestisci piano","chatCloudUnavailable": "L’IA di OpenPencil Cloud non è disponibile. Accedi a OpenPencil Cloud e scegli un’area di lavoro nelle impostazioni.","chatInsufficientCredit": "L’account del provider non dispone di credito o quota sufficiente. Ricaricalo e riprova.",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 94bdc362a..113db8392 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -160,6 +160,11 @@"cloudAICatalogFailed": "OpenPencil Cloud のモデル一覧を取得できませんでした。接続を確認して、もう一度お試しください。","cloudAIWorkspacesFailed": "OpenPencil Cloud で AI を含むワークスペースを確認できませんでした。接続を確認して、もう一度お試しください。","chatCloudCreditsExhausted": "このワークスペースは今月の AI クレジットを使い切りました。追加するにはプランを管理してください。",+ "chatCloudAllowanceUsed": "このワークスペースは今月の AI 割り当てを使い切りました。増やすには Cloud の管理者に依頼してください。",+ "chatCloudAllowanceUsedUntil": "このワークスペースは今月の AI 割り当てを使い切りました。{date} に更新されます。それより早く増やすには Cloud の管理者に依頼してください。",+ "connectionTestCloudCreditsExhausted": "このワークスペースには今月の AI クレジットが残っていません。",+ "cloudCreditsLeft": "残りクレジット: {credits}",+ "cloudCreditsRenew": "{date} に更新","manageCloudPlanAction": "プランを管理","chatCloudUnavailable": "OpenPencil Cloud の AI を利用できません。OpenPencil Cloud にサインインし、設定でワークスペースを選んでください。","chatInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex de5f8d17e..0c7a80657 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -154,6 +154,11 @@"cloudAICatalogFailed": "OpenPencil Cloud nie może wyświetlić swoich modeli. Sprawdź połączenie i spróbuj ponownie.","cloudAIWorkspacesFailed": "OpenPencil Cloud nie może sprawdzić, które z Twoich obszarów roboczych obejmują AI. Sprawdź połączenie i spróbuj ponownie.","chatCloudCreditsExhausted": "Ten obszar roboczy wykorzystał kredyty AI na ten miesiąc. Zarządzaj jego planem, aby dodać więcej.",+ "chatCloudAllowanceUsed": "Ten obszar roboczy wykorzystał przydział AI na ten miesiąc. Poproś administratora swojej chmury Cloud o jego zwiększenie.",+ "chatCloudAllowanceUsedUntil": "Ten obszar roboczy wykorzystał przydział AI na ten miesiąc. Odnowi się {date}. Poproś administratora swojej chmury Cloud, aby zwiększył go wcześniej.",+ "connectionTestCloudCreditsExhausted": "Ten obszar roboczy nie ma już kredytów AI w tym miesiącu.",+ "cloudCreditsLeft": "Pozostało kredytów: {credits}",+ "cloudCreditsRenew": "Odnawia się {date}","manageCloudPlanAction": "Zarządzaj planem","chatCloudUnavailable": "AI OpenPencil Cloud jest niedostępne. Zaloguj się do OpenPencil Cloud i wybierz obszar roboczy w ustawieniach.","chatInsufficientCredit": "Konto dostawcy nie ma wystarczających środków lub limitu. Doładuj je i spróbuj ponownie.",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex ab28bf7db..b9b863a09 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -154,6 +154,11 @@"cloudAICatalogFailed": "OpenPencil Cloud не удалось получить список моделей. Проверьте подключение и повторите попытку.","cloudAIWorkspacesFailed": "OpenPencil Cloud не удалось проверить, в каких рабочих пространствах есть ИИ. Проверьте подключение и повторите попытку.","chatCloudCreditsExhausted": "Это рабочее пространство израсходовало кредиты ИИ за этот месяц. Управляйте его тарифом, чтобы добавить ещё.",+ "chatCloudAllowanceUsed": "Это рабочее пространство израсходовало лимит ИИ за этот месяц. Попросите администратора вашего Cloud увеличить его.",+ "chatCloudAllowanceUsedUntil": "Это рабочее пространство израсходовало лимит ИИ за этот месяц. Он обновится {date}. Попросите администратора вашего Cloud увеличить его раньше.",+ "connectionTestCloudCreditsExhausted": "У этого рабочего пространства не осталось кредитов ИИ в этом месяце.",+ "cloudCreditsLeft": "Осталось кредитов: {credits}",+ "cloudCreditsRenew": "Обновится {date}","manageCloudPlanAction": "Управлять тарифом","chatCloudUnavailable": "ИИ OpenPencil Cloud недоступен. Войдите в OpenPencil Cloud и выберите рабочее пространство в настройках.","chatInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex aa936677f..019718099 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -160,6 +160,11 @@"cloudAICatalogFailed": "OpenPencil Cloud 无法列出其模型。请检查网络连接后重试。","cloudAIWorkspacesFailed": "OpenPencil Cloud 无法确认你的哪些工作区包含 AI。请检查网络连接后重试。","chatCloudCreditsExhausted": "此工作区已用完本月的 AI 额度。请管理其方案以增加额度。",+ "chatCloudAllowanceUsed": "此工作区已用完本月的 AI 配额。请联系 Cloud 管理员提高配额。",+ "chatCloudAllowanceUsedUntil": "此工作区已用完本月的 AI 配额,将于 {date} 续期。如需提前增加,请联系 Cloud 管理员。",+ "connectionTestCloudCreditsExhausted": "此工作区本月已没有 AI 额度。",+ "cloudCreditsLeft": "剩余额度:{credits}",+ "cloudCreditsRenew": "将于 {date} 续期","manageCloudPlanAction": "管理方案","chatCloudUnavailable": "OpenPencil Cloud AI 不可用。请登录 OpenPencil Cloud,并在设置中选择一个工作区。","chatInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex 254563452..f161373d4 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -221,6 +221,14 @@ export const aiMessageDefaults = {'OpenPencil Cloud could not check which of your workspaces include AI. Check your connection and try again.',chatCloudCreditsExhausted:'This workspace has used this month’s AI credits. Manage its plan to add more.',+ chatCloudAllowanceUsed:+ 'This workspace has used this month’s AI allowance. Ask your Cloud administrator to raise it.',+ chatCloudAllowanceUsedUntil: params(+ 'This workspace has used this month’s AI allowance. It renews on {date}. Ask your Cloud administrator to raise it sooner.'+ ),+ connectionTestCloudCreditsExhausted: 'This workspace has no AI credits left this month.',+ cloudCreditsLeft: params('{credits} credits left'),+ cloudCreditsRenew: params('Renews {date}'),manageCloudPlanAction: 'Manage plan',chatCloudUnavailable:'OpenPencil Cloud AI is unavailable. Sign in to OpenPencil Cloud and choose a workspace in Settings.',diff --git a/src/app/ai/chat/failure.ts b/src/app/ai/chat/failure.tsindex d90fdecfc..1affe33a1 100644--- a/src/app/ai/chat/failure.ts+++ b/src/app/ai/chat/failure.ts@@ -4,6 +4,7 @@ export type AIChatFailureReason =| 'authentication'| 'forbidden'| 'insufficient-credit'+ | 'cloud-credits-exhausted'| 'model-not-found'| 'network'| 'output-limit'@@ -17,6 +18,8 @@ export type AIChatFailure = {detail?: stringstatusCode?: numberretryable?: boolean+ /** With `cloud-credits-exhausted`: when the workspace's allowance renews, if the service said. */+ resetsAt?: string}export type ProviderErrorShape = {diff --git a/src/app/ai/chat/session.ts b/src/app/ai/chat/session.tsindex 2026758db..e7a6e1338 100644--- a/src/app/ai/chat/session.ts+++ b/src/app/ai/chat/session.ts@@ -12,6 +12,8 @@ import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'import { chatThinkingLevel } from '@/app/ai/chat/thinking'import { createAIModelRuntime, resolveModelConnectionAPIKey } from '@/app/ai/models'import { resolveLanguageModelID } from '@/app/ai/models/language-model'+import { cloudCreditRefusal } from '@/app/ai/providers/openpencil/failure'+import { OPENPENCIL_AI_PROVIDER } from '@/app/ai/providers/openpencil/provider'import { settleMessage } from '@/app/ai/reply/settle'import { currentRun } from '@/app/ai/tools'import type { AgentTurnUsage } from '@/app/ai/transports/acp'@@ -239,6 +241,8 @@ export function createChatSessionManager({if (!chat || transportDirty || currentChatStore !== store) {const messages = initialMessages ?? currentChatMessages.get(store)const diagnosticContext: AIDiagnosticContext = { sessionId, runId: crypto.randomUUID() }+ // Failures belong to the provider this chat was created for, even if the profile changes.+ const chatProviderID = providerID.valuelet transport: ChatTransport<UIMessage>// An ACP or Pi chat's tool calls show as an agent of that kind (`src/app/automation/agents.ts`).let agentKind: 'acp' | 'harness' | null = null@@ -264,9 +268,18 @@ export function createChatSessionManager({const reportedError = activeProviderError ?? erroractiveProviderError = nullconst signInOnly = AI_PROVIDERS.some(- (provider) => provider.id === providerID.value && provider.signInOnly+ (provider) => provider.id === chatProviderID && provider.signInOnly)- failure.value = classifyAIChatError(reportedError, { signInOnly })+ const classified = classifyAIChatError(reportedError, { signInOnly })+ const refusal =+ chatProviderID === OPENPENCIL_AI_PROVIDER ? cloudCreditRefusal(reportedError) : null+ failure.value = refusal+ ? {+ ...classified,+ reason: 'cloud-credits-exhausted',+ resetsAt: refusal.resetsAt ?? undefined+ }+ : classifiedconst { errorName, errorCode, message, stack } = diagnosticErrorDetails(reportedError)recordChatFailed({ errorName, errorCode, message, stack }, diagnosticContext)},diff --git a/src/app/ai/models/connection-test.ts b/src/app/ai/models/connection-test.tsindex f48fdf571..3b98293cb 100644--- a/src/app/ai/models/connection-test.ts+++ b/src/app/ai/models/connection-test.ts@@ -8,6 +8,8 @@ import {resolveLanguageModelID,type ModelConfig} from '@/app/ai/models/language-model'+import { cloudCreditRefusal } from '@/app/ai/providers/openpencil/failure'+import { OPENPENCIL_AI_PROVIDER } from '@/app/ai/providers/openpencil/provider'import type { ModelProviderRuntime } from '@/app/ai/providers/types'import { isTauri } from '@/app/tauri/env'@@ -30,6 +32,7 @@ export type ProviderConnectionTestFailureReason =| 'browser-network'| 'network'| 'cloud-unavailable'+ | 'cloud-credits-exhausted'| 'unknown'function isCompatibleProvider(providerID: ModelConfig['providerID']): boolean {@@ -100,7 +103,14 @@ function classifyMessage(text: string): ProviderConnectionTestFailureReason | nureturn null}-function classifyError(error: unknown): ProviderConnectionTestFailureReason {+function classifyError(+ error: unknown,+ providerID: ModelConfig['providerID']+): ProviderConnectionTestFailureReason {+ // The workspace's plan holds Cloud's credits, not a provider account to top up.+ if (providerID === OPENPENCIL_AI_PROVIDER && cloudCreditRefusal(error)) {+ return 'cloud-credits-exhausted'+ }if (isInsufficientCreditError(error)) return 'insufficient-credit'const text = errorText(error).toLowerCase()return classifyStatus(providerErrorStatus(error), text) ?? classifyMessage(text) ?? 'unknown'@@ -127,7 +137,7 @@ export async function testProviderConnection(})return { ok: true }} catch (error) {- const reason = classifyError(error)+ const reason = classifyError(error, config.providerID)if (reason !== 'auth' || !isSignInOnly(config.providerID)) return { ok: false, reason }// A provider signed in to has no key: a 403 is the plan, anything else the sign-in.const planForbidden = providerErrorStatus(error) === 403diff --git a/src/app/ai/providers/openpencil/balance.ts b/src/app/ai/providers/openpencil/balance.tsnew file mode 100644index 000000000..ebbc3aac2--- /dev/null+++ b/src/app/ai/providers/openpencil/balance.ts@@ -0,0 +1,70 @@+import { computed, shallowRef, watch, type Ref } from 'vue'++import type { CloudAIClient } from '@open-pencil/cloud/client'+import type { AIWallet } from '@open-pencil/cloud/contract'++import { cloudAIClient, cloudAIIdentity } from '@/app/cloud/integration'++/** The Home server's AI service as the balance reads it. */+export interface CloudBalanceSource {+ identity: Readonly<Ref<string | null>>+ client: (workspaceId: string) => Pick<CloudAIClient, 'wallet'> | null+}++const HOME_CLOUD: CloudBalanceSource = { identity: cloudAIIdentity, client: cloudAIClient }++interface CloudBalanceOptions {+ /** The workspace whose credits are shown, or `null` when the chat does not use Cloud. */+ workspaceId: () => string | null+ /** Whether a reply is running; the balance is read again once it ends. */+ replying: () => boolean+}++/**+ * A workspace's credits on Cloud's AI service. Unknown while it loads, when it cannot be read, and+ * for another account's or workspace's answer, so the chat never shows a stale balance.+ */+export function useCloudCreditBalance(+ { workspaceId, replying }: CloudBalanceOptions,+ source: CloudBalanceSource = HOME_CLOUD+) {+ const wallet = shallowRef<AIWallet | null>(null)+ let request = 0++ async function refresh(): Promise<void> {+ const current = ++request+ const id = workspaceId()+ const client = id ? source.client(id) : null+ if (!client) {+ wallet.value = null+ return+ }+ try {+ const next = await client.wallet()+ if (current === request) wallet.value = next+ } catch {+ if (current === request) wallet.value = null+ }+ }++ watch(+ [source.identity, workspaceId],+ () => {+ wallet.value = null+ void refresh()+ },+ { immediate: true }+ )+ watch(replying, (now, before) => {+ if (before && !now) void refresh()+ })++ return {+ /** Credits left, or `null` when unknown or unlimited. */+ balance: computed(() => wallet.value?.balance ?? null),+ /** When the monthly allowance renews, if the workspace has one. */+ renewsAt: computed(+ () => wallet.value?.buckets.find((bucket) => bucket.kind === 'allowance')?.expiresAt ?? null+ )+ }+}diff --git a/src/app/ai/providers/openpencil/failure.ts b/src/app/ai/providers/openpencil/failure.tsnew file mode 100644index 000000000..99c6279e7--- /dev/null+++ b/src/app/ai/providers/openpencil/failure.ts@@ -0,0 +1,18 @@+import { APICallError } from 'ai'+import * as v from 'valibot'++import { aiErrorSchema } from '@open-pencil/cloud/contract'++const errorBodySchema = v.pipe(v.string(), v.parseJson(), aiErrorSchema)++/**+ * Cloud's AI service refusing a request because the workspace has no credits left, with when its+ * allowance renews if the service says. `null` for anything else, such as an upstream's own 402+ * the service passed through, which is the service's provider account, not the workspace.+ */+export function cloudCreditRefusal(error: unknown): { resetsAt: string | null } | null {+ if (!APICallError.isInstance(error) || error.responseBody === undefined) return null+ const parsed = v.safeParse(errorBodySchema, error.responseBody)+ if (!parsed.success || parsed.output.error.code !== 'insufficient_credits') return null+ return { resetsAt: parsed.output.error.resetsAt ?? null }+}diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex a3bd3bfdb..1ac5cbb89 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -8,16 +8,15 @@ import { useI18n } from '@open-pencil/vue/i18n'import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'import { chatDocumentId } from '@/app/ai/chat/history/document'import { useChatRunLocation } from '@/app/ai/chat/run-location'-import { providerID } from '@/app/ai/chat/storage'import type { ChatSubmission } from '@/app/ai/chat/submission/types'import { useChatSubmission } from '@/app/ai/chat/submission/use'import { saveChatTrace } from '@/app/ai/chat/trace/export'import { useAIChat } from '@/app/ai/chat/use'import { openAISetup } from '@/app/ai/models/settings/onboarding/dialog'-import { OPENPENCIL_AI_PROVIDER } from '@/app/ai/providers/openpencil/provider'import { didHitStepLimit } from '@/app/ai/tools'import { cloudBillingURL } from '@/app/cloud/integration'import { getActiveEditorStore } from '@/app/editor/active-store'+import { useDateFormat } from '@/app/i18n/date'import { openSettingsDialog } from '@/app/settings/dialog'import { openExternalLink, toast } from '@/app/shell/ui'import { activeTab } from '@/app/tabs'@@ -32,6 +31,7 @@ import ProviderSetup from '@/components/chat/ProviderSetup.vue'const { isConfigured, ensureChat, history, chatFailure, clearChatFailure } = useAIChat()const { ai } = useI18n()+const dates = useDateFormat()const runLocation = useChatRunLocation()const chat = shallowRef<Chat<UIMessage> | null>(null)@@ -128,6 +128,15 @@ async function saveTrace(id: string) {}}+/**+ * A Cloud that bills sells more credits; a self-hosted one has only the allowance its+ * administrator set, which renews or is raised.+ */+function cloudCreditsMessage(resetsAt: string | undefined): string {+ if (cloudBillingURL.value) return ai.value.chatCloudCreditsExhausted+ if (!resetsAt) return ai.value.chatCloudAllowanceUsed+ return ai.value.chatCloudAllowanceUsedUntil({ date: dates.format(resetsAt, 'dayTime') })+}const failureMessage = computed(() => {switch (chatFailure.value?.reason) {case 'authentication':@@ -135,9 +144,9 @@ const failureMessage = computed(() => {case 'forbidden':return ai.value.chatForbiddencase 'insufficient-credit':- return providerID.value === OPENPENCIL_AI_PROVIDER- ? ai.value.chatCloudCreditsExhausted- : ai.value.chatInsufficientCredit+ return ai.value.chatInsufficientCredit+ case 'cloud-credits-exhausted':+ return cloudCreditsMessage(chatFailure.value.resetsAt)case 'model-not-found':return ai.value.chatModelNotFoundcase 'network':@@ -191,11 +200,7 @@ watch()function failureAction(failedId: string | undefined): { label: string; run: () => void } {const billingURL = cloudBillingURL.value- if (- chatFailure.value?.reason === 'insufficient-credit' &&- providerID.value === OPENPENCIL_AI_PROVIDER &&- billingURL- ) {+ if (chatFailure.value?.reason === 'cloud-credits-exhausted' && billingURL) {return { label: ai.value.manageCloudPlanAction, run: () => void openExternalLink(billingURL) }}return failureHasSettingsAction.valuediff --git a/src/components/chat/ChatCreditBalance.vue b/src/components/chat/ChatCreditBalance.vuenew file mode 100644index 000000000..47d4d924f--- /dev/null+++ b/src/components/chat/ChatCreditBalance.vue@@ -0,0 +1,62 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue/i18n'++import { designModelConnection } from '@/app/ai/models'+import { useCloudCreditBalance } from '@/app/ai/providers/openpencil/balance'+import { OPENPENCIL_AI_PROVIDER } from '@/app/ai/providers/openpencil/provider'+import { cloudBillingURL } from '@/app/cloud/integration'+import { useDateFormat } from '@/app/i18n/date'+import { formatNumber } from '@/app/i18n/number'+import { openExternalLink } from '@/app/shell/ui'+import Tip from '@/components/ui/overlay/Tip.vue'+import { chatProfileTheme } from '@/theme/chat/profile'++const { replying } = defineProps<{ replying: boolean }>()+const { ai } = useI18n()+const dates = useDateFormat()+const ui = chatProfileTheme()++const { balance, renewsAt } = useCloudCreditBalance({+ workspaceId: () => {+ const connection = designModelConnection.value+ return connection?.providerID === OPENPENCIL_AI_PROVIDER+ ? (connection.cloudWorkspaceId ?? null)+ : null+ },+ replying: () => replying+})++const label = computed(() =>+ balance.value === null ? '' : ai.value.cloudCreditsLeft({ credits: formatNumber(balance.value) })+)+// A Cloud that bills links to its plan; a self-hosted allowance only renews.+const hint = computed(() => {+ if (cloudBillingURL.value) return ai.value.manageCloudPlanAction+ return renewsAt.value+ ? ai.value.cloudCreditsRenew({ date: dates.format(renewsAt.value, 'dayTime') })+ : undefined+})++function openPlan(): void {+ if (cloudBillingURL.value) void openExternalLink(cloudBillingURL.value)+}+</script>++<template>+ <Tip v-if="balance !== null" :label="hint" :disabled="!hint" as-child>+ <button+ v-if="cloudBillingURL"+ type="button"+ :class="ui.trigger({ class: 'shrink-0 cursor-pointer hover:text-surface' })"+ data-test-id="chat-cloud-credits"+ @click="openPlan"+ >+ {{ label }}+ </button>+ <span v-else :class="ui.trigger({ class: 'shrink-0' })" data-test-id="chat-cloud-credits">+ {{ label }}+ </span>+ </Tip>+</template>diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vueindex 70ce4624f..f12846a4d 100644--- a/src/components/chat/ChatInput.vue+++ b/src/components/chat/ChatInput.vue@@ -11,6 +11,7 @@ import type { ChatSubmission } from '@/app/ai/chat/submission/types'import { useAIChat } from '@/app/ai/chat/use'import { designModelProfile } from '@/app/ai/models'import { openSettingsDialog } from '@/app/settings/dialog'+import ChatCreditBalance from '@/components/chat/ChatCreditBalance.vue'import ChatNodePreview from '@/components/chat/ChatNodePreview.vue'import ChatProfileSelect from '@/components/chat/ChatProfileSelect.vue'import ChatThinkingSelect from '@/components/chat/ChatThinkingSelect.vue'@@ -217,6 +218,7 @@ const selectedProfileName = computed(</template></ChatProfileSelect><ChatThinkingSelect />+ <ChatCreditBalance :replying="isStreaming" /></template></div></template>diff --git a/src/components/settings/provider/ProviderConnectionTestButton.vue b/src/components/settings/provider/ProviderConnectionTestButton.vueindex fab494c73..e4c03da3b 100644--- a/src/components/settings/provider/ProviderConnectionTestButton.vue+++ b/src/components/settings/provider/ProviderConnectionTestButton.vue@@ -51,6 +51,8 @@ const resultMessage = computed(() => {return ai.value.connectionTestNetworkFailedcase 'cloud-unavailable':return ai.value.cloudAIUnavailable+ case 'cloud-credits-exhausted':+ return ai.value.connectionTestCloudCreditsExhausteddefault:return ai.value.connectionTestUnknownFailed}diff --git a/tests/app/ai/models/connection-test.test.ts b/tests/app/ai/models/connection-test.test.tsnew file mode 100644index 000000000..390eac9c0--- /dev/null+++ b/tests/app/ai/models/connection-test.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test'++import { createCloudAIClient } from '@open-pencil/cloud/client'++import { testProviderConnection } from '@/app/ai/models/connection-test'+import { cloudModelConfig } from '@/app/ai/providers/openpencil/model'++/** Tests a Cloud model whose service answers every request with `status` and `body`. */+function testCloudModel(status: number, body: unknown) {+ const client = createCloudAIClient({+ endpoint: 'https://ai.example.com',+ tokens: { token: async () => 'cloud-token', invalidate: () => undefined },+ fetch: async () => Response.json(body, { status })+ })+ const { config, runtime } = cloudModelConfig(client, 'test/model')+ return testProviderConnection(config, runtime)+}++describe('testProviderConnection on Cloud’s AI service', () => {+ test('reports a workspace out of credits when the service refuses for that', async () => {+ expect(await testCloudModel(402, { error: { code: 'insufficient_credits' } })).toEqual({+ ok: false,+ reason: 'cloud-credits-exhausted'+ })+ })++ test('reports an upstream’s own 402, which the service passed through, as the provider’s', async () => {+ expect(+ await testCloudModel(402, { error: { code: 402, message: 'Insufficient credits' } })+ ).toEqual({ ok: false, reason: 'insufficient-credit' })+ })+})diff --git a/tests/app/ai/providers/openpencil/balance.test.ts b/tests/app/ai/providers/openpencil/balance.test.tsnew file mode 100644index 000000000..31148e0af--- /dev/null+++ b/tests/app/ai/providers/openpencil/balance.test.ts@@ -0,0 +1,142 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { effectScope, nextTick, ref, type EffectScope } from 'vue'++import type { AIWallet } from '@open-pencil/cloud/contract'++import {+ useCloudCreditBalance,+ type CloudBalanceSource+} from '@/app/ai/providers/openpencil/balance'+import { createDeferred, type Deferred } from '@/app/runtime/deferred'++function wallet(balance: number | null): AIWallet {+ return {+ balance,+ buckets:+ balance === null+ ? []+ : [{ kind: 'allowance', remaining: balance, expiresAt: '2026-11-01T00:00:00.000Z' }]+ }+}++/** A Home server whose wallets answer when the test says so. */+function homeCloud() {+ const identity = ref<string | null>('home:alice')+ const answers: Deferred<AIWallet>[] = []+ const source: CloudBalanceSource = {+ identity,+ client: () =>+ identity.value+ ? {+ wallet: () => {+ const next = createDeferred<AIWallet>()+ answers.push(next)+ return next.promise+ }+ }+ : null+ }+ return { identity, source, answers }+}++const scopes: EffectScope[] = []+afterEach(() => {+ for (const scope of scopes.splice(0)) scope.stop()+})++function show(source: CloudBalanceSource, workspaceId = ref<string | null>('team')) {+ const replying = ref(false)+ const scope = effectScope()+ scopes.push(scope)+ const balance = scope.run(() =>+ useCloudCreditBalance(+ { workspaceId: () => workspaceId.value, replying: () => replying.value },+ source+ )+ )+ if (!balance) throw new Error('balance was not created')+ return { ...balance, replying, workspaceId }+}++async function settle(): Promise<void> {+ await nextTick()+ await Promise.resolve()+}++describe('useCloudCreditBalance', () => {+ test('shows the workspace’s credits and when its allowance renews', async () => {+ const home = homeCloud()+ const credits = show(home.source)+ home.answers[0]?.resolve(wallet(1200))+ await settle()++ expect(credits.balance.value).toBe(1200)+ expect(credits.renewsAt.value).toBe('2026-11-01T00:00:00.000Z')+ })++ test('reads the balance again once a reply ends', async () => {+ const home = homeCloud()+ const credits = show(home.source)+ home.answers[0]?.resolve(wallet(1200))+ await settle()++ credits.replying.value = true+ await settle()+ expect(home.answers).toHaveLength(1)+ credits.replying.value = false+ await settle()+ home.answers[1]?.resolve(wallet(1100))+ await settle()++ expect(credits.balance.value).toBe(1100)+ })++ test('drops an earlier workspace’s balance that answers last', async () => {+ const home = homeCloud()+ const credits = show(home.source)+ credits.workspaceId.value = 'other'+ await settle()+ expect(credits.balance.value).toBeNull()++ home.answers[1]?.resolve(wallet(50))+ await settle()+ home.answers[0]?.resolve(wallet(1200))+ await settle()++ expect(credits.balance.value).toBe(50)+ })++ test('hides the balance after signing out, an unlimited one, and one that cannot be read', async () => {+ const home = homeCloud()+ const credits = show(home.source)+ home.answers[0]?.resolve(wallet(1200))+ await settle()+ home.identity.value = null+ await settle()+ expect(credits.balance.value).toBeNull()++ home.identity.value = 'home:alice'+ await settle()+ home.answers[1]?.resolve(wallet(null))+ await settle()+ expect(credits.balance.value).toBeNull()++ credits.replying.value = true+ await settle()+ credits.replying.value = false+ await settle()+ home.answers[2]?.reject(new Error('offline'))+ await settle()+ expect(credits.balance.value).toBeNull()+ })++ test('reads nothing for a chat that does not use Cloud', async () => {+ const home = homeCloud()+ const credits = show(home.source, ref<string | null>(null))+ await settle()++ expect(home.answers).toHaveLength(0)+ expect(credits.balance.value).toBeNull()+ })+})diff --git a/tests/app/ai/providers/openpencil/failure.test.ts b/tests/app/ai/providers/openpencil/failure.test.tsnew file mode 100644index 000000000..5e907c46a--- /dev/null+++ b/tests/app/ai/providers/openpencil/failure.test.ts@@ -0,0 +1,57 @@+import { describe, expect, test } from 'bun:test'++import { createCloudAIClient } from '@open-pencil/cloud/client'++import { createLanguageModel } from '@/app/ai/models/language-model'+import { cloudCreditRefusal } from '@/app/ai/providers/openpencil/failure'+import { cloudModelConfig } from '@/app/ai/providers/openpencil/model'++/** What a model request fails with when the service answers `status` with `body`. */+async function modelFailure(status: number, body: unknown): Promise<unknown> {+ const client = createCloudAIClient({+ endpoint: 'https://ai.example.com',+ tokens: { token: async () => 'cloud-token', invalidate: () => undefined },+ fetch: async () => Response.json(body, { status })+ })+ const { config, runtime } = cloudModelConfig(client, 'test/model')+ const model = createLanguageModel(config, runtime)+ if (typeof model === 'string') throw new Error('Expected a model instance')+ try {+ await model.doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] })+ } catch (error) {+ return error+ }+ throw new Error('The request did not fail')+}++describe('cloudCreditRefusal', () => {+ test('reads when the allowance renews from the service’s refusal', async () => {+ const error = await modelFailure(402, {+ error: { code: 'insufficient_credits', resetsAt: '2026-11-01T00:00:00.000Z' }+ })+ expect(cloudCreditRefusal(error)).toEqual({ resetsAt: '2026-11-01T00:00:00.000Z' })+ })++ test('is a refusal without a renewal when the service does not say when', async () => {+ expect(+ cloudCreditRefusal(await modelFailure(402, { error: { code: 'insufficient_credits' } }))+ ).toEqual({ resetsAt: null })+ })++ test('is not one for an upstream’s own 402 or another refusal', async () => {+ // OpenRouter's answer when the service's own key is out of credits, passed through.+ expect(+ cloudCreditRefusal(+ await modelFailure(402, { error: { code: 402, message: 'Insufficient credits' } })+ )+ ).toBeNull()+ expect(+ cloudCreditRefusal(+ await modelFailure(429, {+ error: { code: 'rate_limited', resetsAt: '2026-11-01T00:00:00.000Z' }+ })+ )+ ).toBeNull()+ expect(cloudCreditRefusal(new Error('offline'))).toBeNull()+ })+})diff --git a/tests/e2e/chat/cloud-ai.spec.ts b/tests/e2e/chat/cloud-ai.spec.tsnew file mode 100644index 000000000..86dbb03a8--- /dev/null+++ b/tests/e2e/chat/cloud-ai.spec.ts@@ -0,0 +1,111 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'+import { ChatHarness } from '#tests/helpers/chat/harness'+import {+ CLOUD_AI_MODEL,+ CLOUD_AI_REPLY,+ cloudHomeStorage,+ routeCloudAI+} from '#tests/helpers/cloud/ai'++/** A balance of exactly zero, however the label words it. */+const NO_CREDITS = /^\D*\b0\b\D*$/++test.use({+ storageState: async ({ baseURL }, use) => {+ if (!baseURL) throw new Error('Browser test baseURL is required')+ await use({+ cookies: [],+ origins: [+ {+ origin: new URL(baseURL).origin,+ localStorage: [+ {+ name: 'open-pencil:preferences:v1',+ value: JSON.stringify({ version: 1, onboarding: { aiSetup: 'done' } })+ },+ cloudHomeStorage()+ ]+ }+ ]+ })+ }+})++const closers: (() => Promise<void>)[] = []+test.afterEach(async () => {+ for (const close of closers.splice(0)) await close()+})++/** Sets up a Design model on the signed-in Cloud server, paid for by its workspace. */+async function openCloudChat(+ page: Page,+ baseURL: string | undefined,+ options: Parameters<typeof routeCloudAI>[2]+) {+ const cloud = await routeCloudAI(page, new URL(baseURL ?? '').origin, options)+ closers.push(cloud.close)+ const chat = new ChatHarness(page)+ await chat.open()+ await new CanvasHelper(page).waitForInit()+ await chat.chatTab.click()+ await page.getByTestId('provider-setup-open-settings').click()+ await page.locator('[data-model-id]').first().click()+ await page.getByTestId('settings-model-provider').click()+ await page.getByRole('option', { name: 'OpenPencil Cloud' }).click()+ await expect(page.getByTestId('settings-cloud-ai-workspace')).toContainText('Studio')+ await expect(page.getByTestId('settings-model-editor')).toContainText(CLOUD_AI_MODEL)+ await page.getByLabel('Name').fill('Cloud')+ await page.getByRole('button', { name: 'Save model' }).click()+ await page.getByTestId('app-settings-done').click()+ await chat.input.waitFor()+ return {+ chat,+ cloud,+ credits: page.getByTestId('chat-cloud-credits'),+ toast: page.locator('[data-slot="toast"]')+ }+}++test('a Cloud model answers through the AI service and its credits go down', async ({+ page,+ baseURL+}) => {+ const { chat, cloud, credits } = await openCloudChat(page, baseURL, { allowance: 1000 })+ await expect(credits).toContainText('1,000')++ await chat.submit('Say hello')++ await expect(chat.assistantMessage()).toContainText(CLOUD_AI_REPLY)+ await expect(credits).toContainText('700')+ expect(cloud.unexpected).toEqual([])+})++test('a self-hosted allowance that runs out offers nothing to buy', async ({ page, baseURL }) => {+ const { chat, credits, toast } = await openCloudChat(page, baseURL, { allowance: 300 })+ await chat.submit('Say hello')+ await expect(chat.assistantMessage()).toContainText(CLOUD_AI_REPLY)+ await expect(credits).toHaveText(NO_CREDITS)+ await expect(credits).not.toHaveRole('button')++ await chat.submit('Say hello again')++ await expect(toast).toBeVisible()+ await expect(toast.getByRole('button', { name: 'Manage plan' })).toHaveCount(0)+})++test('a Cloud that bills offers its plan once the credits run out', async ({ page, baseURL }) => {+ const { chat, credits, toast } = await openCloudChat(page, baseURL, {+ allowance: 300,+ billingURL: 'https://billing.example.com/portal'+ })+ await chat.submit('Say hello')+ await expect(chat.assistantMessage()).toContainText(CLOUD_AI_REPLY)+ await expect(credits).toHaveText(NO_CREDITS)+ await expect(credits).toHaveRole('button')++ await chat.submit('Say hello again')++ await expect(toast.getByRole('button', { name: 'Manage plan' })).toBeVisible()+})diff --git a/tests/helpers/cloud/ai.ts b/tests/helpers/cloud/ai.tsnew file mode 100644index 000000000..7fad5c1e1--- /dev/null+++ b/tests/helpers/cloud/ai.ts@@ -0,0 +1,219 @@+import { createHash } from 'node:crypto'++import {+ createAIRelayApp,+ createAIRelayDatabase,+ migrateAIRelayDatabase,+ parseAIRelayConfig+} from '#cloud/ai-relay'+import { CLOUD_AI_CONTRACT_VERSION, CLOUD_AI_TOKEN_AUDIENCE } from '#cloud/contract'+import { PGlite } from '@electric-sql/pglite'+import type { Page, Route } from '@playwright/test'+import { createLocalJWKSet, exportJWK, generateKeyPair, SignJWT } from 'jose'+import { PGliteDialect } from 'kysely-pglite-dialect'++import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'++const CLOUD = 'https://cloud.example.com'+const AI = 'https://ai.example.com'+const WORKSPACE_ID = '6f1c2d3e-4f50-4d7e-9a52-0b6f4f9e3c1a'+const ACCOUNT = { id: 'user-1', name: 'Ada', email: '[email protected]' }+export const CLOUD_AI_MODEL = 'Cloud Test Model'+export const CLOUD_AI_REPLY = 'Hello from Cloud'+/** What each reply costs: 100,000 input tokens at 3,000 credits per million. */+export const CLOUD_AI_REPLY_CREDITS = 300++interface CloudAIOptions {+ /** Credits the workspace's plan grants each month. */+ allowance: number+ /** Where the server sells credits; a self-hosted server has none. */+ billingURL?: string+}++/** The fake upstream's answer: a short streamed reply that reports its usage. */+function upstreamReply(): Response {+ const event = (data: object) => `data: ${JSON.stringify(data)}\n\n`+ const chunk = { id: 'cloud-test', object: 'chat.completion.chunk', created: 0, model: 'test' }+ return new Response(+ event({+ ...chunk,+ choices: [{ index: 0, delta: { role: 'assistant', content: CLOUD_AI_REPLY } }]+ }) ++ event({ ...chunk, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }) ++ event({ ...chunk, choices: [], usage: { prompt_tokens: 100_000, completion_tokens: 0 } }) ++ 'data: [DONE]\n\n',+ { headers: { 'Content-Type': 'text/event-stream' } }+ )+}++/** The reference relay, with an in-memory database, Cloud's key, and the fake upstream. */+async function startRelay(appOrigin: string) {+ const pglite = await PGlite.create({ dataDir: 'memory://' })+ const database = createAIRelayDatabase(new PGliteDialect(pglite))+ await migrateAIRelayDatabase(database)+ const { privateKey, publicKey } = await generateKeyPair('ES256')+ const app = createAIRelayApp({+ config: parseAIRelayConfig(+ {+ schema_version: 1,+ relay: { cloud_url: CLOUD, allowed_origins: [appOrigin] },+ upstream: { base_url: 'https://upstream.example.com/v1' },+ catalog: {+ default_model: 'test/cloud-model',+ models: [+ {+ id: 'test/cloud-model',+ label: CLOUD_AI_MODEL,+ credits_per_million_input_tokens: 3000,+ credits_per_million_output_tokens: 15000,+ context_tokens: 200_000,+ tools: true+ }+ ]+ }+ },+ { DATABASE_URL: 'postgresql://unused', OPENPENCIL_AI_RELAY_UPSTREAM_KEY: 'upstream-key' }+ ),+ database,+ keys: createLocalJWKSet({ keys: [{ ...(await exportJWK(publicKey)), kid: 'cloud' }] }),+ fetch: async () => upstreamReply()+ })+ return { app, privateKey, close: () => database.destroy() }+}++/** Cloud answers the editor's own origin with its session cookie, as a server listing it would. */+function cloudHeaders(appOrigin: string): Record<string, string> {+ return {+ 'Access-Control-Allow-Origin': appOrigin,+ 'Access-Control-Allow-Credentials': 'true',+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'+ }+}++async function forward(route: Route, fetch: (request: Request) => Promise<Response> | Response) {+ const request = route.request()+ const body = request.postDataBuffer()+ const response = await fetch(+ new Request(request.url(), {+ method: request.method(),+ headers: request.headers(),+ body: body && request.method() !== 'GET' ? new Uint8Array(body) : undefined+ })+ )+ await route.fulfill({+ status: response.status,+ headers: Object.fromEntries(response.headers),+ body: Buffer.from(await response.arrayBuffer())+ })+}++/** The stubbed server on Home, remembering Ada's sign-in, as a `storageState` entry. */+export function cloudHomeStorage(): { name: string; value: string } {+ const serverId = createHash('sha256').update(CLOUD).digest('hex').slice(0, 32)+ return {+ name: 'open-pencil:cloud-servers',+ value: JSON.stringify({+ servers: [+ {+ id: serverId,+ url: CLOUD,+ kind: 'self-hosted',+ account: ACCOUNT,+ addedAt: '2026-10-01T00:00:00.000Z'+ }+ ],+ home: serverId+ })+ }+}++/**+ * A Cloud server, put on Home by `cloudHomeStorage`, with Ada signed in and one workspace whose+ * plan includes AI, advertising the reference relay. Cloud is stubbed; the relay is the real one, metering a fake+ * upstream, so the editor's requests, tokens, and the wallet go through the open contract.+ */+export async function routeCloudAI(page: Page, appOrigin: string, options: CloudAIOptions) {+ const relay = await startRelay(appOrigin)+ const now = new Date().toISOString()+ const discovery = {+ ...cloudDiscoveryFixture(CLOUD),+ ai: { endpoint: AI, contractVersion: CLOUD_AI_CONTRACT_VERSION },+ ...(options.billingURL ? { billing: { portalURL: options.billingURL } } : {})+ }+ const cloud: Record<string, () => unknown | Promise<unknown>> = {+ 'GET /.well-known/openpencil': () => discovery,+ 'GET /api/account/status': () => ({+ user: { userId: ACCOUNT.id, email: ACCOUNT.email, name: ACCOUNT.name },+ state: 'active'+ }),+ 'GET /api/workspaces': () => ({+ workspaces: [+ {+ id: WORKSPACE_ID,+ name: 'Studio',+ slug: 'studio',+ role: 'editor',+ createdAt: now,+ updatedAt: now+ }+ ]+ }),+ [`GET /api/workspaces/${WORKSPACE_ID}/documents`]: () => ({ documents: [] }),+ [`GET /api/workspaces/${WORKSPACE_ID}/entitlements`]: () => ({+ entitlements: {+ features: {+ links: true,+ guestView: true,+ guestEdit: true,+ guestPresence: true,+ collaboration: true,+ revisionHistory: true,+ cloudAI: true+ },+ limits: {+ maximumFileBytes: 100_000_000,+ maximumStorageBytes: null,+ maximumParticipants: null,+ monthlyCreditAllowance: options.allowance+ },+ usage: { committedStorageBytes: 0, reservedStorageBytes: 0 }+ }+ }),+ 'POST /api/ai/token': async () => {+ const expiresAt = new Date(Date.now() + 10 * 60_000)+ const token = await new SignJWT({+ workspaceId: WORKSPACE_ID,+ monthlyCreditAllowance: options.allowance+ })+ .setProtectedHeader({ alg: 'ES256', kid: 'cloud' })+ .setIssuer(CLOUD)+ .setAudience(CLOUD_AI_TOKEN_AUDIENCE)+ .setSubject(ACCOUNT.id)+ .setIssuedAt()+ .setExpirationTime(expiresAt)+ .sign(relay.privateKey)+ return { token, expiresAt: expiresAt.toISOString() }+ }+ }++ const unexpected: string[] = []+ await page.route(`${CLOUD}/**`, async (route) => {+ const request = route.request()+ const headers = cloudHeaders(appOrigin)+ if (request.method() === 'OPTIONS') return route.fulfill({ status: 204, headers })+ const answer = cloud[`${request.method()} ${new URL(request.url()).pathname}`]+ if (!answer) {+ unexpected.push(`${request.method()} ${request.url()}`)+ return route.fulfill({ status: 404, headers, json: { error: { code: 'not_found' } } })+ }+ return route.fulfill({ headers, json: await answer() })+ })+ await page.route(`${AI}/**`, (route) => forward(route, (request) => relay.app.fetch(request)))++ return {+ /** Cloud requests the stub has no answer for, which a test expects to be none. */+ unexpected,+ close: relay.close+ }+}diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex c931804bd..ac5fab781 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -562,3 +562,9 @@ ja:ai.cloudAICatalogFailedzh-cn:ai.cloudAICatalogFailedja:ai.cloudAIWorkspacesFailedzh-cn:ai.cloudAIWorkspacesFailed+ja:ai.chatCloudAllowanceUsed+ja:ai.chatCloudAllowanceUsedUntil+ja:ai.connectionTestCloudCreditsExhausted+zh-cn:ai.chatCloudAllowanceUsed+zh-cn:ai.chatCloudAllowanceUsedUntil+zh-cn:ai.connectionTestCloudCreditsExhausted