Skip to content

Prompt as Code | GPT Image 2 / 2.5 提示词与案例库,530+ 个案例、20+ 套工业级模板与可复用 Skills,新增 2.5 同提示词对比专区,附完整提示词与生成记录,持续更新。

feat: integrate APIMart GPT-Image-2 generation

freestyleflyb477278bb2a3
diff --git a/.env.example b/.env.example
index fdfe44e..39b9666 100644
--- a/.env.example
+++ b/.env.example
@@ -1,5 +1,4 @@
-CIYUAN_API_KEY=
-CIYUAN_BASE_URL=https://ciyuan.today
+APIMART_API_KEY=
VITE_SUPABASE_URL=
VITE_SUPABASE_ANON_KEY=
diff --git a/README.ja.md b/README.ja.md
index 6c56e19..538bfc9 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -305,7 +305,7 @@ Skill のソースは [`agents/skills/gpt-image-2-style-library`](agents/skills/
## 🔐 Web サイト認証と生成
-ビジュアルサイトには、ログイン後にケース生成を試せる機能が含まれています。基盤には Supabase Auth、Supabase Postgres、GPT Image 2 API 向けの Vercel Function プロキシを使用しています。
+ビジュアルサイトでは、ブラウザ内だけに保存する個人 APIMart API Key を使って直接生成できます。個人 Key がない場合は、ログイン、Supabase、プラットフォームクレジット、サーバー側 APIMart Key を利用します。
Vercel で必要な環境変数:
@@ -314,8 +314,7 @@ VITE_SUPABASE_URL=
VITE_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
-CIYUAN_API_KEY=
-CIYUAN_BASE_URL=https://ciyuan.today
+APIMART_API_KEY=
APP_URL=https://gpt-image2.canghe.ai
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
@@ -333,6 +332,7 @@ GOOGLE_ANALYTICS_REFRESH_TOKEN=
- [`supabase/migrations/20260512090000_google_account_center.sql`](supabase/migrations/20260512090000_google_account_center.sql) を適用し、アカウント利用サマリーとスーパー管理者向けの強制クレジット課金を追加します。
- [`supabase/migrations/20260512143000_pricing_admin_metrics.sql`](supabase/migrations/20260512143000_pricing_admin_metrics.sql) を適用し、`$5 / 300 credits` のカタログを更新して管理ダッシュボード指標を追加します。
- [`supabase/migrations/20260515090000_case_favorites.sql`](supabase/migrations/20260515090000_case_favorites.sql) を適用し、ユーザーごとのケースお気に入り機能を追加します。
+- [`supabase/migrations/20260828090000_apimart_generation_tasks.sql`](supabase/migrations/20260828090000_apimart_generation_tasks.sql) を適用し、APIMart タスク ID、実際の USD コスト、有効期限付き結果 URL、プロバイダー索引を追加します。
- Supabase Auth の Redirect URLs に `https://gpt-image2.canghe.ai` と、`http://127.0.0.1:5173` などのローカル開発 URL を追加します。
- Supabase Dashboard に Google OAuth 認証情報を追加したうえで Google Provider を有効化します。
- Google ログインのみに制限したい場合は、Supabase Auth settings で Email Provider を無効化します。
diff --git a/README.md b/README.md
index 73da2cd..db65004 100644
--- a/README.md
+++ b/README.md
@@ -308,7 +308,7 @@ The skill source lives at [`agents/skills/gpt-image-2-style-library`](agents/ski
## 🔐 Website Auth & Generation
-The visual site includes login-gated case generation powered by Supabase Auth, Supabase Postgres, and a Vercel Function proxy for the GPT Image 2 API.
+The visual site supports direct APIMart generation with a personal browser-only API key. Without a personal key, signed-in users continue through Supabase Auth, platform credits, and the server-side APIMart key.
Required Vercel environment variables:
@@ -317,8 +317,7 @@ VITE_SUPABASE_URL=
VITE_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
-CIYUAN_API_KEY=
-CIYUAN_BASE_URL=https://ciyuan.today
+APIMART_API_KEY=
APP_URL=https://gpt-image2.canghe.ai
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
@@ -338,6 +337,7 @@ Setup checklist:
- Apply [`supabase/migrations/20260512090000_google_account_center.sql`](supabase/migrations/20260512090000_google_account_center.sql) to add account usage summaries and forced credit charging for super admins.
- Apply [`supabase/migrations/20260512143000_pricing_admin_metrics.sql`](supabase/migrations/20260512143000_pricing_admin_metrics.sql) to update the `$5 / 300 credits` catalog and add admin dashboard metrics.
- Apply [`supabase/migrations/20260515090000_case_favorites.sql`](supabase/migrations/20260515090000_case_favorites.sql) to add per-user case favorites.
+- Apply [`supabase/migrations/20260828090000_apimart_generation_tasks.sql`](supabase/migrations/20260828090000_apimart_generation_tasks.sql) to add APIMart task IDs, actual USD costs, expiring result URLs, and provider indexes.
- Add `https://gpt-image2.canghe.ai` and local dev URLs such as `http://127.0.0.1:5173` to Supabase Auth redirect URLs.
- Enable the Google Provider after adding Google OAuth credentials in the Supabase Dashboard.
- To force Google-only sign-in, disable the Email Provider in Supabase Auth settings.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 3504753..20a01d6 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -22,7 +22,7 @@
## 🌐 可视化网站
-访问 [gpt-image2.canghe.ai](https://gpt-image2.canghe.ai/) 可以用产品化方式浏览案例:查看大图、复制完整 Prompt、按风格或场景筛选、登录后测试生成,并快速跳回 GitHub 源案例。
+访问 [gpt-image2.canghe.ai](https://gpt-image2.canghe.ai/) 可以用产品化方式浏览案例:查看大图、复制完整 Prompt、按风格或场景筛选、配置个人 APIMart Key 或登录后测试生成,并快速跳回 GitHub 源案例。
<p align="center">
<a href="https://gpt-image2.canghe.ai/">
@@ -306,7 +306,7 @@ skill 源码位于 [`agents/skills/gpt-image-2-style-library`](agents/skills/gpt
## 🔐 网站登录与生成测试
-可视化网站已经接入登录后生成测试图能力,底层使用 Supabase Auth、Supabase Postgres,以及 Vercel Function 代理 GPT Image 2 API。
+可视化网站支持使用仅保存在当前浏览器的个人 APIMart Key 直接生成。没有配置个人 Key 时,登录用户继续使用 Supabase Auth、平台积分和服务端 APIMart Key。
Vercel 需要配置这些环境变量:
@@ -315,8 +315,7 @@ VITE_SUPABASE_URL=
VITE_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
-CIYUAN_API_KEY=
-CIYUAN_BASE_URL=https://ciyuan.today
+APIMART_API_KEY=
APP_URL=https://gpt-image2.canghe.ai
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
@@ -336,6 +335,7 @@ GOOGLE_ANALYTICS_REFRESH_TOKEN=
- 将 [`supabase/migrations/20260512090000_google_account_center.sql`](supabase/migrations/20260512090000_google_account_center.sql) 应用到 Supabase 项目,添加账户用量统计和超级管理员强制扣积分逻辑。
- 将 [`supabase/migrations/20260512143000_pricing_admin_metrics.sql`](supabase/migrations/20260512143000_pricing_admin_metrics.sql) 应用到 Supabase 项目,更新 `$5 / 300 credits` 价格体系,并添加管理员数据看板指标。
- 将 [`supabase/migrations/20260515090000_case_favorites.sql`](supabase/migrations/20260515090000_case_favorites.sql) 应用到 Supabase 项目,添加用户案例收藏表。
+- 将 [`supabase/migrations/20260828090000_apimart_generation_tasks.sql`](supabase/migrations/20260828090000_apimart_generation_tasks.sql) 应用到 Supabase 项目,保存 APIMart 任务 ID、实际美元成本、限时结果地址和服务商索引。
- 在 Supabase Auth Redirect URLs 里加入 `https://gpt-image2.canghe.ai`,以及 `http://127.0.0.1:5173` 等本地开发地址。
- 在 Supabase Dashboard 填入 Google OAuth 凭据并启用 Google Provider。
- 如需强制只允许 Google 登录,可以在 Supabase Auth settings 里关闭 Email Provider。
diff --git a/api/_lib/account.js b/api/_lib/account.js
new file mode 100644
index 0000000..f5d6531
--- /dev/null
+++ b/api/_lib/account.js
@@ -0,0 +1,46 @@
+export function formatTransaction(row) {
+ const caseId = Number(row.metadata?.caseId || 0);
+ return {
+ id: row.id,
+ amount: Number(row.amount || 0),
+ type: row.type || '',
+ source: row.source || '',
+ metadata: row.metadata || {},
+ caseId: Number.isFinite(caseId) && caseId > 0 ? caseId : null,
+ createdAt: row.created_at || ''
+ };
+}
+
+export async function getAccountExtras(client, userId) {
+ const [usageResult, transactionsResult] = await Promise.all([
+ client.rpc('get_user_account_usage', { p_user_id: userId }),
+ client
+ .from('credit_transactions')
+ .select('id,amount,type,source,metadata,created_at')
+ .eq('user_id', userId)
+ .eq('type', 'generation')
+ .order('created_at', { ascending: false })
+ .limit(30)
+ ]);
+
+ if (usageResult.error) throw usageResult.error;
+ if (transactionsResult.error) throw transactionsResult.error;
+
+ const usage = Array.isArray(usageResult.data) ? usageResult.data[0] : usageResult.data;
+ return {
+ usage: {
+ totalGenerations: Number(usage?.total_generations || 0),
+ totalGenerationCredits: Number(usage?.total_generation_credits || 0)
+ },
+ recentTransactions: (transactionsResult.data || []).map(formatTransaction)
+ };
+}
+
+export async function profileWithAccountExtras(client, profile) {
+ if (!profile?.id) return profile;
+ const extras = await getAccountExtras(client, profile.id);
+ return {
+ ...profile,
+ ...extras
+ };
+}
diff --git a/api/_lib/apimart.js b/api/_lib/apimart.js
new file mode 100644
index 0000000..fc538e2
--- /dev/null
+++ b/api/_lib/apimart.js
@@ -0,0 +1,108 @@
+import {
+ APIMART_API_BASE_URL,
+ APIMART_DEFAULT_PRICE_USD,
+ APIMART_PRICE_SNAPSHOT_DATE,
+ apimartErrorCode,
+ buildApimartGenerationPayload,
+ extractApimartTaskId,
+ isValidApimartTaskId,
+ normalizeApimartTask,
+ parseApimartPricing,
+ retryAfterMilliseconds
+} from '../../shared/apimart.js';
+
+export function getApimartConfig() {
+ const apiKey = String(process.env.APIMART_API_KEY || '').trim();
+ return { baseUrl: APIMART_API_BASE_URL, apiKey, configured: Boolean(apiKey) };
+}
+
+function upstreamError(response, payload) {
+ const code = apimartErrorCode(response.status, payload);
+ const error = new Error(code);
+ error.code = code;
+ error.status = response.status;
+ error.retryAfterMs = retryAfterMilliseconds(response.headers?.get?.('retry-after'));
+ error.upstreamMessage = String(payload?.error?.message || '').slice(0, 240);
+ return error;
+}
+
+async function jsonResponse(response) {
+ return response.json().catch(() => ({}));
+}
+
+export async function submitApimartGeneration({
+ apiKey,
+ prompt,
+ language = 'en',
+ webhook = '',
+ fetchImpl = fetch
+}) {
+ const { baseUrl } = getApimartConfig();
+ const response = await fetchImpl(`${baseUrl}/v1/images/generations`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json'
+ },
+ body: JSON.stringify(buildApimartGenerationPayload(prompt, { language, webhook })),
+ cache: 'no-store'
+ });
+ const payload = await jsonResponse(response);
+ if (!response.ok) throw upstreamError(response, payload);
+ const taskId = extractApimartTaskId(payload);
+ if (!isValidApimartTaskId(taskId)) {
+ const error = new Error('APIMART_INVALID_RESPONSE');
+ error.code = error.message;
+ throw error;
+ }
+ return { taskId, status: 'submitted' };
+}
+
+export async function getApimartTask({ apiKey, taskId, language = 'en', fetchImpl = fetch }) {
+ if (!isValidApimartTaskId(taskId)) {
+ const error = new Error('APIMART_INVALID_TASK');
+ error.code = error.message;
+ error.status = 400;
+ throw error;
+ }
+ const { baseUrl } = getApimartConfig();
+ const query = new URLSearchParams({ language: language === 'zh' ? 'zh' : 'en' });
+ const response = await fetchImpl(`${baseUrl}/v1/tasks/${encodeURIComponent(taskId)}?${query}`, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ Accept: 'application/json'
+ },
+ cache: 'no-store'
+ });
+ const payload = await jsonResponse(response);
+ if (!response.ok) throw upstreamError(response, payload);
+ return normalizeApimartTask(payload);
+}
+
+export async function getApimartPricing(fetchImpl = fetch) {
+ const { baseUrl } = getApimartConfig();
+ const response = await fetchImpl(`${baseUrl}/api/pricing/model?model=gpt-image-2`, {
+ method: 'GET',
+ headers: { Accept: 'application/json' },
+ cache: 'no-store'
+ });
+ const payload = await jsonResponse(response);
+ if (!response.ok) throw upstreamError(response, payload);
+ return {
+ ...parseApimartPricing(payload),
+ stale: false,
+ fetchedAt: new Date().toISOString()
+ };
+}
+
+export function fallbackApimartPricing() {
+ return {
+ model: 'gpt-image-2',
+ currency: 'USD',
+ prices: { '1k': APIMART_DEFAULT_PRICE_USD, '2k': 0.0175, '4k': 0.02625 },
+ stale: true,
+ snapshotDate: APIMART_PRICE_SNAPSHOT_DATE
+ };
+}
diff --git a/api/_lib/apimart.test.js b/api/_lib/apimart.test.js
new file mode 100644
index 0000000..ca03812
--- /dev/null
+++ b/api/_lib/apimart.test.js
@@ -0,0 +1,123 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ fallbackApimartPricing,
+ getApimartTask,
+ submitApimartGeneration
+} from './apimart.js';
+import { publicErrorCode, publicErrorStatus, reserveGeneration } from '../generate-image.js';
+import { publicStatusErrorCode } from '../generation/status.js';
+
+function jsonResponse(status, payload, headers = {}) {
+ return new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'content-type': 'application/json', ...headers }
+ });
+}
+
+test('platform submission sends the fixed schema and callback base', async () => {
+ const calls = [];
+ const result = await submitApimartGeneration({
+ apiKey: 'platform-key',
+ prompt: 'draw a fox',
+ language: 'en',
+ webhook: 'https://gpt-image2.canghe.ai/api/generation',
+ fetchImpl: async (url, options) => {
+ calls.push({ url, options, body: JSON.parse(options.body) });
+ return jsonResponse(200, { data: { task_id: 'task_abcdefgh' } });
+ }
+ });
+ assert.equal(result.taskId, 'task_abcdefgh');
+ assert.equal(calls[0].options.headers.Authorization, 'Bearer platform-key');
+ assert.deepEqual(calls[0].body, {
+ model: 'gpt-image-2',
+ prompt: 'draw a fox',
+ n: 1,
+ size: '1:1',
+ resolution: '1k',
+ webhook: 'https://gpt-image2.canghe.ai/api/generation',
+ language: 'en'
+ });
+});
+
+test('platform status parsing carries result URL, expiry and actual cost', async () => {
+ const task = await getApimartTask({
+ apiKey: 'platform-key',
+ taskId: 'task_abcdefgh',
+ fetchImpl: async () => jsonResponse(200, {
+ data: {
+ id: 'task_abcdefgh',
+ status: 'completed',
+ progress: 100,
+ cost: 0.010625,
+ result: { images: [{ url: 'https://cdn.example/result.png', expires_at: 1787961600 }] }
+ }
+ })
+ });
+ assert.equal(task.image, 'https://cdn.example/result.png');
+ assert.equal(task.expiresAt, 1787961600);
+ assert.equal(task.cost, 0.010625);
+});
+
+test('upstream 401, 402, 429 and 5xx remain distinguishable', async () => {
+ for (const [status, code] of [
+ [401, 'APIMART_API_KEY_INVALID'],
+ [402, 'APIMART_BALANCE_REQUIRED'],
+ [429, 'APIMART_RATE_LIMITED'],
+ [503, 'APIMART_UNAVAILABLE']
+ ]) {
+ await assert.rejects(
+ submitApimartGeneration({
+ apiKey: 'platform-key',
+ prompt: 'draw a fox',
+ fetchImpl: async () => jsonResponse(status, { error: { message: 'upstream error' } }, { 'retry-after': '4' })
+ }),
+ { code }
+ );
+ }
+ assert.equal(publicErrorCode({ code: 'APIMART_API_KEY_INVALID' }), 'SERVER_NOT_CONFIGURED');
+ assert.equal(publicErrorCode({ code: 'APIMART_BALANCE_REQUIRED' }), 'SERVER_NOT_CONFIGURED');
+ assert.equal(publicErrorCode({ code: 'APIMART_RATE_LIMITED' }), 'UPSTREAM_BUSY');
+ assert.equal(publicErrorCode({ code: 'APIMART_UNAVAILABLE' }), 'GENERATION_FAILED');
+ assert.equal(publicErrorStatus('SERVER_NOT_CONFIGURED'), 500);
+ assert.equal(publicErrorStatus('UPSTREAM_BUSY'), 503);
+ assert.equal(publicStatusErrorCode({ code: 'APIMART_API_KEY_INVALID' }), 'SERVER_NOT_CONFIGURED');
+});
+
+test('pricing fallback is date-labelled and keeps the confirmed 1K snapshot', () => {
+ const fallback = fallbackApimartPricing();
+ assert.equal(fallback.prices['1k'], 0.010625);
+ assert.equal(fallback.stale, true);
+ assert.match(fallback.snapshotDate, /^\d{4}-\d{2}-\d{2}$/);
+});
+
+test('platform generation reserves the existing free or credit usage before submission', async () => {
+ const calls = [];
+ const client = {
+ async rpc(name, payload) {
+ calls.push({ name, payload });
+ return { data: [{ reservation_id: 'reservation-1' }], error: null };
+ }
+ };
+ assert.deepEqual(await reserveGeneration(client, { isSuperAdmin: true }, 'user-1', 42, 'draw a fox'), {
+ reservationId: 'reservation-1'
+ });
+ assert.deepEqual(calls[0], {
+ name: 'reserve_generation_usage',
+ payload: {
+ p_user_id: 'user-1',
+ p_case_id: 42,
+ p_prompt: 'draw a fox',
+ p_force_credit: true
+ }
+ });
+
+ await assert.rejects(
+ reserveGeneration({
+ async rpc() {
+ return { data: null, error: { message: 'CREDITS_REQUIRED' } };
+ }
+ }, {}, 'user-1', 42, 'draw a fox'),
+ { code: 'CREDITS_REQUIRED' }
+ );
+});
diff --git a/api/_lib/generation.js b/api/_lib/generation.js
new file mode 100644
index 0000000..faa54e6
--- /dev/null
+++ b/api/_lib/generation.js
@@ -0,0 +1,85 @@
+import { profileWithAccountExtras } from './account.js';
+import { getProfileById } from './supabase.js';
+
+export async function getGenerationResponseUser(client, userId) {
+ const profile = await getProfileById(userId).catch(() => null);
+ if (!profile) return null;
+ try {
+ return await profileWithAccountExtras(client, profile);
+ } catch (error) {
+ console.warn('Failed to refresh generation response profile', {
+ userId,
+ message: String(error?.message || 'unknown').slice(0, 240)
+ });
+ return null;
+ }
+}
+
+export function providerFieldsForTask(task) {
+ const expiresAt = task?.expiresAt
+ ? new Date(Number(task.expiresAt) * 1000).toISOString()
+ : null;
+ return {
+ provider_cost_usd: Number.isFinite(Number(task?.cost)) ? Number(task.cost) : null,
+ provider_result_url: task?.image || null,
+ provider_result_expires_at: expiresAt
+ };
+}
+
+export function formatStoredGeneration(reservation) {
+ if (!reservation) return null;
+ const succeeded = reservation.status === 'succeeded';
+ const failed = reservation.status === 'failed';
+ if (!succeeded && !failed) return null;
+ return {
+ taskId: reservation.provider_task_id,
+ status: succeeded ? 'completed' : 'failed',
+ progress: 100,
+ image: reservation.provider_result_url || '',
+ expiresAt: reservation.provider_result_expires_at
+ ? Math.floor(new Date(reservation.provider_result_expires_at).getTime() / 1000)
+ : null,
+ cost: reservation.provider_cost_usd == null ? null : Number(reservation.provider_cost_usd),
+ errorMessage: failed ? reservation.error_code || 'GENERATION_FAILED' : '',
+ errorCode: failed ? reservation.error_code || 'GENERATION_FAILED' : ''
+ };
+}
+
+export async function findPlatformGeneration(client, taskId, userId = '') {
+ let query = client
+ .from('generation_reservations')
+ .select('id,user_id,status,error_code,provider,provider_task_id,provider_cost_usd,provider_result_url,provider_result_expires_at')
+ .eq('provider', 'apimart')
+ .eq('provider_task_id', taskId);
+ if (userId) query = query.eq('user_id', userId);
+ const { data, error } = await query.maybeSingle();
+ if (error) throw error;
+ return data || null;
+}
+
+export async function settlePlatformGeneration(client, reservation, task) {
+ if (!reservation || !['completed', 'failed'].includes(task?.status)) return false;
+ if (reservation.status !== 'pending') return false;
+
+ const { error: updateError } = await client
+ .from('generation_reservations')
+ .update(providerFieldsForTask(task))
+ .eq('id', reservation.id)
+ .eq('status', 'pending');
+ if (updateError) throw updateError;
+
+ if (task.status === 'completed' && task.image) {
+ const { error } = await client.rpc('complete_generation_reservation', {
+ p_reservation_id: reservation.id
+ });
+ if (error) throw error;
+ return true;
+ }
+
+ const { error } = await client.rpc('release_generation_reservation', {
+ p_reservation_id: reservation.id,
+ p_error_code: task.errorCode || 'GENERATION_FAILED'
+ });
+ if (error) throw error;
+ return true;
+}
diff --git a/api/_lib/generation.test.js b/api/_lib/generation.test.js
new file mode 100644
index 0000000..1a97888
--- /dev/null
+++ b/api/_lib/generation.test.js
@@ -0,0 +1,169 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+import {
+ findPlatformGeneration,
+ formatStoredGeneration,
+ providerFieldsForTask,
+ settlePlatformGeneration
+} from './generation.js';
+import { reconcileApimartCallback } from '../generation/callback.js';
+
+const migration = readFileSync(fileURLToPath(new URL(
+ '../../supabase/migrations/20260828090000_apimart_generation_tasks.sql',
+ import.meta.url
+)), 'utf8');
+const callbackSource = readFileSync(fileURLToPath(new URL('../generation/callback.js', import.meta.url)), 'utf8');
+const statusSource = readFileSync(fileURLToPath(new URL('../generation/status.js', import.meta.url)), 'utf8');
+
+function settlementClient() {
+ const calls = [];
+ const client = {
+ calls,
+ from(table) {
+ assert.equal(table, 'generation_reservations');
+ return {
+ update(fields) {
+ calls.push({ type: 'update', fields, filters: [] });
+ const call = calls.at(-1);
+ const chain = {
+ eq(key, value) {
+ call.filters.push([key, value]);
+ return chain;
+ },
+ then(resolve) {
+ resolve({ error: null });
+ }
+ };
+ return chain;
+ }
+ };
+ },
+ async rpc(name, payload) {
+ calls.push({ type: 'rpc', name, payload });
+ return { error: null };
+ }
+ };
+ return client;
+}
+
+test('provider settlement stores actual billing and expiring result fields', () => {
+ assert.deepEqual(providerFieldsForTask({
+ image: 'https://cdn.example/result.png',
+ expiresAt: 1787961600,
+ cost: 0.010625
+ }), {
+ provider_cost_usd: 0.010625,
+ provider_result_url: 'https://cdn.example/result.png',
+ provider_result_expires_at: '2026-08-29T00:00:00.000Z'
+ });
+});
+
+test('success settles once and an already-settled duplicate is ignored', async () => {
+ const client = settlementClient();
+ const reservation = { id: 'reservation-1', status: 'pending' };
+ assert.equal(await settlePlatformGeneration(client, reservation, {
+ status: 'completed',
+ image: 'https://cdn.example/result.png',
+ expiresAt: 1787961600,
+ cost: 0.010625
+ }), true);
+ assert.equal(client.calls.filter((call) => call.type === 'rpc').length, 1);
+ assert.equal(client.calls.at(-1).name, 'complete_generation_reservation');
+ assert.equal(await settlePlatformGeneration(client, { ...reservation, status: 'succeeded' }, {
+ status: 'completed',
+ image: 'https://cdn.example/result.png'
+ }), false);
+ assert.equal(client.calls.filter((call) => call.type === 'rpc').length, 1);
+});
+
+test('failure releases a reservation once through the idempotent refund RPC', async () => {
+ const client = settlementClient();
+ await settlePlatformGeneration(client, { id: 'reservation-2', status: 'pending' }, {
+ status: 'failed',
+ errorCode: 'CONTENT_REJECTED'
+ });
+ const rpc = client.calls.find((call) => call.type === 'rpc');
+ assert.equal(rpc.name, 'release_generation_reservation');
+ assert.deepEqual(rpc.payload, {
+ p_reservation_id: 'reservation-2',
+ p_error_code: 'CONTENT_REJECTED'
+ });
+});
+
+test('task lookup always applies authenticated ownership when supplied', async () => {
+ const filters = [];
+ const query = {
+ select() { return query; },
+ eq(key, value) { filters.push([key, value]); return query; },
+ async maybeSingle() { return { data: null, error: null }; }
+ };
+ await findPlatformGeneration({ from: () => query }, 'task_abcdefgh', 'user-1');
+ assert.deepEqual(filters, [
+ ['provider', 'apimart'],
+ ['provider_task_id', 'task_abcdefgh'],
+ ['user_id', 'user-1']
+ ]);
+});
+
+test('stored terminal rows return the unified browser task shape', () => {
+ assert.deepEqual(formatStoredGeneration({
+ status: 'succeeded',
+ provider_task_id: 'task_abcdefgh',
+ provider_cost_usd: '0.010625',
+ provider_result_url: 'https://cdn.example/result.png',
+ provider_result_expires_at: '2026-08-29T00:00:00.000Z'
+ }), {
+ taskId: 'task_abcdefgh',
+ status: 'completed',
+ progress: 100,
+ image: 'https://cdn.example/result.png',
+ expiresAt: 1787961600,
+ cost: 0.010625,
+ errorMessage: '',
+ errorCode: ''
+ });
+});
+
+test('callback payload only wakes a provider-verified reconciliation', async () => {
+ const calls = [];
+ const result = await reconcileApimartCallback({
+ client: { name: 'client' },
+ apiKey: 'platform-key',
+ taskId: 'task_abcdefgh',
+ findReservation: async (_client, taskId) => ({ id: 'reservation-1', status: 'pending', provider_task_id: taskId }),
+ fetchTask: async ({ apiKey, taskId }) => {
+ calls.push({ type: 'verify', apiKey, taskId });
+ return { status: 'completed', image: 'https://cdn.example/verified.png', cost: 0.010625 };
+ },
+ settle: async (_client, reservation, task) => calls.push({ type: 'settle', reservation, task })
+ });
+ assert.equal(result.state, 'settled');
+ assert.equal(calls[0].type, 'verify');
+ assert.equal(calls[1].task.image, 'https://cdn.example/verified.png');
+
+ let verified = false;
+ const duplicate = await reconcileApimartCallback({
+ client: {},
+ apiKey: 'platform-key',
+ taskId: 'task_abcdefgh',
+ findReservation: async () => ({ id: 'reservation-1', status: 'succeeded' }),
+ fetchTask: async () => {
+ verified = true;
+ return { status: 'completed' };
+ }
+ });
+ assert.equal(duplicate.state, 'duplicate');
+ assert.equal(verified, false);
+});
+
+test('migration, callback verification and status ownership contracts remain present', () => {
+ assert.match(migration, /provider_task_id text/i);
+ assert.match(migration, /provider_cost_usd numeric\(12, 6\)/i);
+ assert.match(migration, /provider_result_url text/i);
+ assert.match(migration, /provider_result_expires_at timestamptz/i);
+ assert.match(migration, /create unique index[\s\S]*\(provider, provider_task_id\)/i);
+ assert.match(callbackSource, /reconcileApimartCallback\([\s\S]*apiKey: config\.apiKey/i);
+ assert.match(statusSource, /findPlatformGeneration\(auth\.client, taskId, auth\.user\.id\)/i);
+});
diff --git a/api/apimart/pricing.js b/api/apimart/pricing.js
new file mode 100644
index 0000000..ff0e3c2
--- /dev/null
+++ b/api/apimart/pricing.js
@@ -0,0 +1,22 @@
+import { fallbackApimartPricing, getApimartPricing } from '../_lib/apimart.js';
+
+function json(res, status, payload) {
+ res.status(status).json(payload);
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ res.setHeader('Cache-Control', 'public, s-maxage=3600, stale-while-revalidate=86400');
+ try {
+ return json(res, 200, { ok: true, ...(await getApimartPricing()) });
+ } catch (error) {
+ console.warn('Failed to refresh APIMart pricing', {
+ code: error?.code || null,
+ message: String(error?.message || 'unknown').slice(0, 160)
+ });
+ return json(res, 200, { ok: true, ...fallbackApimartPricing() });
+ }
+}
diff --git a/api/generate-image.js b/api/generate-image.js
index 8a01b2a..953be81 100644
--- a/api/generate-image.js
+++ b/api/generate-image.js
@@ -1,114 +1,53 @@
-import {
- getAuthContext,
- getProfileById,
- isSupabaseServerConfigured
-} from './_lib/supabase.js';
-
-const MAX_PROMPT_LENGTH = 6000;
-const DEFAULT_CIYUAN_BASE_URL = 'https://ciyuan.today';
+import { getAuthContext, isSupabaseServerConfigured } from './_lib/supabase.js';
+import { getApimartConfig, submitApimartGeneration } from './_lib/apimart.js';
+import { getGenerationResponseUser } from './_lib/generation.js';
+import { APIMART_MAX_PROMPT_LENGTH } from '../shared/apimart.js';
function json(res, status, payload) {
+ res.setHeader('Cache-Control', 'no-store');
res.status(status).json(payload);
}
function isServerConfigured() {
- return Boolean(process.env.CIYUAN_API_KEY && isSupabaseServerConfigured());
+ return getApimartConfig().configured && isSupabaseServerConfigured();
}
async function readBody(req) {
if (Buffer.isBuffer(req.body)) return JSON.parse(req.body.toString('utf8') || '{}');
if (req.body && typeof req.body === 'object') return req.body;
if (typeof req.body === 'string') return JSON.parse(req.body || '{}');
-
const chunks = [];
- for await (const chunk of req) {
- chunks.push(chunk);
- }
+ for await (const chunk of req) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf8');
return raw ? JSON.parse(raw) : {};
}
function normalizeReservation(data) {
const row = Array.isArray(data) ? data[0] : data;
- if (!row?.reservation_id) return null;
- return {
- reservationId: row.reservation_id,
- usedFreeGeneration: Boolean(row.used_free_generation),
- creditAmount: Number(row.credit_amount || 0),
- freeGenerationsUsed: Number(row.free_generations_used || 0),
- creditBalance: Number(row.credit_balance || 0)
- };
-}
-
-function profileFromReservation(profile, reservation) {
- if (!profile || !reservation) return profile;
- const usage = profile.usage || {};
- return {
- ...profile,
- creditBalance: reservation.creditBalance,
- freeGenerationsUsed: reservation.freeGenerationsUsed,
- freeUsed: reservation.freeGenerationsUsed >= 1,
- usage: {
- ...usage,
- totalGenerations: Number(usage.totalGenerations || 0) + 1,
- totalGenerationCredits: Number(usage.totalGenerationCredits || 0) + Number(reservation.creditAmount || 0)
- }
- };
-}
-
-async function reserveGeneration(client, userId, caseId, prompt) {
- const { data, error } = await client.rpc('reserve_generation_usage', {
- p_user_id: userId,
- p_case_id: caseId,
- p_prompt: prompt,
- p_force_credit: false
- });
-
- if (error) {
- const normalizedMessage = String(error.message || error.details || '').toUpperCase();
- if (normalizedMessage.includes('CREDITS_REQUIRED')) {
- const limitError = new Error('CREDITS_REQUIRED');
- limitError.code = 'CREDITS_REQUIRED';
- throw limitError;
- }
- throw error;
- }
-
- const reservation = normalizeReservation(data);
- if (!reservation) throw new Error('RESERVATION_FAILED');
- return reservation;
+ return row?.reservation_id ? { reservationId: row.reservation_id } : null;
}
-async function reserveCreditGeneration(client, userId, caseId, prompt) {
+export async function reserveGeneration(client, profile, userId, caseId, prompt) {
const { data, error } = await client.rpc('reserve_generation_usage', {
p_user_id: userId,
p_case_id: caseId,
p_prompt: prompt,
- p_force_credit: true
+ p_force_credit: Boolean(profile?.isSuperAdmin)
});
-
if (error) {
- const normalizedMessage = String(error.message || error.details || '').toUpperCase();
- if (normalizedMessage.includes('CREDITS_REQUIRED')) {
+ const message = String(error.message || error.details || '').toUpperCase();
+ if (message.includes('CREDITS_REQUIRED')) {
const limitError = new Error('CREDITS_REQUIRED');
limitError.code = 'CREDITS_REQUIRED';
throw limitError;
}
throw error;
}
-
const reservation = normalizeReservation(data);
if (!reservation) throw new Error('RESERVATION_FAILED');
return reservation;
}
-async function completeReservation(client, reservationId) {
- const { error } = await client.rpc('complete_generation_reservation', {
- p_reservation_id: reservationId
- });
- if (error) throw error;
-}
-
async function releaseReservation(client, reservationId, errorCode) {
if (!reservationId) return;
const { error } = await client.rpc('release_generation_reservation', {
@@ -123,37 +62,19 @@ async function releaseReservation(client, reservationId, errorCode) {
}
}
-async function generateImage(prompt) {
- const baseUrl = (process.env.CIYUAN_BASE_URL || DEFAULT_CIYUAN_BASE_URL).replace(/\/$/, '');
- const response = await fetch(`${baseUrl}/v1/images/generations`, {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${process.env.CIYUAN_API_KEY}`,
- 'Content-Type': 'application/json',
- Accept: 'application/json'
- },
- body: JSON.stringify({
- model: 'gpt-image-2',
- prompt,
- n: 1,
- size: '1024x1024',
- quality: 'low',
- format: 'jpeg'
- })
- });
- const payload = await response.json().catch(() => ({}));
- const b64 = payload?.data?.[0]?.b64_json;
-
- if (!response.ok || !b64) {
- const message = payload?.error?.message || payload?.message || `Image generation failed with status ${response.status}`;
- const error = new Error(message);
- error.status = response.status;
- error.code = payload?.error?.code || payload?.code;
- error.type = payload?.error?.type || payload?.type;
- throw error;
+export function publicErrorCode(error) {
+ if (error?.code === 'APIMART_RATE_LIMITED') return 'UPSTREAM_BUSY';
+ if (error?.code === 'APIMART_API_KEY_INVALID' || error?.code === 'APIMART_BALANCE_REQUIRED') {
+ return 'SERVER_NOT_CONFIGURED';
}
+ if (error?.code === 'APIMART_REQUEST_REJECTED') return 'APIMART_REQUEST_REJECTED';
+ return 'GENERATION_FAILED';
+}
- return `data:image/jpeg;base64,${b64}`;
+export function publicErrorStatus(errorCode) {
+ if (errorCode === 'UPSTREAM_BUSY') return 503;
+ if (errorCode === 'SERVER_NOT_CONFIGURED') return 500;
+ return 502;
}
export default async function handler(req, res) {
@@ -161,7 +82,6 @@ export default async function handler(req, res) {
res.setHeader('Allow', 'GET, POST');
return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
}
-
if (!isServerConfigured()) {
return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
}
@@ -174,7 +94,6 @@ export default async function handler(req, res) {
loginRequired: auth.error === 'AUTH_REQUIRED'
});
}
-
if (req.method === 'GET') {
return json(res, 200, {
ok: true,
@@ -183,7 +102,6 @@ export default async function handler(req, res) {
user: auth.profile || null
});
}
-
if (!auth.user || !auth.profile) {
return json(res, 401, { ok: false, error: 'AUTH_REQUIRED', loginRequired: true });
}
@@ -194,18 +112,21 @@ export default async function handler(req, res) {
} catch {
return json(res, 400, { ok: false, error: 'INVALID_PROMPT' });
}
-
const prompt = String(body.prompt || '').trim();
const caseId = Number(body.caseId);
- if (!prompt || prompt.length > MAX_PROMPT_LENGTH || !Number.isFinite(caseId)) {
+ if (!prompt || prompt.length > APIMART_MAX_PROMPT_LENGTH || !Number.isFinite(caseId)) {
return json(res, 400, { ok: false, error: 'INVALID_PROMPT' });
}
let reservation;
try {
- reservation = auth.profile.isSuperAdmin
- ? await reserveCreditGeneration(auth.client, auth.user.id, caseId, prompt)
- : await reserveGeneration(auth.client, auth.user.id, caseId, prompt);
+ reservation = await reserveGeneration(
+ auth.client,
+ auth.profile,
+ auth.user.id,
+ caseId,
+ prompt
+ );
} catch (error) {
if (error?.code === 'CREDITS_REQUIRED') {
return json(res, 402, { ok: false, error: 'CREDITS_REQUIRED' });
@@ -218,28 +139,39 @@ export default async function handler(req, res) {
}
try {
- const image = await generateImage(prompt);
- await completeReservation(auth.client, reservation.reservationId);
- return json(res, 200, {
+ const config = getApimartConfig();
+ const appUrl = String(process.env.APP_URL || '').replace(/\/$/, '');
+ const submitted = await submitApimartGeneration({
+ apiKey: config.apiKey,
+ prompt,
+ language: body.language,
+ webhook: appUrl ? `${appUrl}/api/generation` : ''
+ });
+ const { error: updateError } = await auth.client
+ .from('generation_reservations')
+ .update({ provider: 'apimart', provider_task_id: submitted.taskId })
+ .eq('id', reservation.reservationId)
+ .eq('user_id', auth.user.id);
+ if (updateError) throw updateError;
+
+ return json(res, 202, {
ok: true,
- image,
- user: profileFromReservation(auth.profile, reservation)
+ taskId: submitted.taskId,
+ status: submitted.status,
+ user: await getGenerationResponseUser(auth.client, auth.user.id)
});
} catch (error) {
- console.warn('Image generation failed', {
+ const errorCode = publicErrorCode(error);
+ await releaseReservation(auth.client, reservation.reservationId, errorCode);
+ console.warn('APIMart generation submission failed', {
status: error?.status || null,
code: error?.code || null,
- type: error?.type || null,
- message: String(error?.message || 'unknown').slice(0, 240)
+ message: String(error?.upstreamMessage || error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, publicErrorStatus(errorCode), {
+ ok: false,
+ error: errorCode,
+ user: await getGenerationResponseUser(auth.client, auth.user.id)
});
-
- const errorCode = error?.status === 429 ? 'UPSTREAM_BUSY' : 'GENERATION_FAILED';
- await releaseReservation(auth.client, reservation.reservationId, errorCode);
-
- const refreshedProfile = await getProfileById(auth.user.id).catch(() => null);
- if (error?.status === 429) {
- return json(res, 503, { ok: false, error: 'UPSTREAM_BUSY', user: refreshedProfile });
- }
- return json(res, 502, { ok: false, error: 'GENERATION_FAILED', user: refreshedProfile });
}
}
diff --git a/api/generation/callback.js b/api/generation/callback.js
new file mode 100644
index 0000000..038ecfa
--- /dev/null
+++ b/api/generation/callback.js
@@ -0,0 +1,78 @@
+import { getApimartConfig, getApimartTask } from '../_lib/apimart.js';
+import { findPlatformGeneration, settlePlatformGeneration } from '../_lib/generation.js';
+import { getSupabaseAdminClient } from '../_lib/supabase.js';
+import { extractApimartTaskId, isValidApimartTaskId } from '../../shared/apimart.js';
+
+function json(res, status, payload) {
+ res.setHeader('Cache-Control', 'no-store');
+ res.status(status).json(payload);
+}
+
+async function readBody(req) {
+ if (Buffer.isBuffer(req.body)) return JSON.parse(req.body.toString('utf8') || '{}');
+ if (req.body && typeof req.body === 'object') return req.body;
+ if (typeof req.body === 'string') return JSON.parse(req.body || '{}');
+ const chunks = [];
+ for await (const chunk of req) chunks.push(chunk);
+ const raw = Buffer.concat(chunks).toString('utf8');
+ return raw ? JSON.parse(raw) : {};
+}
+
+export async function reconcileApimartCallback({
+ client,
+ apiKey,
+ taskId,
+ findReservation = findPlatformGeneration,
+ fetchTask = getApimartTask,
+ settle = settlePlatformGeneration
+}) {
+ const reservation = await findReservation(client, taskId);
+ if (!reservation) return { state: 'ignored' };
+ if (reservation.status !== 'pending') return { state: 'duplicate' };
+
+ const verifiedTask = await fetchTask({ apiKey, taskId });
+ if (!['completed', 'failed'].includes(verifiedTask.status)) {
+ return { state: 'pending' };
+ }
+ await settle(client, reservation, verifiedTask);
+ return { state: 'settled' };
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ let payload;
+ try {
+ payload = await readBody(req);
+ } catch {
+ return json(res, 400, { ok: false, error: 'INVALID_CALLBACK' });
+ }
+ const taskId = extractApimartTaskId(payload);
+ if (!isValidApimartTaskId(taskId)) {
+ return json(res, 400, { ok: false, error: 'INVALID_CALLBACK' });
+ }
+
+ const client = getSupabaseAdminClient();
+ const config = getApimartConfig();
+ if (!client || !config.configured) {
+ return json(res, 503, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ }
+
+ try {
+ // The callback wakes the reconciler; APIMart remains the source of truth.
+ const result = await reconcileApimartCallback({ client, apiKey: config.apiKey, taskId });
+ if (result.state === 'ignored') return json(res, 202, { ok: true, ignored: true });
+ if (result.state === 'duplicate') return json(res, 200, { ok: true, duplicate: true });
+ if (result.state === 'pending') return json(res, 202, { ok: true, pending: true });
+ return json(res, 200, { ok: true });
+ } catch (error) {
+ console.warn('Failed to reconcile APIMart callback', {
+ taskId,
+ code: error?.code || null,
+ message: String(error?.upstreamMessage || error?.message || 'unknown').slice(0, 240)
+ });
+ return json(res, 503, { ok: false, error: 'CALLBACK_RECONCILIATION_FAILED' });
+ }
+}
diff --git a/api/generation/status.js b/api/generation/status.js
new file mode 100644
index 0000000..6ff8dd0
--- /dev/null
+++ b/api/generation/status.js
@@ -0,0 +1,88 @@
+import { getApimartConfig, getApimartTask } from '../_lib/apimart.js';
+import {
+ findPlatformGeneration,
+ formatStoredGeneration,
+ getGenerationResponseUser,
+ settlePlatformGeneration
+} from '../_lib/generation.js';
+import { getAuthContext } from '../_lib/supabase.js';
+import { isValidApimartTaskId } from '../../shared/apimart.js';
+
+function json(res, status, payload) {
+ res.setHeader('Cache-Control', 'no-store');
+ res.status(status).json(payload);
+}
+
+function statusForError(error) {
+ if (error?.code === 'APIMART_RATE_LIMITED') return 429;
+ if (error?.code === 'APIMART_INVALID_TASK') return 400;
+ if (error?.code === 'APIMART_API_KEY_INVALID' || error?.code === 'APIMART_BALANCE_REQUIRED') return 500;
+ return 502;
+}
+
+export function publicStatusErrorCode(error) {
+ if (error?.code === 'APIMART_API_KEY_INVALID' || error?.code === 'APIMART_BALANCE_REQUIRED') {
+ return 'SERVER_NOT_CONFIGURED';
+ }
+ return error?.code || 'GENERATION_FAILED';
+}
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET');
+ return json(res, 405, { ok: false, error: 'METHOD_NOT_ALLOWED' });
+ }
+ const auth = await getAuthContext(req);
+ if (auth.error) {
+ return json(res, auth.status || 401, { ok: false, error: auth.error, loginRequired: true });
+ }
+ const taskId = String(req.query?.taskId || '').trim();
+ if (!isValidApimartTaskId(taskId)) {
+ return json(res, 400, { ok: false, error: 'APIMART_INVALID_TASK' });
+ }
+
+ try {
+ const reservation = await findPlatformGeneration(auth.client, taskId, auth.user.id);
+ if (!reservation) return json(res, 404, { ok: false, error: 'GENERATION_NOT_FOUND' });
+ const stored = formatStoredGeneration(reservation);
+ if (stored) {
+ return json(res, 200, {
+ ok: true,
+ ...stored,
+ user: await getGenerationResponseUser(auth.client, auth.user.id)
+ });
+ }
+
+ const config = getApimartConfig();
+ if (!config.configured) return json(res, 500, { ok: false, error: 'SERVER_NOT_CONFIGURED' });
+ const task = await getApimartTask({
+ apiKey: config.apiKey,
+ taskId,
+ language: req.query?.language
+ });
+ if (['completed', 'failed'].includes(task.status)) {
+ await settlePlatformGeneration(auth.client, reservation, task);
+ }
+ return json(res, 200, {
+ ok: true,
+ ...task,
+ user: ['completed', 'failed'].includes(task.status)
+ ? await getGenerationResponseUser(auth.client, auth.user.id)
+ : null
+ });
+ } catch (error) {
+ console.warn('Failed to query APIMart generation task', {
+ taskId,
+ code: error?.code || null,
+ message: String(error?.upstreamMessage || error?.message || 'unknown').slice(0, 240)
+ });
+ if (error?.retryAfterMs) {
+ res.setHeader('Retry-After', String(Math.max(1, Math.ceil(error.retryAfterMs / 1000))));
+ }
+ return json(res, statusForError(error), {
+ ok: false,
+ error: publicStatusErrorCode(error),
+ retryAfterMs: error?.retryAfterMs || undefined
+ });
+ }
+}
diff --git a/package.json b/package.json
index 71ffc5b..422e3a0 100644
--- a/package.json
+++ b/package.json
@@ -16,7 +16,8 @@
"prebuild": "npm run generate:site-data && npm run generate:style-skill",
"build": "vite build",
"preview": "vite preview",
- "test": "node --test api/_lib/*.test.js"
+ "test": "node --test api/_lib/*.test.js",
+ "test:apimart": "node --test shared/apimart.test.js src/apimartClient.test.js api/_lib/apimart.test.js api/_lib/generation.test.js"
},
"dependencies": {
"@google-analytics/data": "^5.2.2",
diff --git a/shared/apimart.js b/shared/apimart.js
new file mode 100644
index 0000000..6ca5d79
--- /dev/null
+++ b/shared/apimart.js
@@ -0,0 +1,122 @@
+export const APIMART_MODEL = 'gpt-image-2';
+export const APIMART_API_BASE_URL = 'https://api.apimart.ai';
+export const APIMART_DEFAULT_PRICE_USD = 0.010625;
+export const APIMART_PRICE_SNAPSHOT_DATE = '2026-08-28';
+export const APIMART_MAX_PROMPT_LENGTH = 10_000;
+
+export function buildApimartGenerationPayload(prompt, options = {}) {
+ const payload = {
+ model: APIMART_MODEL,
+ prompt: String(prompt || '').trim(),
+ n: 1,
+ size: '1:1',
+ resolution: '1k'
+ };
+
+ if (options.webhook) payload.webhook = options.webhook;
+ if (options.language) payload.language = options.language === 'zh' ? 'zh' : 'en';
+ return payload;
+}
+
+export function extractApimartTaskId(payload) {
+ const data = payload?.data;
+ if (Array.isArray(data)) return String(data[0]?.task_id || data[0]?.id || '').trim();
+ return String(data?.task_id || data?.id || payload?.task_id || payload?.id || '').trim();
+}
+
+export function isValidApimartTaskId(taskId) {
+ return /^task_[a-zA-Z0-9_-]{8,180}$/.test(String(taskId || ''));
+}
+
+export function normalizeApimartTask(payload) {
+ const data = payload?.data && !Array.isArray(payload.data) ? payload.data : payload;
+ const rawStatus = String(data?.status || '').toLowerCase();
+ const status = rawStatus === 'in_progress' ? 'processing' : rawStatus;
+ const images = Array.isArray(data?.result?.images) ? data.result.images : [];
+ const firstImage = images[0] || {};
+ const urls = Array.isArray(firstImage.url)
+ ? firstImage.url
+ : firstImage.url
+ ? [firstImage.url]
+ : [];
+ const expiresAt = normalizeApimartExpiry(firstImage.expires_at);
+
+ return {
+ taskId: String(data?.id || data?.task_id || '').trim(),
+ status: status || 'unknown',
+ progress: Number.isFinite(Number(data?.progress)) ? Number(data.progress) : 0,
+ image: String(urls[0] || ''),
+ expiresAt,
+ cost: Number.isFinite(Number(data?.cost)) ? Number(data.cost) : null,
+ errorMessage: String(data?.error?.message || ''),
+ errorCode: String(data?.error?.code || data?.error?.type || '')
+ };
+}
+
+export function normalizeApimartExpiry(value) {
+ const numeric = Number(value);
+ if (Number.isFinite(numeric) && numeric > 0) {
+ return Math.floor(numeric > 10_000_000_000 ? numeric / 1000 : numeric);
+ }
+ const parsed = Date.parse(String(value || ''));
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed / 1000) : null;
+}
+
+export function isTerminalApimartStatus(status) {
+ return status === 'completed' || status === 'failed';
+}
+
+export function apimartErrorCode(status, payload) {
+ const upstreamCode = String(payload?.error?.code || payload?.code || '').toLowerCase();
+ if (status === 401) return 'APIMART_API_KEY_INVALID';
+ if (status === 402) return 'APIMART_BALANCE_REQUIRED';
+ if (status === 429) return 'APIMART_RATE_LIMITED';
+ if (status === 400 || status === 403 || upstreamCode.includes('moderation')) {
+ return 'APIMART_REQUEST_REJECTED';
+ }
+ if (status >= 500) return 'APIMART_UNAVAILABLE';
+ return 'APIMART_REQUEST_FAILED';
+}
+
+export function retryAfterMilliseconds(value, fallbackMs = 2000, nowMs = Date.now()) {
+ const seconds = Number(value);
+ if (Number.isFinite(seconds) && seconds > 0) {
+ return Math.min(60_000, Math.max(1000, Math.round(seconds * 1000)));
+ }
+ const retryAt = Date.parse(String(value || ''));
+ if (Number.isFinite(retryAt) && retryAt > nowMs) {
+ return Math.min(60_000, Math.max(1000, retryAt - nowMs));
+ }
+ return fallbackMs;
+}
+
+export function apimartTaskErrorCode(task) {
+ const detail = `${task?.errorCode || ''} ${task?.errorMessage || ''}`.toLowerCase();
+ if (detail.includes('moderation') || detail.includes('content') || detail.includes('safety') || detail.includes('nsfw')) {
+ return 'APIMART_REQUEST_REJECTED';
+ }
+ if (detail.includes('balance') || detail.includes('credit') || detail.includes('insufficient')) {
+ return 'APIMART_BALANCE_REQUIRED';
+ }
+ if (detail.includes('rate') || detail.includes('limit') || detail.includes('too many')) {
+ return 'APIMART_RATE_LIMITED';
+ }
+ return 'APIMART_TASK_FAILED';
+}
+
+export function parseApimartPricing(payload) {
+ const prices = payload?.data?.resolution_prices || {};
+ const read = (key, fallback) => {
+ const value = Number(prices[key] ?? prices[key.toLowerCase()]);
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+ };
+ return {
+ model: String(payload?.data?.model_name || APIMART_MODEL),
+ currency: 'USD',
+ prices: {
+ '1k': read('1K', APIMART_DEFAULT_PRICE_USD),
+ '2k': read('2K', 0.0175),
+ '4k': read('4K', 0.02625)
+ }
+ };
+}
diff --git a/shared/apimart.test.js b/shared/apimart.test.js
new file mode 100644
index 0000000..394714a
--- /dev/null
+++ b/shared/apimart.test.js
@@ -0,0 +1,90 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ APIMART_DEFAULT_PRICE_USD,
+ APIMART_MODEL,
+ apimartErrorCode,
+ apimartTaskErrorCode,
+ buildApimartGenerationPayload,
+ extractApimartTaskId,
+ normalizeApimartExpiry,
+ normalizeApimartTask,
+ parseApimartPricing,
+ retryAfterMilliseconds
+} from './apimart.js';
+
+test('generation payload locks GPT-Image-2 to one 1K square image', () => {
+ assert.deepEqual(buildApimartGenerationPayload(' draw a fox ', {
+ language: 'zh',
+ webhook: 'https://example.com/api/generation',
+ n: 9,
+ size: '16:9',
+ resolution: '4k'
+ }), {
+ model: APIMART_MODEL,
+ prompt: 'draw a fox',
+ n: 1,
+ size: '1:1',
+ resolution: '1k',
+ webhook: 'https://example.com/api/generation',
+ language: 'zh'
+ });
+});
+
+test('task ids and async task responses are normalized', () => {
+ assert.equal(extractApimartTaskId({ data: { task_id: 'task_12345678' } }), 'task_12345678');
+ const task = normalizeApimartTask({
+ data: {
+ id: 'task_12345678',
+ status: 'in_progress',
+ progress: '67',
+ cost: '0.010625',
+ result: {
+ images: [{
+ url: ['https://cdn.example/result.png'],
+ expires_at: '2026-08-29T00:00:00.000Z'
+ }]
+ }
+ }
+ });
+ assert.equal(task.status, 'processing');
+ assert.equal(task.progress, 67);
+ assert.equal(task.image, 'https://cdn.example/result.png');
+ assert.equal(task.cost, 0.010625);
+ assert.equal(task.expiresAt, Date.parse('2026-08-29T00:00:00.000Z') / 1000);
+});
+
+test('expiry accepts seconds, milliseconds and ISO dates', () => {
+ assert.equal(normalizeApimartExpiry(1787961600), 1787961600);
+ assert.equal(normalizeApimartExpiry(1787961600000), 1787961600);
+ assert.equal(normalizeApimartExpiry('2026-08-29T00:00:00.000Z'), 1787961600);
+ assert.equal(normalizeApimartExpiry('invalid'), null);
+});
+
+test('Retry-After supports seconds and HTTP dates with bounded waits', () => {
+ assert.equal(retryAfterMilliseconds('3'), 3000);
+ assert.equal(retryAfterMilliseconds('120'), 60000);
+ assert.equal(retryAfterMilliseconds('Thu, 01 Jan 2026 00:00:05 GMT', 2000, Date.parse('2026-01-01T00:00:00Z')), 5000);
+ assert.equal(retryAfterMilliseconds('invalid', 2500), 2500);
+});
+
+test('pricing parser uses live 1K pricing and safe fallbacks', () => {
+ assert.deepEqual(parseApimartPricing({
+ data: {
+ model_name: 'gpt-image-2',
+ resolution_prices: { '1K': 0.010625, '2K': 0.0175, '4K': 0.02625 }
+ }
+ }).prices, { '1k': 0.010625, '2k': 0.0175, '4k': 0.02625 });
+ assert.equal(parseApimartPricing({}).prices['1k'], APIMART_DEFAULT_PRICE_USD);
+});
+
+test('HTTP and terminal task errors map to distinct user-facing classes', () => {
+ assert.equal(apimartErrorCode(401, {}), 'APIMART_API_KEY_INVALID');
+ assert.equal(apimartErrorCode(402, {}), 'APIMART_BALANCE_REQUIRED');
+ assert.equal(apimartErrorCode(429, {}), 'APIMART_RATE_LIMITED');
+ assert.equal(apimartErrorCode(503, {}), 'APIMART_UNAVAILABLE');
+ assert.equal(apimartErrorCode(400, { error: { code: 'moderation_failed' } }), 'APIMART_REQUEST_REJECTED');
+ assert.equal(apimartTaskErrorCode({ errorCode: 'NSFW_CONTENT_DETECTED' }), 'APIMART_REQUEST_REJECTED');
+ assert.equal(apimartTaskErrorCode({ errorMessage: 'Insufficient balance' }), 'APIMART_BALANCE_REQUIRED');
+ assert.equal(apimartTaskErrorCode({ errorMessage: 'unknown worker failure' }), 'APIMART_TASK_FAILED');
+});
diff --git a/src/apimartClient.js b/src/apimartClient.js
new file mode 100644
index 0000000..7c49809
--- /dev/null
+++ b/src/apimartClient.js
@@ -0,0 +1,299 @@
+import {
+ APIMART_API_BASE_URL,
+ apimartErrorCode,
+ buildApimartGenerationPayload,
+ extractApimartTaskId,
+ isTerminalApimartStatus,
+ isValidApimartTaskId,
+ normalizeApimartTask,
+ retryAfterMilliseconds
+} from '../shared/apimart.js';
+
+export const APIMART_KEY_STORAGE_KEY = 'gpt-image-2-apimart-key:v1';
+export const APIMART_PENDING_STORAGE_KEY = 'gpt-image-2-pending-tests:v1';
+export const GENERATED_TESTS_STORAGE_KEY = 'gpt-image-2-generated-tests:v1';
+const MAX_SAVED_GENERATIONS = 12;
+
+function browserStorage(storage) {
+ if (storage) return storage;
+ try {
+ return globalThis.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+function readObject(key, storage) {
+ try {
+ return JSON.parse(browserStorage(storage)?.getItem(key) || '{}');
+ } catch {
+ return {};
+ }
+}
+
+function writeObject(key, value, storage) {
+ try {
+ browserStorage(storage)?.setItem(key, JSON.stringify(value));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function getStoredApimartKey(storage) {
+ try {
+ return String(browserStorage(storage)?.getItem(APIMART_KEY_STORAGE_KEY) || '').trim();
+ } catch {
+ return '';
+ }
+}
+
+export function saveStoredApimartKey(apiKey, storage) {
+ const normalized = String(apiKey || '').trim();
+ if (!normalized || normalized.length > 512 || /[\r\n]/.test(normalized)) return false;
+ try {
+ browserStorage(storage)?.setItem(APIMART_KEY_STORAGE_KEY, normalized);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function clearStoredApimartKey(storage) {
+ try {
+ browserStorage(storage)?.removeItem(APIMART_KEY_STORAGE_KEY);
+ } catch {
+ // Storage may be unavailable in privacy-restricted browsers.
+ }
+}
+
+export function maskApimartKey(apiKey) {
+ const normalized = String(apiKey || '').trim();
+ if (!normalized) return '';
+ return `••••••••${normalized.slice(-4)}`;
+}
+
+async function readResponse(response) {
+ return response.json().catch(() => ({}));
+}
+
+function responseError(response, payload) {
+ const error = new Error(apimartErrorCode(response.status, payload));
+ error.code = error.message;
+ error.status = response.status;
+ error.retryAfterMs = retryAfterMilliseconds(response.headers?.get?.('retry-after'));
+ error.upstreamMessage = String(payload?.error?.message || '');
+ return error;
+}
+
+export async function verifyPersonalApimartKey(apiKey, fetchImpl = fetch) {
+ const response = await fetchImpl(`${APIMART_API_BASE_URL}/v1/models`, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ Accept: 'application/json'
+ },
+ cache: 'no-store'
+ });
+ const payload = await readResponse(response);
+ if (!response.ok) throw responseError(response, payload);
+ return true;
+}
+
+export async function submitPersonalGeneration(prompt, apiKey, language, fetchImpl = fetch) {
+ const response = await fetchImpl(`${APIMART_API_BASE_URL}/v1/images/generations`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json'
+ },
+ body: JSON.stringify(buildApimartGenerationPayload(prompt, { language })),
+ cache: 'no-store'
+ });
+ const payload = await readResponse(response);
+ if (!response.ok) throw responseError(response, payload);
+ const taskId = extractApimartTaskId(payload);
+ if (!isValidApimartTaskId(taskId)) {
+ const error = new Error('APIMART_INVALID_RESPONSE');
+ error.code = error.message;
+ throw error;
+ }
+ return { taskId, status: 'submitted' };
+}
+
+export async function fetchPersonalTask(taskId, apiKey, language, fetchImpl = fetch) {
+ if (!isValidApimartTaskId(taskId)) {
+ const error = new Error('APIMART_INVALID_TASK');
+ error.code = error.message;
+ throw error;
+ }
+ const query = new URLSearchParams({ language: language === 'zh' ? 'zh' : 'en' });
+ const response = await fetchImpl(`${APIMART_API_BASE_URL}/v1/tasks/${encodeURIComponent(taskId)}?${query}`, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ Accept: 'application/json'
+ },
+ cache: 'no-store'
+ });
+ const payload = await readResponse(response);
+ if (!response.ok) throw responseError(response, payload);
+ return normalizeApimartTask(payload);
+}
+
+export async function submitPlatformGeneration({ caseId, prompt, language, accessToken }, fetchImpl = fetch) {
+ const response = await fetchImpl('/api/generate-image', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json'
+ },
+ body: JSON.stringify({ caseId, prompt, language }),
+ cache: 'no-store'
+ });
+ const payload = await readResponse(response);
+ if (!response.ok || !payload?.ok) {
+ const error = new Error(payload?.error || apimartErrorCode(response.status, payload));
+ error.code = error.message;
+ error.status = response.status;
+ error.user = payload?.user || null;
+ throw error;
+ }
+ if (!isValidApimartTaskId(payload.taskId)) {
+ const error = new Error('APIMART_INVALID_RESPONSE');
+ error.code = error.message;
+ throw error;
+ }
+ return payload;
+}
+
+export async function fetchPlatformTask(taskId, accessToken, language, fetchImpl = fetch) {
+ if (!isValidApimartTaskId(taskId)) {
+ const error = new Error('APIMART_INVALID_TASK');
+ error.code = error.message;
+ throw error;
+ }
+ const query = new URLSearchParams({ taskId, language: language === 'zh' ? 'zh' : 'en' });
+ const response = await fetchImpl(`/api/generation/status?${query}`, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ Accept: 'application/json'
+ },
+ cache: 'no-store'
+ });
+ const payload = await readResponse(response);
+ if (!response.ok || !payload?.ok) {
+ const code = payload?.error || apimartErrorCode(response.status, payload);
+ const error = new Error(code);
+ error.code = code;
+ error.status = response.status;
+ error.retryAfterMs = Number(payload?.retryAfterMs) || retryAfterMilliseconds(response.headers?.get?.('retry-after'));
+ throw error;
+ }
+ return payload;
+}
+
+function wait(milliseconds, signal) {
+ return new Promise((resolve, reject) => {
+ function handleAbort() {
+ globalThis.clearTimeout(timeout);
+ const error = new Error('APIMART_POLL_ABORTED');
+ error.code = error.message;
+ reject(error);
+ }
+ const timeout = globalThis.setTimeout(() => {
+ signal?.removeEventListener('abort', handleAbort);
+ resolve();
+ }, milliseconds);
+ signal?.addEventListener('abort', handleAbort, { once: true });
+ });
+}
+
+export async function pollApimartTask(fetchTask, options = {}) {
+ const {
+ signal,
+ onProgress,
+ maxAttempts = 120,
+ maxElapsedMs = 10 * 60 * 1000,
+ intervalMs = 2000,
+ waitImpl = wait,
+ now = () => Date.now()
+ } = options;
+ const startedAt = now();
+
+ for (let attempt = 0; attempt < maxAttempts && now() - startedAt < maxElapsedMs; attempt += 1) {
+ if (signal?.aborted) {
+ const error = new Error('APIMART_POLL_ABORTED');
+ error.code = error.message;
+ throw error;
+ }
+ try {
+ const task = await fetchTask();
+ if (signal?.aborted) {
+ const error = new Error('APIMART_POLL_ABORTED');
+ error.code = error.message;
+ throw error;
+ }
+ onProgress?.(task);
+ if (isTerminalApimartStatus(task.status)) return task;
+ await waitImpl(intervalMs, signal);
+ } catch (error) {
+ if (error?.code !== 'APIMART_RATE_LIMITED') throw error;
+ await waitImpl(error.retryAfterMs || intervalMs, signal);
+ }
+ }
+
+ const error = new Error('APIMART_TASK_TIMEOUT');
+ error.code = error.message;
+ throw error;
+}
+
+export function getPendingGeneration(caseId, storage) {
+ const entry = readObject(APIMART_PENDING_STORAGE_KEY, storage)[String(caseId)];
+ return entry?.taskId && isValidApimartTaskId(entry.taskId) ? entry : null;
+}
+
+export function savePendingGeneration(caseId, entry, storage) {
+ const saved = readObject(APIMART_PENDING_STORAGE_KEY, storage);
+ saved[String(caseId)] = entry;
+ return writeObject(APIMART_PENDING_STORAGE_KEY, saved, storage);
+}
+
+export function clearPendingGeneration(caseId, storage) {
+ const saved = readObject(APIMART_PENDING_STORAGE_KEY, storage);
+ delete saved[String(caseId)];
+ writeObject(APIMART_PENDING_STORAGE_KEY, saved, storage);
+}
+
+export function getSavedGeneration(caseId, storage, nowMs = Date.now()) {
+ cleanupExpiredGeneratedTests(storage, nowMs);
+ const saved = readObject(GENERATED_TESTS_STORAGE_KEY, storage);
+ const entry = saved[String(caseId)];
+ return entry?.image ? entry : null;
+}
+
+export function cleanupExpiredGeneratedTests(storage, nowMs = Date.now()) {
+ const saved = readObject(GENERATED_TESTS_STORAGE_KEY, storage);
+ let changed = false;
+ for (const [key, entry] of Object.entries(saved)) {
+ if (entry?.expiresAt && Number(entry.expiresAt) * 1000 <= nowMs) {
+ delete saved[key];
+ changed = true;
+ }
+ }
+ if (changed) writeObject(GENERATED_TESTS_STORAGE_KEY, saved, storage);
+ return changed;
+}
+
+export function saveGeneratedTest(caseId, entry, storage) {
+ const saved = readObject(GENERATED_TESTS_STORAGE_KEY, storage);
+ saved[String(caseId)] = entry;
+ const latestEntries = Object.entries(saved)
+ .filter(([, value]) => value?.image)
+ .sort(([, a], [, b]) => new Date(b.savedAt || 0) - new Date(a.savedAt || 0))
+ .slice(0, MAX_SAVED_GENERATIONS);
+ return writeObject(GENERATED_TESTS_STORAGE_KEY, Object.fromEntries(latestEntries), storage);
+}
diff --git a/src/apimartClient.test.js b/src/apimartClient.test.js
new file mode 100644
index 0000000..72e9905
--- /dev/null
+++ b/src/apimartClient.test.js
@@ -0,0 +1,143 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ clearStoredApimartKey,
+ getPendingGeneration,
+ getSavedGeneration,
+ getStoredApimartKey,
+ maskApimartKey,
+ pollApimartTask,
+ saveGeneratedTest,
+ savePendingGeneration,
+ saveStoredApimartKey,
+ submitPersonalGeneration,
+ submitPlatformGeneration
+} from './apimartClient.js';
+
+class MemoryStorage {
+ constructor() {
+ this.values = new Map();
+ }
+
+ getItem(key) {
+ return this.values.has(key) ? this.values.get(key) : null;
+ }
+
+ setItem(key, value) {
+ this.values.set(key, String(value));
+ }
+
+ removeItem(key) {
+ this.values.delete(key);
+ }
+}
+
+test('personal key stays in browser storage and is displayed only as a suffix mask', () => {
+ const storage = new MemoryStorage();
+ const key = 'apimart_secret_12345678';
+ assert.equal(saveStoredApimartKey(key, storage), true);
+ assert.equal(getStoredApimartKey(storage), key);
+ assert.equal(maskApimartKey(key), '••••••••5678');
+ clearStoredApimartKey(storage);
+ assert.equal(getStoredApimartKey(storage), '');
+});
+
+test('pending tasks persist without an API key and expired results are removed', () => {
+ const storage = new MemoryStorage();
+ savePendingGeneration(42, {
+ taskId: 'task_abcdefgh',
+ mode: 'personal',
+ prompt: 'draw a lighthouse'
+ }, storage);
+ const pending = getPendingGeneration(42, storage);
+ assert.equal(pending.taskId, 'task_abcdefgh');
+ assert.equal(JSON.stringify(pending).includes('apiKey'), false);
+
+ saveGeneratedTest(42, {
+ image: 'https://cdn.example/expired.png',
+ savedAt: '2026-08-28T00:00:00.000Z',
+ expiresAt: 100
+ }, storage);
+ assert.equal(getSavedGeneration(42, storage, 101000), null);
+});
+
+test('personal submission sends the fixed APIMart schema directly', async () => {
+ const calls = [];
+ const result = await submitPersonalGeneration('draw a fox', 'personal-key', 'zh', async (url, options) => {
+ calls.push({ url, options, body: JSON.parse(options.body) });
+ return new Response(JSON.stringify({ data: { task_id: 'task_abcdefgh' } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' }
+ });
+ });
+ assert.equal(result.taskId, 'task_abcdefgh');
+ assert.match(calls[0].url, /api\.apimart\.ai\/v1\/images\/generations$/);
+ assert.equal(calls[0].options.headers.Authorization, 'Bearer personal-key');
+ assert.deepEqual(calls[0].body, {
+ model: 'gpt-image-2',
+ prompt: 'draw a fox',
+ n: 1,
+ size: '1:1',
+ resolution: '1k',
+ language: 'zh'
+ });
+});
+
+test('platform submission contains only site auth and generation fields', async () => {
+ const calls = [];
+ await submitPlatformGeneration({
+ caseId: 42,
+ prompt: 'draw a fox',
+ language: 'en',
+ accessToken: 'site-session-token'
+ }, async (url, options) => {
+ calls.push({ url, options, body: JSON.parse(options.body) });
+ return new Response(JSON.stringify({ ok: true, taskId: 'task_abcdefgh', status: 'submitted' }), {
+ status: 202,
+ headers: { 'content-type': 'application/json' }
+ });
+ });
+ assert.equal(calls[0].url, '/api/generate-image');
+ assert.equal(calls[0].options.headers.Authorization, 'Bearer site-session-token');
+ assert.deepEqual(calls[0].body, { caseId: 42, prompt: 'draw a fox', language: 'en' });
+ assert.equal(JSON.stringify(calls[0]).includes('personal-key'), false);
+});
+
+test('polling stops on completion and honors Retry-After waits', async () => {
+ const waits = [];
+ let calls = 0;
+ const task = await pollApimartTask(async () => {
+ calls += 1;
+ if (calls === 1) {
+ const error = new Error('APIMART_RATE_LIMITED');
+ error.code = error.message;
+ error.retryAfterMs = 7000;
+ throw error;
+ }
+ if (calls === 2) return { status: 'processing', progress: 50 };
+ return { status: 'completed', progress: 100, image: 'https://cdn.example/result.png' };
+ }, {
+ intervalMs: 2000,
+ waitImpl: async (milliseconds) => waits.push(milliseconds),
+ now: () => 0
+ });
+ assert.equal(task.status, 'completed');
+ assert.deepEqual(waits, [7000, 2000]);
+});
+
+test('polling times out without submitting another task', async () => {
+ let fetchCount = 0;
+ await assert.rejects(
+ pollApimartTask(async () => {
+ fetchCount += 1;
+ return { status: 'processing', progress: fetchCount };
+ }, {
+ maxAttempts: 2,
+ intervalMs: 1,
+ waitImpl: async () => {},
+ now: () => 0
+ }),
+ { code: 'APIMART_TASK_TIMEOUT' }
+ );
+ assert.equal(fetchCount, 2);
+});
diff --git a/src/main.jsx b/src/main.jsx
index 77d2d63..b5295d5 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -11,9 +11,11 @@ import {
CreditCard,
Crown,
Eye,
+ EyeOff,
Github,
Heart,
ImageIcon,
+ KeyRound,
LoaderCircle,
LogIn,
LogOut,
@@ -34,11 +36,36 @@ import {
} from 'lucide-react';
import './styles.css';
import { isSupabaseConfigured, supabase } from './supabaseClient';
+import {
+ clearPendingGeneration,
+ clearStoredApimartKey,
+ cleanupExpiredGeneratedTests,
+ fetchPersonalTask,
+ fetchPlatformTask,
+ getPendingGeneration,
+ getSavedGeneration,
+ getStoredApimartKey,
+ maskApimartKey,
+ pollApimartTask,
+ saveGeneratedTest,
+ savePendingGeneration,
+ saveStoredApimartKey,
+ submitPersonalGeneration,
+ submitPlatformGeneration,
+ verifyPersonalApimartKey
+} from './apimartClient';
+import {
+ APIMART_DEFAULT_PRICE_USD,
+ APIMART_MAX_PROMPT_LENGTH,
+ APIMART_PRICE_SNAPSHOT_DATE,
+ apimartTaskErrorCode
+} from '../shared/apimart';
import { CommunityAdminSection, CommunityPage } from './community';
import skillExampleImage from '../agents/skills/gpt-image-2-style-library/assets/city-life-system-map.png';
const fallbackRepoUrl = 'https://github.com/freestylefly/awesome-gpt-image-2';
const sponsorUrl = 'https://apimart.ai/register?aff=oQgzUQ';
+const apimartKeysUrl = 'https://apimart.ai/keys';
const gaMeasurementId = import.meta.env.VITE_GA_MEASUREMENT_ID;
const watchaLogoUrl =
'https://watcha.tos-cn-beijing.volces.com/products/logo/1752064513_guan-cha-insights.png?x-tos-process=image/resize,w_720/format,webp';
@@ -123,7 +150,45 @@ const copy = {
creditsRequired: 'Credits required. Buy credits or start a membership to keep generating.',
generationBusy: 'The image service is busy. Please try again in a moment.',
generationFailed: 'Generation failed. Please try again later.',
- promptRequired: 'Prompt is required and must stay under 6000 characters.',
+ apimartApiSettings: 'APIMart API settings',
+ apimartApiTitle: 'Use your own APIMart API key',
+ apimartApiSubtitle: 'The key is stored only in this browser and calls APIMart directly. Clearing site data removes it.',
+ apimartApiKey: 'APIMart API key',
+ apimartApiPlaceholder: 'Paste your APIMart API key',
+ apimartVerifySave: 'Verify and save',
+ apimartVerifying: 'Verifying...',
+ apimartKeySaved: 'API key verified and saved in this browser.',
+ apimartKeyCleared: 'The saved API key has been removed.',
+ apimartKeyInvalid: 'The APIMart API key is invalid. Check it and try again.',
+ apimartBalanceRequired: 'Your APIMart balance is insufficient. Top up before generating.',
+ apimartRequestRejected: 'APIMart rejected this request. Review the Prompt and try again.',
+ apimartUnavailable: 'APIMart is temporarily unavailable. Try again later.',
+ apimartTaskFailed: 'APIMart could not complete this generation.',
+ apimartTaskTimeout: 'The task is still running. Its task ID is saved, and checking will continue when you reopen this case.',
+ apimartRateLimited: 'APIMart is rate limiting requests. Checking will continue after the requested wait.',
+ apimartContinueChecking: 'Continue checking',
+ apimartTaskId: 'Task ID',
+ apimartExpiresAt: (value) => `Result link expires: ${value}`,
+ apimartPriceFallback: (date) => `Price service is unavailable. Showing the ${date} snapshot.`,
+ apimartAnonymousChoice: 'Add a personal Key for direct generation, or sign in to use platform credits.',
+ apimartPendingNeedsKey: 'This pending personal task needs your APIMart Key before checking can continue.',
+ apimartPendingNeedsLogin: 'Sign in with the same account to continue checking this platform task.',
+ apimartStorageFailed: 'This browser could not save the API Key. Check site storage permissions and try again.',
+ apimartClearKey: 'Remove key',
+ apimartManageKey: 'Manage personal API key',
+ apimartConfigureKey: 'Configure personal API key',
+ apimartGetKey: 'Open API key management',
+ apimartRegister: 'Create APIMart account',
+ apimartLocalOnly: 'Your full key stays in local browser storage and is sent only to APIMart.',
+ apimartPersonalMode: (masked, price) => `Personal APIMart key ${masked} · 1K · about $${price}/image`,
+ apimartPlatformMode: 'Platform credits · 1K · 1 image',
+ apimartPriceNote: (price) => `Current 1K price: $${price}/image. Final billing is determined by APIMart.`,
+ apimartProgress: (progress) => `APIMart is generating · ${progress}%`,
+ apimartActualCost: (cost) => `Actual APIMart cost: $${cost}`,
+ apimartShowKey: 'Show API key',
+ apimartHideKey: 'Hide API key',
+ usePlatformCredits: 'Sign in to use platform credits',
+ promptRequired: 'Prompt is required and must stay under 10,000 characters.',
serverUnavailable: 'Generation service is not configured yet.',
checkoutUnavailable: 'Checkout is not configured yet.',
checkoutFailed: 'Checkout failed. Please try again later.',
@@ -343,7 +408,45 @@ const copy = {
creditsRequired: '积分不足,可购买积分包或开通会员继续生成。',
generationBusy: '生图服务繁忙,请稍后再试。',
generationFailed: '生成失败,请稍后再试。',
- promptRequired: 'Prompt 不能为空,并且不能超过 6000 字符。',
+ apimartApiSettings: 'APIMart API 配置',
+ apimartApiTitle: '使用你自己的 APIMart API Key',
+ apimartApiSubtitle: 'Key 仅保存在当前浏览器,并由浏览器直接调用 APIMart;清除站点数据后会一并删除。',
+ apimartApiKey: 'APIMart API Key',
+ apimartApiPlaceholder: '粘贴你的 APIMart API Key',
+ apimartVerifySave: '验证并保存',
+ apimartVerifying: '验证中...',
+ apimartKeySaved: 'API Key 已验证,并保存到当前浏览器。',
+ apimartKeyCleared: '已删除当前浏览器保存的 API Key。',
+ apimartKeyInvalid: 'APIMart API Key 无效,请检查后重试。',
+ apimartBalanceRequired: '你的 APIMart 余额不足,请充值后再生成。',
+ apimartRequestRejected: 'APIMart 拒绝了本次请求,请检查 Prompt 后重试。',
+ apimartUnavailable: 'APIMart 暂时不可用,请稍后再试。',
+ apimartTaskFailed: 'APIMart 未能完成本次生成。',
+ apimartTaskTimeout: '任务仍在运行,任务 ID 已保存;重新打开此案例后会继续查询。',
+ apimartRateLimited: 'APIMart 当前触发限流,页面会按照服务端要求的等待时间继续查询。',
+ apimartContinueChecking: '继续查询任务',
+ apimartTaskId: '任务 ID',
+ apimartExpiresAt: (value) => `结果链接有效期至:${value}`,
+ apimartPriceFallback: (date) => `实时价格暂时无法获取,当前展示 ${date} 的价格快照。`,
+ apimartAnonymousChoice: '可配置个人 Key 直接生成,也可以登录后使用平台额度。',
+ apimartPendingNeedsKey: '该个人任务需要 APIMart Key 才能继续查询。',
+ apimartPendingNeedsLogin: '请使用提交任务时的同一账号登录,然后继续查询平台任务。',
+ apimartStorageFailed: '当前浏览器无法保存 API Key,请检查站点存储权限后重试。',
+ apimartClearKey: '删除 Key',
+ apimartManageKey: '管理个人 API Key',
+ apimartConfigureKey: '配置个人 API Key',
+ apimartGetKey: '打开 API Key 管理页',
+ apimartRegister: '注册 APIMart',
+ apimartLocalOnly: '完整 Key 只会保存在本地浏览器,并且只发送给 APIMart。',
+ apimartPersonalMode: (masked, price) => `个人 APIMart Key ${masked} · 1K · 当前约 $${price}/张`,
+ apimartPlatformMode: '平台积分 · 1K · 1 张',
+ apimartPriceNote: (price) => `当前 1K 价格为 $${price}/张,最终费用以 APIMart 实际结算为准。`,
+ apimartProgress: (progress) => `APIMart 正在生成 · ${progress}%`,
+ apimartActualCost: (cost) => `APIMart 实际费用:$${cost}`,
+ apimartShowKey: '显示 API Key',
+ apimartHideKey: '隐藏 API Key',
+ usePlatformCredits: '登录使用平台额度',
+ promptRequired: 'Prompt 不能为空,并且不能超过 10,000 字符。',
serverUnavailable: '生成服务还没有完成配置。',
checkoutUnavailable: '支付功能还没有完成配置。',
checkoutFailed: '创建支付失败,请稍后再试。',
@@ -550,8 +653,6 @@ function compactText(value, maxLength = 180) {
return `${value.slice(0, maxLength)}...`;
}
-const GENERATED_TESTS_STORAGE_KEY = 'gpt-image-2-generated-tests:v1';
-const MAX_SAVED_GENERATIONS = 12;
const HERO_CASE_COUNT = 5;
const HOT_STRIP_CASE_COUNT = 8;
let bodyScrollLockCount = 0;
@@ -665,6 +766,21 @@ function formatShortDate(value, language) {
});
}
+function formatApimartPrice(value) {
+ const numeric = Number(value);
+ return Number.isFinite(numeric) && numeric > 0 ? numeric.toFixed(6).replace(/0+$/, '') : '0.010625';
+}
+
+function formatApimartExpiry(value, language) {
+ if (!value) return '';
+ const numeric = Number(value);
+ const date = Number.isFinite(numeric)
+ ? new Date(numeric > 10_000_000_000 ? numeric : numeric * 1000)
+ : new Date(value);
+ if (Number.isNaN(date.getTime())) return '';
+ return date.toLocaleString(language === 'zh' ? 'zh-CN' : 'en-US');
+}
+
function formatRangeDate(value, language) {
if (!value) return '-';
return new Date(`${value}T00:00:00`).toLocaleDateString(language === 'zh' ? 'zh-CN' : 'en-US', {
@@ -693,42 +809,6 @@ function percentOf(value, max) {
return Math.max(4, Math.round((Number(value || 0) / max) * 100));
}
-function readSavedGenerations() {
- try {
- return JSON.parse(localStorage.getItem(GENERATED_TESTS_STORAGE_KEY) || '{}');
- } catch {
- return {};
- }
-}
-
-function getSavedGeneration(caseId) {
- const saved = readSavedGenerations()[String(caseId)];
- return saved?.image ? saved : null;
-}
-
-function saveGeneratedTest(caseId, entry) {
- const key = String(caseId);
- const saved = readSavedGenerations();
- saved[key] = entry;
-
- const latestEntries = Object.entries(saved)
- .filter(([, value]) => value?.image)
- .sort(([, a], [, b]) => new Date(b.savedAt || 0) - new Date(a.savedAt || 0))
- .slice(0, MAX_SAVED_GENERATIONS);
-
- try {
- localStorage.setItem(GENERATED_TESTS_STORAGE_KEY, JSON.stringify(Object.fromEntries(latestEntries)));
- } catch {
- const compactEntries = latestEntries.slice(0, Math.max(1, Math.floor(MAX_SAVED_GENERATIONS / 2)));
- try {
- localStorage.setItem(GENERATED_TESTS_STORAGE_KEY, JSON.stringify(Object.fromEntries(compactEntries)));
- } catch {
- // Browser storage can be full or blocked. The generated image still stays
- // visible for the current dialog state when persistence is unavailable.
- }
- }
-}
-
function normalizeFavoriteRows(favorites = []) {
const rows = Array.isArray(favorites) ? favorites : [];
return rows
@@ -825,6 +905,13 @@ function generationErrorMessage(error, language) {
if (error === 'AUTH_REQUIRED') return t.authRequired;
if (error === 'FORBIDDEN') return t.adminOnly;
if (error === 'UPSTREAM_BUSY') return t.generationBusy;
+ if (error === 'APIMART_API_KEY_INVALID') return t.apimartKeyInvalid;
+ if (error === 'APIMART_BALANCE_REQUIRED') return t.apimartBalanceRequired;
+ if (error === 'APIMART_REQUEST_REJECTED') return t.apimartRequestRejected;
+ if (error === 'APIMART_RATE_LIMITED') return t.apimartRateLimited;
+ if (error === 'APIMART_UNAVAILABLE') return t.apimartUnavailable;
+ if (error === 'APIMART_TASK_FAILED') return t.apimartTaskFailed;
+ if (error === 'APIMART_TASK_TIMEOUT') return t.apimartTaskTimeout;
if (error === 'SERVER_NOT_CONFIGURED') return t.serverUnavailable;
if (
error === 'BILLING_NOT_CONFIGURED'
@@ -1317,6 +1404,147 @@ function AuthModal({ open, language, initialErrorCode, onClose }) {
);
}
+function ApiKeyModal({ open, language, apiKey, price, priceMeta, onClose, onSaved, onCleared }) {
+ const t = copy[language];
+ const [input, setInput] = useState('');
+ const [showKey, setShowKey] = useState(false);
+ const [status, setStatus] = useState('idle');
+ const [message, setMessage] = useState('');
+ useBodyScrollLock(open);
+
+ useEffect(() => {
+ if (!open) return;
+ setInput(apiKey || '');
+ setShowKey(false);
+ setStatus('idle');
+ setMessage('');
+ }, [open, apiKey]);
+
+ useEffect(() => {
+ if (!open) return undefined;
+ function handleKeyDown(event) {
+ if (event.key === 'Escape' && status !== 'loading') onClose();
+ }
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [open, onClose, status]);
+
+ if (!open) return null;
+
+ async function handleSave(event) {
+ event.preventDefault();
+ const nextKey = input.trim();
+ if (!nextKey || nextKey.length > 512 || /[\r\n]/.test(nextKey)) {
+ setStatus('error');
+ setMessage(t.apimartKeyInvalid);
+ return;
+ }
+
+ setStatus('loading');
+ setMessage('');
+ try {
+ await verifyPersonalApimartKey(nextKey);
+ if (!saveStoredApimartKey(nextKey)) {
+ setStatus('error');
+ setMessage(t.apimartStorageFailed);
+ return;
+ }
+ onSaved(nextKey);
+ setStatus('success');
+ setMessage(t.apimartKeySaved);
+ } catch (error) {
+ setStatus('error');
+ setMessage(generationErrorMessage(error?.code || error?.message, language));
+ }
+ }
+
+ function handleClear() {
+ clearStoredApimartKey();
+ setInput('');
+ setShowKey(false);
+ setStatus('success');
+ setMessage(t.apimartKeyCleared);
+ onCleared();
+ }
+
+ return (
+ <div
+ className="previewOverlay apiKeyOverlay"
+ role="presentation"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget && status !== 'loading') onClose();
+ }}
+ >
+ <section className="apiKeyDialog" role="dialog" aria-modal="true" aria-labelledby="apimart-key-title">
+ <button className="previewClose" type="button" onClick={onClose} aria-label={t.closePreview} disabled={status === 'loading'}>
+ <X size={20} />
+ </button>
+ <div className="apiKeyHeading">
+ <span className="authIcon"><KeyRound size={28} /></span>
+ <div>
+ <span className="eyebrow">{t.apimartApiSettings}</span>
+ <h2 id="apimart-key-title">{t.apimartApiTitle}</h2>
+ <p>{t.apimartApiSubtitle}</p>
+ </div>
+ </div>
+
+ <form className="apiKeyForm" onSubmit={handleSave}>
+ <label htmlFor="apimart-api-key">{t.apimartApiKey}</label>
+ <div className="apiKeyInputRow">
+ <input
+ id="apimart-api-key"
+ type={showKey ? 'text' : 'password'}
+ value={input}
+ maxLength={512}
+ autoComplete="off"
+ spellCheck="false"
+ placeholder={t.apimartApiPlaceholder}
+ onChange={(event) => setInput(event.target.value)}
+ />
+ <button
+ type="button"
+ className="apiKeyVisibility"
+ onClick={() => setShowKey((current) => !current)}
+ aria-label={showKey ? t.apimartHideKey : t.apimartShowKey}
+ title={showKey ? t.apimartHideKey : t.apimartShowKey}
+ >
+ {showKey ? <EyeOff size={18} /> : <Eye size={18} />}
+ </button>
+ </div>
+ {apiKey ? <div className="apiKeyMask"><Check size={15} /> {maskApimartKey(apiKey)}</div> : null}
+ <p className="apiKeyLocalNote"><ShieldCheck size={16} /> {t.apimartLocalOnly}</p>
+ <p className="apiKeyPriceNote">{t.apimartPriceNote(formatApimartPrice(price))}</p>
+ {priceMeta?.stale ? (
+ <p className="apiKeyFallback">{t.apimartPriceFallback(priceMeta.snapshotDate || APIMART_PRICE_SNAPSHOT_DATE)}</p>
+ ) : null}
+ <div className="apiKeyActions">
+ <button className="apiKeySave" type="submit" disabled={status === 'loading'}>
+ {status === 'loading' ? <LoaderCircle className="spinIcon" size={17} /> : <Check size={17} />}
+ {status === 'loading' ? t.apimartVerifying : t.apimartVerifySave}
+ </button>
+ {apiKey ? (
+ <button className="apiKeyClear" type="button" onClick={handleClear} disabled={status === 'loading'}>
+ <X size={17} />
+ {t.apimartClearKey}
+ </button>
+ ) : null}
+ </div>
+ </form>
+
+ <div className="apiKeyLinks">
+ <a href={sponsorUrl} target="_blank" rel="noreferrer">
+ {t.apimartRegister}<ArrowUpRight size={16} />
+ </a>
+ <a href={apimartKeysUrl} target="_blank" rel="noreferrer">
+ {t.apimartGetKey}<ArrowUpRight size={16} />
+ </a>
+ </div>
+ {message ? <p className={cx('authMessage', status === 'error' && 'error', status === 'success' && 'sent')}>{message}</p> : null}
+ </section>
+ </div>
+ );
+}
+
function UserMenu({ language, session, profile, onSignIn, onSignOut, onAdmin, onBilling, onAccount, onFavorites }) {
const t = copy[language];
const [open, setOpen] = useState(false);
@@ -1457,8 +1685,11 @@ function AccountPanel({
casesById,
favoriteRows,
initialSection,
+ apimartKey,
+ apimartPrice,
onClose,
onBilling,
+ onApiKeySettings,
onProfileChange,
onOpenCase
}) {
@@ -1610,6 +1841,18 @@ function AccountPanel({
</section>
</div>
+ <section className="apiKeySettingsCard">
+ <div className="apiKeySettingsIcon"><KeyRound size={22} /></div>
+ <div>
+ <h3>{t.apimartApiSettings}</h3>
+ <p>{apiKey ? t.apimartPersonalMode(maskApimartKey(apiKey), formatApimartPrice(apimartPrice)) : t.apimartApiSubtitle}</p>
+ </div>
+ <button type="button" onClick={onApiKeySettings}>
+ <Settings size={16} />
+ {apiKey ? t.apimartManageKey : t.apimartConfigureKey}
+ </button>
+ </section>
+
<section className="transactionSection favoritesSection" ref={favoritesRef}>
<h3>
<Heart size={18} />
@@ -2775,6 +3018,9 @@ function PreviewDialog({
copiedId,
session,
profile,
+ apimartKey,
+ apimartPrice,
+ apimartPriceMeta,
favorite,
favoriteBusy,
onClose,
@@ -2782,6 +3028,7 @@ function PreviewDialog({
onToggleFavorite,
onAuthRequired,
onBillingRequired,
+ onApiKeySettings,
onProfileChange
}) {
const t = copy[language];
@@ -2790,8 +3037,16 @@ function PreviewDialog({
const [generationState, setGenerationState] = useState({
status: 'idle',
image: '',
- message: ''
+ message: '',
+ progress: 0,
+ taskId: '',
+ mode: '',
+ cost: null,
+ expiresAt: null
});
+ const pollControllerRef = useRef(null);
+ const activeCaseRef = useRef(null);
+ activeCaseRef.current = preview?.type === 'case' ? preview.item.id : null;
useBodyScrollLock(Boolean(preview));
useEffect(() => {
@@ -2808,21 +3063,170 @@ function PreviewDialog({
}, [preview, onClose]);
useEffect(() => {
- if (preview?.type !== 'case') return;
+ pollControllerRef.current?.abort();
+ pollControllerRef.current = null;
+ if (preview?.type !== 'case') return undefined;
+
+ const caseId = preview.item.id;
+ let controller = null;
const savedGeneration = getSavedGeneration(preview.item.id);
- setEditablePrompt(preview.item.prompt || '');
- setGenerationState(
- savedGeneration
- ? {
- status: 'saved',
- image: savedGeneration.image,
- message: '',
- prompt: savedGeneration.prompt || preview.item.prompt || '',
- savedAt: savedGeneration.savedAt || ''
- }
- : { status: 'idle', image: '', message: '', prompt: '', savedAt: '' }
- );
- }, [preview]);
+ const pendingGeneration = getPendingGeneration(caseId);
+ setEditablePrompt(pendingGeneration?.prompt || savedGeneration?.prompt || preview.item.prompt || '');
+
+ if (pendingGeneration) {
+ setGenerationState({
+ status: 'generating',
+ image: '',
+ message: '',
+ progress: Number(pendingGeneration.progress || 0),
+ prompt: pendingGeneration.prompt || preview.item.prompt || '',
+ taskId: pendingGeneration.taskId,
+ mode: pendingGeneration.mode,
+ cost: null,
+ expiresAt: null
+ });
+ controller = new AbortController();
+ pollControllerRef.current = controller;
+ void pollPendingGeneration(caseId, pendingGeneration, controller);
+ } else if (savedGeneration) {
+ setGenerationState({
+ status: 'saved',
+ image: savedGeneration.image,
+ message: '',
+ progress: 100,
+ prompt: savedGeneration.prompt || preview.item.prompt || '',
+ savedAt: savedGeneration.savedAt || '',
+ taskId: savedGeneration.taskId || '',
+ mode: savedGeneration.mode || '',
+ cost: savedGeneration.cost ?? null,
+ expiresAt: savedGeneration.expiresAt || null
+ });
+ } else {
+ setGenerationState({
+ status: 'idle',
+ image: '',
+ message: '',
+ progress: 0,
+ prompt: '',
+ savedAt: '',
+ taskId: '',
+ mode: '',
+ cost: null,
+ expiresAt: null
+ });
+ }
+
+ return () => {
+ controller?.abort();
+ pollControllerRef.current?.abort();
+ };
+ }, [preview?.type, preview?.item?.id, apimartKey, session?.access_token, session?.user?.id, language]);
+
+ function updateActiveGeneration(caseId, controller, nextState) {
+ if (activeCaseRef.current !== caseId || controller?.signal?.aborted) return;
+ setGenerationState((current) => (
+ typeof nextState === 'function' ? nextState(current) : nextState
+ ));
+ }
+
+ async function pollPendingGeneration(caseId, pending, controller) {
+ if (pending.mode === 'personal' && !apimartKey) {
+ updateActiveGeneration(caseId, controller, (current) => ({
+ ...current,
+ status: 'paused',
+ message: t.apimartPendingNeedsKey
+ }));
+ return;
+ }
+ if (pending.mode === 'platform' && (!session?.access_token || (pending.userId && pending.userId !== session?.user?.id))) {
+ updateActiveGeneration(caseId, controller, (current) => ({
+ ...current,
+ status: 'paused',
+ message: t.apimartPendingNeedsLogin
+ }));
+ return;
+ }
+
+ updateActiveGeneration(caseId, controller, (current) => ({
+ ...current,
+ status: 'generating',
+ message: '',
+ taskId: pending.taskId,
+ mode: pending.mode,
+ prompt: pending.prompt || current.prompt
+ }));
+
+ const fetchWithSignal = (url, options = {}) => fetch(url, { ...options, signal: controller.signal });
+ try {
+ const task = await pollApimartTask(async () => {
+ const nextTask = pending.mode === 'personal'
+ ? await fetchPersonalTask(pending.taskId, apimartKey, language, fetchWithSignal)
+ : await fetchPlatformTask(pending.taskId, session.access_token, language, fetchWithSignal);
+ if (nextTask?.user) onProfileChange(nextTask.user);
+ return nextTask;
+ }, {
+ signal: controller.signal,
+ onProgress: (nextTask) => {
+ const progress = Math.max(0, Math.min(100, Math.round(Number(nextTask.progress || 0))));
+ savePendingGeneration(caseId, { ...pending, progress, updatedAt: new Date().toISOString() });
+ updateActiveGeneration(caseId, controller, (current) => ({
+ ...current,
+ status: 'generating',
+ progress,
+ taskId: pending.taskId,
+ mode: pending.mode,
+ message: ''
+ }));
+ }
+ });
+
+ if (controller.signal.aborted) return;
+ if (task.status === 'completed' && task.image) {
+ const savedAt = new Date().toISOString();
+ const result = {
+ image: task.image,
+ prompt: pending.prompt,
+ savedAt,
+ taskId: pending.taskId,
+ mode: pending.mode,
+ expiresAt: task.expiresAt || null,
+ cost: task.cost ?? null
+ };
+ saveGeneratedTest(caseId, result);
+ clearPendingGeneration(caseId);
+ updateActiveGeneration(caseId, controller, {
+ status: 'success',
+ message: '',
+ progress: 100,
+ ...result
+ });
+ return;
+ }
+
+ clearPendingGeneration(caseId);
+ const code = task.status === 'failed' ? apimartTaskErrorCode(task) : 'APIMART_INVALID_RESPONSE';
+ updateActiveGeneration(caseId, controller, {
+ status: 'error',
+ image: '',
+ message: generationErrorMessage(code, language),
+ progress: Number(task.progress || 0),
+ prompt: pending.prompt,
+ taskId: pending.taskId,
+ mode: pending.mode,
+ cost: task.cost ?? null,
+ expiresAt: null
+ });
+ } catch (error) {
+ if (error?.code === 'APIMART_POLL_ABORTED' || error?.name === 'AbortError' || controller.signal.aborted) return;
+ updateActiveGeneration(caseId, controller, (current) => ({
+ ...current,
+ status: error?.code === 'APIMART_TASK_TIMEOUT' ? 'timeout' : 'error',
+ message: generationErrorMessage(error?.code || error?.message, language),
+ taskId: pending.taskId,
+ mode: pending.mode
+ }));
+ }
+ }
if (!preview) return null;
@@ -2848,74 +3252,120 @@ function PreviewDialog({
: [...new Set([...(item.styles || []), ...(item.scenes || [])])].slice(0, 8);
const guidance = listFor(item.guidance, language);
const pitfalls = listFor(item.pitfalls, language);
- const isGenerating = generationState.status === 'generating';
+ const isGenerating = generationState.status === 'submitting' || generationState.status === 'generating';
const generatedImage = !isTemplate ? generationState.image : '';
+ const hasPersonalKey = Boolean(apimartKey);
const isSignedIn = Boolean(session?.access_token);
const creditBalance = Number(profile?.creditBalance || 0);
const isOutOfCredits = isSignedIn
&& creditBalance <= 0
&& (profile?.isSuperAdmin || Boolean(profile?.freeUsed));
const generationLocked = isGenerating;
- const quotaText = isSignedIn ? getGenerationQuotaText(profile, language) : t.authRequired;
+ const pendingGeneration = !isTemplate ? getPendingGeneration(item.id) : null;
+ const activeTaskMode = pendingGeneration?.mode
+ || (['submitting', 'generating', 'timeout', 'paused'].includes(generationState.status) ? generationState.mode : '');
+ const generationMode = activeTaskMode || (hasPersonalKey ? 'personal' : 'platform');
+ const quotaText = generationMode === 'personal'
+ ? hasPersonalKey
+ ? t.apimartPersonalMode(maskApimartKey(apimartKey), formatApimartPrice(apimartPrice))
+ : t.apimartPendingNeedsKey
+ : isSignedIn
+ ? `${t.apimartPlatformMode} · ${getGenerationQuotaText(profile, language)}`
+ : t.apimartAnonymousChoice;
+ const generationButtonLabel = isGenerating
+ ? t.generating
+ : pendingGeneration
+ ? t.apimartContinueChecking
+ : !hasPersonalKey && !isSignedIn
+ ? t.apimartConfigureKey
+ : !hasPersonalKey && isOutOfCredits
+ ? t.buyCredits
+ : t.generateImage;
async function handleGenerate() {
if (isTemplate || isGenerating) return;
- if (!isSignedIn) {
- onAuthRequired();
- setGenerationState({ status: 'idle', image: generatedImage, message: '' });
+ const pending = getPendingGeneration(item.id);
+ if (pending) {
+ pollControllerRef.current?.abort();
+ const controller = new AbortController();
+ pollControllerRef.current = controller;
+ await pollPendingGeneration(item.id, pending, controller);
+ return;
+ }
+ if (!hasPersonalKey && !isSignedIn) {
+ onApiKeySettings();
return;
}
const prompt = editablePrompt.trim();
- if (!prompt || prompt.length > 6000) {
+ if (!prompt || prompt.length > APIMART_MAX_PROMPT_LENGTH) {
setGenerationState({ status: 'error', image: '', message: t.promptRequired });
return;
}
- if (isOutOfCredits) {
+ if (!hasPersonalKey && isOutOfCredits) {
onBillingRequired();
- setGenerationState({ status: 'idle', image: generatedImage, message: t.creditsRequired });
+ setGenerationState((current) => ({ ...current, status: 'idle', message: t.creditsRequired }));
return;
}
- setGenerationState({ status: 'generating', image: '', message: '' });
+ const mode = hasPersonalKey ? 'personal' : 'platform';
+ setGenerationState({
+ status: 'submitting',
+ image: '',
+ message: '',
+ progress: 0,
+ prompt,
+ taskId: '',
+ mode,
+ cost: null,
+ expiresAt: null
+ });
try {
- const response = await fetch('/api/generate-image', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- ...getAuthHeaders(session)
- },
- body: JSON.stringify({
- caseId: item.id,
- prompt
- })
- });
- const payload = await response.json().catch(() => ({}));
-
- if (!response.ok || !payload.ok || !payload.image) {
- if (payload.user) onProfileChange(payload.user);
- if (payload.error === 'AUTH_REQUIRED' || payload.loginRequired) {
+ const submitted = mode === 'personal'
+ ? await submitPersonalGeneration(prompt, apimartKey, language)
+ : await submitPlatformGeneration({
+ caseId: item.id,
+ prompt,
+ language,
+ accessToken: session.access_token
+ });
+ if (submitted.user) onProfileChange(submitted.user);
+ const pendingEntry = {
+ taskId: submitted.taskId,
+ mode,
+ prompt,
+ userId: mode === 'platform' ? session.user?.id || '' : '',
+ createdAt: new Date().toISOString(),
+ progress: 0
+ };
+ savePendingGeneration(item.id, pendingEntry);
+
+ if (activeCaseRef.current === item.id) {
+ setGenerationState((current) => ({
+ ...current,
+ status: 'generating',
+ taskId: submitted.taskId,
+ mode
+ }));
+ const controller = new AbortController();
+ pollControllerRef.current = controller;
+ await pollPendingGeneration(item.id, pendingEntry, controller);
+ }
+ } catch (error) {
+ if (error?.user) onProfileChange(error.user);
+ if (error?.code === 'AUTH_REQUIRED') {
+ if (activeCaseRef.current === item.id) {
onAuthRequired();
- setGenerationState({ status: 'idle', image: generatedImage, message: '' });
- return;
}
- throw new Error(payload.error || 'GENERATION_FAILED');
+ return;
+ }
+ if (activeCaseRef.current === item.id) {
+ setGenerationState((current) => ({
+ ...current,
+ status: 'error',
+ message: generationErrorMessage(error?.code || error?.message, language)
+ }));
}
-
- const savedAt = new Date().toISOString();
- saveGeneratedTest(item.id, {
- image: payload.image,
- prompt,
- savedAt
- });
- if (payload.user) onProfileChange(payload.user);
- setGenerationState({ status: 'success', image: payload.image, message: '', prompt, savedAt });
- } catch (error) {
- setGenerationState({
- status: 'error',
- image: '',
- message: generationErrorMessage(error.message, language)
- });
}
}
@@ -2993,7 +3443,7 @@ function PreviewDialog({
{!isTemplate ? (
<button type="button" onClick={handleGenerate} disabled={generationLocked}>
{isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}
- {isGenerating ? t.generating : isOutOfCredits ? t.buyCredits : isSignedIn ? t.generateTest : t.signInToGenerate}
+ {generationButtonLabel}
</button>
) : null}
<a href={primaryLink} target="_blank" rel="noreferrer">
@@ -3023,20 +3473,60 @@ function PreviewDialog({
className="promptEditor"
value={editablePrompt}
onChange={(event) => setEditablePrompt(event.target.value)}
- maxLength={6000}
+ maxLength={APIMART_MAX_PROMPT_LENGTH}
/>
)}
</div>
{!isTemplate ? (
<div className="generationPanel">
- <div className={cx('generationQuota', (!isSignedIn || isOutOfCredits) && 'used')}>
- {quotaText}
+ <div className="generationModeRow">
+ <div className={cx('generationQuota', generationMode === 'platform' && (!isSignedIn || isOutOfCredits) && 'used')}>
+ {generationMode === 'personal' ? <KeyRound size={14} /> : <Coins size={14} />}
+ {quotaText}
+ </div>
+ <button className="generationSettingsButton" type="button" onClick={onApiKeySettings} disabled={generationLocked}>
+ <Settings size={15} />
+ {hasPersonalKey ? t.apimartManageKey : t.apimartConfigureKey}
+ </button>
</div>
- <button type="button" onClick={handleGenerate} disabled={generationLocked}>
- {isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}
- {isGenerating ? t.generating : isOutOfCredits ? t.buyCredits : isSignedIn ? t.generateImage : t.signInToGenerate}
- </button>
- {generationState.status === 'error' ? (
+ <p className="generationPriceNote">{t.apimartPriceNote(formatApimartPrice(apimartPrice))}</p>
+ {apimartPriceMeta?.stale ? (
+ <p className="generationFallbackNote">{t.apimartPriceFallback(apimartPriceMeta.snapshotDate || APIMART_PRICE_SNAPSHOT_DATE)}</p>
+ ) : null}
+ {isGenerating && generationState.taskId ? (
+ <div className="generationProgress" aria-live="polite">
+ <div>
+ <span>{t.apimartProgress(generationState.progress || 0)}</span>
+ <strong>{generationState.progress || 0}%</strong>
+ </div>
+ <progress value={generationState.progress || 0} max="100" />
+ </div>
+ ) : null}
+ <div className="generationButtons">
+ <button className="generationPrimaryButton" type="button" onClick={handleGenerate} disabled={generationLocked}>
+ {isGenerating ? <LoaderCircle className="spinIcon" size={17} /> : <ImageIcon size={17} />}
+ {generationButtonLabel}
+ </button>
+ {!hasPersonalKey && !isSignedIn ? (
+ <button className="generationSecondaryButton" type="button" onClick={onAuthRequired} disabled={generationLocked}>
+ <LogIn size={17} />
+ {t.usePlatformCredits}
+ </button>
+ ) : null}
+ </div>
+ {generationState.taskId ? (
+ <div className="generationTaskId">
+ <span>{t.apimartTaskId}</span>
+ <code>{generationState.taskId}</code>
+ </div>
+ ) : null}
+ {generationState.cost != null ? (
+ <p className="generationResultMeta">{t.apimartActualCost(formatApimartPrice(generationState.cost))}</p>
+ ) : null}
+ {generationState.expiresAt ? (
+ <p className="generationResultMeta">{t.apimartExpiresAt(formatApimartExpiry(generationState.expiresAt, language))}</p>
+ ) : null}
+ {['error', 'timeout', 'paused'].includes(generationState.status) ? (
<p className="generationMessage">{generationState.message}</p>
) : null}
</div>
@@ -3113,12 +3603,21 @@ function App() {
const [billingNotice, setBillingNotice] = useState('');
const [billingReturnOrderId, setBillingReturnOrderId] = useState('');
const alipayReturnHandledRef = useRef('');
+ const [apimartKey, setApimartKey] = useState(() => getStoredApimartKey());
+ const [apiKeyOpen, setApiKeyOpen] = useState(false);
+ const [apimartPriceMeta, setApimartPriceMeta] = useState({
+ prices: { '1k': APIMART_DEFAULT_PRICE_USD },
+ stale: true,
+ snapshotDate: APIMART_PRICE_SNAPSHOT_DATE
+ });
const { copiedId, copyPrompt, copyText } = useCopy();
const repoUrl = siteData?.repository || fallbackRepoUrl;
const t = copy[language];
+ const apimartPrice = Number(apimartPriceMeta?.prices?.['1k']) || APIMART_DEFAULT_PRICE_USD;
useEffect(() => {
let cancelled = false;
+ cleanupExpiredGeneratedTests();
Promise.all([
fetch('/cases.json').then((response) => response.json()),
fetch('/style-library.json').then((response) => response.json())
@@ -3134,6 +3633,31 @@ function App() {
};
}, []);
+ useEffect(() => {
+ let cancelled = false;
+ fetch('/api/apimart/pricing', { headers: { Accept: 'application/json' } })
+ .then(async (response) => {
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok || !payload?.ok) throw new Error('APIMART_PRICING_FAILED');
+ return payload;
+ })
+ .then((payload) => {
+ if (!cancelled) setApimartPriceMeta(payload);
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setApimartPriceMeta({
+ prices: { '1k': APIMART_DEFAULT_PRICE_USD },
+ stale: true,
+ snapshotDate: APIMART_PRICE_SNAPSHOT_DATE
+ });
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
useEffect(() => {
localStorage.setItem('language', language);
document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en';
@@ -3663,10 +4187,7 @@ function App() {
language={language}
onCopy={copyPrompt}
onOpen={(item) => setPreview({ type: 'case', item })}
- onGenerate={(item) => {
- setPreview({ type: 'case', item });
- if (!session?.access_token) openAuth();
- }}
+ onGenerate={(item) => setPreview({ type: 'case', item })}
onToggleFavorite={handleToggleFavorite}
styleLibrary={styleLibrary}
key={caseItem.id}
@@ -3695,6 +4216,9 @@ function App() {
copiedId={copiedId}
session={session}
profile={profile}
+ apimartKey={apimartKey}
+ apimartPrice={apimartPrice}
+ apimartPriceMeta={apimartPriceMeta}
favorite={preview?.type === 'case' ? favoriteCaseIds.has(preview.item.id) : false}
favoriteBusy={preview?.type === 'case' && favoriteBusyId === preview.item.id}
onClose={() => setPreview(null)}
@@ -3705,6 +4229,7 @@ function App() {
setBillingNotice(t.creditsRequired);
setBillingOpen(true);
}}
+ onApiKeySettings={() => setApiKeyOpen(true)}
onProfileChange={handleProfileChange}
/>
<AuthModal
@@ -3724,9 +4249,12 @@ function App() {
casesById={casesById}
favoriteRows={favoriteRows}
initialSection={accountInitialSection}
+ apimartKey={apimartKey}
+ apimartPrice={apimartPrice}
onClose={handleCloseAccount}
onProfileChange={handleProfileChange}
onOpenCase={handleOpenCaseFromAccount}
+ onApiKeySettings={() => setApiKeyOpen(true)}
onBilling={() => {
setAccountOpen(false);
setBillingNotice('');
@@ -3753,6 +4281,16 @@ function App() {
onProfileChange={handleProfileChange}
onOpenCase={handleOpenCaseFromAccount}
/>
+ <ApiKeyModal
+ open={apiKeyOpen}
+ language={language}
+ apiKey={apimartKey}
+ price={apimartPrice}
+ priceMeta={apimartPriceMeta}
+ onClose={() => setApiKeyOpen(false)}
+ onSaved={setApimartKey}
+ onCleared={() => setApimartKey('')}
+ />
</main>
);
}
diff --git a/src/styles.css b/src/styles.css
index 0d97729..a6027ce 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1444,6 +1444,7 @@ button {
display: grid;
grid-template-columns: minmax(0, 1.08fr) minmax(360px, 0.92fr);
width: min(1240px, 100%);
+ height: min(880px, 92vh);
max-height: min(880px, 92vh);
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.16);
@@ -1557,6 +1558,8 @@ button {
}
.previewContent {
+ min-width: 0;
+ min-height: 0;
-webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
overflow: auto;
@@ -1749,6 +1752,7 @@ button {
.generationQuota {
display: inline-flex;
align-items: center;
+ gap: 7px;
width: fit-content;
min-height: 30px;
border: 1px solid rgba(120, 255, 185, 0.24);
@@ -1778,6 +1782,119 @@ button {
font-weight: 900;
}
+.generationModeRow {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 10px;
+}
+
+.generationModeRow .generationQuota {
+ width: auto;
+ max-width: 100%;
+ min-height: 34px;
+ border-radius: 8px;
+ line-height: 1.45;
+}
+
+.generationPanel .generationSettingsButton {
+ flex: 0 0 auto;
+ min-height: 34px;
+ border-color: rgba(103, 232, 249, 0.2);
+ padding: 0 10px;
+ background: rgba(103, 232, 249, 0.08);
+ color: #c9f8ff;
+ font-size: 12px;
+}
+
+.generationPriceNote,
+.generationFallbackNote,
+.generationResultMeta {
+ margin: 0;
+ color: #aebcd0;
+ font-size: 12px;
+ line-height: 1.55;
+}
+
+.generationFallbackNote {
+ color: #ffe1a8;
+}
+
+.generationProgress {
+ display: grid;
+ gap: 8px;
+}
+
+.generationProgress div {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ color: #d8ffe4;
+ font-size: 12px;
+ font-weight: 850;
+}
+
+.generationProgress progress {
+ width: 100%;
+ height: 7px;
+ overflow: hidden;
+ border: 0;
+ border-radius: 999px;
+ appearance: none;
+ background: rgba(255, 255, 255, 0.1);
+}
+
+.generationProgress progress::-webkit-progress-bar {
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.1);
+}
+
+.generationProgress progress::-webkit-progress-value,
+.generationProgress progress::-moz-progress-bar {
+ border-radius: 999px;
+ background: linear-gradient(90deg, #42e6ff, #78ffb9);
+}
+
+.generationButtons {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 9px;
+}
+
+.generationPanel .generationSecondaryButton {
+ border-color: rgba(103, 232, 249, 0.24);
+ background: rgba(103, 232, 249, 0.08);
+ color: #d8fbff;
+}
+
+.generationTaskId {
+ display: grid;
+ gap: 5px;
+ min-width: 0;
+ border-top: 1px solid rgba(255, 255, 255, 0.09);
+ padding-top: 10px;
+}
+
+.generationTaskId span {
+ color: #8eeeff;
+ font-size: 11px;
+ font-weight: 900;
+ text-transform: uppercase;
+}
+
+.generationTaskId code {
+ overflow: hidden;
+ color: #dfeaff;
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.generationResultMeta {
+ color: #c8ffb8;
+}
+
.generationMessage {
margin: 0;
color: #ffd4a8;
@@ -1850,6 +1967,7 @@ button {
}
.authDialog,
+.apiKeyDialog,
.adminDialog,
.billingDialog {
position: relative;
@@ -1871,6 +1989,15 @@ button {
padding: 30px;
}
+.apiKeyOverlay {
+ z-index: 95;
+}
+
+.apiKeyDialog {
+ width: min(100%, 620px);
+ padding: 26px;
+}
+
.authIcon {
display: grid;
width: 54px;
@@ -1883,6 +2010,7 @@ button {
}
.authDialog h2,
+.apiKeyDialog h2,
.adminDialog h2,
.accountDialog h2 {
margin: 18px 48px 10px 0;
@@ -1893,6 +2021,7 @@ button {
}
.authDialog p,
+.apiKeyDialog p,
.adminDialog p,
.accountDialog p {
margin: 0;
@@ -2001,6 +2130,144 @@ button {
color: #ffc7c7;
}
+.apiKeyHeading {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ align-items: start;
+ gap: 16px;
+}
+
+.apiKeyHeading h2 {
+ margin-top: 10px;
+}
+
+.apiKeyForm {
+ display: grid;
+ gap: 11px;
+ margin-top: 22px;
+}
+
+.apiKeyForm > label {
+ color: #8eeeff;
+ font-size: 12px;
+ font-weight: 900;
+ text-transform: uppercase;
+}
+
+.apiKeyInputRow {
+ position: relative;
+}
+
+.apiKeyInputRow input {
+ width: 100%;
+ min-height: 46px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 8px;
+ outline: 0;
+ padding: 0 48px 0 12px;
+ background: rgba(3, 7, 15, 0.72);
+ color: #ffffff;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+}
+
+.apiKeyInputRow input:focus {
+ border-color: rgba(103, 232, 249, 0.72);
+ box-shadow: 0 0 0 3px rgba(103, 232, 249, 0.1);
+}
+
+.apiKeyVisibility {
+ position: absolute;
+ top: 5px;
+ right: 5px;
+ display: grid;
+ width: 36px;
+ height: 36px;
+ border: 0;
+ border-radius: 7px;
+ background: rgba(255, 255, 255, 0.07);
+ color: #c9f8ff;
+ place-items: center;
+}
+
+.apiKeyMask {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ width: fit-content;
+ border-radius: 999px;
+ padding: 6px 9px;
+ background: rgba(120, 255, 185, 0.09);
+ color: #c8ffb8;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 12px;
+ font-weight: 850;
+}
+
+.apiKeyDialog .apiKeyLocalNote {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ color: #c9f8ff;
+ font-size: 12px;
+}
+
+.apiKeyLocalNote svg {
+ flex: 0 0 auto;
+ margin-top: 3px;
+}
+
+.apiKeyDialog .apiKeyPriceNote,
+.apiKeyDialog .apiKeyFallback {
+ color: #aebcd0;
+ font-size: 12px;
+}
+
+.apiKeyDialog .apiKeyFallback {
+ color: #ffe1a8;
+}
+
+.apiKeyActions,
+.apiKeyLinks {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 9px;
+}
+
+.apiKeyActions button,
+.apiKeyLinks a {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 42px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 8px;
+ padding: 0 13px;
+ color: #ffffff;
+ font-weight: 900;
+}
+
+.apiKeyActions .apiKeySave {
+ border-color: rgba(120, 255, 185, 0.34);
+ background: linear-gradient(135deg, rgba(66, 230, 255, 0.2), rgba(120, 255, 185, 0.16));
+}
+
+.apiKeyActions .apiKeyClear {
+ background: rgba(255, 112, 112, 0.08);
+ color: #ffc7c7;
+}
+
+.apiKeyLinks {
+ margin-top: 16px;
+}
+
+.apiKeyLinks a {
+ min-height: 36px;
+ background: rgba(255, 255, 255, 0.055);
+ color: #c9f8ff;
+ font-size: 12px;
+}
+
.adminDialog {
width: min(1180px, 100%);
padding: 24px;
@@ -2672,6 +2939,56 @@ button {
gap: 16px;
}
+.apiKeySettingsCard {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 13px;
+ margin-top: 16px;
+ border: 1px solid rgba(103, 232, 249, 0.16);
+ border-radius: 8px;
+ padding: 14px;
+ background: rgba(103, 232, 249, 0.055);
+}
+
+.apiKeySettingsIcon {
+ display: grid;
+ width: 42px;
+ height: 42px;
+ border-radius: 8px;
+ background: rgba(103, 232, 249, 0.1);
+ color: #9eeeff;
+ place-items: center;
+}
+
+.apiKeySettingsCard h3 {
+ margin: 0 0 4px;
+ color: #eaf3ff;
+ font-size: 15px;
+ letter-spacing: 0;
+}
+
+.accountDialog .apiKeySettingsCard p {
+ color: #9eb0c8;
+ font-size: 12px;
+ line-height: 1.5;
+}
+
+.apiKeySettingsCard button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ min-height: 38px;
+ border: 1px solid rgba(103, 232, 249, 0.24);
+ border-radius: 8px;
+ padding: 0 11px;
+ background: rgba(103, 232, 249, 0.08);
+ color: #d8fbff;
+ font-size: 12px;
+ font-weight: 900;
+}
+
.accountForm,
.accountOverview {
padding: 14px;
@@ -3080,6 +3397,7 @@ button {
.previewDialog {
grid-template-columns: 1fr;
+ height: auto;
overflow: auto;
}
@@ -3099,6 +3417,14 @@ button {
grid-template-columns: 1fr;
}
+ .apiKeySettingsCard {
+ grid-template-columns: auto minmax(0, 1fr);
+ }
+
+ .apiKeySettingsCard button {
+ grid-column: 1 / -1;
+ }
+
.adminMetricGrid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@@ -3336,6 +3662,7 @@ button {
}
.authDialog,
+ .apiKeyDialog,
.adminDialog,
.accountDialog,
.billingDialog {
@@ -3343,12 +3670,35 @@ button {
}
.authDialog,
+ .apiKeyDialog,
.adminDialog,
.accountDialog,
.billingDialog {
padding: 20px 16px;
}
+ .apiKeyHeading {
+ grid-template-columns: 1fr;
+ }
+
+ .apiKeyHeading h2 {
+ margin-top: 14px;
+ }
+
+ .apiKeyActions button,
+ .apiKeyLinks a,
+ .generationButtons button {
+ width: 100%;
+ }
+
+ .generationModeRow {
+ display: grid;
+ }
+
+ .generationPanel .generationSettingsButton {
+ width: 100%;
+ }
+
.adminHeader {
flex-direction: column;
}
diff --git a/supabase/migrations/20260828090000_apimart_generation_tasks.sql b/supabase/migrations/20260828090000_apimart_generation_tasks.sql
new file mode 100644
index 0000000..84bd02f
--- /dev/null
+++ b/supabase/migrations/20260828090000_apimart_generation_tasks.sql
@@ -0,0 +1,21 @@
+alter table public.generation_reservations
+ add column if not exists provider text not null default 'legacy',
+ add column if not exists provider_task_id text,
+ add column if not exists provider_cost_usd numeric(12, 6),
+ add column if not exists provider_result_url text,
+ add column if not exists provider_result_expires_at timestamptz;
+
+create unique index if not exists generation_reservations_provider_task_idx
+ on public.generation_reservations (provider, provider_task_id)
+ where provider_task_id is not null;
+
+create index if not exists generation_reservations_pending_provider_idx
+ on public.generation_reservations (provider, created_at)
+ where status = 'pending';
+
+alter table public.generation_reservations
+ drop constraint if exists generation_reservations_provider_cost_nonnegative;
+
+alter table public.generation_reservations
+ add constraint generation_reservations_provider_cost_nonnegative
+ check (provider_cost_usd is null or provider_cost_usd >= 0);