Initial Beta build
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m27s

This commit is contained in:
Elijah 2026-10-24 09:09:55 -07:00
commit 2b585badac
65 changed files with 3535 additions and 0 deletions

22
scripts/bootstrap.py Normal file
View file

@ -0,0 +1,22 @@
"""Install an isolated, reproducible Windows Android build toolchain."""
import concurrent.futures, pathlib, urllib.request, zipfile
ROOT = pathlib.Path(__file__).resolve().parents[1]
TOOLS = ROOT / '.tools'
TOOLS.mkdir(exist_ok=True)
def install(name, url, destination, marker):
if (TOOLS / marker).exists(): return
archive = TOOLS / (name + '.zip')
if not archive.exists():
print('Downloading ' + name, flush=True)
urllib.request.urlretrieve(url, archive)
with zipfile.ZipFile(archive) as z: z.extractall(TOOLS / destination)
print('Installed ' + name, flush=True)
jobs = [
('jdk','https://cdn.azul.com/zulu/bin/zulu17.68.203-ca-crac-jdk17.0.20.1-win_x64.zip','jdk','jdk/zulu17.68.203-ca-crac-jdk17.0.20.1-win_x64/bin/java.exe'),
('gradle','https://services.gradle.org/distributions/gradle-8.13-bin.zip','','gradle-8.13/bin/gradle.bat'),
('commandline','https://dl.google.com/android/repository/commandlinetools-win-13114758_latest.zip','sdk/cmdline-tools','sdk/cmdline-tools/latest/bin/sdkmanager.bat')]
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
list(pool.map(lambda args: install(*args),jobs))
p = TOOLS / 'sdk/cmdline-tools/cmdline-tools'
if p.exists(): p.rename(p.with_name('latest'))
print('Tool downloads complete', flush=True)

22
scripts/check_video.py Normal file
View file

@ -0,0 +1,22 @@
"""Regression loop: play the known live test title at 90s and assert visible video."""
import pathlib, sys, time, re
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from device import adb,OUT
from PIL import Image
import io
mode=int(sys.argv[1]) if len(sys.argv)>1 else 0
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode',str(mode))
time.sleep(12)
pid=adb('shell','pidof','tv.kaleido.app').decode().strip()
assert pid,'Kaleido process exited during playback'
logs=adb('logcat','-d','-t','1000','--pid='+pid,'-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
assert 'READY item=' in logs,'Player never reached READY: '+logs[-3000:]
assert re.search(r'topResumedActivity=.*tv\.kaleido\.app',adb('shell','dumpsys','activity','activities').decode(errors='replace')),'Kaleido is not the foreground activity'
raw=adb('exec-out','screencap','-p');(OUT/f'video-mode-{mode}.png').write_bytes(raw)
im=Image.open(io.BytesIO(raw)).convert('RGB')
pixels=list(im.crop((450,150,1750,600)).getdata())
visible=sum(max(p)>32 for p in pixels)/len(pixels)
print(f'Video region visible pixels: {visible:.1%}')
assert visible>.05,'BLACK VIDEO: decoded picture is not visible'
print('PASS: actual video picture is visible')

36
scripts/device.py Normal file
View file

@ -0,0 +1,36 @@
"""Operate only Kaleido on the authorized onn streamer. Credentials stay on stdin."""
import argparse, json, pathlib, subprocess, sys, time, xml.etree.ElementTree as ET
ROOT=pathlib.Path(__file__).resolve().parents[1]
ADB=pathlib.Path(r'C:\Users\Elijah\Desktop\platform-tools\adb.exe')
DEVICE='192.168.50.195:5555'
OUT=ROOT/'evidence/private'
OUT.mkdir(parents=True,exist_ok=True)
def adb(*args, data=None):
p=subprocess.run([str(ADB),'-s',DEVICE,*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if p.returncode: raise RuntimeError(p.stderr.decode(errors='replace'))
return p.stdout
def screenshot(name):
path=OUT/(name+'.png');path.write_bytes(adb('exec-out','screencap','-p'));print(path)
def hierarchy():
adb('shell','uiautomator','dump','/data/local/tmp/kaleido-window.xml')
raw=adb('shell','cat','/data/local/tmp/kaleido-window.xml');(OUT/'window.xml').write_bytes(raw)
root=ET.fromstring(raw)
for n in root.iter('node'):
if n.get('text') or n.get('focused')=='true':print({k:n.get(k) for k in ['text','content-desc','focused','bounds']})
def seed():
env=dict(l.strip().split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#'))
data=json.dumps({'server':env['PLEX_SERVER_URL'].strip('\"\''),'token':env['PLEX_TOKEN'].strip('\"\'')}).encode()
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','run-as','tv.kaleido.app','mkdir','-p','files')
adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > files/bootstrap.json"',data=data)
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
print('Private test session provisioned. No credentials are embedded in the APK.')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['seed','screenshot','hierarchy','key','launch','logs']);p.add_argument('value',nargs='?',default='screen');a=p.parse_args()
if a.action=='seed':seed()
if a.action=='screenshot':screenshot(a.value)
if a.action=='hierarchy':hierarchy()
if a.action=='key':adb('shell','input','keyevent',a.value)
if a.action=='launch':print(adb('shell','am','start','-n','tv.kaleido.app/.MainActivity').decode())
if a.action=='logs':
text=adb('logcat','-d','-t','2000','KaleidoPlayback:I','AndroidRuntime:E','ExoPlayerImpl:I','*:S').decode(errors='replace');(OUT/'device.log').write_text(text);print(text[-16000:])

23
scripts/inspect_server.py Normal file
View file

@ -0,0 +1,23 @@
"""Read-only Plex connectivity inventory; never prints credentials."""
import json, pathlib, urllib.request, urllib.parse
ROOT = pathlib.Path(__file__).resolve().parents[1]
env = dict(line.strip().split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
base = env['PLEX_SERVER_URL'].strip('\"\'').rstrip('/')
token = env['PLEX_TOKEN'].strip('\"\'')
def get(path):
req = urllib.request.Request(base+path,headers={'X-Plex-Token':token,'Accept':'application/json','X-Plex-Product':'Kaleido','X-Plex-Client-Identifier':'kaleido-development'})
with urllib.request.urlopen(req,timeout=20) as r: return json.load(r)['MediaContainer']
if __name__ == '__main__':
print('Server:', get('/').get('friendlyName'), 'version:', get('/').get('version'))
sections = get('/library/sections').get('Directory',[])
for s in sections:
print('Section', s['key'],s['title'],s['type'])
d=get('/library/sections/'+s['key']+'/all?X-Plex-Container-Start=0&X-Plex-Container-Size=2&sort=titleSort')
print('Total:', d.get('totalSize',d.get('size')))
for m in d.get('Metadata',[]):
print('Sample:', {k:m.get(k) for k in ['ratingKey','title','type','duration','viewOffset']})
for media in m.get('Media',[]): print('Media:', {k:media.get(k) for k in ['container','videoCodec','audioCodec','videoResolution']})
for path in ['/hubs/home','/hubs','/library/onDeck']:
try:
d=get(path); print(path,[(h.get('title'),len(h.get('Metadata',[]))) for h in d.get('Hub',[])], 'items:',d.get('size'))
except Exception as e: print(path,type(e).__name__)

View file

@ -0,0 +1,15 @@
"""Stage a locally signed APK for Git distribution and tag-triggered Forgejo releases."""
import hashlib, json, pathlib, shutil, subprocess
ROOT=pathlib.Path(__file__).resolve().parents[1]
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l)
apk=ROOT/'app/build/outputs/apk/release/app-release.apk'
if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.')
out=ROOT/'distribution';out.mkdir(exist_ok=True)
shutil.copyfile(apk,out/'Kaleido.apk')
digest=hashlib.sha256(apk.read_bytes()).hexdigest()
(out/'Kaleido.apk.sha256').write_text(digest+' Kaleido.apk\n')
repo='https://git.elijahkuntz.com/Elijah/Kaleido'
tag='v'+version['versionName']
manifest={'version':version['versionName'],'versionCode':int(version['versionCode']),'url':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk','checksumUrl':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk.sha256','notes':(ROOT/'CHANGELOG.md').read_text().split('\n## ')[1].split('\n## ')[0] if (ROOT/'CHANGELOG.md').exists() else ''}
(out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n')
print('Packaged',tag,'SHA-256',digest)

23
scripts/profile_browse.py Normal file
View file

@ -0,0 +1,23 @@
"""Capture app atrace sections around actual remote navigation."""
import re,time,collections
from device import adb,OUT
from verify_ui import launch,key
launch();key(20);time.sleep(2)
pid=adb('shell','pidof','tv.kaleido.app').decode().strip()
adb('shell','atrace','--async_start','-b','16384','-a','tv.kaleido.app','gfx','view','sched')
adb('shell','input','keyevent',*(['KEYCODE_DPAD_RIGHT']*15))
adb('shell','input','keyevent',*(['KEYCODE_DPAD_DOWN']*3))
adb('shell','input','keyevent',*(['KEYCODE_DPAD_UP']*6))
raw=adb('shell','atrace','--async_stop','-a','tv.kaleido.app','gfx','view','sched').decode(errors='replace')
(OUT/'browse-atrace.txt').write_text(raw)
stacks=collections.defaultdict(list);spans=[]
for line in raw.splitlines():
match=re.search(r'-(\d+)\s+.*?\s(\d+\.\d+): tracing_mark_write: ([BE])(?:\|(.*))?',line)
if not match:continue
tid,stamp,kind,payload=match.groups();stamp=float(stamp)
if kind=='B':
owner,_,name=(payload or '').partition('|');stacks[tid].append((stamp,name,owner))
elif stacks[tid]:
start,name,owner=stacks[tid].pop()
if owner==pid:spans.append(((stamp-start)*1000,name,tid))
for duration,name,tid in sorted(spans,reverse=True)[:35]:print(f'{duration:8.2f}ms tid={tid} {name}')

View file

@ -0,0 +1,26 @@
"""Publish the checked-in, signed APK using Forgejo's repository-scoped CI token."""
import hashlib, json, os, pathlib, urllib.request, uuid
ROOT=pathlib.Path(__file__).resolve().parents[1]
API='https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido'
token=os.environ['KALEIDO_RELEASE_TOKEN']
version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l)
tag='v'+version['versionName']
ref=os.environ.get('RELEASE_REF','')
assert ref=='refs/tags/'+tag,'Tag must match version.properties exactly'
out=ROOT/'distribution'
assert hashlib.sha256((out/'Kaleido.apk').read_bytes()).hexdigest()==(out/'Kaleido.apk.sha256').read_text().split()[0]
def call(path,data=None,method=None,content='application/json'):
req=urllib.request.Request(API+path,data=data,method=method,headers={'Authorization':'token '+token,'Content-Type':content})
with urllib.request.urlopen(req,timeout=120) as response:return json.load(response)
try:release=call('/releases/tags/'+tag)
except urllib.error.HTTPError as e:
if e.code!=404:raise
release=call('/releases',json.dumps({'tag_name':tag,'name':'Kaleido '+version['versionName'],'body':(ROOT/'CHANGELOG.md').read_text(),'draft':True,'prerelease':False}).encode(),'POST')
existing={a['name']:a for a in release.get('assets',[])}
for name in ['Kaleido.apk','Kaleido.apk.sha256']:
if name in existing:continue
boundary='kaleido'+uuid.uuid4().hex
data=(f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()+(out/name).read_bytes()+f'\r\n--{boundary}--\r\n'.encode()
call(f'/releases/{release["id"]}/assets?name='+name,data,'POST','multipart/form-data; boundary='+boundary)
call('/releases/'+str(release['id']),json.dumps({'draft':False}).encode(),'PATCH')
print('Published',tag)

117
scripts/repro_runtime.py Normal file
View file

@ -0,0 +1,117 @@
"""On-device regression loops for focus geometry, frame pacing, and episode replacement."""
import sys,time,re,json
from device import adb,OUT,screenshot
from verify_ui import key,snapshot,focus,labels,wait,focused,launch
def sections():
# The splash gates remote input; switch as soon as the first browsing frame is available.
# Initialization must remain independent of tab loading on slow servers.
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
wait(lambda r:'Home' in labels(r) and labels(r).count('KALEIDO')==1,'Cold-start splash must finish')
key(22)
wait(lambda r:'Recently released' in labels(r),'Movies must finish loading after a startup tab switch')
focused('Movies');screenshot('cold-tabs-fixed')
key(22);wait(lambda r:'Next episodes' in labels(r),'TV recommendations must load');focused('TV Shows')
key(21);wait(lambda r:'Recently released' in labels(r),'Cached Movies must return');focused('Movies')
print('PASS startup tab switch, TV loading, and cached section return')
def controls():
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1')
time.sleep(9);key(127);focused('Play')
screenshot('direct-stream-episode')
key(4);wait(lambda r:not labels(r),'One Back must hide controls rather than only clearing focus')
key(23);focused('Play');key(126);time.sleep(6)
wait(lambda r:not labels(r),'Controls must auto-hide during playback')
key(4);wait(lambda r:'Continue Watching' in labels(r),'Back must exit hidden player')
print('PASS one-press Back, OK reveal, timed hide, and exit')
def browse():
launch();key(20)
if focus(snapshot()) in ('Play','Resume'):key(20)
wait(lambda r:focus(r) not in ('','Home','Play','Resume'),'Content focus')
adb('shell','dumpsys','gfxinfo','tv.kaleido.app','reset')
geometry=[]
for _ in range(5):
root=snapshot();node=next(n for n in root.iter('node') if n.get('focused')=='true')
bounds=list(map(int,re.findall(r'\d+',node.get('bounds'))))
geometry.append({'focus':focus(root),'bounds':bounds});key(22)
adb('shell','input','keyevent',*(['KEYCODE_DPAD_RIGHT']*15))
adb('shell','input','keyevent',*(['KEYCODE_DPAD_UP']*12))
stats=adb('shell','dumpsys','gfxinfo','tv.kaleido.app','framestats').decode(errors='replace')
(OUT/'browse-framestats.txt').write_text(stats)
(OUT/'browse-geometry.json').write_text(json.dumps(geometry,indent=2))
print(json.dumps(geometry),flush=True)
print('\n'.join(x for x in stats.splitlines() if any(k in x for k in ('Total frames','Janky frames','percentile','Missed Vsync'))),flush=True)
ys=[r['bounds'][1] for r in geometry]
assert max(ys)-min(ys)<=3,f'Horizontal navigation moved row vertically by {max(ys)-min(ys)}px'
print('PASS stable horizontal focus geometry')
p95=int(re.search(r'95th percentile: (\d+)ms',stats)[1])
assert p95<40,f'Browsing frame pacing regression: p95={p95}ms (target below 40ms)'
def episode():
from inspect_server import get
titles=get('/library/metadata/6115/allLeaves').get('Metadata',[])
item=titles[0];expected=str(titles[1]['ratingKey'])
adb('shell','am','force-stop','tv.kaleido.app')
adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2')
time.sleep(9);key(127);focused('Play')
for _ in range(6):
if 'Next episode' in focus(snapshot()):break
key(22)
focused('Next episode');key(23);time.sleep(5)
logs=adb('logcat','-d','-t','700','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
(OUT/'episode-replacement.log').write_text(logs)
print(logs[-10000:],flush=True)
assert 'FATAL EXCEPTION' not in logs,'Next episode crashed Android runtime'
assert adb('shell','pidof','tv.kaleido.app').strip(),'Process exited'
assert re.search(r'topResumedActivity=.*tv\.kaleido\.app',adb('shell','dumpsys','activity','activities').decode(errors='replace')),'Lost foreground'
assert 'item='+expected in logs,'Next episode did not become the active player'
print('PASS next episode replaced player with expected title')
def postplay():
from inspect_server import get
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(item['duration']-12000),'--ei','testMode','2')
deadline=time.monotonic()+45
while time.monotonic()<deadline:
time.sleep(1)
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
if 'READY item=8594' in logs or 'FATAL EXCEPTION' in logs:break
(OUT/'postplay-ended.log').write_text(logs);print(logs[-8000:],flush=True)
assert 'FATAL EXCEPTION' not in logs,'Episode end crashed'
assert 'reason=ended' in logs,'Natural end did not open postplay'
assert 'AUTOPLAY starting next=8594' in logs,'Five-second countdown did not start next episode'
assert 'READY item=8594' in logs,'Autoplay did not reach READY'
print('PASS natural end -> five-second countdown -> next episode READY')
def credits():
from inspect_server import get
item=get('/library/metadata/7599?includeMarkers=1')['Metadata'][0]
marker=next(m for m in item['Marker'] if m['type']=='credits')
adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2')
time.sleep(6);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits')
screenshot('skip-credits-contrast');key(23)
deadline=time.monotonic()+8
while time.monotonic()<deadline:
time.sleep(.1)
ready=adb('logcat','-d','-s','KaleidoPlayback:I','*:S').decode(errors='replace')
if 'POSTPLAY focus=play' in ready:break
assert 'POSTPLAY focus=play' in ready,'Postplay initial action never received focus'
key(22);key(23)
wait(lambda r:'Autoplay off' in labels(r),'Autoplay cancellation')
screenshot('postplay-season-and-related');time.sleep(6)
root=snapshot();assert 'Up next' in labels(root),'Cancellation failed to keep postplay open'
assert 'Episodes in this season' in labels(root),'Season episodes absent'
assert 'Related shows' in labels(root),'Related shows absent'
logs=adb('logcat','-d','-s','KaleidoPlayback:I','AndroidRuntime:E','*:S').decode(errors='replace')
assert 'reason=skip-credits' in logs,'Skip credits did not open postplay'
assert 'AUTOPLAY starting' not in logs,'Cancelled autoplay still advanced'
(OUT/'postplay-cancel.log').write_text(logs)
print('PASS skip credits -> postplay, episode/related rows, cancellable autoplay')
globals()[sys.argv[1]]()

View file

@ -0,0 +1,41 @@
"""Focused browsing checks for the real onn; all captures stay private."""
import io,json,time
from PIL import Image,ImageChops,ImageStat
from device import adb,OUT,screenshot
from verify_ui import key,snapshot,labels,focus,wait,focused,launch
def capture_bytes(name):
raw=adb('exec-out','screencap','-p');(OUT/(name+'.png')).write_bytes(raw)
return Image.open(io.BytesIO(raw)).convert('RGB')
launch();key(20);focused('Play');key(22,2);focused('Next featured title')
# Explicitly advance to see all three categories without waiting for the carousel timer.
reasons=[]
for i in range(3):
root=snapshot();reasons.append(next((s for s in labels(root) if s in ('RECENTLY RELEASED','HIGHLY RATED · UNWATCHED','SUGGESTED FOR YOU')),''))
if i<2:
focused('Next featured title');key(23);time.sleep(.7);focused('Next featured title')
assert len(set(reasons))==3,reasons
print('PASS real hero cycles recent releases, highly rated unwatched, and suggestions',flush=True)
key(21,2);focused('Play');key(20);time.sleep(1)
first=focus(snapshot());a=capture_bytes('updates-home-focus-one')
key(22);time.sleep(1);second=focus(snapshot());b=capture_bytes('updates-home-focus-two')
assert first!=second
w,h=a.size
# Above the row and below navigation, only the backdrop occupies this region.
region=(int(w*.58),int(h*.10),int(w*.94),int(h*.16))
difference=sum(ImageStat.Stat(ImageChops.difference(a.crop(region),b.crop(region))).mean)/3
assert difference>3,f'Focused Home background did not change: {difference}'
print('PASS Home backdrop follows focused title (mean pixel change %.1f)'%difference,flush=True)
key(20);single_row=focus(snapshot())
launch();key(20);focused('Play');key(20);snapshot()
for _ in range(6):adb('shell','input','keyevent','20');time.sleep(.08)
held=focus(snapshot())
assert held!=single_row,f'Rapid Down kept restarting the same row: {held}'
print('PASS rapid Down advances beyond one animated row',flush=True)
launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
root=wait(lambda r:any('episodes remaining' in n.get('content-desc','') for n in r.iter('node')),'Show episode counts')
screenshot('updates-show-counts');print('PASS show library exposes remaining episode badges',flush=True)
# Leave the device in a useful Home state.
key(4);key(4);focused('Home')
(OUT/'browse-updates-results.json').write_text(json.dumps({'hero_categories':reasons,'backdrop_pixel_difference':difference},indent=2),encoding='utf-8')

89
scripts/verify_ui.py Normal file
View file

@ -0,0 +1,89 @@
"""Remote-only UI regression checks on the authorized onn; captures remain private."""
import argparse,json,pathlib,re,sys,time,xml.etree.ElementTree as ET
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from device import adb,OUT,screenshot
results=[]
def key(code,count=1):
for _ in range(count):
adb('shell','input','keyevent',str(code));time.sleep(.22)
def snapshot():
adb('shell','uiautomator','dump','/data/local/tmp/kaleido-window.xml')
return ET.fromstring(adb('shell','cat','/data/local/tmp/kaleido-window.xml'))
def labels(root):return [n.get('text','') for n in root.iter('node') if n.get('text')]
def focus(root):
n=next((n for n in root.iter('node') if n.get('focused')=='true'),None)
if n is None:return ''
return n.get('content-desc','') or ' '.join(labels(n))
def wait(check,description,timeout=25):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
root=snapshot()
if check(root):return root
time.sleep(.2)
raise AssertionError(description+'; last focus='+focus(root)+'; labels='+str(labels(root)[:10]))
def text(value):return wait(lambda root:value in labels(root),'Expected text '+value)
def focused(value):return wait(lambda root:value in focus(root),'Expected focus '+value)
def passed(name):results.append(name);print('PASS '+name,flush=True)
def capture(name):time.sleep(.4);screenshot('final-'+name)
def launch():
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity')
text('Continue Watching')
wait(lambda r:labels(r).count('KALEIDO')==1,'Cold-start splash must finish')
focused('Home')
def browse():
launch();key(20);wait(lambda r:focus(r) in ('Play','Resume'),'Home hero action');capture('home')
key(20);wait(lambda r:bool(focus(r)) and focus(r) not in ('Home','Play','Resume'),'Continue Watching focus');capture('home-continue')
passed('Large cinematic Home hero and separate landscape Continue Watching')
key(22);selected=focus(snapshot());key(23)
wait(lambda r:any(x.startswith('Resume') or x=='Play' for x in labels(r)),'Playable details')
key(4);focused(selected);passed('Discovery details returns to the same focused card')
key(19);wait(lambda r:focus(r) in ('Play','Resume'),'Return to Home hero');key(19);focused('Home');key(22);text('Recently released');focused('Movies')
capture('movies-discover');key(20);focused('Discover');key(22);focused('Library');key(23)
text('All genres ⌄');focused('Library');capture('movies-library')
passed('Movies prioritizes recent releases and retains a separate filtered A-Z grid')
key(20);wait(lambda r:bool(focus(r)) and 'Library' not in focus(r),'Library content or filter focus')
key(4);focused('Discover');key(19);focused('Movies');key(22)
text('Next episodes');focused('TV Shows');capture('tv-discover')
key(20);focused('Discover');key(20);wait(lambda r:bool(focus(r)) and focus(r)!='Discover','TV next episode focus')
capture('tv-next-episodes');key(20);text('New seasons');capture('tv-new-seasons');key(20);text('New episodes');capture('tv-new-episodes')
passed('TV prioritizes next episodes, new seasons, and new episodes')
key(4);focused('Home');passed('Section Back returns to Home navigation')
key(22,4);focused('Settings');key(23);text('Settings');focused('Sign in with Plex');key(23)
text('Sign in to Plex');text('plex.tv/link')
wait(lambda r:any(re.fullmatch(r'[A-Z0-9]{4,6}',s) for s in labels(r)),'Live Plex PIN')
capture('plex-sign-in');key(4);text('Settings');key(4);focused('Home')
passed('Plex account linking obtains a real PIN and cancellation preserves the session')
def player():
adb('shell','am','force-stop','tv.kaleido.app')
adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2')
time.sleep(12);key(127);focused('Play');capture('player')
passed('Compact player controls over actual video')
key(19);focused('Playback timeline');key(22);capture('timeline');key(20);focused('Play')
passed('D-pad Up focuses timeline, Right seeks, Down returns to play')
key(22,2);focused('Audio tracks');key(23);text('Audio');capture('audio')
key(4);focused('Audio tracks');key(22);focused('Subtitles');key(23);text('Off');capture('subtitles')
passed('Audio and subtitle panels open, close, and restore focus')
key(4);focused('Subtitles');key(22);focused('Playback options');key(23);text('Playback options')
key(20,3);focused('Speed');key(23);text('Playback speed');focused('1.0×');key(20);focused('1.25×');key(23)
focused('Playback options');key(23);text('Speed · 1.25×');key(4);focused('Playback options')
key(23);text('Playback options');key(23);text('Playback mode');focused('Transcode');key(19);focused('Direct stream');key(23)
focused('Playback options');time.sleep(5);key(23);text('Mode · Direct stream');key(4);focused('Playback options')
passed('Player gear changes speed and Direct stream while retaining focus')
key(4)
wait(lambda r:focus(r)=='' and '2 Fast 2 Furious' not in labels(r),'Controls hidden by Back')
key(23);focused('Play');key(126);time.sleep(6)
wait(lambda r:'2 Fast 2 Furious' not in labels(r),'Controls auto-hide during playback')
passed('OK reveals controls; Back and playback timer hide them')
key(4);text('Continue Watching');passed('Back exits playback to live home')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('phase',choices=['browse','player']);args=parser.parse_args()
try:
globals()[args.phase]()
finally:
(OUT/('ui-'+args.phase+'-results.json')).write_text(json.dumps(results,indent=2))
print(f'Completed {len(results)} UI checks',flush=True)