fix(v0.3.4): 开始对话后保持选中的部门

会话切换会让工作台重挂载并重置 selectedSeatId,导致回到丞相;按项目缓存并在初始化时恢复上次选中的部门。
This commit is contained in:
qyh15 2026-11-17 23:15:34 +08:00
parent bada1e602c
commit 359d3e804d
5 changed files with 117 additions and 3 deletions

View File

@ -0,0 +1,43 @@
import { spawn } from 'node:child_process'
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const url = process.argv[2]
const EDGE = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
const profile = await mkdtemp(join(tmpdir(), 'ss-enable-'))
const sleep = ms => new Promise(r => setTimeout(r, ms))
let browser, ws
const out = {}
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)} }
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=90000)=>{ const end=Date.now()+t; while(Date.now()<end){ try{ if(await ev(x)) return true }catch{} await sleep(300) } return false }
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 waitFor("!!document.querySelector('.ssw-nav-hit')",60000)
await ev("document.querySelector('.ssw-nav-hit').click(); true")
await waitFor("!!document.querySelector('.ssw-root')",20000)
await sleep(2200)
await ev("(() => { const b=[...document.querySelectorAll('.ssw-seat')].find(x=>x.innerText.includes('工部')); if(b)b.click(); return !!b })()")
await sleep(400)
out.before = await ev("({ name: document.querySelector('.ssw-current-name')?.innerText, button: document.querySelector('.ssw-current-actions button')?.innerText })")
await ev("(() => { const b=document.querySelector('.ssw-current-actions button'); if(b)b.click(); return !!b })()")
await waitFor("(() => { const b=document.querySelector('.ssw-current-actions button'); return b && b.innerText.includes('开始对话') })", 120000)
await sleep(1500)
out.afterEnable = await ev("({ name: document.querySelector('.ssw-current-name')?.innerText, button: document.querySelector('.ssw-current-actions button')?.innerText, count: document.querySelector('.ssw-count')?.innerText })")
await ev("(() => { const b=document.querySelector('.ssw-current-actions button'); if(b)b.click(); return !!b })()")
await sleep(3500)
out.afterOpen = await ev("({ name: document.querySelector('.ssw-current-name')?.innerText ?? null, title: document.title })")
} catch(e) { out.fatal = String(e?.stack ?? e) } finally { try{ws?.close()}catch{}; try{browser?.kill()}catch{} }
console.log(JSON.stringify(out, null, 2))

41
preview/check-nav.mjs Normal file
View File

@ -0,0 +1,41 @@
import { spawn } from 'node:child_process'
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const url = process.argv[2]
const EDGE = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
const profile = await mkdtemp(join(tmpdir(), 'ss-nav-'))
const sleep = ms => new Promise(r => setTimeout(r, ms))
let browser, ws
const out = {}
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)} }
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=60000)=>{ const end=Date.now()+t; while(Date.now()<end){ try{ if(await ev(x)) return true }catch{} await sleep(300) } return false }
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 waitFor("!!document.querySelector('.ssw-nav-hit')",60000)
await ev("document.querySelector('.ssw-nav-hit').click(); true")
await waitFor("!!document.querySelector('.ssw-root')",20000)
await sleep(2200)
await ev("(() => { const b=[...document.querySelectorAll('.ssw-seat')].find(x=>x.innerText.includes('工部')); if(b)b.click(); return !!b })()")
await sleep(400)
out.selectedBefore = await ev("document.querySelector('.ssw-current-name')?.innerText")
await ev("(() => { const b=document.querySelector('.ssw-current-actions button'); if(b)b.click(); return !!b })()")
await sleep(3000)
out.titleAfter = await ev("document.title")
out.selectedAfter = await ev("document.querySelector('.ssw-current-name')?.innerText ?? null")
out.tab = await ev("(() => { const t=[...document.querySelectorAll('[role=tab]')].find(x=>(x.innerText||'').includes('三省六部')); return t ? t.getAttribute('aria-selected') : null })()")
} catch(e) { out.fatal = String(e?.stack ?? e) } finally { try{ws?.close()}catch{}; try{browser?.kill()}catch{} }
console.log(JSON.stringify(out, null, 2))

View File

@ -1205,6 +1205,8 @@ function apply(ctx) {
console.warn("[sansheng] 注册右侧标签失败:", error && error.message ? error.message : error);
}
}
const selectedSeatCache = /* @__PURE__ */ new Map();
let lastSelectedSeatId = SEAT_IDS[0];
function SanshengWorkbench(props) {
const onClose = props && props.onClose ? props.onClose : null;
const [phase, setPhase] = (0, import_react.useState)("loading");
@ -1213,7 +1215,7 @@ function apply(ctx) {
const [notice, setNotice] = (0, import_react.useState)(null);
const [view, setView] = (0, import_react.useState)(null);
const [models, setModels] = (0, import_react.useState)(null);
const [selectedSeatId, setSelectedSeatId] = (0, import_react.useState)(SEAT_IDS[0]);
const [selectedSeatId, setSelectedSeatId] = (0, import_react.useState)(lastSelectedSeatId);
const [draft, setDraft] = (0, import_react.useState)({});
const [busy, setBusy] = (0, import_react.useState)(false);
const [configOpen, setConfigOpen] = (0, import_react.useState)(false);
@ -1279,6 +1281,15 @@ function apply(ctx) {
(0, import_react.useEffect)(() => {
void loadProject();
}, [loadProject]);
const projectIdForSeat = view && view.project ? view.project.id : null;
(0, import_react.useEffect)(() => {
if (!projectIdForSeat) return;
const saved = selectedSeatCache.get(projectIdForSeat);
if (saved && SEAT_IDS.includes(saved)) {
lastSelectedSeatId = saved;
setSelectedSeatId(saved);
}
}, [projectIdForSeat]);
const wb = buildWorkbenchView(view, { selectedSeatId, models, draft });
const seatById = (0, import_react.useMemo)(() => {
const map = {};
@ -1291,6 +1302,9 @@ function apply(ctx) {
setSelectedSeatId(id);
setConfigOpen(false);
}
lastSelectedSeatId = id;
const pid = view && view.project ? view.project.id : null;
if (pid) selectedSeatCache.set(pid, id);
const seat = seatById[id];
if (seat && seat.status !== "bound" && seat.status !== "creating") setNotice("「" + seat.name + "」还没开启,点下面的按钮开启这个部门");
}

View File

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

View File

@ -320,6 +320,10 @@ export function apply(ctx) {
}
}
// 工作台会随宿主会话切换而重挂载;按项目记住选中的部门,避免又跳回丞相。
const selectedSeatCache = new Map()
let lastSelectedSeatId = SEAT_IDS[0]
// ---------- 工作台组件 ----------
function SanshengWorkbench(props) {
const onClose = props && props.onClose ? props.onClose : null
@ -329,7 +333,7 @@ export function apply(ctx) {
const [notice, setNotice] = useState(null)
const [view, setView] = useState(null)
const [models, setModels] = useState(null)
const [selectedSeatId, setSelectedSeatId] = useState(SEAT_IDS[0])
const [selectedSeatId, setSelectedSeatId] = useState(lastSelectedSeatId)
const [draft, setDraft] = useState({})
const [busy, setBusy] = useState(false)
const [configOpen, setConfigOpen] = useState(false)
@ -382,6 +386,15 @@ export function apply(ctx) {
}, [])
useEffect(() => { void loadProject() }, [loadProject])
const projectIdForSeat = view && view.project ? view.project.id : null
useEffect(() => {
if (!projectIdForSeat) return
const saved = selectedSeatCache.get(projectIdForSeat)
if (saved && SEAT_IDS.includes(saved)) {
lastSelectedSeatId = saved
setSelectedSeatId(saved)
}
}, [projectIdForSeat])
const wb = buildWorkbenchView(view, { selectedSeatId, models, draft })
const seatById = useMemo(() => {
@ -397,6 +410,9 @@ export function apply(ctx) {
setSelectedSeatId(id)
setConfigOpen(false)
}
lastSelectedSeatId = id
const pid = view && view.project ? view.project.id : null
if (pid) selectedSeatCache.set(pid, id)
const seat = seatById[id]
if (seat && seat.status !== 'bound' && seat.status !== 'creating') setNotice('「' + seat.name + '」还没开启,点下面的按钮开启这个部门')
}