From 1d25939f0c79a3225395cc6afffe62ef98220601 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 07:02:49 -0500 Subject: [PATCH 1/6] OpenConceptLab/ocl_online#641 | The usage read names the open map project, and each project keeps its own report The OCL AI Assistant reports the count for the map project a call names. The Mapper's $invoke calls already name it in X-OCL-Event-Metadata, but GET /match/usage/ named none, so the chip could switch between two counts on one project. The read now names the project the same way, and the report is kept per person and project (none for a project not saved yet). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 39 ++++++++++ src/common/aiAssistantUsage.js | 74 +++++++++++-------- src/common/utils.js | 22 +++--- src/components/map-projects/MapProject.jsx | 14 +++- .../map-projects/MapperQuotaChip.jsx | 5 +- 5 files changed, 110 insertions(+), 44 deletions(-) diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index a5fe027..f775649 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 as the calls on it do, 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, {'X-OCL-Request-Source': 'mapper-ui-manual', 'X-OCL-Event-Metadata': '{"map_project_id":"139"}', Authorization: 'Token personal-token'}) + 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.headers['X-OCL-Event-Metadata'], 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), ['{"map_project_id":"1"}', '{"map_project_id":"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..ed4efca 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -1,3 +1,5 @@ +import { buildAttributionHeaders } from '../services/attribution.js' + // 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 => @@ -9,49 +11,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 !== undefined && project !== null && project !== '' + +// 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 now, to tell whether it changed: undefined if -// the storage can't be read. -const read = (storage, username) => { +// 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 +79,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 in the same header +// the calls on it send, so the report is the count their replies carry. +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 headers = { + ...(hasProject(project) ? buildAttributionHeaders({projectId: project}) : {}), + Authorization: `Token ${token}`, + } + return get(url, {headers, timeout: 10000}) .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..d281699 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -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(() => { @@ -6150,8 +6154,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 +6210,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) @@ -6423,7 +6429,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 From cf38d73de0bed2fb2da404d1bf88f721adbf4d28 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 11:00:29 -0500 Subject: [PATCH 2/6] OpenConceptLab/ocl_online#641 | The usage read names its project in the query string, and a first save asks once the route has the id The usage read names the map project as `map_project` in the query string rather than in the attribution header, which attributes a call: the OCL AI Assistant reports the count the calls on that project are charged to. A project's first save refreshed the usage before the route had the new project's id, so its report was never asked for. The save now refreshes only the capabilities, and the route gaining a project id asks for that project's report. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/common/__tests__/aiAssistantUsage.test.js | 8 +-- src/common/aiAssistantUsage.js | 16 +++-- src/components/map-projects/MapProject.jsx | 17 +++++- .../__tests__/usageRouteProject.test.js | 58 +++++++++++++++++++ 4 files changed, 84 insertions(+), 15 deletions(-) create mode 100644 src/components/map-projects/__tests__/usageRouteProject.test.js diff --git a/src/common/__tests__/aiAssistantUsage.test.js b/src/common/__tests__/aiAssistantUsage.test.js index f775649..aed281e 100644 --- a/src/common/__tests__/aiAssistantUsage.test.js +++ b/src/common/__tests__/aiAssistantUsage.test.js @@ -184,7 +184,7 @@ test('each map project keeps its own report, apart from the one for calls that n assert.equal(getAIAssistantUsage(storage, 'someone-else', '139'), null) }) -test('a refresh for a map project names it as the calls on it do, and keeps the report for it', async () => { +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) => { @@ -192,7 +192,7 @@ test('a refresh for a map project names it as the calls on it do, and keeps the 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, {'X-OCL-Request-Source': 'mapper-ui-manual', 'X-OCL-Event-Metadata': '{"map_project_id":"139"}', Authorization: 'Token personal-token'}) + 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}) }) @@ -200,10 +200,10 @@ test('a refresh for a map project names it as the calls on it do, and keeps the 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.headers['X-OCL-Event-Metadata'], answer: data => resolve({status: 200, data})})) + 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), ['{"map_project_id":"1"}', '{"map_project_id":"2"}']) + 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]) diff --git a/src/common/aiAssistantUsage.js b/src/common/aiAssistantUsage.js index ed4efca..f265dd7 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -1,5 +1,3 @@ -import { buildAttributionHeaders } from '../services/attribution.js' - // 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 => @@ -79,17 +77,17 @@ 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. The request names the project in the same header -// the calls on it send, so the report is the count their replies carry. +// 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 key = storageKey(username, project) const keptBefore = read(storage, key) - const headers = { - ...(hasProject(project) ? buildAttributionHeaders({projectId: project}) : {}), - Authorization: `Token ${token}`, - } - return get(url, {headers, timeout: 10000}) + 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, key) !== keptBefore) return false diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index d281699..6cbadd4 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'; @@ -843,6 +843,18 @@ 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 (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) + refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1), params.projectId) + }, [params.projectId]) + const newProjectBlockReason = (!params.projectId && !project?.id && mapperQuotaCacheVersion > 0) ? getNewProjectBlockReason(getMapperPreview()) : null @@ -1841,8 +1853,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 { 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..7afbd87 --- /dev/null +++ b/src/components/map-projects/__tests__/usageRouteProject.test.js @@ -0,0 +1,58 @@ +/** + * 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 (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 asks for 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 asks = [] + path.traverse({ + CallExpression({node}) { + if(node.callee.name === 'refreshAIAssistantUsageCache') + asks.push(code(node.arguments[1])) + } + }) + if(asks.length) + effects.push({asks, body: code(effect)}) + } + }) + assert.equal(effects.length, 1) + assert.deepEqual(effects[0].asks, ['params.projectId']) + // 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/) +}) From c335c17e834549e825e83ff5e130d1ca9f1569f5 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 11:17:56 -0500 Subject: [PATCH 3/6] OpenConceptLab/ocl_online#641 | Codex pass 1 on OpenConceptLab/oclmap#134: a reply kept for another project asks for the open one's report F1.3: a call made before a project's first save keeps its reply's report for no project, and skipped the refresh because the reply carried one, so the saved project's report could miss that call. When the reply's project isn't the open one, the open one's report is asked for. F1.4: the route gaining a project id refreshes the capabilities with the usage, so a permission granted only now still asks for the report. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/components/map-projects/MapProject.jsx | 12 +++++--- .../__tests__/usageRouteProject.test.js | 30 ++++++++++++++----- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 6cbadd4..7db78dd 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, 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'; @@ -845,14 +845,15 @@ const MapProject = () => { // 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 (OpenConceptLab/ocl_online#641). + // 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) - refreshAIAssistantUsageCache(() => setAIAssistantUsageVersion(version => version + 1), params.projectId) + refreshMapperQuotaCache() }, [params.projectId]) const newProjectBlockReason = (!params.projectId && !project?.id && mapperQuotaCacheVersion > 0) @@ -6267,7 +6268,10 @@ const MapProject = () => { const lastOfOverlapping = singleAICallsInFlightRef.current === 0 && singleAICallsOverlappedRef.current if(singleAICallsInFlightRef.current === 0) singleAICallsOverlappedRef.current = false - refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping}) + // 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 + refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping || !keptForOpenProject}) } } } else { diff --git a/src/components/map-projects/__tests__/usageRouteProject.test.js b/src/components/map-projects/__tests__/usageRouteProject.test.js index 7afbd87..fd7e924 100644 --- a/src/components/map-projects/__tests__/usageRouteProject.test.js +++ b/src/components/map-projects/__tests__/usageRouteProject.test.js @@ -1,7 +1,8 @@ /** * 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 (OpenConceptLab/ocl_online#641). + * 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. @@ -33,26 +34,39 @@ test('the first save refreshes the capabilities without asking for a usage repor assert.deepEqual(refreshes, [['{usage: false}']]) }) -test('the route gaining a project id asks for that project\'s usage report', () => { +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 asks = [] + const refreshes = [] path.traverse({ CallExpression({node}) { - if(node.callee.name === 'refreshAIAssistantUsageCache') - asks.push(code(node.arguments[1])) + if(node.callee.name === 'refreshMapperQuotaCache') + refreshes.push(node.arguments.map(code)) } }) - if(asks.length) - effects.push({asks, body: code(effect)}) + if(refreshes.length) + effects.push({refreshes, body: code(effect)}) } }) assert.equal(effects.length, 1) - assert.deepEqual(effects[0].asks, ['params.projectId']) + // 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/) +}) From 9d60f105a561e2ada47a4cac98495666f7cb3c8e Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 11:23:16 -0500 Subject: [PATCH 4/6] OpenConceptLab/ocl_online#641 | Codex pass 2 on OpenConceptLab/oclmap#134: a late AutoMatch reply for another project asks for the open one's report F2.1: an AutoMatch reply that lands after the project was saved is kept for no project, and a run leaves the usage to its end, which had passed. It now asks for the open project's report too. F2.2: the source test also pins that the usage read names the route's project, the same id the calls name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/components/map-projects/MapProject.jsx | 9 +++++---- .../map-projects/__tests__/usageRouteProject.test.js | 11 +++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 7db78dd..8cf7b1d 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -6263,16 +6263,17 @@ 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 - // 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 refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping || !keptForOpenProject}) - } + } else if(usageKept && !keptForOpenProject) + refreshMapperQuotaCache() } } else { markRecommend(analysis[__index]?.length > 0 ? 1 : -3) diff --git a/src/components/map-projects/__tests__/usageRouteProject.test.js b/src/components/map-projects/__tests__/usageRouteProject.test.js index fd7e924..57e11a0 100644 --- a/src/components/map-projects/__tests__/usageRouteProject.test.js +++ b/src/components/map-projects/__tests__/usageRouteProject.test.js @@ -69,4 +69,15 @@ test('a reply kept for another project than the open one asks for the open one\' }) 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. + assert.match(source, /else if\(usageKept && !keptForOpenProject\)\s*refreshMapperQuotaCache\(\)/) +}) + +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/) }) From 5f5614fcb5e04f75b099ac48c4061896c7ca4cb2 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 11:24:15 -0500 Subject: [PATCH 5/6] OpenConceptLab/ocl_online#641 | Simplification review of OpenConceptLab/oclmap#134 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 f265dd7..5390f9a 100644 --- a/src/common/aiAssistantUsage.js +++ b/src/common/aiAssistantUsage.js @@ -9,7 +9,7 @@ export const USAGE_CHIP_METERS = ['calls', 'tokens'] export const getUsageChipReport = usage => usage && USAGE_CHIP_METERS.includes(usage.meter) ? usage : null -const hasProject = project => project !== undefined && project !== null && project !== '' +const hasProject = project => project != null && project !== '' // 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, From 800f5f5f02a9894e54f751659e89de2e75d88975 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 19 Nov 2026 11:27:19 -0500 Subject: [PATCH 6/6] OpenConceptLab/ocl_online#641 | A late AutoMatch reply for another project asks only for the open one's report Codex's check of c335c17..5f5614f on OpenConceptLab/oclmap#134 (FC.1): the refresh also asked for the account, and a throttled reply to that could hold up the Mapper. A run's own refresh already did the capabilities, so this asks only for the report, which never blocks the Mapper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qVq1YwJv43QFnQSLDP --- src/components/map-projects/MapProject.jsx | 5 +++-- .../map-projects/__tests__/usageRouteProject.test.js | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 8cf7b1d..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'; @@ -6273,7 +6273,8 @@ const MapProject = () => { singleAICallsOverlappedRef.current = false refreshMapperQuotaCache({usage: !usageKept || lastOfOverlapping || !keptForOpenProject}) } else if(usageKept && !keptForOpenProject) - refreshMapperQuotaCache() + // 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) diff --git a/src/components/map-projects/__tests__/usageRouteProject.test.js b/src/components/map-projects/__tests__/usageRouteProject.test.js index 57e11a0..4909b35 100644 --- a/src/components/map-projects/__tests__/usageRouteProject.test.js +++ b/src/components/map-projects/__tests__/usageRouteProject.test.js @@ -69,8 +69,9 @@ test('a reply kept for another project than the open one asks for the open one\' }) 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. - assert.match(source, /else if\(usageKept && !keptForOpenProject\)\s*refreshMapperQuotaCache\(\)/) + // 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', () => {