fix(v0.1.5): 中间保持对话,右侧工作台正确落位

接入 better-sidebar 原生标签(排队落位),整行点击先切回会话再重试打开右栏,避免空白主区;当前席位新增「开始对话」按钮。
This commit is contained in:
qyh15 2026-11-17 15:42:49 +08:00
parent d537a07e73
commit 02935c62d0
6 changed files with 231 additions and 44 deletions

46
preview/check-v015.mjs Normal file
View File

@ -0,0 +1,46 @@
import { spawn } from 'node:child_process'
import { mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const url = process.argv[2]
const EDGE = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
const dir = dirname(fileURLToPath(import.meta.url))
const profile = await mkdtemp(join(tmpdir(), 'ss-v015-'))
const out = { consoleErrors: [] }
const sleep = ms => new Promise(r => setTimeout(r, ms))
let browser, ws
try {
browser = spawn(EDGE, ['--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--remote-debugging-port=0','--user-data-dir=' + profile, 'about:blank'], { stdio: ['ignore','ignore','pipe'] })
const endpoint = await new Promise((resolve, reject) => { let log=''; const t=setTimeout(()=>reject(Error('timeout')),20000); browser.stderr.on('data', b=>{ log+=b; const m=log.match(/DevTools listening on (.+)/); if(m){clearTimeout(t);resolve(m[1].trim())} }); browser.on('error',reject) })
ws = new WebSocket(endpoint); await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j})
let n=0; const pend=new Map()
ws.onmessage = e => { const m=JSON.parse(e.data); if(m.id){const p=pend.get(m.id);pend.delete(m.id);m.error?p.reject(Error(JSON.stringify(m.error))):p.resolve(m.result)} else if(m.method==='Runtime.exceptionThrown'){ out.consoleErrors.push((m.params.exceptionDetails.exception?.description||m.params.exceptionDetails.text||'').slice(0,200)) } }
const cdp=(method,params={},sid)=>new Promise((res,rej)=>{const id=++n;pend.set(id,{resolve:res,reject:rej});ws.send(JSON.stringify({id,method,params,...(sid?{sessionId:sid}:{})}))})
const { targetId } = await cdp('Target.createTarget', { url: 'about:blank' })
const { sessionId } = await cdp('Target.attachToTarget', { targetId, flatten: true })
const call=(m,p={})=>cdp(m,p,sessionId)
await call('Page.enable'); await call('Runtime.enable')
const ev = async x => { const r=await call('Runtime.evaluate',{expression:x,returnByValue:true,awaitPromise:true}); if(r.exceptionDetails) throw Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text); return r.result.value }
const waitFor = async (x,t=45000)=>{ const end=Date.now()+t; while(Date.now()<end){ try{ if(await ev(x)) return true }catch{} await sleep(250) } return false }
const shot = async name => { const r=await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false}); await writeFile(join(dir,name),Buffer.from(r.data,'base64')) }
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false})
await call('Page.navigate',{url})
await waitFor("document.readyState === 'complete'",30000)
try { await ev("(() => { const b=[...document.querySelectorAll('button')].find(x=>(x.innerText||'').trim()==='继续'); if(b)b.click(); return !!b })()") } catch {}
await sleep(700)
await waitFor("!!document.querySelector('.ssw-nav-hit')",60000)
if (process.argv.includes('--row')) await ev("(() => { const hit=document.querySelector('.ssw-nav-hit'); const row=hit?.closest('button, [role=button], li, a'); (row||hit)?.click(); return !!row })()")
else await ev("document.querySelector('.ssw-nav-hit').click(); true")
const opened = await waitFor("!!document.querySelector('.ssw-root')",20000)
await sleep(3000)
out.opened = opened
out.inlineBar = await ev("!!document.querySelector('.ssw-inline-bar')")
out.tabCount = await ev("[...document.querySelectorAll('[data-sidebar-right-tab]')].filter(e=>(e.innerText||'').includes('三省六部')).length")
out.rootRect = await ev("(() => { const r=document.querySelector('.ssw-root'); if(!r) return null; const b=r.getBoundingClientRect(); return { left:Math.round(b.left), width:Math.round(b.width), win:window.innerWidth } })()")
out.composer = await ev("(() => { const els=[...document.querySelectorAll('textarea, [contenteditable=true], .composer, [data-placeholder]')]; return els.map(e=>(e.getAttribute('placeholder')||e.className||e.tagName).toString().slice(0,40)).slice(0,5) })()")
out.mainText = await ev("(() => (document.querySelector('main')?.innerText||'').replace(/\\s+/g,' ').trim().slice(0,120))()")
out.startButtons = await ev("(() => [...document.querySelectorAll('.ssw-current-actions button')].map(b=>b.innerText.trim()))()")
await shot('v015-layout.png')
} catch(e) { out.fatal = String(e?.stack ?? e) } finally { try{ws?.close()}catch{}; try{browser?.kill()}catch{} }
console.log(JSON.stringify(out, null, 2))

BIN
preview/v015-layout.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

@ -449,6 +449,9 @@ body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background:
.ssw-nav-hit{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;color:inherit;cursor:pointer}
.ssw-nav-hit svg{width:16px;height:16px;flex:none;display:block}
.ssw-hint{margin:6px 0 0;font-size:11px;color:var(--ssw-faint)}
.ssw-current-actions{margin-top:10px;display:flex;gap:8px}
.ssw-inline-bar{flex:none;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 12px;border-bottom:1px solid var(--ssw-line);background:var(--ssw-card);font-size:12px;color:var(--ssw-muted)}
.ssw-link{color:var(--ssw-blue);font-size:12px;padding:2px 4px}
@media (prefers-reduced-motion:reduce){.ssw-scope *{transition:none!important}}
.ssw-tab-body{height:100%;min-height:0;display:flex;flex-direction:column}
.ssw-tab-body .ssw-root{flex:1;min-height:0}
@ -1033,6 +1036,19 @@ function apply(ctx) {
}
}
function tryOpenRightTab() {
const bs = get("betterSidebar");
if (bs && isFn(bs.openTab)) {
try {
const snap = isFn(bs.getSnapshot) ? bs.getSnapshot() : null;
const sessionId = snap && typeof snap === "object" ? snap.sessionId : void 0;
if (!sessionId) return false;
bs.openTab({ type: TAB_KIND, title: "三省六部" });
for (const delay of [200, 600, 1200]) setTimeout(revealRightTab, delay);
return true;
} catch (error) {
console.warn("[sansheng] better-sidebar 打开失败,改用宿主接口:", error && error.message ? error.message : error);
}
}
const right = get("sidebarRight");
if (!right || !isFn(right.openTab)) return false;
if (!ensureRightTab()) return false;
@ -1043,11 +1059,7 @@ function apply(ctx) {
return false;
}
revealRightTab();
try {
const rows = isFn(right.openTabs?.getSnapshot) ? right.openTabs.getSnapshot() : null;
if (Array.isArray(rows) && rows.length > 0 && !rows.some((item) => item && item.kind === TAB_KIND)) return false;
} catch {
}
for (const delay of [150, 500, 1200]) setTimeout(revealRightTab, delay);
return true;
}
function SanshengTabBody() {
@ -1057,6 +1069,28 @@ function apply(ctx) {
return (0, import_react.createElement)("span", { className: "ssw-tab-title" }, "三省六部");
}
function registerRightTabType() {
try {
const bs = get("betterSidebar");
if (bs && isFn(bs.registerTab)) {
const dispose = bs.registerTab({
id: TAB_KIND,
title: "三省六部",
description: "十席角色与独立会话的当前项目工作台",
icon: (size) => (0, import_react.createElement)(TreeIcon, { width: size, height: size }),
order: 32,
single: true,
component: () => (0, import_react.createElement)("div", { className: "ssw-tab-body" }, (0, import_react.createElement)(SanshengWorkbench, {}))
});
return () => {
try {
if (isFn(dispose)) dispose();
} catch {
}
};
}
} catch (error) {
console.warn("[sansheng] 注册 better-sidebar 标签失败:", error && error.message ? error.message : error);
}
try {
if (!isFn(ctx.inject)) return;
ctx.inject(["sidebarRightTabs"], (injected) => {
@ -1310,7 +1344,22 @@ function apply(ctx) {
(0, import_react.createElement)("strong", { className: "ssw-current-name" }, wb.selected.name),
(0, import_react.createElement)("span", { className: "ssw-current-label" }, "角色职责 · " + wb.selected.statusLabel)
),
(0, import_react.createElement)("p", { className: "ssw-current-text" }, wb.selected.responsibility)
(0, import_react.createElement)("p", { className: "ssw-current-text" }, wb.selected.responsibility),
(0, import_react.createElement)(
"div",
{ className: "ssw-current-actions" },
wb.ready ? (0, import_react.createElement)("button", {
type: "button",
className: "ssw-primary",
disabled: busy,
onClick: () => pickSeat(wb.selected.id)
}, "开始对话") : (0, import_react.createElement)("button", {
type: "button",
className: "ssw-primary",
disabled: busy,
onClick: enableSeats
}, busy ? "正在启用…" : "启用此项目的十席")
)
);
const optionEls = wb.selected.modelOptions.map((option) => (0, import_react.createElement)("option", { key: option.value, value: option.value }, option.label));
if (wb.selected.modelValue && !wb.selected.modelOptions.some((option) => option.value === wb.selected.modelValue)) {
@ -1440,6 +1489,9 @@ function apply(ctx) {
function SanshengNavButton(props) {
const size = props && typeof props.size === "number" ? props.size : 16;
const [floating, setFloating] = (0, import_react.useState)(false);
const stop = (event) => {
if (event && isFn(event.stopPropagation)) event.stopPropagation();
};
const onClick = (event) => {
if (event && isFn(event.stopPropagation)) event.stopPropagation();
if (event && isFn(event.preventDefault)) event.preventDefault();
@ -1467,38 +1519,61 @@ function apply(ctx) {
role: "presentation",
title: "三省六部",
onClick,
onPointerDown: stop,
onMouseDown: stop,
"aria-expanded": floating ? "true" : "false"
}, (0, import_react.createElement)(TreeIcon, { width: size, height: size })),
panel
);
}
function backToChat() {
const layout = get("layout");
if (layout && isFn(layout.selectPanel)) {
try {
layout.selectPanel(null);
} catch {
}
}
}
function SanshengNavFallback() {
const [mode, setMode] = (0, import_react.useState)("pending");
(0, import_react.useEffect)(() => {
setMode(openRightWorkbench() ? "docked" : "inline");
const hasBetter = !!get("betterSidebar");
backToChat();
if (!hasBetter) {
const timer = setTimeout(() => {
if (!openRightWorkbench()) setMode("inline");
}, 400);
return () => clearTimeout(timer);
}
for (const delay of [200, 600, 1200, 2e3]) {
setTimeout(() => {
try {
if (openRightWorkbench()) backToChat();
} catch {
}
}, delay);
}
}, []);
(0, import_react.useEffect)(() => {
if (mode !== "docked") return;
const layout = get("layout");
if (layout && isFn(layout.selectPanel)) {
try {
layout.selectPanel(null);
} catch {
}
}
backToChat();
const timer = setTimeout(backToChat, 700);
return () => clearTimeout(timer);
}, [mode]);
if (mode !== "inline") return null;
return (0, import_react.createElement)("div", { className: "ssw-tab-body" }, (0, import_react.createElement)(SanshengWorkbench, {
onClose: () => {
const layout = get("layout");
if (layout && isFn(layout.selectPanel)) {
try {
layout.selectPanel(null);
} catch {
}
}
}
}));
if (mode === "pending") return null;
if (mode === "docked") return null;
return (0, import_react.createElement)(
"div",
{ className: "ssw-tab-body" },
(0, import_react.createElement)(
"div",
{ className: "ssw-inline-bar" },
(0, import_react.createElement)("span", null, "右侧工作台未能打开,先显示在这里"),
(0, import_react.createElement)("button", { type: "button", className: "ssw-link", onClick: backToChat }, "返回对话")
),
(0, import_react.createElement)(SanshengWorkbench, {})
);
}
function registerNavEntry() {
if (!ctx.slots || !isFn(ctx.slots.inject) || !isFn(ctx.slots.register)) {

View File

@ -1,6 +1,6 @@
{
"name": "dsh-sansheng-liubu",
"version": "0.1.4",
"version": "0.1.5",
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
"keywords": [
"dsh-plugin",

View File

@ -212,6 +212,21 @@ export function apply(ctx) {
}
}
function tryOpenRightTab() {
// 桌面版右栏由 dsh-better-sidebar 接管:它自己的 openTab 会排队等待会话面板挂载,
// 主区正被切走时也不会丢;直接调宿主 sidebarRight 反而会因“没有挂载的会话面板”失败。
const bs = get('betterSidebar')
if (bs && isFn(bs.openTab)) {
try {
const snap = isFn(bs.getSnapshot) ? bs.getSnapshot() : null
const sessionId = snap && typeof snap === 'object' ? snap.sessionId : undefined
if (!sessionId) return false
bs.openTab({ type: TAB_KIND, title: '三省六部' })
for (const delay of [200, 600, 1200]) setTimeout(revealRightTab, delay)
return true
} catch (error) {
console.warn('[sansheng] better-sidebar 打开失败,改用宿主接口:', error && error.message ? error.message : error)
}
}
const right = get('sidebarRight')
if (!right || !isFn(right.openTab)) return false
if (!ensureRightTab()) return false
@ -219,12 +234,10 @@ export function apply(ctx) {
console.warn('[sansheng] 打开右侧标签失败,改用浮动面板:', error && error.message ? error.message : error)
return false
}
// 右栏(尤其 better-sidebar 的原生面)是异步落位的,不能同步看不到就当失败,
// 否则会误退成主区渲染、把中间聊天顶掉。这里先乐观返回,再多次补一次聚焦/展开。
revealRightTab()
// 确认页签确实出现;宿主拒绝(例如当前没有会话面板)时返回 false,让调用方回退,避免“点了没反应”。
try {
const rows = isFn(right.openTabs?.getSnapshot) ? right.openTabs.getSnapshot() : null
if (Array.isArray(rows) && rows.length > 0 && !rows.some(item => item && item.kind === TAB_KIND)) return false
} catch { /* 读不到就按已打开处理 */ }
for (const delay of [150, 500, 1200]) setTimeout(revealRightTab, delay)
return true
}
function SanshengTabBody() {
@ -235,6 +248,24 @@ export function apply(ctx) {
}
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
function registerRightTabType() {
// 桌面版:向 better-sidebar 注册一个原生右侧标签(它自己负责正文/标题与落位)。
try {
const bs = get('betterSidebar')
if (bs && isFn(bs.registerTab)) {
const dispose = bs.registerTab({
id: TAB_KIND,
title: '三省六部',
description: '十席角色与独立会话的当前项目工作台',
icon: (size) => h(TreeIcon, { width: size, height: size }),
order: 32,
single: true,
component: () => h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {})),
})
return () => { try { if (isFn(dispose)) dispose() } catch { /* 忽略 */ } }
}
} catch (error) {
console.warn('[sansheng] 注册 better-sidebar 标签失败:', error && error.message ? error.message : error)
}
try {
if (!isFn(ctx.inject)) return
ctx.inject(['sidebarRightTabs'], (injected) => {
@ -445,6 +476,16 @@ export function apply(ctx) {
h('span', { className: 'ssw-current-label' }, '角色职责 · ' + wb.selected.statusLabel),
),
h('p', { className: 'ssw-current-text' }, wb.selected.responsibility),
h('div', { className: 'ssw-current-actions' },
wb.ready
? h('button', {
type: 'button', className: 'ssw-primary', disabled: busy,
onClick: () => pickSeat(wb.selected.id),
}, '开始对话')
: h('button', {
type: 'button', className: 'ssw-primary', disabled: busy, onClick: enableSeats,
}, busy ? '正在启用…' : '启用此项目的十席'),
),
)
const optionEls = wb.selected.modelOptions.map(option => h('option', { key: option.value, value: option.value }, option.label))
@ -557,6 +598,9 @@ export function apply(ctx) {
function SanshengNavButton(props) {
const size = props && typeof props.size === 'number' ? props.size : 16
const [floating, setFloating] = useState(false)
const stop = (event) => {
if (event && isFn(event.stopPropagation)) event.stopPropagation()
}
const onClick = (event) => {
if (event && isFn(event.stopPropagation)) event.stopPropagation()
if (event && isFn(event.preventDefault)) event.preventDefault()
@ -573,6 +617,7 @@ export function apply(ctx) {
return h(Fragment, null,
h('span', {
className: 'ssw-nav-hit', role: 'presentation', title: '三省六部', onClick,
onPointerDown: stop, onMouseDown: stop,
'aria-expanded': floating ? 'true' : 'false',
}, h(TreeIcon, { width: size, height: size })),
panel,
@ -581,25 +626,43 @@ export function apply(ctx) {
// 兜底:若宿主按整行点击切了主区,先把工作台打开到右侧并切回会话;
// 右侧打不开时就在主区直接渲染工作台(而不是空白),保证点击一定有反应。
function backToChat() {
const layout = get('layout')
if (layout && isFn(layout.selectPanel)) { try { layout.selectPanel(null) } catch { /* 忽略 */ } }
}
function SanshengNavFallback() {
const [mode, setMode] = useState('pending')
useEffect(() => {
setMode(openRightWorkbench() ? 'docked' : 'inline')
// 整行点击会先把主区切成本页(此时会话面板已卸载,右栏开不了)。
// 立刻切回会话,然后在会话重新挂载后用全局定时器重试打开右栏;
// 这些定时器不随本组件卸载取消,否则切回会话就把自己“清理”掉了。
const hasBetter = !!get('betterSidebar')
backToChat()
if (!hasBetter) {
const timer = setTimeout(() => { if (!openRightWorkbench()) setMode('inline') }, 400)
return () => clearTimeout(timer)
}
for (const delay of [200, 600, 1200, 2000]) {
setTimeout(() => {
try { if (openRightWorkbench()) backToChat() } catch { /* 忽略 */ }
}, delay)
}
}, [])
useEffect(() => {
if (mode !== 'docked') return
const layout = get('layout')
if (layout && isFn(layout.selectPanel)) {
try { layout.selectPanel(null) } catch { /* 忽略 */ }
}
backToChat()
const timer = setTimeout(backToChat, 700)
return () => clearTimeout(timer)
}, [mode])
if (mode !== 'inline') return null
return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {
onClose: () => {
const layout = get('layout')
if (layout && isFn(layout.selectPanel)) { try { layout.selectPanel(null) } catch { /* 忽略 */ } }
},
}))
if (mode === 'pending') return null
if (mode === 'docked') return null
return h('div', { className: 'ssw-tab-body' },
h('div', { className: 'ssw-inline-bar' },
h('span', null, '右侧工作台未能打开,先显示在这里'),
h('button', { type: 'button', className: 'ssw-link', onClick: backToChat }, '返回对话'),
),
h(SanshengWorkbench, {}),
)
}
function registerNavEntry() {

View File

@ -81,6 +81,9 @@ body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background:
.ssw-nav-hit{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;color:inherit;cursor:pointer}
.ssw-nav-hit svg{width:16px;height:16px;flex:none;display:block}
.ssw-hint{margin:6px 0 0;font-size:11px;color:var(--ssw-faint)}
.ssw-current-actions{margin-top:10px;display:flex;gap:8px}
.ssw-inline-bar{flex:none;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 12px;border-bottom:1px solid var(--ssw-line);background:var(--ssw-card);font-size:12px;color:var(--ssw-muted)}
.ssw-link{color:var(--ssw-blue);font-size:12px;padding:2px 4px}
@media (prefers-reduced-motion:reduce){.ssw-scope *{transition:none!important}}
.ssw-tab-body{height:100%;min-height:0;display:flex;flex-direction:column}
.ssw-tab-body .ssw-root{flex:1;min-height:0}