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..cb3857a3e3
--- /dev/null
+++ b/changelog/2026-12-04-digitakt-ii-trial-preview.md
@@ -0,0 +1 @@
+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=>
Reviewed contribution {item.description}
stats.module_id===item.module_id)}/>View module → )}
}
- : 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 ??
}
+
+
{connection.details}
+
+
+
+
+
+
+}
+
+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 ??
}
-
-
-
- {device.name}
-
{line}
- {error &&
{error}
}
-
- {status === 'idle' && Connect }
-
-
-
-
-
-
+ return
{error},
+ action: status === 'idle' && Connect ,
+ }}>
+
@@ -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 => {module.name || 'Unnamed module'} {module.id} )} }
-
-
-
-
+
+
}
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. */}
-
{line}{hint && (!screenView || connected) && {hint} }
+ {/* 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} · {when(lastSync.at)} }
}
-
- {!screenView && action}
-
+
{ const value = event.target.value; if (value.startsWith('set:')) onSelect(value.slice(4)); else window.location.hash = UNIT_VIEWS.find(item => item.view === value)!.href }}>
{NAV_VIEWS.map(item => {item.title} )}
diff --git a/src/components/UnitStatusHero.tsx b/src/components/UnitStatusHero.tsx
new file mode 100644
index 0000000000..d5cc18638e
--- /dev/null
+++ b/src/components/UnitStatusHero.tsx
@@ -0,0 +1,17 @@
+import type { ReactNode } from 'react'
+import type { DeviceProfile } from '../devices/registry'
+import { DeviceImage } from '../devices/DeviceImage'
+
+export function UnitStatusHero({ device, title = device.name, led, line, action, children }: {
+ device: DeviceProfile; title?: string; led: string; line: ReactNode; action?: ReactNode; children?: ReactNode
+}) {
+ return
+
+
+
{title}
+
{line}
+ {children}
+
+ {action}
+
+}
diff --git a/src/dev/Dt2TrialPreview.test.ts b/src/dev/Dt2TrialPreview.test.ts
new file mode 100644
index 0000000000..d0e611789b
--- /dev/null
+++ b/src/dev/Dt2TrialPreview.test.ts
@@ -0,0 +1,418 @@
+// @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 { encodeUploadRequest, ZERO_DIGEST } from '../engine/elekloader/upload-wire'
+import { LINK_COMMANDS, linkRequest, unpack7 } from '../engine/elektron/dn2-link'
+import type { TrialCapabilities } from '../engine/elektron/elektron-trial-client'
+import Dt2TrialPreview from './Dt2TrialPreview'
+import { createMockDt2Client, createMockDt2Device } from './dt2-trial-mock'
+
+vi.mock('../engine/elektron/usb-upgrade', async original => ({
+ ...await original(),
+ browserMidi: () => { throw new Error('The mock Status page must not initialize browser MIDI') },
+}))
+
+let container: HTMLElement
+let root: Root
+const statusPage = () => container.querySelector('section[aria-label="Status"]')!
+const text = () => container.textContent
+const button = (name: string) => [...statusPage().querySelectorAll('button')].find(item => item.textContent === name)!
+const click = (name: string) => act(() => button(name).click())
+const settle = () => act(() => vi.runAllTimersAsync())
+const modules = () => [...statusPage().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(actions?: TrialCapabilities) {
+ const device = createMockDt2Device(undefined, actions)
+ const readPart = device.inventory
+ const checkLink = vi.spyOn(device, 'checkLink')
+ const hello = vi.spyOn(device, 'hello')
+ const inventory = vi.spyOn(device, 'inventory')
+ const undo = vi.spyOn(device, 'undo')
+ const tryInRam = vi.spyOn(device, 'tryInRam')
+ const sent: Uint8Array[] = []
+ const openLine = device.reconnect
+ const openReconnectLine = vi.spyOn(device, 'reconnect').mockImplementation(() => {
+ const line = openLine()
+ const send = line.send
+ line.send = frame => { sent.push(frame); send(frame) }
+ return line
+ })
+ const mock = createMockDt2Client(device)
+ const reconnect = vi.spyOn(mock.client, 'reconnect')
+ await act(() => root.render(createElement(Dt2TrialPreview, { makeMock: () => mock })))
+ expect(container.querySelector('nav[aria-label="Your Digitakt II"] a[aria-current="page"]')?.getAttribute('href')).toBe('#digitakt-ii/unit')
+ expect(statusPage().closest('.hub-pane')).not.toBeNull()
+ expect(text()).toContain('Reading the box')
+ expect(button('Try').disabled).toBe(true)
+ await settle()
+ return { device, checkLink, hello, inventory, undo, tryInRam, reconnect, openReconnectLine, readPart, sent }
+}
+
+function expectReconnectReads(sent: Uint8Array[], reads: readonly ('ident' | 'hello')[]) {
+ expect(sent).toHaveLength(reads.length)
+ for (const [index, command] of reads.entries()) {
+ const frame = sent[index]
+ if (command === 'ident') expect(frame).toEqual(linkRequest(frame[6], 'ident'))
+ else {
+ expect(frame[7]).toBe(LINK_COMMANDS.upload)
+ expect(unpack7(frame.subarray(8, -1))).toEqual(encodeUploadRequest({ command: 'hello' }))
+ }
+ }
+}
+
+async function setScenario(value: string) {
+ const picker = statusPage().querySelector('select')!
+ await act(() => {
+ picker.value = value
+ picker.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+}
+
+describe('Digitakt II beta Status page', () => {
+ it('reads the box, tries in RAM and verifies that Undo restores the prior set', async () => {
+ const { checkLink, hello, inventory } = 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(checkLink).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')
+ 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 { checkLink, hello, inventory, undo, tryInRam, reconnect, sent } = await open()
+ await click('Try')
+ await settle()
+ await setScenario(scenario)
+ await click('Undo')
+ await settle()
+ expect(hello).toHaveBeenCalledTimes(4)
+ 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)
+
+ checkLink.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(checkLink).toHaveBeenCalledOnce()
+ expect(hello).toHaveBeenCalledTimes(2)
+ expect(checkLink.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(tryInRam).toHaveBeenCalledOnce()
+ expect(undo).toHaveBeenCalledOnce()
+ expectReconnectReads(sent, ['ident', 'hello', 'hello'])
+ 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('Reconnected to the same session.')
+ 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)
+ })
+
+ it.each([
+ ['missing', 'drop-no-reply'],
+ ['truncated', 'drop-after-restore'],
+ ] as const)('stops at a %s IDENT reply and lets Reconnect try again', async (failure, scenario) => {
+ const { hello, inventory, undo, tryInRam, openReconnectLine, sent } = await open()
+ await click('Try')
+ await settle()
+ await setScenario(scenario)
+ await click('Undo')
+ await settle()
+
+ if (failure === 'truncated') {
+ const openLine = openReconnectLine.getMockImplementation()!
+ openReconnectLine.mockImplementationOnce(() => {
+ const line = openLine()
+ const next = line.next
+ line.next = async ms => {
+ const reply = await next(ms)
+ // Keep the matching SysEx header and success status, but omit the IDENT counters.
+ return reply?.[7] === (LINK_COMMANDS.ident | 0x40) ? Uint8Array.of(...reply.subarray(0, 9), 0xf7) : reply
+ }
+ return line
+ })
+ }
+ hello.mockClear()
+ inventory.mockClear()
+ await click('Reconnect')
+ await settle()
+ expectReconnectReads(sent, ['ident'])
+ expect(hello).not.toHaveBeenCalled()
+ expect(inventory).not.toHaveBeenCalled()
+ expect(text()).toContain('Device state unconfirmed')
+ expect(text()).toContain('Reconnect reply unconfirmed.')
+ expect(text()).toContain('Undo result unknown')
+ expect(text()).toContain('Last confirmed set')
+ expect(modules()).toEqual(['Track Names', 'Chord Arp'])
+ expect(button('Reconnect').disabled).toBe(false)
+ expect(button('Keep').disabled).toBe(true)
+
+ await click('Reconnect')
+ await settle()
+ expectReconnectReads(sent, ['ident', 'ident', 'hello', 'hello'])
+ expect(tryInRam).toHaveBeenCalledOnce()
+ expect(undo).toHaveBeenCalledOnce()
+ expect(text()).toContain('Previous set restored')
+ expect(text()).toContain('On the box')
+ expect(modules()).toEqual(['Track Names'])
+ expect(button('Keep').disabled).toBe(true)
+ })
+
+ it('replaces the last confirmed set when reconnect confirms an empty inventory', async () => {
+ const { hello, inventory, tryInRam } = await open()
+ const initial = await hello.mock.results.at(-1)!.value
+ tryInRam.mockRejectedValueOnce(new Error('Mock USB disconnected'))
+ await click('Try')
+ await settle()
+ expect(text()).toContain('Last confirmed set')
+ expect(modules()).toEqual(['Track Names'])
+
+ const empty = { ...initial, generation: initial.generation + 1, active: '0a'.repeat(32) }
+ hello.mockClear().mockResolvedValueOnce(empty).mockResolvedValueOnce(empty)
+ inventory.mockClear().mockResolvedValueOnce({ offset: 0, data: Uint8Array.of(0x4d, 0x57, 0x49, 0) })
+
+ await click('Reconnect')
+ await settle()
+ expect(hello).toHaveBeenCalledTimes(2)
+ expect(inventory.mock.calls).toEqual([[0]])
+ expect(hello.mock.invocationCallOrder[0]).toBeLessThan(inventory.mock.invocationCallOrder[0])
+ expect(inventory.mock.invocationCallOrder[0]).toBeLessThan(hello.mock.invocationCallOrder[1])
+ expect(text()).toContain('On the box')
+ expect(text()).toContain('No modules running.')
+ expect(text()).not.toContain('Track Names')
+ expect(text()).not.toContain('Last confirmed set')
+ })
+
+ it('keeps the last confirmed list until HELLO and INVENTORY agree', async () => {
+ const { device, hello, inventory, reconnect, readPart } = 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()
+
+ const lastHello = await hello.mock.results.at(-1)!.value
+ hello.mockResolvedValueOnce({ ...lastHello, phase: 'recovery', activeKnown: false, active: null })
+ inventory.mockClear()
+ await click('Reconnect')
+ await settle()
+ expect(inventory).not.toHaveBeenCalled()
+ expect(text()).toContain('Reconnected to the same session.')
+ expect(text()).toContain('Last confirmed set')
+ expect(text()).toContain('Undo result unknown')
+ expect(modules()).toEqual(['Track Names', 'Chord Arp'])
+
+ // Change the generation after INVENTORY starts, with a valid record still available.
+ let generation = normal.generation
+ const reportSet = async () => ({ ...normal, generation })
+ hello.mockImplementationOnce(reportSet).mockImplementationOnce(reportSet)
+ inventory.mockImplementationOnce(async offset => {
+ const part = await readPart(offset)
+ generation++
+ return part
+ })
+ 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('Reconnected to the same session.')
+ expect(text()).toContain('Undo result unknown')
+ expect(modules()).toEqual(['Track Names', 'Chord Arp'])
+
+ hello.mockResolvedValueOnce(normal).mockResolvedValueOnce({ ...normal, session: '99'.repeat(32) })
+ await click('Reconnect')
+ await settle()
+ await expect(reconnect.mock.results.at(-1)!.value).resolves.toMatchObject({
+ status: 'unconfirmed', reason: 'session-changed-during-read',
+ })
+ expect(text()).toContain('Reconnect reply unconfirmed.')
+ 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) }, 'new-session', 'New session detected.'],
+ [{ active: '99'.repeat(32) }, 'same-session', 'Reconnected to the same session.'],
+ ] as const)('uses HELLO to qualify the Undo result with %j', async (field, continuity, message) => {
+ 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()
+ 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 },
+ })
+ expect(text()).toContain('Box checked')
+ expect(text()).toContain(message)
+ expect(text()).not.toContain('Previous set restored')
+ expect(modules()).toEqual(['Track Names'])
+ })
+
+ it.each([
+ ['drop-new-session', 'New session detected.', 'Box checked', 1],
+ ['drop-after-restore', 'Reconnect reply unconfirmed.', 'Previous set restored', 0],
+ ] as const)('keeps Undo pending when reconnect cannot confirm inventory after %s', async (scenario, message, final, inventoryReads) => {
+ const { hello, inventory, undo, tryInRam, sent } = await open()
+ await click('Try')
+ await settle()
+ await setScenario(scenario)
+ await click('Undo')
+ await settle()
+
+ if (scenario === 'drop-new-session') inventory.mockRejectedValueOnce(new Error('Inventory temporarily unavailable'))
+ if (scenario === 'drop-after-restore') {
+ const lastHello = await hello.mock.results.at(-1)!.value
+ hello.mockResolvedValueOnce({ ...lastHello, session: ZERO_DIGEST })
+ }
+ inventory.mockClear()
+ await click('Reconnect')
+ await settle()
+ expectReconnectReads(sent, ['ident', 'hello'])
+ expect(inventory).toHaveBeenCalledTimes(inventoryReads)
+ expect(text()).toContain(message)
+ expect(text()).toContain('Undo result unknown')
+ expect(text()).toContain('Last confirmed set')
+ expect(text()).not.toContain('Previous set restored')
+ expect(modules()).toEqual(['Track Names', 'Chord Arp'])
+ expect(button('Keep').disabled).toBe(true)
+
+ await click('Reconnect')
+ await settle()
+ expectReconnectReads(sent, ['ident', 'hello', 'ident', 'hello', 'hello'])
+ expect(tryInRam).toHaveBeenCalledOnce()
+ expect(undo).toHaveBeenCalledOnce()
+ expect(text()).toContain(final)
+ expect(text()).toContain('On the box')
+ expect(text()).not.toContain('Undo result unknown')
+ 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', () => {
+ 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))
+ 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
new file mode 100644
index 0000000000..6cfbc53602
--- /dev/null
+++ b/src/dev/Dt2TrialPreview.tsx
@@ -0,0 +1,184 @@
+import { useEffect, useState } from 'react'
+import { DEVICES_BY_ID } from '../devices/registry'
+import { DT2_UNIT, ElektronUnit } from '../components/ModelCyclesUnit'
+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 './dt2-trial-preview.css'
+
+type Phase = 'reading' | 'ready' | 'trying' | 'undoing' | 'undo-unknown' | 'reconnecting' | 'read-failed'
+type Review = 'restored' | 'reread' | 'new-session'
+type ReconnectSession = TrialReading['session']['continuity'] | 'unconfirmed'
+
+const RECONNECT_MESSAGES: Record = {
+ 'same-session': 'Reconnected to the same session.',
+ 'new-session': 'New session detected.',
+ 'first-read': 'Device session read.',
+ unconfirmed: 'Reconnect reply unconfirmed.',
+}
+type Control = {
+ phase: Phase
+ confirmed: ConfirmedTrialReading | null
+ observed?: TrialReading
+ review?: Review
+ undoPending?: boolean
+ reconnectSession?: ReconnectSession
+}
+
+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 = 'new-session'
+ 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] {
+ 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 [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 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 === 'new-session') return ['Box checked', '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.`]
+ }
+ }
+}
+
+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, observed, reconnectSession } = control
+ const stale = phase === 'undo-unknown' || phase === 'reconnecting' || phase === 'read-failed'
+ const pending = phase === 'trying' || phase === 'undoing'
+ 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…'
+ : phase === 'read-failed' ? 'Device state unconfirmed'
+ : phase === 'reading' ? 'Reading over USB…' : 'Connected via USB'
+ const led = phase === 'undo-unknown' || phase === 'read-failed' ? 'leaving'
+ : phase === 'reading' || phase === 'reconnecting' ? 'load' : 'on'
+
+ const details = build &&
+
Unit DT2-MOCK-01
+
OS {build.os}
+
{stale ? 'Last read base' : 'Base'} {build.digest.slice(0, 8)}
+
+ return Your Digitakt II Mock preview with Digitone II loader replies on Reconnect
}>
+
+
+
{stale || pending ? 'Last confirmed set' : 'On the box'}
+ {modules?.length ?
+ {modules.map(module => {
+ const inTrial = module.source === 'trial-ram'
+ return
+
+ {module.name}
+ {inTrial ? 'Trial in RAM' : module.source === 'saved' ? 'Saved' : 'Active'}
+
+ })}
+ : {confirmed ? (stale || pending ? 'No modules in the last confirmed set.' : 'No modules running.') : stale ? 'No confirmed inventory.' : 'Reading active modules…'}
}
+
+
+
+
{title}
+
{detail}
+ {reconnectSession && phase !== 'reconnecting' &&
+
{RECONNECT_MESSAGES[reconnectSession]}
}
+
+
+ {!stale && !trial && Try }
+ Keep
+ {!stale && Undo }
+ {stale && Reconnect }
+
+ Keep requires a base that supports saving the set.
+
+
+
+ Mock device
+ setScenario(event.currentTarget.value as UndoScenario)}>
+ {UNDO_SCENARIOS.map(option => {option.label} )}
+
+
+
+}
+
+export default function Dt2TrialPreview({ makeMock = createMockDt2Client }: {
+ makeMock?: () => { client: ElektronTrialClient; setUndoScenario: (value: UndoScenario) => void }
+}) {
+ 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 client.read().then(reading => {
+ if (active) setControl(showReading(reading, null))
+ }, () => {
+ if (active) setControl({ phase: 'read-failed', confirmed: null })
+ })
+ return () => { active = false }
+ }, [client])
+
+ async function refresh(mode: 'read' | 'reconnect', undoPending = false) {
+ try {
+ const reading = await client[mode](confirmed?.session.id)
+ const next = showReading(reading, confirmed, undoPending)
+ if (mode === 'reconnect') {
+ next.reconnectSession = reading.status === 'unconfirmed' && reading.reason === 'session-changed-during-read'
+ ? 'unconfirmed' : reading.session.continuity
+ }
+ setControl(next)
+ } catch {
+ setControl({ phase: 'read-failed', confirmed, undoPending, reconnectSession: mode === 'reconnect' ? 'unconfirmed' : undefined })
+ }
+ }
+
+ 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 })
+ }
+ }
+
+ async function reconnect() {
+ setControl({ ...control, phase: 'reconnecting' })
+ await refresh('reconnect', control.undoPending)
+ }
+
+ return { setUndoScenario(value); setScenario(value) }}
+ onTry={() => void runAction('tryInRam')} onUndo={() => void runAction('undo')} onReconnect={() => void reconnect()} />
+}
diff --git a/src/dev/Dt2UnitRoute.test.ts b/src/dev/Dt2UnitRoute.test.ts
new file mode 100644
index 0000000000..a16a4a211e
--- /dev/null
+++ b/src/dev/Dt2UnitRoute.test.ts
@@ -0,0 +1,83 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import 'fake-indexeddb/auto'
+import App from '../App'
+import { DT2_UNIT_ROUTE } from '../devices/registry'
+
+const beta = vi.hoisted(() => {
+ window.matchMedia = (query: string) => ({
+ matches: false, media: query, onchange: null, addListener() {}, removeListener() {},
+ addEventListener() {}, removeEventListener() {}, dispatchEvent: () => true,
+ })
+ return { allowed: false, createUsbKit: vi.fn(() => { throw new Error('The mock page must not create a USB kit') }) }
+})
+vi.mock('../community/beta-access', async original => ({
+ ...await original(),
+ hasBetaUi: () => beta.allowed,
+ hasUsbLinkAccess: () => beta.allowed,
+}))
+vi.mock('../components/beta', async original => ({
+ ...await original(),
+ createUsbKit: beta.createUsbKit,
+}))
+
+let root: Root, container: HTMLDivElement
+beforeEach(() => {
+ beta.createUsbKit.mockClear()
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 404 })))
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
+ Object.defineProperty(HTMLElement.prototype, 'scrollTo', { configurable: true, value: () => {} })
+ window.history.replaceState(null, '', '/#' + DT2_UNIT_ROUTE)
+ container = document.createElement('div')
+ document.body.append(container)
+ root = createRoot(container)
+})
+
+afterEach(async () => {
+ await act(() => root.unmount())
+ container.remove()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+it.each([
+ ['drop-before-restore', ['Track Names', 'Chord Arp'], 'Trial active', 'Reconnected to the same session.'],
+ ['drop-after-restore', ['Track Names'], 'Previous set restored', 'Reconnected to the same session.'],
+ ['drop-new-session', ['Track Names'], 'Box checked', 'New session detected.'],
+ ['drop-no-reply', ['Track Names', 'Chord Arp'], 'Undo result unknown', 'Reconnect reply unconfirmed.'],
+] as const)('shows the reconnect result after %s on the routed beta unit page', async (scenario, expected, result, session) => {
+ beta.allowed = true
+ await act(() => root.render(createElement(App)))
+ const status = () => container.querySelector('main .octatrack-hub .hub-view-status')
+ const button = (name: string) => [...status()?.querySelectorAll('button') ?? []].find(item => item.textContent === name)
+ await vi.waitFor(() => expect(button('Try')?.disabled).toBe(false), { timeout: 4000 })
+ expect(container.querySelector('main .hub-page-heading h1')?.textContent).toBe('Your Digitakt II')
+ expect(container.querySelector('nav[aria-label="Your Digitakt II"] a[aria-current="page"]')?.getAttribute('href')).toBe('#' + DT2_UNIT_ROUTE)
+ const picker = status()!.querySelector('select')!
+ await act(() => {
+ picker.value = scenario
+ picker.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ await act(() => button('Try')!.click())
+ await vi.waitFor(() => expect(button('Undo')?.disabled).toBe(false))
+ await act(() => button('Undo')!.click())
+ await vi.waitFor(() => expect(status()?.textContent).toContain('Undo result unknown'))
+ expect(status()?.textContent).toContain('Last confirmed set')
+ await act(() => button('Reconnect')!.click())
+ await vi.waitFor(() => expect(status()?.textContent).toContain(session))
+ expect(status()?.textContent).toContain(result)
+ expect(status()?.textContent).toContain(scenario === 'drop-no-reply' ? 'Last confirmed set' : 'On the box')
+ expect([...status()!.querySelectorAll('.hub-unit-modules strong')].map(item => item.textContent)).toEqual(expected)
+ expect(button('Keep')?.disabled).toBe(true)
+ expect(beta.createUsbKit).not.toHaveBeenCalled()
+})
+
+it('does not mount the mock page when beta access is off', async () => {
+ beta.allowed = false
+ await act(() => root.render(createElement(App)))
+ await vi.waitFor(() => expect(container.textContent).toContain('Page not found'))
+ expect(container.querySelector('.dt2-trial-panel')).toBeNull()
+})
diff --git a/src/dev/dn2-loader-mock.ts b/src/dev/dn2-loader-mock.ts
new file mode 100644
index 0000000000..0c18da0024
--- /dev/null
+++ b/src/dev/dn2-loader-mock.ts
@@ -0,0 +1,54 @@
+import { digestBytes, encodeUploadRequest, UploadCommand, UploadPhase, UPLOAD_RESPONSE, UPLOAD_VERSION, ZERO_DIGEST } from '../engine/elekloader/upload-wire'
+import { LINK_COMMANDS, LINK_HEADER, pack7, u32, unpack7, type LinkLine } from '../engine/elektron/dn2-link'
+import type { TrialHello } from '../engine/elektron/elektron-trial-client'
+
+function helloResponse(status: TrialHello) {
+ const bytes = new Uint8Array(UPLOAD_RESPONSE)
+ const view = new DataView(bytes.buffer)
+ view.setUint32(0, 0x4d575552) // MWUR
+ view.setUint16(4, UPLOAD_VERSION)
+ view.setUint16(6, UploadCommand.hello)
+ view.setUint32(12, UPLOAD_RESPONSE - 16)
+ view.setUint32(20, UploadPhase.indexOf(status.phase))
+ view.setUint32(24, Number(status.activeKnown))
+ view.setUint32(28, status.generation)
+ if (status.phase === 'trial') {
+ view.setUint32(32, 1) // last transaction
+ view.setUint32(36, 1) // current transaction
+ view.setUint32(40, 1024) // bytes received
+ }
+ view.setUint32(44, 262144) // capacity
+ bytes.set(digestBytes(status.base), 48)
+ bytes.set(digestBytes(status.session), 80)
+ bytes.set(digestBytes(status.active ?? ZERO_DIGEST), 112)
+ return bytes
+}
+
+/** A simulated Digitone II line for IDENT and loader HELLO. The mock inventory is separate. */
+export function mockDn2LoaderLine(checkLink: () => Promise, readHello: () => Promise,
+ missIdentReply: boolean): LinkLine {
+ const ident = [1, 0, 0, 0].flatMap(u32) // Link version, received, dropped, ticks.
+ const hello = encodeUploadRequest({ command: 'hello' })
+ const reply = (seq: number, command: number, payload: number[]) =>
+ Uint8Array.from([...LINK_HEADER, seq, command | 0x40, 0, ...payload, 0xf7])
+ let request: Uint8Array | undefined
+ return {
+ send(frame) { request = frame },
+ async next() {
+ const frame = request
+ request = undefined
+ if (!frame) return null
+ const seq = frame[6], command = frame[7]
+ if (command === LINK_COMMANDS.ident) {
+ if (frame.length !== LINK_HEADER.length + 3) throw new Error('Expected IDENT without a payload')
+ await checkLink()
+ return missIdentReply ? null : reply(seq, command, ident)
+ }
+ if (command !== LINK_COMMANDS.upload) throw new Error('Unexpected mock loader command')
+ const body = unpack7(frame.subarray(8, -1))
+ if (body.length !== hello.length || body.some((byte, i) => byte !== hello[i]))
+ throw new Error('Expected a read-only HELLO')
+ return reply(seq, command, pack7(helloResponse(await readHello())))
+ },
+ }
+}
diff --git a/src/dev/dt2-trial-mock.ts b/src/dev/dt2-trial-mock.ts
new file mode 100644
index 0000000000..f02d9c57c1
--- /dev/null
+++ b/src/dev/dt2-trial-mock.ts
@@ -0,0 +1,152 @@
+import type { MissingModule } from '../engine/elekloader/upload-usb'
+import { ident, readLoaderStatus, type LinkLine } from '../engine/elektron/dn2-link'
+import { readTrialInventory, type ElektronTrialClient, type TrialCapabilities, type TrialHello, type TrialReading } from '../engine/elektron/elektron-trial-client'
+import { mockDn2LoaderLine } from './dn2-loader-mock'
+
+export type UndoScenario = 'standard' | 'drop-before-restore' | 'drop-after-restore' | 'drop-new-session' | 'drop-no-reply'
+
+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' },
+ { value: 'drop-new-session', label: 'USB drops and a new session starts' },
+ { value: 'drop-no-reply', label: 'USB drops and the first reconnect gets no reply' },
+]
+
+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 PANEL_ACTIONS: TrialCapabilities = { try: true, undo: true, keep: false }
+
+const INVENTORY_HEADER = 4
+const ENTRY_BYTES = 24
+const PART_BYTES = 16 // Deliberately crosses entry boundaries in this mock.
+
+type MockDevice = ReturnType
+
+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 readTrialState(device: MockDevice, previousSession?: string, readHello = device.hello): Promise {
+ const { model, os, actions } = device.profile
+ const reading = await readTrialInventory({ hello: readHello, inventory: device.inventory })
+ const { hello } = reading
+ const knownBuild = hello.base === BASE
+ const metadata: Pick = {
+ build: { machine: model, 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 && actions.try,
+ undo: knownBuild && PANEL_ACTIONS.undo && actions.undo,
+ keep: PANEL_ACTIONS.keep && knownBuild && actions.keep,
+ },
+ }
+ if (reading.status === 'unconfirmed') return { ...metadata, status: reading.status, reason: reading.reason }
+
+ // The flashed set is a host-side build record. INVENTORY is the running set.
+ const trial = hello.phase === 'trial'
+ const saved = knownBuild ? SAVED : []
+ return { ...metadata, status: 'confirmed', activeSet: {
+ digest: reading.hello.active,
+ generation: hello.generation,
+ modules: reading.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 = {
+ async read(previousSession) {
+ await device.checkLink()
+ return readTrialState(device, previousSession)
+ },
+ async reconnect(previousSession) {
+ const line = device.reconnect()
+ await ident(line)
+ const signal = new AbortController().signal
+ return readTrialState(device, previousSession, () => readLoaderStatus(line, signal))
+ },
+ 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)),
+ actions: TrialCapabilities = PANEL_ACTIONS) {
+ let connected = true
+ let trial = false
+ let session = SESSION
+ let sessionNumber = 0
+ let missIdentReply = false
+
+ async function request() {
+ await wait()
+ if (!connected) throw new Error('Mock USB disconnected')
+ }
+
+ const device = {
+ profile: { model: 'digitakt-ii', os: '1.17', actions } as const,
+ checkLink: request,
+ async hello(): Promise {
+ await request()
+ return { base: BASE, session, generation: trial ? 1 : 0,
+ phase: trial ? 'trial' : 'normal', activeKnown: true, active: trial ? TRIAL_DIGEST : SAVED_DIGEST }
+ },
+ async inventory(offset: number) {
+ 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 request()
+ trial = true
+ },
+ async undo(scenario: UndoScenario) {
+ await request()
+ if (scenario !== 'drop-before-restore') trial = false
+ // The box may restore the set before the link loses the reply.
+ connected = scenario === 'standard'
+ if (scenario === 'drop-new-session') session = (++sessionNumber).toString(16).padStart(64, '0')
+ missIdentReply = scenario === 'drop-no-reply'
+ return connected
+ },
+ reconnect(): LinkLine {
+ connected = true
+ const missReply = missIdentReply
+ missIdentReply = false
+ return mockDn2LoaderLine(device.checkLink, () => device.hello(), missReply)
+ },
+ }
+ return device
+}
diff --git a/src/dev/dt2-trial-preview.css b/src/dev/dt2-trial-preview.css
new file mode 100644
index 0000000000..219c1dd7e5
--- /dev/null
+++ b/src/dev/dt2-trial-preview.css
@@ -0,0 +1,16 @@
+.dt2-trial-panel { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1px; background: var(--line); }
+.dt2-trial-panel .hub-cell h3 { margin: 0; font-size: 15px; }
+.dt2-trial-panel .hub-unit-modules { margin-top: 8px; }
+.dt2-trial-panel .hub-unit-modules .dt2-trial-ram,
+.dt2-trial-warning { color: var(--warn); }
+.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; }
+.dt2-trial-actions { gap: 8px; margin: 12px 0 8px; }
+.dt2-trial-note, .dt2-trial-scenario { color: var(--muted); font-size: 13px; line-height: 1.5; }
+.dt2-trial-scenario { gap: 12px; padding: 14px 18px; border-top: 1px solid var(--line); }
+.dt2-trial-scenario select { max-width: 100%; }
+.dt2-trial-scenario select:disabled { opacity: .65; }
+
+@container hub-pane (max-width: 530px) {
+ .dt2-trial-panel { grid-template-columns: minmax(0, 1fr); }
+}
diff --git a/src/devices/MachinePages.tsx b/src/devices/MachinePages.tsx
index ef78e0f38d..4abb5edee4 100644
--- a/src/devices/MachinePages.tsx
+++ b/src/devices/MachinePages.tsx
@@ -24,7 +24,7 @@ import { LibraryResultsBar } from '../components/LibraryResultsBar'
import { compareModules, downloadCoverage, downloadPeriod, periodCoverage, type ModuleStatistics } from '../community/module-statistics'
import { DownloadPeriodContext } from '../community/download-period'
import { DeviceImage, PhotoCredit } from './DeviceImage'
-import { ALL_MACHINES, DEVICES, DEVICES_BY_ID, MC_UNIT_ROUTE, RYTM_UNIT_ROUTE, STATUS_LABELS, deviceHref, deviceSteps, deviceTitle, readyForMods, stepsDone, type DeviceProfile } from './registry'
+import { ALL_MACHINES, DEVICES, DEVICES_BY_ID, DT2_UNIT_ROUTE, MC_UNIT_ROUTE, RYTM_UNIT_ROUTE, STATUS_LABELS, deviceHref, deviceSteps, deviceTitle, readyForMods, stepsDone, type DeviceProfile } from './registry'
import { MACHINE_STACK } from './machine-contract'
import { coreBuildPreviewOpen, isCoreBuildPreview } from '../engine/elekloader/protocol'
import { useCommunity } from '../community/context'
@@ -297,13 +297,16 @@ function Hero({ device, children, embedded = false }: { device: DeviceProfile; c
// Where a machine stands on the way to the Octatrack's stack (docs/MACHINE_RECIPE.md): the road after the first mod.
// The machines whose unit page reads them over a Modwerk base's link (ModelCyclesUnit.tsx): linked from the ladder, beta.
-const UNIT_ROUTES: Partial> = { 'model-cycles': MC_UNIT_ROUTE, 'analog-rytm-mkii': RYTM_UNIT_ROUTE }
+const UNIT_ROUTES: Partial> = {
+ 'model-cycles': MC_UNIT_ROUTE, 'analog-rytm-mkii': RYTM_UNIT_ROUTE,
+ ...(import.meta.env.DEV ? { 'digitakt-ii': DT2_UNIT_ROUTE } : {}),
+}
function StackLadder({ device }: { device: DeviceProfile }) {
const betaUi = hasBetaUi(useCommunity().session), unitRoute = betaUi ? UNIT_ROUTES[device.id] : undefined // as EmptyMachine's
const zoom = device.id === 'zoom-ms-70cdr'
const guide = zoom ? 'ZOOM_MULTISTOMP.md#ms-70cdr-stack-progress' : 'MACHINE_RECIPE.md'
return
- Road to the Octatrack’s stack {unitRoute && <>Your {device.name} · >}{MACHINE_STACK.filter(piece => device.stack[piece.id] === 'done').length} of {MACHINE_STACK.length} done
+ Road to the Octatrack’s stack {unitRoute && <>Your {device.name}{device.id === 'digitakt-ii' && ' (mock)'} · >}{MACHINE_STACK.filter(piece => device.stack[piece.id] === 'done').length} of {MACHINE_STACK.length} done
{MACHINE_STACK.map((piece, index) => { const state = device.stack[piece.id]; return {state === 'done' ? : index + 1} {piece.title} {piece.description} {STEP_LABELS[state]} })}
{zoom ? 'Read the roadmap' : 'Read the recipe'} ↗
diff --git a/src/devices/registry.ts b/src/devices/registry.ts
index 91f3a7a941..4304e27ae0 100644
--- a/src/devices/registry.ts
+++ b/src/devices/registry.ts
@@ -167,6 +167,8 @@ export function parseDeviceRoute(route: string): DeviceRoute | undefined {
export const MC_UNIT_ROUTE = 'model-cycles/unit'
/** The Analog Rytm MKII's own page (ModelCyclesUnit.tsx's RytmUnit), beside its machine page. */
export const RYTM_UNIT_ROUTE = 'analog-rytm-mkii/unit'
+/** The Digitakt II mock Status page in local development builds. */
+export const DT2_UNIT_ROUTE = 'digitakt-ii/unit'
/** Routes the build gives a static page at `/` (scripts/site-pages.ts, scripts/forum-pages.ts), so search engines can index them; src/routing.ts moves a bare hash link to one to its path. */
export const PATH_PAGES: readonly string[] = ['submit', 'support', 'library', 'faq', 'forum', ...DEVICES.filter(device => hasDeviceModulePages(device.id)).map(device => device.id)]
diff --git a/src/engine/elekloader/upload-session.ts b/src/engine/elekloader/upload-session.ts
index d999779402..5a4301d5db 100644
--- a/src/engine/elekloader/upload-session.ts
+++ b/src/engine/elekloader/upload-session.ts
@@ -3,7 +3,7 @@
import { sha } from '../elektron/bytes.ts'
import {
decodeUploadResponse, digestBytes, encodeUploadRequest, UPLOAD_CHUNK, UPLOAD_HEADER, UPLOAD_MAX_BYTES,
- type UploadRequest, type UploadStatus,
+ UploadWireError, ZERO_DIGEST, type UploadRequest, type UploadStatus,
} from './upload-wire.ts'
/** One complete request/reply exchange; no implicit retries or command queue.
@@ -47,6 +47,17 @@ export class UploadUnconfirmedError extends Error {
}
}
+/** Discover the running loader before selecting a package or opening a write session. */
+export async function readUploadHello(transport: UploadTransport, signal: AbortSignal): Promise {
+ const request = { command: 'hello' } as const
+ const bytes = await transport.exchange(encodeUploadRequest(request), signal)
+ signal.throwIfAborted()
+ const status = decodeUploadResponse(bytes, request)
+ if (status.result !== 'ok') throw new UploadDeviceError(status)
+ if (status.base === ZERO_DIGEST) throw new UploadWireError('The device did not report a base identity.')
+ return status
+}
+
/** The longest wait for one acknowledgement or publication; a base writing itself to NOR (OctatrackLink.updateBase,
* scripts/device.mjs flash) needs the full 180 s. */
export const UPLOAD_TIMEOUT_MAX_MS = 180000
diff --git a/src/engine/elektron/dn2-link.test.ts b/src/engine/elektron/dn2-link.test.ts
index 6af868bbe7..7e5c460459 100644
--- a/src/engine/elektron/dn2-link.test.ts
+++ b/src/engine/elektron/dn2-link.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
import { sha } from './bytes.ts'
import { UploadSession } from '../elekloader/upload-session'
import { UploadCommand, UploadPhase, UploadResult } from '../elekloader/upload-wire'
-import { ask, frameRows, get32, ident, LINK_HEADER, linkRequest, LinkError, mem, pack7 as linkPack7, parseLinkReply, readLog, screen, u32, unpack7, uploadTransport, UPLOAD_BASE, UPLOAD_BASE_TEXT, type LinkLine } from './dn2-link'
+import { ask, frameRows, get32, ident, LINK_HEADER, linkRequest, LinkError, mem, pack7 as linkPack7, parseLinkReply, readLoaderStatus, readLog, screen, u32, unpack7, uploadTransport, UPLOAD_BASE, UPLOAD_BASE_TEXT, type LinkLine } from './dn2-link'
// What link.c packs: groups of seven, each led by a byte holding their top bits.
function pack7(data: Uint8Array): number[] {
@@ -58,6 +58,15 @@ describe('the Digitone II link from the site', () => {
await expect(ask(line, 'mem', [0x40000000])).rejects.toBeInstanceOf(LinkError)
})
+ it.each([0, 15, 21])('rejects an incomplete %i-byte IDENT payload', async length => {
+ let reply: Uint8Array
+ const line: LinkLine = {
+ send(data) { reply = Uint8Array.of(...LINK_HEADER, data[6], 0x41, 0, ...new Uint8Array(length), 0xf7) },
+ async next() { return reply },
+ }
+ await expect(ident(line)).rejects.toThrow('ident: incomplete reply')
+ })
+
it('reads the frame on the screen through its pointer', async () => {
const memory = new Map(), frame = 0x44623fc8
put(memory, 0x402a10c8, [...be(0x44623bc8), ...be(frame)])
@@ -104,7 +113,7 @@ describe('the Digitone II link from the site', () => {
/** A unit whose link carries upload frames (link.c's upload command) to a controller as far as a trial reaches it
* (sdk/runtime/upload/upload.c): hello, enter, begin, chunk, verify, commit, leave. */
-function uploadUnit() {
+function uploadUnit(base = UPLOAD_BASE) {
const names = Object.fromEntries(Object.entries(UploadCommand).map(([name, code]) => [code, name]))
const state = { phase: 'normal', last: 0, current: 0, received: 0, generation: 0, active: UPLOAD_BASE, digest: '', frames: 0, longest: 0 }
const respond = (command: number, transaction: number, result = 'ok') => {
@@ -112,7 +121,7 @@ function uploadUnit() {
view.setUint32(0, 0x4d575552); view.setUint16(4, 1); view.setUint16(6, command); view.setUint32(8, transaction); view.setUint32(12, 128)
;[UploadResult.indexOf(result as never), UploadPhase.indexOf(state.phase as never), 1, state.generation, state.last, state.current, state.received, 262144]
.forEach((value, i) => view.setUint32(16 + 4 * i, value))
- out.set(Buffer.from(UPLOAD_BASE, 'hex'), 48); out.set(new Uint8Array(32).fill(0x53), 80); out.set(Buffer.from(state.active, 'hex'), 112)
+ out.set(Buffer.from(base, 'hex'), 48); out.set(new Uint8Array(32).fill(0x53), 80); out.set(Buffer.from(state.active, 'hex'), 112)
return out
}
const controller = (frame: Uint8Array) => {
@@ -149,6 +158,32 @@ describe('the runtime loader over the Digitone II link', () => {
expect(UPLOAD_BASE).toBe(sha(new TextEncoder().encode(UPLOAD_BASE_TEXT)))
})
+ it('discovers the running build and session with one read-only turn', async () => {
+ const unit = uploadUnit()
+ let turns = 0
+ const status = await readLoaderStatus(unit.line, new AbortController().signal, async work => {
+ turns++
+ return work()
+ })
+ expect(status).toMatchObject({ result: 'ok', base: UPLOAD_BASE, session: '53'.repeat(32), phase: 'normal' })
+ expect(unit.state).toMatchObject({ frames: 1, current: 0, generation: 0, phase: 'normal' })
+ expect(turns).toBe(1)
+ })
+
+ it('does not send HELLO if cancelled while waiting for the line', async () => {
+ const unit = uploadUnit(), abort = new AbortController()
+ await expect(readLoaderStatus(unit.line, abort.signal, async work => {
+ abort.abort()
+ return work()
+ })).rejects.toThrow('upload: cancelled')
+ expect(unit.state.frames).toBe(0)
+ })
+
+ it('rejects a HELLO reply without a build identity', async () => {
+ const unit = uploadUnit('0'.repeat(64))
+ await expect(readLoaderStatus(unit.line, new AbortController().signal)).rejects.toThrow('did not report a base identity')
+ })
+
it('stages a package, publishes it and opens a trial through UploadSession', async () => {
const unit = uploadUnit(), data = new Uint8Array(10000).map((_, i) => i * 7), pkg = { base: UPLOAD_BASE, data, sha256: sha(data) }
const session = await UploadSession.connect(uploadTransport(unit.line), UPLOAD_BASE)
diff --git a/src/engine/elektron/dn2-link.ts b/src/engine/elektron/dn2-link.ts
index bc575449ac..69a993a827 100644
--- a/src/engine/elektron/dn2-link.ts
+++ b/src/engine/elektron/dn2-link.ts
@@ -9,7 +9,7 @@
// Transport-free (LinkLine): the page gives it Web MIDI, a test a simulated unit.
import { sha } from './bytes.ts'
import { DEVICE_LOG_IMAGE_BYTES, parseDeviceLog, type DeviceLog } from '../elekloader/device-log.ts'
-import type { UploadTransport } from '../elekloader/upload-session.ts'
+import { readUploadHello, type UploadTransport } from '../elekloader/upload-session.ts'
import { UPLOAD_RESPONSE } from '../elekloader/upload-wire.ts'
import { askLink, get32, LinkError, linkFrame, pack7, u32, unpack7, type LinkLine } from './link-wire.ts'
@@ -35,7 +35,9 @@ export async function ask(line: LinkLine, command: LinkCommand, values: number[]
export type LinkIdent = { version: number; received: number; dropped: number; ticks: number; armed?: boolean; person?: boolean; bootStatus?: number }
export async function ident(line: LinkLine): Promise {
- const p = await ask(line, 'ident'), v = Array.from({ length: Math.floor(p.length / 5) }, (_, i) => get32(p, 5 * i))
+ const p = await ask(line, 'ident')
+ if (p.length < 20 || p.length % 5 !== 0) throw new LinkError('ident: incomplete reply')
+ const v = Array.from({ length: p.length / 5 }, (_, i) => get32(p, 5 * i))
return { version: v[0], received: v[1], dropped: v[2], ticks: v[3], ...(v.length >= 9 ? { armed: v[4] === 1, person: v[5] === 1 } : {}), ...(v.length >= 11 ? { bootStatus: v[9] } : {}) }
}
/** Up to MEM_MAX bytes of DDR or SRAM. */
@@ -75,18 +77,29 @@ export const UPLOAD_BASE_TEXT = 'Modwerk Digitone II OS 1.12 development base, l
export const UPLOAD_BASE = sha(new TextEncoder().encode(UPLOAD_BASE_TEXT))
/** The longest wait for one controller frame's reply: a commit admits and switches on the unit. */
export const UPLOAD_REPLY_MS = 10000
+/** Runs one request and its reply on the caller's shared line. */
+export type LinkTurn = (work: () => Promise) => Promise
+const ownTurn: LinkTurn = work => work()
+
/** The upload controller (sdk/runtime/upload) over the link's upload command: one frame out, its 144-byte response
* back, for UploadSession. Armed and stopped only: the unit refuses otherwise (status, or the controller's 'unsafe').
* A frame the unit is still running when the signal aborts is not taken back; the session then trusts the line no
* more (UploadUnconfirmedError). */
-export function uploadTransport(line: LinkLine): UploadTransport {
+export function uploadTransport(line: LinkLine, turn: LinkTurn = ownTurn): UploadTransport {
return {
async exchange(frame, signal) {
- if (signal.aborted) throw new LinkError('upload: cancelled')
- const payload = await ask(line, 'upload', [], UPLOAD_REPLY_MS, pack7(frame))
- const response = unpack7(payload)
- if (response.length !== UPLOAD_RESPONSE) throw new LinkError(`upload: a ${response.length}-byte response`)
- return response
+ return turn(async () => {
+ if (signal.aborted) throw new LinkError('upload: cancelled')
+ const payload = await ask(line, 'upload', [], UPLOAD_REPLY_MS, pack7(frame))
+ const response = unpack7(payload)
+ if (response.length !== UPLOAD_RESPONSE) throw new LinkError(`upload: a ${response.length}-byte response`)
+ return response
+ })
},
}
}
+
+/** Read the development loader's build and session through a single scheduled HELLO. */
+export function readLoaderStatus(line: LinkLine, signal: AbortSignal, turn: LinkTurn = ownTurn) {
+ return readUploadHello(uploadTransport(line, turn), signal)
+}
diff --git a/src/engine/elektron/elektron-trial-client.ts b/src/engine/elektron/elektron-trial-client.ts
new file mode 100644
index 0000000000..2ff8f28768
--- /dev/null
+++ b/src/engine/elektron/elektron-trial-client.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// The Try / Keep / Undo panel's view of the shared client, independent of the transport.
+
+import { parseInventory, type MissingModule } from '../elekloader/upload-usb'
+import type { UploadStatus } from '../elekloader/upload-wire'
+
+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' | 'session-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
+}
+
+export type TrialHello = Pick
+type TrialInventoryLink = {
+ hello(): Promise
+ inventory(offset: number): Promise<{ offset: number; data: Uint8Array }>
+}
+type TrialInventoryReading =
+ | { status: 'confirmed'; hello: TrialHello & { active: string }; entries: readonly MissingModule[] }
+ | (Pick, 'status' | 'reason'> & { hello: TrialHello })
+
+const INVENTORY_HEADER = 4
+const INVENTORY_ENTRY = 24
+
+async function readInventory(link: TrialInventoryLink) {
+ let part = await link.inventory(0)
+ if (part.offset !== 0 || part.data.length < INVENTORY_HEADER ||
+ part.data[0] !== 0x4d || part.data[1] !== 0x57 || part.data[2] !== 0x49)
+ throw new Error('Invalid INVENTORY header')
+
+ const bytes = new Uint8Array(INVENTORY_HEADER + INVENTORY_ENTRY * part.data[3])
+ let offset = 0
+ while (true) {
+ 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))
+ part = await link.inventory(offset)
+ }
+}
+
+/** After IDENT, bracket the offset reads with HELLO. A rollback can change the active set between parts. */
+export async function readTrialInventory(link: TrialInventoryLink): Promise {
+ const hello = { ...await link.hello() }
+ const active = hello.active
+ if (!hello.activeKnown || !active || !['normal', 'ready', 'trial'].includes(hello.phase))
+ return { hello, status: 'unconfirmed', reason: 'unknown-active-set' }
+
+ let entries: MissingModule[], end: TrialHello
+ try {
+ entries = await readInventory(link)
+ end = await link.hello()
+ } catch {
+ return { hello, status: 'unconfirmed', reason: 'inventory-unavailable' }
+ }
+ if (end.session !== hello.session)
+ return { hello, status: 'unconfirmed', reason: 'session-changed-during-read' }
+ if (end.base !== hello.base || end.generation !== hello.generation ||
+ end.phase !== hello.phase || !end.activeKnown || end.active !== active)
+ return { hello, status: 'unconfirmed', reason: 'set-changed-during-read' }
+
+ return { status: 'confirmed', hello: { ...hello, active }, entries }
+}
diff --git a/src/main.tsx b/src/main.tsx
index 5180e91cfc..31ea36e06c 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -10,17 +10,21 @@ import { MODULES } from './catalog/modules'
import { PublicAudioPreviews } from './components/PublicAudioPreviews'
import { PageError } from './components/PageError'
import { RenderBoundary } from './components/RenderBoundary'
+import { DT2_UNIT_ROUTE } from './devices/registry'
+const preview = import.meta.env.DEV ? new URLSearchParams(window.location.search).get('preview') : null
+if (preview === 'dt2-trial' && !window.location.hash) window.history.replaceState(window.history.state, '', '#' + DT2_UNIT_ROUTE)
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 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 === 'audio' ? Opening audio previews…}>
+ : preview === 'reporting' || preview === 'reporting-module' ? Opening reporting previews…}>
+ : }
,
)