Files
pipelines/web/test/chat-compaction-browser.mjs
T

74 lines
5.4 KiB
JavaScript

// Native compaction fixture through the real chat fold/view; no harness calls.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const out = resolve(process.argv[2] ?? "captures-chat-compaction");
await mkdir(out, {recursive:true});
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread, applyChatEvent, resumedThread } from '/src/chat.js';
const id='scratch';
const state={view:'chat',connection:{kind:'connected'},chatSubscriptions:new Set(),chatActiveId:id,chatSessions:[{id,title:'Context compaction',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map()};
const repo={subscribeChat:async()=>{event('running');},chatHistory:async()=>({messages:state.chatThreads.get(id).messages}),chatShells:async()=>[]};
const rt={state,repo,renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.setup=(history)=>{
const messages=[{id:'user',role:'user',parts:[{type:'text',text:'Continue the task.'}]}];
if(history)messages.push({id:'assistant',role:'assistant',parts:[{id:'reason',type:'reasoning',text:'Inspecting the existing context.'},{id:'tool',type:'tool',name:'read',state:{status:'completed'}},{type:'text',text:'Continuing after checking the files.'}]});
state.chatThreads.set(id,{...newChatThread(id),loaded:true,messages});paint();};
window.event=(status)=>{state.chatThreads.set(id,applyChatEvent(state.chatThreads.get(id),{session_id:id,kind:'compaction',compaction:{id:'native-compaction',status}}));paint();};
window.end=()=>{state.chatThreads.set(id,applyChatEvent(state.chatThreads.get(id),{session_id:id,kind:'step',step:{status:'ended'}}));paint();};
window.drop=()=>{state.chatThreads.set(id,resumedThread(state.chatThreads.get(id)));paint();};
window.reconnect=()=>{state.chatSubscriptions.clear();return view.resyncOpenChat();};
window.messageCount=()=>state.chatThreads.get(id).messages.length;
setup(true);
</script>`;
const server=createServer(async(req,res)=>{try{
const path=new URL(req.url,"http://fixture").pathname;
if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}
const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");
res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));
}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));
let browser;
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector("#chatInput");
for(const width of [390,1100]) {
await page.resize(width,844);
for(const history of [false,true]) {
await page.evaluate(`setup(${history});event('running')`);
await page.waitForSelector(".chat-compaction-status");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status').textContent"),"Compacting context…");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status').getAttribute('role')"),"status");
assert.equal(await page.evaluate("messageCount()"),history?2:1);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),1);
if(history) assert.equal(await page.evaluate("document.querySelector('.chat-reasoning-label').textContent"),"Reasoning");
assert.equal(await page.evaluate("document.documentElement.scrollWidth>innerWidth"),false);
await page.screenshot(resolve(out,`compacting-${history?'with-history':'before-answer'}-${width}.png`));
await page.evaluate("event('completed')");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),1);
await page.evaluate("end()");
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),0);
}
}
await page.evaluate("setup(true);event('running');drop()");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
await page.screenshot(resolve(out,"compaction-clears-on-disconnect.png"));
await page.evaluate("reconnect()");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status')?.textContent"),"Compacting context…");
await page.screenshot(resolve(out,"compaction-replay-survives-history-refresh.png"));
console.log("PASS: native compaction is visible before/alongside answers, clears on completion/disconnect, survives reconnect history refresh, and creates no fake message or premature turn completion.");
} finally {await browser?.close();await new Promise(r=>server.close(r));}