Persist hosted Choano progress through app records

This commit is contained in:
waozi committed 2026-11-20 00:46:02 -03:00
1 parent e767df39ca
commit 106be8ab7e
10 files changed
+181 -53

No files matched your search

+1
View File
@@ -2,6 +2,7 @@
## [Unreleased]
- Keep portable Choano progress in the host’s app record store.
- Run desktop and Android on Kryon 0.6.0 with Ziran 0.7.0.
- Run in the current Arcade and Inner Breeze package format.
+7
View File
@@ -1,10 +1,17 @@
host_api :: #system_library "host_api";
AppServiceHost :: (name: string, request: string) -> string #foreign host_api;
AppSupportsHost :: (name: string) -> bool #foreign host_api;
AppKeyHost :: () -> s32 #foreign host_api;
AppRecordHost :: (name: string) -> string #foreign host_api;
SaveAppRecordHost :: (name: string, text: string) -> bool #foreign host_api;
frame_now: float64;
frame_key: s32;
Milliseconds :: () -> s64 { return cast(s64)(frame_now * 1000.0) }
Supports :: (name: string) -> bool { return AppSupportsHost(name) }
Service :: (name: string, request: string) -> string { return AppServiceHost(name, request) }
ReadRecord :: (name: string) -> string { return AppRecordHost(name) }
SaveRecord :: (name: string, text: string) -> bool { return SaveAppRecordHost(name, text) }
CaptureKey :: () { frame_key = AppKeyHost() }
PressedKey :: () -> s32 { return frame_key }
+3 -5
View File
@@ -1,11 +1,9 @@
#import "std/text_buffer"
Accessories :: #import "accessories";
#if #defined(CHOANO_PORTABLE) {
host_api :: #system_library "host_api";
AppRecordHost :: (name: string) -> string #foreign host_api;
SaveAppRecordHost :: (name: string, text: string) -> bool #foreign host_api;
Read :: () -> string { return AppRecordHost("choano.preferences") }
Write :: (value: string) -> bool { return SaveAppRecordHost("choano.preferences", value) }
Runtime :: #import "portable_runtime";
Read :: () -> string { return Runtime.ReadRecord("choano.preferences") }
Write :: (value: string) -> bool { return Runtime.SaveRecord("choano.preferences", value) }
} else #if #defined(ANDROID_BUILD) {
// The APK's assets are read-only; settings live in the app's private
// files folder, which Android creates.
+76 -22
View File
@@ -9,15 +9,41 @@
Prefs :: #import "preferences";
Game :: #import "game";
#if #defined(CHOANO_PORTABLE) {
Context :: #import "kryon/app_context";
#import "crypto/sha256"
Runtime :: #import "portable_runtime";
Close :: () {}
Ready :: () -> bool { return Context.DocumentStorageReady() }
Confirm :: () -> bool { return Context.DocumentFlush() }
Read :: (name: string) -> string { return Context.DocumentRead(name) }
ReleaseRead :: (text: string) { unused text }
Missing :: () -> bool { return Context.DocumentStatus() == 0 }
Write :: (name: string, value: string) -> bool {
return Context.DocumentWrite(name, value) && Context.DocumentFlush()
PortableName :: (owner: string, output: []u8) -> string {
if owner == "" { return "local.choano.earned.v1.guest" }
// App record names are limited to 63 characters across the two hosts.
// Use a bounded digest for 64-character account IDs and any legacy IDs.
hash := Sha256Of(owner)
digest: [40]u8
for index: 0..19 {
digest[index * 2] = HexCharacter(hash[index] >> cast(u8)4)
digest[index * 2 + 1] = HexCharacter(hash[index] & cast(u8)15)
}
out: Vec(u8)
BuilderPrint(*out, "local.choano.earned.v1.%", TextView(digest[:]))
copied := CopyCString(TextView(VecSlice(out, 0, out.count)), output)
VecFree(out)
return ifx copied then TextUntilNul(output) else ""
}
PortableLegacyName :: (owner: string, name: string) -> bool {
if name.count >= 64 {
if owner.count != 64 || !Runtime.Supports("DocumentReadHost") { return false }
for byte: owner {
if !((byte >= #char "a" && byte <= #char "f") ||
(byte >= #char "0" && byte <= #char "9")) { return false }
}
return true
}
for byte: name {
if !((byte >= #char "a" && byte <= #char "z") ||
(byte >= #char "0" && byte <= #char "9") || byte == #char "." || byte == #char "-") { return false }
}
return true
}
} else {
#import "kryon/app_files"
@@ -57,23 +83,42 @@ Name :: (owner: string, output: []u8) -> string {
return ifx copied then TextUntilNul(output) else ""
}
Load :: (owner: string, record: *GameProgressRecord, pending: *bool) -> bool {
if !Ready() || !Confirm() { return false }
name_bytes: [256]u8
name := Name(owner, name_bytes[:])
if name == "" { return false }
text := Read(name)
defer { ReleaseRead(text) }
if text == "" && Missing() {
record.* = .{}; unused CopyCString("choano", record.game[:]); record.unlocked = 1
pending.* = false
// Existing device earnings belong to the guest only.
if owner == "" {
legacy := Prefs.Load()
if legacy.accessories_stage > record.unlocked { record.unlocked = legacy.accessories_stage }
if legacy.fish_unlocked { record.unlocked = Game.PLAYER_STAGE_LAST }
#if #defined(CHOANO_PORTABLE) {
key_bytes: [64]u8
key := PortableName(owner, key_bytes[:])
if key == "" { return false }
text := Runtime.ReadRecord(key)
if text != "" { return Decode(text, record, pending) }
// Standalone Arcade keeps app records beside the older documents.
// Migrate only valid old saves, and bind only after the host commits.
if PortableLegacyName(owner, name) {
legacy := Runtime.ReadRecord(name)
if legacy != "" {
return Decode(legacy, record, pending) && Runtime.SaveRecord(key, legacy)
}
}
return Persist(owner, record, false)
} else {
if !Ready() || !Confirm() { return false }
text := Read(name)
defer { ReleaseRead(text) }
if text != "" { return Decode(text, record, pending) }
if !Missing() { return false }
}
record.* = .{}; unused CopyCString("choano", record.game[:]); record.unlocked = 1
pending.* = false
// Existing device earnings belong to the guest only.
if owner == "" {
legacy := Prefs.Load()
if legacy.accessories_stage > record.unlocked { record.unlocked = legacy.accessories_stage }
if legacy.fish_unlocked { record.unlocked = Game.PLAYER_STAGE_LAST }
}
return Persist(owner, record, false)
}
Decode :: (text: string, record: *GameProgressRecord, pending: *bool) -> bool {
at := FieldAt(text, 0, "earned")
if at < 0 { return false }
end := ValueEnd(text, at, 0)
@@ -88,7 +133,9 @@ Load :: (owner: string, record: *GameProgressRecord, pending: *bool) -> bool {
return true
}
Persist :: (owner: string, record: *GameProgressRecord, pending: bool) -> bool {
if !Ready() { return false }
#if !#defined(CHOANO_PORTABLE) {
if !Ready() { return false }
}
name_bytes: [256]u8
name := Name(owner, name_bytes[:])
if name == "" { return false }
@@ -97,5 +144,12 @@ Persist :: (owner: string, record: *GameProgressRecord, pending: bool) -> bool {
GameProgressWrite(record, *out)
BuilderPrint(*out, "}")
defer { VecFree(out) }
return Write(name, TextView(VecSlice(out, 0, out.count)))
text := TextView(VecSlice(out, 0, out.count))
#if #defined(CHOANO_PORTABLE) {
key_bytes: [64]u8
key := PortableName(owner, key_bytes[:])
return key != "" && Runtime.SaveRecord(key, text)
} else {
return Write(name, text)
}
}
+31 -1
View File
@@ -6,6 +6,7 @@ import os
from pathlib import Path
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
os.chdir(ROOT)
@@ -61,6 +62,35 @@ def main():
run(ZIRAN, 'build', '--project', *LOCKED, '--target=c', '--exe',
'--entry', 'portable_input_test:main', '-o', 'build/portable-input-test',
'tests/portable_input_test.zi', env=portable_env)
run('xvfb-run', '-a', './build/portable-input-test/portable_input_test')
check_portable_progress()
def check_portable_progress():
for phase, owner in (('guest', ''), ('linked', '0123456789abcdef' * 4),
('new-account', 'fedcba9876543210' * 4)):
with tempfile.TemporaryDirectory(prefix='portable-progress-', dir=WORK) as directory:
name = owner or 'guest'
suffix = hashlib.sha256(owner.encode()).hexdigest()[:40] if owner else 'guest'
key = f'local.choano.earned.v1.{suffix}'
legacy = f'choano.earned.{name}.v1' if phase != 'new-account' else ''
env = dict(ENV, CHOANO_DATA=directory, CHOANO_TEST_PROGRESS_KEY=key,
CHOANO_TEST_LEGACY_KEY=legacy, CHOANO_TEST_PROGRESS_PHASE=phase,
CHOANO_TEST_RECORD_STATUS=json.dumps({'account': owner}))
old = {'earned': {'game': 'choano', 'unlocked': 1 if not owner else 5,
'completed': '', 'updated_at': 37}, 'pending': False}
target = Path(directory, key)
if legacy:
original = Path(directory, legacy)
original.write_text(json.dumps(old))
run('xvfb-run', '-a', './build/portable-input-test/portable_input_test', env=env)
saved = json.loads(target.read_text())
if legacy:
assert json.loads(original.read_text()) == old
assert saved == old
else:
assert saved['earned']['unlocked'] == 1 and not saved['pending']
run('xvfb-run', '-a', './build/portable-input-test/portable_input_test',
env=dict(env, CHOANO_TEST_PROGRESS_PHASE='restart'))
assert json.loads(target.read_text()) == saved
if __name__ == '__main__': main()
+50 -21
View File
@@ -2,10 +2,14 @@ AudioFixture :: #import "audio_test";
#import "kryon/media_audio_host"
sound_allowed: bool;
progress_files: AppFiles;
Documents :: (context: *void, node: *AppNode) -> *AppFiles {
if TextUntilNul(node.identity.id[:]) != "xyz.waozi.choano" { return null }
return *progress_files
}
record_text: string;
progress_owner: string;
progress_key: string;
legacy_key: string;
can_write_progress: bool;
progress_writes: s32;
progress_reads: s32;
legacy_reads: s32;
// Actual Choano node/2 bundle through the published Apps and widget boundary.
#import "apps/host"
@@ -34,26 +38,32 @@ Documents :: (context: *void, node: *AppNode) -> *AppFiles {
Allow :: (context: *void, node: *AppNode, name: string) -> bool {
unused context; unused node
return AppHostDocumentFunction(name) || name == "DocumentReadHost" || name == "DocumentWriteHost" || name == "DocumentStatusHost" || name == "AppRecordHost" || name == "SaveAppRecordHost" || (name == "AppSoundHost" && sound_allowed)
return (name == "DocumentReadHost" && legacy_key != "") || name == "AppRecordHost" ||
name == "SaveAppRecordHost" || name == "entity.records" || (name == "AppSoundHost" && sound_allowed)
}
Service :: (context: *void, node: *AppNode, module: *u8, function: *u8, arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
unused context; unused node; unused module; unused arguments; unused count
unused context; unused module
if TextUntilNul(node.identity.id[:]) != "xyz.waozi.choano" { return 0 }
name := TextFromCString(function)
if name == "DocumentReadHost" {
result.* = AppHostText(AppFileRead(*progress_files, AppArgumentText(arguments[0])))
} else if name == "DocumentWriteHost" {
result.* = HostScalar("bool", ifx AppFileWrite(*progress_files, AppArgumentText(arguments[0]), AppArgumentText(arguments[1])) then 1 else 0)
} else if name == "DocumentStatusHost" {
result.* = HostScalar("s32", cast(s64)progress_files.status)
} else if name == "AppServiceHost" {
result.* = AppHostText("{\"account\":\"local\"}")
} else if name == "AppRecordHost" {
value := "1s000"
result.* = HostValue.{.kind = cast(s32)HostString, .type_name = HostTextData("string"),
.data = HostTextData(value), .length = cast(usize)value.count}
} else { result.* = HostScalar("bool", 1) }
if name == "AppServiceHost" && count == 2 && AppArgumentText(arguments[0]) == "entity.records" {
request := AppArgumentText(arguments[1])
result.* = AppHostText(ifx request == "{\"operation\":\"status\"}" then progress_owner else "{\"status\":\"unavailable\"}")
} else if name == "AppRecordHost" && count == 1 {
key := AppArgumentText(arguments[0])
if key == progress_key { progress_reads += 1 }
if key == legacy_key { legacy_reads += 1 }
AppFileFree(record_text)
record_text = AppFileRead(*progress_files, key)
result.* = AppHostText(record_text)
} else if name == "SaveAppRecordHost" && count == 2 {
key := AppArgumentText(arguments[0])
if key == progress_key { progress_writes += 1 }
saved := can_write_progress && AppFileWrite(*progress_files, key, AppArgumentText(arguments[1]))
result.* = HostScalar("bool", ifx saved then 1 else 0)
} else { return 0 }
return 1
}
using HostValueKind;
Widgets :: (context: *void, node: *AppNode, module: *u8, function: *u8, arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
@@ -93,8 +103,11 @@ main :: () -> s32 {
bytes, found := ReadEntireFile("work/frame-input-adoption/guest.zx")
host: AppHost
if !AppFilesOpen(*progress_files, EnvironmentText("CHOANO_DATA")) { return 27 }
defer { AppFilesClose(*progress_files) }
platform := AppPlatform.{.documents = Documents, .host_api = 43, .allows = Allow, .call = Service, .widgets = Widgets, .save = Save}
defer { AppFilesClose(*progress_files); AppFileFree(record_text) }
progress_owner = EnvironmentText("CHOANO_TEST_RECORD_STATUS")
progress_key = EnvironmentText("CHOANO_TEST_PROGRESS_KEY")
legacy_key = EnvironmentText("CHOANO_TEST_LEGACY_KEY")
platform := AppPlatform.{.host_api = 43, .allows = Allow, .call = Service, .widgets = Widgets, .save = Save}
digest, digest_found := ReadEntireFile("work/frame-input-adoption/portable.sha256")
if !found || !digest_found || !AppHostStart(*host, bytes, "local.test", "xyz.waozi.choano", "choano",
digest, "input-test", platform, "", "en", APPS_NODE_PROTOCOL) { return 2 }
@@ -104,6 +117,22 @@ main :: () -> s32 {
runtime.app.bounds = .{0.0, 0.0, 900.0, 680.0}
runtime.legacy.frame = .{.session = session, .width = 900, .height = 680, .now = 1.0}
sample := FrameInputSnapshot.{.available = true, .focused = true}
phase := EnvironmentText("CHOANO_TEST_PROGRESS_PHASE")
if phase == "restart" {
if !Draw(*host, sample) || progress_reads != 1 || legacy_reads != 0 || progress_writes != 0 { return 28 }
print("Choano reopened its committed progress in a fresh host process.\n")
return 0
}
// A failed commit must leave the old file in place and let Load retry.
if !Draw(*host, sample) || progress_writes != 1 { return 29 }
missing := AppFileRead(*progress_files, progress_key)
not_created := missing == "" && progress_files.status == 0
AppFileFree(missing)
if !not_created { return 30 }
can_write_progress = true
if !Draw(*host, sample) || progress_writes < 2 { return 31 }
if phase == "linked" && legacy_reads < 2 { return 32 }
if phase != "guest" { return 0 }
if !Draw(*host, sample, KeyEnter) || !Draw(*host, sample) { return 3 }
if AudioFixture.plays != 0 { return 23 }
sound_allowed = true
+6 -1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Production Choano earned saves in an isolated native namespace."""
import json
import os
from pathlib import Path
import subprocess
@@ -15,10 +16,14 @@ subprocess.run(['ziran', 'build', '--project', *([] if (ROOT / 'ziran.local.toml
'tests/progress_storage_test.zi'], check=True, env=env)
with tempfile.TemporaryDirectory(prefix='progress-storage-', dir=ROOT / 'work') as data:
env['CHOANO_DATA'] = data
legacy = Path(data, 'choano.earned.account-b.v1')
legacy_data = {'pending': False, 'earned': {'game': 'choano', 'unlocked': 4,
'completed': '', 'updated_at': 23}}
legacy.write_text(json.dumps(legacy_data))
subprocess.run(['./build/progress-storage-test/progress_storage_test'], check=True, env=env)
documents = list(Path(data).glob('choano.earned.*.v1'))
assert len(documents) == 2
import json
assert json.loads(legacy.read_text()) == legacy_data
for document in documents:
saved = json.loads(document.read_text())
assert saved['pending'] is False
+1 -1
View File
@@ -14,7 +14,7 @@ main :: () -> s32 {
if !Storage.Load("account-a", *value, *pending) || !pending || value.unlocked != 5 { return 3 }
if !Storage.Persist("account-a", *value, false) { return 4 }
Storage.Close()
if !Storage.Load("account-b", *value, *pending) || pending || value.unlocked != 1 { return 5 }
if !Storage.Load("account-b", *value, *pending) || pending || value.unlocked != 4 { return 5 }
if Storage.Load("../account-a", *value, *pending) { return 6 }
Storage.Close()
if !Storage.Load("account-a", *value, *pending) || pending || value.unlocked != 5 { return 7 }
+2 -2
View File
@@ -233,8 +233,8 @@
}
],
"root": {
"dependencies": {"apps": "p333db0ddd841f1ec", "css": "p6269d7141b731fe4", "entity": "pb3958804740a96f2", "game2d": "pcad095808686987d", "kryon": "p09ea4e5550e9f459", "mingcute": "pe1027b9d16704793"},
"dependency_refs": {"apps": "b95d19334ab4338d3611ec9d44db62b50694e464", "css": "9ee24b3f70b9c7d776dc391cba15ba97533db227", "entity": "fc8f3d899dfc3d3e0b535006526485c6d8c8c279", "game2d": "fcacb49c1e128e9eb100884e6029b24b4e608d38", "kryon": "8d5d2e752a219674f993473c8410847ba42fad48", "mingcute": "master"},
"dependencies": {"apps": "p333db0ddd841f1ec", "crypto": "pc23fbf455e97614d", "css": "p6269d7141b731fe4", "entity": "pb3958804740a96f2", "game2d": "pcad095808686987d", "kryon": "p09ea4e5550e9f459", "mingcute": "pe1027b9d16704793"},
"dependency_refs": {"apps": "b95d19334ab4338d3611ec9d44db62b50694e464", "crypto": "master", "css": "9ee24b3f70b9c7d776dc391cba15ba97533db227", "entity": "fc8f3d899dfc3d3e0b535006526485c6d8c8c279", "game2d": "fcacb49c1e128e9eb100884e6029b24b4e608d38", "kryon": "8d5d2e752a219674f993473c8410847ba42fad48", "mingcute": "master"},
"name": "Choano"
},
"toolchain": {
+4
View File
@@ -52,3 +52,7 @@ ref = "master"
[dependencies.css]
git = "https://github.com/kryonlabs/css.git"
ref = "9ee24b3f70b9c7d776dc391cba15ba97533db227"
[dependencies.crypto]
git = "https://github.com/ziranlang/crypto.git"
ref = "master"