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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,26 @@ researcher's workspace from there.
- **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL`.
Its CORS must allow PUT from this app's origin. Needs only the OSB login.

### Testing on a sandbox (local only)

Deployments always use EMBER-DANDI. To test on a sandbox instead, add this to
`applications/idp-arc/frontend/.env.local` and restart `yarn start:dev`:

```bash
# dandi-sandbox or ember-dandi-sandbox
VITE_DANDI_INSTANCE=dandi-sandbox
```

MAABCD copies then go to the protocol's dandiset for that sandbox in `src/data/protocols.json`
(none listed: nothing is shared).

The sandboxes have no OAuth app for us, so also add your API key on that sandbox there. The dev
server signs DANDI calls with it, so it never reaches the browser, and `yarn build` ignores it:

```bash
DANDI_SANDBOX_API_KEY=<your sandbox API key>
```

---

## Docker (Local Build + Run)
Expand Down
3 changes: 2 additions & 1 deletion applications/idp-arc/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^9.0.0",
"@mui/material": "^9.0.0",
"fflate": "^0.8.2",
"i18next": "^26.0.3",
"keycloak-js": "^26.2.3",
"react": "^19.2.0",
Expand All @@ -42,4 +43,4 @@
"typescript-eslint": "^8.48.0",
"vite": "^7.3.1"
}
}
}
29 changes: 19 additions & 10 deletions applications/idp-arc/frontend/src/app/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore'
import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient'
import { EmberDandiDirectClient } from '../infra/emberDandiDirectClient'
import { EmberUploadApiClient } from '../infra/emberUploadApiClient'
import { EMBER_API_ORIGIN, EMBER_WEB_ORIGIN } from '../infra/emberUrls'
import { dandiInstance } from '../core/dandiInstances'
import { SandboxApiKeyEmberAuth } from '../infra/sandboxApiKeyEmberAuth'
import type { IEmberAuth } from '../core/ports/IEmberAuth'
import type { IObjectStore } from '../core/ports/IObjectStore'
import { createEmberObjectStore } from '../core/use-cases/emberObjectStore'
import { createProtocolDandisetsUseCases, type ProtocolDandiset } from '../core/use-cases/protocolDandisets'
Expand All @@ -45,10 +47,14 @@ const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}`
export type UploadBackend = 'ember' | 'bucket'
/** VITE_UPLOAD_BACKEND: `bucket`, or EMBER-DANDI for anything else, unset included. */
export const UPLOAD_BACKEND: UploadBackend = import.meta.env.VITE_UPLOAD_BACKEND === 'bucket' ? 'bucket' : 'ember'
/** The DANDI instance in use: VITE_DANDI_INSTANCE in the dev server, EMBER-DANDI otherwise. Sets where
* the researcher's uploads go, and which of a protocol's MAABCD dandisets the copy goes to. */
export const DANDI_INSTANCE = dandiInstance(import.meta.env.DEV ? import.meta.env.VITE_DANDI_INSTANCE : undefined)
const { api: EMBER_API_ORIGIN, web: EMBER_WEB_ORIGIN } = DANDI_INSTANCE
/** The OSB (Keycloak) user whose key (user attribute `DANDI_API_KEY`) signs the copy into the
* protocol's MAABCD dandiset, and the DANDI deployment it goes to (dandi-cli's name). */
* protocol's MAABCD dandiset, on the same instance (dandi-cli's name for it). */
const MAABCD_EMBER_USERNAME = 'maabcd-consortium'
const MAABCD_DANDI_INSTANCE = 'ember-dandi'
const MAABCD_DANDI_INSTANCE = DANDI_INSTANCE.name
/** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's
* token response carries no CORS headers. */
const EMBER_FETCH_BASE = '/ember-proxy'
Expand All @@ -67,12 +73,15 @@ const workspaceApi = new WorkspaceApiClient(WORKSPACES_API, WORKSPACES_LIST_URL)

/** Signs the researcher in to EMBER-DANDI (OAuth in a popup, a full-page redirect if it is blocked);
* their token stays in the browser. */
export const emberAuth = new EmberOAuthClient({
authOrigin: EMBER_API_ORIGIN,
apiBase: EMBER_FETCH_BASE,
clientId: import.meta.env.VITE_EMBER_CLIENT_ID ?? '',
redirectUri: `${window.location.origin}${EMBER_CALLBACK_PATH}`,
})
export const emberAuth: IEmberAuth = __DANDI_SANDBOX_API_KEY__
// Dev server only: the proxy signs every call with its DANDI_SANDBOX_API_KEY (vite.config.ts).
? new SandboxApiKeyEmberAuth(EMBER_FETCH_BASE)
: new EmberOAuthClient({
authOrigin: EMBER_API_ORIGIN,
apiBase: EMBER_FETCH_BASE,
clientId: import.meta.env.VITE_EMBER_CLIENT_ID ?? '',
redirectUri: `${window.location.origin}${EMBER_CALLBACK_PATH}`,
})
export { EMBER_CALLBACK_PATH }
export { EmberPopupBlocked, EmberSignInCancelled } from '../infra/emberOAuthClient'
const emberDirect = new EmberDandiDirectClient(EMBER_FETCH_BASE)
Expand All @@ -83,7 +92,7 @@ const protocolDandisets = createProtocolDandisetsUseCases({

/** Where uploads go before OSB imports them (UPLOAD_BACKEND): EMBER-DANDI, or the public bucket. */
export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember'
? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_API_ORIGIN)
? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_API_ORIGIN, EMBER_WEB_ORIGIN)
: new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL)

// ─── Use-cases (injected with their concrete dependencies) ────────────────────
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useState } from 'react'
import { Box, IconButton, Popover, Tooltip, Typography } from '@mui/material'
import AccountTreeOutlinedIcon from '@mui/icons-material/AccountTreeOutlined'
import { contentSize, type OutputFile } from '../core/bids/convert'
import { fileTree } from '../core/bids/fileTree'
import { formatBytes } from '../core/formatBytes'

/** Shows, in a popover, the folders and files the BIDS conversion of the picked file would produce. */
export default function BidsStructureButton({ files }: { files: OutputFile[] }) {
const [anchor, setAnchor] = useState<HTMLElement | null>(null)
const sizes = new Map(files.map((f) => [f.path, contentSize(f.content)]))
const lines = fileTree(files.map((f) => f.path))
// A line's full path, to look its size up: the folders above it, then its name.
const parents: string[] = []

return (
<>
<Tooltip title="Show the structure for DANDI">
<IconButton size="small" aria-label="Show the structure for DANDI" onClick={(e) => { e.stopPropagation(); setAnchor(e.currentTarget) }}>
<AccountTreeOutlinedIcon fontSize="small" />
</IconButton>
</Tooltip>
<Popover
open={!!anchor}
anchorEl={anchor}
onClose={() => setAnchor(null)}
onClick={(e) => e.stopPropagation()}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
transformOrigin={{ vertical: 'top', horizontal: 'center' }}
slotProps={{
paper: {
sx: {
// Opaque, so the dialog underneath doesn't show through.
bgcolor: '#2A2A2A',
backgroundImage: 'none',
border: '1px solid',
borderColor: 'divider',
boxShadow: 12,
mt: 1,
},
},
}}
>
<Box sx={{ p: 2, width: 'min(640px, 90vw)', maxHeight: '60vh', overflow: 'auto' }}>
<Typography variant="body2" sx={{ mb: 1.5, pb: 1, opacity: 0.8, borderBottom: '1px solid', borderColor: 'divider' }}>
What would go to DANDI, worked out in your browser. Nothing has been uploaded.
</Typography>
<Box component="pre" sx={{ m: 0, fontFamily: 'monospace', fontSize: '12px', lineHeight: 1.6, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
{lines.map((line, i) => {
parents.length = line.depth
const path = [...parents, line.name].join('')
if (line.folder) parents.push(line.name)
const size = sizes.get(path)
return (
<Box key={i} component="span" sx={{ display: 'block', opacity: line.folder ? 0.75 : 1 }}>
{' '.repeat(line.depth)}{line.name}
{size !== undefined && <Box component="span" sx={{ opacity: 0.5 }}>{` ${formatBytes(size)}`}</Box>}
</Box>
)
})}
</Box>
</Box>
</Popover>
</>
)
}
83 changes: 74 additions & 9 deletions applications/idp-arc/frontend/src/components/DataUploadDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
MenuItem,
Select,
Stack,
TextField,
Typography,
} from '@mui/material'
import CloudUploadOutlinedIcon from '@mui/icons-material/CloudUploadOutlined'
Expand All @@ -21,7 +22,8 @@ import OpenInNewIcon from '@mui/icons-material/OpenInNewOutlined'
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined'
import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty'

import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, recordedWorkspace, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container'
import { DANDI_INSTANCE, emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, recordedWorkspace, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container'
import { maabcdDandisetFor } from '../core/dandiInstances'
import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages'
import { withRunLock } from './runStorage'
import { INITIAL_FORM, restoreSession, session } from './uploadSession'
Expand All @@ -35,10 +37,16 @@ import { isNonBlocking, PUBLISH_STEP, PUBLISHING_LABEL, type RunProtocolInput }
import { formatBytes } from '../core/formatBytes'
import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates'
import { SIGN_IN_AGAIN } from '../core/userMessages'
import type { BidsConfig } from '../core/bids/convert'
import { useBidsCheck } from './useBidsCheck'
import BidsStructureButton from './BidsStructureButton'
import protocols from '../data/protocols.json'

/** Only protocols with an analysis repository can be run, so only those are offered. */
const runnableProtocols = protocols.filter((p) => 'repoZipUrl' in p && p.repoZipUrl)
/** Only protocols with an analysis repository can be run, so only those are offered. Each carries
* its MAABCD dandiset on the DANDI instance in use (none: nothing is shared). */
const runnableProtocols = protocols
.filter((p) => 'repoZipUrl' in p && p.repoZipUrl)
.map((p) => ({ ...p, maabcdAggregateDandisetId: maabcdDandisetFor(p, DANDI_INSTANCE.name) }))
type RunnableProtocol = (typeof runnableProtocols)[number]

export interface DataUploadDialogProps {
Expand Down Expand Up @@ -69,7 +77,7 @@ const MIN_ATTEMPT_MS = 300
export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) {
const { tokenParsed } = useAppContext()
const [form] = useSessionStore(session)
const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi, publishing, publishError, checkpoint } = form
const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, dandisetName, shareWithMaabcd, doi, publishing, publishError, checkpoint } = form
// EMBER-DANDI: the upload goes to the researcher's own account. Choosing a protocol lists their
// dandisets for it, each with the workspace it runs in, so choosing one chooses both.
const usesEmber = UPLOAD_BACKEND === 'ember'
Expand All @@ -81,6 +89,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
const workspaceLookup = useRef(0)
const fileInputRef = useRef<HTMLInputElement>(null)
const user = typeof tokenParsed?.sub === 'string' ? tokenParsed.sub : null
const researcher = typeof tokenParsed?.name === 'string' ? tokenParsed.name.trim() || undefined : undefined

// Once the user is known, their run saved before a reload comes back.
useEffect(() => { if (user) restoreSession(user) }, [user])
Expand Down Expand Up @@ -192,9 +201,14 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
const inputFormats = inputFormatsFor(selectedProtocol?.inputFormats)
const templatesHref = templatesZipHref(selectedProtocol)
const fileProblem = file ? inputFileProblem(file, selectedProtocol?.name ?? 'This protocol', selectedProtocol?.inputFormats) : null
// The file is converted to BIDS on pick, and its errors stop the upload.
const bidsConfig = selectedProtocol?.bids as BidsConfig | undefined
const bidsCheck = useBidsCheck(fileProblem ? null : file, bidsConfig, selectedProtocol?.name ?? '')
const bidsProblems = bidsCheck.result?.problems ?? []
const bidsBlocks = bidsCheck.checking || bidsProblems.some((p) => p.level === 'error')

const handleUpload = async () => {
if (fileProblem || !selectedProtocol) return
if (fileProblem || bidsBlocks || !selectedProtocol) return
// Picked up after a reload: the file is needed again unless it was already uploaded.
if (!file) {
if (checkpoint?.stored) return runLocked(selectedProtocol, null)
Expand All @@ -211,13 +225,16 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut

/** What every attempt is given: it carries on from `checkpoint` where that applies. */
const inputFor = (selectedProtocol: RunnableProtocol, file: File | null): RunProtocolInput => ({
protocol: selectedProtocol,
// protocols.json is typed by what it holds, so its rule types are plain strings here.
protocol: selectedProtocol as RunProtocolInput['protocol'],
file,
// `spawnedWorkspaceId` is set as soon as the run has a workspace, so a retry reuses it
// instead of creating another one.
workspaceId: spawnedWorkspaceId,
workspaceName: selectedProtocol.name,
dandisetId: dandisetId || undefined,
dandisetName: dandisetId ? undefined : dandisetName,
researcher,
shareWithMaabcd,
resume: checkpoint,
})
Expand Down Expand Up @@ -308,7 +325,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut

const stepIndex = step === 'select' ? 0 : 1
const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null && !findingWorkspace))
const canUpload = !!file && !fileProblem && emberSignedIn
const canUpload = !!file && !fileProblem && !bidsBlocks && emberSignedIn

return (
<Dialog
Expand Down Expand Up @@ -465,8 +482,25 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
)}
</>
)}
{emberSignedIn && protocolDandisets !== null && !dandisetId && (
<TextField
fullWidth
size="small"
label="Name of the new dandiset"
placeholder={selectedProtocol?.name}
value={dandisetName}
onChange={(e) => setForm((prev) => ({ ...prev, dandisetName: e.target.value }))}
slotProps={{ htmlInput: { style: { fontFamily: 'Inter, sans-serif', fontSize: '14px' } } }}
sx={{ mt: 1.5 }}
/>
)}
</Box>
)}
{usesEmber && selectedProtocol && 'maabcdAggregateDandisets' in selectedProtocol && !selectedProtocol.maabcdAggregateDandisetId && (
<Typography variant="body2" sx={{ opacity: 0.7 }}>
No MAABCD dandiset on {DANDI_INSTANCE.name} for this protocol, so nothing is shared with the consortium.
</Typography>
)}
{usesEmber && selectedProtocol?.maabcdAggregateDandisetId && (
<FormControlLabel
control={
Expand Down Expand Up @@ -511,7 +545,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
)}
{usesEmber && (
<Typography variant="body2" sx={{ opacity: 0.7 }}>
{dandisetId ? `Uploading into your dandiset ${dandisetId}` : 'Uploading into a new dandiset in your EMBER-DANDI account'}
{dandisetId ? `Uploading into your dandiset ${dandisetId}` : `Uploading into a new dandiset${dandisetName.trim() ? ` "${dandisetName.trim()}"` : ''} in your EMBER-DANDI account`}
{spawnedWorkspaceId !== undefined ? `, analyzed in workspace ${spawnedWorkspaceId}.` : ', analyzed in a new workspace.'}
</Typography>
)}
Expand Down Expand Up @@ -554,6 +588,30 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
{fileProblem}
</Typography>
)}
{bidsCheck.checking && (
<Typography variant="body2" sx={{ opacity: 0.6 }}>Checking the file…</Typography>
)}
{bidsCheck.result && (
<Stack sx={{ gap: 0.5, px: 4, textAlign: 'center' }} onClick={(e) => e.stopPropagation()}>
{!bidsProblems.some((p) => p.level === 'error') && (
<Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'center', gap: 0.5 }}>
<Typography variant="body2" sx={{ color: 'success.main' }}>
Ready for DANDI: {bidsCheck.result.subjects.length === 1 ? '1 animal' : `${bidsCheck.result.subjects.length} animals`} ({bidsCheck.result.subjects.map((s) => s.id).join(', ')}),{' '}
{bidsCheck.result.files.filter((f) => f.path.startsWith('sub-') && f.path.endsWith('.tsv')).length} tables
</Typography>
<BidsStructureButton files={bidsCheck.result.files} />
</Stack>
)}
{bidsProblems.slice(0, 8).map((p, i) => (
<Typography key={i} variant="body2" sx={{ color: p.level === 'error' ? 'error.main' : 'warning.main' }}>
{p.message}
</Typography>
))}
{bidsProblems.length > 8 && (
<Typography variant="body2" sx={{ opacity: 0.6 }}>…and {bidsProblems.length - 8} more</Typography>
)}
</Stack>
)}
</>
) : (
<>
Expand All @@ -571,6 +629,11 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
<Typography sx={{ fontFamily: 'Inter, sans-serif', fontWeight: 400, fontSize: '14px', lineHeight: 1, color: '#FFFFFFCC' }}>
Download an example input file for this protocol and fill in your data the same way.
</Typography>
{bidsConfig && (
<Typography sx={{ fontFamily: 'Inter, sans-serif', fontWeight: 400, fontSize: '14px', lineHeight: 1.4, color: '#FFFFFFCC' }}>
Upload one filled reporting sheet per animal, or a zip of them. Other files in the zip, such as the weight log or the protocol PDFs, are kept with your data.
</Typography>
)}
<Button
variant="outlined"
size="small"
Expand Down Expand Up @@ -608,7 +671,9 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut
{step === 'stillRunning' ? 'Results will be in' : 'Results are in'} <code>{outputsDir}/</code> in your workspace.
</Typography>
)}
{step !== 'uploading' && spawnedWorkspaceId !== undefined && (
{/* Only once this run has its workspace: one merely recorded in the dandiset may not be touched yet. */}
{step !== 'uploading' && spawnedWorkspaceId !== undefined
&& runSteps.some((s) => s.id === RUN_STEP.workspace && s.state === 'succeeded') && (
<Button variant="outlined" onClick={() => openWorkspaceTab(spawnedWorkspaceId)}>
Open workspace
</Button>
Expand Down
Loading
Loading