Complete Android bootstrap failure contracts, platform TLS and warm CI caches
android-ci / android-arm64 (push) Successful in 38m53s
android-ci / android-arm64 (push) Successful in 38m53s
This commit is contained in:
1 parent
3cc9565fab
commit
5799fcb0d1
21 files changed
+611
-85
No files matched your search
@@ -16,6 +16,7 @@ import pathlib
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
import tomllib
|
||||
|
||||
ROOT = pathlib.Path.cwd().resolve()
|
||||
STATE = ROOT / '.android-ci'
|
||||
@@ -33,26 +34,52 @@ def tracked_paths():
|
||||
['git', 'ls-files', '-z']).split(b'\0') if name]
|
||||
|
||||
|
||||
def identity():
|
||||
names = {name for name in tracked_paths() if pathlib.PurePosixPath(name).name == 'Cargo.toml'}
|
||||
names.update(('Cargo.lock', 'rust-toolchain.toml', '.cargo/config.toml',
|
||||
'.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh',
|
||||
'.gitea/build-android-variant.sh', '.gitea/android-rustc-low-memory.sh',
|
||||
'.gitea/android-application-cache.py', 'xtask/src/build_native.rs',
|
||||
'xtask/src/deps.rs', '.gitea/prepare-android-dependency-cache.py'))
|
||||
policy = json.loads((ROOT / 'native/native-deps.lock.json').read_text())
|
||||
policy.pop('builds', None)
|
||||
inputs = {name: digest(ROOT / name) for name in sorted(names)}
|
||||
inputs['dependency-policy'] = policy
|
||||
inputs['target'] = os.environ['TARGET']
|
||||
inputs['low-memory'] = os.environ['TEAMSPEACH_ANDROID_LOW_MEMORY']
|
||||
inputs['profile'] = 'release'
|
||||
inputs['variant'] = 'harness'
|
||||
for name in ('RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER'):
|
||||
inputs[name] = os.environ.get(name, '')
|
||||
def compatibility():
|
||||
# Content changes belong to Cargo's fingerprints and the input snapshot, not
|
||||
# the restore prefix. Only configuration that changes the build contract is
|
||||
# a compatibility boundary. In particular, dependency versions/features and
|
||||
# source/dependency drivers are deliberately absent here.
|
||||
target_dir = pathlib.Path(os.environ['CARGO_TARGET_DIR']).resolve()
|
||||
if target_dir != STATE / 'cargo-target':
|
||||
raise ValueError('Application cache requires the isolated .android-ci/cargo-target')
|
||||
names = {'.gitea/android-ci-tools.json', 'rust-toolchain.toml',
|
||||
'.gitea/setup-android-ci.sh', '.gitea/build-android-variant.sh',
|
||||
'.gitea/android-rustc-low-memory.sh',
|
||||
'platform/android/gradle/wrapper/gradle-wrapper.properties'}
|
||||
profiles = {}
|
||||
for name in tracked_paths():
|
||||
path = pathlib.PurePosixPath(name)
|
||||
if path.name in ('config', 'config.toml') and path.parent.name == '.cargo':
|
||||
names.add(name)
|
||||
if path.name == 'Cargo.toml':
|
||||
profile = tomllib.loads((ROOT / name).read_text()).get('profile')
|
||||
if profile:
|
||||
profiles[name] = profile
|
||||
environment = {
|
||||
name: os.environ.get(name, '') for name in (
|
||||
'TARGET', 'TEAMSPEACH_ANDROID_LOW_MEMORY', 'CARGO_TARGET_DIR',
|
||||
'RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'RUSTC_WRAPPER',
|
||||
'RUSTC_WORKSPACE_WRAPPER', 'RUSTUP_TOOLCHAIN', 'CARGO_HOME',
|
||||
'RUSTUP_HOME', 'HOME', 'LLVM_HOME', 'LIBCLANG_PATH',
|
||||
'ANDROID_SDK_ROOT', 'ANDROID_NDK_ROOT', 'ANDROID_API_LEVEL',
|
||||
'SKIA_SOURCE_DIR', 'SKIA_GN_COMMAND', 'SKIA_NINJA_COMMAND',
|
||||
'SKIA_FORCE_BUILD', 'CMAKE_BUILD_PARALLEL_LEVEL')}
|
||||
environment.update({name: value for name, value in os.environ.items()
|
||||
if name.startswith(('CARGO_PROFILE_', 'CARGO_TARGET_'))})
|
||||
return {
|
||||
'files': {name: digest(ROOT / name) for name in sorted(names)},
|
||||
'profiles': profiles, 'environment': environment,
|
||||
'rustc': subprocess.check_output(['rustc', '-vV'], text=True),
|
||||
'cargo': subprocess.check_output(['cargo', '-V'], text=True),
|
||||
'profile': 'release', 'variant': 'harness',
|
||||
}
|
||||
|
||||
|
||||
def identity(inputs):
|
||||
fingerprint = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
|
||||
mode = 'low-memory' if inputs['low-memory'] == 'true' else 'normal'
|
||||
return f"android-application-linux-x64-{inputs['target']}-release-{mode}-harness-v1-{fingerprint}"
|
||||
environment = inputs['environment']
|
||||
mode = 'low-memory' if environment['TEAMSPEACH_ANDROID_LOW_MEMORY'] == 'true' else 'normal'
|
||||
return f"android-application-linux-x64-{environment['TARGET']}-release-{mode}-harness-v2-{fingerprint}"
|
||||
|
||||
|
||||
def record(path):
|
||||
@@ -81,21 +108,48 @@ def collect(names):
|
||||
return result
|
||||
|
||||
|
||||
def load():
|
||||
if not RECEIPT.exists():
|
||||
def load(contract, path=RECEIPT):
|
||||
if path == RECEIPT and not path.exists():
|
||||
return {'inputs': {}, 'completed_ns': 0}
|
||||
data = json.loads(RECEIPT.read_text())
|
||||
if data['schema'] != 1 or data['identity'] != identity() or data['workspace'] != str(ROOT):
|
||||
raise ValueError('Application cache input identity/workspace mismatch')
|
||||
data = json.loads(path.read_text())
|
||||
if (data['schema'] != 2 or data['compatibility'] != contract
|
||||
or data['identity'] != identity(contract) or data['workspace'] != str(ROOT)):
|
||||
# v1's opaque content identity cannot prove configuration compatibility
|
||||
# after a manifest change. Start a new cache generation, never guess.
|
||||
raise ValueError('Application cache compatibility/workspace mismatch (requires v2 receipt)')
|
||||
return data
|
||||
|
||||
|
||||
def save(path, inputs):
|
||||
def cargo_timestamps():
|
||||
# These are Cargo's real host/target build-start stamps, not target/ at the
|
||||
# repository root (which contains the separately verified WebRTC tree).
|
||||
target = STATE / 'cargo-target'
|
||||
paths = [*target.glob('*/.fingerprint/*/invoked.timestamp'),
|
||||
*target.glob('*/*/.fingerprint/*/invoked.timestamp')]
|
||||
return {str(path.relative_to(ROOT)): path.stat().st_mtime_ns for path in paths}
|
||||
|
||||
|
||||
def report_cargo_timestamps(previous):
|
||||
current = cargo_timestamps()
|
||||
recorded = previous.get('cargo_timestamps', {})
|
||||
changed = sum(current.get(name) != stamp for name, stamp in recorded.items())
|
||||
print(f'Cargo target: {STATE / "cargo-target"}; restored build-start stamps: '
|
||||
f'{len(current)}; missing/retimed since snapshot: {changed}; '
|
||||
f'cached completion ns: {previous["completed_ns"]}', flush=True)
|
||||
if changed:
|
||||
print('Cargo output timestamps changed during cache transport; Cargo may rebuild. '
|
||||
'Build output timestamps are never rewritten.', flush=True)
|
||||
|
||||
|
||||
def save(path, inputs, contract):
|
||||
STATE.mkdir(exist_ok=True)
|
||||
temporary = path.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps({'schema': 1, 'identity': identity(),
|
||||
stamps = cargo_timestamps() if path == RECEIPT else {}
|
||||
temporary.write_text(json.dumps({'schema': 2, 'identity': identity(contract),
|
||||
'compatibility': contract,
|
||||
'workspace': str(ROOT), 'inputs': inputs,
|
||||
'completed_ns': time.time_ns()}, sort_keys=True))
|
||||
'completed_ns': time.time_ns(),
|
||||
'cargo_timestamps': stamps}, sort_keys=True))
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
@@ -122,12 +176,14 @@ def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('key', 'sources', 'dependencies', 'snapshot'))
|
||||
action = parser.parse_args().action
|
||||
contract = compatibility()
|
||||
if action == 'key':
|
||||
with open(os.environ['GITHUB_OUTPUT'], 'a') as out:
|
||||
out.write(f'key={identity()}\n')
|
||||
out.write(f'key={identity(contract)}\n')
|
||||
return
|
||||
previous = load()
|
||||
previous = load(contract)
|
||||
if action == 'sources':
|
||||
report_cargo_timestamps(previous)
|
||||
names = set(tracked_paths())
|
||||
# Cargo's directory rerun rules also inspect directory mtimes. Preserve
|
||||
# those only if their exact child-name inventory and mode still match.
|
||||
@@ -135,23 +191,23 @@ def main():
|
||||
names.update(str(parent) for parent in pathlib.Path(name).parents if parent != pathlib.Path('.'))
|
||||
current = collect(names)
|
||||
restore(current, previous)
|
||||
save(PENDING, current)
|
||||
save(PENDING, current, contract)
|
||||
elif action == 'dependencies':
|
||||
base = pathlib.Path('target/native-deps') / os.environ['TARGET'] / 'webrtc'
|
||||
if not base.is_dir():
|
||||
raise ValueError('Verified WebRTC artifact tree is missing')
|
||||
current = collect([str(base), *(str(path) for path in base.rglob('*'))])
|
||||
restore(current, previous)
|
||||
pending = json.loads(PENDING.read_text())['inputs']
|
||||
pending = load(contract, PENDING)['inputs']
|
||||
pending.update(current)
|
||||
save(PENDING, pending)
|
||||
save(PENDING, pending, contract)
|
||||
else:
|
||||
pending = json.loads(PENDING.read_text())['inputs']
|
||||
pending = load(contract, PENDING)['inputs']
|
||||
current = collect(pending)
|
||||
# Only retain inputs whose bytes/mode/mtime stayed stable throughout the
|
||||
# build. A generated or concurrently edited file is never backdated.
|
||||
stable = {name: item for name, item in current.items() if item == pending[name]}
|
||||
save(RECEIPT, stable)
|
||||
save(RECEIPT, stable, contract)
|
||||
print(f'Recorded {len(stable)} stable application/dependency inputs', flush=True)
|
||||
|
||||
|
||||
|
||||
@@ -93,10 +93,20 @@ jobs:
|
||||
.android-ci/tools/android-sdk
|
||||
.android-ci/tools/skia-m153-0.101.2
|
||||
.android-ci/tools/gradle
|
||||
key: android-tools-linux-x64-arm64-v2-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'Cargo.lock', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ github.sha }}
|
||||
# Lock changes may need new registry sources, not a new SDK/toolchain.
|
||||
# v3 starts one cold generation: v2 has no independently verifiable tool contract.
|
||||
key: android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('Cargo.lock') }}-${{ github.sha }}-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
android-tools-linux-x64-arm64-v2-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'Cargo.lock', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-
|
||||
android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('Cargo.lock') }}-
|
||||
android-tools-linux-x64-arm64-v3-${{ hashFiles('.gitea/android-ci-tools.json', '.gitea/setup-android-ci.sh', 'rust-toolchain.toml', 'platform/android/gradle/wrapper/gradle-wrapper.properties') }}-
|
||||
- name: Provision pinned Android tools in the job container
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: tools
|
||||
run: bash .gitea/setup-android-ci.sh
|
||||
|
||||
|
||||
# Setup publishes the pinned environment before compatibility is computed.
|
||||
# Never cross the opaque v1 application identity: one cold v2 generation.
|
||||
- name: Compute isolated application cache identity
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: application-key
|
||||
@@ -119,11 +129,6 @@ jobs:
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
run: python3 .gitea/android-application-cache.py sources
|
||||
|
||||
- name: Provision pinned Android tools in the job container
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
id: tools
|
||||
run: bash .gitea/setup-android-ci.sh
|
||||
|
||||
- name: Require exact revision and no production signing
|
||||
if: ${{ github.event.inputs.mode != 'inventory' }}
|
||||
run: |
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Bootstrap creation/recovery now shares validation and worker-owned persistence, preserves committed
|
||||
identities on retry, acknowledges service initialization failures and publishes revisioned terminal
|
||||
errors. UI queue rejection and background snapshots no longer strand or reset pending form state.
|
||||
- Android profile creation now traverses search-only sandbox ancestors without reading them and uses
|
||||
real descriptor-owned flock locks on Rust1.96; unsupported I/O is no longer reported as contention.
|
||||
- Android TLS initializes the pinned platform verifier with the process Application/classloader before
|
||||
networking; packages its matching JVM helper/Kotlin runtime and verifies helper definitions in DEX.
|
||||
- Android insets follow the NativeActivity window rather than a nonexistent SurfaceView; IME updates
|
||||
are sampled after layout commits. Import backup remains in Identities settings, not first-run onboarding.
|
||||
- Android CI separates cached toolchain/profile compatibility from Cargo dependency/source changes,
|
||||
retains content-verified input timestamps and saves completed Cargo artifacts before uploads.
|
||||
- Android CI now runs on trusted feature/mobile-port pushes using an isolated Ubuntu24.04 container.
|
||||
Added checksum-pinned SDK/NDK/Rust/Skia/Gradle provisioning, early disk/RAM gates, four-job CI compilation,
|
||||
dependency checkpoints before native build, memory evidence and SHA-labelled test APK artifacts;
|
||||
|
||||
Generated
+2
@@ -7529,6 +7529,7 @@ dependencies = [
|
||||
"image",
|
||||
"indexmap",
|
||||
"jni 0.21.1",
|
||||
"jni 0.22.4",
|
||||
"katex-native",
|
||||
"katex-rs",
|
||||
"ksni",
|
||||
@@ -7542,6 +7543,7 @@ dependencies = [
|
||||
"ringbuf",
|
||||
"roxmltree 0.21.2",
|
||||
"rubato",
|
||||
"rustls-platform-verifier",
|
||||
"same-file",
|
||||
"secret-service",
|
||||
"security-framework",
|
||||
|
||||
@@ -120,10 +120,22 @@ fallback be enabled: `TEAMSPEACH_ANDROID_LOW_MEMORY=true` selects codegen-units2
|
||||
`teamspeach_native/aarch64-linux-android` through `.gitea/android-rustc-low-memory.sh`. All features stay
|
||||
enabled and `build-info.json` records the variant. Other targets and Windows settings remain unchanged.
|
||||
|
||||
Tools/downloads/SDK/Skia/Gradle/Cargo caches live under ignored `.android-ci/`; Actions cache v3 keys
|
||||
include tool pins, Cargo.lock and source SHA, restoring only within the same tool/dependency prefix.
|
||||
Tool/Cargo state is checkpointed after successful dependency provisioning, before compiling the app;
|
||||
the final successful job saves a newer checkpoint. Private signing keys and profiles are excluded.
|
||||
Tools/downloads/SDK/Skia/Gradle/Cargo caches live under ignored `.android-ci/`. Tools-v3 keys
|
||||
separate pinned tool/setup compatibility from Cargo.lock and source SHA: a changed lock first looks
|
||||
for matching registry sources, then falls back within the same tool contract. Provisioning still
|
||||
verifies the pinned tools and resolves any newly required sources. Tool/Cargo state is checkpointed
|
||||
after successful dependency provisioning, before compiling the app; the final successful job saves
|
||||
a newer checkpoint. Private signing keys and profiles are excluded.
|
||||
A separate application-v2 cache keeps the actual `.android-ci/cargo-target` and a content snapshot.
|
||||
Its compatibility identity is computed **after setup** from toolchain, target, optimization profiles,
|
||||
Cargo config and the stable build environment, not Cargo.lock, dependency declarations or source
|
||||
contents. Cargo fingerprints invalidate changed inputs. Only path/SHA-256/type/mode-matched inputs
|
||||
regain their recorded mtimes; changed inputs are never backdated and fail closed if their timestamp
|
||||
predates the cached compilation. Verified WebRTC inputs are considered only after the mandatory
|
||||
`xtask deps` run. Cargo build-start timestamps are recorded/reported, never rewritten. Every hit
|
||||
still runs revision checks, dependency provenance regeneration and full build/package verification.
|
||||
The old tools-v2/application-v1 opaque hashes cannot prove this independent compatibility contract,
|
||||
so this migration needs one cold cache generation; there is no unverified legacy fallback.
|
||||
A separate exact-key cache keeps `target/native-deps/aarch64-linux-android`, including pinned Git
|
||||
checkouts and Ninja objects. Its key excludes completed build receipts but includes source policy,
|
||||
tool pins and dependency drivers; there is no cross-policy fallback. Every cache hit still runs
|
||||
|
||||
@@ -507,3 +507,29 @@ other targets; all std file-lock callsites in core/native services migrate throu
|
||||
fs2 locking remains compatible. Windows real contention/shared-reader/drop-release regression passed;
|
||||
Android runtime proof remains pending. This is platform compatibility, not a phone-specific exception.
|
||||
|
||||
### Onboarding failure contracts and actual run4867 result
|
||||
|
||||
Current device proof: creation reached main shell and persisted across a force-stop/cold start. This
|
||||
establishes the local identity path, not voice/network or all lifecycle variants. Prior PermissionDenied
|
||||
and Unsupported lock failures were distinct platform integration defects, not evidence of slow key search.
|
||||
|
||||
Remaining source-confirmed failure paths:
|
||||
- [runtime worker](../native/src/app/runtime/mod.rs): terminal Err changes snapshot data without bumping
|
||||
revision; [UI update](../native/src/ui/application.rs) gates presentation on revision. Construct uses `?`
|
||||
before captured FormComplete, so post-persistence service errors can leave onboarding pending.
|
||||
- [shell submission/editor](../native/src/ui/shell.rs): busy precedes dispatch; pre-profile enqueue errors
|
||||
have no form acknowledgement; background merge overwrites busy/error. Retained edits alone are not a
|
||||
complete operation-state contract.
|
||||
- Initialized-empty-profile branch bypasses Bootstrap.handle's theme validation/persistence and blocking
|
||||
worker, doing synchronous onboard on the current-thread actor. This can stall lifecycle event handling.
|
||||
- [Android initialization](../native/src/platform/android.rs) and Gradle omit rustls-platform-verifier JVM
|
||||
setup/helper. Actual logcat panic repeats on create and cold launch; APK DEX prefix inspection confirms
|
||||
helper absent. Pinned verifier panics when verifying a certificate, not constructing reqwest Client.
|
||||
[PhishingList](../native/src/services/privacy.rs) spawns an unobserved background task; that task's panic
|
||||
need not kill the application actor. Main-shell success rules out claiming this alone explains Loading.
|
||||
|
||||
Correct follow-up: integrate pinned OS verifier/JVM helper without disabling TLS; explicit terminal
|
||||
bootstrap operation acknowledgement and revision publication; one consistent create/resume path with
|
||||
safe persisted-identity recovery; targeted failure regressions and real first-run/relaunch acceptance.
|
||||
No timeout-based fake success, profile deletion as recovery, or device-model exception.
|
||||
|
||||
@@ -171,6 +171,43 @@ Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c
|
||||
Window's ANativeWindow, while NativeContentView only reports unobscured content. The SurfaceView guard
|
||||
suppressed all inset updates. Corrected observation/projection to decor/native-window coordinates.
|
||||
New APK still required to prove keyboard actions, creation and navigation modes end to end.
|
||||
- **Run4867 (`3cc9565fab907fc1c8d81b465e689ae1df6472ad`) SUCCESS**, normal optimization; bundle hashes
|
||||
matched, APK SHA256 `0559559e12d15ccf6a4075cf1d02842a1dc394d71e836bb21a0e812d7180ffc2` installed.
|
||||
Real keyboard-visible Create/Cancel are reachable with gestures and three-button navigation; Cancel
|
||||
exited the app. After keyboard dismissal an excessively short content area was observed; do not claim
|
||||
full inset/lifecycle acceptance. Original gesture mode restored and verified (`navigation_mode=2`).
|
||||
- Owner requested thorough onboarding analysis before further build attempts. **Current run4867 identity
|
||||
creation succeeded:** known vault/prefs files exist (metadata-only), onboarding disappeared, main shell
|
||||
appeared. Force-stop/cold launch without data deletion returned to main shell, not onboarding. Exact
|
||||
create latency was not measured. Evidence: `android-4867-analysis-{submit,current,cold-start}.png` in
|
||||
`target/desktop-acceptance/`; no identity contents, microphone or TeamSpeak server used.
|
||||
- Separate reproducible defect: app-scoped logcat on creation and cold start reports panic at
|
||||
`rustls-platform-verifier-0.7.1/src/android.rs:90`, `Expect rustls-platform-verifier to be initialized`.
|
||||
Android nativeInstall never initializes its JVM context; Gradle supplies only WebRTC and all4 APK DEX
|
||||
files lack the verifier class prefix. Verifier::new itself does NOT panic: certificate verification does.
|
||||
[INFERENCE] PhishingList's detached startup refresh is a likely caller, not proven without a stack;
|
||||
main-shell operation continued. Do NOT claim this background panic proves the cause of persistent Loading.
|
||||
- Static failure-contract defects: runtime fatal Result publication does not increment snapshot.revision;
|
||||
UI applies snapshots only on revision changes. Construct errors propagate with `?` before FormComplete.
|
||||
Submission sets editor busy before dispatch, but enqueue failure routes only through services (absent
|
||||
before bootstrap), not a negative form acknowledgement. Editor.merge replaces busy/error on unrelated
|
||||
snapshots. Initialized-empty-profile retry calls onboard synchronously and ignores the selected theme.
|
||||
These are source-confirmed failure paths, not all reproduced on the device; root-cause work must repair
|
||||
terminal acknowledgement/state publication, not merely add a timer or clear busy blindly.
|
||||
- Cache optimization work is local/unverified: tools-v3/application-v2 compatibility keys separate
|
||||
dependency content from toolchain/profile/environment. Run4867 logs proved tools/application MISS due
|
||||
changed Cargo.lock/manifests; WebRTC hit. No new build started after the owner's analysis request.
|
||||
- Follow-up implementation: unified worker-owned create/resume persists theme and reuses committed
|
||||
identities; actor stays responsive during storage work. Captured FormComplete reports startup failure,
|
||||
terminal snapshots advance revision and clear unusable forms; dispatch rejection is attachment-local.
|
||||
Added7 targeted bootstrap failure/recovery/UI regressions; guarded Windows execution in progress.
|
||||
- Android TLS now initializes verifier0.7.1 via a JNI0.22 adapter alongside unchanged app JNI0.21,
|
||||
loads helper classes eagerly, packages Maven helper0.2.0/Kotlin runtime, retains R8 JNI classes and
|
||||
verifies their DEX definitions. Platform trust verification remains enabled. Native IME reporting is
|
||||
deferred until root insets/layout commit to avoid retaining the old keyboard obstruction on dismissal.
|
||||
- Warm-cache compatibility/source-timestamp fixtures and workflow ordering passed locally (Windows
|
||||
no-follow utime adapter only); one new cache generation required because legacy opaque identities
|
||||
cannot prove tool/profile compatibility independently. Real cold/warm timing proof remains pending.
|
||||
|
||||
|
||||
## First Android APK build
|
||||
|
||||
@@ -93,6 +93,9 @@ slint = { workspace = true, features = ["backend-winit", "renderer-skia"] }
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
slint = { workspace = true, features = ["backend-android-activity-06"] }
|
||||
jni = "=0.21.1"
|
||||
# rustls-platform-verifier uses JNI 0.22; keep the app/WebRTC JNI 0.21 ABI unchanged.
|
||||
jni-verifier = { package = "jni", version = "=0.22.4", default-features = false }
|
||||
rustls-platform-verifier = "=0.7.1"
|
||||
i-slint-backend-android-activity = { version = "=1.18.1", default-features = false, features = ["aa-06", "native-activity"] }
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
use std::path::PathBuf;
|
||||
use crate::{AppConfig,services::{Result,ServiceError,profile::ProfileServices,profile_import as import},ui::{shell::*,i18n::Catalog}};
|
||||
use super::model::{AppState,BootstrapState};
|
||||
#[derive(Clone)]
|
||||
pub struct Bootstrap {pub root:PathBuf,pub candidates:Vec<PathBuf>,pub selected:Option<PathBuf>,pub interrupted:bool}
|
||||
impl Bootstrap {
|
||||
pub async fn inspect(config:&AppConfig)->Result<(Self,Option<ProfileServices>)>{
|
||||
@@ -41,10 +42,7 @@ impl Bootstrap {
|
||||
let root=self.root.clone();tokio::task::spawn_blocking(move||import::discard_interrupted_import(&root,true)).await.map_err(|_|error("profile_worker","Import recovery worker stopped"))??;self.interrupted=false;Ok(None)
|
||||
},
|
||||
Operation::CreateProfile=>{
|
||||
let nickname=text(values,"nickname")?;let theme=text(values,"theme")?;if nickname.trim().chars().count()<3||nickname.trim().chars().count()>30{return Err(error("invalid_nickname","Choose a nickname with 3–30 characters"))}
|
||||
if !matches!(theme.as_str(),"dark"|"light"|"system"){return Err(error("bad_request","Choose dark, light or system appearance"))}
|
||||
if self.interrupted{return Err(error("import_interrupted","Discard or retry the incomplete import before creating a profile"))}
|
||||
let root=self.root.clone();tokio::task::spawn_blocking(move||{import::initialize_native_root(&root)?;let mut profile=ProfileServices::open(&root)?;profile.identities.onboard(nickname.trim())?;profile.prefs.set(serde_json::json!({"theme":theme}))?;Ok(Some(profile))}).await.map_err(|_|error("profile_worker","Profile creation worker stopped"))?
|
||||
self.create(values.clone(),None).await.map(Some)
|
||||
},
|
||||
Operation::ImportLegacyProfile=>{
|
||||
config_policy(config).check()?;
|
||||
@@ -60,6 +58,21 @@ impl Bootstrap {
|
||||
},_=>Err(error("profile_required","Finish profile creation or import before using server services"))
|
||||
}
|
||||
}
|
||||
/// A retry may find a committed identity after a later preference/service failure. Reuse it;
|
||||
/// never replace the vault or roll back an already committed identity.
|
||||
pub async fn create(&self,values:Values,existing:Option<ProfileServices>)->Result<ProfileServices>{
|
||||
let root=self.root.clone();let interrupted=self.interrupted;
|
||||
tokio::task::spawn_blocking(move||{
|
||||
let nickname=text(&values,"nickname")?;let theme=text(&values,"theme")?;
|
||||
if !(3..=30).contains(&nickname.trim().chars().count()){return Err(error("invalid_nickname","Choose a nickname with 3–30 characters"))}
|
||||
if !matches!(theme.as_str(),"dark"|"light"|"system"){return Err(error("bad_request","Choose dark, light or system appearance"))}
|
||||
if interrupted{return Err(error("import_interrupted","Discard or retry the incomplete import before creating a profile"))}
|
||||
let mut profile=match existing{Some(profile)=>profile,None=>{import::initialize_native_root(&root)?;ProfileServices::open(&root)?}};
|
||||
if profile.identities.list()?.identities.is_empty(){profile.identities.onboard(nickname.trim())?;}
|
||||
profile.prefs.set(serde_json::json!({"theme":theme}))?;
|
||||
Ok(profile)
|
||||
}).await.map_err(|error|ServiceError::new("profile_worker",format!("Profile creation worker stopped: {error}")))?
|
||||
}
|
||||
pub fn confirmation_form(&self,target:Target,operation:Operation)->Result<Form>{
|
||||
let mut form=crate::ui::shell::forms::form("bootstrap-confirmation",operation,target.clone(),&Catalog::default()).ok_or_else(||error("confirmation_required","Confirmation form is unavailable"))?;
|
||||
form.confirmation=Some(target.name.clone());form.destructive=operation==Operation::ConfirmOverwrite;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Consumer-level bootstrap regressions: real profile storage, actor snapshots and captured effects.
|
||||
use super::*;
|
||||
use crate::services::{identities::IdentityService,profile_import};
|
||||
|
||||
fn values(nickname:&str,theme:&str)->Values{
|
||||
Values::from([("nickname".into(),FieldValue::Text(nickname.into())),("theme".into(),FieldValue::Choice(theme.into()))])
|
||||
}
|
||||
fn submit(runtime:&AppRuntime,id:&str,nickname:&str,theme:&str){
|
||||
runtime.dispatch_shell(ShellAction::Submit{editor_id:id.into(),target:Target::application(),operation:Operation::CreateProfile,values:values(nickname,theme),confirmation:String::new()}).unwrap();
|
||||
}
|
||||
async fn snapshot_when(runtime:&AppRuntime,predicate:impl Fn(&model::Snapshot)->bool)->Arc<model::Snapshot>{
|
||||
let mut snapshots=runtime.subscribe();
|
||||
tokio::time::timeout(Duration::from_secs(20),async{
|
||||
loop{let snapshot=snapshots.borrow_and_update().clone();if predicate(&snapshot){return snapshot}snapshots.changed().await.expect("runtime snapshot publisher stopped");}
|
||||
}).await.expect("bootstrap did not publish the expected consumer state")
|
||||
}
|
||||
async fn acknowledgement(runtime:&AppRuntime,id:&str)->Result<()>{
|
||||
tokio::time::timeout(Duration::from_secs(20),async{
|
||||
let mut effects=runtime.effects.lock().unwrap();
|
||||
loop{match effects.recv().await.expect("runtime effects ended without a form acknowledgement"){
|
||||
UiEffect::FormComplete{id:captured,target,result}=>{assert_eq!(captured,id);assert_eq!(target,Target::application());return result},_=>{}
|
||||
}}
|
||||
}).await.expect("bootstrap did not acknowledge the captured submission")
|
||||
}
|
||||
async fn shutdown(runtime:&AppRuntime)->Result<()>{
|
||||
tokio::time::timeout(Duration::from_secs(20),runtime.shutdown()).await.expect("bootstrap did not release its workers")
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn bootstrap_contract_initialized_empty_validation_and_saved_profile_failure_are_distinct(){
|
||||
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
|
||||
let mut config=AppConfig::isolated(root.clone());config.build_version="invalid-version";
|
||||
let runtime=AppRuntime::start(config.clone()).unwrap();
|
||||
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
|
||||
submit(&runtime,"invalid-nickname","ab","dark");
|
||||
assert_eq!(acknowledgement(&runtime,"invalid-nickname").await.unwrap_err().code,"invalid_nickname");
|
||||
let rejected=snapshot_when(&runtime,|snapshot|!snapshot.error.is_empty()).await;
|
||||
assert_eq!(rejected.bootstrap,BootstrapState::Username);assert!(rejected.profile_form.is_some());
|
||||
assert!(IdentityService::open(&root).unwrap().list().unwrap().identities.is_empty());
|
||||
submit(&runtime,"invalid-theme","Valid User","unsupported");
|
||||
assert_eq!(acknowledgement(&runtime,"invalid-theme").await.unwrap_err().code,"bad_request");
|
||||
submit(&runtime,"saved-profile","Native User","light");
|
||||
let error=acknowledgement(&runtime,"saved-profile").await.unwrap_err();
|
||||
assert_eq!(error.code,"services_initialization_failed");assert!(error.message.contains("profile is saved"));
|
||||
let terminal=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Failed).await;
|
||||
assert_ne!(terminal.revision,rejected.revision,"revision-gated consumers must receive terminal failure");
|
||||
assert!(terminal.ready);assert!(!terminal.loading);assert!(terminal.profile_form.is_none());assert!(terminal.dialog.is_none());
|
||||
assert_eq!(terminal.error,error.message);assert_eq!(terminal.last_error.as_ref().unwrap().code,error.code);
|
||||
assert_eq!(shutdown(&runtime).await.unwrap_err().code,error.code);drop(runtime);
|
||||
let saved=ProfileServices::open(&root).unwrap();let identities=saved.identities.list().unwrap();
|
||||
assert_eq!(identities.identities.len(),1);assert_eq!(saved.prefs.get()["theme"],"light");let uid=identities.default_id;drop(saved);
|
||||
// Cold-start failure must expose the same truthful outcome, without repeating onboarding.
|
||||
let runtime=AppRuntime::start(config).unwrap();
|
||||
let terminal=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Failed).await;
|
||||
assert!(terminal.revision>0);assert!(terminal.profile_form.is_none());assert!(terminal.error.contains("profile is saved"));
|
||||
assert_eq!(shutdown(&runtime).await.unwrap_err().code,"services_initialization_failed");drop(runtime);
|
||||
assert_eq!(ProfileServices::open(&root).unwrap().identities.list().unwrap().default_id,uid);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn bootstrap_contract_late_construction_failure_joins_workers_before_restart(){
|
||||
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
|
||||
// Theme scanning fails only after the real connection and audio owners have started.
|
||||
std::fs::write(root.join("extensions"),b"not a directory").unwrap();
|
||||
let config=AppConfig::isolated(root.clone());let runtime=AppRuntime::start(config.clone()).unwrap();
|
||||
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
|
||||
submit(&runtime,"late-failure","Native User","system");
|
||||
assert_eq!(acknowledgement(&runtime,"late-failure").await.unwrap_err().code,"services_initialization_failed");
|
||||
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Failed).await;
|
||||
assert_eq!(shutdown(&runtime).await.unwrap_err().code,"services_initialization_failed");drop(runtime);
|
||||
let profile=ProfileServices::open(&root).unwrap();let uid=profile.identities.list().unwrap().default_id;assert_eq!(profile.prefs.get()["theme"],"system");drop(profile);
|
||||
std::fs::remove_file(root.join("extensions")).unwrap();
|
||||
let runtime=AppRuntime::start(config).unwrap();
|
||||
let resumed=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Ready&&snapshot.settings.loaded).await;
|
||||
assert!(resumed.profile_form.is_none());assert!(!resumed.loading);
|
||||
shutdown(&runtime).await.unwrap();drop(runtime);
|
||||
assert_eq!(ProfileServices::open(&root).unwrap().identities.list().unwrap().default_id,uid);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn bootstrap_contract_fresh_create_acknowledges_only_after_services_start(){
|
||||
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");
|
||||
let runtime=AppRuntime::start(AppConfig::isolated(root.clone())).unwrap();
|
||||
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
|
||||
submit(&runtime,"fresh-create","Native User","light");acknowledgement(&runtime,"fresh-create").await.unwrap();
|
||||
let ready=snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Ready&&snapshot.settings.loaded).await;
|
||||
assert!(ready.profile_form.is_none());assert_eq!(ready.settings.prefs["theme"],"light");
|
||||
shutdown(&runtime).await.unwrap();drop(runtime);
|
||||
let profile=ProfileServices::open(&root).unwrap();assert_eq!(profile.identities.list().unwrap().identities.len(),1);assert_eq!(profile.prefs.get()["theme"],"light");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn bootstrap_contract_preference_failure_retry_preserves_committed_identity(){
|
||||
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
|
||||
let mut existing=ProfileServices::open(&root).unwrap();existing.prefs.set(serde_json::json!({"theme":"dark"})).unwrap();
|
||||
std::fs::remove_file(root.join("prefs.json")).unwrap();std::fs::create_dir(root.join("prefs.json")).unwrap();
|
||||
let bootstrap=bootstrap::Bootstrap{root:root.clone(),candidates:vec![],selected:None,interrupted:false};
|
||||
assert!(bootstrap.create(values("Original User","light"),Some(existing)).await.is_err());
|
||||
let committed=IdentityService::open(&root).unwrap().list().unwrap();assert_eq!(committed.identities.len(),1);
|
||||
std::fs::remove_dir(root.join("prefs.json")).unwrap();
|
||||
let recovered=bootstrap.create(values("Different User","system"),None).await.unwrap();
|
||||
assert_eq!(recovered.identities.list().unwrap(),committed,"recovery must not regenerate or rename the committed identity");
|
||||
assert_eq!(recovered.prefs.get()["theme"],"system");drop(recovered);
|
||||
let reopened=ProfileServices::open(&root).unwrap();assert_eq!(reopened.identities.list().unwrap(),committed);assert_eq!(reopened.prefs.get()["theme"],"system");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor="current_thread")]
|
||||
async fn bootstrap_contract_quit_is_consumed_while_storage_commit_is_blocked(){
|
||||
let directory=tempfile::tempdir().unwrap();let root=directory.path().join("native");profile_import::initialize_native_root(&root).unwrap();
|
||||
let runtime=AppRuntime::start(AppConfig::isolated(root.clone())).unwrap();
|
||||
snapshot_when(&runtime,|snapshot|snapshot.bootstrap==BootstrapState::Username).await;
|
||||
let lock=std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(root.join("core/profile.lock")).unwrap();
|
||||
teamspeach_core::file_lock::try_lock(&lock,false).unwrap();
|
||||
let mut cancelled=runtime.cancel.subscribe();
|
||||
submit(&runtime,"blocked-create","Native User","light");runtime.platform_event(crate::platform::lifecycle::PlatformEvent::Quit);
|
||||
let responsive=tokio::time::timeout(Duration::from_secs(5),async{while !*cancelled.borrow_and_update(){cancelled.changed().await.unwrap();}}).await;
|
||||
drop(lock); // allow the already-started atomic storage operation to finish, not roll back
|
||||
shutdown(&runtime).await.unwrap();drop(runtime);
|
||||
assert!(responsive.is_ok(),"the current-thread actor must consume lifecycle events during profile work");
|
||||
let profile=ProfileServices::open(&root).unwrap();assert_eq!(profile.identities.list().unwrap().identities.len(),1);assert_eq!(profile.prefs.get()["theme"],"light");
|
||||
}
|
||||
@@ -41,14 +41,29 @@ pub fn start(config:AppConfig)->std::result::Result<Arc<AppRuntime>,AppError>{
|
||||
let _platform=bootstrap_platform;
|
||||
let observed=snapshots_tx.clone();let wake=weak.clone();
|
||||
let result=executor.block_on(run(config,weak,incoming,cancelled,snapshots_tx,effects_tx));
|
||||
if let Err(error)=&result{let mut snapshot=(**observed.borrow()).clone();snapshot.error=error.message.clone();snapshot.loading=false;snapshot.ready=true;snapshot.bootstrap=BootstrapState::Failed;observed.send_replace(Arc::new(snapshot));if let Some(runtime)=wake.upgrade(){runtime.notify_ui();}}
|
||||
if let Err(error)=&result{publish_failure(&wake,&observed,error);}
|
||||
drop(executor);finished_tx.send_replace(Some(result));
|
||||
})?;*runtime.worker.lock().expect("runtime worker")=Some(worker);Ok(runtime)
|
||||
}
|
||||
fn publish_failure(runtime:&Weak<AppRuntime>,sender:&watch::Sender<Arc<model::Snapshot>>,error:&ServiceError){
|
||||
let mut snapshot=(**sender.borrow()).clone();
|
||||
snapshot.revision=snapshot.revision.wrapping_add(1);snapshot.error=error.message.clone();snapshot.last_error=Some(error.clone());
|
||||
snapshot.loading=false;snapshot.ready=true;snapshot.bootstrap=BootstrapState::Failed;snapshot.profile_form=None;snapshot.dialog=None;
|
||||
sender.send_replace(Arc::new(snapshot));if let Some(runtime)=runtime.upgrade(){runtime.notify_ui();}
|
||||
}
|
||||
fn failed(message:impl Into<String>)->ServiceError{ServiceError::new("runtime_failed",message)}
|
||||
struct Owner {ctx:Arc<RuntimeServices>,audio:AudioEngine,audio_events:std::sync::mpsc::Receiver<AudioEvent>,settings:mpsc::Sender<settings_queue::Request>,settings_worker:tokio::task::JoinHandle<()>,_platform:Option<crate::platform::lifecycle::Subscription>}
|
||||
async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRuntime>,events:mpsc::Sender<ServiceEvent>,cancelled:watch::Receiver<bool>,controls:mpsc::Sender<ConnectionEvent>)->Result<Owner>{
|
||||
let root=profile.root.clone();let prefs=profile.prefs.get();
|
||||
let policy=crate::platform::resources::ActionPolicy{allow_os_actions:config.allow_os_actions};
|
||||
let (installation,installed)=distribution::detect(config)?;
|
||||
let updates=crate::services::updates::UpdateService::new(installation,root.join("update-cache"),if prefs["updateChannel"]=="preview"{crate::services::updates::Channel::Preview}else{crate::services::updates::Channel::Stable},Instant::now(),policy).map_err(|e|ServiceError::new(e.code,e.detail))?;
|
||||
let phishing=crate::services::privacy::PhishingList::new(&root,config.network_enabled)?;let badges=Arc::new(crate::services::badges::BadgeCatalog::new(&root,config.network_enabled)?);
|
||||
let notifications=crate::services::notifications::Notifications::new(serde_json::from_value(prefs.clone())?)?;
|
||||
#[cfg(not(target_os="android"))]
|
||||
let subscription={let weak=runtime.clone();if config.allow_os_actions{Some(crate::platform::lifecycle::subscribe(Arc::new(move|event|{if let Some(runtime)=weak.upgrade(){runtime.platform_event(event);}}))?)}else{None}};
|
||||
#[cfg(target_os="android")]
|
||||
let subscription=None;
|
||||
let reports=events.clone();let error_runtime=runtime.clone();let errors=Arc::new(move|error|{if reports.try_send(ServiceEvent::Effect(UiEffect::Error(error))).is_err(){if let Some(runtime)=error_runtime.upgrade(){runtime.cancel.send_replace(true);}}});
|
||||
let binding=Arc::new(AudioSessionBinding::new(errors));let binding_sink=binding.clone();let overflow_runtime=runtime.clone();
|
||||
let consumer:Arc<dyn ConnectionSink>=Arc::new(move|event:ConnectionEvent|{
|
||||
@@ -57,13 +72,12 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
|
||||
if controls.try_send(event).is_err(){if let Some(runtime)=overflow_runtime.upgrade(){runtime.release_held();runtime.cancel.send_replace(true);}}
|
||||
});
|
||||
let connected=Arc::new(crate::services::connected::ConnectedServices::start(root.clone(),profile.files.clone(),config.network_enabled,consumer)?);
|
||||
let(engine,audio_events)=AudioEngine::start(connected.connections.clone(),teamspeach_denoise::CaptureSettings::default())?;let audio=engine.handle();binding.bind(audio.clone())?;
|
||||
let(engine,audio_events)=match AudioEngine::start(connected.connections.clone(),teamspeach_denoise::CaptureSettings::default()){
|
||||
Ok(value)=>value,Err(mut error)=>{if let Err(cleanup)=connected.shutdown().await{error.message.push_str(&format!("; cleanup failed: {cleanup}"));}return Err(error)}
|
||||
};
|
||||
let audio=engine.handle();if let Err(error)=binding.bind(audio.clone()){return Err(stop_construction(&connected,engine,error).await)}
|
||||
let signal=Arc::new(CoreSignal::new(connected.connections.clone()));let failures=events.clone();
|
||||
let streams=StreamHub::new(signal,tokio::runtime::Handle::current(),Arc::new(move|_key,error|{let _=failures.try_send(ServiceEvent::Effect(UiEffect::Error(ServiceError::new(error.code,error.message))));}));
|
||||
let policy=crate::platform::resources::ActionPolicy{allow_os_actions:config.allow_os_actions};
|
||||
let (installation,installed)=distribution::detect(config)?;
|
||||
let updates=crate::services::updates::UpdateService::new(installation,root.join("update-cache"),if prefs["updateChannel"]=="preview"{crate::services::updates::Channel::Preview}else{crate::services::updates::Channel::Stable},Instant::now(),policy).map_err(|e|ServiceError::new(e.code,e.detail))?;
|
||||
let phishing=crate::services::privacy::PhishingList::new(&root,config.network_enabled)?;let badges=Arc::new(crate::services::badges::BadgeCatalog::new(&root,config.network_enabled)?);
|
||||
let ctx=Arc::new(RuntimeServices{
|
||||
mobile_call:Default::default(),
|
||||
#[cfg(target_os="ios")]apple_call:Default::default(),
|
||||
@@ -71,7 +85,7 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
|
||||
root:root.clone(),profile:Mutex::new(profile),connected,audio,streams,
|
||||
themes:Mutex::new(crate::services::themes::ThemeService::new(root.join("extensions"),prefs["userStyle"].as_str().map(str::to_owned))),
|
||||
phishing,badges,
|
||||
notifications:Mutex::new(crate::services::notifications::Notifications::new(serde_json::from_value(prefs.clone())?)?),
|
||||
notifications:Mutex::new(notifications),
|
||||
updates,keys:Default::default(),settings_drafts:Default::default(),settings_status:Default::default(),
|
||||
audio_defaults:Mutex::new((false,false)),
|
||||
improvements:Mutex::new(HashMap::new()),progress:Mutex::new(HashMap::new()),
|
||||
@@ -84,27 +98,35 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
|
||||
network_enabled:config.network_enabled,version:config.build_version,runtime:runtime.clone(),
|
||||
revision:AtomicU64::new(0),events,cancelled,dialogs:Semaphore::new(8),prompt_counter:AtomicU64::new(1)
|
||||
});
|
||||
let initialized:Result<()>=async{
|
||||
ctx.notifications.lock().map_err(|_|failed("Notifications unavailable"))?.set_presentation(crate::services::notifications::Presentation{focused:true,prohibit_os_effects:!config.allow_os_actions});
|
||||
ctx.connected.connections.create().await.map_err(context::connection_error)?;
|
||||
let scheme=theme_actions::scheme(&ctx)?;let theme=ctx.themes.lock().map_err(|_|failed("Theme service unavailable"))?.resolve(scheme)?;ctx.effect(UiEffect::Theme(theme)).await?;
|
||||
// Restoring configuration doesn't grant or open hardware, even for autostart/resume.
|
||||
if let Err(error)=settings_actions::sync_keys(ctx.clone()).await{ctx.settings_status.lock().map_err(|_|failed("Shortcut state unavailable"))?.key_status=error.message;}
|
||||
Ok(())
|
||||
}.await;
|
||||
if let Err(error)=initialized{ctx.streams.shutdown();return Err(stop_construction(&ctx.connected,engine,error).await)}
|
||||
ctx.phishing.start();
|
||||
if let Some(runtime)=runtime.upgrade(){*runtime.services.lock().expect("runtime services")=Arc::downgrade(&ctx);}
|
||||
#[cfg(not(target_os="android"))]
|
||||
let subscription={let weak=runtime.clone();if config.allow_os_actions{Some(crate::platform::lifecycle::subscribe(Arc::new(move|event|{if let Some(runtime)=weak.upgrade(){runtime.platform_event(event);}}))?)}else{None}};
|
||||
#[cfg(target_os="android")]
|
||||
let subscription=None;
|
||||
ctx.notifications.lock().map_err(|_|failed("Notifications unavailable"))?.set_presentation(crate::services::notifications::Presentation{focused:true,prohibit_os_effects:!config.allow_os_actions});
|
||||
ctx.phishing.start();ctx.connected.connections.create().await.map_err(context::connection_error)?;
|
||||
// Restoring configuration doesn't grant or open hardware, even for autostart/resume.
|
||||
if let Err(error)=settings_actions::sync_keys(ctx.clone()).await{ctx.settings_status.lock().map_err(|_|failed("Shortcut state unavailable"))?.key_status=error.message;}
|
||||
let scheme=theme_actions::scheme(&ctx)?;let theme=ctx.themes.lock().map_err(|_|failed("Theme service unavailable"))?.resolve(scheme)?;ctx.effect(UiEffect::Theme(theme)).await?;
|
||||
let(settings,settings_worker)=settings_queue::start(ctx.clone());
|
||||
Ok(Owner{ctx,audio:engine,audio_events,settings,settings_worker,_platform:subscription})
|
||||
}
|
||||
async fn stop_construction(connected:&crate::services::connected::ConnectedServices,engine:AudioEngine,mut error:ServiceError)->ServiceError{
|
||||
for result in [connected.shutdown().await,engine.shutdown().await]{if let Err(cleanup)=result{error.message.push_str(&format!("; cleanup failed: {cleanup}"));}}
|
||||
error
|
||||
}
|
||||
fn services_failed(error:ServiceError)->ServiceError{ServiceError::new("services_initialization_failed",format!("Your profile is saved, but application services could not start: {}. Restart the app to resume the saved profile.",error.message))}
|
||||
async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiver<RuntimeCommand>,mut cancelled:watch::Receiver<bool>,snapshots:watch::Sender<Arc<model::Snapshot>>,effects:mpsc::Sender<UiEffect>)->Result<()> {
|
||||
let(events,mut service_events)=mpsc::channel(1024);let(controls,mut control_events)=mpsc::channel(1024);let mut state=AppState::default();let mut prompts:std::collections::VecDeque<Prompt>=Default::default();let mut jobs=tokio::task::JoinSet::new();let mut owner=None;
|
||||
let inspected=bootstrap::Bootstrap::inspect(&config).await;let(mut bootstrap,mut profile)=match inspected{Ok(value)=>value,Err(error)=>{state.snapshot.bootstrap=BootstrapState::Failed;state.snapshot.error=error.message;state.snapshot.loading=false;publish(&runtime,&snapshots,&mut state);wait_failed(commands,cancelled).await?;return send_effect(&runtime,&effects,UiEffect::Quit).await;}};
|
||||
bootstrap.present(&mut state,profile.as_ref())?;
|
||||
if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}
|
||||
if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await.map_err(services_failed)?);}
|
||||
publish(&runtime,&snapshots,&mut state);let mut tick=tokio::time::interval(Duration::from_millis(20));let mut dirty=true;let mut last_update=Instant::now();let mut update_gate=None;let mut relaunch=false;
|
||||
let mut desktop_state=desktop_actions::DesktopState::default();let mut startup_done=false;
|
||||
let mut settings_serial=0u64;
|
||||
let mut onboarding:Option<tokio::task::JoinHandle<(bootstrap::Bootstrap,Result<Option<ProfileServices>>)>>=None;
|
||||
let mut submission:Option<(String,Target)>=None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
_=cancelled.changed()=>{if *cancelled.borrow(){break}},
|
||||
@@ -118,9 +140,15 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
|
||||
if prompts.front().is_some_and(|p|p.form.id==editor_id){let prompt=prompts.pop_front().unwrap();let answer=if prompt.form.target!=target||prompt.form.confirmation.as_ref().is_some_and(|c|c!=&confirmation){Err(context::changed())}else{Ok(values)};let result=answer.as_ref().map(|_|()).map_err(Clone::clone);let _=prompt.answer.send(answer);send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result}).await?;state.snapshot.dialog=prompts.front().map(|p|p.form.clone());dirty=true;continue}
|
||||
if let Some(owner)=&owner{let ctx=owner.ctx.clone();let sender=events.clone();jobs.spawn(async move{let result=controller::dispatch(ctx,target.clone(),operation,values).await;let ack=result.as_ref().map(|_|()).map_err(Clone::clone);let _=sender.send(ServiceEvent::Effect(UiEffect::FormComplete{id:editor_id,target,result:ack})).await;let _=sender.send(ServiceEvent::Workflow(result)).await;});}
|
||||
else{
|
||||
let result=if let Some(existing)=profile.as_mut(){if operation==Operation::CreateProfile{let nickname=values.get("nickname").and_then(|v|if let FieldValue::Text(v)=v{Some(v.clone())}else{None}).unwrap_or_default();existing.identities.onboard(nickname.trim()).map(|_|None)}else{Err(ServiceError::new("profile_exists","Continue onboarding the initialized profile"))}}else{bootstrap.handle(&config,&target,operation,&values,confirmation==target.name).await};
|
||||
if result.is_ok(){state.snapshot.dialog=None;}
|
||||
match result{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Ok(())}).await?;},Err(error)=>{state.snapshot.error=error.message.clone();send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(error)}).await?;}}dirty=true;
|
||||
if onboarding.is_some(){send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(ServiceError::new("profile_busy","Profile initialization is already running"))}).await?;continue}
|
||||
let mut pending=bootstrap.clone();let config=config.clone();let existing=profile.take();let captured=target.clone();
|
||||
submission=Some((editor_id,target));
|
||||
onboarding=Some(tokio::spawn(async move{
|
||||
let result=if operation==Operation::CreateProfile{pending.create(values,existing).await.map(Some)}
|
||||
else if existing.is_some(){Err(ServiceError::new("profile_exists","Continue onboarding the initialized profile"))}
|
||||
else{pending.handle(&config,&captured,operation,&values,confirmation==captured.name).await};
|
||||
(pending,result)
|
||||
}));
|
||||
}
|
||||
},
|
||||
RuntimeCommand::Shell(action)=>{
|
||||
@@ -135,8 +163,9 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
|
||||
ShellAction::Page{target,offset}=>{state.query.offset=offset.min(u32::MAX as usize) as u32;if let Some(operation)=state.detail_operation{spawn_query(&mut jobs,events.clone(),ctx,target,operation,state.query.clone());}},
|
||||
ShellAction::PaneWidths{sidebar,server}=>{let sender=events.clone();jobs.spawn(async move{let result=ctx.mutate(move|p|{p.prefs.set(serde_json::json!({"sidebarWidth":sidebar.round(),"serverPaneWidth":server.round()}))?;Ok(())}).await.map(|_|events::WorkflowResult::default());let _=sender.send(ServiceEvent::Workflow(result)).await;});},_=>{}
|
||||
}}else if let ShellAction::Invoke{target,operation}=action{
|
||||
if onboarding.is_some(){state.snapshot.error="Profile initialization is already running".into();dirty=true;continue}
|
||||
if matches!(operation,Operation::ImportIdentity|Operation::ImportLegacyProfile|Operation::ConfirmOverwrite){state.snapshot.dialog=Some(bootstrap.confirmation_form(target,operation)?);}
|
||||
else{match bootstrap.handle(&config,&target,operation,&Values::new(),false).await{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}},Err(error)=>state.snapshot.error=error.message}}dirty=true;
|
||||
else{match bootstrap.handle(&config,&target,operation,&Values::new(),false).await{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await.map_err(services_failed)?);}},Err(error)=>state.snapshot.error=error.message}}dirty=true;
|
||||
}
|
||||
},
|
||||
RuntimeCommand::Settings(action)=>{if let Some(owner)=&owner{settings_serial=settings_serial.checked_add(1).ok_or_else(||failed("Settings request IDs exhausted"))?;state.snapshot.error.clear();state.snapshot.last_error=None;let pending=settings_queue::pending(&action,&state.snapshot);let request=settings_queue::Request{action,pending,serial:settings_serial};if let Err(error)=settings_queue::enqueue(&owner.ctx,&owner.settings,request){state.snapshot.settings_completed=settings_serial;state.snapshot.last_error=Some(error.clone());state.snapshot.error=error.message;}dirty=true;}},
|
||||
@@ -155,6 +184,32 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
|
||||
},
|
||||
RuntimeCommand::Platform(event)=>{if let Some(owner)=&owner{match platform(&owner.ctx,&runtime,&mut state,event).await{Ok(true)=>break,Ok(false)=>{},Err(error)=>state.snapshot.error=error.message}dirty=true;}},
|
||||
}},
|
||||
completed=async{onboarding.as_mut().expect("pending onboarding").await},if onboarding.is_some()=>{
|
||||
onboarding=None;let(editor_id,target)=submission.take().expect("onboarding submission");
|
||||
let result=match completed{Ok((updated,result))=>{bootstrap=updated;result},Err(error)=>Err(ServiceError::new("profile_worker",format!("Profile initialization worker stopped: {error}")))};
|
||||
let result=match result{
|
||||
Ok(created)=>{
|
||||
if created.is_some(){profile=created}
|
||||
match bootstrap.present(&mut state,profile.as_ref()){
|
||||
Ok(()) if state.snapshot.bootstrap==BootstrapState::Ready=>{
|
||||
match construct(&config,profile.take().expect("ready profile"),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await{
|
||||
Ok(created)=>{owner=Some(created);Ok(())},
|
||||
Err(error)=>{
|
||||
let error=services_failed(error);
|
||||
send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(error.clone())}).await?;
|
||||
return Err(error)
|
||||
}
|
||||
}
|
||||
},
|
||||
result=>result,
|
||||
}
|
||||
},
|
||||
Err(error)=>Err(error),
|
||||
};
|
||||
if let Err(error)=&result{state.snapshot.error=error.message.clone();state.snapshot.last_error=Some(error.clone());}
|
||||
else{state.snapshot.dialog=None;state.snapshot.error.clear();state.snapshot.last_error=None;}
|
||||
send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result}).await?;dirty=true;
|
||||
},
|
||||
event=control_events.recv()=>{if let(Some(owner),Some(event))=(&owner,event){if let Err(error)=control(&owner.ctx,event).await{state.snapshot.error=error.message;}dirty=true;}},
|
||||
event=service_events.recv()=>{if let Some(event)=event{match event{
|
||||
ServiceEvent::Changed=>dirty=true,
|
||||
@@ -201,6 +256,9 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
|
||||
}
|
||||
if let Some(runtime)=runtime.upgrade(){runtime.cancel.send_replace(true);runtime.release_held();}
|
||||
for prompt in prompts{let _=prompt.answer.send(Err(context::closed()));}
|
||||
// A blocking storage commit cannot be cancelled safely. Join it before releasing the runtime
|
||||
// so a restart cannot race its profile lease or replace a just-committed identity.
|
||||
if let Some(onboarding)=onboarding{onboarding.await.map_err(|error|ServiceError::new("profile_worker",format!("Profile initialization worker stopped: {error}")))?;}
|
||||
if let Some(owner)=owner{
|
||||
owner.ctx.phishing.stop();owner.ctx.badges.stop();owner.ctx.updates.stop();for cancel in owner.ctx.improvements.lock().map_err(|_|failed("Identity jobs unavailable"))?.values(){cancel.store(true,Ordering::Release);}
|
||||
jobs.abort_all();while jobs.join_next().await.is_some(){}
|
||||
@@ -236,3 +294,6 @@ async fn isolated_settings(ctx:Arc<RuntimeServices>,action:crate::ui::settings::
|
||||
SettingsAction::Invoke(O::Reload(Category::Audio))=>return Err(ServiceError::new("os_actions_disabled","Physical audio enumeration is disabled in this isolated runtime")),_=>{}
|
||||
}}settings_actions::handle(ctx,action).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bootstrap_tests;
|
||||
@@ -8,6 +8,7 @@ mod documents;
|
||||
mod smoke;
|
||||
mod call_audio;
|
||||
mod private_container;
|
||||
mod tls;
|
||||
pub use smoke::{AndroidSmokeRequest, smoke_request};
|
||||
pub mod accessibility;
|
||||
pub use accessibility::{attach_accessibility, AccessibilityLease};
|
||||
@@ -296,6 +297,8 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeInstall(m
|
||||
let result=(|| -> Result<()> {
|
||||
if BINDING.get().is_some() { return Ok(()); }
|
||||
if !java(env.is_instance_of(&application,"android/app/Application"))? { return Err(error("android_context", "Application context required")); }
|
||||
// Install the process Application/classloader before publishing BINDING or starting workers.
|
||||
tls::initialize(&mut env, &application)?;
|
||||
let vm=java(env.get_java_vm())?;
|
||||
#[cfg(feature="webrtc")]
|
||||
if !libwebrtc::android::initialize_android_context(&vm,&application) { return Err(error("android_webrtc", "Matching prefixed WebRTC JNI jar/context initialization failed")); }
|
||||
@@ -315,8 +318,17 @@ pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeInstall(m
|
||||
if !unsafe { cpal::android_context::set_process_android_context(vm,application) } { return Err(error("android_context","CPAL process context conflict")); }
|
||||
Ok(())
|
||||
})();
|
||||
if env.exception_check().unwrap_or(true) { let _=env.exception_clear(); }
|
||||
result.is_ok() as u8
|
||||
match result {
|
||||
Ok(()) => 1,
|
||||
Err(error) => {
|
||||
// Preserve the original JVM exception (including missing helper classes), otherwise
|
||||
// surface the native initialization failure instead of the bridge's generic boolean error.
|
||||
if !env.exception_check().unwrap_or(true) {
|
||||
let _ = env.throw_new("java/lang/IllegalStateException", format!("{}: {}", error.code, error.message));
|
||||
}
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "system" fn Java_dev_teamspeach_mobile_PlatformBridge_nativeEvent(_env:JNIEnv,_class:JClass,generation:jlong,event:jint,value:jboolean) {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
//! JNI-version boundary for the process-owned Android platform trust verifier.
|
||||
use jni::{JNIEnv, objects::{JObject, JValue}};
|
||||
use jni_verifier::{EnvUnowned, Outcome};
|
||||
|
||||
use super::{error, java};
|
||||
use crate::services::Result;
|
||||
|
||||
pub(super) fn initialize(env: &mut JNIEnv<'_>, application: &JObject<'_>) -> Result<()> {
|
||||
// Use the same Application classloader the verifier retains, not FindClass on a
|
||||
// native worker (whose default loader cannot see application dependencies).
|
||||
let loader = env.call_method(application, "getClassLoader", "()Ljava/lang/ClassLoader;", &[])
|
||||
.and_then(|value| value.l())
|
||||
.map_err(|cause| error("android_tls", format!("Android TLS Application classloader unavailable: {cause}")))?;
|
||||
if loader.is_null() {
|
||||
return Err(error("android_tls", "Android TLS Application classloader is null"));
|
||||
}
|
||||
for class in ["org.rustls.platformverifier.CertificateVerifier", "org.rustls.platformverifier.VerificationResult", "org.rustls.platformverifier.StatusCode"] {
|
||||
let name = java(env.new_string(class))?;
|
||||
// Initialize as well as load, so absent Kotlin runtime/linkage fails during install.
|
||||
let loaded = env.call_static_method("java/lang/Class", "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;", &[JValue::Object(name.as_ref()), JValue::Bool(1), JValue::Object(&loader)])
|
||||
.and_then(|value| value.l())
|
||||
.map_err(|cause| error("android_tls", format!("Android TLS helper {class} is unavailable; package org.rustls:rustls-platform-verifier:0.2.0 and retain its JNI classes: {cause}")))?;
|
||||
if loaded.is_null() {
|
||||
return Err(error("android_tls", format!("Android TLS helper classloader returned null for {class}")));
|
||||
}
|
||||
}
|
||||
|
||||
// JNI 0.21 remains the app/WebRTC API. Borrow its current-thread environment
|
||||
// only inside this call; JNI 0.22 never receives a transmuted Rust wrapper.
|
||||
// Give 0.22 its own local reference so there are no competing owning wrappers.
|
||||
let context = java(env.new_local_ref(application))?.into_raw();
|
||||
// SAFETY: nativeInstall supplied a valid current-thread JNI environment. The
|
||||
// adapter cannot escape this call or detach the JVM-owned native stack frame.
|
||||
let mut verifier_env = unsafe { EnvUnowned::from_raw(env.get_raw().cast()) };
|
||||
let outcome = verifier_env.with_env(|env| {
|
||||
// SAFETY: context is the transferred local above, belongs to this thread/
|
||||
// native frame, and has no remaining JNI 0.21 owner. The verifier retains
|
||||
// its own global Application/classloader references, never an Activity.
|
||||
let context = unsafe { jni_verifier::objects::JObject::from_raw(env, context.cast()) };
|
||||
rustls_platform_verifier::android::init_with_env(env, context)
|
||||
}).into_outcome();
|
||||
match outcome {
|
||||
Outcome::Ok(()) => Ok(()),
|
||||
Outcome::Err(cause) => Err(error("android_tls", format!("Android platform TLS verifier initialization failed: {cause}"))),
|
||||
Outcome::Panic(_) => Err(error("android_tls", "Android platform TLS verifier initialization panicked")),
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,17 @@
|
||||
use std::{cell::RefCell,collections::HashMap,rc::Rc,sync::Arc,time::Duration};
|
||||
use slint::ComponentHandle;
|
||||
use crate::{AppRuntime,AppWindow,AppError,Theme,ShellBridge,app::runtime::{events::UiEffect,model::Snapshot},ui::{shell,settings,chat}};
|
||||
struct DispatchFeedback{form:Option<(String,shell::Target)>,result:crate::services::Result<()>}
|
||||
fn dispatch_shell(runtime:&AppRuntime,action:shell::ShellAction)->DispatchFeedback{
|
||||
let form=match &action{shell::ShellAction::Submit{editor_id,target,..}=>Some((editor_id.clone(),target.clone())),_=>None};
|
||||
DispatchFeedback{form,result:runtime.dispatch_shell(action)}
|
||||
}
|
||||
struct Bindings {
|
||||
shell:shell::ShellBinding,settings:settings::Binding,chat:chat::ChatBinding,
|
||||
revision:u64,destination:shell::Destination,
|
||||
fonts:super::theme::Fonts,
|
||||
panes:Option<(i32,i32)>,
|
||||
feedback:std::sync::mpsc::Receiver<DispatchFeedback>,dispatch_error:Option<String>,
|
||||
#[cfg(feature="webrtc")]
|
||||
frames:HashMap<String,(Arc<crate::media::stream::frames::VideoFrames>,crate::media::stream::frames::PresentedFrame)>,
|
||||
}
|
||||
@@ -32,10 +38,13 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
|
||||
let generation=if generation==0{runtime.next_ui_generation()}else{generation};
|
||||
if !runtime.is_ui_current(generation){return Err(crate::services::ServiceError::new("ui_destroyed","The UI attachment was replaced").into())}
|
||||
let window=AppWindow::new()?;
|
||||
let weak=Arc::downgrade(&runtime);let shell=shell::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){if let Err(error)=runtime.dispatch_shell(action){report(&runtime,error);}}}));
|
||||
let weak=Arc::downgrade(&runtime);let settings=settings::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){if let Err(error)=runtime.dispatch_settings(action){report(&runtime,error);}}}));
|
||||
let weak=Arc::downgrade(&runtime);let chat=chat::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){if let Err(error)=runtime.dispatch_chat(action){report(&runtime,error);}}}));
|
||||
let bindings=Rc::new(RefCell::new(Bindings{shell,settings,chat,revision:u64::MAX,destination:shell::Destination::Servers,fonts:Default::default(),panes:None,#[cfg(feature="webrtc")]frames:HashMap::new()}));
|
||||
// Dispatch can fail before RuntimeServices exists (or after it stops). Return captured failures
|
||||
// through the attachment, deferred until the callback releases the shell editor borrow.
|
||||
let(feedback_tx,feedback)=std::sync::mpsc::channel();
|
||||
let weak=Arc::downgrade(&runtime);let sender=feedback_tx.clone();let shell=shell::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){let _=sender.send(dispatch_shell(&runtime,action));}}));
|
||||
let weak=Arc::downgrade(&runtime);let sender=feedback_tx.clone();let settings=settings::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){let _=sender.send(DispatchFeedback{form:None,result:runtime.dispatch_settings(action)});}}));
|
||||
let weak=Arc::downgrade(&runtime);let chat=chat::bind(&window,Arc::new(move|action|{if let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)){let _=feedback_tx.send(DispatchFeedback{form:None,result:runtime.dispatch_chat(action)});}}));
|
||||
let bindings=Rc::new(RefCell::new(Bindings{shell,settings,chat,feedback,dispatch_error:None,revision:u64::MAX,destination:shell::Destination::Servers,fonts:Default::default(),panes:None,#[cfg(feature="webrtc")]frames:HashMap::new()}));
|
||||
{let runtime=runtime.clone();window.window().on_close_requested(move||{runtime.release_held();runtime.platform_event(crate::platform::lifecycle::PlatformEvent::Quit);slint::CloseRequestResponse::KeepWindowShown});}
|
||||
window.show()?;
|
||||
let startup_error=Rc::new(RefCell::new(None));
|
||||
@@ -68,10 +77,15 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
|
||||
let timer=slint::Timer::default();let tick=update.clone();timer.start(slint::TimerMode::Repeated,Duration::from_millis(16),move||tick());update();
|
||||
Ok(UiAttachment{window,runtime,generation,_bindings:bindings,_timer:timer,startup_error,#[cfg(not(any(target_os="android",target_os="ios")))]_desktop:desktop,#[cfg(not(any(target_os="android",target_os="ios")))]desktop_task,#[cfg(target_os="ios")]_apple:apple,#[cfg(target_os="android")]_accessibility:accessibility})
|
||||
}
|
||||
fn report(runtime:&AppRuntime,error:crate::services::ServiceError){if let Some(ctx)=runtime.services.lock().expect("runtime services").upgrade(){let _=ctx.events.try_send(crate::app::runtime::events::ServiceEvent::Effect(UiEffect::Error(error)));}}
|
||||
fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
||||
let mut feedback_changed=false;
|
||||
while let Ok(feedback)=bindings.feedback.try_recv(){
|
||||
feedback_changed=true;
|
||||
bindings.dispatch_error=feedback.result.as_ref().err().map(|error|error.message.clone());
|
||||
if let(Some((id,target)),Err(error))=(feedback.form,feedback.result){bindings.shell.complete(ui,&id,&target,Err(error.message));}
|
||||
}
|
||||
let snapshot=runtime.snapshot();let changed=bindings.revision!=snapshot.revision;
|
||||
if changed{if let Err(error)=bindings.fonts.synchronize(&snapshot){report(runtime,error);}apply_theme(ui,&snapshot);let panes=(snapshot.settings.prefs["sidebarWidth"].as_i64().filter(|n|*n>0).unwrap_or(270) as i32,snapshot.settings.prefs["serverPaneWidth"].as_i64().filter(|n|*n>0).unwrap_or(500) as i32);if bindings.panes!=Some(panes){ui.global::<ShellBridge>().set_sidebar_width(panes.0 as f32);ui.global::<ShellBridge>().set_server_width(panes.1 as f32);bindings.panes=Some(panes);}bindings.revision=snapshot.revision;}
|
||||
if changed{if let Err(error)=bindings.fonts.synchronize(&snapshot){bindings.dispatch_error=Some(error.message);}apply_theme(ui,&snapshot);let panes=(snapshot.settings.prefs["sidebarWidth"].as_i64().filter(|n|*n>0).unwrap_or(270) as i32,snapshot.settings.prefs["serverPaneWidth"].as_i64().filter(|n|*n>0).unwrap_or(500) as i32);if bindings.panes!=Some(panes){ui.global::<ShellBridge>().set_sidebar_width(panes.0 as f32);ui.global::<ShellBridge>().set_server_width(panes.1 as f32);bindings.panes=Some(panes);}bindings.revision=snapshot.revision;}
|
||||
let mut new_frames=Vec::new();
|
||||
#[cfg(feature="webrtc")]
|
||||
{
|
||||
@@ -90,6 +104,8 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
||||
if snapshot.destination!=bindings.destination{bindings.shell.navigate(ui,snapshot.destination);bindings.destination=snapshot.destination;}
|
||||
if changed{settings::present(ui,&bindings.settings,settings::build(&snapshot.settings,&snapshot.settings_view,&snapshot.catalog));chat::present(ui,&bindings.chat,snapshot.chat.clone());}
|
||||
}
|
||||
if changed&&snapshot.bootstrap==crate::app::runtime::model::BootstrapState::Failed{bindings.dispatch_error=None;bindings.shell.failed(ui);}
|
||||
if feedback_changed||bindings.dispatch_error.is_some(){ui.global::<ShellBridge>().set_error(bindings.dispatch_error.as_deref().unwrap_or(&snapshot.error).into());}
|
||||
if !changed&&!new_frames.is_empty(){bindings.shell.update_frames(ui,&new_frames);}
|
||||
{let shell=ui.global::<ShellBridge>();let theme=ui.global::<Theme>();let compact=ui.window().size().width as f32/ui.window().scale_factor()-theme.get_safe_left()-theme.get_safe_right()<600.;let visible=(shell.get_destination()==1||shell.get_destination()==0&&shell.get_stage()==1&&(!compact||shell.get_depth()>0))&&!ui.global::<crate::MarkupBridge>().get_visible();chat::set_visibility(&bindings.chat,visible);}
|
||||
for effect in runtime.drain_effects(){match effect{
|
||||
@@ -118,6 +134,7 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
||||
UiEffect::Platform(crate::platform::lifecycle::PlatformEvent::Focus{focused:false,..}|crate::platform::lifecycle::PlatformEvent::Visibility{visible:false,..}|crate::platform::lifecycle::PlatformEvent::AndroidCallAudio{..})=>ui.invoke_focus_lost(),
|
||||
_=>{}
|
||||
}}
|
||||
if (changed||feedback_changed)&&snapshot.bootstrap==crate::app::runtime::model::BootstrapState::Failed{ui.global::<ShellBridge>().set_error(snapshot.error.clone().into());}
|
||||
}
|
||||
fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
|
||||
use crate::services::themes::TokenValue;
|
||||
@@ -134,3 +151,7 @@ fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
|
||||
let base=match resolved.values.get("--tsv-font-size"){Some(TokenValue::LengthPx(size))=>*size,_=>15.};let size=match prefs["displaySize"].as_str(){Some("small")=>13./15.,Some("large")=>17./15.,_=>1.};theme.set_font_size(base*snapshot.text_scale*size);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))]
|
||||
#[path="application_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,43 @@
|
||||
use super::*;
|
||||
use crate::{DialogBridge,app::runtime::{RuntimeCommand,model::BootstrapState}};
|
||||
use slint::{Model,platform::{Platform,WindowAdapter,software_renderer::{MinimalSoftwareWindow,RepaintBufferType}}};
|
||||
use std::sync::{Mutex,Weak,atomic::{AtomicBool,AtomicU64}};
|
||||
|
||||
struct TestPlatform;
|
||||
impl Platform for TestPlatform{
|
||||
fn create_window_adapter(&self)->Result<Rc<dyn WindowAdapter>,slint::PlatformError>{
|
||||
let window=MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer);window.set_size(slint::PhysicalSize::new(360,760));Ok(window)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_contract_ui_dispatch_rejection_and_terminal_failure_are_visible_without_services(){
|
||||
slint::platform::set_platform(Box::new(TestPlatform)).unwrap();
|
||||
let(commands,mut incoming)=tokio::sync::mpsc::channel(1);
|
||||
assert!(commands.try_send(RuntimeCommand::Detached(0)).is_ok()); // real bounded queue, deliberately full
|
||||
let(cancel,_cancelled)=tokio::sync::watch::channel(false);
|
||||
let mut snapshot=Snapshot::default();snapshot.revision=1;snapshot.bootstrap=BootstrapState::Username;snapshot.loading=false;snapshot.ready=true;
|
||||
snapshot.profile_form=Some(shell::forms::form("onboarding",shell::Operation::CreateProfile,shell::Target::application(),&snapshot.catalog).unwrap());
|
||||
let(snapshots_tx,snapshots)=tokio::sync::watch::channel(Arc::new(snapshot));
|
||||
let(_effects_tx,effects)=tokio::sync::mpsc::channel(1);let(_finished_tx,finished)=tokio::sync::watch::channel(None);
|
||||
let directory=tempfile::tempdir().unwrap();
|
||||
let runtime=Arc::new(AppRuntime{config:crate::AppConfig::isolated(directory.path().join("native")),commands,cancel,snapshots,effects:Mutex::new(effects),services:Mutex::new(Weak::new()),wake:Mutex::new(None),pending_wake:AtomicBool::new(false),active_ui:AtomicU64::new(0),finished,worker:Mutex::new(None),desktop:Mutex::new(None)});
|
||||
let attachment=bind(runtime.clone(),0).unwrap();let ui=attachment.window();let dialog=ui.global::<DialogBridge>();
|
||||
assert!(runtime.services.lock().unwrap().upgrade().is_none());assert!(dialog.get_visible());
|
||||
dialog.invoke_edit("nickname".into(),"Native User".into());dialog.invoke_submit();assert!(dialog.get_busy());
|
||||
update(ui,&runtime,&mut attachment._bindings.borrow_mut());
|
||||
assert!(!dialog.get_busy());assert!(dialog.get_error().contains("queue is full or stopped"));assert!(dialog.get_visible());
|
||||
let mut unrelated=(*runtime.snapshot()).clone();unrelated.revision+=1;unrelated.status="Unrelated lifecycle update".into();snapshots_tx.send_replace(Arc::new(unrelated));
|
||||
update(ui,&runtime,&mut attachment._bindings.borrow_mut());
|
||||
assert!(!dialog.get_busy());assert!(dialog.get_error().contains("queue is full or stopped"));
|
||||
assert!(dialog.get_fields().iter().any(|field|field.id=="nickname"&&field.value=="Native User"));
|
||||
incoming.try_recv().unwrap();dialog.invoke_submit();assert!(dialog.get_busy());
|
||||
update(ui,&runtime,&mut attachment._bindings.borrow_mut());assert!(dialog.get_busy(),"accepted enqueue is not completion");
|
||||
let mut unrelated=(*runtime.snapshot()).clone();unrelated.revision+=1;snapshots_tx.send_replace(Arc::new(unrelated));
|
||||
update(ui,&runtime,&mut attachment._bindings.borrow_mut());assert!(dialog.get_busy(),"snapshots cannot acknowledge submission");
|
||||
// Exercise the revision-gated consumer when the actor cannot deliver a final form effect.
|
||||
let mut terminal=(*runtime.snapshot()).clone();terminal.revision+=1;terminal.bootstrap=BootstrapState::Failed;terminal.profile_form=None;terminal.dialog=None;terminal.error="Your profile is saved, but application services could not start".into();
|
||||
snapshots_tx.send_replace(Arc::new(terminal));update(ui,&runtime,&mut attachment._bindings.borrow_mut());
|
||||
assert!(!dialog.get_busy());assert!(!dialog.get_visible(),"a terminal actor cannot accept another create submission");
|
||||
assert!(ui.global::<ShellBridge>().get_error().contains("profile is saved"));
|
||||
}
|
||||
+21
-3
@@ -9,11 +9,18 @@ use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc};
|
||||
struct Editor { form: Form, raw: BTreeMap<String,String>, dirty: BTreeMap<String,bool>, confirmation: String }
|
||||
impl Editor {
|
||||
fn new(form:Form)->Self { let raw=form.fields.iter().map(|f|(f.id.clone(),forms::value_text(&f.value))).collect(); Self {form,raw,dirty:BTreeMap::new(),confirmation:String::new()} }
|
||||
fn merge(&mut self, form:Form) {
|
||||
fn merge(&mut self, mut form:Form) {
|
||||
if self.form.id!=form.id || self.form.target!=form.target || self.form.acknowledged_revision!=form.acknowledged_revision { *self=Self::new(form); return; }
|
||||
for field in &form.fields { if !self.dirty.contains_key(&field.id) { self.raw.insert(field.id.clone(),forms::value_text(&field.value)); } }
|
||||
// Presentation snapshots are not submission acknowledgements. Only complete() (or an
|
||||
// explicit acknowledged revision) ends local busy/error state for this captured editor.
|
||||
form.busy|=self.form.busy;
|
||||
if form.error.is_empty(){form.error=self.form.error.clone();}
|
||||
self.form=form;
|
||||
}
|
||||
fn complete(&mut self,result:Result<(),String>)->bool{
|
||||
match result{Ok(())=>true,Err(error)=>{self.form.busy=false;self.form.error=error;false}}
|
||||
}
|
||||
}
|
||||
struct State {
|
||||
presentation:ShellPresentation,
|
||||
@@ -58,7 +65,7 @@ fn projected_field(field:&Field,raw:&str)->ShellField {
|
||||
}
|
||||
fn project_editor(ui:&AppWindow,state:&mut State) {
|
||||
let bridge=ui.global::<DialogBridge>();
|
||||
let Some(editor)=&state.editor else {bridge.set_visible(false);return};
|
||||
let Some(editor)=&state.editor else {bridge.set_visible(false);bridge.set_busy(false);return};
|
||||
let c=state.presentation.catalog;
|
||||
bridge.set_visible(true);bridge.set_title(editor.form.title.clone().into());bridge.set_description(editor.form.description.clone().into());
|
||||
bridge.set_onboarding(editor.form.operation==Operation::CreateProfile);
|
||||
@@ -243,7 +250,9 @@ impl ShellBinding {
|
||||
s.presentation=p;project_editor(ui,&mut s);
|
||||
}
|
||||
/// Explicit result for a captured submission, not a background snapshot. Failure retains edits.
|
||||
pub fn complete(&self,ui:&AppWindow,id:&str,target:&Target,result:Result<(),String>){let mut s=self.state.borrow_mut();if let Some(editor)=&mut s.editor{if editor.form.id!=id||&editor.form.target!=target{return}match result{Ok(())=>s.editor=None,Err(error)=>{editor.form.busy=false;editor.form.error=error;}}}project_editor(ui,&mut s);}
|
||||
pub fn complete(&self,ui:&AppWindow,id:&str,target:&Target,result:Result<(),String>){let mut s=self.state.borrow_mut();if let Some(editor)=&mut s.editor{if editor.form.id!=id||&editor.form.target!=target{return}if editor.complete(result){s.editor=None;}}project_editor(ui,&mut s);}
|
||||
/// A terminal runtime failure is authoritative even when no form effect could be delivered.
|
||||
pub(crate) fn failed(&self,ui:&AppWindow){let mut s=self.state.borrow_mut();s.editor=None;project_editor(ui,&mut s);}
|
||||
pub fn release_holds(&self){release_hold(&mut self.state.borrow_mut(),&self.emit);}
|
||||
}
|
||||
impl Drop for ShellBinding{fn drop(&mut self){self.release_holds();}}
|
||||
@@ -283,6 +292,15 @@ mod tests {
|
||||
assert_eq!(editor.raw.get("name").map(String::as_str),Some(""));assert!(editor.dirty.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn bootstrap_contract_pending_submission_and_failed_ack_survive_snapshots(){
|
||||
let form=forms::form("onboarding",Operation::CreateProfile,Target::application(),&super::super::i18n::Catalog::default()).unwrap();
|
||||
let mut editor=Editor::new(form.clone());editor.raw.insert("nickname".into(),"Retained User".into());editor.dirty.insert("nickname".into(),true);
|
||||
editor.form.busy=true;editor.merge(form.clone());assert!(editor.form.busy,"a snapshot must not permit duplicate creation");
|
||||
assert!(!editor.complete(Err("Profile saved; services failed".into())));
|
||||
editor.merge(form);assert!(!editor.form.busy);assert_eq!(editor.form.error,"Profile saved; services failed");
|
||||
assert_eq!(editor.raw["nickname"],"Retained User");
|
||||
}
|
||||
#[test]
|
||||
fn compact_detail_navigation_only_reveals_read_views() {
|
||||
for operation in [Operation::FileBrowse,Operation::FileRefresh,Operation::ChannelInfo,Operation::TransferList,Operation::ServerIcons] {
|
||||
assert!(opens_detail(operation));
|
||||
|
||||
@@ -17,6 +17,14 @@ val buildChannel = providers.gradleProperty("buildChannel").getOrElse("direct")
|
||||
require(buildChannel in listOf("direct", "google-play", "development")) { "Unsupported Android distribution channel" }
|
||||
val debugKey = layout.buildDirectory.file("native-test/debug.keystore")
|
||||
require(abi in listOf("arm64-v8a", "x86_64")) { "Only ARM64 production and x64 emulator are supported" }
|
||||
// This Maven helper is the Android component of the locked Rust verifier, not its Rust version.
|
||||
val rustlsPlatformVerifierVersion = "0.2.0"
|
||||
val cargoLock = providers.fileContents(layout.projectDirectory.file("../../Cargo.lock")).asText
|
||||
val lockedRustlsAndroidVersions = Regex("""(?m)^name = "rustls-platform-verifier-android"\r?\nversion = "([^"]+)"""")
|
||||
.findAll(cargoLock.get()).map { it.groupValues[1] }.toList()
|
||||
require(lockedRustlsAndroidVersions == listOf(rustlsPlatformVerifierVersion)) {
|
||||
"Android JVM verifier $rustlsPlatformVerifierVersion must match rustls-platform-verifier-android in Cargo.lock"
|
||||
}
|
||||
android {
|
||||
namespace = "dev.teamspeach.mobile"
|
||||
compileSdk = 36
|
||||
@@ -61,7 +69,14 @@ android {
|
||||
}
|
||||
}
|
||||
}
|
||||
dependencies { if (webrtcJar.isPresent) implementation(files(webrtcJar.get())) }
|
||||
dependencies {
|
||||
if (webrtcJar.isPresent) implementation(files(webrtcJar.get()))
|
||||
implementation("org.rustls:rustls-platform-verifier:$rustlsPlatformVerifierVersion") {
|
||||
version { strictly(rustlsPlatformVerifierVersion) }
|
||||
}
|
||||
// The published helper POM omits its Kotlin runtime dependencies; its AAR does not embed them.
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:2.2.10")
|
||||
}
|
||||
tasks.register("requireNativeInputs") {
|
||||
doLast {
|
||||
require(nativeJniDir.isPresent) { "xtask must supply -PnativeJniDir with verified Cargo/SDK libraries" }
|
||||
|
||||
Vendored
+2
@@ -1,3 +1,5 @@
|
||||
-keep class dev.teamspeach.mobile.** { *; }
|
||||
-keep class livekit.org.webrtc.** { *; }
|
||||
# The platform trust verifier is invoked from Rust JNI, invisible to R8 reachability.
|
||||
-keep,includedescriptorclasses class org.rustls.platformverifier.** { *; }
|
||||
-keepclasseswithmembernames class * { native <methods>; }
|
||||
@@ -1,3 +1,13 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
maven {
|
||||
url = uri("https://raw.githubusercontent.com/rustls/rustls-platform-verifier/maven-archive/android-release-support/maven/")
|
||||
content { includeModule("org.rustls", "rustls-platform-verifier") }
|
||||
}
|
||||
}
|
||||
}
|
||||
rootProject.name = "TeamsPeach"
|
||||
@@ -24,7 +24,8 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
private int requestedPermission;
|
||||
private final Rect insetWindow = new Rect(), visibleWindow = new Rect();
|
||||
private final int[] decorLocation = new int[2];
|
||||
private final ViewTreeObserver.OnGlobalLayoutListener insetLayout = this::reportInsets;
|
||||
private final Runnable insetReport = this::reportInsets;
|
||||
private final ViewTreeObserver.OnGlobalLayoutListener insetLayout = this::scheduleInsets;
|
||||
private int insetTop, insetRight, insetBottom, insetLeft, insetKeyboard;
|
||||
private float insetScale;
|
||||
private long insetGeneration;
|
||||
@@ -39,11 +40,17 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
if (Build.VERSION.SDK_INT == 33) getOnBackInvokedDispatcher().registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, () -> PlatformBridge.nativeBack(generation));
|
||||
// Observe without replacing Slint's decor listener or IME animation callback.
|
||||
accessibility.setOnApplyWindowInsetsListener((view, insets) -> {
|
||||
reportInsets();
|
||||
scheduleInsets();
|
||||
return insets;
|
||||
});
|
||||
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(insetLayout);
|
||||
}
|
||||
private void scheduleInsets() {
|
||||
// Read root insets after dispatch/layout commits them, including IME dismissal.
|
||||
View decor = getWindow().getDecorView();
|
||||
decor.removeCallbacks(insetReport);
|
||||
decor.post(insetReport);
|
||||
}
|
||||
private void reportInsets() {
|
||||
View decor = getWindow().getDecorView();
|
||||
if (generation == 0 || !decor.isAttachedToWindow()
|
||||
@@ -103,6 +110,7 @@ public final class TeamsPeachActivity extends NativeActivity {
|
||||
@Override protected void onDestroy() {
|
||||
CaptureBridge.unbindActivity(this);
|
||||
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(insetLayout);
|
||||
getWindow().getDecorView().removeCallbacks(insetReport);
|
||||
if (picker > 0) PlatformBridge.nativePick(picker, null, "activity_destroyed");
|
||||
if (permissionRequest > 0) PlatformBridge.nativeText(permissionRequest, null, "activity_destroyed");
|
||||
if (pipToken != 0) PlatformBridge.nativePip(pipToken, false, true);
|
||||
|
||||
@@ -184,6 +184,9 @@ fn payload(root:&Path,directory:&Path,target:Target<'_>,nsis:bool)->Result<Value
|
||||
if target.os=="android"{
|
||||
let mut classes=String::new();for path in all.iter().filter(|p|p.extension().is_some_and(|s|s=="dex")){classes.push_str(&capture(Command::new("dexdump").arg(path))?);}
|
||||
if !classes.contains("Llivekit/org/webrtc/ContextUtils;"){return Err("APK/AAB lacks matching prefixed WebRTC Java classes".into());}
|
||||
for class in ["Lorg/rustls/platformverifier/CertificateVerifier;", "Lorg/rustls/platformverifier/VerificationResult;", "Lorg/rustls/platformverifier/StatusCode;"] {
|
||||
if !classes.lines().any(|line|line.trim_start().starts_with("Class descriptor")&&line.contains(class)){return Err(format!("APK/AAB lacks Android platform TLS helper class {class}"));}
|
||||
}
|
||||
if classes.contains("Landroid/webkit/WebView;"){return Err("Android payload references browser WebView".into());}
|
||||
}
|
||||
Ok(json!({"binaries":binaries,"files":all.len()}))
|
||||
|
||||
Reference in new issue
Block a user