roc-native-windows is a Roc platform for desktop apps. Roc Signals connects application state to a tree of Ui controls. The Rust host creates the corresponding Win32 controls and routes events back to Roc.

App authors can start at Create a Windows app and refer to the control reference. Contributors can start at Run the examples on Windows.

Browse the source repository and the platform releases.

Build a Windows app§

Create and package a starter app§

Install the Roc nightly for 0.1.0 as roc. Use the windows-VERSION-HASH.tar.zst CLI bundle URL from a platform release. Set $env:WINDOWS_TOOL_URL to that URL in PowerShell.

roc $env:WINDOWS_TOOL_URL -- init my-app
Set-Location my-app
roc windows.roc -- package --target x64mingw

The command writes dist/my-app-x64mingw.msi. On Windows x64, open the MSI to install the app. Launch it from the Start menu. Enter a title, select Add, mark the title read, and remove it. During development on Windows, use roc windows.roc -- dev to rebuild and relaunch from the app.

The starter keeps the Roc Signals view in src/, pure decisions in a separate logic/ package, and its image, icon and font in assets/. Edit the view in src/main.roc or change the reading-list rules in logic/ReadingList.roc. Use init --simple my-app for a single-file counter. From a checkout, run roc cli/windows.roc -- init my-app at the repository root to use the local platform.

Choose a Windows build target§

ArgumentApp architecture
--target x64mingwWindows x64
--target arm64mingwWindows ARM64

On macOS and Linux the default target is x64. On Windows it follows the architecture running Roc. Build writes the executable and its assets to build/<target>/. Package writes a Windows MSI or ZIP to dist/. The release includes the Win32 host and its linker inputs, so the consumer build needs Roc. Use ROC_WINDOWS_ROC to select a particular compiler executable if needed.

An MSI packager’s filename identifies the machine running that tool. For example, roc-windows-msi-0.1.0-linux-x64 runs on an x64 Linux machine and can produce either Windows target. The CLI selects the packager automatically and checks its SHA-256 before running it. For a custom platform, use init --platform <platform/main.roc-or-bundle-URL>.

Choose a build profile§

build and package accept --profile dev, --profile size and --profile speed. speed is the default and passes --opt=speed to Roc. size passes --opt=size, and dev uses the Roc dev backend, which builds in about a second but makes a larger, slower executable. test builds its scenario executable with dev unless you pass --profile. With the tested nightly, speed can miscompile List.map over a list of UI elements or signals (roc-lang/roc#13391), so an app that crashes while mounting under speed but not under size has probably hit it. Use --profile size, or build the list with a fold. Every profile strips the linked debug metadata and writes the selected target to build/<target>/. package uses the selected executable in the MSI or ZIP.

roc windows.roc -- build --target arm64mingw
roc windows.roc -- package --profile size

Reload during development§

From the app directory on Windows, start a development session.

roc windows.roc -- dev

The launcher builds with Roc’s --opt=dev backend. Each session has its own temporary directory under build/dev/. It stages the executable, packaged assets, catalog, and manifest settings together, as in a normal build. The target defaults to the architecture running Roc. Use --target to select another Windows architecture when your machine can launch it.

Save your changes and press Ctrl+R in an app window. The launcher closes the app, rebuilds it from disk, and starts a new process. If the build fails, the terminal reports the errors and the launcher restarts the last successful build. The new process opens fresh windows and starts with fresh in-memory signals, session storage, and effects. Local app storage on disk survives. Close the app normally to end the development session.

Reload uses a rebuilt executable so the current assets and manifest settings travel with the new code. To preview a shipping build, run build and launch build/<target>/<app>.exe.

Select native features§

Export native alongside main in the app header. Keep the configuration pure by passing the registration functions themselves to Win.Features.use. For an app that fetches HTTP responses and displays packaged images, use the following configuration.

native = Win.Features.use([Win.Features.http!, Win.Features.image_codecs!])

The platform runs the selected registrations before mounting the UI. Use Win.Features.use([]) for an app that only needs the core Win32 controls. The core includes native accessibility, keyboard input, signals, and app settings. The linker can discard optional implementations when the app omits their registration. Every configuration uses the same platform package and build commands.

RegistrationUse it for
Win.Features.clipboard!Copy buttons that write plain text.
Win.Features.direct3d!Shader views and their image textures. Includes image codecs.
Win.Features.files!Native file and folder pickers, drops, file operations, and folder listings.
Win.Features.grid!Editable data grids with their accessibility provider.
Win.Features.http!Native HTTP requests. Declare allowed origins in windows.json.
Win.Features.image_codecs!PNG, JPEG, and BMP assets and selected file decoding.
Win.Features.taskbar!Progress on the Windows taskbar button.
Win.Features.workers!Background Roc workers declared through with_workers.

To move a project to this platform version, add native to app [main, native] and select the registrations used by the project. Both init templates supply the configuration for their own features.

Check an app§

Run these commands from the directory containing src/main.roc or main.roc.

roc windows.roc -- test --check
roc windows.roc -- fuzz --check

Use test on Windows to execute the app’s behaviour specs. The portable check runs Roc expects and validates spec syntax. The starter has a separate roc-fuzz target in tests/fuzz/main.roc. On Apple Silicon macOS or x64 Linux, fuzz runs a short generated-input campaign, and fuzz --check runs the declared cases once.

See Write behaviour specs for native control actions, effect simulation, and recording.

Open packaged assets§

Images, shaders, command icons, and packaged fonts open their files beneath the installed assets directory. Use a relative name such as images/preview.png. Each directory component resolves through an open parent handle, and the loader uses the resulting file or its bytes. The Windows loader rejects traversal, alternate streams, reserved device names, and reparse points. Use a drive-letter installation path with regular files and directories.

Persist app settings§

Local storage uses the current user’s Windows Local App Data Known Folder and keeps the existing roc-native-windows/<executable-stem>/storage directory and key names. Renaming the executable changes this namespace. Storage opens directories relative to held handles, refuses reparse points and multiply linked entries, and stages replacements in the same directory.

Copy text from an app action§

Use Win.Ui.copy_button(title, { text, on_result }) for a custom Copy command. The native button copies its current text once when the user activates it. The host checks plain text, including Windows line endings, against a 64 KiB UTF-16 limit before touching the clipboard. The result is Copied, Unavailable for a busy clipboard, InvalidText for embedded NUL, or TooLarge. Retrying takes another activation. Native edit Copy, Cut, and Paste continue to follow focus.

Files uses this button for Copy SHA-256. HTTP uses it for Copy request details. An app-authored Clipboard.text request returns NotAllowed. Move its text signal and response handling to the button.

Read time and regional settings§

boot.now_ms and Engine.timer(0) provide signed Unix milliseconds. Engine.interval(milliseconds) uses a monotonic schedule and samples the Windows wall clock on each tick. For elapsed time, request System.monotonic({}) at both ends and call later.elapsed_ms_since(earlier). Marks are meaningful only during the current app process. Equal millisecond marks are valid, and reversing the order returns OutOfOrder.

boot.languages contains the user’s ordered Windows display languages. Use System.regional_settings({}) for the separate formatting locale and optional Windows time-zone key. For local offsets, use boot.zone.offset_at(unix_ms) and handle OutsideZone by requesting a fresh Engine.environment({}) snapshot. The zone table uses minutes east of UTC and has inclusive bounds. Windows zone keys are provided in regional settings. At boot, Windows may supply coverage for only the sample instant when extended rules are unavailable. If that offset cannot be read, boot logs a diagnostic and uses UTC. A failed refresh returns Refused. Use Engine.utc when the app wants an explicit UTC policy.

System.format_timestamps(instants, {}) formats up to 64 timestamps using the local time zone and the Windows short date format by default. Pass { zone: Utc, date: LongDate } to choose both options explicitly. The returned date and time are presentation strings. Keep the original timestamps for storage and comparison. The formatting call returns OutsideRange for an unsupported calendar date, TooLarge for an oversized batch, and Unavailable or Refused if it cannot provide a result. Regional settings and monotonic requests report Unavailable or Refused.

System.secure_random(count) draws up to 65,536 bytes from Windows CNG. Zero returns an empty list. Handle TooLarge, Unavailable, and Refused explicitly. The HTTP example asks for 16 bytes for each request and still offers Copy request details when the reference is unavailable.

These services read the clock, language and format preferences, and OS entropy for the current app. They need no external-resource grant and give the app no ability to change settings or query machine or account identity. Bound checks precede native allocation and are repeated in the host for raw requests. Region and time-zone refreshes run on a worker and only the current effect can deliver a response. Regional facts, timestamps, and bytes stay in the app until it chooses to share them. Clipboard export is a separate user action.

Declare packaged assets§

Keep packaged files under assets/. Put an optional assets.json next to windows.json to give the files your app relies on stable names. Paths are relative to assets/.

{
  "logo": "images/logo.png",
  "title-font": "fonts/CrimsonText-Bold.ttf"
}

Import pf.Win and pass Win.asset("logo") to a control that accepts an asset path. For an image’s signal parameter, use Engine.const(Win.asset("logo")) when the image is fixed. Use the same lookup for a command icon, shader, texture, or font. Existing literal paths still work and remain useful for computed paths.

windows.roc test --check and the build validate the asset tree and every declared path. The build checks the staged files before running Roc and replaces the previous executable only after staging succeeds. The checks cover regular files, Windows-safe path components and supported media headers and size limits. Windows still verifies decoding and font or shader compatibility when loading the asset.

The launcher embeds the name-to-path catalog in the executable. The app opens requested files directly and uses no directory scan at startup. An unknown name or an asset unavailable after installation uses the consuming control’s normal fallback. A name computed by Roc is resolved when the app uses it.

Package an app for distribution§

Set app and MSI metadata in windows.json at the app root, beside windows.roc. The optional display_name supplies the initial window title, the MSI product name and the Start shortcut label. Use a Windows-safe ASCII name of up to 64 bytes. The name defaults to the executable’s basename. The ZIP retains the title through the executable resource. Set icon to a catalog name or an .ico path relative to assets/ to brand the executable on both Windows architectures. A multi-size icon serves the window, Start shortcut and Explorer. The launcher embeds it in the staged executable and uses that executable for both MSI and ZIP. The Reading List scaffold includes an icon you can replace with your own. The starter sets an example ID from the project name. Choose your own stable reverse-DNS ID before publishing, and keep it for upgrades. The version is a three-part MSI product version. The ID, publisher, and asset filenames use ASCII.

{
  "id": "com.example.reading-list",
  "version": "1.0.0",
  "publisher": "Example",
  "display_name": "Reading List",
  "icon": "reading-list.ico"
}
roc windows.roc -- package --target x64mingw
roc windows.roc -- package --target arm64mingw --format zip

Use --id, --app-version, or --publisher to override a field for one build. Projects can omit windows.json for local development defaults. See the embedded Win32 manifest for process settings such as DPI awareness.

The MSI uses roc-<id> for its folder under Program Files and its Start menu group. It adds the app’s named shortcut inside that group. The ZIP contains an executable that can run after extraction. Both carry the executable, assets/, and any top-level LICENSE or THIRD_PARTY_LICENSES.md supplied by the app author.

Grant an HTTP origin§

The app can use HTTP only for exact origins declared in windows.json. Declare the scheme, ASCII DNS name or IPv4 address, and port. An omitted port uses the scheme’s default. An origin grants all paths at that scheme, host and port. Apps without a grant can still use native pickers, clipboard commands, assets and local settings.

{
  "capabilities": {
    "version": 1,
    "http": { "origins": ["https://api.example.com"] }
  }
}

The launcher validates the declaration and embeds it in the app EXE. The host checks requests before starting network work or supplying a scenario response. It follows same-origin redirects with a bounded deadline. A redirect to another granted origin returns the 3xx response so the app can issue a fresh request. An undeclared destination returns the existing Network failure. A Signals proposal describes a distinct policy result.

Choose an example§

ExampleWhat it demonstrates
Reading ListA pure logic package, specs, and fuzz cases
CounterLocal state and a label updated by button actions
TodosTasks, due dates, and notes in a modal dialog
WorkersA stock-count grid with validation and snapshot reconciliation on a Roc worker
FilesFile selection, text and raster previews, contrast adjustment, image comparison and SHA-256
HTTPWinHTTP requests and bounded response previews
AppearanceLight, dark and themed appearances derived from app state, with toggle switches

Win32 controls§

Import pf.Win to use Win.Ui for controls, Win.Files for files and Win.System for system services. The standalone pf.Ui import also works. Examples in this reference use Ui as shorthand for Win.Ui.

Windows and dialogs§

An ordinary app gets one main window. Use Ui.window(props, content) as the outermost element to set its title, close behaviour, or chrome. title defaults to AppTitle, which uses the application’s configured display name. Use Title(text) to supply a title from an app signal.

The optional startup record requests placement and state when a window opens. This example opens maximized on the monitor Windows chooses.

Ui.window({ startup: { position: Centered, state: Maximized } }, content)

Placement is applied when each independent window mounts. Scenario and recording windows use the spec’s scripted geometry and visibility.

Use Ui.windows(declarations) at the root for independent windows sharing one app store. For example, use Engine.each with a stable key per window and return a Ui.window from each row. A managed window requires close: Handle(handler). The handler runs when the user requests a close. Remove the declaration to accept the request. Closing the last independent window ends the app once the turn settles.

Ui.dialog({ title, open, on_close_request }, content) mounts an owned modal dialog while its open signal is true. Its owner is the enclosing window. Close and Escape request dismissal, and the app accepts by clearing the open signal. Save and Cancel can update state and dismiss in one turn. The dialog’s controls can set their own default Enter action. Opening or closing the dialog leaves the owner’s layout in place.

Window chrome§

The status_bar prop defaults to NoStatusBar. Set StatusBar({ text, trailing }) to show a primary status signal and optional trailing panes. A trailing pane takes a text signal and an optional width in device-independent pixels, with a default of 128. The primary pane fills the remaining width. At narrow widths, trailing panes drop from the right so the primary status stays available. The bar stays at the bottom while the window content scrolls.

Set taskbar_progress to a Ui.Progress signal to reflect work in the app’s Windows taskbar button. It defaults to Idle and shares the in-window indicator’s progress modes and normalization. The taskbar receives the current value when its button becomes available, including after Explorer recreates it.

Control reference§

Import pf.Ui from the Windows platform. The controls receive Roc Signals values. A handler sends writes to the state the view reads. See the Roc Signals manual for state, stores, and worker tasks.

BuilderNative roleInputs
Ui.vstackVertical layoutChildren, spacing and padding
Ui.hstackHorizontal layoutChildren, spacing and padding
Ui.panelPadded grouping surfaceContent and optional surface, border, padding and width
Ui.text, Ui.text_withLabelText signal and optional style, tone, align, overflow and font with text_with
Ui.buttonPush buttonTitle, on_press, optional enabled
Ui.toolbarCommand toolbarGroup label, ordered commands and separators
Ui.text_fieldSingle-line edit controlValue, on_input, optional label, placeholder and enabled
Ui.text_areaMultiline edit controlValue and label, optional rows, enabled, mode and reference
Ui.checkboxCheck boxTitle, checked, on_change, optional enabled
Ui.toggle_switchOn/off switch (a check box to assistive technology)Title, checked, on_change, optional enabled
Ui.combo_boxSelection-only drop-downlabel, selected, on_select, optional enabled, and its options as children
Ui.list_boxSingle-selection listlabel, selected, on_select, optional enabled and visible_rows (default 6), and its options as children
Ui.date_fieldCivil date entryDate selection signal, accessible label, typed on_change, optional enabled
Ui.time_fieldCivil time entryTime selection signal, accessible label, typed on_change, optional enabled
Ui.progress_barProgress indicatorProgress signal, accessible label, optional height (default 16 DIP)
Ui.radio_groupLabeled radio buttonslabel, selected key, on_select, optional enabled, and a fixed list of Ui.radio items
Ui.tree_viewHierarchical selectionlabel, selected, on_select, on_expand, optional enabled and visible_rows (default 8), and its nodes as children
Ui.tabsTab strip and active pagelabel, selected key, on_select, a fixed list of Ui.tab items and the page element
Ui.file_drop_targetLabeled Explorer drop arealabel, on_files and content
Ui.file_buttonSystem file pickerTitle, on_files handler, and optional selection (SingleFile or MultipleFiles)
Ui.list_viewSingle-selection reportLabel, columns, rows, selected key, handlers and optional sort
Ui.data_gridEditable report gridLabel, columns, table rows and optional sort
Ui.asset_imagePackaged imageAsset path, description, width, height and optional fit
Ui.imageRaster imageRaster source signal, description, width, height and optional fit
Ui.shader_viewShader-drawn surfacePackaged pixel shader, description, size, optional textures and parameter signals
Ui.sliderHorizontal trackbarInteger value signal, accessible label, on_change, optional range, step and focus reference

Stack spacing, padding and image dimensions use device-independent pixels. Set stack_below on a horizontal stack to lay its children out vertically when the available width in device-independent pixels drops below that value. The default of 0 keeps a horizontal layout at every width. An image path is relative to the app’s assets/ directory. Give each interactive control a meaningful caption or label. The test runner uses those names to locate controls. See the accessibility chapter for field labels, descriptions and status announcements.

Options, radios and tabs§

A drop-down and a list box take their options as children, like the rows of a report list. Ui.option(label, { key }) is one option. Give it a nonempty key unique within the control, and keep the key stable when renaming or reordering options. Visible labels may repeat. Build the options in one of three ways:

Ui.combo_box(
    { label: "Status filter", selected: filter, on_select: Engine.handle(|value| [cells.filter.set(value)]) },
    Ui.options([{ key: "all", label: "All statuses" }, { key: "read", label: "Read" }]),
)

Ui.list_box(
    { label: "Picked files", selected, on_select },
    Ui.rows_by(cells.queue, |key, _| key, |key, file| Ui.option(file.signal().map(|f| f.name()), { key: key.map(U64.to_str) })),
)

A selected key that has no corresponding option is shown as an empty selection. The on_select handlers receive Ui.Selection.Selected(key) or Ui.Selection.NoSelection.

Ui.radio_group(props, radios) shows a fixed list of radio buttons made with Ui.radio(key, label, { enabled }). A radio’s key is fixed for the group’s lifetime, while its label and enabled signal can change. A label change renames that radio alone, and a disabled radio cannot be chosen. Disabling the group disables every radio. Ui.radios(choices) makes always-enabled radios from a List(Ui.Choice). A group needs at least one radio and a selected key from its radios. Its on_select handler receives the selected string key. While the checked radio is disabled, Tab reaches the first enabled radio instead.

These controls show the selection supplied by the app. A user choice becomes the displayed selection when the handler updates that signal.

Ui.CivilDate.from_parts({ year, month, day }) validates a Gregorian date from 1753-01-01 through 9999-12-31, inclusive. It returns YearOutOfRange or InvalidCalendarDate on error. The date picker uses the Windows short-date format and renders the NoDate selection with its checkbox clear. The typed change handler receives Date(date) or NoDate.

Ui.CivilTime.from_parts({ hour, minute }) accepts clock hours 0–23 and minutes 0–59 and returns InvalidClockTime on error. The time picker uses the Windows short-time format and renders NoTime with its checkbox clear. The change handler receives Time(time) or NoTime. The field displays an example in the Windows short-date or short-time format. Date input uses four-digit Gregorian years and also accepts ISO YYYY-MM-DD. Time input has minute precision and also accepts 24-hour HH:MM. Enter or a move to another control commits a valid draft. Clearing the field and committing proposes NoDate or NoTime. An invalid draft stays visible with a validation message. Escape restores the committed value. A handler may decline a proposal and keep the previous value.

The date field also provides a Choose date button. In the calendar, use the arrow keys to move by day or week and Page Up or Page Down to change month. Enter or Space chooses a date. Escape closes the calendar and restores focus to Choose date.

Both civil types expose parts() and to_iso(). A date and clock reading describe calendar fields. To resolve them to an instant, supply an application policy for timezones, offsets and ambiguous times.

Tree views§

Ui.tree_view(props, nodes) takes its nodes as flat children. Each Ui.tree_node(label, { key, parent, expanded }) names its parent, Root or ChildOf(key), and whether it is expanded (default False). Parents can appear anywhere among the nodes. The order of the children orders siblings. Use unique nonempty keys and existing parents. Build the nodes in one of three ways:

Ui.tree_view(
    { label: "Folders", selected, on_select, on_expand },
    Ui.tree_literal([Branch("docs", "Documents", [Leaf("cv", "CV.docx")]), Leaf("notes", "Notes.txt")], expanded),
)

A tree supports up to 16,384 nodes, 64 levels, keys of up to 1024 UTF-8 bytes and labels of up to 1024 UTF-16 code units. A label or expansion change costs the same at any size. A change that adds, removes, moves or reparents nodes reads only the nodes between those that kept their place, and rebuilds the tree’s model in time linear in its nodes.

on_expand receives a key and either Expanded or Collapsed. Write membership and any selection change in the same handler. If the app keeps a selected descendant when its branch collapses, the native caret moves to the collapsed ancestor and the descendant has no visible selection until it is revealed again.

Tabs§

Ui.tabs(props, tabs, page) displays a native tab strip above the active page. Make each tab with Ui.tab(key, label), or fixed tabs from a List(Ui.Choice) with Ui.tab_list(choices). A tab’s key is fixed for the strip’s lifetime, and a change of its label signal renames that tab in place. Use at least one tab with a unique key and supply one of those keys as selected. Pass that same signal to Engine.switch to mount the matching page. If on_select declines an intent, the selected tab and page keep their previous state. Keep drafts or results that should survive a page switch in app state outside the page’s scope.

Use Ui.Progress.Indeterminate while work is active and its total is unknown. Determinate({ completed, total }) caps completed work at total. A zero total resolves to Idle. The bar and its label keep their layout space while idle. With client-area animation disabled, an indeterminate indicator displays steady busy text.

Ui.file_drop_target(props, content) accepts an Explorer file drop over its frame or content. A drop over nested targets goes to the innermost target. Its on_files handler receives the same file capabilities and refusal count as the file picker. Keep a file picker in the area so users can also open files with the keyboard.

The Windows Open dialog binds each accepted file to a read handle before it closes. A multi-file confirmation delivers its files and refusal count in one event. Cancelling leaves the app’s selection alone. Reads, hashes, image decoding, and export use the held file even if its name changes. Windows may still allow another program to edit that file in place. On Windows, Engine.object_url returns Err(Unavailable) for these capabilities. Use a file read or image decode to display the contents.

Save As asks the user to confirm an overwrite before it writes to an existing file. It holds the chosen directory and the confirmed file. For a new filename, it creates the file only if that name is still available. A late arrival or a replaced directory produces an error and leaves existing files alone. Save As supports ordinary files in drive-letter paths and refuses reparse points and multiply linked targets.

Ui.folder_button delivers either FolderChosen(folder) or FolderRefused(Unavailable). The picker retains the chosen directory before it closes. Cancelling keeps the previous selection. Use folder.name() for display and folder.files({}) in an engine request to obtain up to 16 immediate ordinary files. Set limit to request fewer. Results are ordered by UTF-16 filename and report a partial listing when the scan or result limit is reached or an entry is skipped. Enumeration skips subdirectories and reports reparse points as skipped entries. The returned files support reading, hashing, and saving a copy. The host keeps their paths private.

Command toolbars§

Use Ui.toolbar({ label }, items) above the content its commands act on. Build each command with Ui.toolbar_button(title, { key, on_press, enabled }). Keys are nonempty and unique within the toolbar. The title, enabled state, and the action’s context can follow your Roc state. on_press uses the same click handler as a push button. Insert Ui.toolbar_separator() between command groups.

Use Tab to reach the toolbar, arrow keys to move between commands, and Enter or Space to activate a command. Commands wrap when the window narrows. Use short captions that fit at the smallest supported window width.

Both push buttons and toolbar commands can display an ICO beside the caption. Pass an icon signal such as icon: Engine.const(Ui.CommandIcon.IconAsset("reading-list.ico")). Paths are relative to assets/ and can include subdirectories. The default NoIcon omits the image. A missing or unreadable icon leaves the command caption and action available. Windows displays the image at the appropriate size for the window DPI.

Report lists§

Use Ui.list_view(props, rows) to display records with native headers and single-row selection. Define columns with unique nonempty key values and a heading for each. The default width, Auto, measures the heading and mounted cells and clamps the result to 48–360 device-independent pixels. Use Fixed(width) for a positive width in device-independent pixels. The list scrolls independently. Set visible_rows to budget space for 1–64 rows. The default is eight.

Build rows with Ui.list_row({ key }, cells) and Ui.list_cell(value, { column }). Give each row a stable, unique, nonempty key and one cell per column. The column key determines where the cell appears. For dynamic rows, pass the element produced by Engine.each or Engine.table_view in the list’s child array.

Supply a selected signal of type Ui.Selection and write its new value from on_select. The selection is NoSelection or Selected(key). When the key is outside the mounted rows, the highlight clears. Use on_activate: Handle(handler) to respond to Enter or a double-click on a row, even if it is already selected. Use on_column_press: Handle(handler) to receive a column key and update the row order in Roc.

Show the order with sort, a signal of Unsorted, Ascending(column) or Descending(column). The header item of that column shows the native sort arrow, which the host also draws in dark mode. The arrow does not reorder rows: sort them in Roc, for example with the sort of Ui.rows_by or a table view’s plan. A change of sort writes only the header. UI Automation exposes a header item’s name and its Invoke pattern, which presses the column, but not the arrow: the Win32 header proxy leaves its ItemStatus empty and ignores annotations of it. When the order matters to a screen reader user, also say it in nearby text, such as a status bar. Specs check the arrow with expect-sort.

on_column_press: Handle(Engine.handle(|key| if (key == "title") [cells.sorted.update(|sorted| !sorted)] else [])),
sort: cells.sorted.signal().map(|sorted| if (sorted) Ascending("title") else Unsorted),

For rows kept in an Engine.table, Ui.rows_by(table, sort, template) draws every row ordered by sort(key, row) and then by key. Keys and sort values must be ordered, such as numbers or tuples of numbers.

For a complete report list example, see the Starter app and its specs described in Choose an example.

Default actions and mixed check boxes§

Set a button’s enter_action to WindowDefault to submit from a single-line field when Enter is available. A focused push button retains its own action. Mount one default button per window.

Ui.aggregate_checkbox displays Unchecked, Checked, or Mixed from a state signal. Activating it requests true from Unchecked or Mixed and false from Checked. Use on_change to update the underlying items and derive the aggregate state from them.

Text labels and multiline values§

Ui.text(value) wraps onto as many lines as needed. Use Ui.text_with(value, { overflow: EllipsizeEnd }) to keep a caption on one line and show an ellipsis when it runs out of room. The control retains the full caption for accessibility and behaviour specs.

Ui.text_area(value, { label: "Contents" }) displays a read-only preview that users can select, scroll and copy. Set rows to choose the visible height. It defaults to five lines. Use mode: Editable(on_input) to receive the complete draft after each edit. The value and handler use LF line endings. Enter inserts a line break. Use a separate button to submit edits.

Echo the draft through the value signal to keep the displayed text and the app’s state in sync. If the value signal changes to a different string while an editable area has focus, the native draft remains until focus leaves. To reset the focused draft deliberately, set its reference and issue Engine.command(ApplyValue(reference)) from an effect plan in the same turn as the new value. An active input method composition finishes before the reset is applied.

Editable data grids§

Use Ui.data_grid({ label, columns }, rows) with Engine.table_view or Ui.rows_by over a typed table. Column widths, the visible-row budget and the sort arrow follow report lists. A grid can mount up to 1024 rows and 64 columns. Use the table view’s window to page larger datasets.

Build each row with Ui.grid_row(cells) and each cell with Ui.grid_cell(value, { column }). Define one cell per column. The default is read-only. An editable cell uses editor: TextEditor(row.set_value(apply_edit)), for example. The handler receives a Ui.CellEdit containing draft, the complete text. Put validation in the Roc handler and pass a feedback signal of Clear or Invalid(message). An invalid edit can retain the committed text and return feedback in the same write.

Use the arrow keys to move between cells and Enter or F2 to open the editor. Enter commits an open edit. Escape or leaving the editor discards it. The edit stays with its mounted cell when rows move and is discarded when the cell leaves the window or its committed value changes. The Workers example edits stock counts and reconciles a snapshot on a worker.

Hold Shift while moving with the arrow keys to extend a rectangular selection. To handle Ctrl+V while the grid has focus, supply \on_paste: Handle(handler)\. The handler receives \Try(Ui.GridPaste, Ui.GridPasteError)\. A successful batch contains a one-based \first_row\, ordered column keys, and rows of values. Resolve the batch against the same sort, filter and page used to display the grid. Apply domain validation and changes in one Roc decision.

The clipboard accepts plain tab-separated text up to 64 KiB of UTF-16 data and at most 64 rows by 32 columns. A single active cell is the top-left corner for the pasted rectangle. A selected range must match the paste size. A paste that exceeds the mounted rows, includes read-only cells or has unequal line lengths returns a paste error before any cells change. Ctrl+V in the open cell editor uses the native EDIT clipboard behavior.

Native styling§

Ui.window accepts an appearance signal. Pass a fixed appearance with Engine.const, or map app state to restyle the window while it runs. Every field defaults to following Windows.

Win.Ui.window(
    {
        appearance: Engine.const({
            accent: CustomAccent({ red: 27, green: 101, blue: 91 }),
            caption: AccentCaption,
        }),
    },
    content,
)

The host derives tints, outlines and secondary and accent text from these colors. Text keeps at least 4.5:1 contrast and outlines 3:1, whatever colors the app supplies. Owned dialogs inherit their window’s appearance. Windows contrast themes use the system colors and ignore the scheme, palette and caption.

Ui.toggle_switch draws a 40×20 DIP switch. When on, its track fills with the accent at 3:1 or better against the background. When off, it is outlined in the secondary tone. It mirrors right to left and uses system colors in contrast themes. Narrators read a check box with the Toggle pattern, and specs find it with toggle-switch.

Set emphasis: Accent on Ui.button for the primary action. It stays a native push button, so focus, Enter and narrators behave as before, but draws a 4 DIP rounded accent fill with black or white text at 4.5:1, and lighter hover and pressed fills. emphasis defaults to Standard.

Lists, list boxes, trees, grids and dropdowns select rows in the accent when the app sets an accent or palette. A focused list fills selected rows with the accent at 3:1 against the field, and an unfocused list uses a muted mix. Other windows keep the system selection.

Sliders and progress bars draw a Fluent track, an accent fill and a round slider thumb unless the window uses the light system palette. Progress marquees sweep an accent segment. Column headers, disabled buttons and disabled date and time fields use palette colors when dark or custom.

Contrast themes keep native drawing for all of these. Custom drawing follows the window DPI, right to left layout, disabled state and focus cues.

In dark windows, stock controls use the Windows dark control themes. Date picker calendars and toolbar icons keep their light drawing, and other controls may differ from the native dark style.

Ui.text_with defaults to Body style, PrimaryText tone and Start alignment. Other styles are Caption, Heading, Title, Display and Monospace. SecondaryText de-emphasizes supporting labels, and AccentText draws from the window accent with a readable foreground. Alignment can be Start, Center or End. Start and end follow the interface reading direction. Text wraps by default. Use EllipsizeEnd for a single line that retains its full accessible caption.

Ui.panel(props, content) defaults to Inset surface, NoBorder, 12 DIP of padding and Natural width. Use AccentTint for a tinted surface, Outline for a border, and Fill for the width available after fixed-width siblings and gaps. A panel uses a single element as its content. Use a stack inside it to group several controls.

Counter keeps the default Windows look with a Display value in an Inset card. Reading List and Todos each define a palette, accent and caption in an app-owned style record, and tint only their entry panel. See Appearance for live theme switching. It derives one appearance signal from a mode, a theme preset and toggle switches, and its Themes module collects the example palettes for reuse.

Packaged fonts§

Ui.text_with uses SystemFont by default. To use an app font, place a single static TrueType face under assets/, declare it in the asset catalog and define a text style your views can share.

Reading List declares "title-font": "fonts/CrimsonText-Bold.ttf" and uses it for its page title.

page_title : Win.Ui.TextProps
page_title = {
	style: Display,
	tone: AccentText,
	font: PackagedFont({
		asset: Win.asset("title-font"),
		family: "Crimson Text",
		face: Bold,
	}),
}

heading = Win.Ui.text_with("Reading list", page_title)

Ui.PackagedFontProps defaults to Regular and also accepts Bold, Italic, or BoldItalic. Use a separate asset for each face. The GDI family name can differ from the filename and has a maximum of 31 UTF-16 code units. The host selects the weight the file declares. Bold needs the bold style bit or at least SemiBold (600); Regular accepts any file without the bold bit, such as a Medium or SemiBold family. The text style supplies the size and fallback role. Windows registers the font privately for the app process. The host verifies the selected face against the file and uses the system role when the face cannot be loaded or selected, or when the text needs complex shaping or glyphs the packaged face lacks. Use a Windows system role for text that regularly mixes scripts. The native label retains its full text as its accessible name. Editors, commands, and other native controls keep their system fonts.

The ordinary build, ZIP, and MSI asset flow carries the font. Check that its license permits redistribution and keep the license text alongside the file. Reading List bundles Crimson Text Bold and HTTP bundles IBM Plex Mono Regular. Reading List, Todos and Workers collect colors, typography and layout choices in app-owned style records.

Raster images§

Place PNG, JPEG (.jpg or .jpeg), and BMP artwork under assets/. Ui.asset_image(path, props) resolves its path from that directory. Pass an empty path to clear the picture. Use fit: Contain to center the picture in the requested size while keeping its aspect ratio. The default Stretch uses the full box. PNG alpha blends over the surrounding surface, and JPEG orientation is applied before fitting.

To preview a picked or dropped Engine.File, issue Ui.decode_image(file) with Engine.watch_latest. Keep the resulting Ui.Raster in app state. Show it as RasterImage(raster) with Ui.image, or pass NoImage to clear the surface. Use Ui.raster({ width, height, rgba }) when the app already has the pixels, such as a heatmap or rendered report page. Supply 8-bit, straight-alpha sRGB bytes in top-down, row-major RGBA order. The decode path assumes sRGB for image colors. The constructor checks the dimensions and requires exactly four bytes per pixel. Images can be up to 8,192 pixels on either axis and 8,388,608 pixels in total. Encoded preview inputs can be up to 32 MiB.

Selected files remain opaque capabilities. The decoder passes an immutable host-held raster by capability. App-produced RGBA crosses through a typed binary attachment and is converted to premultiplied BGRA for presentation. The Files example uses one decoded image in an ordinary view and in a shader and supplies a second raster generated in Roc.

Shader views§

Use Ui.shader_view({ description, shader, width, height, ... }) for one Direct3D 11 pixel pass. Put precompiled shader-model 5.0 DXBC (.cso) in the app’s assets directory and reference it with Win.asset(...). You can build and run the Files example with its checked-in bytecode. If you change the HLSL source, regenerate the bytecode from the example directory. This command uses FXC on Windows.

fxc /T ps_5_0 /E main /Fo assets/scan-contrast.cso shaders/scan-contrast.hlsl

Roc builds and packages the checked-in shader asset on macOS, Linux and Windows. The executable uses the Windows Direct3D 11 runtime.

The host supplies a full-screen triangle with normalized TEXCOORD0 coordinates from the upper left. Set texture for slot t0 and second_texture for slot t1. Either can be NoTexture (the default), AssetTexture(path) or RasterTexture(raster). The source spans UV 0–1 on each axis. The s0 sampler clamps at the edges and defaults to Linear. Use Nearest when exact texels matter. Sampled colors use normalized sRGB-encoded channels and premultiplied alpha. Return color in the same format for compositing.

Declare named scalar floats in one constant buffer at b0. Supply all reflected values as { name, value: F32 } records through the reactive parameters prop. The host checks names, finite values and supported bindings. A parameter change reuses the live texture. Windows uses a hardware device where available and can fall back to WARP, then to the unprocessed first texture or a visible diagnostic.

Surface input and sliders§

Ui.image and Ui.shader_view default to ReadOnly. Use input: Interactive({ pointer, keys }) to opt into input. A Pointer binding gives the zone a name and supplies the needed down, move, up and cancel handlers. Choose CaptureOnPress to continue receiving mouse reports during a drag outside the surface, and LatestMove for the latest waiting move per frame. Coordinates are in 0–10000 inside the zone. An outside report is Outside. A pending move is delivered before the gesture ends.

FocusedKeys({ key, handle }) opts the surface into focus traversal. The host supports arrows, Home, End, Page Up and Page Down with a rendered Engine.Keymap. A pointer-only surface can use a companion native control for keyboard access.

Ui.slider(value, { label, on_change }) uses an I32 signal. Its default range is { min: 0, max: 100 } with a keyboard increment of 1. Set range and positive step to change them. The handler receives a requested position. Update the signal to commit the value. Use reference with a Focus command to move focus to the slider when a user drags its companion graphic.

Windows accessibility§

Labels, graphics, and status§

Give a field a visible label signal that says what the user can enter. Keep the placeholder for an example or format hint. A label remains the field’s name as its value changes. The host keeps the label beside the control and preserves the system’s edit and selection patterns.

Supply a description for asset images, raster images, and shader views. Use Described({ label }) for an informative graphic and add details: Details(text) through a signal for supplemental information. Use Decorative for an image whose information is already available nearby. A described image is available in the accessibility tree. Decorative graphics and empty raster views stay out of its control and content views. Both stay out of Tab traversal by default.

Files uses a native slider as the keyboard and automation route for its image comparison. The slider and pointer events update one value. Workers displays its variance as text alongside its meter.

Mount Ui.status_text(message, {}) once around each workflow that reports a meaningful result. The initial text is available for navigation. A later nonempty change can raise a polite live-region event without moving focus. announcement: Quiet makes the status available for reading without an announcement. Use ordinary text for frequent counts. Use the native progress control for progress. When Windows has disabled client-area animations, an indeterminate operation provides a steady busy caption.

Editable grid semantics§

The grid’s UI Automation provider exposes mounted cells with their current row, column, column header, selection, and committed value. An invalid edit leaves the value intact and makes the validation message available with the affected cell. A surviving mounted cell keeps its runtime identity when displayed at another index. The provider for a removed cell returns an unavailable-element error.

An automation edit requests the same typed commit as a keyboard edit. UI Automation observes the model after the app accepts or rejects the draft. The provider accepts bounded text for an editable cell and routes it through the owning UI thread. It rejects reads from retired providers and changes to disabled or read-only cells. The host rechecks the mount, window, and editor state before applying queued work. These checks cover the app’s own controls. Windows governs which desktop processes can use accessibility APIs.

Verify UI Automation on Windows§

Stage the host as described in Run the examples on Windows, then run the following command from an interactive Windows desktop.

blueprint run test-accessibility

The contributor probe launches the real examples, queries UI Automation from a separate MTA process, and checks names, patterns, state changes, and focus. Each app and client are terminated after the check. Add -- -FreshStarter to also scaffold and test a Reading List project with windows.roc init. The hosted accessibility workflow uses this option. For a focused run or a project created by the release launcher, invoke the same script directly.

powershell.exe -NoProfile -File tests/accessibility/run.ps1 -Example workers
powershell.exe -NoProfile -File tests/accessibility/run.ps1 -Example starter -Starter C:\work\reading-list

Record the Windows version, architecture, and display preferences with results. Then use the keyboard and Narrator for these checks.

Repeat with a Windows contrast theme, larger Text size, and mixed monitor DPI when available. Run the core Reading List check on a fresh app from the standalone initializer. Keep native Windows evidence distinct from cross-build and Wine results.

Test and record Win32 apps§

Write a behaviour spec§

Put one named (test ...) or (demo ...) form in each tests/specs/*.scm file. Place input data under tests/fixtures/. A spec can look up a control by its type and caption or accessible label. This scenario adds and checks one item in the Starter app.

(test "mark a title read"
  (steps
    (fill (text-field "Title") "Roc guide")
    (click (button "Add"))
    (expect-row-selected (list-view "Titles") "Roc guide")
    (click (toolbar-button "Mark read"))
    (expect-visible (text "0 unread"))))

Run roc windows.roc -- test --check to check source, run Roc expects, and validate test and demo syntax. On a Windows desktop, use roc windows.roc -- test to build the app and run each test against a fresh process. Each failure names the spec and step. The CLI must match the runner protocol in the platform bundle. On Windows on Arm, an x64 Roc process can test an ARM64 build with test --target arm64mingw. Add --skip-expects when Roc expects run on another machine. Source checks and the Win32 scenarios still run. Hosted Windows ARM64 uses this option.

Keyboard and mouse actions use the named controls on the scenario’s UI thread. Scenario windows ignore queued desktop keyboard and mouse messages, including while shown for recording. Use a normal app build for manual keyboard traversal and physical mouse capture checks.

Selectors look up button, checkbox, toggle-switch, text-field, text-area, text, file-button, folder-button, file-drop-target, image, combo-box, list-box, radio-group, list-view, date-field, time-field, data-grid, tabs, toolbar, toolbar-button, progress-bar, and tree-view. Use (within OUTER INNER) to narrow a selector to a row or container. An action needs a unique match. Use expect-text, expect-visible, expect-absent, expect-disabled and expect-checked to inspect the current control state. Keep control assertions independent of pixel output. text-area finds a multiline control by its visible label. expect-text compares the full text with LF line endings. fill works on editable areas. Use "first\nsecond" for multiline content.

Use (select (combo-box "Status filter") "unread") to propose a choice and (expect-selection (combo-box "Status filter") "unread") to assert the current selection. Both forms use the choice key. An empty string represents no selection for a drop-down or list box. Select a tab by key with (select (tabs "File details") "fingerprint"). A locator scoped to the tabs finds controls in the active page. Use select with a tree-view to choose a visible item by key. expect-selection reads an empty string when the app’s retained selection is hidden.

(expand (tree-view "Picked files") "type:txt")
(expect-expanded (tree-view "Picked files") "type:txt" true)
(collapse (tree-view "Picked files") "type:txt")

Use (toolbar "Group label") to locate a command group and (toolbar-button "Caption") to click a command or inspect its enabled state. Scope a command with within when captions repeat.

For a report list, pass the locator and stable key to select-row, activate-row, press-column or expect-row-selected. Pass an empty string to select-row or expect-row-selected to clear or verify an empty selection. Use expect-list-rows with the row keys in display order, or with just the locator for an empty report. expect-sort checks the sort arrow of a list view or data grid: (expect-sort (list-view "Titles") "title" ascending), descending, or (expect-sort (list-view "Titles") "") for no arrow.

Date and time steps compare the committed typed value across locales. Use no-date and no-time to set or assert the unset state. In the Todos app, clearing the due date also clears the due time.

(set-date (date-field "New due date") (date 2028 2 29))
(set-time (time-field "New due time") (time 9 15))
(expect-date (date-field "New due date") (date 2028 2 29))
(expect-time (time-field "New due time") (time 9 15))
(set-date (date-field "New due date") no-date)
(expect-time (time-field "New due time") no-time)

To exercise draft entry, use fill, followed by press-enter. Use expect-invalid to check the validation state and expect-text to check the retained draft. press-escape restores the committed value.

For an editable data grid, focus-cell and begin-cell take a grid, a one-based mounted row number and a quoted column key. Use fill-cell with the grid and a draft, then commit-cell or cancel-cell with the grid. expect-cell-focused takes a row and column. expect-cell-text and expect-cell-feedback also take the expected text. An empty feedback string means the cell has cleared its error.

Use \select-cell-range\ with the grid and two row-column pairs to set a rectangle. \paste-grid\ supplies tab-separated text to the grid’s normal paste handler without using the shared desktop clipboard.

Custom surfaces accept pointer-down, pointer-move, pointer-up and pointer-cancel steps with an image or shader locator. Positions are normalized to 0–10000 per axis. Use outside for a move or release outside the zone. Send several positions in one move step to exercise latest-only delivery. A native slider accepts set-slider, expect-slider and navigation via key-press.

(pointer-down (shader-view "Image comparison") 4200 5000)
(pointer-move (shader-view "Image comparison") 4500 5000 7000 5000)
(pointer-up (shader-view "Image comparison") outside)
(expect-slider (slider "Comparison divider") 70)
(key-press (slider "Comparison divider") "ArrowLeft")
(await-work)
(expect-shader (shader-view "Image comparison") "rendered")

Shader statuses include rendered, fallback and error. Wait for work before checking a frame or capturing it with screenshot. Use (expect-shader-pixel LOCATOR X Y "RRGGBB" TOLERANCE) to check a committed frame at an integer pixel coordinate from the upper left.

Use (expect-progress (progress-bar "Request progress") indeterminate) while a request is held. An assertion can also check idle or (determinate COMPLETED TOTAL). It reads the native bar’s visibility, mode and determinate position. (expect-taskbar-progress indeterminate) checks the requested window progress. It works without a Windows taskbar button.

Use (expect-status "2 visible" "1 unread") to check the native status panes in order. Narrow windows may have fewer trailing panes. An empty (expect-status) asserts that the app has no status bar.

To exercise file-drop routing with app fixtures, drop a batch over the labeled target and outside every target in the window.

(drop-files (file-drop-target "Drop files here") "tests/fixtures/hello.txt")
(drop-files-outside "tests/fixtures/elsewhere.txt")

Scope actions to a window or dialog§

Use the native title to scope a locator when a label appears in more than one window or dialog. A dialog title can also be scoped to its owner. Unscoped control locators still work when they match one live control.

(expect-visible (window "File Inspector"))
(select (within (window "File Inspector") (tabs "File details")) "preview")
(fill (within (dialog "Notes for First") (text-area "Notes")) "Remember this")
(dismiss (within (window "Todos") (dialog "Notes for First")))
(expect-absent (dialog "Notes for First"))

close-window issues a close request to an independent or main window. dismiss issues the same title-bar request to a dialog. The app may keep the surface open. Use expect-visible or expect-absent with its locator to assert the result. Actions against a window blocked by a modal dialog fail. (expect-disabled (window "Todos") true) can check that the owner is blocked while a dialog is open.

When the scenario closes the last window, place (expect-exit) as its final step. The runner waits for the application’s successful quit message. Omitting the assertion makes an early application exit a failed scenario.

Simulate and run effects§

Tests start with isolated storage and hold HTTP requests, timers and intervals by default. An optional setup form can seed local-storage or session-storage, set initial-time in milliseconds, or set a worker-pool limit. The HTTP example checks a submitted request and answers it explicitly.

(expect-request 1 :method "GET" :url "https://example.test/guide")
(stub-http "guide" :status 200 :body "Read the guide.")
(run-effect 1)
(expect-visible (text "Read the guide."))

Held effects are numbered in issue order, starting at one. Use expect-pending-effects and expect-cancelled to inspect them. Use fail-http to stage a failure. Advance virtual time with advance-time to exercise HTTP timeouts. Trigger a one-shot timer or matching interval with fire-timer or tick-interval. Inspect a period with expect-interval.

(tick-interval 1000) delivers each live 1000 ms interval’s tick and pumps after each one, so every tick is its own turn and its own native sync. (tick-interval 1000 coalesced) queues every tick first and then pumps once, as a running app does when completions arrive between two pump ticks. The tick’s turns still run one by one, in order, but turns that change no structure share one native sync. Budget that with expect-work:

(tick-interval 1000 coalesced)
(expect-work (roc-turn = 6) (surface-sync = 1))

(files "tests/fixtures/hello.txt") supplies a file as a picker result. Pass several paths to simulate a multi-file picker. The app reads or hashes files through the production file adapter. (folder "tests/fixtures/photos") supplies a directory to a folder picker and runs the same bounded listing as a live selection. (folder) simulates cancelling the dialog. Fixture paths are relative to the app. (await-work) waits for file, Roc worker, image and shader work to settle with a real-time bound. Use (setup (live-effects http)) to exercise the real HTTP adapter or (setup (live-effects time)) for real timers. Use a loopback HTTP fixture for an integration test that can run independently.

Clipboard requests in a scenario use a private test clipboard. (expect-clipboard N "value") checks the successful write count and last text. (clipboard-busy) makes the next plain-text copy return Unavailable.

Native specs simulate wall time, monotonic time, and entropy independently. (advance-time 1000) advances both clocks. (set-wall-time -1000) changes only signed wall time and leaves HTTP timeout deadlines and elapsed marks alone. (live-effects time) opts into real clocks and regional settings, while (live-effects entropy) independently uses CNG.

Use (regional-fixture "tests/fixtures/regional.txt") in setup to supply regional facts. Fixture lines name a locale, ordered language entries, a Windows zone, an inclusive span of two Unix millisecond values, and ascending offset entries with a timestamp and minutes east of UTC. The first offset starts at the span’s start. For exact formatting, use formatted utc|short|0|01/01/1970|00:00:00. The first two fields accept utc or local and short or long. Simulated formatting requires a matching entry for each timestamp.

Nonzero in-bounds simulated entropy requests wait for a reply. Their request numbers are independent of HTTP and timer effect numbers. (random-bytes 1 "tests/fixtures/reference.bin") delivers exact fixture bytes with the requested length. (fail-random 2 failed) injects a CNG failure. The other failure modes are unavailable and refused. (expect-random-cancelled 2) checks that supersession retired a request. Cancelled requests cannot receive fixture bytes. The native caps on timestamps and entropy also apply under simulation.

Assert native work§

(expect-work (COUNTER BOUND N) ...) checks the native work that the previous step caused. That covers the step’s input, the sync it triggered, and the message pump until the queue is empty. It also waits for the images the step queued, since when the image worker finishes is timing but what it does is not. An (await-work) right after a step extends that step, so an expect-work after the wait reads the input and all the work it started. BOUND is <=, = or >=. A failure lists every counter the step moved.

(set-slider (slider "Accent hue") 120)
(expect-work (invalidate >= 1) (redraw = 0) (set-window-pos = 0) (dwm-set <= 2))

The host names the counters. Use set-window-pos, frame-changed, invalidate, invalidate-erase, redraw, redraw-erase, redraw-frame, redraw-all, set-text, repaint-message, set-font, create-brush, create-font, delete-object, dwm-set, set-theme, set-prop, set-scroll-info, scroll-window and measure-text for native calls. Use paint, erase and nc-paint for messages the host handled. Use sync-visit, style-visit, layout-visit and arrange for the host’s tree walks. Use tree-scan and tree-shift for the wire tree’s own child-list searches and moves, plan-visit for window plan rebuilds and bridge-visit for the nodes the raster bridge checks. Use roc-turn for Roc turns, command-bytes for the view command bytes they returned, and raster-queued, raster-dropped and raster-backlog for image jobs and queue pressure. Use invalidate-rect for partial invalidations, and the list-*, choice-*, tree-*, uia-* and collection-scan counters for list views, data grids, option lists, tab strips and tree views. The contributing guide lists each one. The set-window-pos-redundant, set-text-redundant and dwm-set-redundant counters count writes that repeat the window’s last value. Test windows stay hidden unless the spec takes a screenshot, so paint is usually zero there. Budget the calls that cause painting instead. See Budget native work.

A sync visits only what the step changed, so sync-visit, style-visit and layout-visit make tight budgets: (sync-visit <= 2) holds however large the window grows.

Read the work report§

Set ROC_HOST_WORK_REPORT=1 and each expect-work step appends one JSON object, on one line, to work.txt in the spec’s artifacts directory. The line describes the step the expect-work checks:

{"v": 1, "work": {"set-window-pos": 0, "set-text": 6, ...}, "spans_us": {"turn": 234, "apply": 3, "sync": 181, "layout": 0, "arrange": 0, "paint": 0, "pump": 421}, "span_calls": {"turn": 6, ...}, "gdi_before": 10, "gdi_after": 10, "user_before": 21, "user_after": 21, "peak_working_set": 17211392, "roc_turns": 6, "command_bytes": 120, "raster_queued": 0, "raster_dropped": 0, "line": 11, "column": 5, "spec": "tests/specs/effects.scm", "test": "effects", "step": "tick-interval", "args": ["1000", "coalesced"]}
FieldHolds
vThe format version, 1. A new field keeps the version; a changed one bumps it.
workEvery counter, including those at zero, by its expect-work name.
spans_us, span_callsMicroseconds in, and entries into, each timed span. See Time the host’s phases.
gdi_before, gdi_after, user_before, user_afterThe process’s GDI and USER handle counts from GetGuiResources as the step began and at the expect-work.
peak_working_setThe process’s peak working set in bytes so far.
roc_turns, command_bytes, raster_queued, raster_droppedCopies of the roc-turn, command-bytes, raster-queued and raster-dropped counters.
line, column, step, argsThe measured step’s source position, command and plan arguments. The mount, before the first step, is "step": "mount" at line 0.
spec, testThe spec file (ROC_WINDOWS_SPEC_FILE, which windows.roc test sets) and the test’s name.

Identity fields come last, so a reader can take the numbers without a JSON parser. The verify mode’s work and time are left out, as they are from expect-work.

Set ROC_WINDOWS_SPEC_VERIFY=fresh to compare every step’s windows with a fresh mount of the same tree. See Check the host against oracles.

Capture a screenshot or record a demo§

Use a Windows desktop session for capture. A (setup (window-size 640 520)) form sets client size. Use (screenshot "after-add") for a PNG checkpoint or (screenshot (window "File Inspector") "main-preview") to capture a particular window. A dialog locator can select a dialog screenshot. Use test --screenshot-on-failure for a diagnostic image. Results are written under build/specs/. Use a test’s control assertions for repeatable checks across themes and display settings.

A (demo ...) scenario uses real timing. It is validated with the test suite and executed by the explicit record command. The starter’s tests/specs/demo.scm adds and marks an item.

roc windows.roc -- record tests/specs/demo.scm --format gif

GIF is the default. Use --format png for frames. The artifacts are under build/specs/. Automatic recordings follow the first app window until it closes. Use explicit screenshot checkpoints to capture other windows. Capture of minimized, occluded, locked or noninteractive sessions requires separate verification.

Runner boundary§

Native test and record build a separate executable under build/spec-executables/<target>. Only an executable with the embedded scenario marker accepts the runner’s plan and fixture environment. Ordinary build and distribution use the shipping executable under build/<target>. Shipping executables ignore runner settings, and the MSI packager refuses a marked scenario executable.

The CLI lowers a parsed scenario to a versioned plan file with source locations. The built Win32 host executes that plan through its native window, control and effect paths. Success requires an explicit completion result. The runner uses separate storage per scenario and a watchdog that still runs when the scenario uses virtual time.

Capture uses the app’s window and child controls. GDI draws the window into a bitmap. The installed Windows Imaging Component encodes PNG, and the host encodes GIF on a separate thread. See What the bundle contains.

Check form actions§

(press-enter (text-field "URL")) exercises the window’s default-button routing from that field. A disabled default leaves the current state unchanged. Use (expect-checked (checkbox "Complete all visible tasks") mixed) for a mixed aggregate check box.

Platform architecture§

How Roc and Win32 fit together§

A Roc app describes a view and how events change its state. The Roc Signals engine owns the reactive state and emits incremental commands. The Rust host applies those commands to a tree of Win32 controls. It translates native notifications into Roc events on the window thread.

Worker jobs have their own Roc instances. The UI thread receives their results from the host event pump. When an app no longer wants a result, the host can discard the reply while a pure computation finishes. A Roc crash in a worker stops the process.

Windows Imaging Component decodes bounded images off the window thread. The image worker resamples large images to their display size and keeps the immutable source available for shader input. A separate Direct3D 11 worker retains textures and coalesces pending changes for each view. It reads back the committed frame for compositing in the native child window. Screenshots and recordings use that same frame.

Incremental sync§

The wire tree records what each batch of commands changed (Tree::changes): the nodes created or changed in value, and the parents whose children changed. Every node also carries the newest revision of any change below it. After a batch, SurfaceRegistry::sync_changed skips every window whose declaration has no newer change, so editing one window leaves the others alone. In a window it changes, Surface::sync_changed does work in proportion to the change:

Raster updates land before the batch’s one sync. An image whose pixels arrive shows them at its laid-out size, and the sync visits nothing else in the window.

The full walk, Surface::sync, is the reference. It visits every node, restyles every control and lays the window out again. A surface’s first sync uses it, and so do the spec verify mode’s fresh twins. ROC_WINDOWS_FULL_SYNC=1 makes every batch use it, to tell an incremental sync bug from an app bug or to measure what incremental sync saves. The differential test in host/src/sync_differential.rs and the spec verify mode check that both give the same native state. See Check the host against oracles.

The event pump§

Effect answers, progress reports, timer ticks and worker results queue for the UI thread, and a pump on a 15 ms timer delivers them. Each one is still its own Roc turn, delivered in order. A turn that only changes text, attributes or effects defers its native sync, so all such turns in one pump tick share one sync at the end of the tick. A turn that adds, removes or moves nodes or listeners, asks for a reference, or attaches a raster syncs at once, as before. The tree and the native windows end in the same state either way. Turns from user input still sync one by one.

The pump stops its timer after a few idle ticks. Any window message, turn, running effect, timer, queued storage write, image or shader job keeps it running or starts it again. Effect threads post a wake-up when they finish.

Effects run on their own threads, at most 32 admitted at once. More wait in a queue, and only a full queue of 1024 refuses one. Specs use the same policy, with the pool size from setup-worker-pool. Cancelling an effect frees its slot at once. A cancelled HTTP request closes its WinHTTP request handle, so its thread stops instead of waiting out the timeout.

A raster update keeps the current picture until the replacement is ready, and a shader keeps its last frame while a new texture renders.

The image queue never refuses work, so no number of images can fail an app. Each image has at most one pending source and one pending resize. A newer input for an image replaces its older one before the worker shows it, so the queue holds only the latest input of each mounted image. The worker takes jobs oldest first. The jobs one native sync queues form a batch, and the pump publishes a batch once the worker has finished all of it. Each image then shows once, and the whole batch lands in one native sync however the worker’s timing falls. A batch still running after 100 ms shows what is ready, so a very large batch still makes progress. The bind turns of newly mounted images share one sync, like queued answers do, so mounting R images costs a fixed number of syncs and O® bridge work.

Local storage and Save As§

Local storage writes and removals run on one background thread. A read sees the latest write at once. The thread writes keys in the order of their last update, and writes only the last value of a key that changed several times while it was busy. Each write is staged, flushed and renamed into place. Normal exit waits for queued writes, so a killed process can lose the last moments' writes. A failed write is reported on stderr instead of stopping the app, and its value stays visible to reads for the rest of the session.

Save As shows its picker on the UI thread and copies the file on a worker. A failed copy shows its error once the copy ends.

Link native features at startup§

An app’s pure native configuration carries the registration functions it selects. The platform calls them on the UI thread before it mounts the first view. Registrations install function pointers or factories. The core calls optional native code through those registrations, so a direct reference from the core cannot keep the optional implementation in every executable. Worker jobs receive the selected function pointers when scheduled. Core control accessibility stays enabled, and an editable grid brings its accessibility provider with it.

Use the feature configuration to select implementations. Registration only supplies code. File choices and the manifest HTTP allowlist still control access to external resources.

Authority at the application boundary§

This section defines the platform’s intended security contract. The app and control chapters describe the APIs available today.

Start with the user’s choice§

An ordinary desktop app should work without a capability declaration. The platform provides its controls, read-only packaged assets, and app-scoped storage. For external resources, prefer a Windows interaction that expresses the user’s choice of target and operation. Opening or dropping an item grants read access to that item. A folder choice grants the documented operations beneath that folder. Save As authorizes one export to the confirmed destination. It gives no standing write access to the input or destination directory.

Bind a user gesture to the specific operation the host exposes for that control. An ordinary Roc event, a path string, a clipboard value, or a launch argument carries data. Treat a native file activation as authority only when the host can establish the provenance and scope of the designation. A later effect does not gain authority merely because the app posts it after a click. Keep native edit and clipboard gestures scoped to the focused operation. Any API that retains a user’s choice across launches must define how the user can revoke it and what happens when the resource moves, is replaced, or becomes inaccessible.

Carry authority in bounded handles§

Use typed, opaque, host-issued handles for live resources. Put the resource identity, allowed operations, and lifetime in the host contract. A helper or worker receives the authority in the handles passed to it. Read-only types have no write operations. The host keeps native handles and transport IDs private and releases resources when their owners are gone. Bound admission and retained work before opening or retaining resources.

Bind rights to the opened object or a confined directory and leaf. A path can be reused for a different object. Preserve identity across asynchronous work, check each descendant under its authorized root, and handle replacement and links without extending the grant. Keep saved paths as display or discovery data unless a supported, host-managed mechanism can re-establish the grant.

Declare unattended access only when needed§

Start with the workflow and show why platform-provided authority or a user grant cannot cover it. Then allow an optional, narrowly scoped declaration for access that must occur without a fresh user choice. The declaration sets an auditable ceiling for the application. Any code able to construct a public app-wide request can use that grant. Omitting the declaration grants no unattended external authority. Malformed or unsupported declarations fail closed. Launch flags, environment variables, and mutable files beside the executable do not extend policy in a distributed app.

Enforce the boundary in the host§

The app decides what should happen, the platform API expresses the request, and the host mediates access to Windows. This split lets the host enforce the app author’s declared limits and the scope of the user’s choice, even if a dependency submits a request directly or untrusted data supplies its target. The Roc API helps callers express valid requests. The host is responsible for checking the actual operation and the authority behind it.

Authorize each operation in the host before native work, queue admission, or test simulation. Apply the same rule to raw requests, native ports, and changes of target, such as a network redirect. A test runner may substitute outcomes for admitted requests. It cannot extend the application’s authority.

The trust boundary is Roc application code running through a trusted native host. A dependency can use authority the app has made available to it. The host enforces the scope of that authority and cannot infer the user’s intent from an otherwise valid request. Ordinary desktop Windows still applies its own process rights, ACLs, and privacy rules. OS-enforced isolation is a separate deployment property and requires verification of the running process. The Roc capability contract applies there as well.

Make the secure path the ordinary API§

Design the simplest call to do the safe thing for the usual workflow. Prefer a read handle for opening an item, an exact target for external access, and finite bounds for data and work. Let callers request broader authority explicitly when a workflow warrants it. Handle an unavailable grant as a normal outcome. Preserve the requested scope when permissions or external conditions change. A failed check never authorizes a broader grant or a fallback target.

Use types to express valid inputs and separate rights where practical. Report expected failures as named result tags. Distinguish policy denial, cancellation, invalid runtime input, OS access failure, resource limits, and temporary unavailability where they lead to different app behavior. Give a tag a structured payload when the app needs a fact to decide what to do, such as the byte limit behind TooLarge. Keep messages and native diagnostics for people. Application code should be able to handle a denial, ask for a fresh selection, or report a limit by matching on the result, without parsing a string. Limit result payloads and diagnostics to details the caller is authorized to see.

What the bundle contains§

platform/main.roc declares the host calls and linker inputs. host/src/roc_platform_abi.rs records the generated ABI. The Windows platform bundle links the same generated resource into both target architectures. It embeds the Common Controls v6, DPI-awareness, and long-path manifest from host/windows/windows.manifest.

The Rust host uses bindings from windows-rs. Zig supplies open-source startup and runtime inputs and generates import libraries from its bundled definitions. Windows supplies the DLL implementations when the app runs. The bundle carries compiled host and linker inputs. See the third-party notices for their origins.

The platform runner uses the same host to mount an app, send control events, and handle effects. See Runner boundary for how the CLI hands a scenario to the host.

Contribute to the platform§

Run the examples on Windows§

Use this path to work on Win32 behaviour and test the app examples. To write your own app, start at Create and package a starter app.

Install the x64 Windows builds of Blueprint 0.13.0 and Roc. Put blueprint.exe and roc.exe on your PowerShell path. Use a platform bundle built from this checkout. In a scratch directory, run roc unbundle on its raw HASH.tar.zst archive and copy the extracted targets/ folder into platform/ in your checkout.

Run the suite from the repository root on Windows x64.

blueprint run test-native -- --target x64mingw

On Windows on Arm, run the x64 Blueprint and Roc binaries under Windows emulation and pass --target arm64mingw to test native ARM64 executables. The task runs Roc expects and the app’s specs where present.

For host changes on Windows, install Rustup and Zig 0.17.1. Run blueprint run build to rebuild the local link inputs and cross-build the examples with the Roc dev backend.

Run blueprint run check before opening or updating a pull request. It checks formatting, runs Clippy with warnings denied and the Cargo tests with your native Rust toolchain, and checks every app and its expects with Roc warnings treated as errors. It builds no hosts or app executables, so it finishes in a few minutes. Install the linker for your toolchain if Cargo needs it. Run blueprint run bundle from a checkout with spaces in its path as part of the first native contributor verification.

To develop one example interactively, open PowerShell at the repository root.

Set-Location examples/starter
roc ../../cli/windows.roc -- dev --target x64mingw

When verifying a release, use the same staged bundle on each architecture and bootstrap a fresh project with an empty Roc package cache. Use an interactive Windows desktop for capture. Check focus, DPI, Narrator, file dialogs, networking and workers. Install, start, upgrade and uninstall the MSI on a clean machine. Cross-builds and Wine compatibility checks provide separate evidence from native Windows runs. Hosted CI builds both hosts and the platform bundle once on Linux. Every later job builds and tests the apps against that bundle, served on loopback, so they all use the hosts a release would ship. CI runs the source checks on macOS, cross-builds every app with the Roc dev backend on Linux, and checks the Win32 behavior scenarios on Windows x64. Run the interactive desktop checks below for Narrator, input focus, and display settings. The workflow’s manual options run the external UI Automation probe and native ARM64 scenarios. The macOS runner stages ARM64 apps and scenario plans so the ARM64 runners can execute them directly. The standalone option stages a local release preview on macOS and verifies a Reading List project generated from that preview on Windows x64 with a fresh Roc cache.

Run the accessibility probe and desktop walkthroughs before recording accessibility verification for a release.

Windows handoff checks§

Use an interactive Windows desktop and record the OS build and the app architecture with each result. Run the following with the bundled targets from this checkout. Use arm64mingw for the native app tests on Windows on Arm.

blueprint run test-native -- --target x64mingw
blueprint run test-accessibility -- -FreshStarter

Run the keyboard probes in tests/native-keyboard/ and repeat the Reading List accessibility check on a project created by the standalone release launcher. In windows.roc dev, press Ctrl+R after a valid edit and then after a syntax error. Verify that a valid edit starts a fresh app instance and a failed build reopens the last successful executable. Record cross-build, Wine, and native Windows results separately.

TODO: Native ARM64 verification needs a contributor with a Windows on Arm machine. Until then, hosted CI runs the ARM64 scenarios, ARM64 accessibility, and standalone jobs only on manual dispatch, and a release only installs and launches the ARM64 MSI. If you can help, run the commands above with --target arm64mingw and report the results with the OS build.

Track the remaining accessibility work in Native control accessibility and Windows desktop accessibility baseline.

Development tasksImplemented in the examples or hostWindows verification remaining
01–09, 11–15List and grid, native choices, edit, button, static labels, tabs, tree, toolbar, and progress and status bars.Verify keyboard and IME interaction, native names, long labels and read-only text, overflow, and focus at high DPI. Check task-specific behavior against the existing specs and UI Automation probe.
10, 21–22Localized date and time edits, date chooser, independent windows, and owned Notes dialog.Verify two locales, a 24-hour time format, Narrator, Escape during IME, opener focus, and window activation across monitors.
16–18App and command icons, HTTP taskbar progress, Start shortcut, and Explorer drop handling.Install two apps with the same display name. Check Explorer and Start icons, ordinary upgrade and rollback after a failed upgrade, and uninstall. Check taskbar progress across an Explorer restart and drag a real file from Explorer into Files.
19–20Clipboard text, file and folder pickers, and scoped file results.Check copy into a second app, native picker cancellation, Unicode names, and Save As on Windows. Task 36 covers the authority checks.
23–27Packaged and rendered rasters, Direct3D shader views, custom input, and native styling.Compare hardware and WARP output and test device loss. Check real mouse capture, zoom and mixed DPI, contrast themes, and recording on desktop.
28–32Control and grid semantics, keyboard focus, an external UI Automation probe, accessible graphics and slider, and polite status feedback.Establish the desktop baseline for all seven examples. Inspect civil field label and validation relationships, the focused grid EDIT and its native text interface, decorative graphic visibility, and announcements during completion and cancellation. Check Narrator, Text size, contrast themes, and mixed-DPI focus. The previous hosted x64 probe failed in Workers with Expecting object to be local. Use the updated probe’s operation and exception details to trace the failure if it recurs.
33–34Private packaged fonts and app-owned themes. Standalone init carries the Reading List theme, its Crimson Text title font and its assets.Verify the selected faces, glyph fallback, Text size and DPI across multiple windows. Check a generated app and an installed app with clean OS font settings.
35Wall and monotonic clocks, time-zone and regional facts, and secure randomness with deterministic spec fixtures.Check OS time-zone transitions, locale overrides, and CNG on both Windows architectures.
36Retained file and directory handles at picker confirmation, exclusive Save As creation, rooted assets and settings, native Copy, dedicated scenario executables, and an exact HTTP origin allowlist.Verify picker behavior, replacement, cancellation, and installed capabilities on both Windows architectures. HTTP uses a generic network failure for denial pending a dedicated result in Signals.

Before publication, validate one exact set of versioned release assets. Collect the native Windows run results, dependency license texts, SBOMs, and provenance alongside the installer and bootstrap checks.

Budget native work§

The host counts the native work it does, so tests and specs can check cost as well as behaviour. host/src/work.rs holds per-thread counters, one per Op, and host/src/native.rs wraps each costly Win32 call. The wrappers count moves, invalidation and redraws, window text, EnableWindow (enable-window, for controls and single radios), the SendMessageW calls that repaint (native::send_repaint, native::set_font), GDI brushes, fonts and deletions, DWM attributes, theme changes, window properties, the scrollbar and text measurement. The host’s window procedures count WM_PAINT, WM_ERASEBKGND and WM_NCPAINT. sync_node, style_node, layout and arrange count their visits. Counting stays on in release builds because specs run the app’s release host. Each count is one thread-local add. Only tests and spec runs turn on tracing, which records each call’s window and the shadow state that marks redundant writes.

host/clippy.toml forbids the raw calls everywhere except native.rs, so blueprint run check fails on a new direct call. To cover another call, add a wrapper to native.rs, add a line to the ops! list in work.rs if it needs a new counter, and add the raw function to disallowed-methods. Every Op name works in (expect-work ...) without a CLI change. Send a repaint-causing message through native::send_repaint. Plain queries keep using SendMessageW.

The collection controls send every message through native::send, which counts it as the Op the caller names. Each control’s own send helper picks the counter from the message:

CounterCounts
collection-scanNodes a list view, data grid, tree view, option list or tab strip visits or compares to find which of its items a change to its child lists replaced. A change that only edits items scans nothing.
list-readHeadings and cells a report projection reads from the wire tree.
list-insert, list-delete, list-set-textLVM_INSERTITEMW, LVM_DELETEITEM or LVM_DELETEALLITEMS, and LVM_SETITEMTEXTW sent to a list view or data grid.
list-messageAny other list view or header message, such as a query, a state or column width change, a sort arrow (HDM_GETITEMW and HDM_SETITEMW on the header), or a scroll.
choice-readOptions a combo box, list box, radio group or tab strip reads. A label or enabled change reads only that option or radio.
choice-insert, choice-delete, choice-setOption and tab inserts, deletes and clears, and TCM_SETITEMW relabels.
choice-messageAny other option list or tab strip message, such as a selection query.
tree-readTree nodes a tree view reads from the wire tree.
tree-query, tree-editTVM_GET* queries, and every other tree view message: inserts, deletes, renames, expansion and selection.
uia-snapshotCells copied into a new version of a data grid’s UI Automation table.
uia-lookupRow lookups, hit-test probes and announcement cell comparisons in the data grid’s UI Automation provider.
uia-eventUI Automation events the data grid raises.
invalidate-rectPartial invalidations through native::invalidate_rect. While tracing, tests read the rectangles back with native::take_invalidated.

Budget tests live in host/src/test_host.rs. TestHost::mount builds a tree with wire_builder::Commands and mounts it in a hidden native window. apply runs one batch and its incremental sync (SurfaceRegistry::sync_changed) the way App::apply does and returns its Work. TestHost::reference mounts a host that syncs every batch with the full reference walk instead, to measure what a change cost before incremental sync. Assert the work with work.at_most(&[(Op::SetWindowPos, 0)]), or check which windows the batch touched with touched(Op::Invalidate). Set ROC_HOST_WORK_REPORT=1 to print each batch’s work.

let mut host = TestHost::mount(LIGHT, |c| column(c, 30));
host.resync();
let work = host.apply(|c| {
    c.attr(14, "checked", Some("true"));
});
work.at_most(&[(Op::RepaintMessage, 1), (Op::SetWindowPos, 0)]);

A passing budget test is a tight budget. An #[ignore]d budget test is an open audit finding. Its reason names the finding, such as #[ignore = "reconcile-1: ..."], and its comment records the work measured today. A fix removes the #[ignore], and the test then guards it. Run the open findings with cargo test --manifest-path host/Cargo.toml -- --ignored test_host.

Some counters measure host work beyond Win32 calls:

CounterCounts
surface-syncnative syncs after one or more turns, incremental or full
pump-tickpump polls; an idle app makes none
font-verifyfull-file checks of a packaged font against the selected face
icon-decode.ico asset reads and decodes for buttons and toolbars
class-namewindow class names read by the paint and notify paths
system-queryreads of high contrast, the DWM colour, the locale layout and dark mode
roc-turnRoc turns: the mount and each delivered event
command-bytesbytes of view commands the turns returned
raster-queued, raster-droppedimage jobs queued for the image worker, and pending jobs a newer input for the same image replaced
raster-backlogimage jobs queued while 64 jobs or 64 MiB were already pending

Native tests that need an app use window::turn_tests. They build an App whose script answers each turn in place of Roc, so they can queue effect answers and measure one pump tick.

In a spec, (expect-work ...) asserts the previous step’s work. See Assert native work. Choose budgets that hold now and would fail on the regression they guard. Check that by reverting the fix locally. With ROC_HOST_WORK_REPORT=1, each expect-work step also appends a JSON line to work.txt in the spec’s artifacts directory, since the CLI keeps a passing spec’s output to itself. The line names the step and holds every counter, the span times, the GDI and USER handle counts before and after the step and the peak working set. See Read the work report for the fields. Set ROC_WINDOWS_FULL_SYNC=1 as well to measure the same steps with the full reference walk.

Sync work is bounded by the change, not the window, so a budget can name visits. sync-visit and style-visit count the nodes a sync visited and restyled, and layout-visit the nodes layout measured or placed. An unchanged batch visits nothing. A one-leaf change visits one node, and lays the window out only when the leaf’s size can change. one_leaf_change_does_constant_work checks that with assert_scales at 100, 200 and 400 controls. Only a new palette restyles every control.

Time the host’s phases§

work.rs also times the host’s phases with QueryPerformanceCounter. Hold a guard for the phase, let _span = work::span(Span::Sync);, and its elapsed ticks and one entry are added to a per-thread total when it drops. The spans are:

SpanTimes
turnthe Roc engine’s mount and each event, in App::start and App::deliver
applyApp::apply, which reads the turn’s commands and, unless the turn is coalesced, syncs
syncApp::flush, one native sync of one or more turns
layoutLayout::place_root and measure_root (not yet guarded, so 0 until layout.rs holds the span)
arrangeSurface::place, which lays a window out and moves its controls (not yet guarded, so 0 until view.rs holds the span)
paintdispatching a WM_PAINT, in the message loop and the spec runner
pumpApp::poll, one pump tick

Spans nest and each total is inclusive: pump holds the tick’s turns, applies and syncs, sync holds layout and arrange, and arrange holds its layout. A span that re-enters itself is timed once. Like the counters, the totals are thread-local, allocate nothing and stay on in release builds. QueryPerformanceCounter reads the invariant TSC in user mode, so a span is two reads and a few adds: spans_cost_little measures about 30 ns a span in a release test build, against a step’s handful of spans and the microseconds each Win32 call costs. Spec runs report span times in work.txt. They are machine-dependent, so the benchmark reports them and never gates on them.

Watch a running app’s budget§

The budget sentry watches every native sync of a running app and logs any whose work is out of proportion to its change. It is on in dev builds (windows.roc dev, whose executable carries the development marker). A shipped app never runs it, and spec runs leave it off because specs assert their own budgets. Set ROC_HOST_BUDGET_SENTRY=0 to silence it, or =1 to turn it on for any build. Off, it costs one branch per sync. On, it copies the counters before and after each sync.

It uses the sync’s change set from Tree::take_changes, the nodes created or changed and the parents whose children changed, and names a sync when one of these holds:

The mount is never judged. The log goes to standard error, at most one line a second. The next line says how many it held back. A line names the turns and command bytes since the last sync, the findings, up to six changed nodes by tag and child-index path, the time in the sync and in its layout, arrange and paint, and the sync’s work:

roc-native-windows: budget: a sync after 1 turn (10 command bytes) changed 1 node and took 42.3 ms: set-window-pos=420 (420 per changed node), plan-visit=842 (842 per changed node), sync took 42.3 ms (frame budget 16 ms); changed: ui-vstack [0, 0, 0]; timing: turns 0.0 ms, sync 42.3 ms (layout 0.0 ms, arrange 0.0 ms, paint 0.0 ms); work: set-window-pos=420 sync-visit=1 layout-visit=2 arrange=1 surface-sync=1 plan-visit=842

That line comes from budget_sentry_names_a_disproportionate_turn_only in window.rs, which moves one text to the front of a 420-row column. The test also checks that a one-text change logs nothing. A line is a lead, not a failure. Reproduce the turn in a spec or a test_host budget test, and fix the host or record the budget there.

Check layout against its reference model§

host/src/layout.rs lays out a window without one. Source describes each node (a stack, panel, tabs, drop target or leaf control) and Measure answers text and control metrics, so tests run the real layout with a fixed-pitch fake measurer on any OS. view.rs implements both over the wire tree, the mounted controls and an HDC. Layout memoises each node’s measurement for the whole arrange, and TextCache keeps text measurements across arranges, keyed by node, text, font and width. After an incremental sync, layout::Memo keeps node measurements and placements across arranges too, less those of the changed nodes and their ancestors, and Layout::place_changes lists only the placements that changed, each with the placement before it in tab order.

host/src/layout/reference.rs keeps the original naive algorithm as the specification. The property test in host/src/layout/tests.rs builds random trees of rows, columns, panels, tabs, drop targets, texts and controls, with random captions, labels, padding, spacing, stack-below widths, maximum widths and DPIs. It checks that:

The containment check skips trees where some container is given less width than its padding. The original algorithm never clamps padding, so such a container overflows its parent; the test reports how many trees it checked.

Run it, and the linear-scaling tests next to it, with cargo test --manifest-path host/Cargo.toml layout. The in-tree generator in host/src/oracle/rng.rs is SplitMix64 seeded from ROC_HOST_SEED (decimal or 0x hex) or a fixed default, so every run checks the same 2,000 trees. Set ROC_HOST_ITERS to check more, and ROC_HOST_WORK_REPORT=1 with -- --nocapture to print the coverage:

$env:ROC_HOST_SEED = "0x1234"; $env:ROC_HOST_ITERS = "200000"
cargo test --manifest-path host/Cargo.toml --release layout::tests -- --nocapture

A failure shrinks the tree with ddmin (host/src/oracle/shrink.rs) and prints the run’s seed, the failing case’s own seed, the width and DPI and the shrunk tree. Set ROC_HOST_SEED to the printed run seed to replay it. To keep a failure as a regression test, copy the shrunk specs into a #[test] next to nested_rows_layout_is_linear.

Scrolling keeps the layout and moves every child with one ScrollWindowEx. A control whose top lies beyond the 16-bit range SetWindowPos accepts is parked at the clamp, and a scroll that brings it within reach moves it to its place; content_taller_than_the_native_limit_stays_in_place checks that at about 100,000 pixels. scrolled_pixels_match_a_full_repaint in host/src/test_host.rs compares the scrolled screen pixels with a full repaint. It needs a visible, unobscured window on an interactive desktop, so it is ignored by default; run it with cargo test scrolled_pixels_match_a_full_repaint -- --ignored.

A change to layout must keep the reference model unchanged and pass the property test. A deliberate change to layout behaviour changes the reference in the same commit, and the example specs and recordings show the change.

Check the host against oracles§

The host’s pure code is checked against simpler references, so a fix or an optimisation cannot quietly change behaviour. The oracles live in host/src/oracle/ and run with cargo test. They need no extra crates, and share the generator and shrinker described in Check layout against its reference model.

The wire tree model

oracle/model.rs holds ModelTree, a naive reference for wire::Tree. It keeps nodes in a Vec, finds ids by scanning, clones itself to make each command atomic and finds what changed by comparing before and after. The property test tree_matches_the_reference_model generates random edit sequences with wire_builder::Commands. They cover templates and instantiation, elements, text and comments, attributes, properties, listeners, row holes, moves, removal and clearing. About one edit in ten is invalid and must be refused. After every edit the test checks four things. The tree and the model must agree on whether the edit applied. The tree must pass Tree::check_invariants. The two canonical() forms must be equal. The recorded Tree::changes must match the model’s. A failure is shrunk with ddmin and printed with its seed.

Tree invariants

Tree::check_invariants asserts the following:

  • Parent and child links agree, and each child is listed once.

  • Every node is reachable from the root exactly once, so there are no cycles and no orphaned keys.

  • Wire ids and the nodes that carry them form a bijection.

  • Every ref targets a live node, and that node’s reverse index lists the ref.

  • Each row hole names either a removed node or a node inside its row.

  • The tag and listener indices are exact.

  • Recorded changes name only live nodes.

    A command that fails leaves the tree exactly as it was.

Change recording

Tree::changes (taken with take_changes) records the nodes created or changed in value, and the parents whose children changed. Setting a value to what it already is records nothing. Tree::revision and structure_revision let callers cache what they read, and Node::subtree_revision lets a collection skip an unchanged subtree. The host takes the changes once per sync, so coalesced turns sync with their union.

Surface::sync_changed groups the changes by the list view, data grid, tree view or option list that reads them and hands each its share as a list_view::Delta. The collection reads again only the rows, cells, nodes or options the delta names. When one of its child lists changed, it compares its mounted items with the new ones from both ends and reads only the range between, then plans that range with the same minimal reorder plans as a full read. A data grid patches its UI Automation table with only the cells whose value, feedback or editability changed, and announces only those. The full walk, Surface::sync, gives a collection no delta, so it reads everything, which is what the incremental path must match.

Incremental sync

Surface::sync_changed syncs only what Tree::changes names, and Surface::sync is the full walk it must match (see Incremental sync). host/src/sync_differential.rs checks them against each other. It mounts the same random UI in two hidden windows, one synced incrementally and one with the full walk, and applies random batches of edits to both: inserted subtrees of stacks, panels, tab pages, texts, buttons, checkboxes, switches, sliders, fields, progress bars, option lists and list views; removals and moves; attributes that change content, size, enabled state and colour; texts; and appearance changes. After every batch the two windows' NativeSnapshots and the placements of their last arrange must be equal. A batch that fails must fail in both, which ends the case as it would end the app. A failure shrinks with ddmin and prints its seed and case. ROC_HOST_ITERS sets the number of batches (default 300). ROC_WINDOWS_FULL_SYNC=1 makes a real app use the full walk, to tell an incremental sync bug from an app bug.

When you change what a control reads during sync, keep the two in step: anything Nodes::item or flex reads is part of a node’s layout fingerprint, and state that changes outside a sync must drop that node’s fingerprint, as refresh_grid and the civil field commit do. resumed_memo_matches_a_fresh_layout in host/src/layout/tests.rs checks that a layout memo kept across arranges, with the changed node and its ancestors invalidated, places exactly as a fresh layout, and that its changes, applied in order to the controls the last layout left, give the fresh layout’s order and places. The differential test also mounts content up to about 120,000 pixels tall and scrolls it, past the 16-bit child window coordinates.

Fuzz smoke

oracle/smoke.rs feeds real, generated and mutated command streams through Reader and Tree::command. The mutations are bit flips, overwrites, inserts, deletes, corrupt length words, truncation and splices. A command must apply or return an error. It must never panic or read past its input. The tree must pass its invariants after every command. The seeds are in host/fuzz/corpus/wire_commands/. To refresh them, run the example specs with ROC_HOST_WIRE_CORPUS set to an absolute directory. The host then writes every view command it applies to wire-<pid>.bin there. Copy the small files into the corpus. recorded_streams_apply_in_full checks that each one still applies without error.

Scaling

oracle/scale.rs provides assert_scales(what, n, max_exponent, work). It counts operations at n, 2n and 4n, never time, and fails when the log-log slope exceeds the limit: LINEAR (1.15) or CONSTANT (0.1). The wire tree counts tree-scan (child lookups and ref sweeps) and tree-shift (siblings moved to make or close a gap). A node’s children are a linked list, so a child lookup is one step and inserting, moving and removing a child moves no siblings: tree-shift stays 0. WindowPlan::visit counts plan-visit, and the raster bridge counts bridge-visit. Write a scaling test before a complexity fix, watch it fail, then fix.

Seeds and iterations

Every random test prints ROC_HOST_SEED=0x... and the case number when it fails. Replay a failure with that seed, for example ROC_HOST_SEED=0x1234 cargo test --manifest-path host/Cargo.toml tree_matches, with the printed seed in place of 0x1234. ROC_HOST_ITERS sets the number of cases. The defaults are 300 model and plan cases and 2,000 fuzz inputs. Before a change to wire.rs, windows.rs or the sync in view.rs, run once with ROC_HOST_ITERS=20000. Set ROC_HOST_WORK_REPORT=1 to print the scaling points and the generators' statistics.

Verify specs against a fresh mount§

With ROC_WINDOWS_SPEC_VERIFY=fresh, the spec runner checks every step against a fresh mount. After each step and its pump, it mounts the app’s current tree fresh in hidden twin windows. The twins get the same client size and the same decoded images. The runner then compares a NativeSnapshot of each synced window with its twin (host/src/native_snapshot.rs). Per view, the snapshot holds the class, text, rect in the parent’s client area, visibility, enabled state, button check state, slider position and the colours the view was styled with. Per parent, it holds the z-order of the mounted children. Views are keyed by tree key. The verify work is left out of expect-work counts, and the twin leaves the synced window’s text measurement cache intact, so a step after it measures what it would have.

$env:ROC_WINDOWS_SPEC_VERIFY = "fresh"
roc ../../cli/windows.roc -- test --target x64mingw

blueprint run test-native-verify (scripts/build.roc -- test-native-verify) runs every example’s specs this way, and CI runs it after the native scenarios.

A mismatch fails the step and lists every difference, with both windows' client size and scroll state. It is a real bug unless it comes from state the tree does not hold. The snapshot leaves that state out:

If a difference is state like this, add it to that list in native_snapshot.rs. Otherwise fix the incremental path.

Benchmark the host§

blueprint run bench measures how the host’s work grows as an app gets bigger. It runs real apps through the spec runner and counts work, so its results do not depend on the machine. It needs a Windows desktop session and the x64 host in platform/targets/x64mingw.

blueprint run bench
blueprint run bench -- --large --no-examples
blueprint run bench -- --only list --sizes 1000,2000,4000

The quick default runs every scenario at three small sizes, three times each, and then samples the examples. It takes under two minutes. --large runs once at sizes up to 100,000 list rows and takes much longer. --repeat N sets the repeats, --no-examples skips the examples and --examples-only skips the sweep.

examples/bench is one app with a scenario per dimension. Its boot storage picks the scenario and the size, and shared buttons change one row, a tenth of the rows or every row, reorder, filter, unmount and remount, switch the appearance and advance a shader. Each tests/specs/*.scm file is a scenario at a small size and passes as an ordinary spec. The harness rewrites the spec’s bench-size setup and drops its assertions. It adds an (expect-work (sync-visit >= 0)) probe after every step and runs the plan with ROC_HOST_WORK_REPORT=1, so each probe appends a JSON line for that step to work.txt (Read the work report). Each line names the step it measured by line, column and command, so the harness matches a line to its step by that identity, not by its position, and a missing line cannot shift the rest onto the wrong steps. A step followed by await-work shares its probe with the wait. mount is the work from startup to the first step. The harness still reads the counter-only lines of an older host by position.

The harness writes three reports to build/bench/:

results.json

every counter of every step at every size, each step’s span times (spans_us), GDI and USER handles before and after (gdi, user) and peak working set, the run times, the fits and the example samples.

summary.md

regressions and handle leaks, flagged growth, run times, the time per span and the handle deltas at each scenario’s largest size, and every fit.

examples.md

each example spec step ranked by its total work, and the three most expensive steps for each counter.

Each fit is the least-squares slope of log(count + 1) against log(size) for one scenario, step and counter. A slope near 0 is constant work and near 1 is linear work. Above 1.15 is flagged superlinear. A step whose change has a fixed size, such as click Change one, is flagged nonconstant above 0.15. Pump ticks count timed polls and are never flagged or gated. Wall time and span times are advisory: they keep the fastest of the repeats and never gate.

Handle leaks gate at every size, quick or large, without a baseline. A round trip in round_trips, such as click Toggle then click Toggle #2 in churn, must end with the GDI and USER handle counts it started with. A steady step in steady_steps, one that changes only text and values such as click Change one, must end with the counts it began with. Both allow 2 handles plus 1% for a caret or a tooltip. Add a pair to round_trips when a scenario gains a step that undoes another.

To add a scenario, add a case to Bench.Scenario and its view in examples/bench/src/main.roc, and add tests/specs/NAME.scm with (setup (local-storage "bench-scenario" "NAME") (local-storage "bench-size" "N")). Add its quick and large sizes to sizes_for in scripts/bench.roc, and add a step to constant_steps if its change has a fixed size. Keep a process under 10,000 USER handles: every control is its own window.

bench/baseline.json holds the fits of a quick run. Each run gates on it. A count that rises more than 10% plus two at any size fails, and so does a whole growth order that rises. Work on a step that had none also fails. A run reports the least count of its repeats, and the baseline keeps the greatest it saw, so worker timing does not fail the gate. A fall in growth order prints IMPROVED. Flags in the baseline record known-bad growth.

Change the baseline only on purpose, in the commit that changes the work. Run blueprint run bench -- --update-baseline, which repeats each scenario six times, and review the diff. One fit is one line. A counter the baseline has never recorded, such as a newly added Op, prints NEW COUNTER and is not gated until an update records it, so a new counter needs no baseline change in the commit that adds it. The baseline format is unchanged by the JSON report.

The benchmark runs locally only. CI does not run it, and long fuzz or oracle campaigns such as ROC_HOST_ITERS=20000 are local too.

test --stage-native also writes demo plans to demo-plans/ beside plans/, so the harness can sample demos. Demos run without their wait steps.

Diagnose a local Windows build§

Use the example’s build/x64mingw/ or build/arm64mingw/ executable from the commit under test. Save traces and local tools under the ignored repository-root build/windows-diagnostics/ directory.

Review each feature’s security model§

Include a security discussion in every feature design or change description. Use the authority contract and describe the feature’s hazards, the controls that address them, and what remains outside those controls. For work that leaves the security boundary as it is, a brief explanation is enough.

Put lasting explanations of hazards, controls, and security limits in the relevant manual chapter. Keep API doc comments focused on the contract callers need at the call site, including authority, defaults, and result tags. Link to the manual for the rationale and examples.

From an example’s directory, record its gallery scenario on a Windows desktop.

roc ../../cli/windows.roc -- record tests/specs/demo.scm --format gif

The command prints its output directory under build/specs/. Copy the resulting demo.gif to docs/images/<example>.gif at the repository root. Keep the example’s scenario under tests/specs/ so the recording can be repeated.

The HTTP demo uses a local response. Run this from examples/http in a separate terminal while recording that example.

roc ../../scripts/serve.roc -- tests/fixtures --port 48393

Cross-build the platform from source§

For the maintainer build on Apple Silicon macOS, install Blueprint 0.13.0, Roc as roc, Zig 0.17.1, and Rustup. Blueprint.roc names the tooling compiler and Blueprint.lock carries the fetched digests. rust-toolchain.toml selects the Rust version and Windows targets. Use the Roc nightly validated by this checkout when testing the current compiler and platform together.

blueprint run check
blueprint run build
blueprint run bundle
blueprint run docs

check runs Rust format, lint, and portable tests, checks generated ABI bindings using the vendored host/glue/RustGlue.roc, runs Roc expects and spec validation, and cross-builds the examples. build writes the example executables under examples/<name>/build/<target>/. bundle writes the Windows platform bundle to dist/platform/. docs renders the manual website, Markdown, and PDF under .docs-out/ on macOS or Linux using the locked roc-docs utility from roc-automation. The Documentation workflow builds the same manual for pull requests and publishes the main branch to GitHub Pages.

The platform examples depend on the local platform through relative paths. Keep compiler pins in scripts/, keep generated ABI changes reviewable, and keep build products out of source control. An example with specs adds .scm files under tests/specs/ and data under tests/fixtures/.

To exercise packaging directly from the checkout, build the local MSI packager and run the CLI from the example directory.

blueprint run packager
export ROC_WINDOWS_MSI="$PWD/packaging/target/release/roc-windows-msi"
cd examples/counter
roc ../../cli/windows.roc -- package --target x64mingw

Publish an MSI packager release§

The MSI packager, roc-windows-msi, has its own version in packaging/Cargo.toml and its own GitHub release tagged msi-<version>. It changes rarely, so several platform releases can share one packager release.

To release a new packager, raise the version in packaging/Cargo.toml and merge that change to main. Then run the Release MSI packager workflow on main with the same version and publish enabled. It cross-builds the six packagers on macOS, records their SBOMs, license notices and SHA256SUMS, attests the files and publishes them. The release is not marked as the latest, so the newest platform release keeps that place. Pull requests that change the packager or the release scripts run the same staging as a dry run.

To stage the files locally on Apple Silicon macOS, add the Intel macOS and Linux musl Rust targets.

rustup target add x86_64-apple-darwin x86_64-unknown-linux-musl aarch64-unknown-linux-musl
blueprint run release -- packager 0.1.0 dist/msi

Stage a release§

Record user-visible changes in docs/releases/unreleased.adoc as they land on the integration branch. Fold those entries into the versioned notes when preparing the next release.

Copy the release notes template to docs/releases/<version>.adoc. Replace the title’s version, write a short summary for app authors, and remove the template comments. Keep {roc-version}, {platform-url} and {cli-url} for the workflow to fill from the tested compiler and staged assets. Use HTTPS links and keep the release notes self-contained for GitHub.

The Release Windows platform workflow stages the public assets and a loopback preview, then uses the preview to bootstrap Reading List and test MSI installation, upgrade, launch, and removal on Windows x64 and ARM64. Run it on main with publish enabled to attest the staged files, verify the GitHub draft assets, and publish. The final job bootstraps from the public URLs. Pull requests render the newest authored version’s notes during the dry run. A manual run uses the version supplied to the workflow.

A platform release does not build the MSI packagers. It links to the packager release pinned in packaging/msi-release.sha256, which lists the SHA-256 of each of the six roc-windows-msi-<version>-<system> files. The staged windows.roc embeds their msi-<version> download URLs and checksums, and windows.roc -- package downloads the one for the build machine and checks it. Releases that pin the same packager share its files.

To move the platform to a new packager release, replace the pin with the packager lines from that release’s SHA256SUMS.

gh release download msi-0.1.0 --pattern SHA256SUMS --output - \
  | grep -E '  roc-windows-msi-[^ ]+$' | grep -v '\.spdx\.json$' > packaging/msi-release.sha256

Download the pinned packagers and check them. Build the platform bundle and pass its generated path, the release version, the public asset base URL and the packager directory. The base URL must end with the release version, because the packager URLs point to msi-<version> beside it.

gh release download msi-0.1.0 --dir dist/msi --pattern 'roc-windows-msi-*'
(cd dist/msi && sha256sum --check ../../packaging/msi-release.sha256)
blueprint run bundle
blueprint run release -- --packagers dist/msi 0.1.1 dist/platform/HASH.tar.zst "$RELEASE_BASE_URL" dist/release

The output directory must be new. Every attachment includes the version. The CLI and platform bundle use underscores in the version so Roc can read URLs containing a dotted release tag. The standalone launcher and the two license files use the dotted version. The scaffold writes the fetched launcher as windows.roc.

Stage and serve the files to test a local HTTP URL. A preview copies the pinned packagers beside the platform and links to those copies. Without --packagers, a preview on macOS builds the packagers from source instead, which is how CI tests packager changes before their release.

blueprint run release -- --local --packagers dist/msi 0.1.1 dist/platform/HASH.tar.zst dist/release-preview
blueprint run serve -- dist/release-preview

The preview server uses Basic CLI’s TCP support and binds to 127.0.0.1:8000. If you choose a different port with serve --port, pass the matching loopback URL to the release task when staging the files.

In another terminal, set TOOL_BUNDLE to the generated windows-0_1_1-HASH.tar.zst filename and use a fresh directory and cache to check the first-user path.

roc "http://127.0.0.1:8000/$TOOL_BUNDLE" -- init /tmp/windows-release-preview
cd /tmp/windows-release-preview
roc windows.roc -- test --check
roc windows.roc -- package --target x64mingw
roc windows.roc -- package --target arm64mingw

Before a public release, verify the exact bytes to be published, include license and provenance evidence, and produce validated SBOM sidecars. Use the roc-automation platform guide for the release matrix and the SBOM contract for release evidence.