From a4d7ae0376dd9861cc3f71e574e9c534db65aaa5 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 3 Dec 2026 02:06:18 -0500 Subject: [PATCH 1/8] OpenConceptLab/ocl_online#654 | Map projects go by their owner's limits and permissions, and the Owner field says which organizations can own one OpenConceptLab/ocl_online#716 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/common/utils.js | 11 ++- src/components/common/NamespaceDropdown.jsx | 68 +++++++++++++++--- .../common/__tests__/ownerAccess.test.js | 69 +++++++++++++++++++ src/components/common/ownerAccess.js | 56 +++++++++++++++ src/components/common/useOwnerAccess.js | 55 +++++++++++++++ .../map-projects/AutoMatchDialog.jsx | 3 +- .../map-projects/ConfigurationForm.jsx | 3 +- src/components/map-projects/MapProject.jsx | 51 +++++++++----- src/components/map-projects/MapProjects.jsx | 5 +- .../map-projects/MapperQuotaChip.jsx | 5 +- src/components/map-projects/autoMatchCheck.js | 12 ++-- 11 files changed, 299 insertions(+), 39 deletions(-) create mode 100644 src/components/common/__tests__/ownerAccess.test.js create mode 100644 src/components/common/ownerAccess.js create mode 100644 src/components/common/useOwnerAccess.js diff --git a/src/common/utils.js b/src/common/utils.js index 44477d34..f3bd76ef 100644 --- a/src/common/utils.js +++ b/src/common/utils.js @@ -21,6 +21,7 @@ import { SERVER_CONFIGS } from './serverConfigs'; import { legacyHashRoute, isSameSitePath } from './history'; import { resolveV3URL, resolveIntegratedV3URL } from './appUrls'; import { getAIAssistantUsage, keepAIAssistantUsage, refreshAIAssistantUsage } from './aiAssistantUsage'; +import { getAvailableOwner } from '../components/common/ownerAccess'; export const currentPath = () => window.location.pathname; @@ -1206,8 +1207,9 @@ export const toCamelCase = str => { export const hasCapability = (user, capability) => Boolean((user || getCurrentUser())?.permissions?.includes(capability)) // `projectId`: the map project whose OCL AI Assistant report to include. -export const getMapperPreview = ({projectId} = {}) => { - const user = getCurrentUser() +// `user`: the signed-in person as they are on a map project (ownerAccess.js), +// else on their own. +export const getMapperPreview = ({projectId, user = getCurrentUser()} = {}) => { const capabilities = user?.capabilities || [] const toMeter = key => { const entry = capabilities.find(c => c.name === key) || {} @@ -1237,10 +1239,13 @@ export const getMapperPreview = ({projectId} = {}) => { } } -export const getNewProjectBlockReason = (preview = getMapperPreview()) => { +// `projectOwners`: which organizations can own a new project of theirs, when +// the API says (ownerAccess.js). Their own projects don't matter for those. +export const getNewProjectBlockReason = (preview = getMapperPreview(), projectOwners = null) => { if(isAdminUser()) return null if(!preview.hasAccess) return 'access' + if(getAvailableOwner(projectOwners)) return null const { projects } = preview if(projects.limit === null || projects.limit === undefined) return 'projects_not_entitled' if(!projects.unlimited && projects.remaining <= 0) return 'projects' diff --git a/src/components/common/NamespaceDropdown.jsx b/src/components/common/NamespaceDropdown.jsx index bf3fd981..4481ffd5 100644 --- a/src/components/common/NamespaceDropdown.jsx +++ b/src/components/common/NamespaceDropdown.jsx @@ -6,26 +6,73 @@ import ListItem from '@mui/material/ListItem' import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import InputAdornment from '@mui/material/InputAdornment'; +import Box from '@mui/material/Box' +import Link from '@mui/material/Link' +import Tooltip from '@mui/material/Tooltip' +import useMediaQuery from '@mui/material/useMediaQuery' +import { visuallyHidden } from '@mui/utils' import GlobalIcon from '@mui/icons-material/Language'; import filter from 'lodash/filter'; import { getCurrentUser, getCurrentUserOrgs } from '../../common/utils'; import UserIcon from '../users/UserIcon'; import OrgIcon from '../orgs/OrgIcon'; +import { LockMark } from './NoticeLock' -const OwnerOption = ({ option, selected, ...rest }) => { - return ( - - +// An owner that can't be chosen is listed, locked, with why on hover or tap. +// MUI turns a disabled option's pointer events off, which would stop the +// tooltip, so they're back on here and the option takes no click. +const OwnerOption = ({ option, selected, onClick, sx, ...rest }) => { + const { unavailable } = option + const { reason, link } = unavailable || {} + const isNarrow = useMediaQuery(theme => theme.breakpoints.down('md')) + const item = ( + + {option.icon} - + + { + unavailable && + + } + {reason && {reason}} ) + return reason ? ( + + {reason} + { + link && + + {link.label} + + } + + } + > + {item} + + ) : item } -const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner, personalOnly, size, disabled, sx, helperText}) => { +// `orgAvailability` ({organization url: {available, reason, link}}): which of the +// person's organizations can be chosen. Each is listed, whatever +// `personalOnly` says; without it, `personalOnly` leaves them out. +const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner, personalOnly, orgAvailability, size, disabled, sx, helperText}) => { const { t } = useTranslation() const user = getCurrentUser() const [ownerOptions, setOwnerOptions] = React.useState([]) @@ -36,9 +83,10 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner ] if(!asOwner) options = [global, ...options] - if(!personalOnly) { + if(orgAvailability || !personalOnly) { getCurrentUserOrgs().forEach(org => { - options.push({url: org.url, id: org.id, type: org.type, name: org.name, icon: , group: t('org.my')}) + const unavailable = orgAvailability && !orgAvailability[org.url]?.available ? (orgAvailability[org.url] || {}) : null + options.push({url: org.url, id: org.id, type: org.type, name: org.name, icon: , group: t('org.my'), unavailable}) }) } setOwnerOptions(options) @@ -46,7 +94,7 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner React.useEffect(() => { prepareOwnerOptions() - }, [personalOnly, asOwner]) + }, [personalOnly, orgAvailability, asOwner]) const filterOptions = (options, { inputValue }) => inputValue ? filter(options, option => option.id.toLowerCase().includes(inputValue.toLowerCase()) || option.name.toLowerCase().includes(inputValue.toLowerCase())) : options; const selectedOption = ownerOptions.find(value => value?.url === owner) || '' @@ -61,6 +109,8 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner blurOnSelect id={id} options={ownerOptions} + getOptionDisabled={option => Boolean(option.unavailable)} + disabledItemsFocusable value={selectedOption} groupBy={option => option.group} getOptionLabel={option => option.id || ''} diff --git a/src/components/common/__tests__/ownerAccess.test.js b/src/components/common/__tests__/ownerAccess.test.js new file mode 100644 index 00000000..d978a720 --- /dev/null +++ b/src/components/common/__tests__/ownerAccess.test.js @@ -0,0 +1,69 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +const { + getAvailableOwner, getOwnerAccessRequest, getProjectOwnersRequest, isAskedAbout, toOwnerAccess, toProjectOwners, + withOwnerAccess, +} = await import('../ownerAccess.js') + +const API = {baseURL: 'https://api.example.org/', token: 'personal-token'} +const headers = {Authorization: 'Token personal-token'} + +test('asks about an organization\'s content, never a person\'s', () => { + assert.deepEqual(getOwnerAccessRequest({...API, owner: '/orgs/Example/'}), { + url: 'https://api.example.org/capabilities/orgs/Example/', params: undefined, headers, + }) + for(const owner of ['/users/someone/', '/orgs/Example/sources/', '/orgs//', '', null, undefined]) { + assert.equal(isAskedAbout(owner), false, owner) + assert.equal(getOwnerAccessRequest({...API, owner}), null, owner) + } + assert.equal(getOwnerAccessRequest({...API, token: '', owner: '/orgs/Example/'}), null) + assert.equal(getOwnerAccessRequest({...API, baseURL: '', owner: '/orgs/Example/'}), null) +}) + +test('the person has what the API says on that content, and stays themselves', () => { + const user = {username: 'someone', url: '/users/someone/', auth_groups: ['a'], capabilities: [{name: 'x', limit: 1}], permissions: ['p']} + const access = toOwnerAccess({capabilities: [{name: 'x', limit: 15}], permissions: ['p', 'q'], other: 1}) + assert.deepEqual(withOwnerAccess(user, access), { + ...user, capabilities: [{name: 'x', limit: 15}], permissions: ['p', 'q'], ownerAccess: access + }) + for(const none of [null, undefined]) + assert.equal(withOwnerAccess(user, none), user) + assert.equal(withOwnerAccess(null, access), null) +}) + +test('only a whole answer counts', () => { + for(const data of [null, undefined, '', 'text', [], {}, {capabilities: []}, {permissions: []}, {capabilities: {}, permissions: []}]) + assert.equal(toOwnerAccess(data), null, JSON.stringify(data)) +}) + +test('asks which organizations can own a new project, in the UI language', () => { + assert.deepEqual(getProjectOwnersRequest({...API, lang: 'pt-BR'}), { + url: 'https://api.example.org/capabilities/mapper.projects/owners/', params: {lang: 'pt-BR'}, headers, + }) + assert.equal(getProjectOwnersRequest({...API, token: ''}), null) +}) + +test('an organization is available only when the API says so, and the reason is the API\'s', () => { + const link = {label: 'Read more', url: 'https://example.org/more'} + assert.deepEqual(toProjectOwners({owners: { + '/orgs/A/': {available: true, reason: 'x', link}, + '/orgs/B/': {available: false, reason: ' Not this one ', link}, + '/orgs/C/': {available: 'yes', reason: 3, link: {label: 'Bad', url: 'javascript:alert(1)'}}, + '/orgs/D/': null, + '/users/someone/': {available: true}, + }}), { + '/orgs/A/': {available: true, reason: null, link: null}, + '/orgs/B/': {available: false, reason: 'Not this one', link}, + '/orgs/C/': {available: false, reason: null, link: null}, + '/orgs/D/': {available: false, reason: null, link: null}, + }) + for(const data of [null, undefined, 'text', {}, {owners: null}, {owners: []}]) + assert.equal(toProjectOwners(data), null, JSON.stringify(data)) +}) + +test('the first organization that can own one', () => { + assert.equal(getAvailableOwner({'/orgs/A/': {available: false}, '/orgs/B/': {available: true}, '/orgs/C/': {available: true}}), '/orgs/B/') + for(const owners of [null, undefined, {}, {'/orgs/A/': {available: false}}]) + assert.equal(getAvailableOwner(owners), null) +}) diff --git a/src/components/common/ownerAccess.js b/src/components/common/ownerAccess.js new file mode 100644 index 00000000..e7b724c0 --- /dev/null +++ b/src/components/common/ownerAccess.js @@ -0,0 +1,56 @@ +// What the API may say about who owns a map project (OpenConceptLab/ocl_online#654, +// #716): what the signed-in person can use on an organization's content, and +// which of their organizations can own a new map project. Open code uses only +// what it's sent. An API without these routes sends nothing, and the person's +// own limits and permissions then apply everywhere. +const ORG_URL = /^\/orgs\/[^/]+\/$/ + +const toRequest = (baseURL, token, path, params) => baseURL && token ? { + url: `${baseURL.replace(/\/+$/, '')}/capabilities${path}`, + params, + headers: {Authorization: `Token ${token}`}, +} : null + +// A person's own content goes by their own user detail, so only an +// organization's is asked about. +export const isAskedAbout = owner => ORG_URL.test(owner || '') + +export const getOwnerAccessRequest = ({baseURL, token, owner}) => + isAskedAbout(owner) ? toRequest(baseURL, token, owner) : null + +// `capabilities` and `permissions` as the user detail gives a person's own. +// Only a whole answer counts. +export const toOwnerAccess = data => + Array.isArray(data?.capabilities) && Array.isArray(data?.permissions) ? data : null + +// The person as they are on that content. `ownerAccess` is the API's whole +// answer, for the checkpoints (autoMatchCheck.js). +export const withOwnerAccess = (user, ownerAccess) => user && ownerAccess ? + {...user, capabilities: ownerAccess.capabilities, permissions: ownerAccess.permissions, ownerAccess} : + user + +export const getProjectOwnersRequest = ({baseURL, token, lang}) => + toRequest(baseURL, token, '/mapper.projects/owners/', {lang}) + +const toText = value => typeof value === 'string' && value.trim() ? value.trim() : null + +// Only an http(s) link with a label is shown. +const toLink = link => { + const label = toText(link?.label) + return label && /^https?:\/\//.test(link.url) ? {label, url: link.url} : null +} + +// {organization url: {available, reason, link}}. `reason` and `link` say why one +// that isn't available can't be chosen, and where to read more. +export const toProjectOwners = data => { + const owners = data?.owners + if(!owners || typeof owners !== 'object' || Array.isArray(owners)) + return null + return Object.fromEntries(Object.entries(owners).filter(([url]) => isAskedAbout(url)).map(([url, owner]) => { + const available = owner?.available === true + return [url, {available, reason: available ? null : toText(owner?.reason), link: available ? null : toLink(owner?.link)}] + })) +} + +export const getAvailableOwner = owners => + Object.keys(owners || {}).find(url => owners[url].available) || null diff --git a/src/components/common/useOwnerAccess.js b/src/components/common/useOwnerAccess.js new file mode 100644 index 00000000..c789c61c --- /dev/null +++ b/src/components/common/useOwnerAccess.js @@ -0,0 +1,55 @@ +import React from 'react' +import axios from 'axios' +import { useTranslation } from 'react-i18next' + +import { currentUserToken, getAPIURL } from '../../common/utils' +import { getOwnerAccessRequest, getProjectOwnersRequest, isAskedAbout, toOwnerAccess, toProjectOwners } from './ownerAccess' + +// The API's answer for `key`: undefined while it's being asked, null when there +// is nothing to ask or the API gives none. A new `version` asks again and keeps +// the last answer until the next, also when asking fails. axios directly, not +// APIService, so a missing route or a refusal skips its sign-out and throttling +// handling. +const useAnswer = (key, request, toAnswer, version) => { + const [state, setState] = React.useState({key: null, answer: null}) + React.useEffect(() => { + if(!key) + return undefined + // only the latest request's reply + let current = true + const keepOr = answer => current && setState(prev => answer || prev.key !== key ? {key, answer} : prev) + if(request) + axios.get(request.url, {params: request.params, headers: request.headers, timeout: 10000}) + .then(response => keepOr(toAnswer(response.data))) + .catch(() => keepOr(null)) + else + keepOr(null) + return () => { + current = false + } + }, [key, version]) + + if(!key) + return null + return state.key === key ? state.answer : undefined +} + +// What the person can use on `owner`'s content, or null when it's their own +// that applies (ownerAccess.js). +export const useOwnerAccess = (owner, version) => useAnswer( + isAskedAbout(owner) ? owner : null, + getOwnerAccessRequest({baseURL: getAPIURL(), token: currentUserToken(), owner}), + toOwnerAccess, + version +) + +// Which of the person's organizations can own a new map project of theirs. +export const useProjectOwners = version => { + const { i18n } = useTranslation() + return useAnswer( + i18n.language, + getProjectOwnersRequest({baseURL: getAPIURL(), token: currentUserToken(), lang: i18n.language}), + toProjectOwners, + version + ) +} diff --git a/src/components/map-projects/AutoMatchDialog.jsx b/src/components/map-projects/AutoMatchDialog.jsx index fe560d45..b8857554 100644 --- a/src/components/map-projects/AutoMatchDialog.jsx +++ b/src/components/map-projects/AutoMatchDialog.jsx @@ -62,6 +62,7 @@ const AutoMatchDialog = ({ onSubmit, inAIAssistantGroup, aiAssistant, + user, algosSelected, runnableAlgos, retrieveCandidates: retrieveCandidatesChecked, @@ -112,7 +113,7 @@ const AutoMatchDialog = ({ const matchAlgorithmCount = retrieveCandidates ? runnableAlgos.filter(algo => matchAlgorithmIdSet.has(algo.id)).length : 0 const check = useAutoMatchCheck({ open, autoMatchScope, rowsToMatchCount, totalRows, retrieveCandidates, matchAlgorithmCount, - runAI, isAIOnly, aiRowsToAnalyse, inAIAssistantGroup, aiAssistant + runAI, isAIOnly, aiRowsToAnalyse, inAIAssistantGroup, aiAssistant, user }) React.useEffect(() => { diff --git a/src/components/map-projects/ConfigurationForm.jsx b/src/components/map-projects/ConfigurationForm.jsx index 7c0fd0e7..ad1d4fea 100644 --- a/src/components/map-projects/ConfigurationForm.jsx +++ b/src/components/map-projects/ConfigurationForm.jsx @@ -75,7 +75,7 @@ const getSuggestedRepos = () => (window.REPO_SUGGESTIONS || process.env.REPO_SUG .filter(([owner, id]) => owner && id) .map(([owner, id]) => ({id, short_code: id, name: id, owner, ownerType: 'Organization', type: 'Source', url: `/orgs/${owner}/sources/${id}/`})) -const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showTargetRepoVersionError, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => { +const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showTargetRepoVersionError, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, projectOwners, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => { const { t } = useTranslation(); // A read-only project's settings are shown, not changed: every field that // changes them is disabled (OpenConceptLab/ocl_online#424). @@ -172,6 +172,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n onChange={(event, item) => setOwner(item?.url || '')} asOwner personalOnly={!canUseOrgProjects} + orgAvailability={projectOwners} disabled={locked} sx={{marginTop: '12px'}} helperText={projectsNote} diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 4d60ee69..5bbf40f3 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -118,6 +118,8 @@ import { EditLockContext, LockMark, LockTooltip } from '../common/NoticeLock' import useResourceNotice from '../common/useResourceNotice' import { createReadOnlyLock } from './readOnlyLock' import { toLimitRefusal } from '../common/limitNotice.js' +import { getAvailableOwner, withOwnerAccess } from '../common/ownerAccess.js' +import { useOwnerAccess, useProjectOwners } from '../common/useOwnerAccess.js' import MapperQuotaChip from './MapperQuotaChip' import MapProjectBreadcrumb from './MapProjectBreadcrumb' import { getPreviewLimitError, isAIPreviewLimitError, isPreviewLimitError } from './previewLimits' @@ -170,7 +172,7 @@ const fetchMappedSourcesPage = (url, page) => APIService.new().overrideURL(url). const MapProject = () => { const { t } = useTranslation(); const { toggles, setAlert: baseSetAlert, setProjectRowSearch } = React.useContext(OperationsContext); - const user = getCurrentUser() + const signedInUser = getCurrentUser() const [mapperQuotaCacheVersion, setMapperQuotaCacheVersion] = React.useState(0) const [, setAIAssistantUsageVersion] = React.useState(0) // {usage: false} skips asking the OCL AI Assistant, when its reply already @@ -202,7 +204,14 @@ const MapProject = () => { // project state const [project, setProject] = React.useState(null) const [name, setName] = React.useState('') - const [owner, setOwner] = React.useState(user?.url) + const [owner, setOwner] = React.useState(signedInUser?.url) + // The project's own limits and permissions, not the person's, when its owner + // has any: `user` is the person as they are on this project + // (OpenConceptLab/ocl_online#654). A saved project goes by the owner it has. + const projectOwnerURL = project?.owner_url || (params.projectId ? `/${params.ownerType}/${params.owner}/` : owner) + const ownerAccess = useOwnerAccess(projectOwnerURL, mapperQuotaCacheVersion) + const user = withOwnerAccess(signedInUser, ownerAccess) + const projectOwners = useProjectOwners() const [description, setDescription] = React.useState('') const [file, setFile] = React.useState(false) const [data, setData] = React.useState(false) @@ -782,7 +791,7 @@ const MapProject = () => { const inAIAssistantGroup = Boolean(hasCapability(user, 'users.mapper_ai_assistant') && AI_ASSISTANT_API_URL) // What the checkpoints in autoMatchCheck.js get about the OCL AI Assistant const aiAssistant = { - usage: getMapperPreview({projectId: params.projectId}).aiAssistantUsage, + usage: getMapperPreview({projectId: params.projectId, user}).aiAssistantUsage, projectId: params.projectId, apiURL: getAPIURL(), } @@ -790,7 +799,7 @@ const MapProject = () => { // Batch size and concurrent requests per algorithm the user can set // (ocl_online#274, ocl_issues#2849, ocl_online#517) const requestLimits = getRequestLimits(getMapperSettings(user)) - const mapperPreview = getMapperPreview() + const mapperPreview = getMapperPreview({user}) // Only staff choose the AI model and prompt template (canSelectAIModel gates // both pickers). Users granted it keep the output language; everyone else // gets the project's template and its default model. @@ -929,9 +938,15 @@ const MapProject = () => { refreshMapperQuotaCache() }, [params.projectId]) - const newProjectBlockReason = (!params.projectId && !project?.id && mapperQuotaCacheVersion > 0) - ? getNewProjectBlockReason(getMapperPreview()) - : null + const isCheckedNewProject = !params.projectId && !project?.id && mapperQuotaCacheVersion > 0 && projectOwners !== undefined + const newProjectBlockReason = isCheckedNewProject ? getNewProjectBlockReason(getMapperPreview(), projectOwners) : null + + // Someone who can start no more projects of their own starts one in an + // organization that can own it. + React.useEffect(() => { + if(isCheckedNewProject && owner === signedInUser?.url && getNewProjectBlockReason(getMapperPreview())) + setOwner(getAvailableOwner(projectOwners) || owner) + }, [isCheckedNewProject]) React.useEffect(() => { const isDefaultApplied = isRepoDefaultFilterApplied(repoVersion) @@ -1675,7 +1690,7 @@ const MapProject = () => { if(!isResuming) { // Preview projects hold the first N rows of the spreadsheet; say so at // import instead of surprising the user at Auto Match. - const { rowsPerProject } = getMapperPreview() + const { rowsPerProject } = mapperPreview if(!rowsPerProject.unlimited && isNumber(rowsPerProject.limit) && _data.length > rowsPerProject.limit) baseSetAlert({ severity: 'info', @@ -3350,7 +3365,7 @@ const MapProject = () => { applied: autoMatchAIDefaultAppliedRef.current, logsLoaded: projectLogsLoaderRef.current.isLoaded(), projectLogs: projectLogsRef.current, - aiOnByDefault: aiOnByDefault({aiAssistant}), + aiOnByDefault: aiOnByDefault({aiAssistant, user}), }) autoMatchAIDefaultAppliedRef.current = applied setAutoRunAIAnalysis(runAI) @@ -3375,8 +3390,8 @@ const MapProject = () => { // algorithms the rows the OCL AI Assistant can analyse. const getAutoMatchRunRows = (rows, selectedAlgos) => { const algos = filter(runnableAlgos, algo => selectedAlgos.includes(algo.id)) - const scopeRows = getRowsToProcess(rows, rowStatuses, autoMatchScope, getSelectedRowIndexes(rows), getPreviewEligibleRowIndexes(rows, getMapperPreview())) - const maxRows = getMaxRunRows({matchAlgorithmCount: filter(algos, algo => spendsMatchQuota(algo, {canBridge})).length}) + const scopeRows = getRowsToProcess(rows, rowStatuses, autoMatchScope, getSelectedRowIndexes(rows), getPreviewEligibleRowIndexes(rows, mapperPreview)) + const maxRows = getMaxRunRows({matchAlgorithmCount: filter(algos, algo => spendsMatchQuota(algo, {canBridge})).length, user}) const firstRows = takeRunRows(scopeRows, maxRows) const isAIOnly = !algos.length && Boolean(inAIAssistantGroup && autoRunAIAnalysis) return { @@ -4015,8 +4030,8 @@ const MapProject = () => { } const previewEligibleRowIndexes = React.useMemo( - () => getPreviewEligibleRowIndexes(data, getMapperPreview()), - [data, mapperQuotaCacheVersion] + () => getPreviewEligibleRowIndexes(data, mapperPreview), + [data, mapperQuotaCacheVersion, ownerAccess] ) const previewEligibleRowIndexSet = React.useMemo( () => Array.isArray(previewEligibleRowIndexes) ? new Set(previewEligibleRowIndexes.map(id => id?.toString())) : null, @@ -6537,7 +6552,8 @@ const MapProject = () => { canSelectAIModel={canSelectAIModel} canSetAIOutputLocale={canSetAIOutputLocale} canScispacy={canScispacy} - canUseOrgProjects={mapperPreview.hasOrgProjects} + projectOwners={projectOwners} + canUseOrgProjects={mapperPreview.hasOrgProjects || ownerAccess === undefined} canUseCustomAlgorithms={mapperPreview.hasCustomAlgorithms} scispacyEnabled={scispacyEnabled} setAIAssistantColumns={setAIAssistantColumns} @@ -6569,7 +6585,7 @@ const MapProject = () => { const onCopyClick = event => { event.preventDefault() event.stopPropagation() - const blockReason = getNewProjectBlockReason() + const blockReason = getNewProjectBlockReason(getMapperPreview(), projectOwners) if(blockReason) { setPreviewLimit({errorCode: NEW_PROJECT_BLOCK_ERROR_CODES[blockReason]}) return @@ -6614,7 +6630,7 @@ const MapProject = () => { })() } { - loadingProject && + (loadingProject || (params.projectId && ownerAccess === undefined)) && } { } - + { scispacyCandidatesStartedAt && @@ -7032,6 +7048,7 @@ const MapProject = () => { retryTargetReadsWaiting: targetReadsRetryAt > 0, inAIAssistantGroup, aiAssistant, + user, algosSelected, runnableAlgos, retrieveCandidates: autoRetrieveCandidates, diff --git a/src/components/map-projects/MapProjects.jsx b/src/components/map-projects/MapProjects.jsx index 203d1c80..63a047ce 100644 --- a/src/components/map-projects/MapProjects.jsx +++ b/src/components/map-projects/MapProjects.jsx @@ -33,6 +33,7 @@ import DeleteOutlined from '@mui/icons-material/DeleteOutlined'; import APIService from '../../services/APIService' import { getCurrentUser, getMapperPreview, getNewProjectBlockReason, refreshCurrentUserCapabilitiesCache, refreshCapabilitiesAndAIAssistantUsage } from '../../common/utils' +import { useProjectOwners } from '../common/useOwnerAccess' import OwnerIcon from '../common/OwnerIcon' import NoResults from '../search/NoResults'; import MapProjectDeleteConfirmDialog from './MapProjectDeleteConfirmDialog'; @@ -72,6 +73,7 @@ const MapProjects = () => { refreshCapabilitiesAndAIAssistantUsage({onCapabilities: onChange, onUsage: onChange}) }, []) React.useEffect(() => { refreshMapperQuotaCache() }, []) + const projectOwners = useProjectOwners() const [newProjectBlock, setNewProjectBlock] = React.useState(null) const [checkingNewProject, setCheckingNewProject] = React.useState(false) const [loading, setLoading] = React.useState([]) @@ -118,7 +120,8 @@ const MapProjects = () => { const startNewProject = templateURL => { const goToNewProject = () => history.push(templateURL ? `/map-projects/new?templateFrom=${encodeURIComponent(templateURL)}` : '/map-projects/new') - const reasonFromCache = () => getNewProjectBlockReason(getMapperPreview()) + // Until the API's answer is in, the new project's page decides. + const reasonFromCache = () => projectOwners === undefined ? null : getNewProjectBlockReason(getMapperPreview(), projectOwners) const showBlock = reason => setNewProjectBlock({reason}) const cachedReason = reasonFromCache() diff --git a/src/components/map-projects/MapperQuotaChip.jsx b/src/components/map-projects/MapperQuotaChip.jsx index 50c3906e..41a9c26f 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -33,9 +33,10 @@ const AIAssistantUsageChip = ({usage, size}) => { } // `projectId`: the map project open, whose OCL AI Assistant report it shows. -const MapperQuotaChip = ({size = 'small', projectId}) => { +// `user`: the person as they are on it. +const MapperQuotaChip = ({size = 'small', projectId, user}) => { const { t } = useTranslation() - const preview = getMapperPreview({projectId}) + const preview = getMapperPreview({projectId, user}) const { rowsPerProject, matchOperations, aiAssistantCalls, aiAssistantUsage, projects } = preview if(!preview.hasAccess) return null diff --git a/src/components/map-projects/autoMatchCheck.js b/src/components/map-projects/autoMatchCheck.js index da8e58d3..627abebd 100644 --- a/src/components/map-projects/autoMatchCheck.js +++ b/src/components/map-projects/autoMatchCheck.js @@ -5,8 +5,10 @@ // useAutoMatchCheck receives what the user has selected in the dialog: // {open, autoMatchScope, rowsToMatchCount, totalRows, retrieveCandidates, // matchAlgorithmCount, runAI, isAIOnly, aiRowsToAnalyse, inAIAssistantGroup, -// aiAssistant} -// where aiAssistant is {usage, projectId, apiURL}: what the connected OCL AI +// aiAssistant, user} +// where user is the signed-in person with the capabilities and permissions they +// have on this project, and user.ownerAccess what the API said about its owner, +// when it did (ownerAccess.js). aiAssistant is {usage, projectId, apiURL}: what the connected OCL AI // Assistant last reported for the open project ({meter, used}, or null), the // project's id (none until it's saved) and the OCL API the user is signed in // to. It returns {summary: ReactNode | null, notices: [{key, severity, text, @@ -17,17 +19,17 @@ const useAutoMatchCheck = selection => ({summary: null, notices: []}) // Whether the OCL AI Assistant may start ticked when the dialog opens, given -// {aiAssistant}. +// {aiAssistant, user}. export const aiOnByDefault = () => true -// The most rows a run may include, given {matchAlgorithmCount}, or null for +// The most rows a run may include, given {matchAlgorithmCount, user}, or null for // all of the rows in its scope. A run takes its scope's first rows. // eslint-disable-next-line no-unused-vars export const getMaxRunRows = run => null // The most rows per matching request, and requests in flight per algorithm, // that the user can set in the form: {batchSize, concurrentRequests}. A saved -// project runs within them too. Here, the form's full range. +// project runs within them too. `user` is as above. Here, the form's full range. // eslint-disable-next-line no-unused-vars export const getMapperSettings = user => ({batchSize: 1000, concurrentRequests: 50}) From 6f38d70f411e07a5a1c3e35f97fd38da4c1602a3 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 3 Dec 2026 02:07:34 -0500 Subject: [PATCH 2/8] OpenConceptLab/ocl_online#654 | The rows chip says how many rows a project may have, with no "Preview" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/map-projects/MapperQuotaChip.jsx | 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 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/components/map-projects/MapperQuotaChip.jsx b/src/components/map-projects/MapperQuotaChip.jsx index 41a9c26f..175c6a46 100644 --- a/src/components/map-projects/MapperQuotaChip.jsx +++ b/src/components/map-projects/MapperQuotaChip.jsx @@ -83,7 +83,7 @@ const MapperQuotaChip = ({size = 'small', projectId, user}) => { size={size} variant='outlined' color={atLimit ? 'error' : (nearLimit ? 'warning' : 'default')} - label={t('map_project.preview_quota_chip', {limit: rowsPerProject.limit})} + label={t('map_project.preview_quota_chip', {limit: rowsPerProject.limit?.toLocaleString()})} /> ) diff --git a/src/i18n/locales/en/translations.json b/src/i18n/locales/en/translations.json index d2d86ef1..01d34dcb 100644 --- a/src/i18n/locales/en/translations.json +++ b/src/i18n/locales/en/translations.json @@ -323,7 +323,7 @@ "preview_splash_subhead": "The OCL Mapper takes a spreadsheet of local clinical terms and proposes standard-terminology matches, ranked, with the evidence for each one.", "preview_splash_sign_in_cta": "Sign in and start mapping", "preview_splash_register_cta": "Create a free account", - "preview_quota_chip": "Preview: {{limit}} rows per project", + "preview_quota_chip": "{{limit}} rows per project", "preview_quota_tooltip_title": "Your Mapper preview (one-time allowance)", "preview_quota_projects": "Projects", "preview_quota_rows": "Rows per project", diff --git a/src/i18n/locales/es/translations.json b/src/i18n/locales/es/translations.json index 74768eec..576fbbba 100644 --- a/src/i18n/locales/es/translations.json +++ b/src/i18n/locales/es/translations.json @@ -304,7 +304,7 @@ "preview_splash_subhead": "El Mapper de OCL toma una hoja de cálculo de términos clínicos locales y propone coincidencias con terminologías estándar, clasificadas, con la evidencia de cada una.", "preview_splash_sign_in_cta": "Iniciar sesión y empezar a mapear", "preview_splash_register_cta": "Crear una cuenta gratuita", - "preview_quota_chip": "Vista previa: {{limit}} filas por proyecto", + "preview_quota_chip": "{{limit}} filas por proyecto", "preview_quota_tooltip_title": "Tu vista previa del Mapper (asignación única)", "preview_quota_projects": "Proyectos", "preview_quota_rows": "Filas por proyecto", diff --git a/src/i18n/locales/pt-BR/translations.json b/src/i18n/locales/pt-BR/translations.json index 72362fee..98367380 100644 --- a/src/i18n/locales/pt-BR/translations.json +++ b/src/i18n/locales/pt-BR/translations.json @@ -323,7 +323,7 @@ "preview_splash_subhead": "O OCL Mapper pega uma planilha de termos clínicos locais e propõe correspondências de terminologia padrão, ranqueadas, com a evidência para cada uma.", "preview_splash_sign_in_cta": "Entre e comece a mapear", "preview_splash_register_cta": "Criar uma conta gratuita", - "preview_quota_chip": "Prévia: {{limit}} linhas por projeto", + "preview_quota_chip": "{{limit}} linhas por projeto", "preview_quota_tooltip_title": "Sua prévia do Mapper (cota única)", "preview_quota_projects": "Projetos", "preview_quota_rows": "Linhas por projeto", diff --git a/src/i18n/locales/zh/translations.json b/src/i18n/locales/zh/translations.json index 1ca75730..8440b21b 100644 --- a/src/i18n/locales/zh/translations.json +++ b/src/i18n/locales/zh/translations.json @@ -316,7 +316,7 @@ "preview_splash_subhead": "OCL Mapper 读取本地临床术语表,提出经过排序的标准术语匹配建议,并附带每条建议的依据。", "preview_splash_sign_in_cta": "登录并开始映射", "preview_splash_register_cta": "创建免费账户", - "preview_quota_chip": "预览:每个项目 {{limit}} 行", + "preview_quota_chip": "每个项目 {{limit}} 行", "preview_quota_tooltip_title": "你的 Mapper 预览额度(一次性配额)", "preview_quota_projects": "项目", "preview_quota_rows": "每个项目的行数", From d878017dca9cb57802e52ec9ab7bcf05fea9e6b0 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 3 Dec 2026 02:26:49 -0500 Subject: [PATCH 3/8] OpenConceptLab/ocl_online#654 | Until a project is saved, its requests count as the person's own; the reason shows by keyboard too, and the usage chip's title says only what it lists Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/common/NamespaceDropdown.jsx | 17 +++++++++++----- .../common/__tests__/ownerAccess.test.js | 20 ++++++++++++++++--- src/components/common/ownerAccess.js | 17 +++++++++++++--- .../map-projects/ConfigurationForm.jsx | 4 ++-- src/components/map-projects/MapProject.jsx | 9 ++++++--- 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 +- 9 files changed, 55 insertions(+), 20 deletions(-) diff --git a/src/components/common/NamespaceDropdown.jsx b/src/components/common/NamespaceDropdown.jsx index 4481ffd5..5b410936 100644 --- a/src/components/common/NamespaceDropdown.jsx +++ b/src/components/common/NamespaceDropdown.jsx @@ -19,13 +19,15 @@ import OrgIcon from '../orgs/OrgIcon'; import { LockMark } from './NoticeLock' -// An owner that can't be chosen is listed, locked, with why on hover or tap. -// MUI turns a disabled option's pointer events off, which would stop the -// tooltip, so they're back on here and the option takes no click. -const OwnerOption = ({ option, selected, onClick, sx, ...rest }) => { +// An owner that can't be chosen is listed, locked, with why on hover, on tap and +// when the arrow keys reach it (`isReached`: the focus stays in the field). MUI +// turns a disabled option's pointer events off, which would stop the tooltip, so +// they're back on here and the option takes no click. +const OwnerOption = ({ option, selected, isReached, onClick, sx, ...rest }) => { const { unavailable } = option const { reason, link } = unavailable || {} const isNarrow = useMediaQuery(theme => theme.breakpoints.down('md')) + const [isPointedAt, setIsPointedAt] = React.useState(false) const item = ( { return reason ? ( setIsPointedAt(true)} + onClose={() => setIsPointedAt(false)} placement={isNarrow ? 'top-start' : 'right'} enterTouchDelay={0} leaveTouchDelay={6000} @@ -76,6 +81,7 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner const { t } = useTranslation() const user = getCurrentUser() const [ownerOptions, setOwnerOptions] = React.useState([]) + const [reachedURL, setReachedURL] = React.useState(null) const prepareOwnerOptions = () => { const global = {url: '/', id: t('url_registry.global_registry'), type: '', name: t('url_registry.global_registry'), icon: , group: '' } let options = [ @@ -111,10 +117,11 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner options={ownerOptions} getOptionDisabled={option => Boolean(option.unavailable)} disabledItemsFocusable + onHighlightChange={(event, option, reason) => setReachedURL(reason === 'keyboard' && option ? option.url : null)} value={selectedOption} groupBy={option => option.group} getOptionLabel={option => option.id || ''} - renderOption={(props, option, { selected }) => } + renderOption={(props, option, { selected }) => } onChange={onChange} renderInput={ params => { diff --git a/src/components/common/__tests__/ownerAccess.test.js b/src/components/common/__tests__/ownerAccess.test.js index d978a720..2f1b3f6b 100644 --- a/src/components/common/__tests__/ownerAccess.test.js +++ b/src/components/common/__tests__/ownerAccess.test.js @@ -24,12 +24,26 @@ test('asks about an organization\'s content, never a person\'s', () => { test('the person has what the API says on that content, and stays themselves', () => { const user = {username: 'someone', url: '/users/someone/', auth_groups: ['a'], capabilities: [{name: 'x', limit: 1}], permissions: ['p']} const access = toOwnerAccess({capabilities: [{name: 'x', limit: 15}], permissions: ['p', 'q'], other: 1}) - assert.deepEqual(withOwnerAccess(user, access), { + assert.deepEqual(withOwnerAccess(user, access, true), { ...user, capabilities: [{name: 'x', limit: 15}], permissions: ['p', 'q'], ownerAccess: access }) for(const none of [null, undefined]) - assert.equal(withOwnerAccess(user, none), user) - assert.equal(withOwnerAccess(null, access), null) + assert.equal(withOwnerAccess(user, none, true), user) + assert.equal(withOwnerAccess(null, access, true), null) +}) + +test('until the project is saved, what its requests use is the person\'s own', () => { + const own = [{name: 'mapper.match_operations', limit: 100}, {name: 'ai_assistant.calls', limit: 5}, {name: 'mapper.rows_per_project', limit: 25}] + const owners = [{name: 'mapper.match_operations', limit: 1250}, {name: 'mapper.rows_per_project', limit: 2000}] + const access = {capabilities: owners, permissions: []} + const limits = user => Object.fromEntries(user.capabilities.map(({ name, limit }) => [name, limit])) + assert.deepEqual(limits(withOwnerAccess({capabilities: own}, access, false)), { + 'mapper.rows_per_project': 2000, 'mapper.match_operations': 100, 'ai_assistant.calls': 5 + }) + assert.deepEqual(limits(withOwnerAccess({}, access, false)), {'mapper.rows_per_project': 2000}) + assert.deepEqual(limits(withOwnerAccess({capabilities: own}, access, true)), { + 'mapper.rows_per_project': 2000, 'mapper.match_operations': 1250 + }) }) test('only a whole answer counts', () => { diff --git a/src/components/common/ownerAccess.js b/src/components/common/ownerAccess.js index e7b724c0..b8218e1f 100644 --- a/src/components/common/ownerAccess.js +++ b/src/components/common/ownerAccess.js @@ -23,11 +23,22 @@ export const getOwnerAccessRequest = ({baseURL, token, owner}) => export const toOwnerAccess = data => Array.isArray(data?.capabilities) && Array.isArray(data?.permissions) ? data : null +// What a request uses counts as the person's own until the project is saved: +// before that, no request can name it. +const COUNTED_BY_REQUEST = ['mapper.match_operations', 'ai_assistant.calls'] +const getCounted = capabilities => (capabilities || []).filter(({ name }) => COUNTED_BY_REQUEST.includes(name)) +const getUncounted = capabilities => capabilities.filter(({ name }) => !COUNTED_BY_REQUEST.includes(name)) + // The person as they are on that content. `ownerAccess` is the API's whole // answer, for the checkpoints (autoMatchCheck.js). -export const withOwnerAccess = (user, ownerAccess) => user && ownerAccess ? - {...user, capabilities: ownerAccess.capabilities, permissions: ownerAccess.permissions, ownerAccess} : - user +export const withOwnerAccess = (user, ownerAccess, isSaved) => user && ownerAccess ? { + ...user, + capabilities: isSaved ? + ownerAccess.capabilities : + [...getUncounted(ownerAccess.capabilities), ...getCounted(user.capabilities)], + permissions: ownerAccess.permissions, + ownerAccess +} : user export const getProjectOwnersRequest = ({baseURL, token, lang}) => toRequest(baseURL, token, '/mapper.projects/owners/', {lang}) diff --git a/src/components/map-projects/ConfigurationForm.jsx b/src/components/map-projects/ConfigurationForm.jsx index ad1d4fea..dd5c59dc 100644 --- a/src/components/map-projects/ConfigurationForm.jsx +++ b/src/components/map-projects/ConfigurationForm.jsx @@ -75,7 +75,7 @@ const getSuggestedRepos = () => (window.REPO_SUGGESTIONS || process.env.REPO_SUG .filter(([owner, id]) => owner && id) .map(([owner, id]) => ({id, short_code: id, name: id, owner, ownerType: 'Organization', type: 'Source', url: `/orgs/${owner}/sources/${id}/`})) -const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showTargetRepoVersionError, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, projectOwners, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => { +const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showTargetRepoVersionError, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, projectOwners, isOwnerPending, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => { const { t } = useTranslation(); // A read-only project's settings are shown, not changed: every field that // changes them is disabled (OpenConceptLab/ocl_online#424). @@ -219,7 +219,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n sx={{textTransform: 'none', marginTop: '12px', width: '100%'}} startIcon={} endIcon={} - disabled={locked || Boolean(project?.id && project.input_file_name)} + disabled={locked || isOwnerPending || Boolean(project?.id && project.input_file_name)} > { file?.name ? file.name : t('map_project.upload_file') diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 5bbf40f3..43f0dae6 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -210,7 +210,8 @@ const MapProject = () => { // (OpenConceptLab/ocl_online#654). A saved project goes by the owner it has. const projectOwnerURL = project?.owner_url || (params.projectId ? `/${params.ownerType}/${params.owner}/` : owner) const ownerAccess = useOwnerAccess(projectOwnerURL, mapperQuotaCacheVersion) - const user = withOwnerAccess(signedInUser, ownerAccess) + const user = withOwnerAccess(signedInUser, ownerAccess, Boolean(params.projectId)) + const isOwnerPending = ownerAccess === undefined const projectOwners = useProjectOwners() const [description, setDescription] = React.useState('') const [file, setFile] = React.useState(false) @@ -6553,7 +6554,9 @@ const MapProject = () => { canSetAIOutputLocale={canSetAIOutputLocale} canScispacy={canScispacy} projectOwners={projectOwners} - canUseOrgProjects={mapperPreview.hasOrgProjects || ownerAccess === undefined} + // only creating one needs the permission + canUseOrgProjects={Boolean(project?.id) || mapperPreview.hasOrgProjects || isOwnerPending} + isOwnerPending={isOwnerPending} canUseCustomAlgorithms={mapperPreview.hasCustomAlgorithms} scispacyEnabled={scispacyEnabled} setAIAssistantColumns={setAIAssistantColumns} @@ -6630,7 +6633,7 @@ const MapProject = () => { })() } { - (loadingProject || (params.projectId && ownerAccess === undefined)) && + (loadingProject || (params.projectId && isOwnerPending)) && } Date: Thu, 3 Dec 2026 02:34:45 -0500 Subject: [PATCH 4/8] OpenConceptLab/ocl_online#654 | The form waits for the owner's answer, goes by which organizations can own a project, and its notices name no preview Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/map-projects/ConfigurationForm.jsx | 4 +++- src/components/map-projects/MapProject.jsx | 10 ++++++---- src/i18n/locales/en/translations.json | 8 ++++---- src/i18n/locales/es/translations.json | 8 ++++---- src/i18n/locales/pt-BR/translations.json | 8 ++++---- src/i18n/locales/zh/translations.json | 8 ++++---- 6 files changed, 25 insertions(+), 21 deletions(-) diff --git a/src/components/map-projects/ConfigurationForm.jsx b/src/components/map-projects/ConfigurationForm.jsx index dd5c59dc..04964a9d 100644 --- a/src/components/map-projects/ConfigurationForm.jsx +++ b/src/components/map-projects/ConfigurationForm.jsx @@ -125,6 +125,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n canUseCustomAlgorithms, }) const hasAccessErrors = accessErrors.length > 0 + const isFileLocked = Boolean(locked || isOwnerPending || (project?.id && project.input_file_name)) // While the project is new, any line the API sends about the projects // the chosen owner has (OpenConceptLab/ocl_online#700). const projectsNote = useCapabilityNote('mapper.projects', owner, !project?.id) @@ -219,7 +220,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n sx={{textTransform: 'none', marginTop: '12px', width: '100%'}} startIcon={} endIcon={} - disabled={locked || isOwnerPending || Boolean(project?.id && project.input_file_name)} + disabled={isFileLocked} > { file?.name ? file.name : t('map_project.upload_file') @@ -227,6 +228,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 43f0dae6..269415fb 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -4031,7 +4031,8 @@ const MapProject = () => { } const previewEligibleRowIndexes = React.useMemo( - () => getPreviewEligibleRowIndexes(data, mapperPreview), + // until the owner's answer is in, none is left out: the selection keeps its rows + () => isOwnerPending ? null : getPreviewEligibleRowIndexes(data, mapperPreview), [data, mapperQuotaCacheVersion, ownerAccess] ) const previewEligibleRowIndexSet = React.useMemo( @@ -6555,7 +6556,7 @@ const MapProject = () => { canScispacy={canScispacy} projectOwners={projectOwners} // only creating one needs the permission - canUseOrgProjects={Boolean(project?.id) || mapperPreview.hasOrgProjects || isOwnerPending} + canUseOrgProjects={Boolean(project?.id) || (projectOwners?.[owner]?.available ?? (isOwnerPending || mapperPreview.hasOrgProjects))} isOwnerPending={isOwnerPending} canUseCustomAlgorithms={mapperPreview.hasCustomAlgorithms} scispacyEnabled={scispacyEnabled} @@ -6588,7 +6589,8 @@ const MapProject = () => { const onCopyClick = event => { event.preventDefault() event.stopPropagation() - const blockReason = getNewProjectBlockReason(getMapperPreview(), projectOwners) + // until the API's answer is in, the new project's page decides + const blockReason = projectOwners === undefined ? null : getNewProjectBlockReason(getMapperPreview(), projectOwners) if(blockReason) { setPreviewLimit({errorCode: NEW_PROJECT_BLOCK_ERROR_CODES[blockReason]}) return @@ -6633,7 +6635,7 @@ const MapProject = () => { })() } { - (loadingProject || (params.projectId && isOwnerPending)) && + (loadingProject || (isOwnerPending && (params.projectId || data))) && } Date: Thu, 3 Dec 2026 03:27:13 -0500 Subject: [PATCH 5/8] OpenConceptLab/ocl_online#654 | The Owner field lists an organization joined since signing in; a row the new owner's limit leaves out is closed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/common/NamespaceDropdown.jsx | 3 ++- src/components/common/__tests__/ownerAccess.test.js | 10 +++++++++- src/components/common/ownerAccess.js | 13 +++++++++++++ src/components/map-projects/MapProject.jsx | 5 +++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/components/common/NamespaceDropdown.jsx b/src/components/common/NamespaceDropdown.jsx index 5b410936..a57acf9e 100644 --- a/src/components/common/NamespaceDropdown.jsx +++ b/src/components/common/NamespaceDropdown.jsx @@ -17,6 +17,7 @@ import { getCurrentUser, getCurrentUserOrgs } from '../../common/utils'; import UserIcon from '../users/UserIcon'; import OrgIcon from '../orgs/OrgIcon'; import { LockMark } from './NoticeLock' +import { withProjectOwners } from './ownerAccess' // An owner that can't be chosen is listed, locked, with why on hover, on tap and @@ -90,7 +91,7 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner if(!asOwner) options = [global, ...options] if(orgAvailability || !personalOnly) { - getCurrentUserOrgs().forEach(org => { + withProjectOwners(getCurrentUserOrgs(), orgAvailability).forEach(org => { const unavailable = orgAvailability && !orgAvailability[org.url]?.available ? (orgAvailability[org.url] || {}) : null options.push({url: org.url, id: org.id, type: org.type, name: org.name, icon: , group: t('org.my'), unavailable}) }) diff --git a/src/components/common/__tests__/ownerAccess.test.js b/src/components/common/__tests__/ownerAccess.test.js index 2f1b3f6b..e3d9a4dc 100644 --- a/src/components/common/__tests__/ownerAccess.test.js +++ b/src/components/common/__tests__/ownerAccess.test.js @@ -3,7 +3,7 @@ import assert from 'node:assert/strict' const { getAvailableOwner, getOwnerAccessRequest, getProjectOwnersRequest, isAskedAbout, toOwnerAccess, toProjectOwners, - withOwnerAccess, + withOwnerAccess, withProjectOwners, } = await import('../ownerAccess.js') const API = {baseURL: 'https://api.example.org/', token: 'personal-token'} @@ -81,3 +81,11 @@ test('the first organization that can own one', () => { for(const owners of [null, undefined, {}, {'/orgs/A/': {available: false}}]) assert.equal(getAvailableOwner(owners), null) }) + +test('an organization joined since signing in is listed too', () => { + const orgs = [{url: '/orgs/A/', id: 'A', name: 'First'}] + assert.deepEqual(withProjectOwners(orgs, {'/orgs/A/': {available: true}, '/orgs/B/': {available: true}}), [ + ...orgs, {url: '/orgs/B/', id: 'B', name: 'B', type: 'Organization'} + ]) + assert.deepEqual(withProjectOwners(orgs, undefined), orgs) +}) diff --git a/src/components/common/ownerAccess.js b/src/components/common/ownerAccess.js index b8218e1f..95a9297d 100644 --- a/src/components/common/ownerAccess.js +++ b/src/components/common/ownerAccess.js @@ -63,5 +63,18 @@ export const toProjectOwners = data => { })) } +// The signed-in person's organizations, as they were when they signed in, and +// any the answer has that they joined since. +export const withProjectOwners = (orgs, owners) => { + const known = new Set(orgs.map(({ url }) => url)) + return [ + ...orgs, + ...Object.keys(owners || {}).filter(url => !known.has(url)).map(url => { + const id = url.split('/')[2] + return {url, id, name: id, type: 'Organization'} + }) + ] +} + export const getAvailableOwner = owners => Object.keys(owners || {}).find(url => owners[url].available) || null diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 269415fb..c7d6b842 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -5873,6 +5873,11 @@ const MapProject = () => { return next.length === prev.length ? prev : next }) }, [visibleRowIdKey, isRowPreviewEligible]) + React.useEffect(() => { + // the owner changed to one whose projects don't take the open row + if(row && !isRowPreviewEligible(row)) + onCloseDecisions() + }, [isRowPreviewEligible]) const onDataGridCellClick = (params, event) => { if(params.field === '__check__') return From f591c3b729c43358beb5d8bd43ff004485dd7f2c Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 3 Dec 2026 03:31:52 -0500 Subject: [PATCH 6/8] OpenConceptLab/ocl_online#654 | Simplify how the owner's answer is joined with the person's own Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/common/__tests__/ownerAccess.test.js | 6 ++---- src/components/common/ownerAccess.js | 5 ++--- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/components/common/__tests__/ownerAccess.test.js b/src/components/common/__tests__/ownerAccess.test.js index e3d9a4dc..48be74ef 100644 --- a/src/components/common/__tests__/ownerAccess.test.js +++ b/src/components/common/__tests__/ownerAccess.test.js @@ -2,7 +2,7 @@ import test from 'node:test' import assert from 'node:assert/strict' const { - getAvailableOwner, getOwnerAccessRequest, getProjectOwnersRequest, isAskedAbout, toOwnerAccess, toProjectOwners, + getAvailableOwner, getOwnerAccessRequest, getProjectOwnersRequest, toOwnerAccess, toProjectOwners, withOwnerAccess, withProjectOwners, } = await import('../ownerAccess.js') @@ -13,10 +13,8 @@ test('asks about an organization\'s content, never a person\'s', () => { assert.deepEqual(getOwnerAccessRequest({...API, owner: '/orgs/Example/'}), { url: 'https://api.example.org/capabilities/orgs/Example/', params: undefined, headers, }) - for(const owner of ['/users/someone/', '/orgs/Example/sources/', '/orgs//', '', null, undefined]) { - assert.equal(isAskedAbout(owner), false, owner) + for(const owner of ['/users/someone/', '/orgs/Example/sources/', '/orgs//', '', null, undefined]) assert.equal(getOwnerAccessRequest({...API, owner}), null, owner) - } assert.equal(getOwnerAccessRequest({...API, token: '', owner: '/orgs/Example/'}), null) assert.equal(getOwnerAccessRequest({...API, baseURL: '', owner: '/orgs/Example/'}), null) }) diff --git a/src/components/common/ownerAccess.js b/src/components/common/ownerAccess.js index 95a9297d..e2e777f0 100644 --- a/src/components/common/ownerAccess.js +++ b/src/components/common/ownerAccess.js @@ -26,8 +26,7 @@ export const toOwnerAccess = data => // What a request uses counts as the person's own until the project is saved: // before that, no request can name it. const COUNTED_BY_REQUEST = ['mapper.match_operations', 'ai_assistant.calls'] -const getCounted = capabilities => (capabilities || []).filter(({ name }) => COUNTED_BY_REQUEST.includes(name)) -const getUncounted = capabilities => capabilities.filter(({ name }) => !COUNTED_BY_REQUEST.includes(name)) +const isCounted = ({ name }) => COUNTED_BY_REQUEST.includes(name) // The person as they are on that content. `ownerAccess` is the API's whole // answer, for the checkpoints (autoMatchCheck.js). @@ -35,7 +34,7 @@ export const withOwnerAccess = (user, ownerAccess, isSaved) => user && ownerAcce ...user, capabilities: isSaved ? ownerAccess.capabilities : - [...getUncounted(ownerAccess.capabilities), ...getCounted(user.capabilities)], + [...ownerAccess.capabilities.filter(item => !isCounted(item)), ...(user.capabilities || []).filter(isCounted)], permissions: ownerAccess.permissions, ownerAccess } : user From 6a8337fdf425ce18944fd48122d2ede2ef8c843c Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 3 Dec 2026 03:39:09 -0500 Subject: [PATCH 7/8] OpenConceptLab/ocl_online#654 | A row opened just as the new owner's limit leaves it out is closed too Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/map-projects/MapProject.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index c7d6b842..7e69e56c 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -5877,7 +5877,7 @@ const MapProject = () => { // the owner changed to one whose projects don't take the open row if(row && !isRowPreviewEligible(row)) onCloseDecisions() - }, [isRowPreviewEligible]) + }, [isRowPreviewEligible, rowIndex]) const onDataGridCellClick = (params, event) => { if(params.field === '__check__') return From c431565c98838e010014f4502f7db8d8aef30824 Mon Sep 17 00:00:00 2001 From: Jonathan Payne Date: Thu, 3 Dec 2026 04:18:34 -0500 Subject: [PATCH 8/8] OpenConceptLab/ocl_online#654 | A run starts from the latest counts, as before Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AaZ4qTEw8c6qZh5C69F1V4 --- src/components/map-projects/MapProject.jsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 7e69e56c..838c7efd 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -3392,7 +3392,11 @@ const MapProject = () => { const getAutoMatchRunRows = (rows, selectedAlgos) => { const algos = filter(runnableAlgos, algo => selectedAlgos.includes(algo.id)) const scopeRows = getRowsToProcess(rows, rowStatuses, autoMatchScope, getSelectedRowIndexes(rows), getPreviewEligibleRowIndexes(rows, mapperPreview)) - const maxRows = getMaxRunRows({matchAlgorithmCount: filter(algos, algo => spendsMatchQuota(algo, {canBridge})).length, user}) + const maxRows = getMaxRunRows({ + matchAlgorithmCount: filter(algos, algo => spendsMatchQuota(algo, {canBridge})).length, + // read again: another tab may have used some since this one last rendered + user: withOwnerAccess(getCurrentUser(), ownerAccess, Boolean(params.projectId)) + }) const firstRows = takeRunRows(scopeRows, maxRows) const isAIOnly = !algos.length && Boolean(inAIAssistantGroup && autoRunAIAnalysis) return {