Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/common/__tests__/aiAssistantUsage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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})
})
72 changes: 43 additions & 29 deletions src/common/aiAssistantUsage.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
}
22 changes: 13 additions & 9 deletions src/common/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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));

Expand Down Expand Up @@ -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 => {
Expand All @@ -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),
}
}

Expand Down
41 changes: 33 additions & 8 deletions src/components/map-projects/MapProject.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -6423,7 +6448,7 @@ const MapProject = () => {
</span>
}
<span style={{marginRight: '8px'}}>
<MapperQuotaChip />
<MapperQuotaChip projectId={params.projectId} />
</span>
{
scispacyCandidatesStartedAt &&
Expand Down
5 changes: 3 additions & 2 deletions src/components/map-projects/MapperQuotaChip.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading