From 3035c34269c21c8b4d6fd8535eea4f9a1004d06d Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Wed, 18 Nov 2026 23:43:17 -0500 Subject: [PATCH 01/12] OpenConceptLab/ocl_online#641 | The Mapper follows a refusal's own scope and capability, and shows the usage the OCL AI Assistant reports Rebuilt on main from the Oct 29 branch reviewed on OpenConceptLab/ocl_online#614. - A 403 with a string error_code and a string capability opens the limit dialog, even with a code the Mapper doesn't know; the dialog asks /billing/plan/ about that capability. - The AI step skips the row on scope "request" and stops otherwise. The Mapper reads no limit, used or renews_at from a refusal. - The Preview chip's tooltip shows {meter, used} from GET /match/usage/, fetched with axios (not APIService, so a throttled refresh never blocks the Mapper) and kept per person; without a report it keeps its call line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 73 +++++++++++++++++++ src/common/aiAssistantUsage.js | 36 +++++++++ src/common/utils.js | 18 +++++ src/components/common/LimitDialog.jsx | 4 +- src/components/common/QuotaDialog.jsx | 4 +- .../common/__tests__/limitAction.test.js | 11 +++ .../common/__tests__/quotaErrors.test.js | 21 ++++++ src/components/common/limitAction.js | 9 ++- src/components/common/useLimitAction.js | 8 +- src/components/map-projects/MapProject.jsx | 45 +++++++++--- src/components/map-projects/MapProjects.jsx | 3 +- .../map-projects/MapperQuotaChip.jsx | 16 +++- .../map-projects/PreviewLimitDialog.jsx | 8 +- .../__tests__/previewLimits.test.js | 17 +++++ src/components/map-projects/previewLimits.js | 12 ++- src/i18n/__tests__/aiAssistantNaming.test.js | 1 + src/i18n/locales/en/translations.json | 7 ++ src/i18n/locales/es/translations.json | 7 ++ src/i18n/locales/pt-BR/translations.json | 7 ++ src/i18n/locales/zh/translations.json | 7 ++ 20 files changed, 286 insertions(+), 28 deletions(-) create mode 100644 src/common/__tests__/aiAssistantUsage.test.js create mode 100644 src/common/aiAssistantUsage.js diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js new file mode 100644 index 00000000..287d9de5 --- /dev/null +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -0,0 +1,73 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +import { getAIAssistantUsage, refreshAIAssistantUsage, toAIAssistantUsage } 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}) +}) + +test('nothing but the unit and the count is read', () => { + 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: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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: '{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: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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) +}) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js new file mode 100644 index 00000000..411bdf36 --- /dev/null +++ b/src/common/aiAssistantUsage.js @@ -0,0 +1,36 @@ +// 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 + +const STORAGE_KEY = 'ai_assistant_usage' + +// The last report kept for this person. Without one, the chip keeps its call line. +export const getAIAssistantUsage = (storage, username) => { + try { + const stored = JSON.parse(storage.getItem(STORAGE_KEY)) + return username && stored?.username === username ? toAIAssistantUsage(stored) : null + } catch(_) { + return null + } +} + +// 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. +// Resolves to whether the kept report changed. +export const refreshAIAssistantUsage = ({get, storage, baseURL, token, username}) => { + if(!baseURL || !token || !username) + return Promise.resolve(false) + const url = `${baseURL.replace(/\/+$/, '')}/match/usage/` + return get(url, {headers: {Authorization: `Token ${token}`}, timeout: 10000}) + .then(response => { + const usage = toAIAssistantUsage(response?.data) + if(usage) + storage.setItem(STORAGE_KEY, JSON.stringify({...usage, username})) + else + storage.removeItem(STORAGE_KEY) + return true + }) + .catch(() => false) +} diff --git a/src/common/utils.js b/src/common/utils.js index 85f38a7a..93dc3b01 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, refreshAIAssistantUsage } from './aiAssistantUsage'; export const currentPath = () => window.location.pathname; @@ -272,6 +274,21 @@ export const refreshCurrentUserCapabilitiesCache = callback => { }); } +// Asks the OCL AI Assistant what it has counted for this person +// (OpenConceptLab/ocl_online#641). +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()) +} + export const replaceCurrentUserCacheWith = data => localStorage.setItem('user', JSON.stringify(data)); export const formatByteSize = bytes => { @@ -1193,6 +1210,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 2032a87c..ccc7a2db 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 19f98997..0c4d5532 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 814f2161..7a73d9b4 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/__tests__/quotaErrors.test.js b/src/components/common/__tests__/quotaErrors.test.js index 1f041c46..b87ec5d5 100644 --- a/src/components/common/__tests__/quotaErrors.test.js +++ b/src/components/common/__tests__/quotaErrors.test.js @@ -1,5 +1,6 @@ import test from 'node:test' import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' import { getQuotaError, isCapMeter, isQuotaError } from '../quotaErrors.js' @@ -30,3 +31,23 @@ test('isCapMeter: only projects and rows are caps', () => { assert.equal(isCapMeter('rows'), true) assert.equal(isCapMeter('match_operations'), false) }) + +// QuotaDialog builds its keys at run time, so the catalog key check can't see +// them. ai_assistant_request is a refusal scoped to its request, with its own +// title (OpenConceptLab/ocl_online#641). +test('every meter a refusal names has its consequence in each language', () => { + const meters = [ + 'mapper_match_operations_limit_reached', + 'ai_assistant_calls_limit_reached', + 'ai_assistant_change_comments_limit_reached', + 'mapper_projects_limit_reached', + 'mapper_rows_per_project_limit_reached', + ].map(error_code => getQuotaError({error_code}).meter) + for (const locale of ['en', 'es', 'pt-BR', 'zh']) { + const quota = JSON.parse(readFileSync(new URL(`../../../i18n/locales/${locale}/translations.json`, import.meta.url), 'utf8')).quota + const consequence = quota.consequence + assert.ok(quota.title_ai_assistant_request, locale) + assert.deepEqual([...meters, 'ai_assistant_request'].filter(meter => !consequence[meter]?.default), [], locale) + assert.deepEqual(['match_operations', 'ai_assistant_calls', 'ai_assistant_request'].filter(meter => !consequence[meter]?.auto_match), [], locale) + } +}) diff --git a/src/components/common/limitAction.js b/src/components/common/limitAction.js index 1871ba85..2751f758 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 bd90292c..63633176 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 23e8065d..398d5ea3 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -73,7 +73,7 @@ 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, refreshCurrentUserCapabilitiesCache, refreshAIAssistantUsageCache } from '../../common/utils'; import { WHITE, SURFACE_COLORS, TEXT_GRAY } from '../../common/colors'; import { useDoubleClick } from '../common/useDoubleClick' @@ -157,8 +157,10 @@ const MapProject = () => { const { toggles, setAlert: baseSetAlert, setProjectRowSearch } = React.useContext(OperationsContext); const user = getCurrentUser() const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) + const [, setAIAssistantUsageVersion] = React.useState(0) const refreshMapperQuotaCache = React.useCallback(() => { refreshCurrentUserCapabilitiesCache(() => setMapperQuotaCacheVersion(version => version + 1)) + refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1)) }, []) const params = useParams() const history = useHistory() @@ -262,7 +264,10 @@ 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); @@ -272,7 +277,8 @@ const MapProject = () => { // Holds the limit's error_code, or null. const matchQuotaStopRef = React.useRef(null); const rerankQuotaStopRef = React.useRef(null); - // The at-limit dialog opens once per run, not once per failed request. + // The at-limit dialog opens once per run, not once per failed request: + // false, true, or 'skip' while only a skipped row's dialog has opened. const runPreviewLimitShownRef = React.useRef(false); const bulkMatchAlgoIdsRef = React.useRef([]); // ocl_online#105 Phase 5: the active AutomatchRun ({id, algoIds}) or null. @@ -290,7 +296,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, skipsRow, isRun} or null const previewLimitQuota = previewLimit ? getQuotaError({error_code: previewLimit.errorCode}) : null const [row, setRow] = React.useState(false) @@ -2121,7 +2127,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 +2425,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,6 +4061,10 @@ 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) @@ -4062,18 +4073,22 @@ const MapProject = () => { 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) + // A superseded run's late refusal comes with no row, and isn't this run's. + else if(skipsRow && isNumber(rowId)) + aiQuotaSkippedRef.current = true + // A skipped row's dialog says the run goes on, so a stop after it is shown too. + if(runPreviewLimitShownRef.current && (skipsRow || runPreviewLimitShownRef.current !== 'skip')) return true - runPreviewLimitShownRef.current = true + runPreviewLimitShownRef.current = skipsRow ? 'skip' : 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, skipsRow, isRun}) return true } @@ -6753,11 +6768,21 @@ const MapProject = () => { }} /> { + previewLimit?.skipsRow ? + setPreviewLimit(null)} + errorCode={previewLimit.errorCode} + capability={previewLimit.capability} + meter='ai_assistant_request' + surface={previewLimit.isRun ? 'auto_match' : 'default'} + /> : previewLimitQuota ? setPreviewLimit(null)} errorCode={previewLimitQuota.errorCode} + capability={previewLimit.capability} meter={previewLimitQuota.meter} surface={MAPPER_QUOTA_SURFACE[previewLimitQuota.meter]} /> : @@ -6765,6 +6790,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 e9e92cd8..054af2fb 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, refreshAIAssistantUsageCache } from '../../common/utils' import OwnerIcon from '../common/OwnerIcon' import NoResults from '../search/NoResults'; @@ -69,6 +69,7 @@ const MapProjects = () => { const [, setQuotaCacheVersion] = React.useState(0) const refreshMapperQuotaCache = React.useCallback(() => { refreshCurrentUserCapabilitiesCache(() => setQuotaCacheVersion(version => version + 1)) + refreshAIAssistantUsageCache(() => setQuotaCacheVersion(version => version + 1)) }, []) 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 0229a393..6d8ded70 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -7,10 +7,13 @@ import Typography from '@mui/material/Typography' import { getMapperPreview } from '../../common/utils' +// 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'} + 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 @@ -38,7 +41,16 @@ 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: a unit and the count + // used (OpenConceptLab/ocl_online#641). + aiAssistantUsage ? + AI_ASSISTANT_USAGE_LABELS[aiAssistantUsage.meter] && + + {t(AI_ASSISTANT_USAGE_LABELS[aiAssistantUsage.meter])}: {t('map_project.preview_quota_used', {used: aiAssistantUsage.used})} + : + 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 b6439813..2289737a 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 15772b98..5cc5889c 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 70e37114..4dc4e566 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 a0a59714..e7487ccb 100644 --- a/src/i18n/__tests__/aiAssistantNaming.test.js +++ b/src/i18n/__tests__/aiAssistantNaming.test.js @@ -28,6 +28,7 @@ const NAMES_THE_ASSISTANT = [ 'input_language_helper', 'ai_assistant', 'preview_quota_ai_calls', + 'preview_quota_ai_tokens', '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 0f5e377e..657310f9 100644 --- a/src/i18n/locales/en/translations.json +++ b/src/i18n/locales/en/translations.json @@ -329,7 +329,9 @@ "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", "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.", @@ -584,12 +586,17 @@ "quota": { "title_quota": "You've reached your quota", "title_cap": "You've reached your limit", + "title_ai_assistant_request": "The OCL AI Assistant skipped a row", "consequence": { "generic": "Some features are paused.", "ai_assistant_calls": { "default": "Features that use the OCL AI Assistant are paused.", "auto_match": "AutoMatch will keep running without recommendations from the OCL AI Assistant." }, + "ai_assistant_request": { + "default": "The OCL AI Assistant can't analyse this request now.", + "auto_match": "AutoMatch will keep running. The OCL AI Assistant skips rows it can't analyse now and goes on to the next ones." + }, "ai_assistant_change_comments": { "default": "You can still write the update comment yourself, without a draft from the OCL AI Assistant.", "tbv3_change_comment": "You can still write the update comment yourself, without a draft from the OCL AI Assistant." diff --git a/src/i18n/locales/es/translations.json b/src/i18n/locales/es/translations.json index f0dc2849..2d7fcf26 100644 --- a/src/i18n/locales/es/translations.json +++ b/src/i18n/locales/es/translations.json @@ -310,7 +310,9 @@ "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", "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.", @@ -584,12 +586,17 @@ "quota": { "title_quota": "Ha alcanzado su cuota", "title_cap": "Ha alcanzado su límite", + "title_ai_assistant_request": "El asistente de IA de OCL omitió una fila", "consequence": { "generic": "Algunas funciones están en pausa.", "ai_assistant_calls": { "default": "Las funciones que usan el asistente de IA de OCL están en pausa.", "auto_match": "AutoMatch seguirá funcionando sin recomendaciones del asistente de IA de OCL." }, + "ai_assistant_request": { + "default": "El asistente de IA de OCL no puede analizar esta solicitud ahora.", + "auto_match": "AutoMatch seguirá funcionando. El asistente de IA de OCL omite las filas que no puede analizar ahora y continúa con las siguientes." + }, "ai_assistant_change_comments": { "default": "Aún puede escribir el comentario de actualización usted mismo, sin un borrador del asistente de IA de OCL.", "tbv3_change_comment": "Aún puede escribir el comentario de actualización usted mismo, sin un borrador del asistente de IA de OCL." diff --git a/src/i18n/locales/pt-BR/translations.json b/src/i18n/locales/pt-BR/translations.json index c1d24487..d28b3873 100644 --- a/src/i18n/locales/pt-BR/translations.json +++ b/src/i18n/locales/pt-BR/translations.json @@ -329,7 +329,9 @@ "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", "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.", @@ -584,12 +586,17 @@ "quota": { "title_quota": "Você atingiu sua cota", "title_cap": "Você atingiu seu limite", + "title_ai_assistant_request": "O Assistente de IA do OCL pulou uma linha", "consequence": { "generic": "Alguns recursos estão pausados.", "ai_assistant_calls": { "default": "Recursos que usam o Assistente de IA do OCL estão pausados.", "auto_match": "O AutoMatch continuará rodando sem recomendações do Assistente de IA do OCL." }, + "ai_assistant_request": { + "default": "O Assistente de IA do OCL não pode analisar esta solicitação agora.", + "auto_match": "O AutoMatch continuará rodando. O Assistente de IA do OCL pula as linhas que não pode analisar agora e segue para as próximas." + }, "ai_assistant_change_comments": { "default": "Você ainda pode escrever o comentário de atualização sozinho, sem um rascunho do Assistente de IA do OCL.", "tbv3_change_comment": "Você ainda pode escrever o comentário de atualização sozinho, sem um rascunho do Assistente de IA do OCL." diff --git a/src/i18n/locales/zh/translations.json b/src/i18n/locales/zh/translations.json index 54e18693..cc43b4d6 100644 --- a/src/i18n/locales/zh/translations.json +++ b/src/i18n/locales/zh/translations.json @@ -322,7 +322,9 @@ "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}}", "preview_rows_activated_notice": "预览项目最多包含 {{limit}} 行——我们已激活你 {{total}} 行中的前 {{limit}} 行。", "limit_unavailable_title": "你的账户无法使用此功能", "limit_unavailable_body_access": "你的账户没有 Mapper 访问权限。", @@ -583,12 +585,17 @@ "quota": { "title_quota": "您已达到配额上限", "title_cap": "您已达到使用上限", + "title_ai_assistant_request": "OCL AI 助手跳过了一行", "consequence": { "generic": "部分功能已暂停。", "ai_assistant_calls": { "default": "使用 OCL AI 助手的功能已暂停。", "auto_match": "AutoMatch 将继续运行,但不再提供 OCL AI 助手的推荐。" }, + "ai_assistant_request": { + "default": "OCL AI 助手现在无法分析此请求。", + "auto_match": "AutoMatch 将继续运行。OCL AI 助手会跳过现在无法分析的行,继续处理后续的行。" + }, "ai_assistant_change_comments": { "default": "您仍可自行撰写更新备注,只是没有 OCL AI 助手的草稿。", "tbv3_change_comment": "您仍可自行撰写更新备注,只是没有 OCL AI 助手的草稿。" From 1238cac46b66c63b135286d8cc5691d477d5d012 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Wed, 18 Nov 2026 23:43:18 -0500 Subject: [PATCH 02/12] OpenConceptLab/ocl_online#641 | The Mapper follows the usage each $invoke reply reports, and a chip shows it where there's no Preview chip - A reply's metadata.usage ({meter, used}) is kept as a /match/usage/ refresh would keep it, also during a run, so the Mapper asks /match/usage/ only for first paint and after a refusal or error. - What a project stores of a reply (its analysis history and log) leaves out metadata.usage: it's the person's own count, and a project can be an organization's. - Where the Mapper shows no Preview chip, a chip shows the OCL AI Assistant's report: "OCL AI Assistant: 1.2M tokens used", the exact count in its tooltip. USAGE_CHIP_METERS says which units get it. - Copy in en, es, pt-BR and zh. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 35 ++++++++++++++++++- src/common/aiAssistantUsage.js | 26 ++++++++++++++ src/common/utils.js | 6 +++- src/components/map-projects/MapProject.jsx | 27 +++++++++----- .../map-projects/MapperQuotaChip.jsx | 25 ++++++++++++- src/i18n/__tests__/aiAssistantNaming.test.js | 2 ++ src/i18n/locales/en/translations.json | 2 ++ src/i18n/locales/es/translations.json | 2 ++ src/i18n/locales/pt-BR/translations.json | 2 ++ src/i18n/locales/zh/translations.json | 2 ++ 10 files changed, 118 insertions(+), 11 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index 287d9de5..c5328309 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -1,7 +1,7 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { getAIAssistantUsage, refreshAIAssistantUsage, toAIAssistantUsage } from '../aiAssistantUsage.js' +import { getAIAssistantUsage, getUsageChipReport, keepAIAssistantUsage, refreshAIAssistantUsage, toAIAssistantUsage, withoutAIAssistantUsage } from '../aiAssistantUsage.js' const memoryStorage = (initial = {}) => { const store = {...initial} @@ -71,3 +71,36 @@ test('no service URL, token or person: nothing is asked', async () => { 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: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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)) +}) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index 411bdf36..14243822 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -3,6 +3,12 @@ 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 + const STORAGE_KEY = 'ai_assistant_usage' // The last report kept for this person. Without one, the chip keeps its call line. @@ -15,6 +21,26 @@ export const getAIAssistantUsage = (storage, username) => { } } +// Keeps the report a reply carries in `metadata.usage` (an $invoke reply), as +// a refresh would. Returns whether it kept one. +export const keepAIAssistantUsage = (storage, username, reply) => { + const usage = toAIAssistantUsage(reply?.metadata?.usage) + if(!usage || !username) + return false + storage.setItem(STORAGE_KEY, JSON.stringify({...usage, username})) + return true +} + +// The reply without `metadata.usage`, for what a project stores: the report is +// the person's own count, and a project's history can be an organization's. +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. diff --git a/src/common/utils.js b/src/common/utils.js index 93dc3b01..7c1898c3 100644 --- a/src/common/utils.js +++ b/src/common/utils.js @@ -20,7 +20,7 @@ import { ensureIdToken, prepareSignOut, settleForcedSignOut, renewSessionSilentl import { SERVER_CONFIGS } from './serverConfigs'; import { legacyHashRoute, isSameSitePath } from './history'; import { resolveV3URL, resolveIntegratedV3URL } from './appUrls'; -import { getAIAssistantUsage, refreshAIAssistantUsage } from './aiAssistantUsage'; +import { getAIAssistantUsage, keepAIAssistantUsage, refreshAIAssistantUsage } from './aiAssistantUsage'; export const currentPath = () => window.location.pathname; @@ -289,6 +289,10 @@ export const refreshAIAssistantUsageCache = callback => { }).then(changed => changed && callback && callback()) } +// Keeps the usage an OCL AI Assistant reply carries for the person signed in. +// Returns whether it kept one. +export const keepAIAssistantUsageFromReply = reply => keepAIAssistantUsage(localStorage, getCurrentUser()?.username, reply) + export const replaceCurrentUserCacheWith = data => localStorage.setItem('user', JSON.stringify(data)); export const formatByteSize = bytes => { diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 398d5ea3..95a6f906 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, refreshAIAssistantUsageCache } from '../../common/utils'; +import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCurrentUserCapabilitiesCache, refreshAIAssistantUsageCache, keepAIAssistantUsageFromReply } from '../../common/utils'; +import { withoutAIAssistantUsage } from '../../common/aiAssistantUsage'; import { WHITE, SURFACE_COLORS, TEXT_GRAY } from '../../common/colors'; import { useDoubleClick } from '../common/useDoubleClick' @@ -158,9 +159,12 @@ const MapProject = () => { const user = getCurrentUser() const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) const [, setAIAssistantUsageVersion] = React.useState(0) - const refreshMapperQuotaCache = React.useCallback(() => { + // {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} = {}) => { refreshCurrentUserCapabilitiesCache(() => setMapperQuotaCacheVersion(version => version + 1)) - refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1)) + if(usage) + refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1)) }, []) const params = useParams() const history = useHistory() @@ -6134,6 +6138,7 @@ const MapProject = () => { const service = APIService.new() service.URL = getPromptTemplateInvokeURL(activePromptTemplate, promptTemplateRef?.key) const invokeTs = Date.now() + let usageKept = false try { const response = await retryWithBackoff( attempt => service.request('POST', payload, undefined, {headers: { @@ -6176,19 +6181,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) + 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 @@ -6212,7 +6223,7 @@ const MapProject = () => { return -2 } finally { if(!isBulk) - refreshMapperQuotaCache() + refreshMapperQuotaCache({usage: !usageKept}) } } else { markRecommend(analysis[__index]?.length > 0 ? 1 : -3) diff --git a/src/components/map-projects/MapperQuotaChip.jsx b/src/components/map-projects/MapperQuotaChip.jsx index 6d8ded70..5222ec45 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -6,16 +6,39 @@ 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 usage the OCL AI Assistant reports, on a chip of its own: the unit and +// the count, never a limit (OpenConceptLab/ocl_online#641). +const AIAssistantUsageChip = ({usage, size}) => { + const { t } = useTranslation() + return ( + + {t(AI_ASSISTANT_USAGE_LABELS[usage.meter])}: {t('map_project.preview_quota_used', {used: usage.used})} + + } + > + + + ) +} + const MapperQuotaChip = ({size = 'small'}) => { const { t } = useTranslation() const preview = getMapperPreview() 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. diff --git a/src/i18n/__tests__/aiAssistantNaming.test.js b/src/i18n/__tests__/aiAssistantNaming.test.js index e7487ccb..3b680484 100644 --- a/src/i18n/__tests__/aiAssistantNaming.test.js +++ b/src/i18n/__tests__/aiAssistantNaming.test.js @@ -29,6 +29,8 @@ const NAMES_THE_ASSISTANT = [ '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 657310f9..940b8ddc 100644 --- a/src/i18n/locales/en/translations.json +++ b/src/i18n/locales/en/translations.json @@ -332,6 +332,8 @@ "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 2d7fcf26..4a224e42 100644 --- a/src/i18n/locales/es/translations.json +++ b/src/i18n/locales/es/translations.json @@ -313,6 +313,8 @@ "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 d28b3873..49274590 100644 --- a/src/i18n/locales/pt-BR/translations.json +++ b/src/i18n/locales/pt-BR/translations.json @@ -332,6 +332,8 @@ "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 cc43b4d6..9c8783e3 100644 --- a/src/i18n/locales/zh/translations.json +++ b/src/i18n/locales/zh/translations.json @@ -325,6 +325,8 @@ "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 访问权限。", From 9a72acd109b39ba79e2f8301022417151ad6b7ec Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Wed, 18 Nov 2026 23:53:09 -0500 Subject: [PATCH 03/12] OpenConceptLab/ocl_online#641 | Each person keeps their own usage report, a refresh can't overwrite a newer one, and storage errors cost only the report Codex pass 1: - F1.1: a /match/usage/ refresh sent before an $invoke reply kept its report no longer overwrites that report with the older count. - F1.2: reports are kept under one key per person, so another account signing in on the same browser doesn't evict them. - F1.4: a reply's report is kept for the person signed in when the request was sent. - F1.6: a full or blocked storage no longer throws out of the success path, so the recommendation is still saved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 37 ++++++++++++--- src/common/aiAssistantUsage.js | 45 +++++++++++++------ src/common/utils.js | 6 +-- src/components/map-projects/MapProject.jsx | 4 +- 4 files changed, 70 insertions(+), 22 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index c5328309..a40e5405 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -31,12 +31,12 @@ test('a report without a unit and a count is no report', () => { }) test('a kept report is only for the person it was asked for', () => { - const storage = memoryStorage({ai_assistant_usage: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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: '{not json'}), '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 () => { @@ -53,7 +53,7 @@ test('asks the service with the person\'s token and keeps its report', async () test('a failed or throttled request keeps the last report', async () => { for (const status of [429, 404, 500]) { - const storage = memoryStorage({ai_assistant_usage: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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)) @@ -61,7 +61,7 @@ test('a failed or throttled request keeps the last report', async () => { }) test('a report without a unit and a count clears the kept one', async () => { - const storage = memoryStorage({ai_assistant_usage: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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) }) @@ -81,7 +81,7 @@ test('a reply\'s usage is kept for the person, as a refresh keeps it', () => { }) test('a reply without a usage report keeps the last one', () => { - const storage = memoryStorage({ai_assistant_usage: JSON.stringify({meter: 'tokens', used: 5, username: 'someone'})}) + 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) @@ -104,3 +104,30 @@ test('the usage chip shows a report in a unit it knows, and nothing else', () => 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 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) +}) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index 14243822..d78072be 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -9,25 +9,44 @@ export const USAGE_CHIP_METERS = ['calls', 'tokens'] export const getUsageChipReport = usage => usage && USAGE_CHIP_METERS.includes(usage.meter) ? usage : null -const STORAGE_KEY = 'ai_assistant_usage' +// Each person's last report, under their own key. +const storageKey = username => `ai_assistant_usage:${username}` + +// Counts the reports kept from replies, so a refresh that was sent before one +// doesn't overwrite it with an older count. +let keptFromReplies = 0 + +// 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 { - const stored = JSON.parse(storage.getItem(STORAGE_KEY)) - return username && stored?.username === username ? toAIAssistantUsage(stored) : null + return toAIAssistantUsage(JSON.parse(storage.getItem(storageKey(username)))) } catch(_) { return null } } -// Keeps the report a reply carries in `metadata.usage` (an $invoke reply), as -// a refresh would. Returns whether it kept one. +// 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 - storage.setItem(STORAGE_KEY, JSON.stringify({...usage, username})) + keptFromReplies += 1 + store(storage, username, usage) return true } @@ -43,19 +62,19 @@ export const withoutAIAssistantUsage = reply => { // 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. -// Resolves to whether the kept report changed. +// without a unit and a count clears the kept one; a failed request, or one +// overtaken by a reply's report, keeps it. Resolves to whether the kept +// report changed. export const refreshAIAssistantUsage = ({get, storage, baseURL, token, username}) => { if(!baseURL || !token || !username) return Promise.resolve(false) const url = `${baseURL.replace(/\/+$/, '')}/match/usage/` + const keptBefore = keptFromReplies return get(url, {headers: {Authorization: `Token ${token}`}, timeout: 10000}) .then(response => { - const usage = toAIAssistantUsage(response?.data) - if(usage) - storage.setItem(STORAGE_KEY, JSON.stringify({...usage, username})) - else - storage.removeItem(STORAGE_KEY) + if(keptFromReplies !== keptBefore) + return false + store(storage, username, toAIAssistantUsage(response?.data)) return true }) .catch(() => false) diff --git a/src/common/utils.js b/src/common/utils.js index 7c1898c3..d5eb1d52 100644 --- a/src/common/utils.js +++ b/src/common/utils.js @@ -289,9 +289,9 @@ export const refreshAIAssistantUsageCache = callback => { }).then(changed => changed && callback && callback()) } -// Keeps the usage an OCL AI Assistant reply carries for the person signed in. -// Returns whether it kept one. -export const keepAIAssistantUsageFromReply = reply => keepAIAssistantUsage(localStorage, getCurrentUser()?.username, reply) +// 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)); diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 95a6f906..8346e2e4 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -6138,6 +6138,8 @@ 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 try { const response = await retryWithBackoff( @@ -6183,7 +6185,7 @@ const MapProject = () => { 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) + usageKept = keepAIAssistantUsageFromReply(response.data, invokeUsername) if(usageKept) setAIAssistantUsageVersion(version => version + 1) const reply = withoutAIAssistantUsage(response.data) From 95dfe6e62d21e5a4d541b17b848ef27435519d1a Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Wed, 18 Nov 2026 23:59:03 -0500 Subject: [PATCH 04/12] OpenConceptLab/ocl_online#641 | A refresh yields to any report kept while it was in flight; refusals keep their capability everywhere Codex pass 2: - F2.1: a /match/usage/ refresh compares what's kept for the person before and after, so a report kept by another tab is no longer overwritten by an older count. - F2.3: a superseded run's late request-scoped refusal leaves the current run's dialog and skip flag alone. - F2.4: the save and AutoMatch run handlers pass the refusal's capability to the dialog. - F2.5: a candidate-matching refusal without a detail is handled as a refusal, not as an empty match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 12 ++++++++++ src/common/aiAssistantUsage.js | 24 ++++++++++++------- src/components/map-projects/MapProject.jsx | 16 ++++++++----- 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index a40e5405..cd7b8cb5 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -126,6 +126,18 @@ test('a refresh sent before a reply\'s report doesn\'t overwrite it', async () = 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) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index d78072be..9eaeca3d 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -12,9 +12,15 @@ export const getUsageChipReport = usage => usage && USAGE_CHIP_METERS.includes(u // Each person's last report, under their own key. const storageKey = username => `ai_assistant_usage:${username}` -// Counts the reports kept from replies, so a refresh that was sent before one -// doesn't overwrite it with an older count. -let keptFromReplies = 0 +// 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) => { @@ -45,7 +51,6 @@ export const keepAIAssistantUsage = (storage, username, reply) => { const usage = toAIAssistantUsage(reply?.metadata?.usage) if(!usage || !username) return false - keptFromReplies += 1 store(storage, username, usage) return true } @@ -62,17 +67,18 @@ export const withoutAIAssistantUsage = reply => { // 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, or one -// overtaken by a reply's report, keeps it. Resolves to whether the kept -// report changed. +// 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. export const refreshAIAssistantUsage = ({get, storage, baseURL, token, username}) => { if(!baseURL || !token || !username) return Promise.resolve(false) const url = `${baseURL.replace(/\/+$/, '')}/match/usage/` - const keptBefore = keptFromReplies + const keptBefore = read(storage, username) return get(url, {headers: {Authorization: `Token ${token}`}, timeout: 10000}) .then(response => { - if(keptFromReplies !== keptBefore) + if(read(storage, username) !== keptBefore) return false store(storage, username, toAIAssistantUsage(response?.data)) return true diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 8346e2e4..775b1910 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -114,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' @@ -1854,7 +1854,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}) } @@ -2101,7 +2101,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})}}) @@ -4072,6 +4072,10 @@ const MapProject = () => { setIsLoadingInDecisionView(false) if(isNumber(rowId) && !restoreRefreshRowStage(rowId) && algoId) markAlgo(rowId, algoId, -2) + // A superseded run's late refusal comes with no row: one scoped to its + // request isn't this run's, so it leaves this run's dialog alone. + if(isRun && skipsRow && !isNumber(rowId)) + return true if(isRun) { if(stopPhase === 'match' && !matchQuotaStopRef.current) matchQuotaStopRef.current = response.error_code @@ -4079,8 +4083,7 @@ const MapProject = () => { rerankQuotaStopRef.current = response.error_code if(stopsAIStep) aiQuotaExhaustedRef.current = true - // A superseded run's late refusal comes with no row, and isn't this run's. - else if(skipsRow && isNumber(rowId)) + else if(skipsRow) aiQuotaSkippedRef.current = true // A skipped row's dialog says the run goes on, so a stop after it is shown too. if(runPreviewLimitShownRef.current && (skipsRow || runPreviewLimitShownRef.current !== 'skip')) @@ -4248,7 +4251,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) From 7fc52c833335f5a781e66846517fe632bcc6de52 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 00:05:03 -0500 Subject: [PATCH 05/12] OpenConceptLab/ocl_online#641 | Ask the OCL AI Assistant for usage once the permissions are fresh Codex pass 3, F3.3 (P2): the usage refresh is limited to people with the OCL AI Assistant permission, so it now runs after the permissions refresh lands rather than beside it, and a stale cached permission no longer skips it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/components/map-projects/MapProject.jsx | 11 +++++++---- src/components/map-projects/MapProjects.jsx | 6 ++++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 775b1910..1d469bc1 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -159,12 +159,15 @@ const MapProject = () => { const user = getCurrentUser() const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) const [, setAIAssistantUsageVersion] = React.useState(0) - // {usage: false} skips asking the OCL AI Assistant, when its reply already + // The OCL AI Assistant is asked once the permissions are fresh, since only + // those with it are asked; {usage: false} skips it when a reply already // carried the usage (OpenConceptLab/ocl_online#641). const refreshMapperQuotaCache = React.useCallback(({usage = true} = {}) => { - refreshCurrentUserCapabilitiesCache(() => setMapperQuotaCacheVersion(version => version + 1)) - if(usage) - refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1)) + refreshCurrentUserCapabilitiesCache(() => { + setMapperQuotaCacheVersion(version => version + 1) + if(usage) + refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1)) + }) }, []) const params = useParams() const history = useHistory() diff --git a/src/components/map-projects/MapProjects.jsx b/src/components/map-projects/MapProjects.jsx index 054af2fb..9d4ebd9a 100644 --- a/src/components/map-projects/MapProjects.jsx +++ b/src/components/map-projects/MapProjects.jsx @@ -68,8 +68,10 @@ const MapProjects = () => { const user = getCurrentUser() const [, setQuotaCacheVersion] = React.useState(0) const refreshMapperQuotaCache = React.useCallback(() => { - refreshCurrentUserCapabilitiesCache(() => setQuotaCacheVersion(version => version + 1)) - refreshAIAssistantUsageCache(() => setQuotaCacheVersion(version => version + 1)) + refreshCurrentUserCapabilitiesCache(() => { + setQuotaCacheVersion(version => version + 1) + refreshAIAssistantUsageCache(() => setQuotaCacheVersion(version => version + 1)) + }) }, []) React.useEffect(() => { refreshMapperQuotaCache() }, []) const [newProjectBlock, setNewProjectBlock] = React.useState(null) From 72ba7ed03a5d4b40578151fff41dcc8bade93796 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 00:06:43 -0500 Subject: [PATCH 06/12] OpenConceptLab/ocl_online#641 | Simplification: one usage line for the chip and the Preview tooltip, one test for what's read From the simplification review: S3 (the usage line built once, in UsageLine, for both places) and S2 (the extra-fields check joins the first toAIAssistantUsage test). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 4 +-- .../map-projects/MapperQuotaChip.jsx | 30 +++++++++---------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index cd7b8cb5..d22e7aec 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -19,9 +19,7 @@ const REQUEST = {baseURL: 'https://ai.example.org/', token: 'personal-token', us 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}) -}) - -test('nothing but the unit and the count is read', () => { + // nothing but the unit and the count assert.deepEqual(toAIAssistantUsage({meter: 'tokens', used: 5, limit: 3000, remaining: 2995}), {meter: 'tokens', used: 5}) }) diff --git a/src/components/map-projects/MapperQuotaChip.jsx b/src/components/map-projects/MapperQuotaChip.jsx index 5222ec45..af1184fb 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -11,18 +11,22 @@ 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 usage the OCL AI Assistant reports, on a chip of its own: the unit and -// the count, never a limit (OpenConceptLab/ocl_online#641). +// 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 ( - - {t(AI_ASSISTANT_USAGE_LABELS[usage.meter])}: {t('map_project.preview_quota_used', {used: usage.used})} - - } - > + }> ) @@ -65,13 +69,9 @@ const MapperQuotaChip = ({size = 'small'}) => { {meterLine('map_project.preview_quota_match_operations', matchOperations)} { - // The service's own report, when it sends one: a unit and the count - // used (OpenConceptLab/ocl_online#641). + // The service's own report, when it sends one. aiAssistantUsage ? - AI_ASSISTANT_USAGE_LABELS[aiAssistantUsage.meter] && - - {t(AI_ASSISTANT_USAGE_LABELS[aiAssistantUsage.meter])}: {t('map_project.preview_quota_used', {used: aiAssistantUsage.used})} - : + : meterLine('map_project.preview_quota_ai_calls', aiAssistantCalls) } From b470e4d9cfc8c1bc15cec424c2e6e6385c03b19d Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 00:08:24 -0500 Subject: [PATCH 07/12] OpenConceptLab/ocl_online#641 | After overlapping single-row AI calls, the last one asks for the current usage Codex pass 3, F3.1 (P1): each reply's usage is a snapshot, and overlapping calls can land out of order, so the chip could keep an older count. The reports carry no time to order them by, so when single-row calls overlap, the last to finish refreshes from /match/usage/ instead of trusting its own reply. An AutoMatch run already refreshes when it ends. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/components/map-projects/MapProject.jsx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 1d469bc1..e7e0b23a 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -278,6 +278,10 @@ const MapProject = () => { // 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. @@ -6148,6 +6152,13 @@ const MapProject = () => { // 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: { @@ -6231,8 +6242,13 @@ const MapProject = () => { setAlert({message: errorMessage, severity: 'error'}) return -2 } finally { - if(!isBulk) - refreshMapperQuotaCache({usage: !usageKept}) + 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) From 9f040df8d6dd245d0219e936b465a6b5d9790708 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 00:12:46 -0500 Subject: [PATCH 08/12] OpenConceptLab/ocl_online#641 | Usage is asked for beside the permissions again, and one refresh at a time per person Final Codex check of 95dfe6e..b470e4d: - FC.1 (P1): chaining the usage refresh after the permissions refresh skipped it whenever /user/ failed. refreshCapabilitiesAndAIAssistantUsage asks for both side by side again, and asks for usage once more when the fresh permissions newly grant the OCL AI Assistant (pass 3's F3.3). - FC.2 (P2): a refresh asked for while one is in flight waits for it, and those requests share one more, so a refresh can't overtake another and discard its newer count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 23 ++++++++++++++++ src/common/aiAssistantUsage.js | 27 ++++++++++++++++--- src/common/utils.js | 15 +++++++++++ src/components/map-projects/MapProject.jsx | 13 +++++---- src/components/map-projects/MapProjects.jsx | 8 +++--- 5 files changed, 71 insertions(+), 15 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index d22e7aec..cd7c9bd7 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -141,3 +141,26 @@ test('a storage that refuses to keep a report throws nothing', async () => { 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 => setImmediate(resolve)) + 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}) +}) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index 9eaeca3d..0ed8da31 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -71,9 +71,7 @@ export const withoutAIAssistantUsage = reply => { // 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. -export const refreshAIAssistantUsage = ({get, storage, baseURL, token, username}) => { - if(!baseURL || !token || !username) - return Promise.resolve(false) +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}) @@ -85,3 +83,26 @@ export const refreshAIAssistantUsage = ({get, storage, baseURL, token, username} }) .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 = {} + +export const refreshAIAssistantUsage = request => { + const { baseURL, token, username } = request + if(!baseURL || !token || !username) + return Promise.resolve(false) + const running = refreshing[username] + if(running) { + running.next = running.next || running.promise.then(() => refreshAIAssistantUsage(request)) + return running.next + } + const entry = {} + entry.promise = fetchAIAssistantUsage(request).finally(() => { + if(refreshing[username] === entry) + delete refreshing[username] + }) + refreshing[username] = entry + return entry.promise +} diff --git a/src/common/utils.js b/src/common/utils.js index d5eb1d52..5ab8316c 100644 --- a/src/common/utils.js +++ b/src/common/utils.js @@ -276,6 +276,21 @@ 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')) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index e7e0b23a..6f50db51 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -73,7 +73,7 @@ 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, refreshAIAssistantUsageCache, keepAIAssistantUsageFromReply } 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'; @@ -159,14 +159,13 @@ const MapProject = () => { const user = getCurrentUser() const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) const [, setAIAssistantUsageVersion] = React.useState(0) - // The OCL AI Assistant is asked once the permissions are fresh, since only - // those with it are asked; {usage: false} skips it when a reply already + // {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} = {}) => { - refreshCurrentUserCapabilitiesCache(() => { - setMapperQuotaCacheVersion(version => version + 1) - if(usage) - refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1)) + refreshCapabilitiesAndAIAssistantUsage({ + onCapabilities: () => setMapperQuotaCacheVersion(version => version + 1), + onUsage: () => setAIAssistantUsageVersion(version => version + 1), + usage, }) }, []) const params = useParams() diff --git a/src/components/map-projects/MapProjects.jsx b/src/components/map-projects/MapProjects.jsx index 9d4ebd9a..203d1c80 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, refreshAIAssistantUsageCache } from '../../common/utils' +import { getCurrentUser, getMapperPreview, getNewProjectBlockReason, refreshCurrentUserCapabilitiesCache, refreshCapabilitiesAndAIAssistantUsage } from '../../common/utils' import OwnerIcon from '../common/OwnerIcon' import NoResults from '../search/NoResults'; @@ -68,10 +68,8 @@ const MapProjects = () => { const user = getCurrentUser() const [, setQuotaCacheVersion] = React.useState(0) const refreshMapperQuotaCache = React.useCallback(() => { - refreshCurrentUserCapabilitiesCache(() => { - setQuotaCacheVersion(version => version + 1) - refreshAIAssistantUsageCache(() => setQuotaCacheVersion(version => version + 1)) - }) + const onChange = () => setQuotaCacheVersion(version => version + 1) + refreshCapabilitiesAndAIAssistantUsage({onCapabilities: onChange, onUsage: onChange}) }, []) React.useEffect(() => { refreshMapperQuotaCache() }, []) const [newProjectBlock, setNewProjectBlock] = React.useState(null) From 0037e49c918ab1da40b05027c949e50730f3a5c6 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 00:15:35 -0500 Subject: [PATCH 09/12] OpenConceptLab/ocl_online#641 | The refresh queue is a Map, and the queue test passes CI's lint Final Codex check of b470e4d..9f040df: - FC.1 (P1): the new test used setImmediate, which CI's ESLint rejects (no-undef); it waits with setTimeout instead. - FC.2 (P2): the per-person refresh queue was a plain object, so a username such as "constructor" found an inherited property; it's a Map. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 9 ++++++++- src/common/aiAssistantUsage.js | 10 +++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index cd7c9bd7..a5fe027c 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -158,9 +158,16 @@ test('a refresh asked for while one is in flight runs after it, and keeps its ne assert.equal(answers.length, 1) answers[0]({meter: 'tokens', used: 200}) assert.equal(await first, true) - await new Promise(resolve => setImmediate(resolve)) + 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 index 0ed8da31..fc87dc6c 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -87,22 +87,22 @@ const fetchAIAssistantUsage = ({get, storage, baseURL, token, username}) => { // 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 = {} +const refreshing = new Map() export const refreshAIAssistantUsage = request => { const { baseURL, token, username } = request if(!baseURL || !token || !username) return Promise.resolve(false) - const running = refreshing[username] + 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[username] === entry) - delete refreshing[username] + if(refreshing.get(username) === entry) + refreshing.delete(username) }) - refreshing[username] = entry + refreshing.set(username, entry) return entry.promise } From e63a65da093aba8922e1a0b3e8b9559977f7fd05 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 08:16:46 -0500 Subject: [PATCH 10/12] OpenConceptLab/ocl_online#641 | A refusal scoped to its request opens no dialog of its own The row is still skipped and a run still goes on. What the person is told, and its wording, is left to OpenConceptLab/ocl_online#702, which designs these notices. This drops the dialog's title and text in each language, and the test that checked them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/components/common/QuotaDialog.jsx | 2 +- .../common/__tests__/quotaErrors.test.js | 21 ----------- src/components/map-projects/MapProject.jsx | 35 ++++++++----------- src/i18n/locales/en/translations.json | 5 --- src/i18n/locales/es/translations.json | 5 --- src/i18n/locales/pt-BR/translations.json | 5 --- src/i18n/locales/zh/translations.json | 5 --- 7 files changed, 15 insertions(+), 63 deletions(-) diff --git a/src/components/common/QuotaDialog.jsx b/src/components/common/QuotaDialog.jsx index 0c4d5532..e272e4fc 100644 --- a/src/components/common/QuotaDialog.jsx +++ b/src/components/common/QuotaDialog.jsx @@ -8,7 +8,7 @@ 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__/quotaErrors.test.js b/src/components/common/__tests__/quotaErrors.test.js index b87ec5d5..1f041c46 100644 --- a/src/components/common/__tests__/quotaErrors.test.js +++ b/src/components/common/__tests__/quotaErrors.test.js @@ -1,6 +1,5 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' import { getQuotaError, isCapMeter, isQuotaError } from '../quotaErrors.js' @@ -31,23 +30,3 @@ test('isCapMeter: only projects and rows are caps', () => { assert.equal(isCapMeter('rows'), true) assert.equal(isCapMeter('match_operations'), false) }) - -// QuotaDialog builds its keys at run time, so the catalog key check can't see -// them. ai_assistant_request is a refusal scoped to its request, with its own -// title (OpenConceptLab/ocl_online#641). -test('every meter a refusal names has its consequence in each language', () => { - const meters = [ - 'mapper_match_operations_limit_reached', - 'ai_assistant_calls_limit_reached', - 'ai_assistant_change_comments_limit_reached', - 'mapper_projects_limit_reached', - 'mapper_rows_per_project_limit_reached', - ].map(error_code => getQuotaError({error_code}).meter) - for (const locale of ['en', 'es', 'pt-BR', 'zh']) { - const quota = JSON.parse(readFileSync(new URL(`../../../i18n/locales/${locale}/translations.json`, import.meta.url), 'utf8')).quota - const consequence = quota.consequence - assert.ok(quota.title_ai_assistant_request, locale) - assert.deepEqual([...meters, 'ai_assistant_request'].filter(meter => !consequence[meter]?.default), [], locale) - assert.deepEqual(['match_operations', 'ai_assistant_calls', 'ai_assistant_request'].filter(meter => !consequence[meter]?.auto_match), [], locale) - } -}) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 6f50db51..e99c90da 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -287,8 +287,7 @@ const MapProject = () => { // Holds the limit's error_code, or null. const matchQuotaStopRef = React.useRef(null); const rerankQuotaStopRef = React.useRef(null); - // The at-limit dialog opens once per run, not once per failed request: - // false, true, or 'skip' while only a skipped row's dialog has opened. + // The at-limit dialog opens once per run, not once per failed request. const runPreviewLimitShownRef = React.useRef(false); const bulkMatchAlgoIdsRef = React.useRef([]); // ocl_online#105 Phase 5: the active AutomatchRun ({id, algoIds}) or null. @@ -306,7 +305,7 @@ const MapProject = () => { const ownNavigationRef = React.useRef(false) const refreshRowStageSnapshotRef = React.useRef({}); - const [previewLimit, setPreviewLimit] = React.useState(null) // {errorCode, capability, phase, skipsRow, isRun} 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) @@ -4078,10 +4077,16 @@ const MapProject = () => { setIsLoadingInDecisionView(false) if(isNumber(rowId) && !restoreRefreshRowStage(rowId) && algoId) markAlgo(rowId, algoId, -2) - // A superseded run's late refusal comes with no row: one scoped to its - // request isn't this run's, so it leaves this run's dialog alone. - if(isRun && skipsRow && !isNumber(rowId)) + // 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 @@ -4089,19 +4094,16 @@ const MapProject = () => { rerankQuotaStopRef.current = response.error_code if(stopsAIStep) aiQuotaExhaustedRef.current = true - else if(skipsRow) - aiQuotaSkippedRef.current = true - // A skipped row's dialog says the run goes on, so a stop after it is shown too. - if(runPreviewLimitShownRef.current && (skipsRow || runPreviewLimitShownRef.current !== 'skip')) + if(runPreviewLimitShownRef.current) return true - runPreviewLimitShownRef.current = skipsRow ? 'skip' : true + runPreviewLimitShownRef.current = true } else { if(stopsAIStep) aiQuotaExhaustedRef.current = true if(isNumber(rowId)) refreshMapperQuotaCache() } - setPreviewLimit({errorCode: response.error_code, capability: response.capability, phase: stopPhase, skipsRow, isRun}) + setPreviewLimit({errorCode: response.error_code, capability: response.capability, phase: stopPhase}) return true } @@ -6803,15 +6805,6 @@ const MapProject = () => { }} /> { - previewLimit?.skipsRow ? - setPreviewLimit(null)} - errorCode={previewLimit.errorCode} - capability={previewLimit.capability} - meter='ai_assistant_request' - surface={previewLimit.isRun ? 'auto_match' : 'default'} - /> : previewLimitQuota ? Date: Thu, 19 Nov 2026 08:19:20 -0500 Subject: [PATCH 11/12] OpenConceptLab/ocl_online#641 | Say why a project leaves out a reply's usage without saying whose count it is A reply's usage can be counted for more than the person who sent it, so the comment gives the reason that holds either way: it's a running count, not part of the project's work. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/aiAssistantUsage.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index fc87dc6c..40a30668 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -56,7 +56,7 @@ export const keepAIAssistantUsage = (storage, username, reply) => { } // The reply without `metadata.usage`, for what a project stores: the report is -// the person's own count, and a project's history can be an organization's. +// a running count for whoever sent the request, not part of the project's work. export const withoutAIAssistantUsage = reply => { if(!reply?.metadata || !Object.prototype.hasOwnProperty.call(reply.metadata, 'usage')) return reply From 54ee227815db105d903489930cf150a30f187adf Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 08:21:12 -0500 Subject: [PATCH 12/12] OpenConceptLab/ocl_online#641 | The comment says the report covers more than the project, not whose it is Answers the Codex check of 5892a6d: "for whoever sent the request" read as if the count were the sender's alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/aiAssistantUsage.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index 40a30668..d3af1518 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -56,7 +56,7 @@ export const keepAIAssistantUsage = (storage, username, reply) => { } // The reply without `metadata.usage`, for what a project stores: the report is -// a running count for whoever sent the request, not part of the project's work. +// 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