From 1967c1c15f7a22517b74d9aaae0875963e937130 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 00:08:34 +0100 Subject: [PATCH 01/54] Move the run's option classes into RunOptions.js The 24 Option and tree-file subclasses and the constants they read (binaries, analysis option lists, CPU count, RAxML settings aliases) move verbatim from Run.js to RunOptions.js, so the run and its options can be covered and converted in separate tickets. Run imports what it uses; RunOptions never imports Run. Typecheck baseline paths updated. Closes #119 Co-Authored-By: Claude Opus 5.5 --- scripts/typecheck-baseline.txt | 36 +- src/app/store/Run.js | 793 ++------------------------------- src/app/store/RunOptions.js | 767 +++++++++++++++++++++++++++++++ 3 files changed, 814 insertions(+), 782 deletions(-) create mode 100644 src/app/store/RunOptions.js diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index d3526632..e7989b1f 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -13,21 +13,21 @@ src/app/store/Alignment.js(54,5): error TS2554: Expected 5-6 arguments, but got src/app/store/Alignment.js(138,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/index.js(5,8): error TS2551: Property 'store' does not exist on type 'Window & typeof globalThis'. Did you mean 'Storage'? src/app/store/Option.js(12,14): error TS2304: Cannot find name 'yup'. -src/app/store/Run.js(278,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(291,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(306,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(313,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(323,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(333,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(353,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(397,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(409,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(422,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(459,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(519,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(554,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(585,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(630,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(662,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/Run.js(681,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Run.js(693,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(265,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(278,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(293,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(300,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(310,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(320,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(340,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(384,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(396,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(409,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(446,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(506,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(541,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(572,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(617,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(649,5): error TS2554: Expected 5-6 arguments, but got 4. +src/app/store/RunOptions.js(668,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/RunOptions.js(680,5): error TS2554: Expected 5-6 arguments, but got 4. diff --git a/src/app/store/Run.js b/src/app/store/Run.js index 40ff8f46..0bb7068e 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -1,780 +1,45 @@ import { observable, computed, action, createAtom } from 'mobx'; -import { range } from 'd3-array'; import { promisedComputed } from 'computed-async-mobx'; import filenamify from 'filenamify'; import Alignment, { FinalAlignment } from './Alignment'; import AstralTree from './AstralTree'; -import Option from './Option'; import StoreBase, { runEvents } from './StoreBase'; import { host } from './host'; -import { basename, dir, join, name, quote } from '../paths'; -import * as raxmlSettings from '../../settings/raxml'; +import { + binaries, + analysisOptions, + raxmlNgAnalysisOptions, + Binary, + NumThreads, + Analysis, + RaxmlNgAnalysis, + NumRuns, + NumRepetitions, + NumRepetitionsNg, + BranchLength, + SHlike, + CombinedOutput, + StartingTree, + OutGroup, + SubstitutionMatrix, + SubstitutionRate, + SubstitutionI, + SubstitutionAscertainment, + AAMatrixName, + EstimatedFrequencies, + BaseFrequencies, + MultistateModel, + Tree, + BackboneConstraintTree, + MultifurcatingConstraintTree, +} from './RunOptions'; +import { basename, join, quote } from '../paths'; import remove from 'lodash/remove'; import UserFixError from '../../common/errors'; -const raxmlMatrixOptions = raxmlSettings.matrixOptions; -const raxmlRateOptions = raxmlSettings.rateOptions; -const raxmlIOptions = raxmlSettings.iOptions; -const raxmlAscertainmentOptions = raxmlSettings.ascertainmentOptions; - const { windows } = host; -export const MAX_NUM_CPUS = navigator.hardwareConcurrency || 1; - -// On Windows 7 (= 6.1) use older versions of RAxML -const [majorVersion, minorVersion] = host.release.split( '.' ); -const winBinaries = - majorVersion === '6' && minorVersion === '1' - ? [ - // TODO: add raxml ng windows exe - // TODO: Crashes on Win7, disabled for now - // { name: 'modeltest-ng.exe', version: '0.1.7' }, - { - name: 'raxmlHPC_Win7.exe', - multithreaded: false, - version: '8.2.10', - type: 'raxml', - }, - { - name: 'raxmlHPC-SSE3_Win7.exe', - multithreaded: false, - version: '8.2.10', - type: 'raxml', - }, - // TODO: Crashes on Win7, disabled for now - // { - // name: 'raxmlHPC-PTHREADS-AVX_Win7.exe', - // multithreaded: true, - // version: '8.2.10', - // }, - { - name: 'raxmlHPC-PTHREADS-SSE3_Win7.exe', - multithreaded: true, - version: '8.2.10', - initial: true, - type: 'raxml', - }, - // TODO: put back in Astral - // { - // name: 'astral.5.7.8.jar', - // multithreaded: false, - // version: '5.7.8', - // type: 'astral', - // }, - ] - : [ - // TODO: add raxml ng windows exe - { name: 'modeltest-ng.exe', version: '0.1.7', type: 'modeltest' }, - { - name: 'raxmlHPC.exe', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-SSE3.exe', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-AVX.exe', - multithreaded: true, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-SSE3.exe', - multithreaded: true, - version: '8.2.12', - initial: true, - type: 'raxml', - }, - // TODO: put back in Astral - // { - // name: 'astral.5.7.8.jar', - // multithreaded: false, - // version: '5.7.8', - // type: 'astral', - // }, - ]; - -const likelyARM = - host.arch.includes( 'arm64' ) || host.cpuModel.includes( 'Apple' ); -const armBinaries = [ - { - name: 'modeltest-ng-ARM64', - multithreaded: true, - version: '0.1.7', - type: 'modeltest', - }, -]; -const x64Binaries = [ - { - name: 'modeltest-ng', - multithreaded: true, - version: '0.1.7', - type: 'modeltest', - }, -]; - -const allBinaries = host.windows - ? winBinaries - : [ - ...( !likelyARM - ? x64Binaries - : armBinaries ), - { - name: 'raxml-ng', - multithreaded: true, - version: '1.2.2', - initial: true, - type: 'raxml', - }, - { - name: 'raxmlHPC', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-SSE3', - multithreaded: false, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-AVX', - multithreaded: true, - version: '8.2.12', - type: 'raxml', - }, - { - name: 'raxmlHPC-PTHREADS-SSE3', - multithreaded: true, - version: '8.2.12', - type: 'raxml', - }, - // TODO: put back in Astral - // { - // name: 'astral.5.7.8.jar', - // multithreaded: false, - // version: '5.7.8', - // type: 'astral', - // }, - ]; - -const binaries = allBinaries.filter( ( { multithreaded } ) => - MAX_NUM_CPUS === 1 - ? !multithreaded - : true, -); - -const initialBinaryName = binaries.filter( ( { initial } ) => initial )[0].name; - -// Available parameters for different analysis -const params = { - brL: 'brL', - SHlike: 'SHlike', - combinedOutput: 'combinedOutput', - reps: 'reps', - repsNg: 'repsNg', - runs: 'runs', - tree: 'tree', - startingTree: 'startingTree', - outGroup: 'outGroup', -}; - -const analysisOptions = [ - { - title: 'Fast tree search', - value: 'FT', - params: [params.brL, params.SHlike, params.outGroup], - }, - { - title: 'ML search', - value: 'ML', - params: [ - params.runs, - params.SHlike, - params.combinedOutput, - params.outGroup, - ], - }, - { - title: 'ML + rapid bootstrap', - value: 'ML+rBS', - params: [params.reps, params.brL, params.outGroup], - }, // default - { - title: 'ML + thorough bootstrap', - value: 'ML+tBS', - params: [params.runs, params.reps, params.brL, params.outGroup], - }, - { - title: 'Bootstrap + consensus', - value: 'BS+con', - params: [params.reps, params.brL, params.outGroup], - }, - { - title: 'Ancestral states', - value: 'AS', - needTree: true, - params: [params.tree], - }, - { - title: 'Pairwise distances', - value: 'PD', - params: [params.startingTree], - }, - { - title: 'RELL bootstraps', - value: 'RBS', - params: [], - }, -]; - -const raxmlNgAnalysisOptions = [ - { - title: 'Sanity check', - value: 'SC', - params: [], - }, - { - title: 'Compression and conversion to binary format', - value: 'CC', - params: [], - }, - { - title: 'ML tree inference', - value: 'TI', - params: [params.runs, params.outGroup], - }, - { - title: 'ML + thorough bootstrap + consensus', - value: 'ML+tBS+con', - params: [params.runs, params.repsNg, params.outGroup], - }, - { - title: 'ML + transfer bootstrap expectation + consensus', - value: 'ML+TBE+con', - params: [params.runs, params.repsNg, params.outGroup], - }, - { - title: 'Ancestral state reconstruction', - value: 'AS', - needTree: true, - params: [params.tree], - }, -]; - -class Binary extends Option { - constructor( run ) { - super( run, initialBinaryName, 'Binary', 'Name of binary' ); - } - options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); - @computed get version() { - return binaries.filter( ( b ) => b.name === this.value )[0].version; - } - @computed get type() { - return binaries.filter( ( b ) => b.name === this.value )[0].type; - } -} - -class NumThreads extends Option { - constructor( run ) { - super( run, 2, 'Threads', 'Number of cpu threads' ); - } - options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { - value, - title: value, - } ) ); - @computed get notAvailable() { - return !( - /PTHREADS/.test( this.run.binary.value ) || this.run.usesModeltestNg - ); - } -} - -class Analysis extends Option { - constructor( run ) { - super( run, 'ML+rBS', 'Analysis', 'Type of analysis' ); - } - options = analysisOptions.map( ( { value, title } ) => ( { value, title } ) ); -} - -class RaxmlNgAnalysis extends Option { - constructor( run ) { - super( run, 'ML+TBE+con', 'Analysis', 'Type of analysis' ); - } - options = raxmlNgAnalysisOptions.map( ( { value, title } ) => ( { - value, - title, - } ) ); -} - -class NumRuns extends Option { - constructor( run ) { - super( run, 1, 'Runs', 'Number of runs' ); - } - options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.runs ); - } -} - -class NumRepetitions extends Option { - constructor( run ) { - super( run, 100, 'Reps.', 'Number of repetitions' ); - } - options = [ - 100, - 200, - 500, - 1000, - 10000, - 'autoMR', - 'autoMRE', - 'autoMRE_IGN', - 'autoFC', - ].map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.reps ); - } -} - -class NumRepetitionsNg extends Option { - constructor( run ) { - super( run, 100, 'Reps.', 'Number of repetitions' ); - } - options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { - value, - title: value, - } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.repsNg ); - } -} - -//TODO: Another branch lengths option for FT? ('compute brL' vs 'BS brL' for the rest) -class BranchLength extends Option { - constructor( run ) { - super( - run, - false, - 'BS brL', - 'Compute branch lengths', - 'Optimize model parameters and branch lengths for the given input tree', - ); - } - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.brL ); - } -} - -class SHlike extends Option { - constructor( run ) { - super( - run, - false, - 'SH-like', - 'Compute log-likelihood test', - 'Shimodaira-Hasegawa-like procedure', - ); - } - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.SHlike ); - } -} - -class CombinedOutput extends Option { - constructor( run ) { - super( run, false, 'Combined output', 'Concatenate output trees' ); - } - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.combinedOutput ); - } - @computed get isUsed() { - return this.value && !this.notAvailable; - } -} - -class StartingTree extends Option { - constructor( run ) { - super( run, 'Maximum parsimony', 'Starting tree', '' ); - } - options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { - value, - title: value, - } ) ); - @computed get notAvailable() { - return !this.run.analysisOption.params.includes( params.startingTree ); - } -} - -class OutGroup extends Option { - constructor( run ) { - super( run, [''], 'Outgroup', '' ); - this.multiple = true; - } - @computed get options() { - return ['', ...this.run.taxons].map( ( value ) => ( { - value, - title: value, - } ) ); - } - - @action setValue = ( value ) => { - if ( this.value.includes( '' ) ) { - this.value = value.filter( ( v ) => v !== '' ); - return; - } - if ( !this.value.includes( '' ) && value.includes( '' ) ) { - this.value = value.filter( ( v ) => v === '' ); - return; - } - this.value = value; - }; - - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - !this.run.analysisOption.params.includes( params.outGroup ) - ); - } - @computed get cmdValue() { - return this.value.includes( '' ) - ? '' - : this.value.join( ',' ); - } -} - -class SubstitutionMatrix extends Option { - constructor( run ) { - super( run, 'GTR', 'Substitution matrix' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlMatrixOptions[this.run.dataType]; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { - value, - title: value === 'GTR' - ? value - : `${value} + GAMMA`, - } ) ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - this.run.dataType === 'binary' || - this.run.dataType === 'protein' || - this.run.dataType === 'multistate' || - this.run.usesRaxmlNg - ); - } - @computed get cmdValue() { - if ( this.run.dataType === 'binary' ) { - return 'BIN'; - } - if ( this.run.dataType === 'protein' ) { - return 'PROT'; - } - if ( this.run.dataType === 'multistate' ) { - return 'MULTI'; - } - if ( this.value === 'JC' || this.value === 'K80' || this.value === 'HKY' ) { - return 'GTR'; - } - return this.value; - } - @computed get extraCmdValue() { - switch ( this.value ) { - case 'JC': - return '--JC69'; - case 'K80': - return '--K80'; - case 'HKY': - return '--HKY85'; - default: - return ''; - } - } - @computed get notGTR() { - return this.value !== 'GTR'; - } -} - -class SubstitutionRate extends Option { - constructor( run ) { - super( run, 'GAMMA', 'Substitution rates' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlRateOptions; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - ( ( this.run.dataType === 'dna' || - this.run.dataType === 'rna' || - this.run.dataType === 'nucleotide' ) && - this.run.substitutionMatrix.notGTR ) || - this.run.usesRaxmlNg - ); - } - @computed get cmdValue() { - if ( this.run.substitutionMatrix.notGTR ) { - return 'GAMMA'; - } - return this.value; - } - @computed get isCAT() { - return this.value === 'CAT'; - } -} - -class SubstitutionI extends Option { - constructor( run ) { - super( run, 'none', 'Proportion of invariant sites' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlIOptions; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return ( - this.run.substitutionAscertainment.isSet || - !this.run.haveAlignments || - this.run.usesRaxmlNg - ); - } - @computed get cmdValue() { - return this.value === 'none' - ? '' - : 'I'; - } - @computed get isSet() { - return this.value !== 'none'; - } -} - -class SubstitutionAscertainment extends Option { - constructor( run ) { - super( run, 'none', 'Ascertainment bias correction' ); - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlAscertainmentOptions; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - this.run.usesRaxmlNg || - this.run.dataType === 'mixed' || - this.run.finalAlignment.hasInvariantSites || - this.run.substitutionI.isSet - ); - } - @computed get cmdValue() { - return this.value === 'none' - ? '' - : 'ASC_'; - } - @computed get extraCmdValue() { - switch ( this.value ) { - case "Lewis' method": - return '--asc-corr=lewis'; - case "Felsenstein's method": - return '--asc-corr=felsenstein'; - case "Stamatakis' method": - return '--asc-corr=stamatakis'; - default: - return ''; - } - } - @computed get isSet() { - return this.value !== 'none'; - } -} - -class AAMatrixName extends Option { - constructor( run ) { - super( - run, - 'BLOSUM62', - 'Matrix name', - 'Amino Acid Substitution Matrix name', - ); - } - options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( - ( value ) => ( { value, title: value } ), - ); - @computed get notAvailable() { - return this.run.dataType !== 'protein'; - } -} - -class EstimatedFrequencies extends Option { - constructor( run ) { - super( - run, - false, - 'ML Freq.', - 'Estimated base frequencies', - 'Use estimated base frequencies instead of empirical.', - ); - } - @computed get notAvailable() { - return this.run.dataType === 'protein' || this.run.usesRaxmlNg; - } -} - -class BaseFrequencies extends Option { - constructor( run ) { - super( - run, - 'default', - 'Base frequencies', - 'Empirical, ML estimated or model based base frequencies', - ); - } - options = [ - { title: 'From model', value: 'default' }, - { title: 'Empirical', value: 'F' }, - { title: 'Estimated (ML)', value: 'X' }, - ]; - @computed get notAvailable() { - return this.run.dataType !== 'protein' || this.run.usesRaxmlNg; - } -} - -class MultistateModel extends Option { - constructor( run ) { - super( run, 'GTR', 'Multistate model' ); - } - options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( - ( value ) => ( { value, title: value } ), - ); - @computed get notAvailable() { - return this.run.dataType !== 'multistate' || this.run.usesRaxmlNg; - } -} - -class TreeFile extends Option { - constructor( run ) { - super( run, '', 'Tree', '' ); - } - @observable filePath = ''; - @computed get haveFile() { - return !!this.filePath; - } - @computed get filename() { - return basename( this.filePath ); - } - @computed get name() { - return name( this.filePath ); - } - @computed get dir() { - return dir( this.filePath ); - } - @action setFilePath = ( filePath ) => { - this.filePath = filePath; - }; - @action openFolder = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.filePath ); - }; - @action openFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.filePath ); - }; - @action remove = () => { - this.setFilePath( '' ); - }; -} - -class Tree extends TreeFile { - @computed get notAvailable() { - return !( - this.run.analysisOption.params.includes( params.tree ) || - ( !this.run.startingTree.notAvailable && - this.run.startingTree.value === 'User defined' ) - ); - } -} - -class BackboneConstraintTree extends TreeFile { - @computed get isSet() { - return this.run.useBackboneConstraint && this.haveFile; - } - @computed get canConstraint() { - const analysisWithConstraint = [ - 'ML', - 'ML+rBS', - 'ML+tBS', - 'BS+con', - 'RBS', - 'SC', - 'CC', - 'TI', - 'ML+tBS+con', - 'ML+TBE+con', - ]; - return analysisWithConstraint.includes( this.run.analysis.value ); - } - @computed get notAvailable() { - return !this.run.useBackboneConstraint || !this.canConstraint; - } -} - -class MultifurcatingConstraintTree extends TreeFile { - @computed get isSet() { - return this.run.useMultifurcatingConstraint && this.haveFile; - } - @computed get canConstraint() { - const analysisWithConstraint = [ - 'ML', - 'ML+rBS', - 'ML+tBS', - 'BS+con', - 'RBS', - 'SC', - 'CC', - 'TI', - 'ML+tBS+con', - 'ML+TBE+con', - ]; - return analysisWithConstraint.includes( this.run.analysis.value ); - } - @computed get notAvailable() { - return !this.run.useMultifurcatingConstraint || !this.canConstraint; - } -} - class Run extends StoreBase { constructor( parent, id ) { super(); diff --git a/src/app/store/RunOptions.js b/src/app/store/RunOptions.js new file mode 100644 index 00000000..5513f0d6 --- /dev/null +++ b/src/app/store/RunOptions.js @@ -0,0 +1,767 @@ +import { observable, computed, action } from 'mobx'; +import { range } from 'd3-array'; + +import Option from './Option'; +import { host } from './host'; +import { basename, dir, name } from '../paths'; +import * as raxmlSettings from '../../settings/raxml'; + +const raxmlMatrixOptions = raxmlSettings.matrixOptions; +const raxmlRateOptions = raxmlSettings.rateOptions; +const raxmlIOptions = raxmlSettings.iOptions; +const raxmlAscertainmentOptions = raxmlSettings.ascertainmentOptions; + +export const MAX_NUM_CPUS = navigator.hardwareConcurrency || 1; + +// On Windows 7 (= 6.1) use older versions of RAxML +const [majorVersion, minorVersion] = host.release.split( '.' ); +const winBinaries = + majorVersion === '6' && minorVersion === '1' + ? [ + // TODO: add raxml ng windows exe + // TODO: Crashes on Win7, disabled for now + // { name: 'modeltest-ng.exe', version: '0.1.7' }, + { + name: 'raxmlHPC_Win7.exe', + multithreaded: false, + version: '8.2.10', + type: 'raxml', + }, + { + name: 'raxmlHPC-SSE3_Win7.exe', + multithreaded: false, + version: '8.2.10', + type: 'raxml', + }, + // TODO: Crashes on Win7, disabled for now + // { + // name: 'raxmlHPC-PTHREADS-AVX_Win7.exe', + // multithreaded: true, + // version: '8.2.10', + // }, + { + name: 'raxmlHPC-PTHREADS-SSE3_Win7.exe', + multithreaded: true, + version: '8.2.10', + initial: true, + type: 'raxml', + }, + // TODO: put back in Astral + // { + // name: 'astral.5.7.8.jar', + // multithreaded: false, + // version: '5.7.8', + // type: 'astral', + // }, + ] + : [ + // TODO: add raxml ng windows exe + { name: 'modeltest-ng.exe', version: '0.1.7', type: 'modeltest' }, + { + name: 'raxmlHPC.exe', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-SSE3.exe', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-AVX.exe', + multithreaded: true, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-SSE3.exe', + multithreaded: true, + version: '8.2.12', + initial: true, + type: 'raxml', + }, + // TODO: put back in Astral + // { + // name: 'astral.5.7.8.jar', + // multithreaded: false, + // version: '5.7.8', + // type: 'astral', + // }, + ]; + +const likelyARM = + host.arch.includes( 'arm64' ) || host.cpuModel.includes( 'Apple' ); +const armBinaries = [ + { + name: 'modeltest-ng-ARM64', + multithreaded: true, + version: '0.1.7', + type: 'modeltest', + }, +]; +const x64Binaries = [ + { + name: 'modeltest-ng', + multithreaded: true, + version: '0.1.7', + type: 'modeltest', + }, +]; + +const allBinaries = host.windows + ? winBinaries + : [ + ...( !likelyARM + ? x64Binaries + : armBinaries ), + { + name: 'raxml-ng', + multithreaded: true, + version: '1.2.2', + initial: true, + type: 'raxml', + }, + { + name: 'raxmlHPC', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-SSE3', + multithreaded: false, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-AVX', + multithreaded: true, + version: '8.2.12', + type: 'raxml', + }, + { + name: 'raxmlHPC-PTHREADS-SSE3', + multithreaded: true, + version: '8.2.12', + type: 'raxml', + }, + // TODO: put back in Astral + // { + // name: 'astral.5.7.8.jar', + // multithreaded: false, + // version: '5.7.8', + // type: 'astral', + // }, + ]; + +export const binaries = allBinaries.filter( ( { multithreaded } ) => + MAX_NUM_CPUS === 1 + ? !multithreaded + : true, +); + +const initialBinaryName = binaries.filter( ( { initial } ) => initial )[0].name; + +// Available parameters for different analysis +const params = { + brL: 'brL', + SHlike: 'SHlike', + combinedOutput: 'combinedOutput', + reps: 'reps', + repsNg: 'repsNg', + runs: 'runs', + tree: 'tree', + startingTree: 'startingTree', + outGroup: 'outGroup', +}; + +export const analysisOptions = [ + { + title: 'Fast tree search', + value: 'FT', + params: [params.brL, params.SHlike, params.outGroup], + }, + { + title: 'ML search', + value: 'ML', + params: [ + params.runs, + params.SHlike, + params.combinedOutput, + params.outGroup, + ], + }, + { + title: 'ML + rapid bootstrap', + value: 'ML+rBS', + params: [params.reps, params.brL, params.outGroup], + }, // default + { + title: 'ML + thorough bootstrap', + value: 'ML+tBS', + params: [params.runs, params.reps, params.brL, params.outGroup], + }, + { + title: 'Bootstrap + consensus', + value: 'BS+con', + params: [params.reps, params.brL, params.outGroup], + }, + { + title: 'Ancestral states', + value: 'AS', + needTree: true, + params: [params.tree], + }, + { + title: 'Pairwise distances', + value: 'PD', + params: [params.startingTree], + }, + { + title: 'RELL bootstraps', + value: 'RBS', + params: [], + }, +]; + +export const raxmlNgAnalysisOptions = [ + { + title: 'Sanity check', + value: 'SC', + params: [], + }, + { + title: 'Compression and conversion to binary format', + value: 'CC', + params: [], + }, + { + title: 'ML tree inference', + value: 'TI', + params: [params.runs, params.outGroup], + }, + { + title: 'ML + thorough bootstrap + consensus', + value: 'ML+tBS+con', + params: [params.runs, params.repsNg, params.outGroup], + }, + { + title: 'ML + transfer bootstrap expectation + consensus', + value: 'ML+TBE+con', + params: [params.runs, params.repsNg, params.outGroup], + }, + { + title: 'Ancestral state reconstruction', + value: 'AS', + needTree: true, + params: [params.tree], + }, +]; + +export class Binary extends Option { + constructor( run ) { + super( run, initialBinaryName, 'Binary', 'Name of binary' ); + } + options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); + @computed get version() { + return binaries.filter( ( b ) => b.name === this.value )[0].version; + } + @computed get type() { + return binaries.filter( ( b ) => b.name === this.value )[0].type; + } +} + +export class NumThreads extends Option { + constructor( run ) { + super( run, 2, 'Threads', 'Number of cpu threads' ); + } + options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { + value, + title: value, + } ) ); + @computed get notAvailable() { + return !( + /PTHREADS/.test( this.run.binary.value ) || this.run.usesModeltestNg + ); + } +} + +export class Analysis extends Option { + constructor( run ) { + super( run, 'ML+rBS', 'Analysis', 'Type of analysis' ); + } + options = analysisOptions.map( ( { value, title } ) => ( { value, title } ) ); +} + +export class RaxmlNgAnalysis extends Option { + constructor( run ) { + super( run, 'ML+TBE+con', 'Analysis', 'Type of analysis' ); + } + options = raxmlNgAnalysisOptions.map( ( { value, title } ) => ( { + value, + title, + } ) ); +} + +export class NumRuns extends Option { + constructor( run ) { + super( run, 1, 'Runs', 'Number of runs' ); + } + options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.runs ); + } +} + +export class NumRepetitions extends Option { + constructor( run ) { + super( run, 100, 'Reps.', 'Number of repetitions' ); + } + options = [ + 100, + 200, + 500, + 1000, + 10000, + 'autoMR', + 'autoMRE', + 'autoMRE_IGN', + 'autoFC', + ].map( ( value ) => ( { value, title: value } ) ); + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.reps ); + } +} + +export class NumRepetitionsNg extends Option { + constructor( run ) { + super( run, 100, 'Reps.', 'Number of repetitions' ); + } + options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { + value, + title: value, + } ) ); + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.repsNg ); + } +} + +//TODO: Another branch lengths option for FT? ('compute brL' vs 'BS brL' for the rest) +export class BranchLength extends Option { + constructor( run ) { + super( + run, + false, + 'BS brL', + 'Compute branch lengths', + 'Optimize model parameters and branch lengths for the given input tree', + ); + } + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.brL ); + } +} + +export class SHlike extends Option { + constructor( run ) { + super( + run, + false, + 'SH-like', + 'Compute log-likelihood test', + 'Shimodaira-Hasegawa-like procedure', + ); + } + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.SHlike ); + } +} + +export class CombinedOutput extends Option { + constructor( run ) { + super( run, false, 'Combined output', 'Concatenate output trees' ); + } + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.combinedOutput ); + } + @computed get isUsed() { + return this.value && !this.notAvailable; + } +} + +export class StartingTree extends Option { + constructor( run ) { + super( run, 'Maximum parsimony', 'Starting tree', '' ); + } + options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { + value, + title: value, + } ) ); + @computed get notAvailable() { + return !this.run.analysisOption.params.includes( params.startingTree ); + } +} + +export class OutGroup extends Option { + constructor( run ) { + super( run, [''], 'Outgroup', '' ); + this.multiple = true; + } + @computed get options() { + return ['', ...this.run.taxons].map( ( value ) => ( { + value, + title: value, + } ) ); + } + + @action setValue = ( value ) => { + if ( this.value.includes( '' ) ) { + this.value = value.filter( ( v ) => v !== '' ); + return; + } + if ( !this.value.includes( '' ) && value.includes( '' ) ) { + this.value = value.filter( ( v ) => v === '' ); + return; + } + this.value = value; + }; + + @computed get notAvailable() { + return ( + !this.run.haveAlignments || + !this.run.analysisOption.params.includes( params.outGroup ) + ); + } + @computed get cmdValue() { + return this.value.includes( '' ) + ? '' + : this.value.join( ',' ); + } +} + +export class SubstitutionMatrix extends Option { + constructor( run ) { + super( run, 'GTR', 'Substitution matrix' ); + } + @computed get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlMatrixOptions[this.run.dataType]; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { + value, + title: value === 'GTR' + ? value + : `${value} + GAMMA`, + } ) ); + } + @computed get notAvailable() { + return ( + !this.run.haveAlignments || + this.run.dataType === 'binary' || + this.run.dataType === 'protein' || + this.run.dataType === 'multistate' || + this.run.usesRaxmlNg + ); + } + @computed get cmdValue() { + if ( this.run.dataType === 'binary' ) { + return 'BIN'; + } + if ( this.run.dataType === 'protein' ) { + return 'PROT'; + } + if ( this.run.dataType === 'multistate' ) { + return 'MULTI'; + } + if ( this.value === 'JC' || this.value === 'K80' || this.value === 'HKY' ) { + return 'GTR'; + } + return this.value; + } + @computed get extraCmdValue() { + switch ( this.value ) { + case 'JC': + return '--JC69'; + case 'K80': + return '--K80'; + case 'HKY': + return '--HKY85'; + default: + return ''; + } + } + @computed get notGTR() { + return this.value !== 'GTR'; + } +} + +export class SubstitutionRate extends Option { + constructor( run ) { + super( run, 'GAMMA', 'Substitution rates' ); + } + @computed get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlRateOptions; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + @computed get notAvailable() { + return ( + !this.run.haveAlignments || + ( ( this.run.dataType === 'dna' || + this.run.dataType === 'rna' || + this.run.dataType === 'nucleotide' ) && + this.run.substitutionMatrix.notGTR ) || + this.run.usesRaxmlNg + ); + } + @computed get cmdValue() { + if ( this.run.substitutionMatrix.notGTR ) { + return 'GAMMA'; + } + return this.value; + } + @computed get isCAT() { + return this.value === 'CAT'; + } +} + +export class SubstitutionI extends Option { + constructor( run ) { + super( run, 'none', 'Proportion of invariant sites' ); + } + @computed get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlIOptions; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + @computed get notAvailable() { + return ( + this.run.substitutionAscertainment.isSet || + !this.run.haveAlignments || + this.run.usesRaxmlNg + ); + } + @computed get cmdValue() { + return this.value === 'none' + ? '' + : 'I'; + } + @computed get isSet() { + return this.value !== 'none'; + } +} + +export class SubstitutionAscertainment extends Option { + constructor( run ) { + super( run, 'none', 'Ascertainment bias correction' ); + } + @computed get options() { + if ( !this.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlAscertainmentOptions; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + @computed get notAvailable() { + return ( + !this.run.haveAlignments || + this.run.usesRaxmlNg || + this.run.dataType === 'mixed' || + this.run.finalAlignment.hasInvariantSites || + this.run.substitutionI.isSet + ); + } + @computed get cmdValue() { + return this.value === 'none' + ? '' + : 'ASC_'; + } + @computed get extraCmdValue() { + switch ( this.value ) { + case "Lewis' method": + return '--asc-corr=lewis'; + case "Felsenstein's method": + return '--asc-corr=felsenstein'; + case "Stamatakis' method": + return '--asc-corr=stamatakis'; + default: + return ''; + } + } + @computed get isSet() { + return this.value !== 'none'; + } +} + +export class AAMatrixName extends Option { + constructor( run ) { + super( + run, + 'BLOSUM62', + 'Matrix name', + 'Amino Acid Substitution Matrix name', + ); + } + options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( + ( value ) => ( { value, title: value } ), + ); + @computed get notAvailable() { + return this.run.dataType !== 'protein'; + } +} + +export class EstimatedFrequencies extends Option { + constructor( run ) { + super( + run, + false, + 'ML Freq.', + 'Estimated base frequencies', + 'Use estimated base frequencies instead of empirical.', + ); + } + @computed get notAvailable() { + return this.run.dataType === 'protein' || this.run.usesRaxmlNg; + } +} + +export class BaseFrequencies extends Option { + constructor( run ) { + super( + run, + 'default', + 'Base frequencies', + 'Empirical, ML estimated or model based base frequencies', + ); + } + options = [ + { title: 'From model', value: 'default' }, + { title: 'Empirical', value: 'F' }, + { title: 'Estimated (ML)', value: 'X' }, + ]; + @computed get notAvailable() { + return this.run.dataType !== 'protein' || this.run.usesRaxmlNg; + } +} + +export class MultistateModel extends Option { + constructor( run ) { + super( run, 'GTR', 'Multistate model' ); + } + options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( + ( value ) => ( { value, title: value } ), + ); + @computed get notAvailable() { + return this.run.dataType !== 'multistate' || this.run.usesRaxmlNg; + } +} + +class TreeFile extends Option { + constructor( run ) { + super( run, '', 'Tree', '' ); + } + @observable filePath = ''; + @computed get haveFile() { + return !!this.filePath; + } + @computed get filename() { + return basename( this.filePath ); + } + @computed get name() { + return name( this.filePath ); + } + @computed get dir() { + return dir( this.filePath ); + } + @action setFilePath = ( filePath ) => { + this.filePath = filePath; + }; + @action openFolder = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.filePath ); + }; + @action openFile = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.filePath ); + }; + @action remove = () => { + this.setFilePath( '' ); + }; +} + +export class Tree extends TreeFile { + @computed get notAvailable() { + return !( + this.run.analysisOption.params.includes( params.tree ) || + ( !this.run.startingTree.notAvailable && + this.run.startingTree.value === 'User defined' ) + ); + } +} + +export class BackboneConstraintTree extends TreeFile { + @computed get isSet() { + return this.run.useBackboneConstraint && this.haveFile; + } + @computed get canConstraint() { + const analysisWithConstraint = [ + 'ML', + 'ML+rBS', + 'ML+tBS', + 'BS+con', + 'RBS', + 'SC', + 'CC', + 'TI', + 'ML+tBS+con', + 'ML+TBE+con', + ]; + return analysisWithConstraint.includes( this.run.analysis.value ); + } + @computed get notAvailable() { + return !this.run.useBackboneConstraint || !this.canConstraint; + } +} + +export class MultifurcatingConstraintTree extends TreeFile { + @computed get isSet() { + return this.run.useMultifurcatingConstraint && this.haveFile; + } + @computed get canConstraint() { + const analysisWithConstraint = [ + 'ML', + 'ML+rBS', + 'ML+tBS', + 'BS+con', + 'RBS', + 'SC', + 'CC', + 'TI', + 'ML+tBS+con', + 'ML+TBE+con', + ]; + return analysisWithConstraint.includes( this.run.analysis.value ); + } + @computed get notAvailable() { + return !this.run.useMultifurcatingConstraint || !this.canConstraint; + } +} From 351911383fe85690cced61b26ad3bac7c4a1a5dd Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 00:19:28 +0100 Subject: [PATCH 02/54] Lint import cycles; add a rename mode to the typecheck baseline import/no-cycle turns the spec's no-circular-import criterion into a lint error (src has none today). typecheck-baseline.js --rename repoints baseline entries after a pure file move, refusing any entry with no same-message diagnostic at the new path. Co-Authored-By: Claude Opus 5.5 --- .eslintrc.cjs | 1 + scripts/typecheck-baseline.js | 44 ++++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 463b650a..0e377d56 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -5,6 +5,7 @@ module.exports = { plugins: ['lodash'], rules: { 'lodash/import-scope': 2, + 'import/no-cycle': 'error', 'comma-dangle': ['error', 'always-multiline'], 'prefer-destructuring': [ 'error', diff --git a/scripts/typecheck-baseline.js b/scripts/typecheck-baseline.js index 32452189..aa8ef106 100644 --- a/scripts/typecheck-baseline.js +++ b/scripts/typecheck-baseline.js @@ -43,6 +43,29 @@ function unusedLines(known, actual) { return known.filter( (line, i) => !seen.has(knownOwned[i]) ); } +/** + * Repoint baseline entries from one file path to another after a pure move. + * An entry is rewritten only when tsc reports the same code and message at the + * new path, so the rename can never shelter a new diagnostic. + */ +function renameLines(known, actual, from, to) { + const unclaimed = actual.filter( (line) => line.startsWith(`${to}(`) ); + const missing = []; + const renamed = known.map((line) => { + if (!line.startsWith(`${from}(`)) { + return line; + } + const want = fingerprint(`${to}${line.slice(from.length)}`); + const i = unclaimed.findIndex( (candidate) => fingerprint(candidate) === want ); + if (i === -1) { + missing.push(line); + return line; + } + return unclaimed.splice(i, 1)[0]; + }); + return { renamed, missing }; +} + function main() { if (!fs.existsSync(baselinePath)) { console.error('typecheck baseline is missing: ' + baselinePath); @@ -63,6 +86,25 @@ function main() { process.exit(result.status || 1); } const actual = diagnosticLines(`${result.stdout || ''}\n${result.stderr || ''}`); + const renameAt = process.argv.indexOf('--rename'); + if (renameAt !== -1) { + const [from, to] = process.argv.slice(renameAt + 1, renameAt + 3); + if (!from || !to) { + console.error('usage: typecheck-baseline.js --rename '); + process.exit(1); + } + if (!baseline.some( (line) => line.startsWith(`${from}(`) )) { + console.error('no baseline entries at ' + from); + process.exit(1); + } + const { renamed, missing } = renameLines(baseline, actual, from, to); + if (missing.length) { + console.error('no matching diagnostic at ' + to + ' for:\n' + missing.join('\n')); + process.exit(1); + } + fs.writeFileSync(baselinePath, renamed.join('\n') + '\n'); + return; + } const fresh = freshLines(actual, baseline); const unused = unusedLines(baseline, actual); if (fresh.length || unused.length) { @@ -80,4 +122,4 @@ if (require.main === module) { main(); } -module.exports = { diagnosticLines, freshLines, unusedLines, ownedFingerprints }; +module.exports = { diagnosticLines, freshLines, unusedLines, ownedFingerprints, renameLines }; From 577d5059c57b9b014c0b610a3ead14ec708a1be2 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 00:34:49 +0100 Subject: [PATCH 03/54] Split Alignment.js into one module per class family FinalAlignment moves verbatim to FinalAlignment.js, and the raxml-ng model options and MultistateNumber move verbatim to AlignmentOptions.js, so each family can be covered and converted in its own ticket. Alignment.js keeps only Alignment and imports its option classes; neither new module imports Alignment. Run imports FinalAlignment from its new module. Typecheck baseline entries repointed with --rename. Closes #120 Co-Authored-By: Claude Opus 5.5 --- scripts/typecheck-baseline.txt | 6 +- src/app/store/Alignment.js | 342 +----------------------------- src/app/store/AlignmentOptions.js | 143 +++++++++++++ src/app/store/FinalAlignment.js | 207 ++++++++++++++++++ src/app/store/Run.js | 3 +- 5 files changed, 365 insertions(+), 336 deletions(-) create mode 100644 src/app/store/AlignmentOptions.js create mode 100644 src/app/store/FinalAlignment.js diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index e7989b1f..ce174476 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -8,9 +8,9 @@ src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is mi src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. -src/app/store/Alignment.js(27,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Alignment.js(54,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/Alignment.js(138,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. +src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/index.js(5,8): error TS2551: Property 'store' does not exist on type 'Window & typeof globalThis'. Did you mean 'Storage'? src/app/store/Option.js(12,14): error TS2304: Cannot find name 'yup'. src/app/store/RunOptions.js(265,5): error TS2554: Expected 5-6 arguments, but got 4. diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.js index f8a65724..41626470 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.js @@ -1,149 +1,25 @@ import { observable, computed, action, runInAction } from 'mobx'; -import union from 'lodash/union'; -import intersection from 'lodash/intersection'; -import Option from './Option'; import * as raxmlSettings from '../../settings/raxml'; import * as raxmlNgSettings from '../../settings/raxmlng'; -import Partition, { FinalPartition } from './Partition'; +import Partition from './Partition'; import InputFile from './InputFile'; +import { + RaxmlNgAlignmentSubstitutionModel, + RaxmlNgModelF, + RaxmlNgModelI, + RaxmlNgModelG, + RaxmlNgModelASC, + MultistateNumber, +} from './AlignmentOptions'; import { runEvents } from './StoreBase'; import { getFinalDataType } from '../../common/typecheckAlignment'; import UserFixError from '../../common/errors'; import { host } from './host'; -import { join } from '../paths'; const raxmlMatrixOptions = raxmlSettings.matrixOptions; const raxmlNgModelOptions = raxmlNgSettings.modelOptions; -class RaxmlNgAlignmentSubstitutionModel extends Option { - constructor( alignment ) { - super( alignment.run, '', 'Substitution model' ); - this.alignment = alignment; - } - @computed get options() { - if ( !this.alignment.run.haveAlignments ) { - return []; - } - const modelSettings = raxmlNgModelOptions[this.alignment.dataType]; - if ( !modelSettings ) { - return []; - } - return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return !this.alignment.run.haveAlignments; - } - @computed get cmdValue() { - let model = this.value; - if ( this.alignment.dataType === 'multistate' ) { - model = model.replace( 'x', this.alignment.multistateNumber.value ); - } - return model; - } -} - -class RaxmlNgModelExtraParam extends Option { - constructor( alignment, label, options, { addNone = true } = {} ) { - super( alignment.run, addNone - ? '' - : options[0].value, label ); - this.alignment = alignment; - this.optionsSource = addNone - ? [{ value: '', title: 'none' }, ...options] - : options; - this.addNone = addNone; - } - @computed get options() { - if ( !this.run.haveAlignments ) { - return []; - } - return this.optionsSource; - } - @computed get notAvailable() { - return !this.run.haveAlignments || !this.run.usesRaxmlNg; - } - @computed get cmdValue() { - return this.value === '' - ? '' - : this.value; - } -} - -class RaxmlNgModelF extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Stationary frequencies', - raxmlNgSettings.stationaryFrequenciesOptions.options.map( - ( { value, label: title } ) => ( { value, title } ), - ), - ); - } -} - -class RaxmlNgModelI extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Proportion of invariant sites', - raxmlNgSettings.proportionOfInvariantSitesOptions.options.map( - ( { value, label: title } ) => ( { value, title } ), - ), - ); - } -} - -class RaxmlNgModelG extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Rate heterogeneity', - raxmlNgSettings.amongsiteRateHeterogeneityModelOptions.options.map( - ( { value, label: title } ) => ( { value, title } ), - ), - ); - } -} - -class RaxmlNgModelASC extends RaxmlNgModelExtraParam { - constructor( alignment ) { - super( - alignment, - 'Ascertainment bias', - [ - { value: '', label: 'No correction' }, - ...raxmlNgSettings.ascertainmentBiasCorrectionOptions.options, - ].map( ( { value, label: title } ) => ( { value, title } ) ), - { addNone: false }, - ); - } - @computed get notAvailable() { - return ( - !this.run.haveAlignments || - !this.run.usesRaxmlNg || - this.alignment.hasInvariantSites - ); - } -} - -class MultistateNumber extends Option { - constructor( alignment ) { - super( alignment.run, '', 'Number of states' ); - this.alignment = alignment; - this.placeholder = 'Integer'; - } - @computed get notAvailable() { - return ( - this.alignment.dataType !== 'multistate' || - !this.alignment.run.usesRaxmlNg - ); - } - @computed get error() { - return !this.value || !Number.isInteger( Number( this.value ) ); - } -} - class Alignment extends InputFile { constructor( run, path ) { super( run, path ); @@ -553,202 +429,4 @@ class Alignment extends InputFile { }; } -class FinalAlignment { - constructor( run ) { - this.run = run; - this.partition = new FinalPartition( run ); - } - - @computed get filename() { - if ( this.numAlignments === 1 ) { - return this.run.alignments[0].filename; - } - return `RAxML_${this.run.outputNameSafe}_concat.txt`; - } - - @computed get dir() { - if ( this.numAlignments === 1 ) { - return this.run.alignments[0].dir; - } - return this.run.outputDir; - } - - @computed get path() { - if ( this.numAlignments === 1 ) { - return this.run.alignments[0].path; - } - return join( `${this.dir}`, `${this.filename}` ); - } - - @observable parsingComplete = true; - - @computed get numAlignments() { - return this.run.alignments.length; - } - - // By default add empty sequences to fill gaps up to the union of taxons - // else drop taxons that doesn't exist in all alignments by taking the intersection - @observable fillTaxonGapsWithEmptySeqeunces = true; - - @action setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { - this.fillTaxonGapsWithEmptySeqeunces = checked; - }; - - @computed get taxons() { - const setMethod = this.fillTaxonGapsWithEmptySeqeunces - ? union - : intersection; - return setMethod.apply( - setMethod, - this.run.alignments.map( ( { taxons } ) => taxons ), - ); - } - - @computed get numSequences() { - return this.taxons.length; - } - - @computed get length() { - return this.run.alignments.reduce( - ( sumLength, alignment ) => sumLength + alignment.length, - 0, - ); - } - - @computed get hasInvariantSites() { - // If any one of the alignments has invariant sites return true - for ( const alignment of this.run.alignments ) { - if ( alignment.hasInvariantSites ) { - return true; - } - } - return false; - } - - // @computed get dataType() { - // const numAlignments = this.numAlignments; - // if (numAlignments === 0) { - // return 'none'; - // } - // const firstType = this.run.alignments[0].dataType; - // if (numAlignments === 1) { - // return firstType; - // } - // for (let i = 1; i < numAlignments; ++i) { - // if (this.run.alignments[i].dataType !== firstType) { - // return 'mixed'; - // } - // } - // return firstType; - // } - - @computed get dataType() { - const { alignments } = this.run; - const dataTypes = alignments.map( ( { dataType } ) => dataType ); - return getFinalDataType( dataTypes ); - } - - @computed get modelFlagName() { - const {numAlignments} = this; - if ( numAlignments === 0 ) { - return 'none'; - } - const first = this.run.alignments[0].modelFlagName; - if ( numAlignments === 1 ) { - return first; - } - return first; - } - - @computed get partitionFilePath() { - if ( this.partition.isDefault ) { - return ''; - } - const suffix = this.numAlignments > 1 - ? '_concat' - : ''; - return join( - `${this.dir}`, - `RAxML_${this.run.outputNameSafe}${suffix}.part.txt`, - ); - } - - @computed get partitionFileContent() { - return this.partition.text; - } - - @action - openFile = async () => { - await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.path ); - }; - - @action - openPartition = async () => { - await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.partitionFilePath ); - }; - - @action - showFileInFolder = async () => { - await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.path ); - }; - - @action - openFolder = async () => { - await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.dir ); - }; - - @action - writeConcatenatedAlignmentAndPartition = async () => { - await this.writeConcatenatedAlignment(); - await this.writePartition(); - }; - - @action - writeConcatenatedAlignment = async () => { - const { taxons, numSequences } = this; - try { - console.log( - `Write concatenated alignment in FASTA format to ${this.path}..`, - ); - let text = ''; - for ( let i = 0; i < numSequences; ++i ) { - for ( let j = 0; j < this.numAlignments; ++j ) { - if ( j === 0 ) { - const prefix = i === 0 - ? '>' - : '\n>'; - text += `${prefix}${taxons[i]}\n`; - } - text += this.run.alignments[j].getSequenceCode( taxons[i] ); - } - } - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.path, text ); - } catch ( err ) { - console.error( 'Error writing concatenated alignment:', err ); - throw err; - } - }; - - @action - writePartition = async () => { - try { - console.log( `Writing partition to ${this.partitionFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); - } catch ( err ) { - console.error( 'Error writing partition:', err ); - throw err; - } - }; -} - -export { Alignment as default, FinalAlignment }; +export default Alignment; diff --git a/src/app/store/AlignmentOptions.js b/src/app/store/AlignmentOptions.js new file mode 100644 index 00000000..9019fb6b --- /dev/null +++ b/src/app/store/AlignmentOptions.js @@ -0,0 +1,143 @@ +import { computed } from 'mobx'; + +import Option from './Option'; +import * as raxmlNgSettings from '../../settings/raxmlng'; + +const raxmlNgModelOptions = raxmlNgSettings.modelOptions; + +class RaxmlNgAlignmentSubstitutionModel extends Option { + constructor( alignment ) { + super( alignment.run, '', 'Substitution model' ); + this.alignment = alignment; + } + @computed get options() { + if ( !this.alignment.run.haveAlignments ) { + return []; + } + const modelSettings = raxmlNgModelOptions[this.alignment.dataType]; + if ( !modelSettings ) { + return []; + } + return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); + } + @computed get notAvailable() { + return !this.alignment.run.haveAlignments; + } + @computed get cmdValue() { + let model = this.value; + if ( this.alignment.dataType === 'multistate' ) { + model = model.replace( 'x', this.alignment.multistateNumber.value ); + } + return model; + } +} + +class RaxmlNgModelExtraParam extends Option { + constructor( alignment, label, options, { addNone = true } = {} ) { + super( alignment.run, addNone + ? '' + : options[0].value, label ); + this.alignment = alignment; + this.optionsSource = addNone + ? [{ value: '', title: 'none' }, ...options] + : options; + this.addNone = addNone; + } + @computed get options() { + if ( !this.run.haveAlignments ) { + return []; + } + return this.optionsSource; + } + @computed get notAvailable() { + return !this.run.haveAlignments || !this.run.usesRaxmlNg; + } + @computed get cmdValue() { + return this.value === '' + ? '' + : this.value; + } +} + +class RaxmlNgModelF extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Stationary frequencies', + raxmlNgSettings.stationaryFrequenciesOptions.options.map( + ( { value, label: title } ) => ( { value, title } ), + ), + ); + } +} + +class RaxmlNgModelI extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Proportion of invariant sites', + raxmlNgSettings.proportionOfInvariantSitesOptions.options.map( + ( { value, label: title } ) => ( { value, title } ), + ), + ); + } +} + +class RaxmlNgModelG extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Rate heterogeneity', + raxmlNgSettings.amongsiteRateHeterogeneityModelOptions.options.map( + ( { value, label: title } ) => ( { value, title } ), + ), + ); + } +} + +class RaxmlNgModelASC extends RaxmlNgModelExtraParam { + constructor( alignment ) { + super( + alignment, + 'Ascertainment bias', + [ + { value: '', label: 'No correction' }, + ...raxmlNgSettings.ascertainmentBiasCorrectionOptions.options, + ].map( ( { value, label: title } ) => ( { value, title } ) ), + { addNone: false }, + ); + } + @computed get notAvailable() { + return ( + !this.run.haveAlignments || + !this.run.usesRaxmlNg || + this.alignment.hasInvariantSites + ); + } +} + +class MultistateNumber extends Option { + constructor( alignment ) { + super( alignment.run, '', 'Number of states' ); + this.alignment = alignment; + this.placeholder = 'Integer'; + } + @computed get notAvailable() { + return ( + this.alignment.dataType !== 'multistate' || + !this.alignment.run.usesRaxmlNg + ); + } + @computed get error() { + return !this.value || !Number.isInteger( Number( this.value ) ); + } +} + +export { + RaxmlNgAlignmentSubstitutionModel, + RaxmlNgModelF, + RaxmlNgModelI, + RaxmlNgModelG, + RaxmlNgModelASC, + MultistateNumber, +}; diff --git a/src/app/store/FinalAlignment.js b/src/app/store/FinalAlignment.js new file mode 100644 index 00000000..2a693bfa --- /dev/null +++ b/src/app/store/FinalAlignment.js @@ -0,0 +1,207 @@ +import { observable, computed, action } from 'mobx'; +import union from 'lodash/union'; +import intersection from 'lodash/intersection'; + +import { FinalPartition } from './Partition'; +import { getFinalDataType } from '../../common/typecheckAlignment'; +import { join } from '../paths'; + +class FinalAlignment { + constructor( run ) { + this.run = run; + this.partition = new FinalPartition( run ); + } + + @computed get filename() { + if ( this.numAlignments === 1 ) { + return this.run.alignments[0].filename; + } + return `RAxML_${this.run.outputNameSafe}_concat.txt`; + } + + @computed get dir() { + if ( this.numAlignments === 1 ) { + return this.run.alignments[0].dir; + } + return this.run.outputDir; + } + + @computed get path() { + if ( this.numAlignments === 1 ) { + return this.run.alignments[0].path; + } + return join( `${this.dir}`, `${this.filename}` ); + } + + @observable parsingComplete = true; + + @computed get numAlignments() { + return this.run.alignments.length; + } + + // By default add empty sequences to fill gaps up to the union of taxons + // else drop taxons that doesn't exist in all alignments by taking the intersection + @observable fillTaxonGapsWithEmptySeqeunces = true; + + @action setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { + this.fillTaxonGapsWithEmptySeqeunces = checked; + }; + + @computed get taxons() { + const setMethod = this.fillTaxonGapsWithEmptySeqeunces + ? union + : intersection; + return setMethod.apply( + setMethod, + this.run.alignments.map( ( { taxons } ) => taxons ), + ); + } + + @computed get numSequences() { + return this.taxons.length; + } + + @computed get length() { + return this.run.alignments.reduce( + ( sumLength, alignment ) => sumLength + alignment.length, + 0, + ); + } + + @computed get hasInvariantSites() { + // If any one of the alignments has invariant sites return true + for ( const alignment of this.run.alignments ) { + if ( alignment.hasInvariantSites ) { + return true; + } + } + return false; + } + + // @computed get dataType() { + // const numAlignments = this.numAlignments; + // if (numAlignments === 0) { + // return 'none'; + // } + // const firstType = this.run.alignments[0].dataType; + // if (numAlignments === 1) { + // return firstType; + // } + // for (let i = 1; i < numAlignments; ++i) { + // if (this.run.alignments[i].dataType !== firstType) { + // return 'mixed'; + // } + // } + // return firstType; + // } + + @computed get dataType() { + const { alignments } = this.run; + const dataTypes = alignments.map( ( { dataType } ) => dataType ); + return getFinalDataType( dataTypes ); + } + + @computed get modelFlagName() { + const {numAlignments} = this; + if ( numAlignments === 0 ) { + return 'none'; + } + const first = this.run.alignments[0].modelFlagName; + if ( numAlignments === 1 ) { + return first; + } + return first; + } + + @computed get partitionFilePath() { + if ( this.partition.isDefault ) { + return ''; + } + const suffix = this.numAlignments > 1 + ? '_concat' + : ''; + return join( + `${this.dir}`, + `RAxML_${this.run.outputNameSafe}${suffix}.part.txt`, + ); + } + + @computed get partitionFileContent() { + return this.partition.text; + } + + @action + openFile = async () => { + await this.writeConcatenatedAlignment(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.path ); + }; + + @action + openPartition = async () => { + await this.writeConcatenatedAlignmentAndPartition(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.partitionFilePath ); + }; + + @action + showFileInFolder = async () => { + await this.writeConcatenatedAlignment(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.path ); + }; + + @action + openFolder = async () => { + await this.writeConcatenatedAlignmentAndPartition(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.dir ); + }; + + @action + writeConcatenatedAlignmentAndPartition = async () => { + await this.writeConcatenatedAlignment(); + await this.writePartition(); + }; + + @action + writeConcatenatedAlignment = async () => { + const { taxons, numSequences } = this; + try { + console.log( + `Write concatenated alignment in FASTA format to ${this.path}..`, + ); + let text = ''; + for ( let i = 0; i < numSequences; ++i ) { + for ( let j = 0; j < this.numAlignments; ++j ) { + if ( j === 0 ) { + const prefix = i === 0 + ? '>' + : '\n>'; + text += `${prefix}${taxons[i]}\n`; + } + text += this.run.alignments[j].getSequenceCode( taxons[i] ); + } + } + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.path, text ); + } catch ( err ) { + console.error( 'Error writing concatenated alignment:', err ); + throw err; + } + }; + + @action + writePartition = async () => { + try { + console.log( `Writing partition to ${this.partitionFilePath}...` ); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); + } catch ( err ) { + console.error( 'Error writing partition:', err ); + throw err; + } + }; +} + +export default FinalAlignment; diff --git a/src/app/store/Run.js b/src/app/store/Run.js index 0bb7068e..a3df10b3 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -2,7 +2,8 @@ import { observable, computed, action, createAtom } from 'mobx'; import { promisedComputed } from 'computed-async-mobx'; import filenamify from 'filenamify'; -import Alignment, { FinalAlignment } from './Alignment'; +import Alignment from './Alignment'; +import FinalAlignment from './FinalAlignment'; import AstralTree from './AstralTree'; import StoreBase, { runEvents } from './StoreBase'; import { host } from './host'; From 2b0f93f6aff9a3514ee3ca1228a479d45a62c786 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 00:25:19 +0100 Subject: [PATCH 04/54] Split the partition file into one module per class family Move the part option classes to PartOptions.js and FinalPartition to FinalPartition.js; Part and Partition stay in Partition.js. Pure move. Closes #121 Co-Authored-By: Claude Opus 5.5 --- src/app/store/Alignment.js | 3 +- src/app/store/FinalPartition.js | 38 ++++++ src/app/store/PartOptions.js | 154 ++++++++++++++++++++++++ src/app/store/Partition.js | 199 ++------------------------------ 4 files changed, 206 insertions(+), 188 deletions(-) create mode 100644 src/app/store/FinalPartition.js create mode 100644 src/app/store/PartOptions.js diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.js index f8a65724..9dc275fe 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.js @@ -5,7 +5,8 @@ import intersection from 'lodash/intersection'; import Option from './Option'; import * as raxmlSettings from '../../settings/raxml'; import * as raxmlNgSettings from '../../settings/raxmlng'; -import Partition, { FinalPartition } from './Partition'; +import Partition from './Partition'; +import FinalPartition from './FinalPartition'; import InputFile from './InputFile'; import { runEvents } from './StoreBase'; import { getFinalDataType } from '../../common/typecheckAlignment'; diff --git a/src/app/store/FinalPartition.js b/src/app/store/FinalPartition.js new file mode 100644 index 00000000..87dcb1e5 --- /dev/null +++ b/src/app/store/FinalPartition.js @@ -0,0 +1,38 @@ +import { computed } from 'mobx'; + +class FinalPartition { + constructor( run ) { + this.run = run; + } + /* + Example: + DNA, gene1 = 1-3676 + BIN, morph = 3677-3851 + */ + @computed get text() { + if ( !this.run.haveAlignments ) { + return ''; + } + const partitionTexts = []; + let total = 0; + this.run.alignments.forEach( ( alignment, index ) => { + partitionTexts.push( alignment.partition.transform( total, `${index}_` ) ); + total += alignment.length; + } ); + return partitionTexts.join( '\n' ); + } + @computed get isDefault() { + return ( + this.run.alignments.length === 0 || + ( this.run.alignments.length === 1 && + this.run.alignments[0].partition.isDefault ) + ); + } + @computed get isComplete() { + return this.run.alignments.every( + ( alignment ) => alignment.partition.isComplete, + ); + } +} + +export default FinalPartition; diff --git a/src/app/store/PartOptions.js b/src/app/store/PartOptions.js new file mode 100644 index 00000000..4f921908 --- /dev/null +++ b/src/app/store/PartOptions.js @@ -0,0 +1,154 @@ +import { computed } from 'mobx'; +import Option from './Option'; +import * as raxmlSettings from '../../settings/raxml'; +import * as yup from 'yup'; + +export const CODON_NONE = 'None'; +export const CODON_SPECIFIC = 'Codon specific'; +export const CODON_THIRD = 'Third codon'; +export const CodonModels = [CODON_NONE, CODON_SPECIFIC, CODON_THIRD]; + +class PartBase extends Option { + constructor( + part, + defaultValue, + title, + description, + hoverInfo, + { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, + ) { + super( + part.partition.alignment.run, + defaultValue, + title, + description, + hoverInfo, + { + schema, + allowOnlyValidChange, + helperText, + }, + ); + this.part = part; + } + @computed get alignment() { + return this.part.partition.alignment; + } +} + +class PartType extends PartBase { + constructor( part, value = 'DNA' ) { + super( part, value, 'Data type', 'Data type of the part', '', { + schema: yup.string(), + allowOnlyValidChange: true, + } ); + } + @computed get finalValue() { + const { dataType, partitionType } = this.alignment; + if ( dataType === 'protein' || this.value === 'protein' ) { + return this.part.aaType.value; + } + if ( dataType === 'mixed' ) { + return this.value; + } + return partitionType; + } + @computed get options() { + const { dataType } = this.alignment; + let opts = [dataType]; + if ( dataType === '' || dataType === 'mixed' ) { + opts = ['DNA', 'BIN', 'MULTI', 'protein']; + } + return opts.map( ( value ) => ( { value, title: value } ) ); + } + @computed get notAvailable() { + return this.alignment.dataType !== 'mixed'; + } +} +class PartAAType extends PartBase { + constructor( part, value = 'BLOSUM62' ) { + super( part, value, 'Model', 'Substitution model for the part', '', { + schema: yup.string(), + allowOnlyValidChange: true, + } ); + } + options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( + ( value ) => ( { value, title: value } ), + ); + @computed get notAvailable() { + return this.alignment.dataType !== 'protein'; + } +} +class PartName extends PartBase { + constructor( part, value = 'part1' ) { + super( part, value, 'Name', 'Name of part', '', { + schema: yup.string(), // TODO: Check that it is unique within partition + allowOnlyValidChange: true, + } ); + } + @computed get notAvailable() { + return false; + } +} +class PartStart extends PartBase { + constructor( part, value = 1 ) { + super( part, value, 'from', 'Start position for this part', '', { + schema: yup.number(), + allowOnlyValidChange: false, + } ); + this.disabled = true; + } + @computed get notAvailable() { + return false; + } +} + +class PartEnd extends PartBase { + constructor( part, value = 1 ) { + super( + part, + value, + 'to', + 'Ending position (inclusive) for this part', + 'Ending position (inclusive) for this part', + { + schema: yup.number().test( { + name: 'part-end', + message: () => `Must be in interval [${this.min}, ${this.max}]`, + test: ( value ) => { + return value >= this.min && value <= this.max; + }, + } ), + allowOnlyValidChange: false, + }, + ); + } + @computed get min() { + return ( + this.part.start.value + ( this.part.codon.value === CODON_NONE + ? 0 + : 2 ) + ); + } + @computed get max() { + return this.alignment.length; + } + @computed get notAvailable() { + return false; + } +} + +class PartCodon extends PartBase { + constructor( part, value = 'None' ) { + super( part, value, 'Codon model', '', '', { + schema: yup.string(), + allowOnlyValidChange: true, + } ); + } + options = CodonModels.map( ( value ) => ( { value, title: value } ) ); + @computed get notAvailable() { + return this.alignment.partition.partToAdd.type.value !== 'DNA'; + } +} + +export { PartType, PartAAType, PartName, PartStart, PartEnd, PartCodon }; diff --git a/src/app/store/Partition.js b/src/app/store/Partition.js index dbd31fec..d12b63f8 100644 --- a/src/app/store/Partition.js +++ b/src/app/store/Partition.js @@ -1,12 +1,15 @@ import { observable, computed, action, reaction } from 'mobx'; -import Option from './Option'; -import * as raxmlSettings from '../../settings/raxml'; -import * as yup from 'yup'; - -const CODON_NONE = 'None'; -const CODON_SPECIFIC = 'Codon specific'; -const CODON_THIRD = 'Third codon'; -export const CodonModels = [CODON_NONE, CODON_SPECIFIC, CODON_THIRD]; +import { + CODON_NONE, + CODON_SPECIFIC, + CODON_THIRD, + PartType, + PartAAType, + PartName, + PartStart, + PartEnd, + PartCodon, +} from './PartOptions'; const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { // for old raxml @@ -25,149 +28,6 @@ const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { } }; -class PartBase extends Option { - constructor( - part, - defaultValue, - title, - description, - hoverInfo, - { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, - ) { - super( - part.partition.alignment.run, - defaultValue, - title, - description, - hoverInfo, - { - schema, - allowOnlyValidChange, - helperText, - }, - ); - this.part = part; - } - @computed get alignment() { - return this.part.partition.alignment; - } -} - -class PartType extends PartBase { - constructor( part, value = 'DNA' ) { - super( part, value, 'Data type', 'Data type of the part', '', { - schema: yup.string(), - allowOnlyValidChange: true, - } ); - } - @computed get finalValue() { - const { dataType, partitionType } = this.alignment; - if ( dataType === 'protein' || this.value === 'protein' ) { - return this.part.aaType.value; - } - if ( dataType === 'mixed' ) { - return this.value; - } - return partitionType; - } - @computed get options() { - const { dataType } = this.alignment; - let opts = [dataType]; - if ( dataType === '' || dataType === 'mixed' ) { - opts = ['DNA', 'BIN', 'MULTI', 'protein']; - } - return opts.map( ( value ) => ( { value, title: value } ) ); - } - @computed get notAvailable() { - return this.alignment.dataType !== 'mixed'; - } -} -class PartAAType extends PartBase { - constructor( part, value = 'BLOSUM62' ) { - super( part, value, 'Model', 'Substitution model for the part', '', { - schema: yup.string(), - allowOnlyValidChange: true, - } ); - } - options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( - ( value ) => ( { value, title: value } ), - ); - @computed get notAvailable() { - return this.alignment.dataType !== 'protein'; - } -} -class PartName extends PartBase { - constructor( part, value = 'part1' ) { - super( part, value, 'Name', 'Name of part', '', { - schema: yup.string(), // TODO: Check that it is unique within partition - allowOnlyValidChange: true, - } ); - } - @computed get notAvailable() { - return false; - } -} -class PartStart extends PartBase { - constructor( part, value = 1 ) { - super( part, value, 'from', 'Start position for this part', '', { - schema: yup.number(), - allowOnlyValidChange: false, - } ); - this.disabled = true; - } - @computed get notAvailable() { - return false; - } -} - -class PartEnd extends PartBase { - constructor( part, value = 1 ) { - super( - part, - value, - 'to', - 'Ending position (inclusive) for this part', - 'Ending position (inclusive) for this part', - { - schema: yup.number().test( { - name: 'part-end', - message: () => `Must be in interval [${this.min}, ${this.max}]`, - test: ( value ) => { - return value >= this.min && value <= this.max; - }, - } ), - allowOnlyValidChange: false, - }, - ); - } - @computed get min() { - return ( - this.part.start.value + ( this.part.codon.value === CODON_NONE - ? 0 - : 2 ) - ); - } - @computed get max() { - return this.alignment.length; - } - @computed get notAvailable() { - return false; - } -} - -class PartCodon extends PartBase { - constructor( part, value = 'None' ) { - super( part, value, 'Codon model', '', '', { - schema: yup.string(), - allowOnlyValidChange: true, - } ); - } - options = CodonModels.map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { - return this.alignment.partition.partToAdd.type.value !== 'DNA'; - } -} - class Part { constructor( partition, { type, aaType, name, start, end, codon } ) { this.partition = partition; @@ -376,39 +236,4 @@ class Partition { }; } -class FinalPartition { - constructor( run ) { - this.run = run; - } - /* - Example: - DNA, gene1 = 1-3676 - BIN, morph = 3677-3851 - */ - @computed get text() { - if ( !this.run.haveAlignments ) { - return ''; - } - const partitionTexts = []; - let total = 0; - this.run.alignments.forEach( ( alignment, index ) => { - partitionTexts.push( alignment.partition.transform( total, `${index}_` ) ); - total += alignment.length; - } ); - return partitionTexts.join( '\n' ); - } - @computed get isDefault() { - return ( - this.run.alignments.length === 0 || - ( this.run.alignments.length === 1 && - this.run.alignments[0].partition.isDefault ) - ); - } - @computed get isComplete() { - return this.run.alignments.every( - ( alignment ) => alignment.partition.isComplete, - ); - } -} - -export { Partition as default, FinalPartition }; +export default Partition; From 4e8158f8d989630523e2d4e1ab577d1a81fa0ab2 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 00:42:56 +0100 Subject: [PATCH 05/54] Pin private-property-in-object to silence the react-app babel warning @babel/preset-env pulls in a placeholder build of @babel/plugin-proposal-private-property-in-object, which yarn nests under babel-preset-react-app; that copy prints a ten-line warning on every lint run. A resolution to 7.21.11 dedupes it to the real plugin already in devDependencies, so lint output is just the lint result. Co-Authored-By: Claude Opus 5.5 --- package.json | 1 + yarn.lock | 7 +------ 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index d8bad7c8..bb1fdfe0 100644 --- a/package.json +++ b/package.json @@ -216,6 +216,7 @@ } }, "resolutions": { + "@babel/plugin-proposal-private-property-in-object": "7.21.11", "@typescript-eslint/eslint-plugin": "^8.72.1", "@typescript-eslint/parser": "^8.72.1" } diff --git a/yarn.lock b/yarn.lock index e958fc50..f8d388a7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -726,12 +726,7 @@ "@babel/helper-create-class-features-plugin" "^7.18.6" "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2": - version "7.21.0-placeholder-for-preset-env.2" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz#7844f9289546efa9febac2de4cfe358a050bd703" - integrity sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w== - -"@babel/plugin-proposal-private-property-in-object@^7.21.11": +"@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2", "@babel/plugin-proposal-private-property-in-object@7.21.11", "@babel/plugin-proposal-private-property-in-object@^7.21.11": version "7.21.11" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz#69d597086b6760c4126525cfa154f34631ff272c" integrity sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw== From 8f496032a87be6b5a3490e3f0227aa09c2f49667 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:10:04 +0100 Subject: [PATCH 06/54] Import FinalPartition from its own module #121 moved FinalPartition out of Partition.js; FinalAlignment still imported it from there, breaking the build after the spec merge. Co-Authored-By: Claude Opus 5.5 --- src/app/store/FinalAlignment.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/store/FinalAlignment.js b/src/app/store/FinalAlignment.js index 2a693bfa..c8fbc33e 100644 --- a/src/app/store/FinalAlignment.js +++ b/src/app/store/FinalAlignment.js @@ -2,7 +2,7 @@ import { observable, computed, action } from 'mobx'; import union from 'lodash/union'; import intersection from 'lodash/intersection'; -import { FinalPartition } from './Partition'; +import FinalPartition from './FinalPartition'; import { getFinalDataType } from '../../common/typecheckAlignment'; import { join } from '../paths'; From 59d3ec61880aaa753dc573012502a77aff8c2e69 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:15:00 +0100 Subject: [PATCH 07/54] Cover the citation and config on MobX 5 Pins today's behaviour of Citation and Config through the page store: each citation format's text, allText following format, show/hide, clipboard copy, dark mode loading, switching and menu events, and dispose. Bridge stub lives in the test file. Closes #124 Co-Authored-By: Claude Opus 5.5 --- src/app/store/citationConfig.test.js | 185 +++++++++++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 src/app/store/citationConfig.test.js diff --git a/src/app/store/citationConfig.test.js b/src/app/store/citationConfig.test.js new file mode 100644 index 00000000..a75c5ac2 --- /dev/null +++ b/src/app/store/citationConfig.test.js @@ -0,0 +1,185 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { reaction, runInAction } from 'mobx'; + +import AppStore from './AppStore'; + +let listeners; +let bridge; + +beforeEach( () => { + listeners = {}; + const subscribe = ( key ) => jest.fn( ( listener ) => { + listeners[key] = listener; + return () => { + delete listeners[key]; + }; + } ); + bridge = { + getVersion: jest.fn( async () => '2.0.0' ), + getDarkMode: jest.fn( async () => false ), + setDarkMode: jest.fn( async () => {} ), + copyText: jest.fn( async () => {} ), + onLightMode: subscribe( 'light' ), + onDarkMode: subscribe( 'dark' ), + }; + window.rendererBridge = bridge; +} ); + +async function settle() { + await Promise.all( bridge.getDarkMode.mock.results.map( ( r ) => r.value ) ); +} + +function track( expression ) { + const seen = []; + const stop = reaction( expression, ( value ) => seen.push( value ) ); + return { seen, stop }; +} + +describe( 'citation', () => { + it( 'offers plain text, RIS and BibTeX, plain text first', () => { + const { citation } = new AppStore(); + expect( citation.formats.map( ( f ) => f.value ) ).toEqual( ['txt', 'ris', 'bib'] ); + expect( citation.format ).toBe( 'txt' ); + } ); + + it( 'plain text format text', () => { + const { citation } = new AppStore(); + const lines = citation.allText.split( '\n' ); + expect( lines ).toHaveLength( 4 ); + expect( lines[0] ).toBe( 'Edler, D, Klein, J, Antonelli, A, Silvestro, D. raxmlGUI 2.0: A graphical interface and toolkit for phylogenetic analyses using RAxML. Methods Ecol Evol. 2021; 12: 373– 377. https://doi.org/10.1111/2041-210X.13512' ); + expect( lines[1] ).toMatch( /^Alexandros Stamatakis, RAxML version 8: .*btu033$/ ); + expect( lines[2] ).toMatch( /^Alexey M Kozlov, .*RAxML-NG: .*btz305$/ ); + expect( lines[3] ).toMatch( /^Diego Darriba, .*ModelTest-NG: .*msz189$/ ); + } ); + + it( 'RIS format text', () => { + const { citation } = new AppStore(); + citation.setFormat( 'ris' ); + const text = citation.allText; + expect( text.match( /^TY {2}- JOUR$/gm ) ).toHaveLength( 4 ); + expect( text.match( /^ER {2}- ?$/gm ) ).toHaveLength( 4 ); + expect( text.startsWith( '\nTY - JOUR\nT1 - raxmlGUI 2.0:' ) ).toBe( true ); + for ( const doi of ['10.1111/2041-210X.13512', '10.1093/bioinformatics/btu033', '10.1093/bioinformatics/btz305', '10.1093/molbev/msz189'] ) { + expect( text ).toContain( `UR - https://doi.org/${doi}` ); + } + expect( text ).not.toContain( '@article' ); + } ); + + it( 'BibTeX format text', () => { + const { citation } = new AppStore(); + citation.setFormat( 'bib' ); + const text = citation.allText; + expect( text.match( /@article\{/g ) ).toHaveLength( 4 ); + expect( text.startsWith( '@article{https://doi.org/10.1111/2041-210X.13512,\nauthor = {Edler, Daniel' ) ).toBe( true ); + expect( text ).toContain( '@article{10.1093/bioinformatics/btu033,' ); + expect( text ).toContain( '@article{10.1093/bioinformatics/btz305,' ); + expect( text.endsWith( 'eprint = {https://academic.oup.com/mbe/article-pdf/37/1/291/32085561/msz189.pdf},\n}' ) ).toBe( true ); + expect( text ).not.toContain( 'TY - JOUR' ); + } ); + + it( 'allText follows format, set by action or directly', () => { + const { citation } = new AppStore(); + const { seen, stop } = track( () => citation.allText ); + + citation.setFormat( 'bib' ); + runInAction( () => { + citation.format = 'ris'; + } ); + stop(); + + expect( seen ).toHaveLength( 2 ); + expect( seen[0] ).toContain( '@article{' ); + expect( seen[1] ).toContain( 'TY - JOUR' ); + } ); + + it( 'show and hide switch visibility, and a reaction sees it', () => { + const { citation } = new AppStore(); + expect( citation.visible ).toBe( false ); + const { seen, stop } = track( () => citation.visible ); + + citation.show(); + expect( citation.visible ).toBe( true ); + citation.hide(); + expect( citation.visible ).toBe( false ); + runInAction( () => { + citation.visible = true; + } ); + stop(); + + expect( seen ).toEqual( [true, false, true] ); + } ); + + it( 'copyToClipboard copies the text in the current format', async () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + const { citation } = new AppStore(); + citation.setFormat( 'bib' ); + await citation.copyToClipboard(); + expect( bridge.copyText ).toHaveBeenCalledWith( citation.allText ); + expect( bridge.copyText.mock.calls[0][0] ).toContain( '@article{' ); + } ); +} ); + +describe( 'config dark mode', () => { + it( 'starts light and loads dark mode from the renderer bridge', async () => { + bridge.getDarkMode.mockImplementation( async () => 1 ); + const { config } = new AppStore(); + expect( config.isDarkMode ).toBe( false ); + await settle(); + expect( config.isDarkMode ).toBe( true ); + } ); + + it( 'a falsy loaded value stays light', async () => { + bridge.getDarkMode.mockImplementation( async () => undefined ); + const { config } = new AppStore(); + await settle(); + expect( config.isDarkMode ).toBe( false ); + } ); + + it( 'setDarkMode switches the theme and tells the bridge, as a boolean', async () => { + const { config } = new AppStore(); + await settle(); + const { seen, stop } = track( () => config.isDarkMode ); + + config.setDarkMode( 'yes' ); + expect( config.isDarkMode ).toBe( true ); + config.setDarkMode( 0 ); + expect( config.isDarkMode ).toBe( false ); + runInAction( () => { + config.isDarkMode = true; + } ); + stop(); + + expect( seen ).toEqual( [true, false, true] ); + expect( bridge.setDarkMode.mock.calls ).toEqual( [[true], [false]] ); + } ); + + it( 'dark and light menu events switch the theme', async () => { + const { config } = new AppStore(); + await settle(); + + listeners.dark(); + expect( config.isDarkMode ).toBe( true ); + listeners.light(); + expect( config.isDarkMode ).toBe( false ); + expect( bridge.setDarkMode.mock.calls ).toEqual( [[true], [false]] ); + } ); + + it( 'onDarkMode and onLightMode switch the theme', async () => { + const { config } = new AppStore(); + await settle(); + + config.onDarkMode(); + expect( config.isDarkMode ).toBe( true ); + config.onLightMode(); + expect( config.isDarkMode ).toBe( false ); + } ); + + it( 'dispose stops listening for menu events', async () => { + const { config } = new AppStore(); + await settle(); + expect( Object.keys( listeners ).sort() ).toEqual( ['dark', 'light'] ); + + config.dispose(); + expect( listeners ).toEqual( {} ); + } ); +} ); From f74708dd578fc1d96e07088a0a29d26a02777fef Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:15:17 +0100 Subject: [PATCH 08/54] Cover the option base on MobX 5 Pin Option's actions, computeds and value reactivity before the MobX 7 rewrite. Closes #123 Co-Authored-By: Claude Opus 5.5 --- src/app/store/Option.test.js | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/app/store/Option.test.js diff --git a/src/app/store/Option.test.js b/src/app/store/Option.test.js new file mode 100644 index 00000000..c1224320 --- /dev/null +++ b/src/app/store/Option.test.js @@ -0,0 +1,83 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; +import * as yup from 'yup'; + +import Option from './Option'; + +const positive = () => new Option( null, 2, 'Count', 'desc', 'hover', { + schema: yup.number().positive(), +} ); + +it( 'starts at the default value', () => { + const option = positive(); + expect( option.value ).toBe( 2 ); + expect( option.isDefault ).toBe( true ); + expect( option.error ).toBeNull(); + expect( option.haveError ).toBe( false ); + expect( option.errorMessage ).toBe( '' ); +} ); + +it( 'sets a value, casting it through the schema', () => { + const option = positive(); + option.setValue( '5' ); + expect( option.value ).toBe( 5 ); + expect( option.isDefault ).toBe( false ); +} ); + +it( 'keeps an invalid value as given and reports its error', () => { + const option = positive(); + option.setValue( -1 ); + expect( option.value ).toBe( -1 ); + expect( option.error ).toBeInstanceOf( yup.ValidationError ); + expect( option.haveError ).toBe( true ); + expect( option.errorMessage ).toBe( option.error.message ); + expect( option.errorMessage ).not.toBe( '' ); +} ); + +it( 'ignores an invalid value when only valid changes are allowed', () => { + const option = new Option( null, 'a', 'Name', 'desc', 'hover', { + schema: yup.string().max( 3 ), + allowOnlyValidChange: true, + } ); + option.setValue( 'toolong' ); + expect( option.value ).toBe( 'a' ); + option.setValue( 'abc' ); + expect( option.value ).toBe( 'abc' ); +} ); + +it( 'accepts any value without a schema', () => { + const option = new Option( null, 'x', 'Title', 'desc', 'hover' ); + option.setValue( 42 ); + expect( option.value ).toBe( 42 ); + expect( option.error ).toBeNull(); + expect( option.helperText ).toBe( '' ); +} ); + +it( 'resets to the default value', () => { + const option = positive(); + option.setValue( -1 ); + option.reset(); + expect( option.value ).toBe( 2 ); + expect( option.isDefault ).toBe( true ); + expect( option.haveError ).toBe( false ); +} ); + +it( 'updates computeds and reactions when value changes', () => { + const option = positive(); + const seen = []; + const dispose = autorun( () => { + seen.push( [option.isDefault, option.errorMessage === ''] ); + } ); + runInAction( () => { + option.value = -3; + } ); + runInAction( () => { + option.value = 2; + } ); + dispose(); + expect( seen ).toEqual( [ + [true, true], + [false, false], + [true, true], + ] ); +} ); From a2bd52622488ad5f9859dda182e34c713ec92190 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:20:15 +0100 Subject: [PATCH 09/54] Drop dark mode tests the citation and config file now covers darkMode.test.js and the light/dark case in menu.test.js assert what citationConfig.test.js asserts through the page store. Co-Authored-By: Claude Opus 5.5 --- src/app/store/citationConfig.test.js | 10 ---------- src/app/store/darkMode.test.js | 21 --------------------- src/app/store/menu.test.js | 11 ----------- 3 files changed, 42 deletions(-) delete mode 100644 src/app/store/darkMode.test.js diff --git a/src/app/store/citationConfig.test.js b/src/app/store/citationConfig.test.js index a75c5ac2..6ebd4380 100644 --- a/src/app/store/citationConfig.test.js +++ b/src/app/store/citationConfig.test.js @@ -164,16 +164,6 @@ describe( 'config dark mode', () => { expect( bridge.setDarkMode.mock.calls ).toEqual( [[true], [false]] ); } ); - it( 'onDarkMode and onLightMode switch the theme', async () => { - const { config } = new AppStore(); - await settle(); - - config.onDarkMode(); - expect( config.isDarkMode ).toBe( true ); - config.onLightMode(); - expect( config.isDarkMode ).toBe( false ); - } ); - it( 'dispose stops listening for menu events', async () => { const { config } = new AppStore(); await settle(); diff --git a/src/app/store/darkMode.test.js b/src/app/store/darkMode.test.js deleted file mode 100644 index 24bffd1d..00000000 --- a/src/app/store/darkMode.test.js +++ /dev/null @@ -1,21 +0,0 @@ -// @ts-nocheck — Jest globals. checkJs has no test runner types. -import { act } from 'react'; - -import Config from './Config'; - -it( 'loads dark mode from the renderer bridge', async () => { - const getDarkMode = jest.fn( async () => true ); - const setDarkMode = jest.fn( async () => {} ); - window.rendererBridge = { getDarkMode, setDarkMode }; - - const config = new Config(); - expect( config.isDarkMode ).toBe( false ); - await act( async () => { - await getDarkMode.mock.results[0].value; - } ); - expect( config.isDarkMode ).toBe( true ); - - config.setDarkMode( false ); - expect( config.isDarkMode ).toBe( false ); - expect( setDarkMode ).toHaveBeenCalledWith( false ); -} ); diff --git a/src/app/store/menu.test.js b/src/app/store/menu.test.js index a7f0dbed..0eb30898 100644 --- a/src/app/store/menu.test.js +++ b/src/app/store/menu.test.js @@ -29,17 +29,6 @@ it( 'onAddRun and onRemoveRun update the page runs', () => { expect( runs.runs ).toHaveLength( 1 ); } ); -it( 'onLightMode and onDarkMode update the page theme', () => { - const listeners = bridge(); - const runs = new RunList(); - - listeners.dark(); - expect( runs.config.isDarkMode ).toBe( true ); - - listeners.light(); - expect( runs.config.isDarkMode ).toBe( false ); -} ); - it( 'onToggleBackboneConstraint and onToggleMultifurcatingConstraint update those constraints', () => { const listeners = bridge(); const runs = new RunList(); From 6e6318228f434e89d83f201c9d1893ec33650740 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:23:20 +0100 Subject: [PATCH 10/54] Fail lint on warnings eslint exits 0 on warnings, so the CI lint job let them through. Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d8bad7c8..29bd3275 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "docs-serve": "cd docs && bundle exec jekyll serve --config _config.yml,_config_dev.yml", "typecheck": "tsc --noEmit", "typecheck:baseline": "node scripts/typecheck-baseline.js", - "lint": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\"", + "lint": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\" --max-warnings 0", "lint:fix": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\" --fix" }, "dependencies": { From 4936a259152517cc7b1337fd9cca5b21c2d67a81 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:16:17 +0100 Subject: [PATCH 11/54] Cover the app store and run list on MobX 5 Pins today's behaviour of AppStore and RunList: every action and computed, a reaction per observable field, adding, removing and switching runs, and independent state between two runs. Closes #125 Co-Authored-By: Claude Opus 5.5 --- src/app/store/RunList.test.js | 278 ++++++++++++++++++++++++++++++++++ 1 file changed, 278 insertions(+) create mode 100644 src/app/store/RunList.test.js diff --git a/src/app/store/RunList.test.js b/src/app/store/RunList.test.js new file mode 100644 index 00000000..bbb68d4e --- /dev/null +++ b/src/app/store/RunList.test.js @@ -0,0 +1,278 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import AppStore from './AppStore'; +import RunList from './RunList'; +import { runEvents } from './StoreBase'; + +let listeners; +let cancelRun; + +// The run list subscribes to bridge events; keep each listener so a test can fire it. +function stubBridge() { + const byName = {}; + listeners = byName; + cancelRun = jest.fn(); + const bridge = { cancelRun, getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = ( listener ) => { + ( byName[name] ||= [] ).push( listener ); + return () => { + byName[name] = byName[name].filter( ( l ) => l !== listener ); + }; + }; + } + window.rendererBridge = bridge; +} + +function fire( name, ...args ) { + ( listeners[name] || [] ).forEach( ( listener ) => listener( ...args ) ); +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +beforeEach( () => stubBridge() ); + +describe( 'AppStore', () => { + it( 'loads the version from the renderer bridge', async () => { + const store = new AppStore(); + const { seen, stop } = track( () => store.version ); + await Promise.resolve(); + expect( store.version ).toBe( '2.0.0' ); + expect( seen ).toEqual( [undefined, '2.0.0'] ); + stop(); + } ); + + it( 'a reaction sees a version set directly', () => { + const store = new AppStore(); + const { seen, stop } = track( () => store.version ); + runInAction( () => { + store.version = '9.9.9'; + } ); + expect( seen ).toEqual( [undefined, '9.9.9'] ); + stop(); + } ); + + it( 'setAppSnack and clearAppSnack toggle the snack', () => { + const store = new AppStore(); + const { seen, stop } = track( () => store.showAppSnack ); + store.setAppSnack(); + expect( store.showAppSnack ).toBe( true ); + store.clearAppSnack(); + expect( store.showAppSnack ).toBe( false ); + expect( seen ).toEqual( [false, true, false] ); + stop(); + } ); + + it( 'has a citation and a config', () => { + const store = new AppStore(); + expect( store.citation.format ).toBe( 'txt' ); + expect( store.config.isDarkMode ).toBe( false ); + } ); +} ); + +describe( 'RunList', () => { + it( 'starts with one active run', () => { + const list = new RunList(); + expect( list.runs ).toHaveLength( 1 ); + expect( list.activeIndex ).toBe( 0 ); + expect( list.activeRun ).toBe( list.runs[0] ); + expect( list.activeRun.id ).toBe( 1 ); + } ); + + it( 'adding a run appends it with the next id and makes it active', () => { + const list = new RunList(); + const { seen, stop } = track( () => list.activeRun.id ); + list.addRun(); + list.addRun(); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1, 2, 3] ); + expect( list.activeIndex ).toBe( 2 ); + expect( seen ).toEqual( [1, 2, 3] ); + stop(); + } ); + + it( 'adding a run after a delete uses one more than the highest id', () => { + const list = new RunList(); + list.addRun(); + list.addRun(); + list.deleteRun( list.runs[1] ); + list.addRun(); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1, 3, 4] ); + } ); + + it( 'switching the active run changes activeRun', () => { + const list = new RunList(); + list.addRun(); + const { seen, stop } = track( () => list.activeRun.id ); + list.setActive( 0 ); + expect( list.activeIndex ).toBe( 0 ); + expect( list.activeRun ).toBe( list.runs[0] ); + list.setActive( 1 ); + expect( seen ).toEqual( [2, 1, 2] ); + stop(); + } ); + + it( 'activeRun follows activeIndex and runs set directly', () => { + const list = new RunList(); + list.addRun(); + const { seen, stop } = track( () => list.activeRun?.id ); + runInAction( () => { + list.activeIndex = 0; + } ); + runInAction( () => { + list.runs = list.runs.slice().reverse(); + } ); + expect( seen ).toEqual( [2, 1, 2] ); + stop(); + } ); + + it( 'removing a run disposes it and clamps the active index', () => { + const list = new RunList(); + list.addRun(); + list.addRun(); + const last = list.runs[2]; + list.deleteRun( last ); + expect( cancelRun ).toHaveBeenCalledWith( 3 ); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1, 2] ); + expect( list.activeIndex ).toBe( 1 ); + expect( list.activeRun.id ).toBe( 2 ); + } ); + + it( 'removing a run before the active one keeps the index', () => { + const list = new RunList(); + list.addRun(); + list.addRun(); + list.setActive( 1 ); + list.deleteRun( list.runs[0] ); + expect( list.activeIndex ).toBe( 1 ); + expect( list.activeRun.id ).toBe( 3 ); + } ); + + it( 'removing the only run replaces it with a fresh run 1', () => { + const list = new RunList(); + list.addRun(); + list.deleteRun( list.runs[0] ); + const remaining = list.runs[0]; + list.deleteRun( remaining ); + expect( list.runs ).toHaveLength( 1 ); + expect( list.runs[0] ).not.toBe( remaining ); + expect( list.activeRun.id ).toBe( 1 ); + expect( list.activeIndex ).toBe( 0 ); + } ); + + it( 'deleteActive removes the active run', () => { + const list = new RunList(); + list.addRun(); + list.setActive( 0 ); + list.deleteActive(); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [2] ); + expect( list.activeRun.id ).toBe( 2 ); + } ); + + it( 'a removed run stops listening to bridge events', () => { + const list = new RunList(); + list.addRun(); + const removed = list.runs[1]; + list.deleteRun( removed ); + fire( runEvents.onRunStdout, { id: 2, content: 'late' } ); + expect( removed.stdout ).toBe( '' ); + } ); + + it( 'two runs keep independent state', () => { + const list = new RunList(); + list.addRun(); + const [first, second] = list.runs; + runInAction( () => { + first.useBackboneConstraint = true; + } ); + fire( runEvents.onRunStdout, { id: 2, content: 'second only' } ); + expect( first.useBackboneConstraint ).toBe( true ); + expect( second.useBackboneConstraint ).toBe( false ); + expect( first.stdout ).toBe( '' ); + expect( second.stdout ).toBe( 'second only' ); + expect( first.outputNamePlaceholder ).toBe( '1' ); + expect( second.outputNamePlaceholder ).toBe( '2' ); + } ); + + it( 'onError sets the error and clears the title; clearError resets both', () => { + const list = new RunList(); + const { seen, stop } = track( () => [list.errorTitle, list.error] ); + runInAction( () => { + list.errorTitle = 'Old'; + } ); + const error = new Error( 'boom' ); + list.onError( error ); + expect( list.error ).toBe( error ); + expect( list.errorTitle ).toBeNull(); + list.clearError(); + expect( list.error ).toBeNull(); + expect( list.errorTitle ).toBeNull(); + expect( seen ).toEqual( [ + [null, null], + ['Old', null], + [null, error], + [null, null], + ] ); + stop(); + } ); + + it( 'onUnhandledError sets the title and error', () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + const list = new RunList(); + const error = new Error( 'crash' ); + list.onUnhandledError( { title: 'Oops', error } ); + expect( list.errorTitle ).toBe( 'Oops' ); + expect( list.error ).toBe( error ); + console.log.mockRestore(); + } ); + + it( 'the constraint toggles flip the active run only', () => { + const list = new RunList(); + list.addRun(); + const [first, second] = list.runs; + list.onBackboneConstraint(); + list.onMultifurcatingConstraint(); + expect( second.useBackboneConstraint ).toBe( true ); + expect( second.useMultifurcatingConstraint ).toBe( true ); + expect( first.useBackboneConstraint ).toBe( false ); + expect( first.useMultifurcatingConstraint ).toBe( false ); + list.onBackboneConstraint(); + list.onMultifurcatingConstraint(); + expect( second.useBackboneConstraint ).toBe( false ); + expect( second.useMultifurcatingConstraint ).toBe( false ); + } ); + + it( 'routes bridge events to its actions', () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + const list = new RunList(); + fire( runEvents.onAddRun ); + expect( list.runs ).toHaveLength( 2 ); + fire( runEvents.onToggleBackboneConstraint ); + fire( runEvents.onToggleMultifurcatingConstraint ); + expect( list.activeRun.useBackboneConstraint ).toBe( true ); + expect( list.activeRun.useMultifurcatingConstraint ).toBe( true ); + fire( runEvents.onRemoveRun ); + expect( list.runs.map( ( r ) => r.id ) ).toEqual( [1] ); + const error = new Error( 'main' ); + fire( runEvents.onUnhandledError, { title: 'Main', error } ); + expect( list.errorTitle ).toBe( 'Main' ); + expect( list.error ).toBe( error ); + console.log.mockRestore(); + } ); + + it( 'generateReport reports the active run with truncated stdout', () => { + const list = new RunList(); + runInAction( () => { + list.activeRun.stdout = 'abcdef'; + } ); + const report = list.generateReport( { maxStdoutLength: 3 } ); + expect( report.stdout ).toBe( '[3 more characters]...def' ); + expect( report.command ).toBe( list.activeRun.command ); + expect( list.generateReport().stdout ).toBe( 'abcdef' ); + } ); +} ); From 0cecc9957d6406458a6bd53ea0188f30b65246bd Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:42:38 +0100 Subject: [PATCH 12/54] Cover the input file, ASTRAL tree and store base on MobX 5 Replaces the 'shows an input file in its folder' test in showItemInFolder.test.js, now covered by InputFile.test.js. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/InputFile.test.js | 133 +++++++++++++++++++++++++ src/app/store/showItemInFolder.test.js | 11 -- 2 files changed, 133 insertions(+), 11 deletions(-) create mode 100644 src/app/store/InputFile.test.js diff --git a/src/app/store/InputFile.test.js b/src/app/store/InputFile.test.js new file mode 100644 index 00000000..570b0636 --- /dev/null +++ b/src/app/store/InputFile.test.js @@ -0,0 +1,133 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import AstralTree from './AstralTree'; +import InputFile from './InputFile'; +import StoreBase from './StoreBase'; + +let bridge; + +beforeEach( () => { + bridge = { + getVersion: jest.fn( () => Promise.resolve( '2.0.0' ) ), + openPath: jest.fn( () => Promise.resolve() ), + showItemInFolder: jest.fn( () => Promise.resolve() ), + }; + window.rendererBridge = bridge; +} ); + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const run = { id: 'run1', removeAstralTree: jest.fn() }; + +describe( 'StoreBase', () => { + it( 'initialises the version from the renderer bridge', async () => { + const store = new StoreBase(); + expect( store.version ).toBeUndefined(); + await Promise.resolve(); + expect( bridge.getVersion ).toHaveBeenCalledTimes( 1 ); + expect( store.version ).toBe( '2.0.0' ); + } ); + + it( 'subscribe registers a bridge listener and unlisten stops them all', () => { + const stopA = jest.fn(); + const stopB = jest.fn(); + bridge.onRunStdout = jest.fn( () => stopA ); + bridge.onRunStderr = jest.fn( () => stopB ); + const store = new StoreBase(); + const listener = () => {}; + store.subscribe( 'onRunStdout', listener ); + store.subscribe( 'onRunStderr', listener ); + expect( bridge.onRunStdout ).toHaveBeenCalledWith( listener ); + expect( store.eventStops ).toHaveLength( 2 ); + store.unlisten(); + expect( stopA ).toHaveBeenCalledTimes( 1 ); + expect( stopB ).toHaveBeenCalledTimes( 1 ); + expect( store.eventStops ).toHaveLength( 0 ); + } ); + + it( 'dispose stops the listeners', () => { + const stop = jest.fn(); + bridge.onRunStdout = () => stop; + const store = new StoreBase(); + store.subscribe( 'onRunStdout', () => {} ); + store.dispose(); + expect( stop ).toHaveBeenCalledTimes( 1 ); + } ); +} ); + +describe( 'InputFile', () => { + it( 'derives its parts from the path', () => { + const file = new InputFile( run, '/data/trees/astral.tre' ); + expect( file.id ).toBe( 'run1_/data/trees/astral.tre' ); + expect( file.name ).toBe( 'astral' ); + expect( file.dir ).toBe( '/data/trees' ); + expect( file.base ).toBe( 'astral.tre' ); + expect( file.filename ).toBe( 'astral.tre' ); + expect( file.ok ).toBe( true ); + } ); + + it( 'is not ok with an empty path', () => { + expect( new InputFile( run, '' ).ok ).toBe( false ); + } ); + + it( 'every computed updates when the path changes', () => { + const file = new InputFile( run, '/a/one.tre' ); + const keys = ['id', 'name', 'dir', 'base', 'filename', 'ok']; + const tracked = Object.fromEntries( keys.map( ( key ) => [key, track( () => file[key] )] ) ); + runInAction( () => { + file.path = ''; + } ); + runInAction( () => { + file.path = '/b/two.nwk'; + } ); + expect( tracked.id.seen ).toEqual( ['run1_/a/one.tre', 'run1_', 'run1_/b/two.nwk'] ); + expect( tracked.name.seen ).toEqual( ['one', '', 'two'] ); + expect( tracked.dir.seen ).toEqual( ['/a', '', '/b'] ); + expect( tracked.base.seen ).toEqual( ['one.tre', '', 'two.nwk'] ); + expect( tracked.filename.seen ).toEqual( ['one.tre', '', 'two.nwk'] ); + expect( tracked.ok.seen ).toEqual( [true, false, true] ); + keys.forEach( ( key ) => tracked[key].stop() ); + } ); + + it( 'openFile asks the bridge to open the path', async () => { + const file = new InputFile( run, '/a/one.tre' ); + await file.openFile(); + expect( bridge.openPath ).toHaveBeenCalledWith( '/a/one.tre' ); + } ); + + it( 'showFileInFolder asks the bridge to reveal the path', async () => { + const file = new InputFile( run, '/a/one.tre' ); + await file.showFileInFolder(); + expect( bridge.showItemInFolder ).toHaveBeenCalledWith( '/a/one.tre' ); + } ); + + it( 'initialises the version like any store', async () => { + const file = new InputFile( run, '/a/one.tre' ); + await Promise.resolve(); + expect( file.version ).toBe( '2.0.0' ); + } ); +} ); + +describe( 'AstralTree', () => { + it( 'remove removes the tree from its run', () => { + run.removeAstralTree.mockClear(); + new AstralTree( run, '/a/one.tre' ).remove(); + expect( run.removeAstralTree ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'inherits the input file computeds', () => { + const tree = new AstralTree( run, '/a/one.tre' ); + const { seen, stop } = track( () => tree.name ); + runInAction( () => { + tree.path = '/a/other.tre'; + } ); + expect( seen ).toEqual( ['one', 'other'] ); + stop(); + } ); +} ); diff --git a/src/app/store/showItemInFolder.test.js b/src/app/store/showItemInFolder.test.js index ffa6a094..ce6a727e 100644 --- a/src/app/store/showItemInFolder.test.js +++ b/src/app/store/showItemInFolder.test.js @@ -1,5 +1,4 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. -import InputFile from './InputFile'; import Run from './Run'; it( 'shows a tree file in its folder', async () => { @@ -13,16 +12,6 @@ it( 'shows a tree file in its folder', async () => { expect( showItemInFolder ).toHaveBeenCalledWith( '/data/start.nwk' ); } ); -it( 'shows an input file in its folder', async () => { - const file = new InputFile( { id: 7 }, '/data/primates.fasta' ); - const showItemInFolder = jest.fn( async () => {} ); - window.rendererBridge = { showItemInFolder }; - - await file.showFileInFolder(); - - expect( showItemInFolder ).toHaveBeenCalledWith( '/data/primates.fasta' ); -} ); - it( 'shows the concatenated alignment in its folder', async () => { const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; From 93389ca4289b65b8f151002bcedfdb0fc9ccf45b Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:42:57 +0100 Subject: [PATCH 13/54] Cover the alignment's option classes on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/AlignmentOptions.test.js | 218 +++++++++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 src/app/store/AlignmentOptions.test.js diff --git a/src/app/store/AlignmentOptions.test.js b/src/app/store/AlignmentOptions.test.js new file mode 100644 index 00000000..4d5ae669 --- /dev/null +++ b/src/app/store/AlignmentOptions.test.js @@ -0,0 +1,218 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import * as raxmlNgSettings from '../../settings/raxmlng'; + +beforeEach( () => { + window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; +} ); + +function setup() { + const run = new Run( { onError() {} }, 1 ); + run.addAlignments( [{ path: '/data/a.fasta' }] ); + const alignment = run.alignments[0]; + runInAction( () => { + run.binary.value = 'raxml-ng'; + alignment.dataType = 'nucleotide'; + } ); + return { run, alignment }; +} + +function useOtherBinary( run ) { + runInAction( () => { + run.binary.value = run.binary.options.find( + ( o ) => !o.value.includes( 'raxml-ng' ), + ).value; + } ); +} + +// Records every value a computed takes while the store changes. +function watch( read ) { + const seen = []; + const stop = autorun( () => seen.push( read() ) ); + return { seen, stop }; +} + +describe( 'substitution model', () => { + it( 'lists the options of the alignment data type', () => { + const { alignment } = setup(); + const { options } = raxmlNgSettings.modelOptions.nucleotide; + expect( alignment.substitutionModel.options ).toEqual( + options.map( ( value ) => ( { value, title: value } ) ), + ); + } ); + + it( 'has no options for an unknown data type', () => { + const { alignment } = setup(); + runInAction( () => { + alignment.dataType = undefined; + } ); + expect( alignment.substitutionModel.options ).toEqual( [] ); + } ); + + it( 'has no options and is not available without alignments', () => { + const { run, alignment } = setup(); + const model = alignment.substitutionModel; + const { seen, stop } = watch( () => [model.options.length > 0, model.notAvailable] ); + run.removeAlignment( alignment ); + stop(); + expect( seen ).toEqual( [[true, false], [false, true]] ); + } ); + + it( 'updates the options when the data type changes', () => { + const { alignment } = setup(); + const { seen, stop } = watch( () => alignment.substitutionModel.options.length ); + runInAction( () => { + alignment.dataType = 'protein'; + } ); + stop(); + expect( seen ).toEqual( [ + raxmlNgSettings.modelOptions.nucleotide.options.length, + raxmlNgSettings.modelOptions.protein.options.length, + ] ); + } ); + + it( 'uses its value as the command value and follows value changes', () => { + const { alignment } = setup(); + const model = alignment.substitutionModel; + const { seen, stop } = watch( () => model.cmdValue ); + model.setValue( 'HKY' ); + stop(); + expect( seen ).toEqual( ['', 'HKY'] ); + } ); + + it( 'puts the multistate number into the command value', () => { + const { alignment } = setup(); + runInAction( () => { + alignment.dataType = 'multistate'; + } ); + alignment.substitutionModel.setValue( 'MULTIx_GTR' ); + const { seen, stop } = watch( () => alignment.substitutionModel.cmdValue ); + alignment.multistateNumber.setValue( '5' ); + stop(); + expect( seen ).toEqual( ['MULTI_GTR', 'MULTI5_GTR'] ); + } ); +} ); + +describe( 'extra model parameters', () => { + const extras = [ + ['ngStationaryFrequencies', 'Stationary frequencies', '+F'], + ['ngInvariantSites', 'Proportion of invariant sites', '+I'], + ['ngRateHeterogeneity', 'Rate heterogeneity', '+G'], + ]; + + it.each( extras )( '%s starts at none and has an empty command value', ( key, title ) => { + const { alignment } = setup(); + const option = alignment[key]; + expect( option.title ).toBe( title ); + expect( option.value ).toBe( '' ); + expect( option.cmdValue ).toBe( '' ); + expect( option.options[0] ).toEqual( { value: '', title: 'none' } ); + expect( option.options.length ).toBeGreaterThan( 1 ); + } ); + + it.each( extras )( '%s command value follows its value', ( key, _title, value ) => { + const { alignment } = setup(); + const option = alignment[key]; + const { seen, stop } = watch( () => option.cmdValue ); + option.setValue( value ); + option.setValue( '' ); + stop(); + expect( seen ).toEqual( ['', value, ''] ); + } ); + + it.each( extras )( '%s is only available with alignments and raxml-ng', ( key ) => { + const { run, alignment } = setup(); + const option = alignment[key]; + const { seen, stop } = watch( () => [option.notAvailable, option.options.length > 0] ); + useOtherBinary( run ); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + run.removeAlignment( alignment ); + stop(); + expect( seen ).toEqual( [ + [false, true], + [true, true], + [false, true], + [true, false], + ] ); + } ); + + it( 'ascertainment bias defaults to no correction', () => { + const { alignment } = setup(); + const asc = alignment.ngAscertainmentBias; + expect( asc.value ).toBe( '' ); + expect( asc.cmdValue ).toBe( '' ); + expect( asc.options ).toEqual( [ + { value: '', title: 'No correction' }, + { value: '+ASC_LEWIS', title: "Lewis' method" }, + ] ); + const { seen, stop } = watch( () => asc.cmdValue ); + asc.setValue( '+ASC_LEWIS' ); + stop(); + expect( seen ).toEqual( ['', '+ASC_LEWIS'] ); + } ); + + it( 'ascertainment bias is unavailable with invariant sites, without raxml-ng or without alignments', () => { + const { run, alignment } = setup(); + const asc = alignment.ngAscertainmentBias; + const { seen, stop } = watch( () => asc.notAvailable ); + runInAction( () => { + alignment.hasInvariantSites = true; + } ); + runInAction( () => { + alignment.hasInvariantSites = false; + } ); + useOtherBinary( run ); + stop(); + expect( seen ).toEqual( [false, true, false, true] ); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + run.removeAlignment( alignment ); + expect( asc.notAvailable ).toBe( true ); + } ); +} ); + +describe( 'multistate number', () => { + it( 'starts empty with an integer placeholder', () => { + const { alignment } = setup(); + expect( alignment.multistateNumber.value ).toBe( '' ); + expect( alignment.multistateNumber.placeholder ).toBe( 'Integer' ); + } ); + + it( 'has an error for a missing value', () => { + const { alignment } = setup(); + expect( alignment.multistateNumber.error ).toBe( true ); + } ); + + it( 'has an error for a non-integer value', () => { + const { alignment } = setup(); + alignment.multistateNumber.setValue( '2.5' ); + expect( alignment.multistateNumber.error ).toBe( true ); + alignment.multistateNumber.setValue( 'abc' ); + expect( alignment.multistateNumber.error ).toBe( true ); + } ); + + it( 'has no error for a valid value and follows value changes', () => { + const { alignment } = setup(); + const { seen, stop } = watch( () => alignment.multistateNumber.error ); + alignment.multistateNumber.setValue( '4' ); + stop(); + expect( seen ).toEqual( [true, false] ); + } ); + + it( 'is available only for multistate data with raxml-ng', () => { + const { run, alignment } = setup(); + const number = alignment.multistateNumber; + const { seen, stop } = watch( () => number.notAvailable ); + runInAction( () => { + alignment.dataType = 'multistate'; + } ); + useOtherBinary( run ); + stop(); + expect( seen ).toEqual( [true, false, true] ); + } ); +} ); From d4a69e1cb8d29652d4ab7e50ca7835281c78f298 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:43:01 +0100 Subject: [PATCH 14/54] Cover the final alignment on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/finalAlignment.test.js | 206 +++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 src/app/store/finalAlignment.test.js diff --git a/src/app/store/finalAlignment.test.js b/src/app/store/finalAlignment.test.js new file mode 100644 index 00000000..63b46c30 --- /dev/null +++ b/src/app/store/finalAlignment.test.js @@ -0,0 +1,206 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +// The final alignment reads its run's alignments; build a real run with +// sequences set directly, as writeConcatenatedAlignment.test.js does. +function makeRun( alignments ) { + const run = new Run( {}, 7 ); + // outputNameAvailable is a promisedComputed that only reads inside a reaction; pin it. + run.outputNameAvailable = { get: () => ( { outputNameUnused: 'out' } ) }; + window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; + run.addAlignments( alignments.map( ( { path } ) => ( { path } ) ) ); + runInAction( () => { + run.outputDir = '/out'; + alignments.forEach( ( spec, i ) => { + const a = run.alignments[i]; + a.sequences = spec.sequences; + a.length = spec.length; + a.dataType = spec.dataType || 'nucleotide'; + a.hasInvariantSites = !!spec.hasInvariantSites; + } ); + } ); + return run; +} + +const A = { + path: '/data/a.fasta', + length: 2, + sequences: [ + { taxon: 'Homo', code: 'AT' }, + { taxon: 'Mus', code: 'GC' }, + ], +}; +const B = { + path: '/data/b.fasta', + length: 3, + dataType: 'protein', + sequences: [ + { taxon: 'Mus', code: 'AAA' }, + { taxon: 'Rat', code: 'CCC' }, + ], +}; + +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +describe( 'FinalAlignment computeds', () => { + it( 'uses the single alignment file as is', () => { + const { finalAlignment: f } = makeRun( [A] ); + expect( f.numAlignments ).toBe( 1 ); + expect( f.filename ).toBe( 'a.fasta' ); + expect( f.dir ).toBe( '/data' ); + expect( f.path ).toBe( '/data/a.fasta' ); + expect( f.length ).toBe( 2 ); + expect( f.dataType ).toBe( 'nucleotide' ); + expect( f.partitionFilePath ).toBe( '' ); + } ); + + it( 'names a concatenated file in the output dir', () => { + const run = makeRun( [A, B] ); + const f = run.finalAlignment; + expect( f.numAlignments ).toBe( 2 ); + expect( f.filename ).toBe( `RAxML_${run.outputNameSafe}_concat.txt` ); + expect( f.dir ).toBe( '/out' ); + expect( f.path ).toBe( `/out/${f.filename}` ); + expect( f.length ).toBe( 5 ); + expect( f.partitionFilePath ).toBe( + `/out/RAxML_${run.outputNameSafe}_concat.part.txt`, + ); + expect( f.partitionFileContent ).toBe( f.partition.text ); + expect( f.partitionFileContent ).not.toBe( '' ); + } ); + + it( 'reports no model flag without alignments, else the first one', () => { + expect( makeRun( [] ).finalAlignment.modelFlagName ).toBe( 'none' ); + const run = makeRun( [A, B] ); + expect( run.finalAlignment.modelFlagName ).toBe( + run.alignments[0].modelFlagName, + ); + } ); + + it( 'combines data types and invariant sites over alignments', () => { + const run = makeRun( [A, B] ); + expect( run.finalAlignment.dataType ).toBe( 'mixed' ); + expect( run.finalAlignment.hasInvariantSites ).toBe( false ); + runInAction( () => { + run.alignments[1].hasInvariantSites = true; + } ); + expect( run.finalAlignment.hasInvariantSites ).toBe( true ); + } ); +} ); + +describe( 'FinalAlignment observables', () => { + it( 'fillTaxonGapsWithEmptySeqeunces switches taxons between union and intersection', () => { + const f = makeRun( [A, B] ).finalAlignment; + const { seen, stop } = track( () => [f.taxons, f.numSequences] ); + expect( seen[0] ).toEqual( [['Homo', 'Mus', 'Rat'], 3] ); + f.setFillTaxonGapsWithEmptySeqeunces( false ); + expect( seen[1] ).toEqual( [['Mus'], 1] ); + runInAction( () => { + f.fillTaxonGapsWithEmptySeqeunces = true; + } ); + expect( seen[2] ).toEqual( [['Homo', 'Mus', 'Rat'], 3] ); + stop(); + } ); + + it( 'parsingComplete is seen by a reaction', () => { + const f = makeRun( [A] ).finalAlignment; + const { seen, stop } = track( () => f.parsingComplete ); + runInAction( () => { + f.parsingComplete = false; + } ); + expect( seen ).toEqual( [true, false] ); + stop(); + } ); +} ); + +describe( 'FinalAlignment actions', () => { + function stubBridge() { + const bridge = { + writeFile: jest.fn( async () => {} ), + openPath: jest.fn( async () => {} ), + showItemInFolder: jest.fn( async () => {} ), + }; + window.rendererBridge = bridge; + return bridge; + } + + beforeEach( () => { + jest.spyOn( console, 'log' ).mockImplementation( () => {} ); + jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + } ); + afterEach( () => jest.restoreAllMocks() ); + + it( 'writeConcatenatedAlignment fills gaps or drops taxons', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + f.setFillTaxonGapsWithEmptySeqeunces( false ); + await f.writeConcatenatedAlignment(); + expect( bridge.writeFile ).toHaveBeenCalledWith( f.path, '>Mus\nGCAAA' ); + } ); + + it( 'writeConcatenatedAlignment rethrows a write failure', async () => { + const f = makeRun( [A] ).finalAlignment; + stubBridge().writeFile.mockRejectedValue( new Error( 'disk' ) ); + await expect( f.writeConcatenatedAlignment() ).rejects.toThrow( 'disk' ); + } ); + + it( 'writePartition writes the partition text and rethrows failures', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.writePartition(); + expect( bridge.writeFile ).toHaveBeenCalledWith( + f.partitionFilePath, + f.partitionFileContent, + ); + bridge.writeFile.mockRejectedValue( new Error( 'nope' ) ); + await expect( f.writePartition() ).rejects.toThrow( 'nope' ); + } ); + + it( 'writeConcatenatedAlignmentAndPartition writes both files', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.writeConcatenatedAlignmentAndPartition(); + expect( bridge.writeFile.mock.calls.map( ( c ) => c[0] ) ).toEqual( [ + f.path, + f.partitionFilePath, + ] ); + } ); + + it( 'openFile writes then opens the alignment', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.openFile(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 1 ); + expect( bridge.openPath ).toHaveBeenCalledWith( f.path ); + } ); + + it( 'openPartition writes both files then opens the partition', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.openPartition(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 2 ); + expect( bridge.openPath ).toHaveBeenCalledWith( f.partitionFilePath ); + } ); + + it( 'showFileInFolder writes then reveals the alignment', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.showFileInFolder(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 1 ); + expect( bridge.showItemInFolder ).toHaveBeenCalledWith( f.path ); + } ); + + it( 'openFolder writes both files then reveals the folder', async () => { + const f = makeRun( [A, B] ).finalAlignment; + const bridge = stubBridge(); + await f.openFolder(); + expect( bridge.writeFile ).toHaveBeenCalledTimes( 2 ); + expect( bridge.showItemInFolder ).toHaveBeenCalledWith( f.dir ); + } ); +} ); From 78ec9842e7194e47572f80e928e1e2b6a8e95c89 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:43:51 +0100 Subject: [PATCH 15/54] Cover the part and its options on MobX 5 (#130) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Part.test.js | 527 +++++++++++++++++++++++++++++++++++++ 1 file changed, 527 insertions(+) create mode 100644 src/app/store/Part.test.js diff --git a/src/app/store/Part.test.js b/src/app/store/Part.test.js new file mode 100644 index 00000000..057e58f8 --- /dev/null +++ b/src/app/store/Part.test.js @@ -0,0 +1,527 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Alignment from './Alignment'; +import Run from './Run'; +import { + CODON_NONE, + CODON_SPECIFIC, + CODON_THIRD, + CodonModels, +} from './PartOptions'; + +// The alignment subscribes to bridge events and parses its file on creation. +beforeEach( () => { + window.rendererBridge = { + parseAlignment: () => new Promise( () => {} ), + onModelSelectionSuccess: () => () => {}, + onModelSelectionFailure: () => () => {}, + onRunStdout: () => () => {}, + onRunStderr: () => () => {}, + }; +} ); + +// The run defaults to raxml-ng, whose partition type is the model command; classic raxml uses the data type. +function makeAlignment( { dataType = 'dna', length = 100, ng = false } = {} ) { + const run = new Run( {}, 1 ); + const alignment = new Alignment( run, '/data/a.fasta' ); + runInAction( () => { + if ( !ng ) { + run.binary.value = run.binary.options + .map( ( o ) => o.value ) + .find( ( v ) => /raxml/i.test( v ) && !v.includes( 'raxml-ng' ) ); + } + alignment.dataType = dataType; + alignment.length = length; + } ); + return alignment; +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const part = ( alignment, values ) => { + const { partition } = alignment; + runInAction( () => { + Object.entries( values ).forEach( ( [key, value] ) => { + partition.partToAdd[key].value = value; + } ); + } ); + return partition.partToAdd; +}; + +describe( 'Part', () => { + it( 'starts from the alignment: default part covers all sites', () => { + const { partition } = makeAlignment(); + expect( partition.defaultPartition.values ).toEqual( { + type: 'DNA', + aaType: 'BLOSUM62', + name: 'part_1', + start: 1, + end: 100, + codon: CODON_NONE, + } ); + expect( partition.partToAdd.end.value ).toBe( 1 ); + } ); + + it( 'typePadded pads the final type to twelve characters', () => { + const alignment = makeAlignment(); + const { typePadded } = alignment.partition.partToAdd; + expect( typePadded ).toBe( 'DNA, ' ); + expect( typePadded ).toHaveLength( 12 ); + } ); + + it( 'a reaction sees typePadded change with the alignment data type', () => { + const alignment = makeAlignment(); + const { seen, stop } = track( () => alignment.partition.partToAdd.typePadded ); + runInAction( () => { + alignment.dataType = 'binary'; + } ); + expect( seen ).toEqual( ['DNA, ', 'BIN, '] ); + stop(); + } ); + + it( 'typePadded uses the model command under raxml-ng', () => { + const alignment = makeAlignment( { ng: true } ); + const { seen, stop } = track( () => alignment.partition.partToAdd.typePadded ); + runInAction( () => { + alignment.ngInvariantSites.value = true; + } ); + expect( seen[0] ).toBe( ', ' ); + expect( seen ).toHaveLength( 2 ); + expect( seen[1] ).toBe( `${alignment.ngSubstitutionModelCmd},`.padEnd( 12 ) ); + stop(); + } ); + + it( 'transform without codons writes one row', () => { + const p = part( makeAlignment(), { name: 'g', start: 3, end: 9 } ); + expect( p.transform() ).toBe( 'DNA, g = 3-9' ); + expect( p.transform( 10, 'x_' ) ).toBe( 'DNA, x_g = 13-19' ); + } ); + + it( 'transform with codon specific writes three rows', () => { + const p = part( makeAlignment(), { + name: 'g', + start: 1, + end: 9, + codon: CODON_SPECIFIC, + } ); + expect( p.transform() ).toBe( + [ + 'DNA, g_codon1 = 1-9\\3', + 'DNA, g_codon2 = 2-9\\3', + 'DNA, g_codon3 = 3-9\\3', + ].join( '\n' ), + ); + expect( p.transform( 100, 'p_' ).split( '\n' )[1] ).toBe( + 'DNA, p_g_codon2 = 102-109\\3', + ); + } ); + + it( 'transform with third codon writes the first two codons and the third', () => { + const p = part( makeAlignment(), { + name: 'g', + start: 1, + end: 9, + codon: CODON_THIRD, + } ); + expect( p.transform() ).toBe( + [ + 'DNA, g_codon1and2 = 1-9\\3, 2-9\\3', + 'DNA, g_codon3 = 3-9\\3', + ].join( '\n' ), + ); + } ); + + it( 'transform throws on an unknown codon model', () => { + const p = part( makeAlignment(), { codon: 'Bogus' } ); + expect( () => p.transform() ).toThrow( 'Codon type Bogus not recognized.' ); + } ); + + it( 'text is the transform and a reaction sees it change', () => { + const alignment = makeAlignment(); + const p = alignment.partition.partToAdd; + const { seen, stop } = track( () => p.text ); + expect( p.text ).toBe( p.transform() ); + runInAction( () => { + p.name.value = 'other'; + } ); + expect( seen ).toEqual( ['DNA, part_1 = 1-1', 'DNA, other = 1-1'] ); + stop(); + } ); + + it( 'parse accepts a row and returns nothing', () => { + const p = makeAlignment().partition.partToAdd; + expect( p.parse( 'DNA, g = 1-9' ) ).toBeUndefined(); + } ); + + it( 'values collects every option value and tracks changes', () => { + const p = makeAlignment().partition.partToAdd; + const { seen, stop } = track( () => p.values.start ); + runInAction( () => { + p.start.value = 4; + } ); + expect( seen ).toEqual( [1, 4] ); + expect( p.values ).toEqual( { + type: 'DNA', + aaType: 'BLOSUM62', + name: 'part_1', + start: 4, + end: 1, + codon: CODON_NONE, + } ); + stop(); + } ); + + it( 'clone copies the values into an independent part', () => { + const p = part( makeAlignment(), { name: 'g', start: 2, end: 8 } ); + const copy = p.clone(); + expect( copy ).not.toBe( p ); + expect( copy.values ).toEqual( p.values ); + expect( copy.partition ).toBe( p.partition ); + runInAction( () => { + p.name.value = 'changed'; + } ); + expect( copy.name.value ).toBe( 'g' ); + } ); +} ); + +describe( 'part options', () => { + it( 'PartType.finalValue follows the alignment partition type', () => { + const alignment = makeAlignment(); + const { type } = alignment.partition.partToAdd; + const { seen, stop } = track( () => type.finalValue ); + runInAction( () => { + alignment.dataType = 'multistate'; + } ); + expect( seen ).toEqual( ['DNA', 'MULTI'] ); + stop(); + } ); + + it( 'PartType.finalValue is the amino acid model for protein', () => { + const alignment = makeAlignment( { dataType: 'protein' } ); + const { type, aaType } = alignment.partition.partToAdd; + const { seen, stop } = track( () => type.finalValue ); + runInAction( () => { + aaType.value = 'WAG'; + } ); + expect( seen ).toEqual( ['BLOSUM62', 'WAG'] ); + stop(); + } ); + + it( 'PartType.finalValue is the own value for a mixed alignment', () => { + const alignment = makeAlignment( { dataType: 'mixed' } ); + const { type } = alignment.partition.partToAdd; + const { seen, stop } = track( () => type.finalValue ); + runInAction( () => { + type.value = 'BIN'; + } ); + expect( seen ).toEqual( [expect.anything(), 'BIN'] ); + expect( type.finalValue ).toBe( 'BIN' ); + stop(); + } ); + + it( 'PartType.finalValue is the amino acid model when the part itself is protein', () => { + const alignment = makeAlignment( { dataType: 'mixed' } ); + const { type } = alignment.partition.partToAdd; + runInAction( () => { + type.value = 'protein'; + } ); + expect( type.finalValue ).toBe( 'BLOSUM62' ); + } ); + + it( 'PartType.options and notAvailable follow the alignment data type', () => { + const alignment = makeAlignment(); + const { type } = alignment.partition.partToAdd; + const seen = track( () => [type.options.map( ( o ) => o.value ), type.notAvailable] ); + expect( seen.seen[0] ).toEqual( [['dna'], true] ); + runInAction( () => { + alignment.dataType = 'mixed'; + } ); + expect( seen.seen[1] ).toEqual( [['DNA', 'BIN', 'MULTI', 'protein'], false] ); + runInAction( () => { + alignment.dataType = ''; + } ); + expect( type.options.map( ( o ) => o.title ) ).toEqual( [ + 'DNA', + 'BIN', + 'MULTI', + 'protein', + ] ); + expect( type.notAvailable ).toBe( true ); + seen.stop(); + } ); + + it( 'PartType accepts only strings', () => { + const { type } = makeAlignment().partition.partToAdd; + type.setValue( 5 ); + expect( type.value ).toBe( '5' ); + type.setValue( {} ); + expect( type.value ).toBe( '5' ); + } ); + + it( 'PartAAType offers the amino acid matrices and is available for protein only', () => { + const alignment = makeAlignment(); + const { aaType } = alignment.partition.partToAdd; + const { seen, stop } = track( () => aaType.notAvailable ); + expect( aaType.options.length ).toBeGreaterThan( 1 ); + expect( aaType.options[0] ).toEqual( { + value: aaType.options[0].title, + title: aaType.options[0].value, + } ); + expect( aaType.options.map( ( o ) => o.value ) ).toContain( 'WAG' ); + runInAction( () => { + alignment.dataType = 'protein'; + } ); + expect( seen ).toEqual( [true, false] ); + stop(); + } ); + + it( 'PartName is always available and keeps its value as a string', () => { + const { name } = makeAlignment().partition.partToAdd; + expect( name.notAvailable ).toBe( false ); + name.setValue( 'gene' ); + expect( name.value ).toBe( 'gene' ); + } ); + + it( 'PartStart is always available, disabled and stores invalid input as given', () => { + const { start } = makeAlignment().partition.partToAdd; + expect( start.notAvailable ).toBe( false ); + expect( start.disabled ).toBe( true ); + start.setValue( '7' ); + expect( start.value ).toBe( 7 ); + start.setValue( 'abc' ); + expect( start.value ).toBe( 'abc' ); + } ); + + it( 'PartEnd.min follows the start and the codon model', () => { + const alignment = makeAlignment(); + const { start, end, codon } = alignment.partition.partToAdd; + const { seen, stop } = track( () => end.min ); + runInAction( () => { + start.value = 5; + } ); + runInAction( () => { + codon.value = CODON_SPECIFIC; + } ); + expect( seen ).toEqual( [1, 5, 7] ); + stop(); + } ); + + it( 'PartEnd.max follows the alignment length', () => { + const alignment = makeAlignment(); + const { end } = alignment.partition.partToAdd; + const { seen, stop } = track( () => end.max ); + runInAction( () => { + alignment.length = 250; + } ); + expect( seen ).toEqual( [100, 250] ); + expect( end.notAvailable ).toBe( false ); + stop(); + } ); + + it( 'PartEnd reports an error outside [min, max] and a reaction sees it', () => { + const alignment = makeAlignment(); + const { end } = alignment.partition.partToAdd; + const { seen, stop } = track( () => end.haveError ); + end.setValue( 50 ); + expect( end.haveError ).toBe( false ); + expect( end.errorMessage ).toBe( '' ); + end.setValue( 101 ); + expect( end.haveError ).toBe( true ); + expect( end.errorMessage ).toBe( 'Must be in interval [1, 100]' ); + runInAction( () => { + alignment.length = 200; + } ); + expect( end.haveError ).toBe( false ); + expect( seen ).toEqual( [false, true, false] ); + stop(); + } ); + + it( 'PartCodon offers the codon models and is available for a DNA part to add only', () => { + const alignment = makeAlignment(); + const { codon, type } = alignment.partition.partToAdd; + const { seen, stop } = track( () => codon.notAvailable ); + expect( codon.options.map( ( o ) => o.value ) ).toEqual( CodonModels ); + expect( seen ).toEqual( [false] ); + runInAction( () => { + type.value = 'BIN'; + } ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); +} ); + +describe( 'Partition', () => { + const add = ( partition, values ) => { + runInAction( () => { + Object.entries( values ).forEach( ( [key, value] ) => { + partition.partToAdd[key].value = value; + } ); + } ); + partition.addPart(); + }; + + it( 'is the default partition until a part is added', () => { + const alignment = makeAlignment(); + const { partition } = alignment; + expect( partition.isDefault ).toBe( true ); + expect( partition.isMixed ).toBe( false ); + expect( partition.maxEndValue ).toBe( 100 ); + expect( partition.currentEndValue ).toBe( 100 ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.progress ).toBe( 100 ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-100' ); + expect( partition.transform( 5, 'x_' ) ).toBe( 'DNA, x_part_1 = 6-105' ); + } ); + + it( 'isMixed follows the alignment data type', () => { + const alignment = makeAlignment(); + const { seen, stop } = track( () => alignment.partition.isMixed ); + runInAction( () => { + alignment.dataType = 'mixed'; + } ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'addPart appends a copy and moves partToAdd past it', () => { + const { partition } = makeAlignment(); + const { seen, stop } = track( () => [partition.isDefault, partition.currentEndValue] ); + add( partition, { end: 40, codon: CODON_SPECIFIC } ); + expect( partition.parts ).toHaveLength( 1 ); + expect( partition.parts[0].values ).toMatchObject( { + name: 'part_1', + start: 1, + end: 40, + codon: CODON_SPECIFIC, + } ); + expect( partition.isDefault ).toBe( false ); + expect( partition.currentEndValue ).toBe( 40 ); + expect( partition.progress ).toBe( 40 ); + expect( partition.isComplete ).toBe( false ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.partToAdd.codon.value ).toBe( CODON_NONE ); + expect( partition.partToAdd.start.value ).toBe( 41 ); + expect( partition.partToAdd.end.value ).toBe( 41 ); + expect( partition.partToAdd.name.value ).toBe( 'part_2' ); + expect( seen ).toEqual( [[true, 100], [false, 40]] ); + stop(); + } ); + + it( 'addPart appends _1 to a name without a trailing number', () => { + const { partition } = makeAlignment(); + add( partition, { name: 'gene', end: 10 } ); + expect( partition.partToAdd.name.value ).toBe( 'gene_1' ); + } ); + + it( 'addPart completing the alignment leaves partToAdd and disables adding', () => { + const { partition } = makeAlignment(); + const { seen, stop } = track( () => partition.addPartDisabled ); + add( partition, { end: 60 } ); + add( partition, { end: 100 } ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( true ); + expect( partition.progress ).toBe( 100 ); + expect( partition.addPartDisabled ).toBe( true ); + expect( partition.partToAdd.name.value ).toBe( 'part_2' ); + expect( partition.partToAdd.start.value ).toBe( 61 ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'text and transform join the rows of all parts', () => { + const { partition } = makeAlignment(); + add( partition, { end: 40 } ); + add( partition, { end: 100 } ); + const expected = 'DNA, part_1 = 1-40\nDNA, part_2 = 41-100'; + expect( partition.text ).toBe( expected ); + expect( partition.transform() ).toBe( expected ); + expect( partition.transform( 10, 'a_' ) ).toBe( + 'DNA, a_part_1 = 11-50\nDNA, a_part_2 = 51-110', + ); + } ); + + it( 'haveError and errorMessage report the end position of the part to add', () => { + const { partition } = makeAlignment(); + const { seen, stop } = track( () => partition.errorMessage ); + partition.partToAdd.end.setValue( 500 ); + expect( partition.haveError ).toBe( true ); + expect( partition.addPartDisabled ).toBe( true ); + expect( partition.errorMessage ).toBe( + 'End position error: Must be in interval [1, 100]', + ); + partition.partToAdd.end.setValue( 20 ); + expect( partition.haveError ).toBe( false ); + expect( seen ).toEqual( [ + '', + 'End position error: Must be in interval [1, 100]', + '', + ] ); + stop(); + } ); + + it( 'reset drops the parts and restores partToAdd', () => { + const { partition } = makeAlignment(); + add( partition, { end: 40 } ); + partition.reset(); + expect( partition.parts ).toHaveLength( 0 ); + expect( partition.isDefault ).toBe( true ); + expect( partition.partToAdd.name.value ).toBe( 'part_1' ); + expect( partition.partToAdd.start.value ).toBe( 1 ); + expect( partition.partToAdd.end.value ).toBe( 1 ); + } ); + + it( 'reset without parts changes nothing', () => { + const { partition } = makeAlignment(); + runInAction( () => { + partition.partToAdd.name.value = 'keep'; + } ); + partition.reset(); + expect( partition.partToAdd.name.value ).toBe( 'keep' ); + } ); + + it( 'the default part end follows the alignment length once', () => { + const alignment = makeAlignment( { length: 0 } ); + const { partition } = alignment; + runInAction( () => { + alignment.length = 80; + } ); + expect( partition.defaultPartition.end.value ).toBe( 80 ); + runInAction( () => { + alignment.length = 90; + } ); + expect( partition.defaultPartition.end.value ).toBe( 80 ); + } ); + + it( 'the default part end stays put for a mixed alignment', () => { + const alignment = makeAlignment( { dataType: 'mixed', length: 0 } ); + runInAction( () => { + alignment.length = 80; + } ); + expect( alignment.partition.defaultPartition.end.value ).toBe( 0 ); + } ); + + it( 'the part types follow the alignment data type and matrix', () => { + const alignment = makeAlignment(); + const { partition } = alignment; + runInAction( () => { + alignment.dataType = 'binary'; + } ); + expect( partition.partToAdd.type.value ).toBe( 'BIN' ); + expect( partition.defaultPartition.type.value ).toBe( 'BIN' ); + runInAction( () => { + alignment.dataType = 'protein'; + alignment.aaMatrixName = 'WAG'; + } ); + expect( partition.partToAdd.type.value ).toBe( 'protein' ); + expect( partition.defaultPartition.type.value ).toBe( 'protein' ); + expect( partition.defaultPartition.aaType.value ).toBe( 'WAG' ); + expect( partition.partToAdd.aaType.value ).toBe( 'WAG' ); + } ); +} ); From 70c70e03c373b603750b2be30e87af29248ad8b5 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:43:57 +0100 Subject: [PATCH 16/54] Cover the partition and final partition on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Partition.test.js | 334 ++++++++++++++++++++++++++++++++ 1 file changed, 334 insertions(+) create mode 100644 src/app/store/Partition.test.js diff --git a/src/app/store/Partition.test.js b/src/app/store/Partition.test.js new file mode 100644 index 00000000..8f69329a --- /dev/null +++ b/src/app/store/Partition.test.js @@ -0,0 +1,334 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Alignment from './Alignment'; +import RunList from './RunList'; +import { runEvents } from './StoreBase'; + +// The run and alignment subscribe to bridge events; a no-op bridge is enough here. +function stubBridge() { + const bridge = { cancelRun: jest.fn(), getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = () => () => {}; + } + window.rendererBridge = bridge; +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +let run; + +// Adds an alignment to the run the way loading a file would, minus the file. +function addAlignment( { dataType = 'nucleotide', length = 100 } = {} ) { + const alignment = new Alignment( run, `/data/aln${run.alignments.length}.fasta` ); + runInAction( () => { + alignment.dataType = dataType; + alignment.length = length; + run.alignments.push( alignment ); + } ); + return alignment; +} + +// Sets the end of the part to add, then adds it. +function addPartEndingAt( partition, end ) { + runInAction( () => { + partition.partToAdd.end.value = end; + } ); + partition.addPart(); +} + +beforeEach( () => { + stubBridge(); + run = new RunList().activeRun; + runInAction( () => { + run.binary.value = 'raxmlHPC'; + } ); +} ); + +describe( 'Partition', () => { + it( 'starts as the default partition covering the alignment', () => { + const { partition } = addAlignment( { length: 100 } ); + expect( partition.parts ).toEqual( [] ); + expect( partition.isDefault ).toBe( true ); + expect( partition.isMixed ).toBe( false ); + expect( partition.maxEndValue ).toBe( 100 ); + expect( partition.currentEndValue ).toBe( 100 ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.progress ).toBe( 100 ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-100' ); + } ); + + it( 'the default partition follows the alignment length and data type', () => { + const alignment = new Alignment( run, '/data/a.fasta' ); + const { partition } = alignment; + const { seen, stop } = track( () => partition.text ); + runInAction( () => { + alignment.dataType = 'nucleotide'; + alignment.length = 250; + } ); + expect( partition.defaultPartition.end.value ).toBe( 250 ); + expect( partition.defaultPartition.type.value ).toBe( 'DNA' ); + expect( partition.partToAdd.type.value ).toBe( 'DNA' ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-250' ); + runInAction( () => { + alignment.dataType = 'binary'; + } ); + expect( partition.defaultPartition.type.value ).toBe( 'BIN' ); + expect( partition.partToAdd.type.value ).toBe( 'BIN' ); + expect( seen[seen.length - 1] ).toBe( 'BIN, part_1 = 1-250' ); + stop(); + } ); + + it( 'a protein alignment takes the amino acid matrix as the model', () => { + const alignment = new Alignment( run, '/data/a.fasta' ); + const { partition } = alignment; + runInAction( () => { + alignment.dataType = 'protein'; + alignment.aaMatrixName = 'WAG'; + alignment.length = 30; + } ); + expect( partition.defaultPartition.type.value ).toBe( 'protein' ); + expect( partition.defaultPartition.aaType.value ).toBe( 'WAG' ); + expect( partition.partToAdd.aaType.value ).toBe( 'WAG' ); + expect( partition.text ).toBe( 'WAG, part_1 = 1-30' ); + } ); + + it( 'a mixed alignment keeps the default partition end', () => { + const alignment = new Alignment( run, '/data/a.fasta' ); + const before = alignment.partition.defaultPartition.end.value; + runInAction( () => { + alignment.dataType = 'mixed'; + alignment.length = 80; + } ); + expect( alignment.partition.isMixed ).toBe( true ); + expect( alignment.partition.defaultPartition.end.value ).toBe( before ); + } ); + + it( 'adding a part appends it and prepares the next start and a fresh name', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => partition.parts.length ); + addPartEndingAt( partition, 40 ); + expect( partition.parts.map( ( p ) => p.values ) ).toEqual( [ + { type: 'DNA', aaType: 'BLOSUM62', name: 'part_1', start: 1, end: 40, codon: 'None' }, + ] ); + expect( partition.partToAdd.start.value ).toBe( 41 ); + expect( partition.partToAdd.end.value ).toBe( 41 ); + expect( partition.partToAdd.name.value ).toBe( 'part_2' ); + expect( partition.partToAdd.codon.value ).toBe( 'None' ); + expect( seen ).toEqual( [0, 1] ); + stop(); + } ); + + it( 'adding a part to a name without digits appends _1', () => { + const { partition } = addAlignment( { length: 100 } ); + runInAction( () => { + partition.partToAdd.name.value = 'gene'; + } ); + addPartEndingAt( partition, 10 ); + expect( partition.partToAdd.name.value ).toBe( 'gene_1' ); + } ); + + it( 'adding the last part completes the partition', () => { + const { partition } = addAlignment( { length: 100 } ); + addPartEndingAt( partition, 60 ); + const { seen, stop } = track( () => partition.addPartDisabled ); + addPartEndingAt( partition, 100 ); + expect( partition.isDefault ).toBe( false ); + expect( partition.currentEndValue ).toBe( 100 ); + expect( partition.isComplete ).toBe( true ); + expect( partition.nonDefaultPartitionComplete ).toBe( true ); + expect( partition.progress ).toBe( 100 ); + expect( partition.addPartDisabled ).toBe( true ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'progress, currentEndValue and text follow the parts', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => [ + partition.currentEndValue, + partition.progress, + partition.isDefault, + ] ); + addPartEndingAt( partition, 25 ); + expect( partition.isComplete ).toBe( false ); + expect( partition.nonDefaultPartitionComplete ).toBe( false ); + expect( partition.text ).toBe( 'DNA, part_1 = 1-25' ); + expect( seen ).toEqual( [ + [100, 100, true], + [25, 25, false], + ] ); + addPartEndingAt( partition, 100 ); + expect( partition.text ).toBe( + 'DNA, part_1 = 1-25\nDNA, part_2 = 26-100', + ); + stop(); + } ); + + it( 'a codon specific part expands to one row per codon', () => { + const { partition } = addAlignment( { length: 99 } ); + runInAction( () => { + partition.partToAdd.codon.value = 'Codon specific'; + } ); + addPartEndingAt( partition, 99 ); + expect( partition.text ).toBe( + [ + 'DNA, part_1_codon1 = 1-99\\3', + 'DNA, part_1_codon2 = 2-99\\3', + 'DNA, part_1_codon3 = 3-99\\3', + ].join( '\n' ), + ); + expect( partition.partToAdd.codon.value ).toBe( 'None' ); + } ); + + it( 'transform applies the offset and prefix to the default and added parts', () => { + const { partition } = addAlignment( { length: 100 } ); + expect( partition.transform( 10, 'x_' ) ).toBe( 'DNA, x_part_1 = 11-110' ); + addPartEndingAt( partition, 30 ); + expect( partition.transform( 10, 'x_' ) ).toBe( 'DNA, x_part_1 = 11-40' ); + expect( partition.transform() ).toBe( 'DNA, part_1 = 1-30' ); + } ); + + it( 'haveError, errorMessage and addPartDisabled follow the end of the part to add', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => [ + partition.haveError, + partition.errorMessage, + partition.addPartDisabled, + ] ); + expect( seen[0] ).toEqual( [false, '', false] ); + runInAction( () => { + partition.partToAdd.end.value = 500; + } ); + expect( partition.haveError ).toBe( true ); + expect( partition.errorMessage ).toBe( + 'End position error: Must be in interval [1, 100]', + ); + expect( partition.addPartDisabled ).toBe( true ); + runInAction( () => { + partition.partToAdd.end.value = 50; + } ); + expect( seen[seen.length - 1] ).toEqual( [false, '', false] ); + stop(); + } ); + + it( 'a reaction sees parts set directly', () => { + const { partition } = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => [partition.isDefault, partition.text] ); + runInAction( () => { + partition.parts.push( partition.partToAdd.clone() ); + } ); + expect( seen.map( ( s ) => s[0] ) ).toEqual( [true, false] ); + expect( seen[1][1] ).toBe( 'DNA, part_1 = 1-1' ); + stop(); + } ); + + it( 'maxEndValue and isComplete follow the alignment length', () => { + const alignment = addAlignment( { length: 100 } ); + const { partition } = alignment; + addPartEndingAt( partition, 100 ); + const { seen, stop } = track( () => [partition.maxEndValue, partition.isComplete] ); + runInAction( () => { + alignment.length = 120; + } ); + expect( seen ).toEqual( [ + [100, true], + [120, false], + ] ); + stop(); + } ); + + it( 'reset removes the parts and restores the part to add', () => { + const { partition } = addAlignment( { length: 100 } ); + addPartEndingAt( partition, 30 ); + const { seen, stop } = track( () => partition.isDefault ); + partition.reset(); + expect( partition.parts ).toEqual( [] ); + expect( partition.partToAdd.name.value ).toBe( 'part_1' ); + expect( partition.partToAdd.start.value ).toBe( 1 ); + expect( partition.partToAdd.end.value ).toBe( 1 ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'reset leaves the part to add alone when there are no parts', () => { + const { partition } = addAlignment( { length: 100 } ); + runInAction( () => { + partition.partToAdd.name.value = 'keep'; + } ); + partition.reset(); + expect( partition.partToAdd.name.value ).toBe( 'keep' ); + } ); +} ); + +describe( 'FinalPartition', () => { + it( 'is empty, default and complete without alignments', () => { + const finalPartition = run.finalAlignment.partition; + expect( finalPartition.text ).toBe( '' ); + expect( finalPartition.isDefault ).toBe( true ); + expect( finalPartition.isComplete ).toBe( true ); + } ); + + it( 'text offsets and prefixes each alignment partition', () => { + const finalPartition = run.finalAlignment.partition; + const { seen, stop } = track( () => finalPartition.text ); + addAlignment( { dataType: 'nucleotide', length: 100 } ); + addAlignment( { dataType: 'binary', length: 50 } ); + expect( finalPartition.text ).toBe( + 'DNA, 0_part_1 = 1-100\nBIN, 1_part_1 = 101-150', + ); + expect( seen[0] ).toBe( '' ); + expect( seen[seen.length - 1] ).toBe( finalPartition.text ); + stop(); + } ); + + it( 'text follows the added parts of an alignment', () => { + const finalPartition = run.finalAlignment.partition; + const first = addAlignment( { length: 100 } ); + addAlignment( { length: 50 } ); + addPartEndingAt( first.partition, 40 ); + addPartEndingAt( first.partition, 100 ); + expect( finalPartition.text ).toBe( + [ + 'DNA, 0_part_1 = 1-40', + 'DNA, 0_part_2 = 41-100', + 'DNA, 1_part_1 = 101-150', + ].join( '\n' ), + ); + } ); + + it( 'isDefault is true for one default alignment and false otherwise', () => { + const finalPartition = run.finalAlignment.partition; + const { seen, stop } = track( () => finalPartition.isDefault ); + const first = addAlignment( { length: 100 } ); + expect( finalPartition.isDefault ).toBe( true ); + addPartEndingAt( first.partition, 40 ); + expect( finalPartition.isDefault ).toBe( false ); + first.partition.reset(); + expect( finalPartition.isDefault ).toBe( true ); + addAlignment( { length: 10 } ); + expect( finalPartition.isDefault ).toBe( false ); + expect( seen ).toEqual( [true, false, true, false] ); + stop(); + } ); + + it( 'isComplete requires every alignment partition to be complete', () => { + const finalPartition = run.finalAlignment.partition; + const first = addAlignment( { length: 100 } ); + const second = addAlignment( { length: 100 } ); + const { seen, stop } = track( () => finalPartition.isComplete ); + addPartEndingAt( second.partition, 40 ); + expect( finalPartition.isComplete ).toBe( false ); + addPartEndingAt( second.partition, 100 ); + expect( finalPartition.isComplete ).toBe( true ); + expect( first.partition.isComplete ).toBe( true ); + expect( seen ).toEqual( [true, false, true] ); + stop(); + } ); +} ); From d5b99ef75362a0638c5848aa99b42222cb030f40 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:43:59 +0100 Subject: [PATCH 17/54] Cover the alignment on MobX 5 Tests pin the alignment's computeds, actions, observable fields, parsed-alignment loader and model selection start, success, failure and cancel (#127). Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/alignmentStore.test.js | 589 +++++++++++++++++++++++++++ 1 file changed, 589 insertions(+) create mode 100644 src/app/store/alignmentStore.test.js diff --git a/src/app/store/alignmentStore.test.js b/src/app/store/alignmentStore.test.js new file mode 100644 index 00000000..624aaa01 --- /dev/null +++ b/src/app/store/alignmentStore.test.js @@ -0,0 +1,589 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { runEvents } from './StoreBase'; + +let listeners; +let bridge; + +// Alignment construction subscribes to bridge events and parses; this stub is local to this file. +function stubBridge( extra = {} ) { + const byName = {}; + listeners = byName; + bridge = { + parseAlignment: () => new Promise( () => {} ), + startModelSelection: jest.fn( async () => {} ), + cancelModelSelection: jest.fn(), + ...extra, + }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = ( listener ) => { + ( byName[name] ||= [] ).push( listener ); + return () => { + byName[name] = byName[name].filter( ( l ) => l !== listener ); + }; + }; + } + window.rendererBridge = bridge; +} + +function fire( name, payload ) { + ( listeners[name] || [] ).forEach( ( listener ) => listener( payload ) ); +} + +// Records every value a reaction sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +function setup( { onError = () => {}, path = '/data/primates.fasta' } = {} ) { + const run = new Run( { onError }, 7 ); + run.addAlignments( [{ path }] ); + return { run, alignment: run.alignments[0] }; +} + +function set( object, values ) { + runInAction( () => Object.assign( object, values ) ); +} + +const parsed = { + sequences: [ + { taxon: 'Homo', code: 'ACGT' }, + { taxon: 'Mus', code: 'ACGA' }, + ], + fileFormat: 'fasta', + numSequences: 2, + length: 4, + dataType: 'dna', + hasInvariantSites: true, + typecheckingComplete: true, +}; + +beforeEach( () => stubBridge() ); + +describe( 'Alignment observable fields update the page store', () => { + it( 'path updates id, name, dir, base, filename and ok', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => [ + alignment.id, + alignment.name, + alignment.dir, + alignment.base, + alignment.filename, + alignment.ok, + ] ); + set( alignment, { path: '/other/apes.fasta' } ); + expect( seen[seen.length - 1][0] ).toBe( '7_/other/apes.fasta' ); + expect( seen.length ).toBe( 2 ); + expect( alignment.ok ).toBe( true ); + set( alignment, { path: '' } ); + expect( alignment.ok ).toBe( false ); + stop(); + } ); + + it( 'error, parsingComplete, typecheckingComplete and checkRunComplete drive status', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => alignment.status ); + set( alignment, { parsingComplete: true } ); + set( alignment, { typecheckingComplete: true } ); + set( alignment, { checkRunComplete: true } ); + set( alignment, { error: 'bad file' } ); + expect( seen ).toEqual( [ + 'Parsing...', + 'Type checking...', + 'Check run with RAxML...', + 'ok', + 'Error: bad file', + ] ); + stop(); + } ); + + it( 'sequences update taxons and the run taxons', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => run.taxons ); + expect( alignment.taxons ).toEqual( [] ); + set( alignment, { sequences: parsed.sequences } ); + expect( alignment.taxons ).toEqual( ['Homo', 'Mus'] ); + expect( seen ).toEqual( [[], ['Homo', 'Mus']] ); + stop(); + } ); + + it( 'length updates numSites and getSequenceCode padding', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => alignment.numSites ); + set( alignment, { sequences: parsed.sequences, length: 4 } ); + expect( seen ).toEqual( [0, 4] ); + expect( alignment.getSequenceCode( 'Homo' ) ).toBe( 'ACGT' ); + expect( alignment.getSequenceCode( 'Missing' ) ).toBe( '----' ); + stop(); + } ); + + it( 'dataType updates partitionType, modelTestCanRun and modelExtra', () => { + const { run, alignment } = setup(); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + runInAction( () => { + run.binary.value = run.binary.options.find( + ( { value } ) => !value.includes( 'raxml-ng' ), + ).value; + } ); + expect( run.usesRaxmlNg ).toBe( false ); + const { seen, stop } = track( () => [ + alignment.partitionType, + alignment.modelTestCanRun, + alignment.modelExtra && alignment.modelExtra.value, + ] ); + const types = { + dna: ['DNA', false, null], + nucleotide: ['DNA', true, null], + protein: ['BLOSUM62', true, 'BLOSUM62'], + binary: ['BIN', false, null], + multistate: ['MULTI', false, null], + mixed: ['mixed', false, null], + }; + for ( const [dataType, expected] of Object.entries( types ) ) { + set( alignment, { dataType } ); + expect( seen[seen.length - 1] ).toEqual( expected ); + } + stop(); + } ); + + it( 'aaMatrixName updates partitionType and modelExtra, and onChangeAAMatrixName sets it', () => { + const { run, alignment } = setup(); + set( run.binary, { + value: run.binary.options.find( ( { value } ) => !value.includes( 'raxml-ng' ) ).value, + } ); + set( alignment, { dataType: 'protein' } ); + const { seen, stop } = track( () => [ + alignment.partitionType, + alignment.modelExtra?.value, + ] ); + alignment.modelExtra.onChange( 'WAG' ); + expect( alignment.aaMatrixName ).toBe( 'WAG' ); + expect( seen[seen.length - 1] ).toEqual( ['WAG', 'WAG'] ); + stop(); + } ); + + it( 'modelExtra is null for protein with raxml-ng', () => { + const { run, alignment } = setup(); + set( alignment, { dataType: 'protein' } ); + const ng = run.binary.options.find( ( { value } ) => value.includes( 'raxml-ng' ) ); + const old = run.binary.options.find( ( { value } ) => !value.includes( 'raxml-ng' ) ); + set( run.binary, { value: old.value } ); + const { seen, stop } = track( () => alignment.modelExtra?.value ); + set( run.binary, { value: ng.value } ); + expect( run.usesRaxmlNg ).toBe( true ); + expect( seen ).toEqual( ['BLOSUM62', undefined] ); + stop(); + } ); + + it( 'partitionText and the partition flag update showPartition', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => alignment.showPartition ); + alignment.setShowPartition(); + expect( run.showPartitionFor ).toBe( alignment ); + alignment.hidePartition(); + alignment.setShowPartition( true ); + alignment.setShowPartition( false ); + expect( seen ).toEqual( [false, true, false, true, false] ); + alignment.setPartitionText( 'DNA, a = 1-4' ); + expect( alignment.partitionText ).toBe( 'DNA, a = 1-4' ); + stop(); + } ); + + it( 'dataType, length and aaMatrixName update partitionFileContent', () => { + const { run, alignment } = setup(); + set( alignment, { dataType: 'nucleotide', length: 10 } ); + const ng = run.binary.options.find( ( { value } ) => value.includes( 'raxml-ng' ) ); + const old = run.binary.options.find( ( { value } ) => !value.includes( 'raxml-ng' ) ); + set( run.binary, { value: old.value } ); + const { seen, stop } = track( () => alignment.partitionFileContent ); + set( alignment, { length: 12 } ); + set( alignment, { dataType: 'protein' } ); + set( alignment, { aaMatrixName: 'JTT' } ); + expect( seen ).toEqual( [ + 'DNA, nucleotide_0 = 1-10\n', + 'DNA, nucleotide_0 = 1-12\n', + 'BLOSUM62, protein_0 = 1-12\n', + 'JTT, protein_0 = 1-12\n', + ] ); + set( run.binary, { value: ng.value } ); + expect( alignment.partitionFileContent ).toBe( + `${alignment.ngSubstitutionModelCmd}, protein_0 = 1-12\n`, + ); + stop(); + } ); + + it( 'the model options update ngSubstitutionModelCmd', () => { + const { alignment } = setup(); + set( alignment, { dataType: 'nucleotide' } ); + alignment.substitutionModel.setValue( 'GTR' ); + const { seen, stop } = track( () => alignment.ngSubstitutionModelCmd ); + alignment.ngStationaryFrequencies.setValue( '+FO' ); + alignment.ngInvariantSites.setValue( '+I' ); + alignment.ngRateHeterogeneity.setValue( '+G' ); + alignment.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); + expect( seen ).toEqual( [ + 'GTR', + 'GTR+FO', + 'GTR+FO+I', + 'GTR+FO+I+G', + 'GTR+FO+I+G+ASC_LEWIS', + ] ); + stop(); + } ); + + it( 'multistateNumber updates the multistate model command', () => { + const { alignment } = setup(); + set( alignment, { dataType: 'multistate' } ); + alignment.substitutionModel.setValue( 'MULTIx_GTR' ); + const { seen, stop } = track( () => alignment.ngSubstitutionModelCmd ); + alignment.multistateNumber.setValue( 5 ); + expect( seen[0] ).toContain( 'MULTI' ); + expect( seen[seen.length - 1] ).toBe( alignment.substitutionModel.value.replace( 'x', '5' ) + '' ); + stop(); + } ); + + it( 'hasInvariantSites updates ascertainment bias availability', () => { + const { run, alignment } = setup(); + const ng = run.binary.options.find( ( { value } ) => value.includes( 'raxml-ng' ) ); + set( run.binary, { value: ng.value } ); + const { seen, stop } = track( () => alignment.ngAscertainmentBias.notAvailable ); + set( alignment, { hasInvariantSites: true } ); + expect( seen ).toEqual( [false, true] ); + stop(); + } ); + + it( 'modified fields update the run converted and modified flags', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => [run.converted, run.modified] ); + set( alignment, { converted: true } ); + set( alignment, { modified: true } ); + const last = seen[seen.length - 1]; + expect( last ).toEqual( [true, true] ); + expect( seen.length ).toBeGreaterThanOrEqual( 3 ); + stop(); + } ); + + it( 'the dialog and snack flags are set and cleared by clearModified', () => { + const { alignment } = setup(); + const { seen, stop } = track( () => [alignment.showModifiedSnack, alignment.showModifiedDialog] ); + set( alignment, { showModifiedSnack: true, showModifiedDialog: true } ); + alignment.clearModified(); + expect( seen ).toEqual( [[false, false], [true, true], [false, false]] ); + stop(); + } ); + + it( 'dataType updates the final alignment data type of the run', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => run.dataType ); + set( alignment, { dataType: 'protein' } ); + expect( run.dataType ).toBe( 'protein' ); + expect( seen[0] ).not.toBe( 'protein' ); + expect( seen[seen.length - 1] ).toBe( 'protein' ); + stop(); + } ); + + it( 'the remaining observable fields can be set and read back', () => { + const { alignment } = setup(); + const values = { + size: 1, + fileFormat: 'fasta', + convertedFrom: 'nexus', + modificationMessages: ['a'], + numSequences: 3, + checkRunData: 'out', + checkRunSuccess: true, + loading: true, + modeltestLoading: true, + partitionText: 'x', + }; + const { seen, stop } = track( () => JSON.stringify( Object.keys( values ).map( ( k ) => alignment[k] ) ) ); + set( alignment, values ); + for ( const [key, value] of Object.entries( values ) ) { + expect( alignment[key] ).toEqual( value ); + } + expect( seen.length ).toBe( 2 ); + stop(); + } ); +} ); + +describe( 'Alignment onChangeModel', () => { + it( 'sets model from the event target', () => { + const { alignment } = setup(); + alignment.onChangeModel( { target: { value: 'GTR' } } ); + expect( alignment.model ).toBe( 'GTR' ); + } ); +} ); + +describe( 'Alignment stdout and stderr', () => { + it( 'appends content for its own id only', () => { + const { run, alignment } = setup(); + const { seen, stop } = track( () => [run.stdout, run.stderr] ); + fire( runEvents.onRunStdout, { id: 'other', content: 'no' } ); + fire( runEvents.onRunStdout, { id: alignment.id, content: 'a' } ); + fire( runEvents.onRunStdout, { id: alignment.id, content: 'b' } ); + fire( runEvents.onRunStderr, { id: alignment.id, content: 'e' } ); + expect( run.stdout ).toBe( 'ab' ); + expect( run.stderr ).toBe( 'e' ); + expect( seen[seen.length - 1] ).toEqual( ['ab', 'e'] ); + stop(); + } ); +} ); + +describe( 'Alignment constructor', () => { + it( 'builds the option objects and the partition', () => { + const { alignment } = setup(); + expect( alignment.substitutionModel.run ).toBe( alignment.run ); + expect( alignment.multistateNumber ).toBeDefined(); + expect( alignment.partition ).toBeDefined(); + expect( typeof alignment.modeltestDisabled ).toBe( 'boolean' ); + } ); + + it( 'disables modeltest on Windows 7', () => { + window.rendererBridge = { ...bridge, host: { ...bridge.host, windows: true, release: '6.1.7601' } }; + jest.isolateModules( () => { + const IsolatedRun = require( './Run' ).default; + const run = new IsolatedRun( {}, 1 ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.alignments[0].modeltestDisabled ).toBe( true ); + } ); + } ); +} ); + +describe( 'Alignment loadParsedAlignment', () => { + async function load( parse, run ) { + let pending; + stubBridge( { + parseAlignment: ( ...args ) => { + pending = parse( ...args ); + return pending; + }, + } ); + const result = setup(); + await pending.catch( () => {} ); + return result; + } + + it( 'writes the parsed fields', async () => { + const parseAlignment = jest.fn( async () => ( { alignment: parsed, change: null } ) ); + const { alignment } = await load( parseAlignment ); + expect( parseAlignment ).toHaveBeenCalledWith( '7_/data/primates.fasta', '/data/primates.fasta' ); + expect( alignment.sequences ).toEqual( parsed.sequences ); + expect( alignment.numSequences ).toBe( 2 ); + expect( alignment.parsingComplete ).toBe( true ); + expect( alignment.loading ).toBe( false ); + expect( alignment.status ).toBe( 'Check run with RAxML...' ); + } ); + + it( 'writes the substitution model default and the substitution matrix default', async () => { + const { run, alignment } = await load( async () => ( { + alignment: { ...parsed, dataType: 'protein' }, + change: null, + } ) ); + expect( alignment.substitutionModel.value ).toBe( 'Blosum62' ); + expect( run.substitutionMatrix.value ).toBe( 'BLOSUM62' ); + } ); + + it( 'keeps the substitution matrix when the run data type is unchanged', async () => { + const { run, alignment } = await load( async () => ( { + alignment: { ...parsed, dataType: 'dna' }, + change: null, + } ) ); + expect( run.substitutionMatrix.value ).toBe( 'GTR' ); + expect( alignment.substitutionModel.value ).toBe( 'GTR' ); + } ); + + it( 'a modification with messages shows the dialog', async () => { + const { alignment } = await load( async () => ( { + alignment: parsed, + change: { + newFilePath: '/data/primates_modified.fas', + format: 'nexus', + converted: true, + modified: true, + modificationMessages: ['fixed a name'], + }, + } ) ); + expect( alignment.path ).toBe( '/data/primates_modified.fas' ); + expect( alignment.convertedFrom ).toBe( 'nexus' ); + expect( alignment.converted ).toBe( true ); + expect( alignment.modified ).toBe( true ); + expect( alignment.showModifiedDialog ).toBe( true ); + expect( alignment.showModifiedSnack ).toBe( false ); + } ); + + it( 'a conversion without messages shows the snack', async () => { + const { alignment } = await load( async () => ( { + alignment: parsed, + change: { + newFilePath: '/data/primates.fas', + format: 'nexus', + converted: true, + modified: false, + modificationMessages: [], + }, + } ) ); + expect( alignment.showModifiedSnack ).toBe( true ); + expect( alignment.showModifiedDialog ).toBe( false ); + } ); + + it( 'a failed parse sets the error, removes the alignment and stops listening', async () => { + const error = new Error( 'unrecognized format' ); + const { run, alignment } = await load( async () => { + throw error; + } ); + expect( alignment.error ).toBe( error ); + expect( alignment.loading ).toBe( false ); + expect( run.error ).toBe( error ); + expect( run.alignments ).toEqual( [] ); + expect( listeners[runEvents.onModelSelectionSuccess] ).toEqual( [] ); + } ); +} ); + +describe( 'Alignment model selection', () => { + it( 'runModelTest reports an error for fewer than three sequences', async () => { + const onError = jest.fn(); + const { alignment } = setup( { onError } ); + set( alignment, { numSequences: 2 } ); + await alignment.runModelTest(); + expect( onError ).toHaveBeenCalledTimes( 1 ); + expect( onError.mock.calls[0][0].message ).toBe( + 'ModelTest can only be run on alignments with more than two sequences.', + ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( bridge.startModelSelection ).not.toHaveBeenCalled(); + } ); + + it( 'start sets loading and calls the bridge', async () => { + const { run, alignment } = setup(); + run.setOutputDir( '/out' ); + set( alignment, { numSequences: 4, dataType: 'nucleotide' } ); + const { seen, stop } = track( () => alignment.modeltestLoading ); + await alignment.runModelTest(); + expect( seen ).toEqual( [false, true] ); + expect( bridge.startModelSelection ).toHaveBeenCalledWith( { + id: '7_/data/primates.fasta', + filePath: '/data/primates.fasta', + outputDir: '/out', + dataType: 'nucleotide', + numThreads: run.numThreads.value, + binaryName: run.modeltestName, + } ); + stop(); + } ); + + it( 'cancel clears loading and calls the bridge only while loading', () => { + const { alignment } = setup(); + alignment.cancelModelTest(); + expect( bridge.cancelModelSelection ).not.toHaveBeenCalled(); + set( alignment, { modeltestLoading: true } ); + alignment.cancelModelTest(); + expect( alignment.modeltestLoading ).toBe( false ); + expect( bridge.cancelModelSelection ).toHaveBeenCalledWith( alignment.id ); + } ); + + it( 'success for its own id sets the model and ends the run', () => { + const { run, alignment } = setup(); + set( alignment, { modeltestLoading: true } ); + set( run, { running: true } ); + const result = { raxml: 'GTRGAMMA', extraFlag: '--HKY85', raxmlNG: 'HKY+G' }; + fire( runEvents.onModelSelectionSuccess, { id: 'other', result } ); + expect( alignment.modeltestLoading ).toBe( true ); + expect( run.running ).toBe( true ); + fire( runEvents.onModelSelectionSuccess, { id: alignment.id, result } ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( alignment.substitutionModel.value ).toBe( 'HKY' ); + expect( alignment.ngRateHeterogeneity.value ).toBe( '+G' ); + expect( run.substitutionMatrix.value ).toBe( 'HKY' ); + expect( run.substitutionRate.value ).toBe( 'GAMMA' ); + expect( run.running ).toBe( false ); + } ); + + it( 'failure for its own id sets the run error and ends the run', () => { + const { run, alignment } = setup(); + set( alignment, { modeltestLoading: true } ); + set( run, { running: true } ); + fire( runEvents.onModelSelectionFailure, { id: 'other', error: 'x' } ); + expect( run.error ).toBe( null ); + fire( runEvents.onModelSelectionFailure, { id: alignment.id, error: 'missing binary' } ); + expect( run.error ).toBe( 'missing binary' ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( run.running ).toBe( false ); + } ); + + it( 'dispose stops listening and cancels a running model selection', () => { + const { alignment } = setup(); + set( alignment, { modeltestLoading: true } ); + const before = listeners[runEvents.onModelSelectionSuccess].length; + alignment.dispose(); + expect( bridge.cancelModelSelection ).toHaveBeenCalledWith( alignment.id ); + expect( listeners[runEvents.onModelSelectionSuccess].length ).toBe( before - 1 ); + } ); + + it( 'remove disposes and removes the alignment from the run', () => { + const { run, alignment } = setup(); + alignment.remove(); + expect( run.alignments ).toEqual( [] ); + } ); +} ); + +describe( 'Alignment setModelFromString', () => { + function apply( result, dataType = 'nucleotide' ) { + const { run, alignment } = setup(); + set( alignment, { dataType, modeltestLoading: true } ); + alignment.setModelFromString( result ); + return { run, alignment }; + } + + it( 'maps renamed models and the ng parameters', () => { + const { alignment } = apply( { raxml: 'GTRGAMMAIF', extraFlag: '', raxmlNG: 'TrN+FO+IC+GA+ASC_LEWIS' } ); + expect( alignment.modeltestLoading ).toBe( false ); + expect( alignment.substitutionModel.value ).toBe( 'TN93' ); + expect( alignment.ngStationaryFrequencies.value ).toBe( '+FO' ); + expect( alignment.ngInvariantSites.value ).toBe( '+IC' ); + expect( alignment.ngRateHeterogeneity.value ).toBe( '+GA' ); + expect( alignment.ngAscertainmentBias.value ).toBe( '+ASC_LEWIS' ); + } ); + + it( 'maps TPM1 to K81', () => { + const { alignment } = apply( { raxml: 'GTRGAMMA', extraFlag: '', raxmlNG: 'TPM1' } ); + expect( alignment.substitutionModel.value ).toBe( 'K81' ); + } ); + + it( 'reads the raxml flags F, X, invariant sites and rate', () => { + const f = apply( { raxml: 'GTRGAMMAIF', extraFlag: '', raxmlNG: 'GTR' } ); + expect( f.run.baseFrequencies.value ).toBe( 'F' ); + expect( f.run.substitutionI.value ).toBe( '+I (ML estimate)' ); + expect( f.run.substitutionRate.value ).toBe( 'GAMMA' ); + expect( f.run.substitutionAscertainment.value ).toBe( 'none' ); + + const x = apply( { raxml: 'GTRCATX', extraFlag: '', raxmlNG: 'GTR' } ); + expect( x.run.estimatedFrequencies.value ).toBe( true ); + expect( x.run.baseFrequencies.value ).toBe( 'X' ); + expect( x.run.substitutionRate.value ).toBe( 'CAT' ); + expect( x.run.substitutionI.value ).toBe( 'none' ); + + const d = apply( { raxml: 'GTRGAMMA', extraFlag: '', raxmlNG: 'GTR' } ); + expect( d.run.baseFrequencies.value ).toBe( 'default' ); + } ); + + it( 'maps the extra flags to the substitution matrix', () => { + const jc = apply( { raxml: 'GTRCAT', extraFlag: '--JC69', raxmlNG: 'JC' } ); + expect( jc.run.substitutionMatrix.value ).toBe( 'JC' ); + expect( jc.run.substitutionRate.value ).toBe( 'GAMMA' ); + const k80 = apply( { raxml: 'GTRCAT', extraFlag: '--K80', raxmlNG: 'K80' } ); + expect( k80.run.substitutionMatrix.value ).toBe( 'K80' ); + const hky = apply( { raxml: 'GTRCAT', extraFlag: '--HKY85', raxmlNG: 'HKY' } ); + expect( hky.run.substitutionMatrix.value ).toBe( 'HKY' ); + } ); + + it( 'parses the amino acid matrix for protein', () => { + const { alignment } = apply( { raxml: 'PROTGAMMAWAGF', extraFlag: '', raxmlNG: 'WAG+FO' }, 'protein' ); + expect( alignment.aaMatrixName ).toBe( 'WAG' ); + } ); +} ); From 7e82eb1c78186cf6c24f52e5dfa5a30d0ba01f8a Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:44:06 +0100 Subject: [PATCH 18/54] Cover the outgroup option on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/OutGroup.test.js | 105 +++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/app/store/OutGroup.test.js diff --git a/src/app/store/OutGroup.test.js b/src/app/store/OutGroup.test.js new file mode 100644 index 00000000..48433b2e --- /dev/null +++ b/src/app/store/OutGroup.test.js @@ -0,0 +1,105 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import RunList from './RunList'; +import { runEvents } from './StoreBase'; + +// A run subscribes to bridge events when it is created. +beforeEach( () => { + const bridge = { cancelRun: jest.fn(), getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = () => () => {}; + } + window.rendererBridge = bridge; +} ); + +const newRun = () => new RunList().activeRun; + +const setAlignments = ( run, taxons ) => runInAction( () => { + run.alignments = [{ taxons }]; +} ); + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +describe( 'OutGroup', () => { + it( 'starts at none', () => { + const { outGroup } = newRun(); + expect( outGroup.value ).toEqual( [''] ); + expect( outGroup.multiple ).toBe( true ); + expect( outGroup.cmdValue ).toBe( '' ); + } ); + + it( 'options are none followed by the taxa, and follow the alignments', () => { + const run = newRun(); + const { seen, stop } = track( () => run.outGroup.options.map( ( o ) => o.value ) ); + setAlignments( run, ['a', 'b'] ); + expect( run.outGroup.options ).toEqual( [ + { value: '', title: '' }, + { value: 'a', title: 'a' }, + { value: 'b', title: 'b' }, + ] ); + expect( seen ).toEqual( [[''], ['', 'a', 'b']] ); + stop(); + } ); + + describe( 'setValue', () => { + it( 'choosing a taxon clears none', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['', 'a'] ); + expect( outGroup.value ).toEqual( ['a'] ); + } ); + + it( 'choosing none clears the taxa', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['a', 'b'] ); + outGroup.setValue( ['a', 'b', ''] ); + expect( outGroup.value ).toEqual( [''] ); + } ); + + it( 'keeps several taxa', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['a', 'b'] ); + expect( outGroup.value ).toEqual( ['a', 'b'] ); + } ); + } ); + + it( 'reset returns to none', () => { + const { outGroup } = newRun(); + outGroup.setValue( ['a'] ); + outGroup.reset(); + expect( outGroup.value ).toEqual( [''] ); + expect( outGroup.isDefault ).toBe( false ); // default is an array compared by identity + } ); + + it( 'cmdValue is empty for none and comma-joined for taxa, and follows value', () => { + const { outGroup } = newRun(); + const { seen, stop } = track( () => outGroup.cmdValue ); + runInAction( () => { + outGroup.value = ['a', 'b']; + } ); + runInAction( () => { + outGroup.value = ['']; + } ); + expect( seen ).toEqual( ['', 'a,b', ''] ); + stop(); + } ); + + it( 'notAvailable follows alignments and the analysis', () => { + const run = newRun(); + const { seen, stop } = track( () => run.outGroup.notAvailable ); + expect( run.outGroup.notAvailable ).toBe( true ); // no alignments + setAlignments( run, ['a'] ); + expect( run.outGroup.notAvailable ).toBe( false ); // default analysis takes an outgroup + runInAction( () => { + run.analysis.value = 'AS'; // takes no outgroup + } ); + expect( run.outGroup.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true] ); + stop(); + } ); +} ); From 0cea78ed9f661b45d0f0410cc648e02272281948 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:44:15 +0100 Subject: [PATCH 19/54] Cover the substitution options on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/substitutionOptions.test.js | 315 ++++++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 src/app/store/substitutionOptions.test.js diff --git a/src/app/store/substitutionOptions.test.js b/src/app/store/substitutionOptions.test.js new file mode 100644 index 00000000..fcc67056 --- /dev/null +++ b/src/app/store/substitutionOptions.test.js @@ -0,0 +1,315 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +// Run's constructor subscribes to bridge events; a no-op stub is enough here. +beforeEach( () => { + window.rendererBridge = new Proxy( {}, { + get: ( _, name ) => { + if ( name === 'getVersion' ) { + return () => Promise.resolve( '2.0.0' ); + } + // A load that never settles keeps the test in control of dataType. + return name === 'parseAlignment' + ? () => new Promise( () => {} ) + : () => () => {}; + }, + } ); +} ); + +const binaryNamed = ( run, prefix ) => run.binary.options + .map( ( o ) => o.value ).find( ( v ) => v.startsWith( prefix ) ); +const ngName = () => binaryNamed( new Run( { onError() {} }, 1 ), 'raxml-ng' ); + +// The default binary depends on the host platform, so pin a classic RAxML one. +function newRun() { + const run = new Run( { onError() {} }, 1 ); + run.binary.setValue( binaryNamed( run, 'raxmlHPC' ) ); + return run; +} + +function makeRun( dataType = 'nucleotide' ) { + const run = newRun(); + run.addAlignments( [{ path: '/data/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = dataType; + } ); + return run; +} + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const noAlignmentRun = newRun; + +describe( 'SubstitutionMatrix', () => { + it( 'has no options without alignments, then lists them per data type', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionMatrix.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionMatrix.options ).toEqual( [ + { value: 'JC', title: 'JC + GAMMA' }, + { value: 'K80', title: 'K80 + GAMMA' }, + { value: 'HKY', title: 'HKY + GAMMA' }, + { value: 'GTR', title: 'GTR' }, + ] ); + expect( seen[seen.length - 1] ).toHaveLength( 4 ); + stop(); + } ); + + it( 'has no options for a data type without settings', () => { + const run = makeRun( 'unknown' ); + expect( run.substitutionMatrix.options ).toEqual( [] ); + } ); + + it( 'is not available without alignments, for other data types or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionMatrix.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionMatrix.notAvailable ).toBe( false ); + for ( const type of ['binary', 'protein', 'multistate'] ) { + runInAction( () => { + run.alignments[0].dataType = type; + } ); + expect( run.substitutionMatrix.notAvailable ).toBe( true ); + } + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + run.binary.setValue( ngName() ); + expect( run.substitutionMatrix.notAvailable ).toBe( true ); + expect( seen ).toContain( false ); + stop(); + } ); + + it( 'maps the data type and value to the command value', () => { + const run = makeRun( 'nucleotide' ); + const { seen, stop } = track( () => run.substitutionMatrix.cmdValue ); + expect( seen[0] ).toBe( 'GTR' ); + for ( const [value, cmd] of [['JC', 'GTR'], ['K80', 'GTR'], ['HKY', 'GTR']] ) { + run.substitutionMatrix.setValue( value ); + expect( run.substitutionMatrix.cmdValue ).toBe( cmd ); + } + for ( const [type, cmd] of [['binary', 'BIN'], ['protein', 'PROT'], ['multistate', 'MULTI']] ) { + runInAction( () => { + run.alignments[0].dataType = type; + } ); + expect( run.substitutionMatrix.cmdValue ).toBe( cmd ); + } + expect( seen ).toEqual( ['GTR', 'BIN', 'PROT', 'MULTI'] ); + stop(); + } ); + + it( 'passes the value through for a mixed run', () => { + const run = makeRun( 'mixed' ); + run.substitutionMatrix.setValue( 'BIN' ); + expect( run.substitutionMatrix.cmdValue ).toBe( 'BIN' ); + } ); + + it( 'gives the extra raxml-ng flag and notGTR per value', () => { + const run = makeRun(); + const matrix = run.substitutionMatrix; + const flags = track( () => matrix.extraCmdValue ); + const notGTR = track( () => matrix.notGTR ); + expect( flags.seen[0] ).toBe( '' ); + expect( notGTR.seen[0] ).toBe( false ); + for ( const [value, flag] of [['JC', '--JC69'], ['K80', '--K80'], ['HKY', '--HKY85'], ['GTR', '']] ) { + matrix.setValue( value ); + expect( matrix.extraCmdValue ).toBe( flag ); + expect( matrix.notGTR ).toBe( value !== 'GTR' ); + } + expect( flags.seen ).toEqual( ['', '--JC69', '--K80', '--HKY85', ''] ); + expect( notGTR.seen ).toEqual( [false, true, false] ); + flags.stop(); + notGTR.stop(); + } ); +} ); + +describe( 'SubstitutionRate', () => { + it( 'lists rate options once there are alignments', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionRate.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionRate.options ).toEqual( [ + { value: 'CAT', title: 'CAT' }, + { value: 'GAMMA', title: 'GAMMA' }, + ] ); + expect( seen ).toHaveLength( 2 ); + stop(); + } ); + + it( 'is unavailable without alignments, for non-GTR nucleotide or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionRate.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionRate.notAvailable ).toBe( false ); + run.substitutionMatrix.setValue( 'HKY' ); + expect( run.substitutionRate.notAvailable ).toBe( true ); + runInAction( () => { + run.alignments[0].dataType = 'protein'; + } ); + expect( run.substitutionRate.notAvailable ).toBe( false ); + run.binary.setValue( ngName() ); + expect( run.substitutionRate.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true, false, true] ); + stop(); + } ); + + it( 'forces GAMMA unless the matrix is GTR, and reports CAT', () => { + const run = makeRun(); + const rate = run.substitutionRate; + const cmd = track( () => rate.cmdValue ); + const cat = track( () => rate.isCAT ); + expect( cmd.seen[0] ).toBe( 'GAMMA' ); + expect( cat.seen[0] ).toBe( false ); + rate.setValue( 'CAT' ); + expect( rate.cmdValue ).toBe( 'CAT' ); + expect( rate.isCAT ).toBe( true ); + run.substitutionMatrix.setValue( 'K80' ); + expect( rate.cmdValue ).toBe( 'GAMMA' ); + expect( rate.isCAT ).toBe( true ); + expect( cmd.seen ).toEqual( ['GAMMA', 'CAT', 'GAMMA'] ); + expect( cat.seen ).toEqual( [false, true] ); + cmd.stop(); + cat.stop(); + } ); +} ); + +describe( 'SubstitutionI', () => { + it( 'lists the invariant-sites options once there are alignments', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionI.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionI.options ).toEqual( [ + { value: 'none', title: 'none' }, + { value: '+I (ML estimate)', title: '+I (ML estimate)' }, + ] ); + expect( seen ).toHaveLength( 2 ); + stop(); + } ); + + it( 'is unavailable without alignments, with ascertainment set or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionI.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionI.notAvailable ).toBe( false ); + run.substitutionAscertainment.setValue( "Lewis' method" ); + expect( run.substitutionI.notAvailable ).toBe( true ); + run.substitutionAscertainment.setValue( 'none' ); + run.binary.setValue( ngName() ); + expect( run.substitutionI.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true, false, true] ); + stop(); + } ); + + it( 'gives I and isSet once a value is chosen', () => { + const run = makeRun(); + const cmd = track( () => run.substitutionI.cmdValue ); + const set = track( () => run.substitutionI.isSet ); + expect( cmd.seen ).toEqual( [''] ); + expect( set.seen ).toEqual( [false] ); + run.substitutionI.setValue( '+I (ML estimate)' ); + expect( cmd.seen ).toEqual( ['', 'I'] ); + expect( set.seen ).toEqual( [false, true] ); + cmd.stop(); + set.stop(); + } ); +} ); + +describe( 'SubstitutionAscertainment', () => { + it( 'lists the ascertainment options once there are alignments', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionAscertainment.options ); + expect( seen[0] ).toEqual( [] ); + run.addAlignments( [{ path: '/a.fasta' }] ); + expect( run.substitutionAscertainment.options.map( ( o ) => o.value ) ).toEqual( [ + 'none', + "Lewis' method", + "Felsenstein's method", + "Stamatakis' method", + ] ); + expect( seen ).toHaveLength( 2 ); + stop(); + } ); + + it( 'is unavailable without alignments, mixed data, invariant sites, +I or raxml-ng', () => { + const run = noAlignmentRun(); + const { seen, stop } = track( () => run.substitutionAscertainment.notAvailable ); + expect( seen[0] ).toBe( true ); + run.addAlignments( [{ path: '/a.fasta' }] ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + expect( run.substitutionAscertainment.notAvailable ).toBe( false ); + runInAction( () => { + run.alignments[0].dataType = 'mixed'; + } ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + runInAction( () => { + run.alignments[0].dataType = 'nucleotide'; + } ); + runInAction( () => { + run.alignments[0].hasInvariantSites = true; + } ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + runInAction( () => { + run.alignments[0].hasInvariantSites = false; + } ); + run.substitutionI.setValue( '+I (ML estimate)' ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + run.substitutionI.setValue( 'none' ); + run.binary.setValue( ngName() ); + expect( run.substitutionAscertainment.notAvailable ).toBe( true ); + expect( seen ).toEqual( [true, false, true, false, true, false, true, false, true] ); + stop(); + } ); + + it( 'gives ASC_, the raxml-ng flag and isSet per value', () => { + const run = makeRun(); + const asc = run.substitutionAscertainment; + const cmd = track( () => asc.cmdValue ); + const extra = track( () => asc.extraCmdValue ); + const set = track( () => asc.isSet ); + expect( [cmd.seen[0], extra.seen[0], set.seen[0]] ).toEqual( ['', '', false] ); + for ( const [value, flag] of [ + [ "Lewis' method", '--asc-corr=lewis' ], + [ "Felsenstein's method", '--asc-corr=felsenstein' ], + [ "Stamatakis' method", '--asc-corr=stamatakis' ], + ] ) { + asc.setValue( value ); + expect( asc.cmdValue ).toBe( 'ASC_' ); + expect( asc.extraCmdValue ).toBe( flag ); + expect( asc.isSet ).toBe( true ); + } + asc.setValue( 'none' ); + expect( [asc.cmdValue, asc.extraCmdValue, asc.isSet] ).toEqual( ['', '', false] ); + expect( extra.seen ).toEqual( [ + '', '--asc-corr=lewis', '--asc-corr=felsenstein', '--asc-corr=stamatakis', '', + ] ); + expect( cmd.seen ).toEqual( ['', 'ASC_', ''] ); + expect( set.seen ).toEqual( [false, true, false] ); + cmd.stop(); + extra.stop(); + set.stop(); + } ); +} ); From 87dae919cc84f356735f8ff03df1dee3b210af04 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:44:35 +0100 Subject: [PATCH 20/54] Cover the tree file options on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/treeFileOptions.test.js | 159 ++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 src/app/store/treeFileOptions.test.js diff --git a/src/app/store/treeFileOptions.test.js b/src/app/store/treeFileOptions.test.js new file mode 100644 index 00000000..190c420e --- /dev/null +++ b/src/app/store/treeFileOptions.test.js @@ -0,0 +1,159 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +const files = [ + [ 'tree', '/data/start.nwk' ], + [ 'backboneConstraint', '/data/backbone.tre' ], + [ 'multifurcatingConstraint', '/data/multi.tre' ], +]; + +let showItemInFolder; +let openPath; +let selectTree; +let run; +let disposers; + +// Records every value an autorun sees, so a test can prove it re-ran. +// Run.analysis is a computed that builds a new option; observing it keeps the set value. +function observe( fn ) { + const seen = []; + disposers.push( autorun( () => seen.push( fn() ) ) ); + return { seen }; +} + +beforeEach( () => { + showItemInFolder = jest.fn( async () => {} ); + openPath = jest.fn( async () => {} ); + selectTree = jest.fn(); + window.rendererBridge = { showItemInFolder, openPath, selectTree }; + run = new Run( {}, 3 ); + disposers = []; + // The default binary is raxml-ng; these tests use the classic RAxML analyses. + run.binary.setValue( run.binary.options.find( ( { value } ) => value.includes( 'raxmlHPC' ) ).value ); + observe( () => run.analysis.value ); +} ); + +afterEach( () => { + disposers.forEach( ( stop ) => stop() ); +} ); + +describe.each( files )( '%s file', ( key, filePath ) => { + const option = () => run[key]; + const filename = filePath.split( '/' ).pop(); + const stem = filename.replace( /\.\w+$/, '' ); + + it( 'starts without a file', () => { + expect( option().filePath ).toBe( '' ); + expect( option().haveFile ).toBe( false ); + expect( option().filename ).toBe( '' ); + expect( option().dir ).toBe( '' ); + } ); + + it( 'loading a file sets path, filename, name, dir and haveFile', async () => { + selectTree.mockResolvedValue( { type: key, filePath } ); + const load = { + tree: run.loadTreeFile, + backboneConstraint: run.loadBackboneConstraintFile, + multifurcatingConstraint: run.loadMultifurcatingConstraintFile, + }[key]; + await load(); + expect( selectTree ).toHaveBeenCalledWith( 3, key ); + expect( option().filePath ).toBe( filePath ); + expect( option().haveFile ).toBe( true ); + expect( option().filename ).toBe( filename ); + expect( option().name ).toBe( stem ); + expect( option().dir ).toBe( '/data' ); + } ); + + it( 'setFilePath updates every computed', () => { + const { seen } = observe( () => [ + option().haveFile, option().filename, option().name, option().dir, + ] ); + option().setFilePath( filePath ); + expect( seen ).toEqual( [ + [ false, '', '', '' ], + [ true, filename, stem, '/data' ], + ] ); + } ); + + it( 'a reaction sees filePath set directly', () => { + const { seen } = observe( () => option().haveFile ); + runInAction( () => { + option().filePath = filePath; + } ); + expect( seen ).toEqual( [ false, true ] ); + } ); + + it( 'remove clears the file', () => { + option().setFilePath( filePath ); + const { seen } = observe( () => option().haveFile ); + option().remove(); + expect( option().filePath ).toBe( '' ); + expect( seen ).toEqual( [ true, false ] ); + } ); + + it( 'openFolder and openFile pass the path to the bridge', async () => { + option().setFilePath( filePath ); + await option().openFolder(); + await option().openFile(); + expect( showItemInFolder ).toHaveBeenCalledWith( filePath ); + expect( openPath ).toHaveBeenCalledWith( filePath ); + } ); +} ); + +describe( 'Tree notAvailable', () => { + it( 'is unavailable for the default analysis', () => { + expect( run.tree.notAvailable ).toBe( true ); + } ); + + it( 'follows the analysis that takes a tree', () => { + const { seen } = observe( () => run.tree.notAvailable ); + run.analysis.setValue( 'AS' ); + run.analysis.setValue( 'ML+rBS' ); + expect( seen ).toEqual( [ true, false, true ] ); + } ); + + it( 'follows a user defined starting tree', () => { + const { seen } = observe( () => run.tree.notAvailable ); + run.analysis.setValue( 'PD' ); + run.startingTree.setValue( 'User defined' ); + run.startingTree.setValue( 'Maximum parsimony' ); + expect( seen ).toEqual( [ true, false, true ] ); + } ); +} ); + +describe.each( [ + [ 'backboneConstraint', 'useBackboneConstraint', 'onBackboneConstraint' ], + [ 'multifurcatingConstraint', 'useMultifurcatingConstraint', 'onMultifurcatingConstraint' ], +] )( '%s toggle', ( key, flag, toggle ) => { + const option = () => run[key]; + + it( 'notAvailable follows the toggle', () => { + const { seen } = observe( () => option().notAvailable ); + run[toggle](); + run[toggle](); + expect( seen ).toEqual( [ true, false, true ] ); + } ); + + it( 'notAvailable follows the analysis', () => { + runInAction( () => { + run[flag] = true; + } ); + const { seen } = observe( () => [ option().canConstraint, option().notAvailable ] ); + run.analysis.setValue( 'FT' ); + expect( seen ).toEqual( [ [ true, false ], [ false, true ] ] ); + } ); + + it( 'isSet needs the toggle and a file', () => { + const { seen } = observe( () => option().isSet ); + run[toggle](); + option().setFilePath( '/data/c.tre' ); + run[toggle](); + option().remove(); + run[toggle](); + // the computed only notifies when its value changes + expect( seen ).toEqual( [ false, true, false ] ); + } ); +} ); From 282b43873cfae34ef22f4094685202683d0b8805 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:44:53 +0100 Subject: [PATCH 21/54] Cover the run's simple options on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/RunSimpleOptions.test.js | 362 +++++++++++++++++++++++++ 1 file changed, 362 insertions(+) create mode 100644 src/app/store/RunSimpleOptions.test.js diff --git a/src/app/store/RunSimpleOptions.test.js b/src/app/store/RunSimpleOptions.test.js new file mode 100644 index 00000000..8841e026 --- /dev/null +++ b/src/app/store/RunSimpleOptions.test.js @@ -0,0 +1,362 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { binaries, MAX_NUM_CPUS } from './RunOptions'; + +const threaded = binaries.find( ( b ) => /PTHREADS/.test( b.name ) ); +const plain = binaries.find( ( b ) => b.type === 'raxml' && !/PTHREADS|-ng/.test( b.name ) ); + +// Run.analysis is a computed that builds a new option on each evaluation, so an +// unobserved run forgets a set analysis value. A kept-alive reaction models the page. +const stops = []; +afterEach( () => stops.splice( 0 ).forEach( ( stop ) => stop() ) ); + +// The initial binary is raxml-ng on some hosts; most tests start from classic RAxML. +const newRun = () => { + const run = new Run( null, 1 ); + stops.push( autorun( () => run.analysis ) ); + runInAction( () => { + run.binary.value = plain.name; + } ); + return run; +}; + +// Records every value an autorun sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +const set = ( option, value ) => runInAction( () => { + option.value = value; +} ); + +const setAnalysis = ( run, value ) => set( run.analysis, value ); + +const addAlignment = ( run, dataType ) => runInAction( () => { + run.alignments.push( { dataType, taxons: ['a', 'b'], partition: { isDefault: true } } ); +} ); + +describe( 'Binary', () => { + it( 'defaults to the initial binary and offers every binary', () => { + const run = new Run( null, 1 ); + expect( run.binary.value ).toBe( binaries.find( ( b ) => b.initial ).name ); + expect( run.binary.options.map( ( o ) => o.value ) ).toEqual( + binaries.map( ( b ) => b.name ), + ); + } ); + + it( 'derives version and type from the chosen binary and updates reactions', () => { + const run = newRun(); + const modeltest = binaries.find( ( b ) => b.type === 'modeltest' ); + const { seen, stop } = track( () => [run.binary.version, run.binary.type] ); + set( run.binary, modeltest.name ); + stop(); + expect( seen ).toEqual( [ + [plain.version, plain.type], + [modeltest.version, modeltest.type], + ] ); + } ); + + it( 'a reaction on the run command updates when the binary changes', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.command ); + set( run.binary, threaded.name ); + stop(); + expect( seen[0].startsWith( plain.name ) ).toBe( true ); + expect( seen[1].startsWith( threaded.name ) ).toBe( true ); + } ); +} ); + +describe( 'NumThreads', () => { + it( 'offers one to the number of cpus', () => { + const run = newRun(); + expect( run.numThreads.options.map( ( o ) => o.value ) ).toEqual( + Array.from( { length: MAX_NUM_CPUS }, ( _, i ) => i + 1 ), + ); + } ); + + it( 'is available with a PTHREADS binary and not otherwise', () => { + const run = newRun(); + const { seen, stop } = track( () => run.numThreads.notAvailable ); + set( run.binary, threaded.name ); + set( run.binary, plain.name ); + stop(); + expect( seen ).toEqual( [...seen.slice( 0, 1 ), false, true] ); + } ); + + it( 'is available with modeltest-ng', () => { + const run = newRun(); + set( run.binary, 'modeltest-ng' ); + expect( run.numThreads.notAvailable ).toBe( false ); + } ); + + it( 'a reaction on the run command updates when the thread count changes', () => { + const run = newRun(); + set( run.binary, threaded.name ); + setAnalysis( run, 'FT' ); + const { seen, stop } = track( () => run.command ); + set( run.numThreads, 4 ); + stop(); + expect( seen[0] ).toContain( '-T 2 ' ); + expect( seen[1] ).toContain( '-T 4 ' ); + } ); +} ); + +describe( 'Analysis and RaxmlNgAnalysis', () => { + it( 'uses the RAxML analysis list by default', () => { + const run = newRun(); + expect( run.usesRaxmlNg ).toBe( false ); + expect( run.analysis.value ).toBe( 'ML+rBS' ); + expect( run.analysis.options.map( ( o ) => o.value ) ).toEqual( + ['FT', 'ML', 'ML+rBS', 'ML+tBS', 'BS+con', 'AS', 'PD', 'RBS'], + ); + expect( run.analysisOption.title ).toBe( 'ML + rapid bootstrap' ); + } ); + + it( 'uses the RAxML-NG analysis list with a raxml-ng binary', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + expect( run.analysis.value ).toBe( 'ML+TBE+con' ); + expect( run.analysis.options.map( ( o ) => o.value ) ).toEqual( + ['SC', 'CC', 'TI', 'ML+tBS+con', 'ML+TBE+con', 'AS'], + ); + expect( run.analysisOption.title ).toBe( + 'ML + transfer bootstrap expectation + consensus', + ); + } ); + + it( 'a reaction on analysisOption updates when the analysis value changes', () => { + const run = newRun(); + const { seen, stop } = track( () => run.analysisOption.title ); + setAnalysis( run, 'FT' ); + stop(); + expect( seen ).toEqual( ['ML + rapid bootstrap', 'Fast tree search'] ); + } ); + + it( 'a reaction on analysisOption updates when the RAxML-NG analysis value changes', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + const { seen, stop } = track( () => run.analysisOption.title ); + setAnalysis( run, 'TI' ); + stop(); + expect( seen ).toEqual( [ + 'ML + transfer bootstrap expectation + consensus', + 'ML tree inference', + ] ); + } ); +} ); + +describe( 'analysis dependent availability', () => { + const cases = [ + // [option name, analyses that use it, analyses that do not] + ['numRuns', ['ML', 'ML+tBS'], ['FT', 'ML+rBS', 'RBS']], + ['numRepetitions', ['ML+rBS', 'ML+tBS', 'BS+con'], ['FT', 'ML', 'PD']], + ['branchLength', ['FT', 'ML+rBS', 'ML+tBS', 'BS+con'], ['ML', 'PD', 'AS']], + ['sHlike', ['FT', 'ML'], ['ML+rBS', 'RBS']], + ['combinedOutput', ['ML'], ['FT', 'ML+rBS']], + ['startingTree', ['PD'], ['FT', 'ML']], + ]; + + it.each( cases )( '%s is available only for its analyses', ( name, used, unused ) => { + const run = newRun(); + const { seen, stop } = track( () => run[name].notAvailable ); + used.forEach( ( value ) => { + setAnalysis( run, value ); + expect( run[name].notAvailable ).toBe( false ); + } ); + unused.forEach( ( value ) => { + setAnalysis( run, value ); + expect( run[name].notAvailable ).toBe( true ); + } ); + stop(); + expect( seen ).toContain( true ); + expect( seen ).toContain( false ); + } ); + + it( 'numRepetitionsNg is available for the bootstrap analyses of RAxML-NG', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + const { seen, stop } = track( () => run.numRepetitionsNg.notAvailable ); + setAnalysis( run, 'TI' ); + setAnalysis( run, 'ML+tBS+con' ); + stop(); + expect( seen ).toEqual( [false, true, false] ); + } ); + + it( 'numRuns is available for RAxML-NG tree inference', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + setAnalysis( run, 'TI' ); + expect( run.numRuns.notAvailable ).toBe( false ); + setAnalysis( run, 'SC' ); + expect( run.numRuns.notAvailable ).toBe( true ); + } ); +} ); + +describe( 'option lists', () => { + it( 'lists the values the run offers', () => { + const run = newRun(); + const values = ( option ) => option.options.map( ( o ) => o.value ); + expect( values( run.numRuns ) ).toEqual( [1, 10, 20, 50, 100, 500] ); + expect( values( run.numRepetitions ) ).toEqual( + [100, 200, 500, 1000, 10000, 'autoMR', 'autoMRE', 'autoMRE_IGN', 'autoFC'], + ); + expect( values( run.numRepetitionsNg ) ).toEqual( + [100, 200, 500, 1000, 10000, 'autoMRE'], + ); + expect( values( run.startingTree ) ).toEqual( ['Maximum parsimony', 'User defined'] ); + expect( values( run.baseFrequencies ) ).toEqual( ['default', 'F', 'X'] ); + expect( values( run.aaMatrixName ).length ).toBeGreaterThan( 0 ); + expect( values( run.multistateModel ).length ).toBeGreaterThan( 0 ); + } ); +} ); + +describe( 'CombinedOutput', () => { + it( 'is used only when checked and available', () => { + const run = newRun(); + setAnalysis( run, 'ML' ); + const { seen, stop } = track( () => run.combinedOutput.isUsed ); + set( run.combinedOutput, true ); + setAnalysis( run, 'FT' ); + stop(); + expect( seen.map( Boolean ) ).toEqual( [false, true, false] ); + } ); +} ); + +describe( 'option values reach the run command', () => { + it( 'branchLength and sHlike add their follow-up commands', () => { + const run = newRun(); + set( run.binary, plain.name ); + setAnalysis( run, 'FT' ); + const { seen, stop } = track( () => run.command ); + set( run.branchLength, true ); + set( run.sHlike, true ); + stop(); + const steps = ( command ) => command.split( ' &&\\\n' ).length; + expect( seen.map( steps ) ).toEqual( [1, 2, 3] ); + } ); + + it( 'numRuns and numRepetitions change the command', () => { + const run = newRun(); + set( run.binary, plain.name ); + setAnalysis( run, 'ML' ); + const runs = track( () => run.command ); + set( run.numRuns, 10 ); + runs.stop(); + expect( runs.seen[0] ).toContain( '-N 1 ' ); + expect( runs.seen[1] ).toContain( '-N 10 ' ); + + setAnalysis( run, 'ML+rBS' ); + const reps = track( () => run.command ); + set( run.numRepetitions, 200 ); + reps.stop(); + expect( reps.seen[0] ).toContain( '100' ); + expect( reps.seen[1] ).toContain( '200' ); + } ); + + it( 'numRepetitionsNg changes the RAxML-NG command', () => { + const run = newRun(); + set( run.binary, 'raxml-ng' ); + setAnalysis( run, 'ML+tBS+con' ); + const { seen, stop } = track( () => run.command ); + set( run.numRepetitionsNg, 500 ); + stop(); + expect( seen[0] ).toContain( '100' ); + expect( seen[1] ).toContain( '500' ); + } ); +} ); + +describe( 'data type options', () => { + it( 'AAMatrixName is available only for protein', () => { + const run = newRun(); + const { seen, stop } = track( () => run.aaMatrixName.notAvailable ); + addAlignment( run, 'protein' ); + stop(); + expect( seen ).toEqual( [true, false] ); + expect( run.aaMatrixName.value ).toBe( 'BLOSUM62' ); + } ); + + + it( 'EstimatedFrequencies is unavailable for protein and RAxML-NG', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.estimatedFrequencies.notAvailable ); + addAlignment( run, 'protein' ); + stop(); + expect( seen ).toEqual( [false, true] ); + const ng = newRun(); + set( ng.binary, 'raxml-ng' ); + expect( ng.estimatedFrequencies.notAvailable ).toBe( true ); + } ); + + it( 'BaseFrequencies is available only for protein with RAxML', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.baseFrequencies.notAvailable ); + addAlignment( run, 'protein' ); + set( run.binary, 'raxml-ng' ); + stop(); + expect( seen ).toEqual( [true, false, true] ); + } ); + + it( 'MultistateModel is available only for multistate with RAxML', () => { + const run = newRun(); + set( run.binary, plain.name ); + const { seen, stop } = track( () => run.multistateModel.notAvailable ); + addAlignment( run, 'multistate' ); + set( run.binary, 'raxml-ng' ); + stop(); + expect( seen ).toEqual( [true, false, true] ); + expect( run.multistateModel.value ).toBe( 'GTR' ); + } ); + + it( 'value changes of the data type options reach reactions', () => { + const run = newRun(); + set( run.binary, plain.name ); + addAlignment( run, 'multistate' ); + setAnalysis( run, 'FT' ); + const { seen, stop } = track( () => run.command ); + set( run.multistateModel, 'ORDERED' ); + stop(); + expect( seen[0] ).toContain( '-K GTR' ); + expect( seen[1] ).toContain( '-K ORDERED' ); + } ); + + it( 'EstimatedFrequencies adds X to the model for nucleotide data', () => { + const run = newRun(); + addAlignment( run, 'nucleotide' ); + const { seen, stop } = track( () => run.raxmlSubstitutionModelCmd ); + set( run.estimatedFrequencies, true ); + stop(); + expect( seen[1] ).toBe( `${seen[0]}X` ); + } ); + + it( 'BaseFrequencies adds its suffix to the model for protein data', () => { + const run = newRun(); + addAlignment( run, 'protein' ); + const { seen, stop } = track( () => run.raxmlSubstitutionModelCmd ); + set( run.baseFrequencies, 'F' ); + set( run.baseFrequencies, 'default' ); + stop(); + expect( seen[1] ).toBe( `${seen[0]}F` ); + expect( seen[2] ).toBe( seen[0] ); + } ); + + // No page store computed reads these two values, so the reaction reads them itself. + it( 'a reaction on StartingTree and AAMatrixName values updates when they are set', () => { + const run = newRun(); + const { seen, stop } = track( () => [run.startingTree.value, run.aaMatrixName.value] ); + set( run.startingTree, 'User defined' ); + set( run.aaMatrixName, 'WAG' ); + stop(); + expect( seen ).toEqual( [ + ['Maximum parsimony', 'BLOSUM62'], + ['User defined', 'BLOSUM62'], + ['User defined', 'WAG'], + ] ); + } ); +} ); From a2cccb27cca626a6912e951b0a7764cca653af6d Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:45:44 +0100 Subject: [PATCH 22/54] Cover the run's lifecycle actions on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/runLifecycle.test.js | 354 +++++++++++++++++++++++++++++ 1 file changed, 354 insertions(+) create mode 100644 src/app/store/runLifecycle.test.js diff --git a/src/app/store/runLifecycle.test.js b/src/app/store/runLifecycle.test.js new file mode 100644 index 00000000..24d5208c --- /dev/null +++ b/src/app/store/runLifecycle.test.js @@ -0,0 +1,354 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { runEvents } from './StoreBase'; + +let listeners; +let bridge; + +function subscribeTo( byName, name ) { + return ( listener ) => { + ( byName[name] ||= [] ).push( listener ); + return () => { + byName[name] = byName[name].filter( ( l ) => l !== listener ); + }; + }; +} + +// The run subscribes to bridge events at construction; keep each listener so a test can fire it. +beforeEach( () => { + listeners = {}; + bridge = { + startRun: jest.fn( async () => {} ), + startAstral: jest.fn( async () => {} ), + cancelRun: jest.fn(), + writeFile: jest.fn( async () => {} ), + checkOutput: jest.fn( async () => ( { ok: true, resultFilenames: ['out.tre'] } ) ), + parseAlignment: () => new Promise( () => {} ), + }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = subscribeTo( listeners, name ); + } + window.rendererBridge = bridge; +} ); + +function fire( name, payload ) { + ( listeners[name] || [] ).forEach( ( listener ) => listener( payload ) ); +} + +// Records every value a reaction sees, so a test can prove it re-ran. +function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} + +function makeRun( { numSequences = 4 } = {} ) { + const parent = { onError: jest.fn() }; + const run = new Run( parent, 7 ); + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + run.alignments[0].sequences = Array.from( { length: numSequences }, ( _, i ) => ( { + taxon: `T${i}`, + } ) ); + run.setOutputDir( '/out' ); + return { run, parent }; +} + +describe( 'start', () => { + it( 'marks the run running and starts it on the bridge', async () => { + const { run } = makeRun(); + const startDisabled = track( () => run.startDisabled ); + expect( startDisabled.seen.at( -1 ) ).toBe( false ); + + await run.start(); + + expect( run.running ).toBe( true ); + expect( bridge.startRun ).toHaveBeenCalledTimes( 1 ); + expect( bridge.startRun.mock.calls[0][0] ).toMatchObject( { + id: 7, + binaryName: run.binary.value, + outputDir: '/out', + inputPath: '/data/primates.fasta', + } ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + startDisabled.stop(); + } ); + + it( 'writes the settings file before starting', async () => { + const { run } = makeRun(); + await run.start(); + expect( bridge.writeFile ).toHaveBeenCalledWith( + run.settingsFilePath, + run.settingsFileContent, + ); + } ); + + it( 'reports an error and does not start with fewer than four sequences', async () => { + const { run, parent } = makeRun( { numSequences: 3 } ); + + await run.start(); + + expect( parent.onError ).toHaveBeenCalledTimes( 1 ); + expect( parent.onError.mock.calls[0][0].message ).toMatch( /at least four sequences/ ); + expect( run.running ).toBe( false ); + expect( bridge.startRun ).not.toHaveBeenCalled(); + } ); + + it( 'adopts the safe output name, which a reaction on the name sees', async () => { + const { run } = makeRun(); + bridge.checkOutput = jest.fn( async () => ( { + ok: false, + outputNameUnused: 'primates_2', + resultFilenames: [], + } ) ); + const name = track( () => run.outputName ); + const safe = track( () => run.outputNameSafe ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + expect( safe.seen.at( -1 ) ).toBe( 'primates_2' ); + + await run.start(); + + expect( run.outputName ).toBe( 'primates_2' ); + expect( name.seen.at( -1 ) ).toBe( 'primates_2' ); + name.stop(); + safe.stop(); + } ); +} ); + +describe( 'streamed output', () => { + it( 'appends stdout and stderr for this run only, and reactions see it', () => { + const { run } = makeRun(); + const report = track( () => run.generateReport().stdout ); + const stderr = track( () => run.stderr ); + + fire( runEvents.onRunStdout, { id: 7, content: 'tree\n' } ); + fire( runEvents.onRunStdout, { id: 7, content: 'more\n' } ); + fire( runEvents.onRunStdout, { id: 8, content: 'other run' } ); + fire( runEvents.onRunStderr, { id: 7, content: 'warn\n' } ); + fire( runEvents.onRunStderr, { id: 8, content: 'other run' } ); + + expect( run.stdout ).toBe( 'tree\nmore\n' ); + expect( run.stderr ).toBe( 'warn\n' ); + expect( report.seen.at( -1 ) ).toBe( 'tree\nmore\n' ); + expect( stderr.seen.at( -1 ) ).toBe( 'warn\n' ); + report.stop(); + stderr.stop(); + } ); + + it( 'clearing the console empties both streams for reactions', () => { + const { run } = makeRun(); + fire( runEvents.onRunStdout, { id: 7, content: 'a' } ); + fire( runEvents.onRunStderr, { id: 7, content: 'b' } ); + const both = track( () => `${run.stdout}|${run.stderr}` ); + + run.clearConsole(); + + expect( both.seen.at( -1 ) ).toBe( '|' ); + both.stop(); + } ); +} ); + +describe( 'finish', () => { + it( 'records the result and frees the run', async () => { + const { run } = makeRun(); + const startDisabled = track( () => run.startDisabled ); + const finished = track( () => [run.finished, run.exitCode] ); + const haveResult = track( () => run.haveResult ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + runInAction( () => { + run.running = true; + } ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + expect( haveResult.seen.at( -1 ) ).toBe( false ); + + fire( runEvents.onRunFinished, { + id: 7, + resultDir: '/out', + resultFilenames: ['out.tre'], + exitCode: 0, + } ); + + expect( run.resultDir ).toBe( '/out' ); + expect( run.finished ).toBe( true ); + expect( run.exitCode ).toBe( 0 ); + expect( run.running ).toBe( false ); + expect( startDisabled.seen.at( -1 ) ).toBe( false ); + expect( finished.seen.at( -1 ) ).toEqual( [true, 0] ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + expect( haveResult.seen.at( -1 ) ).toBe( true ); + startDisabled.stop(); + finished.stop(); + haveResult.stop(); + } ); + + it( 'records a non-zero exit code and clearFinished resets it', () => { + const { run } = makeRun(); + const finished = track( () => [run.finished, run.exitCode] ); + + fire( runEvents.onRunFinished, { + id: 7, + resultDir: '/out', + resultFilenames: [], + exitCode: 2, + } ); + expect( finished.seen.at( -1 ) ).toEqual( [true, 2] ); + + run.clearFinished(); + expect( finished.seen.at( -1 ) ).toEqual( [false, 0] ); + finished.stop(); + } ); + + it( 'ignores a finish for another run', () => { + const { run } = makeRun(); + runInAction( () => { + run.running = true; + } ); + + fire( runEvents.onRunFinished, { id: 8, resultDir: '/x', resultFilenames: [], exitCode: 1 } ); + + expect( run.finished ).toBe( false ); + expect( run.running ).toBe( true ); + expect( run.resultDir ).toBe( '' ); + } ); + + it( 'checks the output again after the run, so the result list refreshes', async () => { + const { run } = makeRun(); + const files = track( () => run.resultFilenames ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + const before = bridge.checkOutput.mock.calls.length; + + fire( runEvents.onRunFinished, { + id: 7, + resultDir: '/out', + resultFilenames: ['out.tre'], + exitCode: 0, + } ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + + expect( bridge.checkOutput.mock.calls.length ).toBeGreaterThan( before ); + expect( files.seen.at( -1 ) ).toEqual( ['out.tre'] ); + files.stop(); + } ); +} ); + +describe( 'failure', () => { + it( 'shows the error, frees the run, and ok follows the error', () => { + const { run } = makeRun(); + runInAction( () => { + run.running = true; + } ); + const ok = track( () => run.ok ); + const error = track( () => run.error ); + expect( ok.seen.at( -1 ) ).toBe( true ); + + fire( runEvents.onRunError, { id: 7, error: 'missing binary' } ); + + expect( run.error ).toBe( 'missing binary' ); + expect( run.running ).toBe( false ); + expect( run.finished ).toBe( false ); + expect( ok.seen.at( -1 ) ).toBe( false ); + expect( error.seen.at( -1 ) ).toBe( 'missing binary' ); + + run.clearError(); + expect( ok.seen.at( -1 ) ).toBe( true ); + ok.stop(); + error.stop(); + } ); + + it( 'ignores an error for another run', () => { + const { run } = makeRun(); + + fire( runEvents.onRunError, { id: 8, error: 'not mine' } ); + + expect( run.error ).toBe( null ); + } ); +} ); + +describe( 'cancel', () => { + it( 'tells the bridge, frees the run, and stays quiet', () => { + const { run, parent } = makeRun(); + runInAction( () => { + run.running = true; + } ); + const startDisabled = track( () => run.startDisabled ); + const ok = track( () => run.ok ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + + run.cancel(); + + expect( bridge.cancelRun ).toHaveBeenCalledWith( 7 ); + expect( run.running ).toBe( false ); + expect( startDisabled.seen.at( -1 ) ).toBe( false ); + expect( run.error ).toBe( null ); + expect( ok.seen.at( -1 ) ).toBe( true ); + expect( run.finished ).toBe( false ); + expect( parent.onError ).not.toHaveBeenCalled(); + startDisabled.stop(); + ok.stop(); + } ); + + it( 'stops a start that is still writing files from starting the run', async () => { + const { run } = makeRun(); + let release; + bridge.writeFile = jest.fn( + () => new Promise( ( resolve ) => { + release = resolve; + } ), + ); + + const pending = run.start(); + run.cancel(); + release(); + await pending; + + expect( bridge.startRun ).not.toHaveBeenCalled(); + expect( run.running ).toBe( false ); + expect( run.error ).toBe( null ); + } ); + + it( 'dispose cancels the run and unsubscribes its listeners', () => { + const { run } = makeRun(); + + run.dispose(); + + expect( bridge.cancelRun ).toHaveBeenCalledWith( 7 ); + fire( runEvents.onRunStdout, { id: 7, content: 'late' } ); + expect( run.stdout ).toBe( '' ); + } ); +} ); + +describe( 'ASTRAL', () => { + it( 'shows ASTRAL is running and starts it on the bridge', async () => { + const { run } = makeRun(); + const startDisabled = track( () => run.startDisabled ); + + await run.startAstral(); + + expect( run.running ).toBe( true ); + expect( startDisabled.seen.at( -1 ) ).toBe( true ); + expect( bridge.startAstral ).toHaveBeenCalledWith( { + id: 7, + binaryName: run.binary.value, + args: run.args, + } ); + startDisabled.stop(); + } ); + + it( 'reports the ASTRAL result for this run', () => { + const { run } = makeRun(); + runInAction( () => { + run.running = true; + } ); + const finished = track( () => [run.finished, run.exitCode, run.running] ); + + fire( runEvents.onAstralSuccess, { id: 8, exitCode: 4 } ); + expect( finished.seen.at( -1 ) ).toEqual( [false, 0, true] ); + + fire( runEvents.onAstralSuccess, { id: 7, exitCode: 0 } ); + + expect( run.resultDir ).toBe( '/out' ); + expect( finished.seen.at( -1 ) ).toEqual( [true, 0, false] ); + finished.stop(); + } ); +} ); From 77c1ff7364117dbca3460291c40b5aca960265e1 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:46:10 +0100 Subject: [PATCH 23/54] Cover the run's option and input-file actions on MobX 5 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/runInputActions.test.js | 321 ++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 src/app/store/runInputActions.test.js diff --git a/src/app/store/runInputActions.test.js b/src/app/store/runInputActions.test.js new file mode 100644 index 00000000..cc1c27f6 --- /dev/null +++ b/src/app/store/runInputActions.test.js @@ -0,0 +1,321 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; + +const stayParsed = async () => ( { + alignment: { + sequences: [], + fileFormat: 'fasta', + numSequences: 0, + length: 0, + dataType: 'dna', + hasInvariantSites: false, + typecheckingComplete: true, + }, + change: null, +} ); + +const checkOutput = jest.fn( async ( { outputName } ) => ( { + ok: true, + outputNameUnused: outputName, + resultFilenames: [], +} ) ); + +const flush = () => new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); + +// Runs `read` in an autorun and returns every value it saw, newest last. +function watch( read ) { + const seen = []; + const dispose = autorun( () => seen.push( read() ) ); + return { seen, dispose }; +} + +let run; + +beforeEach( () => { + checkOutput.mockClear(); + window.rendererBridge = { parseAlignment: stayParsed, checkOutput }; + run = new Run( {}, 7 ); +} ); + +describe( 'output name and directory', () => { + it( 'setOutputName replaces spaces and trims the name', () => { + run.setOutputName( ' my run ' ); + expect( run.outputName ).toBe( '_my_run_' ); + } ); + + it( 'a new output name reaches the output check and the safe name', async () => { + const { seen, dispose } = watch( () => run.outputNameSafe ); + await flush(); + run.setOutputName( 'primates' ); + await flush(); + dispose(); + + expect( checkOutput ).toHaveBeenLastCalledWith( { + outputDir: '', + outputName: 'primates', + } ); + expect( seen[seen.length - 1] ).toBe( 'primates' ); + } ); + + it( 'setOutputDir sets the directory and moves the settings file path', () => { + const { seen, dispose } = watch( () => run.settingsFilePath ); + run.setOutputDir( '/out' ); + dispose(); + + expect( run.outputDir ).toBe( '/out' ); + expect( seen[seen.length - 1] ).toContain( '/out' ); + expect( seen[seen.length - 1] ).toContain( 'RAxML_GUI_Settings_' ); + } ); + + it( 'openOutputDir opens the output directory', async () => { + const openPath = jest.fn( async () => {} ); + window.rendererBridge = { checkOutput, openPath }; + run.setOutputDir( '/out' ); + + await run.openOutputDir(); + + expect( openPath ).toHaveBeenCalledWith( '/out' ); + } ); +} ); + +describe( 'random seed', () => { + it( 'setRandomSeed accepts a number and the seeds follow', () => { + const { seen, dispose } = watch( () => run.seedBootstrap ); + run.setRandomSeed( '12345' ); + dispose(); + + expect( run.randomSeed ).toBe( 12345 ); + expect( run.seedParsimony ).toBe( 12345 ); + expect( run.seedRapidBootstrap ).toBe( 12345 ); + expect( seen[seen.length - 1] ).toBe( 12345 ); + } ); + + it.each( [ '0', 'abc', '1000000', '2000000' ] )( + 'setRandomSeed ignores %s', + ( value ) => { + run.setRandomSeed( '42' ); + run.setRandomSeed( value ); + expect( run.randomSeed ).toBe( 42 ); + }, + ); +} ); + +describe( 'alignments', () => { + it( 'addAlignments adds the paths and names the run after the first', () => { + const { seen, dispose } = watch( () => run.haveAlignments ); + run.addAlignments( [ + { path: '/data/primates.fasta' }, + { path: '/data/cats.phy' }, + ] ); + dispose(); + + expect( run.alignments ).toHaveLength( 2 ); + expect( run.alignments[0].path ).toBe( '/data/primates.fasta' ); + expect( run.outputName ).toBe( run.alignments[0].name ); + expect( run.outputDir ).toBe( run.alignments[0].dir ); + expect( seen ).toEqual( [ false, true ] ); + } ); + + it( 'addAlignments keeps an output directory that is already set', () => { + run.setOutputDir( '/elsewhere' ); + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + expect( run.outputDir ).toBe( '/elsewhere' ); + } ); + + it( 'a loaded alignment lets the partition file load, a second one blocks it', () => { + const { seen, dispose } = watch( () => run.canLoadPartitionFile ); + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + run.addAlignments( [{ path: '/data/cats.phy' }] ); + dispose(); + + expect( seen ).toEqual( [ false, true, false ] ); + } ); + + it( 'removeAlignment removes it and keeps the partition while others remain', async () => { + window.rendererBridge = { + parseAlignment: stayParsed, + checkOutput, + readFile: async () => 'DNA, g = 1-10\n', + }; + run.addAlignments( [ + { path: '/data/primates.fasta' }, + { path: '/data/cats.phy' }, + ] ); + await run.addPartitionFiles( [{ path: '/data/g.part' }] ); + + run.removeAlignment( run.alignments[0] ); + + expect( run.alignments.map( ( a ) => a.path ) ).toEqual( [ '/data/cats.phy' ] ); + expect( run.partitionFile ).toBe( '/data/g.part' ); + } ); + + it( 'removing the last alignment resets the partition file', async () => { + window.rendererBridge = { + parseAlignment: stayParsed, + checkOutput, + readFile: async () => 'DNA, g = 1-10\n', + }; + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + await run.addPartitionFiles( [{ path: '/data/g.part' }] ); + const { seen, dispose } = watch( () => run.haveAlignments ); + + run.removeAlignment( run.alignments[0] ); + dispose(); + + expect( seen ).toEqual( [ true, false ] ); + expect( run.partitionFile ).toBe( '' ); + expect( run.partitionFileContent ).toBe( '' ); + } ); + + it( 'removeAlignment ignores an alignment the run does not hold', () => { + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + const other = new Run( {}, 8 ); + other.addAlignments( [{ path: '/data/other.fasta' }] ); + + run.removeAlignment( other.alignments[0] ); + + expect( run.alignments ).toHaveLength( 1 ); + } ); + + it( 'showPartition marks that alignment as shown, hidePartition clears it', () => { + run.addAlignments( [{ path: '/data/primates.fasta' }] ); + const [ alignment ] = run.alignments; + const { seen, dispose } = watch( () => alignment.showPartition ); + + run.showPartition( alignment ); + expect( run.showPartitionFor ).toBe( alignment ); + run.hidePartition(); + dispose(); + + expect( run.showPartitionFor ).toBeNull(); + expect( seen ).toEqual( [ false, true, false ] ); + } ); +} ); + +describe( 'ASTRAL tree', () => { + it( 'addAstralFiles sets the tree, the name and the directory once', () => { + const { seen, dispose } = watch( () => run.hasAstralTree ); + run.addAstralFiles( { path: '/data/trees.tre' } ); + run.addAstralFiles( { path: '/data/second.tre' } ); + dispose(); + + expect( run.astralTree.path ).toBe( '/data/trees.tre' ); + expect( run.outputName ).toBe( run.astralTree.name ); + expect( run.outputDir ).toBe( run.astralTree.dir ); + expect( seen ).toEqual( [ false, true ] ); + } ); + + it( 'removeAstralTree clears the tree', () => { + run.addAstralFiles( { path: '/data/trees.tre' } ); + const { seen, dispose } = watch( () => run.hasAstralTree ); + + run.removeAstralTree(); + dispose(); + + expect( run.astralTree ).toBeNull(); + expect( seen ).toEqual( [ true, false ] ); + } ); +} ); + +describe( 'partition file', () => { + it( 'loadPartitionFile shows the path and content after the read resolves', async () => { + let finishRead; + const readFile = jest.fn( + () => new Promise( ( resolve ) => { finishRead = resolve; } ), + ); + window.rendererBridge = { + checkOutput, + selectPartitionFile: async () => '/data/genes.part', + readFile, + }; + const { seen, dispose } = watch( () => `${run.partitionFile}|${run.partitionFileContent}` ); + + const loading = run.loadPartitionFile(); + await flush(); + expect( readFile ).toHaveBeenCalledWith( '/data/genes.part' ); + expect( run.partitionFile ).toBe( '' ); + expect( run.partitionFileContent ).toBe( '' ); + + finishRead( 'DNA, gene = 1-100\n' ); + await loading; + dispose(); + + expect( run.partitionFile ).toBe( '/data/genes.part' ); + expect( run.partitionFileContent ).toBe( 'DNA, gene = 1-100\n' ); + expect( seen[seen.length - 1] ).toBe( '/data/genes.part|DNA, gene = 1-100\n' ); + } ); + + it( 'a loaded partition file moves its computeds and blocks the alignment picker', async () => { + window.rendererBridge = { checkOutput, readFile: async () => 'x' }; + const name = watch( () => run.partitionFileName ); + const have = watch( () => run.havePartitionFile ); + const canLoad = watch( () => run.canLoadAlignment ); + + await run.addPartitionFiles( [{ path: '/data/genes.part' }] ); + name.dispose(); + have.dispose(); + canLoad.dispose(); + + expect( name.seen[name.seen.length - 1] ).toBe( 'genes.part' ); + expect( have.seen ).toEqual( [ false, true ] ); + expect( canLoad.seen ).toEqual( [ true, false ] ); + } ); + + it( 'addPartitionFiles with no files changes nothing', async () => { + window.rendererBridge = { checkOutput, readFile: jest.fn() }; + await run.addPartitionFiles( [] ); + expect( run.partitionFile ).toBe( '' ); + expect( window.rendererBridge.readFile ).not.toHaveBeenCalled(); + } ); + + it( 'removePartitionFile clears the path and the content', async () => { + window.rendererBridge = { checkOutput, readFile: async () => 'x' }; + await run.addPartitionFiles( [{ path: '/data/genes.part' }] ); + const { seen, dispose } = watch( () => run.havePartitionFile ); + + run.removePartitionFile(); + dispose(); + + expect( run.partitionFile ).toBe( '' ); + expect( run.partitionFileContent ).toBe( '' ); + expect( seen ).toEqual( [ true, false ] ); + } ); +} ); + +describe( 'tree files', () => { + it.each( [ 'tree', 'backboneConstraint', 'multifurcatingConstraint' ] )( + 'addTreeFiles sets the %s file', + ( type ) => { + const { seen, dispose } = watch( () => run[type].haveFile ); + run.addTreeFiles( type, [{ path: '/data/t.nwk' }] ); + dispose(); + + expect( run[type].filePath ).toBe( '/data/t.nwk' ); + expect( run[type].filename ).toBe( 't.nwk' ); + expect( seen ).toEqual( [ false, true ] ); + }, + ); + + it( 'addTreeFiles ignores an unknown type and an empty list', () => { + run.addTreeFiles( 'other', [{ path: '/data/t.nwk' }] ); + run.addTreeFiles( 'tree', [] ); + + expect( run.tree.filePath ).toBe( '' ); + expect( run.backboneConstraint.filePath ).toBe( '' ); + expect( run.multifurcatingConstraint.filePath ).toBe( '' ); + } ); +} ); + +describe( 'state set directly', () => { + it( 'setting the alignments inside runInAction moves numSites', () => { + const { seen, dispose } = watch( () => run.numSites ); + runInAction( () => { + run.alignments = [ 3, 4 ]; + } ); + dispose(); + + expect( seen ).toEqual( [ 0, 7 ] ); + } ); +} ); From 3179e60ed07833a790968f88ed66051d88eb73d8 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 01:46:26 +0100 Subject: [PATCH 24/54] Cover the run's computeds on MobX 5 (#136) Pins binary flags, analysis options, alignment-derived values, start gating, output-name fields and the command preview. Overlaps checkOutputName.test.js on the taken-name case; left in place. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Run.computeds.test.js | 396 ++++++++++++++++++++++++++++ 1 file changed, 396 insertions(+) create mode 100644 src/app/store/Run.computeds.test.js diff --git a/src/app/store/Run.computeds.test.js b/src/app/store/Run.computeds.test.js new file mode 100644 index 00000000..28ec2cc2 --- /dev/null +++ b/src/app/store/Run.computeds.test.js @@ -0,0 +1,396 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import { analysisOptions, binaries } from './RunOptions'; +import { runEvents } from './StoreBase'; + +const modeltestName = binaries.find( ( b ) => b.type === 'modeltest' ).name; + +let checkOutput; +let stops = []; + +// The run subscribes to bridge events in its constructor; the stub accepts and ignores them. +beforeEach( () => { + stops = []; + checkOutput = jest.fn( async ( { outputName } ) => ( { + ok: true, + outputNameUnused: outputName, + resultFilenames: [], + } ) ); + const bridge = { checkOutput, getVersion: () => Promise.resolve( '2.0.0' ) }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = () => () => {}; + } + window.rendererBridge = bridge; +} ); + +afterEach( () => stops.forEach( ( stop ) => stop() ) ); + +const nucleotide = ( over = {} ) => ( { + name: 'a.fasta', + path: '/in/a.fasta', + filename: 'a.fasta', + dir: '/in', + taxons: ['t1', 't2', 't3'], + length: 10, + dataType: 'nucleotide', + modified: false, + converted: false, + showModifiedSnack: false, + showModifiedDialog: false, + modeltestLoading: false, + modificationMessages: [], + ngSubstitutionModelCmd: 'GTR+G', + partition: { isDefault: true, isComplete: true }, + ...over, +} ); + +function makeRun( { alignments = [nucleotide()], binary = 'raxmlHPC', outputDir = '/out' } = {} ) { + const run = new Run( null, 1 ); + runInAction( () => { + run.binary.value = binary; + run.outputDir = outputDir; + run.alignments = alignments; + } ); + // analysis is a computed that builds its option; keep it observed so a set value sticks. + stops.push( autorun( () => run.analysis ) ); + return run; +} + +// outputNameAvailable only works inside a reaction, so reads that touch it go through here. +function read( fn ) { + let value; + autorun( () => { + value = fn(); + } )(); + return value; +} + +// outputNameAvailable is async and only computes while observed. +async function observeOutput( run ) { + stops.push( autorun( () => run.outputNameAvailable.get() ) ); + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); +} + +describe( 'Run binary computeds', () => { + it( 'maps the binary to its flags', () => { + const run = makeRun( { binary: 'raxml-ng' } ); + expect( [run.usesRaxmlNg, run.usesRaxml, run.usesModeltest, run.usesAstral] ) + .toEqual( [true, true, false, false] ); + expect( [run.inputIsAlignment, run.inputIsTree] ).toEqual( [true, false] ); + runInAction( () => { + run.binary.value = 'raxmlHPC'; + } ); + expect( [run.usesRaxmlNg, run.usesRaxml] ).toEqual( [false, true] ); + runInAction( () => { + run.binary.value = modeltestName; + } ); + expect( [run.usesModeltestNg, run.usesModeltest, run.usesRaxml] ) + .toEqual( [true, true, false] ); + expect( run.inputIsAlignment ).toBe( true ); + } ); + + it( 'analysis and analysisOption follow the binary family', () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + expect( run.analysisOption.title ).toBe( 'Fast tree search' ); + runInAction( () => { + run.binary.value = 'raxml-ng'; + } ); + expect( run.analysisOption.value ).toBe( run.analysis.value ); + expect( run.analysisOption.title ).not.toBe( 'Fast tree search' ); + } ); + + it( 'haveRandomSeed is true only for analyses that take a seed', () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + expect( run.haveRandomSeed ).toBe( true ); + run.analysis.setValue( 'SC' ); + expect( run.haveRandomSeed ).toBe( false ); + } ); + + it( 'the three seeds mirror randomSeed', () => { + const run = makeRun(); + run.setRandomSeed( 42 ); + expect( [run.seedParsimony, run.seedRapidBootstrap, run.seedBootstrap] ) + .toEqual( [42, 42, 42] ); + } ); +} ); + +describe( 'Run alignment computeds', () => { + it( 'haveAlignments, taxons and numSites follow the alignments', () => { + const run = makeRun( { alignments: [] } ); + expect( run.haveAlignments ).toBe( false ); + expect( run.taxons ).toEqual( [] ); + runInAction( () => { + run.alignments = [nucleotide()]; + } ); + expect( run.haveAlignments ).toBe( true ); + expect( run.taxons ).toEqual( ['t1', 't2', 't3'] ); + expect( run.dataType ).toBe( 'nucleotide' ); + } ); + + it( 'hasAstralTree and canLoadAstralTree follow the tree', () => { + const run = makeRun(); + expect( run.hasAstralTree ).toBe( false ); + expect( run.canLoadAstralTree ).toBe( false ); + runInAction( () => { + run.astralTree = { path: '/in/t.tre' }; + } ); + expect( run.hasAstralTree ).toBe( true ); + } ); + + it( 'canLoadAlignment is false once a partition file is loaded', () => { + const run = makeRun(); + expect( run.canLoadAlignment ).toBe( true ); + runInAction( () => { + run.partitionFile = '/in/parts.txt'; + } ); + expect( run.havePartitionFile ).toBe( true ); + expect( run.partitionFileName ).toBe( 'parts.txt' ); + expect( run.canLoadAlignment ).toBe( false ); + expect( run.canLoadPartitionFile ).toBe( false ); + } ); + + it( 'canLoadPartitionFile needs exactly one alignment', () => { + const one = makeRun(); + expect( one.canLoadPartitionFile ).toBe( true ); + const two = makeRun( { alignments: [nucleotide(), nucleotide()] } ); + expect( two.canLoadPartitionFile ).toBe( false ); + } ); + + it( 'modified flags are true when any alignment is flagged', () => { + const run = makeRun( { + alignments: [ + nucleotide(), + nucleotide( { + name: 'b.fasta', + modified: true, + converted: true, + convertedFrom: 'phylip', + showModifiedSnack: true, + showModifiedDialog: true, + modificationMessages: ['fixed names'], + } ), + ], + } ); + expect( run.modified ).toBe( true ); + expect( run.converted ).toBe( true ); + expect( run.convertedAlignmentFrom ).toBe( 'phylip' ); + expect( run.showModifiedSnack ).toBe( true ); + expect( run.showModifiedDialog ).toBe( true ); + expect( run.modificationMessages ).toEqual( [ + 'a.fasta:\n', 'b.fasta:\n', 'fixed names\n', + ] ); + } ); + + it( 'modified flags are false without alignments', () => { + const run = makeRun( { alignments: [] } ); + expect( [run.modified, run.converted, run.showModifiedSnack, run.showModifiedDialog] ) + .toEqual( [false, false, false, false] ); + expect( run.convertedAlignmentFrom ).toBe( null ); + expect( run.ngSubstitutionModelCmd ).toBe( '' ); + } ); + + it( 'modelTestIsRunningOnAlignment and modelTestCanRun', () => { + const run = makeRun( { alignments: [nucleotide( { modeltestLoading: true } )] } ); + expect( run.modelTestIsRunningOnAlignment ).toBe( true ); + expect( run.modelTestCanRun ).toBe( true ); + runInAction( () => { + run.alignments[0].dataType = 'multistate'; + run.alignments[0].modeltestLoading = false; + } ); + expect( run.modelTestIsRunningOnAlignment ).toBe( false ); + expect( run.modelTestCanRun ).toBe( false ); + } ); + + it( 'ngSubstitutionModelCmd comes from the first alignment', () => { + expect( makeRun().ngSubstitutionModelCmd ).toBe( 'GTR+G' ); + } ); + + it( 'numSites is 0 without alignments', () => { + expect( makeRun( { alignments: [] } ).numSites ).toBe( 0 ); + } ); + + it( 'needAlignment is always true', () => { + expect( makeRun().needAlignment ).toBe( true ); + } ); +} ); + +describe( 'Run state computeds', () => { + it( 'missing asks for a tree only for an analysis that needs one', () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + const needsTree = analysisOptions.find( ( o ) => o.params.includes( 'tree' ) ); + run.analysis.setValue( 'FT' ); + expect( run.missing ).toBe( '' ); + run.analysis.setValue( needsTree.value ); + expect( run.missing ).toBe( 'Missing tree, please load one.' ); + expect( run.ok ).toBe( false ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'ok is false while an error is set', () => { + const run = makeRun(); + const { missing } = run; + expect( run.ok ).toBe( !missing ); + runInAction( () => { + run.error = 'boom'; + } ); + expect( run.ok ).toBe( false ); + } ); + + it( 'startDisabled is true without alignments or tree', () => { + expect( makeRun( { alignments: [] } ).startDisabled ).toBe( true ); + } ); + + it( 'startDisabled is true while running or in error', () => { + const run = makeRun(); + runInAction( () => { + run.error = 'boom'; + } ); + expect( run.startDisabled ).toBe( true ); + runInAction( () => { + run.error = null; + run.running = true; + } ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'startDisabled is true while an alignment runs model test', () => { + const run = makeRun( { alignments: [nucleotide( { modeltestLoading: true } )] } ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'startDisabled is true when the partition is incomplete', () => { + const run = makeRun( { + alignments: [nucleotide( { partition: { isDefault: false, isComplete: false } } )], + } ); + expect( run.startDisabled ).toBe( true ); + } ); + + it( 'modeltest-ng cannot start on several alignments', () => { + const run = makeRun( { + binary: modeltestName, + alignments: [nucleotide(), nucleotide()], + } ); + expect( run.startDisabled ).toBe( true ); + } ); +} ); + +describe( 'Run output computeds', () => { + it( 'output name falls back to the placeholder and reports no notice', async () => { + const run = makeRun(); + await observeOutput( run ); + expect( read( () => run.outputNameOk ) ).toBe( true ); + expect( read( () => run.outputNameSafe ) ).toBe( 'output' ); + expect( read( () => run.outputFilenameSafe ) ).toBe( 'output.tre' ); + expect( read( () => run.outputNameNotice ) ).toBe( '' ); + expect( checkOutput ).toHaveBeenCalledWith( { outputDir: '/out', outputName: 'output' } ); + } ); + + it( 'a taken output name shows the notice with the unused name', async () => { + checkOutput.mockResolvedValue( { + ok: false, + outputNameUnused: 'output_2', + resultFilenames: ['a.tre'], + } ); + const run = makeRun(); + await observeOutput( run ); + expect( read( () => run.outputNameOk ) ).toBe( false ); + expect( read( () => run.outputNameSafe ) ).toBe( 'output_2' ); + expect( read( () => run.outputFilenameSafe ) ).toBe( 'output_2.tre' ); + expect( read( () => run.outputNameNotice ) ) + .toBe( "Output with that id already exists. New run will use output id 'output_2'" ); + expect( read( () => run.resultFilenames ) ).toEqual( ['a.tre'] ); + } ); + + it( 'haveResult needs result files from the current output directory', async () => { + checkOutput.mockResolvedValue( { ok: false, outputNameUnused: 'x', resultFilenames: ['a.tre'] } ); + const run = makeRun(); + await observeOutput( run ); + runInAction( () => { + run.resultDir = '/other'; + } ); + expect( read( () => run.haveResult ) ).toBe( false ); + runInAction( () => { + run.resultDir = '/out'; + } ); + expect( read( () => run.haveResult ) ).toBe( true ); + } ); + + it( 'the settings file path and content use the output name and args', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + await observeOutput( run ); + expect( read( () => run.settingsFilePath ) ).toBe( '/out/RAxML_GUI_Settings_output.txt' ); + const content = read( () => run.settingsFileContent ); + expect( content ).toContain( 'Analysis: Fast tree search' ); + expect( content ).toContain( 'Binary: raxmlHPC version 8.2.12' ); + expect( content ).toContain( 'Results saved to: /out' ); + expect( content ).toContain( `1.) ${read( () => run.args )[0].join( ' ' )}` ); + } ); +} ); + +describe( 'Run command', () => { + it( 'starts with the binary and carries the paths and output name', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + await observeOutput( run ); + const command = read( () => run.command ); + expect( command.startsWith( 'raxmlHPC ' ) ).toBe( true ); + expect( command ).toContain( '-f E' ); + expect( command ).toContain( '-n output.tre' ); + expect( command ).toContain( '-s /in/a.fasta' ); + expect( command ).toContain( '-w /out' ); + } ); + + it( 'changing an option updates the command preview', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + await observeOutput( run ); + const seen = []; + stops.push( autorun( () => seen.push( run.command ) ) ); + run.analysis.setValue( 'ML' ); + expect( seen[seen.length - 1] ).toContain( '-f d' ); + expect( seen[seen.length - 1] ).not.toBe( seen[0] ); + run.setRandomSeed( 7 ); + expect( seen[seen.length - 1] ).toContain( '-p 7' ); + runInAction( () => { + run.outputDir = '/elsewhere'; + } ); + expect( seen[seen.length - 1] ).toContain( '-w /elsewhere' ); + } ); + + it( 'multiple commands are joined with &&', async () => { + const run = makeRun( { binary: 'raxmlHPC' } ); + run.analysis.setValue( 'FT' ); + run.branchLength.setValue( true ); + await observeOutput( run ); + const args = read( () => run.args ); + expect( args.length ).toBeGreaterThan( 1 ); + expect( read( () => run.command ).split( ' &&\\\n' ) ).toHaveLength( args.length ); + } ); + + it( 'raxml-ng and modeltest-ng build their own command', async () => { + const run = makeRun( { binary: 'raxml-ng' } ); + await observeOutput( run ); + expect( read( () => run.command ).startsWith( 'raxml-ng ' ) ).toBe( true ); + runInAction( () => { + run.binary.value = modeltestName; + } ); + const command = read( () => run.command ); + expect( command.startsWith( `${modeltestName} ` ) ).toBe( true ); + expect( command ).toContain( '-d nt' ); + expect( command ).toContain( '-i /in/a.fasta' ); + } ); + + it( 'raxmlSubstitutionModelCmd adds X for estimated frequencies', () => { + const run = makeRun(); + const before = run.raxmlSubstitutionModelCmd; + runInAction( () => { + run.estimatedFrequencies.value = true; + } ); + expect( run.raxmlSubstitutionModelCmd ).toBe( `${before}X` ); + } ); +} ); From 5ab3cc34321765262ae40762d198a380ca99de9d Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 10:44:34 +0100 Subject: [PATCH 25/54] Drop stale App.test.js typecheck baseline entries Jest types fixed these two errors; the baseline check failed on them as unused. Co-Authored-By: Claude Sonnet 5.5 --- scripts/typecheck-baseline.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index ce174476..3743f8e4 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -6,8 +6,6 @@ src/app/App.js(322,24): error TS2769: No overload matches this call. Property 'title' does not exist on type 'IntrinsicAttributes & SvgIconOwnProps & CommonProps & Omit, "fontSize" | ... 10 more ... | "titleAccess">'. src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is missing the following properties from type '{ error: any; onClose: any; needReload: any; title: any; }': needReload, title src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. -src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. -src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. From 5c664e422c33410d2d42c2d51664f25a6bfac8ce Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 10:48:36 +0100 Subject: [PATCH 26/54] Share the store test bridge stub and reaction recorder Co-Authored-By: Claude Sonnet 5.5 --- jest/storeBridge.js | 29 +++++++++++++++++++++++ src/app/store/alignmentStore.test.js | 35 +++++++--------------------- 2 files changed, 37 insertions(+), 27 deletions(-) create mode 100644 jest/storeBridge.js diff --git a/jest/storeBridge.js b/jest/storeBridge.js new file mode 100644 index 00000000..0e7fd651 --- /dev/null +++ b/jest/storeBridge.js @@ -0,0 +1,29 @@ +import { autorun } from 'mobx'; + +import { runEvents } from '../src/app/store/StoreBase'; + +// Installs a renderer bridge whose run events record their listeners; `extra` adds or overrides methods. +// `listeners[name]` always holds the live subscribers, and `fire` calls them. +export function stubBridge( extra = {} ) { + const listeners = {}; + const bridge = { ...extra }; + for ( const name of Object.values( runEvents ) ) { + bridge[name] = ( listener ) => { + ( listeners[name] ||= [] ).push( listener ); + return () => { + listeners[name] = listeners[name].filter( ( l ) => l !== listener ); + }; + }; + } + window.rendererBridge = bridge; + const fire = ( name, payload ) => + ( listeners[name] || [] ).forEach( ( listener ) => listener( payload ) ); + return { bridge, listeners, fire }; +} + +// Records every value a reaction sees, so a test can prove it re-ran. +export function track( fn ) { + const seen = []; + const stop = autorun( () => seen.push( fn() ) ); + return { seen, stop }; +} diff --git a/src/app/store/alignmentStore.test.js b/src/app/store/alignmentStore.test.js index 624aaa01..bd97d9fa 100644 --- a/src/app/store/alignmentStore.test.js +++ b/src/app/store/alignmentStore.test.js @@ -1,42 +1,23 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. -import { autorun, runInAction } from 'mobx'; +import { runInAction } from 'mobx'; + +import { stubBridge as sharedStubBridge, track } from '../../../jest/storeBridge'; import Run from './Run'; import { runEvents } from './StoreBase'; -let listeners; let bridge; +let listeners; +let fire; -// Alignment construction subscribes to bridge events and parses; this stub is local to this file. +// Alignment construction subscribes to bridge events and parses. function stubBridge( extra = {} ) { - const byName = {}; - listeners = byName; - bridge = { + ( { bridge, listeners, fire } = sharedStubBridge( { parseAlignment: () => new Promise( () => {} ), startModelSelection: jest.fn( async () => {} ), cancelModelSelection: jest.fn(), ...extra, - }; - for ( const name of Object.values( runEvents ) ) { - bridge[name] = ( listener ) => { - ( byName[name] ||= [] ).push( listener ); - return () => { - byName[name] = byName[name].filter( ( l ) => l !== listener ); - }; - }; - } - window.rendererBridge = bridge; -} - -function fire( name, payload ) { - ( listeners[name] || [] ).forEach( ( listener ) => listener( payload ) ); -} - -// Records every value a reaction sees, so a test can prove it re-ran. -function track( fn ) { - const seen = []; - const stop = autorun( () => seen.push( fn() ) ); - return { seen, stop }; + } ) ); } function setup( { onError = () => {}, path = '/data/primates.fasta' } = {} ) { From 2537ec64af337404709f2d7da879adac4723f22a Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 12:08:39 +0100 Subject: [PATCH 27/54] Revert "Drop stale App.test.js typecheck baseline entries" This reverts commit 5ab3cc34321765262ae40762d198a380ca99de9d. --- scripts/typecheck-baseline.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index 3743f8e4..ce174476 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -6,6 +6,8 @@ src/app/App.js(322,24): error TS2769: No overload matches this call. Property 'title' does not exist on type 'IntrinsicAttributes & SvgIconOwnProps & CommonProps & Omit, "fontSize" | ... 10 more ... | "titleAccess">'. src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is missing the following properties from type '{ error: any; onClose: any; needReload: any; title: any; }': needReload, title src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. +src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. +src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. From 35e2af0420333ebaf81de929c30d8f394c6abb4e Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 12:11:18 +0100 Subject: [PATCH 28/54] Skip type-check on the jest store bridge helper Co-Authored-By: Claude Sonnet 5.5 --- jest/storeBridge.js | 1 + 1 file changed, 1 insertion(+) diff --git a/jest/storeBridge.js b/jest/storeBridge.js index 0e7fd651..613730c1 100644 --- a/jest/storeBridge.js +++ b/jest/storeBridge.js @@ -1,3 +1,4 @@ +// @ts-nocheck — Jest helper. checkJs has no jsdom bridge type. import { autorun } from 'mobx'; import { runEvents } from '../src/app/store/StoreBase'; From 91fbbb8bef9740ada9f3995309d642ba7c08de25 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 15:29:01 +0100 Subject: [PATCH 29/54] Prove the page store coverage bar by script scripts/page-store-coverage.js lists every computed and action in the page store and reports which run under jest (164 computeds, 90 actions: 3 not run before this change, 0 after). Tests cover the three it found and the one observable no test named. Co-Authored-By: Claude Sonnet 5.5 --- scripts/page-store-coverage.js | 79 ++++++++++++++++++++++++ src/app/store/pageStoreGaps.test.js | 96 +++++++++++++++++++++++++++++ 2 files changed, 175 insertions(+) create mode 100644 scripts/page-store-coverage.js create mode 100644 src/app/store/pageStoreGaps.test.js diff --git a/scripts/page-store-coverage.js b/scripts/page-store-coverage.js new file mode 100644 index 00000000..3358079d --- /dev/null +++ b/scripts/page-store-coverage.js @@ -0,0 +1,79 @@ +// Lists every @computed and @action in the page store and reports which run +// under jest. Exits 1 when any member is not run. Also lists @observable +// fields whose name appears in no test file (a pointer, not proof). +const { spawnSync } = require( 'child_process' ); +const fs = require( 'fs' ); +const os = require( 'os' ); +const path = require( 'path' ); +const parser = require( '@babel/parser' ); + +const root = path.join( __dirname, '..' ); +const storeDir = path.join( root, 'src/app/store' ); +const files = fs.readdirSync( storeDir ).filter( f => f.endsWith( '.js' ) && !f.endsWith( '.test.js' ) ); +const tests = fs.readdirSync( storeDir ).filter( f => f.endsWith( '.test.js' ) ) + .map( f => fs.readFileSync( path.join( storeDir, f ), 'utf8' ) ).join( '\n' ); + +const covDir = fs.mkdtempSync( path.join( os.tmpdir(), 'page-store-cov-' ) ); +const jest = spawnSync( 'node', [ + 'node_modules/jest/bin/jest.js', '--watchAll=false', '--coverage', '--coverageReporters=json', + `--coverageDirectory=${covDir}`, '--collectCoverageFrom=src/app/store/*.js', + '--collectCoverageFrom=!src/app/store/*.test.js', +], { cwd: root, encoding: 'utf8' } ); +if ( jest.status !== 0 ) { + console.error( jest.stdout, jest.stderr ); + process.exit( 1 ); +} +const coverage = JSON.parse( fs.readFileSync( path.join( covDir, 'coverage-final.json' ), 'utf8' ) ); + +const decoratorName = d => { + let e = d.expression; + if ( e.type === 'CallExpression' ) e = e.callee; + while ( e.type === 'MemberExpression' ) e = e.object; + return e.name; +}; + +const notRun = []; +const noObservableTest = []; +let computeds = 0; +let actions = 0; +let observables = 0; +for ( const file of files ) { + const full = path.join( storeDir, file ); + const ast = parser.parse( fs.readFileSync( full, 'utf8' ), { + sourceType: 'module', plugins: [ 'jsx', 'typescript', [ 'decorators', { decoratorsBeforeExport: true } ], 'classProperties' ], + } ); + const cov = Object.entries( coverage ).find( ( [ p ] ) => p === full )?.[ 1 ]; + const walk = node => { + if ( !node || typeof node.type !== 'string' ) return; + if ( node.type === 'ClassDeclaration' || node.type === 'ClassExpression' ) { + for ( const m of node.body.body ) { + const kind = ( m.decorators || [] ).map( decoratorName ) + .find( n => [ 'computed', 'action', 'observable' ].includes( n ) ); + if ( !kind ) continue; + const name = `${node.id?.name}.${m.key.name}`; + if ( kind === 'observable' ) { + observables += 1; + if ( !new RegExp( `\\b${m.key.name}\\b` ).test( tests ) ) noObservableTest.push( `${file} ${name}` ); + continue; + } + if ( kind === 'computed' ) computeds += 1; else actions += 1; + // The member's own function is the earliest one inside its range. + const fns = cov ? Object.entries( cov.fnMap ) + .filter( ( [ , f ] ) => f.loc.start.line >= m.loc.start.line && f.loc.end.line <= m.loc.end.line ) + .sort( ( [ , a ], [ , b ] ) => a.loc.start.line - b.loc.start.line || a.loc.start.column - b.loc.start.column ) : []; + if ( !fns.length || !cov.f[fns[0][0]] ) notRun.push( `${file}:${m.loc.start.line} ${kind} ${name}` ); + } + } + for ( const v of Object.values( node ) ) { + if ( Array.isArray( v ) ) v.forEach( walk ); else if ( v && typeof v === 'object' ) walk( v ); + } + }; + walk( ast.program ); +} + +console.log( `computeds: ${computeds}, actions: ${actions}, observables: ${observables}` ); +console.log( `members not run: ${notRun.length}` ); +notRun.forEach( l => console.log( ` ${l}` ) ); +console.log( `observables named in no test: ${noObservableTest.length}` ); +noObservableTest.forEach( l => console.log( ` ${l}` ) ); +process.exit( notRun.length ? 1 : 0 ); diff --git a/src/app/store/pageStoreGaps.test.js b/src/app/store/pageStoreGaps.test.js new file mode 100644 index 00000000..1501fbfe --- /dev/null +++ b/src/app/store/pageStoreGaps.test.js @@ -0,0 +1,96 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { autorun, runInAction } from 'mobx'; + +import Run from './Run'; +import RunList from './RunList'; + +let bridge; + +beforeEach( () => { + bridge = { + cancelModelSelection: jest.fn(), + parseAlignment: () => new Promise( () => {} ), + }; + window.rendererBridge = bridge; +} ); + +function makeRun() { + const parent = { onError: jest.fn(), deleteRun: jest.fn() }; + const run = new Run( parent, 7 ); + run.addAlignments( [{ path: '/data/a.fasta' }, { path: '/data/b.fasta' }] ); + return { run, parent }; +} + +describe( 'cancelModeltestOnAlignment', () => { + it( 'cancels the model selection of each loading alignment only', () => { + const { run } = makeRun(); + const [ loading, idle ] = run.alignments; + runInAction( () => { loading.modeltestLoading = true; } ); + + run.cancelModeltestOnAlignment(); + + expect( loading.modeltestLoading ).toBe( false ); + expect( run.modelTestIsRunningOnAlignment ).toBe( false ); + expect( bridge.cancelModelSelection ).toHaveBeenCalledTimes( 1 ); + expect( bridge.cancelModelSelection ).toHaveBeenCalledWith( loading.id ); + expect( idle.modeltestLoading ).toBe( false ); + } ); +} ); + +describe( 'clearShowModified', () => { + it( 'hides the modified snack and dialog on every alignment', () => { + const { run } = makeRun(); + runInAction( () => { + run.alignments.forEach( ( a ) => { + a.showModifiedSnack = true; + a.showModifiedDialog = true; + } ); + } ); + + run.clearShowModified(); + + run.alignments.forEach( ( a ) => { + expect( a.showModifiedSnack ).toBe( false ); + expect( a.showModifiedDialog ).toBe( false ); + } ); + } ); +} ); + +describe( 'removeRun', () => { + it( 'asks the run list to delete this run', () => { + const { run, parent } = makeRun(); + + run.removeRun(); + + expect( parent.deleteRun ).toHaveBeenCalledWith( run ); + } ); + + it( 'removes the run from a real run list', () => { + const list = new RunList(); + list.addRun(); + const [ first, second ] = list.runs; + + second.removeRun(); + + expect( list.runs ).toEqual( [ first ] ); + } ); +} ); + +describe( 'disableCheckUndeterminedSequence', () => { + it( 'is observed by the run: the -O argument follows it', () => { + const { run } = makeRun(); + runInAction( () => { run.binary.value = 'raxmlHPC'; } ); + // analysis is a computed that builds its option; keep it observed so a set value sticks. + const keepAnalysis = autorun( () => run.analysis ); + runInAction( () => { run.analysis.value = 'FT'; } ); + const seen = []; + const stop = autorun( () => seen.push( run.args.flat().includes( '-O' ) ) ); + + runInAction( () => { run.disableCheckUndeterminedSequence = false; } ); + runInAction( () => { run.disableCheckUndeterminedSequence = true; } ); + stop(); + keepAnalysis(); + + expect( seen ).toEqual( [ true, false, true ] ); + } ); +} ); From 2d3c8a14fa265eaf3afe5f920e80a9c1abefda5d Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 15:29:21 +0100 Subject: [PATCH 30/54] Add temporary parity test and baseline for page store annotations (#140) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/annotationParity.baseline.txt | 313 ++++++++++++++++++++ src/app/store/annotationParity.test.js | 59 ++++ 2 files changed, 372 insertions(+) create mode 100644 src/app/store/annotationParity.baseline.txt create mode 100644 src/app/store/annotationParity.test.js diff --git a/src/app/store/annotationParity.baseline.txt b/src/app/store/annotationParity.baseline.txt new file mode 100644 index 00000000..2d2d23e9 --- /dev/null +++ b/src/app/store/annotationParity.baseline.txt @@ -0,0 +1,313 @@ +AAMatrixName.notAvailable +Alignment.aaMatrixName +Alignment.cancelModelTest +Alignment.checkRunComplete +Alignment.checkRunData +Alignment.checkRunSuccess +Alignment.clearModified +Alignment.converted +Alignment.convertedFrom +Alignment.dataType +Alignment.dispose +Alignment.error +Alignment.fileFormat +Alignment.hasInvariantSites +Alignment.hidePartition +Alignment.length +Alignment.loading +Alignment.modelExtra +Alignment.modelTestCanRun +Alignment.modeltestLoading +Alignment.modificationMessages +Alignment.modified +Alignment.ngSubstitutionModelCmd +Alignment.numSequences +Alignment.numSites +Alignment.onChangeAAMatrixName +Alignment.onChangeModel +Alignment.onModelSelectionFailure +Alignment.onModelSelectionSuccess +Alignment.onRunStderr +Alignment.onRunStdout +Alignment.parsingComplete +Alignment.partitionFileContent +Alignment.partitionText +Alignment.partitionType +Alignment.remove +Alignment.runModelTest +Alignment.sequences +Alignment.setModelFromString +Alignment.setPartitionText +Alignment.setShowPartition +Alignment.showModifiedDialog +Alignment.showModifiedSnack +Alignment.showPartition +Alignment.size +Alignment.status +Alignment.taxons +Alignment.typecheckingComplete +AppStore.clearAppSnack +AppStore.setAppSnack +AppStore.showAppSnack +AppStore.version +AstralTree.remove +BackboneConstraintTree.canConstraint +BackboneConstraintTree.isSet +BackboneConstraintTree.notAvailable +BaseFrequencies.notAvailable +Binary.type +Binary.version +BranchLength.notAvailable +Citation.allText +Citation.format +Citation.hide +Citation.setFormat +Citation.show +Citation.visible +CombinedOutput.isUsed +CombinedOutput.notAvailable +Config.isDarkMode +Config.setDarkMode +EstimatedFrequencies.notAvailable +FinalAlignment.dataType +FinalAlignment.dir +FinalAlignment.filename +FinalAlignment.fillTaxonGapsWithEmptySeqeunces +FinalAlignment.hasInvariantSites +FinalAlignment.length +FinalAlignment.modelFlagName +FinalAlignment.numAlignments +FinalAlignment.numSequences +FinalAlignment.openFile +FinalAlignment.openFolder +FinalAlignment.openPartition +FinalAlignment.parsingComplete +FinalAlignment.partitionFileContent +FinalAlignment.partitionFilePath +FinalAlignment.path +FinalAlignment.setFillTaxonGapsWithEmptySeqeunces +FinalAlignment.showFileInFolder +FinalAlignment.taxons +FinalAlignment.writeConcatenatedAlignment +FinalAlignment.writeConcatenatedAlignmentAndPartition +FinalAlignment.writePartition +FinalPartition.isComplete +FinalPartition.isDefault +FinalPartition.text +InputFile.base +InputFile.dir +InputFile.filename +InputFile.id +InputFile.name +InputFile.ok +InputFile.openFile +InputFile.path +InputFile.showFileInFolder +MultifurcatingConstraintTree.canConstraint +MultifurcatingConstraintTree.isSet +MultifurcatingConstraintTree.notAvailable +MultistateModel.notAvailable +MultistateNumber.error +MultistateNumber.notAvailable +NumRepetitions.notAvailable +NumRepetitionsNg.notAvailable +NumRuns.notAvailable +NumThreads.notAvailable +Option.error +Option.errorMessage +Option.haveError +Option.isDefault +Option.reset +Option.setValue +Option.value +OutGroup.cmdValue +OutGroup.notAvailable +OutGroup.options +OutGroup.setValue +Part.text +Part.typePadded +Part.values +PartAAType.notAvailable +PartBase.alignment +PartCodon.notAvailable +PartEnd.max +PartEnd.min +PartEnd.notAvailable +PartName.notAvailable +PartStart.notAvailable +PartType.finalValue +PartType.notAvailable +PartType.options +Partition.addPartDisabled +Partition.currentEndValue +Partition.errorMessage +Partition.haveError +Partition.isComplete +Partition.isDefault +Partition.isMixed +Partition.maxEndValue +Partition.nonDefaultPartitionComplete +Partition.parts +Partition.progress +Partition.reset +Partition.text +RaxmlNgAlignmentSubstitutionModel.cmdValue +RaxmlNgAlignmentSubstitutionModel.notAvailable +RaxmlNgAlignmentSubstitutionModel.options +RaxmlNgModelASC.notAvailable +RaxmlNgModelExtraParam.cmdValue +RaxmlNgModelExtraParam.notAvailable +RaxmlNgModelExtraParam.options +Run.addAlignments +Run.addAstralFiles +Run.addPartitionFiles +Run.addTreeFiles +Run.afterRun +Run.alignments +Run.analysis +Run.analysisOption +Run.args +Run.astralTree +Run.canLoadAlignment +Run.canLoadAstralTree +Run.canLoadPartitionFile +Run.cancel +Run.cancelModeltestOnAlignment +Run.clearConsole +Run.clearError +Run.clearFinished +Run.clearShowModified +Run.clearStderr +Run.clearStdout +Run.code +Run.command +Run.converted +Run.convertedAlignmentFrom +Run.data +Run.dataType +Run.disableCheckUndeterminedSequence +Run.error +Run.exitCode +Run.finished +Run.hasAstralTree +Run.haveAlignments +Run.havePartitionFile +Run.haveRandomSeed +Run.haveResult +Run.hidePartition +Run.inputIsAlignment +Run.inputIsTree +Run.loadAlignmentFiles +Run.loadAstralTree +Run.loadBackboneConstraintFile +Run.loadMultifurcatingConstraintFile +Run.loadPartitionFile +Run.loadTreeFile +Run.missing +Run.modelTestCanRun +Run.modelTestIsRunningOnAlignment +Run.modificationMessages +Run.modified +Run.needAlignment +Run.ngSubstitutionModelCmd +Run.numSites +Run.ok +Run.onAstralSuccess +Run.onBackboneConstraint +Run.onMultifurcatingConstraint +Run.onRunError +Run.onRunFinished +Run.onRunStderr +Run.onRunStdout +Run.openFile +Run.openOutputDir +Run.outputDir +Run.outputFilenameSafe +Run.outputName +Run.outputNameNotice +Run.outputNameOk +Run.outputNameSafe +Run.partitionFile +Run.partitionFileContent +Run.partitionFileName +Run.path +Run.randomSeed +Run.raxmlSubstitutionModelCmd +Run.removeAlignment +Run.removeAstralTree +Run.removePartitionFile +Run.removeRun +Run.reset +Run.resultDir +Run.resultFilenames +Run.running +Run.seedBootstrap +Run.seedParsimony +Run.seedRapidBootstrap +Run.selectOutputDir +Run.setOutputDir +Run.setOutputName +Run.setRandomSeed +Run.settingsFileContent +Run.settingsFilePath +Run.showModifiedDialog +Run.showModifiedSnack +Run.showPartition +Run.showPartitionFor +Run.start +Run.startDisabled +Run.stderr +Run.stdout +Run.taxons +Run.useBackboneConstraint +Run.useMultifurcatingConstraint +Run.usesAstral +Run.usesModeltest +Run.usesModeltestNg +Run.usesRaxml +Run.usesRaxmlNg +Run.writeSettings +RunList.activeIndex +RunList.activeRun +RunList.addRun +RunList.clearError +RunList.deleteActive +RunList.deleteRun +RunList.error +RunList.errorTitle +RunList.onBackboneConstraint +RunList.onError +RunList.onMultifurcatingConstraint +RunList.onUnhandledError +RunList.runs +RunList.setActive +SHlike.notAvailable +StartingTree.notAvailable +SubstitutionAscertainment.cmdValue +SubstitutionAscertainment.extraCmdValue +SubstitutionAscertainment.isSet +SubstitutionAscertainment.notAvailable +SubstitutionAscertainment.options +SubstitutionI.cmdValue +SubstitutionI.isSet +SubstitutionI.notAvailable +SubstitutionI.options +SubstitutionMatrix.cmdValue +SubstitutionMatrix.extraCmdValue +SubstitutionMatrix.notAvailable +SubstitutionMatrix.notGTR +SubstitutionMatrix.options +SubstitutionRate.cmdValue +SubstitutionRate.isCAT +SubstitutionRate.notAvailable +SubstitutionRate.options +Tree.notAvailable +TreeFile.dir +TreeFile.filePath +TreeFile.filename +TreeFile.haveFile +TreeFile.name +TreeFile.openFile +TreeFile.openFolder +TreeFile.remove +TreeFile.setFilePath diff --git a/src/app/store/annotationParity.test.js b/src/app/store/annotationParity.test.js new file mode 100644 index 00000000..70abc7c0 --- /dev/null +++ b/src/app/store/annotationParity.test.js @@ -0,0 +1,59 @@ +// @ts-nocheck +// TEMPORARY (spec #118): guards the decorators -> makeObservable conversion. +// Delete this file and annotationParity.baseline.txt in the cleanup ticket. +import fs from 'fs'; +import path from 'path'; +import { parse } from '@babel/parser'; +import traverse from '@babel/traverse'; + +const BASELINE = path.join( __dirname, 'annotationParity.baseline.txt' ); +const memberName = ( key ) => key.name ?? key.value; + +// Collects "Class.member" for every decorated member and every makeObservable map entry +// (including `override`). The annotation kind is deliberately not recorded. +const scan = ( file ) => { + const ast = parse( fs.readFileSync( file, 'utf8' ), { + sourceType: 'module', + plugins: [ + 'decorators-legacy', + 'classProperties', + ...( /\.tsx?$/.test( file ) + ? [ 'typescript' ] + : [] ), + ], + } ); + const found = []; + const classOf = ( p ) => p.findParent( ( q ) => q.isClass() )?.node.id.name; + traverse( ast, { + 'ClassProperty|ClassMethod'( p ) { + if ( p.node.decorators?.length ) { + found.push( `${classOf( p )}.${memberName( p.node.key )}` ); + } + }, + CallExpression( p ) { + const { callee, arguments: args } = p.node; + if ( callee.name !== 'makeObservable' || args[1]?.type !== 'ObjectExpression' ) return; + args[1].properties.forEach( ( prop ) => { + if ( prop.type !== "SpreadElement" && prop.value?.value !== false ) found.push( `${classOf( p )}.${memberName( prop.key )}` ); + } ); + }, + } ); + return found; +}; + +const scanAll = () => fs.readdirSync( __dirname ) + .filter( ( f ) => /\.(js|ts)$/.test( f ) && !/\.test\.(js|ts)$/.test( f ) ) + .flatMap( ( f ) => scan( path.join( __dirname, f ) ) ) + .sort(); + +describe( 'page store annotation parity (temporary)', () => { + it( 'matches the baseline', () => { + const actual = [ ...new Set( scanAll() ) ]; + if ( process.env.WRITE_BASELINE ) { + fs.writeFileSync( BASELINE, `${actual.join( '\n' )}\n` ); + } + const baseline = fs.readFileSync( BASELINE, 'utf8' ).split( '\n' ).filter( Boolean ); + expect( actual.filter( ( m ) => !baseline.includes( m ) ) ).toEqual( [] ); // gained + expect( baseline.filter( ( m ) => !actual.includes( m ) ) ).toEqual( [] ); // lost + } ); +} ); From 77b408a04ebeb796b2c38bcb2d10d8ecc9d89b38 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 17:38:30 +0100 Subject: [PATCH 31/54] Assign Option value in the constructor (#141) MobX 6 and 7 run field initializers before the constructor body, so the value can no longer read defaultValue from a field initializer. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Option.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/store/Option.js b/src/app/store/Option.js index 6898fd1b..f49f9b08 100644 --- a/src/app/store/Option.js +++ b/src/app/store/Option.js @@ -29,8 +29,9 @@ class Option { : mixed(); this.allowOnlyValidChange = allowOnlyValidChange; this.helperText = helperText; + this.value = defaultValue; } - @observable value = this.defaultValue; + @observable value; @action setValue = ( value ) => { const isValid = this.schema.isValidSync( value ); if ( !this.allowOnlyValidChange || isValid ) { From 78d68f1c5677913eb123555a98a40097d72eac78 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 18:59:42 +0100 Subject: [PATCH 32/54] Make setValue a prototype method the outgroup option overrides Closes #142 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Option.js | 4 ++-- src/app/store/RunOptions.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/app/store/Option.js b/src/app/store/Option.js index f49f9b08..a630252e 100644 --- a/src/app/store/Option.js +++ b/src/app/store/Option.js @@ -32,14 +32,14 @@ class Option { this.value = defaultValue; } @observable value; - @action setValue = ( value ) => { + @action setValue( value ) { const isValid = this.schema.isValidSync( value ); if ( !this.allowOnlyValidChange || isValid ) { this.value = isValid ? this.schema.cast( value ) : value; } - }; + } @action reset() { this.value = this.defaultValue; } diff --git a/src/app/store/RunOptions.js b/src/app/store/RunOptions.js index 5513f0d6..13def9fb 100644 --- a/src/app/store/RunOptions.js +++ b/src/app/store/RunOptions.js @@ -416,7 +416,7 @@ export class OutGroup extends Option { } ) ); } - @action setValue = ( value ) => { + @action setValue( value ) { if ( this.value.includes( '' ) ) { this.value = value.filter( ( v ) => v !== '' ); return; @@ -426,7 +426,7 @@ export class OutGroup extends Option { return; } this.value = value; - }; + } @computed get notAvailable() { return ( From 20fa944675f43de5a34b5d03ea1372a115ccfa07 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 19:00:00 +0100 Subject: [PATCH 33/54] Fix out-of-action writes in alignment, partition and store base Wrap the post-await option writes in loadParsedAlignment and the version write in StoreBase._init in runInAction; make Partition.addPart an action and add it to the parity baseline. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Alignment.js | 14 +++++++------- src/app/store/Partition.js | 2 +- src/app/store/StoreBase.js | 6 +++++- src/app/store/annotationParity.baseline.txt | 1 + 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.js index 41626470..ec3343cf 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.js @@ -304,14 +304,14 @@ class Alignment extends InputFile { .map( ( { dataType } ) => dataType ) .concat( alignment.dataType ), ); - if ( this.run.dataType !== newDataType ) { - this.run.substitutionMatrix.value = - raxmlMatrixOptions[newDataType].default; - } - // When the alignment has finished processing take the default substitution model for this datatype - this.substitutionModel.value = - raxmlNgModelOptions[alignment.dataType]?.default; runInAction( () => { + if ( this.run.dataType !== newDataType ) { + this.run.substitutionMatrix.value = + raxmlMatrixOptions[newDataType].default; + } + // When the alignment has finished processing take the default substitution model for this datatype + this.substitutionModel.value = + raxmlNgModelOptions[alignment.dataType]?.default; this.sequences = alignment.sequences; this.fileFormat = alignment.fileFormat; this.numSequences = alignment.numSequences; diff --git a/src/app/store/Partition.js b/src/app/store/Partition.js index d12b63f8..b8270f2a 100644 --- a/src/app/store/Partition.js +++ b/src/app/store/Partition.js @@ -155,7 +155,7 @@ class Partition { } @observable parts = []; // Add current part values - addPart = () => { + @action addPart = () => { this.parts.push( this.partToAdd.clone() ); // Reset or update in partToAdd this.partToAdd.codon.value = CODON_NONE; diff --git a/src/app/store/StoreBase.js b/src/app/store/StoreBase.js index b2054448..6efcc320 100644 --- a/src/app/store/StoreBase.js +++ b/src/app/store/StoreBase.js @@ -1,3 +1,5 @@ +import { runInAction } from 'mobx'; + export const runEvents = { onRunStdout: 'onRunStdout', onRunStderr: 'onRunStderr', @@ -40,7 +42,9 @@ export default class StoreBase { _init = () => { const { rendererBridge } = /** @type {any} */ ( window ); rendererBridge.getVersion().then( ( version ) => { - this.version = version; + runInAction( () => { + this.version = version; + } ); } ); }; } diff --git a/src/app/store/annotationParity.baseline.txt b/src/app/store/annotationParity.baseline.txt index 2d2d23e9..f9bcbc29 100644 --- a/src/app/store/annotationParity.baseline.txt +++ b/src/app/store/annotationParity.baseline.txt @@ -138,6 +138,7 @@ PartStart.notAvailable PartType.finalValue PartType.notAvailable PartType.options +Partition.addPart Partition.addPartDisabled Partition.currentEndValue Partition.errorMessage From 21c81d98e68687e77a42f336e8add796c10a13db Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 20:05:04 +0100 Subject: [PATCH 34/54] Set observable state inside runInAction in three page store tests Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/modelSelection.test.js | 7 ++++-- src/app/store/showItemInFolder.test.js | 13 +++++++---- .../store/writeConcatenatedAlignment.test.js | 23 +++++++++++-------- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/app/store/modelSelection.test.js b/src/app/store/modelSelection.test.js index 6194defb..0643a58b 100644 --- a/src/app/store/modelSelection.test.js +++ b/src/app/store/modelSelection.test.js @@ -1,4 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. +import { runInAction } from 'mobx'; import Run from './Run'; import { runEvents } from './StoreBase'; @@ -34,8 +35,10 @@ it( 'startModelSelection starts model selection', async () => { run.setOutputDir( '/out' ); run.addAlignments( [{ path: '/data/primates.fasta' }] ); const alignment = run.alignments[0]; - alignment.numSequences = 4; - alignment.dataType = 'nucleotide'; + runInAction( () => { + alignment.numSequences = 4; + alignment.dataType = 'nucleotide'; + } ); await alignment.runModelTest(); diff --git a/src/app/store/showItemInFolder.test.js b/src/app/store/showItemInFolder.test.js index ce6a727e..d51fc798 100644 --- a/src/app/store/showItemInFolder.test.js +++ b/src/app/store/showItemInFolder.test.js @@ -1,4 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. +import { runInAction } from 'mobx'; import Run from './Run'; it( 'shows a tree file in its folder', async () => { @@ -16,11 +17,13 @@ it( 'shows the concatenated alignment in its folder', async () => { const run = new Run( {}, 7 ); window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; run.addAlignments( [ { path: '/data/a.fasta' } ] ); - run.alignments[0].sequences = [ - { taxon: 'Homo', code: 'AT' }, - { taxon: 'Mus', code: 'GC' }, - ]; - run.alignments[0].length = 2; + runInAction( () => { + run.alignments[0].sequences = [ + { taxon: 'Homo', code: 'AT' }, + { taxon: 'Mus', code: 'GC' }, + ]; + run.alignments[0].length = 2; + } ); const showItemInFolder = jest.fn( async () => {} ); window.rendererBridge = { writeFile: jest.fn( async () => {} ), diff --git a/src/app/store/writeConcatenatedAlignment.test.js b/src/app/store/writeConcatenatedAlignment.test.js index f06655ea..e641f4db 100644 --- a/src/app/store/writeConcatenatedAlignment.test.js +++ b/src/app/store/writeConcatenatedAlignment.test.js @@ -1,4 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. +import { runInAction } from 'mobx'; import Run from './Run'; it( 'writes one concatenated FASTA', async () => { @@ -8,16 +9,18 @@ it( 'writes one concatenated FASTA', async () => { { path: '/data/a.fasta' }, { path: '/data/b.fasta' }, ] ); - run.alignments[0].sequences = [ - { taxon: 'Homo', code: 'AT' }, - { taxon: 'Mus', code: 'GC' }, - ]; - run.alignments[0].length = 2; - run.alignments[1].sequences = [ - { taxon: 'Homo', code: 'TT' }, - { taxon: 'Mus', code: 'AA' }, - ]; - run.alignments[1].length = 2; + runInAction( () => { + run.alignments[0].sequences = [ + { taxon: 'Homo', code: 'AT' }, + { taxon: 'Mus', code: 'GC' }, + ]; + run.alignments[0].length = 2; + run.alignments[1].sequences = [ + { taxon: 'Homo', code: 'TT' }, + { taxon: 'Mus', code: 'AA' }, + ]; + run.alignments[1].length = 2; + } ); const writeFile = jest.fn( async () => {} ); window.rendererBridge = { writeFile }; From 0ce33bb26fed7334e083a3399ef37ee11440fc0b Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 21:02:32 +0100 Subject: [PATCH 35/54] Fix out-of-action writes in the run (#144) startAstral becomes an action; addPartitionFiles wraps the writes after its await in runInAction. Parity baseline gains Run.startAstral. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Run.js | 31 +++++++++++---------- src/app/store/annotationParity.baseline.txt | 1 + 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/app/store/Run.js b/src/app/store/Run.js index a3df10b3..a462ca29 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -1,4 +1,4 @@ -import { observable, computed, action, createAtom } from 'mobx'; +import { observable, computed, action, runInAction, createAtom } from 'mobx'; import { promisedComputed } from 'computed-async-mobx'; import filenamify from 'filenamify'; @@ -1216,17 +1216,18 @@ Results saved to: ${this.outputDir} } }; - startAstral = async () => { - const { id, binary, args } = this; - console.log( `Start astral run ${id}` ); - this.running = true; - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.startAstral( { - id, - binaryName: binary.value, - args, - } ); - }; + @action + startAstral = async () => { + const { id, binary, args } = this; + console.log( `Start astral run ${id}` ); + this.running = true; + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.startAstral( { + id, + binaryName: binary.value, + args, + } ); + }; @action start = async () => { @@ -1447,8 +1448,10 @@ Results saved to: ${this.outputDir} const { path } = files[0]; const { rendererBridge } = /** @type {any} */ ( window ); const content = await rendererBridge.readFile( path ); - this.partitionFile = path; - this.partitionFileContent = content; + runInAction( () => { + this.partitionFile = path; + this.partitionFileContent = content; + } ); }; @action diff --git a/src/app/store/annotationParity.baseline.txt b/src/app/store/annotationParity.baseline.txt index f9bcbc29..9244c88f 100644 --- a/src/app/store/annotationParity.baseline.txt +++ b/src/app/store/annotationParity.baseline.txt @@ -256,6 +256,7 @@ Run.showModifiedSnack Run.showPartition Run.showPartitionFor Run.start +Run.startAstral Run.startDisabled Run.stderr Run.stdout From 26542f23c1d8159c9cf6fd4b29c339ea2b41a1f2 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 22:07:19 +0100 Subject: [PATCH 36/54] Bump to MobX 6 with decorators kept (#146) mobx 6.16 and mobx-react-lite 4.1; makeObservable( this ) in every decorated class, override on the three subclass members that replace a parent's, define semantics for class fields in Babel, Jest and tsconfig. computed-async-mobx 7 mixes decorators with annotations, which MobX 6 rejects, so Run uses a small local promisedComputed on mobx-utils 6. MobX 6 passes the previous value, not the reaction, as the second effect argument; Partition's one-shot reaction takes the third. StoreBase.dispose is a method so Alignment's decorated dispose does not redefine a field. Co-Authored-By: Claude Sonnet 5.5 --- .babelrc | 2 +- electron.vite.config.js | 2 +- jest/babelTransform.js | 2 +- jest/setup.js | 4 +++ package.json | 7 ++-- src/app/promisedComputed.js | 59 +++++++++++++++++++++++++++++++ src/app/store/Alignment.js | 15 ++++---- src/app/store/AlignmentOptions.js | 10 ++++-- src/app/store/AppStore.js | 6 +++- src/app/store/AstralTree.js | 6 +++- src/app/store/Citation.js | 5 ++- src/app/store/Config.js | 3 +- src/app/store/FinalAlignment.js | 3 +- src/app/store/FinalPartition.js | 3 +- src/app/store/InputFile.js | 3 +- src/app/store/Option.js | 3 +- src/app/store/PartOptions.js | 9 ++++- src/app/store/Partition.js | 6 ++-- src/app/store/Run.js | 5 +-- src/app/store/RunList.js | 3 +- src/app/store/RunOptions.js | 35 ++++++++++++++++-- src/app/store/StoreBase.js | 5 +-- tsconfig.json | 2 +- yarn.lock | 36 ++++++++++--------- 24 files changed, 181 insertions(+), 53 deletions(-) create mode 100644 src/app/promisedComputed.js diff --git a/.babelrc b/.babelrc index 4e1dc0e1..a981a7ab 100644 --- a/.babelrc +++ b/.babelrc @@ -10,6 +10,6 @@ ], "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }], - ["@babel/plugin-proposal-class-properties", { "loose": true }] + ["@babel/plugin-proposal-class-properties", { "loose": false }] ] } diff --git a/electron.vite.config.js b/electron.vite.config.js index ae6d9f84..631c5fb4 100644 --- a/electron.vite.config.js +++ b/electron.vite.config.js @@ -53,7 +53,7 @@ export default defineConfig( ( { command } ) => ( { babel: { plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }], - ['@babel/plugin-proposal-class-properties', { loose: true }], + ['@babel/plugin-proposal-class-properties', { loose: false }], ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }], ], }, diff --git a/jest/babelTransform.js b/jest/babelTransform.js index 3bc5092c..7e13f168 100644 --- a/jest/babelTransform.js +++ b/jest/babelTransform.js @@ -11,7 +11,7 @@ module.exports = babelJest.default.createTransformer( { ], plugins: [ [ '@babel/plugin-proposal-decorators', { legacy: true } ], - [ '@babel/plugin-proposal-class-properties', { loose: true } ], + [ '@babel/plugin-proposal-class-properties', { loose: false } ], [ '@babel/plugin-transform-react-jsx', { runtime: 'automatic' } ], ], } ); diff --git a/jest/setup.js b/jest/setup.js index 2a373e2a..2d6d5929 100644 --- a/jest/setup.js +++ b/jest/setup.js @@ -42,6 +42,10 @@ function withBridgeEvents( next ) { if ( typeof next.getVersion !== 'function' ) { next.getVersion = () => Promise.resolve(); } + // The output panel checks the output name; MobX 6 re-renders it inside the render test when this rejects. + if ( typeof next.checkOutput !== 'function' ) { + next.checkOutput = () => Promise.resolve( { ok: true, resultFilenames: [] } ); + } // Config construction reads and may write dark mode. if ( typeof next.getDarkMode !== 'function' ) { next.getDarkMode = () => Promise.resolve( false ); diff --git a/package.json b/package.json index a3f1b406..3e5f78dd 100644 --- a/package.json +++ b/package.json @@ -63,16 +63,15 @@ "allotment": "^1.20.6", "classnames": "^2.3.2", "clean-stack": "3.0.1", - "computed-async-mobx": "^4.2.0", "d3-array": "^3.2.5", "electron-log": "^4.4.8", "electron-store": "^8.1.0", "electron-updater": "^5.2.4", "filenamify": "^4.3.0", "lodash": "^4.18.1", - "mobx": "^5.15.7", - "mobx-react-lite": "^2.2.2", - "mobx-utils": "^5.6.2", + "mobx": "^6.16.0", + "mobx-react-lite": "^4.1.0", + "mobx-utils": "^6.1.0", "parse-filepath": "^1.0.2", "patch-package": "^8.0.1", "postinstall-postinstall": "^2.1.0", diff --git a/src/app/promisedComputed.js b/src/app/promisedComputed.js new file mode 100644 index 00000000..20d3506c --- /dev/null +++ b/src/app/promisedComputed.js @@ -0,0 +1,59 @@ +import { computed, makeObservable, _getGlobalState } from 'mobx'; +import { fromPromise, isPromiseBasedObservable } from 'mobx-utils'; + +const ok = ( value ) => ( { ok: true, value } ); +const failed = ( error ) => ( { ok: false, error } ); + +// Replaces computed-async-mobx: its 7.0 build mixes decorators with annotations, which MobX 6 rejects. +// Like a computed that unwraps a promise: `init` until the first resolve, then the latest resolved value. +// `get` must run inside a reaction; `busy` is true while the promise is pending. +class PromisedComputed { + constructor( init, fetch ) { + this.fetch = fetch; + this.cached = ok( init ); + makeObservable( this, { + currentState: computed, + busy: computed, + value: computed, + } ); + } + + get currentState() { + try { + const promiseOrValue = this.fetch(); + return typeof promiseOrValue?.then === 'function' + ? fromPromise( promiseOrValue.then( ok, failed ) ) + : ok( promiseOrValue ); + } catch ( err ) { + return failed( err ); + } + } + + get busy() { + const state = this.currentState; + return isPromiseBasedObservable( state ) && state.state === 'pending'; + } + + get value() { + const state = this.currentState; + const result = !isPromiseBasedObservable( state ) + ? state + : state.state === 'fulfilled' + ? state.value + : this.cached; + this.cached = result; + if ( result.ok ) { + return result.value; + } + throw result.error; + } + + get() { + if ( !_getGlobalState().trackingDerivation ) { + throw new Error( 'promisedComputed must be used inside reactions' ); + } + return this.value; + } +} + +export const promisedComputed = ( init, fetch ) => new PromisedComputed( init, fetch ); diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.js index ec3343cf..59c2cc83 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.js @@ -1,4 +1,4 @@ -import { observable, computed, action, runInAction } from 'mobx'; +import { observable, computed, action, runInAction, makeObservable } from 'mobx'; import * as raxmlSettings from '../../settings/raxml'; import * as raxmlNgSettings from '../../settings/raxmlng'; @@ -23,6 +23,7 @@ const raxmlNgModelOptions = raxmlNgSettings.modelOptions; class Alignment extends InputFile { constructor( run, path ) { super( run, path ); + makeObservable( this ); this.substitutionModel = new RaxmlNgAlignmentSubstitutionModel( this ); this.multistateNumber = new MultistateNumber( this ); this.ngStationaryFrequencies = new RaxmlNgModelF( this ); @@ -379,12 +380,12 @@ class Alignment extends InputFile { }; @action - dispose = () => { - this.unlisten(); - if ( this.modeltestLoading ) { - this.cancelModelTest(); - } - }; + dispose() { + this.unlisten(); + if ( this.modeltestLoading ) { + this.cancelModelTest(); + } + } @action remove = () => { diff --git a/src/app/store/AlignmentOptions.js b/src/app/store/AlignmentOptions.js index 9019fb6b..0a9d5feb 100644 --- a/src/app/store/AlignmentOptions.js +++ b/src/app/store/AlignmentOptions.js @@ -1,4 +1,4 @@ -import { computed } from 'mobx'; +import { computed, makeObservable, override } from 'mobx'; import Option from './Option'; import * as raxmlNgSettings from '../../settings/raxmlng'; @@ -8,6 +8,7 @@ const raxmlNgModelOptions = raxmlNgSettings.modelOptions; class RaxmlNgAlignmentSubstitutionModel extends Option { constructor( alignment ) { super( alignment.run, '', 'Substitution model' ); + makeObservable( this ); this.alignment = alignment; } @computed get options() { @@ -37,6 +38,7 @@ class RaxmlNgModelExtraParam extends Option { super( alignment.run, addNone ? '' : options[0].value, label ); + makeObservable( this ); this.alignment = alignment; this.optionsSource = addNone ? [{ value: '', title: 'none' }, ...options] @@ -106,8 +108,9 @@ class RaxmlNgModelASC extends RaxmlNgModelExtraParam { ].map( ( { value, label: title } ) => ( { value, title } ) ), { addNone: false }, ); + makeObservable( this ); } - @computed get notAvailable() { + @override get notAvailable() { return ( !this.run.haveAlignments || !this.run.usesRaxmlNg || @@ -119,6 +122,7 @@ class RaxmlNgModelASC extends RaxmlNgModelExtraParam { class MultistateNumber extends Option { constructor( alignment ) { super( alignment.run, '', 'Number of states' ); + makeObservable( this ); this.alignment = alignment; this.placeholder = 'Integer'; } @@ -128,7 +132,7 @@ class MultistateNumber extends Option { !this.alignment.run.usesRaxmlNg ); } - @computed get error() { + @override get error() { return !this.value || !Number.isInteger( Number( this.value ) ); } } diff --git a/src/app/store/AppStore.js b/src/app/store/AppStore.js index e976b17e..e9e02ed5 100644 --- a/src/app/store/AppStore.js +++ b/src/app/store/AppStore.js @@ -1,9 +1,13 @@ -import { observable, action } from 'mobx'; +import { observable, action, makeObservable } from 'mobx'; import StoreBase from './StoreBase'; import Citation from './Citation'; import Config from './Config'; class AppStore extends StoreBase { + constructor() { + super(); + makeObservable( this ); + } citation = new Citation(); config = new Config(); diff --git a/src/app/store/AstralTree.js b/src/app/store/AstralTree.js index 2450c18b..1a0da00d 100644 --- a/src/app/store/AstralTree.js +++ b/src/app/store/AstralTree.js @@ -1,8 +1,12 @@ -import { action } from 'mobx'; +import { action, makeObservable } from 'mobx'; import InputFile from './InputFile'; class AstralTree extends InputFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this ); + } @action remove = () => { this.run.removeAstralTree(); diff --git a/src/app/store/Citation.js b/src/app/store/Citation.js index 788b8ae4..9e025f69 100644 --- a/src/app/store/Citation.js +++ b/src/app/store/Citation.js @@ -1,6 +1,9 @@ -import { observable, action, computed } from 'mobx'; +import { observable, action, computed, makeObservable } from 'mobx'; export default class Citation { + constructor() { + makeObservable( this ); + } @observable visible = false; formats = [ diff --git a/src/app/store/Config.js b/src/app/store/Config.js index dda5676c..b3dcd924 100644 --- a/src/app/store/Config.js +++ b/src/app/store/Config.js @@ -1,9 +1,10 @@ -import { observable, action, runInAction } from 'mobx'; +import { observable, action, runInAction, makeObservable } from 'mobx'; import StoreBase, { runEvents } from './StoreBase'; export default class Config extends StoreBase { constructor() { super(); + makeObservable( this ); this.listen(); const { rendererBridge } = /** @type {any} */ ( window ); rendererBridge.getDarkMode().then( ( value ) => { diff --git a/src/app/store/FinalAlignment.js b/src/app/store/FinalAlignment.js index c8fbc33e..964c40a9 100644 --- a/src/app/store/FinalAlignment.js +++ b/src/app/store/FinalAlignment.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import union from 'lodash/union'; import intersection from 'lodash/intersection'; @@ -8,6 +8,7 @@ import { join } from '../paths'; class FinalAlignment { constructor( run ) { + makeObservable( this ); this.run = run; this.partition = new FinalPartition( run ); } diff --git a/src/app/store/FinalPartition.js b/src/app/store/FinalPartition.js index 87dcb1e5..60c0d439 100644 --- a/src/app/store/FinalPartition.js +++ b/src/app/store/FinalPartition.js @@ -1,7 +1,8 @@ -import { computed } from 'mobx'; +import { computed, makeObservable } from 'mobx'; class FinalPartition { constructor( run ) { + makeObservable( this ); this.run = run; } /* diff --git a/src/app/store/InputFile.js b/src/app/store/InputFile.js index 347634b0..a4613987 100644 --- a/src/app/store/InputFile.js +++ b/src/app/store/InputFile.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import { base, dir, name } from '../paths'; import StoreBase from './StoreBase'; @@ -8,6 +8,7 @@ class InputFile extends StoreBase { constructor( run, path ) { super(); + makeObservable( this ); this.run = run; this.path = path; } diff --git a/src/app/store/Option.js b/src/app/store/Option.js index a630252e..7d9d956a 100644 --- a/src/app/store/Option.js +++ b/src/app/store/Option.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import { mixed } from 'yup'; class Option { @@ -19,6 +19,7 @@ class Option { hoverInfo, { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, ) { + makeObservable( this ); this.run = run; this.defaultValue = defaultValue; this.title = title; diff --git a/src/app/store/PartOptions.js b/src/app/store/PartOptions.js index 4f921908..778e8289 100644 --- a/src/app/store/PartOptions.js +++ b/src/app/store/PartOptions.js @@ -1,4 +1,4 @@ -import { computed } from 'mobx'; +import { computed, makeObservable } from 'mobx'; import Option from './Option'; import * as raxmlSettings from '../../settings/raxml'; import * as yup from 'yup'; @@ -29,6 +29,7 @@ class PartBase extends Option { helperText, }, ); + makeObservable( this ); this.part = part; } @computed get alignment() { @@ -42,6 +43,7 @@ class PartType extends PartBase { schema: yup.string(), allowOnlyValidChange: true, } ); + makeObservable( this ); } @computed get finalValue() { const { dataType, partitionType } = this.alignment; @@ -71,6 +73,7 @@ class PartAAType extends PartBase { schema: yup.string(), allowOnlyValidChange: true, } ); + makeObservable( this ); } options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( ( value ) => ( { value, title: value } ), @@ -85,6 +88,7 @@ class PartName extends PartBase { schema: yup.string(), // TODO: Check that it is unique within partition allowOnlyValidChange: true, } ); + makeObservable( this ); } @computed get notAvailable() { return false; @@ -96,6 +100,7 @@ class PartStart extends PartBase { schema: yup.number(), allowOnlyValidChange: false, } ); + makeObservable( this ); this.disabled = true; } @computed get notAvailable() { @@ -122,6 +127,7 @@ class PartEnd extends PartBase { allowOnlyValidChange: false, }, ); + makeObservable( this ); } @computed get min() { return ( @@ -144,6 +150,7 @@ class PartCodon extends PartBase { schema: yup.string(), allowOnlyValidChange: true, } ); + makeObservable( this ); } options = CodonModels.map( ( value ) => ( { value, title: value } ) ); @computed get notAvailable() { diff --git a/src/app/store/Partition.js b/src/app/store/Partition.js index b8270f2a..63779450 100644 --- a/src/app/store/Partition.js +++ b/src/app/store/Partition.js @@ -1,4 +1,4 @@ -import { observable, computed, action, reaction } from 'mobx'; +import { observable, computed, action, reaction, makeObservable } from 'mobx'; import { CODON_NONE, CODON_SPECIFIC, @@ -30,6 +30,7 @@ const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { class Part { constructor( partition, { type, aaType, name, start, end, codon } ) { + makeObservable( this ); this.partition = partition; this.type = new PartType( this, type ); this.aaType = new PartAAType( this, aaType ); @@ -108,6 +109,7 @@ class Part { } class Partition { constructor( alignment ) { + makeObservable( this ); this.alignment = alignment; this.defaultPartition = new Part( this, { type: alignment.partitionType, @@ -127,7 +129,7 @@ class Partition { } ); reaction( () => alignment.length, - ( length, reaction ) => { + ( length, _previous, reaction ) => { reaction.dispose(); // Make default alignment complete except for mixed type if ( this.alignment.dataType !== 'mixed' ) { diff --git a/src/app/store/Run.js b/src/app/store/Run.js index a462ca29..2d630678 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -1,5 +1,5 @@ -import { observable, computed, action, runInAction, createAtom } from 'mobx'; -import { promisedComputed } from 'computed-async-mobx'; +import { observable, computed, action, runInAction, createAtom, makeObservable } from 'mobx'; +import { promisedComputed } from '../promisedComputed'; import filenamify from 'filenamify'; import Alignment from './Alignment'; @@ -44,6 +44,7 @@ const { windows } = host; class Run extends StoreBase { constructor( parent, id ) { super(); + makeObservable( this ); this.parent = parent; this.id = id; this.finalAlignment = new FinalAlignment( this ); diff --git a/src/app/store/RunList.js b/src/app/store/RunList.js index 10156ecd..27f3fff8 100644 --- a/src/app/store/RunList.js +++ b/src/app/store/RunList.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable } from 'mobx'; import Run from './Run'; import AppStore from './AppStore'; import { runEvents } from './StoreBase'; @@ -9,6 +9,7 @@ class RunList extends AppStore { constructor() { super(); + makeObservable( this ); this.addRun(); this.listen(); } diff --git a/src/app/store/RunOptions.js b/src/app/store/RunOptions.js index 13def9fb..af935638 100644 --- a/src/app/store/RunOptions.js +++ b/src/app/store/RunOptions.js @@ -1,4 +1,4 @@ -import { observable, computed, action } from 'mobx'; +import { observable, computed, action, makeObservable, override } from 'mobx'; import { range } from 'd3-array'; import Option from './Option'; @@ -263,6 +263,7 @@ export const raxmlNgAnalysisOptions = [ export class Binary extends Option { constructor( run ) { super( run, initialBinaryName, 'Binary', 'Name of binary' ); + makeObservable( this ); } options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); @computed get version() { @@ -276,6 +277,7 @@ export class Binary extends Option { export class NumThreads extends Option { constructor( run ) { super( run, 2, 'Threads', 'Number of cpu threads' ); + makeObservable( this ); } options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { value, @@ -308,6 +310,7 @@ export class RaxmlNgAnalysis extends Option { export class NumRuns extends Option { constructor( run ) { super( run, 1, 'Runs', 'Number of runs' ); + makeObservable( this ); } options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); @computed get notAvailable() { @@ -318,6 +321,7 @@ export class NumRuns extends Option { export class NumRepetitions extends Option { constructor( run ) { super( run, 100, 'Reps.', 'Number of repetitions' ); + makeObservable( this ); } options = [ 100, @@ -338,6 +342,7 @@ export class NumRepetitions extends Option { export class NumRepetitionsNg extends Option { constructor( run ) { super( run, 100, 'Reps.', 'Number of repetitions' ); + makeObservable( this ); } options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { value, @@ -358,6 +363,7 @@ export class BranchLength extends Option { 'Compute branch lengths', 'Optimize model parameters and branch lengths for the given input tree', ); + makeObservable( this ); } @computed get notAvailable() { return !this.run.analysisOption.params.includes( params.brL ); @@ -373,6 +379,7 @@ export class SHlike extends Option { 'Compute log-likelihood test', 'Shimodaira-Hasegawa-like procedure', ); + makeObservable( this ); } @computed get notAvailable() { return !this.run.analysisOption.params.includes( params.SHlike ); @@ -382,6 +389,7 @@ export class SHlike extends Option { export class CombinedOutput extends Option { constructor( run ) { super( run, false, 'Combined output', 'Concatenate output trees' ); + makeObservable( this ); } @computed get notAvailable() { return !this.run.analysisOption.params.includes( params.combinedOutput ); @@ -394,6 +402,7 @@ export class CombinedOutput extends Option { export class StartingTree extends Option { constructor( run ) { super( run, 'Maximum parsimony', 'Starting tree', '' ); + makeObservable( this ); } options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { value, @@ -407,6 +416,7 @@ export class StartingTree extends Option { export class OutGroup extends Option { constructor( run ) { super( run, [''], 'Outgroup', '' ); + makeObservable( this ); this.multiple = true; } @computed get options() { @@ -416,7 +426,7 @@ export class OutGroup extends Option { } ) ); } - @action setValue( value ) { + @override setValue( value ) { if ( this.value.includes( '' ) ) { this.value = value.filter( ( v ) => v !== '' ); return; @@ -444,6 +454,7 @@ export class OutGroup extends Option { export class SubstitutionMatrix extends Option { constructor( run ) { super( run, 'GTR', 'Substitution matrix' ); + makeObservable( this ); } @computed get options() { if ( !this.run.haveAlignments ) { @@ -504,6 +515,7 @@ export class SubstitutionMatrix extends Option { export class SubstitutionRate extends Option { constructor( run ) { super( run, 'GAMMA', 'Substitution rates' ); + makeObservable( this ); } @computed get options() { if ( !this.run.haveAlignments ) { @@ -539,6 +551,7 @@ export class SubstitutionRate extends Option { export class SubstitutionI extends Option { constructor( run ) { super( run, 'none', 'Proportion of invariant sites' ); + makeObservable( this ); } @computed get options() { if ( !this.run.haveAlignments ) { @@ -570,6 +583,7 @@ export class SubstitutionI extends Option { export class SubstitutionAscertainment extends Option { constructor( run ) { super( run, 'none', 'Ascertainment bias correction' ); + makeObservable( this ); } @computed get options() { if ( !this.run.haveAlignments ) { @@ -620,6 +634,7 @@ export class AAMatrixName extends Option { 'Matrix name', 'Amino Acid Substitution Matrix name', ); + makeObservable( this ); } options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( ( value ) => ( { value, title: value } ), @@ -638,6 +653,7 @@ export class EstimatedFrequencies extends Option { 'Estimated base frequencies', 'Use estimated base frequencies instead of empirical.', ); + makeObservable( this ); } @computed get notAvailable() { return this.run.dataType === 'protein' || this.run.usesRaxmlNg; @@ -652,6 +668,7 @@ export class BaseFrequencies extends Option { 'Base frequencies', 'Empirical, ML estimated or model based base frequencies', ); + makeObservable( this ); } options = [ { title: 'From model', value: 'default' }, @@ -666,6 +683,7 @@ export class BaseFrequencies extends Option { export class MultistateModel extends Option { constructor( run ) { super( run, 'GTR', 'Multistate model' ); + makeObservable( this ); } options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( ( value ) => ( { value, title: value } ), @@ -678,6 +696,7 @@ export class MultistateModel extends Option { class TreeFile extends Option { constructor( run ) { super( run, '', 'Tree', '' ); + makeObservable( this ); } @observable filePath = ''; @computed get haveFile() { @@ -709,6 +728,10 @@ class TreeFile extends Option { } export class Tree extends TreeFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this ); + } @computed get notAvailable() { return !( this.run.analysisOption.params.includes( params.tree ) || @@ -719,6 +742,10 @@ export class Tree extends TreeFile { } export class BackboneConstraintTree extends TreeFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this ); + } @computed get isSet() { return this.run.useBackboneConstraint && this.haveFile; } @@ -743,6 +770,10 @@ export class BackboneConstraintTree extends TreeFile { } export class MultifurcatingConstraintTree extends TreeFile { + constructor( ...args ) { + super( ...args ); + makeObservable( this ); + } @computed get isSet() { return this.run.useMultifurcatingConstraint && this.haveFile; } diff --git a/src/app/store/StoreBase.js b/src/app/store/StoreBase.js index 6efcc320..86a80780 100644 --- a/src/app/store/StoreBase.js +++ b/src/app/store/StoreBase.js @@ -35,9 +35,10 @@ export default class StoreBase { } }; - dispose = () => { + // A method: a field here would clash with a subclass's decorated dispose. + dispose() { this.unlisten(); - }; + } _init = () => { const { rendererBridge } = /** @type {any} */ ( window ); diff --git a/tsconfig.json b/tsconfig.json index 61517d59..534a7d41 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -9,7 +9,7 @@ "module": "ESNext", "moduleResolution": "bundler", "experimentalDecorators": true, - "useDefineForClassFields": false, + "useDefineForClassFields": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": false, diff --git a/yarn.lock b/yarn.lock index f8d388a7..cf3d3019 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4523,11 +4523,6 @@ compare-version@^0.1.2: resolved "https://registry.yarnpkg.com/compare-version/-/compare-version-0.1.2.tgz#0162ec2d9351f5ddd59a9202cba935366a725080" integrity sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A== -computed-async-mobx@^4.2.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/computed-async-mobx/-/computed-async-mobx-4.2.1.tgz#868c899f209af0bcdecaf677abd9bb50f9f39105" - integrity sha512-kThbGHul+3YrXWFfxRJpuHAv9CdEl/UVGI79BmMq3m6UMuWggZq3Hyp2tj1hEe3ZScokTzg+Quxk7X5cN3YKpA== - concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" @@ -7940,20 +7935,22 @@ mkdirp@^1.0.3: resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -mobx-react-lite@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/mobx-react-lite/-/mobx-react-lite-2.2.2.tgz#87c217dc72b4e47b22493daf155daf3759f868a6" - integrity sha512-2SlXALHIkyUPDsV4VTKVR9DW7K3Ksh1aaIv3NrNJygTbhXe2A9GrcKHZ2ovIiOp/BXilOcTYemfHHZubP431dg== +mobx-react-lite@^4.1.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/mobx-react-lite/-/mobx-react-lite-4.1.1.tgz#725d74b025235f73dc2ab815766ffe010be2cf8a" + integrity sha512-iUxiMpsvNraCKXU+yPotsOncNNmyeS2B5DKL+TL6Tar/xm+wwNJAubJmtRSeAoYawdZqwv8Z/+5nPRHeQxTiXg== + dependencies: + use-sync-external-store "^1.4.0" -mobx-utils@^5.6.2: - version "5.6.2" - resolved "https://registry.yarnpkg.com/mobx-utils/-/mobx-utils-5.6.2.tgz#4858acbdb03f0470e260854f87e8c2ba916ebaec" - integrity sha512-a/WlXyGkp6F12b01sTarENpxbmlRgPHFyR1Xv2bsSjQBm5dcOtd16ONb40/vOqck8L99NHpI+C9MXQ+SZ8f+yw== +mobx-utils@^6.1.0: + version "6.1.1" + resolved "https://registry.yarnpkg.com/mobx-utils/-/mobx-utils-6.1.1.tgz#61c66563e7646fb75462c189f4110a76d2e35768" + integrity sha512-ZR4tOKucWAHOdMjqElRl2BEvrzK7duuDdKmsbEbt2kzgVpuLuoYLiDCjc3QwWQl8CmOlxPgaZQpZ7emwNqPkIg== -mobx@^5.15.7: - version "5.15.7" - resolved "https://registry.yarnpkg.com/mobx/-/mobx-5.15.7.tgz#b9a5f2b6251f5d96980d13c78e9b5d8d4ce22665" - integrity sha512-wyM3FghTkhmC+hQjyPGGFdpehrcX1KOXsDuERhfK2YbJemkUhEB+6wzEN639T21onxlfYBmriA1PFnvxTUhcKw== +mobx@^6.16.0: + version "6.16.1" + resolved "https://registry.yarnpkg.com/mobx/-/mobx-6.16.1.tgz#8b3166186d1298b1848395e10e64b5c43d6dc43b" + integrity sha512-syNcDdX3KT+Jq3je6eGjBhuc24Z68td2VG0zNFqRswaE433D9SNH5VRy/xrGbJsUixfppLLccXhAW9JSf6n+SQ== ms@2.0.0: version "2.0.0" @@ -10051,6 +10048,11 @@ url-to-options@^1.0.1: resolved "https://registry.yarnpkg.com/url-to-options/-/url-to-options-1.0.1.tgz#1505a03a289a48cbd7a434efbaeec5055f5633a9" integrity sha512-0kQLIzG4fdk/G5NONku64rSH/x32NOA39LVQqlK8Le6lvTF6GGRJpqaQFGgU+CLwySIqBSMdwYM0sYcW9f6P4A== +use-sync-external-store@^1.4.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz#6dcb66ef569e02f186af6b3d575f414ce746e18f" + integrity sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A== + usehooks-ts@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/usehooks-ts/-/usehooks-ts-3.1.1.tgz#0bb7f38f36f8219ee4509cc5e944ae610fb97656" From c637d754fcf1fd6408144021a5ce51f0d4221ad3 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 22:44:48 +0100 Subject: [PATCH 37/54] Drop stale App.test.js typecheck baseline entries The Jest types commit resolved them, so typecheck:baseline exited 1 on unused baseline lines. Co-Authored-By: Claude Sonnet 5.5 --- scripts/typecheck-baseline.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index ce174476..3743f8e4 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -6,8 +6,6 @@ src/app/App.js(322,24): error TS2769: No overload matches this call. Property 'title' does not exist on type 'IntrinsicAttributes & SvgIconOwnProps & CommonProps & Omit, "fontSize" | ... 10 more ... | "titleAccess">'. src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is missing the following properties from type '{ error: any; onClose: any; needReload: any; title: any; }': needReload, title src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. -src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. -src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. From e996b957bc07b626d7872a888636569c41559412 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 23:02:15 +0100 Subject: [PATCH 38/54] Restore App.test.js typecheck baseline entries The spec branch lacks the Jest types, so CI still reports them; the local node_modules came from master and hid them. Co-Authored-By: Claude Sonnet 5.5 --- scripts/typecheck-baseline.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index 3743f8e4..ce174476 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -6,6 +6,8 @@ src/app/App.js(322,24): error TS2769: No overload matches this call. Property 'title' does not exist on type 'IntrinsicAttributes & SvgIconOwnProps & CommonProps & Omit, "fontSize" | ... 10 more ... | "titleAccess">'. src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is missing the following properties from type '{ error: any; onClose: any; needReload: any; title: any; }': needReload, title src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. +src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. +src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. From d6bcca852577a2dc0d8efe356a4ace2fc61e2d6d Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 23:18:35 +0100 Subject: [PATCH 39/54] Fail a Jest test on a MobX action warning Co-Authored-By: Claude Sonnet 5.5 --- jest.config.js | 1 + jest/mobxActionWarning.js | 25 +++++++++++++++++++++++++ src/mobxActionWarning.test.js | 26 ++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 jest/mobxActionWarning.js create mode 100644 src/mobxActionWarning.test.js diff --git a/jest.config.js b/jest.config.js index ed3f490a..b912988c 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,6 +1,7 @@ module.exports = { testEnvironment: 'jsdom', setupFiles: [ '/jest/setup.js' ], + setupFilesAfterEnv: [ '/jest/mobxActionWarning.js' ], roots: [ '/src' ], transform: { '^.+\\.(js|jsx|mjs|ts|tsx)$': '/jest/babelTransform.js', diff --git a/jest/mobxActionWarning.js b/jest/mobxActionWarning.js new file mode 100644 index 00000000..5de05ca5 --- /dev/null +++ b/jest/mobxActionWarning.js @@ -0,0 +1,25 @@ +// Fails a test when MobX warns that observable state was changed outside an action. +const collected = []; +let warn; + +// The warnings collected during the running test; the proof test clears them after asserting. +export const actionWarnings = () => collected; + +beforeEach( () => { + collected.length = 0; + const original = console.warn; + warn = jest.spyOn( console, 'warn' ).mockImplementation( ( ...args ) => { + if ( /\[MobX\] Since strict-mode is enabled/.test( String( args[0] ) ) ) { + collected.push( args[0] ); + } else { + original.apply( console, args ); + } + } ); +} ); + +afterEach( () => { + warn.mockRestore(); + if ( collected.length ) { + throw new Error( `MobX changed observable state outside an action:\n${collected.join( '\n' )}` ); + } +} ); diff --git a/src/mobxActionWarning.test.js b/src/mobxActionWarning.test.js new file mode 100644 index 00000000..ea70a995 --- /dev/null +++ b/src/mobxActionWarning.test.js @@ -0,0 +1,26 @@ +import { observable, runInAction, autorun } from 'mobx'; + +import { actionWarnings } from '../jest/mobxActionWarning'; + +function observed() { + const box = observable.box( 0 ); + const stop = autorun( () => box.get() ); + return { box, stop }; +} + +describe( 'MobX action warning check', () => { + test( 'a write inside runInAction passes', () => { + const { box, stop } = observed(); + runInAction( () => box.set( 1 ) ); + stop(); + expect( actionWarnings() ).toHaveLength( 0 ); + } ); + + test( 'a write outside an action is collected, and would fail the test', () => { + const { box, stop } = observed(); + box.set( 1 ); + stop(); + expect( actionWarnings() ).toHaveLength( 1 ); + actionWarnings().length = 0; // consumed here, so the global afterEach does not fail this proof + } ); +} ); From 59afeed0a100f620513c95e4b018382cafc760a0 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 23:18:43 +0100 Subject: [PATCH 40/54] Convert the citation to an annotation map (#148) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Citation.js | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/app/store/Citation.js b/src/app/store/Citation.js index 9e025f69..731b3013 100644 --- a/src/app/store/Citation.js +++ b/src/app/store/Citation.js @@ -2,9 +2,16 @@ import { observable, action, computed, makeObservable } from 'mobx'; export default class Citation { constructor() { - makeObservable( this ); + makeObservable( this, { + visible: observable, + format: observable, + setFormat: action, + allText: computed, + show: action, + hide: action, + } ); } - @observable visible = false; + visible = false; formats = [ { value: 'txt', name: 'Plain text' }, @@ -12,8 +19,8 @@ export default class Citation { { value: 'bib', name: 'BibTeX' }, ]; - @observable format = 'txt'; - @action setFormat = ( format ) => { + format = 'txt'; + setFormat = ( format ) => { this.format = format; }; @@ -193,19 +200,16 @@ ER - `, }, ]; - @computed get allText() { return this.content.map( ( ref ) => ref[this.format] ).join( '\n' ); } - @action - show = () => { - this.visible = true; - }; - @action - hide = () => { - this.visible = false; - }; + show = () => { + this.visible = true; + }; + hide = () => { + this.visible = false; + }; copyToClipboard = async () => { const { rendererBridge } = /** @type {any} */ ( window ); From 798d13a4a80ba7e661350a2026a1ee47943e92dc Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Sun, 15 Nov 2026 23:50:49 +0100 Subject: [PATCH 41/54] Skip type-check on the Jest action-warning files Co-Authored-By: Claude Sonnet 5.5 --- jest/mobxActionWarning.js | 1 + src/mobxActionWarning.test.js | 1 + 2 files changed, 2 insertions(+) diff --git a/jest/mobxActionWarning.js b/jest/mobxActionWarning.js index 5de05ca5..3177d9b1 100644 --- a/jest/mobxActionWarning.js +++ b/jest/mobxActionWarning.js @@ -1,3 +1,4 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. // Fails a test when MobX warns that observable state was changed outside an action. const collected = []; let warn; diff --git a/src/mobxActionWarning.test.js b/src/mobxActionWarning.test.js index ea70a995..cff9546e 100644 --- a/src/mobxActionWarning.test.js +++ b/src/mobxActionWarning.test.js @@ -1,3 +1,4 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. import { observable, runInAction, autorun } from 'mobx'; import { actionWarnings } from '../jest/mobxActionWarning'; From 64d9d1223aad9d4d7141ffc88e6ab59e0f8fa5fc Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:00:48 +0100 Subject: [PATCH 42/54] Convert the config to an annotation map (#149) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Config.js | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/app/store/Config.js b/src/app/store/Config.js index b3dcd924..ba9cd58e 100644 --- a/src/app/store/Config.js +++ b/src/app/store/Config.js @@ -4,7 +4,10 @@ import StoreBase, { runEvents } from './StoreBase'; export default class Config extends StoreBase { constructor() { super(); - makeObservable( this ); + makeObservable( this, { + isDarkMode: observable, + setDarkMode: action, + } ); this.listen(); const { rendererBridge } = /** @type {any} */ ( window ); rendererBridge.getDarkMode().then( ( value ) => { @@ -14,15 +17,14 @@ export default class Config extends StoreBase { } ); } - @observable isDarkMode = false; + isDarkMode = false; - @action - setDarkMode = ( value ) => { - value = !!value; - this.isDarkMode = value; - const { rendererBridge } = /** @type {any} */ ( window ); - void rendererBridge.setDarkMode( value ); - }; + setDarkMode = ( value ) => { + value = !!value; + this.isDarkMode = value; + const { rendererBridge } = /** @type {any} */ ( window ); + void rendererBridge.setDarkMode( value ); + }; onLightMode = () => { this.setDarkMode( false ); From bdd6b59b69d212d60ce8230e21aa22e01c108bad Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:08:12 +0100 Subject: [PATCH 43/54] Convert the part, partition and final partition to annotation maps (#151) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/FinalPartition.js | 12 ++++--- src/app/store/Partition.js | 57 ++++++++++++++++++++++----------- 2 files changed, 46 insertions(+), 23 deletions(-) diff --git a/src/app/store/FinalPartition.js b/src/app/store/FinalPartition.js index 60c0d439..36bdfb68 100644 --- a/src/app/store/FinalPartition.js +++ b/src/app/store/FinalPartition.js @@ -2,7 +2,11 @@ import { computed, makeObservable } from 'mobx'; class FinalPartition { constructor( run ) { - makeObservable( this ); + makeObservable( this, { + text: computed, + isDefault: computed, + isComplete: computed, + } ); this.run = run; } /* @@ -10,7 +14,7 @@ class FinalPartition { DNA, gene1 = 1-3676 BIN, morph = 3677-3851 */ - @computed get text() { + get text() { if ( !this.run.haveAlignments ) { return ''; } @@ -22,14 +26,14 @@ class FinalPartition { } ); return partitionTexts.join( '\n' ); } - @computed get isDefault() { + get isDefault() { return ( this.run.alignments.length === 0 || ( this.run.alignments.length === 1 && this.run.alignments[0].partition.isDefault ) ); } - @computed get isComplete() { + get isComplete() { return this.run.alignments.every( ( alignment ) => alignment.partition.isComplete, ); diff --git a/src/app/store/Partition.js b/src/app/store/Partition.js index 63779450..a55f5e42 100644 --- a/src/app/store/Partition.js +++ b/src/app/store/Partition.js @@ -30,7 +30,11 @@ const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { class Part { constructor( partition, { type, aaType, name, start, end, codon } ) { - makeObservable( this ); + makeObservable( this, { + typePadded: computed, + text: computed, + values: computed, + } ); this.partition = partition; this.type = new PartType( this, type ); this.aaType = new PartAAType( this, aaType ); @@ -40,7 +44,7 @@ class Part { this.codon = new PartCodon( this, codon ); } - @computed get typePadded() { + get typePadded() { return `${this.type.finalValue},`.padEnd( 12 ); } @@ -85,14 +89,14 @@ class Part { } }; - @computed get text() { + get text() { // return `${this.typePadded}${this.name.value} = ${this.start.value}-${this.end.value}`; return this.transform(); } parse = ( row ) => {}; - @computed get values() { + get values() { return { type: this.type.value, aaType: this.aaType.value, @@ -109,7 +113,22 @@ class Part { } class Partition { constructor( alignment ) { - makeObservable( this ); + makeObservable( this, { + parts: observable, + addPart: action, + isMixed: computed, + isDefault: computed, + maxEndValue: computed, + currentEndValue: computed, + isComplete: computed, + nonDefaultPartitionComplete: computed, + progress: computed, + haveError: computed, + errorMessage: computed, + addPartDisabled: computed, + text: computed, + reset: action, + } ); this.alignment = alignment; this.defaultPartition = new Part( this, { type: alignment.partitionType, @@ -155,9 +174,9 @@ class Partition { { name: 'React to default partition type change' }, ); } - @observable parts = []; + parts = []; // Add current part values - @action addPart = () => { + addPart = () => { this.parts.push( this.partToAdd.clone() ); // Reset or update in partToAdd this.partToAdd.codon.value = CODON_NONE; @@ -177,44 +196,44 @@ class Partition { this.partToAdd.name.value = newName; } }; - @computed get isMixed() { + get isMixed() { return this.alignment.dataType === 'mixed'; } - @computed get isDefault() { + get isDefault() { return this.parts.length === 0; } - @computed get maxEndValue() { + get maxEndValue() { return this.alignment.length; } - @computed get currentEndValue() { + get currentEndValue() { return this.isDefault ? this.defaultPartition.end.value : this.parts[this.parts.length - 1].end.value; } - @computed get isComplete() { + get isComplete() { return this.currentEndValue === this.maxEndValue; } - @computed get nonDefaultPartitionComplete() { + get nonDefaultPartitionComplete() { return !this.isDefault && this.isComplete; } - @computed get progress() { + get progress() { return this.isDefault ? 100 : ( this.currentEndValue * 100.0 ) / this.alignment.length; } - @computed get haveError() { + get haveError() { return this.partToAdd.end.haveError; } - @computed get errorMessage() { + get errorMessage() { return this.haveError ? `End position error: ${this.partToAdd.end.errorMessage}` : ''; } - @computed get addPartDisabled() { + get addPartDisabled() { return this.nonDefaultPartitionComplete || this.haveError; } - @computed get text() { + get text() { if ( this.isDefault ) { // return this.alignment.partitionFileContent; return this.defaultPartition.text; @@ -228,7 +247,7 @@ class Partition { return this.parts.map( ( part ) => part.transform( offset, prefix ) ).join( '\n' ); }; - @action reset = () => { + reset = () => { if ( this.parts.length > 0 ) { this.parts.splice( 0 ); this.partToAdd.name.value = 'part_1'; From e51b6d7276132aa3b9cf525c7698b8b4b0377392 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:08:27 +0100 Subject: [PATCH 44/54] Convert the final alignment to an annotation map (#150) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/FinalAlignment.js | 182 +++++++++++++++++--------------- src/app/store/FinalPartition.js | 12 ++- 2 files changed, 107 insertions(+), 87 deletions(-) diff --git a/src/app/store/FinalAlignment.js b/src/app/store/FinalAlignment.js index 964c40a9..3a8892ad 100644 --- a/src/app/store/FinalAlignment.js +++ b/src/app/store/FinalAlignment.js @@ -8,47 +8,70 @@ import { join } from '../paths'; class FinalAlignment { constructor( run ) { - makeObservable( this ); + makeObservable( this, { + filename: computed, + dir: computed, + path: computed, + parsingComplete: observable, + numAlignments: computed, + fillTaxonGapsWithEmptySeqeunces: observable, + setFillTaxonGapsWithEmptySeqeunces: action, + taxons: computed, + numSequences: computed, + length: computed, + hasInvariantSites: computed, + dataType: computed, + modelFlagName: computed, + partitionFilePath: computed, + partitionFileContent: computed, + openFile: action, + openPartition: action, + showFileInFolder: action, + openFolder: action, + writeConcatenatedAlignmentAndPartition: action, + writeConcatenatedAlignment: action, + writePartition: action, + } ); this.run = run; this.partition = new FinalPartition( run ); } - @computed get filename() { + get filename() { if ( this.numAlignments === 1 ) { return this.run.alignments[0].filename; } return `RAxML_${this.run.outputNameSafe}_concat.txt`; } - @computed get dir() { + get dir() { if ( this.numAlignments === 1 ) { return this.run.alignments[0].dir; } return this.run.outputDir; } - @computed get path() { + get path() { if ( this.numAlignments === 1 ) { return this.run.alignments[0].path; } return join( `${this.dir}`, `${this.filename}` ); } - @observable parsingComplete = true; + parsingComplete = true; - @computed get numAlignments() { + get numAlignments() { return this.run.alignments.length; } // By default add empty sequences to fill gaps up to the union of taxons // else drop taxons that doesn't exist in all alignments by taking the intersection - @observable fillTaxonGapsWithEmptySeqeunces = true; + fillTaxonGapsWithEmptySeqeunces = true; - @action setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { + setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { this.fillTaxonGapsWithEmptySeqeunces = checked; }; - @computed get taxons() { + get taxons() { const setMethod = this.fillTaxonGapsWithEmptySeqeunces ? union : intersection; @@ -58,18 +81,18 @@ class FinalAlignment { ); } - @computed get numSequences() { + get numSequences() { return this.taxons.length; } - @computed get length() { + get length() { return this.run.alignments.reduce( ( sumLength, alignment ) => sumLength + alignment.length, 0, ); } - @computed get hasInvariantSites() { + get hasInvariantSites() { // If any one of the alignments has invariant sites return true for ( const alignment of this.run.alignments ) { if ( alignment.hasInvariantSites ) { @@ -79,7 +102,7 @@ class FinalAlignment { return false; } - // @computed get dataType() { + // get dataType() { // const numAlignments = this.numAlignments; // if (numAlignments === 0) { // return 'none'; @@ -96,13 +119,13 @@ class FinalAlignment { // return firstType; // } - @computed get dataType() { + get dataType() { const { alignments } = this.run; const dataTypes = alignments.map( ( { dataType } ) => dataType ); return getFinalDataType( dataTypes ); } - @computed get modelFlagName() { + get modelFlagName() { const {numAlignments} = this; if ( numAlignments === 0 ) { return 'none'; @@ -114,7 +137,7 @@ class FinalAlignment { return first; } - @computed get partitionFilePath() { + get partitionFilePath() { if ( this.partition.isDefault ) { return ''; } @@ -127,82 +150,75 @@ class FinalAlignment { ); } - @computed get partitionFileContent() { + get partitionFileContent() { return this.partition.text; } - @action - openFile = async () => { - await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.path ); - }; + openFile = async () => { + await this.writeConcatenatedAlignment(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.path ); + }; - @action - openPartition = async () => { - await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.partitionFilePath ); - }; + openPartition = async () => { + await this.writeConcatenatedAlignmentAndPartition(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.partitionFilePath ); + }; - @action - showFileInFolder = async () => { - await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.path ); - }; + showFileInFolder = async () => { + await this.writeConcatenatedAlignment(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.path ); + }; - @action - openFolder = async () => { - await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.dir ); - }; - - @action - writeConcatenatedAlignmentAndPartition = async () => { - await this.writeConcatenatedAlignment(); - await this.writePartition(); - }; - - @action - writeConcatenatedAlignment = async () => { - const { taxons, numSequences } = this; - try { - console.log( - `Write concatenated alignment in FASTA format to ${this.path}..`, - ); - let text = ''; - for ( let i = 0; i < numSequences; ++i ) { - for ( let j = 0; j < this.numAlignments; ++j ) { - if ( j === 0 ) { - const prefix = i === 0 - ? '>' - : '\n>'; - text += `${prefix}${taxons[i]}\n`; - } - text += this.run.alignments[j].getSequenceCode( taxons[i] ); + openFolder = async () => { + await this.writeConcatenatedAlignmentAndPartition(); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.dir ); + }; + + writeConcatenatedAlignmentAndPartition = async () => { + await this.writeConcatenatedAlignment(); + await this.writePartition(); + }; + + writeConcatenatedAlignment = async () => { + const { taxons, numSequences } = this; + try { + console.log( + `Write concatenated alignment in FASTA format to ${this.path}..`, + ); + let text = ''; + for ( let i = 0; i < numSequences; ++i ) { + for ( let j = 0; j < this.numAlignments; ++j ) { + if ( j === 0 ) { + const prefix = i === 0 + ? '>' + : '\n>'; + text += `${prefix}${taxons[i]}\n`; } + text += this.run.alignments[j].getSequenceCode( taxons[i] ); } - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.path, text ); - } catch ( err ) { - console.error( 'Error writing concatenated alignment:', err ); - throw err; - } - }; - - @action - writePartition = async () => { - try { - console.log( `Writing partition to ${this.partitionFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); - } catch ( err ) { - console.error( 'Error writing partition:', err ); - throw err; } - }; + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.path, text ); + } catch ( err ) { + console.error( 'Error writing concatenated alignment:', err ); + throw err; + } + }; + + writePartition = async () => { + try { + console.log( `Writing partition to ${this.partitionFilePath}...` ); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); + } catch ( err ) { + console.error( 'Error writing partition:', err ); + throw err; + } + }; } export default FinalAlignment; diff --git a/src/app/store/FinalPartition.js b/src/app/store/FinalPartition.js index 60c0d439..36bdfb68 100644 --- a/src/app/store/FinalPartition.js +++ b/src/app/store/FinalPartition.js @@ -2,7 +2,11 @@ import { computed, makeObservable } from 'mobx'; class FinalPartition { constructor( run ) { - makeObservable( this ); + makeObservable( this, { + text: computed, + isDefault: computed, + isComplete: computed, + } ); this.run = run; } /* @@ -10,7 +14,7 @@ class FinalPartition { DNA, gene1 = 1-3676 BIN, morph = 3677-3851 */ - @computed get text() { + get text() { if ( !this.run.haveAlignments ) { return ''; } @@ -22,14 +26,14 @@ class FinalPartition { } ); return partitionTexts.join( '\n' ); } - @computed get isDefault() { + get isDefault() { return ( this.run.alignments.length === 0 || ( this.run.alignments.length === 1 && this.run.alignments[0].partition.isDefault ) ); } - @computed get isComplete() { + get isComplete() { return this.run.alignments.every( ( alignment ) => alignment.partition.isComplete, ); From 74ebd345d3b5f1b140e82b8571d1b9ce5f4ec5a1 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:09:00 +0100 Subject: [PATCH 45/54] Convert the run list to an annotation map (#153) AppStore converts with it: its decorators and the run list's map cannot share an inheritance chain. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/AppStore.js | 15 +++-- src/app/store/RunList.js | 115 ++++++++++++++++++++------------------ 2 files changed, 70 insertions(+), 60 deletions(-) diff --git a/src/app/store/AppStore.js b/src/app/store/AppStore.js index e9e02ed5..b5bc5aec 100644 --- a/src/app/store/AppStore.js +++ b/src/app/store/AppStore.js @@ -6,20 +6,25 @@ import Config from './Config'; class AppStore extends StoreBase { constructor() { super(); - makeObservable( this ); + makeObservable( this, { + version: observable, + showAppSnack: observable, + setAppSnack: action, + clearAppSnack: action, + } ); } citation = new Citation(); config = new Config(); - @observable version = undefined; + version = undefined; - @observable showAppSnack = false; + showAppSnack = false; - @action setAppSnack = () => { + setAppSnack = () => { this.showAppSnack = true; }; - @action clearAppSnack = () => { + clearAppSnack = () => { this.showAppSnack = false; }; } diff --git a/src/app/store/RunList.js b/src/app/store/RunList.js index 27f3fff8..a5630c9a 100644 --- a/src/app/store/RunList.js +++ b/src/app/store/RunList.js @@ -4,82 +4,87 @@ import AppStore from './AppStore'; import { runEvents } from './StoreBase'; class RunList extends AppStore { - @observable runs = []; - @observable activeIndex = 0; + runs = []; + activeIndex = 0; constructor() { super(); - makeObservable( this ); + makeObservable( this, { + runs: observable, + activeIndex: observable, + error: observable, + errorTitle: observable, + clearError: action, + activeRun: computed, + addRun: action, + deleteRun: action, + setActive: action, + deleteActive: action, + onError: action, + onUnhandledError: action, + onBackboneConstraint: action, + onMultifurcatingConstraint: action, + } ); this.addRun(); this.listen(); } - @observable error = null; - @observable errorTitle = null; - @action - clearError = () => { - this.error = null; - this.errorTitle = null; - }; + error = null; + errorTitle = null; + clearError = () => { + this.error = null; + this.errorTitle = null; + }; - @computed get activeRun() { return this.runs[this.activeIndex]; } - @action - addRun = () => { - let maxId = 0; - this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); - this.runs.push( new Run( this, maxId + 1 ) ); - this.activeIndex = this.runs.length - 1; - }; + addRun = () => { + let maxId = 0; + this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); + this.runs.push( new Run( this, maxId + 1 ) ); + this.activeIndex = this.runs.length - 1; + }; - @action - deleteRun = ( run ) => { - run.dispose(); - const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); - this.runs.splice( runIndex, 1 ); - if ( this.runs.length === 0 ) { - this.runs.push( new Run( this, 1 ) ); - } - this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); - }; + deleteRun = ( run ) => { + run.dispose(); + const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); + this.runs.splice( runIndex, 1 ); + if ( this.runs.length === 0 ) { + this.runs.push( new Run( this, 1 ) ); + } + this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); + }; - @action - setActive = ( index ) => { - this.activeIndex = index; - }; + setActive = ( index ) => { + this.activeIndex = index; + }; - @action - deleteActive = () => { - this.deleteRun( this.activeRun ); - }; + deleteActive = () => { + this.deleteRun( this.activeRun ); + }; - @action - onError = ( error ) => { - this.errorTitle = null; - this.error = error; - }; + onError = ( error ) => { + this.errorTitle = null; + this.error = error; + }; - @action - onUnhandledError = ( { title, error } ) => { - console.log( `Unhandled error:`, error ); - this.errorTitle = title; - this.error = error; - }; + onUnhandledError = ( { title, error } ) => { + console.log( `Unhandled error:`, error ); + this.errorTitle = title; + this.error = error; + }; - @action - onBackboneConstraint = ( event, params ) => { - this.activeRun.useBackboneConstraint = + onBackboneConstraint = ( event, params ) => { + this.activeRun.useBackboneConstraint = !this.activeRun.useBackboneConstraint; - }; + }; - @action - onMultifurcatingConstraint = ( event, params ) => { - this.activeRun.useMultifurcatingConstraint = + onMultifurcatingConstraint = ( event, params ) => { + this.activeRun.useMultifurcatingConstraint = !this.activeRun.useMultifurcatingConstraint; - }; + }; listen = () => { this.subscribe( runEvents.onUnhandledError, this.onUnhandledError ); From af425e99f407ed645900872576b7b9ad073c3455 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:09:27 +0100 Subject: [PATCH 46/54] Convert the Option family to annotation maps (#155) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/AlignmentOptions.js | 39 +++-- src/app/store/Option.js | 24 ++- src/app/store/PartOptions.js | 54 ++++--- src/app/store/RunOptions.js | 235 ++++++++++++++++++++---------- 4 files changed, 233 insertions(+), 119 deletions(-) diff --git a/src/app/store/AlignmentOptions.js b/src/app/store/AlignmentOptions.js index 0a9d5feb..6b8affae 100644 --- a/src/app/store/AlignmentOptions.js +++ b/src/app/store/AlignmentOptions.js @@ -8,10 +8,14 @@ const raxmlNgModelOptions = raxmlNgSettings.modelOptions; class RaxmlNgAlignmentSubstitutionModel extends Option { constructor( alignment ) { super( alignment.run, '', 'Substitution model' ); - makeObservable( this ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + } ); this.alignment = alignment; } - @computed get options() { + get options() { if ( !this.alignment.run.haveAlignments ) { return []; } @@ -21,10 +25,10 @@ class RaxmlNgAlignmentSubstitutionModel extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - @computed get notAvailable() { + get notAvailable() { return !this.alignment.run.haveAlignments; } - @computed get cmdValue() { + get cmdValue() { let model = this.value; if ( this.alignment.dataType === 'multistate' ) { model = model.replace( 'x', this.alignment.multistateNumber.value ); @@ -38,23 +42,27 @@ class RaxmlNgModelExtraParam extends Option { super( alignment.run, addNone ? '' : options[0].value, label ); - makeObservable( this ); + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + } ); this.alignment = alignment; this.optionsSource = addNone ? [{ value: '', title: 'none' }, ...options] : options; this.addNone = addNone; } - @computed get options() { + get options() { if ( !this.run.haveAlignments ) { return []; } return this.optionsSource; } - @computed get notAvailable() { + get notAvailable() { return !this.run.haveAlignments || !this.run.usesRaxmlNg; } - @computed get cmdValue() { + get cmdValue() { return this.value === '' ? '' : this.value; @@ -108,9 +116,11 @@ class RaxmlNgModelASC extends RaxmlNgModelExtraParam { ].map( ( { value, label: title } ) => ( { value, title } ) ), { addNone: false }, ); - makeObservable( this ); + makeObservable( this, { + notAvailable: override, + } ); } - @override get notAvailable() { + get notAvailable() { return ( !this.run.haveAlignments || !this.run.usesRaxmlNg || @@ -122,17 +132,20 @@ class RaxmlNgModelASC extends RaxmlNgModelExtraParam { class MultistateNumber extends Option { constructor( alignment ) { super( alignment.run, '', 'Number of states' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + error: override, + } ); this.alignment = alignment; this.placeholder = 'Integer'; } - @computed get notAvailable() { + get notAvailable() { return ( this.alignment.dataType !== 'multistate' || !this.alignment.run.usesRaxmlNg ); } - @override get error() { + get error() { return !this.value || !Number.isInteger( Number( this.value ) ); } } diff --git a/src/app/store/Option.js b/src/app/store/Option.js index 7d9d956a..36aa7279 100644 --- a/src/app/store/Option.js +++ b/src/app/store/Option.js @@ -19,7 +19,15 @@ class Option { hoverInfo, { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, ) { - makeObservable( this ); + makeObservable( this, { + value: observable, + setValue: action, + reset: action, + isDefault: computed, + error: computed, + haveError: computed, + errorMessage: computed, + } ); this.run = run; this.defaultValue = defaultValue; this.title = title; @@ -32,8 +40,8 @@ class Option { this.helperText = helperText; this.value = defaultValue; } - @observable value; - @action setValue( value ) { + value; + setValue( value ) { const isValid = this.schema.isValidSync( value ); if ( !this.allowOnlyValidChange || isValid ) { this.value = isValid @@ -41,13 +49,13 @@ class Option { : value; } } - @action reset() { + reset() { this.value = this.defaultValue; } - @computed get isDefault() { + get isDefault() { return this.value === this.defaultValue; } - @computed get error() { + get error() { try { this.schema.validateSync( this.value ); return null; @@ -55,10 +63,10 @@ class Option { return err; } } - @computed get haveError() { + get haveError() { return this.error !== null; } - @computed get errorMessage() { + get errorMessage() { return this.haveError ? this.error.message : ''; diff --git a/src/app/store/PartOptions.js b/src/app/store/PartOptions.js index 778e8289..6a6166a9 100644 --- a/src/app/store/PartOptions.js +++ b/src/app/store/PartOptions.js @@ -29,10 +29,12 @@ class PartBase extends Option { helperText, }, ); - makeObservable( this ); + makeObservable( this, { + alignment: computed, + } ); this.part = part; } - @computed get alignment() { + get alignment() { return this.part.partition.alignment; } } @@ -43,9 +45,13 @@ class PartType extends PartBase { schema: yup.string(), allowOnlyValidChange: true, } ); - makeObservable( this ); + makeObservable( this, { + finalValue: computed, + options: computed, + notAvailable: computed, + } ); } - @computed get finalValue() { + get finalValue() { const { dataType, partitionType } = this.alignment; if ( dataType === 'protein' || this.value === 'protein' ) { return this.part.aaType.value; @@ -55,7 +61,7 @@ class PartType extends PartBase { } return partitionType; } - @computed get options() { + get options() { const { dataType } = this.alignment; let opts = [dataType]; if ( dataType === '' || dataType === 'mixed' ) { @@ -63,7 +69,7 @@ class PartType extends PartBase { } return opts.map( ( value ) => ( { value, title: value } ) ); } - @computed get notAvailable() { + get notAvailable() { return this.alignment.dataType !== 'mixed'; } } @@ -73,12 +79,14 @@ class PartAAType extends PartBase { schema: yup.string(), allowOnlyValidChange: true, } ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( ( value ) => ( { value, title: value } ), ); - @computed get notAvailable() { + get notAvailable() { return this.alignment.dataType !== 'protein'; } } @@ -88,9 +96,11 @@ class PartName extends PartBase { schema: yup.string(), // TODO: Check that it is unique within partition allowOnlyValidChange: true, } ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } - @computed get notAvailable() { + get notAvailable() { return false; } } @@ -100,10 +110,12 @@ class PartStart extends PartBase { schema: yup.number(), allowOnlyValidChange: false, } ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); this.disabled = true; } - @computed get notAvailable() { + get notAvailable() { return false; } } @@ -127,19 +139,23 @@ class PartEnd extends PartBase { allowOnlyValidChange: false, }, ); - makeObservable( this ); + makeObservable( this, { + min: computed, + max: computed, + notAvailable: computed, + } ); } - @computed get min() { + get min() { return ( this.part.start.value + ( this.part.codon.value === CODON_NONE ? 0 : 2 ) ); } - @computed get max() { + get max() { return this.alignment.length; } - @computed get notAvailable() { + get notAvailable() { return false; } } @@ -150,10 +166,12 @@ class PartCodon extends PartBase { schema: yup.string(), allowOnlyValidChange: true, } ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = CodonModels.map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { + get notAvailable() { return this.alignment.partition.partToAdd.type.value !== 'DNA'; } } diff --git a/src/app/store/RunOptions.js b/src/app/store/RunOptions.js index af935638..bb7ca28f 100644 --- a/src/app/store/RunOptions.js +++ b/src/app/store/RunOptions.js @@ -263,13 +263,16 @@ export const raxmlNgAnalysisOptions = [ export class Binary extends Option { constructor( run ) { super( run, initialBinaryName, 'Binary', 'Name of binary' ); - makeObservable( this ); + makeObservable( this, { + version: computed, + type: computed, + } ); } options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); - @computed get version() { + get version() { return binaries.filter( ( b ) => b.name === this.value )[0].version; } - @computed get type() { + get type() { return binaries.filter( ( b ) => b.name === this.value )[0].type; } } @@ -277,13 +280,15 @@ export class Binary extends Option { export class NumThreads extends Option { constructor( run ) { super( run, 2, 'Threads', 'Number of cpu threads' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { value, title: value, } ) ); - @computed get notAvailable() { + get notAvailable() { return !( /PTHREADS/.test( this.run.binary.value ) || this.run.usesModeltestNg ); @@ -310,10 +315,12 @@ export class RaxmlNgAnalysis extends Option { export class NumRuns extends Option { constructor( run ) { super( run, 1, 'Runs', 'Number of runs' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.runs ); } } @@ -321,7 +328,9 @@ export class NumRuns extends Option { export class NumRepetitions extends Option { constructor( run ) { super( run, 100, 'Reps.', 'Number of repetitions' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = [ 100, @@ -334,7 +343,7 @@ export class NumRepetitions extends Option { 'autoMRE_IGN', 'autoFC', ].map( ( value ) => ( { value, title: value } ) ); - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.reps ); } } @@ -342,13 +351,15 @@ export class NumRepetitions extends Option { export class NumRepetitionsNg extends Option { constructor( run ) { super( run, 100, 'Reps.', 'Number of repetitions' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { value, title: value, } ) ); - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.repsNg ); } } @@ -363,9 +374,11 @@ export class BranchLength extends Option { 'Compute branch lengths', 'Optimize model parameters and branch lengths for the given input tree', ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.brL ); } } @@ -379,9 +392,11 @@ export class SHlike extends Option { 'Compute log-likelihood test', 'Shimodaira-Hasegawa-like procedure', ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.SHlike ); } } @@ -389,12 +404,15 @@ export class SHlike extends Option { export class CombinedOutput extends Option { constructor( run ) { super( run, false, 'Combined output', 'Concatenate output trees' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + isUsed: computed, + } ); } - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.combinedOutput ); } - @computed get isUsed() { + get isUsed() { return this.value && !this.notAvailable; } } @@ -402,13 +420,15 @@ export class CombinedOutput extends Option { export class StartingTree extends Option { constructor( run ) { super( run, 'Maximum parsimony', 'Starting tree', '' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { value, title: value, } ) ); - @computed get notAvailable() { + get notAvailable() { return !this.run.analysisOption.params.includes( params.startingTree ); } } @@ -416,17 +436,22 @@ export class StartingTree extends Option { export class OutGroup extends Option { constructor( run ) { super( run, [''], 'Outgroup', '' ); - makeObservable( this ); + makeObservable( this, { + options: computed, + setValue: override, + notAvailable: computed, + cmdValue: computed, + } ); this.multiple = true; } - @computed get options() { + get options() { return ['', ...this.run.taxons].map( ( value ) => ( { value, title: value, } ) ); } - @override setValue( value ) { + setValue( value ) { if ( this.value.includes( '' ) ) { this.value = value.filter( ( v ) => v !== '' ); return; @@ -438,13 +463,13 @@ export class OutGroup extends Option { this.value = value; } - @computed get notAvailable() { + get notAvailable() { return ( !this.run.haveAlignments || !this.run.analysisOption.params.includes( params.outGroup ) ); } - @computed get cmdValue() { + get cmdValue() { return this.value.includes( '' ) ? '' : this.value.join( ',' ); @@ -454,9 +479,15 @@ export class OutGroup extends Option { export class SubstitutionMatrix extends Option { constructor( run ) { super( run, 'GTR', 'Substitution matrix' ); - makeObservable( this ); - } - @computed get options() { + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + extraCmdValue: computed, + notGTR: computed, + } ); + } + get options() { if ( !this.run.haveAlignments ) { return []; } @@ -471,7 +502,7 @@ export class SubstitutionMatrix extends Option { : `${value} + GAMMA`, } ) ); } - @computed get notAvailable() { + get notAvailable() { return ( !this.run.haveAlignments || this.run.dataType === 'binary' || @@ -480,7 +511,7 @@ export class SubstitutionMatrix extends Option { this.run.usesRaxmlNg ); } - @computed get cmdValue() { + get cmdValue() { if ( this.run.dataType === 'binary' ) { return 'BIN'; } @@ -495,7 +526,7 @@ export class SubstitutionMatrix extends Option { } return this.value; } - @computed get extraCmdValue() { + get extraCmdValue() { switch ( this.value ) { case 'JC': return '--JC69'; @@ -507,7 +538,7 @@ export class SubstitutionMatrix extends Option { return ''; } } - @computed get notGTR() { + get notGTR() { return this.value !== 'GTR'; } } @@ -515,9 +546,14 @@ export class SubstitutionMatrix extends Option { export class SubstitutionRate extends Option { constructor( run ) { super( run, 'GAMMA', 'Substitution rates' ); - makeObservable( this ); - } - @computed get options() { + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + isCAT: computed, + } ); + } + get options() { if ( !this.run.haveAlignments ) { return []; } @@ -527,7 +563,7 @@ export class SubstitutionRate extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - @computed get notAvailable() { + get notAvailable() { return ( !this.run.haveAlignments || ( ( this.run.dataType === 'dna' || @@ -537,13 +573,13 @@ export class SubstitutionRate extends Option { this.run.usesRaxmlNg ); } - @computed get cmdValue() { + get cmdValue() { if ( this.run.substitutionMatrix.notGTR ) { return 'GAMMA'; } return this.value; } - @computed get isCAT() { + get isCAT() { return this.value === 'CAT'; } } @@ -551,9 +587,14 @@ export class SubstitutionRate extends Option { export class SubstitutionI extends Option { constructor( run ) { super( run, 'none', 'Proportion of invariant sites' ); - makeObservable( this ); - } - @computed get options() { + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + isSet: computed, + } ); + } + get options() { if ( !this.run.haveAlignments ) { return []; } @@ -563,19 +604,19 @@ export class SubstitutionI extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - @computed get notAvailable() { + get notAvailable() { return ( this.run.substitutionAscertainment.isSet || !this.run.haveAlignments || this.run.usesRaxmlNg ); } - @computed get cmdValue() { + get cmdValue() { return this.value === 'none' ? '' : 'I'; } - @computed get isSet() { + get isSet() { return this.value !== 'none'; } } @@ -583,9 +624,15 @@ export class SubstitutionI extends Option { export class SubstitutionAscertainment extends Option { constructor( run ) { super( run, 'none', 'Ascertainment bias correction' ); - makeObservable( this ); - } - @computed get options() { + makeObservable( this, { + options: computed, + notAvailable: computed, + cmdValue: computed, + extraCmdValue: computed, + isSet: computed, + } ); + } + get options() { if ( !this.run.haveAlignments ) { return []; } @@ -595,7 +642,7 @@ export class SubstitutionAscertainment extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - @computed get notAvailable() { + get notAvailable() { return ( !this.run.haveAlignments || this.run.usesRaxmlNg || @@ -604,12 +651,12 @@ export class SubstitutionAscertainment extends Option { this.run.substitutionI.isSet ); } - @computed get cmdValue() { + get cmdValue() { return this.value === 'none' ? '' : 'ASC_'; } - @computed get extraCmdValue() { + get extraCmdValue() { switch ( this.value ) { case "Lewis' method": return '--asc-corr=lewis'; @@ -621,7 +668,7 @@ export class SubstitutionAscertainment extends Option { return ''; } } - @computed get isSet() { + get isSet() { return this.value !== 'none'; } } @@ -634,12 +681,14 @@ export class AAMatrixName extends Option { 'Matrix name', 'Amino Acid Substitution Matrix name', ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( ( value ) => ( { value, title: value } ), ); - @computed get notAvailable() { + get notAvailable() { return this.run.dataType !== 'protein'; } } @@ -653,9 +702,11 @@ export class EstimatedFrequencies extends Option { 'Estimated base frequencies', 'Use estimated base frequencies instead of empirical.', ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } - @computed get notAvailable() { + get notAvailable() { return this.run.dataType === 'protein' || this.run.usesRaxmlNg; } } @@ -668,14 +719,16 @@ export class BaseFrequencies extends Option { 'Base frequencies', 'Empirical, ML estimated or model based base frequencies', ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = [ { title: 'From model', value: 'default' }, { title: 'Empirical', value: 'F' }, { title: 'Estimated (ML)', value: 'X' }, ]; - @computed get notAvailable() { + get notAvailable() { return this.run.dataType !== 'protein' || this.run.usesRaxmlNg; } } @@ -683,12 +736,14 @@ export class BaseFrequencies extends Option { export class MultistateModel extends Option { constructor( run ) { super( run, 'GTR', 'Multistate model' ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( ( value ) => ( { value, title: value } ), ); - @computed get notAvailable() { + get notAvailable() { return this.run.dataType !== 'multistate' || this.run.usesRaxmlNg; } } @@ -696,33 +751,43 @@ export class MultistateModel extends Option { class TreeFile extends Option { constructor( run ) { super( run, '', 'Tree', '' ); - makeObservable( this ); - } - @observable filePath = ''; - @computed get haveFile() { + makeObservable( this, { + filePath: observable, + haveFile: computed, + filename: computed, + name: computed, + dir: computed, + setFilePath: action, + openFolder: action, + openFile: action, + remove: action, + } ); + } + filePath = ''; + get haveFile() { return !!this.filePath; } - @computed get filename() { + get filename() { return basename( this.filePath ); } - @computed get name() { + get name() { return name( this.filePath ); } - @computed get dir() { + get dir() { return dir( this.filePath ); } - @action setFilePath = ( filePath ) => { + setFilePath = ( filePath ) => { this.filePath = filePath; }; - @action openFolder = async () => { + openFolder = async () => { const { rendererBridge } = /** @type {any} */ ( window ); await rendererBridge.showItemInFolder( this.filePath ); }; - @action openFile = async () => { + openFile = async () => { const { rendererBridge } = /** @type {any} */ ( window ); await rendererBridge.openPath( this.filePath ); }; - @action remove = () => { + remove = () => { this.setFilePath( '' ); }; } @@ -730,9 +795,11 @@ class TreeFile extends Option { export class Tree extends TreeFile { constructor( ...args ) { super( ...args ); - makeObservable( this ); + makeObservable( this, { + notAvailable: computed, + } ); } - @computed get notAvailable() { + get notAvailable() { return !( this.run.analysisOption.params.includes( params.tree ) || ( !this.run.startingTree.notAvailable && @@ -744,12 +811,16 @@ export class Tree extends TreeFile { export class BackboneConstraintTree extends TreeFile { constructor( ...args ) { super( ...args ); - makeObservable( this ); + makeObservable( this, { + isSet: computed, + canConstraint: computed, + notAvailable: computed, + } ); } - @computed get isSet() { + get isSet() { return this.run.useBackboneConstraint && this.haveFile; } - @computed get canConstraint() { + get canConstraint() { const analysisWithConstraint = [ 'ML', 'ML+rBS', @@ -764,7 +835,7 @@ export class BackboneConstraintTree extends TreeFile { ]; return analysisWithConstraint.includes( this.run.analysis.value ); } - @computed get notAvailable() { + get notAvailable() { return !this.run.useBackboneConstraint || !this.canConstraint; } } @@ -772,12 +843,16 @@ export class BackboneConstraintTree extends TreeFile { export class MultifurcatingConstraintTree extends TreeFile { constructor( ...args ) { super( ...args ); - makeObservable( this ); + makeObservable( this, { + isSet: computed, + canConstraint: computed, + notAvailable: computed, + } ); } - @computed get isSet() { + get isSet() { return this.run.useMultifurcatingConstraint && this.haveFile; } - @computed get canConstraint() { + get canConstraint() { const analysisWithConstraint = [ 'ML', 'ML+rBS', @@ -792,7 +867,7 @@ export class MultifurcatingConstraintTree extends TreeFile { ]; return analysisWithConstraint.includes( this.run.analysis.value ); } - @computed get notAvailable() { + get notAvailable() { return !this.run.useMultifurcatingConstraint || !this.canConstraint; } } From 5133ae43e4771111f822386190f6dbc293b02c60 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:09:30 +0100 Subject: [PATCH 47/54] Convert the input file, alignment and ASTRAL tree to annotation maps (#154) Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Alignment.js | 450 +++++++++++++++++++----------------- src/app/store/AstralTree.js | 9 +- src/app/store/InputFile.js | 40 ++-- 3 files changed, 265 insertions(+), 234 deletions(-) diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.js index 59c2cc83..8c94e42f 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.js @@ -23,7 +23,55 @@ const raxmlNgModelOptions = raxmlNgSettings.modelOptions; class Alignment extends InputFile { constructor( run, path ) { super( run, path ); - makeObservable( this ); + makeObservable( this, { + error: observable, + dataType: observable, + aaMatrixName: observable, + size: observable, + fileFormat: observable, + convertedFrom: observable, + converted: observable, + modified: observable, + modificationMessages: observable, + showModifiedSnack: observable, + showModifiedDialog: observable, + length: observable, + numSequences: observable, + sequences: observable, + hasInvariantSites: observable, + parsingComplete: observable, + typecheckingComplete: observable, + loading: observable, + checkRunComplete: observable, + checkRunData: observable, + checkRunSuccess: observable, + partitionText: observable, + modeltestLoading: observable, + taxons: computed, + showPartition: computed, + partitionType: computed, + partitionFileContent: computed, + ngSubstitutionModelCmd: computed, + numSites: computed, + status: computed, + modelExtra: computed, + modelTestCanRun: computed, + setShowPartition: action, + hidePartition: action, + setPartitionText: action, + runModelTest: action, + cancelModelTest: action, + setModelFromString: action, + onModelSelectionSuccess: action, + onModelSelectionFailure: action, + clearModified: action, + dispose: action, + remove: action, + onChangeModel: action, + onChangeAAMatrixName: action, + onRunStdout: action, + onRunStderr: action, + } ); this.substitutionModel = new RaxmlNgAlignmentSubstitutionModel( this ); this.multistateNumber = new MultistateNumber( this ); this.ngStationaryFrequencies = new RaxmlNgModelF( this ); @@ -39,64 +87,60 @@ class Alignment extends InputFile { this.listen(); } - @observable error = null; + error = null; - @observable dataType = undefined; + dataType = undefined; /** @type {string} */ - @observable aaMatrixName = + aaMatrixName = raxmlSettings.aminoAcidSubstitutionMatrixOptions.default; - @observable size = 0; - @observable fileFormat = undefined; - @observable convertedFrom = undefined; - @observable converted = false; - @observable modified = false; - @observable modificationMessages = []; - @observable showModifiedSnack = false; - @observable showModifiedDialog = false; - @observable length = 0; - @observable numSequences = 0; - @observable sequences = []; - @observable hasInvariantSites = false; - - @computed get taxons() { + size = 0; + fileFormat = undefined; + convertedFrom = undefined; + converted = false; + modified = false; + modificationMessages = []; + showModifiedSnack = false; + showModifiedDialog = false; + length = 0; + numSequences = 0; + sequences = []; + hasInvariantSites = false; + + get taxons() { return this.sequences.map( ( seq ) => seq.taxon ); } - @observable parsingComplete = false; - @observable typecheckingComplete = false; - @observable loading = true; + parsingComplete = false; + typecheckingComplete = false; + loading = true; - @observable checkRunComplete = false; - @observable checkRunData = ''; - @observable checkRunSuccess = false; - // @observable taxons = []; + checkRunComplete = false; + checkRunData = ''; + checkRunSuccess = false; // Partition stuff - @computed get showPartition() { + get showPartition() { return this.run.showPartitionFor === this; } - @action - setShowPartition = ( value = true ) => { - this.run.showPartition( value - ? this - : null ); - }; + setShowPartition = ( value = true ) => { + this.run.showPartition( value + ? this + : null ); + }; - @action - hidePartition = () => { - this.setShowPartition( false ); - }; + hidePartition = () => { + this.setShowPartition( false ); + }; - @action - setPartitionText = ( value ) => { - this.partitionText = value; - }; + setPartitionText = ( value ) => { + this.partitionText = value; + }; - @observable partitionText = ''; + partitionText = ''; - @computed get partitionType() { + get partitionType() { if ( this.run.usesRaxmlNg ) { return this.ngSubstitutionModelCmd; } @@ -115,7 +159,7 @@ class Alignment extends InputFile { } } - @computed get partitionFileContent() { + get partitionFileContent() { /* DNA, gene1 = 1-3676 BIN, morph = 3677-3851 @@ -131,16 +175,14 @@ class Alignment extends InputFile { return partitionFileText; } - @computed get ngSubstitutionModelCmd() { + get ngSubstitutionModelCmd() { return `${this.substitutionModel.cmdValue}${this.ngStationaryFrequencies.cmdValue}${this.ngInvariantSites.cmdValue}${this.ngRateHeterogeneity.cmdValue}${this.ngAscertainmentBias.cmdValue}`; } - @computed get numSites() { return this.length; } - @computed get status() { if ( this.error ) { return `Error: ${this.error}`; @@ -157,7 +199,6 @@ class Alignment extends InputFile { return 'ok'; } - @computed get modelExtra() { switch ( this.dataType ) { case 'protein': @@ -176,124 +217,121 @@ class Alignment extends InputFile { } } - @computed get modelTestCanRun() { + get modelTestCanRun() { return this.dataType === 'nucleotide' || this.dataType === 'protein'; } - @observable modeltestLoading = false; + modeltestLoading = false; - @action - runModelTest = async () => { + runModelTest = async () => { // Show an error if there are not enough sequences and dont start the run - if ( this.numSequences < 3 ) { - this.run.parent.onError( - new UserFixError( - 'ModelTest can only be run on alignments with more than two sequences.', - ), - ); - return; - } - this.modeltestLoading = true; - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.startModelSelection( { - id: this.id, - filePath: this.path, - outputDir: this.run.outputDir, - dataType: this.dataType, - numThreads: this.run.numThreads.value, - binaryName: this.run.modeltestName, - } ); - }; - - @action - cancelModelTest = () => { - if ( this.modeltestLoading ) { - this.modeltestLoading = false; - const { rendererBridge } = /** @type {any} */ ( window ); - rendererBridge.cancelModelSelection( this.id ); - } - }; - - @action - setModelFromString = ( { raxml, extraFlag, raxmlNG } ) => { + if ( this.numSequences < 3 ) { + this.run.parent.onError( + new UserFixError( + 'ModelTest can only be run on alignments with more than two sequences.', + ), + ); + return; + } + this.modeltestLoading = true; + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.startModelSelection( { + id: this.id, + filePath: this.path, + outputDir: this.run.outputDir, + dataType: this.dataType, + numThreads: this.run.numThreads.value, + binaryName: this.run.modeltestName, + } ); + }; + + cancelModelTest = () => { + if ( this.modeltestLoading ) { this.modeltestLoading = false; - // For raxml-ng - let model = raxmlNG.split( '+' )[0]; - // Two models have different names in modeltest-ng and raxml-ng - model = model.replace( 'TrN', 'TN93' ); - model = model.replace( 'TPM1', 'K81' ); - this.substitutionModel.setValue( model ); - if ( /\+F[O|E]?/.test( raxmlNG ) ) { - this.ngStationaryFrequencies.setValue( /\+F[O|E]?/.exec( raxmlNG )[0] ); - } - if ( /\+IC?/.test( raxmlNG ) ) { - this.ngInvariantSites.setValue( /\+IC?/.exec( raxmlNG )[0] ); - } - if ( /\+GA?/.test( raxmlNG ) ) { - this.ngRateHeterogeneity.setValue( /\+GA?/.exec( raxmlNG )[0] ); - } - if ( /\+ASC_LEWIS/.test( raxmlNG ) ) { - this.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); - } - - model = raxml; - // For raxml - if ( /F$/.test( raxml ) ) { - this.run.baseFrequencies.setValue( 'F' ); - model = model.slice( 0, -1 ); - } else if ( /X$/.test( raxml ) ) { - this.run.estimatedFrequencies.setValue( true ); // for all but proteins - this.run.baseFrequencies.setValue( 'X' ); // for proteins - model = model.slice( 0, -1 ); - } else { - this.run.baseFrequencies.setValue( 'default' ); - } - - if ( this.dataType === 'protein' ) { - console.log( 'parsing matrix name...' ); - const { options } = raxmlSettings.aminoAcidSubstitutionMatrixOptions; - const re = new RegExp( `(${options.join( '|' )})$` ); - const matrixName = re.exec( model )[1]; - this.aaMatrixName = matrixName; - model = model.replace( re, '' ); - } - // I couldnt find information if ModelTest checks for ASC_ - this.run.substitutionAscertainment.setValue( 'none' ); - - // Check for invariant sites - if ( /I$/.test( model ) ) { - this.run.substitutionI.setValue( '+I (ML estimate)' ); - model = model.slice( 0, -1 ); - } else { - this.run.substitutionI.setValue( 'none' ); - } - // Check for substitution rates - if ( /GAMMA/.test( model ) ) { - this.run.substitutionRate.setValue( 'GAMMA' ); - model = model.replace( 'GAMMA', '' ); - } - if ( /CAT/.test( model ) ) { - this.run.substitutionRate.setValue( 'CAT' ); - model = model.replace( 'CAT', '' ); - } - // Checks for the different nucleotide substitution matrices - // Default is GTR - if ( extraFlag === '--JC69' ) { - this.run.substitutionMatrix.setValue( 'JC' ); - // We dont allow CAT model for this matrix - this.run.substitutionRate.setValue( 'GAMMA' ); - } - if ( extraFlag === '--K80' ) { - this.run.substitutionMatrix.setValue( 'K80' ); - // We dont allow CAT model for this matrix - this.run.substitutionRate.setValue( 'GAMMA' ); - } - if ( extraFlag === '--HKY85' ) { - this.run.substitutionMatrix.setValue( 'HKY' ); - // We dont allow CAT model for this matrix - this.run.substitutionRate.setValue( 'GAMMA' ); - } - }; + const { rendererBridge } = /** @type {any} */ ( window ); + rendererBridge.cancelModelSelection( this.id ); + } + }; + + setModelFromString = ( { raxml, extraFlag, raxmlNG } ) => { + this.modeltestLoading = false; + // For raxml-ng + let model = raxmlNG.split( '+' )[0]; + // Two models have different names in modeltest-ng and raxml-ng + model = model.replace( 'TrN', 'TN93' ); + model = model.replace( 'TPM1', 'K81' ); + this.substitutionModel.setValue( model ); + if ( /\+F[O|E]?/.test( raxmlNG ) ) { + this.ngStationaryFrequencies.setValue( /\+F[O|E]?/.exec( raxmlNG )[0] ); + } + if ( /\+IC?/.test( raxmlNG ) ) { + this.ngInvariantSites.setValue( /\+IC?/.exec( raxmlNG )[0] ); + } + if ( /\+GA?/.test( raxmlNG ) ) { + this.ngRateHeterogeneity.setValue( /\+GA?/.exec( raxmlNG )[0] ); + } + if ( /\+ASC_LEWIS/.test( raxmlNG ) ) { + this.ngAscertainmentBias.setValue( '+ASC_LEWIS' ); + } + + model = raxml; + // For raxml + if ( /F$/.test( raxml ) ) { + this.run.baseFrequencies.setValue( 'F' ); + model = model.slice( 0, -1 ); + } else if ( /X$/.test( raxml ) ) { + this.run.estimatedFrequencies.setValue( true ); // for all but proteins + this.run.baseFrequencies.setValue( 'X' ); // for proteins + model = model.slice( 0, -1 ); + } else { + this.run.baseFrequencies.setValue( 'default' ); + } + + if ( this.dataType === 'protein' ) { + console.log( 'parsing matrix name...' ); + const { options } = raxmlSettings.aminoAcidSubstitutionMatrixOptions; + const re = new RegExp( `(${options.join( '|' )})$` ); + const matrixName = re.exec( model )[1]; + this.aaMatrixName = matrixName; + model = model.replace( re, '' ); + } + // I couldnt find information if ModelTest checks for ASC_ + this.run.substitutionAscertainment.setValue( 'none' ); + + // Check for invariant sites + if ( /I$/.test( model ) ) { + this.run.substitutionI.setValue( '+I (ML estimate)' ); + model = model.slice( 0, -1 ); + } else { + this.run.substitutionI.setValue( 'none' ); + } + // Check for substitution rates + if ( /GAMMA/.test( model ) ) { + this.run.substitutionRate.setValue( 'GAMMA' ); + model = model.replace( 'GAMMA', '' ); + } + if ( /CAT/.test( model ) ) { + this.run.substitutionRate.setValue( 'CAT' ); + model = model.replace( 'CAT', '' ); + } + // Checks for the different nucleotide substitution matrices + // Default is GTR + if ( extraFlag === '--JC69' ) { + this.run.substitutionMatrix.setValue( 'JC' ); + // We dont allow CAT model for this matrix + this.run.substitutionRate.setValue( 'GAMMA' ); + } + if ( extraFlag === '--K80' ) { + this.run.substitutionMatrix.setValue( 'K80' ); + // We dont allow CAT model for this matrix + this.run.substitutionRate.setValue( 'GAMMA' ); + } + if ( extraFlag === '--HKY85' ) { + this.run.substitutionMatrix.setValue( 'HKY' ); + // We dont allow CAT model for this matrix + this.run.substitutionRate.setValue( 'GAMMA' ); + } + }; loadParsedAlignment = async () => { const { rendererBridge } = /** @type {any} */ ( window ); @@ -347,24 +385,22 @@ class Alignment extends InputFile { } }; - @action - onModelSelectionSuccess = ( { id, result } ) => { - if ( id === this.id ) { - console.log( id, 'Modeltest result:', result ); - this.setModelFromString( result ); - this.run.afterRun(); - } - }; - - @action - onModelSelectionFailure = ( { id, error } ) => { - if ( id === this.id ) { - this.modeltestLoading = false; - console.log( id, 'Modeltest error:', error ); - this.run.error = error; - this.run.afterRun(); - } - }; + onModelSelectionSuccess = ( { id, result } ) => { + if ( id === this.id ) { + console.log( id, 'Modeltest result:', result ); + this.setModelFromString( result ); + this.run.afterRun(); + } + }; + + onModelSelectionFailure = ( { id, error } ) => { + if ( id === this.id ) { + this.modeltestLoading = false; + console.log( id, 'Modeltest error:', error ); + this.run.error = error; + this.run.afterRun(); + } + }; listen = () => { this.loadParsedAlignment(); @@ -374,12 +410,11 @@ class Alignment extends InputFile { this.subscribe( runEvents.onRunStderr, this.onRunStderr ); }; - @action clearModified = () => { + clearModified = () => { this.showModifiedSnack = false; this.showModifiedDialog = false; }; - @action dispose() { this.unlisten(); if ( this.modeltestLoading ) { @@ -387,38 +422,33 @@ class Alignment extends InputFile { } } - @action - remove = () => { - this.dispose(); - this.run.removeAlignment( this ); - }; - - @action - onChangeModel = ( event ) => { - console.log( 'onChangeModel' ); - this.model = event.target.value; - }; - - @action - onChangeAAMatrixName = ( value ) => { - console.log( 'onChangeAAMatrixName' ); - this.aaMatrixName = value; - }; - - @action - onRunStdout = ( { id, content } ) => { - if ( id === this.id ) { + remove = () => { + this.dispose(); + this.run.removeAlignment( this ); + }; + + onChangeModel = ( event ) => { + console.log( 'onChangeModel' ); + this.model = event.target.value; + }; + + onChangeAAMatrixName = ( value ) => { + console.log( 'onChangeAAMatrixName' ); + this.aaMatrixName = value; + }; + + onRunStdout = ( { id, content } ) => { + if ( id === this.id ) { // TODO: Keep local log? - this.run.stdout += content; - } - }; - - @action - onRunStderr = ( { id, content } ) => { - if ( id === this.id ) { - this.run.stderr += content; - } - }; + this.run.stdout += content; + } + }; + + onRunStderr = ( { id, content } ) => { + if ( id === this.id ) { + this.run.stderr += content; + } + }; getSequenceCode = ( taxon ) => { // TODO: Sort sequences on taxon for quicker search, intersection and union diff --git a/src/app/store/AstralTree.js b/src/app/store/AstralTree.js index 1a0da00d..e1b7f400 100644 --- a/src/app/store/AstralTree.js +++ b/src/app/store/AstralTree.js @@ -5,12 +5,11 @@ import InputFile from './InputFile'; class AstralTree extends InputFile { constructor( ...args ) { super( ...args ); - makeObservable( this ); + makeObservable( this, { remove: action } ); } - @action - remove = () => { - this.run.removeAstralTree(); - }; + remove = () => { + this.run.removeAstralTree(); + }; } export default AstralTree; diff --git a/src/app/store/InputFile.js b/src/app/store/InputFile.js index a4613987..d9f93945 100644 --- a/src/app/store/InputFile.js +++ b/src/app/store/InputFile.js @@ -8,55 +8,57 @@ class InputFile extends StoreBase { constructor( run, path ) { super(); - makeObservable( this ); + makeObservable( this, { + path: observable, + id: computed, + name: computed, + dir: computed, + base: computed, + filename: computed, + ok: computed, + openFile: action, + showFileInFolder: action, + } ); this.run = run; this.path = path; } // Observable because it may change on correcting errors or reformating of alignments - @observable path = ''; + path = ''; - @computed get id() { return `${this.run.id}_${this.path}`; } - @computed get name() { return name( this.path ); } - @computed get dir() { return dir( this.path ); } - @computed get base() { return base( this.path ); } - @computed get filename() { return base( this.path ); } - @computed get ok() { return this.path !== ''; } - @action - openFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.openPath( this.path ); - }; - - @action - showFileInFolder = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.showItemInFolder( this.path ); - }; + openFile = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.openPath( this.path ); + }; + + showFileInFolder = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.showItemInFolder( this.path ); + }; } export default InputFile; From 4690fa0089b40cdcafc7a10a2eb703a131a3918e Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 00:09:40 +0100 Subject: [PATCH 48/54] Convert the app store to an annotation map (#152) The run list converts with it: a decorated subclass cannot sit under a parent that passes an annotation map, so the two convert as one unit. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/AppStore.js | 15 +++-- src/app/store/RunList.js | 115 ++++++++++++++++++++------------------ 2 files changed, 70 insertions(+), 60 deletions(-) diff --git a/src/app/store/AppStore.js b/src/app/store/AppStore.js index e9e02ed5..b5bc5aec 100644 --- a/src/app/store/AppStore.js +++ b/src/app/store/AppStore.js @@ -6,20 +6,25 @@ import Config from './Config'; class AppStore extends StoreBase { constructor() { super(); - makeObservable( this ); + makeObservable( this, { + version: observable, + showAppSnack: observable, + setAppSnack: action, + clearAppSnack: action, + } ); } citation = new Citation(); config = new Config(); - @observable version = undefined; + version = undefined; - @observable showAppSnack = false; + showAppSnack = false; - @action setAppSnack = () => { + setAppSnack = () => { this.showAppSnack = true; }; - @action clearAppSnack = () => { + clearAppSnack = () => { this.showAppSnack = false; }; } diff --git a/src/app/store/RunList.js b/src/app/store/RunList.js index 27f3fff8..a5630c9a 100644 --- a/src/app/store/RunList.js +++ b/src/app/store/RunList.js @@ -4,82 +4,87 @@ import AppStore from './AppStore'; import { runEvents } from './StoreBase'; class RunList extends AppStore { - @observable runs = []; - @observable activeIndex = 0; + runs = []; + activeIndex = 0; constructor() { super(); - makeObservable( this ); + makeObservable( this, { + runs: observable, + activeIndex: observable, + error: observable, + errorTitle: observable, + clearError: action, + activeRun: computed, + addRun: action, + deleteRun: action, + setActive: action, + deleteActive: action, + onError: action, + onUnhandledError: action, + onBackboneConstraint: action, + onMultifurcatingConstraint: action, + } ); this.addRun(); this.listen(); } - @observable error = null; - @observable errorTitle = null; - @action - clearError = () => { - this.error = null; - this.errorTitle = null; - }; + error = null; + errorTitle = null; + clearError = () => { + this.error = null; + this.errorTitle = null; + }; - @computed get activeRun() { return this.runs[this.activeIndex]; } - @action - addRun = () => { - let maxId = 0; - this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); - this.runs.push( new Run( this, maxId + 1 ) ); - this.activeIndex = this.runs.length - 1; - }; + addRun = () => { + let maxId = 0; + this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); + this.runs.push( new Run( this, maxId + 1 ) ); + this.activeIndex = this.runs.length - 1; + }; - @action - deleteRun = ( run ) => { - run.dispose(); - const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); - this.runs.splice( runIndex, 1 ); - if ( this.runs.length === 0 ) { - this.runs.push( new Run( this, 1 ) ); - } - this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); - }; + deleteRun = ( run ) => { + run.dispose(); + const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); + this.runs.splice( runIndex, 1 ); + if ( this.runs.length === 0 ) { + this.runs.push( new Run( this, 1 ) ); + } + this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); + }; - @action - setActive = ( index ) => { - this.activeIndex = index; - }; + setActive = ( index ) => { + this.activeIndex = index; + }; - @action - deleteActive = () => { - this.deleteRun( this.activeRun ); - }; + deleteActive = () => { + this.deleteRun( this.activeRun ); + }; - @action - onError = ( error ) => { - this.errorTitle = null; - this.error = error; - }; + onError = ( error ) => { + this.errorTitle = null; + this.error = error; + }; - @action - onUnhandledError = ( { title, error } ) => { - console.log( `Unhandled error:`, error ); - this.errorTitle = title; - this.error = error; - }; + onUnhandledError = ( { title, error } ) => { + console.log( `Unhandled error:`, error ); + this.errorTitle = title; + this.error = error; + }; - @action - onBackboneConstraint = ( event, params ) => { - this.activeRun.useBackboneConstraint = + onBackboneConstraint = ( event, params ) => { + this.activeRun.useBackboneConstraint = !this.activeRun.useBackboneConstraint; - }; + }; - @action - onMultifurcatingConstraint = ( event, params ) => { - this.activeRun.useMultifurcatingConstraint = + onMultifurcatingConstraint = ( event, params ) => { + this.activeRun.useMultifurcatingConstraint = !this.activeRun.useMultifurcatingConstraint; - }; + }; listen = () => { this.subscribe( runEvents.onUnhandledError, this.onUnhandledError ); From 2de4b483f28647f6bfa59f0ef732dd766811c8cf Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 07:52:27 +0100 Subject: [PATCH 49/54] Convert the run to an annotation map Replace the run's decorators with a makeObservable annotation map. Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/Run.js | 804 ++++++++++++++++++++----------------- src/app/store/StoreBase.js | 2 +- 2 files changed, 440 insertions(+), 366 deletions(-) diff --git a/src/app/store/Run.js b/src/app/store/Run.js index 2d630678..eafb9861 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -44,7 +44,118 @@ const { windows } = host; class Run extends StoreBase { constructor( parent, id ) { super(); - makeObservable( this ); + makeObservable( this, { + analysis: computed, + analysisOption: computed, + loadTreeFile: action, + loadBackboneConstraintFile: action, + loadMultifurcatingConstraintFile: action, + disableCheckUndeterminedSequence: observable, + outputName: observable, + setOutputName: action, + outputNameOk: computed, + outputNameSafe: computed, + outputNameNotice: computed, + outputFilenameSafe: computed, + outputDir: observable, + setOutputDir: action, + selectOutputDir: action, + openOutputDir: action, + showPartitionFor: observable.ref, + showPartition: action, + hidePartition: action, + resultDir: observable, + resultFilenames: computed, + haveResult: computed, + openFile: action, + haveAlignments: computed, + hasAstralTree: computed, + taxons: computed, + dataType: computed, + error: observable, + missing: computed, + running: observable, + finished: observable, + exitCode: observable, + clearFinished: action, + ok: computed, + startDisabled: computed, + randomSeed: observable, + seedParsimony: computed, + seedRapidBootstrap: computed, + seedBootstrap: computed, + setRandomSeed: action, + haveRandomSeed: computed, + usesRaxmlNg: computed, + usesModeltestNg: computed, + inputIsAlignment: computed, + inputIsTree: computed, + usesModeltest: computed, + usesRaxml: computed, + usesAstral: computed, + modelTestCanRun: computed, + modelTestIsRunningOnAlignment: computed, + cancelModeltestOnAlignment: action, + args: computed, + ngSubstitutionModelCmd: computed, + showModifiedSnack: computed, + showModifiedDialog: computed, + modificationMessages: computed, + converted: computed, + modified: computed, + convertedAlignmentFrom: computed, + clearShowModified: action, + raxmlSubstitutionModelCmd: computed, + command: computed, + settingsFileContent: computed, + settingsFilePath: computed, + writeSettings: action, + startAstral: action, + start: action, + cancel: action, + afterRun: action, + alignments: observable, + astralTree: observable, + code: observable, + data: observable, + path: observable, + stdout: observable, + stderr: observable, + useBackboneConstraint: observable, + useMultifurcatingConstraint: observable, + numSites: computed, + needAlignment: computed, + removeRun: action, + loadAlignmentFiles: action, + loadAstralTree: action, + addAlignments: action, + addAstralFiles: action, + removeAlignment: action, + removeAstralTree: action, + canLoadAlignment: computed, + canLoadAstralTree: computed, + partitionFile: observable, + partitionFileContent: observable, + partitionFileName: computed, + havePartitionFile: computed, + canLoadPartitionFile: computed, + loadPartitionFile: action, + addPartitionFiles: action, + addTreeFiles: action, + removePartitionFile: action, + clearStdout: action, + clearStderr: action, + clearConsole: action, + clearError: action, + reset: action, + onRunStdout: action, + onRunStderr: action, + onAstralSuccess: action, + onRunFinished: action, + onRunError: action, + onBackboneConstraint: action, + onMultifurcatingConstraint: action, + } ); this.parent = parent; this.id = id; this.finalAlignment = new FinalAlignment( this ); @@ -69,12 +180,10 @@ class Run extends StoreBase { return raxmlParam; }; - @computed get analysis() { return this.raxmlNgSwitch( new RaxmlNgAnalysis( this ), new Analysis( this ) ); } - @computed get analysisOption() { return this.raxmlNgSwitch( raxmlNgAnalysisOptions.find( ( opt ) => opt.value === this.analysis.value ), @@ -113,19 +222,16 @@ class Run extends StoreBase { this.addTreeFiles( chosen.type, [{ path: chosen.filePath }] ); }; - @action - loadTreeFile = () => this.chooseTree( 'tree' ); + loadTreeFile = () => this.chooseTree( 'tree' ); - @action - loadBackboneConstraintFile = () => this.chooseTree( 'backboneConstraint' ); + loadBackboneConstraintFile = () => this.chooseTree( 'backboneConstraint' ); - @action - loadMultifurcatingConstraintFile = () => this.chooseTree( 'multifurcatingConstraint' ); + loadMultifurcatingConstraintFile = () => this.chooseTree( 'multifurcatingConstraint' ); - @observable disableCheckUndeterminedSequence = true; + disableCheckUndeterminedSequence = true; - @observable outputName = 'output'; - @action setOutputName = ( value ) => { + outputName = 'output'; + setOutputName = ( value ) => { this.outputName = filenamify( value.replace( /\s+/g, '_' ).trim() ); }; @@ -158,113 +264,109 @@ class Run extends StoreBase { }, ); - @computed get outputNameOk() { + get outputNameOk() { return this.outputNameAvailable.get().ok; } - @computed get outputNameSafe() { + get outputNameSafe() { return ( this.outputNameAvailable.get().outputNameUnused || this.outputNamePlaceholder ); } - @computed get outputNameNotice() { + get outputNameNotice() { return this.outputNameOk ? '' : `Output with that id already exists. New run will use output id '${this.outputNameSafe}'`; } - @computed get outputFilenameSafe() { + get outputFilenameSafe() { return `${this.outputNameSafe}.tre`; } - @observable outputDir = ''; - @action - setOutputDir = ( dir ) => { - this.outputDir = dir; - }; - @action - selectOutputDir = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - const outputDir = await rendererBridge.selectOutputDir( this.id ); - if ( !outputDir ) { - return; - } - this.setOutputDir( outputDir ); - }; + outputDir = ''; + setOutputDir = ( dir ) => { + this.outputDir = dir; + }; + selectOutputDir = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + const outputDir = await rendererBridge.selectOutputDir( this.id ); + if ( !outputDir ) { + return; + } + this.setOutputDir( outputDir ); + }; - @action openOutputDir = async () => { + openOutputDir = async () => { const { rendererBridge } = /** @type {any} */ ( window ); await rendererBridge.openPath( this.outputDir ); }; - @observable.ref showPartitionFor = null; - @action - showPartition = ( alignment ) => { - this.showPartitionFor = alignment; - }; - @action - hidePartition = () => { - this.showPartition( null ); - }; + showPartitionFor = null; + showPartition = ( alignment ) => { + this.showPartitionFor = alignment; + }; + hidePartition = () => { + this.showPartition( null ); + }; // Result - @observable resultDir = ''; - @computed get resultFilenames() { + resultDir = ''; + get resultFilenames() { return this.outputNameAvailable.get().resultFilenames || []; } - @computed get haveResult() { + get haveResult() { return this.resultFilenames.length > 0 && this.resultDir === this.outputDir; } - @action openFile = async ( filePath ) => { + openFile = async ( filePath ) => { const { rendererBridge } = /** @type {any} */ ( window ); await rendererBridge.openPath( filePath ); }; - @computed get haveAlignments() { + get haveAlignments() { return this.alignments.length > 0; } - @computed get hasAstralTree() { + get hasAstralTree() { return !!this.astralTree; } - @computed get taxons() { + get taxons() { return this.haveAlignments ? this.alignments[0].taxons : []; } - @computed get dataType() { + get dataType() { return this.finalAlignment.dataType; } - @observable error = null; + error = null; - @computed get missing() { + get missing() { if ( !this.tree.notAvailable && !this.tree.filePath ) { return 'Missing tree, please load one.'; } return ''; } - @observable running = false; - @observable finished = false; - @observable exitCode = 0; - @action clearFinished = () => { + running = false; + finished = false; + exitCode = 0; + clearFinished = () => { this.finished = false; this.exitCode = 0; }; atomFinished; - @computed get ok() { + get ok() { return !this.error && !this.missing; } - @computed get startDisabled() { + get startDisabled() { return ( ( this.alignments.length === 0 && !this.hasAstralTree ) || !this.ok || @@ -276,25 +378,25 @@ class Run extends StoreBase { ); } - @observable randomSeed = Math.floor( 1000000 * Math.random() ); - @computed get seedParsimony() { + randomSeed = Math.floor( 1000000 * Math.random() ); + get seedParsimony() { return this.randomSeed; } - @computed get seedRapidBootstrap() { + get seedRapidBootstrap() { return this.randomSeed; } - @computed get seedBootstrap() { + get seedBootstrap() { return this.randomSeed; } - @action setRandomSeed = ( value ) => { + setRandomSeed = ( value ) => { const v = Number( value ); if ( !Number.isNaN( v ) && v !== 0 && v < 1e6 ) { this.randomSeed = v; } }; - @computed get haveRandomSeed() { + get haveRandomSeed() { const analysisWithSeed = [ 'FT', 'ML', @@ -310,50 +412,50 @@ class Run extends StoreBase { return analysisWithSeed.includes( this.analysis.value ); } - @computed get usesRaxmlNg() { + get usesRaxmlNg() { return this.binary.value.includes( 'raxml-ng' ); } - @computed get usesModeltestNg() { + get usesModeltestNg() { return this.binary.value.includes( 'modeltest-ng' ); } - @computed get inputIsAlignment() { + get inputIsAlignment() { return this.usesModeltest || this.usesRaxml; } - @computed get inputIsTree() { + get inputIsTree() { return this.usesAstral; } - @computed get usesModeltest() { + get usesModeltest() { return this.binary.type === 'modeltest'; } - @computed get usesRaxml() { + get usesRaxml() { return this.binary.type === 'raxml'; } - @computed get usesAstral() { + get usesAstral() { return this.binary.type === 'astral'; } - @computed get modelTestCanRun() { + get modelTestCanRun() { return this.dataType === 'nucleotide' || this.dataType === 'protein'; } - @computed get modelTestIsRunningOnAlignment() { + get modelTestIsRunningOnAlignment() { const running = this.alignments.some( ( alignment ) => alignment.modeltestLoading, ); return running; } - @action cancelModeltestOnAlignment = () => { + cancelModeltestOnAlignment = () => { this.alignments.forEach( ( alignment ) => alignment.cancelModelTest() ); }; - @computed get args() { + get args() { if ( this.usesAstral ) { return this.astralArgs(); } @@ -366,27 +468,27 @@ class Run extends StoreBase { return this.raxmlArgs(); } - @computed get ngSubstitutionModelCmd() { + get ngSubstitutionModelCmd() { return this.haveAlignments ? this.alignments[0].ngSubstitutionModelCmd : ''; } - @computed get showModifiedSnack() { + get showModifiedSnack() { const shouldShow = this.alignments .map( ( a ) => a.showModifiedSnack ) .some( ( e ) => e ); return this.haveAlignments && shouldShow; } - @computed get showModifiedDialog() { + get showModifiedDialog() { const shouldShow = this.alignments .map( ( a ) => a.showModifiedDialog ) .some( ( e ) => e ); return this.haveAlignments && shouldShow; } - @computed get modificationMessages() { + get modificationMessages() { const messages = []; this.alignments.forEach( ( a ) => { messages.push( `${a.name}:\n` ); @@ -397,17 +499,17 @@ class Run extends StoreBase { return messages; } - @computed get converted() { + get converted() { const converted = this.alignments.map( ( a ) => a.converted ).some( ( e ) => e ); return this.haveAlignments && converted; } - @computed get modified() { + get modified() { const modified = this.alignments.map( ( a ) => a.modified ).some( ( e ) => e ); return this.haveAlignments && modified; } - @computed get convertedAlignmentFrom() { + get convertedAlignmentFrom() { if ( !this.haveAlignments ) { return null; } @@ -415,13 +517,13 @@ class Run extends StoreBase { return convertedAlignments[0].convertedFrom; } - @action clearShowModified = () => { + clearShowModified = () => { for ( let i = 0; i < this.alignments.length; i++ ) { this.alignments[i].clearModified(); } }; - @computed get raxmlSubstitutionModelCmd() { + get raxmlSubstitutionModelCmd() { let model = this.substitutionAscertainment.cmdValue + this.substitutionMatrix.cmdValue + @@ -1169,7 +1271,7 @@ class Run extends StoreBase { return cmdArgs.filter( ( args ) => args.length > 0 ); }; - @computed get command() { + get command() { if ( this.usesAstral ) { return this.args .map( ( cmdArgs ) => `java -jar ${this.binary.value} ${cmdArgs.join( ' ' )}` ) @@ -1180,7 +1282,7 @@ class Run extends StoreBase { .join( ' &&\\\n' ); } - @computed get settingsFileContent() { + get settingsFileContent() { let text = `The analysis was run using raxmlGUI 2.0 (version ${this.version}) as follows: Analysis: ${this.analysisOption.title} Binary: ${this.binary.value} version ${this.binary.version} @@ -1198,241 +1300,227 @@ Results saved to: ${this.outputDir} return text; } - @computed get settingsFilePath() { + get settingsFilePath() { return join( `${this.outputDir}`, `RAxML_GUI_Settings_${this.outputNameSafe}.txt`, ); } - @action - writeSettings = async () => { - try { - console.log( `Writing settings to ${this.settingsFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.writeFile( this.settingsFilePath, this.settingsFileContent ); - } catch ( err ) { - console.error( 'Error writing settings:', err ); - throw err; - } - }; - - @action - startAstral = async () => { - const { id, binary, args } = this; - console.log( `Start astral run ${id}` ); - this.running = true; + writeSettings = async () => { + try { + console.log( `Writing settings to ${this.settingsFilePath}...` ); const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.startAstral( { - id, - binaryName: binary.value, - args, - } ); - }; + await rendererBridge.writeFile( this.settingsFilePath, this.settingsFileContent ); + } catch ( err ) { + console.error( 'Error writing settings:', err ); + throw err; + } + }; - @action - start = async () => { - const { - id, - args, - binary, - outputDir, - outputFilenameSafe: outputFilename, - outputNameSafe: outputName, - combinedOutput, - usesRaxmlNg, - usesModeltestNg, - finalAlignment, - } = this; - - // If binary is astral use start in seperate function - if ( this.usesAstral ) { - return this.startAstral(); - } + startAstral = async () => { + const { id, binary, args } = this; + console.log( `Start astral run ${id}` ); + this.running = true; + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.startAstral( { + id, + binaryName: binary.value, + args, + } ); + }; - // Less than 4 sequences and RAxML would error out - if ( this.finalAlignment.numSequences <= 3 ) { - this.parent.onError( - new UserFixError( - 'To start a run with RAxML the final alignment needs to have at least four sequences.', - ), - ); - return; - } + start = async () => { + const { + id, + args, + binary, + outputDir, + outputFilenameSafe: outputFilename, + outputNameSafe: outputName, + combinedOutput, + usesRaxmlNg, + usesModeltestNg, + finalAlignment, + } = this; + + // If binary is astral use start in seperate function + if ( this.usesAstral ) { + return this.startAstral(); + } - this.running = true; - const startToken = {}; - this.startToken = startToken; - if ( this.outputName !== this.outputNameSafe ) { - this.outputName = this.outputNameSafe; - } + // Less than 4 sequences and RAxML would error out + if ( this.finalAlignment.numSequences <= 3 ) { + this.parent.onError( + new UserFixError( + 'To start a run with RAxML the final alignment needs to have at least four sequences.', + ), + ); + return; + } - if ( this.finalAlignment.numAlignments > 1 ) { - await this.finalAlignment.writeConcatenatedAlignmentAndPartition(); - } else if ( !this.finalAlignment.partition.isDefault ) { - await this.finalAlignment.writePartition(); - } - await this.writeSettings(); - if ( this.startToken !== startToken ) { - return; - } - console.log( `Start run ${id} with args ${args}` ); - const { rendererBridge } = /** @type {any} */ ( window ); - await rendererBridge.startRun( { - id, - args, - binaryName: binary.value, - outputDir, - outputFilename, - outputName, - combinedOutput: combinedOutput.isUsed, - usesRaxmlNg, - usesModeltestNg, - inputPath: finalAlignment.path, - } ); - }; + this.running = true; + const startToken = {}; + this.startToken = startToken; + if ( this.outputName !== this.outputNameSafe ) { + this.outputName = this.outputNameSafe; + } - @action - cancel = () => { - this.startToken = null; - const { rendererBridge } = /** @type {any} */ ( window ); - rendererBridge.cancelRun( this.id ); - this.afterRun(); - }; + if ( this.finalAlignment.numAlignments > 1 ) { + await this.finalAlignment.writeConcatenatedAlignmentAndPartition(); + } else if ( !this.finalAlignment.partition.isDefault ) { + await this.finalAlignment.writePartition(); + } + await this.writeSettings(); + if ( this.startToken !== startToken ) { + return; + } + console.log( `Start run ${id} with args ${args}` ); + const { rendererBridge } = /** @type {any} */ ( window ); + await rendererBridge.startRun( { + id, + args, + binaryName: binary.value, + outputDir, + outputFilename, + outputName, + combinedOutput: combinedOutput.isUsed, + usesRaxmlNg, + usesModeltestNg, + inputPath: finalAlignment.path, + } ); + }; - @action - afterRun = () => { - this.running = false; - this.atomAfterRun.reportChanged(); - }; + cancel = () => { + this.startToken = null; + const { rendererBridge } = /** @type {any} */ ( window ); + rendererBridge.cancelRun( this.id ); + this.afterRun(); + }; + + afterRun = () => { + this.running = false; + this.atomAfterRun.reportChanged(); + }; - @observable alignments = []; - @observable astralTree = undefined; - @observable code = undefined; - @observable data = ''; - @observable path = undefined; - @observable stdout = ''; - @observable stderr = ''; + alignments = []; + astralTree = undefined; + code = undefined; + data = ''; + path = undefined; + stdout = ''; + stderr = ''; - @observable useBackboneConstraint = false; - @observable useMultifurcatingConstraint = false; + useBackboneConstraint = false; + useMultifurcatingConstraint = false; - @computed get numSites() { return this.alignments.reduce( ( sum, n ) => sum + n, 0 ); } - @computed get needAlignment() { return true; } - @action - removeRun = () => { - this.parent.deleteRun( this ); - }; + removeRun = () => { + this.parent.deleteRun( this ); + }; - @action - loadAlignmentFiles = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - const alignments = await rendererBridge.selectAlignment( this.id ); - if ( !alignments ) { - return; - } - this.addAlignments( alignments ); - }; + loadAlignmentFiles = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + const alignments = await rendererBridge.selectAlignment( this.id ); + if ( !alignments ) { + return; + } + this.addAlignments( alignments ); + }; - @action - loadAstralTree = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); - const file = await rendererBridge.selectAstralFile( this.id ); - if ( !file ) { - return; - } - this.addAstralFiles( file ); - }; + loadAstralTree = async () => { + const { rendererBridge } = /** @type {any} */ ( window ); + const file = await rendererBridge.selectAstralFile( this.id ); + if ( !file ) { + return; + } + this.addAstralFiles( file ); + }; haveAlignment = ( id ) => { // TODO: Input.js queries without id, doe it work as expected? Later queries with path instead of id return this.alignments.findIndex( ( alignment ) => alignment.id === id ) >= 0; }; - @action - addAlignments = ( alignments ) => { - alignments.forEach( ( { path } ) => { - if ( !this.haveAlignment( path ) ) { - this.alignments.push( new Alignment( this, path ) ); - if ( this.alignments.length === 1 ) { - this.setOutputName( this.alignments[0].name ); - if ( !this.outputDir ) { - this.setOutputDir( this.alignments[0].dir ); - } + addAlignments = ( alignments ) => { + alignments.forEach( ( { path } ) => { + if ( !this.haveAlignment( path ) ) { + this.alignments.push( new Alignment( this, path ) ); + if ( this.alignments.length === 1 ) { + this.setOutputName( this.alignments[0].name ); + if ( !this.outputDir ) { + this.setOutputDir( this.alignments[0].dir ); } } - } ); - }; - - @action - addAstralFiles = ( { path } ) => { - if ( !this.hasAstralTree ) { - this.astralTree = new AstralTree( this, path ); - this.setOutputName( this.astralTree.name ); - if ( !this.outputDir ) { - this.setOutputDir( this.astralTree.dir ); - } } - }; + } ); + }; - @action - removeAlignment = ( alignment ) => { - const oldDataType = this.dataType; - const index = this.alignments.indexOf( alignment ); - if ( index >= 0 ) { - this.alignments.splice( index, 1 ); + addAstralFiles = ( { path } ) => { + if ( !this.hasAstralTree ) { + this.astralTree = new AstralTree( this, path ); + this.setOutputName( this.astralTree.name ); + if ( !this.outputDir ) { + this.setOutputDir( this.astralTree.dir ); } - if ( this.haveAlignments ) { + } + }; + + removeAlignment = ( alignment ) => { + const oldDataType = this.dataType; + const index = this.alignments.indexOf( alignment ); + if ( index >= 0 ) { + this.alignments.splice( index, 1 ); + } + if ( this.haveAlignments ) { // this.dataType is computed automatically with the reduced set, reset to default if changed (from mixed or multistate) - if ( this.dataType !== oldDataType ) { + if ( this.dataType !== oldDataType ) { // This parameter is deleted, but there seems to be no need for updating other params // this.substitutionModel.value = raxmlModelOptions[this.dataType].default; - } - } else { - this.reset(); } - }; + } else { + this.reset(); + } + }; - @action - removeAstralTree = () => { - this.astralTree = null; - }; + removeAstralTree = () => { + this.astralTree = null; + }; - @computed get canLoadAlignment() { + get canLoadAlignment() { return ( ( this.binary.type === 'raxml' || this.binary.type === 'modeltest' ) && !this.havePartitionFile ); } - @computed get canLoadAstralTree() { + get canLoadAstralTree() { return this.usesAstral && !this.hasAstralTree; } - @observable partitionFile = ''; - @observable partitionFileContent = ''; + partitionFile = ''; + partitionFileContent = ''; - @computed get partitionFileName() { + get partitionFileName() { return basename( this.partitionFile ); } - @computed get havePartitionFile() { + get havePartitionFile() { return this.partitionFile !== ''; } - @computed get canLoadPartitionFile() { + get canLoadPartitionFile() { return this.alignments.length === 1 && !this.havePartitionFile; } - @action loadPartitionFile = async () => { + loadPartitionFile = async () => { const { rendererBridge } = /** @type {any} */ ( window ); const filePath = await rendererBridge.selectPartitionFile( this.id ); if ( !filePath ) { @@ -1441,72 +1529,65 @@ Results saved to: ${this.outputDir} await this.addPartitionFiles( [{ path: filePath }] ); }; - @action - addPartitionFiles = async ( files ) => { - if ( !files.length ) { - return; - } - const { path } = files[0]; - const { rendererBridge } = /** @type {any} */ ( window ); - const content = await rendererBridge.readFile( path ); - runInAction( () => { - this.partitionFile = path; - this.partitionFileContent = content; - } ); - }; + addPartitionFiles = async ( files ) => { + if ( !files.length ) { + return; + } + const { path } = files[0]; + const { rendererBridge } = /** @type {any} */ ( window ); + const content = await rendererBridge.readFile( path ); + runInAction( () => { + this.partitionFile = path; + this.partitionFileContent = content; + } ); + }; - @action - addTreeFiles = ( type, files ) => { - if ( !files.length ) { - return; - } - const { path } = files[0]; - switch ( type ) { - case 'tree': - this.tree.setFilePath( path ); - break; - case 'backboneConstraint': - this.backboneConstraint.setFilePath( path ); - break; - case 'multifurcatingConstraint': - this.multifurcatingConstraint.setFilePath( path ); - break; - default: - break; - } - }; + addTreeFiles = ( type, files ) => { + if ( !files.length ) { + return; + } + const { path } = files[0]; + switch ( type ) { + case 'tree': + this.tree.setFilePath( path ); + break; + case 'backboneConstraint': + this.backboneConstraint.setFilePath( path ); + break; + case 'multifurcatingConstraint': + this.multifurcatingConstraint.setFilePath( path ); + break; + default: + break; + } + }; - @action removePartitionFile = () => { + removePartitionFile = () => { this.partitionFile = ''; this.partitionFileContent = ''; }; - @action - clearStdout = () => { - this.stdout = ''; - }; + clearStdout = () => { + this.stdout = ''; + }; - @action - clearStderr = () => { - this.stderr = ''; - }; + clearStderr = () => { + this.stderr = ''; + }; - @action - clearConsole = () => { - this.clearStdout(); - this.clearStderr(); - }; + clearConsole = () => { + this.clearStdout(); + this.clearStderr(); + }; - @action - clearError = () => { - this.error = null; - }; + clearError = () => { + this.error = null; + }; - @action - reset = () => { - this.outGroup.reset(); - this.removePartitionFile(); - }; + reset = () => { + this.outGroup.reset(); + this.removePartitionFile(); + }; dispose = () => { this.cancel(); @@ -1525,64 +1606,57 @@ Results saved to: ${this.outputDir} // Listeners // ----------------------------------------------------------- - @action - onRunStdout = ( { id, content } ) => { - if ( id === this.id ) { - this.stdout += content; - } - }; + onRunStdout = ( { id, content } ) => { + if ( id === this.id ) { + this.stdout += content; + } + }; - @action - onRunStderr = ( { id, content } ) => { - if ( id === this.id ) { - this.stderr += content; - } - }; + onRunStderr = ( { id, content } ) => { + if ( id === this.id ) { + this.stderr += content; + } + }; - @action - onAstralSuccess = ( { id, exitCode } ) => { - if ( id === this.id ) { - console.log( `Process ${id} finished with exitCode '${exitCode}'` ); - this.resultDir = this.outputDir; - this.atomFinished.reportChanged(); - this.finished = true; - this.exitCode = exitCode; - this.afterRun(); - } - }; + onAstralSuccess = ( { id, exitCode } ) => { + if ( id === this.id ) { + console.log( `Process ${id} finished with exitCode '${exitCode}'` ); + this.resultDir = this.outputDir; + this.atomFinished.reportChanged(); + this.finished = true; + this.exitCode = exitCode; + this.afterRun(); + } + }; - @action - onRunFinished = ( { id, resultDir, resultFilenames, exitCode } ) => { - if ( id === this.id ) { - console.log( - `Process ${id} finished with exitCode '${exitCode}' and result filenames ${resultFilenames} in dir ${resultDir}.`, - ); - this.resultDir = resultDir; - this.atomFinished.reportChanged(); - this.finished = true; - this.exitCode = exitCode; - this.afterRun(); - } - }; + onRunFinished = ( { id, resultDir, resultFilenames, exitCode } ) => { + if ( id === this.id ) { + console.log( + `Process ${id} finished with exitCode '${exitCode}' and result filenames ${resultFilenames} in dir ${resultDir}.`, + ); + this.resultDir = resultDir; + this.atomFinished.reportChanged(); + this.finished = true; + this.exitCode = exitCode; + this.afterRun(); + } + }; - @action - onRunError = ( { id, error } ) => { - if ( id === this.id ) { - console.log( `Process ${id} finished with error:`, error ); - this.error = error; - this.afterRun(); - } - }; + onRunError = ( { id, error } ) => { + if ( id === this.id ) { + console.log( `Process ${id} finished with error:`, error ); + this.error = error; + this.afterRun(); + } + }; - @action - onBackboneConstraint = ( event, params ) => { - this.useBackboneConstraint = !this.useBackboneConstraint; - }; + onBackboneConstraint = ( event, params ) => { + this.useBackboneConstraint = !this.useBackboneConstraint; + }; - @action - onMultifurcatingConstraint = ( event, params ) => { - this.useMultifurcatingConstraint = !this.useMultifurcatingConstraint; - }; + onMultifurcatingConstraint = ( event, params ) => { + this.useMultifurcatingConstraint = !this.useMultifurcatingConstraint; + }; generateReport = ( { maxStdoutLength = 1000 } = {} ) => { const { command, stdout } = this; diff --git a/src/app/store/StoreBase.js b/src/app/store/StoreBase.js index 86a80780..8efd2ac6 100644 --- a/src/app/store/StoreBase.js +++ b/src/app/store/StoreBase.js @@ -35,7 +35,7 @@ export default class StoreBase { } }; - // A method: a field here would clash with a subclass's decorated dispose. + // A method: a field here would clash with a subclass's dispose field. dispose() { this.unlisten(); } From f9077772373a1ca75ee1323412f4e43af43ce715 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 08:19:32 +0100 Subject: [PATCH 50/54] Bump to MobX 7 and mobx-react-lite 5 (#157) observable.ref becomes observableRef. mobx-utils 6.1.1 works on MobX 7 despite its ^6 peer range; no new action warnings. Co-Authored-By: Claude Sonnet 5.5 --- package.json | 4 ++-- src/app/store/Run.js | 4 ++-- yarn.lock | 23 ++++++++--------------- 3 files changed, 12 insertions(+), 19 deletions(-) diff --git a/package.json b/package.json index 3e5f78dd..bf0f76a0 100644 --- a/package.json +++ b/package.json @@ -69,8 +69,8 @@ "electron-updater": "^5.2.4", "filenamify": "^4.3.0", "lodash": "^4.18.1", - "mobx": "^6.16.0", - "mobx-react-lite": "^4.1.0", + "mobx": "^7.1.7", + "mobx-react-lite": "^5.1.3", "mobx-utils": "^6.1.0", "parse-filepath": "^1.0.2", "patch-package": "^8.0.1", diff --git a/src/app/store/Run.js b/src/app/store/Run.js index eafb9861..35e8ae68 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.js @@ -1,4 +1,4 @@ -import { observable, computed, action, runInAction, createAtom, makeObservable } from 'mobx'; +import { observable, observableRef, computed, action, runInAction, createAtom, makeObservable } from 'mobx'; import { promisedComputed } from '../promisedComputed'; import filenamify from 'filenamify'; @@ -61,7 +61,7 @@ class Run extends StoreBase { setOutputDir: action, selectOutputDir: action, openOutputDir: action, - showPartitionFor: observable.ref, + showPartitionFor: observableRef, showPartition: action, hidePartition: action, resultDir: observable, diff --git a/yarn.lock b/yarn.lock index cf3d3019..d77ea15e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7935,22 +7935,20 @@ mkdirp@^1.0.3: resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -mobx-react-lite@^4.1.0: - version "4.1.1" - resolved "https://registry.yarnpkg.com/mobx-react-lite/-/mobx-react-lite-4.1.1.tgz#725d74b025235f73dc2ab815766ffe010be2cf8a" - integrity sha512-iUxiMpsvNraCKXU+yPotsOncNNmyeS2B5DKL+TL6Tar/xm+wwNJAubJmtRSeAoYawdZqwv8Z/+5nPRHeQxTiXg== - dependencies: - use-sync-external-store "^1.4.0" +mobx-react-lite@^5.1.3: + version "5.1.3" + resolved "https://registry.yarnpkg.com/mobx-react-lite/-/mobx-react-lite-5.1.3.tgz#8ef099ee04332bef4c5b616626bb782341fcb1a6" + integrity sha512-/Qh+wwtyNp9zXXns+B2MxVHC/npHsYvnVJNe0ddvHW4rgAxTOgVr0z/6hWSm2mqdT0jv1QWYZuJ6+3dediv+wQ== mobx-utils@^6.1.0: version "6.1.1" resolved "https://registry.yarnpkg.com/mobx-utils/-/mobx-utils-6.1.1.tgz#61c66563e7646fb75462c189f4110a76d2e35768" integrity sha512-ZR4tOKucWAHOdMjqElRl2BEvrzK7duuDdKmsbEbt2kzgVpuLuoYLiDCjc3QwWQl8CmOlxPgaZQpZ7emwNqPkIg== -mobx@^6.16.0: - version "6.16.1" - resolved "https://registry.yarnpkg.com/mobx/-/mobx-6.16.1.tgz#8b3166186d1298b1848395e10e64b5c43d6dc43b" - integrity sha512-syNcDdX3KT+Jq3je6eGjBhuc24Z68td2VG0zNFqRswaE433D9SNH5VRy/xrGbJsUixfppLLccXhAW9JSf6n+SQ== +mobx@^7.1.7: + version "7.1.7" + resolved "https://registry.yarnpkg.com/mobx/-/mobx-7.1.7.tgz#12281ff4c4329c0e31bf9ad846b602090bd56c0c" + integrity sha512-fzFPm0u0xHxrAyjFsjfA/a99JgyvLh8R/bnTe7uD37cwbO5O7OUrv/e6Q4rlYdBGCf3rR/pVvh1OVMPF10ghng== ms@2.0.0: version "2.0.0" @@ -10048,11 +10046,6 @@ url-to-options@^1.0.1: resolved "https://registry.yarnpkg.com/url-to-options/-/url-to-options-1.0.1.tgz#1505a03a289a48cbd7a434efbaeec5055f5633a9" integrity sha512-0kQLIzG4fdk/G5NONku64rSH/x32NOA39LVQqlK8Le6lvTF6GGRJpqaQFGgU+CLwySIqBSMdwYM0sYcW9f6P4A== -use-sync-external-store@^1.4.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz#6dcb66ef569e02f186af6b3d575f414ce746e18f" - integrity sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A== - usehooks-ts@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/usehooks-ts/-/usehooks-ts-3.1.1.tgz#0bb7f38f36f8219ee4509cc5e944ae610fb97656" From 7a4cfc959a2f9ce909202c1a19aaa5de6d0747ae Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 08:20:03 +0100 Subject: [PATCH 51/54] Remove the stale decorator note from the file menu The menu already updates the page through the renderer bridge; the note described a workaround that no longer exists. Co-Authored-By: Claude Sonnet 5.5 --- src/main/menu/subMenuFile.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/menu/subMenuFile.ts b/src/main/menu/subMenuFile.ts index eb151602..324f2efc 100644 --- a/src/main/menu/subMenuFile.ts +++ b/src/main/menu/subMenuFile.ts @@ -3,7 +3,6 @@ import * as ipc from '../../constants/ipc'; import { appStore } from '../appStore'; import { activeWindow } from '../utils/utils'; -// The page's store class is decorated. This build does not compile decorators. const sendToFocusedWindow = ( channel: string ): void => { const win = activeWindow(); if ( !win ) { From a5d5d44c6cafacc3f0383d2169c4da56d469ced1 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 08:44:10 +0100 Subject: [PATCH 52/54] Remove the decorator plugin and the TypeScript decorator flag Co-Authored-By: Claude Sonnet 5.5 --- .babelrc | 15 --------------- electron.vite.config.js | 5 ++--- jest/babelTransform.js | 3 +-- package.json | 1 - tsconfig.json | 1 - yarn.lock | 16 ---------------- 6 files changed, 3 insertions(+), 38 deletions(-) delete mode 100644 .babelrc diff --git a/.babelrc b/.babelrc deleted file mode 100644 index a981a7ab..00000000 --- a/.babelrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "presets": [ - [ - "@babel/preset-env", { - "targets": { - "node": "current" - } - } - ] - ], - "plugins": [ - ["@babel/plugin-proposal-decorators", { "legacy": true }], - ["@babel/plugin-proposal-class-properties", { "loose": false }] - ] -} diff --git a/electron.vite.config.js b/electron.vite.config.js index 631c5fb4..29a493ec 100644 --- a/electron.vite.config.js +++ b/electron.vite.config.js @@ -47,12 +47,11 @@ export default defineConfig( ( { command } ) => ( { }, }, plugins: [ - // plugin-react 5: its babel option compiles legacy MobX decorators. 6 dropped babel. - // JSX in .js is compiled here too: Vite's oxc parser does not treat .js as JSX. + // plugin-react 5: its babel option compiles JSX in .js files. 6 dropped babel. + // Vite's oxc parser does not treat .js as JSX. react( { babel: { plugins: [ - ['@babel/plugin-proposal-decorators', { legacy: true }], ['@babel/plugin-proposal-class-properties', { loose: false }], ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }], ], diff --git a/jest/babelTransform.js b/jest/babelTransform.js index 7e13f168..0802f01f 100644 --- a/jest/babelTransform.js +++ b/jest/babelTransform.js @@ -1,6 +1,6 @@ const babelJest = require( 'babel-jest' ); -// Decorator plugins match the page build. preset-env and preset-typescript +// Plugins match the page build. preset-env and preset-typescript // are what Jest needs to load the page's ESM and .tsx imports. module.exports = babelJest.default.createTransformer( { babelrc: false, @@ -10,7 +10,6 @@ module.exports = babelJest.default.createTransformer( { '@babel/preset-typescript', ], plugins: [ - [ '@babel/plugin-proposal-decorators', { legacy: true } ], [ '@babel/plugin-proposal-class-properties', { loose: false } ], [ '@babel/plugin-transform-react-jsx', { runtime: 'automatic' } ], ], diff --git a/package.json b/package.json index bf0f76a0..a7b33ca4 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,6 @@ "lint:fix": "eslint \"src/**/*.{js,jsx,ts,tsx}\" electron.vite.config.js jest.config.js \"jest/**/*.js\" --fix" }, "dependencies": { - "@babel/plugin-proposal-decorators": "^7.29.7", "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@mui/icons-material": "^7.3.11", diff --git a/tsconfig.json b/tsconfig.json index 534a7d41..0f13d91b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,7 +8,6 @@ "lib": ["ESNext", "DOM"], "module": "ESNext", "moduleResolution": "bundler", - "experimentalDecorators": true, "useDefineForClassFields": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, diff --git a/yarn.lock b/yarn.lock index d77ea15e..108174ca 100644 --- a/yarn.lock +++ b/yarn.lock @@ -684,15 +684,6 @@ "@babel/helper-plugin-utils" "^7.24.7" "@babel/plugin-syntax-decorators" "^7.24.7" -"@babel/plugin-proposal-decorators@^7.29.7": - version "7.29.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-decorators/-/plugin-proposal-decorators-7.29.7.tgz#ebc57bd4d711df920a553de8a456a3a020ce0d72" - integrity sha512-EtU0Hi3GvrTqD56xKmZvV/uCXK2ZbwVNPNLAquVItcAZpUhkXwWlo3Fmj0c2LxgSf2I8IDULeAepwNP1OefLXg== - dependencies: - "@babel/helper-create-class-features-plugin" "^7.29.7" - "@babel/helper-plugin-utils" "^7.29.7" - "@babel/plugin-syntax-decorators" "^7.29.7" - "@babel/plugin-proposal-nullish-coalescing-operator@^7.16.0": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.18.6.tgz#fdd940a99a740e577d6c753ab6fbb43fdb9467e1" @@ -771,13 +762,6 @@ dependencies: "@babel/helper-plugin-utils" "^7.24.7" -"@babel/plugin-syntax-decorators@^7.29.7": - version "7.29.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-decorators/-/plugin-syntax-decorators-7.29.7.tgz#9a23ab91fb8e61d142684108bca6f343ceee88f6" - integrity sha512-9MTTLbF39X6sqM92JPEsoI7++26hjZvzkxKZy64aMhWLH2mPkJ/Q3AV4QLmls3R14FpSpkOwQQfUh962JGQxxg== - dependencies: - "@babel/helper-plugin-utils" "^7.29.7" - "@babel/plugin-syntax-dynamic-import@^7.8.3": version "7.8.3" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz#62bf98b2da3cd21d626154fc96ee5b3cb68eacb3" From 3cbac76a64ab20bbcec6c7760bdb032ec0f56df5 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 09:28:01 +0100 Subject: [PATCH 53/54] Delete the parity test and its baseline Closes #160 Co-Authored-By: Claude Sonnet 5.5 --- src/app/store/annotationParity.baseline.txt | 315 -------------------- src/app/store/annotationParity.test.js | 59 ---- 2 files changed, 374 deletions(-) delete mode 100644 src/app/store/annotationParity.baseline.txt delete mode 100644 src/app/store/annotationParity.test.js diff --git a/src/app/store/annotationParity.baseline.txt b/src/app/store/annotationParity.baseline.txt deleted file mode 100644 index 9244c88f..00000000 --- a/src/app/store/annotationParity.baseline.txt +++ /dev/null @@ -1,315 +0,0 @@ -AAMatrixName.notAvailable -Alignment.aaMatrixName -Alignment.cancelModelTest -Alignment.checkRunComplete -Alignment.checkRunData -Alignment.checkRunSuccess -Alignment.clearModified -Alignment.converted -Alignment.convertedFrom -Alignment.dataType -Alignment.dispose -Alignment.error -Alignment.fileFormat -Alignment.hasInvariantSites -Alignment.hidePartition -Alignment.length -Alignment.loading -Alignment.modelExtra -Alignment.modelTestCanRun -Alignment.modeltestLoading -Alignment.modificationMessages -Alignment.modified -Alignment.ngSubstitutionModelCmd -Alignment.numSequences -Alignment.numSites -Alignment.onChangeAAMatrixName -Alignment.onChangeModel -Alignment.onModelSelectionFailure -Alignment.onModelSelectionSuccess -Alignment.onRunStderr -Alignment.onRunStdout -Alignment.parsingComplete -Alignment.partitionFileContent -Alignment.partitionText -Alignment.partitionType -Alignment.remove -Alignment.runModelTest -Alignment.sequences -Alignment.setModelFromString -Alignment.setPartitionText -Alignment.setShowPartition -Alignment.showModifiedDialog -Alignment.showModifiedSnack -Alignment.showPartition -Alignment.size -Alignment.status -Alignment.taxons -Alignment.typecheckingComplete -AppStore.clearAppSnack -AppStore.setAppSnack -AppStore.showAppSnack -AppStore.version -AstralTree.remove -BackboneConstraintTree.canConstraint -BackboneConstraintTree.isSet -BackboneConstraintTree.notAvailable -BaseFrequencies.notAvailable -Binary.type -Binary.version -BranchLength.notAvailable -Citation.allText -Citation.format -Citation.hide -Citation.setFormat -Citation.show -Citation.visible -CombinedOutput.isUsed -CombinedOutput.notAvailable -Config.isDarkMode -Config.setDarkMode -EstimatedFrequencies.notAvailable -FinalAlignment.dataType -FinalAlignment.dir -FinalAlignment.filename -FinalAlignment.fillTaxonGapsWithEmptySeqeunces -FinalAlignment.hasInvariantSites -FinalAlignment.length -FinalAlignment.modelFlagName -FinalAlignment.numAlignments -FinalAlignment.numSequences -FinalAlignment.openFile -FinalAlignment.openFolder -FinalAlignment.openPartition -FinalAlignment.parsingComplete -FinalAlignment.partitionFileContent -FinalAlignment.partitionFilePath -FinalAlignment.path -FinalAlignment.setFillTaxonGapsWithEmptySeqeunces -FinalAlignment.showFileInFolder -FinalAlignment.taxons -FinalAlignment.writeConcatenatedAlignment -FinalAlignment.writeConcatenatedAlignmentAndPartition -FinalAlignment.writePartition -FinalPartition.isComplete -FinalPartition.isDefault -FinalPartition.text -InputFile.base -InputFile.dir -InputFile.filename -InputFile.id -InputFile.name -InputFile.ok -InputFile.openFile -InputFile.path -InputFile.showFileInFolder -MultifurcatingConstraintTree.canConstraint -MultifurcatingConstraintTree.isSet -MultifurcatingConstraintTree.notAvailable -MultistateModel.notAvailable -MultistateNumber.error -MultistateNumber.notAvailable -NumRepetitions.notAvailable -NumRepetitionsNg.notAvailable -NumRuns.notAvailable -NumThreads.notAvailable -Option.error -Option.errorMessage -Option.haveError -Option.isDefault -Option.reset -Option.setValue -Option.value -OutGroup.cmdValue -OutGroup.notAvailable -OutGroup.options -OutGroup.setValue -Part.text -Part.typePadded -Part.values -PartAAType.notAvailable -PartBase.alignment -PartCodon.notAvailable -PartEnd.max -PartEnd.min -PartEnd.notAvailable -PartName.notAvailable -PartStart.notAvailable -PartType.finalValue -PartType.notAvailable -PartType.options -Partition.addPart -Partition.addPartDisabled -Partition.currentEndValue -Partition.errorMessage -Partition.haveError -Partition.isComplete -Partition.isDefault -Partition.isMixed -Partition.maxEndValue -Partition.nonDefaultPartitionComplete -Partition.parts -Partition.progress -Partition.reset -Partition.text -RaxmlNgAlignmentSubstitutionModel.cmdValue -RaxmlNgAlignmentSubstitutionModel.notAvailable -RaxmlNgAlignmentSubstitutionModel.options -RaxmlNgModelASC.notAvailable -RaxmlNgModelExtraParam.cmdValue -RaxmlNgModelExtraParam.notAvailable -RaxmlNgModelExtraParam.options -Run.addAlignments -Run.addAstralFiles -Run.addPartitionFiles -Run.addTreeFiles -Run.afterRun -Run.alignments -Run.analysis -Run.analysisOption -Run.args -Run.astralTree -Run.canLoadAlignment -Run.canLoadAstralTree -Run.canLoadPartitionFile -Run.cancel -Run.cancelModeltestOnAlignment -Run.clearConsole -Run.clearError -Run.clearFinished -Run.clearShowModified -Run.clearStderr -Run.clearStdout -Run.code -Run.command -Run.converted -Run.convertedAlignmentFrom -Run.data -Run.dataType -Run.disableCheckUndeterminedSequence -Run.error -Run.exitCode -Run.finished -Run.hasAstralTree -Run.haveAlignments -Run.havePartitionFile -Run.haveRandomSeed -Run.haveResult -Run.hidePartition -Run.inputIsAlignment -Run.inputIsTree -Run.loadAlignmentFiles -Run.loadAstralTree -Run.loadBackboneConstraintFile -Run.loadMultifurcatingConstraintFile -Run.loadPartitionFile -Run.loadTreeFile -Run.missing -Run.modelTestCanRun -Run.modelTestIsRunningOnAlignment -Run.modificationMessages -Run.modified -Run.needAlignment -Run.ngSubstitutionModelCmd -Run.numSites -Run.ok -Run.onAstralSuccess -Run.onBackboneConstraint -Run.onMultifurcatingConstraint -Run.onRunError -Run.onRunFinished -Run.onRunStderr -Run.onRunStdout -Run.openFile -Run.openOutputDir -Run.outputDir -Run.outputFilenameSafe -Run.outputName -Run.outputNameNotice -Run.outputNameOk -Run.outputNameSafe -Run.partitionFile -Run.partitionFileContent -Run.partitionFileName -Run.path -Run.randomSeed -Run.raxmlSubstitutionModelCmd -Run.removeAlignment -Run.removeAstralTree -Run.removePartitionFile -Run.removeRun -Run.reset -Run.resultDir -Run.resultFilenames -Run.running -Run.seedBootstrap -Run.seedParsimony -Run.seedRapidBootstrap -Run.selectOutputDir -Run.setOutputDir -Run.setOutputName -Run.setRandomSeed -Run.settingsFileContent -Run.settingsFilePath -Run.showModifiedDialog -Run.showModifiedSnack -Run.showPartition -Run.showPartitionFor -Run.start -Run.startAstral -Run.startDisabled -Run.stderr -Run.stdout -Run.taxons -Run.useBackboneConstraint -Run.useMultifurcatingConstraint -Run.usesAstral -Run.usesModeltest -Run.usesModeltestNg -Run.usesRaxml -Run.usesRaxmlNg -Run.writeSettings -RunList.activeIndex -RunList.activeRun -RunList.addRun -RunList.clearError -RunList.deleteActive -RunList.deleteRun -RunList.error -RunList.errorTitle -RunList.onBackboneConstraint -RunList.onError -RunList.onMultifurcatingConstraint -RunList.onUnhandledError -RunList.runs -RunList.setActive -SHlike.notAvailable -StartingTree.notAvailable -SubstitutionAscertainment.cmdValue -SubstitutionAscertainment.extraCmdValue -SubstitutionAscertainment.isSet -SubstitutionAscertainment.notAvailable -SubstitutionAscertainment.options -SubstitutionI.cmdValue -SubstitutionI.isSet -SubstitutionI.notAvailable -SubstitutionI.options -SubstitutionMatrix.cmdValue -SubstitutionMatrix.extraCmdValue -SubstitutionMatrix.notAvailable -SubstitutionMatrix.notGTR -SubstitutionMatrix.options -SubstitutionRate.cmdValue -SubstitutionRate.isCAT -SubstitutionRate.notAvailable -SubstitutionRate.options -Tree.notAvailable -TreeFile.dir -TreeFile.filePath -TreeFile.filename -TreeFile.haveFile -TreeFile.name -TreeFile.openFile -TreeFile.openFolder -TreeFile.remove -TreeFile.setFilePath diff --git a/src/app/store/annotationParity.test.js b/src/app/store/annotationParity.test.js deleted file mode 100644 index 70abc7c0..00000000 --- a/src/app/store/annotationParity.test.js +++ /dev/null @@ -1,59 +0,0 @@ -// @ts-nocheck -// TEMPORARY (spec #118): guards the decorators -> makeObservable conversion. -// Delete this file and annotationParity.baseline.txt in the cleanup ticket. -import fs from 'fs'; -import path from 'path'; -import { parse } from '@babel/parser'; -import traverse from '@babel/traverse'; - -const BASELINE = path.join( __dirname, 'annotationParity.baseline.txt' ); -const memberName = ( key ) => key.name ?? key.value; - -// Collects "Class.member" for every decorated member and every makeObservable map entry -// (including `override`). The annotation kind is deliberately not recorded. -const scan = ( file ) => { - const ast = parse( fs.readFileSync( file, 'utf8' ), { - sourceType: 'module', - plugins: [ - 'decorators-legacy', - 'classProperties', - ...( /\.tsx?$/.test( file ) - ? [ 'typescript' ] - : [] ), - ], - } ); - const found = []; - const classOf = ( p ) => p.findParent( ( q ) => q.isClass() )?.node.id.name; - traverse( ast, { - 'ClassProperty|ClassMethod'( p ) { - if ( p.node.decorators?.length ) { - found.push( `${classOf( p )}.${memberName( p.node.key )}` ); - } - }, - CallExpression( p ) { - const { callee, arguments: args } = p.node; - if ( callee.name !== 'makeObservable' || args[1]?.type !== 'ObjectExpression' ) return; - args[1].properties.forEach( ( prop ) => { - if ( prop.type !== "SpreadElement" && prop.value?.value !== false ) found.push( `${classOf( p )}.${memberName( prop.key )}` ); - } ); - }, - } ); - return found; -}; - -const scanAll = () => fs.readdirSync( __dirname ) - .filter( ( f ) => /\.(js|ts)$/.test( f ) && !/\.test\.(js|ts)$/.test( f ) ) - .flatMap( ( f ) => scan( path.join( __dirname, f ) ) ) - .sort(); - -describe( 'page store annotation parity (temporary)', () => { - it( 'matches the baseline', () => { - const actual = [ ...new Set( scanAll() ) ]; - if ( process.env.WRITE_BASELINE ) { - fs.writeFileSync( BASELINE, `${actual.join( '\n' )}\n` ); - } - const baseline = fs.readFileSync( BASELINE, 'utf8' ).split( '\n' ).filter( Boolean ); - expect( actual.filter( ( m ) => !baseline.includes( m ) ) ).toEqual( [] ); // gained - expect( baseline.filter( ( m ) => !actual.includes( m ) ) ).toEqual( [] ); // lost - } ); -} ); From 964898f964c3ea99199c1109ec74c41ebb816e04 Mon Sep 17 00:00:00 2001 From: Johannes Klein Agents Date: Mon, 16 Nov 2026 10:28:36 +0100 Subject: [PATCH 54/54] Slim promisedComputed: drop busy, ok/failed wrapping and the private MobX guard busy was only read by one test. fromPromise already exposes rejection, so the ok/failed wrapper is gone. The _getGlobalState guard used a private MobX API that the MobX 7 bump could break. Adds a direct test for the shim. Co-Authored-By: Claude Sonnet 5.5 --- src/app/promisedComputed.js | 45 +++++++-------------------- src/app/promisedComputed.test.js | 36 +++++++++++++++++++++ src/app/store/Run.computeds.test.js | 2 +- src/app/store/checkOutputName.test.js | 2 +- src/app/store/finalAlignment.test.js | 2 +- 5 files changed, 51 insertions(+), 36 deletions(-) create mode 100644 src/app/promisedComputed.test.js diff --git a/src/app/promisedComputed.js b/src/app/promisedComputed.js index 20d3506c..fbded5c3 100644 --- a/src/app/promisedComputed.js +++ b/src/app/promisedComputed.js @@ -1,57 +1,36 @@ -import { computed, makeObservable, _getGlobalState } from 'mobx'; -import { fromPromise, isPromiseBasedObservable } from 'mobx-utils'; - -const ok = ( value ) => ( { ok: true, value } ); -const failed = ( error ) => ( { ok: false, error } ); +import { computed, makeObservable } from 'mobx'; +import { fromPromise } from 'mobx-utils'; // Replaces computed-async-mobx: its 7.0 build mixes decorators with annotations, which MobX 6 rejects. // Like a computed that unwraps a promise: `init` until the first resolve, then the latest resolved value. -// `get` must run inside a reaction; `busy` is true while the promise is pending. +// Read it inside a reaction: outside one, every read re-runs `fetch` and returns `init`. class PromisedComputed { constructor( init, fetch ) { this.fetch = fetch; - this.cached = ok( init ); + this.cached = init; makeObservable( this, { currentState: computed, - busy: computed, value: computed, } ); } + // fetch must return a promise (the only caller is async) get currentState() { - try { - const promiseOrValue = this.fetch(); - return typeof promiseOrValue?.then === 'function' - ? fromPromise( promiseOrValue.then( ok, failed ) ) - : ok( promiseOrValue ); - } catch ( err ) { - return failed( err ); - } - } - - get busy() { - const state = this.currentState; - return isPromiseBasedObservable( state ) && state.state === 'pending'; + return fromPromise( this.fetch() ); } get value() { const state = this.currentState; - const result = !isPromiseBasedObservable( state ) - ? state - : state.state === 'fulfilled' - ? state.value - : this.cached; - this.cached = result; - if ( result.ok ) { - return result.value; + if ( state.state === 'rejected' ) { + throw state.value; + } + if ( state.state === 'fulfilled' ) { + this.cached = state.value; } - throw result.error; + return this.cached; } get() { - if ( !_getGlobalState().trackingDerivation ) { - throw new Error( 'promisedComputed must be used inside reactions' ); - } return this.value; } } diff --git a/src/app/promisedComputed.test.js b/src/app/promisedComputed.test.js new file mode 100644 index 00000000..9d010158 --- /dev/null +++ b/src/app/promisedComputed.test.js @@ -0,0 +1,36 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. +import { observable, runInAction, reaction, when } from 'mobx'; +import { promisedComputed } from './promisedComputed'; + +it( 'keeps the last value while pending and throws a rejection', async () => { + const input = observable.box( 1 ); + const pc = promisedComputed( 0, async () => { + const n = input.get(); + if ( n === 3 ) { + throw new Error( 'boom' ); + } + return n * 10; + } ); + const seen = []; + const errors = []; + const stop = reaction( + () => { + try { + return pc.get(); + } catch ( e ) { + errors.push( e.message ); + return 'error'; + } + }, + ( v ) => seen.push( v ), + { fireImmediately: true }, + ); + await when( () => pc.value === 10, { timeout: 1000 } ).catch( () => {} ); + runInAction( () => input.set( 2 ) ); + await when( () => pc.value === 20, { timeout: 1000 } ); + runInAction( () => input.set( 3 ) ); + await new Promise( ( r ) => setTimeout( r, 20 ) ); + stop(); + expect( seen ).toEqual( [0, 10, 20, 'error'] ); + expect( errors ).toEqual( ['boom'] ); +} ); diff --git a/src/app/store/Run.computeds.test.js b/src/app/store/Run.computeds.test.js index 28ec2cc2..5768779a 100644 --- a/src/app/store/Run.computeds.test.js +++ b/src/app/store/Run.computeds.test.js @@ -58,7 +58,7 @@ function makeRun( { alignments = [nucleotide()], binary = 'raxmlHPC', outputDir return run; } -// outputNameAvailable only works inside a reaction, so reads that touch it go through here. +// outputNameAvailable only settles inside a reaction, so reads that touch it go through here. function read( fn ) { let value; autorun( () => { diff --git a/src/app/store/checkOutputName.test.js b/src/app/store/checkOutputName.test.js index 2d6327a8..bc7ba708 100644 --- a/src/app/store/checkOutputName.test.js +++ b/src/app/store/checkOutputName.test.js @@ -19,7 +19,7 @@ it( 'the output-name check uses checkOutput', async () => { let seen; await when( () => { const value = run.outputNameAvailable.get(); - if ( run.outputNameAvailable.busy || value.outputNameUnused !== 'tree_1' ) { + if ( value.outputNameUnused !== 'tree_1' ) { return false; } seen = { diff --git a/src/app/store/finalAlignment.test.js b/src/app/store/finalAlignment.test.js index 63b46c30..50e79769 100644 --- a/src/app/store/finalAlignment.test.js +++ b/src/app/store/finalAlignment.test.js @@ -7,7 +7,7 @@ import Run from './Run'; // sequences set directly, as writeConcatenatedAlignment.test.js does. function makeRun( alignments ) { const run = new Run( {}, 7 ); - // outputNameAvailable is a promisedComputed that only reads inside a reaction; pin it. + // outputNameAvailable is a promisedComputed that only settles inside a reaction (outside one each read calls the bridge); pin it. run.outputNameAvailable = { get: () => ( { outputNameUnused: 'out' } ) }; window.rendererBridge = { parseAlignment: () => new Promise( () => {} ) }; run.addAlignments( alignments.map( ( { path } ) => ( { path } ) ) );