|
| 1 | +import assert from "node:assert/strict"; |
| 2 | +import {execFileSync} from "node:child_process"; |
| 3 | +import {mkdtemp, rm} from "node:fs/promises"; |
| 4 | +import {tmpdir} from "node:os"; |
| 5 | +import {resolve} from "node:path"; |
| 6 | +import {resolveTestPython} from "../../scripts/test-python.mjs"; |
| 7 | +import {outputDir, repoRoot} from "./fixture.mjs"; |
| 8 | +import {startHistoryOwner} from "./research-history.mjs"; |
| 9 | + |
| 10 | +// Real source verification, TS reduction, pack registry, HTTP and packaged UI. |
| 11 | +// The fixture has no model outputs: ordinary metric reading needs no analysis. |
| 12 | +export const researchToolContextScenario = { |
| 13 | + id: "research-tool-context", |
| 14 | + async run({browser}) { |
| 15 | + const temporary = await mkdtemp(resolve(tmpdir(), "loopx-tool-context-")); |
| 16 | + let owner, page; |
| 17 | + try { |
| 18 | + const fixture = resolve(temporary, "capture.json"); |
| 19 | + execFileSync(resolveTestPython(), ["-c", ` |
| 20 | +import hashlib,json,sys |
| 21 | +from pathlib import Path |
| 22 | +from loopx.capabilities.explore.result_log import build_explore_node_event |
| 23 | +goal='synthetic-context-reading' |
| 24 | +text='Synthetic research observation; utility remains unknown.' |
| 25 | +scope=dict(goal_id=goal,case_id='synthetic',run_id='fixed',revision='fixture',window='fixed capture') |
| 26 | +pack=dict(schema_version='trajectory_assessment_input_v1',scope=scope,objective='Compare research outcomes and complete costs', |
| 27 | + selection=dict(rule='one synthetic episode',population_episodes=1,exhaustive=True), |
| 28 | + sources=[dict(id='facts',artifact='facts.txt',artifact_sha256=hashlib.sha256(text.encode()).hexdigest(),first_line=1,text=text)], |
| 29 | + episodes=[dict(id='episode',question='Did new evidence change the next experiment?',source_ids=['facts'],eligible_metrics=['evidence_adoption'])]) |
| 30 | +usage=dict(input_tokens=100,cached_input_tokens=60,output_tokens=5) |
| 31 | +rows=[dict(type='session_meta',payload=dict(id='session')), |
| 32 | + dict(type='event_msg',payload=dict(type='task_started',turn_id='turn')), |
| 33 | + dict(type='response_item',payload=dict(type='message',role='user',content=[dict(type='input_text',text='x'*100)])), |
| 34 | + dict(type='response_item',payload=dict(type='function_call',name='exec_command',call_id='control',arguments=json.dumps(dict(cmd='loopx quota context-read')))), |
| 35 | + dict(type='response_item',payload=dict(type='function_call_output',call_id='control',output='x'*60)), |
| 36 | + dict(type='response_item',payload=dict(type='function_call_output',call_id='task',output='x'*40)), |
| 37 | + dict(type='event_msg',payload=dict(type='token_count',info=dict(total_token_usage=usage,last_token_usage=usage))), |
| 38 | + dict(type='event_msg',payload=dict(type='task_complete',turn_id='turn'))] |
| 39 | +for i,row in enumerate(rows):row['timestamp']=f'2026-01-01T00:00:0{i}Z' |
| 40 | +analyses=[] |
| 41 | +for enabled in [False,True]: |
| 42 | + analyses.append(dict(title='Captured tool context' if enabled else 'Without tool inventory',input=pack, |
| 43 | + artifacts={'facts.txt':text,'usage.jsonl':'\\n'.join(map(json.dumps,rows))},outputs={}, |
| 44 | + usage_jsonl='usage.jsonl',usage_session_id='session',include_tool_context=enabled)) |
| 45 | +broken=json.loads(json.dumps(analyses[-1])) |
| 46 | +broken['title']='Conflicting tool capture' |
| 47 | +conflicting=rows[:5]+[dict(type='response_item',payload=dict(type='function_call_output',call_id='control',output='different'))]+rows[5:] |
| 48 | +broken['artifacts']['usage.jsonl']='\\n'.join(map(json.dumps,conflicting)) |
| 49 | +analyses.append(broken) |
| 50 | +Path(sys.argv[1]).write_text(json.dumps(dict(goal_id=goal,display_name='Synthetic context cost study', |
| 51 | + events=[build_explore_node_event(goal_id=goal,node_id='question',title='Synthetic research question',recorded_at='2026-01-01T00:00:00Z')],analyses=analyses))) |
| 52 | +`, fixture], {cwd: repoRoot}); |
| 53 | + owner = await startHistoryOwner(fixture); |
| 54 | + page = await browser.newPage({viewport: {width: 1440, height: 900}}); |
| 55 | + const errors = []; |
| 56 | + page.on("pageerror", error => errors.push(error.message)); |
| 57 | + await page.goto(`${owner.base}/chat/?goalId=synthetic-context-reading&view=research&research_goal=synthetic-context-reading&statusUrl=%2Fstatus.json`, {waitUntil: "networkidle"}); |
| 58 | + const progress = page.locator('.research-progress'); |
| 59 | + const selector = progress.locator('select'); |
| 60 | + await selector.selectOption({label: 'Without tool inventory'}); |
| 61 | + await progress.locator('.research-usage').waitFor({state: 'attached'}); |
| 62 | + await page.screenshot({path: resolve(outputDir, 'research-tool-context-before.png'), animations: 'disabled'}); |
| 63 | + assert.equal(await progress.locator('[data-loopx-tool-context-share]').count(), 0); |
| 64 | + await selector.selectOption({label: 'Captured tool context'}); |
| 65 | + const basis = progress.locator('.research-progress-basis'); |
| 66 | + await basis.locator(':scope > summary').focus(); await page.keyboard.press('Enter'); |
| 67 | + const share = progress.locator('[data-loopx-tool-context-share]'); |
| 68 | + await share.waitFor({state: 'visible'}); |
| 69 | + assert.equal(await share.textContent(), '30%'); |
| 70 | + const inventory = progress.getByRole('region', {name: 'LoopX 工具上下文', exact: true}); |
| 71 | + const details = inventory.locator('details'); |
| 72 | + await details.locator('summary').focus(); await page.keyboard.press('Enter'); |
| 73 | + assert.match(await details.innerText(), /60 B/); |
| 74 | + assert.match(await details.innerText(), /200 B/); |
| 75 | + assert.match(await details.innerText(), /quota context-read/); |
| 76 | + for (const width of [1440, 390]) { |
| 77 | + await page.setViewportSize({width, height: 900}); |
| 78 | + await inventory.scrollIntoViewIfNeeded(); |
| 79 | + assert(await inventory.evaluate(node => node.scrollWidth <= node.clientWidth + 1)); |
| 80 | + await page.screenshot({path: resolve(outputDir, `research-tool-context-${width}.png`), animations: 'disabled'}); |
| 81 | + } |
| 82 | + await page.evaluate(() => localStorage.setItem('loopx-pw-locale', 'en')); |
| 83 | + await page.reload({waitUntil: 'networkidle'}); |
| 84 | + const english = progress.getByRole('region', {name: 'LoopX tool context', exact: true}); |
| 85 | + await share.waitFor({state: 'attached'}); |
| 86 | + if (!await progress.locator('.research-progress-basis').evaluate(node => node.open)) { |
| 87 | + await progress.locator('.research-progress-basis > summary').focus(); await page.keyboard.press('Enter'); |
| 88 | + } |
| 89 | + await english.waitFor({state: 'visible'}); |
| 90 | + assert.equal(await share.textContent(), '30%'); |
| 91 | + await selector.selectOption({label: 'Conflicting tool capture'}); |
| 92 | + const unavailable = progress.getByRole('region', {name: 'LoopX tool context', exact: true, includeHidden: true}); |
| 93 | + await unavailable.locator('[role="status"]').waitFor({state: 'attached'}); |
| 94 | + if (!await progress.locator('.research-progress-basis').evaluate(node => node.open)) { |
| 95 | + await progress.locator('.research-progress-basis > summary').focus(); await page.keyboard.press('Enter'); |
| 96 | + } |
| 97 | + assert.match(await unavailable.innerText(), /share unknown/); |
| 98 | + assert.equal(await progress.locator('[data-loopx-tool-context-share]').count(), 0); |
| 99 | + const readback = await (await page.request.get(`${owner.base}/fixture/readback`)).json(); |
| 100 | + assert(readback.source_unchanged && readback.mutation_attempts === 0); |
| 101 | + assert.deepEqual(errors, []); |
| 102 | + return {coverageEntries: [], note: 'real-owner byte inventory, opt-out parity, unknown analysis, keyboard, desktop/phone and English; zero model calls'}; |
| 103 | + } catch (error) { |
| 104 | + if (page && !page.isClosed()) await page.screenshot({path: resolve(outputDir, 'research-tool-context-failed.png')}); |
| 105 | + throw error; |
| 106 | + } finally { |
| 107 | + await page?.close(); await owner?.close(); await rm(temporary, {recursive: true, force: true}); |
| 108 | + } |
| 109 | + }, |
| 110 | +}; |
0 commit comments