From 5c95dceb5840f4465f62dc3154d3b643161e9405 Mon Sep 17 00:00:00 2001 From: karigardarsson <10534568+karigardarsson@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:15:49 +0000 Subject: [PATCH 1/8] Preview Digitakt II Try and Undo with a mock device --- .../2026-12-04-digitakt-ii-trial-preview.md | 1 + src/dev/Dt2TrialPreview.test.ts | 108 +++++++++++++ src/dev/Dt2TrialPreview.tsx | 142 ++++++++++++++++++ src/dev/dt2-trial-mock.ts | 55 +++++++ src/dev/dt2-trial-preview.css | 29 ++++ src/main.tsx | 6 +- 6 files changed, 340 insertions(+), 1 deletion(-) create mode 100644 changelog/2026-12-04-digitakt-ii-trial-preview.md create mode 100644 src/dev/Dt2TrialPreview.test.ts create mode 100644 src/dev/Dt2TrialPreview.tsx create mode 100644 src/dev/dt2-trial-mock.ts create mode 100644 src/dev/dt2-trial-preview.css diff --git a/changelog/2026-12-04-digitakt-ii-trial-preview.md b/changelog/2026-12-04-digitakt-ii-trial-preview.md new file mode 100644 index 0000000000..e55829e802 --- /dev/null +++ b/changelog/2026-12-04-digitakt-ii-trial-preview.md @@ -0,0 +1 @@ +Digitakt II: a local mock preview shows the running modules, tries a module in RAM and restores the previous set with Undo. If USB drops during Undo, the panel shows the last confirmed set and checks it again on reconnect. Keep stays disabled. diff --git a/src/dev/Dt2TrialPreview.test.ts b/src/dev/Dt2TrialPreview.test.ts new file mode 100644 index 0000000000..d572412864 --- /dev/null +++ b/src/dev/Dt2TrialPreview.test.ts @@ -0,0 +1,108 @@ +// @vitest-environment jsdom +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Dt2TrialPreview from './Dt2TrialPreview' +import { createMockDt2Device } from './dt2-trial-mock' + +let container: HTMLElement +let root: Root +const text = () => container.textContent +const button = (name: string) => [...container.querySelectorAll('button')].find(item => item.textContent === name)! +const click = (name: string) => act(() => button(name).click()) +const settle = () => act(() => vi.runAllTimersAsync()) +const modules = () => [...container.querySelectorAll('.hub-unit-modules strong')].map(item => item.textContent) + +beforeEach(() => { + vi.useFakeTimers() + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) +}) + +afterEach(async () => { + await act(() => root.unmount()) + container.remove() + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +async function open() { + const device = createMockDt2Device() + const read = vi.spyOn(device, 'read') + const undo = vi.spyOn(device, 'undo') + await act(() => root.render(createElement(Dt2TrialPreview, { makeDevice: () => device }))) + expect(text()).toContain('Reading the box') + expect(button('Try').disabled).toBe(true) + await settle() + return { read, undo } +} + +describe('Digitakt II trial preview', () => { + it('reads the box, tries in RAM and verifies that Undo restores the prior set', async () => { + const { read } = await open() + expect(text()).toContain('DT2-MOCK-01') + expect(text()).toContain('1.17') + expect(text()).toContain('7f31c2a0') + expect(modules()).toEqual(['Track Names']) + expect(button('Keep').disabled).toBe(true) + expect(button('Undo').disabled).toBe(true) + + await click('Try') + expect(text()).toContain('Starting trial') + expect(modules()).toEqual(['Track Names']) + await settle() + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + expect(text()).toContain('Trial in RAM') + expect(text()).toContain('Undo restores the previous set: Track Names') + expect(button('Keep').disabled).toBe(true) + + await click('Undo') + expect(button('Undo').disabled).toBe(true) + expect(text()).toContain('Undoing trial') + await settle() + expect(read).toHaveBeenCalledTimes(3) + expect(modules()).toEqual(['Track Names']) + expect(text()).toContain('Previous set restored') + expect(button('Try').disabled).toBe(false) + }) + + it.each([ + ['drop-before-restore', ['Track Names', 'Chord Arp'], 'Box checked.', false], + ['drop-after-restore', ['Track Names'], 'Previous set restored', true], + ] as const)('reads actual mock state after %s without replaying Undo', async (scenario, expected, message, undoDisabled) => { + const { read, undo } = await open() + await click('Try') + await settle() + const picker = container.querySelector('select')! + await act(() => { + picker.value = scenario + picker.dispatchEvent(new Event('change', { bubbles: true })) + }) + await click('Undo') + await settle() + expect(read).toHaveBeenCalledTimes(2) + expect(text()).toContain('USB disconnected') + expect(text()).toContain('Last confirmed set') + expect(text()).toContain('Undo result unknown') + expect(text()).toContain('Last read base') + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + expect(button('Undo')).toBeUndefined() + expect(button('Keep').disabled).toBe(true) + + await click('Reconnect') + expect(button('Reconnect').disabled).toBe(true) + expect(text()).toContain('Undo result unknown') + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + await settle() + expect(read).toHaveBeenCalledTimes(3) + expect(undo).toHaveBeenCalledTimes(1) + expect(text()).toContain('On the box') + expect(text()).toContain(message) + expect(text()).not.toContain('Undo result unknown') + expect(modules()).toEqual(expected) + expect(button('Undo').disabled).toBe(undoDisabled) + expect(button('Keep').disabled).toBe(true) + }) +}) diff --git a/src/dev/Dt2TrialPreview.tsx b/src/dev/Dt2TrialPreview.tsx new file mode 100644 index 0000000000..04f7303ee9 --- /dev/null +++ b/src/dev/Dt2TrialPreview.tsx @@ -0,0 +1,142 @@ +import { useEffect, useState } from 'react' +import { DeviceImage } from '../devices/DeviceImage' +import { DEVICES_BY_ID } from '../devices/registry' +import { createMockDt2Device, TRIAL_MODULE, UNDO_SCENARIOS, type Dt2Snapshot, type UndoScenario } from './dt2-trial-mock' +import '../devices/devices.css' +import '../components/octatrack-link.css' +import './dt2-trial-preview.css' + +type Phase = 'reading' | 'ready' | 'trying' | 'undoing' | 'undo-unknown' | 'reconnecting' +type Review = 'restored' | 'reread' +type Control = { + phase: Phase + confirmed: Dt2Snapshot | null + review?: Review +} + +function trialMessage({ phase, confirmed, review }: Control): [title: string, detail: string] { + switch (phase) { + case 'reading': return ['Reading the box…', 'Checking the build and active modules.'] + case 'trying': return ['Starting trial…', `Loading ${TRIAL_MODULE} into RAM.`] + case 'undoing': return ['Undoing trial…', 'Restoring the previous set and checking what is running.'] + case 'undo-unknown': return ['Undo result unknown', 'USB disconnected during Undo. Reconnect to check what’s on the box.'] + case 'reconnecting': return ['Undo result unknown', 'Reading the box again to check what’s running…'] + case 'ready': { + const trial = confirmed?.trial + if (trial) return ['Trial active', `${review === 'reread' ? 'Box checked. ' : ''}${trial.module} is running from RAM. Undo restores the previous set: ${trial.previous.join(', ') || 'no modules'}.`] + if (review === 'restored') return ['Previous set restored', 'The box confirmed that the previous set is running.'] + return [`Try ${TRIAL_MODULE}`, `Load ${TRIAL_MODULE} into RAM. You can undo the trial to restore the current set.`] + } + } +} + +export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, onReconnect }: { + control: Control + scenario: UndoScenario + setScenario: (scenario: UndoScenario) => void + onTry: () => void + onUndo: () => void + onReconnect: () => void +}) { + const { phase, confirmed } = control + const stale = phase === 'undo-unknown' || phase === 'reconnecting' + const pending = phase === 'trying' || phase === 'undoing' + const trial = confirmed?.trial + const [title, detail] = trialMessage(control) + const linkLabel = phase === 'undo-unknown' ? 'USB disconnected' + : phase === 'reconnecting' ? 'Reconnecting…' + : phase === 'reading' ? 'Reading over USB…' : 'Connected via USB' + const led = phase === 'undo-unknown' ? 'leaving' : phase === 'reading' || phase === 'reconnecting' ? 'load' : 'on' + + return
+

Try, Keep and Undo

Digitakt II mock preview

+
+
+ +
+

Digitakt II

+

+ {confirmed &&
+
Unit
{confirmed.unitId}
+
OS
{confirmed.os}
+
{stale ? 'Last read base' : 'Base'}
{confirmed.build}
+
} +
+
+
+

{stale || pending ? 'Last confirmed set' : 'On the box'}

+ {confirmed?.modules.length ?
    + {confirmed.modules.map(module => { + const inTrial = module === trial?.module + return
  • +
  • + })} +
:

{confirmed ? 'No modules running.' : 'Reading active modules…'}

} +
+
+
+

{title}

+

{detail}

+
+
+ {!stale && !trial && } + + {!stale && } + {stale && } +
+

Keep requires a base that supports saving the set.

+
+
+ +
+} + +export default function Dt2TrialPreview({ makeDevice = createMockDt2Device }: { + makeDevice?: () => ReturnType +}) { + const [device] = useState(makeDevice) + const [scenario, setScenario] = useState('standard') + const [control, setControl] = useState({ phase: 'reading', confirmed: null }) + const { confirmed } = control + + useEffect(() => { + let active = true + void device.read().then(snapshot => { + if (active) setControl({ phase: 'ready', confirmed: snapshot }) + }) + return () => { active = false } + }, [device]) + + async function startTrial() { + setControl({ phase: 'trying', confirmed }) + await device.tryInRam() + setControl({ phase: 'ready', confirmed: await device.read() }) + } + + async function undo() { + setControl({ phase: 'undoing', confirmed }) + if (!await device.undo(scenario)) { + setControl({ phase: 'undo-unknown', confirmed }) + return + } + setControl({ phase: 'ready', confirmed: await device.read(), review: 'restored' }) + } + + async function reconnect() { + setControl({ phase: 'reconnecting', confirmed }) + device.reconnect() + const snapshot = await device.read() + setControl({ phase: 'ready', confirmed: snapshot, review: snapshot.trial ? 'reread' : 'restored' }) + } + + return void startTrial()} onUndo={() => void undo()} onReconnect={() => void reconnect()} /> +} diff --git a/src/dev/dt2-trial-mock.ts b/src/dev/dt2-trial-mock.ts new file mode 100644 index 0000000000..68ce003112 --- /dev/null +++ b/src/dev/dt2-trial-mock.ts @@ -0,0 +1,55 @@ +export type UndoScenario = 'standard' | 'drop-before-restore' | 'drop-after-restore' + +export const UNDO_SCENARIOS: ReadonlyArray<{ value: UndoScenario; label: string }> = [ + { value: 'standard', label: 'Standard trial' }, + { value: 'drop-before-restore', label: 'USB drops before restore' }, + { value: 'drop-after-restore', label: 'USB drops after restore' }, +] + +const savedModule = 'Track Names' +export const TRIAL_MODULE = 'Chord Arp' + +export type Dt2Snapshot = { + unitId: string + os: string + build: string + modules: readonly string[] + trial?: { module: string; previous: readonly string[] } +} + +export function createMockDt2Device(wait: () => Promise = () => new Promise(resolve => setTimeout(resolve, 400))) { + let connected = true + let snapshot: Dt2Snapshot = { unitId: 'DT2-MOCK-01', os: '1.17', build: '7f31c2a0', modules: [savedModule] } + + function restore() { + if (!snapshot.trial) return + const { trial, ...unit } = snapshot + snapshot = { ...unit, modules: trial.previous } + } + + return { + async read() { + await wait() + if (!connected) throw new Error('Mock USB disconnected') + return snapshot + }, + async tryInRam() { + await wait() + snapshot = { + ...snapshot, + modules: [...snapshot.modules, TRIAL_MODULE], + trial: { module: TRIAL_MODULE, previous: snapshot.modules }, + } + }, + async undo(scenario: UndoScenario) { + await wait() + if (scenario !== 'drop-before-restore') restore() + // The box may have restored its previous modules even though the browser lost the reply. + connected = scenario === 'standard' + return connected + }, + reconnect() { + connected = true + }, + } +} diff --git a/src/dev/dt2-trial-preview.css b/src/dev/dt2-trial-preview.css new file mode 100644 index 0000000000..8ed81b8832 --- /dev/null +++ b/src/dev/dt2-trial-preview.css @@ -0,0 +1,29 @@ +.dt2-trial-preview { width: min(100% - 32px, 920px); margin: 40px auto; } +.dt2-trial-panel { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); overflow: hidden; } +.dt2-trial-panel .hub-hero, .dt2-trial-panel .hub-cell { padding: 20px 24px; } +.dt2-trial-panel .hub-hero .device-photo { width: 136px; } +.dt2-trial-panel .hub-hero h2 { font-family: var(--display); font-size: 24px; } +.dt2-trial-panel .hub-cell h3 { margin: 0; font-size: 15px; font-weight: 600; } +.dt2-trial-panel .hub-unit-modules { margin-top: 8px; } +.dt2-trial-panel .hub-unit-modules li { min-height: 40px; } +.dt2-trial-panel .hub-unit-modules .dt2-trial-ram, +.dt2-trial-panel .dt2-trial-warning { color: var(--warn); } +.dt2-trial-review { border-inline-start: 1px solid var(--chrome-edge); } +.dt2-trial-message { min-height: 72px; } +.dt2-trial-detail { margin-top: 8px; color: var(--text-secondary); font-size: 14px; line-height: 1.55; } +.dt2-trial-actions, .dt2-trial-scenario { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.dt2-trial-actions { margin: 12px 0 8px; } +.dt2-trial-note, .dt2-trial-scenario { color: var(--muted); font-size: 13px; line-height: 1.5; } +.dt2-trial-scenario { margin-top: 16px; gap: 12px; } +.dt2-trial-scenario select { max-width: 100%; } +.dt2-trial-scenario select:disabled { opacity: .65; } + +@media (max-width: 620px) { + .dt2-trial-preview { margin-block: 20px; } + .dt2-trial-panel { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto; } + .dt2-trial-panel .hub-hero, .dt2-trial-panel .hub-cell { padding: 16px; } + .dt2-trial-panel .hub-hero { display: flex; } + .dt2-trial-panel .hub-hero .device-photo { width: 90px; } + .dt2-trial-review { border-inline-start: 0; border-top: 1px solid var(--chrome-edge); } + .dt2-trial-message { min-height: 0; } +} diff --git a/src/main.tsx b/src/main.tsx index 5180e91cfc..aa52be8abf 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -15,12 +15,16 @@ startRouting(MODULES.map(module => module.id)) markDesktopShell(document.documentElement) const ReportingPreview = import.meta.env.DEV ? lazy(() => import('./components/ReportingPreview')) : () => null const AudioPreviewPrototype = import.meta.env.DEV ? lazy(() => import('./components/AudioPreviewPrototype')) : () => null +const Dt2TrialPreview = import.meta.env.DEV ? lazy(() => import('./dev/Dt2TrialPreview')) : () => null const preview = import.meta.env.DEV ? new URLSearchParams(window.location.search).get('preview') : null createRoot(document.getElementById('root')!).render( }> - {preview === 'audio' ? Opening audio previews…

}>
: preview === 'reporting' || preview === 'reporting-module' ? Opening reporting previews…

}>
: } + {preview === 'dt2-trial' ? Opening Digitakt II preview…

}>
+ : preview === 'audio' ? Opening audio previews…

}>
+ : preview === 'reporting' || preview === 'reporting-module' ? Opening reporting previews…

}>
+ : }
, ) From 329f3543059a16ce70882beb27446f94e1ccee1d Mon Sep 17 00:00:00 2001 From: karigardarsson <10534568+karigardarsson@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:07:33 +0000 Subject: [PATCH 2/8] Read linked Digitakt II mock inventory on reconnect --- .../2026-12-04-digitakt-ii-trial-preview.md | 2 +- src/dev/Dt2TrialPreview.test.ts | 111 ++++++++++++++-- src/dev/Dt2TrialPreview.tsx | 67 ++++++---- src/dev/dt2-trial-mock.ts | 119 ++++++++++++++---- 4 files changed, 240 insertions(+), 59 deletions(-) diff --git a/changelog/2026-12-04-digitakt-ii-trial-preview.md b/changelog/2026-12-04-digitakt-ii-trial-preview.md index e55829e802..a5dc6535c9 100644 --- a/changelog/2026-12-04-digitakt-ii-trial-preview.md +++ b/changelog/2026-12-04-digitakt-ii-trial-preview.md @@ -1 +1 @@ -Digitakt II: a local mock preview shows the running modules, tries a module in RAM and restores the previous set with Undo. If USB drops during Undo, the panel shows the last confirmed set and checks it again on reconnect. Keep stays disabled. +Digitakt II: a local mock preview shows the running modules, tries a module in RAM and restores the previous set with Undo. If USB drops during Undo, the panel shows the last confirmed set and reads the unit’s active modules again on reconnect. Keep stays disabled. diff --git a/src/dev/Dt2TrialPreview.test.ts b/src/dev/Dt2TrialPreview.test.ts index d572412864..5c28a12c7e 100644 --- a/src/dev/Dt2TrialPreview.test.ts +++ b/src/dev/Dt2TrialPreview.test.ts @@ -3,7 +3,7 @@ import { act, createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import Dt2TrialPreview from './Dt2TrialPreview' -import { createMockDt2Device } from './dt2-trial-mock' +import { createMockDt2Device, readDt2Snapshot } from './dt2-trial-mock' let container: HTMLElement let root: Root @@ -30,18 +30,28 @@ afterEach(async () => { async function open() { const device = createMockDt2Device() - const read = vi.spyOn(device, 'read') + const ident = vi.spyOn(device, 'ident') + const hello = vi.spyOn(device, 'hello') + const inventory = vi.spyOn(device, 'inventory') const undo = vi.spyOn(device, 'undo') await act(() => root.render(createElement(Dt2TrialPreview, { makeDevice: () => device }))) expect(text()).toContain('Reading the box') expect(button('Try').disabled).toBe(true) await settle() - return { read, undo } + return { device, ident, hello, inventory, undo } +} + +async function setScenario(value: string) { + const picker = container.querySelector('select')! + await act(() => { + picker.value = value + picker.dispatchEvent(new Event('change', { bubbles: true })) + }) } describe('Digitakt II trial preview', () => { it('reads the box, tries in RAM and verifies that Undo restores the prior set', async () => { - const { read } = await open() + const { ident, hello, inventory } = await open() expect(text()).toContain('DT2-MOCK-01') expect(text()).toContain('1.17') expect(text()).toContain('7f31c2a0') @@ -62,7 +72,9 @@ describe('Digitakt II trial preview', () => { expect(button('Undo').disabled).toBe(true) expect(text()).toContain('Undoing trial') await settle() - expect(read).toHaveBeenCalledTimes(3) + expect(ident).toHaveBeenCalledTimes(3) + expect(hello).toHaveBeenCalledTimes(3) + expect(inventory.mock.calls.flat()).toEqual([0, 16, 0, 16, 32, 48, 0, 16]) expect(modules()).toEqual(['Track Names']) expect(text()).toContain('Previous set restored') expect(button('Try').disabled).toBe(false) @@ -72,17 +84,13 @@ describe('Digitakt II trial preview', () => { ['drop-before-restore', ['Track Names', 'Chord Arp'], 'Box checked.', false], ['drop-after-restore', ['Track Names'], 'Previous set restored', true], ] as const)('reads actual mock state after %s without replaying Undo', async (scenario, expected, message, undoDisabled) => { - const { read, undo } = await open() + const { ident, hello, inventory, undo } = await open() await click('Try') await settle() - const picker = container.querySelector('select')! - await act(() => { - picker.value = scenario - picker.dispatchEvent(new Event('change', { bubbles: true })) - }) + await setScenario(scenario) await click('Undo') await settle() - expect(read).toHaveBeenCalledTimes(2) + expect(hello).toHaveBeenCalledTimes(2) expect(text()).toContain('USB disconnected') expect(text()).toContain('Last confirmed set') expect(text()).toContain('Undo result unknown') @@ -91,12 +99,19 @@ describe('Digitakt II trial preview', () => { expect(button('Undo')).toBeUndefined() expect(button('Keep').disabled).toBe(true) + ident.mockClear() + hello.mockClear() + inventory.mockClear() await click('Reconnect') expect(button('Reconnect').disabled).toBe(true) expect(text()).toContain('Undo result unknown') expect(modules()).toEqual(['Track Names', 'Chord Arp']) await settle() - expect(read).toHaveBeenCalledTimes(3) + expect(ident).toHaveBeenCalledOnce() + expect(hello).toHaveBeenCalledOnce() + expect(ident.mock.invocationCallOrder[0]).toBeLessThan(hello.mock.invocationCallOrder[0]) + expect(hello.mock.invocationCallOrder[0]).toBeLessThan(inventory.mock.invocationCallOrder[0]) + expect(inventory.mock.calls.flat()).toEqual(undoDisabled ? [0, 16] : [0, 16, 32, 48]) expect(undo).toHaveBeenCalledTimes(1) expect(text()).toContain('On the box') expect(text()).toContain(message) @@ -105,4 +120,74 @@ describe('Digitakt II trial preview', () => { expect(button('Undo').disabled).toBe(undoDisabled) expect(button('Keep').disabled).toBe(true) }) + + it('keeps the last confirmed list through unknown HELLO and incomplete INVENTORY', async () => { + const { device, hello, inventory } = await open() + await click('Try') + await settle() + await setScenario('drop-after-restore') + await click('Undo') + await settle() + + const lastHello = await hello.mock.results.at(-1)!.value + hello.mockResolvedValueOnce({ ...lastHello, activeKnown: false, active: null }) + inventory.mockClear() + await click('Reconnect') + await settle() + expect(inventory).not.toHaveBeenCalled() + expect(text()).toContain('Undo result unknown') + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + + inventory.mockImplementationOnce(async () => ({ offset: 16, data: new Uint8Array([0x4d, 0x57, 0x49, 1]) })) + await click('Reconnect') + await settle() + expect(text()).toContain('Undo result unknown') + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + + // Reconnect must render the device's name even when the host build record has a different one. + const reading = device.inventory(0) + await settle() + const first = await reading + first.data[12] = 0x74 + inventory.mockResolvedValueOnce(first) + await click('Reconnect') + await settle() + expect(text()).toContain('Previous set restored') + expect(modules()).toEqual(['track Names']) + }) + + it.each([ + [{ session: '99'.repeat(32) }, 'Box restarted'], + [{ active: '99'.repeat(32) }, 'Box checked'], + ] as const)('uses HELLO to qualify the Undo result with %j', async (field, result) => { + const { hello } = await open() + const normal = await hello.mock.results.at(-1)!.value + await click('Try') + await settle() + await setScenario('drop-after-restore') + await click('Undo') + await settle() + hello.mockResolvedValueOnce({ ...normal, ...field }) + await click('Reconnect') + await settle() + expect(text()).toContain(result) + expect(text()).not.toContain('Previous set restored') + expect(modules()).toEqual(['Track Names']) + }) +}) + +describe('mock INVENTORY wire record', () => { + it('serves MWI plus its count and fixed-size big-endian entries by byte offset', async () => { + const device = createMockDt2Device(async () => {}) + expect((await device.inventory(0)).data.slice(0, 4)).toEqual(Uint8Array.of(0x4d, 0x57, 0x49, 1)) + await device.tryInRam() + const parts = await Promise.all([0, 16, 32, 48].map(offset => device.inventory(offset))) + expect(parts.map(part => [part.offset, part.data.length])).toEqual([[0, 16], [16, 16], [32, 16], [48, 4]]) + const bytes = Uint8Array.from(parts.flatMap(part => [...part.data])) + expect(bytes.slice(0, 4)).toEqual(Uint8Array.of(0x4d, 0x57, 0x49, 2)) + expect(bytes.slice(28, 36)).toEqual(Uint8Array.of(0xff, 0, 0x12, 0x34, 0xec, 0xa8, 0x72, 0x2f)) + expect(new TextDecoder().decode(bytes.slice(36, 52))).toBe('Chord Arp' + '\0'.repeat(7)) + expect((await readDt2Snapshot(device)).modules[1]).toMatchObject({ module: 'eca8722f', layout: 0x1234, name: 'Chord Arp' }) + await expect(device.inventory(52)).rejects.toThrow('Invalid INVENTORY offset') + }) }) diff --git a/src/dev/Dt2TrialPreview.tsx b/src/dev/Dt2TrialPreview.tsx index 04f7303ee9..82a8293b82 100644 --- a/src/dev/Dt2TrialPreview.tsx +++ b/src/dev/Dt2TrialPreview.tsx @@ -1,30 +1,43 @@ import { useEffect, useState } from 'react' import { DeviceImage } from '../devices/DeviceImage' import { DEVICES_BY_ID } from '../devices/registry' -import { createMockDt2Device, TRIAL_MODULE, UNDO_SCENARIOS, type Dt2Snapshot, type UndoScenario } from './dt2-trial-mock' +import { createMockDt2Device, readDt2Snapshot, TRIAL_MODULE, UNDO_SCENARIOS, type Dt2Snapshot, type UndoScenario } from './dt2-trial-mock' import '../devices/devices.css' import '../components/octatrack-link.css' import './dt2-trial-preview.css' -type Phase = 'reading' | 'ready' | 'trying' | 'undoing' | 'undo-unknown' | 'reconnecting' -type Review = 'restored' | 'reread' +type Phase = 'reading' | 'ready' | 'trying' | 'undoing' | 'undo-unknown' | 'reconnecting' | 'read-failed' +type Review = 'restored' | 'reread' | 'restarted' type Control = { phase: Phase confirmed: Dt2Snapshot | null review?: Review + undoPending?: boolean } -function trialMessage({ phase, confirmed, review }: Control): [title: string, detail: string] { +function reviewUndo(before: Dt2Snapshot, after: Dt2Snapshot): Review { + if (after.hello.session !== before.hello.session) return 'restarted' + return !after.trial && after.hello.active === before.trial?.previous?.digest ? 'restored' : 'reread' +} + +function trialMessage({ phase, confirmed, review, undoPending }: Control): [title: string, detail: string] { switch (phase) { case 'reading': return ['Reading the box…', 'Checking the build and active modules.'] case 'trying': return ['Starting trial…', `Loading ${TRIAL_MODULE} into RAM.`] case 'undoing': return ['Undoing trial…', 'Restoring the previous set and checking what is running.'] case 'undo-unknown': return ['Undo result unknown', 'USB disconnected during Undo. Reconnect to check what’s on the box.'] - case 'reconnecting': return ['Undo result unknown', 'Reading the box again to check what’s running…'] + case 'reconnecting': return [undoPending ? 'Undo result unknown' : 'Reading the box…', 'Reading the box again to check what’s running…'] + case 'read-failed': return [undoPending ? 'Undo result unknown' : 'Active set unconfirmed', 'The box’s active set could not be confirmed. Reconnect to read it again.'] case 'ready': { const trial = confirmed?.trial - if (trial) return ['Trial active', `${review === 'reread' ? 'Box checked. ' : ''}${trial.module} is running from RAM. Undo restores the previous set: ${trial.previous.join(', ') || 'no modules'}.`] + if (trial) { + const running = trial.names.length ? `Trial in RAM: ${trial.names.join(', ')}.` : 'A trial is running from RAM.' + const previous = trial.previous ? `the previous set: ${trial.previous.names.join(', ') || 'no modules'}` : 'the previous set' + return ['Trial active', `${review ? 'Box checked. ' : ''}${running} Undo restores ${previous}.`] + } if (review === 'restored') return ['Previous set restored', 'The box confirmed that the previous set is running.'] + if (review === 'restarted') return ['Box restarted', 'The active modules were read from the new session.'] + if (review === 'reread') return ['Box checked', 'The module list shows what the box reported after Undo.'] return [`Try ${TRIAL_MODULE}`, `Load ${TRIAL_MODULE} into RAM. You can undo the trial to restore the current set.`] } } @@ -39,14 +52,16 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o onReconnect: () => void }) { const { phase, confirmed } = control - const stale = phase === 'undo-unknown' || phase === 'reconnecting' + const stale = phase === 'undo-unknown' || phase === 'reconnecting' || phase === 'read-failed' const pending = phase === 'trying' || phase === 'undoing' const trial = confirmed?.trial const [title, detail] = trialMessage(control) const linkLabel = phase === 'undo-unknown' ? 'USB disconnected' : phase === 'reconnecting' ? 'Reconnecting…' + : phase === 'read-failed' ? 'Device state unconfirmed' : phase === 'reading' ? 'Reading over USB…' : 'Connected via USB' - const led = phase === 'undo-unknown' ? 'leaving' : phase === 'reading' || phase === 'reconnecting' ? 'load' : 'on' + const led = phase === 'undo-unknown' || phase === 'read-failed' ? 'leaving' + : phase === 'reading' || phase === 'reconnecting' ? 'load' : 'on' return

Try, Keep and Undo

Digitakt II mock preview

@@ -59,7 +74,7 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o {confirmed &&
Unit
{confirmed.unitId}
OS
{confirmed.os}
-
{stale ? 'Last read base' : 'Base'}
{confirmed.build}
+
{stale ? 'Last read base' : 'Base'}
{confirmed.hello.base.slice(0, 8)}
} @@ -67,14 +82,14 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o

{stale || pending ? 'Last confirmed set' : 'On the box'}

{confirmed?.modules.length ?
    {confirmed.modules.map(module => { - const inTrial = module === trial?.module - return
  • + const inTrial = !!trial && !module.saved + return
  • })} -
:

{confirmed ? 'No modules running.' : 'Reading active modules…'}

} + :

{confirmed ? 'No modules running.' : stale ? 'No confirmed inventory.' : 'Reading active modules…'}

}
@@ -109,32 +124,42 @@ export default function Dt2TrialPreview({ makeDevice = createMockDt2Device }: { useEffect(() => { let active = true - void device.read().then(snapshot => { + void readDt2Snapshot(device).then(snapshot => { if (active) setControl({ phase: 'ready', confirmed: snapshot }) + }, () => { + if (active) setControl({ phase: 'read-failed', confirmed: null }) }) return () => { active = false } }, [device]) + async function refresh(undoPending = false) { + try { + const snapshot = await readDt2Snapshot(device) + setControl({ phase: 'ready', confirmed: snapshot, review: undoPending && confirmed ? reviewUndo(confirmed, snapshot) : undefined }) + } catch { + setControl({ phase: 'read-failed', confirmed, undoPending }) + } + } + async function startTrial() { setControl({ phase: 'trying', confirmed }) await device.tryInRam() - setControl({ phase: 'ready', confirmed: await device.read() }) + await refresh() } async function undo() { setControl({ phase: 'undoing', confirmed }) if (!await device.undo(scenario)) { - setControl({ phase: 'undo-unknown', confirmed }) + setControl({ phase: 'undo-unknown', confirmed, undoPending: true }) return } - setControl({ phase: 'ready', confirmed: await device.read(), review: 'restored' }) + await refresh(true) } async function reconnect() { - setControl({ phase: 'reconnecting', confirmed }) + setControl({ phase: 'reconnecting', confirmed, undoPending: control.undoPending }) device.reconnect() - const snapshot = await device.read() - setControl({ phase: 'ready', confirmed: snapshot, review: snapshot.trial ? 'reread' : 'restored' }) + await refresh(control.undoPending) } return = [ @@ -6,45 +9,113 @@ export const UNDO_SCENARIOS: ReadonlyArray<{ value: UndoScenario; label: string { value: 'drop-after-restore', label: 'USB drops after restore' }, ] -const savedModule = 'Track Names' -export const TRIAL_MODULE = 'Chord Arp' +const BASE = '7f31c2a0'.repeat(8) +const SESSION = '01234567'.repeat(8) +const SAVED_DIGEST = '8a2b4310'.repeat(8) +const TRIAL_DIGEST = 'f251c965'.repeat(8) +const SAVED = [{ handle: 0xff, layout: 0, module: '7d2f8b1f', name: 'Track Names' }] +const CHORD_ARP = { handle: 0xff, layout: 0x1234, module: 'eca8722f', name: 'Chord Arp' } +const TRIAL = [...SAVED, CHORD_ARP] +export const TRIAL_MODULE = CHORD_ARP.name + +const INVENTORY_HEADER = 4 +const ENTRY_BYTES = 24 +const PART_BYTES = 16 // Deliberately crosses entry boundaries in this mock. + +type Hello = Pick +type InventoryPart = { offset: number; data: Uint8Array } +type Reads = Pick, 'ident' | 'hello' | 'inventory'> export type Dt2Snapshot = { unitId: string os: string - build: string - modules: readonly string[] - trial?: { module: string; previous: readonly string[] } + hello: Hello + modules: Array + trial?: { names: string[]; previous?: { names: string[]; digest: string } } +} + +function encodeInventory(modules: MissingModule[]) { + const bytes = new Uint8Array(INVENTORY_HEADER + ENTRY_BYTES * modules.length) + const view = new DataView(bytes.buffer) + bytes.set([0x4d, 0x57, 0x49, modules.length]) // MWI + entry count (2 during this trial). + for (const [index, module] of modules.entries()) { + const at = INVENTORY_HEADER + index * ENTRY_BYTES + view.setUint8(at, module.handle) + view.setUint16(at + 2, module.layout) + view.setUint32(at + 4, Number.parseInt(module.module, 16)) + for (let i = 0; i < 16 && i < module.name.length; i++) view.setUint8(at + 8 + i, module.name.charCodeAt(i)) + } + return bytes +} + +async function readInventory(device: Reads) { + const first = await device.inventory(0) + if (first.offset !== 0 || first.data.length < INVENTORY_HEADER || + first.data[0] !== 0x4d || first.data[1] !== 0x57 || first.data[2] !== 0x49) + throw new Error('Invalid INVENTORY header') + const bytes = new Uint8Array(INVENTORY_HEADER + ENTRY_BYTES * first.data[3]) + let part = first + for (let offset = 0; ; part = await device.inventory(offset)) { + if (part.offset !== offset || !part.data.length || offset + part.data.length > bytes.length) + throw new Error('Invalid INVENTORY part') + bytes.set(part.data, offset) + offset += part.data.length + if (offset === bytes.length) return parseInventory(new DataView(bytes.buffer)) + } } -export function createMockDt2Device(wait: () => Promise = () => new Promise(resolve => setTimeout(resolve, 400))) { +export async function readDt2Snapshot(device: Reads): Promise { + const ident = await device.ident() + if (ident.model !== 'digitakt-ii' || !ident.link) throw new Error('Digitakt II link unavailable') + const hello = await device.hello() + if (!hello.activeKnown || !hello.active || !['normal', 'ready', 'trial'].includes(hello.phase)) + throw new Error('The active set is unknown') + + // The flashed set is a host-side build record. INVENTORY is the running set. + const saved = hello.base === BASE ? SAVED : [] + const modules = (await readInventory(device)).map(entry => ({ + ...entry, saved: saved.some(module => module.module === entry.module && module.layout === entry.layout), + })) + const trial = hello.phase === 'trial' ? { + names: modules.filter(entry => !entry.saved).map(entry => entry.name || entry.module), + previous: hello.base === BASE ? { names: saved.map(entry => entry.name), digest: SAVED_DIGEST } : undefined, + } : undefined + return { unitId: 'DT2-MOCK-01', os: ident.os, hello, modules, trial } +} + +export function createMockDt2Device(wait: () => Promise = () => new Promise(resolve => setTimeout(resolve, 85))) { let connected = true - let snapshot: Dt2Snapshot = { unitId: 'DT2-MOCK-01', os: '1.17', build: '7f31c2a0', modules: [savedModule] } + let trial = false - function restore() { - if (!snapshot.trial) return - const { trial, ...unit } = snapshot - snapshot = { ...unit, modules: trial.previous } + async function request() { + await wait() + if (!connected) throw new Error('Mock USB disconnected') } return { - async read() { - await wait() - if (!connected) throw new Error('Mock USB disconnected') - return snapshot + async ident() { + await request() + return { model: 'digitakt-ii', os: '1.17', link: true } + }, + async hello(): Promise { + await request() + return { base: BASE, session: SESSION, generation: trial ? 1 : 0, + phase: trial ? 'trial' : 'normal', activeKnown: true, active: trial ? TRIAL_DIGEST : SAVED_DIGEST } + }, + async inventory(offset: number): Promise { + await request() + const bytes = encodeInventory(trial ? TRIAL : SAVED) + if (!Number.isInteger(offset) || offset < 0 || offset >= bytes.length) throw new RangeError('Invalid INVENTORY offset') + return { offset, data: bytes.slice(offset, offset + PART_BYTES) } }, async tryInRam() { - await wait() - snapshot = { - ...snapshot, - modules: [...snapshot.modules, TRIAL_MODULE], - trial: { module: TRIAL_MODULE, previous: snapshot.modules }, - } + await request() + trial = true }, async undo(scenario: UndoScenario) { - await wait() - if (scenario !== 'drop-before-restore') restore() - // The box may have restored its previous modules even though the browser lost the reply. + await request() + if (scenario !== 'drop-before-restore') trial = false + // The box may restore the set before the link loses the reply. connected = scenario === 'standard' return connected }, From e2ddd10bcc2456256bc42a23d92e0a5c0114603a Mon Sep 17 00:00:00 2001 From: karigardarsson <10534568+karigardarsson@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:50:48 +0000 Subject: [PATCH 3/8] Define the shared client contract for the Digitakt II trial panel --- .../2026-12-04-digitakt-ii-trial-preview.md | 2 +- src/dev/Dt2TrialPreview.test.ts | 82 ++++++++++--- src/dev/Dt2TrialPreview.tsx | 111 ++++++++++-------- src/dev/dt2-trial-mock.ts | 88 ++++++++++---- src/engine/elektron/elektron-trial-client.ts | 51 ++++++++ 5 files changed, 245 insertions(+), 89 deletions(-) create mode 100644 src/engine/elektron/elektron-trial-client.ts diff --git a/changelog/2026-12-04-digitakt-ii-trial-preview.md b/changelog/2026-12-04-digitakt-ii-trial-preview.md index a5dc6535c9..c949f197e9 100644 --- a/changelog/2026-12-04-digitakt-ii-trial-preview.md +++ b/changelog/2026-12-04-digitakt-ii-trial-preview.md @@ -1 +1 @@ -Digitakt II: a local mock preview shows the running modules, tries a module in RAM and restores the previous set with Undo. If USB drops during Undo, the panel shows the last confirmed set and reads the unit’s active modules again on reconnect. Keep stays disabled. +Digitakt II: a local mock preview shows the box’s build, running modules and available actions. Try starts a RAM trial and Undo restores the previous set. If USB drops during Undo, the panel shows the last confirmed set and checks the session and active modules again on reconnect. Keep stays disabled. diff --git a/src/dev/Dt2TrialPreview.test.ts b/src/dev/Dt2TrialPreview.test.ts index 5c28a12c7e..63d825ab5c 100644 --- a/src/dev/Dt2TrialPreview.test.ts +++ b/src/dev/Dt2TrialPreview.test.ts @@ -2,8 +2,9 @@ import { act, createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { TrialCapabilities } from '../engine/elektron/elektron-trial-client' import Dt2TrialPreview from './Dt2TrialPreview' -import { createMockDt2Device, readDt2Snapshot } from './dt2-trial-mock' +import { createMockDt2Client, createMockDt2Device } from './dt2-trial-mock' let container: HTMLElement let root: Root @@ -28,17 +29,19 @@ afterEach(async () => { vi.unstubAllGlobals() }) -async function open() { - const device = createMockDt2Device() +async function open(actions?: TrialCapabilities) { + const device = createMockDt2Device(undefined, actions) const ident = vi.spyOn(device, 'ident') const hello = vi.spyOn(device, 'hello') const inventory = vi.spyOn(device, 'inventory') const undo = vi.spyOn(device, 'undo') - await act(() => root.render(createElement(Dt2TrialPreview, { makeDevice: () => device }))) + const mock = createMockDt2Client(device) + const reconnect = vi.spyOn(mock.client, 'reconnect') + await act(() => root.render(createElement(Dt2TrialPreview, { makeMock: () => mock }))) expect(text()).toContain('Reading the box') expect(button('Try').disabled).toBe(true) await settle() - return { device, ident, hello, inventory, undo } + return { device, ident, hello, inventory, undo, reconnect } } async function setScenario(value: string) { @@ -73,7 +76,7 @@ describe('Digitakt II trial preview', () => { expect(text()).toContain('Undoing trial') await settle() expect(ident).toHaveBeenCalledTimes(3) - expect(hello).toHaveBeenCalledTimes(3) + expect(hello).toHaveBeenCalledTimes(6) expect(inventory.mock.calls.flat()).toEqual([0, 16, 0, 16, 32, 48, 0, 16]) expect(modules()).toEqual(['Track Names']) expect(text()).toContain('Previous set restored') @@ -84,13 +87,13 @@ describe('Digitakt II trial preview', () => { ['drop-before-restore', ['Track Names', 'Chord Arp'], 'Box checked.', false], ['drop-after-restore', ['Track Names'], 'Previous set restored', true], ] as const)('reads actual mock state after %s without replaying Undo', async (scenario, expected, message, undoDisabled) => { - const { ident, hello, inventory, undo } = await open() + const { ident, hello, inventory, undo, reconnect } = await open() await click('Try') await settle() await setScenario(scenario) await click('Undo') await settle() - expect(hello).toHaveBeenCalledTimes(2) + expect(hello).toHaveBeenCalledTimes(4) expect(text()).toContain('USB disconnected') expect(text()).toContain('Last confirmed set') expect(text()).toContain('Undo result unknown') @@ -108,11 +111,20 @@ describe('Digitakt II trial preview', () => { expect(modules()).toEqual(['Track Names', 'Chord Arp']) await settle() expect(ident).toHaveBeenCalledOnce() - expect(hello).toHaveBeenCalledOnce() + expect(hello).toHaveBeenCalledTimes(2) expect(ident.mock.invocationCallOrder[0]).toBeLessThan(hello.mock.invocationCallOrder[0]) expect(hello.mock.invocationCallOrder[0]).toBeLessThan(inventory.mock.invocationCallOrder[0]) + expect(inventory.mock.invocationCallOrder.at(-1)).toBeLessThan(hello.mock.invocationCallOrder[1]) expect(inventory.mock.calls.flat()).toEqual(undoDisabled ? [0, 16] : [0, 16, 32, 48]) expect(undo).toHaveBeenCalledTimes(1) + expect(reconnect).toHaveBeenCalledOnce() + await expect(reconnect.mock.results[0].value).resolves.toMatchObject({ + build: { machine: 'digitakt-ii', os: '1.17', digest: '7f31c2a0'.repeat(8) }, + session: { continuity: 'same-session' }, + capabilities: { try: true, keep: false, undo: true }, + status: 'confirmed', + activeSet: { phase: undoDisabled ? 'normal' : 'trial', modules: expected.map(name => expect.objectContaining({ name })) }, + }) expect(text()).toContain('On the box') expect(text()).toContain(message) expect(text()).not.toContain('Undo result unknown') @@ -121,8 +133,9 @@ describe('Digitakt II trial preview', () => { expect(button('Keep').disabled).toBe(true) }) - it('keeps the last confirmed list through unknown HELLO and incomplete INVENTORY', async () => { - const { device, hello, inventory } = await open() + it('keeps the last confirmed list until HELLO and INVENTORY agree', async () => { + const { device, hello, inventory, reconnect } = await open() + const normal = await hello.mock.results.at(-1)!.value await click('Try') await settle() await setScenario('drop-after-restore') @@ -138,6 +151,15 @@ describe('Digitakt II trial preview', () => { expect(text()).toContain('Undo result unknown') expect(modules()).toEqual(['Track Names', 'Chord Arp']) + hello.mockResolvedValueOnce(normal).mockResolvedValueOnce({ ...normal, generation: normal.generation + 1 }) + await click('Reconnect') + await settle() + await expect(reconnect.mock.results.at(-1)!.value).resolves.toMatchObject({ + status: 'unconfirmed', reason: 'set-changed-during-read', + }) + expect(text()).toContain('Undo result unknown') + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + inventory.mockImplementationOnce(async () => ({ offset: 16, data: new Uint8Array([0x4d, 0x57, 0x49, 1]) })) await click('Reconnect') await settle() @@ -160,20 +182,44 @@ describe('Digitakt II trial preview', () => { [{ session: '99'.repeat(32) }, 'Box restarted'], [{ active: '99'.repeat(32) }, 'Box checked'], ] as const)('uses HELLO to qualify the Undo result with %j', async (field, result) => { - const { hello } = await open() + const { hello, reconnect } = await open() const normal = await hello.mock.results.at(-1)!.value await click('Try') await settle() await setScenario('drop-after-restore') await click('Undo') await settle() - hello.mockResolvedValueOnce({ ...normal, ...field }) + const returned = { ...normal, ...field } + hello.mockResolvedValueOnce(returned).mockResolvedValueOnce(returned) await click('Reconnect') await settle() + await expect(reconnect.mock.results[0].value).resolves.toMatchObject({ + status: 'confirmed', session: { continuity: 'session' in field ? 'new-session' : 'same-session' }, + }) expect(text()).toContain(result) expect(text()).not.toContain('Previous set restored') expect(modules()).toEqual(['Track Names']) }) + + it('disables actions the connected build does not support', async () => { + const { device, undo } = await open({ try: false, undo: false, keep: true }) + expect(text()).toContain('Try unavailable') + expect(button('Try').disabled).toBe(true) + expect(button('Keep').disabled).toBe(true) + + // Simulate a trial started elsewhere before opening the panel. + const writing = device.tryInRam() + await settle() + await writing + await act(() => root.render(createElement(Dt2TrialPreview, { + key: 'trial', makeMock: () => createMockDt2Client(device), + }))) + await settle() + expect(modules()).toEqual(['Track Names', 'Chord Arp']) + expect(button('Undo').disabled).toBe(true) + await click('Undo') + expect(undo).not.toHaveBeenCalled() + }) }) describe('mock INVENTORY wire record', () => { @@ -187,7 +233,15 @@ describe('mock INVENTORY wire record', () => { expect(bytes.slice(0, 4)).toEqual(Uint8Array.of(0x4d, 0x57, 0x49, 2)) expect(bytes.slice(28, 36)).toEqual(Uint8Array.of(0xff, 0, 0x12, 0x34, 0xec, 0xa8, 0x72, 0x2f)) expect(new TextDecoder().decode(bytes.slice(36, 52))).toBe('Chord Arp' + '\0'.repeat(7)) - expect((await readDt2Snapshot(device)).modules[1]).toMatchObject({ module: 'eca8722f', layout: 0x1234, name: 'Chord Arp' }) + const { client } = createMockDt2Client(device) + await expect(client.read()).resolves.toMatchObject({ + status: 'confirmed', + session: { continuity: 'first-read' }, + activeSet: { generation: 1, modules: [ + expect.objectContaining({ name: 'Track Names', source: 'saved' }), + { id: 'eca8722f', layout: 0x1234, name: 'Chord Arp', source: 'trial-ram' }, + ] }, + }) await expect(device.inventory(52)).rejects.toThrow('Invalid INVENTORY offset') }) }) diff --git a/src/dev/Dt2TrialPreview.tsx b/src/dev/Dt2TrialPreview.tsx index 82a8293b82..ae1fc4c955 100644 --- a/src/dev/Dt2TrialPreview.tsx +++ b/src/dev/Dt2TrialPreview.tsx @@ -1,7 +1,8 @@ import { useEffect, useState } from 'react' import { DeviceImage } from '../devices/DeviceImage' import { DEVICES_BY_ID } from '../devices/registry' -import { createMockDt2Device, readDt2Snapshot, TRIAL_MODULE, UNDO_SCENARIOS, type Dt2Snapshot, type UndoScenario } from './dt2-trial-mock' +import type { ConfirmedTrialReading, ElektronTrialClient, TrialReading } from '../engine/elektron/elektron-trial-client' +import { createMockDt2Client, TRIAL_MODULE, UNDO_SCENARIOS, type UndoScenario } from './dt2-trial-mock' import '../devices/devices.css' import '../components/octatrack-link.css' import './dt2-trial-preview.css' @@ -10,14 +11,21 @@ type Phase = 'reading' | 'ready' | 'trying' | 'undoing' | 'undo-unknown' | 'reco type Review = 'restored' | 'reread' | 'restarted' type Control = { phase: Phase - confirmed: Dt2Snapshot | null + confirmed: ConfirmedTrialReading | null + observed?: TrialReading review?: Review undoPending?: boolean } -function reviewUndo(before: Dt2Snapshot, after: Dt2Snapshot): Review { - if (after.hello.session !== before.hello.session) return 'restarted' - return !after.trial && after.hello.active === before.trial?.previous?.digest ? 'restored' : 'reread' +function showReading(reading: TrialReading, confirmed: Control['confirmed'], undoPending = false): Control { + if (reading.status === 'unconfirmed') return { phase: 'read-failed', confirmed, observed: reading, undoPending } + let review: Review | undefined + if (reading.session.continuity === 'new-session') review = 'restarted' + else if (undoPending && confirmed?.activeSet.phase === 'trial') { + review = reading.activeSet.phase === 'normal' && reading.activeSet.digest === confirmed.activeSet.rollback?.digest + ? 'restored' : 'reread' + } + return { phase: 'ready', confirmed: reading, review } } function trialMessage({ phase, confirmed, review, undoPending }: Control): [title: string, detail: string] { @@ -29,15 +37,18 @@ function trialMessage({ phase, confirmed, review, undoPending }: Control): [titl case 'reconnecting': return [undoPending ? 'Undo result unknown' : 'Reading the box…', 'Reading the box again to check what’s running…'] case 'read-failed': return [undoPending ? 'Undo result unknown' : 'Active set unconfirmed', 'The box’s active set could not be confirmed. Reconnect to read it again.'] case 'ready': { - const trial = confirmed?.trial - if (trial) { - const running = trial.names.length ? `Trial in RAM: ${trial.names.join(', ')}.` : 'A trial is running from RAM.' - const previous = trial.previous ? `the previous set: ${trial.previous.names.join(', ') || 'no modules'}` : 'the previous set' - return ['Trial active', `${review ? 'Box checked. ' : ''}${running} Undo restores ${previous}.`] + const active = confirmed?.activeSet + if (active?.phase === 'trial') { + const names = active.modules.filter(module => module.source === 'trial-ram').map(module => module.name) + const running = names.length ? `Trial in RAM: ${names.join(', ')}.` : 'A trial is running from RAM.' + const previous = active.rollback ? `the previous set: ${active.rollback.names.join(', ') || 'no modules'}` : 'the previous set' + const undo = confirmed?.capabilities.undo ? `Undo restores ${previous}.` : 'Undo is unavailable on this build.' + return ['Trial active', `${review ? 'Box checked. ' : ''}${running} ${undo}`] } if (review === 'restored') return ['Previous set restored', 'The box confirmed that the previous set is running.'] if (review === 'restarted') return ['Box restarted', 'The active modules were read from the new session.'] if (review === 'reread') return ['Box checked', 'The module list shows what the box reported after Undo.'] + if (!confirmed?.capabilities.try) return ['Try unavailable', 'This connection does not support starting a RAM trial.'] return [`Try ${TRIAL_MODULE}`, `Load ${TRIAL_MODULE} into RAM. You can undo the trial to restore the current set.`] } } @@ -51,10 +62,12 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o onUndo: () => void onReconnect: () => void }) { - const { phase, confirmed } = control + const { phase, confirmed, observed } = control const stale = phase === 'undo-unknown' || phase === 'reconnecting' || phase === 'read-failed' const pending = phase === 'trying' || phase === 'undoing' - const trial = confirmed?.trial + const build = observed?.build ?? confirmed?.build + const modules = confirmed?.activeSet.modules + const trial = confirmed?.activeSet.phase === 'trial' const [title, detail] = trialMessage(control) const linkLabel = phase === 'undo-unknown' ? 'USB disconnected' : phase === 'reconnecting' ? 'Reconnecting…' @@ -71,22 +84,22 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o

Digitakt II

- {confirmed &&
-
Unit
{confirmed.unitId}
-
OS
{confirmed.os}
-
{stale ? 'Last read base' : 'Base'}
{confirmed.hello.base.slice(0, 8)}
+ {build &&
+
Unit
DT2-MOCK-01
+
OS
{build.os}
+
{stale ? 'Last read base' : 'Base'}
{build.digest.slice(0, 8)}
}

{stale || pending ? 'Last confirmed set' : 'On the box'}

- {confirmed?.modules.length ?
    - {confirmed.modules.map(module => { - const inTrial = !!trial && !module.saved - return
  • + {modules?.length ?
      + {modules.map(module => { + const inTrial = module.source === 'trial-ram' + return
    • })}
    :

    {confirmed ? 'No modules running.' : stale ? 'No confirmed inventory.' : 'Reading active modules…'}

    } @@ -97,9 +110,9 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o

    {detail}

- {!stale && !trial && } + {!stale && !trial && } - {!stale && } + {!stale && } {stale && }

Keep requires a base that supports saving the set.

@@ -114,54 +127,50 @@ export function Dt2TrialPanel({ control, scenario, setScenario, onTry, onUndo, o
} -export default function Dt2TrialPreview({ makeDevice = createMockDt2Device }: { - makeDevice?: () => ReturnType +export default function Dt2TrialPreview({ makeMock = createMockDt2Client }: { + makeMock?: () => { client: ElektronTrialClient; setUndoScenario: (value: UndoScenario) => void } }) { - const [device] = useState(makeDevice) + const [{ client, setUndoScenario }] = useState(makeMock) const [scenario, setScenario] = useState('standard') const [control, setControl] = useState({ phase: 'reading', confirmed: null }) const { confirmed } = control useEffect(() => { let active = true - void readDt2Snapshot(device).then(snapshot => { - if (active) setControl({ phase: 'ready', confirmed: snapshot }) + void client.read().then(reading => { + if (active) setControl(showReading(reading, null)) }, () => { if (active) setControl({ phase: 'read-failed', confirmed: null }) }) return () => { active = false } - }, [device]) + }, [client]) - async function refresh(undoPending = false) { + async function refresh(mode: 'read' | 'reconnect', undoPending = false) { try { - const snapshot = await readDt2Snapshot(device) - setControl({ phase: 'ready', confirmed: snapshot, review: undoPending && confirmed ? reviewUndo(confirmed, snapshot) : undefined }) + const reading = await client[mode](confirmed?.session.id) + setControl(showReading(reading, confirmed, undoPending)) } catch { - setControl({ phase: 'read-failed', confirmed, undoPending }) + setControl({ phase: 'read-failed', confirmed, observed: control.observed, undoPending }) } } - async function startTrial() { - setControl({ phase: 'trying', confirmed }) - await device.tryInRam() - await refresh() - } - - async function undo() { - setControl({ phase: 'undoing', confirmed }) - if (!await device.undo(scenario)) { - setControl({ phase: 'undo-unknown', confirmed, undoPending: true }) - return + async function runAction(action: 'tryInRam' | 'undo') { + const undoPending = action === 'undo' + setControl({ phase: undoPending ? 'undoing' : 'trying', confirmed }) + try { + const result = await client[action]() + if (result === 'acknowledged') return await refresh('read', undoPending) + setControl({ phase: result === 'disconnected' && undoPending ? 'undo-unknown' : 'read-failed', confirmed, undoPending }) + } catch { + setControl({ phase: 'read-failed', confirmed, undoPending }) } - await refresh(true) } async function reconnect() { - setControl({ phase: 'reconnecting', confirmed, undoPending: control.undoPending }) - device.reconnect() - await refresh(control.undoPending) + setControl({ ...control, phase: 'reconnecting' }) + await refresh('reconnect', control.undoPending) } - return void startTrial()} onUndo={() => void undo()} onReconnect={() => void reconnect()} /> + return { setUndoScenario(value); setScenario(value) }} + onTry={() => void runAction('tryInRam')} onUndo={() => void runAction('undo')} onReconnect={() => void reconnect()} /> } diff --git a/src/dev/dt2-trial-mock.ts b/src/dev/dt2-trial-mock.ts index e17b36a4f7..6f0f474477 100644 --- a/src/dev/dt2-trial-mock.ts +++ b/src/dev/dt2-trial-mock.ts @@ -1,5 +1,6 @@ import { parseInventory, type MissingModule } from '../engine/elekloader/upload-usb' import type { UploadStatus } from '../engine/elekloader/upload-wire' +import type { ElektronTrialClient, TrialCapabilities, TrialReading } from '../engine/elektron/elektron-trial-client' export type UndoScenario = 'standard' | 'drop-before-restore' | 'drop-after-restore' @@ -17,6 +18,7 @@ const SAVED = [{ handle: 0xff, layout: 0, module: '7d2f8b1f', name: 'Track Names const CHORD_ARP = { handle: 0xff, layout: 0x1234, module: 'eca8722f', name: 'Chord Arp' } const TRIAL = [...SAVED, CHORD_ARP] export const TRIAL_MODULE = CHORD_ARP.name +const PANEL_ACTIONS: TrialCapabilities = { try: true, undo: true, keep: false } const INVENTORY_HEADER = 4 const ENTRY_BYTES = 24 @@ -24,15 +26,7 @@ const PART_BYTES = 16 // Deliberately crosses entry boundaries in this mock. type Hello = Pick type InventoryPart = { offset: number; data: Uint8Array } -type Reads = Pick, 'ident' | 'hello' | 'inventory'> - -export type Dt2Snapshot = { - unitId: string - os: string - hello: Hello - modules: Array - trial?: { names: string[]; previous?: { names: string[]; digest: string } } -} +type MockDevice = ReturnType function encodeInventory(modules: MissingModule[]) { const bytes = new Uint8Array(INVENTORY_HEADER + ENTRY_BYTES * modules.length) @@ -48,7 +42,7 @@ function encodeInventory(modules: MissingModule[]) { return bytes } -async function readInventory(device: Reads) { +async function readInventory(device: MockDevice) { const first = await device.inventory(0) if (first.offset !== 0 || first.data.length < INVENTORY_HEADER || first.data[0] !== 0x4d || first.data[1] !== 0x57 || first.data[2] !== 0x49) @@ -64,26 +58,74 @@ async function readInventory(device: Reads) { } } -export async function readDt2Snapshot(device: Reads): Promise { +async function readTrialState(device: MockDevice, previousSession?: string): Promise { const ident = await device.ident() if (ident.model !== 'digitakt-ii' || !ident.link) throw new Error('Digitakt II link unavailable') const hello = await device.hello() + const knownBuild = hello.base === BASE + const metadata: Pick = { + build: { machine: ident.model, os: ident.os, digest: hello.base }, + session: { id: hello.session, continuity: previousSession === undefined ? 'first-read' + : previousSession === hello.session ? 'same-session' : 'new-session' }, + // These flags are fixture metadata, not new IDENT fields on the wire. + capabilities: { + try: knownBuild && PANEL_ACTIONS.try && ident.actions.try, + undo: knownBuild && PANEL_ACTIONS.undo && ident.actions.undo, + keep: PANEL_ACTIONS.keep && knownBuild && ident.actions.keep, + }, + } if (!hello.activeKnown || !hello.active || !['normal', 'ready', 'trial'].includes(hello.phase)) - throw new Error('The active set is unknown') + return { ...metadata, status: 'unconfirmed', reason: 'unknown-active-set' } + + let entries: MissingModule[], end: Hello + try { + entries = await readInventory(device) + end = await device.hello() + } catch { + return { ...metadata, status: 'unconfirmed', reason: 'inventory-unavailable' } + } + // A rollback can happen while the host is reading the parts. + if (end.session !== hello.session || end.base !== hello.base || end.generation !== hello.generation || + end.phase !== hello.phase || !end.activeKnown || end.active !== hello.active) + return { ...metadata, status: 'unconfirmed', reason: 'set-changed-during-read' } // The flashed set is a host-side build record. INVENTORY is the running set. - const saved = hello.base === BASE ? SAVED : [] - const modules = (await readInventory(device)).map(entry => ({ - ...entry, saved: saved.some(module => module.module === entry.module && module.layout === entry.layout), - })) - const trial = hello.phase === 'trial' ? { - names: modules.filter(entry => !entry.saved).map(entry => entry.name || entry.module), - previous: hello.base === BASE ? { names: saved.map(entry => entry.name), digest: SAVED_DIGEST } : undefined, - } : undefined - return { unitId: 'DT2-MOCK-01', os: ident.os, hello, modules, trial } + const trial = hello.phase === 'trial' + const saved = knownBuild ? SAVED : [] + return { ...metadata, status: 'confirmed', activeSet: { + digest: hello.active, + generation: hello.generation, + modules: entries.map(entry => ({ + id: entry.module, layout: entry.layout, name: entry.name || entry.module, + source: saved.some(module => module.module === entry.module && module.layout === entry.layout) + ? 'saved' : trial ? 'trial-ram' : 'active', + })), + ...(trial ? { phase: 'trial', rollback: knownBuild ? { names: saved.map(entry => entry.name), digest: SAVED_DIGEST } : undefined } + : { phase: 'normal' }), + } } +} + +export function createMockDt2Client(device = createMockDt2Device()) { + let scenario: UndoScenario = 'standard' + const client: ElektronTrialClient = { + read: previousSession => readTrialState(device, previousSession), + async reconnect(previousSession) { + device.reconnect() + return readTrialState(device, previousSession) + }, + async tryInRam() { + await device.tryInRam() + return 'acknowledged' + }, + async undo() { + return await device.undo(scenario) ? 'acknowledged' : 'disconnected' + }, + } + return { client, setUndoScenario: (value: UndoScenario) => { scenario = value } } } -export function createMockDt2Device(wait: () => Promise = () => new Promise(resolve => setTimeout(resolve, 85))) { +export function createMockDt2Device(wait: () => Promise = () => new Promise(resolve => setTimeout(resolve, 85)), + actions: TrialCapabilities = PANEL_ACTIONS) { let connected = true let trial = false @@ -95,7 +137,7 @@ export function createMockDt2Device(wait: () => Promise = () => new Promis return { async ident() { await request() - return { model: 'digitakt-ii', os: '1.17', link: true } + return { model: 'digitakt-ii', os: '1.17', link: true, actions } }, async hello(): Promise { await request() diff --git a/src/engine/elektron/elektron-trial-client.ts b/src/engine/elektron/elektron-trial-client.ts new file mode 100644 index 0000000000..09606205f0 --- /dev/null +++ b/src/engine/elektron/elektron-trial-client.ts @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Try / Keep / Undo panel's view of the shared client, independent of the transport. + +export type TrialCapabilities = Readonly<{ try: boolean; keep: boolean; undo: boolean }> + +type ActiveModule = Readonly<{ + id: string + layout: number + name: string + source: 'saved' | 'trial-ram' | 'active' +}> + +type ActiveSet = Readonly<{ + digest: string + generation: number + modules: readonly ActiveModule[] +} & ( + { phase: 'normal' } | + { phase: 'trial'; rollback?: Readonly<{ digest: string; names: readonly string[] }> } +)> + +type BuildAndSession = Readonly<{ + build: Readonly<{ machine: 'digitakt-ii' | 'digitone-ii'; os: string; digest: string }> + session: Readonly<{ + id: string + // Relative to the last confirmed session on the selected unit. No serial or unit identity is implied. + continuity: 'first-read' | 'same-session' | 'new-session' + }> + // Client/profile and connected-build support. It does not say an action is safe in the current state. + capabilities: TrialCapabilities +}> + +export type TrialReading = BuildAndSession & ( + Readonly<{ status: 'confirmed'; activeSet: ActiveSet }> | + Readonly<{ status: 'unconfirmed'; reason: 'unknown-active-set' | 'inventory-unavailable' | 'set-changed-during-read' }> +) + +export type ConfirmedTrialReading = Extract +export type TrialActionResult = 'acknowledged' | 'unconfirmed' | 'disconnected' + +export interface ElektronTrialClient { + // Confirmed means the active-set identity and the full INVENTORY were read from a consistent session. + // A missing inventory may still yield build and session information. Link or identity failure may reject. + read(previousSession?: string): Promise + // Open a fresh connection and read it. A reconnect never replays the prior write. + reconnect(previousSession?: string): Promise + // The panel's client is bound to the current trial selection by its caller. + // An acknowledgement still requires read-back. 'disconnected' and 'unconfirmed' leave the write outcome unknown. + tryInRam(): Promise + undo(): Promise +} From 5c01c2e8fc4bacb9ca136d5fb221e56a1ddf7424 Mon Sep 17 00:00:00 2001 From: karigardarsson <10534568+karigardarsson@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:30:40 +0000 Subject: [PATCH 4/8] Mount the Digitakt II mock on the shared beta unit page --- .../2026-12-04-digitakt-ii-trial-preview.md | 2 +- src/App.tsx | 17 ++-- src/components/ModelCyclesUnit.tsx | 85 +++++++++++-------- src/components/OctatrackHub.tsx | 15 ++-- src/components/UnitStatusHero.tsx | 17 ++++ src/dev/Dt2TrialPreview.test.ts | 16 +++- src/dev/Dt2TrialPreview.tsx | 30 +++---- src/dev/Dt2UnitRoute.test.ts | 79 +++++++++++++++++ src/dev/dt2-trial-preview.css | 29 ++----- src/devices/MachinePages.tsx | 9 +- src/devices/registry.ts | 2 + src/main.tsx | 8 +- 12 files changed, 207 insertions(+), 102 deletions(-) create mode 100644 src/components/UnitStatusHero.tsx create mode 100644 src/dev/Dt2UnitRoute.test.ts diff --git a/changelog/2026-12-04-digitakt-ii-trial-preview.md b/changelog/2026-12-04-digitakt-ii-trial-preview.md index c949f197e9..cb3857a3e3 100644 --- a/changelog/2026-12-04-digitakt-ii-trial-preview.md +++ b/changelog/2026-12-04-digitakt-ii-trial-preview.md @@ -1 +1 @@ -Digitakt II: a local mock preview shows the box’s build, running modules and available actions. Try starts a RAM trial and Undo restores the previous set. If USB drops during Undo, the panel shows the last confirmed set and checks the session and active modules again on reconnect. Keep stays disabled. +Digitakt II: the local beta Status page shows the mock box’s build and running modules. Try starts a RAM trial and Undo restores the previous set. If USB drops during Undo, the page shows the last confirmed set and reads the active modules again on reconnect. Keep stays disabled. diff --git a/src/App.tsx b/src/App.tsx index 58a56785dc..5032831cf0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -84,7 +84,7 @@ import { ZoomEffectDetail } from './devices/ZoomEffectDetail' import { ZOOM_EFFECTS, isZoomSetDevice } from './devices/zoom-effects' import { LibraryDock } from './components/LibraryDock' import { LibrarySelection } from './components/LibrarySelection' -import { ALL_MACHINES, DEVICES, DEVICES_BY_ID, MC_UNIT_ROUTE, RYTM_UNIT_ROUTE, deviceHref, lastMachine, parseDeviceRoute, rememberDevice, rememberedDevice, type DeviceProfile } from './devices/registry' +import { ALL_MACHINES, DEVICES, DEVICES_BY_ID, DT2_UNIT_ROUTE, MC_UNIT_ROUTE, RYTM_UNIT_ROUTE, deviceHref, lastMachine, parseDeviceRoute, rememberDevice, rememberedDevice, type DeviceProfile } from './devices/registry' import { sidebarMachine } from './devices/sidebar-machine' import { parseZoomHubRoute, zoomHubHref } from './devices/zoom-hub-route' import type { ZoomLink } from './engine/zoom/zoom-link' @@ -116,6 +116,7 @@ const OctatrackHub = lazy(() => beta().then(module => ({ default: module.Octatra const ZoomHub = lazy(() => beta().then(module => ({ default: module.ZoomHub }))) const ModelCyclesUnit = lazy(() => beta().then(module => ({ default: module.ModelCyclesUnit }))) const RytmUnit = lazy(() => beta().then(module => ({ default: module.RytmUnit }))) +const Dt2TrialUnit = import.meta.env.DEV ? lazy(() => import('./dev/Dt2TrialPreview')) : () => null const ZoomSidebarStatus = lazy(() => beta().then(module => ({ default: module.ZoomSidebarStatus }))) const ZoomBaseDialog = lazy(() => beta().then(module => ({ default: module.ZoomBaseDialog }))) const LoadDialog = lazy(() => beta().then(module => ({ default: module.LoadDialog }))) @@ -185,6 +186,7 @@ export default function App() { const presence = useMembersOnline(), online = presence?.online ?? null const { session, loading: sessionLoading, developer, catalog } = useCommunity() const betaAccess = hasBetaAccess(session), accessibleModules = listedModules(betaAccess), betaUi = hasBetaUi(session) + const dt2MockUnit = import.meta.env.DEV && betaUi && moduleRoute === DT2_UNIT_ROUTE const detailModule = moduleRoute.startsWith('module/') ? accessibleModules.find((module) => module.id === moduleRoute.slice(7)) : undefined const pausedModule = MODULES.find(module => isModulePaused(module.id) && !isModuleAvailable(module.id, betaAccess) && !isModuleListedPaused(module.id, betaAccess) && (moduleRoute === 'module/' + module.id || moduleRoute === 'community-module/' + module.id)) const configuration = route === 'octatrack/set' @@ -210,7 +212,7 @@ export default function App() { // The Octatrack base path's interface (module sets, the hub, sync, base install; one switch releases it) and the rest // of the beta (the beta-only Zoom pedal pages): beta testers, verified administrators and dev builds; else main's. const octatrackUi = hasOctatrackBase(session), w = setWords(octatrackUi) - const usbAllowed = !mobileWorkspace && hasUsbLinkAccess(session, touchOnly) && !usbLinkPreview && usbPreview !== 'diagnostics' + const usbAllowed = !dt2MockUnit && !mobileWorkspace && hasUsbLinkAccess(session, touchOnly) && !usbLinkPreview && usbPreview !== 'diagnostics' // This member can sync over USB here: the base path is open to them and this browser reaches the unit (not Firefox, // Safari or a phone). Without it the module set goes onto the unit as the card file. const usbBrowser = browserHasUsb(touchOnly, mobileWorkspace) @@ -279,9 +281,12 @@ export default function App() { // A Zoom pedal's page (ZoomHub.tsx): #/pedal, over its own Web MIDI link; who may open it is zoomHub's below. // A pedal page: open to everyone for a pedal whose effects the library lists (the MS-70CDR), beta for the others. const zoomRoute = parseZoomHubRoute(moduleRoute), zoomHub = zoomRoute && (betaUi || isZoomSetDevice(zoomRoute.device.id)) ? zoomRoute : undefined - // The Model:Cycles' and the Analog Rytm MKII's page (ModelCyclesUnit.tsx): Status over their link, beta only. A Rytm - // module is never called "unit", so #analog-rytm-mkii/unit reaches no module page first. - const unitDevice = !betaUi ? undefined : moduleRoute === MC_UNIT_ROUTE ? 'model-cycles' : moduleRoute === RYTM_UNIT_ROUTE ? 'analog-rytm-mkii' : undefined + // The shared Elektron Status page (ModelCyclesUnit.tsx), beta only. The DT2 route is a local mock. + const unitDevice = !betaUi ? undefined : dt2MockUnit ? 'digitakt-ii' + : moduleRoute === MC_UNIT_ROUTE ? 'model-cycles' : moduleRoute === RYTM_UNIT_ROUTE ? 'analog-rytm-mkii' : undefined + const elektronUnit = unitDevice === 'digitakt-ii' ? + : unitDevice === 'analog-rytm-mkii' ? + : unitDevice === 'model-cycles' ? : null const mcUnit = !!unitDevice const unitPageName = zoomHub?.device.name ?? (unitDevice ? DEVICES_BY_ID[unitDevice].name : undefined) useEffect(() => { if (zoomHub && !mobileWorkspace) void beta().then(module => setZoomLink(link => link ?? module.createZoomLink())).catch(console.error) }, [!!zoomHub, mobileWorkspace]) // eslint-disable-line react-hooks/exhaustive-deps @@ -727,7 +732,7 @@ export default function App() { {projectsRoute ? : faqRoute ? : route === 'credits' ? : stabilityViewRoute ? Loading the Stability view…

}>
: route === 'support' ? : route === 'base' ? : overviewRoute ? : !ready ?
Opening your workspace…
: <> {onLibrary ? setQuery('')} onBrowse={rememberBrowse} device={allMachines ? undefined : currentDevice} machinePicker={phoneLayout ? undefined : machinePicker} phone={phoneLayout} resultsSlot={resultsSlot} query={query} category={libraryCategory as ModuleCategory | undefined} octatrackModules={visibleModules} family={family} onFamilyChange={setFamily} liveOnly={liveOnly} onLiveOnlyChange={setLiveOnly} sort={sort} onSortChange={setSort} statistics={statistics} octatrackBlocks={addBlockMap} onSwapOctatrack={swapModule} comparison={comparison} onCompare={toggleComparison} onOpenComparison={() => setCompareOpen(true)} viewedModuleVersions={viewedModuleVersions} moduleBaseline={moduleBaseline} octatrackSelected={selectedIds} onToggleOctatrack={toggleModule} digiSelected={digiSelected} onToggleDigi={(device, id) => workspace.toggleModule(id, device)} zoomSelected={zoomSelected} onToggleZoom={(device, id) => workspace.toggleModule(id, device)} onClearSearch={() => { setQuery(''); setFamily('all'); setLiveOnly(false) }}> {!allMachines && currentDevice.id === 'octatrack' && !!catalog.filter((item,index,items)=>!MODULES.some(module=>module.id===item.module_id)&&items.findIndex(other=>other.module_id===item.module_id)===index).length &&

Community modules

{catalog.filter((item,index,items)=>!MODULES.some(module=>module.id===item.module_id)&&items.findIndex(other=>other.module_id===item.module_id)===index).sort((a,b)=>compareModules({id:a.module_id,name:a.title,authorName:a.author,addedAt:a.added_at??undefined,updatedAt:a.updated_at??undefined},{id:b.module_id,name:b.title,authorName:b.author,addedAt:b.added_at??undefined,updatedAt:b.updated_at??undefined},sort,statistics)).map(item=>)}
} -
: digiDevice && digiMod ? toggleMachineModule(digiMod.id)} /> : zoomEffect ? toggleMachineModule(zoomEffect.id)} /> : digiDevice && machineView === 'configuration' ? machineActive && setReportingConfiguration({ machine: digiDevice.id, id: machineActive.id })} device={digiDevice} configuration={machineActive} configurations={machineConfigurations} onSelect={id => { workspace.selectConfiguration(id) }} onDialog={setConfigDialog} onToggle={toggleMachineModule} onImport={item => workspace.importConfiguration(item.name,item.moduleIds,false,item.moduleVersions,digiDevice.id,undefined,undefined,undefined,item.storageLock)} onStorageLock={workspace.saveStorageLock} /> : missingRoute?

{pausedModule ? 'Module temporarily unavailable' : 'Page not found'}

{pausedModule ? pausedModule.name + ' is temporarily unavailable.' : 'This module or page is not in the current catalog.'}

Open module library
:unitDevice?{unitDevice === 'analog-rytm-mkii' ? : }:zoomHub? setZoomInstall(true)} {...isZoomSetDevice(zoomHub.device.id) ? { sets: configurationsFor(zoomHub.device.id), selectedId: activeFor(zoomHub.device.id)?.id, onSelect: (id: string) => { workspace.selectConfiguration(id); window.location.assign(zoomHubHref(zoomHub.device.id, 'set')) }, onNew: () => newConfiguration(zoomHub.device.id), onSetAction: setAction, onToggle: (effect: string) => workspace.toggleModule(effect, zoomHub.device.id) } : {}} />:hubRoute?hubPage:route==='module-sets'||route.startsWith('module-set/')?(octatrackUi ? : {workspace.importConfiguration(name,ids);openEditedSet('octatrack')}}/>):forumRoute ? {const device=config.device??'octatrack';workspace.importConfiguration(config.name,config.moduleIds,config.keepStockFx2,config.moduleVersions,device,config.usbAudio);openEditedSet(device)}}/> : developerRoute ? : accountRoute ? betaInvitationRoute ? : : route === 'privacy' ? : ['impressum','community-rules','modding-guidelines','report-content'].includes(route) ? : route.startsWith('submit') ? : adminRoute ? : communityModule ? : detailModule ? item.module_id === detailModule.id)} selected={selectedIds.includes(detailModule.id)} addBlock={addBlockMap[detailModule.id]} onSwap={removeIds => swapModule(detailModule.id, removeIds)} usbAudio={active?.usbAudio} configurationName={active?.name} configurationId={active?.id} onConfigureUsbAudio={configureUsbAudio} onToggle={() => toggleModule(detailModule.id)} /> : null} + : digiDevice && digiMod ? toggleMachineModule(digiMod.id)} /> : zoomEffect ? toggleMachineModule(zoomEffect.id)} /> : digiDevice && machineView === 'configuration' ? machineActive && setReportingConfiguration({ machine: digiDevice.id, id: machineActive.id })} device={digiDevice} configuration={machineActive} configurations={machineConfigurations} onSelect={id => { workspace.selectConfiguration(id) }} onDialog={setConfigDialog} onToggle={toggleMachineModule} onImport={item => workspace.importConfiguration(item.name,item.moduleIds,false,item.moduleVersions,digiDevice.id,undefined,undefined,undefined,item.storageLock)} onStorageLock={workspace.saveStorageLock} /> : missingRoute?

{pausedModule ? 'Module temporarily unavailable' : 'Page not found'}

{pausedModule ? pausedModule.name + ' is temporarily unavailable.' : 'This module or page is not in the current catalog.'}

Open module library
:elektronUnit?{elektronUnit}:zoomHub? setZoomInstall(true)} {...isZoomSetDevice(zoomHub.device.id) ? { sets: configurationsFor(zoomHub.device.id), selectedId: activeFor(zoomHub.device.id)?.id, onSelect: (id: string) => { workspace.selectConfiguration(id); window.location.assign(zoomHubHref(zoomHub.device.id, 'set')) }, onNew: () => newConfiguration(zoomHub.device.id), onSetAction: setAction, onToggle: (effect: string) => workspace.toggleModule(effect, zoomHub.device.id) } : {}} />:hubRoute?hubPage:route==='module-sets'||route.startsWith('module-set/')?(octatrackUi ? : {workspace.importConfiguration(name,ids);openEditedSet('octatrack')}}/>):forumRoute ? {const device=config.device??'octatrack';workspace.importConfiguration(config.name,config.moduleIds,config.keepStockFx2,config.moduleVersions,device,config.usbAudio);openEditedSet(device)}}/> : developerRoute ? : accountRoute ? betaInvitationRoute ? : : route === 'privacy' ? : ['impressum','community-rules','modding-guidelines','report-content'].includes(route) ? : route.startsWith('submit') ? : adminRoute ? : communityModule ? : detailModule ? item.module_id === detailModule.id)} selected={selectedIds.includes(detailModule.id)} addBlock={addBlockMap[detailModule.id]} onSwap={removeIds => swapModule(detailModule.id, removeIds)} usbAudio={active?.usbAudio} configurationName={active?.name} configurationId={active?.id} onConfigureUsbAudio={configureUsbAudio} onToggle={() => toggleModule(detailModule.id)} /> : null} } diff --git a/src/components/ModelCyclesUnit.tsx b/src/components/ModelCyclesUnit.tsx index 1fd745aedb..4154fd8a39 100644 --- a/src/components/ModelCyclesUnit.tsx +++ b/src/components/ModelCyclesUnit.tsx @@ -1,6 +1,5 @@ import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react' -import { DeviceImage } from '../devices/DeviceImage' -import { MC_UNIT_ROUTE, RYTM_UNIT_ROUTE, deviceHref, type DeviceProfile } from '../devices/registry' +import { DT2_UNIT_ROUTE, MC_UNIT_ROUTE, RYTM_UNIT_ROUTE, deviceHref, type DeviceProfile } from '../devices/registry' import { findUnit, type MidiAccessLike } from '../engine/elektron/os-upgrade-midi' import { readMcLog, readMcStatus, type McLoad, type McModules } from '../engine/elektron/mc-link' import { RYTM_PORT, readRytmLog, readRytmStatus } from '../engine/elektron/rytm-link' @@ -12,6 +11,7 @@ import { browserMidi } from '../engine/elektron/usb-upgrade' import { useMobileWorkspace } from '../hooks/useMobileWorkspace' import { Icon } from './Icon' import { LoadChart, Meter } from './OctatrackLoad' +import { UnitStatusHero } from './UnitStatusHero' import './octatrack-link.css' import './octatrack-load.css' @@ -24,13 +24,16 @@ export type UnitStatus = { } /** A machine the page reads over its link: the model name its USB MIDI port carries, its reader, its route, and how * its audio note reads. */ -export type UnitKind = { port: string; route: string; read: (access: MidiAccessLike) => Promise; audio: string +type MidiUnitKind = { port: string; route: string; read: (access: MidiAccessLike) => Promise; audio: string /** The unit's own log, shared with the member's diagnostics (octatrack-diagnostics.ts reportDeviceLog). */ log?: { machine: DiagnosticLogMachine; read: (access: MidiAccessLike, stop: () => boolean) => Promise<{ log: DeviceLog | undefined } | 'unsupported' | null> } } -export const MC_UNIT: UnitKind = { port: 'Model:Cycles', route: MC_UNIT_ROUTE, read: access => readMcStatus(access), audio: 'the six tracks’ sound takes', +type MockUnitKind = { route: string; source: 'mock' } +export type UnitKind = MidiUnitKind | MockUnitKind +export const MC_UNIT: MidiUnitKind = { port: 'Model:Cycles', route: MC_UNIT_ROUTE, read: access => readMcStatus(access), audio: 'the six tracks’ sound takes', log: { machine: 'model-cycles', read: (access, stop) => readMcLog(access, 2000, stop) } } -export const RYTM_UNIT: UnitKind = { port: RYTM_PORT, route: RYTM_UNIT_ROUTE, read: access => readRytmStatus(access), audio: 'the voices, the sample playback and the FX take', +export const RYTM_UNIT: MidiUnitKind = { port: RYTM_PORT, route: RYTM_UNIT_ROUTE, read: access => readRytmStatus(access), audio: 'the voices, the sample playback and the FX take', log: { machine: 'analog-rytm-mkii', read: (access, stop) => readRytmLog(access, 2000, stop) } } +export const DT2_UNIT: MockUnitKind = { route: DT2_UNIT_ROUTE, source: 'mock' } const INTERVAL = 2000, HISTORY = 150 const SERIES: { key: 'audio' | 'block'; title: string; className: string }[] = [{ key: 'audio', title: 'Audio', className: 'load-core1' }, { key: 'block', title: 'Busiest block', className: 'load-cpu' }] @@ -44,7 +47,7 @@ const kb = (bytes: number) => (bytes / 1024).toFixed(1) + ' KB' /** Reads the unit every two seconds once MIDI is allowed: identity, live modules and load over one line each time. * A load window that hasn't moved is a gap. shortcut: kept while this page is open, not app-wide as the Octatrack's; * record it across pages when someone needs that. */ -function useUnit(kind: UnitKind, request: (() => Promise) | null) { +function useUnit(kind: MidiUnitKind, request: (() => Promise) | null) { const [access, setAccess] = useState() const [state, setState] = useState<{ status: Status; read?: UnitStatus; points: Point[]; now: number; error?: string }>({ status: request ? 'idle' : 'unsupported', points: [], now: 0 }) useEffect(() => { @@ -85,6 +88,7 @@ function useUnit(kind: UnitKind, request: (() => Promise) | null } type UnitProps = { device: DeviceProfile; header?: ReactNode; request?: (() => Promise) | null } +type UnitConnection = { line: ReactNode; led: string; details?: ReactNode; action?: ReactNode } /** Your Model:Cycles (mc-link.ts). */ export const ModelCyclesUnit = (props: UnitProps) => /** Your Analog Rytm MKII (rytm-link.ts). */ @@ -92,10 +96,39 @@ export const RytmUnit = (props: UnitProps) => & { kind: MockUnitKind; connection: UnitConnection; children: ReactNode })) { + if ('connection' in props) return + {props.children} + + return +} + +function UnitFrame({ device, header, route, connection, children }: { + device: DeviceProfile; header?: ReactNode; route: string; connection: UnitConnection; children: ReactNode +}) { + return
+ {header ??

Your {device.name}

} +
+ {connection.details} + +
{children}
+
+
+} + +function MidiUnit({ device, header, request = browserMidi(), kind }: UnitProps & { kind: MidiUnitKind }) { const mobile = useMobileWorkspace() const { status, read, points, now, error, connect, clear } = useUnit(kind, request) const sharing = useSyncExternalStore(subscribeDiagnosticPreference, diagnosticPreference, diagnosticPreference).enabled, privacy = browserRequestsPrivacy() @@ -117,28 +150,12 @@ export function ElektronUnit({ device, header, request = browserMidi(), kind }:

Your {device.name}

Connecting your {device.name} needs Chrome or Edge on a computer.

Open {device.name} page - return
- {header ??

Your {device.name}

} -
-
- -

{device.name}

-

- {error &&

{error}

} -
- {status === 'idle' && } -
- -
-
+ return {error}

, + action: status === 'idle' && , + }}> +
@@ -165,8 +182,6 @@ export function ElektronUnit({ device, header, request = browserMidi(), kind }: {!ready ? offCell : !modules?.modules.length ?

{modules ? 'No modules loaded. Modules kept over USB show here until the next power cycle.' : 'This base loads no modules over USB.'}

:
    {modules.modules.map(module =>
  • )}
}
-
-
-
- + + } diff --git a/src/components/OctatrackHub.tsx b/src/components/OctatrackHub.tsx index a0bb0a260d..483ef09589 100644 --- a/src/components/OctatrackHub.tsx +++ b/src/components/OctatrackHub.tsx @@ -8,7 +8,6 @@ import { BaseLayoutRequired, BaseUpdateRequired, baseOutdated, moduleSetReview, import { baseLayout, baseVersion, type BaseLayout } from '../engine/elekloader/base-variants' import { comesWithBase } from '../config/usb-audio' import type { Configuration } from '../config/workspace' -import { DeviceImage } from '../devices/DeviceImage' import { DEVICES_BY_ID } from '../devices/registry' import { LINK_BUSY, type OctatrackLink } from '../engine/elekloader/octatrack-link' import { useOctatrackHealth } from '../hooks/useOctatrackHealth' @@ -18,6 +17,7 @@ import { HubSetHead, HubSetList, SetMenu, type SetAction } from './HubSets' import { Icon, type IconName } from './Icon' import { OctatrackBackups } from './OctatrackBackups' import { CardSetButton } from './UnitPanel' +import { UnitStatusHero } from './UnitStatusHero' import { OctatrackDiagnosticsSettings } from './OctatrackDiagnostics' import { SupportActions } from './SupportActions' import { OctatrackOverview } from './OctatrackOverview' @@ -158,19 +158,16 @@ function DesktopOctatrackHub({ view, link, inventory, sets, selectedId, needs, u return
{header}
-
- -

{model}

- {/* While not connected, Screen gives its own detail beside the preview, so the hint stays off it. */} -

+ {/* While not connected, Screen gives its own detail beside the preview, so the hint stays off it. */} + {line}{hint && (!screenView || connected) && {hint}}} + action={!screenView && action}> {state.notice?.tone === 'error' && hint === state.notice.text && } {connected &&
Base
{baseVersion(identity!.base) ?? {identity!.base.slice(0, 8)}}
{lastSync &&
Last sync here
{lastSync.name} ·
}
} -
- {!screenView && action} -
+