diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js new file mode 100644 index 0000000..a5fe027 --- /dev/null +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -0,0 +1,173 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +import { getAIAssistantUsage, getUsageChipReport, keepAIAssistantUsage, refreshAIAssistantUsage, toAIAssistantUsage, withoutAIAssistantUsage } from '../aiAssistantUsage.js' + +const memoryStorage = (initial = {}) => { + const store = {...initial} + return { + store, + getItem: key => (key in store ? store[key] : null), + setItem: (key, value) => { store[key] = String(value) }, + removeItem: key => { delete store[key] }, + } +} + +const REQUEST = {baseURL: 'https://ai.example.org/', token: 'personal-token', username: 'someone'} + +// OpenConceptLab/ocl_online#641 +test('the usage the service reports is read as sent: a unit and a count', () => { + assert.deepEqual(toAIAssistantUsage({meter: 'tokens', used: 1234}), {meter: 'tokens', used: 1234}) + assert.deepEqual(toAIAssistantUsage({meter: 'calls', used: 0}), {meter: 'calls', used: 0}) + // nothing but the unit and the count + assert.deepEqual(toAIAssistantUsage({meter: 'tokens', used: 5, limit: 3000, remaining: 2995}), {meter: 'tokens', used: 5}) +}) + +test('a report without a unit and a count is no report', () => { + for (const data of [undefined, null, {}, 'Not found.', {detail: 'Nope'}, {meter: 'tokens'}, {used: 5}, {meter: 'tokens', used: '5'}, {meter: 7, used: 5}, {meter: 'tokens', used: NaN}]) + assert.equal(toAIAssistantUsage(data), null, JSON.stringify(data)) +}) + +test('a kept report is only for the person it was asked for', () => { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'tokens', used: 5})}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 5}) + assert.equal(getAIAssistantUsage(storage, 'someone-else'), null) + assert.equal(getAIAssistantUsage(storage, undefined), null) + assert.equal(getAIAssistantUsage(memoryStorage(), 'someone'), null) + assert.equal(getAIAssistantUsage(memoryStorage({'ai_assistant_usage:someone': '{not json'}), 'someone'), null) +}) + +test('asks the service with the person\'s token and keeps its report', async () => { + const storage = memoryStorage() + const calls = [] + const get = (url, config) => { + calls.push({url, config}) + return Promise.resolve({status: 200, data: {meter: 'tokens', used: 42}}) + } + assert.equal(await refreshAIAssistantUsage({...REQUEST, get, storage}), true) + assert.deepEqual(calls, [{url: 'https://ai.example.org/match/usage/', config: {headers: {Authorization: 'Token personal-token'}, timeout: 10000}}]) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 42}) +}) + +test('a failed or throttled request keeps the last report', async () => { + for (const status of [429, 404, 500]) { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'tokens', used: 5})}) + const get = () => Promise.reject({response: {status, headers: {'retry-after': '30'}}}) + assert.equal(await refreshAIAssistantUsage({...REQUEST, get, storage}), false, String(status)) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 5}, String(status)) + } +}) + +test('a report without a unit and a count clears the kept one', async () => { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'tokens', used: 5})}) + assert.equal(await refreshAIAssistantUsage({...REQUEST, get: () => Promise.resolve({status: 200, data: {}}), storage}), true) + assert.equal(getAIAssistantUsage(storage, 'someone'), null) +}) + +test('no service URL, token or person: nothing is asked', async () => { + const get = () => assert.fail('asked') + for (const missing of ['baseURL', 'token', 'username']) + assert.equal(await refreshAIAssistantUsage({...REQUEST, [missing]: undefined, get, storage: memoryStorage()}), false, missing) +}) + +// OpenConceptLab/ocl_online#641 +test('a reply\'s usage is kept for the person, as a refresh keeps it', () => { + const storage = memoryStorage() + assert.equal(keepAIAssistantUsage(storage, 'someone', {output: {}, metadata: {provider: 'x', usage: {meter: 'tokens', used: 7}}}), true) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 7}) + assert.equal(getAIAssistantUsage(storage, 'someone-else'), null) +}) + +test('a reply without a usage report keeps the last one', () => { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'tokens', used: 5})}) + for (const reply of [undefined, null, {}, {metadata: {}}, {metadata: {usage: {meter: 'tokens'}}}, {metadata: {usage: {meter: 'tokens', used: '9'}}}]) + assert.equal(keepAIAssistantUsage(storage, 'someone', reply), false, JSON.stringify(reply)) + assert.equal(keepAIAssistantUsage(storage, undefined, {metadata: {usage: {meter: 'tokens', used: 9}}}), false) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 5}) +}) + +test('what a project stores of a reply leaves out the usage, and only that', () => { + const reply = {output: {rationale: 'r'}, metadata: {provider: 'openrouter', tokens: {total: 150}, usage: {meter: 'tokens', used: 7}}} + assert.deepEqual(withoutAIAssistantUsage(reply), {output: {rationale: 'r'}, metadata: {provider: 'openrouter', tokens: {total: 150}}}) + assert.deepEqual(reply.metadata.usage, {meter: 'tokens', used: 7}) + const noUsage = {output: {}, metadata: {provider: 'x'}} + assert.equal(withoutAIAssistantUsage(noUsage), noUsage) + for (const value of [undefined, null, {output: {}}]) + assert.equal(withoutAIAssistantUsage(value), value) +}) + +test('the usage chip shows a report in a unit it knows, and nothing else', () => { + assert.deepEqual(getUsageChipReport({meter: 'tokens', used: 7}), {meter: 'tokens', used: 7}) + assert.deepEqual(getUsageChipReport({meter: 'calls', used: 3}), {meter: 'calls', used: 3}) + for (const usage of [null, undefined, {meter: 'credits', used: 1}]) + assert.equal(getUsageChipReport(usage), null, JSON.stringify(usage)) +}) + +test('each person keeps their own report', async () => { + const storage = memoryStorage() + keepAIAssistantUsage(storage, 'someone', {metadata: {usage: {meter: 'tokens', used: 5}}}) + keepAIAssistantUsage(storage, 'someone-else', {metadata: {usage: {meter: 'calls', used: 2}}}) + const get = () => Promise.reject({response: {status: 429}}) + assert.equal(await refreshAIAssistantUsage({...REQUEST, get, storage}), false) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 5}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone-else'), {meter: 'calls', used: 2}) +}) + +test('a refresh sent before a reply\'s report doesn\'t overwrite it', async () => { + const storage = memoryStorage() + let answer + const get = () => new Promise(resolve => { answer = resolve }) + const refreshed = refreshAIAssistantUsage({...REQUEST, get, storage}) + keepAIAssistantUsage(storage, 'someone', {metadata: {usage: {meter: 'tokens', used: 300}}}) + answer({status: 200, data: {meter: 'tokens', used: 100}}) + assert.equal(await refreshed, false) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 300}) +}) + +test('a refresh sent before another tab kept a report doesn\'t overwrite it', async () => { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'tokens', used: 100})}) + let answer + const get = () => new Promise(resolve => { answer = resolve }) + const refreshed = refreshAIAssistantUsage({...REQUEST, get, storage}) + // the other tab shares the storage, not this module + storage.setItem('ai_assistant_usage:someone', JSON.stringify({meter: 'tokens', used: 300})) + answer({status: 200, data: {meter: 'tokens', used: 100}}) + assert.equal(await refreshed, false) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 300}) +}) + +test('a storage that refuses to keep a report throws nothing', async () => { + const storage = {...memoryStorage(), setItem: () => { throw new Error('QuotaExceededError') }, removeItem: () => { throw new Error('SecurityError') }} + assert.equal(keepAIAssistantUsage(storage, 'someone', {metadata: {usage: {meter: 'tokens', used: 7}}}), true) + assert.equal(await refreshAIAssistantUsage({...REQUEST, get: () => Promise.resolve({status: 200, data: {}}), storage}), true) +}) + +test('a refresh asked for while one is in flight runs after it, and keeps its newer count', async () => { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'tokens', used: 100})}) + const answers = [] + let inFlight = 0 + const get = () => { + inFlight += 1 + assert.equal(inFlight, 1, 'one request at a time') + return new Promise(resolve => answers.push(data => { inFlight -= 1; resolve({status: 200, data}) })) + } + const first = refreshAIAssistantUsage({...REQUEST, get, storage}) + const second = refreshAIAssistantUsage({...REQUEST, get, storage}) + const third = refreshAIAssistantUsage({...REQUEST, get, storage}) + assert.equal(second, third, 'requests made meanwhile share one more') + assert.equal(answers.length, 1) + answers[0]({meter: 'tokens', used: 200}) + assert.equal(await first, true) + await new Promise(resolve => setTimeout(resolve, 0)) + assert.equal(answers.length, 2) + answers[1]({meter: 'tokens', used: 300}) + assert.equal(await second, true) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'tokens', used: 300}) +}) + +test('any username, even one an object has as a property, is refreshed', async () => { + const storage = memoryStorage() + const get = () => Promise.resolve({status: 200, data: {meter: 'tokens', used: 9}}) + assert.equal(await refreshAIAssistantUsage({...REQUEST, username: 'constructor', get, storage}), true) + assert.deepEqual(getAIAssistantUsage(storage, 'constructor'), {meter: 'tokens', used: 9}) +}) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js new file mode 100644 index 0000000..d3af151 --- /dev/null +++ b/src/common/aiAssistantUsage.js @@ -0,0 +1,108 @@ +// The OCL AI Assistant's usage as the service reports it: the unit it counts in +// and how many it has counted, never a limit (OpenConceptLab/ocl_online#641). +export const toAIAssistantUsage = data => + typeof data?.meter === 'string' && Number.isFinite(data?.used) ? {meter: data.meter, used: data.used} : null + +// The units whose report gets a chip of its own where the Mapper shows no +// Preview chip (OpenConceptLab/ocl_online#641). +export const USAGE_CHIP_METERS = ['calls', 'tokens'] + +export const getUsageChipReport = usage => usage && USAGE_CHIP_METERS.includes(usage.meter) ? usage : null + +// Each person's last report, under their own key. +const storageKey = username => `ai_assistant_usage:${username}` + +// What's kept for this person now, to tell whether it changed: undefined if +// the storage can't be read. +const read = (storage, username) => { + try { + return storage.getItem(storageKey(username)) + } catch(_) { + return undefined + } +} + +// A full or blocked storage only costs the chip its report. +const store = (storage, username, usage) => { + try { + if(usage) + storage.setItem(storageKey(username), JSON.stringify(usage)) + else + storage.removeItem(storageKey(username)) + } catch(_) { + // nothing to keep + } +} + +// The last report kept for this person. Without one, the chip keeps its call line. +export const getAIAssistantUsage = (storage, username) => { + if(!username) + return null + try { + return toAIAssistantUsage(JSON.parse(storage.getItem(storageKey(username)))) + } catch(_) { + return null + } +} + +// Keeps the report a reply carries in `metadata.usage` (an $invoke reply) for +// the person who sent the request. Returns whether it kept one. +export const keepAIAssistantUsage = (storage, username, reply) => { + const usage = toAIAssistantUsage(reply?.metadata?.usage) + if(!usage || !username) + return false + store(storage, username, usage) + return true +} + +// The reply without `metadata.usage`, for what a project stores: the report is +// the service's running count, which covers more than this project's work. +export const withoutAIAssistantUsage = reply => { + if(!reply?.metadata || !Object.prototype.hasOwnProperty.call(reply.metadata, 'usage')) + return reply + const metadata = {...reply.metadata} + delete metadata.usage + return {...reply, metadata} +} + +// Asks for the report with `get` (axios.get, not APIService, so a refused or +// throttled request skips its sign-out and throttling handling). A report +// without a unit and a count clears the kept one. A failed request keeps it, +// and so does one that's overtaken: something else (a reply's report, in this +// tab or another) kept a report while it was in flight. Resolves to whether +// the kept report changed. +const fetchAIAssistantUsage = ({get, storage, baseURL, token, username}) => { + const url = `${baseURL.replace(/\/+$/, '')}/match/usage/` + const keptBefore = read(storage, username) + return get(url, {headers: {Authorization: `Token ${token}`}, timeout: 10000}) + .then(response => { + if(read(storage, username) !== keptBefore) + return false + store(storage, username, toAIAssistantUsage(response?.data)) + return true + }) + .catch(() => false) +} + +// One refresh at a time per person: a request made while one is in flight +// waits for it, then all such requests share one more, so a refresh never +// overtakes another and discards its newer count. +const refreshing = new Map() + +export const refreshAIAssistantUsage = request => { + const { baseURL, token, username } = request + if(!baseURL || !token || !username) + return Promise.resolve(false) + const running = refreshing.get(username) + if(running) { + running.next = running.next || running.promise.then(() => refreshAIAssistantUsage(request)) + return running.next + } + const entry = {} + entry.promise = fetchAIAssistantUsage(request).finally(() => { + if(refreshing.get(username) === entry) + refreshing.delete(username) + }) + refreshing.set(username, entry) + return entry.promise +} diff --git a/src/common/utils.js b/src/common/utils.js index 85f38a7..5ab8316 100644 --- a/src/common/utils.js +++ b/src/common/utils.js @@ -13,12 +13,14 @@ import { DATE_FORMAT, TIME_FORMAT, DATETIME_FORMAT, OCL_SERVERS_GROUP, OCL_FHIR_SERVERS_GROUP, HAPI_FHIR_SERVERS_GROUP, OPENMRS_URL, DEFAULT_FHIR_SERVER_FOR_LOCAL_ID, OPERATIONS_PANEL_GROUP } from './constants'; +import axios from 'axios'; import APIService from '../services/APIService'; import GAService from '../services/GAService'; import { ensureIdToken, prepareSignOut, settleForcedSignOut, renewSessionSilently } from './ssoSession'; import { SERVER_CONFIGS } from './serverConfigs'; import { legacyHashRoute, isSameSitePath } from './history'; import { resolveV3URL, resolveIntegratedV3URL } from './appUrls'; +import { getAIAssistantUsage, keepAIAssistantUsage, refreshAIAssistantUsage } from './aiAssistantUsage'; export const currentPath = () => window.location.pathname; @@ -272,6 +274,40 @@ export const refreshCurrentUserCapabilitiesCache = callback => { }); } +// Asks the OCL AI Assistant what it has counted for this person +// (OpenConceptLab/ocl_online#641). +// Refreshes the capabilities and, beside them, the OCL AI Assistant's usage +// report, which is asked for only with the OCL AI Assistant permission: if the +// cached permissions lacked it, it's asked for again once fresh ones arrive. +// `usage: false` skips the report. Each callback runs when its part changed. +export const refreshCapabilitiesAndAIAssistantUsage = ({onCapabilities, onUsage, usage = true}) => { + const hadAIAssistant = hasCapability(getCurrentUser(), 'users.mapper_ai_assistant') + refreshCurrentUserCapabilitiesCache(() => { + onCapabilities() + if(usage && !hadAIAssistant) + refreshAIAssistantUsageCache(onUsage) + }) + if(usage) + refreshAIAssistantUsageCache(onUsage) +} + +export const refreshAIAssistantUsageCache = callback => { + const user = getCurrentUser() + if(!hasCapability(user, 'users.mapper_ai_assistant')) + return + refreshAIAssistantUsage({ + get: axios.get, + storage: localStorage, + baseURL: window.AI_ASSISTANT_API_URL || process.env.AI_ASSISTANT_API_URL, + token: currentUserToken(), + username: user?.username, + }).then(changed => changed && callback && callback()) +} + +// Keeps the usage an OCL AI Assistant reply carries for `username`, the person +// signed in when the request was sent. Returns whether it kept one. +export const keepAIAssistantUsageFromReply = (reply, username) => keepAIAssistantUsage(localStorage, username, reply) + export const replaceCurrentUserCacheWith = data => localStorage.setItem('user', JSON.stringify(data)); export const formatByteSize = bytes => { @@ -1193,6 +1229,7 @@ export const getMapperPreview = () => { rowsPerProject: toCap('mapper.rows_per_project'), matchOperations: toMeter('mapper.match_operations'), aiAssistantCalls: toMeter('ai_assistant.calls'), + aiAssistantUsage: getAIAssistantUsage(localStorage, user?.username), } } diff --git a/src/components/common/LimitDialog.jsx b/src/components/common/LimitDialog.jsx index 2032a87..ccc7a2d 100644 --- a/src/components/common/LimitDialog.jsx +++ b/src/components/common/LimitDialog.jsx @@ -14,9 +14,9 @@ import useLimitAction from './useLimitAction' // The frame every limit dialog shares: what was refused, then any next step // the connected service sends (OpenConceptLab/ocl_online#367), which opens // in a new tab. -const LimitDialog = ({open, onClose, errorCode, title, children}) => { +const LimitDialog = ({open, onClose, errorCode, capability, title, children}) => { const { t } = useTranslation() - const { action, onActionClick } = useLimitAction(open, errorCode) + const { action, onActionClick } = useLimitAction(open, errorCode, capability) return ( diff --git a/src/components/common/QuotaDialog.jsx b/src/components/common/QuotaDialog.jsx index 19f9899..e272e4f 100644 --- a/src/components/common/QuotaDialog.jsx +++ b/src/components/common/QuotaDialog.jsx @@ -4,11 +4,11 @@ import { useTranslation } from 'react-i18next' import LimitDialog from './LimitDialog' import { isCapMeter } from './quotaErrors' -const QuotaDialog = ({open, onClose, errorCode, meter, surface}) => { +const QuotaDialog = ({open, onClose, errorCode, capability, meter, surface}) => { const { t } = useTranslation() return ( - + {t([`quota.consequence.${meter}.${surface}`, `quota.consequence.${meter}.default`, 'quota.consequence.generic'])} ) diff --git a/src/components/common/__tests__/limitAction.test.js b/src/components/common/__tests__/limitAction.test.js index 814f216..7a73d9b 100644 --- a/src/components/common/__tests__/limitAction.test.js +++ b/src/components/common/__tests__/limitAction.test.js @@ -30,6 +30,17 @@ test('an access check asks about its permission', () => { ) }) +// OpenConceptLab/ocl_online#641 +test('a refusal that names its capability is asked about that one', () => { + assert.deepEqual( + getLimitActionRequest({baseURL: 'https://online.example.org', token: 'personal-token', errorCode: 'example_service_limit_reached', capability: 'example.capability', lang: 'es'}).params, + {context: 'limit', capability: 'example.capability', lang: 'es'} + ) + assert.deepEqual(getLimitSubject('ai_assistant_calls_limit_reached', 'example.capability'), {capability: 'example.capability'}) + for (const capability of [undefined, null, '', 7]) + assert.deepEqual(getLimitSubject('ai_assistant_calls_limit_reached', capability), {capability: 'ai_assistant.calls'}, String(capability)) +}) + test('every refusal the dialogs show names one capability or permission', () => { [ 'mapper_match_operations_limit_reached', diff --git a/src/components/common/limitAction.js b/src/components/common/limitAction.js index 1871ba8..2751f75 100644 --- a/src/components/common/limitAction.js +++ b/src/components/common/limitAction.js @@ -21,14 +21,17 @@ const LIMIT_SUBJECTS = { mapper_scispacy_denied: {permission: 'users.mapper_scispacy'}, } -export const getLimitSubject = errorCode => LIMIT_SUBJECTS[errorCode] || {} +// A refusal that names its own capability is asked about that one +// (OpenConceptLab/ocl_online#641). +export const getLimitSubject = (errorCode, capability) => + typeof capability === 'string' && capability ? {capability} : (LIMIT_SUBJECTS[errorCode] || {}) -export const getLimitActionRequest = ({baseURL, token, errorCode, lang}) => { +export const getLimitActionRequest = ({baseURL, token, errorCode, capability, lang}) => { if(!baseURL || !token) return null return { url: `${baseURL.replace(/\/+$/, '')}/billing/plan/`, - params: {context: 'limit', ...getLimitSubject(errorCode), lang}, + params: {context: 'limit', ...getLimitSubject(errorCode, capability), lang}, headers: {Authorization: `Token ${token}`}, } } diff --git a/src/components/common/useLimitAction.js b/src/components/common/useLimitAction.js index bd90292..6363317 100644 --- a/src/components/common/useLimitAction.js +++ b/src/components/common/useLimitAction.js @@ -13,17 +13,17 @@ const getOnlineAPIURL = () => window.OCL_ONLINE_API_URL || process.env.OCL_ONLIN // Records the refusal and, when online-api is configured, asks it for the // person's next step. Not configured, failing or nothing to offer: no action. // axios directly, not APIService, so online-api's errors skip its sign-out and throttling handling. -const useLimitAction = (open, errorCode) => { +const useLimitAction = (open, errorCode, capability) => { const { i18n } = useTranslation() const [action, setAction] = React.useState(null) - const subject = getLimitSubject(errorCode) + const subject = getLimitSubject(errorCode, capability) React.useEffect(() => { setAction(null) if(!open) return undefined GAService.recordActionEvent('Limit', 'limit_hit', errorCode, subject) - const request = getLimitActionRequest({baseURL: getOnlineAPIURL(), token: currentUserToken(), errorCode, lang: i18n.language}) + const request = getLimitActionRequest({baseURL: getOnlineAPIURL(), token: currentUserToken(), errorCode, capability, lang: i18n.language}) if(!request) return undefined let current = true @@ -33,7 +33,7 @@ const useLimitAction = (open, errorCode) => { return () => { current = false } - }, [open, errorCode]) + }, [open, errorCode, capability]) const onActionClick = () => GAService.recordActionEvent('Limit', 'limit_action_click', errorCode, {...subject, action_kind: action?.kind}) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 23e8065..e99c90d 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -73,7 +73,8 @@ import APIService, { isTransientNetworkError, retryWithBackoff } from '../../ser import { matchToken, lookupTokenFor, needsSessionToken, needsSessionLookupToken, withoutTokens, withSavedTokenURL, withoutLocalKeys, isAbsoluteURL } from '../../services/tokenScope' import { buildAttributionHeaders, buildConfigSnapshot, summarizeRunCompletion, matchesOnOCL } from '../../services/attribution' import { CAPACITY_LIMIT, RATE_LIMIT, CAPACITY_WAIT_CAP_MS, HEAVY_REQUEST_TIMEOUT_MS, LIGHT_REQUEST_TIMEOUT_MS, createCapacityGate, createLimiter, isRetryableError, requestWithCapacityRetry, sleepUnlessCancelled, untilCancelled } from '../../services/capacity' -import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCurrentUserCapabilitiesCache } from '../../common/utils'; +import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCapabilitiesAndAIAssistantUsage, keepAIAssistantUsageFromReply } from '../../common/utils'; +import { withoutAIAssistantUsage } from '../../common/aiAssistantUsage'; import { WHITE, SURFACE_COLORS, TEXT_GRAY } from '../../common/colors'; import { useDoubleClick } from '../common/useDoubleClick' @@ -113,7 +114,7 @@ import QuotaDialog from '../common/QuotaDialog' import { getQuotaError } from '../common/quotaErrors' import MapperQuotaChip from './MapperQuotaChip' import MapProjectBreadcrumb from './MapProjectBreadcrumb' -import { getPreviewLimitError, isAIPreviewLimitError } from './previewLimits' +import { getPreviewLimitError, isAIPreviewLimitError, isPreviewLimitError } from './previewLimits' import { formatRowNumbers, rowNumberOf, runMatchBatch, requestSingleMatch, runWithConcurrency, INTERACTIVE_WAIT_CAP_MS } from './matchBatch' import { getAIAssistantChoices, getModelUsed, getPromptTemplateKey, createLatestRequestGate } from './aiVisibility' import { DEFAULT_ENCODER_MODEL } from './rerankerModels' @@ -157,8 +158,15 @@ const MapProject = () => { const { toggles, setAlert: baseSetAlert, setProjectRowSearch } = React.useContext(OperationsContext); const user = getCurrentUser() const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) - const refreshMapperQuotaCache = React.useCallback(() => { - refreshCurrentUserCapabilitiesCache(() => setMapperQuotaCacheVersion(version => version + 1)) + const [, setAIAssistantUsageVersion] = React.useState(0) + // {usage: false} skips asking the OCL AI Assistant, when its reply already + // carried the usage (OpenConceptLab/ocl_online#641). + const refreshMapperQuotaCache = React.useCallback(({usage = true} = {}) => { + refreshCapabilitiesAndAIAssistantUsage({ + onCapabilities: () => setMapperQuotaCacheVersion(version => version + 1), + onUsage: () => setAIAssistantUsageVersion(version => version + 1), + usage, + }) }, []) const params = useParams() const history = useHistory() @@ -262,10 +270,17 @@ const MapProject = () => { const bridgeCallContextRef = React.useRef(null) // ai_assistant.calls is a one-time allowance (no reset, R2) - once exhausted it // stays exhausted for the rest of the session, so this is never reset per-run. + // A refusal scoped to its request skips only its row and never sets it. const aiQuotaExhaustedRef = React.useRef(false); + // The current run skipped a row's AI step for a refusal scoped to its request. + const aiQuotaSkippedRef = React.useRef(false); // Consecutive rows whose AI step failed for a reason other than quota. Reset // at the start of each run's AI step (see shouldStopAIStep). const aiFailuresInARowRef = React.useRef(0); + // Single-row AI calls in flight, and whether any overlapped since none were + // (OpenConceptLab/ocl_online#641). + const singleAICallsInFlightRef = React.useRef(0); + const singleAICallsOverlappedRef = React.useRef(false); const isBulkMatchRunningRef = React.useRef(false); // A run that hits a preview limit mid-way stops sending $match but still // finishes (rerank, AI, autosave) - unlike abortRef, which is the user's Stop. @@ -290,7 +305,7 @@ const MapProject = () => { const ownNavigationRef = React.useRef(false) const refreshRowStageSnapshotRef = React.useRef({}); - const [previewLimit, setPreviewLimit] = React.useState(null) // {errorCode} or null + const [previewLimit, setPreviewLimit] = React.useState(null) // {errorCode, capability, phase} or null const previewLimitQuota = previewLimit ? getQuotaError({error_code: previewLimit.errorCode}) : null const [row, setRow] = React.useState(false) @@ -1844,7 +1859,7 @@ const MapProject = () => { // The user has left the project, so no dialog can show: say so once. baseSetAlert({severity: 'error', message: t('map_project.leave_save_failed', {name: name || project?.name, detail: errorData?.detail || t('unknown_error')}), duration: 12000}) } else if(status === 403 && errorData?.error_code) { - setPreviewLimit({errorCode: errorData.error_code}) + setPreviewLimit({errorCode: errorData.error_code, capability: errorData.capability}) } else if(!isAutoSave && status !== 429 && status !== 401) { baseSetAlert({severity: 'error', message: errorData?.detail || t('unknown_error'), duration: 8000}) } @@ -2091,7 +2106,7 @@ const MapProject = () => { abortRef.current = true setLoadingMatches(false) setIsLoadingInDecisionView(false) - setPreviewLimit({errorCode: data.error_code}) + setPreviewLimit({errorCode: data.error_code, capability: data.capability}) return } projectLog({action: 'automatch_run_create_failed', extras: {status: status || 'no-id', ...(result.ok ? {} : {reason: result.reason, error: result.error?.message || null})}}) @@ -2121,7 +2136,7 @@ const MapProject = () => { algoIds: run.algoIds?.length ? run.algoIds : map(selectedAlgos, 'id'), aiOnly: Boolean(run.aiOnly), aborted, - stoppedForQuota: Boolean(matchQuotaStopRef.current || (run.aiOnly && aiQuotaExhaustedRef.current)), + stoppedForQuota: Boolean(matchQuotaStopRef.current || (run.aiOnly && (aiQuotaExhaustedRef.current || aiQuotaSkippedRef.current))), }) // The tab is closing: one request, sent before this function yields. if(keepalive) @@ -2419,6 +2434,7 @@ const MapProject = () => { matchQuotaStopRef.current = null; rerankQuotaStopRef.current = null; runPreviewLimitShownRef.current = false; + aiQuotaSkippedRef.current = false; const selectedRowIndexes = getSelectedRowIndexes(rows) const isAutoMatchUnmappedOnly = autoMatchScope === 'unmapped' const isAutoMatchAllIncludingApproved = autoMatchScope === 'allIncludingApproved' @@ -4054,26 +4070,40 @@ const MapProject = () => { return false const isRun = options.isRun === undefined ? isBulkMatchRunningRef.current : options.isRun const stopPhase = options.stopPhase || (isAIPreviewLimitError(response.error_code) ? 'ai' : 'match') + // A refusal scoped to its request skips that row: another may still go + // through. Any other scope, or none, stops the AI step. + const skipsRow = stopPhase === 'ai' && response.scope === 'request' + const stopsAIStep = stopPhase === 'ai' && !skipsRow setIsLoadingInDecisionView(false) if(isNumber(rowId) && !restoreRefreshRowStage(rowId) && algoId) markAlgo(rowId, algoId, -2) + // A refusal scoped to its request opens no dialog: only its row is + // skipped, and a run goes on. A superseded run's late one comes with no + // row, and isn't this run's. + if(skipsRow) { + if(isRun && isNumber(rowId)) + aiQuotaSkippedRef.current = true + else if(!isRun && isNumber(rowId)) + refreshMapperQuotaCache() + return true + } if(isRun) { if(stopPhase === 'match' && !matchQuotaStopRef.current) matchQuotaStopRef.current = response.error_code if(stopPhase === 'rerank' && !rerankQuotaStopRef.current) rerankQuotaStopRef.current = response.error_code - if(stopPhase === 'ai') + if(stopsAIStep) aiQuotaExhaustedRef.current = true if(runPreviewLimitShownRef.current) return true runPreviewLimitShownRef.current = true } else { - if(stopPhase === 'ai') + if(stopsAIStep) aiQuotaExhaustedRef.current = true if(isNumber(rowId)) refreshMapperQuotaCache() } - setPreviewLimit({errorCode: response.error_code}) + setPreviewLimit({errorCode: response.error_code, capability: response.capability, phase: stopPhase}) return true } @@ -4229,7 +4259,8 @@ const MapProject = () => { const onResponse = (response, payload) => { const projectContext = buildProjectContext() const logExtras = getAlgoLogExtras(getAlgoDef(algoId)) - if(response?.detail) { + // A refusal is handled as one even without a detail. + if(response?.detail || isPreviewLimitError(response)) { if(handlePreviewLimitError(response, __row.__index, algoId)) return clearRefreshRowStageSnapshot(__row.__index) @@ -6119,6 +6150,16 @@ const MapProject = () => { const service = APIService.new() service.URL = getPromptTemplateInvokeURL(activePromptTemplate, promptTemplateRef?.key) const invokeTs = Date.now() + // The reply's usage is this person's, whoever is signed in when it lands. + const invokeUsername = getCurrentUser()?.username + let usageKept = false + // Overlapping single-row calls can land out of order, and each reply's + // usage is a snapshot: the last of them asks for the current count. + if(!isBulk) { + if(singleAICallsInFlightRef.current > 0) + singleAICallsOverlappedRef.current = true + singleAICallsInFlightRef.current += 1 + } try { const response = await retryWithBackoff( attempt => service.request('POST', payload, undefined, {headers: { @@ -6161,19 +6202,25 @@ const MapProject = () => { markRecommend(1) if(!isSuperseded()) aiFailuresInARowRef.current = 0 + // The chip follows the usage the reply reports, also during a run; the + // project keeps the reply without it (OpenConceptLab/ocl_online#641). + usageKept = keepAIAssistantUsageFromReply(response.data, invokeUsername) + if(usageKept) + setAIAssistantUsageVersion(version => version + 1) + const reply = withoutAIAssistantUsage(response.data) // Record the model that answered, not the one the UI shows: the AI // Assistant runs the template's default for everyone but staff. - const modelUsed = getModelUsed(response.data) || requestedModel?.id || null + const modelUsed = getModelUsed(reply) || requestedModel?.id || null const modelUsedRef = modelUsed ? (find(AIModels, {id: modelUsed}) || {id: modelUsed, name: modelUsed}) : null - log({created_at: timestamp, action: 'AIRecommendation', description: get(response.data, 'output.rationale') || get(response.data, 'rationale'), extras: {...response.data, model: modelUsedRef, prompt_template: promptTemplateRef, prompt_template_uri: promptTemplateRef?.uri}}, __index) - const resolvedTemplate = response.data?.template || {} + log({created_at: timestamp, action: 'AIRecommendation', description: get(reply, 'output.rationale') || get(reply, 'rationale'), extras: {...reply, model: modelUsedRef, prompt_template: promptTemplateRef, prompt_template_uri: promptTemplateRef?.uri}}, __index) + const resolvedTemplate = reply?.template || {} const resolvedVersion = resolvedTemplate.version || promptTemplateRef?.version || null const resolvedPromptRef = { ...promptTemplateRef, version: resolvedVersion, uri: resolvedVersion && promptTemplateRef?.key ? `/prompts/${promptTemplateRef.key}/${resolvedVersion}/` : (promptTemplateRef?.uri || null) } - const newEntry = {...response.data, model: modelUsed, model_name: modelUsedRef?.name, prompt_template: resolvedPromptRef, prompt_template_uri: resolvedPromptRef.uri, output_locale: promptOutputLocale || null, candidate_pool_fingerprint: candidatePoolFingerprint, timestamp: timestamp, user: user.username || user.id} + const newEntry = {...reply, model: modelUsed, model_name: modelUsedRef?.name, prompt_template: resolvedPromptRef, prompt_template_uri: resolvedPromptRef.uri, output_locale: promptOutputLocale || null, candidate_pool_fingerprint: candidatePoolFingerprint, timestamp: timestamp, user: user.username || user.id} setAnalysis(prev => ({...prev, [__index]: [...(prev[__index] || []), newEntry]})) // Schedule a save, or leaving loses the result // (OpenConceptLab/ocl_issues#2833). Auto Match rows (isBulk) are saved @@ -6196,8 +6243,13 @@ const MapProject = () => { setAlert({message: errorMessage, severity: 'error'}) return -2 } finally { - if(!isBulk) - refreshMapperQuotaCache() + if(!isBulk) { + singleAICallsInFlightRef.current -= 1 + const lastOfOverlapping = singleAICallsInFlightRef.current === 0 && singleAICallsOverlappedRef.current + if(singleAICallsInFlightRef.current === 0) + singleAICallsOverlappedRef.current = false + refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping}) + } } } else { markRecommend(analysis[__index]?.length > 0 ? 1 : -3) @@ -6758,6 +6810,7 @@ const MapProject = () => { open onClose={() => setPreviewLimit(null)} errorCode={previewLimitQuota.errorCode} + capability={previewLimit.capability} meter={previewLimitQuota.meter} surface={MAPPER_QUOTA_SURFACE[previewLimitQuota.meter]} /> : @@ -6765,6 +6818,8 @@ const MapProject = () => { open={Boolean(previewLimit)} onClose={() => setPreviewLimit(null)} errorCode={previewLimit?.errorCode} + capability={previewLimit?.capability} + phase={previewLimit?.phase} /> } diff --git a/src/components/map-projects/MapProjects.jsx b/src/components/map-projects/MapProjects.jsx index e9e92cd..203d1c8 100644 --- a/src/components/map-projects/MapProjects.jsx +++ b/src/components/map-projects/MapProjects.jsx @@ -31,7 +31,7 @@ import ContentCopy from '@mui/icons-material/ContentCopy'; import DeleteOutlined from '@mui/icons-material/DeleteOutlined'; import APIService from '../../services/APIService' -import { getCurrentUser, getMapperPreview, getNewProjectBlockReason, refreshCurrentUserCapabilitiesCache } from '../../common/utils' +import { getCurrentUser, getMapperPreview, getNewProjectBlockReason, refreshCurrentUserCapabilitiesCache, refreshCapabilitiesAndAIAssistantUsage } from '../../common/utils' import OwnerIcon from '../common/OwnerIcon' import NoResults from '../search/NoResults'; @@ -68,7 +68,8 @@ const MapProjects = () => { const user = getCurrentUser() const [, setQuotaCacheVersion] = React.useState(0) const refreshMapperQuotaCache = React.useCallback(() => { - refreshCurrentUserCapabilitiesCache(() => setQuotaCacheVersion(version => version + 1)) + const onChange = () => setQuotaCacheVersion(version => version + 1) + refreshCapabilitiesAndAIAssistantUsage({onCapabilities: onChange, onUsage: onChange}) }, []) React.useEffect(() => { refreshMapperQuotaCache() }, []) const [newProjectBlock, setNewProjectBlock] = React.useState(null) diff --git a/src/components/map-projects/MapperQuotaChip.jsx b/src/components/map-projects/MapperQuotaChip.jsx index 0229a39..af1184f 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -6,13 +6,43 @@ import Box from '@mui/material/Box' import Typography from '@mui/material/Typography' import { getMapperPreview } from '../../common/utils' +import { getUsageChipReport } from '../../common/aiAssistantUsage' + +// Labels for the units the OCL AI Assistant reports its usage in. +const AI_ASSISTANT_USAGE_LABELS = {calls: 'map_project.preview_quota_ai_calls', tokens: 'map_project.preview_quota_ai_tokens'} + +// The OCL AI Assistant's report as one line: the unit and the count, never a +// limit (OpenConceptLab/ocl_online#641). Nothing for a unit it has no label for. +const UsageLine = ({usage, sx}) => { + const { t } = useTranslation() + return AI_ASSISTANT_USAGE_LABELS[usage.meter] ? ( + + {t(AI_ASSISTANT_USAGE_LABELS[usage.meter])}: {t('map_project.preview_quota_used', {used: usage.used})} + + ) : null +} + +// The report on a chip of its own. +const AIAssistantUsageChip = ({usage, size}) => { + const { t } = useTranslation() + return ( + }> + + + ) +} const MapperQuotaChip = ({size = 'small'}) => { const { t } = useTranslation() const preview = getMapperPreview() - const { rowsPerProject, matchOperations, aiAssistantCalls, projects } = preview + const { rowsPerProject, matchOperations, aiAssistantCalls, aiAssistantUsage, projects } = preview - if(!preview.hasAccess || rowsPerProject.unlimited || rowsPerProject.limit === null) return null + if(!preview.hasAccess) return null + // No Preview chip: the OCL AI Assistant's own report, when it sent one. + if(rowsPerProject.unlimited || rowsPerProject.limit === null) { + const usage = preview.hasAIAssistant ? getUsageChipReport(aiAssistantUsage) : null + return usage ? : null + } // Rows per project is a cap (the first N rows of each project), not a // spendable quota, so the warning colors follow match operations. @@ -38,7 +68,12 @@ const MapperQuotaChip = ({size = 'small'}) => { {t('map_project.preview_quota_rows')}: {t('map_project.preview_quota_rows_cap', {limit: rowsPerProject.limit})} {meterLine('map_project.preview_quota_match_operations', matchOperations)} - {meterLine('map_project.preview_quota_ai_calls', aiAssistantCalls)} + { + // The service's own report, when it sends one. + aiAssistantUsage ? + : + meterLine('map_project.preview_quota_ai_calls', aiAssistantCalls) + } } > diff --git a/src/components/map-projects/PreviewLimitDialog.jsx b/src/components/map-projects/PreviewLimitDialog.jsx index b643981..2289737 100644 --- a/src/components/map-projects/PreviewLimitDialog.jsx +++ b/src/components/map-projects/PreviewLimitDialog.jsx @@ -2,15 +2,15 @@ import React from 'react' import { useTranslation } from 'react-i18next' import LimitDialog from '../common/LimitDialog' -import { PREVIEW_LIMIT_COPY_KEY } from './previewLimits' +import { getPreviewLimitCopyKey } from './previewLimits' // Says what the account can't use. -const PreviewLimitDialog = ({open, onClose, errorCode}) => { +const PreviewLimitDialog = ({open, onClose, errorCode, capability, phase}) => { const { t } = useTranslation() - const kind = PREVIEW_LIMIT_COPY_KEY[errorCode] || 'generic' + const kind = getPreviewLimitCopyKey(errorCode, phase) return ( - + {t([`map_project.limit_unavailable_body_${kind}`, 'map_project.limit_unavailable_body_generic'])} ) diff --git a/src/components/map-projects/__tests__/previewLimits.test.js b/src/components/map-projects/__tests__/previewLimits.test.js index 15772b9..5cc5889 100644 --- a/src/components/map-projects/__tests__/previewLimits.test.js +++ b/src/components/map-projects/__tests__/previewLimits.test.js @@ -3,6 +3,7 @@ import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' import { + getPreviewLimitCopyKey, getPreviewLimitError, isAIPreviewLimitError, isPreviewLimitError, @@ -52,6 +53,22 @@ test('AI preview errors use AI Assistant dialog copy', () => { assert.equal(isAIPreviewLimitError('mapper_match_operations_limit_reached'), false) }) +// OpenConceptLab/ocl_online#641 +test('a refusal with a code the Mapper does not know counts when it names its capability', () => { + const refusal = {error_code: 'example_service_limit_reached', capability: 'example.capability', detail: 'Refused.'} + assert.deepEqual(getPreviewLimitError({response: {status: 403, data: refusal}}), refusal) + assert.equal(isPreviewLimitError({error_code: 'example_service_limit_reached'}), false) + assert.equal(isPreviewLimitError({error_code: 'example_service_limit_reached', capability: 7}), false) + assert.equal(isPreviewLimitError({capability: 'example.capability', detail: 'No code.'}), false) +}) + +test('a refusal with a code the Mapper does not know gets the copy of the step it refused', () => { + assert.equal(getPreviewLimitCopyKey('mapper_scispacy_denied', 'ai'), 'scispacy') + assert.equal(getPreviewLimitCopyKey('example_service_not_entitled', 'ai'), 'ai_assistant') + assert.equal(getPreviewLimitCopyKey('example_service_not_entitled', 'match'), 'generic') + assert.equal(getPreviewLimitCopyKey(undefined, undefined), 'generic') +}) + // Limits reached go to QuotaDialog; PreviewLimitDialog shows the rest. test('every refusal PreviewLimitDialog shows has its own message in each language', () => { for (const locale of ['en', 'es', 'pt-BR', 'zh']) { diff --git a/src/components/map-projects/previewLimits.js b/src/components/map-projects/previewLimits.js index 70e3711..4dc4e56 100644 --- a/src/components/map-projects/previewLimits.js +++ b/src/components/map-projects/previewLimits.js @@ -30,11 +30,21 @@ export const PREVIEW_LIMIT_COPY_KEY = { ai_assistant_calls_not_entitled: 'ai_assistant', } +// A refusal can name what it's about (capability) and how far it reaches +// (scope), in the service's own terms (OpenConceptLab/ocl_online#641). +// One whose code the Mapper doesn't know still counts when it names its +// capability. +const namesItsCapability = response => typeof response?.error_code === 'string' && typeof response?.capability === 'string' + export const getPreviewLimitError = value => { const response = value?.response?.data || value?.data || value - return PREVIEW_LIMIT_ERROR_CODES.has(response?.error_code) ? response : null + return PREVIEW_LIMIT_ERROR_CODES.has(response?.error_code) || namesItsCapability(response) ? response : null } +// The copy for a refusal the Mapper has no code for follows the step it refused. +export const getPreviewLimitCopyKey = (errorCode, phase) => + PREVIEW_LIMIT_COPY_KEY[errorCode] || (phase === 'ai' ? 'ai_assistant' : 'generic') + export const isPreviewLimitError = value => Boolean(getPreviewLimitError(value)) export const isAIPreviewLimitError = errorCode => diff --git a/src/i18n/__tests__/aiAssistantNaming.test.js b/src/i18n/__tests__/aiAssistantNaming.test.js index a0a5971..3b68048 100644 --- a/src/i18n/__tests__/aiAssistantNaming.test.js +++ b/src/i18n/__tests__/aiAssistantNaming.test.js @@ -28,6 +28,9 @@ const NAMES_THE_ASSISTANT = [ 'input_language_helper', 'ai_assistant', 'preview_quota_ai_calls', + 'preview_quota_ai_tokens', + 'ai_assistant_usage_chip_tokens', + 'ai_assistant_usage_chip_calls', 'limit_unavailable_body_ai_assistant', 'column_send_to_ai_assistant', 'ai_prompt_template_description', diff --git a/src/i18n/locales/en/translations.json b/src/i18n/locales/en/translations.json index 0f5e377..b9942bc 100644 --- a/src/i18n/locales/en/translations.json +++ b/src/i18n/locales/en/translations.json @@ -329,7 +329,11 @@ "preview_quota_rows_cap": "first {{limit}} rows of each project", "preview_quota_match_operations": "Match operations", "preview_quota_ai_calls": "OCL AI Assistant calls", + "preview_quota_ai_tokens": "OCL AI Assistant tokens", "preview_quota_used_of_limit": "{{used}} of {{limit}} used", + "preview_quota_used": "{{used, number}} used", + "ai_assistant_usage_chip_tokens": "OCL AI Assistant: {{used, number(notation: compact)}} tokens used", + "ai_assistant_usage_chip_calls": "OCL AI Assistant: {{used, number}} calls used", "preview_rows_activated_notice": "Preview projects hold {{limit}} rows - we activated the first {{limit}} of your {{total}}.", "limit_unavailable_title": "Not available for your account", "limit_unavailable_body_access": "Your account doesn't have access to the Mapper.", diff --git a/src/i18n/locales/es/translations.json b/src/i18n/locales/es/translations.json index f0dc284..f6c9fb1 100644 --- a/src/i18n/locales/es/translations.json +++ b/src/i18n/locales/es/translations.json @@ -310,7 +310,11 @@ "preview_quota_rows_cap": "primeras {{limit}} filas de cada proyecto", "preview_quota_match_operations": "Operaciones de coincidencia", "preview_quota_ai_calls": "Llamadas al asistente de IA de OCL", + "preview_quota_ai_tokens": "Tokens del asistente de IA de OCL", "preview_quota_used_of_limit": "{{used}} de {{limit}} usados", + "preview_quota_used": "{{used, number}} usados", + "ai_assistant_usage_chip_tokens": "Asistente de IA de OCL: {{used, number(notation: compact)}} tokens usados", + "ai_assistant_usage_chip_calls": "Asistente de IA de OCL: {{used, number}} llamadas usadas", "preview_rows_activated_notice": "Los proyectos de vista previa contienen {{limit}} filas: activamos las primeras {{limit}} de tus {{total}}.", "limit_unavailable_title": "No disponible para tu cuenta", "limit_unavailable_body_access": "Tu cuenta no tiene acceso al Mapper.", diff --git a/src/i18n/locales/pt-BR/translations.json b/src/i18n/locales/pt-BR/translations.json index c1d2448..6670508 100644 --- a/src/i18n/locales/pt-BR/translations.json +++ b/src/i18n/locales/pt-BR/translations.json @@ -329,7 +329,11 @@ "preview_quota_rows_cap": "primeiras {{limit}} linhas de cada projeto", "preview_quota_match_operations": "Operações de correspondência", "preview_quota_ai_calls": "Chamadas do Assistente de IA do OCL", + "preview_quota_ai_tokens": "Tokens do Assistente de IA do OCL", "preview_quota_used_of_limit": "{{used}} de {{limit}} usado(s)", + "preview_quota_used": "{{used, number}} usados", + "ai_assistant_usage_chip_tokens": "Assistente de IA do OCL: {{used, number(notation: compact)}} tokens usados", + "ai_assistant_usage_chip_calls": "Assistente de IA do OCL: {{used, number}} chamadas usadas", "preview_rows_activated_notice": "Projetos de prévia contêm {{limit}} linhas - ativamos as primeiras {{limit}} de suas {{total}}.", "limit_unavailable_title": "Não disponível para sua conta", "limit_unavailable_body_access": "Sua conta não tem acesso ao Mapper.", diff --git a/src/i18n/locales/zh/translations.json b/src/i18n/locales/zh/translations.json index 54e1869..b69ca0d 100644 --- a/src/i18n/locales/zh/translations.json +++ b/src/i18n/locales/zh/translations.json @@ -322,7 +322,11 @@ "preview_quota_rows_cap": "每个项目的前 {{limit}} 行", "preview_quota_match_operations": "匹配操作", "preview_quota_ai_calls": "OCL AI 助手调用", + "preview_quota_ai_tokens": "OCL AI 助手 Token", "preview_quota_used_of_limit": "已用 {{used}} / {{limit}}", + "preview_quota_used": "已用 {{used, number}}", + "ai_assistant_usage_chip_tokens": "OCL AI 助手:已用 {{used, number(notation: compact)}} Token", + "ai_assistant_usage_chip_calls": "OCL AI 助手:已调用 {{used, number}} 次", "preview_rows_activated_notice": "预览项目最多包含 {{limit}} 行——我们已激活你 {{total}} 行中的前 {{limit}} 行。", "limit_unavailable_title": "你的账户无法使用此功能", "limit_unavailable_body_access": "你的账户没有 Mapper 访问权限。",