diff --git a/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-group-option.test.tsx b/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-group-option.test.tsx new file mode 100644 index 0000000..d3dd047 --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-group-option.test.tsx @@ -0,0 +1,72 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { expect, it, vi } from 'vitest' + +import { StudioGroupOption } from '../studio-group-option' +import { STUDIO_KEY_NAME, type StudioGroup } from '../studio-key' + +const GROUP: StudioGroup = { + name: 'NanoBanana-官转', + desc: '', + ratio: 2, + imageModels: ['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8'], +} + +it('names the first six image models and counts the rest', () => { + render( + {}} + /> + ) + + expect(screen.getByText('8 image models')).toBeInTheDocument() + expect( + screen.getByText('m1, m2, m3, m4, m5, m6 and 2 more') + ).toBeInTheDocument() +}) + +it('shows the key to create when the group has no key to choose, and ticks the row from it', async () => { + const onChange = vi.fn() + render( + + ) + + expect(screen.getByText('1 image model')).toBeInTheDocument() + expect(screen.queryByRole('combobox')).toBeNull() + await userEvent.click(screen.getByText(`Create a "${STUDIO_KEY_NAME}" key`)) + expect(onChange).toHaveBeenCalledWith({ checked: true, keyId: 'new' }) +}) + +it('blocks ticking another group once the most groups are ticked', () => { + render( + {}} + /> + ) + + expect(screen.getByRole('checkbox', { name: GROUP.name })).toHaveAttribute( + 'aria-disabled', + 'true' + ) +}) diff --git a/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-key-link.test.tsx b/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-key-link.test.tsx new file mode 100644 index 0000000..432ddd4 --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-key-link.test.tsx @@ -0,0 +1,362 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + RouterProvider, +} from '@tanstack/react-router' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +import { api } from '@/lib/api' +import { useAuthStore } from '@/stores/auth-store' + +import { STUDIO_KEY_NAME, studioLinkSearchSchema } from '../studio-key' +import { StudioKeyLink } from '../studio-key-link' + +vi.mock('@/features/chat/hooks/use-chat-presets', () => ({ + useChatPresets: () => ({ + chatPresets: [ + { + id: '0', + name: 'Image Studio', + // Same origin as jsdom, so the final navigation is a fragment change. + url: `${window.location.origin}/#key={key}`, + type: 'web', + }, + ], + serverAddress: window.location.origin, + }), +})) + +type TestKey = { id: number; name: string; group: string } + +const STATE = 'AbCdEfGhIjKlMnOpQrSt_-' +// Live-like groups: no "default"; the cheapest one has text models only. +const USER_GROUPS = { + 'Claude Code': { desc: 'Text models', ratio: 0.5 }, + 'GPT-image特价': { desc: 'Image models', ratio: 1 }, + 'NanoBanana-官转': { desc: 'Gemini images', ratio: 2 }, +} +const PRICING = [ + { + model_name: 'gpt-4o-mini', + enable_groups: ['Claude Code'], + supported_endpoint_types: ['openai'], + }, + { + model_name: 'flux-dev', + enable_groups: ['GPT-image特价'], + supported_endpoint_types: ['image-generation'], + }, + { + model_name: 'gemini-3-pro-image-preview', + enable_groups: ['NanoBanana-官转'], + supported_endpoint_types: ['gemini'], + }, +] + +function apiKey(fields: TestKey) { + return { + key: `abcd**********${String(fields.id).padStart(4, '0')}`, + status: 1, + remain_quota: 0, + used_quota: 0, + unlimited_quota: true, + expired_time: -1, + created_time: 0, + accessed_time: 0, + model_limits_enabled: false, + ...fields, + } +} + +/** Fake console API: the key list grows when a key is created. */ +function serve(initial: TestKey[], userGroups: object = USER_GROUPS) { + const keys = initial.map(apiKey) + vi.spyOn(api, 'get').mockImplementation(async (url: string) => { + if (url.startsWith('/api/token/?')) { + const newestFirst = [...keys].sort((a, b) => b.id - a.id) + return { + data: { + success: true, + data: { items: newestFirst, total: keys.length }, + }, + } + } + if (url === '/api/user/self/groups') { + return { data: { success: true, data: userGroups } } + } + if (url === '/api/pricing') { + return { data: { success: true, data: PRICING } } + } + throw new Error(`unexpected GET ${url}`) + }) + return vi + .spyOn(api, 'post') + .mockImplementation(async (url: string, body?: unknown) => { + if (url === '/api/token/') { + const created = body as { name: string; group: string } + keys.push( + apiKey({ + id: 90 + keys.length, + name: created.name, + group: created.group, + }) + ) + return { data: { success: true, message: '' } } + } + if (url === '/api/token/batch/keys') { + const ids = (body as { ids: number[] }).ids + const revealed = Object.fromEntries(ids.map((id) => [id, `full${id}`])) + return { data: { success: true, data: { keys: revealed } } } + } + throw new Error(`unexpected POST ${url}`) + }) +} + +async function renderPage(path = '/chat2link?app=studio') { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }) + const root = createRootRoute() + const page = createRoute({ + getParentRoute: () => root, + path: 'chat2link', + validateSearch: studioLinkSearchSchema, + component: StudioKeyLink, + }) + const keys = createRoute({ + getParentRoute: () => root, + path: 'keys', + component: () => null, + }) + const router = createRouter({ + routeTree: root.addChildren([page, keys]), + history: createMemoryHistory({ initialEntries: [path] }), + }) + await router.load() + render( + + + + ) + return router +} + +const returnedTo = () => decodeURIComponent(window.location.hash) +const postedUrls = (post: ReturnType) => + post.mock.calls.map((call) => call[0]) + +beforeEach(() => { + window.history.replaceState(null, '', '/') + useAuthStore + .getState() + .auth.setUser({ id: 7, username: 'artist', role: 1, group: 'default' }) +}) + +afterEach(() => { + useAuthStore.getState().auth.setUser(null) + vi.restoreAllMocks() +}) + +it('returns the newest dedicated key of every group at once with the state, in one key request', async () => { + const post = serve([ + { id: 1, name: STUDIO_KEY_NAME, group: 'NanoBanana-官转' }, + { id: 2, name: STUDIO_KEY_NAME, group: 'GPT-image特价' }, + { id: 3, name: STUDIO_KEY_NAME, group: 'GPT-image特价' }, + { id: 4, name: 'newest', group: 'Claude Code' }, + ]) + await renderPage(`/chat2link?app=studio&state=${STATE}`) + + await waitFor(() => + expect(returnedTo()).toBe( + '#key=sk-full3&group=GPT-image特价' + + `&key=sk-full1&group=NanoBanana-官转&state=${STATE}` + ) + ) + expect(post.mock.calls).toEqual([['/api/token/batch/keys', { ids: [3, 1] }]]) + expect(screen.queryByRole('checkbox')).toBeNull() +}) + +it('never echoes a malformed state', async () => { + serve([{ id: 1, name: STUDIO_KEY_NAME, group: 'GPT-image特价' }]) + await renderPage('/chat2link?app=studio&state=short%26x%3D1') + + await waitFor(() => + expect(returnedTo()).toBe('#key=sk-full1&group=GPT-image特价') + ) +}) + +it('keeps the state and pick=1 when the console navigates here after sign-in', async () => { + serve([{ id: 1, name: STUDIO_KEY_NAME, group: 'GPT-image特价' }]) + const router = await renderPage('/keys') + await router.navigate({ + href: `/chat2link?app=studio&state=${STATE}&pick=1`, + replace: true, + }) + + await userEvent.click( + await screen.findByRole('button', { name: 'Return 1 key' }) + ) + await waitFor(() => + expect(returnedTo()).toBe( + `#key=sk-full1&group=GPT-image特价&state=${STATE}` + ) + ) +}) + +it('stops on the choices with pick=1 and ticks the groups that have a dedicated key', async () => { + const post = serve([ + { id: 1, name: STUDIO_KEY_NAME, group: 'NanoBanana-官转' }, + ]) + await renderPage(`/chat2link?app=studio&pick=1&state=${STATE}`) + + const nano = await screen.findByRole('checkbox', { name: 'NanoBanana-官转' }) + expect(nano).toHaveAttribute('aria-checked', 'true') + expect( + screen.getByRole('checkbox', { name: 'GPT-image特价' }) + ).toHaveAttribute('aria-checked', 'false') + expect(screen.getAllByRole('checkbox')).toHaveLength(2) + expect( + // The tests' i18next escapes interpolated quotes; the console does not. + screen.getByText( + /Not listed, as they have no image models: .*Claude Code.*Groups that already have/ + ) + ).toBeInTheDocument() + expect( + screen.getByRole('combobox', { name: 'Key for group NanoBanana-官转' }) + ).toHaveValue('1') + expect(post).not.toHaveBeenCalled() + + await userEvent.click(screen.getByRole('button', { name: 'Return 1 key' })) + await waitFor(() => + expect(returnedTo()).toBe( + `#key=sk-full1&group=NanoBanana-官转&state=${STATE}` + ) + ) + expect(postedUrls(post)).toEqual(['/api/token/batch/keys']) +}) + +it('creates nothing until the click, then creates a key only in the cheapest image group', async () => { + const post = serve([]) + await renderPage() + + const submit = await screen.findByRole('button', { + name: 'Return 1 new key', + }) + expect( + screen.getByRole('checkbox', { name: 'GPT-image特价' }) + ).toHaveAttribute('aria-checked', 'true') + expect( + screen.getByRole('checkbox', { name: 'NanoBanana-官转' }) + ).toHaveAttribute('aria-checked', 'false') + expect( + screen.getByText(/the group with the lowest ratio is ticked/) + ).toBeInTheDocument() + expect(post).not.toHaveBeenCalled() + + await userEvent.click(submit) + + await waitFor(() => + expect(returnedTo()).toBe('#key=sk-full90&group=GPT-image特价') + ) + expect(post.mock.calls).toEqual([ + [ + '/api/token/', + expect.objectContaining({ + name: STUDIO_KEY_NAME, + group: 'GPT-image特价', + unlimited_quota: true, + expired_time: -1, + model_limits_enabled: false, + }), + ], + ['/api/token/batch/keys', { ids: [90] }], + ]) +}) + +it('defaults a group with only other keys to a new key, creates keys only for new ones and reuses the key picked', async () => { + const post = serve([ + { id: 5, name: 'gemini', group: 'NanoBanana-官转' }, + { id: 6, name: 'claude', group: 'Claude Code' }, + ]) + await renderPage(`/chat2link?app=studio&state=${STATE}`) + + await userEvent.click( + await screen.findByRole('checkbox', { name: 'NanoBanana-官转' }) + ) + const choice = screen.getByRole('combobox', { + name: 'Key for group NanoBanana-官转', + }) + expect(choice).toHaveValue('new') + expect( + [...choice.querySelectorAll('option')].map((option) => option.textContent) + ).toEqual([ + `Create a "${STUDIO_KEY_NAME}" key`, + 'Use existing: gemini · …0005', + ]) + expect( + screen.getByRole('button', { name: 'Return 2 keys (2 new)' }) + ).toBeEnabled() + await userEvent.selectOptions(choice, '5') + await userEvent.click( + screen.getByRole('button', { name: 'Return 2 keys (1 new)' }) + ) + + await waitFor(() => + expect(returnedTo()).toBe( + '#key=sk-full92&group=GPT-image特价' + + `&key=sk-full5&group=NanoBanana-官转&state=${STATE}` + ) + ) + expect(postedUrls(post)).toEqual(['/api/token/', '/api/token/batch/keys']) + expect(post.mock.calls[0][1]).toMatchObject({ group: 'GPT-image特价' }) + expect(post.mock.calls[1][1]).toEqual({ ids: [92, 5] }) +}) + +it('keeps the return button disabled while no group is ticked', async () => { + serve([]) + await renderPage() + + await userEvent.click( + await screen.findByRole('checkbox', { name: 'GPT-image特价' }) + ) + expect( + screen.getByRole('button', { name: 'Select at least one group' }) + ).toBeDisabled() +}) + +it('toggles a group from anywhere on its row', async () => { + serve([]) + await renderPage() + + const nano = await screen.findByRole('checkbox', { name: 'NanoBanana-官转' }) + await userEvent.click(screen.getByText('gemini-3-pro-image-preview')) + expect(nano).toHaveAttribute('aria-checked', 'true') + expect( + screen.getByRole('button', { name: 'Return 2 keys (2 new)' }) + ).toBeEnabled() +}) + +it('explains when no group available to the user serves image models', async () => { + const post = serve([{ id: 1, name: 'claude', group: 'Claude Code' }], { + 'Claude Code': USER_GROUPS['Claude Code'], + }) + await renderPage() + + expect( + await screen.findByText('No group available to you serves image models') + ).toBeInTheDocument() + expect(screen.queryByRole('checkbox')).toBeNull() + expect(post).not.toHaveBeenCalled() +}) diff --git a/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-key.test.ts b/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-key.test.ts new file mode 100644 index 0000000..061cb59 --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/__tests__/studio-key.test.ts @@ -0,0 +1,321 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ +import { describe, expect, it } from 'vitest' + +import { apiKeySchema, type ApiKey } from '@/features/keys/types' + +import { + STUDIO_KEY_NAME, + imageModelsByGroup, + initialStudioChoices, + isStudioImageModel, + newestStudioKeyByGroup, + readStudioLinkSearch, + studioCandidateKeys, + studioImageGroups, + studioReturnUrl, + type StudioPricingModel, +} from '../studio-key' + +const NOW = 1_800_000_000 + +function model( + name: string, + groups: string[], + endpoints: string[] = ['openai'] +): StudioPricingModel { + return { + model_name: name, + enable_groups: groups, + supported_endpoint_types: endpoints, + } +} + +function key(fields: Partial & { id: number }): ApiKey { + return apiKeySchema.parse({ + name: `key-${fields.id}`, + key: 'abcd**********wxyz', + status: 1, + remain_quota: 0, + used_quota: 0, + unlimited_quota: true, + expired_time: -1, + created_time: 0, + accessed_time: 0, + group: '', + model_limits_enabled: false, + ...fields, + }) +} + +// Live-like groups: no "default", text models in one group, image models in +// three, one image model shared by two groups. +const PRICING = [ + model('gpt-4o-mini', ['Claude Code']), + model('flux-dev', ['GPT-image特价'], ['image-generation', 'openai']), + model( + 'gemini-3-pro-image-preview', + ['NanoBanana-官转', 'GPT-image特价'], + ['gemini', 'openai'] + ), + model('gpt-image-2', ['OpenAI-官转', 'GPT-image特价'], ['image-generation']), + model('veo-3-image-to-video', ['NanoBanana-官转'], ['openai-video']), +] +const USER_GROUPS = { + 'Claude Code': { desc: 'Text', ratio: 0.5 }, + 'NanoBanana-官转': { desc: 'Gemini', ratio: 2 }, + 'GPT-image特价': { desc: 'Images', ratio: 1 }, + 'OpenAI-官转': { desc: 'OpenAI', ratio: 1.5 }, + auto: { desc: 'Auto', ratio: 'auto' }, +} +const groups = studioImageGroups( + USER_GROUPS, + imageModelsByGroup(PRICING, Object.keys(USER_GROUPS)) +) + +describe('isStudioImageModel', () => { + it('accepts gateway image models and image-named models the gateway does not mark', () => { + expect( + isStudioImageModel(model('flux-dev', [], ['image-generation'])) + ).toBe(true) + expect( + isStudioImageModel(model('gemini-2.5-flash-image', [], ['gemini'])) + ).toBe(true) + expect( + isStudioImageModel(model('doubao-seedream-4-0', [], ['openai'])) + ).toBe(true) + }) + + it('rejects text, video, embedding and Midjourney models', () => { + expect(isStudioImageModel(model('gpt-4o-mini', []))).toBe(false) + expect( + isStudioImageModel(model('veo-3-image-to-video', [], ['openai-video'])) + ).toBe(false) + expect( + isStudioImageModel(model('image-embedding-v1', [], ['embeddings'])) + ).toBe(false) + expect(isStudioImageModel(model('mj_imagine', [], ['openai']))).toBe(false) + }) +}) + +describe('studioImageGroups', () => { + it('lists only groups that serve an image model, cheapest first, with their image models', () => { + expect( + groups.map((group) => [group.name, group.ratio, group.imageModels]) + ).toEqual([ + [ + 'GPT-image特价', + 1, + ['flux-dev', 'gemini-3-pro-image-preview', 'gpt-image-2'], + ], + ['OpenAI-官转', 1.5, ['gpt-image-2']], + ['NanoBanana-官转', 2, ['gemini-3-pro-image-preview']], + ]) + }) + + it('counts a model enabled for "all" in every group, as rc.52 pricing still keeps "all"', () => { + const everywhere = imageModelsByGroup( + [model('flux-dev', ['all'])], + ['Claude Code'] + ) + expect( + studioImageGroups( + { 'Claude Code': { desc: '', ratio: 3.5 } }, + everywhere + ).map((group) => group.imageModels) + ).toEqual([['flux-dev']]) + }) + + it('reads pricing already trimmed to the groups the viewer may use', () => { + // rc.52 drops the groups the viewer may not use from enable_groups. + const trimmed = [model('flux-dev', ['GPT-image特价'], ['image-generation'])] + expect( + studioImageGroups( + USER_GROUPS, + imageModelsByGroup(trimmed, Object.keys(USER_GROUPS)) + ).map((group) => group.name) + ).toEqual(['GPT-image特价']) + }) + + it('is empty when no group the user may use serves an image model', () => { + const textOnly = imageModelsByGroup(PRICING, ['Claude Code']) + expect( + studioImageGroups({ 'Claude Code': USER_GROUPS['Claude Code'] }, textOnly) + ).toEqual([]) + }) +}) + +describe('studioCandidateKeys', () => { + const candidates = (keys: ApiKey[], userGroup = 'default') => + studioCandidateKeys(keys, userGroup, groups, NOW).map((item) => item.id) + + it('keeps enabled keys in image groups in list order and drops the text group key', () => { + const keys = [ + key({ id: 3, group: 'Claude Code' }), + key({ id: 2, group: 'NanoBanana-官转' }), + key({ id: 1, group: 'GPT-image特价' }), + ] + expect(candidates(keys)).toEqual([2, 1]) + }) + + it('bills a key without a group in the user group', () => { + expect(candidates([key({ id: 1, group: '' })])).toEqual([]) + expect(candidates([key({ id: 1, group: '' })], 'GPT-image特价')).toEqual([ + 1, + ]) + }) + + it('drops disabled, expired and used-up keys', () => { + const keys = [ + key({ id: 1, group: 'GPT-image特价', status: 2 }), + key({ id: 2, group: 'GPT-image特价', expired_time: NOW - 1 }), + key({ + id: 3, + group: 'GPT-image特价', + unlimited_quota: false, + remain_quota: 0, + }), + key({ id: 4, group: 'GPT-image特价', expired_time: NOW + 60 }), + ] + expect(candidates(keys)).toEqual([4]) + }) + + it('drops a key whose model limits allow no image model of its group', () => { + const keys = [ + key({ + id: 1, + group: 'GPT-image特价', + model_limits_enabled: true, + model_limits: 'gpt-4o-mini', + }), + key({ + id: 2, + group: 'GPT-image特价', + model_limits_enabled: true, + model_limits: 'gpt-4o-mini, flux-dev', + }), + ] + expect(candidates(keys)).toEqual([2]) + }) +}) + +describe('newestStudioKeyByGroup', () => { + it('takes the newest dedicated key of each group and ignores other names', () => { + const keys = [ + key({ id: 4, name: 'mine', group: 'GPT-image特价' }), + key({ id: 2, name: STUDIO_KEY_NAME, group: 'GPT-image特价' }), + key({ id: 7, name: STUDIO_KEY_NAME, group: 'GPT-image特价' }), + key({ id: 5, name: STUDIO_KEY_NAME, group: 'NanoBanana-官转' }), + ] + const byGroup = newestStudioKeyByGroup(keys, 'default') + expect([...byGroup].map(([group, item]) => [group, item.id])).toEqual([ + ['GPT-image特价', 7], + ['NanoBanana-官转', 5], + ]) + }) + + it('files a dedicated key without a group under the user group', () => { + const keys = [key({ id: 1, name: STUDIO_KEY_NAME, group: '' })] + expect([...newestStudioKeyByGroup(keys, 'OpenAI-官转').keys()]).toEqual([ + 'OpenAI-官转', + ]) + }) +}) + +describe('initialStudioChoices', () => { + it('ticks the groups with a dedicated key and uses that key', () => { + const dedicated = new Map([ + ['NanoBanana-官转', key({ id: 5, name: STUDIO_KEY_NAME })], + ]) + expect(initialStudioChoices(groups, dedicated)).toEqual({ + 'GPT-image特价': { checked: false, keyId: 'new' }, + 'OpenAI-官转': { checked: false, keyId: 'new' }, + 'NanoBanana-官转': { checked: true, keyId: 5 }, + }) + }) + + it('ticks only the cheapest group, with a new key, when no group has a dedicated key', () => { + expect(initialStudioChoices(groups, new Map())).toEqual({ + 'GPT-image特价': { checked: true, keyId: 'new' }, + 'OpenAI-官转': { checked: false, keyId: 'new' }, + 'NanoBanana-官转': { checked: false, keyId: 'new' }, + }) + }) +}) + +describe('readStudioLinkSearch', () => { + const state = 'AbCdEfGhIjKlMnOpQrSt_-' + + it('keeps a well-formed state exactly as sent', () => { + expect(readStudioLinkSearch(`?app=studio&state=${state}`)).toEqual({ + state, + pick: false, + }) + }) + + it('keeps a state of digits only as the same string', () => { + const digits = '12345678901234567890' + expect(readStudioLinkSearch(`?app=studio&state=${digits}`).state).toBe( + digits + ) + }) + + it.each([ + ['missing', '?app=studio'], + ['too short', '?app=studio&state=AbCdEfGhIjKlMnO'], + ['too long', `?app=studio&state=${'a'.repeat(65)}`], + ['with other characters', '?app=studio&state=AbCdEfGhIjKlMnOp%2B%2F'], + ['encoded padding', '?app=studio&state=AbCdEfGhIjKlMnOpQrSt%3D%3D'], + ])('treats a state that is %s as no state', (_case, search) => { + expect(readStudioLinkSearch(search).state).toBeUndefined() + }) + + it('asks for the choice page only with pick=1', () => { + expect(readStudioLinkSearch('?app=studio&pick=1').pick).toBe(true) + expect(readStudioLinkSearch('?app=studio&pick=0').pick).toBe(false) + expect(readStudioLinkSearch('?app=studio&pick=true').pick).toBe(false) + expect(readStudioLinkSearch('?app=studio').pick).toBe(false) + }) +}) + +describe('studioReturnUrl', () => { + const preset = 'https://image.example.test/#key=sk-A' + + it('appends the first key group, then each further key with its group, then the state', () => { + expect( + studioReturnUrl( + preset, + [ + { key: 'sk-A', group: 'GPT-image特价' }, + { key: 'sk-B', group: 'NanoBanana-官转' }, + ], + 'AbCdEfGhIjKlMnOpQrSt_-' + ) + ).toBe( + 'https://image.example.test/#key=sk-A&group=GPT-image%E7%89%B9%E4%BB%B7' + + '&key=sk-B&group=NanoBanana-%E5%AE%98%E8%BD%AC' + + '&state=AbCdEfGhIjKlMnOpQrSt_-' + ) + }) + + it('sends no state when the request had none, like the single-key link of 0.3.2', () => { + expect(studioReturnUrl(preset, [{ key: 'sk-A', group: 'a b&c' }])).toBe( + 'https://image.example.test/#key=sk-A&group=a%20b%26c' + ) + }) + + it('starts a fragment when the preset has none, so nothing reaches a server', () => { + expect( + studioReturnUrl( + 'https://image.example.test/', + [{ key: 'sk-A', group: 'g' }], + 'AbCdEfGhIjKlMnOpQrSt_-' + ) + ).toBe('https://image.example.test/#group=g&state=AbCdEfGhIjKlMnOpQrSt_-') + }) +}) diff --git a/web/src/routes/_authenticated/-studio-key-link/i18n.ts b/web/src/routes/_authenticated/-studio-key-link/i18n.ts new file mode 100644 index 0000000..d03339f --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/i18n.ts @@ -0,0 +1,293 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ + +/* +Translations for the /chat2link?app=studio page. They are registered here +instead of in src/i18n/locales/*.json so the patch does not touch the large +locale files, which change in almost every upstream release. English is the +key itself, as everywhere else in the console; counts that read differently +in the singular have their own English key, as the console has no plurals. +*/ +import i18next from 'i18next' + +const translations: Record> = { + zhCN: { + 'Connecting to Image Studio...': '正在连接生图工作站...', + 'Connect Image Studio': '连接生图工作站', + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.': + '勾选要在生图工作站里用的分组,每个分组带回一把密钥。在那里生成的费用从这个账号扣除。', + Groups: '分组', + ', ': '、', + '"{{name}}"': '「{{name}}」', + '{{names}} and {{more}} more': '{{names}} 等 {{total}} 个', + '1 image model': '1 个图像模型', + '{{number}} image models': '{{number}} 个图像模型', + 'Create a "{{name}}" key': '新建一把「{{name}}」', + 'Use existing: {{name}} · …{{last4}}': '用已有:{{name}} · …{{last4}}', + 'Key for group {{group}}': '{{group}} 用哪把密钥', + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.': + '只列出有图像模型的分组。已有「{{name}}」密钥的分组已经勾上。', + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + '只列出有图像模型的分组。你还没有名为「{{name}}」的密钥,已经替你勾上倍率最低的分组。', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.': + '只列出有图像模型的分组({{groups}}没有图像模型,未列出)。已有「{{name}}」密钥的分组已经勾上。', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + '只列出有图像模型的分组({{groups}}没有图像模型,未列出)。你还没有名为「{{name}}」的密钥,已经替你勾上倍率最低的分组。', + 'At most {{number}} groups at a time.': '一次最多勾选 {{number}} 个分组。', + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.': + '新密钥名为「{{name}}」,不限额度、永不过期,点「带回」时才创建,可以在「API 密钥」页修改或删除。带回的密钥加进生图工作站已有的密钥里,不会替换它们。', + 'Select at least one group': '请至少勾选一个分组', + 'Returning...': '正在带回...', + 'Return 1 key': '带回 1 把密钥', + 'Return 1 new key': '带回 1 把密钥(其中新建 1 把)', + 'Return {{number}} keys': '带回 {{number}} 把密钥', + 'Return {{number}} keys ({{fresh}} new)': + '带回 {{number}} 把密钥(其中新建 {{fresh}} 把)', + 'Manage API keys': '管理 API 密钥', + 'No group available to you serves image models': + '你可用的分组里没有图像模型', + 'Ask the site administrator to open an image model group to your account.': + '请联系站点管理员,为你的账号开放有图像模型的分组。', + 'Could not load your keys, groups or model prices': + '读取密钥、分组或模型价格失败', + 'The key was created, but it could not be found. Check it on the API Keys page.': + '密钥已创建,但没有找到它。请到「API 密钥」页查看。', + }, + zhTW: { + 'Connecting to Image Studio...': '正在連接生圖工作站...', + 'Connect Image Studio': '連接生圖工作站', + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.': + '勾選要在生圖工作站裡用的分組,每個分組帶回一把金鑰。在那裡生成的費用從這個帳號扣除。', + Groups: '分組', + ', ': '、', + '"{{name}}"': '「{{name}}」', + '{{names}} and {{more}} more': '{{names}} 等 {{total}} 個', + '1 image model': '1 個圖像模型', + '{{number}} image models': '{{number}} 個圖像模型', + 'Create a "{{name}}" key': '建立一把「{{name}}」', + 'Use existing: {{name}} · …{{last4}}': '用已有:{{name}} · …{{last4}}', + 'Key for group {{group}}': '{{group}} 用哪把金鑰', + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.': + '只列出有圖像模型的分組。已有「{{name}}」金鑰的分組已經勾上。', + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + '只列出有圖像模型的分組。你還沒有名為「{{name}}」的金鑰,已經替你勾上倍率最低的分組。', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.': + '只列出有圖像模型的分組({{groups}}沒有圖像模型,未列出)。已有「{{name}}」金鑰的分組已經勾上。', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + '只列出有圖像模型的分組({{groups}}沒有圖像模型,未列出)。你還沒有名為「{{name}}」的金鑰,已經替你勾上倍率最低的分組。', + 'At most {{number}} groups at a time.': '一次最多勾選 {{number}} 個分組。', + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.': + '新金鑰名為「{{name}}」,不限額度、永不過期,點「帶回」時才建立,可以在「API 金鑰」頁修改或刪除。帶回的金鑰加進生圖工作站已有的金鑰裡,不會取代它們。', + 'Select at least one group': '請至少勾選一個分組', + 'Returning...': '正在帶回...', + 'Return 1 key': '帶回 1 把金鑰', + 'Return 1 new key': '帶回 1 把金鑰(其中新建 1 把)', + 'Return {{number}} keys': '帶回 {{number}} 把金鑰', + 'Return {{number}} keys ({{fresh}} new)': + '帶回 {{number}} 把金鑰(其中新建 {{fresh}} 把)', + 'Manage API keys': '管理 API 金鑰', + 'No group available to you serves image models': + '你可用的分組裡沒有圖像模型', + 'Ask the site administrator to open an image model group to your account.': + '請聯絡站點管理員,為你的帳號開放有圖像模型的分組。', + 'Could not load your keys, groups or model prices': + '讀取金鑰、分組或模型價格失敗', + 'The key was created, but it could not be found. Check it on the API Keys page.': + '金鑰已建立,但沒有找到它。請到「API 金鑰」頁查看。', + }, + fr: { + 'Connecting to Image Studio...': 'Connexion à Image Studio...', + 'Connect Image Studio': 'Connecter Image Studio', + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.': + 'Cochez les groupes à utiliser dans Image Studio. Une clé est renvoyée par groupe. Ce que vous y générez est facturé à ce compte.', + Groups: 'Groupes', + ', ': ', ', + '"{{name}}"': '« {{name}} »', + '{{names}} and {{more}} more': '{{names}} et {{more}} autres', + '1 image model': '1 modèle d’image', + '{{number}} image models': '{{number}} modèles d’image', + 'Create a "{{name}}" key': 'Créer une clé « {{name}} »', + 'Use existing: {{name}} · …{{last4}}': + 'Clé existante : {{name}} · …{{last4}}', + 'Key for group {{group}}': 'Clé du groupe {{group}}', + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.': + 'Seuls les groupes proposant des modèles d’image sont listés. Les groupes qui ont déjà une clé « {{name}} » sont cochés.', + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + 'Seuls les groupes proposant des modèles d’image sont listés. Vous n’avez pas encore de clé « {{name}} » : le groupe au ratio le plus bas est coché.', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.': + 'Seuls les groupes proposant des modèles d’image sont listés. Sans modèle d’image, donc non listés : {{groups}}. Les groupes qui ont déjà une clé « {{name}} » sont cochés.', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + 'Seuls les groupes proposant des modèles d’image sont listés. Sans modèle d’image, donc non listés : {{groups}}. Vous n’avez pas encore de clé « {{name}} » : le groupe au ratio le plus bas est coché.', + 'At most {{number}} groups at a time.': + 'Au plus {{number}} groupes à la fois.', + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.': + 'Une nouvelle clé s’appelle « {{name}} », n’a pas de limite de quota et n’expire jamais. Elle n’est créée que lorsque vous cliquez sur Renvoyer, et vous pouvez la modifier ou la supprimer sur la page Clés API. Les clés s’ajoutent à celles qu’Image Studio a déjà et ne les remplacent pas.', + 'Select at least one group': 'Cochez au moins un groupe', + 'Returning...': 'Renvoi en cours...', + 'Return 1 key': 'Renvoyer 1 clé', + 'Return 1 new key': 'Renvoyer 1 clé (nouvelle)', + 'Return {{number}} keys': 'Renvoyer {{number}} clés', + 'Return {{number}} keys ({{fresh}} new)': + 'Renvoyer {{number}} clés (dont {{fresh}} nouvelles)', + 'Manage API keys': 'Gérer les clés API', + 'No group available to you serves image models': + 'Aucun groupe disponible ne propose de modèles d’image', + 'Ask the site administrator to open an image model group to your account.': + 'Demandez à l’administrateur du site d’ouvrir un groupe de modèles d’image à votre compte.', + 'Could not load your keys, groups or model prices': + 'Impossible de charger vos clés, groupes ou prix des modèles', + 'The key was created, but it could not be found. Check it on the API Keys page.': + 'La clé a été créée, mais elle est introuvable. Vérifiez-la sur la page Clés API.', + }, + ru: { + 'Connecting to Image Studio...': 'Подключение к Image Studio...', + 'Connect Image Studio': 'Подключить Image Studio', + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.': + 'Отметьте группы, которые нужны в Image Studio. Для каждой группы возвращается один ключ. Всё, что вы там создаёте, оплачивается с этого аккаунта.', + Groups: 'Группы', + ', ': ', ', + '"{{name}}"': '«{{name}}»', + '{{names}} and {{more}} more': '{{names}} и ещё {{more}}', + '1 image model': 'Моделей изображений: 1', + '{{number}} image models': 'Моделей изображений: {{number}}', + 'Create a "{{name}}" key': 'Создать ключ «{{name}}»', + 'Use existing: {{name}} · …{{last4}}': + 'Существующий: {{name}} · …{{last4}}', + 'Key for group {{group}}': 'Ключ для группы {{group}}', + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.': + 'Показаны только группы с моделями изображений. Группы, где уже есть ключ «{{name}}», отмечены.', + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + 'Показаны только группы с моделями изображений. Ключа «{{name}}» у вас ещё нет, поэтому отмечена группа с наименьшим коэффициентом.', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.': + 'Показаны только группы с моделями изображений. Без моделей изображений, поэтому не показаны: {{groups}}. Группы, где уже есть ключ «{{name}}», отмечены.', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + 'Показаны только группы с моделями изображений. Без моделей изображений, поэтому не показаны: {{groups}}. Ключа «{{name}}» у вас ещё нет, поэтому отмечена группа с наименьшим коэффициентом.', + 'At most {{number}} groups at a time.': + 'Групп за один раз — не больше {{number}}.', + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.': + 'Новый ключ называется «{{name}}», без лимита квоты и бессрочный. Он создаётся только после нажатия «Вернуть»; изменить или удалить его можно на странице «Ключи API». Ключи добавляются к тем, что уже есть в Image Studio, и не заменяют их.', + 'Select at least one group': 'Отметьте хотя бы одну группу', + 'Returning...': 'Возвращаем...', + 'Return 1 key': 'Вернуть ключи: 1', + 'Return 1 new key': 'Вернуть ключи: 1 (новых: 1)', + 'Return {{number}} keys': 'Вернуть ключи: {{number}}', + 'Return {{number}} keys ({{fresh}} new)': + 'Вернуть ключи: {{number}} (новых: {{fresh}})', + 'Manage API keys': 'Управление ключами API', + 'No group available to you serves image models': + 'В доступных вам группах нет моделей изображений', + 'Ask the site administrator to open an image model group to your account.': + 'Попросите администратора сайта открыть вашему аккаунту группу с моделями изображений.', + 'Could not load your keys, groups or model prices': + 'Не удалось загрузить ключи, группы или цены моделей', + 'The key was created, but it could not be found. Check it on the API Keys page.': + 'Ключ создан, но не найден. Проверьте его на странице «Ключи API».', + }, + ja: { + 'Connecting to Image Studio...': '画像スタジオに接続しています...', + 'Connect Image Studio': '画像スタジオに接続', + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.': + '画像スタジオで使うグループを選んでください。グループごとにキーを1つ持ち帰ります。そこでの生成料金はこのアカウントから差し引かれます。', + Groups: 'グループ', + ', ': '、', + '"{{name}}"': '「{{name}}」', + '{{names}} and {{more}} more': '{{names}} ほか(全 {{total}} 個)', + '1 image model': '画像モデル 1 個', + '{{number}} image models': '画像モデル {{number}} 個', + 'Create a "{{name}}" key': '「{{name}}」を新規作成', + 'Use existing: {{name}} · …{{last4}}': '既存のキー:{{name}} · …{{last4}}', + 'Key for group {{group}}': '{{group}} で使うキー', + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.': + '画像モデルのあるグループのみ表示しています。「{{name}}」キーがあるグループは選択済みです。', + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + '画像モデルのあるグループのみ表示しています。「{{name}}」という名前のキーがまだないため、倍率が最も低いグループを選択しています。', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.': + '画像モデルのあるグループのみ表示しています({{groups}} は画像モデルがないため表示していません)。「{{name}}」キーがあるグループは選択済みです。', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + '画像モデルのあるグループのみ表示しています({{groups}} は画像モデルがないため表示していません)。「{{name}}」という名前のキーがまだないため、倍率が最も低いグループを選択しています。', + 'At most {{number}} groups at a time.': + '一度に選べるグループは最大 {{number}} 個です。', + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.': + '新しいキーの名前は「{{name}}」で、クォータ無制限、有効期限なしです。「戻る」を押したときにだけ作成され、APIキーのページで変更・削除できます。持ち帰ったキーは画像スタジオの既存のキーに追加され、置き換えはしません。', + 'Select at least one group': 'グループを1つ以上選んでください', + 'Returning...': '持ち帰っています...', + 'Return 1 key': 'キー 1 個を持って戻る', + 'Return 1 new key': 'キー 1 個を持って戻る(うち新規 1 個)', + 'Return {{number}} keys': 'キー {{number}} 個を持って戻る', + 'Return {{number}} keys ({{fresh}} new)': + 'キー {{number}} 個を持って戻る(うち新規 {{fresh}} 個)', + 'Manage API keys': 'APIキーを管理', + 'No group available to you serves image models': + '利用できるグループに画像モデルがありません', + 'Ask the site administrator to open an image model group to your account.': + '画像モデルのあるグループを開放するよう、サイト管理者に依頼してください。', + 'Could not load your keys, groups or model prices': + 'キー、グループ、モデル価格を読み込めませんでした', + 'The key was created, but it could not be found. Check it on the API Keys page.': + 'キーは作成されましたが見つかりません。APIキーのページで確認してください。', + }, + vi: { + 'Connecting to Image Studio...': 'Đang kết nối Image Studio...', + 'Connect Image Studio': 'Kết nối Image Studio', + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.': + 'Chọn các nhóm dùng trong Image Studio. Mỗi nhóm mang về một khóa. Chi phí tạo ảnh ở đó được trừ vào tài khoản này.', + Groups: 'Nhóm', + ', ': ', ', + '"{{name}}"': '“{{name}}”', + '{{names}} and {{more}} more': '{{names}} và {{more}} mô hình khác', + '1 image model': '1 mô hình tạo ảnh', + '{{number}} image models': '{{number}} mô hình tạo ảnh', + 'Create a "{{name}}" key': 'Tạo khóa “{{name}}”', + 'Use existing: {{name}} · …{{last4}}': + 'Dùng khóa có sẵn: {{name}} · …{{last4}}', + 'Key for group {{group}}': 'Khóa cho nhóm {{group}}', + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.': + 'Chỉ liệt kê các nhóm có mô hình tạo ảnh. Các nhóm đã có khóa “{{name}}” đã được chọn sẵn.', + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + 'Chỉ liệt kê các nhóm có mô hình tạo ảnh. Bạn chưa có khóa tên “{{name}}”, nên nhóm có hệ số thấp nhất đã được chọn sẵn.', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.': + 'Chỉ liệt kê các nhóm có mô hình tạo ảnh. Không liệt kê vì không có mô hình tạo ảnh: {{groups}}. Các nhóm đã có khóa “{{name}}” đã được chọn sẵn.', + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.': + 'Chỉ liệt kê các nhóm có mô hình tạo ảnh. Không liệt kê vì không có mô hình tạo ảnh: {{groups}}. Bạn chưa có khóa tên “{{name}}”, nên nhóm có hệ số thấp nhất đã được chọn sẵn.', + 'At most {{number}} groups at a time.': + 'Mỗi lần chọn tối đa {{number}} nhóm.', + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.': + 'Khóa mới có tên “{{name}}”, không giới hạn hạn mức và không hết hạn. Khóa chỉ được tạo khi bạn bấm Mang về, và bạn có thể sửa hoặc xóa ở trang Khóa API. Các khóa được thêm vào những khóa Image Studio đã có, không thay thế chúng.', + 'Select at least one group': 'Hãy chọn ít nhất một nhóm', + 'Returning...': 'Đang mang về...', + 'Return 1 key': 'Mang về 1 khóa', + 'Return 1 new key': 'Mang về 1 khóa (1 khóa mới)', + 'Return {{number}} keys': 'Mang về {{number}} khóa', + 'Return {{number}} keys ({{fresh}} new)': + 'Mang về {{number}} khóa ({{fresh}} khóa mới)', + 'Manage API keys': 'Quản lý khóa API', + 'No group available to you serves image models': + 'Các nhóm bạn được dùng không có mô hình tạo ảnh', + 'Ask the site administrator to open an image model group to your account.': + 'Hãy nhờ quản trị viên trang mở cho tài khoản của bạn một nhóm có mô hình tạo ảnh.', + 'Could not load your keys, groups or model prices': + 'Không tải được khóa, nhóm hoặc giá mô hình', + 'The key was created, but it could not be found. Check it on the API Keys page.': + 'Đã tạo khóa nhưng không tìm thấy. Hãy kiểm tra ở trang Khóa API.', + }, +} + +// Merge without overwriting: a key the upstream locale files already translate +// (for example "Groups") keeps the upstream wording. init() replaces the store, +// so the bundles go in only once i18next is initialized. +function addStudioLinkTranslations() { + for (const [language, strings] of Object.entries(translations)) { + i18next.addResourceBundle(language, 'translation', strings, true, false) + } +} + +if (i18next.isInitialized) { + addStudioLinkTranslations() +} else { + i18next.on('initialized', addStudioLinkTranslations) +} diff --git a/web/src/routes/_authenticated/-studio-key-link/studio-group-option.tsx b/web/src/routes/_authenticated/-studio-key-link/studio-group-option.tsx new file mode 100644 index 0000000..8d3f887 --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/studio-group-option.tsx @@ -0,0 +1,149 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ + +/* +One group on the /chat2link?app=studio choice page: whether its key goes back +to the image studio, the group's ratio and image models, and whether the key +is created on return or is one the user already has. The whole row toggles +the group; the key choice beside it does not. +*/ +import { useTranslation } from 'react-i18next' + +import { GroupMultiplierBadge } from '@/components/group-badge' +import { Badge } from '@/components/ui/badge' +import { Checkbox } from '@/components/ui/checkbox' +import { Label } from '@/components/ui/label' +import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select' +import type { ApiKey } from '@/features/keys/types' +import { cn } from '@/lib/utils' + +import { + STUDIO_KEY_NAME, + type StudioGroup, + type StudioGroupChoice, +} from './studio-key' + +// Model names shown in a row; the rest are counted. +const SHOWN_MODELS = 6 + +type StudioGroupOptionProps = { + group: StudioGroup + // Candidate keys billed in this group, newest first. + keys: ApiKey[] + choice: StudioGroupChoice + // Ticking is blocked once the most keys one return carries are ticked. + disabled: boolean + onChange: (choice: StudioGroupChoice) => void +} + +export function StudioGroupOption(props: StudioGroupOptionProps) { + const { t } = useTranslation() + const id = `studio-link-group-${props.group.name}` + const models = props.group.imageModels + const separator = t(', ') + const shown = models.slice(0, SHOWN_MODELS).join(separator) + const modelNames = + models.length > SHOWN_MODELS + ? t('{{names}} and {{more}} more', { + names: shown, + more: models.length - SHOWN_MODELS, + total: models.length, + }) + : shown + const createLabel = t('Create a "{{name}}" key', { name: STUDIO_KEY_NAME }) + const blocked = props.disabled && !props.choice.checked + + return ( +
+ +
+ {props.keys.length > 0 ? ( + + props.onChange({ + ...props.choice, + keyId: + event.target.value === 'new' + ? 'new' + : Number(event.target.value), + }) + } + > + {createLabel} + {props.keys.map((key) => ( + + {t('Use existing: {{name}} · …{{last4}}', { + name: key.name, + last4: key.key.slice(-4), + })} + + ))} + + ) : ( + // Nothing to choose: a key is created. The box toggles the row too. + + )} +
+
+ ) +} diff --git a/web/src/routes/_authenticated/-studio-key-link/studio-key-link.tsx b/web/src/routes/_authenticated/-studio-key-link/studio-key-link.tsx new file mode 100644 index 0000000..26cc376 --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/studio-key-link.tsx @@ -0,0 +1,411 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ + +/* +/chat2link?app=studio: send the user back to the CodaAPI image studio with one +key for each group whose image models the studio may use. Groups that already +have a dedicated key go back at once; otherwise, or with &pick=1, the user +ticks groups here, and keys are only created when the user clicks the button. +The keys travel in the URL fragment of the first web chat preset, like +upstream /chat2link, each followed by its group, then the studio's one-time +state (studio-key.ts, and the link protocol in coda/patches/README.md). +*/ +import { useMutation, useQuery } from '@tanstack/react-query' +import { Link, useLocation } from '@tanstack/react-router' +import { Loader2 } from 'lucide-react' +import { useEffect, useMemo, useRef, useState } from 'react' +import { useTranslation } from 'react-i18next' + +import { ErrorState } from '@/components/error-state' +import { LoadingState } from '@/components/loading-state' +import { Button } from '@/components/ui/button' +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from '@/components/ui/card' +import { useChatPresets } from '@/features/chat/hooks/use-chat-presets' +import { resolveChatUrl } from '@/features/chat/lib/chat-links' +import { + createApiKey, + fetchTokenKeysBatch, + getApiKeys, +} from '@/features/keys/api' +import { + API_KEY_FORM_DEFAULT_VALUES, + transformFormDataToPayload, +} from '@/features/keys/lib/api-key-form' +import { getPricing } from '@/features/pricing/api' +import { getUserGroups } from '@/lib/api' +import { handleServerError } from '@/lib/handle-server-error' +import { + createServerError, + requireServerSuccess, +} from '@/lib/server-error-message' +import { useAuthStore } from '@/stores/auth-store' + +import './i18n' +import { StudioGroupOption } from './studio-group-option' +import { + STUDIO_KEY_NAME, + STUDIO_MAX_KEYS, + effectiveKeyGroup, + imageModelsByGroup, + initialStudioChoices, + newestStudioKeyByGroup, + readStudioLinkSearch, + studioCandidateKeys, + studioImageGroups, + studioReturnUrl, + type StudioGroupChoice, +} from './studio-key' + +// One group's key on return: an existing key's id, or one to create first. +type StudioPick = { group: string; keyId: number | 'new' } + +// The upstream list is newest first; /chat2link itself reads 50. +const KEY_PAGE_SIZE = 100 + +export function StudioKeyLink() { + const { t } = useTranslation() + const { chatPresets, serverAddress } = useChatPresets() + const searchStr = useLocation({ select: (location) => location.searchStr }) + const link = useMemo(() => readStudioLinkSearch(searchStr), [searchStr]) + const userId = useAuthStore((state) => state.auth.user?.id) + const userGroup = useAuthStore((state) => state.auth.user?.group) || 'default' + const preset = useMemo( + () => chatPresets.find((item) => item.type === 'web'), + [chatPresets] + ) + const [edited, setEdited] = useState>() + // Decided once, when the data first arrives: return at once, or show the + // choices. A later refetch (after a failed return) never returns by itself. + const autoDecided = useRef(false) + + const keysQuery = useQuery({ + queryKey: ['studio-link-keys', userId], + queryFn: async () => + requireServerSuccess(await getApiKeys({ p: 1, size: KEY_PAGE_SIZE })), + enabled: Boolean(userId), + staleTime: 0, + meta: { errorToast: false }, + }) + const groupsQuery = useQuery({ + queryKey: ['studio-link-groups', userId], + queryFn: async () => requireServerSuccess(await getUserGroups()), + enabled: Boolean(userId), + staleTime: 0, + meta: { errorToast: false }, + }) + const pricingQuery = useQuery({ + queryKey: ['studio-link-pricing', userId], + queryFn: async () => requireServerSuccess(await getPricing()), + enabled: Boolean(userId), + staleTime: 0, + meta: { errorToast: false }, + }) + + const userGroups = groupsQuery.data?.data + const models = pricingQuery.data?.data + const groups = useMemo( + () => + studioImageGroups( + userGroups ?? {}, + imageModelsByGroup(models ?? [], Object.keys(userGroups ?? {})) + ), + [models, userGroups] + ) + const keys = keysQuery.data?.data?.items + const candidates = useMemo( + () => + studioCandidateKeys( + keys ?? [], + userGroup, + groups, + Math.floor(Date.now() / 1000) + ), + [keys, userGroup, groups] + ) + const dedicated = useMemo( + () => newestStudioKeyByGroup(candidates, userGroup), + [candidates, userGroup] + ) + const ready = Boolean(preset && keys && userGroups && models) + + const connect = useMutation({ + mutationFn: async (picks: StudioPick[]) => { + const knownIds = new Set((keys ?? []).map((key) => key.id)) + const created = picks.filter((pick) => pick.keyId === 'new') + for (const pick of created) { + const response = await createApiKey( + transformFormDataToPayload({ + ...API_KEY_FORM_DEFAULT_VALUES, + name: STUDIO_KEY_NAME, + group: pick.group, + }) + ) + if (!response.success) { + throw createServerError(response, t('Failed to create API key')) + } + } + let listed = keys ?? [] + if (created.length > 0) { + // Creating a key does not return it: take the newest new key with the + // studio name in each group. + const refreshed = requireServerSuccess( + await getApiKeys({ p: 1, size: KEY_PAGE_SIZE }) + ) + listed = refreshed.data?.items ?? [] + } + const ids = picks.map((pick) => { + if (pick.keyId !== 'new') return pick.keyId + const fresh = listed + .filter( + (key) => + !knownIds.has(key.id) && + key.name === STUDIO_KEY_NAME && + key.group === pick.group + ) + .sort((a, b) => b.id - a.id)[0] + if (!fresh) { + throw new Error( + t( + 'The key was created, but it could not be found. Check it on the API Keys page.' + ) + ) + } + return fresh.id + }) + // One request for all keys: POST /api/token/:id/key counts against the + // critical rate limit (shared with sign-in) once per key. + const revealed = await fetchTokenKeysBatch(ids) + if (!revealed.success || !revealed.data?.keys) { + throw createServerError(revealed, t('Failed to load API keys')) + } + return ids.map((id, index) => { + const full = revealed.data?.keys[id] + if (!full) throw new Error(t('Failed to load API keys')) + return { key: `sk-${full}`, group: picks[index].group } + }) + }, + onSuccess: (returned) => { + if (!preset || returned.length === 0) return + const url = resolveChatUrl({ + template: preset.url, + apiKey: returned[0].key, + serverAddress, + }) + // replace: going back from the studio must not land on this page again. + if (!url) return + window.location.replace(studioReturnUrl(url, returned, link.state)) + }, + onError: (error) => { + handleServerError(error) + // Keys created before the failure are dedicated keys now: start the + // choices over from the fresh list, so trying again does not create + // them a second time. + setEdited(undefined) + void keysQuery.refetch() + }, + }) + + // Groups with a dedicated key go back without asking, unless the studio + // asked for the choices (&pick=1). The ref makes it happen once, also under + // React's development double effects. + const returnsAtOnce = ready && !link.pick && dedicated.size > 0 + useEffect(() => { + if (!ready || autoDecided.current) return + autoDecided.current = true + if (!returnsAtOnce) return + const picks: StudioPick[] = [] + for (const group of groups) { + const key = dedicated.get(group.name) + if (key) picks.push({ group: group.name, keyId: key.id }) + } + connect.mutate(picks.slice(0, STUDIO_MAX_KEYS)) + }, [ready, returnsAtOnce, groups, dedicated, connect]) + + // A refetch (the window regains focus) can bring a group the edits do not + // know yet; it starts from the defaults. + const choices = useMemo( + () => ({ ...initialStudioChoices(groups, dedicated), ...edited }), + [edited, groups, dedicated] + ) + + const loadError = keysQuery.error ?? groupsQuery.error ?? pricingQuery.error + if (loadError) { + return ( + { + void keysQuery.refetch() + void groupsQuery.refetch() + void pricingQuery.refetch() + }} + /> + ) + } + if (!preset && chatPresets.length > 0) { + return ( + + ) + } + // When the automatic return fails (the error is shown as a toast), the + // choices below let the user try again. + if (!ready || connect.isSuccess || (returnsAtOnce && !connect.isError)) { + return ( + + ) + } + if (groups.length === 0) { + return ( + }> + {t('Manage API keys')} + + } + /> + ) + } + + const picks: StudioPick[] = groups + .filter((group) => choices[group.name]?.checked) + .map((group) => ({ group: group.name, keyId: choices[group.name].keyId })) + const fresh = picks.filter((pick) => pick.keyId === 'new').length + const full = picks.length >= STUDIO_MAX_KEYS + // Groups the user may use that are not listed, so nobody wonders where they went. + const unlisted = Object.keys(userGroups ?? {}) + .filter( + (name) => name !== 'auto' && !groups.some((group) => group.name === name) + ) + .map((name) => t('"{{name}}"', { name })) + .join(t(', ')) + // Whole sentences, so each language can join them its own way. + let listNote: string + if (unlisted && dedicated.size > 0) { + listNote = t( + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. Groups that already have a "{{name}}" key are ticked.', + { groups: unlisted, name: STUDIO_KEY_NAME } + ) + } else if (unlisted) { + listNote = t( + 'Only groups that serve image models are listed. Not listed, as they have no image models: {{groups}}. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.', + { groups: unlisted, name: STUDIO_KEY_NAME } + ) + } else if (dedicated.size > 0) { + listNote = t( + 'Only groups that serve image models are listed. Groups that already have a "{{name}}" key are ticked.', + { name: STUDIO_KEY_NAME } + ) + } else { + listNote = t( + 'Only groups that serve image models are listed. You have no key named "{{name}}" yet, so the group with the lowest ratio is ticked.', + { name: STUDIO_KEY_NAME } + ) + } + + let submitLabel = t('Select at least one group') + if (connect.isPending) { + submitLabel = t('Returning...') + } else if (picks.length === 1) { + submitLabel = fresh ? t('Return 1 new key') : t('Return 1 key') + } else if (picks.length > 1) { + submitLabel = fresh + ? t('Return {{number}} keys ({{fresh}} new)', { + number: picks.length, + fresh, + }) + : t('Return {{number}} keys', { number: picks.length }) + } + + return ( + // The list can be taller than the console's content area, which does not + // scroll by itself: scroll here, and center the card only when it fits. +
+
+ + + {t('Connect Image Studio')} + + {t( + 'Pick the groups to use in Image Studio. One key comes back per group. What you generate there is charged to this account.' + )} + + + +
+ {groups.map((group) => ( + effectiveKeyGroup(key, userGroup) === group.name + )} + choice={choices[group.name]} + disabled={full} + onChange={(choice) => + setEdited({ ...choices, [group.name]: choice }) + } + /> + ))} +
+

{listNote}

+ {full && ( +

+ {t('At most {{number}} groups at a time.', { + number: STUDIO_MAX_KEYS, + })} +

+ )} +

+ {t( + 'A new key is named "{{name}}", has no quota limit and never expires. It is only created when you click Return, and you can change or delete it on the API Keys page. The keys join the ones Image Studio already has and do not replace them.', + { name: STUDIO_KEY_NAME } + )} +

+
+ + + + +
+
+
+ ) +} diff --git a/web/src/routes/_authenticated/-studio-key-link/studio-key.ts b/web/src/routes/_authenticated/-studio-key-link/studio-key.ts new file mode 100644 index 0000000..0b0d8fc --- /dev/null +++ b/web/src/routes/_authenticated/-studio-key-link/studio-key.ts @@ -0,0 +1,231 @@ +/* +Copyright (C) 2026 CodaAPI + +CodaAPI patch to new-api (coda/patches/0002-chat2link-studio-key.patch), +released under the GNU Affero General Public License, version 3 or later, +like the rest of this program. +*/ + +/* +Which API keys /chat2link?app=studio hands to the CodaAPI image studio. The +studio only works with keys whose group serves image models, so instead of +the newest enabled key (upstream /chat2link) it takes one key per group: the +newest dedicated key of each group, or keys the user picks or creates here. +*/ +import { z } from 'zod' + +import { API_KEY_STATUS } from '@/features/keys/constants' +import type { ApiKey } from '@/features/keys/types' +import type { PricingModel } from '@/features/pricing/types' + +/** The `app` search value the image studio links with. */ +export const STUDIO_APP = 'studio' + +/** + * /chat2link's search: `app` picks the studio page. The studio's `state` and + * `pick` are read from the raw search string (readStudioLinkSearch). + */ +export const studioLinkSearchSchema = z.object({ + app: z.string().optional().catch(undefined), +}) + +/** Name of the dedicated key. Kept the same in every language so it is easy to spot. */ +export const STUDIO_KEY_NAME = '生图工作站' + +/** Most keys one return carries (the link protocol in coda/patches/README.md). */ +export const STUDIO_MAX_KEYS = 20 + +// The studio's one-time state: 16 random bytes in base64url, 22 characters. +// Anything else is treated as no state at all and never echoed back. +const STUDIO_STATE = /^[A-Za-z0-9_-]{16,64}$/ + +// Same rule as the studio's model list (coda/apps/studio/src/app/lib/profiles.ts, +// isImageModel): a model the gateway marks as image-generation, or one whose name +// looks like an image model (Gemini image and Seedream models are not in the +// gateway's list), minus video, audio, embedding and vision models. +const IMAGE_NAME = + /image|imagen|dall-e|seedream|seededit|flux|banana|cogview|kolors|stable-diffusion|sd3|sdxl|recraft|ideogram|hidream|t2i/i +const NOT_IMAGE = + /video|t2v|i2v|tts|whisper|audio|speech|rerank|embed|moderation|realtime|vision|ocr|caption|^mj[-_]|midjourney/i + +export type StudioPricingModel = Pick< + PricingModel, + 'model_name' | 'enable_groups' | 'supported_endpoint_types' +> + +export function isStudioImageModel(model: StudioPricingModel): boolean { + if (NOT_IMAGE.test(model.model_name)) return false + const endpoints = model.supported_endpoint_types ?? [] + if (endpoints.includes('openai-video') || endpoints.includes('embeddings')) { + return false + } + return ( + endpoints.includes('image-generation') || IMAGE_NAME.test(model.model_name) + ) +} + +/** + * Image models served by each group, from /api/pricing, in pricing order. + * "all" serves every group. Since rc.52 /api/pricing already trims + * enable_groups to the groups the viewer may use, plus "all". + */ +export function imageModelsByGroup( + models: StudioPricingModel[], + groups: string[] +): Map { + const byGroup = new Map(groups.map((group) => [group, [] as string[]])) + for (const model of models) { + if (!isStudioImageModel(model)) continue + const everywhere = model.enable_groups.includes('all') + for (const [group, names] of byGroup) { + const served = everywhere || model.enable_groups.includes(group) + if (served && !names.includes(model.model_name)) { + names.push(model.model_name) + } + } + } + return byGroup +} + +export type StudioGroup = { + name: string + desc: string + ratio: number + imageModels: string[] +} + +/** + * Groups the user may pick (GET /api/user/self/groups) that serve at least one + * image model, cheapest first. "auto" is left out: its ratio and models depend + * on routing, so the studio could neither list its models nor estimate a price. + */ +export function studioImageGroups( + userGroups: Record, + imageModels: Map +): StudioGroup[] { + const groups: StudioGroup[] = [] + for (const [name, info] of Object.entries(userGroups)) { + const ratio = Number(info.ratio) + if (name === 'auto' || !Number.isFinite(ratio)) continue + const models = imageModels.get(name) ?? [] + if (models.length === 0) continue + groups.push({ name, desc: info.desc, ratio, imageModels: models }) + } + return groups.sort( + (a, b) => a.ratio - b.ratio || a.name.localeCompare(b.name) + ) +} + +/** The group a key is billed in: its own, or the user's group when it has none. */ +export function effectiveKeyGroup(key: ApiKey, userGroup: string): string { + return key.group || userGroup +} + +/** + * Keys the studio can use: enabled, not expired or used up, in a group that + * serves image models, and, when the key limits its models, allowed at least + * one of them. Order is kept (the API lists the newest key first). + */ +export function studioCandidateKeys( + keys: ApiKey[], + userGroup: string, + groups: StudioGroup[], + nowSeconds: number +): ApiKey[] { + const served = new Map(groups.map((group) => [group.name, group.imageModels])) + return keys.filter((key) => { + if (key.status !== API_KEY_STATUS.ENABLED) return false + if (key.expired_time !== -1 && key.expired_time <= nowSeconds) return false + if (!key.unlimited_quota && key.remain_quota <= 0) return false + const models = served.get(effectiveKeyGroup(key, userGroup)) + if (!models) return false + if (!key.model_limits_enabled) return true + return (key.model_limits ?? '') + .split(',') + .some((name) => models.includes(name.trim())) + }) +} + +/** + * The newest dedicated key (named STUDIO_KEY_NAME) of each group, among the + * candidates. Newest is the highest id, whatever order the list came in. + */ +export function newestStudioKeyByGroup( + candidates: ApiKey[], + userGroup: string +): Map { + const byGroup = new Map() + for (const key of candidates) { + if (key.name !== STUDIO_KEY_NAME) continue + const group = effectiveKeyGroup(key, userGroup) + const kept = byGroup.get(group) + if (!kept || key.id > kept.id) byGroup.set(group, key) + } + return byGroup +} + +/** What one group of the choice page sends back: a key to create, or an existing one. */ +export type StudioGroupChoice = { + checked: boolean + keyId: number | 'new' +} + +/** + * The choice page's starting point: groups that have a dedicated key are + * ticked and use it; when none has one, only the cheapest group is ticked, + * with a key to create. + */ +export function initialStudioChoices( + groups: StudioGroup[], + dedicated: Map +): Record { + const choices: Record = {} + for (const [index, group] of groups.entries()) { + const key = dedicated.get(group.name) + choices[group.name] = { + checked: key ? true : dedicated.size === 0 && index === 0, + keyId: key?.id ?? 'new', + } + } + return choices +} + +/** The studio link's state and pick values, read from the raw search string. */ +export function readStudioLinkSearch(searchStr: string): { + state?: string + pick: boolean +} { + // The raw string, not the router's parsed search: that parses values as + // JSON, and a state of digits only would come back as a different number. + const params = new URLSearchParams(searchStr) + const state = params.get('state') ?? '' + return { + state: STUDIO_STATE.test(state) ? state : undefined, + pick: params.get('pick') === '1', + } +} + +export type StudioReturnedKey = { key: string; group: string } + +/** + * The studio address for the returned keys. `url` is the first web chat + * preset resolved with the first key (#key={key}); after it come that key's + * group, then each further key with its group, in order, then the state the + * studio sent. Everything stays in the fragment, which never reaches a server + * or a Referer header. + */ +export function studioReturnUrl( + url: string, + keys: StudioReturnedKey[], + state?: string +): string { + const parts: string[] = [] + for (const [index, item] of keys.entries()) { + if (index > 0) parts.push(`key=${encodeURIComponent(item.key)}`) + parts.push(`group=${encodeURIComponent(item.group)}`) + } + if (state) parts.push(`state=${state}`) + if (parts.length === 0) return url + const separator = url.includes('#') ? '&' : '#' + return `${url}${separator}${parts.join('&')}` +} diff --git a/web/src/routes/_authenticated/chat2link.tsx b/web/src/routes/_authenticated/chat2link.tsx index afbc646..7626ed8 100644 --- a/web/src/routes/_authenticated/chat2link.tsx +++ b/web/src/routes/_authenticated/chat2link.tsx @@ -27,10 +27,26 @@ import { useChatPresets } from '@/features/chat/hooks/use-chat-presets' import { resolveChatUrl } from '@/features/chat/lib/chat-links' import { handleServerError } from '@/lib/handle-server-error' +import { + STUDIO_APP, + studioLinkSearchSchema, +} from './-studio-key-link/studio-key' +import { StudioKeyLink } from './-studio-key-link/studio-key-link' + export const Route = createFileRoute('/_authenticated/chat2link')({ - component: Chat2LinkPage, + // CodaAPI patch (coda/patches/0002-chat2link-studio-key.patch): the CodaAPI + // image studio links here with ?app=studio. It needs keys whose groups serve + // image models, which the newest enabled key often is not, so that case gets + // its own page (./-studio-key-link). Every other link works as upstream. + validateSearch: studioLinkSearchSchema, + component: Chat2LinkRoute, }) +function Chat2LinkRoute() { + const search = Route.useSearch() + return search.app === STUDIO_APP ? : +} + function Chat2LinkPage() { const { t } = useTranslation() const navigate = useNavigate()