HEL-783: repair readable dialogue, birth explanations and complete real page layouts

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
白栖知
2026-10-22 17:55:05 +08:00
co-authored by multica-agent
parent f6614d4bf9
commit db571ba204
52 changed files with 1200 additions and 93 deletions
+2 -2
View File
@@ -62,10 +62,10 @@ try:
click(page, '下一步')
expect(page.get_by_role('alert')).to_contain_text('名字')
page.get_by_label('她的名字', exact=True).fill('小满')
page.get_by_label('出生日期', exact=True).fill('2020-01-01')
page.get_by_label('出生日期(公历)', exact=True).fill('2020-01-01')
click(page, '下一步')
expect(page.get_by_role('alert')).to_contain_text('18')
page.get_by_label('出生日期', exact=True).fill('2000-10-18')
page.get_by_label('出生日期(公历)', exact=True).fill('2000-10-18')
click(page, '下一步'); click(page, '下一步')
expect(page.get_by_role('button', name='朋友', exact=True)).to_have_attribute('aria-pressed', 'false')
expect(page.get_by_role('button', name='恋人', exact=True)).to_have_attribute('aria-pressed', 'false')
+4 -4
View File
@@ -17,7 +17,7 @@ from test_api import live_server, make_app # noqa: E402
from cybergril.api.app import create_app # noqa: E402
CONTROLLED = '--controlled' in sys.argv
OUT = ROOT/'docs/r1' / ('controlled' if CONTROLLED else '.')
OUT = ROOT/'docs/rework' / ('r1-regression' if CONTROLLED else 'live-gateway')
OUT.mkdir(parents=True, exist_ok=True)
results = {'checks': [], 'real_dialogue': [], 'console_errors': []}
@@ -41,7 +41,7 @@ def send(page, text, source='real gateway'):
click(page, '发送')
expect(page.get_by_role('button', name='取消本轮回复')).not_to_be_visible(timeout=65000)
assert not page.locator('.dialog .failed').count(), page.locator('.dialog').inner_text()
reply = page.locator('.dialog .her').inner_text()
reply = page.locator('.dialog .her .current-text').inner_text()
results['real_dialogue'].append({'input':text,'reply':reply,'source':'controlled provider' if CONTROLLED else source})
print('CONTROLLED_REPLY' if CONTROLLED else 'REAL_REPLY', reply, flush=True)
return reply
@@ -61,7 +61,7 @@ try:
page.goto(url)
expect(page.get_by_text('1 / 4 · 出生资料')).to_be_visible()
page.get_by_label('她的名字', exact=True).fill('星河')
page.get_by_label('出生日期', exact=True).fill('2000-10-18')
page.get_by_label('出生日期(公历)', exact=True).fill('2000-10-18')
click(page,'下一步')
expect(page.get_by_text('出生底色 · 真实排盘')).to_be_visible()
assert real_app.state.store.query_one('SELECT count(*) n FROM companion')['n']==0
@@ -153,7 +153,7 @@ try:
shot(mp,'mobile-relation-fog')
nav(mp,'此刻'); mp.reload()
expect(mp.locator('.meta')).to_contain_text('恋人')
nav(mp,'日子'); expect(mp.get_by_text('尚未接通',exact=True)).to_be_visible()
nav(mp,'日子'); expect(mp.locator('.pane[aria-label="日子"] .empty').first).to_contain_text('还没有可展示的生活记录')
assert mp.locator('.demo').count()==0
passed('mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console')
# Model timeout and abrupt SSE are separately exercised by deterministic backend/unit tests.
+262
View File
@@ -0,0 +1,262 @@
"""HEL-783 foreground Chromium checks. Only temporary SQLite + controlled LLM.
PYTHONPATH=src <python with playwright> web/tests/rework_browser_check.py
No deployed service or user data is read or written. Every server/context closes.
"""
import asyncio
import json
import sys
import tempfile
from pathlib import Path
from playwright.sync_api import expect, sync_playwright
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tests'))
from test_api import ControlledLLM, live_server, make_app # noqa: E402
from cybergril.contracts import LLMDelta # noqa: E402
OUT = ROOT / 'docs/rework'
OUT.mkdir(parents=True, exist_ok=True)
LONG = '开头:每一段都应该完整留下。\n\n' + '\n\n'.join(
f'第{i}段。' + '窗外的灯慢慢亮起来,我们可以把话说完整,再决定下一步。' * 10
for i in range(1, 6)) + '\n\n最后:故事没有被截掉,前文和末尾都能读到。'
USER = '长句开头。' + '这是完整保留的用户长句。' * 15 + '用户长句末尾。'
class ReworkLLM(ControlledLLM):
async def stream(self, messages, **kwargs):
if self.mode != 'long':
async for delta in super().stream(messages, **kwargs):
yield delta
return
self.calls.append(messages)
try:
for index in range(0, len(LONG), 40):
yield LLMDelta(text=LONG[index:index + 40])
await asyncio.sleep(.025)
yield LLMDelta(done=True)
finally:
self.closed += 1
report = {'checks': [], 'viewports': [], 'motion': {}, 'console_errors': [],
'limits': ['Chromium only; physical phone keyboard, Safari and screen reader not tested.',
'LLM is controlled for deterministic long-stream/error/cancel checks, not a live gateway.']}
def passed(text):
report['checks'].append(text)
print('PASS', text, flush=True)
def click(page, label):
(page.locator('.pane-manage .back') if label == '设置' else page.get_by_role('button', name=label, exact=True)).click()
def nav(page, label):
page.get_by_role('navigation', name='主导航').get_by_role('button', name=label, exact=True).click()
if label == '设置' and page.viewport_size['width'] <= 720 and page.locator('.pane-manage.has-detail').is_visible(): page.locator('.pane-manage .back').click()
def shot(page, name):
page.evaluate("""async () => { await Promise.all([...document.querySelectorAll('.wstep,.pane,.pane .detail,.portal,.tabs button')].flatMap(el=>el.getAnimations()).filter(a=>a.effect.getTiming().iterations !== Infinity).map(a=>a.finished.catch(()=>{}))); }""")
page.screenshot(path=str(OUT / (name + '.png')))
def send(page, text):
page.get_by_role('textbox', name='想和她说的话').fill(text)
click(page, '发送')
try:
with tempfile.TemporaryDirectory(prefix='cg-rework-') as directory, sync_playwright() as pw:
provider = ReworkLLM()
app, _ = make_app(Path(directory) / 'isolated.db', provider)
with live_server(app) as url:
browser = pw.chromium.launch(headless=True, args=['--no-sandbox'])
context = browser.new_context(viewport={'width': 1440, 'height': 900})
page = context.new_page()
page.on('pageerror', lambda e: report['console_errors'].append(str(e)))
page.add_init_script("""
const get = Storage.prototype.getItem;
Storage.prototype.getItem = function(key) {
if(key === 'cybergril.demo.v1' && !location.search.includes('demo=1')) throw new Error('real read demo');
return get.call(this, key);
};
window.motionStarts = [];
const animate = Element.prototype.animate;
Element.prototype.animate = function(...args) {
if (this.matches('.her .current-text')) window.motionStarts.push({text:this.textContent, duration:args[1].duration});
return animate.apply(this, args);
};
"""
)
page.goto(url)
page.get_by_label('她的名字', exact=True).fill('星河')
page.get_by_label('出生日期(公历)', exact=True).fill('2001-05-23')
click(page, '下一步')
expect(page.locator('.calendar')).to_contain_text('闰四月初一')
expect(page.locator('.color-sections section')).to_have_count(6)
assert app.state.store.query_one('SELECT count(*) n FROM companion')['n'] == 0
shot(page, 'birth-preview-moon')
page.locator('.birth-help summary').click()
shot(page, 'birth-calendar-help-moon')
click(page, '下一步'); click(page, '朋友'); click(page, '下一步')
expect(page.locator('.calendar')).to_contain_text('闰四月初一')
page.get_by_role('checkbox').check(); click(page, '确认创建'); click(page, '去看看她')
passed('Real creation: lunar leap month, all six explanations, same final confirmation; preview writes no rows')
nav(page, '交谈')
provider.mode = 'long'
before = page.evaluate('motionStarts.length')
send(page, USER)
expect(page.locator('.her .current-text')).to_contain_text('开头:')
page.evaluate("window.streamNode = document.querySelector('.her .current-text')")
# Pause the actual animation and inspect deterministic frames, then resume.
frames = []
for time in (0, 80, 200):
values = page.evaluate("""t => {const el=window.streamNode;const a=el.getAnimations()[0];if(a){a.pause();a.currentTime=t;}const s=getComputedStyle(el);return {time:t,opacity:s.opacity,transform:s.transform};}""", time)
frames.append(values)
shot(page, f'motion-enter-{time}')
page.evaluate('window.streamNode.getAnimations().forEach(a=>a.play())')
expect(page.get_by_role('button', name='取消本轮回复')).not_to_be_visible()
expect(page.locator('.her .current-text')).to_have_text(LONG)
assert page.evaluate("window.streamNode === document.querySelector('.her .current-text')")
assert page.evaluate('motionStarts.length') - before == 1
assert float(frames[0]['opacity']) < float(frames[1]['opacity']) < float(frames[2]['opacity'])
report['motion']['entry_frames'] = frames
expect(page.locator('.you .current-text')).to_have_text(USER)
passed('Long Chinese stream: entire user/reply retained; final keeps same DOM; one entrance across all chunks and final')
# Replace a completed sentence; retain its exit DOM until the animation ends.
send(page, '再讲一次')
outgoing = page.locator('.her .outgoing-text')
expect(outgoing).to_have_count(1)
assert outgoing.text_content() == LONG
exit_frames = page.evaluate("""() => {const el=document.querySelector('.her .outgoing-text');const a=el.getAnimations()[0];a.pause();return [0,80,159].map(t=>{a.currentTime=t;return {time:t,opacity:getComputedStyle(el).opacity,retained:el.isConnected}});} """)
assert float(exit_frames[0]['opacity']) > float(exit_frames[-1]['opacity'])
report['motion']['exit_frames'] = exit_frames
page.evaluate("document.querySelector('.her .outgoing-text').getAnimations().forEach(a=>a.play())")
expect(outgoing).to_have_count(0)
expect(page.get_by_role('button', name='取消本轮回复')).not_to_be_visible()
passed('Old sentence stays mounted during a visible 160ms fade-out, then leaves')
for width, height in [(1440, 900), (360, 640), (390, 700), (390, 844), (390, 420), (844, 390)]:
page.set_viewport_size({'width': width, 'height': height})
for theme, label in [('moon', '靛蓝月光'), ('fog', '蓝紫雾光')]:
click(page, label)
expect(page.locator('html')).to_have_attribute('data-theme', theme)
page.get_by_role('textbox', name='想和她说的话').focus()
metrics = page.evaluate("""() => {
const box=s=>{const b=document.querySelector(s).getBoundingClientRect();return {top:b.top,bottom:b.bottom,height:b.height}};
const scroll=document.querySelector('.dialog-scroll');return {dialog:box('.dialog'),composer:box('.composer'),nav:box('.nav'),stage:box('.portal'),scrollHeight:scroll.scrollHeight,clientHeight:scroll.clientHeight,width:innerWidth,overflow:document.documentElement.scrollWidth>innerWidth};
}""")
assert not metrics['overflow'], metrics
assert metrics['stage']['bottom'] <= metrics['dialog']['top'] + 1, metrics
assert metrics['dialog']['bottom'] <= metrics['composer']['top'] + 1, metrics
assert metrics['composer']['bottom'] < metrics['nav']['top'], metrics
assert metrics['clientHeight'] >= 60, metrics
assert metrics['scrollHeight'] > metrics['clientHeight'], metrics
report['viewports'].append({'width': width, 'height': height, 'theme': theme, **metrics})
page.locator('.dialog-scroll').evaluate('el=>el.scrollTop=0')
expect(page.locator('.you .current-text')).to_have_text('再讲一次')
if width in (360, 390) and height in (640, 420, 844): shot(page, f'long-start-{width}-{height}-{theme}')
page.locator('.dialog-scroll').evaluate('el=>el.scrollTop=el.scrollHeight')
if width in (360, 390) and height in (640, 420, 844): shot(page, f'long-end-{width}-{height}-{theme}')
click(page, '完整记录')
expect(page.locator('.log-panel')).to_contain_text('长句开头')
expect(page.locator('.log-panel')).to_contain_text('故事没有被截掉')
if width == 390 and height == 844: shot(page, f'full-history-{theme}')
click(page, '关闭记录')
passed('12 viewport/theme combinations: long text scrolls, stage/dialog/composer/navigation never overlap; full history reachable')
page.set_viewport_size({'width': 390, 'height': 700})
provider.mode = 'slow'; send(page, '取消并重发')
expect(page.locator('.her .current-text')).to_have_text('答')
click(page, '取消本轮回复')
provider.mode = 'normal'; send(page, '新轮')
expect(page.get_by_role('button', name='取消本轮回复')).not_to_be_visible()
expect(page.locator('.her .current-text')).to_have_text('答复')
provider.mode = 'error'; send(page, '失败再试')
expect(page.locator('.dialog .failed')).to_be_visible()
expect(page.get_by_role('textbox', name='想和她说的话')).to_have_value('失败再试')
count = app.state.store.query_one('SELECT count(*) n FROM chat_message')['n']
provider.mode = 'normal'; page.locator('.dialog .retry').click()
expect(page.locator('.dialog .failed')).not_to_be_visible()
expect(page.get_by_role('button', name='取消本轮回复')).not_to_be_visible()
assert app.state.store.query_one('SELECT count(*) n FROM chat_message')['n'] == count + 1
passed('Cancel then immediate new turn, model error and same-turn retry preserve roles and avoid duplicate user messages')
nav(page, '设置'); click(page, '她')
expect(page.locator('.color-sections section')).to_have_count(6)
expect(page.locator('.calendar')).to_contain_text('闰四月初一')
shot(page, 'existing-birth-fog')
page.locator('.color-sections section').last.scroll_into_view_if_needed()
shot(page, 'existing-growth-fog')
click(page, '设置')
for label in ('城市', '外观素材', '备份', '外接服务'):
page.get_by_role('navigation', name='设置分区').get_by_role('button', name=label, exact=True).click()
shot(page, {'城市':'city','外观素材':'appearance','备份':'backup','外接服务':'services'}[label] + '-fog')
if label == '城市':
page.get_by_label('搜索城市').fill('不存在')
expect(page.get_by_text('当前目录没有匹配的城市。')).to_be_visible()
if label == '外接服务':
click(page, '重新检查连接')
expect(page.get_by_role('status')).to_contain_text('文字服务可达')
click(page, '设置')
click(page, '关系')
page.get_by_label('相处边界').fill('未保存的边界')
nav(page, '日子')
expect(page.get_by_role('dialog')).to_contain_text('有未保存的修改')
click(page, '取消')
expect(page.locator('.pane-manage')).to_be_visible()
nav(page, '日子'); click(page, '放弃修改并离开')
expect(page.get_by_text('还没有可展示的生活记录')).to_be_visible()
shot(page, 'life-empty-fog')
page.get_by_role('tab', name='我们的回忆').click()
expect(page.locator('.pane .list .grp')).to_have_count(4)
shot(page, 'memory-groups-empty-fog')
assert app.state.store.query_one('SELECT count(*) n FROM life_event')['n'] == 0
passed('Restored real pages: city search/empty, appearance/check/compare, backup/recovery, four services/live health, life/memory groups; unsaved close guard')
nav(page, '交谈'); page.keyboard.press('Escape')
expect(page.get_by_role('navigation', name='主导航').get_by_role('button', name='此刻', exact=True)).to_have_attribute('aria-current', 'page')
nav(page, '设置'); click(page, '显示')
page.get_by_role('checkbox').check(); click(page, '保存')
expect(page.get_by_role('status')).to_contain_text('此浏览器')
page.reload(); nav(page, '交谈')
assert page.locator('html').evaluate("el=>el.classList.contains('reduced')")
provider.mode = 'normal'; send(page, '减少动效检查')
expect(page.get_by_role('button', name='取消本轮回复')).not_to_be_visible()
assert page.evaluate('motionStarts.at(-1).duration') == 120
reduced = browser.new_context(viewport={'width': 390, 'height': 700}, reduced_motion='reduce')
rp = reduced.new_page(); rp.goto(url); nav(rp, '交谈'); send(rp, '系统减少动效')
expect(rp.get_by_role('button', name='取消本轮回复')).not_to_be_visible()
reduced.close()
passed('Escape navigation; browser display preference survives reload; settings/system reduced motion uses gentle opacity')
# Demonstration mode must never request APIs or borrow a real profile.
demo = browser.new_context(viewport={'width': 390, 'height': 844})
dp = demo.new_page(); requests = []
dp.on('request', lambda r: requests.append(r.url) if '/api/' in r.url else None)
dp.goto(url + '/?demo=1')
expect(dp.get_by_text('1 / 4 · 出生资料')).to_be_visible()
dp.get_by_label('她的名字', exact=True).fill('小满')
click(dp, '下一步'); click(dp, '下一步'); click(dp, '朋友'); click(dp, '下一步')
dp.get_by_role('checkbox').check(); click(dp, '确认创建'); click(dp, '去看看她')
nav(dp, '交谈'); click(dp, '开始模拟语音'); click(dp, '开始模拟')
expect(dp.get_by_role('button', name='结束语音')).to_be_visible()
assert dp.locator('.voicebar').bounding_box()['y'] > dp.locator('.dialog').bounding_box()['y']
shot(dp, 'demo-voice-390')
click(dp, '结束语音')
dp.locator('.demo > button').click(); click(dp, '载入三天记录')
nav(dp, '日子'); dp.locator('.ev').first.click(); click(dp, '看那段聊天')
expect(dp.locator('.log-panel')).to_be_visible(); click(dp, '关闭记录'); click(dp, '返回日子')
expect(dp.locator('.pane[aria-label="日子"]')).to_have_class('pane glass read open has-detail')
assert not requests
passed('Demo has its own profile, voice simulation, life/detail/chat/return path and zero API requests')
demo.close(); browser.close()
assert not report['console_errors'], report['console_errors']
finally:
(OUT / 'browser-results.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')