diff --git a/docs/cells.md b/docs/cells.md index 2cb0a5bf2..b22747d11 100644 --- a/docs/cells.md +++ b/docs/cells.md @@ -380,6 +380,15 @@ unrelated app VMs. Cancellation retires jobs until their workers and parsers finish; it never joins an unfinished worker in a frame. Web and Windows retain the synchronous fallback, as does validation of additional node-app trees. +Additional app icons also load through one owned worker on Linux and Android. +Drawing requests an icon and uses the catalog outline until its copied shape +is ready. Cache reads, payload hashing, program verification and cache writes +run on that worker without invoking an app or the host's shared asset index. +The small persistent icon cache is keyed by the signed payload digest. A +completed job is published only while its slot, account, package revision and +temporary-session state still match; obsolete jobs finish without blocking +navigation or starting more workers alongside them. + Practice downloads, cold loads and cache reviews use the same owned content worker. Recently used verified packs stay in memory within a soft 64 MiB budget; the selected practice and its voices are never evicted for that limit. diff --git a/src/cells/node_apps.zi b/src/cells/node_apps.zi index 153ff3e1d..f06df2d06 100644 --- a/src/cells/node_apps.zi +++ b/src/cells/node_apps.zi @@ -38,6 +38,7 @@ Time :: #import "date_time_linux"; #import, file "node_app_tree.zi"; #import, file "node_app_snapshot.zi"; #import, file "node_app_replacements.zi"; +#import, file "node_icon_work.zi"; #import, file "achievement_media.zi"; Nested :: #import "apps/host"; #import, file "package_manager.zi"; @@ -78,8 +79,6 @@ NODE_APP_CATALOG_RETRY_SECONDS :: 30 NODE_APP_REGISTRY_BYTES :: 524288 NODE_APP_SHARED_LIMIT :: 64 NODE_APP_GENERIC_ICON :: "S1.6rr:M5 5H10V10H5ZM14 5H19V10H14ZM5 14H10V19H5ZM14 14H19V19H14Z" -NODE_APP_ICON_MAX :: 4096 -NODE_APP_ICON_VERSION_MAX :: 64 NodeAppOffer :: struct { name: [NODE_APP_NAME_MAX + 1]u8 @@ -156,11 +155,23 @@ node_shared_json: string; // to network installs only, as for a local --bundle. node_local_path: [4096]u8; node_local_name: [NODE_APP_NAME_MAX + 1]u8; -// Each installed app's outline icon and the package version it was read -// from, so Apps and the navigation show it before the app has run. -node_icons: [NodeAppSlots][NODE_APP_ICON_MAX]u8; -node_icon_sizes: [NodeAppSlots]s32; -node_icon_versions: [NodeAppSlots][NODE_APP_ICON_VERSION_MAX]u8; +NodeAppIconState :: struct { + name: [NODE_APP_NAME_MAX + 1]u8 + account: [65]u8 + version: [NODE_APP_ICON_VERSION_MAX]u8 + revision: s32 + generation: s32 + requested: bool + attempted: bool + temporary: bool + shape: [NODE_APP_ICON_MAX]u8 + size: s32 +} + +node_app_icons: [NodeAppSlots]NodeAppIconState; +// A canceled job still owns its inputs until it finishes. Keeping it here +// also bounds icon work to one worker, including work that became obsolete. +node_icon_work: *NodeIconWork; // Names and slots. @@ -229,6 +240,7 @@ NodeAppAssign :: (slot: s32, name: string) { unused AppCopyText(name, bytes[:]) unused SettingsStoreText(key, bytes[:]) PackageSetNodeApp(slot, name) + NodeAppForgetIcon(slot) // Another app in this slot has none of the previous one's leaves. node_installed_releases[slot][0] = 0 } @@ -290,10 +302,6 @@ NodeAppTitle :: (name: string) -> string { return name } -NodeAppIconValid :: (shape: string) -> bool { - return shape.count > 6 && shape.count < NODE_APP_ICON_MAX && shape[:1] == "S" -} - // Small catalog icons remain available before the app is downloaded. NodeAppCatalogIcon :: (name: string) -> string { if !NodeAppNameValid(name) { return NODE_APP_GENERIC_ICON } @@ -310,6 +318,9 @@ NodeAppCatalogIcon :: (name: string) -> string { // Prefer an installed app's own outline, then its catalog icon. NodeAppIconShape :: (slot: s32) -> string { + if slot < 0 || slot >= NodeAppSlots { + return NODE_APP_GENERIC_ICON + } if NodeAppRunning(slot) { path := NodeAppAssetPath(NodeAppName(slot), "sidebar.shape") defer { @@ -320,92 +331,113 @@ NodeAppIconShape :: (slot: s32) -> string { return asset.data } } - if slot < 0 || slot >= NodeAppSlots { - return NODE_APP_GENERIC_ICON - } fallback := NodeAppCatalogIcon(NodeAppName(slot)) if !NodeAppInstalled(slot) { return fallback } version := ifx NodeAppLocal(NodeAppName(slot)) then "local" else PackageVersion(NodeAppIndex(slot)) if version.count == 0 || version.count >= NODE_APP_ICON_VERSION_MAX { return fallback } - if TextUntilNul(node_icon_versions[slot][:]) != version { - NodeAppLoadIcon(slot, version) - } - if node_icon_sizes[slot] == 0 { + NodeAppRequestIcon(slot, version) + state := *node_app_icons[slot] + if state.size == 0 { return fallback } - return TextFromBytes(node_icons[slot][:node_icon_sizes[slot]]) + return TextFromBytes(state.shape[:state.size]) } -// Reads the installed package's icon once per version. The first read opens -// the verified package; the icon is then kept beside it, as -// "\n", so later launches read only that small file. A -// local package is read once per run. -NodeAppLoadIcon :: (slot: s32, version: string) { - unused AppCopyText(version, node_icon_versions[slot][:]) - node_icon_sizes[slot] = 0 - if NodeAppLocal(NodeAppName(slot)) { - local := PackageRead(TextUntilNul(node_local_path[:]), PackageMaximumBytes) - unused NodeAppReadIcon(slot, local) - PackageFree(local) +NodeAppForgetIcon :: (slot: s32) { + generation := node_app_icons[slot].generation + 1 + node_app_icons[slot] = NodeAppIconState.{.generation = generation} +} + +// Drawing only requests work and returns the icon already in memory. Slot, +// account and release changes invalidate both copied icons and pending jobs. +NodeAppRequestIcon :: (slot: s32, version: string) { + state := *node_app_icons[slot] + name := NodeAppName(slot) + account := PackageAccount() + revision := PackageRevisionFor(NodeAppIndex(slot)) + if state.requested && TextUntilNul(state.name[:]) == name && + TextUntilNul(state.account[:]) == account && TextUntilNul(state.version[:]) == version && + state.revision == revision && state.temporary == DataTemporary() { return } + NodeAppForgetIcon(slot) + unused AppCopyText(name, state.name[:]) + unused AppCopyText(account, state.account[:]) + unused AppCopyText(version, state.version[:]) + state.revision = revision + state.temporary = DataTemporary() + state.requested = true +} + +NodeAppIconCurrent :: (slot: s32) -> bool { + state := *node_app_icons[slot] + return state.requested && TextUntilNul(state.name[:]) == NodeAppName(slot) && + TextUntilNul(state.account[:]) == PackageAccount() && + TextUntilNul(state.version[:]) == + (ifx NodeAppLocal(NodeAppName(slot)) then "local" else PackageVersion(NodeAppIndex(slot))) && + state.revision == PackageRevisionFor(NodeAppIndex(slot)) && + state.temporary == DataTemporary() && NodeAppInstalled(slot) +} + +NodeAppsIconsPump :: () { + if node_icon_work != null { + if !NodeIconWorkReady(node_icon_work) { + return + } + state := *node_app_icons[node_icon_work.slot] + if state.generation == node_icon_work.generation && NodeAppIconCurrent(node_icon_work.slot) { + for at: cast(s32)0..node_icon_work.size - 1 { + state.shape[at] = node_icon_work.shape[at] + } + state.size = node_icon_work.size + } + NodeIconWorkFree(node_icon_work) + node_icon_work = null + } + for slot: cast(s32)0..NodeAppSlots - 1 { + state := *node_app_icons[slot] + if !state.requested || state.attempted || !NodeAppIconCurrent(slot) { + continue + } + state.attempted = true + NodeAppStartIcon(slot) + break + } +} + +NodeAppStartIcon :: (slot: s32) { index := NodeAppIndex(slot) - cache := PackagePath(index, ".icon") + local := NodeAppLocal(NodeAppName(slot)) + release: PackageRelease + if !local { + release = PackageInstalledRelease(index) + if !release.valid || TextUntilNul(release.version[:]) != TextUntilNul(node_app_icons[slot].version[:]) { + return + } + } + path: string + if local { + path = PackageText(TextUntilNul(node_local_path[:]), "") + } else { + path = PackagePayloadPath(index, TextUntilNul(release.hash[:])) + } + cache := ifx local then "" else PackagePath(index, ".icon") + resource := NodeAppAssetPath(NodeAppName(slot), "sidebar.shape") defer { + PackageFree(path) PackageFree(cache) + PackageFree(resource) } - if cache.count == 0 { + if path.count == 0 || (!local && cache.count == 0) { return } - saved := PackageRead(cache, NODE_APP_ICON_MAX + NODE_APP_ICON_VERSION_MAX) - defer { - PackageFree(saved) + node_icon_work = NodeIconWorkCreate(path, cache, resource, release, local) + if node_icon_work != null { + node_icon_work.slot = slot + node_icon_work.generation = node_app_icons[slot].generation } - if saved.count > version.count + 1 && saved[:version.count] == version && - saved[version.count] == cast(u8)10 && NodeAppIconValid(saved[version.count + 1:]) { - NodeAppKeepIcon(slot, saved[version.count + 1:]) - return - } - bytes := PackageInstalledBytes(index) - defer { - PackageFree(bytes) - } - if NodeAppReadIcon(slot, bytes) { - out: Vec(u8) - BuilderPrint(*out, "%\n%", version, TextFromBytes(node_icons[slot][:node_icon_sizes[slot]])) - value := BuilderFinish(out) - unused PackageWrite(cache, value) - PackageFree(value) - } -} - -// Keeps the icon a package carries; false when it has none. -NodeAppReadIcon :: (slot: s32, bytes: string) -> bool { - if bytes.count == 0 { - return false - } - opened: HostedApp - if !HostedAppOpen(*opened, bytes) { - return false - } - path := NodeAppAssetPath(NodeAppName(slot), "sidebar.shape") - asset := HostedAppAsset(*opened, path) - PackageFree(path) - found := asset.found && NodeAppIconValid(asset.data) - if found { - NodeAppKeepIcon(slot, asset.data) - } - HostedAppClose(*opened) - return found -} - -NodeAppKeepIcon :: (slot: s32, shape: string) { - for byte, at: shape { - node_icons[slot][at] = byte - } - node_icon_sizes[slot] = cast(s32)shape.count } // The apps the node offers that this build can run, as last read. @@ -1782,6 +1814,7 @@ NodeAppsCatalogPump :: (now: s32, wanted: bool) { NodeAppsPump :: (now: s32, catalog_wanted: bool, defer_open: bool = false) { NodeAppsInitialize() NodeAppsCatalogPump(now, catalog_wanted) + NodeAppsIconsPump() if PackageRevision() != node_package_revision { node_package_revision = PackageRevision() node_open_next = ifx node_first_pump_done then 0 else -1 diff --git a/src/cells/node_icon_work.zi b/src/cells/node_icon_work.zi new file mode 100644 index 000000000..fc354da3e --- /dev/null +++ b/src/cells/node_icon_work.zi @@ -0,0 +1,148 @@ +// An icon cache miss must never open a whole app while its navigation draws. +// One worker owns the file paths, signed descriptor, payload and copied shape. +#import "bundle_host" +#import "byte_text_linux" +#import "text" +#import "vec" +#import, file "package_files.zi"; +#import, file "package_release.zi"; +#import, file "catalog.zi"; + +NODE_APP_ICON_MAX :: 4096 +NODE_APP_ICON_VERSION_MAX :: 64 +NODE_ICON_THREADS :: !#defined(PLATFORM_WEB) && !#defined(_WIN32) +#if NODE_ICON_THREADS { + #import "std/thread_linux" +} + +NodeIconWork :: struct { + path: string + cache: string + resource: string + release: PackageRelease + local: bool + shape: [NODE_APP_ICON_MAX]u8 + size: s32 + ready: bool + slot: s32 + generation: s32 + #if NODE_ICON_THREADS { + thread: Thread + } +} + +node_icon_c :: #system_library "c"; +NodeIconAllocate :: (size: usize) -> *void #foreign node_icon_c "malloc"; +NodeIconRelease :: (memory: *void) #foreign node_icon_c "free"; + +NodeAppIconValid :: (shape: string) -> bool { + return shape.count > 6 && shape.count < NODE_APP_ICON_MAX && shape[:1] == "S" +} + +NodeIconWorkKeep :: (work: *NodeIconWork, shape: string) -> bool { + if !NodeAppIconValid(shape) { + return false + } + for byte, at: shape { + work.shape[at] = byte + } + work.size = cast(s32)shape.count + return true +} + +NodeIconWorkRun :: (argument: *void) { + work := cast(*NodeIconWork)argument + if !work.local && !work.release.valid { + return + } + key := TextFromBytes(work.release.hash[:64]) + if !work.local && work.cache.count > 0 { + saved := PackageRead(work.cache, NODE_APP_ICON_MAX + 65) + defer { + PackageFree(saved) + } + if saved.count > 65 && saved[:64] == key && saved[64] == cast(u8)10 && + NodeIconWorkKeep(work, saved[65:]) { + return + } + } + bytes := PackageRead(work.path, PackageMaximumBytes) + defer { + PackageFree(bytes) + } + if bytes.count == 0 || (!work.local && !PackageVerifyBytes(bytes, work.release)) { + return + } + descriptor := cast(*TextDescriptor)(*bytes) + bundle := OpenBundleBytes(descriptor.data, cast(u64)bytes.count) + if bundle == null { + return + } + defer { + CloseBundle(bundle) + } + // Use the raw bundle API: HostedAppAsset's shared index belongs to the + // frame thread. No instance, host callback or shared codec runs here. + asset: u64 = 0 + while asset < BundleAssets(bundle) { + if TextFromCString(BundleAssetPath(bundle, asset)) != work.resource { + asset += 1 + continue + } + size := BundleAssetLength(bundle, asset) + if size >= cast(u64)NODE_APP_ICON_MAX { + return + } + shape := TextFromBytes(BytesFromPointer(BundleAssetBytes(bundle, asset), size)) + if !NodeIconWorkKeep(work, shape) || work.local || work.cache.count == 0 { + return + } + out: Vec(u8) + BuilderPrint(*out, "%\n%", key, shape) + saved := BuilderFinish(out) + unused PackageWrite(work.cache, saved) + PackageFree(saved) + return + } +} + +NodeIconWorkReady :: (work: *NodeIconWork) -> bool { + #if NODE_ICON_THREADS { + if !work.ready { + work.ready = !ThreadRunning(*work.thread) || ThreadFinished(*work.thread) + } + } + return work.ready +} + +NodeIconWorkFree :: (work: *NodeIconWork) { + PackageFree(work.path) + PackageFree(work.cache) + PackageFree(work.resource) + NodeIconRelease(cast(*void)work) +} + +NodeIconWorkCreate :: (path: string, cache: string, resource: string, + release: PackageRelease, local: bool) -> *NodeIconWork { + work := cast(*NodeIconWork)NodeIconAllocate(size_of(NodeIconWork)) + if work == null { + return null + } + work.* = NodeIconWork.{} + work.path = PackageText(path, "") + work.cache = PackageText(cache, "") + work.resource = PackageText(resource, "") + work.release = release + work.local = local + #if NODE_ICON_THREADS { + procedure: ThreadProcedure = NodeIconWorkRun + if !ThreadStart(*work.thread, procedure, cast(*void)work) { + NodeIconWorkFree(work) + return null + } + } else { + NodeIconWorkRun(cast(*void)work) + work.ready = true + } + return work +} diff --git a/src/cells/package_manager.zi b/src/cells/package_manager.zi index f015b4950..b391abc54 100644 --- a/src/cells/package_manager.zi +++ b/src/cells/package_manager.zi @@ -256,13 +256,11 @@ PackagePayloadPath :: (index: s32, hash: string) -> string { return PackagePath(index, full_suffix) } -PackageInstalledBytes :: (index: s32) -> string { - if index < 0 || index >= PackageSlots { - return "" - } - package_versions[index][0] = cast(u8)0 - if DataTemporary() { - return "" +// A small signed descriptor can be captured on the frame thread before a +// worker reads its immutable payload. This never marks unchecked bytes usable. +PackageInstalledRelease :: (index: s32) -> PackageRelease { + if index < 0 || index >= PackageSlots || DataTemporary() { + return PackageRelease.{} } pointer := PackagePath(index, ".current.json") defer { @@ -274,15 +272,27 @@ PackageInstalledBytes :: (index: s32) -> string { } release := PackageTrustedRelease(metadata, index) if !release.valid { - return "" + return PackageRelease.{} } high_water := PackageSequence(index) approved := PackageRollbackAllows(index, release) if release.sequence < high_water && !approved { - return "" + return PackageRelease.{} } if PackageBundledSequence(index) > 0 && PackageVersionCompare(TextFromCString(*release.version[0]), PackageFallbackVersion(index)) < 0 && !approved { + return PackageRelease.{} + } + return release +} + +PackageInstalledBytes :: (index: s32) -> string { + if index < 0 || index >= PackageSlots { + return "" + } + package_versions[index][0] = cast(u8)0 + release := PackageInstalledRelease(index) + if !release.valid { return "" } path := PackagePayloadPath(index, TextFromCString(*release.hash[0])) diff --git a/tests/node_app_icons_behavior.zi b/tests/node_app_icons_behavior.zi new file mode 100644 index 000000000..4c68b62fc --- /dev/null +++ b/tests/node_app_icons_behavior.zi @@ -0,0 +1,207 @@ +// A parser blocked on another thread cannot block drawing or publish into +// a different account, slot, release or temporary session. +#import "crypto" +#import "std/byte_text_linux" +#import "std/c_string" +#import "std/file_linux" +#import, file "../src/cells/node_apps.zi"; +#import, file "../src/cells/node_icon_work.zi"; +#import, file "../src/cells/package_manager.zi"; +#import, file "../src/cells/package_files.zi"; +#import, file "../src/cells/package_release.zi"; +#import, file "../src/cells/catalog.zi"; +#import, file "../src/storage/temporary_data.zi"; + +icons_c :: #system_library "c"; +IconsBlockParser :: (blocked: bool) #foreign icons_c; +IconsParserStarted :: () -> bool #foreign icons_c; +IconsBundleOpens :: () -> s32 #foreign icons_c; +IconsYield :: () #foreign icons_c; +IconsNow :: () -> float64 #foreign icons_c; +IconsOtherAccount :: (enabled: bool) #foreign icons_c; +IconsEnvironment :: (name: *u8) -> *u8 #foreign icons_c "getenv"; + +ICONS_SHAPE :: "S1.6rr:M5 5H10V10H5Z" + +IconsEnvironmentPath :: (key: string) -> string { + name: [64]u8 + unused CopyCString(key, name[:]) + return TextFromCString(IconsEnvironment(*name[0])) +} + +IconsRelease :: (path: string) -> PackageRelease { + bytes := PackageRead(path, PackageMaximumBytes) + defer { + PackageFree(bytes) + } + release: PackageRelease + release.valid = true + release.size = bytes.count + unused CopyCString("1.0.0", release.version[:]) + descriptor := cast(*TextDescriptor)(*bytes) + Sha256Hex(descriptor.data, bytes.count, *release.hash[0]) + return release +} + +IconsRequest :: (slot: s32) { + NodeAppForgetIcon(slot) + PackageSetNodeApp(slot, "fixture") + unused CopyCString("1.0.0", package_versions[NodeAppIndex(slot)][:]) + unused NodeAppIconShape(slot) + // Tests supply a trusted release directly, keeping signing tests in the + // package lifecycle fixture and exercising the real worker and publisher. + node_app_icons[slot].attempted = true +} + +IconsStart :: (slot: s32, path: string, cache: string, release: PackageRelease, + local: bool = false) -> bool { + node_icon_work = NodeIconWorkCreate(path, cache, "assets/fixture/sidebar.shape", release, local) + if node_icon_work == null { + return false + } + node_icon_work.slot = slot + node_icon_work.generation = node_app_icons[slot].generation + return true +} + +IconsWait :: () -> bool { + end := IconsNow() + 10.0 + while node_icon_work != null && IconsNow() < end { + NodeAppsIconsPump() + IconsYield() + } + return node_icon_work == null +} + +IconsWaitParser :: () -> bool { + end := IconsNow() + 10.0 + while !IconsParserStarted() && IconsNow() < end { + IconsYield() + } + return IconsParserStarted() +} + +IconsStaleCheck :: (slot: s32, path: string, release: PackageRelease) -> s32 { + for change: cast(s32)0..4 { + IconsRequest(slot) + IconsBlockParser(true) + if !IconsStart(slot, path, "", release, true) || !IconsWaitParser() { + IconsBlockParser(false) + return 40 + } + if change == 0 { + PackageSetNodeApp(slot, "replacement") + } else if change == 1 { + IconsOtherAccount(true) + } else if change == 2 { + package_slot_revisions[NodeAppIndex(slot)] += 1 + } else if change == 3 { + DataSetTemporary(true) + } else { + NodeAppForgetIcon(slot) + } + start := IconsNow() + for frame: cast(s32)0..99 { + NodeAppsIconsPump() + } + if IconsNow() - start > 0.05 || node_icon_work == null { + IconsBlockParser(false) + return 41 + } + IconsBlockParser(false) + if !IconsWait() || node_app_icons[slot].size != 0 { + return 42 + change + } + IconsOtherAccount(false) + DataSetTemporary(false) + } + return 0 +} + +NodeAppIconsCheck :: () -> s32 { + slot := cast(s32)(NodeAppSlots - 1) + path := IconsEnvironmentPath("ICON_VALID_BUNDLE") + release := IconsRelease(path) + cache := IconsEnvironmentPath("ICON_CACHE_PATH") + unused RemoveFile(cache) + before := IconsBundleOpens() + IconsRequest(slot) + if NodeAppIconShape(slot) != NODE_APP_GENERIC_ICON || IconsBundleOpens() != before || + NodeAppIconShape(-1) != NODE_APP_GENERIC_ICON || NodeAppIconShape(NodeAppSlots) != NODE_APP_GENERIC_ICON { + return 30 + } + // The job copies its input paths before starting. The caller can free + // its path immediately, even while the parser is deliberately blocked. + owned := PackageText(path, "") + IconsBlockParser(true) + started := IconsStart(slot, owned, cache, release) + PackageFree(owned) + if !started || !IconsWaitParser() { + IconsBlockParser(false) + return 31 + } + start := IconsNow() + for frame: cast(s32)0..99 { + if NodeAppIconShape(slot) != NODE_APP_GENERIC_ICON { + IconsBlockParser(false) + return 32 + } + NodeAppsIconsPump() + } + if IconsNow() - start > 0.05 || IconsBundleOpens() != before + 1 { + IconsBlockParser(false) + return 33 + } + IconsBlockParser(false) + if !IconsWait() || NodeAppIconShape(slot) != ICONS_SHAPE { + return 34 + } + // A warm cache is keyed by the signed digest and does not reopen code. + IconsRequest(slot) + before = IconsBundleOpens() + if !IconsStart(slot, "missing-payload", cache, release) || !IconsWait() || + NodeAppIconShape(slot) != ICONS_SHAPE || IconsBundleOpens() != before { + return 35 + } + // Exercise the actual draw -> pump -> start -> publish path as well as + // the controlled worker fixtures, using the supported local app mode. + unused CopyCString("fixture", node_local_name[:]) + unused CopyCString(path, node_local_path[:]) + NodeAppForgetIcon(slot) + if NodeAppIconShape(slot) != NODE_APP_GENERIC_ICON || node_icon_work != null { + return 38 + } + NodeAppsIconsPump() + if node_icon_work == null || !IconsWait() || NodeAppIconShape(slot) != ICONS_SHAPE { + return 39 + } + node_local_name[0] = cast(u8)0 + node_local_path[0] = cast(u8)0 + before = IconsBundleOpens() + // A different digest cannot reuse the previous icon, even at the same + // version. A corrupt payload never reaches the bundle parser. + IconsRequest(slot) + wrong := release + wrong.hash[0] = ifx wrong.hash[0] == #char "0" then #char "1" else #char "0" + if !IconsStart(slot, path, cache, wrong) || !IconsWait() || + node_app_icons[slot].size != 0 || IconsBundleOpens() != before { + return 36 + } + invalid: [3]string = .["ICON_INVALID_BUNDLE", "ICON_EMPTY_BUNDLE", "ICON_CORRUPT_BUNDLE"] + for key: invalid { + IconsRequest(slot) + fixture := IconsEnvironmentPath(key) + if !IconsStart(slot, fixture, "", IconsRelease(fixture)) || !IconsWait() || + node_app_icons[slot].size != 0 { + return 37 + } + } + stale := IconsStaleCheck(slot, path, release) + if stale != 0 { + return stale + } + NodeAppForgetIcon(slot) + PackageSetNodeApp(slot, "") + package_versions[NodeAppIndex(slot)][0] = cast(u8)0 + return 0 +} diff --git a/tests/node_app_icons_host.c b/tests/node_app_icons_host.c new file mode 100644 index 000000000..05309fe48 --- /dev/null +++ b/tests/node_app_icons_host.c @@ -0,0 +1,62 @@ +#define _DEFAULT_SOURCE +#include "ziran_host.h" +#include +#include +#include +#include +#include + +static atomic_bool parser_blocked; +static atomic_bool parser_started; +static atomic_int bundle_opens; +static bool other_account; + +void IconsBlockParser(bool blocked) +{ + if (blocked) atomic_store(&parser_started, false); + atomic_store(&parser_blocked, blocked); +} + +bool IconsParserStarted(void) +{ + return atomic_load(&parser_started); +} + +int32_t IconsBundleOpens(void) +{ + return atomic_load(&bundle_opens); +} + +void IconsYield(void) +{ + usleep(1000); +} + +double IconsNow(void) +{ + struct timespec now; + assert(clock_gettime(CLOCK_MONOTONIC, &now) == 0); + return (double)now.tv_sec + (double)now.tv_nsec / 1e9; +} + +void IconsOtherAccount(bool enabled) +{ + other_account = enabled; +} + +unsigned char *__real_storage_user_id_buffer(void); +unsigned char *__wrap_storage_user_id_buffer(void) +{ + return other_account ? (unsigned char *)"another-account" : __real_storage_user_id_buffer(); +} + +Bundle *__real_BundleOpenBytes(const unsigned char *bytes, size_t size); +Bundle *__wrap_BundleOpenBytes(const unsigned char *bytes, size_t size) +{ + atomic_fetch_add(&bundle_opens, 1); + if (atomic_load(&parser_blocked)) { + atomic_store(&parser_started, true); + while (atomic_load(&parser_blocked)) usleep(1000); + } + return __real_BundleOpenBytes(bytes, size); +} diff --git a/tests/node_app_snapshot_behavior.zi b/tests/node_app_snapshot_behavior.zi index 630d7e05d..c209e5305 100644 --- a/tests/node_app_snapshot_behavior.zi +++ b/tests/node_app_snapshot_behavior.zi @@ -9,6 +9,7 @@ #import "apps/catalog" #import "apps/protocol" #import, file "delegate_account_host.zi"; +#import, file "node_app_icons_behavior.zi"; #import, file "../src/cells/node_app_snapshot.zi"; #import, file "../src/cells/node_app_tree.zi"; #import, file "../src/cells/node_apps.zi"; @@ -61,8 +62,8 @@ SnapshotDiscoveryCheck :: () -> s32 { if !AppCatalogAppend(*root.catalog, entry) { return 11 } } if !AppTreeStart(*host.tree, root, NodeTreeAccount(), AppProvider.{ - .open = SnapshotOpen, .save = SnapshotSave, .close = SnapshotClose, - .effect = SnapshotEffect}) { return 12 } + .open = SnapshotOpen, .save = SnapshotSave, .close = SnapshotClose, + .effect = SnapshotEffect}) { return 12 } slot := cast(s32)(NodeAppSlots - 1) node_runners[slot].nested = *host if !NodeInstalledScanStart(slot) || snapshot_opened != 0 { return 13 } @@ -130,6 +131,8 @@ Check :: () -> s32 { if NodeAppInstalledLeafRevision() == before { return 9 } discovery := SnapshotDiscoveryCheck() if discovery != 0 { return discovery } + icons := NodeAppIconsCheck() + if icons != 0 { return icons } storage_close() return 0 } diff --git a/tests/node_app_snapshot_test.py b/tests/node_app_snapshot_test.py index 21c3e937c..bed81d480 100644 --- a/tests/node_app_snapshot_test.py +++ b/tests/node_app_snapshot_test.py @@ -11,17 +11,32 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--ziran', type=Path, required=True) parser.add_argument('--runtime', type=Path, required=True) + parser.add_argument('--output', type=Path, help='Separate output for a concurrent diagnostic run') args = parser.parse_args() root = Path(__file__).resolve().parents[1] - work = root / 'build/node-app-snapshot-test' + work = args.output.resolve() if args.output else root / 'build/node-app-snapshot-test' generated = work / 'c' if generated.exists(): shutil.rmtree(generated) generated.mkdir(parents=True) environment = {key: value for key, value in os.environ.items() if key not in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS', - 'ZIRAN_PACKAGE_MAP')} + 'SESSION_MANAGER', 'ZIRAN_PACKAGE_MAP')} environment.update(YUE_DESKTOP_RECOVERY='0') + fixture = work / 'fixtures' + fixture.mkdir(exist_ok=True) + source = fixture / 'fixture.zi' + source.write_text('#program_export\nMain :: () -> s32 { return 1 }\n') + for name, shape in [('valid', 'S1.6rr:M5 5H10V10H5Z'), ('invalid', 'invalid'), ('empty', None)]: + assets = fixture / name + assets.mkdir(exist_ok=True) + if shape is not None: + (assets / 'sidebar.shape').write_text(shape) + subprocess.run([str(args.ziran.resolve()), 'bundle', '--root', str(fixture), + '--entry', 'fixture:Main', '--asset-dir', f'assets/fixture={assets}', + '-o', str(fixture / f'{name}.zib'), str(source)], + cwd=root, env=environment, check=True) + (fixture / 'corrupt.zib').write_bytes(b'ZIB\0invalid envelope') package_paths = subprocess.check_output(['sh', str(root / 'scripts/package-paths.sh'), str(root / 'build/packages')], text=True).splitlines() module_paths = [item for path in ('src', 'build/packages/kryon/src/ui', 'build/packages/kryon/src/backend', @@ -41,15 +56,26 @@ def main(): for item in ('-iquote', str(directory))] result = subprocess.run([os.environ.get('CC', 'cc'), '-std=c11', '-O0', '-ffunction-sections', '-fdata-sections', '-I' + str(root / 'build/packages/ziran/include'), *includes, + '-I' + str(root / 'build/packages/monocypher/src'), *map(str, sorted(generated.rglob('*.c'))), + str(root / 'tests/node_app_icons_host.c'), + str(root / 'build/packages/monocypher/src/monocypher.c'), + str(root / 'build/packages/monocypher/src/optional/monocypher-ed25519.c'), str(root / 'vendor-builds/sqlite/sqlite3.c'), str(args.runtime.resolve()), str(root / 'vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a'), - '-Wl,--gc-sections', '-lm', '-ldl', '-lpthread', '-o', str(work / 'test')]) + '-Wl,--gc-sections', '-Wl,--wrap=BundleOpenBytes', + '-Wl,--wrap=storage_user_id_buffer', + '-lm', '-ldl', '-lpthread', '-o', str(work / 'test')]) if result.returncode: raise SystemExit('Snapshot native link failed; see compiler diagnostics above') with tempfile.TemporaryDirectory(prefix='profile-', dir=work) as profile: - subprocess.run([str(work / 'test')], env=environment | {'APP_DATA_ROOT': profile}, check=True) - print('Installed-leaf SQLite snapshot: duplicate roots, visibility, owned assets, incremental discovery and safe cancellation passed') + subprocess.run([str(work / 'test')], env=environment | { + 'APP_DATA_ROOT': profile, + 'ICON_CACHE_PATH': str(Path(profile) / 'fixture.icon'), + **{f'ICON_{name.upper()}_BUNDLE': str(fixture / f'{name}.zib') + for name in ('valid', 'invalid', 'empty', 'corrupt')}, + }, check=True) + print('Installed-leaf SQLite snapshot and icons: discovery, nonblocking loading, digest caches and stale-job isolation passed') if __name__ == '__main__':