feat: 内容窗收敛4项 + 终端loadPkg修复(E2E验证) + 文件路由 + 标签跨窗拖动吸附 + 自动化测试

This commit is contained in:
Aisland
2026-08-17 12:49:27 +08:00
parent eabd367e48
commit dcb75d78cc
7 changed files with 329 additions and 17 deletions
+88
View File
@@ -0,0 +1,88 @@
const http = require('http');
const { spawn } = require('child_process');
const WebSocket = require('ws');
const PORT = 9335;
const proc = spawn('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', [
'--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check',
'--remote-debugging-port=' + PORT,
'--user-data-dir=C:\\Users\\SJL\\AppData\\Local\\Temp\\wt-chrome-func2',
'about:blank',
], { stdio: 'ignore' });
function getJSON(path) {
return new Promise((res, rej) => {
http.get({ host: '127.0.0.1', port: PORT, path }, (r) => {
let d = '';
r.on('data', (c) => d += c);
r.on('end', () => { try { res(JSON.parse(d)) } catch (e) { rej(e) } });
}).on('error', rej);
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
let list = null;
for (let i = 0; i < 40; i++) {
try { list = await getJSON('/json/list'); if (list && list.length) break; } catch {}
await sleep(500);
}
const target = list.find((t) => t.type === 'page') || list[0];
const ws = new WebSocket(target.webSocketDebuggerUrl);
let id = 0;
const pending = new Map();
const events = [];
const send = (method, params) => new Promise((res) => {
const mid = ++id;
pending.set(mid, res);
ws.send(JSON.stringify({ id: mid, method, params }));
});
ws.on('message', (raw) => {
const msg = JSON.parse(String(raw));
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
else if (msg.method) events.push(msg);
});
await new Promise((r) => ws.on('open', r));
await send('Runtime.enable');
await send('Log.enable');
await send('Page.enable');
await send('Page.navigate', { url: 'http://127.0.0.1:3080/' });
await sleep(11000);
const evaluate = async (expr) => {
const r = await send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true });
if (r.result && r.result.exceptionDetails) return { error: (r.result.exceptionDetails.exception || {}).description || r.result.exceptionDetails.text };
return r.result && r.result.result ? r.result.result.value : undefined;
};
const step1 = await evaluate("(function(){ var out={}; out.debugExport=!!window.__dshWorktable; var st=window.__dshWorktable&&window.__dshWorktable.splitStore; if(!st) return JSON.stringify(out); out.openResult=st.open({id:'t-diag',title:'diag',top:null,main:[{id:'p1',title:'1',min:200,content:null},{id:'p2',title:'2',min:200,content:null}],chatWidth:{default:320,min:240,max:600}}); out.afterOpen={active:st.active,spec:st.spec&&st.spec.id}; return JSON.stringify(out) })()");
console.log('STEP1:', JSON.stringify(step1));
await sleep(900);
const step2 = await evaluate("(function(){ var out={}; out.pickers=document.querySelectorAll('.dsh-wt_panePicker').length; out.pickButtons=document.querySelectorAll('.dsh-wt_panePick').length; var st=window.__dshWorktable.splitStore; st.openTab('main',0,{kind:'builtin',type:'browser'}); st.openTab('main',1,{kind:'builtin',type:'explorer'}); return JSON.stringify(out) })()");
console.log('STEP2:', JSON.stringify(step2));
await sleep(900);
const step3 = await evaluate("(function(){ var out={}; out.browserBar=document.querySelectorAll('.dsh-wt_browserBar').length; out.browserIframe=document.querySelectorAll('.dsh-wt_paneFrame').length; out.explorerBars=document.querySelectorAll('.dsh-wt_subBar').length; out.tabs=document.querySelectorAll('.dsh-wt_tab').length; return JSON.stringify(out) })()");
console.log('STEP3:', JSON.stringify(step3));
const step4 = await evaluate("(function(){ var st=window.__dshWorktable.splitStore; var tabId=st.spec.main[0].tabs[0].id; st.moveTab('main',0,tabId,'main',1); var out={pane0Tabs:(st.spec.main[0].tabs||[]).length,pane1Tabs:(st.spec.main[1].tabs||[]).length}; return JSON.stringify(out) })()");
console.log('STEP4:', JSON.stringify(step4));
await sleep(700);
const step5 = await evaluate("(function(){ var out={}; out.pane0PickerBack=document.querySelectorAll('.dsh-wt_panePicker').length; var st=window.__dshWorktable.splitStore; st.close(); out.closed=st.active===false; return JSON.stringify(out) })()");
console.log('STEP5:', JSON.stringify(step5));
const errors = events.filter((e) =>
e.method === 'Runtime.exceptionThrown' ||
(e.method === 'Log.entryAdded' && e.params.entry.level === 'error') ||
(e.method === 'Runtime.consoleAPICalled' && e.params.type === 'error'),
).slice(0, 10).map((e) => e.method === 'Runtime.exceptionThrown'
? 'EXCEPTION: ' + ((e.params.exceptionDetails.exception || {}).description || e.params.exceptionDetails.text)
: 'LOG: ' + (e.params.entry ? e.params.entry.text : '').slice(0, 200));
console.log('ERRORS_COUNT:', errors.length);
errors.forEach((x) => console.log(x));
ws.close();
proc.kill();
process.exit(0);
})().catch((e) => { console.log('SCRIPT_FAIL:', e); proc.kill(); process.exit(1); });
+28
View File
@@ -0,0 +1,28 @@
const { createRequire } = require('module');
const { pathToFileURL } = require('url');
const fs = require('fs');
const os = require('os');
const path = require('path');
function tryResolve(fromDir, pkg) {
try {
const req = createRequire(pathToFileURL(fromDir.replace(/\\/g,'/') + '/__probe__.js').href);
return req.resolve(pkg);
} catch (e) { return null; }
}
console.log('--- 沿 junction 链 ---');
let d = 'C:/Users/SJL/.dsh/profiles/web/node_modules/dsh-worktable/lib';
while (true) {
const r = tryResolve(d, 'ws');
if (r) { console.log('FOUND at', d, '->', r); break; }
const parent = d.replace(/[\\/][^\\/]+$/, '');
if (!parent || parent === d) { console.log('链走完未找到'); break; }
d = parent;
}
console.log('--- homedir profiles 兜底 ---');
const pd = path.resolve(os.homedir(), '.dsh', 'profiles');
console.log('profilesDir:', pd, 'exists:', fs.existsSync(pd));
for (const p of fs.readdirSync(pd, { withFileTypes: true })) {
const nm = path.resolve(pd, p.name, 'node_modules');
console.log(p.name, 'isDir:', p.isDirectory(), 'nmExists:', fs.existsSync(nm), 'ws:', tryResolve(nm, 'ws'), 'pty:', tryResolve(nm, 'node-pty'));
}
+53
View File
@@ -0,0 +1,53 @@
/**
* 终端端到端测试:模拟宿主加载方式(经 profile junction 路径 import 服务端 bundle),
* 用真实 http server + ws 客户端验证 /api/worktable/term 能否拉起 shell。
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
(async () => {
const bundleUrl = 'file:///C:/Users/SJL/.dsh/profiles/web/node_modules/dsh-worktable/lib/index.js';
const mod = await import(bundleUrl);
const upgrades = [];
const routes = [];
const ctx = {
logger: {
warn: (...a) => console.log('[logger-warn]', ...a),
info: (...a) => console.log('[logger-info]', ...a),
},
sessions: { get: () => undefined },
webServer: {
register(r) { routes.push(r); return () => {} },
registerUpgrade(r) { upgrades.push(r); return () => {} },
},
};
mod.apply(ctx);
await new Promise((r) => setTimeout(r, 2500)); // 等异步 setupTerminal 完成(真实宿主进程长驻)
console.log('routes:', routes.map((r) => r.path).join(', '));
console.log('upgrade routes:', upgrades.map((r) => r.path).join(', ') || '(none)');
if (upgrades.length === 0) { console.log('RESULT: NO_TERMINAL_ROUTE'); process.exit(1); }
const server = http.createServer((req, res) => { res.writeHead(404); res.end(); });
server.on('upgrade', (req, socket, head) => {
const u = new URL(req.url ?? '/', 'http://x');
const route = upgrades.find((r) => u.pathname === r.path);
if (!route) { socket.destroy(); return; }
route.handler(req, socket, head);
});
await new Promise((r) => server.listen(19087, '127.0.0.1', r));
const ws = new WebSocket('ws://127.0.0.1:19087/api/worktable/term?cwd=' + encodeURIComponent(process.cwd()) + '&cols=80&rows=24');
const received = [];
const done = (code, msg) => { console.log('RESULT: ' + code + ' ' + msg); try { ws.close(); } catch {} server.close(); process.exit(code === 'PASS' ? 0 : 1); };
const timer = setTimeout(() => done('FAIL', '10s 内无输出'), 10000);
ws.on('open', () => { ws.send('echo __WT_TERM_OK__\r'); });
ws.on('message', (d) => {
const t = String(d);
received.push(t);
if (t.includes('__WT_TERM_OK__')) { clearTimeout(timer); done('PASS', 'shell 回显正常 (' + received.length + ' 帧)'); }
});
ws.on('error', (e) => { clearTimeout(timer); done('FAIL', String(e)); });
})().catch((e) => { console.log('RESULT: HARNESS_FAIL', e); process.exit(1); });