MIDIClient.init;
MIDIIn.connectAll;


(
// MIDI
// EMF: one major issue here is that ~notes is never actually initialized as an array, so it's nil. when you try to store a Synth at index nn, SC throws an error, because you can't put an item into nil. So, we first initialize ~notes as an array of size 128. After I add this line, your polyphonic MIDI code seems to work fine (no stuck notes)

~notes = Array.newClear(128);

MIDIdef.noteOn(\noteOnTest, {
	arg vel, nn, chan, src;
	// [vel, nn].postln;
	~notes[nn] = Synth.new(
		\rhubarb,
		[
			\freq, nn.midicps,
			\amp, vel.linexp(1,127,0.01,0.3),
			\gate, 1,
			\detune, 2,
			\cutoff, 400,
			\rq, 0.7,
		]
	);
});

MIDIdef.noteOff(\noteOffTest, {
	arg vel, nn;
	// [vel, nn].postln;
	~notes[nn].set(\gate, 0);
	~notes[nn] = nil;
});
)






(
SynthDef(\rhubarb, {
    |freq = 440, gate = 1, cutoff = 1e4, rq = 0.3, amp = 0.3, modDepth = 0.3, detune = 0|
	var env, osc, osc2, filt, lfo, lfo2, sig;

	sig = Pulse.ar(freq + detune);
	env = EnvGen.kr(Env.adsr(0.1, 0.3, 0.3, 0.1), gate, doneAction: 2);
    lfo = LFNoise2.kr(20).range(1 - modDepth, 1 + modDepth);
	filt = RLPF.ar(sig, cutoff * lfo, rq);
	sig = filt * env * amp;

    Out.ar(0, sig!2);
}).add;
)