Add isolated Liam persona test APK profile

This commit is contained in:
zenord
2026-10-14 17:50:40 +08:00
parent 5a7be557d0
commit 4c70ff665e
12 changed files with 197 additions and 54 deletions
+4 -4
View File
@@ -8,9 +8,9 @@ def characterProfileId = providers.gradleProperty('characterProfile').orNull ?:
def characterCatalogFile = rootProject.file('manifests/character-build-profiles.json') def characterCatalogFile = rootProject.file('manifests/character-build-profiles.json')
def characterCatalog = new groovy.json.JsonSlurper().parse(characterCatalogFile) def characterCatalog = new groovy.json.JsonSlurper().parse(characterCatalogFile)
def characterProfile = characterCatalog.profiles[characterProfileId] def characterProfile = characterCatalog.profiles[characterProfileId]
if (!characterProfile || !(characterProfileId in ['main', 'lvbu-test'])) throw new GradleException('Unknown trusted character profile') if (!characterProfile || !(characterProfileId in ['main', 'lvbu-test', 'liam-test'])) throw new GradleException('Unknown trusted character profile')
if (characterProfileId != 'main') layout.buildDirectory.set(file('build/characters/' + characterProfileId)) if (characterProfileId != 'main') layout.buildDirectory.set(file('build/characters/' + characterProfileId))
if (characterProfileId == 'lvbu-test' && gradle.startParameter.taskNames.any { it.toLowerCase().contains('release') }) throw new GradleException('Lvbu profile is debug-only') if (characterProfileId != 'main' && gradle.startParameter.taskNames.any { it.toLowerCase().contains('release') }) throw new GradleException('Persona test profile is debug-only')
// Populated once by scripts/prepare-expression.sh from stable Maven versions, then pinned. // Populated once by scripts/prepare-expression.sh from stable Maven versions, then pinned.
def expressionVersions = new Properties() def expressionVersions = new Properties()
@@ -40,7 +40,7 @@ def avatarPlaybackDiagnostic = providers.gradleProperty('avatarPlaybackDiagnosti
def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true' def avatarRuntimeFix = providers.gradleProperty('avatarRuntimeFix').orNull == 'true'
def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true' def avatarFullActionCandidate = providers.gradleProperty('avatarFullActionCandidate').orNull == 'true'
def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger() def actionVersionCode = (providers.gradleProperty('actionVersionCode').orNull ?: '16').toInteger()
if (characterProfileId == 'lvbu-test' && (!avatarUserAssetCandidate || !avatarUserNetworkActions || actionVersionCode < 34)) throw new GradleException('Lvbu test requires existing exact black media/network flags and fresh code >=34') if (characterProfileId != 'main' && (!avatarUserAssetCandidate || !avatarUserNetworkActions || actionVersionCode < characterProfile.minimumVersionCode)) throw new GradleException('Persona test requires existing exact black media/network flags and its minimum version code')
if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) { if (avatarActionCandidate && (!avatarMouthCandidate || actionVersionCode < 16)) {
throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16') throw new GradleException('Action stage requires the existing mouth runtime and a fresh code >=16')
} }
@@ -182,7 +182,7 @@ android {
tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig, stagePackagedAssets) } tasks.named('preBuild').configure { dependsOn(generateNetworkSecurityConfig, stagePackagedAssets) }
androidComponents { androidComponents {
beforeVariants(selector().withBuildType('release')) { variant -> beforeVariants(selector().withBuildType('release')) { variant ->
if (characterProfileId == 'lvbu-test') variant.enable = false if (characterProfileId != 'main') variant.enable = false
} }
} }
dependencies { dependencies {
@@ -27,7 +27,7 @@ object DialogueProtocol {
const val DOWNLINK_PCM_BYTES = 1_920 const val DOWNLINK_PCM_BYTES = 1_920
fun hello(actionPackSha: String? = null,pendingPackSha: String?=null,persona: String="default"): String { fun hello(actionPackSha: String? = null,pendingPackSha: String?=null,persona: String="default"): String {
require(persona in setOf("default","lvbu")) require(persona in setOf("default","lvbu","liam"))
return JSONObject() return JSONObject()
.put("type", "hello") .put("type", "hello")
.put("codec", "pcm16") .put("codec", "pcm16")
+78
View File
@@ -0,0 +1,78 @@
# Liam 独立 persona 测试包
2026-10-14。基线 `5a7be557d08121909f253c424764b5f7b5e84437`,开始时本地与 origin/main 一致、工作树干净。在已交付吕布构建上增加第三个可信 profile,不实现 APK 内角色切换或任意 persona 注册。
## 交付身份
| 字段 | 实际值 |
|---|---|
| profile / 显示名 | liam-test / 声伴·Liam测试 |
| applicationId | com.gorios.lanvoice.liamtest |
| versionName / versionCode | 0.7.14-liam-test / 35 |
| HELLO persona | liam,显式发送 |
| 媒体身份 | a01,仍为 code33 黑裙 correct03,不冒充 Liam 肖像 |
| APK | lan-voice-v0714-liam-test-code35-arm64-debug.apk |
| APK 字节数 | 61,386,974 |
| SHA256 | fa462046e65c9ed0acac21f19e6528b73cdc79fecb238d98b80e368d5b7a2efc |
| 下载 | http://192.168.31.124:8080/lan-voice-v0714-liam-test-code35-arm64-debug.apk |
| 校验文件 | 同下载 URL 加 .sha256 |
| debug 证书 SHA256 | b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1 |
实际 APK 的 manifest、DEX、签名和 HTTP 返回字节均已核验;min26、target34、仅 arm64-v8a。独立 AndroidX authority 为 `com.gorios.lanvoice.liamtest.androidx-startup`;无 sharedUserId,禁用备份,prefs、权限及私有校验 receipt 按 appId 隔离。
## 最小实现与资产保留
- `manifests/character-build-profiles.json` 增加 liam-test,复用 black-correct03 媒体条目。主包默认 profile 和吕布身份不改。
- `app/build.gradle` 和 `scripts/select-character-assets.py` 接受第三个可信 profile;测试 profile 仅 debug,Liam 最小 code35。输出在 `app/build/characters/liam-test/`,与 main、lvbu-test 隔离。
- `DialogueProtocol.hello` 允许 liam;MainActivity → VoiceSession → DialogueClient 鉴权回调沿用现有 persona 传递。客户端不发送 voice_id 或旧 conversation_id。
- `scripts/package-character-test.py` 支持按 profile 打包、校验和发布,拒绝覆盖已有同名 APK;实际 DEX 核 appId/persona/root/pin/bootstrap/版本及生命周期标志,逐路径核包内文件。
媒体 index pin 保持 `208f703ed92bf795bfeb78a1cef89b67bed2e45da80038a56157fd1ecd4cfa93`。4051 个 assets 和两个 poster 与冻结 code33 APK 逐字节相同;5 body、8 own-mouth 桥及两 dance 的原合同不变。594 历史文件保留原因及精确选包/恢复方法见 `docs/CHARACTER_LVBU_TEST.md`。不生成素材、不改原包 metadata、不提交人物或音乐二进制。
发布后再次核旧主包 SHA 为 `ba00023507e8f396f95e165f1aa744aba3a51d5072cbb8d5c2504a6159c75157`,旧吕布包 SHA 为 `10a4542feecf726bcdf1a0d63253d2e3a3526d2c866db9f415411fb91367a2c9`;两产物没有覆盖。
## 服务端登记、隔离握手与生命周期
2026-10-14 09:37:22 UTC 只读核服务端 Liam 登记:voice_id 为 `e50a8ac2-08e9-57ae-be13-2aa3a32afc3d` 且 active,persona manifest 与 lorebook language 均为 en。声音由服务端 resolver 锁定,不依赖全局 active_profile,也不在客户端写入该 UUID。
用户在服务端独立增加 Liam 后,仓库内旧 gateway 归档尚未包含 Liam。此次没有修改该归档、live 源码、注册表或配置,没有重启 gateway。有限握手使用 live canonical 源码的只读副本 `.runtime/liam-canonical-gateway/`,21 个文件由 `SNAPSHOT.json` 逐文件 SHA 固定;副本和日志不入 Git,不复制私人 voice manifest。
实际源 hashes:
| 文件 | SHA256 |
|---|---|
| gateway.py | 0c4c975e00ec8597d408f4d5dc9301cbecab9ff646792434842ea99c4f448657 |
| persona_resolver.py | ea69541c9abcfd175025acb6c5255cccaaff5cb85104d3cf5a68de876df7aecf |
| reviewed_action_packs.json | 83ae8ab7dca27ffc329bfba3dd44a6b5b14ddf2716436e2844df46b7eb3228d3 |
| llm_provider.py | b3cf6ab5e4c953ef13dc00802f4594055164c89b10b875dda44f071ad1ede082 |
| personas/liam.lorebook.json | 6808a941aedad9bb9ea7451438f54556739e33ea0be8a1de3a565b530de7b942 |
隔离 ASGI 握手使用临时 synthetic voice/history 和禁止推理的模型替身,确认实际 Dialogue 的 Liam language=en、显式 persona 绕开 active_profile、服务端锁 voice、fresh CID、完整/待准备 pin 能力以及断连 busy 清理。登记 UUID 是独立只读核验,握手未合成该声音,不能代替听审。0 ASR、0 LLM、0 TTS 调用。
Liam 复用吕布 `permissionConnectionRetention=false`:MainActivity.onPause 先 session.background 结束旧轮、停止录音/播放/action 并断 WS,再 closeCamera;旧回调由既有 generation 隔离。未更改相机/presence/time/provider/TTS。gateway 仍全局单 WS busy,三个 APK 应依次使用。此新包不能修复 code33 主包在异常 HAL 下先关闭相机而拖延断连的问题。
## 实际验证
| 检查 | 本轮结果与边界 |
|---|---|
| JVM/UI | 11 个入口通过;含 Liam/Lvbu 生产 session/client 后台释放、权限暂停、迟到 capture/playback/HELLO 隔离,757 clock 与 103 native assertions 保留 |
| 包装 | 全量 75 项通过;三个 profile inventory 一致、身份/输出隔离、pin/root/bootstrap/poster、未知目录排除及旧包回归 |
| GLES | 13 个选定 runtime 各 40 项,合计 520 项离屏 EGL/GLES pixel golden;另 30 项 720 边界/Fit 检查通过;采样检查不表示每个素材帧或手机 GPU 都已验证 |
| 握手 | 6 组实际 DialogueClient AUTH→生产 HELLO,8 次 canonical ASGI WS 握手通过,default/lvbu/liam × ready/pending;duplicate AUTH、pending 更新、旧 socket fence 保留 |
| 实际 APK 回放 | 生产 loader/View/renderer 在真实包字节上通过;5 body、8 桥、两 dance、30s idle 合法轮换、newturn return、action 独占层;Surface/codec/music/record confirmation 为 host doubles |
| 启动 loader | 实际包冷校验 main asset reads=0、patch reads=3425;可信 receipt 重载 patch reads=0,同进程不重复加载;非手机性能测量 |
| 构建/安装 | assembleDebug 和 compileDebugAndroidTestKotlin 通过;instrumentation 未执行,未安装设备 |
```bash
# 构建示例;已发布的 code35 不得再次覆盖。
python3 scripts/package-character-test.py --profile liam-test --version-code 35 \
--build --output logs/liam-build-verification.json
# 必须用包含 Liam 登记的真实源码副本;默认旧归档只覆盖它已注册的 persona。
/home/ubuntu/miniconda3/envs/gori-speech/bin/python scripts/check-character-handshake.py \
--gateway-source .runtime/liam-canonical-gateway
```
协调者核 hash 后 USB 安装:先退出当前通话 APK,再启动 Liam,正常模式可能在已授权时自动启麦克风/相机;offline 只测媒体,不测英语 persona 或 TTS。确认 HELLO Liam、新 CID、实际英语回复和登记音色,退后台后再开吕布或主包确认 busy 已释放、历史不串人格。真实声音、人设、摄像头、Android GPU 和切包时序尚未验证。
回滚只需停止或卸载独立 Liam 包,继续使用既有主包/吕布包;不清旧 App 数据、不改后端配置。原 main、吕布和 camera-probe 产物及旧媒体均保留。本轮素材生成和模型调用均为零。
+12
View File
@@ -19,7 +19,19 @@
"permissionConnectionRetention": false, "permissionConnectionRetention": false,
"mediaSelection": "black-correct03", "mediaSelection": "black-correct03",
"versionSuffix": "-lvbu-test", "versionSuffix": "-lvbu-test",
"minimumVersionCode": 34,
"settingsNote": "吕布人设与服务端绑定音色测试;外观仍为黑裙角色,媒体身份为 a01。" "settingsNote": "吕布人设与服务端绑定音色测试;外观仍为黑裙角色,媒体身份为 a01。"
},
"liam-test": {
"applicationId": "com.gorios.lanvoice.liamtest",
"appName": "声伴·Liam测试",
"persona": "liam",
"allowBackup": false,
"permissionConnectionRetention": false,
"mediaSelection": "black-correct03",
"versionSuffix": "-liam-test",
"minimumVersionCode": 35,
"settingsNote": "Liam 英语人设与服务端绑定音色测试;外观仍为黑裙角色,媒体身份为 a01。"
} }
}, },
"mediaBundles": { "mediaBundles": {
+45 -17
View File
@@ -5,7 +5,9 @@ Run with the existing gori-speech interpreter. Compiles Kotlin against determini
Android main/transport/JSON adapters. All server identities and history are synthetic. Android main/transport/JSON adapters. All server identities and history are synthetic.
""" """
import ast import ast
import argparse
import asyncio import asyncio
import hashlib
import json import json
from pathlib import Path from pathlib import Path
import shutil import shutil
@@ -14,6 +16,20 @@ import sys
import tempfile import tempfile
ROOT=Path(__file__).resolve().parents[1] ROOT=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--gateway-source',type=Path,default=ROOT/'gateway',
help='Existing canonical source or read-only snapshot; never changes/deploys the gateway')
args=parser.parse_args()
gateway_root=args.gateway_source.resolve(strict=True)
snapshot=gateway_root/'SNAPSHOT.json'
if snapshot.exists():
for name,digest in json.loads(snapshot.read_bytes()).items():
path=(gateway_root/name).resolve(strict=True)
assert path.is_relative_to(gateway_root) and hashlib.sha256(path.read_bytes()).hexdigest()==digest,'canonical snapshot drift'
resolver=ast.parse((gateway_root/'persona_resolver.py').read_text())
registered=next(ast.literal_eval(n.value) for n in resolver.body if isinstance(n,ast.Assign) and
any(isinstance(t,ast.Name) and t.id=='PERSONAS' for t in n.targets))
personas=['default','lvbu']+(['liam'] if 'liam' in registered else [])
tree=ast.parse((ROOT/'scripts/check-reply-regressions.py').read_text()) tree=ast.parse((ROOT/'scripts/check-reply-regressions.py').read_text())
nodes=[] nodes=[]
for node in tree.body: for node in tree.body:
@@ -35,15 +51,16 @@ with tempfile.TemporaryDirectory(prefix='character-handshake-') as folder:
'-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',ns['cp'], '-no-stdlib','-no-reflect','-jvm-target','17','-nowarn','-classpath',ns['cp'],
'-d',str(stage/'classes'),*map(str,files)],check=True) '-d',str(stage/'classes'),*map(str,files)],check=True)
hello_file=stage/'hello.jsonl' hello_file=stage/'hello.jsonl'
subprocess.run([ns['JAVA'],'-Dcharacter.helloFile='+str(hello_file),'-cp', subprocess.run([ns['JAVA'],'-Dcharacter.helloFile='+str(hello_file),
'-Dcharacter.personas='+','.join(personas),'-cp',
str(stage/'classes')+':'+ns['cp'],'HandshakeCheckKt'],check=True,timeout=30) str(stage/'classes')+':'+ns['cp'],'HandshakeCheckKt'],check=True,timeout=30)
hellos=[json.loads(row) for row in hello_file.read_text().splitlines()] hellos=[json.loads(row) for row in hello_file.read_text().splitlines()]
for path in (ROOT/'gateway').glob('*.py'):shutil.copyfile(path,stage/path.name) for path in gateway_root.glob('*.py'):shutil.copyfile(path,stage/path.name)
shutil.copyfile(ROOT/'gateway/reviewed_action_packs.json',stage/'reviewed_action_packs.json') shutil.copyfile(gateway_root/'reviewed_action_packs.json',stage/'reviewed_action_packs.json')
shutil.copytree(ROOT/'gateway/personas',stage/'personas') shutil.copytree(gateway_root/'personas',stage/'personas')
(stage/'web').mkdir() (stage/'web').mkdir()
(stage/'.runtime/personas').mkdir(parents=True) (stage/'.runtime/personas').mkdir(parents=True)
for persona in ('lvbu','yangmi_fiction'): for persona in [p for p in personas if p!='default']+['yangmi_fiction']:
(stage/'.runtime/personas'/ (persona+'.json')).write_text(json.dumps({'voice_id':'synthetic-'+persona})) (stage/'.runtime/personas'/ (persona+'.json')).write_text(json.dumps({'voice_id':'synthetic-'+persona}))
# New interpreter: imports never reach a live gateway or its private configuration. # New interpreter: imports never reach a live gateway or its private configuration.
runner=r''' runner=r'''
@@ -62,34 +79,45 @@ class NoInferenceModel:
def infer(self,*args): raise AssertionError('no ASR/VAD/model calls authorized by this fixture') def infer(self,*args): raise AssertionError('no ASR/VAD/model calls authorized by this fixture')
state.model=NoInferenceModel();state.client=None;state.guests=GuestSessions() state.model=NoInferenceModel();state.client=None;state.guests=GuestSessions()
state.guest_enabled=False;state.lan_open=False;state.debug=None state.guest_enabled=False;state.lan_open=False;state.debug=None
state.voices=[dict(id=v) for v in (gateway.DEFAULT_VOICE_ID,'synthetic-lvbu','synthetic-yangmi_fiction')] state.voices=[dict(id=v) for v in (gateway.DEFAULT_VOICE_ID,'synthetic-lvbu','synthetic-yangmi_fiction','synthetic-liam')]
history=History(Path('synthetic.sqlite3'));asyncio.run(history.initialize());state.history=history history=History(Path('synthetic.sqlite3'));asyncio.run(history.initialize());state.history=history
client=TestClient(gateway.app) # no lifespan/model loading client=TestClient(gateway.app) # no lifespan/model loading
hellos=[json.loads(row) for row in Path('hello.jsonl').read_text().splitlines()] hellos=[json.loads(row) for row in Path('hello.jsonl').read_text().splitlines()]
ids=[] ids=[]
sessions=[]
original=gateway.Dialogue.send_history
async def observe_session(self):
sessions.append((self.persona,getattr(self,'persona_language','zh'),self.voice_id))
await original(self)
gateway.Dialogue.send_history=observe_session
for hello in hellos: for hello in hellos:
with patch('gateway.load_active_profile',return_value={'persona':'yangmi_fiction','voice_id':'synthetic-yangmi_fiction'}) as profile: with patch('gateway.load_active_profile',return_value={'persona':'yangmi_fiction','voice_id':'synthetic-yangmi_fiction'}) as profile:
with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws: with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws:
ws.send_json(dict(type='auth',token=state.token));assert ws.receive_json()['type']=='auth' ws.send_json(dict(type='auth',token=state.token));assert ws.receive_json()['type']=='auth'
ws.send_json(hello) ws.send_json(hello)
ack=ws.receive_json();assert ack['type']=='hello' ack=ws.receive_json();assert ack['type']=='hello'
assert ack['voice_id']==('synthetic-lvbu' if hello['persona']=='lvbu' else 'synthetic-yangmi_fiction') persona=hello['persona']
assert profile.call_count==(0 if hello['persona']=='lvbu' else 1) expected_voice='synthetic-'+(persona if persona!='default' else 'yangmi_fiction')
assert ack['voice_id']==expected_voice
assert profile.call_count==(1 if persona=='default' else 0)
assert ack['action_available']==('action_pack_sha256' in hello) assert ack['action_available']==('action_pack_sha256' in hello)
assert ack['action_pending']==('action_pending_pack_sha256' in hello) assert ack['action_pending']==('action_pending_pack_sha256' in hello)
assert ack['conversation_id'] not in ids;ids.append(ack['conversation_id']) assert ack['conversation_id'] not in ids;ids.append(ack['conversation_id'])
assert ws.receive_json()['type']=='history' assert ws.receive_json()['type']=='history'
assert sessions[-1]==('yangmi_fiction' if persona=='default' else persona,
'en' if persona=='liam' else 'zh',expected_voice)
assert state.busy is False, 'disconnect did not release existing gateway busy owner' assert state.busy is False, 'disconnect did not release existing gateway busy owner'
# A non-default persona stays server-locked even if a caller offers another voice/CID. # A non-default persona stays server-locked even if a caller offers another voice/CID.
hello=next(x for x in hellos if x['persona']=='lvbu' and 'action_pack_sha256' in x) for persona in sorted({x['persona'] for x in hellos}-{'default'}):
with patch('gateway.load_active_profile',side_effect=AssertionError('lvbu must ignore global profile')): hello=next(x for x in hellos if x['persona']==persona and 'action_pack_sha256' in x)
with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws: with patch('gateway.load_active_profile',side_effect=AssertionError('explicit persona must ignore global profile')):
ws.send_json(dict(type='auth',token=state.token));ws.receive_json() with client.websocket_connect('/ws/dialogue',headers={'Origin':'https://192.168.31.61:5011'}) as ws:
ws.send_json(dict(hello,voice_id=gateway.DEFAULT_VOICE_ID,conversation_id=ids[0])) ws.send_json(dict(type='auth',token=state.token));ws.receive_json()
ack=ws.receive_json() ws.send_json(dict(hello,voice_id=gateway.DEFAULT_VOICE_ID,conversation_id=ids[0]))
assert ack['voice_id']=='synthetic-lvbu' and ack['conversation_id'] not in ids ack=ws.receive_json()
ws.receive_json() assert ack['voice_id']=='synthetic-'+persona and ack['conversation_id'] not in ids
ws.receive_json();ids.append(ack['conversation_id'])
assert state.busy is False assert state.busy is False
print('PASS: five existing ASGI WS handshakes from actual Android HELLO; lvbu ignores active_profile, server-locks voice, fresh CID, ready/pending exact pin and disconnect busy cleanup; 0 ASR/LLM/TTS calls, synthetic-only') print('PASS: '+str(len(ids))+' canonical ASGI WS handshakes from actual Android HELLO; personas='+','.join(sorted({x["persona"] for x in hellos}))+'; explicit persona ignores active_profile, server-locks voice/language, fresh CID, ready/pending exact pin and disconnect busy cleanup; 0 ASR/LLM/TTS calls, synthetic-only')
''' '''
subprocess.run([sys.executable,'-c',runner],cwd=stage,check=True,timeout=30) subprocess.run([sys.executable,'-c',runner],cwd=stage,check=True,timeout=30)
+14 -7
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Build/verify one trusted Lvbu debug profile over unchanged code33 media. """Build/verify one trusted persona debug profile over unchanged code33 media.
No gateway mutations, voice selection, model calls or device installation. No gateway mutations, voice selection, model calls or device installation.
Default profile can be built and verified separately without publishing a main APK. Default profile can be built and verified separately without publishing a main APK.
@@ -116,8 +116,13 @@ def verify(apk, profile, version):
'actual_dex_verified': True, 'device': 'not_run', 'gateway_changed': False} 'actual_dex_verified': True, 'device': 'not_run', 'gateway_changed': False}
def artifact_name(profile, version):
require(profile in ('lvbu-test', 'liam-test'), 'main publication outside this task')
return f"lan-voice-v0714-{profile}-code{version}-arm64-debug.apk"
def publish(apk, report): def publish(apk, report):
name = f"lan-voice-v0714-lvbu-test-code{report['version_code']}-arm64-debug.apk" name = artifact_name(report['profile'], report['version_code'])
artifact = ROOT/'artifacts'/name artifact = ROOT/'artifacts'/name
with artifact.open('xb') as out, apk.open('rb') as src: with artifact.open('xb') as out, apk.open('rb') as src:
shutil.copyfileobj(src, out) shutil.copyfileobj(src, out)
@@ -136,16 +141,18 @@ def publish(apk, report):
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--profile', choices=['main', 'lvbu-test'], default='lvbu-test') parser.add_argument('--profile', choices=sorted(select.catalog()['profiles']), default='lvbu-test')
parser.add_argument('--version-code', type=int, default=34) parser.add_argument('--version-code', type=int)
parser.add_argument('--build', action='store_true') parser.add_argument('--build', action='store_true')
parser.add_argument('--publish', action='store_true') parser.add_argument('--publish', action='store_true')
parser.add_argument('--output', type=Path, required=True) parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args() args = parser.parse_args()
require(args.version_code >= 34, 'fresh character version required') minimum = select.catalog()['profiles'][args.profile].get('minimumVersionCode', 34)
require(not args.publish or args.profile == 'lvbu-test', 'main publication outside this task') args.version_code = args.version_code if args.version_code is not None else minimum
require(args.version_code >= minimum, 'fresh character version required')
require(not args.publish or args.profile != 'main', 'main publication outside this task')
if args.publish: if args.publish:
require(not (ROOT/'artifacts'/f'lan-voice-v0714-lvbu-test-code{args.version_code}-arm64-debug.apk').exists(), require(not (ROOT/'artifacts'/artifact_name(args.profile, args.version_code)).exists(),
'published character version is immutable; choose a new code') 'published character version is immutable; choose a new code')
if args.build: if args.build:
subprocess.run([str(ROOT/'scripts/build.sh'), ':app:assembleDebug', ':app:compileDebugAndroidTestKotlin', subprocess.run([str(ROOT/'scripts/build.sh'), ':app:assembleDebug', ':app:compileDebugAndroidTestKotlin',
+2 -2
View File
@@ -34,7 +34,7 @@ def digest(data):
def catalog(): def catalog():
data = json.loads(CATALOG.read_bytes()) data = json.loads(CATALOG.read_bytes())
require(data['schemaVersion'] == 1 and set(data['profiles']) == {'main', 'lvbu-test'}, 'unsupported profile catalog') require(data['schemaVersion'] == 1 and set(data['profiles']) == {'main', 'lvbu-test', 'liam-test'}, 'unsupported profile catalog')
return data return data
@@ -140,7 +140,7 @@ def stage(assets, output, report):
def main(): def main():
p = argparse.ArgumentParser(description=__doc__) p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--profile', choices=['main', 'lvbu-test'], required=True) p.add_argument('--profile', choices=sorted(catalog()['profiles']), required=True)
p.add_argument('--assets', type=Path, default=ROOT / 'app/src/main/assets') p.add_argument('--assets', type=Path, default=ROOT / 'app/src/main/assets')
p.add_argument('--emotion-sha', default='') p.add_argument('--emotion-sha', default='')
for flag in ('user-assets', 'mouth', 'startup'): for flag in ('user-assets', 'mouth', 'startup'):
+4 -2
View File
@@ -21,7 +21,9 @@ private fun DialogueClient.listener(epoch: Long)=javaClass.getDeclaredMethod("li
fun main() { fun main() {
val wires=mutableListOf<String>() val wires=mutableListOf<String>()
val pin="208f703ed92bf795bfeb78a1cef89b67bed2e45da80038a56157fd1ecd4cfa93" val pin="208f703ed92bf795bfeb78a1cef89b67bed2e45da80038a56157fd1ecd4cfa93"
for(persona in listOf("default","lvbu")) for(pending in listOf(false,true)) { val personas=System.getProperty("character.personas","default,lvbu,liam").split(",")
check(personas.isNotEmpty() && personas.all { it in setOf("default","lvbu","liam") })
for(persona in personas) for(pending in listOf(false,true)) {
var readyPin: String?=if(pending) null else pin var readyPin: String?=if(pending) null else pin
val statuses=mutableListOf<ConnectionStatus>() val statuses=mutableListOf<ConnectionStatus>()
val client=DialogueClient("localhost",5011,statuses::add,persona=persona, val client=DialogueClient("localhost",5011,statuses::add,persona=persona,
@@ -51,5 +53,5 @@ fun main() {
client.release();Handler.drain() client.release();Handler.drain()
} }
java.io.File(checkNotNull(System.getProperty("character.helloFile"))).writeText(wires.joinToString("\n")+"\n") java.io.File(checkNotNull(System.getProperty("character.helloFile"))).writeText(wires.joinToString("\n")+"\n")
println("PASS: four actual DialogueClient AUTH→production HELLO persona/media offers, pending readiness, duplicate AUTH and retired socket fences; transport/main/JSON adapters, device not_run") println("PASS: "+wires.size+" actual DialogueClient AUTH→production HELLO persona/media offers, pending readiness, duplicate AUTH and retired socket fences; transport/main/JSON adapters, device not_run")
} }
+29 -15
View File
@@ -22,12 +22,13 @@ class CharacterProfilesTests(unittest.TestCase):
return select.selection(ASSETS, profile, **flags) return select.selection(ASSETS, profile, **flags)
def test_identities_are_distinct_media_is_identical(self): def test_identities_are_distinct_media_is_identical(self):
main, lvbu = self.full(), self.full('lvbu-test') results=[self.full(p) for p in ('main','lvbu-test','liam-test')]
self.assertEqual(main['files'], lvbu['files']) for row in results:
self.assertEqual(lvbu['file_count'], 4051) self.assertEqual(results[0]['files'],row['files'])
self.assertEqual((main['persona'], lvbu['persona']), ('default', 'lvbu')) self.assertEqual((row['file_count'],row['media_identity']),(4051,'a01'))
self.assertNotEqual(main['application_id'], lvbu['application_id']) self.assertEqual([r['persona'] for r in results],['default','lvbu','liam'])
self.assertEqual((main['media_identity'], lvbu['media_identity']), ('a01', 'a01')) self.assertEqual(len({r['application_id'] for r in results}),3)
self.assertEqual(results[2]['application_id'],'com.gorios.lanvoice.liamtest')
self.assertNotIn('voice_id', json.dumps(select.catalog())) self.assertNotIn('voice_id', json.dumps(select.catalog()))
def test_complete_inventory_is_exact_code33(self): def test_complete_inventory_is_exact_code33(self):
@@ -55,9 +56,9 @@ class CharacterProfilesTests(unittest.TestCase):
self.assertEqual(select.selection(copied)['files'], select.selection(ASSETS)['files']) self.assertEqual(select.selection(copied)['files'], select.selection(ASSETS)['files'])
def test_wrong_persona_flags_or_pin_are_rejected(self): def test_wrong_persona_flags_or_pin_are_rejected(self):
for profile, changes in [('unknown', {}), ('lvbu-test', {'startup': False}), cases=[('unknown',{}),('main',{'emotion_sha':'0'*64})]
('lvbu-test', {'mouth': False}), ('lvbu-test', {'user_assets': False}), cases += [(p,{flag:False}) for p in ('lvbu-test','liam-test') for flag in ('startup','mouth','user_assets')]
('main', {'emotion_sha': '0'*64})]: for profile, changes in cases:
with self.subTest(profile=profile, changes=changes), self.assertRaises(ValueError): with self.subTest(profile=profile, changes=changes), self.assertRaises(ValueError):
self.full(profile, **changes) self.full(profile, **changes)
@@ -83,17 +84,20 @@ class CharacterProfilesTests(unittest.TestCase):
select.relative(name) select.relative(name)
def test_staging_cannot_overwrite_other_profile_or_build_root(self): def test_staging_cannot_overwrite_other_profile_or_build_root(self):
result = self.full('lvbu-test') for profile,other in [('lvbu-test','liam-test'),('liam-test','lvbu-test')]:
for dest in (ROOT/'app/build', ROOT/'app/build/generated/packagedAssets', ASSETS): result=self.full(profile)
with self.subTest(dest=dest), self.assertRaises(ValueError): for dest in (ROOT/'app/build',ROOT/'app/build/generated/packagedAssets',ASSETS,
select.stage(ASSETS, dest, result) ROOT/'app/build/characters'/other/'generated/packagedAssets'):
with self.subTest(profile=profile,dest=dest),self.assertRaises(ValueError):
select.stage(ASSETS,dest,result)
def test_backup_lifecycle_component_contracts(self): def test_backup_lifecycle_component_contracts(self):
profiles = select.catalog()['profiles'] profiles = select.catalog()['profiles']
self.assertTrue(profiles['main']['allowBackup']) self.assertTrue(profiles['main']['allowBackup'])
self.assertTrue(profiles['main']['permissionConnectionRetention']) self.assertTrue(profiles['main']['permissionConnectionRetention'])
self.assertFalse(profiles['lvbu-test']['allowBackup']) for profile in ('lvbu-test','liam-test'):
self.assertFalse(profiles['lvbu-test']['permissionConnectionRetention']) self.assertFalse(profiles[profile]['allowBackup'])
self.assertFalse(profiles[profile]['permissionConnectionRetention'])
text = (ROOT/'app/src/main/AndroidManifest.xml').read_text() text = (ROOT/'app/src/main/AndroidManifest.xml').read_text()
self.assertIn('android:allowBackup="${characterAllowBackup}"', text) self.assertIn('android:allowBackup="${characterAllowBackup}"', text)
self.assertIn('android:name="com.gorios.lanvoice.MainActivity"', text) self.assertIn('android:name="com.gorios.lanvoice.MainActivity"', text)
@@ -106,3 +110,13 @@ class CharacterProfilesTests(unittest.TestCase):
pause=activity[activity.index("override fun onPause()"):activity.index("override fun onStop()")] pause=activity[activity.index("override fun onPause()"):activity.index("override fun onStop()")]
self.assertLess(pause.index("if(releaseSessionFirst"),pause.index("closeCamera()")) self.assertLess(pause.index("if(releaseSessionFirst"),pause.index("closeCamera()"))
self.assertIn("if(!releaseSessionFirst",pause) self.assertIn("if(!releaseSessionFirst",pause)
def test_artifact_names_and_build_directories_are_isolated(self):
spec=importlib.util.spec_from_file_location('character_pack',ROOT/'scripts/package-character-test.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
self.assertEqual(pack.artifact_name('lvbu-test',34),'lan-voice-v0714-lvbu-test-code34-arm64-debug.apk')
self.assertEqual(pack.artifact_name('liam-test',35),'lan-voice-v0714-liam-test-code35-arm64-debug.apk')
self.assertNotEqual(pack.build_dir('liam-test'),pack.build_dir('lvbu-test'))
self.assertIn('-PcharacterProfile=liam-test',pack.flags('liam-test',35))
self.assertEqual(select.catalog()['profiles']['liam-test']['minimumVersionCode'],35)
with self.assertRaises(ValueError):pack.artifact_name('main',35)
+2 -2
View File
@@ -1,7 +1,7 @@
import com.gorios.lanvoice.net.DialogueProtocol import com.gorios.lanvoice.net.DialogueProtocol
fun main() { fun main() {
for(persona in listOf("default","lvbu")) { for(persona in listOf("default","lvbu","liam")) {
for((ready,pending) in listOf(null to null,"a".repeat(64) to null,null to "a".repeat(64))) { for((ready,pending) in listOf(null to null,"a".repeat(64) to null,null to "a".repeat(64))) {
val hello=DialogueProtocol.hello(ready,pending,persona) val hello=DialogueProtocol.hello(ready,pending,persona)
check("\"persona\":\"$persona\"" in hello) check("\"persona\":\"$persona\"" in hello)
@@ -10,7 +10,7 @@ fun main() {
} }
check("\"persona\":\"default\"" in DialogueProtocol.hello()) check("\"persona\":\"default\"" in DialogueProtocol.hello())
check(runCatching { DialogueProtocol.hello(persona="unknown") }.isFailure) check(runCatching { DialogueProtocol.hello(persona="unknown") }.isFailure)
println("PASS: production HELLO default/lvbu for no, ready and pending media; no client voice/CID; unknown persona rejected") println("PASS: production HELLO default/lvbu/liam for no, ready and pending media; no client voice/CID; unknown persona rejected")
check("\"presence_greeting_version\":1" in DialogueProtocol.hello()) check("\"presence_greeting_version\":1" in DialogueProtocol.hello())
for(kind in com.gorios.lanvoice.expression.PresenceKind.entries) { for(kind in com.gorios.lanvoice.expression.PresenceKind.entries) {
val wire=DialogueProtocol.presence(7,25,kind,100) val wire=DialogueProtocol.presence(7,25,kind,100)
+4 -2
View File
@@ -62,8 +62,9 @@ fun checkCallControls() {
session.release(); AudioPlayback.activityFence = null session.release(); AudioPlayback.activityFence = null
// Actual session/client background path: the independent profile never retains // Actual session/client background path: the independent profile never retains
// mic/playback/socket, including when a permission Activity pauses this Activity. // mic/playback/socket, including when a permission Activity pauses this Activity.
for(persona in listOf("lvbu","liam")) {
val independentStates=mutableListOf<VoiceUiState>() val independentStates=mutableListOf<VoiceUiState>()
val independent=VoiceSession("localhost",5011,independentStates::add,persona="lvbu",keepPermissionConnection=false) val independent=VoiceSession("localhost",5011,independentStates::add,persona=persona,keepPermissionConnection=false)
val connection=independent.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(independent) as DialogueClient val connection=independent.javaClass.getDeclaredField("dialogue").apply { isAccessible=true }.get(independent) as DialogueClient
val oldSocket=FakeSocket();connection.setField("socket",oldSocket);connection.setField("ready",true) val oldSocket=FakeSocket();connection.setField("socket",oldSocket);connection.setField("ready",true)
independent.javaClass.getDeclaredField("foreground").apply { isAccessible=true }.set(independent,true) independent.javaClass.getDeclaredField("foreground").apply { isAccessible=true }.set(independent,true)
@@ -80,6 +81,7 @@ fun checkCallControls() {
connection.callbacks(0).onMessage(oldSocket,"hello");Handler.drain() connection.callbacks(0).onMessage(oldSocket,"hello");Handler.drain()
check(independentStates.last().connection==ConnectionStatus.DISCONNECTED) check(independentStates.last().connection==ConnectionStatus.DISCONNECTED)
independent.release() independent.release()
println("PASS: lvbu background/permission pause disconnects actual session/client; late capture/playback/HELLO cannot revive it; default retention covered separately") }
println("PASS: lvbu/liam background/permission pause disconnects actual session/client; late capture/playback/HELLO cannot revive it; default retention covered separately")
println("PASS: real VoiceSession explicit start/duplicate dial, mute discards queued capture/keeps seq/no restart while answering, audio turn/generation/abort/hangup/late-frame fences") println("PASS: real VoiceSession explicit start/duplicate dial, mute discards queued capture/keeps seq/no restart while answering, audio turn/generation/abort/hangup/late-frame fences")
} }
+2 -2
View File
@@ -73,8 +73,8 @@ class StartingFixture(val healthCode: Int = 200, val healthError: java.io.IOExce
fun close() { client.release(); barrier.countDown(); Handler.drain() } fun close() { client.release(); barrier.countDown(); Handler.drain() }
} }
fun runChecks() { fun runChecks() {
Fixture("lvbu").apply { for(persona in listOf("lvbu","liam")) Fixture(persona).apply {
event("auth");check(socket.sent==listOf("hello persona=lvbu")) event("auth");check(socket.sent==listOf("hello persona=$persona"))
event("auth");check(socket.sent.size==1) event("auth");check(socket.sent.size==1)
event("hello");check(statuses==listOf(ConnectionStatus.CONNECTED)) event("hello");check(statuses==listOf(ConnectionStatus.CONNECTED))
client.disconnect() client.disconnect()