Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions chatbot/browser/live-deepseek.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Opt-in real-provider acceptance. Start TestWorkbenchBrowserServer with
// LOOPFORGE_BROWSER_DEEPSEEK_KEY; this test never reads or stores the key.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { chromium } from '@playwright/test';

const base = process.env.LOOPFORGE_BROWSER_TEST_URL || 'http://127.0.0.1:18089';
test('DeepSeek reply survives navigation and reload in the unified workbench', { timeout: 300_000 }, async () => {
const browser = await chromium.launch({ channel: 'chromium', headless: true, args: ['--no-sandbox'] });
try {
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(`${base}/login.html`);
await page.locator('[name="login"]').fill('browser-test');
await page.locator('[name="password"]').fill('disposable-browser-password');
await page.locator('#loginSubmit').click();
await page.waitForURL(url => url.pathname === '/');
const root = page.locator('#chatRoot');
const input = root.locator('.composer-column textarea');
await input.waitFor({ state: 'visible', timeout: 30_000 });
await root.getByRole('button', { name: 'CLI', exact: true }).click();
await root.locator('.permission-menu [role="menuitemradio"]').filter({ hasText: 'DeepSeek Harness' }).click();
await root.getByRole('button', { name: '选择模型', exact: true }).click();
const model = root.locator('.grasp-model-menu [role="menuitemradio"]').filter({ hasText: /deepseek.*flash/i }).first();
await model.waitFor({ state: 'visible', timeout: 30_000 });
await model.click();
const marker = `LIVE-ISSUE118-${Date.now()}`;
await input.fill(`这是只读测试。请只回复 ${marker},不要访问、修改或创建文件和平台对象。`);
const started = page.waitForResponse(response => new URL(response.url()).pathname === '/api/assistant/generations' && response.request().method() === 'POST');
await root.locator('.send-button').click();
const response = await started;
assert.equal(response.status(), 202, `generation returned HTTP ${response.status()}`);
const { sessionId } = await response.json();
assert.ok(sessionId);
await page.evaluate(() => window.loopforgePlatform.navigate('settings'));
await page.locator('#settingsView.active').waitFor();
await page.evaluate(() => { location.hash = '#/collaboration'; });
await input.waitFor({ state: 'visible' });
const deadline = Date.now() + 240_000;
let generation;
while (Date.now() < deadline) {
const snapshot = await page.request.get(`${base}/api/assistant/sessions/${encodeURIComponent(sessionId)}/generation`);
assert.equal(snapshot.status(), 200);
generation = await snapshot.json();
if (generation.status !== 'running') break;
await page.waitForTimeout(1000);
}
assert.equal(generation?.status, 'completed', JSON.stringify({status:generation?.status, error:generation?.error, failure:generation?.failure}));
await root.locator('.message.assistant').last().getByText(marker, { exact: false }).waitFor({ timeout: 30_000 });
await page.reload();
await root.locator('.message.assistant').last().getByText(marker, { exact: false }).waitFor({ timeout: 30_000 });
const saved = await page.request.get(`${base}/api/assistant/sessions/${encodeURIComponent(sessionId)}`);
assert.ok(saved.ok());
assert.ok((await saved.json()).messages.some(message => message.role === 'assistant' && message.content.includes(marker)));
assert.deepEqual(errors, []);
} finally { await browser.close(); }
});
40 changes: 40 additions & 0 deletions chatbot/browser/real-service.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Start the opt-in SQLite fixture with TestWorkbenchBrowserServer first.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { chromium } from '@playwright/test';

const base = process.env.LOOPFORGE_BROWSER_TEST_URL || 'http://127.0.0.1:18089';
test('real Go service: links, session recovery, drafts, settings and navigation', async () => {
const browser = await chromium.launch({channel:'chromium', headless:true, args:['--no-sandbox']});
try {
const page = await browser.newPage({viewport:{width:1440,height:900}});
const errors=[];
page.on('pageerror', e => errors.push(e.message));
await page.goto(`${base}/login.html`);
await page.locator('[name="login"]').fill('browser-test');
await page.locator('[name="password"]').fill('disposable-browser-password');
await page.locator('#loginSubmit').click();
await page.waitForURL(url => url.pathname === '/');
const response = await page.goto(`${base}/chatbot/?session=chat-browser-test`);
assert.equal(response.status(), 200);
await page.getByText('原有会话消息').first().waitFor({timeout:20000});
assert.equal(new URL(page.url()).searchParams.get('chatSession'),'chat-browser-test');
const input=page.locator('#chatRoot .composer-column textarea');
await input.fill('真实服务下保留草稿');
await page.evaluate(()=>window.loopforgePlatform.navigate('settings'));
await page.locator('#settingsView.active').waitFor();
await page.evaluate(()=>window.loopforgePlatform.setTheme('dark'));
assert.equal(await page.locator('html').getAttribute('data-theme'),'dark');
await page.goBack();
await input.waitFor({state:'visible'});
assert.equal(await input.inputValue(),'真实服务下保留草稿');
await page.reload();
await page.getByText('原有会话消息').first().waitFor({timeout:20000});
await input.waitFor({state:'visible'});
await page.waitForFunction(()=>document.querySelector('#chatRoot .composer-column textarea')?.value==='真实服务下保留草稿');
assert.equal(await page.locator('#chatNextFrame').count(),0);
await page.setViewportSize({width:390,height:844});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth),true);
assert.deepEqual(errors,[]);
} finally { await browser.close(); }
});
113 changes: 113 additions & 0 deletions chatbot/browser/unified-entry.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Browser-level integration check with a deterministic API fixture; no Docker
// or running platform is needed. Run after `npm run build`.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from '@playwright/test';
import { sampleBootstrap } from '../../webtest/lib/load-app.mjs';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../web');
const types = { '.html':'text/html', '.css':'text/css', '.js':'application/javascript', '.svg':'image/svg+xml', '.png':'image/png' };

test('main document mounts chat, preserves drafts, and shares theme and routing', async () => {
const server = http.createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://localhost').pathname;
const relative = pathname === '/' ? 'index.html' : pathname.startsWith('/chatbot/') ? 'native-chat/' + pathname.slice(9) : pathname.slice(1);
const file = path.resolve(root, relative);
if (!file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; }
try { const data = await readFile(file); res.writeHead(200, { 'content-type': types[path.extname(file)] || 'application/octet-stream' }); res.end(data); }
catch { res.writeHead(404).end(); }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
let browser;
try {
browser = await chromium.launch({ headless:true, channel:'chromium', args:['--no-sandbox'] });
const page = await browser.newPage({ viewport:{width:1440,height:900} });
const errors=[];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.EventSource = class { close() {} addEventListener() {} removeEventListener() {} };
window.WebSocket = class { close() {} addEventListener() {} removeEventListener() {} send() {} };
});
await page.route('**/api/**', async route => {
const url = new URL(route.request().url()), pathname=url.pathname;
const user={id:1,name:'Test User',username:'tester',isGuest:false,isPlatformAdmin:true};
let body=[];
if(pathname==='/api/auth/current') body={user,authRequired:false};
else if(pathname==='/api/bootstrap') body=sampleBootstrap();
else if(pathname==='/api/projects') body=sampleBootstrap().projects;
else if(pathname==='/api/users') body=[user];
else if(pathname==='/api/issues/issue-browser-test') body={id:'issue-browser-test',title:'需求转交测试',projectId:'project-1'};
else if(pathname==='/api/assistant/references') body={items:[{type:'sop',id:'sop-browser-test',name:'平台验收 · 脚本与审批',projectId:'project-1'}]};
else if(pathname==='/api/assistant/models') body={models:[],default:''};
else if(pathname.startsWith('/api/assistant/sessions/')) body={id:pathname.split('/').pop(),projectId:'',title:'浏览器测试会话',messages:[]};
else if(pathname==='/api/runners/default') body={runnerId:''};
else if(pathname==='/api/auth/local') body={enabled:false};
else if(pathname==='/api/capabilities') body={};
await route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(body)});
});
await page.goto(`http://127.0.0.1:${server.address().port}/#/collaboration`);
const composer=page.locator('#chatRoot .composer-column textarea');
await composer.waitFor({state:'visible',timeout:20000});
await composer.fill('保留这份草稿');
assert.equal(await page.locator('#chatNextFrame').count(),0);
assert.equal(await page.locator('#chatRoot .chat-shell').count(),1);
await page.evaluate(() => window.loopforgePlatform.navigate('settings'));
await page.locator('#settingsView.active').waitFor();
const resize=page.getByRole('button',{name:'调整侧栏宽度'});
await resize.focus();
await page.keyboard.press('ArrowRight');
await page.waitForFunction(() => document.querySelector('#chatRoot .chat-shell')?.style.getPropertyValue('--sidebar-width') === `${localStorage.getItem('agentflow.sidebarWidth')}px`);
assert.equal(await page.evaluate(() => document.querySelector('#chatRoot .chat-shell').style.getPropertyValue('--sidebar-width')), `${await page.evaluate(() => localStorage.getItem('agentflow.sidebarWidth'))}px`);
await page.evaluate(() => window.loopforgePlatform.setTheme('dark'));
assert.equal(await page.locator('html').getAttribute('data-theme'),'dark');
await page.evaluate(() => { location.hash='#/collaboration'; });
await composer.waitFor({state:'visible'});
assert.equal(await composer.inputValue(),'保留这份草稿');
await page.goto(`http://127.0.0.1:${server.address().port}/?chatSession=s-1#/collaboration/s-1`);
await page.getByText('浏览器测试会话').first().waitFor({timeout:10000});
assert.equal(new URL(page.url()).searchParams.get('chatSession'),'s-1');
await page.evaluate(() => window.loopforgePlatform.navigate('settings'));
await page.locator('#settingsView.active').waitFor();
await page.evaluate(() => { location.hash='#/collaboration'; });
await page.getByText('浏览器测试会话').first().waitFor({timeout:10000});
assert.equal(new URL(page.url()).searchParams.get('chatSession'),'s-1');
await page.evaluate(() => window.loopforgePlatform.navigate('settings'));
await page.locator('#settingsView.active').waitFor();
await page.goBack();
await page.locator('#collaborationView.active').waitFor();
assert.equal(new URL(page.url()).searchParams.get('chatSession'),'s-1');
await page.goForward();
await page.locator('#settingsView.active').waitFor();
await page.goBack();
await page.locator('#collaborationView.active').waitFor();
await page.setViewportSize({width:390,height:844});
await composer.waitFor({state:'visible'});
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await page.setViewportSize({width:1440,height:900});
await page.evaluate(() => window.loopforgePlatform.navigate('settings'));
await page.locator('#settingsView.active').waitFor();
await page.evaluate(() => openIssueInChat({id:'issue-browser-test',projectId:'project-1'}));
await page.waitForFunction(() => document.querySelector('#chatRoot .composer-column textarea')?.value.startsWith('@需求转交测试 '));
assert.deepEqual(errors,[]);
await page.addInitScript(() => localStorage.setItem('loopforge.lang','en'));
await page.goto(`http://127.0.0.1:${server.address().port}/#/collaboration`);
await composer.waitFor({state:'visible',timeout:20000});
await composer.fill('@');
await page.locator('#chatRoot .mention-options [role="option"]').filter({hasText:'SOP'}).click();
const option=page.locator('#chatRoot .mention-options [role="option"]').first();
await option.locator('strong').getByText('平台验收 · 脚本与审批',{exact:true}).waitFor();
await option.click();
assert.match(await composer.inputValue(), /@平台验收 · 脚本与审批 /);
await page.locator('#chatRoot .composer-attachment-file > span').filter({hasText:/^平台验收 · 脚本与审批$/}).waitFor();
await page.getByRole('button',{name:'移除引用 平台验收 · 脚本与审批'}).click();
assert.doesNotMatch(await composer.inputValue(), /平台验收/);
assert.deepEqual(errors,[]);
} finally {
await browser?.close();
await new Promise(resolve=>server.close(resolve));
}
});
2 changes: 1 addition & 1 deletion chatbot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<title>LoopForge 工作台</title>
</head>
<body>
<div id="root"></div>
<div id="chatRoot"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
28 changes: 28 additions & 0 deletions chatbot/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions chatbot/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@vitejs/plugin-react": "4.7.0",
"@vitest/coverage-v8": "4.1.12",
"jsdom": "26.1.0",
"postcss-selector-parser": "^7.1.0",
"prettier": "3.6.2",
"vite": "6.4.5",
"vitest": "4.1.12"
Expand Down
26 changes: 26 additions & 0 deletions chatbot/scope-chat-css.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import selectorParser from 'postcss-selector-parser';

// Restore the style boundary previously provided by the iframe. Portals are
// mounted inside #chatRoot so both component and overlay rules stay scoped.
export default function scopeChatCSS() {
return {
postcssPlugin: 'scope-chat-css',
Rule(rule) {
if (rule.parent?.type === 'atrule' && /keyframes$/i.test(rule.parent.name)) return;
const selectors = selectorParser().astSync(rule.selector);
rule.selector = selectors.nodes.map((selector) => {
let value = selector.toString().trim();
// Theme selectors refer to the host document, not a descendant of the
// workbench. Their declarations may also define workbench variables.
const themed = value.match(/^(?:html|:root)?(\[data-theme[^\]]*\])(?:\s+|$)/);
if (themed) {
value = value.slice(themed[0].length).trim();
return `${themed[1]} #chatRoot${value ? ' ' + value : ''}`;
}
// Standalone document roots now mean the workbench container.
value = value.replace(/^(?::root|html|body|#root)(?=$|[\s.:#\[])/, '').trim();
return `#chatRoot${value ? ' ' + value : ''}`;
}).join(', ');
},
};
}
Loading
Loading