Skip to content

feat(harmonyos): add a HarmonyOS preview target - #79

Merged
houko merged 15 commits into
nsgo-dev:mainfrom
togotop:feat/harmony-main
Nov 16, 2026
Merged

houko merged 15 commits into
nsgo-dev:mainfrom
togotop:feat/harmony-main

Conversation

@togotop

@togotop togotop commented Nov 14, 2026

Copy link
Copy Markdown

Summary

Adds harmonyos as a build and test target. nsgo build -target harmonyos assembles a
HAP in Go, the engine runs as WebAssembly inside ArkWeb, and an ArkTS render layer applies
each mount batch to ArkUI views.

This is a preview, not a shipping target, and is scoped as such:

  • it stays out of -target all, since its packages are unsigned;
  • docs/architecture/harmonyos.md marks it Status: preview and lists what each
    backend limit costs;
  • the renderer's coverage is a checked-in table (cmd/nsgo/harmony/items_test.go), so a
    driver kind that loses its renderer, or gains one still listed as unsupported, fails
    the suite.

What the renderer draws

Layout and glyphs are the platform's: the engine lays every view out and measures text
through ArkUI's own measurer, then the render layer places native components at those
frames.

Views: boxes with background, border, corners, opacity; text with spans; text fields;
scroll views with drag, glide, rest, pull to refresh and sticky cells; images from URLs,
embedded bytes or the app's resources at the device's pixel density; canvases replayed
from the engine's draw ops; web views; videos; modals; screens with a system header.

Input and system: every finger on the surface (the engine hit-tests them, so drags on a
slider or a sheet follow), physical keyboard shortcuts matched against the app's keymap,
the back gesture, the system alert dialog, clipboard text and images out, opened links,
the photo/file/folder pickers, the save dialog, the camera picker, a home-screen card
written through widget.Update, and the --nsgo-fps monitor.

How it works

Part Choice
Engine GOOS=js/wasm, the no-DOM build the mini programs use
Carrier ArkWeb attached at 1×1, serving the page from rawfile in onInterceptRequest
Bridge page→ArkTS JavaScriptProxy (answers synchronously); ArkTS→page messages
Nodes imperative FrameNode tree: typeNode for Stack, Text, TextInput, Scroll, Image; BuilderNode for spans, canvases, images from
bytes, headers
Package HAP assembled with archive/zip; module.json and pack.info are plain JSON
Host the committed bytecode carries a 64-byte placeholder bundle that Package swaps byte for byte, so one host serves every app without the SDK;
with hvigorw and OHOS_BASE_SDK_HOME present, CompileHost builds a host for the app's own id instead
Tests nsgo test -target harmonyos builds the tests as the HAP's module and drives the app in the page

nsgo doctor reports whether hdc and the SDK are present, and -run installs and
starts the ability, passing the engine's flags as Want parameters (--ps / --pb), so
--nsgo-fps can be turned on for an already-built HAP.

Fixes found by running a real app

The second commit fixes what only showed up once a non-trivial app ran on the emulator:

  1. A delete-only batch left its views on screen. syncNode was gated on dirty, so a
    structural batch naming only deleted views never walked to the parents whose
    syncChildren drops their ArkUI children. The stale modal then swallowed every later
    press — the app looked frozen after its first interaction. Structural batches now sync
    in full; ordinary batches still write only the views they name.
  2. BuilderNode leaves ignored their position, so canvases and rich text landed at the
    parent's top-left corner. They are wrapped in a Stack that holds the frame.
  3. measureTextSize answers the constraint's width, not the text's, which made every
    centred label start at the left edge. Wrapped text is measured again without a
    constraint and takes the smaller width.
  4. The bottom inset came from TYPE_SYSTEM, which a full-screen window does not fill
    with the navigation indicator, so a bottom bar sat under the gesture area. It now
    takes the larger of that and TYPE_NAVIGATION_INDICATOR.
  5. A multiline field used its whole height as lineHeight, dropping the glyphs into
    the middle of the box; it uses the font's line height and aligns to the top.
  6. Replacing a HAP under a running app left a black window: the old process kept a
    page that no longer loaded, and aa start brought that back instead of starting the
    new one. -run and nsgo test now force-stop first, and a test run stops its own HAP
    when it ends so it cannot cover a later launch.
  7. A test run whose page never started waited forever on hilog; it now fails after
    two minutes with a message saying the page did not start.

Known limitations

Each has its reason in docs/architecture/harmonyos.md#constraints:

  • Native and Shader views: a Go app ships no ArkTS component to mount, and ArkTS has
    no WebGL or WGSL.
  • Desktop-only items (dock, menus, popup menus, windows, tray, global shortcuts, launch at
    login).
  • Notifications, badges and haptics: no public SDK interface answers them here.
  • Reading the clipboard is refused to an ordinary app (READ_PASTEBOARD is system_basic),
    so a read answers empty; writing works.
  • SaveOptions.Path is unsupported — js/wasm has no filesystem — so only
    SaveOptions.Data saves.
  • fetch('resource://rawfile/...') is refused; the host serves those requests itself.
  • Accessibly focused views and ItemBackPreview / ItemHistory are not wired.
  • Nothing here is signed for Huawei devices.

Testing

Run on the OpenHarmony emulator (x86_64, API 24):

  • go test ./cmd/nsgo/harmony/... ./internal/platform/harmonyos/... — including the
    coverage tables, which parse internal/driver's constants and the host's Index.ets so
    that a silently-dropped kind cannot pass.
  • Built, installed and drove a real notes app (about 23 MB HAP) through tab navigation,
    a dialog opened and dismissed, a note created, titled and typed into, and back to the
    list — the first interaction used to freeze the app, which is how (1) was found.
  • nsgo test -target harmonyos -run TestPhoneTabs passes on the device.
  • go vet clean; gofmt clean; the wasm backend and the tool build.

Not covered by this PR, and worth knowing before merging: the emulator is the only device
this ran on, no test drives every view kind through the device-hosted path, and the rest
of the app surfaces (menus, password dialogs, undo/redo) were not exercised on device.

Reviewer notes

  • The host bytecode, resource table and module.json under cmd/nsgo/harmony/host/ are
    committed binaries. host/build.sh rebuilds them with DevEco; nsgo build never needs
    it.
  • .gitignore now excludes signing material (.ohos/, keystores, profiles), with the apk
    tests' fixtures excepted.
  • internal/platform/ops and internal/platform/textruns move into layering_test.go's
    shared platform list, since the HarmonyOS backend and the mini programs both use them.

@github-actions github-actions Bot added the conflict Conflicts with the base branch; resolve it first label Nov 15, 2026
@github-actions github-actions Bot added enhancement New feature or request documentation Improvements or additions to documentation Web core cli size/XL and removed conflict Conflicts with the base branch; resolve it first labels Nov 15, 2026
@github-actions github-actions Bot added the conflict Conflicts with the base branch; resolve it first label Nov 16, 2026
@github-actions github-actions Bot added conflict Conflicts with the base branch; resolve it first and removed conflict Conflicts with the base branch; resolve it first labels Nov 16, 2026
@github-actions github-actions Bot added conflict Conflicts with the base branch; resolve it first and removed conflict Conflicts with the base branch; resolve it first labels Nov 16, 2026
@houko

houko commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Device acceptance on a retail HarmonyOS phone

Device: Huawei Enjoy 90 Plus (JUY-AL50), HarmonyOS 7.0.0.111, API 26, over USB with hdc.

Signing and install. As the PR says, the unsigned HAP is refused (hdc install returns code:9568320 error: no signature file.). For the rest of this run I signed the gallery myself:

  • I used an AppGallery Connect debug profile for dev.oneo.nsgo.gallery, with hap-sign-tool sign-app.
  • The profile has to match the bundle exactly, so the build needs build.harmonyos_bundles: exact. The padded <id>.nsgohost000… name cannot match any AGC profile.
  • My machine only has the API 24 command-line tools, whose hvigor rejects "compileSdkVersion": "26.0.0". So the host for these runs was compiled against API 24, with settings.openAppDetailSettingsPage (API 26) stubbed out locally. Nothing else differs from this branch.

nsgo test -target harmonyos always packages with harmony.Package (padded name), so a test HAP cannot be signed for a device today. On the phone it ends at the same 9568320. Before the fix pushed here it waited two minutes and then reported that the page never started.

What works and what doesn't

Area Result
Views, text, spans, layout Pass, apart from the border, clip and tint gaps below. Rich text never updated before the fix below.
Text fields and IME Pass: focus ring, system keyboard, typing, keyboard inset. Glyphs sit at the bottom of single-line fields.
Scroll: drag, glide, pull to refresh, nested scroll Pass
Scroll: Paging and SnapToInterval Not supported: the sc op does not carry them, so a pager rests between pages
Images (URL, embedded, asset, corners, fit) Pass. Local SVGs (star.svg, mark.svg) are blank and TintColor is not applied.
Canvas Draws, but text comes out at a third of its size (details below)
Web view loading a URL Pass
Web view with inline HTML Blank, and messages are not wired either way
Video Pass: plays, progress, controls
Screens, header, back button, back gesture Pass. The header stays light when the app switches to dark.
System alert dialog Pass: shows and answers the button
Clipboard Write accepted; read answers empty, as documented
Open links Pass, including the refused javascript: URL
Slider drag Pass
Multi-finger gestures, photo/file/folder pickers, save dialog, camera picker, home-screen card Not tested: they would expose the owner's photos and files or change their home screen
--nsgo-fps via aa start --pb nsgo-fps true Pass
Tab bar in ui.TabShell Missing (details below)

gallery video

Performance and taps that seem to do nothing

The app felt slow and taps often seemed lost. I instrumented the host, timing each apply on the UI thread and the frames queued in the page, and measured the gallery on the phone. Each "before" and "after" figure is from three runs.

Measurement Before After
Navigate to Buttons, structural batch on the UI thread 190–198 ms 110–115 ms
Follow-up batch after each navigation 47–49 ms ≤ 8 ms
Navigate back 104–119 ms 50–77 ms
Touch up until the new page's batch is applied 278–468 ms 201–378 ms
Photos demo, three flings: UI-thread time in batches 1,736 ms, worst batch 126 ms 113 ms, worst batch 10 ms
Frames queued in the page with --nsgo-fps up to 112 at launch, 12–15 per navigation 1
Rich text that changes, e.g. System → Frames and timers counter never redrawn redrawn

The rich-text bug is what made taps look dead. Any label, value or counter drawn as spans ignored the change a tap made, because spans were keyed by index only.

Not addressed here: the engine still spends about 90–260 ms in WebAssembly before the first batch of a navigation. On a first visit that includes about 2.4 ms per synchronous measure round trip (64 on Buttons).

Commits pushed to this branch

  • 38c2a486 fix(widget): define publish and available on darwin. The widget package (and the gallery) stopped building for macOS and iOS: undefined: publish.
  • 78edce4e fix(nsgo): fail harmonyos runs when hdc refuses the install. hdc exits 0 on a refused install or a failed aa start, so build -run reported success and nsgo test hung for two minutes.
  • a530afa2 perf(harmonyos): keep one engine frame in flight. Before, each vsync queued another nsgoFrame() behind the last one, and touches waited behind those frames.
  • ace6521c perf(harmonyos): clear the dirty flag of views drawn as they are made. Removes the second write of every new view.
  • 52333eb5 perf(harmonyos): sync only the parents a structural batch changed. Replaces the full rewrite of the tree on every structural batch, including the batches a list sends while scrolling. It keeps fix 1 of this PR (delete-only batches). A changed header or sticky cells now mark their view.
  • fa0e88e5 perf(harmonyos): write only the attributes a view changed.
  • 7beb0c33 fix(harmonyos): redraw rich text whose runs changed.

go tool nsgo check, go tool nsgo check -target all and go test ./cmd/nsgo/harmony/... ./widget/... pass. All of the above was verified on the phone.

The host bytecode needs rebuilding. I could not rebuild the committed host under cmd/nsgo/harmony/host for API 26: my hvigor is too old and the OpenHarmony 7.0 macOS SDK ships x86_64 tools only. Please rerun host/build.sh so the padded-name host picks up the template changes. Hosts built with CompileHost already do.

Other problems found (not fixed here)

  1. No tab bar in any ui.TabShell app. The backend reports OSAndroid, so mobile.IsAvailable is true and TabShell uses mobile.TabBar. That is a Native view (nsgo/tab-bar) with no renderer here, so the bar is simply missing. The gallery's whole Basics tab (Text, Images, Scroll, Canvas, WebView, Video, System, Widgets…) is unreachable on a phone; I opened those demos with NSGO_GALLERY_OPEN.
  2. Canvas text is a third of its size. ctx.font is written in px while the canvas draws in vp. Changing 'px ' to 'vp ' in the font string fixes it on the device: left is before, right is after.
    canvas
  3. Inline-HTML web views are blank. The mounter's web op sends only Source.Src, never Source.HTML or BaseURL. WebPostMessage and page-to-app messages are not wired.
    webview
  4. Borders, corners and other view styles are simplified. mounter.style takes Borders.Top and Corners.TopLeft for all edges and corners, so one-edge separators become full boxes. Clip, shadows and TintColor are not sent, so a data table's rows overflow their card and tinted logos keep their colors.
  5. The header stays light when the app switches to dark. No new ItemScreen reaches the host after the appearance changes, and the header's default colors are hard-coded light.
    dark
  6. The home screen names every app "NSGo". module.json gets the literal label, but labelId still points at the host's NSGo string, and the launcher uses the id.

Rich-text counter before and after 7beb0c33:

counter

oneo-me and others added 11 commits November 17, 2026 07:39
The harmonyos target, its ArkTS host and its render layer come onto the
current main as a scoped port: cmd/nsgo/harmony builds and packages the
HAP, internal/platform/harmonyos runs the engine in ArkWeb, and the
driver's frame clock and kind names arrive with them. Everything else
stays as main has it: the engine, the backends and their build options
are untouched, so the branch's cross-platform ops writer and text runs
are not part of this port.

The tool learns the target in build.go, package.go (running a HAP with
hdc), doctor, check, project settings and the test runner, and keeps it
out of all, as its packages are unsigned previews. A share, an update
check and a notification permission answer with what the platform has
rather than leaving an app's callback waiting.

Checked: go tool nsgo check; the harmonyos and cmd/nsgo/harmony tests;
go build ./...; examples/hello builds into a HAP and its tests pass on
the HarmonyOS emulator (TestGreets 1.06 s, TestNotificationServicesAnswer
890 ms) and headless. cmd/nsgo's TestInitTemplates fails on this machine
with the module proxy off, as it does on main.
A structural batch that only deletes views left their FrameNodes on the
ArkUI tree: syncNode is gated on dirty, so syncChildren never ran to drop
them, and the stale modal covered every later press. Walk the tree in full
for structural batches; ordinary batches still write only the views named.

- Wrap BuilderNode leaves in a Stack: their frame node ignores position,
  so canvases landed at the parent's top left corner.
- Measure wrapped text without a constraint too: measureTextSize answers
  the constraint's width, which left labels as wide as their cell.
- Take the bottom inset from TYPE_NAVIGATION_INDICATOR, which a
  full-screen window's TYPE_SYSTEM area does not include.
- Give multiline inputs their font's line height, not their whole height,
  and align their text to the top.
- Force-stop the app before installing a HAP, and stop the test HAP when
  its run ends, so no stale black window hides the next launch.
- Fail a test run whose page prints nothing within two minutes instead
  of waiting forever.
Rebasing onto the current main brought eleven mount items and six events
this target never answered. What the SDK has is answered now: keep-awake
holds the screen on through setWindowKeepScreenOn, biometrics ask
userAuth for the enrolled kind and show its prompt, and a permission
asks for the microphone or the camera with checkAccessTokenSync and
requestPermissionsFromUser, opening the app's settings page through
settings.openAppDetailSettingsPage. Every other permission key, which
only a Mac keeps, answers unavailable at once.

An overlay permission answers unavailable, since showing over other apps
needs SYSTEM_FLOAT_WINDOW, a system app's.

An app declares the permissions its module asks for in nsgo.yaml's
harmonyos.permissions, which the build writes into module.json with the
reason and used scene a prompt needs: without them the request answers
denied with no dialog.

The bridge test found a real bug: saved() was called by the renderer but
neither declared on Bridge nor listed in javaScriptProxy's methodList, so
a save that never reached the dialog panicked the module. Both are
fixed, and the test now checks every call against the list.

Checked on the HarmonyOS emulator: a test app reads the microphone's
status as denied and accessibility as unavailable, gets no enrolled
biometric, and gets both keep-awake calls; examples/hello passes there
and headless, and the harmony package tests pass. The emulator has no
camera or microphone, so no prompt shows for either: an ask answers
denied with dialogShownResults false.
.agent/skills/nsgo holds the site's llms.txt, which lists every page of
the documentation as Markdown, and a SKILL.md that points at it: an
agent working in this checkout can find the first-party page for a
component, a command or a target instead of guessing from a signature,
and is told to read the source at the commit at hand since no API is
stable.

The skill is not the one apps install (skills/nsgo): that one is for
writing an app, and this one is for finding the docs while changing the
engine.
upstream moved the module root's run_*.go and view_*.go into
internal/backend (a45d732) and the module-wide tests into
internal/moduletest, so the harmonyos backend, which lived in the root
as run_harmonyos.go, no longer filled in the `run` that backend.Run
calls and the target stopped compiling.

Move it to internal/backend/run_harmonyos.go and take the API the
refactor left: engine.App and Options instead of App and options.
internal/backend already may import internal/platform/, so the layering
rules hold.

Record what a span's Style.Cursor does here, which the new core field
raises: nothing, as the platform has no pointer.
A Windows download that carries no signature, or one from a certificate
SmartScreen does not know, warns the user before it opens. MyGo signs
Windows packages; NSGo wrote them unsigned, and Windows code signing was
a roadmap gap.

Add it here without the Windows SDK, so a Mac signs what it builds:

- internal package cmd/nsgo/authenticode signs a PE image: it parses the
  headers, computes the Authenticode digest (headers without the checksum
  and certificate table entry, every section in file order, the bytes
  between and after them, a short last block padded to 8 bytes), writes a
  WIN_CERTIFICATE holding a PKCS nsgo-dev#7 SignedData over SpcIndirectDataContent
  and recomputes the PE checksum. A re-signed image replaces the old
  signature rather than appending a second. The digest covers
  SpcIndirectDataContent's value, not its SEQUENCE header, as Authenticode
  readers check it.
- sign.certificate (a .pfx, NSGO_CERTIFICATE_PASSWORD) signs the
  executable, the command companion, the resources' PE images that carry
  no signature, and the installer. sign.sign_command signs them with a
  tool of its own, %1 standing for the path, for a hardware token or a
  cloud service. sign.timestamp_url, DigiCert's unless "none", asks an
  RFC 3161 server for a token, which the signer carries as its unsigned
  attribute so the signature outlives the certificate.
- The installer's uninstaller comes from makensis, so it signs through
  NSIS's !uninstfinalize running `nsgo sign-uninstaller` with the
  certificate in the environment; that needs NSIS 3.08, and without it
  the uninstaller stays unsigned.
- -certificate, -sign-command and -timestamp-url replace the three from
  the command line. build refuses two ways of signing at once, a
  certificate on a build that names no Windows target, and it refuses a
  certificate outside a release build.

Verified: the package's tests, including osslsigncode's verification of
an image signed here, and a real build of examples/hello whose exe, setup
and uninstaller each verify with osslsigncode.

The MSIX stays unsigned: AppxSignature.p7x is a package signature of its
own, recorded in the roadmap.
f72ed88 added a call to nsisScript before the harmonyos branch gave it a
context, and the rebase that replayed the signing change updated the two
calls above it but not this one, so cmd/nsgo did not vet or test.
widget.Update and Available now call publish and available, which the branch defines in widget_js.go and widget_other.go (!darwin && !js) but not in widget_darwin.go, so the widget package, and every app that imports it, stopped building for macOS and iOS (undefined: publish, undefined: available). widget_darwin.go gets both, with the body Update and Available had before: write the timeline into the app group's container and ask WidgetKit to reload the kind.
hdc exits 0 when a device refuses a HAP or aa start cannot start the ability, and says so only in what it prints. build -run read only the exit status, so on a phone that refuses an unsigned HAP (code 9568320, no signature file) it reported success with nothing installed, and nsgo test -target harmonyos waited its two minutes and then blamed the page for not starting. The install and start steps now also fail on the error line hdc prints, with its output, for both -run and the test runner.
The display clock fires every vsync and each tick queued another runJavaScript('nsgoFrame()') whether or not the page had finished the last one. Whenever a frame took longer than a vsync, ticks piled up in the page: on a Huawei Enjoy 90 Plus (HarmonyOS 7.0) up to 112 frames were queued at launch with --nsgo-fps and 12 to 15 after each navigation, and every touch, scroll report and event the host sent waited behind them, so taps answered late or seemed lost. A tick now finds the pending frame and skips; the engine's clock reads the time, so the next frame catches up. With the change at most one frame is queued.
syncNode writes a view it creates but left its dirty flag set, so the next batch that reached the view's parent wrote it, and every view under it, again: after each navigation in the gallery a small follow-up batch rewrote about 300 views and took 47 to 77 ms on the phone. Making a view now spends its flag; that batch takes 4 to 8 ms.
A structural batch walked the whole tree and wrote every view's attributes again, so that a batch naming only deleted views would still reach the parents that drop them. Every navigation, and every batch a list sends as it recycles rows while scrolling, paid for the full tree: on the phone a scroll batch in the Photos demo took up to 126 ms on the UI thread (1.7 s over three flings) and navigating back 104 to 119 ms. The tree now records the parents whose children a batch inserted, moved or removed, and the renderer syncs those children (removals first, so a moved view leaves its old parent before the new one takes it) and then writes only the views the batch named; a new root is still drawn in full, and a batch that changes a screen's header or a scroll view's sticky cells marks that view, as those are drawn when the view is written. Removing stale children collects the wanted ones once instead of scanning every child for each, which was quadratic in a long list. Navigating back now takes 71 to 81 ms, and with the next commit the scroll batches take at most 10 ms (113 ms over the same flings).
style wrote every common attribute of a view, and text every font attribute, each time the view was written, and each write crosses into ArkUI and dirties the node. A navigation in the gallery writes about 700 views, new ones and the covered page's resized ones, so style alone took 95 to 160 ms of it on the phone. The renderer now keeps what it last wrote to each node and writes an attribute only when it differs, sets a press handler once, and takes a Stack or Text it just made as holding ArkUI's defaults, so a new view's default background, corners, border, opacity, transform and visibility are not written at all. A navigation's structural batch went from 187 to 191 ms to 110 to 115 ms, and navigating back from 71 to 81 ms to 50 to 77 ms.
Rich text is a Text of Spans built with ForEach, which was keyed by each run's index alone. ForEach keeps the child of a key it has already built, so when a batch changed a run's text or style but not the number of runs, the span kept what it first showed: on the phone the gallery's interval counter stayed at 0 while its timer ticked every second, and any label, value or counter drawn as rich text ignored the taps that changed it, which read as taps getting no response. A run is now keyed by its index and its content, so a changed run is built again.
driver.FindKey now takes the keys the focused view uses and returns the binding's ID, which EventKey carries in Count; the page knows only whether a text input has the focus, so it reports KeyUseText alone. Main also added items and events the preview does not answer yet; the coverage table lists them so the suite passes and their gap stays visible.
@houko
houko force-pushed the feat/harmony-main branch from 7beb0c3 to b2ae23f Compare November 16, 2026 22:48
@github-actions github-actions Bot removed the conflict Conflicts with the base branch; resolve it first label Nov 16, 2026
@houko
houko merged commit 35e2c98 into nsgo-dev:main Nov 16, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli core documentation Improvements or additions to documentation enhancement New feature or request size/XL Web

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants