diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index a5fe027..aed281e 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -171,3 +171,42 @@ test('any username, even one an object has as a property, is refreshed', async ( assert.equal(await refreshAIAssistantUsage({...REQUEST, username: 'constructor', get, storage}), true) assert.deepEqual(getAIAssistantUsage(storage, 'constructor'), {meter: 'tokens', used: 9}) }) + +test('each map project keeps its own report, apart from the one for calls that name none', () => { + const storage = memoryStorage() + assert.equal(keepAIAssistantUsage(storage, 'someone', {metadata: {usage: {meter: 'tokens', used: 600}}}, '139'), true) + assert.equal(keepAIAssistantUsage(storage, 'someone', {metadata: {usage: {meter: 'calls', used: 4}}}), true) + assert.deepEqual(getAIAssistantUsage(storage, 'someone', '139'), {meter: 'tokens', used: 600}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone', 139), {meter: 'tokens', used: 600}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'calls', used: 4}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone', ''), {meter: 'calls', used: 4}) + assert.equal(getAIAssistantUsage(storage, 'someone', '140'), null) + assert.equal(getAIAssistantUsage(storage, 'someone-else', '139'), null) +}) + +test('a refresh for a map project names it in the query string, and keeps the report for it', async () => { + const storage = memoryStorage({'ai_assistant_usage:someone': JSON.stringify({meter: 'calls', used: 4})}) + const calls = [] + const get = (url, config) => { + calls.push({url, config}) + return Promise.resolve({status: 200, data: {meter: 'tokens', used: 600}}) + } + assert.equal(await refreshAIAssistantUsage({...REQUEST, project: '139', get, storage}), true) + assert.deepEqual(calls[0].config, {headers: {Authorization: 'Token personal-token'}, params: {map_project: '139'}, timeout: 10000}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone', '139'), {meter: 'tokens', used: 600}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone'), {meter: 'calls', used: 4}) +}) + +test('refreshes for different map projects don\'t wait on each other', async () => { + const storage = memoryStorage() + const answers = [] + const get = (url, config) => new Promise(resolve => answers.push({project: config.params?.map_project, answer: data => resolve({status: 200, data})})) + const first = refreshAIAssistantUsage({...REQUEST, project: '1', get, storage}) + const second = refreshAIAssistantUsage({...REQUEST, project: '2', get, storage}) + assert.deepEqual(answers.map(({project}) => project), ['1', '2']) + answers[1].answer({meter: 'tokens', used: 20}) + answers[0].answer({meter: 'calls', used: 1}) + assert.deepEqual([await first, await second], [true, true]) + assert.deepEqual(getAIAssistantUsage(storage, 'someone', '1'), {meter: 'calls', used: 1}) + assert.deepEqual(getAIAssistantUsage(storage, 'someone', '2'), {meter: 'tokens', used: 20}) +}) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index d3af151..5390f9a 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -9,49 +9,56 @@ export const USAGE_CHIP_METERS = ['calls', 'tokens'] export const getUsageChipReport = usage => usage && USAGE_CHIP_METERS.includes(usage.meter) ? usage : null -// Each person's last report, under their own key. -const storageKey = username => `ai_assistant_usage:${username}` +const hasProject = project => project != null && project !== '' -// What's kept for this person now, to tell whether it changed: undefined if -// the storage can't be read. -const read = (storage, username) => { +// The service reports the count for the map project a call names (none for a +// project not saved yet), so each person's last report is kept per project, +// under its own key. +const storageKey = (username, project) => + `ai_assistant_usage:${username}${hasProject(project) ? `:project:${project}` : ''}` + +// What's kept for this person and project now, to tell whether it changed: +// undefined if the storage can't be read. +const read = (storage, key) => { try { - return storage.getItem(storageKey(username)) + return storage.getItem(key) } catch(_) { return undefined } } // A full or blocked storage only costs the chip its report. -const store = (storage, username, usage) => { +const store = (storage, key, usage) => { try { if(usage) - storage.setItem(storageKey(username), JSON.stringify(usage)) + storage.setItem(key, JSON.stringify(usage)) else - storage.removeItem(storageKey(username)) + storage.removeItem(key) } catch(_) { // nothing to keep } } -// The last report kept for this person. Without one, the chip keeps its call line. -export const getAIAssistantUsage = (storage, username) => { +// The last report kept for this person and project. Without one, the chip +// keeps its call line. +export const getAIAssistantUsage = (storage, username, project) => { if(!username) return null try { - return toAIAssistantUsage(JSON.parse(storage.getItem(storageKey(username)))) + return toAIAssistantUsage(JSON.parse(storage.getItem(storageKey(username, project)))) } catch(_) { return null } } // Keeps the report a reply carries in `metadata.usage` (an $invoke reply) for -// the person who sent the request. Returns whether it kept one. -export const keepAIAssistantUsage = (storage, username, reply) => { +// the person who sent the request and the project it named. Returns whether +// it kept one. +export const keepAIAssistantUsage = (storage, username, reply, project) => { const usage = toAIAssistantUsage(reply?.metadata?.usage) if(!usage || !username) return false - store(storage, username, usage) + store(storage, storageKey(username, project), usage) return true } @@ -70,39 +77,46 @@ export const withoutAIAssistantUsage = reply => { // without a unit and a count clears the kept one. A failed request keeps it, // and so does one that's overtaken: something else (a reply's report, in this // tab or another) kept a report while it was in flight. Resolves to whether -// the kept report changed. -const fetchAIAssistantUsage = ({get, storage, baseURL, token, username}) => { +// the kept report changed. The request names the project (`map_project`), so +// the report is the count the calls on it are charged to, as their replies +// carry it. +const fetchAIAssistantUsage = ({get, storage, baseURL, token, username, project}) => { const url = `${baseURL.replace(/\/+$/, '')}/match/usage/` - const keptBefore = read(storage, username) - return get(url, {headers: {Authorization: `Token ${token}`}, timeout: 10000}) + const key = storageKey(username, project) + const keptBefore = read(storage, key) + const config = {headers: {Authorization: `Token ${token}`}, timeout: 10000} + if(hasProject(project)) + config.params = {map_project: project} + return get(url, config) .then(response => { - if(read(storage, username) !== keptBefore) + if(read(storage, key) !== keptBefore) return false - store(storage, username, toAIAssistantUsage(response?.data)) + store(storage, key, toAIAssistantUsage(response?.data)) return true }) .catch(() => false) } -// One refresh at a time per person: a request made while one is in flight -// waits for it, then all such requests share one more, so a refresh never -// overtakes another and discards its newer count. +// One refresh at a time per person and project: a request made while one is +// in flight waits for it, then all such requests share one more, so a refresh +// never overtakes another and discards its newer count. const refreshing = new Map() export const refreshAIAssistantUsage = request => { - const { baseURL, token, username } = request + const { baseURL, token, username, project } = request if(!baseURL || !token || !username) return Promise.resolve(false) - const running = refreshing.get(username) + const key = storageKey(username, project) + const running = refreshing.get(key) if(running) { running.next = running.next || running.promise.then(() => refreshAIAssistantUsage(request)) return running.next } const entry = {} entry.promise = fetchAIAssistantUsage(request).finally(() => { - if(refreshing.get(username) === entry) - refreshing.delete(username) + if(refreshing.get(key) === entry) + refreshing.delete(key) }) - refreshing.set(username, entry) + refreshing.set(key, entry) return entry.promise } diff --git a/src/common/utils.js b/src/common/utils.js index 5ab8316..44477d3 100644 --- a/src/common/utils.js +++ b/src/common/utils.js @@ -279,19 +279,20 @@ export const refreshCurrentUserCapabilitiesCache = callback => { // 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}) => { +// `usage: false` skips the report, which is the one for map project `project` +// (none for a project not saved yet). Each callback runs when its part changed. +export const refreshCapabilitiesAndAIAssistantUsage = ({onCapabilities, onUsage, usage = true, project}) => { const hadAIAssistant = hasCapability(getCurrentUser(), 'users.mapper_ai_assistant') refreshCurrentUserCapabilitiesCache(() => { onCapabilities() if(usage && !hadAIAssistant) - refreshAIAssistantUsageCache(onUsage) + refreshAIAssistantUsageCache(onUsage, project) }) if(usage) - refreshAIAssistantUsageCache(onUsage) + refreshAIAssistantUsageCache(onUsage, project) } -export const refreshAIAssistantUsageCache = callback => { +export const refreshAIAssistantUsageCache = (callback, project) => { const user = getCurrentUser() if(!hasCapability(user, 'users.mapper_ai_assistant')) return @@ -301,12 +302,14 @@ export const refreshAIAssistantUsageCache = callback => { baseURL: window.AI_ASSISTANT_API_URL || process.env.AI_ASSISTANT_API_URL, token: currentUserToken(), username: user?.username, + project, }).then(changed => changed && callback && callback()) } // Keeps the usage an OCL AI Assistant reply carries for `username`, the person -// signed in when the request was sent. Returns whether it kept one. -export const keepAIAssistantUsageFromReply = (reply, username) => keepAIAssistantUsage(localStorage, username, reply) +// signed in when the request was sent, and `project`, the map project it named. +// Returns whether it kept one. +export const keepAIAssistantUsageFromReply = (reply, username, project) => keepAIAssistantUsage(localStorage, username, reply, project) export const replaceCurrentUserCacheWith = data => localStorage.setItem('user', JSON.stringify(data)); @@ -1202,7 +1205,8 @@ export const toCamelCase = str => { export const hasCapability = (user, capability) => Boolean((user || getCurrentUser())?.permissions?.includes(capability)) -export const getMapperPreview = () => { +// `projectId`: the map project whose OCL AI Assistant report to include. +export const getMapperPreview = ({projectId} = {}) => { const user = getCurrentUser() const capabilities = user?.capabilities || [] const toMeter = key => { @@ -1229,7 +1233,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), + aiAssistantUsage: getAIAssistantUsage(localStorage, user?.username, projectId), } } diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index e99c90d..4ff62b0 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, refreshCapabilitiesAndAIAssistantUsage, keepAIAssistantUsageFromReply } from '../../common/utils'; +import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCapabilitiesAndAIAssistantUsage, refreshAIAssistantUsageCache, keepAIAssistantUsageFromReply } from '../../common/utils'; import { withoutAIAssistantUsage } from '../../common/aiAssistantUsage'; import { WHITE, SURFACE_COLORS, TEXT_GRAY } from '../../common/colors'; @@ -160,15 +160,19 @@ const MapProject = () => { const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) const [, setAIAssistantUsageVersion] = React.useState(0) // {usage: false} skips asking the OCL AI Assistant, when its reply already - // carried the usage (OpenConceptLab/ocl_online#641). + // carried the usage (OpenConceptLab/ocl_online#641). The report asked for is + // the open project's. + const usageProjectIdRef = React.useRef(null) const refreshMapperQuotaCache = React.useCallback(({usage = true} = {}) => { refreshCapabilitiesAndAIAssistantUsage({ onCapabilities: () => setMapperQuotaCacheVersion(version => version + 1), onUsage: () => setAIAssistantUsageVersion(version => version + 1), usage, + project: usageProjectIdRef.current, }) }, []) const params = useParams() + usageProjectIdRef.current = params.projectId const history = useHistory() const location = useLocation() const templateFromProjectURL = React.useMemo(() => { @@ -839,6 +843,19 @@ const MapProject = () => { setPermissionDenied(false) }, [params.projectId]) + // A project's first save gives the route its id, after the save's own + // refresh, which named no project: the chip asks for the new project's + // report then, with the capabilities, in case they grant the OCL AI + // Assistant only now (OpenConceptLab/ocl_online#641). + const usageRouteProjectIdRef = React.useRef(params.projectId) + React.useEffect(() => { + if(usageRouteProjectIdRef.current === params.projectId) + return + usageRouteProjectIdRef.current = params.projectId + if(params.projectId) + refreshMapperQuotaCache() + }, [params.projectId]) + const newProjectBlockReason = (!params.projectId && !project?.id && mapperQuotaCacheVersion > 0) ? getNewProjectBlockReason(getMapperPreview()) : null @@ -1837,8 +1854,9 @@ const MapProject = () => { } setProjectPromptTemplateKey(response.data?.prompt_template_key || getProjectPromptTemplateKey()) setProject(response.data) + // The new project's usage is asked for once the route has its id. if(!isUpdate) - refreshMapperQuotaCache() + refreshMapperQuotaCache({usage: false}) if(response.data.url && isMountedRef.current && !options.leaving && history.location.pathname === pathAtSave) { ownNavigationRef.current = true try { @@ -6150,8 +6168,10 @@ 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. + // The reply's usage is for this person and the project the call names, + // whoever is signed in and whichever project is open when it lands. const invokeUsername = getCurrentUser()?.username + const invokeProjectId = params.projectId 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. @@ -6204,7 +6224,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, invokeUsername) + usageKept = keepAIAssistantUsageFromReply(response.data, invokeUsername, invokeProjectId) if(usageKept) setAIAssistantUsageVersion(version => version + 1) const reply = withoutAIAssistantUsage(response.data) @@ -6243,13 +6263,18 @@ const MapProject = () => { setAlert({message: errorMessage, severity: 'error'}) return -2 } finally { + // A reply kept for another project than the open one (it was saved + // while the call was in flight) leaves the open one's to ask for. + const keptForOpenProject = invokeProjectId === usageProjectIdRef.current if(!isBulk) { singleAICallsInFlightRef.current -= 1 const lastOfOverlapping = singleAICallsInFlightRef.current === 0 && singleAICallsOverlappedRef.current if(singleAICallsInFlightRef.current === 0) singleAICallsOverlappedRef.current = false - refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping}) - } + refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping || !keptForOpenProject}) + } else if(usageKept && !keptForOpenProject) + // only the report: a run's own refresh did the capabilities + refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1), usageProjectIdRef.current) } } else { markRecommend(analysis[__index]?.length > 0 ? 1 : -3) @@ -6423,7 +6448,7 @@ const MapProject = () => { } - + { scispacyCandidatesStartedAt && diff --git a/src/components/map-projects/MapperQuotaChip.jsx b/src/components/map-projects/MapperQuotaChip.jsx index af1184f..50c3906 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -32,9 +32,10 @@ const AIAssistantUsageChip = ({usage, size}) => { ) } -const MapperQuotaChip = ({size = 'small'}) => { +// `projectId`: the map project open, whose OCL AI Assistant report it shows. +const MapperQuotaChip = ({size = 'small', projectId}) => { const { t } = useTranslation() - const preview = getMapperPreview() + const preview = getMapperPreview({projectId}) const { rowsPerProject, matchOperations, aiAssistantCalls, aiAssistantUsage, projects } = preview if(!preview.hasAccess) return null diff --git a/src/components/map-projects/__tests__/usageRouteProject.test.js b/src/components/map-projects/__tests__/usageRouteProject.test.js new file mode 100644 index 0000000..4909b35 --- /dev/null +++ b/src/components/map-projects/__tests__/usageRouteProject.test.js @@ -0,0 +1,84 @@ +/** + * A project's first save asks for no OCL AI Assistant report itself: its route + * has no project id yet, and the report is kept per project. The new project's + * report is asked for once the route has its id, and again when a reply lands + * for another project than the open one (OpenConceptLab/ocl_online#641). + * + * MapProject can't be mounted here (these tests run without a JSX transform), + * so this reads its source. + */ + +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import babel from '@babel/core' + +const source = readFileSync(new URL('../MapProject.jsx', import.meta.url), 'utf8') +const ast = babel.parseSync(source, {babelrc: false, configFile: false, parserOpts: {plugins: ['jsx']}}) +const code = node => source.slice(node.start, node.end) + +test('the first save refreshes the capabilities without asking for a usage report', () => { + const refreshes = [] + babel.traverse(ast, { + IfStatement(path) { + if(code(path.node.test) !== '!isUpdate') + return + path.traverse({ + CallExpression({node}) { + if(node.callee.name === 'refreshMapperQuotaCache') + refreshes.push(node.arguments.map(code)) + } + }) + } + }) + assert.deepEqual(refreshes, [['{usage: false}']]) +}) + +test('the route gaining a project id refreshes the capabilities and that project\'s usage report', () => { + const effects = [] + babel.traverse(ast, { + CallExpression(path) { + const [effect, deps] = path.node.arguments + if(code(path.node.callee) !== 'React.useEffect' || !deps || code(deps) !== '[params.projectId]') + return + const refreshes = [] + path.traverse({ + CallExpression({node}) { + if(node.callee.name === 'refreshMapperQuotaCache') + refreshes.push(node.arguments.map(code)) + } + }) + if(refreshes.length) + effects.push({refreshes, body: code(effect)}) + } + }) + assert.equal(effects.length, 1) + // No argument: the usage too, asked again if the fresh capabilities grant it. + assert.deepEqual(effects[0].refreshes, [[]]) + // Only on a change: the mount's own load asks for the opened project's report. + assert.match(effects[0].body, /usageRouteProjectIdRef\.current === params\.projectId\)\s*return/) +}) + +test('a reply kept for another project than the open one asks for the open one\'s report', () => { + const refreshes = [] + babel.traverse(ast, { + CallExpression({node}) { + if(node.callee.name === 'refreshMapperQuotaCache' && node.arguments.length && code(node.arguments[0]).includes('usageKept')) + refreshes.push(code(node.arguments[0])) + } + }) + assert.deepEqual(refreshes, ['{usage: !usageKept || lastOfOverlapping || !keptForOpenProject}']) + assert.match(source, /const keptForOpenProject = invokeProjectId === usageProjectIdRef\.current/) + // An AutoMatch reply too, which otherwise leaves the usage to the run's end: + // the report only, as a run's own refresh did the capabilities. + assert.match(source, /else if\(usageKept && !keptForOpenProject\)\s*\/\/[^\n]*\n\s*refreshAIAssistantUsageCache\([^\n]*, usageProjectIdRef\.current\)/) +}) + +test('the usage read names the route\'s project, as the calls on it do', () => { + // The read's project is the ref each render sets from the route... + assert.match(source, /usageProjectIdRef\.current = params\.projectId\n/) + assert.match(source, /usage,\s*project: usageProjectIdRef\.current,\s*\}\)/) + // ...the same id the calls' attribution and their kept reports name. + assert.match(source, /projectId: params\.projectId,\s*rowIndex/) + assert.match(source, /const invokeProjectId = params\.projectId\n/) +})