Keep Telegram access and share active practices across account devices
This commit is contained in:
1 parent
8145713c6e
commit
a03e05ddc4
42 files changed
+1542
-44
No files matched your search
@@ -1937,6 +1937,16 @@ sync-safety-test: $(ZI2C_BIN)
|
||||
|
||||
test: sync-safety-test
|
||||
|
||||
.PHONY: account-activity-test
|
||||
account-activity-test: $(ZIRAN_BIN) $(LIBOQS_A)
|
||||
@sh tests/account_activity_zi_test.sh $(ZIRAN_BIN) $(LIBOQS_A)
|
||||
|
||||
test: account-activity-test
|
||||
|
||||
.PHONY: account-activity-ui-test
|
||||
account-activity-ui-test: $(TARGET) $(INBE_FULL_BUNDLE) account-activity-test
|
||||
sh tests/account_activity_ui_test.sh $(abspath $(TARGET))
|
||||
|
||||
.PHONY: sync-status-policy-test
|
||||
sync-status-policy-test: $(ZI2C_BIN)
|
||||
@env -u DISPLAY -u WAYLAND_DISPLAY \
|
||||
|
||||
@@ -17,6 +17,10 @@ Inner Breeze is a free, open-source practice app for breathing, meditation, and
|
||||
habit tracking. It works offline, stores data locally in SQLite, and can
|
||||
optionally sync user-owned data through a Daochi-compatible sync server.
|
||||
|
||||
[Account activity](docs/ACCOUNT_ACTIVITY.md) explains persistent Telegram linking,
|
||||
reopening an authorized installation, and seeing and controlling the running
|
||||
practice from another device connected to the same account.
|
||||
|
||||
## Features
|
||||
|
||||
- Lumi, a local firefly companion with private chat, habit completion, practice starts, and optional todo tools
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Account activity and Telegram reopening
|
||||
|
||||
The Lumi bot's link belongs to the numeric Telegram account and remains in
|
||||
Daochi's database across Telegram clients and node restarts. It does not belong
|
||||
to a Telegram Desktop window or a Mini App launch.
|
||||
|
||||
On reopening the Mini App, Inbe verifies fresh Telegram identity, validates the
|
||||
saved owner's signed delegate grant, and obtains a fresh key-bound session
|
||||
automatically. A temporary sync outage or offline reopening keeps the saved
|
||||
delegate. Offline reopening denies access until a fresh online launch verifies
|
||||
the identity; it does not delete the protected account. Changed
|
||||
identity, revocation, or an expired grant still prevents access. The owner's
|
||||
private key is never sent to the bot or stored in the delegate capsule.
|
||||
|
||||
Telegram SecureStorage is device-local. A new Mini App device still needs its
|
||||
own initial authorization. A native app joins the same account by importing the
|
||||
same account key. The current Mini App grant covers Lumi history and shared
|
||||
activity; it does not grant access to owner-only Diary, Lists, or Habits data.
|
||||
|
||||
The running device publishes encrypted activity every two seconds through the
|
||||
existing v6 private Lumi collection. The shared record identifies the practice,
|
||||
its originating device, session, phase, counters, elapsed or remaining time,
|
||||
pause state, and last update. Phase and round boundaries publish immediately.
|
||||
Other signed-in devices show it on the Practice
|
||||
page and provide a shortcut from other pages. The Telegram Mini App opens the
|
||||
live activity view and can return to Lumi.
|
||||
|
||||
Pause and resume requests target the exact session, originating device, and
|
||||
state revision. The running device acknowledges them in its next activity
|
||||
record. Replayed, expired, and superseded requests are ignored. Observers do not
|
||||
advance the practice or save another result. A finished session publishes an
|
||||
inactive record. A session without updates for twenty seconds shows its last
|
||||
known state and disables remote controls.
|
||||
|
||||
Sync transport continues during practice while changes to its screen and
|
||||
settings remain deferred. Android's existing background practice timer also
|
||||
pumps activity and sync while background play is enabled. Background suspension,
|
||||
an offline device, or concurrent offline starts cannot provide uninterrupted
|
||||
live synchronization. This is a live view and remote pause/resume, not a transfer
|
||||
of practice execution to another device.
|
||||
|
||||
Validation: `make account-activity-test telegram-account-flow-test
|
||||
sync-safety-test android-timer-zi-test android-lifecycle-zi-test`;
|
||||
`make build-laws proof-test sync-recovery-test version-test`; and the
|
||||
two-client `sync-server-test` scenario, which exchanges the encrypted session,
|
||||
pause request, acknowledgement, and completion through a real Daochi server.
|
||||
`make account-activity-ui-test` checks the desktop and narrow-screen live view,
|
||||
remote control acknowledgement, stale controls, and completion on a private
|
||||
Xvfb display. Harmony's application state also exposes the account activity
|
||||
and enables its remote pause/resume controls only while the session is fresh.
|
||||
@@ -2580,3 +2580,19 @@ Možnosti účtu
|
||||
[session_minimize_button]
|
||||
Minimalizovat
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
Probíhá na jiném zařízení
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
Pozastaveno na jiném zařízení
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Poslední známé cvičení · čekání na aktualizace
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Čekání na zařízení, kde cvičení probíhá
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Kontooptionen
|
||||
[session_minimize_button]
|
||||
Minimieren
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
Läuft auf einem anderen Gerät
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
Auf einem anderen Gerät pausiert
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Letzte bekannte Sitzung · warte auf Aktualisierung
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Warte auf das Gerät mit der laufenden Sitzung
|
||||
---
|
||||
@@ -2579,3 +2579,19 @@ Account options
|
||||
[session_minimize_button]
|
||||
Minimize
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
Running on another device
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
Paused on another device
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Last known session · awaiting updates
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Waiting for the running device
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Opciones de cuenta
|
||||
[session_minimize_button]
|
||||
Minimizar
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
En curso en otro dispositivo
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
En pausa en otro dispositivo
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Última sesión conocida · esperando novedades
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Esperando al dispositivo con la sesión en curso
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Options du compte
|
||||
[session_minimize_button]
|
||||
Réduire
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
En cours sur un autre appareil
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
En pause sur un autre appareil
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Dernière séance connue · en attente de mises à jour
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
En attente de l’appareil où la séance est en cours
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Opsi akun
|
||||
[session_minimize_button]
|
||||
Perkecil
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
Berjalan di perangkat lain
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
Dijeda di perangkat lain
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Sesi terakhir yang diketahui · menunggu pembaruan
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Menunggu perangkat yang menjalankan sesi
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Opzioni account
|
||||
[session_minimize_button]
|
||||
Riduci a icona
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
In corso su un altro dispositivo
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
In pausa su un altro dispositivo
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Ultima sessione nota · in attesa di aggiornamenti
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
In attesa del dispositivo con la sessione in corso
|
||||
---
|
||||
@@ -2582,3 +2582,19 @@ Daochiノード
|
||||
[session_minimize_button]
|
||||
最小化
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
別のデバイスで実行中
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
別のデバイスで一時停止中
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
最後に確認したセッション · 更新を待っています
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
実行中のデバイスからの応答を待っています
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Daochi 노드
|
||||
[session_minimize_button]
|
||||
최소화
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
다른 기기에서 진행 중
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
다른 기기에서 일시 정지됨
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
마지막으로 확인한 세션 · 업데이트 대기 중
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
세션이 실행 중인 기기의 응답을 기다리는 중
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Opções da conta
|
||||
[session_minimize_button]
|
||||
Minimizar
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
Em andamento em outro dispositivo
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
Pausado em outro dispositivo
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Última sessão conhecida · aguardando atualizações
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Aguardando o dispositivo com a sessão em andamento
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Inner Breeze бесплатное приложение с открытым ис
|
||||
[session_minimize_button]
|
||||
Свернуть
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
Выполняется на другом устройстве
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
Приостановлено на другом устройстве
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
Последний известный сеанс · ожидание обновлений
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
Ожидание устройства с текущим сеансом
|
||||
---
|
||||
@@ -2580,3 +2580,19 @@ Daochi 节点
|
||||
[session_minimize_button]
|
||||
最小化
|
||||
---
|
||||
|
||||
[activity_remote_running]
|
||||
正在其他设备上进行
|
||||
---
|
||||
|
||||
[activity_remote_paused]
|
||||
已在其他设备上暂停
|
||||
---
|
||||
|
||||
[activity_remote_stale]
|
||||
最后已知的练习 · 等待更新
|
||||
---
|
||||
|
||||
[activity_control_pending]
|
||||
正在等待运行练习的设备
|
||||
---
|
||||
@@ -0,0 +1,284 @@
|
||||
#import "text_buffer"
|
||||
#import "wire"
|
||||
#import "authorization"
|
||||
#import, file "../core/types.zi";
|
||||
#import, file "account_activity_model.zi";
|
||||
#import, file "activity_start.zi";
|
||||
#import, file "app_types.zi";
|
||||
#import, file "session_screen.zi";
|
||||
#import, file "text_buffers.zi";
|
||||
#import, file "../core/breath_timing.zi";
|
||||
#import, file "../storage/cell_records.zi";
|
||||
#import, file "../storage/storage_core.zi";
|
||||
#import, file "../storage/sync_crypto_random.zi";
|
||||
#import, file "../storage/sync_crypto.zi";
|
||||
#import, file "../storage/delegate_store.zi";
|
||||
#import, file "../storage/temporary_data.zi";
|
||||
#import, file "../cells/package_files.zi";
|
||||
#import, file "../platform/environment.zi";
|
||||
|
||||
c :: #system_library "c";
|
||||
#if #defined(_WIN32) {
|
||||
ActivityNow :: (out: *s64) -> s64 #foreign c "_time64";
|
||||
} else {
|
||||
ActivityNow :: (out: *s64) -> s64 #foreign c "time";
|
||||
}
|
||||
ActivityFrameTime :: () -> float64 #foreign c "GetTime";
|
||||
ActivityScheduleSync :: (app: *InnerBreeze) -> s32 #foreign c "app_auto_sync";
|
||||
|
||||
ActivityState :: struct {
|
||||
owner: [65]u8
|
||||
device: [65]u8
|
||||
local: AccountActivity
|
||||
remote: AccountActivity
|
||||
last_poll: float64
|
||||
last_publish: s64
|
||||
was_running: bool
|
||||
last_paused: s32
|
||||
pending_control: [33]u8
|
||||
pending_at: s64
|
||||
view_open: bool
|
||||
observed_session: [33]u8
|
||||
}
|
||||
account_activity: ActivityState;
|
||||
|
||||
ActivityCurrentTime :: () -> s64 {
|
||||
return ActivityNow(null)
|
||||
}
|
||||
|
||||
ActivityRandomID :: (output: []u8, byte_count: s32) -> bool {
|
||||
bytes: [32]u8
|
||||
if byte_count < 1 || byte_count > 32 || output.count < byte_count * 2 + 1 ||
|
||||
SyncCryptoRandom(*bytes[0], byte_count) == 0 {
|
||||
return false
|
||||
}
|
||||
result := SyncCryptoBytesToHex(*bytes[0], byte_count, *output[0], output.count) != 0
|
||||
SyncCryptoWipe(*bytes[0], 32)
|
||||
return result
|
||||
}
|
||||
|
||||
ActivityAvailable :: () -> bool {
|
||||
return PreviewMode() == 0 && !DataTemporary() && storage_sync_enabled() != 0 &&
|
||||
storage_has_sync_account() != 0 &&
|
||||
(StoredAccountMode() != AccountModeDelegate || StoredDelegateAvailable() != 0)
|
||||
}
|
||||
|
||||
ActivityInitialize :: () -> bool {
|
||||
if !ActivityAvailable() {
|
||||
account_activity = ActivityState.{}
|
||||
return false
|
||||
}
|
||||
owner := storage_sync_data_owner_public_id()
|
||||
if owner.count != 64 {
|
||||
return false
|
||||
}
|
||||
state := *account_activity
|
||||
if owner != TextUntilNul(state.owner[:]) {
|
||||
state.* = ActivityState.{}
|
||||
unused AppCopyText(owner, state.owner[:])
|
||||
}
|
||||
if state.device[0] == cast(u8)0 {
|
||||
saved := storage_get_setting_text("activity_device_id")
|
||||
if ActivityHex(saved, 64) {
|
||||
unused AppCopyText(saved, state.device[:])
|
||||
} else {
|
||||
if !ActivityRandomID(state.device[:], 32) {
|
||||
return false
|
||||
}
|
||||
storage_set_setting_text("activity_device_id", TextUntilNul(state.device[:]))
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityRemoteVisible :: () -> bool {
|
||||
return ActivityAvailable() && account_activity.remote.active == 1 &&
|
||||
TextUntilNul(account_activity.remote.device_id[:]) != TextUntilNul(account_activity.device[:])
|
||||
}
|
||||
|
||||
ActivityCanStart :: () -> bool {
|
||||
return !ActivityRemoteVisible() || !ActivityFresh(account_activity.remote, ActivityNow(null))
|
||||
}
|
||||
|
||||
ActivitySample :: (app: *InnerBreeze, previous: AccountActivity, now: s64) -> AccountActivity {
|
||||
value := previous
|
||||
value.time = now
|
||||
value.active = 1
|
||||
value.screen = app_session_screen(app)
|
||||
value.paused = ifx app.session_paused != 0 then 1 else 0
|
||||
value.phase = 0
|
||||
value.round = 0
|
||||
value.count = 0
|
||||
value.elapsed = 0
|
||||
value.remaining = 0
|
||||
value.duration = 0
|
||||
value.cycles = 0
|
||||
value.total = 0
|
||||
if value.screen == ScreenSession {
|
||||
value.phase = app.breathing.phase
|
||||
value.round = app.breathing.round + 1
|
||||
value.count = BreathDigitsRead(app.breathing.count[:])
|
||||
if value.phase == BreathPhaseStarting {
|
||||
value.count = BreathPauseSeconds(app.breathing) - app.breathing.sectick / 60
|
||||
if value.count < 0 {
|
||||
value.count = 0
|
||||
}
|
||||
}
|
||||
value.total = app.breathing.max_rounds
|
||||
} else if value.screen == ScreenMeditation {
|
||||
value.duration = app.meditation.duration_seconds
|
||||
value.remaining = app.meditation.remaining_seconds
|
||||
value.elapsed = value.duration - value.remaining
|
||||
} else if value.screen == ScreenPatterns {
|
||||
value.paused = ifx app.patterns.paused != 0 then 1 else 0
|
||||
value.phase = app.patterns.phase
|
||||
value.elapsed = app.patterns.elapsed_seconds
|
||||
value.duration = app.patterns.duration_minutes * 60
|
||||
value.remaining = ifx value.duration > value.elapsed then value.duration - value.elapsed else 0
|
||||
value.count = app.patterns.phase_second
|
||||
value.cycles = app.patterns.cycle
|
||||
} else if value.screen == ScreenSunSalutation {
|
||||
value.phase = app.sun_salutation.step
|
||||
value.round = app.sun_salutation.repetition + 1
|
||||
value.total = app.sun_salutation.repetitions
|
||||
value.count = app.sun_salutation.step_ticks / 60
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// No remote device advances the originating session or saves a second result.
|
||||
// An acknowledged control can never apply to a replacement session or replay.
|
||||
ActivityApplyControl :: (app: *InnerBreeze, now: s64) -> bool {
|
||||
document := CellRecordRead(ActivityControlKey)
|
||||
defer { PackageFree(document) }
|
||||
command: ActivityControl
|
||||
state := *account_activity
|
||||
if !ActivityControlRead(document, *command) ||
|
||||
!ActivityControlMatches(command, state.local, now) {
|
||||
return false
|
||||
}
|
||||
app.session_paused = command.paused
|
||||
if state.local.screen == ScreenPatterns {
|
||||
app.patterns.paused = command.paused
|
||||
}
|
||||
state.local.control_id = command.id
|
||||
state.local.revision += 1
|
||||
state.local.paused = command.paused
|
||||
state.last_paused = command.paused
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityPump :: (app: *InnerBreeze) {
|
||||
activity_start_check = ActivityCanStart
|
||||
if app == null || !ActivityInitialize() {
|
||||
return
|
||||
}
|
||||
state := *account_activity
|
||||
clock := ActivityFrameTime()
|
||||
if clock >= state.last_poll && clock - state.last_poll < 0.25 {
|
||||
return
|
||||
}
|
||||
state.last_poll = clock
|
||||
now := ActivityNow(null)
|
||||
document := CellRecordRead(ActivityRecordKey)
|
||||
unused ActivityRead(document, *state.remote)
|
||||
PackageFree(document)
|
||||
if ActivityRemoteVisible() &&
|
||||
TextUntilNul(state.observed_session[:]) != TextUntilNul(state.remote.session_id[:]) {
|
||||
state.observed_session = state.remote.session_id
|
||||
state.view_open = true
|
||||
}
|
||||
if state.pending_control[0] != cast(u8)0 &&
|
||||
(TextUntilNul(state.remote.control_id[:]) == TextUntilNul(state.pending_control[:]) ||
|
||||
now - state.pending_at >= ActivityFreshSeconds) {
|
||||
state.pending_control = .{}
|
||||
}
|
||||
running := app_is_session_screen(app_session_screen(app))
|
||||
if !running && !state.was_running {
|
||||
return
|
||||
}
|
||||
replaced := running && state.was_running && app_session_screen(app) != state.local.screen
|
||||
if running && (!state.was_running || replaced) {
|
||||
state.local = AccountActivity.{}
|
||||
if !ActivityRandomID(state.local.session_id[:], 16) {
|
||||
return
|
||||
}
|
||||
state.local.device_id = state.device
|
||||
state.local.revision = 1
|
||||
state.last_publish = 0
|
||||
}
|
||||
changed := running != state.was_running || replaced
|
||||
if running {
|
||||
previous := state.local
|
||||
state.local = ActivitySample(app, state.local, now)
|
||||
// Publish boundaries immediately so observers see the new phase or
|
||||
// round without waiting for the periodic timer snapshot.
|
||||
if state.local.phase != previous.phase || state.local.round != previous.round {
|
||||
changed = true
|
||||
}
|
||||
if state.was_running && state.local.paused != state.last_paused {
|
||||
state.local.revision += 1
|
||||
changed = true
|
||||
}
|
||||
state.last_paused = state.local.paused
|
||||
if ActivityApplyControl(app, now) {
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
state.local.active = 0
|
||||
state.local.time = now
|
||||
state.local.revision += 1
|
||||
}
|
||||
if !changed && now >= state.last_publish && now - state.last_publish < ActivityPublishSeconds {
|
||||
return
|
||||
}
|
||||
payload: [2048]u8
|
||||
if ActivityWrite(state.local, payload[:]) && CellRecordWrite(ActivityRecordKey, TextUntilNul(payload[:])) {
|
||||
state.last_publish = now
|
||||
state.was_running = running
|
||||
unused ActivityScheduleSync(app)
|
||||
}
|
||||
}
|
||||
|
||||
ActivityRequestPause :: (app: *InnerBreeze, paused: s32) -> bool {
|
||||
state := *account_activity
|
||||
now := ActivityNow(null)
|
||||
if app == null || !ActivityRemoteVisible() || !ActivityFresh(state.remote, now) ||
|
||||
state.pending_control[0] != cast(u8)0 || (paused != 0 && paused != 1) {
|
||||
return false
|
||||
}
|
||||
id: [33]u8
|
||||
if !ActivityRandomID(id[:], 16) {
|
||||
return false
|
||||
}
|
||||
output: [1024]u8
|
||||
writer := Writer.{output[:], 0, true}
|
||||
writer = WriteByte(writer, cast(u8)123)
|
||||
writer = JsonTextField(writer, "id", TextUntilNul(id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonTextField(writer, "session_id", TextUntilNul(state.remote.session_id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonTextField(writer, "device_id", TextUntilNul(state.remote.device_id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonNumberField(writer, "time", now)
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonNumberField(writer, "revision", state.remote.revision)
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonNumberField(writer, "paused", paused)
|
||||
writer = WriteByte(writer, cast(u8)125)
|
||||
if !writer.valid || !CellRecordWrite(ActivityControlKey, TextUntilNul(output[:])) {
|
||||
return false
|
||||
}
|
||||
state.pending_control = id
|
||||
state.pending_at = now
|
||||
unused ActivityScheduleSync(app)
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityContext :: (output: []u8) -> bool {
|
||||
value := ifx account_activity.was_running then account_activity.local else account_activity.remote
|
||||
if !ActivityAvailable() || value.session_id[0] == cast(u8)0 || value.active != 1 {
|
||||
return AppCopyText("null", output)
|
||||
}
|
||||
return ActivityWrite(value, output)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// Live activity is a private account record. Only its originating device runs
|
||||
// the practice and saves results; other devices observe and request controls.
|
||||
#import "json_scan"
|
||||
#import "text_buffer"
|
||||
#import "wire"
|
||||
#import "authorization"
|
||||
#import, file "../core/types.zi";
|
||||
|
||||
ActivityRecordKey :: "cell.lumi.activity.current"
|
||||
ActivityControlKey :: "cell.lumi.activity.control"
|
||||
ActivityFreshSeconds :: 20
|
||||
ActivityPublishSeconds :: 2
|
||||
|
||||
AccountActivity :: struct {
|
||||
session_id: [33]u8
|
||||
device_id: [65]u8
|
||||
control_id: [33]u8
|
||||
time: s64
|
||||
revision: s64
|
||||
active: s32
|
||||
paused: s32
|
||||
screen: s32
|
||||
phase: s32
|
||||
round: s32
|
||||
count: s32
|
||||
elapsed: s32
|
||||
remaining: s32
|
||||
duration: s32
|
||||
cycles: s32
|
||||
total: s32
|
||||
}
|
||||
|
||||
ActivityControl :: struct {
|
||||
id: [33]u8
|
||||
session_id: [33]u8
|
||||
device_id: [65]u8
|
||||
time: s64
|
||||
revision: s64
|
||||
paused: s32
|
||||
}
|
||||
|
||||
ActivityHex :: (value: string, length: s32) -> bool {
|
||||
if value.count != length {
|
||||
return false
|
||||
}
|
||||
for byte: value {
|
||||
if !((byte >= 48 && byte <= 57) || (byte >= 97 && byte <= 102)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityInteger :: (json: string, field: string, maximum: s64, output: *s64) -> bool {
|
||||
number := ReadNumber(json, FieldAt(json, 0, field))
|
||||
if !number.valid || number.value < 0 || number.value > cast(float64)maximum ||
|
||||
number.value != cast(float64)cast(s64)number.value {
|
||||
return false
|
||||
}
|
||||
output.* = cast(s64)number.value
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityRead :: (json: string, output: *AccountActivity) -> bool {
|
||||
output.* = AccountActivity.{}
|
||||
if json.count == 0 || json.count > 2048 || json[0] != cast(u8)123 ||
|
||||
ValueEnd(json, 0, 0) != json.count {
|
||||
return false
|
||||
}
|
||||
value: AccountActivity
|
||||
if ReadStringText(json, FieldAt(json, 0, "session_id"), value.session_id[:]) != 32 ||
|
||||
ReadStringText(json, FieldAt(json, 0, "device_id"), value.device_id[:]) != 64 ||
|
||||
!ActivityHex(TextUntilNul(value.session_id[:]), 32) ||
|
||||
!ActivityHex(TextUntilNul(value.device_id[:]), 64) {
|
||||
return false
|
||||
}
|
||||
control_count := ReadStringText(json, FieldAt(json, 0, "control_id"), value.control_id[:])
|
||||
if control_count != 0 && (control_count != 32 || !ActivityHex(TextUntilNul(value.control_id[:]), 32)) {
|
||||
return false
|
||||
}
|
||||
names: [14]string = .["time", "revision", "active", "paused", "screen", "phase", "round",
|
||||
"count", "elapsed", "remaining", "duration", "cycles", "total", "version"]
|
||||
values: [14]s64
|
||||
for index: cast(s32)0..13 {
|
||||
maximum: s64 = ifx index == 0 then 4503599627370495 else 2147483647
|
||||
if !ActivityInteger(json, names[index], maximum, *values[index]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if values[13] != 1 || values[0] == 0 || values[1] == 0 || values[2] > 1 || values[3] > 1 ||
|
||||
values[4] < ScreenSession || values[4] > ScreenPatterns || values[5] > 12 ||
|
||||
values[6] > 12 || values[8] > 86400 || values[9] > 86400 || values[10] > 86400 {
|
||||
return false
|
||||
}
|
||||
value.time = values[0]
|
||||
value.revision = values[1]
|
||||
value.active = cast(s32)values[2]
|
||||
value.paused = cast(s32)values[3]
|
||||
value.screen = cast(s32)values[4]
|
||||
value.phase = cast(s32)values[5]
|
||||
value.round = cast(s32)values[6]
|
||||
value.count = cast(s32)values[7]
|
||||
value.elapsed = cast(s32)values[8]
|
||||
value.remaining = cast(s32)values[9]
|
||||
value.duration = cast(s32)values[10]
|
||||
value.cycles = cast(s32)values[11]
|
||||
value.total = cast(s32)values[12]
|
||||
output.* = value
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityWrite :: (value: AccountActivity, output: []u8) -> bool {
|
||||
writer := Writer.{output, 0, true}
|
||||
writer = WriteText(writer, "{\"version\":1,")
|
||||
writer = JsonTextField(writer, "session_id", TextUntilNul(value.session_id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonTextField(writer, "device_id", TextUntilNul(value.device_id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonTextField(writer, "control_id", TextUntilNul(value.control_id[:]))
|
||||
names: [13]string = .["time", "revision", "active", "paused", "screen", "phase", "round",
|
||||
"count", "elapsed", "remaining", "duration", "cycles", "total"]
|
||||
values: [13]s64 = .[value.time, value.revision, cast(s64)value.active, cast(s64)value.paused,
|
||||
cast(s64)value.screen, cast(s64)value.phase, cast(s64)value.round, cast(s64)value.count,
|
||||
cast(s64)value.elapsed, cast(s64)value.remaining, cast(s64)value.duration,
|
||||
cast(s64)value.cycles, cast(s64)value.total]
|
||||
for index: cast(s32)0..12 {
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonNumberField(writer, names[index], values[index])
|
||||
}
|
||||
return WriteByte(writer, cast(u8)125).valid
|
||||
}
|
||||
|
||||
ActivityFresh :: (value: AccountActivity, now: s64) -> bool {
|
||||
return value.active == 1 && now > 0 && value.time <= now + 5 &&
|
||||
value.time >= now - ActivityFreshSeconds
|
||||
}
|
||||
|
||||
ActivityControlRead :: (json: string, output: *ActivityControl) -> bool {
|
||||
output.* = ActivityControl.{}
|
||||
if json.count == 0 || json.count > 1024 || json[0] != cast(u8)123 ||
|
||||
ValueEnd(json, 0, 0) != json.count {
|
||||
return false
|
||||
}
|
||||
value: ActivityControl
|
||||
paused: s64
|
||||
if ReadStringText(json, FieldAt(json, 0, "id"), value.id[:]) != 32 ||
|
||||
ReadStringText(json, FieldAt(json, 0, "session_id"), value.session_id[:]) != 32 ||
|
||||
ReadStringText(json, FieldAt(json, 0, "device_id"), value.device_id[:]) != 64 ||
|
||||
!ActivityHex(TextUntilNul(value.id[:]), 32) ||
|
||||
!ActivityHex(TextUntilNul(value.session_id[:]), 32) ||
|
||||
!ActivityHex(TextUntilNul(value.device_id[:]), 64) ||
|
||||
!ActivityInteger(json, "time", 4503599627370495, *value.time) ||
|
||||
!ActivityInteger(json, "revision", 2147483647, *value.revision) ||
|
||||
!ActivityInteger(json, "paused", 1, *paused) {
|
||||
return false
|
||||
}
|
||||
value.paused = cast(s32)paused
|
||||
output.* = value
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityControlMatches :: (control: ActivityControl, activity: AccountActivity, now: s64) -> bool {
|
||||
return ActivityFresh(activity, now) && control.time > 0 &&
|
||||
control.time <= now + 5 && control.time >= now - ActivityFreshSeconds &&
|
||||
control.revision == activity.revision &&
|
||||
TextUntilNul(control.session_id[:]) == TextUntilNul(activity.session_id[:]) &&
|
||||
TextUntilNul(control.device_id[:]) == TextUntilNul(activity.device_id[:]) &&
|
||||
TextUntilNul(control.id[:]) != TextUntilNul(activity.control_id[:])
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
#import, file "account_activity.zi";
|
||||
#import, file "account_activity_model.zi";
|
||||
#import, file "../core/types.zi";
|
||||
#import, file "app_types.zi";
|
||||
#import, file "metrics.zi";
|
||||
#import, file "locale.zi";
|
||||
#import, file "text_buffers.zi";
|
||||
#import, file "session_window_view.zi";
|
||||
#import, file "../practices/practice_registry.zi";
|
||||
#import, file "../practices/sun_salutation/sun_salutation_labels.zi";
|
||||
#import, file "../practices/patterns/patterns_rules.zi";
|
||||
#import "text_props"
|
||||
#import "text_widget"
|
||||
#import "button_props"
|
||||
#import "button_widget"
|
||||
#import "geometry"
|
||||
#import "tree"
|
||||
#import "session"
|
||||
#import "text"
|
||||
#import "vec"
|
||||
#import "text_buffer"
|
||||
#import "layout"
|
||||
#import, file "session_screen.zi";
|
||||
#import, file "app_nav_state.zi";
|
||||
#import, file "route_types.zi";
|
||||
#import, file "app_chrome.zi";
|
||||
#import, file "../cells/package_files.zi";
|
||||
|
||||
using AppNavRoute;
|
||||
|
||||
ActivityStatus :: (value: AccountActivity, output: []u8) -> string {
|
||||
if value.screen == ScreenMeditation {
|
||||
return session_window_clock(value.remaining, output)
|
||||
}
|
||||
if value.screen == ScreenPatterns {
|
||||
return session_window_clock(ifx value.duration > 0 then value.remaining else value.elapsed, output)
|
||||
}
|
||||
if value.screen == ScreenSession {
|
||||
key := "notification_starting_seconds"
|
||||
if value.phase == BreathPhaseBreathe {
|
||||
key = "notification_breathing_count"
|
||||
} else if value.phase == BreathPhaseHold {
|
||||
key = "notification_hold_seconds"
|
||||
} else if value.phase == BreathPhaseRecover {
|
||||
key = "notification_breath_in_seconds"
|
||||
} else if value.phase == BreathPhaseNext {
|
||||
key = "session_round_label"
|
||||
}
|
||||
unused FormatNumberTemplate(LocaleText(key),
|
||||
ifx value.phase == BreathPhaseNext then value.round else value.count, output)
|
||||
return TextUntilNul(output)
|
||||
}
|
||||
unused FormatNumberTemplate(LocaleText("session_round_label"), value.round, output)
|
||||
return TextUntilNul(output)
|
||||
}
|
||||
|
||||
ActivityDescription :: () -> string {
|
||||
if !ActivityRemoteVisible() {
|
||||
return ""
|
||||
}
|
||||
value := account_activity.remote
|
||||
status: [160]u8
|
||||
summary := ActivityStatus(value, status[:])
|
||||
out: Vec(u8)
|
||||
state_key := "activity_remote_running"
|
||||
if !ActivityFresh(value, ActivityCurrentTime()) {
|
||||
state_key = "activity_remote_stale"
|
||||
} else if value.paused != 0 {
|
||||
state_key = "activity_remote_paused"
|
||||
}
|
||||
BuilderPrint(*out, "% · %\n%", practice_label(session_window_practice(value.screen)),
|
||||
LocaleText(state_key), summary)
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
// The account's running practice occupies the Practice page on observers.
|
||||
// Its controls request an action; the acknowledged state comes from the runner.
|
||||
ActivityDrawRemote :: (app: *InnerBreeze, hosted: bool = false) -> bool {
|
||||
if app == null || !ActivityRemoteVisible() {
|
||||
return false
|
||||
}
|
||||
value := account_activity.remote
|
||||
session := app.ui.session
|
||||
left := AppScale(24)
|
||||
width := app.ui.view_width - left * 2
|
||||
top := app_content_top_reserved(app) + AppScale(24)
|
||||
name := practice_label(session_window_practice(value.screen))
|
||||
Text(session, TextProps.{.key = KeyHash("inbe/activity/name"),
|
||||
.bounds = Rectangle.{cast(float32)left, cast(float32)top, cast(float32)width, cast(float32)AppScale(56)},
|
||||
.text = name, .font = AppScale(28)})
|
||||
fresh := ActivityFresh(value, ActivityCurrentTime())
|
||||
state_key := "activity_remote_running"
|
||||
if !fresh {
|
||||
state_key = "activity_remote_stale"
|
||||
} else if value.paused != 0 {
|
||||
state_key = "activity_remote_paused"
|
||||
}
|
||||
Text(session, TextProps.{.key = KeyHash("inbe/activity/state"),
|
||||
.bounds = Rectangle.{cast(float32)left, cast(float32)(top + AppScale(72)),
|
||||
cast(float32)width, cast(float32)AppScale(72)},
|
||||
.text = LocaleText(state_key), .font = AppFontSize()})
|
||||
status_buffer: [160]u8
|
||||
status := ActivityStatus(value, status_buffer[:])
|
||||
Text(session, TextProps.{.key = KeyHash("inbe/activity/progress"),
|
||||
.bounds = Rectangle.{cast(float32)left, cast(float32)(top + AppScale(148)),
|
||||
cast(float32)width, cast(float32)AppScale(76)},
|
||||
.text = FrameTextHold(*app.ui.frame_text, status), .font = AppScale(32)})
|
||||
phase: string
|
||||
if value.screen == ScreenPatterns {
|
||||
phase = LocaleText(patterns_phase_label_key(value.phase))
|
||||
} else if value.screen == ScreenSunSalutation {
|
||||
phase = SunSalutationStepTitle(value.phase)
|
||||
} else if value.screen == ScreenSession {
|
||||
round: [64]u8
|
||||
unused FormatNumberTemplate(LocaleText("session_round_label"), value.round, round[:])
|
||||
phase = FrameTextHold(*app.ui.frame_text, TextUntilNul(round[:]))
|
||||
}
|
||||
if phase.count > 0 {
|
||||
Text(session, TextProps.{.key = KeyHash("inbe/activity/phase"),
|
||||
.bounds = Rectangle.{cast(float32)left, cast(float32)(top + AppScale(232)),
|
||||
cast(float32)width, cast(float32)AppScale(60)},
|
||||
.text = phase, .font = AppFontSize()})
|
||||
}
|
||||
pending := account_activity.pending_control[0] != cast(u8)0
|
||||
label := "pause_button"
|
||||
if pending {
|
||||
label = "activity_control_pending"
|
||||
} else if value.paused != 0 {
|
||||
label = "play_button"
|
||||
}
|
||||
if Button(session, ButtonProps.{.key = KeyHash("inbe/activity/pause"),
|
||||
.bounds = Rectangle.{cast(float32)left, cast(float32)(top + AppScale(308)),
|
||||
cast(float32)width, cast(float32)AppScale(48)},
|
||||
.label = LocaleText(label), .disabled = !fresh || pending, .loading = pending}) != 0 {
|
||||
unused ActivityRequestPause(app, ifx value.paused != 0 then 0 else 1)
|
||||
}
|
||||
if hosted && Button(session, ButtonProps.{.key = KeyHash("inbe/activity/lumi"),
|
||||
.bounds = Rectangle.{cast(float32)left, cast(float32)(top + AppScale(372)),
|
||||
cast(float32)width, cast(float32)AppScale(44)}, .label = "Lumi"}) != 0 {
|
||||
account_activity.view_open = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ActivityDrawIndicator :: (app: *InnerBreeze, hosted: bool = false) {
|
||||
if app == null || !ActivityRemoteVisible() || app.launcher_open ||
|
||||
app_is_session_screen(app_session_screen(app)) ||
|
||||
(!hosted && app.breathing.screen == ScreenStart &&
|
||||
app.main_tab == cast(s32)AppMainTab.APP_MAIN_TAB_PRACTICE) {
|
||||
return
|
||||
}
|
||||
status_buffer: [160]u8
|
||||
value := account_activity.remote
|
||||
status := ActivityStatus(value, status_buffer[:])
|
||||
summary: Vec(u8)
|
||||
BuilderPrint(*summary, "% · %", practice_label(session_window_practice(value.screen)), status)
|
||||
text := BuilderFinish(summary)
|
||||
defer { PackageFree(text) }
|
||||
width := AppScale(240)
|
||||
if width > app.ui.view_width - AppScale(16) {
|
||||
width = app.ui.view_width - AppScale(16)
|
||||
}
|
||||
if Button(app.ui.session, ButtonProps.{.key = KeyHash("inbe/activity/open"),
|
||||
.bounds = Rectangle.{cast(float32)(app.ui.view_width - width - AppScale(8)),
|
||||
cast(float32)AppScale(72), cast(float32)width, cast(float32)AppScale(56)},
|
||||
.label = FrameTextHold(*app.ui.frame_text, text)}) != 0 {
|
||||
if hosted {
|
||||
account_activity.view_open = true
|
||||
} else {
|
||||
app_apply_nav_route(app, APP_NAV_ROUTE_PRACTICE)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// The account controller installs this check in a connected application.
|
||||
// Offline practice hosts have no remote session and keep the normal start path.
|
||||
ActivityStartCheck :: #type () -> bool;
|
||||
activity_start_check: ActivityStartCheck;
|
||||
|
||||
ActivityStartAllowed :: () -> bool {
|
||||
return activity_start_check == null || activity_start_check()
|
||||
}
|
||||
+25
-1
@@ -1019,6 +1019,7 @@ draw_global_modal :: (app: *InnerBreeze) {
|
||||
}
|
||||
|
||||
updateapp :: (app: *InnerBreeze) {
|
||||
ActivityPump(app)
|
||||
hover: s32 = 0
|
||||
center_x: s32 = view_width / 2
|
||||
frame_view_height: s32 = view_height
|
||||
@@ -1038,7 +1039,12 @@ updateapp :: (app: *InnerBreeze) {
|
||||
}
|
||||
if TelegramContextCurrent() && StoredDelegateAvailable() != 0 &&
|
||||
(app.enabled_apps & APP_LUMI) != 0 {
|
||||
lumi_screen_draw(app)
|
||||
if account_activity.view_open && ActivityRemoteVisible() {
|
||||
unused ActivityDrawRemote(app, true)
|
||||
} else {
|
||||
lumi_screen_draw(app)
|
||||
ActivityDrawIndicator(app, true)
|
||||
}
|
||||
}
|
||||
DrawTelegramAccountFlow(app)
|
||||
app.breathing.frame += 1
|
||||
@@ -1279,6 +1285,7 @@ updateapp :: (app: *InnerBreeze) {
|
||||
view_height = frame_view_height
|
||||
app_draw_session_nav(app)
|
||||
app_session_window_draw(app)
|
||||
ActivityDrawIndicator(app)
|
||||
app_draw_mini_expand_button(app)
|
||||
practice_screen_draw_first_run_guide(app)
|
||||
habits_screen_draw_first_run_guide(app)
|
||||
@@ -1292,6 +1299,19 @@ updateapp :: (app: *InnerBreeze) {
|
||||
app.breathing.frame += 1
|
||||
}
|
||||
|
||||
// Android's existing practice timer owns the same app-state mutex as the
|
||||
// foreground frame. Exchange live records while background practice continues;
|
||||
// drawing and result ownership remain on their existing paths.
|
||||
#program_export
|
||||
app_activity_background_sync :: (vapp: *void) {
|
||||
app := cast(*InnerBreeze)vapp
|
||||
if app == null {
|
||||
return
|
||||
}
|
||||
ActivityPump(app)
|
||||
app_sync_pump(app)
|
||||
}
|
||||
|
||||
app_update_draw_last_full_w: s32 = -1;
|
||||
|
||||
app_update_draw_last_full_h: s32 = -1;
|
||||
@@ -1355,6 +1375,8 @@ app_update_draw :: (vapp: *void, viewport: Rectangle) {
|
||||
}
|
||||
profile_frame_start = app_profile_now()
|
||||
FrameTextReset(*app.ui.frame_text)
|
||||
// Styles follow the current app route, with cached parsing between edits.
|
||||
unused app_apply_style(app)
|
||||
frame_sample: FrameActivitySample
|
||||
frame_sample.mouse_x = app.ui.mouse_x
|
||||
frame_sample.mouse_y = app.ui.mouse_y
|
||||
@@ -1489,6 +1511,7 @@ app_update_draw :: (vapp: *void, viewport: Rectangle) {
|
||||
}
|
||||
if TelegramAccountFlowOwnsContext() {
|
||||
TelegramAccountFlowPump(app)
|
||||
ActivityPump(app)
|
||||
app_profile_frame_end(profile_frame_start)
|
||||
return
|
||||
}
|
||||
@@ -1496,6 +1519,7 @@ app_update_draw :: (vapp: *void, viewport: Rectangle) {
|
||||
app_profile_record_habits(profile_habits_start)
|
||||
profile_sync_start = app_profile_now()
|
||||
settings_sync_account_pump(app)
|
||||
ActivityPump(app)
|
||||
app_sync_pump(app)
|
||||
app_lumi_pump(app)
|
||||
PackagePump(app.enabled_apps, cast(s32)PackageNow())
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ active_locale_index: s32;
|
||||
|
||||
// Index entries borrow mounted catalog bytes. Rebuild the catalogs whenever
|
||||
// the asset provider changes, before looking up any of their borrowed slices.
|
||||
LocaleCatalogCapacity :: 768
|
||||
LocaleCatalogCapacity :: 1024
|
||||
LocaleCatalogSlots :: 2048
|
||||
|
||||
LocaleCatalog :: struct {
|
||||
|
||||
@@ -17,5 +17,8 @@ SyncUiUpdateSafe :: (app: *InnerBreeze, now: float64,
|
||||
if app.breathing.screen == ScreenLumi && app.ui.text_input_active {
|
||||
return false
|
||||
}
|
||||
return app_background_sync_safe(app) != 0 && SyncUserIdle(now, last_input_at, input_active) && app.breathing.screen != ScreenStart
|
||||
return app_background_sync_safe(app) != 0 &&
|
||||
!SyncScreenBlocksRefresh(app.breathing.screen) &&
|
||||
!SyncScreenBlocksRefresh(app.session_window.screen) &&
|
||||
SyncUserIdle(now, last_input_at, input_active) && app.breathing.screen != ScreenStart
|
||||
}
|
||||
@@ -12,7 +12,8 @@ SyncSafetyState :: struct {
|
||||
}
|
||||
|
||||
SyncScreenBlocksRefresh :: (screen: s32) -> bool {
|
||||
return screen == ScreenPracticeSession || screen == ScreenMeditation || screen == ScreenSunSalutation
|
||||
return screen == ScreenPracticeSession || screen == ScreenMeditation ||
|
||||
screen == ScreenSunSalutation || screen == ScreenPatterns
|
||||
}
|
||||
|
||||
SyncInputBlocksRefresh :: (state: SyncSafetyState) -> bool {
|
||||
@@ -20,7 +21,9 @@ SyncInputBlocksRefresh :: (state: SyncSafetyState) -> bool {
|
||||
}
|
||||
|
||||
BackgroundSyncSafe :: (state: SyncSafetyState) -> bool {
|
||||
return state.modal_active == 0 && !SyncInputBlocksRefresh(state) && !SyncScreenBlocksRefresh(state.screen)
|
||||
// Transport may exchange encrypted records during a practice. Refreshing
|
||||
// its settings or screen remains a separate, deferred operation.
|
||||
return state.modal_active == 0 && !SyncInputBlocksRefresh(state)
|
||||
}
|
||||
|
||||
BackgroundSyncSafeFields :: (modal_active: s32, habit_edit_active: s32,
|
||||
@@ -37,11 +40,12 @@ BackgroundSyncSafeFields :: (modal_active: s32, habit_edit_active: s32,
|
||||
}
|
||||
|
||||
SyncUserIdle :: (now: float64, last_input_at: float64,
|
||||
input_active: bool) -> bool {
|
||||
input_active: bool) -> bool {
|
||||
return !input_active && now >= last_input_at + SYNC_UI_QUIET_SECONDS
|
||||
}
|
||||
|
||||
SyncUiRefreshSafe :: (state: SyncSafetyState, now: float64,
|
||||
last_input_at: float64, input_active: bool) -> bool {
|
||||
return BackgroundSyncSafe(state) && SyncUserIdle(now, last_input_at, input_active) && state.screen != ScreenStart
|
||||
last_input_at: float64, input_active: bool) -> bool {
|
||||
return BackgroundSyncSafe(state) && !SyncScreenBlocksRefresh(state.screen) &&
|
||||
SyncUserIdle(now, last_input_at, input_active) && state.screen != ScreenStart
|
||||
}
|
||||
@@ -26,12 +26,15 @@
|
||||
#import, file "app_types.zi";
|
||||
#import, file "locale.zi";
|
||||
#import, file "text_buffers.zi";
|
||||
#import, file "sync_retry.zi";
|
||||
|
||||
TelegramFlowServer :: "https://api.waozi.xyz"
|
||||
TelegramAccountFlow :: struct {
|
||||
started: bool
|
||||
hosted: bool
|
||||
waiting: bool
|
||||
request_transport_failed: bool
|
||||
preserve_protected: bool
|
||||
phase: s32
|
||||
status: s32
|
||||
retry_at: s64
|
||||
@@ -195,19 +198,25 @@ TelegramFlowPumpRemoteCancellation :: (flow: *TelegramAccountFlow) {
|
||||
}
|
||||
}
|
||||
|
||||
TelegramFlowFail :: (flow: *TelegramAccountFlow) {
|
||||
TelegramFlowFail :: (flow: *TelegramAccountFlow, preserve_protected: bool = false) {
|
||||
keep_saved := TelegramContextCurrent() && (preserve_protected || flow.request_transport_failed)
|
||||
flow.preserve_protected = keep_saved
|
||||
TelegramFlowStopOperations(flow)
|
||||
flow.phase = 90
|
||||
flow.view.busy = false
|
||||
flow.view.restore_failed = true
|
||||
flow.view.status = LocaleText("telegram_account_restore_failed")
|
||||
flow.view.status = LocaleText(ifx keep_saved then "lumi_telegram_error" else "telegram_account_restore_failed")
|
||||
flow.view.review_complete = false
|
||||
flow.view.allowed_actions = cast(u32)1 << 4
|
||||
ClearDelegate()
|
||||
flow.cleanup_pending = false
|
||||
TelegramFlowBeginRemoteCancellation(flow)
|
||||
TelegramFlowWipeSecrets(flow)
|
||||
TelegramFlowClearProtected(flow)
|
||||
// A transport failure says nothing about the saved signed grant. Deny
|
||||
// access in this launch, but retain protected storage for the next one.
|
||||
if !keep_saved {
|
||||
TelegramFlowClearProtected(flow)
|
||||
}
|
||||
}
|
||||
|
||||
TelegramFlowIDBody :: (field: string, value: string, output: []u8) -> bool {
|
||||
@@ -220,6 +229,7 @@ TelegramFlowIDBody :: (field: string, value: string, output: []u8) -> bool {
|
||||
|
||||
TelegramFlowStartRequest :: (flow: *TelegramAccountFlow, path: string,
|
||||
method: string, phase: s32) -> bool {
|
||||
flow.request_transport_failed = false
|
||||
if flow.waiting || flow.owner_operation.active || !TelegramContextCurrent() {
|
||||
return false
|
||||
}
|
||||
@@ -235,7 +245,10 @@ TelegramFlowStartRequest :: (flow: *TelegramAccountFlow, path: string,
|
||||
request.content_type = "application/json"
|
||||
request.accept = "application/json"
|
||||
request.body = ifx method == "GET" then "" else TextUntilNul(flow.body[:])
|
||||
if !transport.start(transport.context, request, flow.response[:]) { return false }
|
||||
if !transport.start(transport.context, request, flow.response[:]) {
|
||||
flow.request_transport_failed = true
|
||||
return false
|
||||
}
|
||||
flow.phase = phase
|
||||
flow.waiting = true
|
||||
flow.view.busy = true
|
||||
@@ -402,6 +415,10 @@ TelegramFlowHandleResponse :: (flow: *TelegramAccountFlow) {
|
||||
phase := flow.phase
|
||||
flow.waiting = false
|
||||
flow.view.busy = false
|
||||
if flow.status == 408 || flow.status == 429 || flow.status >= 500 {
|
||||
TelegramFlowFail(flow, true)
|
||||
return
|
||||
}
|
||||
if phase == 1 {
|
||||
if flow.status != 200 || !ReadTelegramEnvironment(json, TelegramFlowServer, *flow.environment) ||
|
||||
!TelegramRawInitDigest(TextUntilNul(flow.init_data[:]), flow.environment.bot_id, flow.init_digest[:]) ||
|
||||
@@ -618,7 +635,9 @@ TelegramAccountFlowCancel :: () {
|
||||
flow.cleanup_pending = false
|
||||
TelegramFlowBeginRemoteCancellation(flow)
|
||||
TelegramFlowWipeSecrets(flow)
|
||||
TelegramFlowClearProtected(flow)
|
||||
if !flow.preserve_protected {
|
||||
TelegramFlowClearProtected(flow)
|
||||
}
|
||||
flow.phase = 91
|
||||
}
|
||||
|
||||
@@ -742,7 +761,16 @@ TelegramAccountFlowPump :: (app: *InnerBreeze) {
|
||||
if result < 0 { SyncCryptoWipe(*flow.capsule[0], 65537) }
|
||||
if !SetVerifiedDelegateIdentity(flow.environment.bot_id, flow.identity.telegram_id, now + 300) {
|
||||
TelegramFlowFail(flow)
|
||||
} else { TelegramFlowChoice(flow) }
|
||||
} else {
|
||||
TelegramFlowChoice(flow)
|
||||
// Reopening the same verified Telegram account resumes its
|
||||
// saved grant without another account picker. The capsule
|
||||
// still passes the owner signature, identity and node checks,
|
||||
// then obtains a fresh key-bound session from the server.
|
||||
if flow.capsule[0] != cast(u8)0 && flow.phase == 4 {
|
||||
HandleTelegramAccountAction(app, 2)
|
||||
}
|
||||
}
|
||||
} else if flow.protected_phase == 2 {
|
||||
SyncCryptoWipe(*flow.capsule[0], 65537)
|
||||
} else if flow.protected_phase == 5 {
|
||||
@@ -805,7 +833,7 @@ TelegramAccountFlowPump :: (app: *InnerBreeze) {
|
||||
if !completed { return }
|
||||
flow.status = flow.owner_operation.status
|
||||
if flow.owner_operation.result != cast(AuthResult)AuthResult.AUTH_OK {
|
||||
TelegramFlowFail(flow)
|
||||
TelegramFlowFail(flow, retry_is_temporary(cast(s32)flow.owner_operation.result))
|
||||
} else { TelegramFlowHandleResponse(flow) }
|
||||
return
|
||||
}
|
||||
@@ -817,7 +845,10 @@ TelegramAccountFlowPump :: (app: *InnerBreeze) {
|
||||
return
|
||||
}
|
||||
if polled < 0 { return }
|
||||
if polled == 0 { TelegramFlowFail(flow); return }
|
||||
if polled == 0 {
|
||||
TelegramFlowFail(flow, true)
|
||||
return
|
||||
}
|
||||
TelegramFlowHandleResponse(flow)
|
||||
return
|
||||
}
|
||||
@@ -831,12 +862,17 @@ TelegramAccountFlowPump :: (app: *InnerBreeze) {
|
||||
if !TelegramFlowStartPolling(flow) { TelegramFlowFail(flow) }
|
||||
} else if flow.phase == 14 {
|
||||
if flow.sync_operation.active {
|
||||
if PollStoredOperation(*flow.sync_operation) && flow.sync_operation.result != 0 {
|
||||
flow.view.visible = true
|
||||
TelegramFlowFail(flow)
|
||||
if PollStoredOperation(*flow.sync_operation) {
|
||||
if retry_is_temporary(cast(s32)flow.sync_operation.result) {
|
||||
// A lost connection must not erase saved account access.
|
||||
flow.retry_at = now + 5
|
||||
} else if flow.sync_operation.result != 0 {
|
||||
flow.view.visible = true
|
||||
TelegramFlowFail(flow)
|
||||
}
|
||||
}
|
||||
} else if flow.retry_at <= now {
|
||||
flow.retry_at = now + 5
|
||||
flow.retry_at = now + 2
|
||||
flow.sync_renewal = StoredDelegateAvailable() == 0
|
||||
transport := NetworkTransport(*flow.sync_transfer)
|
||||
began := ifx flow.sync_renewal then BeginStoredSession(*flow.sync_operation, TelegramFlowServer, transport) else BeginStoredSync(*flow.sync_operation, TelegramFlowServer, transport)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#import "vec"
|
||||
#import "json_scan"
|
||||
#import "byte_text_linux"
|
||||
#import "text_buffer"
|
||||
#import, file "package_files.zi";
|
||||
#import, file "../screens/elist_types.zi";
|
||||
#import, file "../screens/diary_screen.zi";
|
||||
@@ -28,6 +29,7 @@
|
||||
#import, file "../app/text_buffers.zi";
|
||||
#import, file "../app/exercise_types.zi";
|
||||
#import, file "../practices/practice_registry.zi";
|
||||
#import, file "../app/account_activity.zi";
|
||||
using AppNavRoute;
|
||||
|
||||
AppToolContext :: (app: *InnerBreeze) -> string {
|
||||
@@ -62,7 +64,9 @@ AppToolContext :: (app: *InnerBreeze) -> string {
|
||||
BuilderPrint(*out, ",\"done\":%}", task.done)
|
||||
}
|
||||
}
|
||||
BuilderPrint(*out, "],\"local_time\":")
|
||||
activity: [2048]u8
|
||||
unused ActivityContext(activity[:])
|
||||
BuilderPrint(*out, "],\"account_activity\":%,\"local_time\":", TextUntilNul(activity[:]))
|
||||
LumiJsonString(*out, DiaryStoreClock())
|
||||
BuilderPrint(*out, ",\"apps\":{\"lists\":%,\"habits\":%,\"practices\":%,\"diary\":%},\"context_item_limit\":8}",
|
||||
app_nav_route_available(app, APP_NAV_ROUTE_ELIST), app_nav_route_available(app, APP_NAV_ROUTE_HABITS),
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
TimerNanoSleep :: (duration: *TimerTimespec,
|
||||
remaining: *TimerTimespec) -> s32 #foreign c "nanosleep";
|
||||
TimerAdvance :: (app: *void, elapsed_ms: s32) #foreign c "practice_active_advance_elapsed";
|
||||
TimerSyncActivity :: (app: *void) #foreign c "app_activity_background_sync";
|
||||
|
||||
timer_thread: usize;
|
||||
timer_mutex: AndroidMutex;
|
||||
@@ -71,6 +72,7 @@
|
||||
AndroidMutexUnlock(*timer_mutex)
|
||||
if app != null {
|
||||
TimerAdvance(app, elapsed)
|
||||
TimerSyncActivity(app)
|
||||
}
|
||||
AndroidMutexUnlock(*app_state_mutex)
|
||||
TimerSleep(cast(isize)100000000)
|
||||
|
||||
@@ -4,8 +4,11 @@
|
||||
#import "std/text"
|
||||
#import "std/json_scan"
|
||||
#import "byte_text_linux"
|
||||
#import "text_buffer"
|
||||
#import, file "feature_request.zi";
|
||||
#import, file "../app/app_types.zi";
|
||||
#import, file "../app/account_activity.zi";
|
||||
#import, file "../app/account_activity_model.zi";
|
||||
#import, file "../core/types.zi";
|
||||
#import, file "../app/settings_actions.zi";
|
||||
#import, file "../app/app_nav_state.zi";
|
||||
@@ -122,8 +125,13 @@ HostAction :: (app: *InnerBreeze, control: string, arguments: string) -> bool {
|
||||
}
|
||||
active := practice_active(app)
|
||||
if control == "practice.pause" || control == "practice.resume" {
|
||||
if active == null { return false }
|
||||
if active == null {
|
||||
return ActivityRequestPause(app, ifx control == "practice.pause" then 1 else 0)
|
||||
}
|
||||
app.session_paused = ifx control == "practice.pause" then 1 else 0
|
||||
if active.id == ExerciseType.EXERCISE_PATTERNS {
|
||||
app.patterns.paused = app.session_paused
|
||||
}
|
||||
return true
|
||||
}
|
||||
names: [4]string = .{"practice.whm.start", "practice.meditation.start",
|
||||
@@ -197,6 +205,8 @@ ReportHostState :: (app: *InnerBreeze) {
|
||||
if app.main_tab == APP_MAIN_TAB_DIARY { feature = 8 }
|
||||
active := practice_active(app)
|
||||
active_id := ifx active != null then cast(s32)active.id else -1
|
||||
remote_fresh := ActivityRemoteVisible() && ActivityFresh(account_activity.remote, ActivityCurrentTime())
|
||||
remote_control_ready := remote_fresh && account_activity.pending_control[0] == cast(u8)0
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "{\"interface\":\"harmony.app-state.v1\",\"feature\":%,\"host_feature\":%,\"screen\":%,\"practice\":%,\"practice_running\":%,\"paused\":%,\"round\":%,\"breath\":%,\"last_request_id\":\"%\",\"last_request_ok\":%,\"controls\":[", feature, app.host_feature, app.breathing.screen, active_id, active != null, app.session_paused != 0, app.breathing.round, BreathCountValue(app.breathing), AppTextFromCString(*last_request[0], 65), last_ok)
|
||||
names: [11]string = .{"open.practices", "open.habits", "open.lists",
|
||||
@@ -206,15 +216,26 @@ ReportHostState :: (app: *InnerBreeze) {
|
||||
"Start meditation", "Start Sun Salutation", "Start breathing patterns", "Pause practice", "Resume practice", "Lumi", "Diary"}
|
||||
for i: 0..10 {
|
||||
enabled := !AppMiniMode()
|
||||
if i >= 3 && i <= 6 { enabled = enabled && (active == null || active_id == i - 3) }
|
||||
if i == 7 { enabled = active != null && app.session_paused == 0 }
|
||||
if i == 8 { enabled = active != null && app.session_paused != 0 }
|
||||
if i >= 3 && i <= 6 {
|
||||
enabled = enabled && !remote_fresh && (active == null || active_id == i - 3)
|
||||
}
|
||||
if i == 7 {
|
||||
enabled = (active != null && app.session_paused == 0) ||
|
||||
(active == null && remote_control_ready && account_activity.remote.paused == 0)
|
||||
}
|
||||
if i == 8 {
|
||||
enabled = (active != null && app.session_paused != 0) ||
|
||||
(active == null && remote_control_ready && account_activity.remote.paused != 0)
|
||||
}
|
||||
if i == 9 { enabled = enabled && (CellsInstalledMask() & 16) != 0 }
|
||||
if i == 10 { enabled = enabled && (app.enabled_apps & CellsInstalledMask() & 8) != 0 }
|
||||
BuilderPrint(*out, "%{\"control\":\"%\",\"label\":\"%\",\"enabled\":%}", ifx i == 0 then "" else ",", names[i], labels[i], enabled)
|
||||
}
|
||||
tools := AssetRead("assets/mcp/tools.json")
|
||||
BuilderPrint(*out, "],\"settings\":{\"theme\":\"%\",\"theme_id\":%,\"theme_mode\":%,\"theme_source\":%,\"style\":%,\"scale\":%,\"navigation\":%,\"sidebar_compact\":%},\"mcp\":{\"tools\":%}}",
|
||||
activity: [2048]u8
|
||||
unused ActivityContext(activity[:])
|
||||
BuilderPrint(*out, "],\"account_activity\":%,\"account_activity_fresh\":%,\"settings\":{\"theme\":\"%\",\"theme_id\":%,\"theme_mode\":%,\"theme_source\":%,\"style\":%,\"scale\":%,\"navigation\":%,\"sidebar_compact\":%},\"mcp\":{\"tools\":%}}",
|
||||
TextUntilNul(activity[:]), remote_fresh || (account_activity.was_running && ActivityAvailable()),
|
||||
AppThemeName(app.theme_id), app.theme_id, app.theme_mode, app.theme_source,
|
||||
app.style_index, app.ui_scale_tenths, app.navigation_placement,
|
||||
app.nav_rail_collapsed, ifx tools.found then tools.data else "[]")
|
||||
|
||||
@@ -4,6 +4,7 @@ c :: #system_library "c";
|
||||
#import, file "../../app/app_types.zi";
|
||||
#import, file "../../app/exercise_types.zi";
|
||||
#import, file "../../app/manual_seen_actions.zi";
|
||||
#import, file "../../app/activity_start.zi";
|
||||
|
||||
using ExerciseType;
|
||||
|
||||
@@ -29,7 +30,7 @@ meditation_practice_destroy :: (app: *InnerBreeze) {
|
||||
|
||||
#program_export
|
||||
meditation_practice_start :: (app: *InnerBreeze) {
|
||||
if app == null {
|
||||
if app == null || !ActivityStartAllowed() {
|
||||
return
|
||||
}
|
||||
mark_exercise_manual_seen(app, EXERCISE_MEDITATION)
|
||||
|
||||
@@ -12,6 +12,7 @@ app_draw_session_exit_modal :: (app: *InnerBreeze, can_save: s32,
|
||||
#import, file "../../core/types.zi";
|
||||
#import, file "../../app/app_types.zi";
|
||||
#import, file "../../app/session_screen.zi";
|
||||
#import, file "../../app/activity_start.zi";
|
||||
#import "layout"
|
||||
#import "layout_props"
|
||||
#import "layout_widget"
|
||||
@@ -65,7 +66,7 @@ duration_presets: [5]s32 = .[
|
||||
];
|
||||
|
||||
meditation_start_seconds :: (app: *InnerBreeze, seconds: s32) {
|
||||
if app == null {
|
||||
if app == null || !ActivityStartAllowed() {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ c :: #system_library "c";
|
||||
#import, file "../../app/modal_rules.zi";
|
||||
#import, file "../../core/types.zi";
|
||||
#import, file "patterns_rules.zi";
|
||||
#import, file "../../app/activity_start.zi";
|
||||
|
||||
using ExerciseType;
|
||||
using ModalType;
|
||||
@@ -31,7 +32,7 @@ patterns_practice_destroy :: (app: *InnerBreeze) { unused app }
|
||||
|
||||
#program_export
|
||||
patterns_practice_start :: (app: *InnerBreeze) {
|
||||
if app == null { return }
|
||||
if app == null || !ActivityStartAllowed() { return }
|
||||
app.patterns.active = 1
|
||||
app.patterns.paused = 0
|
||||
app.patterns.phase = PATTERNS_PHASE_INHALE
|
||||
|
||||
@@ -6,6 +6,7 @@ c :: #system_library "c";
|
||||
#import, file "../../app/manual_seen_actions.zi";
|
||||
#import, file "../../core/types.zi";
|
||||
#import, file "sun_salutation_rules.zi";
|
||||
#import, file "../../app/activity_start.zi";
|
||||
|
||||
using ExerciseType;
|
||||
|
||||
@@ -14,7 +15,7 @@ meditation_music_start_session :: (app: *InnerBreeze) #foreign c;
|
||||
|
||||
#program_export
|
||||
sun_salutation_practice_start :: (app: *InnerBreeze) {
|
||||
if app == null { return }
|
||||
if app == null || !ActivityStartAllowed() { return }
|
||||
mark_exercise_manual_seen(app, EXERCISE_SUN_SALUTATION)
|
||||
app.sun_salutation = SalutationStart(app.sun_salutation)
|
||||
app.session_paused = 0
|
||||
|
||||
@@ -4,6 +4,7 @@ c :: #system_library "c";
|
||||
#import, file "../../app/app_types.zi";
|
||||
#import, file "../../app/exercise_types.zi";
|
||||
#import, file "../../app/manual_seen_actions.zi";
|
||||
#import, file "../../app/activity_start.zi";
|
||||
|
||||
using ExerciseType;
|
||||
|
||||
@@ -11,7 +12,7 @@ session_start :: (app: *InnerBreeze) #foreign c;
|
||||
|
||||
#program_export
|
||||
whm_practice_start :: (app: *InnerBreeze) {
|
||||
if app == null {
|
||||
if app == null || !ActivityStartAllowed() {
|
||||
return
|
||||
}
|
||||
mark_exercise_manual_seen(app, EXERCISE_WIM_HOF)
|
||||
|
||||
@@ -73,6 +73,7 @@ storage_has_sync_account :: () -> s32 #foreign c3;
|
||||
#import, file "../app/text_buffers.zi";
|
||||
#import, file "../practices/sun_salutation/sun_salutation_rules.zi";
|
||||
#import, file "../app/widgets.zi";
|
||||
#import, file "../app/account_activity_view.zi";
|
||||
|
||||
|
||||
using AppThemeMode;
|
||||
@@ -751,6 +752,9 @@ practice_screen_draw_home_hero :: (app: *InnerBreeze) -> s32 {
|
||||
}
|
||||
|
||||
practice_screen_draw_home :: (app: *InnerBreeze) {
|
||||
if ActivityDrawRemote(app) {
|
||||
return
|
||||
}
|
||||
start(app)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
#import "text_buffer"
|
||||
#import "byte_text_linux"
|
||||
#import "authorization"
|
||||
#import "wire"
|
||||
#import, file "storage_test_support.zi";
|
||||
#import, file "../src/app/account_activity.zi";
|
||||
#import, file "../src/app/account_activity_model.zi";
|
||||
#import, file "../src/app/activity_start.zi";
|
||||
#import, file "../src/app/app_types.zi";
|
||||
#import, file "../src/core/types.zi";
|
||||
#import, file "../src/storage/storage_core.zi";
|
||||
#import, file "../src/storage/cell_records.zi";
|
||||
#import, file "../src/storage/sync_account.zi";
|
||||
#import, file "../src/storage/account_types.zi";
|
||||
#import, file "../src/storage/data.zi";
|
||||
#import, file "../src/storage/state.zi";
|
||||
#import, file "../src/storage/db.zi";
|
||||
#import, file "../src/storage/storage_sessions.zi";
|
||||
#import, file "../src/storage/sql_query.zi";
|
||||
#import, file "../src/storage/delegate_store.zi";
|
||||
#import, file "../src/cells/package_files.zi";
|
||||
#import, file "../src/app/text_buffers.zi";
|
||||
|
||||
c :: #system_library "c";
|
||||
FixtureAdvance :: (seconds: s64) #foreign c;
|
||||
FixtureSchedules :: () -> s32 #foreign c;
|
||||
fixture_app: InnerBreeze;
|
||||
|
||||
WriteControl :: (activity: AccountActivity, id: string, revision: s64, now: s64) {
|
||||
document: [1024]u8
|
||||
writer := Writer.{document[:], 0, true}
|
||||
writer = WriteByte(writer, cast(u8)123)
|
||||
writer = JsonTextField(writer, "id", id)
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonTextField(writer, "session_id", TextUntilNul(activity.session_id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonTextField(writer, "device_id", TextUntilNul(activity.device_id[:]))
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonNumberField(writer, "time", now)
|
||||
writer = WriteByte(writer, cast(u8)44)
|
||||
writer = JsonNumberField(writer, "revision", revision)
|
||||
writer = WriteText(writer, ",\"paused\":1}")
|
||||
check_true("write control", writer.valid && CellRecordWrite(ActivityControlKey, TextUntilNul(document[:])))
|
||||
}
|
||||
|
||||
ReadStored :: () -> AccountActivity {
|
||||
value: AccountActivity
|
||||
document := CellRecordRead(ActivityRecordKey)
|
||||
check_true("read activity record", ActivityRead(document, *value))
|
||||
PackageFree(document)
|
||||
return value
|
||||
}
|
||||
|
||||
#program_export
|
||||
Check :: () -> s32 {
|
||||
guard := support_begin("/tmp/inbe-account-activity.")
|
||||
if guard != 0 {
|
||||
return guard
|
||||
}
|
||||
root := make_root("runner")
|
||||
check_true("open activity fixture", storage_init(root) != 0)
|
||||
account: SyncAccount
|
||||
check_true("generate owner", sync_account_generate(*account) != 0)
|
||||
check_true("save owner", sync_account_save(*account,
|
||||
SyncAccountLocalDataChoice.SYNC_ACCOUNT_LOCAL_DATA_ASK) == SyncAccountSaveResult.SYNC_ACCOUNT_SAVE_OK)
|
||||
storage_set_sync_enabled(1)
|
||||
fixture_app.breathing.screen = ScreenMeditation
|
||||
fixture_app.meditation.duration_seconds = 600
|
||||
fixture_app.meditation.remaining_seconds = 480
|
||||
ActivityPump(*fixture_app)
|
||||
first := ReadStored()
|
||||
check_true("meditation snapshot", first.active == 1 && first.duration == 600 &&
|
||||
first.remaining == 480 && first.elapsed == 120 && first.paused == 0)
|
||||
check_true("private activity queued", db_select_int64_text(
|
||||
"SELECT COUNT(*) FROM sync_outbox WHERE entity_type='cell_record' AND entity_id='cell.lumi.activity.current'", 0) == 1)
|
||||
check_true("sync scheduled", FixtureSchedules() > 0)
|
||||
check_true("own session is not remote", !ActivityRemoteVisible())
|
||||
check_true("fresh activity", ActivityFresh(first, ActivityCurrentTime()))
|
||||
check_true("stale activity is not fresh", !ActivityFresh(first, first.time + ActivityFreshSeconds + 1))
|
||||
check_true("future activity is not fresh", !ActivityFresh(first, first.time - 6))
|
||||
fixture_app.breathing.screen = ScreenSunSalutation
|
||||
fixture_app.sun_salutation.repetitions = 3
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
sun := ReadStored()
|
||||
check_true("direct practice switch gets a new session", sun.screen == ScreenSunSalutation &&
|
||||
TextUntilNul(sun.session_id[:]) != TextUntilNul(first.session_id[:]))
|
||||
fixture_app.sun_salutation.step = 1
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
step := ReadStored()
|
||||
check_true("phase boundary publishes before periodic heartbeat", step.phase == 1 && step.time == sun.time + 1)
|
||||
fixture_app.breathing.screen = ScreenMeditation
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
first = ReadStored()
|
||||
invalid: AccountActivity
|
||||
check_true("malformed record rejected", !ActivityRead("{\"active\":true}", *invalid))
|
||||
control_id := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
WriteControl(first, control_id, first.revision, first.time)
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
paused := ReadStored()
|
||||
check_true("remote pause applied to originating session", fixture_app.session_paused == 1 && paused.paused == 1 &&
|
||||
paused.revision == first.revision + 1 && TextUntilNul(paused.control_id[:]) == control_id)
|
||||
FixtureAdvance(3)
|
||||
ActivityPump(*fixture_app)
|
||||
repeated := ReadStored()
|
||||
check_true("control replay ignored", repeated.revision == paused.revision)
|
||||
fixture_app.session_paused = 0
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
resumed := ReadStored()
|
||||
WriteControl(resumed, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", paused.revision, resumed.time)
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
check_true("control for old state ignored", fixture_app.session_paused == 0)
|
||||
WriteControl(resumed, "cccccccccccccccccccccccccccccccc", resumed.revision,
|
||||
ActivityCurrentTime() - ActivityFreshSeconds - 1)
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
check_true("delayed offline control ignored", fixture_app.session_paused == 0)
|
||||
fixture_app.breathing.screen = ScreenStart
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
ended := ReadStored()
|
||||
check_true("completion clears active state", ended.active == 0 && TextUntilNul(ended.session_id[:]) == TextUntilNul(first.session_id[:]))
|
||||
check_int("observer never writes a practice result", storage_session_count(), 0)
|
||||
fixture_app.breathing.screen = ScreenPatterns
|
||||
fixture_app.patterns.elapsed_seconds = 91
|
||||
fixture_app.patterns.duration_minutes = 5
|
||||
fixture_app.patterns.phase = 2
|
||||
fixture_app.patterns.cycle = 7
|
||||
fixture_app.patterns.paused = 1
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
patterns := ReadStored()
|
||||
check_true("patterns snapshot retains phase, cycles and pause", patterns.phase == 2 && patterns.cycles == 7 &&
|
||||
patterns.elapsed == 91 && patterns.remaining == 209 && patterns.paused == 1)
|
||||
check_true("replacement session has a new identity", TextUntilNul(patterns.session_id[:]) != TextUntilNul(first.session_id[:]))
|
||||
WriteControl(first, "dddddddddddddddddddddddddddddddd", patterns.revision, ActivityCurrentTime())
|
||||
FixtureAdvance(1)
|
||||
fixture_app.patterns.paused = 0
|
||||
ActivityPump(*fixture_app)
|
||||
check_true("control cannot reach replacement practice", fixture_app.patterns.paused == 0)
|
||||
fixture_app.breathing.screen = ScreenStart
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
remote := first
|
||||
remote.time = ActivityCurrentTime()
|
||||
remote.device_id[0] = ifx remote.device_id[0] == cast(u8)97 then cast(u8)98 else cast(u8)97
|
||||
output: [2048]u8
|
||||
check_true("serialize remote record", ActivityWrite(remote, output[:]))
|
||||
check_true("receive remote record", CellRecordWrite(ActivityRecordKey, TextUntilNul(output[:])))
|
||||
FixtureAdvance(1)
|
||||
ActivityPump(*fixture_app)
|
||||
check_true("remote session visible", ActivityRemoteVisible() && !ActivityStartAllowed())
|
||||
check_true("remote request queued", ActivityRequestPause(*fixture_app, 1))
|
||||
check_true("duplicate pending control not sent", !ActivityRequestPause(*fixture_app, 1))
|
||||
FixtureAdvance(ActivityFreshSeconds + 1)
|
||||
ActivityPump(*fixture_app)
|
||||
check_true("stale remote session cannot receive control", !ActivityRequestPause(*fixture_app, 0))
|
||||
storage_set_sync_data_owner_public_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
|
||||
check_true("switch clears prior remote account", ActivityInitialize() && account_activity.remote.active == 0)
|
||||
storage_set_sync_enabled(0)
|
||||
check_true("disconnect removes activity access", !ActivityInitialize() && !ActivityRemoteVisible())
|
||||
storage_close()
|
||||
return failures
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Observe and control a synthetic account session on an owned Xvfb window."""
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
assert os.environ.get('INBE_ACTIVITY_PRIVATE_DISPLAY') == '1'
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUTPUT = ROOT / 'build/account-activity-ui-test'
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
ENV = os.environ | dict(APP_NO_TRAY='1', SDL_AUDIODRIVER='dummy',
|
||||
SDL_VIDEODRIVER='x11', YUE_DESKTOP_RECOVERY='0')
|
||||
for key in ('WAYLAND_DISPLAY', 'DBUS_SESSION_BUS_ADDRESS', 'SESSION_MANAGER'):
|
||||
ENV.pop(key, None)
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, env=ENV, text=True, timeout=10).strip()
|
||||
|
||||
|
||||
def wait_for(predicate, message):
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(.1)
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def state(window):
|
||||
value = command('xprop', '-id', window, '_HARMONY_APP_STATE')
|
||||
return json.loads(ast.literal_eval(value.split(' = ', 1)[1]))
|
||||
|
||||
|
||||
sequence = 0
|
||||
|
||||
|
||||
def action(window, control):
|
||||
global sequence
|
||||
sequence += 1
|
||||
request = 'activity-' + str(sequence)
|
||||
payload = dict(request_id=request, control=control, arguments={})
|
||||
command('xprop', '-id', window, '-f', '_HARMONY_APP_ACTION', '8s',
|
||||
'-set', '_HARMONY_APP_ACTION', json.dumps(payload))
|
||||
return wait_for(lambda: (value if (value := state(window))['last_request_id'] == request else None),
|
||||
'App did not acknowledge activity control')
|
||||
|
||||
|
||||
def capture(window, label):
|
||||
path = OUTPUT / (label + '.png')
|
||||
command('import', '-window', window, str(path))
|
||||
from PIL import Image
|
||||
enlarged = OUTPUT / 'ocr.png'
|
||||
with Image.open(path) as source:
|
||||
source.resize((source.width * 3, source.height * 3)).save(enlarged)
|
||||
return command('tesseract', str(enlarged), 'stdout', '--psm', '11').lower()
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='inbe-account-activity.') as temporary:
|
||||
profile = Path(temporary) / 'runner'
|
||||
subprocess.run([sys.argv[2]], env=ENV | dict(APP_DATA_ROOT=temporary),
|
||||
check=True, capture_output=True, timeout=20)
|
||||
database = sqlite3.connect(profile / 'inbe.db', timeout=5)
|
||||
user = database.execute('SELECT id FROM users LIMIT 1').fetchone()[0]
|
||||
|
||||
def setting(key, value):
|
||||
database.execute('INSERT INTO settings(user_id,key,value,updated_at) VALUES(?,?,?,?) '
|
||||
'ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value,updated_at=excluded.updated_at',
|
||||
(user, key, str(value), int(time.time())))
|
||||
|
||||
owner = database.execute("SELECT value FROM settings WHERE key='sync_public_id'").fetchone()[0]
|
||||
database.execute("UPDATE meta SET value=? WHERE key='sync_data_owner_public_id'", (owner,))
|
||||
for key, value in dict(sync_enabled=1, sync_server_url='', language='en', language_setup_done=1,
|
||||
enabled_apps=31, tutorial_seen=1, launcher_guide_seen=1,
|
||||
practice_guide_seen=1, habits_guide_seen=1).items():
|
||||
setting(key, value)
|
||||
remote = dict(version=1, session_id='a' * 32, device_id='b' * 64, control_id='',
|
||||
time=int(time.time()), revision=1, active=1, paused=0, screen=2,
|
||||
phase=0, round=0, count=0, elapsed=120, remaining=480,
|
||||
duration=600, cycles=0, total=0)
|
||||
|
||||
def publish(**changes):
|
||||
remote.update(changes)
|
||||
setting('cell.lumi.activity.current', json.dumps(remote, separators=(',', ':')))
|
||||
database.commit()
|
||||
|
||||
publish()
|
||||
with (OUTPUT / 'app.log').open('w') as log:
|
||||
app = subprocess.Popen([sys.argv[1], '--bundle', str(ROOT / 'build/inbe-full.zib')],
|
||||
cwd=ROOT, env=ENV | dict(APP_DATA_ROOT=str(profile)),
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
def find_window():
|
||||
assert app.poll() is None, 'Owned test app exited'
|
||||
result = subprocess.run(['xdotool', 'search', '--onlyvisible', '--pid', str(app.pid)],
|
||||
env=ENV, capture_output=True, text=True, timeout=5)
|
||||
return result.stdout.strip().splitlines()[0] if result.returncode == 0 else ''
|
||||
|
||||
window = wait_for(find_window, 'Owned test app window did not appear')
|
||||
command('xdotool', 'windowsize', window, '900', '720')
|
||||
command('xdotool', 'windowfocus', window)
|
||||
wait_for(lambda: ' = ' in command('xprop', '-id', window, '_HARMONY_APP_STATE'),
|
||||
'App state did not appear')
|
||||
wait_for(lambda: state(window).get('account_activity_fresh'), 'Remote session did not load')
|
||||
assert action(window, 'open.practices')['last_request_ok']
|
||||
time.sleep(.4)
|
||||
text = capture(window, 'running')
|
||||
assert 'meditation' in text and 'running on another device' in text, text
|
||||
report = state(window)
|
||||
assert not report['practice_running'], 'Observer started a duplicate practice'
|
||||
assert report['account_activity']['session_id'] == remote['session_id']
|
||||
assert not next(item for item in report['controls'] if item['control'] == 'practice.meditation.start')['enabled']
|
||||
assert action(window, 'practice.pause')['last_request_ok']
|
||||
row = database.execute("SELECT value FROM settings WHERE key='cell.lumi.activity.control'").fetchone()
|
||||
control = json.loads(row[0])
|
||||
assert control['session_id'] == remote['session_id'] and control['paused'] == 1
|
||||
publish(paused=1, revision=2, control_id=control['id'], time=int(time.time()))
|
||||
wait_for(lambda: state(window)['account_activity']['paused'] == 1, 'Pause acknowledgement did not load')
|
||||
assert 'paused on another device' in capture(window, 'paused')
|
||||
publish(time=int(time.time()) - 25)
|
||||
wait_for(lambda: not state(window)['account_activity_fresh'], 'Stale session remained fresh')
|
||||
report = state(window)
|
||||
assert not next(item for item in report['controls'] if item['control'] == 'practice.resume')['enabled']
|
||||
assert 'last known session' in capture(window, 'stale')
|
||||
command('xdotool', 'windowsize', window, '411', '813')
|
||||
time.sleep(.4)
|
||||
assert 'last known session' in capture(window, 'phone-stale')
|
||||
publish(active=0, revision=3, time=int(time.time()))
|
||||
wait_for(lambda: state(window)['account_activity'] is None, 'Completed session remained active')
|
||||
assert database.execute('SELECT COUNT(*) FROM sessions').fetchone()[0] == 0
|
||||
finally:
|
||||
app.terminate()
|
||||
try:
|
||||
app.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
app.kill()
|
||||
app.wait(timeout=5)
|
||||
database.close()
|
||||
|
||||
print('Account activity UI, host controls, acknowledgement, stale state and completion passed')
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
binary=${1:-"$root/build/bin/linux/inbe-linux-x86_64"}
|
||||
fixture=${2:-"$root/build/account-activity-test/test"}
|
||||
exec env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
|
||||
-u SESSION_MANAGER YUE_DESKTOP_RECOVERY=0 xvfb-run -a --server-num=300 -e /dev/stderr \
|
||||
-s '-screen 0 1280x1000x24' env INBE_ACTIVITY_PRIVATE_DISPLAY=1 \
|
||||
python3 "$root/tests/account_activity_ui_test.py" "$binary" "$fixture"
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
compiler=${1:-"$root/build/ziran-toolchain/bin/ziran"}
|
||||
liboqs=${2:-"$root/vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a"}
|
||||
work=$root/build/account-activity-test
|
||||
data=$(mktemp -d /tmp/inbe-account-activity.XXXXXX)
|
||||
trap 'rm -rf "$data"' EXIT HUP INT TERM
|
||||
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS
|
||||
export YUE_DESKTOP_RECOVERY=0
|
||||
mkdir -p "$work/generated"
|
||||
"$compiler" build --target=c --define PLATFORM_DESKTOP --root "$root/tests" \
|
||||
--module-path "$root/src" --module-path "$root/build/packages/kryon/src/ui" \
|
||||
--module-path "$root/build/packages/kryon/src/backend" \
|
||||
--module-path "kryon=$root/build/packages/kryon/src/ui" \
|
||||
--module-path "kryon=$root/build/packages/kryon/src/backend" \
|
||||
--module-path "$root/build/packages/kss/src" --module-path "oqs=$root/build/packages/oqs/src" \
|
||||
--module-path "$root/build/packages/game2d/src" --module-path "$root/build/packages/ziran/std" \
|
||||
--module-path "$root/build/packages/daochi-client" --entry account_activity_behavior:Check \
|
||||
-o "$work/generated" "$root/tests/account_activity_behavior.zi" "$root/tests/sync_test_host.zi"
|
||||
cat > "$work/generated/main.c" <<'C'
|
||||
#include "account_activity_behavior.h"
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
static int64_t fixture_now = 1791540000;
|
||||
static int schedules;
|
||||
time_t __wrap_time(time_t *output) {
|
||||
if (output) *output = fixture_now;
|
||||
return fixture_now;
|
||||
}
|
||||
double GetTime(void) { return (double)(fixture_now - 1791539990); }
|
||||
void FixtureAdvance(int64_t seconds) { fixture_now += seconds; }
|
||||
int32_t FixtureSchedules(void) { return schedules; }
|
||||
int32_t app_auto_sync(void *app) { (void)app; schedules++; return 1; }
|
||||
int main(void) {
|
||||
int result = Check();
|
||||
if (result) fprintf(stderr, "Account activity checks failed: %d\n", result);
|
||||
return result ? 1 : 0;
|
||||
}
|
||||
C
|
||||
monocypher=$root/build/packages/monocypher/src
|
||||
"${CC:-cc}" -std=c11 -O1 -ffunction-sections -fdata-sections \
|
||||
-I"$root/build/packages/ziran/include" -I"$work/generated" \
|
||||
-I"$root/vendor-builds/sqlite" -I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \
|
||||
-I"$monocypher" -I"$monocypher/optional" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" \
|
||||
"$monocypher/monocypher.c" "$monocypher/optional/monocypher-ed25519.c" "$liboqs" \
|
||||
-Wl,--gc-sections -Wl,--wrap=time -ldl -lpthread -lz -lm -o "$work/test"
|
||||
APP_DATA_ROOT="$data" "$work/test"
|
||||
printf '%s\n' 'Account activity, private outbox, controls, freshness and account switching passed'
|
||||
@@ -8,6 +8,7 @@
|
||||
static pthread_mutex_t callback_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t callback_ready = PTHREAD_COND_INITIALIZER;
|
||||
static int callback_count;
|
||||
static int sync_count;
|
||||
static int self_stop_at;
|
||||
static int self_stop_returned;
|
||||
static int app_value;
|
||||
@@ -15,6 +16,16 @@ static int app_value;
|
||||
int32_t TimerElapsedMillis(int64_t previous_nanoseconds,
|
||||
int64_t now_nanoseconds);
|
||||
|
||||
void
|
||||
app_activity_background_sync(void *app)
|
||||
{
|
||||
assert(app == &app_value);
|
||||
pthread_mutex_lock(&callback_mutex);
|
||||
sync_count++;
|
||||
assert(sync_count <= callback_count);
|
||||
pthread_mutex_unlock(&callback_mutex);
|
||||
}
|
||||
|
||||
void
|
||||
practice_active_advance_elapsed(void *app, int32_t elapsed_ms)
|
||||
{
|
||||
@@ -104,5 +115,6 @@ main(void)
|
||||
android_timer_activate();
|
||||
wait_for_callbacks(self_stop_at + 1);
|
||||
android_timer_stop();
|
||||
assert(sync_count == callback_count);
|
||||
return 0;
|
||||
}
|
||||
@@ -25,18 +25,20 @@ Answer :: () -> s32 {
|
||||
state.friend_input_focused = 0
|
||||
|
||||
state.screen = ScreenPracticeSession
|
||||
if BackgroundSyncSafe(state) { return 8 }
|
||||
if !BackgroundSyncSafe(state) || SyncUiRefreshSafe(state, 3.0, 1.0, false) { return 8 }
|
||||
state.screen = ScreenMeditation
|
||||
if BackgroundSyncSafe(state) { return 9 }
|
||||
if !BackgroundSyncSafe(state) || SyncUiRefreshSafe(state, 3.0, 1.0, false) { return 9 }
|
||||
state.screen = ScreenSunSalutation
|
||||
if BackgroundSyncSafe(state) { return 10 }
|
||||
if !BackgroundSyncSafe(state) || SyncUiRefreshSafe(state, 3.0, 1.0, false) { return 10 }
|
||||
state.screen = ScreenPatterns
|
||||
if !BackgroundSyncSafe(state) || SyncUiRefreshSafe(state, 3.0, 1.0, false) { return 14 }
|
||||
state.screen = ScreenHabits
|
||||
|
||||
if SyncUserIdle(2.49, 1.0, false) ||
|
||||
!SyncUserIdle(2.50, 1.0, false) ||
|
||||
SyncUserIdle(3.0, 1.0, true) { return 11 }
|
||||
!SyncUserIdle(2.50, 1.0, false) ||
|
||||
SyncUserIdle(3.0, 1.0, true) { return 11 }
|
||||
if !SyncUiRefreshSafe(state, 2.50, 1.0, false) ||
|
||||
SyncUiRefreshSafe(state, 2.50, 1.0, true) { return 12 }
|
||||
SyncUiRefreshSafe(state, 2.50, 1.0, true) { return 12 }
|
||||
state.screen = ScreenStart
|
||||
if SyncUiRefreshSafe(state, 3.0, 1.0, false) { return 13 }
|
||||
return 42
|
||||
|
||||
@@ -20,6 +20,13 @@
|
||||
#import, file "../src/habits/habit_memory.zi";
|
||||
#import, file "../src/storage/storage_habits.zi";
|
||||
#import, file "../src/habits/habit_model.zi";
|
||||
#import, file "../src/app/account_activity_model.zi";
|
||||
#import, file "../src/storage/cell_records.zi";
|
||||
#import "text_buffer"
|
||||
#import "wire"
|
||||
#import "authorization"
|
||||
#import, file "../src/core/types.zi";
|
||||
#import, file "../src/cells/package_files.zi";
|
||||
|
||||
// Two clients, a friend, and fresh installs syncing through a real Daochi
|
||||
// server (with a proxy that drops one response), from the first upload to
|
||||
@@ -236,6 +243,71 @@ Check :: () -> s32 {
|
||||
check_int("session reaches the second device", storage_session_count(), 1)
|
||||
expect_habit(AlbumHabitId(), habit_name, 20260919)
|
||||
expect_list(list_text, item_text, "Travel", "Passport", 0)
|
||||
// Private live activity uses the same authenticated, encrypted account
|
||||
// transport as Lumi history, without creating another completed result.
|
||||
open_client(a)
|
||||
live: AccountActivity
|
||||
unused AppCopyText("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", live.session_id[:])
|
||||
unused AppCopyText("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", live.device_id[:])
|
||||
live.active = 1
|
||||
live.screen = ScreenMeditation
|
||||
live.time = CellRecordClock() / 1000000
|
||||
live.revision = 1
|
||||
live.duration = 600
|
||||
live.remaining = 480
|
||||
live.elapsed = 120
|
||||
live_payload: [2048]u8
|
||||
check_true("serialize running activity", ActivityWrite(live, live_payload[:]))
|
||||
check_true("queue private running activity", CellRecordWrite(ActivityRecordKey, TextUntilNul(live_payload[:])))
|
||||
synchronize(url)
|
||||
open_client(b)
|
||||
synchronize(url)
|
||||
observed: AccountActivity
|
||||
live_document := CellRecordRead(ActivityRecordKey)
|
||||
check_true("same running activity reaches another device", ActivityRead(live_document, *observed) &&
|
||||
observed.remaining == 480 && observed.active == 1 &&
|
||||
TextUntilNul(observed.session_id[:]) == TextUntilNul(live.session_id[:]))
|
||||
PackageFree(live_document)
|
||||
command: [1024]u8
|
||||
writer := Writer.{command[:], 0, true}
|
||||
writer = WriteText(writer, "{\"id\":\"cccccccccccccccccccccccccccccccc\",\"session_id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"device_id\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"paused\":1,\"revision\":1,")
|
||||
writer = JsonNumberField(writer, "time", CellRecordClock() / 1000000)
|
||||
writer = WriteByte(writer, cast(u8)125)
|
||||
check_true("queue private pause request", writer.valid && CellRecordWrite(ActivityControlKey, TextUntilNul(command[:])))
|
||||
synchronize(url)
|
||||
open_client(a)
|
||||
synchronize(url)
|
||||
requested: ActivityControl
|
||||
command_document := CellRecordRead(ActivityControlKey)
|
||||
live.time = CellRecordClock() / 1000000
|
||||
check_true("pause request reaches originating session", ActivityControlRead(command_document, *requested) &&
|
||||
ActivityControlMatches(requested, live, live.time))
|
||||
PackageFree(command_document)
|
||||
live.paused = 1
|
||||
live.revision = 2
|
||||
live.control_id = requested.id
|
||||
check_true("serialize acknowledged pause", ActivityWrite(live, live_payload[:]))
|
||||
check_true("queue acknowledged pause", CellRecordWrite(ActivityRecordKey, TextUntilNul(live_payload[:])))
|
||||
synchronize(url)
|
||||
open_client(b)
|
||||
synchronize(url)
|
||||
live_document = CellRecordRead(ActivityRecordKey)
|
||||
check_true("pause acknowledgement returns to observer", ActivityRead(live_document, *observed) &&
|
||||
observed.paused == 1 && TextUntilNul(observed.control_id[:]) == TextUntilNul(requested.id[:]))
|
||||
PackageFree(live_document)
|
||||
open_client(a)
|
||||
live.active = 0
|
||||
live.revision = 3
|
||||
live.time = CellRecordClock() / 1000000
|
||||
check_true("serialize completed activity", ActivityWrite(live, live_payload[:]))
|
||||
check_true("queue completed activity", CellRecordWrite(ActivityRecordKey, TextUntilNul(live_payload[:])))
|
||||
synchronize(url)
|
||||
open_client(b)
|
||||
synchronize(url)
|
||||
live_document = CellRecordRead(ActivityRecordKey)
|
||||
check_true("completion reaches other device", ActivityRead(live_document, *observed) && observed.active == 0)
|
||||
PackageFree(live_document)
|
||||
check_int("live activity does not duplicate results", storage_session_count(), 1)
|
||||
check_true("complete the item", storage_elist_update_item(item_text, "Pack bag", "Passport", 1, 0) != 0)
|
||||
synchronize(url)
|
||||
open_client(a)
|
||||
|
||||
@@ -7,7 +7,7 @@ set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
ziran=${1:-"$root/build/ziran-toolchain/bin/ziran"}
|
||||
liboqs=${2:-"$root/vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a"}
|
||||
work=$root/build/sync-server-zi-test
|
||||
work=${SYNC_SERVER_TEST_WORK:-$root/build/sync-server-zi-test}
|
||||
include=$root/build/packages/ziran/include
|
||||
# The system library, linked by name where there is no development symlink.
|
||||
curl=${CURL_LIBRARY:-$(ls /usr/lib/x86_64-linux-gnu/libcurl.so.4 2>/dev/null || echo -lcurl)}
|
||||
|
||||
@@ -53,6 +53,8 @@ fixture_grant: GrantStorage;
|
||||
fixture_claimed: bool;
|
||||
fixture_approved: bool;
|
||||
fixture_revoked: bool;
|
||||
fixture_sync_unavailable: bool;
|
||||
fixture_bootstrap_failure: s32;
|
||||
fixture_bound: bool;
|
||||
fixture_wrong_owner: bool;
|
||||
fixture_bad_node: bool;
|
||||
@@ -239,6 +241,10 @@ Reply :: (request: HttpRequest, output: []u8, status: *s32) -> bool {
|
||||
flow := *telegram_account_flow
|
||||
path := request.url[TelegramFlowServer.count:]
|
||||
status.* = 200
|
||||
if fixture_bootstrap_failure != 0 && path == "/api/v1/telegram/environment" {
|
||||
status.* = fixture_bootstrap_failure
|
||||
return ifx fixture_bootstrap_failure == 1 then false else AppCopyText("{}", output)
|
||||
}
|
||||
if path == "/api/v1/telegram/environment" {
|
||||
writer := Writer.{output, 0, true}
|
||||
writer = WriteText(writer, "{\"app_id\":\"inbe\",\"node_id\":")
|
||||
@@ -325,6 +331,10 @@ Reply :: (request: HttpRequest, output: []u8, status: *s32) -> bool {
|
||||
status.* = 403
|
||||
return AppCopyText("{}", output)
|
||||
}
|
||||
if fixture_sync_unavailable {
|
||||
status.* = 503
|
||||
return AppCopyText("{}", output)
|
||||
}
|
||||
return AppCopyText("{\"collection\":\"private.inbe.v2.lumi\",\"records\":[],\"next_version\":0,\"truncated\":false,\"applied\":0}", output)
|
||||
}
|
||||
if path == "/api/v1/authorization/challenge" {
|
||||
@@ -382,6 +392,8 @@ StartFixture :: (name: string, mode: string) -> bool {
|
||||
fixture_claimed = false
|
||||
fixture_approved = false
|
||||
fixture_revoked = false
|
||||
fixture_sync_unavailable = false
|
||||
fixture_bootstrap_failure = 0
|
||||
fixture_bound = false
|
||||
fixture_wrong_owner = false
|
||||
fixture_bad_node = false
|
||||
@@ -659,16 +671,49 @@ CheckProtectedRestart :: () {
|
||||
fixture_request_expiry = FlowTime(null) + 600
|
||||
fixture_grant = saved_grant
|
||||
flow_host_capsule = saved_capsule
|
||||
Expect("protected installation offered after verified identity", PumpUntil(4) &&
|
||||
TelegramAccountActionAllowed(*telegram_account_flow.view, 2))
|
||||
HandleTelegramAccountAction(null, 2)
|
||||
Expect("protected installation requires fresh key-bound session", PumpUntil(14) &&
|
||||
Expect("protected restart automatically obtains fresh key-bound session", PumpUntil(14) &&
|
||||
StoredDelegateAvailable() == 1 && fixture_challenge_calls == 1)
|
||||
TelegramAccountFlowPump(null)
|
||||
TelegramAccountFlowPump(null)
|
||||
Expect("protected restart keeps scoped delegate through cleanup", telegram_account_flow.phase == 14 &&
|
||||
StoredDelegateAvailable() == 1 && !fixture_bound && !fixture_claimed && !fixture_approved)
|
||||
Expect("protected restart preserves data/outbox", HistoryCount() == 2 && OutboxCount() == outbox)
|
||||
fixture_sync_unavailable = true
|
||||
FlowAdvanceClock(6)
|
||||
for attempt: cast(s32)0..15 {
|
||||
TelegramAccountFlowPump(null)
|
||||
}
|
||||
Expect("temporary sync outage retains account and protected access", telegram_account_flow.phase == 14 &&
|
||||
StoredDelegateAvailable() == 1 && flow_host_capsule[0] != cast(u8)0)
|
||||
fixture_sync_unavailable = false
|
||||
FlowAdvanceClock(6)
|
||||
for attempt: cast(s32)0..15 {
|
||||
TelegramAccountFlowPump(null)
|
||||
}
|
||||
Expect("account resumes sync after outage", telegram_account_flow.phase == 14 && StoredDelegateAvailable() == 1)
|
||||
for failure: cast(s32)0..1 {
|
||||
Expect("offline reopening fixture opens", StartFixture("connect", "restore"))
|
||||
FlowSetClock(saved_time + 2)
|
||||
fixture_request_expiry = FlowTime(null) + 600
|
||||
fixture_grant = saved_grant
|
||||
flow_host_capsule = saved_capsule
|
||||
fixture_bootstrap_failure = ifx failure == 0 then 1 else 503
|
||||
Expect("offline reopening denies unverified access", PumpUntil(90) && StoredDelegateAvailable() == 0)
|
||||
TelegramAccountFlowPump(null)
|
||||
Expect("offline reopening keeps protected account for next launch",
|
||||
TextUntilNul(flow_host_capsule[:]) == TextUntilNul(saved_capsule[:]))
|
||||
Expect("offline reopening does not retain plaintext credentials", telegram_account_flow.capsule[0] == cast(u8)0 &&
|
||||
telegram_account_flow.owner.private_key_hex[0] == cast(u8)0)
|
||||
HandleTelegramAccountAction(null, 4)
|
||||
Expect("dismissing connection error preserves saved access", telegram_account_flow.phase == 91 &&
|
||||
TextUntilNul(flow_host_capsule[:]) == TextUntilNul(saved_capsule[:]))
|
||||
}
|
||||
Expect("online reopening after offline failure opens", StartFixture("connect", "restore"))
|
||||
FlowSetClock(saved_time + 3)
|
||||
fixture_request_expiry = FlowTime(null) + 600
|
||||
fixture_grant = saved_grant
|
||||
flow_host_capsule = saved_capsule
|
||||
Expect("online reopening after outage restores same account", PumpUntil(14) && StoredDelegateAvailable() == 1)
|
||||
SyncCryptoWipe(*saved_capsule[0], 65537)
|
||||
}
|
||||
|
||||
@@ -701,8 +746,7 @@ CheckDifferentTelegramUser :: () {
|
||||
flow_host_raw = "auth_date=1700000000&user=%7B%22id%22%3A8%7D&hash=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
fixture_grant = saved_grant
|
||||
flow_host_capsule = saved_capsule
|
||||
Expect("second user verified independently", PumpUntil(4))
|
||||
HandleTelegramAccountAction(null, 2)
|
||||
Expect("second user verified and mismatched saved grant rejected", PumpUntil(90))
|
||||
Expect("different Telegram user capsule rejected before session", telegram_account_flow.phase == 90 &&
|
||||
StoredDelegateAvailable() == 0 && fixture_challenge_calls == 0)
|
||||
TelegramAccountFlowPump(null)
|
||||
|
||||
Reference in new issue
Block a user