diff --git a/sansheng/client.js b/sansheng/client.js index fddcc03..aeff42a 100644 --- a/sansheng/client.js +++ b/sansheng/client.js @@ -1496,6 +1496,51 @@ function WorkbenchV2(props) { ); } +// src/client/workspace.js +function samePath(a, b) { + if (typeof a !== "string" || typeof b !== "string") return false; + const norm = (value) => value.replace(/\//g, "\\").replace(/\\+$/g, "").toLowerCase(); + return norm(a) === norm(b); +} +function baseName(path) { + if (typeof path !== "string") return void 0; + const parts = path.replace(/\/+$/g, "").split(/[\\/]/).filter(Boolean); + return parts.length ? parts[parts.length - 1] : void 0; +} +function normalizeWorkspaceItem(item) { + if (!item || typeof item !== "object") return null; + const workspaceId = item.workspaceId ?? item.id ?? null; + if (typeof workspaceId !== "string" || !workspaceId) return null; + return { + workspaceId, + name: typeof item.name === "string" ? item.name : typeof item.title === "string" ? item.title : void 0, + path: typeof item.path === "string" ? item.path : void 0, + sessionIds: Array.isArray(item.sessionIds) ? item.sessionIds : void 0 + }; +} +function workspaceItemsFromSnapshot(snapshot) { + const items = Array.isArray(snapshot) ? snapshot : snapshot && typeof snapshot === "object" && Array.isArray(snapshot.items) ? snapshot.items : []; + return items.map(normalizeWorkspaceItem).filter(Boolean); +} +function sessionSummaryFromSnapshot(snapshot, sessionId) { + if (!snapshot || typeof snapshot !== "object" || typeof sessionId !== "string" || !sessionId) return null; + const byId = snapshot.byId; + if (!byId || typeof byId !== "object") return null; + const summary = byId[sessionId]; + return summary && typeof summary === "object" ? summary : null; +} +function workspaceForSession(items, sessionId, sessionSummary) { + const list = (Array.isArray(items) ? items : []).map(normalizeWorkspaceItem).filter(Boolean); + if (typeof sessionId !== "string" || !sessionId) return null; + const bySession = list.find((item) => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId)); + if (bySession) return bySession; + const cwd = sessionSummary && typeof sessionSummary.cwd === "string" ? sessionSummary.cwd : ""; + if (!cwd) return null; + const byPath = list.find((item) => item.path && samePath(item.path, cwd)); + if (byPath) return byPath; + return { workspaceId: null, name: baseName(cwd), path: cwd, sessionIds: [sessionId] }; +} + // src/client/styles.js var CSS = `.ssv2{ /* ============ shadcn 式干净后台:平整、利落、高对比 ============ @@ -2550,7 +2595,7 @@ var native_default = { install }; // src/client/index.js var import_react2 = require("react"); var import_react_dom = require("react-dom"); -var inject = ["sessions", "uiWorkspace", "uiConversation", "slots", "theme", "layout", "sidebarRightTabs", "sidebarRight"]; +var inject = ["sessions", "workspaces", "uiWorkspace", "uiConversation", "slots", "theme", "layout", "sidebarRightTabs", "sidebarRight"]; var PLUGIN_ID = "dsh-sansheng"; var TAB_KIND = "sansheng-workbench"; var TAB_TYPE_ID = "dsh-sansheng:workbench"; @@ -2677,22 +2722,23 @@ function apply(ctx) { return void 0; } }; + function sessionsSnapshot() { + return snapshotOf(get("sessions")?.list) ?? snapshotOf(get("sessions")); + } function workspaceItems() { - const fromWorkspaces = snapshotOf(get("workspaces")?.list)?.items; - if (Array.isArray(fromWorkspaces)) return fromWorkspaces; - const fromUi = snapshotOf(get("uiWorkspace")?.workspaces)?.items; - if (Array.isArray(fromUi)) return fromUi; + const sources = [ + get("workspaces")?.list, + get("uiWorkspace")?.workspaces, + get("workspaces") + ]; + for (const source of sources) { + const items = workspaceItemsFromSnapshot(snapshotOf(source)); + if (items.length) return items; + } return []; } - function normalizeWorkspace(item) { - if (!item || typeof item !== "object") return null; - const workspaceId = item.workspaceId ?? item.id ?? null; - if (typeof workspaceId !== "string" || !workspaceId) return null; - return { - workspaceId, - name: typeof item.name === "string" ? item.name : typeof item.title === "string" ? item.title : void 0, - path: typeof item.path === "string" ? item.path : void 0 - }; + function sessionSummary(sessionId) { + return sessionSummaryFromSnapshot(sessionsSnapshot(), sessionId); } function currentSessionId() { const snap = snapshotOf(get("sessions")?.list) ?? snapshotOf(get("sessions")); @@ -2724,12 +2770,20 @@ function apply(ctx) { const sessionId = currentSessionId(); if (sessionId) { const owner = workspaceItems().find((item) => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId)); - if (owner) candidates.push(owner.workspaceId ?? owner.id); + if (owner) candidates.push(owner.workspaceId); } return candidates.find((id) => typeof id === "string" && id) ?? null; } + function workspaceForSessionId(sessionId) { + const explicitId = typeof sessionId === "string" && sessionId ? sessionId : null; + const targetId = explicitId || currentSessionId(); + const fromSession = workspaceForSession(workspaceItems(), targetId, sessionSummary(targetId)); + if (fromSession) return fromSession; + if (explicitId && explicitId !== currentSessionId()) return null; + return currentWorkspace(); + } function currentWorkspace() { - const items = workspaceItems().map(normalizeWorkspace).filter(Boolean); + const items = workspaceItems(); const id = currentWorkspaceId(); if (id) { const hit = items.find((item) => item.workspaceId === id); @@ -2795,7 +2849,10 @@ function apply(ctx) { function rightMountedSessionId() { const right = get("sidebarRight"); try { - if (right && isFn(right.mounted?.getSnapshot)) return right.mounted.getSnapshot(); + if (right && isFn(right.mounted?.getSnapshot)) { + const mounted = right.mounted.getSnapshot(); + if (typeof mounted === "string" && mounted) return mounted; + } } catch { } return currentSessionId(); @@ -2812,13 +2869,14 @@ function apply(ctx) { return null; } } - function findRightWorkbenchTab() { + function findRightWorkbenchTab(sessionId) { const right = get("sidebarRight"); if (!right || !isFn(right.openTabs?.getSnapshot)) return null; try { const rows = right.openTabs.getSnapshot(); - const sessionId = rightMountedSessionId(); - const matches = (Array.isArray(rows) ? rows : []).filter((item) => item && item.kind === TAB_KIND && (!sessionId || item.sessionId === sessionId)); + const targetSessionId = typeof sessionId === "string" && sessionId ? sessionId : rightMountedSessionId(); + if (!targetSessionId) return null; + const matches = (Array.isArray(rows) ? rows : []).filter((item) => item && item.kind === TAB_KIND && item.sessionId === targetSessionId); if (matches.length === 0) return null; const activeId = activeRightTabId(); return matches.find((item) => item.tabId === activeId) || matches[0]; @@ -2826,11 +2884,11 @@ function apply(ctx) { return null; } } - function revealRightTab() { + function revealRightTab(sessionId) { const right = get("sidebarRight"); if (!right) return false; try { - const row = findRightWorkbenchTab(); + const row = findRightWorkbenchTab(sessionId); if (!row) return false; const activeId = activeRightTabId(); if (activeId !== row.tabId && isFn(right.focus)) right.focus(row.tabId); @@ -2841,28 +2899,30 @@ function apply(ctx) { return false; } } - function scheduleRevealRightTab() { + function scheduleRevealRightTab(sessionId) { for (const delay of [120, 420]) { setTimeout(() => { if (!rightWorkbenchPinned) return; - revealRightTab(); + revealRightTab(sessionId); }, delay); } } - function tryOpenRightTab() { - const existing = findRightWorkbenchTab(); + function tryOpenRightTab(sessionId) { + const targetSessionId = typeof sessionId === "string" && sessionId ? sessionId : rightMountedSessionId(); + const existing = findRightWorkbenchTab(targetSessionId); if (existing) { - revealRightTab(); + revealRightTab(targetSessionId); return true; } 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: "三省六部" }); - scheduleRevealRightTab(); + if (!targetSessionId) return false; + const summary = sessionSummary(targetSessionId); + const scope = { sessionId: targetSessionId }; + if (summary && typeof summary.cwd === "string" && summary.cwd) scope.cwd = summary.cwd; + bs.openTab({ type: TAB_KIND, title: "三省六部" }, scope); + scheduleRevealRightTab(targetSessionId); return true; } catch (error) { console.warn("[sansheng] better-sidebar 打开失败,改用宿主接口:", error && error.message ? error.message : error); @@ -2872,17 +2932,19 @@ function apply(ctx) { if (!right || !isFn(right.openTab)) return false; if (!ensureRightTab()) return false; try { - right.openTab(TAB_KIND); + const mountedId = rightMountedSessionId(); + if (targetSessionId && targetSessionId !== mountedId && isFn(right.openTabIn)) right.openTabIn(targetSessionId, TAB_KIND); + else right.openTab(TAB_KIND); } catch (error) { console.warn("[sansheng] 打开右侧标签失败,改用浮动面板:", error && error.message ? error.message : error); return false; } - revealRightTab(); - scheduleRevealRightTab(); + revealRightTab(targetSessionId); + scheduleRevealRightTab(targetSessionId); return true; } - function SanshengTabBody() { - return (0, import_react2.createElement)("div", { className: "ssw-tab-body" }, (0, import_react2.createElement)(SanshengWorkbench, {})); + function SanshengTabBody(props) { + return (0, import_react2.createElement)("div", { className: "ssw-tab-body" }, (0, import_react2.createElement)(SanshengWorkbench, { sessionId: props && props.sessionId })); } function SanshengTabTitle() { return (0, import_react2.createElement)("span", { className: "ssw-tab-title" }, "三省六部"); @@ -2898,7 +2960,10 @@ function apply(ctx) { icon: (size) => (0, import_react2.createElement)(TreeIcon, { width: size, height: size }), order: 32, single: true, - component: () => (0, import_react2.createElement)("div", { className: "ssw-tab-body" }, (0, import_react2.createElement)(SanshengWorkbench, {})) + component: (tabProps) => { + const scope = tabProps && tabProps.scope ? tabProps.scope : null; + return (0, import_react2.createElement)("div", { className: "ssw-tab-body" }, (0, import_react2.createElement)(SanshengWorkbench, { sessionId: scope && scope.sessionId })); + } }); return () => { try { @@ -2917,7 +2982,20 @@ function apply(ctx) { if (!tabs || !isFn(tabs.register)) return; let disposeType = null, disposeBody = null, disposeTitle = null; try { - disposeType = tabs.register({ id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: "extension", title: () => "三省六部" }); + disposeType = tabs.register({ + id: TAB_TYPE_ID, + kind: TAB_KIND, + keepMounted: true, + priority: "extension", + title: () => "三省六部", + guide: [{ + id: `${TAB_TYPE_ID}:guide`, + order: 32, + title: () => "三省六部", + description: () => "十席角色与独立会话的当前项目工作台", + icon: TreeIcon + }] + }); disposeBody = ctx.slots.inject("sidebar.right.pane.tab", () => ctx.slots.register({ name: "sidebar.right.pane.tab", key: TAB_TYPE_ID, @@ -2967,9 +3045,12 @@ function apply(ctx) { let lastSelectedSeatId = SEAT_IDS[0]; let rightWorkbenchPinned = readRightWorkbenchPinned(); function SanshengWorkbench(props) { + const sessionId = props && props.sessionId; + const resolveWorkspace = (0, import_react2.useCallback)(() => workspaceForSessionId(sessionId), [sessionId]); return (0, import_react2.createElement)(WorkbenchV2, { + sessionId, onClose: props && props.onClose, - resolveWorkspace: currentWorkspace, + resolveWorkspace, navigateToSession, openRightTab: tryOpenRightTab, selectionCache: selectedSeatCache, @@ -2981,8 +3062,8 @@ function apply(ctx) { } const NAV_PANEL_ID = "sansheng-workbench"; const NAV_ORDER = 32; - function openRightWorkbench() { - const opened = tryOpenRightTab(); + function openRightWorkbench(sessionId) { + const opened = tryOpenRightTab(sessionId); if (opened) { rightWorkbenchPinned = true; writeRightWorkbenchPinned(true); @@ -3036,12 +3117,13 @@ function apply(ctx) { return; } try { - if (findRightWorkbenchTab()) { - revealRightTab(); + const sessionId = rightMountedSessionId(); + if (findRightWorkbenchTab(sessionId)) { + revealRightTab(sessionId); attempt = 0; return; } - if (openRightWorkbench()) { + if (openRightWorkbench(sessionId)) { attempt = 0; return; } @@ -3074,7 +3156,7 @@ function apply(ctx) { const onClick = (event) => { if (event && isFn(event.stopPropagation)) event.stopPropagation(); if (event && isFn(event.preventDefault)) event.preventDefault(); - if (openRightWorkbench()) { + if (openRightWorkbench(currentSessionId())) { setFloating(false); return; } @@ -3085,7 +3167,7 @@ function apply(ctx) { const card = (0, import_react2.createElement)( "div", { className: "ssw-float", role: "dialog", "aria-label": "三省六部工作台" }, - (0, import_react2.createElement)(SanshengWorkbench, { onClose: () => setFloating(false) }) + (0, import_react2.createElement)(SanshengWorkbench, { sessionId: currentSessionId(), onClose: () => setFloating(false) }) ); const canPortal = typeof document !== "undefined" && document.body && isFn(import_react_dom.createPortal); panel = canPortal ? (0, import_react_dom.createPortal)(card, document.body) : card; @@ -3120,7 +3202,7 @@ function apply(ctx) { (0, import_react2.useEffect)(() => { let opened = false; try { - opened = openRightWorkbench(); + opened = openRightWorkbench(currentSessionId()); } catch { opened = false; } @@ -3138,7 +3220,7 @@ function apply(ctx) { for (const delay of [200, 600, 1200, 2e3]) { setTimeout(() => { try { - if (!openedLater && openRightWorkbench()) { + if (!openedLater && openRightWorkbench(currentSessionId())) { openedLater = true; backToChat(); } @@ -3168,7 +3250,7 @@ function apply(ctx) { (0, import_react2.createElement)("span", null, "工作台 · 内嵌模式"), (0, import_react2.createElement)("button", { type: "button", className: "ssw-link", onClick: backToChat }, "返回对话") ), - (0, import_react2.createElement)(SanshengWorkbench, {}) + (0, import_react2.createElement)(SanshengWorkbench, { sessionId: currentSessionId() }) ); } function registerNavEntry() { diff --git a/sansheng/src/client/index.js b/sansheng/src/client/index.js index bf42e16..62863c0 100644 --- a/sansheng/src/client/index.js +++ b/sansheng/src/client/index.js @@ -5,11 +5,12 @@ import { createElement as h, Fragment, useCallback, useEffect, useMemo, useRef, import { createPortal } from 'react-dom' import { SEAT_IDS, SEATS } from '../shared/roles.js' import { WorkbenchV2 } from './workbench-v2.js' +import { workspaceForSession, workspaceItemsFromSnapshot, sessionSummaryFromSnapshot } from './workspace.js' import { request } from './transport.js' import { CSS as WORKBENCH_CSS } from './styles.js' import { install as installNativePanel } from '../native/index.js' -export const inject = ['sessions', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight'] +export const inject = ['sessions', 'workspaces', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight'] const PLUGIN_ID = 'dsh-sansheng' const TAB_KIND = 'sansheng-workbench' @@ -110,23 +111,25 @@ export function apply(ctx) { const get = (name) => { try { return ctx.get(name) } catch { return undefined } } // ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ---------- + function sessionsSnapshot() { + return snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions')) + } + function workspaceItems() { - const fromWorkspaces = snapshotOf(get('workspaces')?.list)?.items - if (Array.isArray(fromWorkspaces)) return fromWorkspaces - const fromUi = snapshotOf(get('uiWorkspace')?.workspaces)?.items - if (Array.isArray(fromUi)) return fromUi + const sources = [ + get('workspaces')?.list, + get('uiWorkspace')?.workspaces, + get('workspaces'), + ] + for (const source of sources) { + const items = workspaceItemsFromSnapshot(snapshotOf(source)) + if (items.length) return items + } return [] } - function normalizeWorkspace(item) { - if (!item || typeof item !== 'object') return null - const workspaceId = item.workspaceId ?? item.id ?? null - if (typeof workspaceId !== 'string' || !workspaceId) return null - return { - workspaceId, - name: typeof item.name === 'string' ? item.name : (typeof item.title === 'string' ? item.title : undefined), - path: typeof item.path === 'string' ? item.path : undefined, - } + function sessionSummary(sessionId) { + return sessionSummaryFromSnapshot(sessionsSnapshot(), sessionId) } function currentSessionId() { @@ -160,13 +163,25 @@ export function apply(ctx) { const sessionId = currentSessionId() if (sessionId) { const owner = workspaceItems().find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId)) - if (owner) candidates.push(owner.workspaceId ?? owner.id) + if (owner) candidates.push(owner.workspaceId) } return candidates.find(id => typeof id === 'string' && id) ?? null } + // 某个会话所属的工作区。右侧标签、浮动面板和主区内嵌都把自己的 sessionId 传进来, + // 因此多工作区下不会再把「当前全局会话」误当成标签页里的会话。 + function workspaceForSessionId(sessionId) { + const explicitId = typeof sessionId === 'string' && sessionId ? sessionId : null + const targetId = explicitId || currentSessionId() + const fromSession = workspaceForSession(workspaceItems(), targetId, sessionSummary(targetId)) + if (fromSession) return fromSession + // 明确指定了别的会话时,不能退回「当前全局会话」的工作区,否则又会串项目。 + if (explicitId && explicitId !== currentSessionId()) return null + return currentWorkspace() + } + function currentWorkspace() { - const items = workspaceItems().map(normalizeWorkspace).filter(Boolean) + const items = workspaceItems() const id = currentWorkspaceId() if (id) { const hit = items.find(item => item.workspaceId === id) @@ -231,7 +246,10 @@ export function apply(ctx) { function rightMountedSessionId() { const right = get('sidebarRight') try { - if (right && isFn(right.mounted?.getSnapshot)) return right.mounted.getSnapshot() + if (right && isFn(right.mounted?.getSnapshot)) { + const mounted = right.mounted.getSnapshot() + if (typeof mounted === 'string' && mounted) return mounted + } } catch { /* 忽略 */ } return currentSessionId() } @@ -247,13 +265,15 @@ export function apply(ctx) { } catch { return null } } - function findRightWorkbenchTab() { + function findRightWorkbenchTab(sessionId) { const right = get('sidebarRight') if (!right || !isFn(right.openTabs?.getSnapshot)) return null try { const rows = right.openTabs.getSnapshot() - const sessionId = rightMountedSessionId() - const matches = (Array.isArray(rows) ? rows : []).filter(item => item && item.kind === TAB_KIND && (!sessionId || item.sessionId === sessionId)) + const targetSessionId = typeof sessionId === 'string' && sessionId ? sessionId : rightMountedSessionId() + // 关键:没有明确会话时不能匹配「所有会话」的工作台标签,否则新工作区会误抓旧会话的标签。 + if (!targetSessionId) return null + const matches = (Array.isArray(rows) ? rows : []).filter(item => item && item.kind === TAB_KIND && item.sessionId === targetSessionId) if (matches.length === 0) return null const activeId = activeRightTabId() return matches.find(item => item.tabId === activeId) || matches[0] @@ -262,11 +282,11 @@ export function apply(ctx) { // 只在“还没有这个会话的工作台标签”时打开;已有标签只做必要的聚焦/展开, // 已处于目标状态时一律不动作,避免切换会话时重复 openTab/focus 造成整块刷新。 - function revealRightTab() { + function revealRightTab(sessionId) { const right = get('sidebarRight') if (!right) return false try { - const row = findRightWorkbenchTab() + const row = findRightWorkbenchTab(sessionId) if (!row) return false const activeId = activeRightTabId() if (activeId !== row.tabId && isFn(right.focus)) right.focus(row.tabId) @@ -279,28 +299,31 @@ export function apply(ctx) { } // 单次补聚焦只用于“标签异步落位”的短窗口;每次先确认标签真的存在,绝不在已有标签时重复 openTab。 - function scheduleRevealRightTab() { + function scheduleRevealRightTab(sessionId) { for (const delay of [120, 420]) { setTimeout(() => { if (!rightWorkbenchPinned) return - revealRightTab() + revealRightTab(sessionId) }, delay) } } - function tryOpenRightTab() { - const existing = findRightWorkbenchTab() - if (existing) { revealRightTab(); return true } + function tryOpenRightTab(sessionId) { + const targetSessionId = (typeof sessionId === 'string' && sessionId) ? sessionId : rightMountedSessionId() + const existing = findRightWorkbenchTab(targetSessionId) + if (existing) { revealRightTab(targetSessionId); return true } // 桌面版右栏由 dsh-better-sidebar 接管:它自己的 openTab 会排队等待会话面板挂载, // 主区正被切走时也不会丢;直接调宿主 sidebarRight 反而会因“没有挂载的会话面板”失败。 + // 显式传 scope:新会话刚建立时 bs 的 active snapshot 可能还停在旧会话,不能靠猜。 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: '三省六部' }) - scheduleRevealRightTab() + if (!targetSessionId) return false + const summary = sessionSummary(targetSessionId) + const scope = { sessionId: targetSessionId } + if (summary && typeof summary.cwd === 'string' && summary.cwd) scope.cwd = summary.cwd + bs.openTab({ type: TAB_KIND, title: '三省六部' }, scope) + scheduleRevealRightTab(targetSessionId) return true } catch (error) { console.warn('[sansheng] better-sidebar 打开失败,改用宿主接口:', error && error.message ? error.message : error) @@ -309,16 +332,22 @@ export function apply(ctx) { const right = get('sidebarRight') if (!right || !isFn(right.openTab)) return false if (!ensureRightTab()) return false - try { right.openTab(TAB_KIND) } catch (error) { + try { + // 原生接口的 openTab 只能作用于 on-screen 会话;目标会话尚未 adopt 时, + // 如果宿主暴露了 openTabIn(跨会话目标通道)就用它,否则退回 openTab 并靠退避重试。 + const mountedId = rightMountedSessionId() + if (targetSessionId && targetSessionId !== mountedId && isFn(right.openTabIn)) right.openTabIn(targetSessionId, TAB_KIND) + else right.openTab(TAB_KIND) + } catch (error) { console.warn('[sansheng] 打开右侧标签失败,改用浮动面板:', error && error.message ? error.message : error) return false } - revealRightTab() - scheduleRevealRightTab() + revealRightTab(targetSessionId) + scheduleRevealRightTab(targetSessionId) return true } - function SanshengTabBody() { - return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {})) + function SanshengTabBody(props) { + return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, { sessionId: props && props.sessionId })) } function SanshengTabTitle() { return h('span', { className: 'ssw-tab-title' }, '三省六部') @@ -336,7 +365,10 @@ export function apply(ctx) { icon: (size) => h(TreeIcon, { width: size, height: size }), order: 32, single: true, - component: () => h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {})), + component: (tabProps) => { + const scope = tabProps && tabProps.scope ? tabProps.scope : null + return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, { sessionId: scope && scope.sessionId })) + }, }) return () => { try { if (isFn(dispose)) dispose() } catch { /* 忽略 */ } } } @@ -350,7 +382,13 @@ export function apply(ctx) { if (!tabs || !isFn(tabs.register)) return let disposeType = null, disposeBody = null, disposeTitle = null try { - disposeType = tabs.register({ id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部' }) + disposeType = tabs.register({ + id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部', + guide: [{ + id: `${TAB_TYPE_ID}:guide`, order: 32, title: () => '三省六部', + description: () => '十席角色与独立会话的当前项目工作台', icon: TreeIcon, + }], + }) disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }), }, SanshengTabBody)) @@ -383,9 +421,12 @@ export function apply(ctx) { // ---------- 工作台组件 ---------- // 工作台 v2:视觉与交互按用户提供的设计稿实现,数据全部走真实 host API。 function SanshengWorkbench(props) { + const sessionId = props && props.sessionId + const resolveWorkspace = useCallback(() => workspaceForSessionId(sessionId), [sessionId]) return h(WorkbenchV2, { + sessionId, onClose: props && props.onClose, - resolveWorkspace: currentWorkspace, + resolveWorkspace, navigateToSession, openRightTab: tryOpenRightTab, selectionCache: selectedSeatCache, @@ -400,8 +441,8 @@ export function apply(ctx) { const NAV_PANEL_ID = 'sansheng-workbench' const NAV_ORDER = 32 - function openRightWorkbench() { - const opened = tryOpenRightTab() + function openRightWorkbench(sessionId) { + const opened = tryOpenRightTab(sessionId) if (opened) { rightWorkbenchPinned = true; writeRightWorkbenchPinned(true) } return opened } @@ -440,12 +481,13 @@ export function apply(ctx) { timer = null if (!rightWorkbenchPinned) { attempt = 0; return } try { - if (findRightWorkbenchTab()) { - revealRightTab() + const sessionId = rightMountedSessionId() + if (findRightWorkbenchTab(sessionId)) { + revealRightTab(sessionId) attempt = 0 return } - if (openRightWorkbench()) { + if (openRightWorkbench(sessionId)) { attempt = 0 return } @@ -480,13 +522,13 @@ export function apply(ctx) { const onClick = (event) => { if (event && isFn(event.stopPropagation)) event.stopPropagation() if (event && isFn(event.preventDefault)) event.preventDefault() - if (openRightWorkbench()) { setFloating(false); return } + if (openRightWorkbench(currentSessionId())) { setFloating(false); return } setFloating(value => !value) } let panel = null if (floating) { const card = h('div', { className: 'ssw-float', role: 'dialog', 'aria-label': '三省六部工作台' }, - h(SanshengWorkbench, { onClose: () => setFloating(false) })) + h(SanshengWorkbench, { sessionId: currentSessionId(), onClose: () => setFloating(false) })) const canPortal = typeof document !== 'undefined' && document.body && isFn(createPortal) panel = canPortal ? createPortal(card, document.body) : card } @@ -514,7 +556,7 @@ export function apply(ctx) { const [mode, setMode] = useState('pending') useEffect(() => { let opened = false - try { opened = openRightWorkbench() } catch { opened = false } + try { opened = openRightWorkbench(currentSessionId()) } catch { opened = false } if (opened) { setMode('docked') backToChat() @@ -530,7 +572,7 @@ export function apply(ctx) { let openedLater = false for (const delay of [200, 600, 1200, 2000]) { setTimeout(() => { - try { if (!openedLater && openRightWorkbench()) { openedLater = true; backToChat() } } catch { /* 忽略 */ } + try { if (!openedLater && openRightWorkbench(currentSessionId())) { openedLater = true; backToChat() } } catch { /* 忽略 */ } }, delay) } setTimeout(() => { if (!openedLater) setMode('inline') }, 2600) @@ -549,7 +591,7 @@ export function apply(ctx) { h('span', null, '工作台 · 内嵌模式'), h('button', { type: 'button', className: 'ssw-link', onClick: backToChat }, '返回对话'), ), - h(SanshengWorkbench, {}), + h(SanshengWorkbench, { sessionId: currentSessionId() }), ) } diff --git a/sansheng/src/client/workspace.js b/sansheng/src/client/workspace.js new file mode 100644 index 0000000..af68086 --- /dev/null +++ b/sansheng/src/client/workspace.js @@ -0,0 +1,55 @@ +// 工作区解析:把「某个会话属于哪个项目工作区」从宿主快照里算出来。 +// 纯函数,便于单测;index.js 只负责把宿主服务快照喂进来。 + +function samePath(a, b) { + if (typeof a !== 'string' || typeof b !== 'string') return false + const norm = value => value.replace(/\//g, '\\').replace(/\\+$/g, '').toLowerCase() + return norm(a) === norm(b) +} + +function baseName(path) { + if (typeof path !== 'string') return undefined + const parts = path.replace(/\/+$/g, '').split(/[\\/]/).filter(Boolean) + return parts.length ? parts[parts.length - 1] : undefined +} + +export function normalizeWorkspaceItem(item) { + if (!item || typeof item !== 'object') return null + const workspaceId = item.workspaceId ?? item.id ?? null + if (typeof workspaceId !== 'string' || !workspaceId) return null + return { + workspaceId, + name: typeof item.name === 'string' ? item.name : (typeof item.title === 'string' ? item.title : undefined), + path: typeof item.path === 'string' ? item.path : undefined, + sessionIds: Array.isArray(item.sessionIds) ? item.sessionIds : undefined, + } +} + +export function workspaceItemsFromSnapshot(snapshot) { + const items = Array.isArray(snapshot) ? snapshot : (snapshot && typeof snapshot === 'object' && Array.isArray(snapshot.items) ? snapshot.items : []) + return items.map(normalizeWorkspaceItem).filter(Boolean) +} + +export function sessionSummaryFromSnapshot(snapshot, sessionId) { + if (!snapshot || typeof snapshot !== 'object' || typeof sessionId !== 'string' || !sessionId) return null + const byId = snapshot.byId + if (!byId || typeof byId !== 'object') return null + const summary = byId[sessionId] + return summary && typeof summary === 'object' ? summary : null +} + +/** + * 按会话解析工作区:优先命中 workspace.sessionIds;否则用会话 cwd 匹配工作区路径; + * 都匹配不到时把 cwd 本身当作可解析路径(host service.open 会按 path resolve/create)。 + */ +export function workspaceForSession(items, sessionId, sessionSummary) { + const list = (Array.isArray(items) ? items : []).map(normalizeWorkspaceItem).filter(Boolean) + if (typeof sessionId !== 'string' || !sessionId) return null + const bySession = list.find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId)) + if (bySession) return bySession + const cwd = sessionSummary && typeof sessionSummary.cwd === 'string' ? sessionSummary.cwd : '' + if (!cwd) return null + const byPath = list.find(item => item.path && samePath(item.path, cwd)) + if (byPath) return byPath + return { workspaceId: null, name: baseName(cwd), path: cwd, sessionIds: [sessionId] } +} diff --git a/sansheng/test/nav.test.js b/sansheng/test/nav.test.js index 8dff56e..7a53787 100644 --- a/sansheng/test/nav.test.js +++ b/sansheng/test/nav.test.js @@ -18,8 +18,15 @@ test('左侧入口使用 sidebar.panellist,位置在记忆系统与更多之 test('右侧工作台依赖宿主 sidebarRight,并在会话切换后重新固定', async () => { const source = await readFile(join(root, 'src/client/index.js'), 'utf8') - assert.match(source, /export const inject = \[[^\]]*'sidebarRightTabs', 'sidebarRight'/) + assert.match(source, /export const inject = \[[^\]]*'workspaces'[^\]]*'sidebarRightTabs', 'sidebarRight'/) assert.match(source, /right\.mounted\.subscribe/) assert.match(source, /right\.openTabs\.getSnapshot/) assert.match(source, /right\.focus\(row\.tabId\)/) }) + +test('右侧栏有可发现的 guide 入口,并把标签会话传给工作台', async () => { + const source = await readFile(join(root, 'src/client/index.js'), 'utf8') + assert.match(source, /guide: \[\{/) + assert.match(source, /sessionId: props && props\.sessionId/) + assert.match(source, /workspaceForSessionId\(sessionId\)/) +}) diff --git a/sansheng/test/workspace.test.js b/sansheng/test/workspace.test.js new file mode 100644 index 0000000..955ebdf --- /dev/null +++ b/sansheng/test/workspace.test.js @@ -0,0 +1,44 @@ +// 工作区解析纯函数:多工作区下按会话/路径找到正确项目。 +import test from 'node:test' +import assert from 'node:assert/strict' +import { + workspaceForSession, + workspaceItemsFromSnapshot, + sessionSummaryFromSnapshot, +} from '../src/client/workspace.js' + +const ITEMS = [ + { workspaceId: 'ws-a', title: '甲项目', path: 'C:\\Work\\A', sessionIds: ['s-a'] }, + { workspaceId: 'ws-b', title: '乙项目', path: 'D:/Work/B', sessionIds: ['s-b'] }, +] + +test('workspaceItemsFromSnapshot 保留会话归属并统一标题字段', () => { + const items = workspaceItemsFromSnapshot({ items: ITEMS }) + assert.equal(items.length, 2) + assert.equal(items[0].workspaceId, 'ws-a') + assert.equal(items[0].name, '甲项目') + assert.deepEqual(items[0].sessionIds, ['s-a']) +}) + +test('workspaceForSession 优先按 sessionIds 命中工作区', () => { + assert.equal(workspaceForSession(ITEMS, 's-b', null).workspaceId, 'ws-b') +}) + +test('workspaceForSession 在会话归属缺失时按 cwd 大小写/斜杠不敏感匹配', () => { + const loose = { cwd: 'd:\\work\\b\\' } + assert.equal(workspaceForSession(ITEMS, 's-new', loose).workspaceId, 'ws-b') +}) + +test('workspaceForSession 匹配不到时返回 cwd 作为 path 兜底', () => { + const out = workspaceForSession(ITEMS, 's-new', { cwd: 'E:\\NewPlace' }) + assert.equal(out.workspaceId, null) + assert.equal(out.path, 'E:\\NewPlace') + assert.equal(out.name, 'NewPlace') +}) + +test('sessionSummaryFromSnapshot 按会话 id 读 cwd', () => { + const summary = sessionSummaryFromSnapshot({ byId: { 's-a': { cwd: 'C:/Work/A' } } }, 's-a') + assert.equal(summary.cwd, 'C:/Work/A') + assert.equal(sessionSummaryFromSnapshot({ byId: {} }, 's-a'), null) + assert.equal(workspaceForSession(ITEMS, '', null), null) +})