diff --git a/server/monitoring/observability-page-collection-integration.ts b/server/monitoring/observability-page-collection-integration.ts index 275f2e6..44e9b86 100644 --- a/server/monitoring/observability-page-collection-integration.ts +++ b/server/monitoring/observability-page-collection-integration.ts @@ -6,14 +6,14 @@ body.ops-observability:has(#view-collection:not(.hidden)) .page-head :is(.worksp function once(script:string,before:string,after:string){if(script.split(before).length!==2)throw new Error('collection_shell_baseline_mismatch');return script.replace(before,after);} export function integrateCollectionScriptA(script:string):string{ let result=once(script,"const viewNames = ['overview'","const viewNames = ['collection','data','overview'"); - result=once(result,'const viewModuleChildren = {platform:',"const viewModuleChildren = {collection:['tasks','sources','modules','runs'],data:['assets','datasets','loops','tasks','overview'],platform:"); + result=once(result,'const viewModuleChildren = {',"const viewModuleChildren = {collection:['tasks','sources','modules','runs'],data:['assets','datasets','loops','tasks','overview'],"); result=once(result,'const viewMeta = {overview:',"const viewMeta = {collection:['数据与可观测中心 / 采集','统一采集工作区','配置现有云端与终端采集,固定流程版本,跟踪每个模块的实际运行与结果。'],data:['数据与可观测中心 / 数据','数据资产与改善闭环','从采集结果追溯资产和固定数据集,以真实证据验证改善。'],overview:"); result=once(result,'const moduleNavKey = {',"const moduleNavKey = {'collection/tasks':'collection/tasks','collection/sources':'collection/tasks','collection/modules':'collection/tasks','collection/runs':'collection/tasks','data/assets':'data/assets','data/datasets':'data/assets','data/loops':'data/assets','data/tasks':'data/assets','data/overview':'data/assets',"); result=once(result,"else if(name!=='devices'&&state.domain==='edge')","else if(!['devices','collection','data'].includes(name)&&state.domain==='edge')"); result=once(result,'applyViewModules(name,source);',"applyViewModules(name,source);const collectionDomainSwitcher=$('domainSwitcher');if(collectionDomainSwitcher)collectionDomainSwitcher.hidden=['collection','data'].includes(name);if(typeof collectionWorkspace!=='undefined'&&name!=='collection')collectionWorkspace.hide();if(typeof dataCenterWorkspace!=='undefined'&&name!=='data')dataCenterWorkspace.hide();if(name==='collection'&&typeof collectionWorkspace!=='undefined')collectionWorkspace.show(resolved.child);if(name==='data'&&typeof dataCenterWorkspace!=='undefined')dataCenterWorkspace.show(resolved.child);"); return result; } -export function integrateCollectionNavScript(script:string):string{return once(script,"const primaryRoutes=['overview','alerts/center','traces','signals','devices'];","const primaryRoutes=['overview','collection/tasks','data/assets','alerts/center','traces','signals','devices'];");} +export function integrateCollectionNavScript(script:string):string{return once(script,"const primaryRoutes=['overview',","const primaryRoutes=['overview','collection/tasks','data/assets',");} export const COLLECTION_SHELL_IDENTITY_SCRIPT=String.raw` function collectionShellContext(){return JSON.stringify([obsAuthState.me&&obsAuthState.me.user&&obsAuthState.me.user.id,Boolean(obsAuthState.me&&obsAuthState.me.admin),obsActiveTenant(),apiHeaders(false)])} let collectionShellIdentity=null; diff --git a/server/monitoring/observability-page-focus-navigation.test.ts b/server/monitoring/observability-page-focus-navigation.test.ts index 13941e2..f0d0b39 100644 --- a/server/monitoring/observability-page-focus-navigation.test.ts +++ b/server/monitoring/observability-page-focus-navigation.test.ts @@ -186,7 +186,7 @@ function harness(mobile = true, authGate = false) { return { body, document, tabs, navMain, primary, buttons, originalOrder, main, more, byId, resize, routeCalls, active: () => active, scheduled: () => scheduled }; } -const PRIMARY_VIEWS = ['overview', 'collection/tasks', 'data/assets', 'alerts/center', 'traces', 'signals', 'devices']; +const PRIMARY_VIEWS = ['overview', 'collection/tasks', 'data/assets', 'alerts/center', 'traces', 'gateway', 'signals', 'devices']; const MOBILE_PRIMARY_VIEWS = ['overview', 'alerts/center', 'traces', 'signals', 'devices']; function assertClosed(h: ReturnType) { @@ -195,7 +195,7 @@ function assertClosed(h: ReturnType) { assert.equal(h.more.getAttribute('aria-expanded'), 'false'); } -test('实际页面提供七个直接工作区,其余路由与看板高级操作按需展开', () => { +test('实际页面提供八个直接工作区,其余路由与看板高级操作按需展开', () => { const h = harness(false); // Application links have href; only workspace route buttons have data-view. assert.deepEqual(h.navMain.querySelectorAll('.module-tab').filter(button => button.dataset.view).map(button => button.dataset.view), PRIMARY_VIEWS); diff --git a/server/monitoring/observability-page-focus.test.ts b/server/monitoring/observability-page-focus.test.ts index d28a774..b05bfc8 100644 --- a/server/monitoring/observability-page-focus.test.ts +++ b/server/monitoring/observability-page-focus.test.ts @@ -103,7 +103,9 @@ function harness() { const state: { overview: typeof overview; actions: unknown[] | null; remediation: null; view: string; viewSource: string; viewChild: string; actionLoop?: ActionState } = { overview, actions: [], remediation: null, view: 'overview', viewSource: 'overview', viewChild: '' }; const viewMeta: Record = {}; const navGroupByView: Record = { overview: 'primary', signals: 'data', devices: 'infra' }; - const moduleNavKey: Record = { 'platform/model-pool': 'model-pool' }; + const moduleNavDeclaration = OPS_OBSERVABILITY_SCRIPT_A.split('\n').find(line => line.includes('const moduleNavKey =')); + assert.ok(moduleNavDeclaration); + const moduleNavKey: Record = vm.runInNewContext(moduleNavDeclaration + '\nmoduleNavKey'); const viewCalls: Array<{ requested: string; updateHash: boolean }> = []; const context = vm.createContext({ document, make, add, $: byId, state, viewMeta, navGroupByView, moduleNavKey, @@ -251,14 +253,19 @@ test('产品无快照时只需一次展开,有数据后保留相同外层披 assert.equal(h.byId('overviewProductHealthEmpty'), null); }); -test('新导航分组复用真实路由解析,旧别名与平台高亮继续可用', () => { +test('新导航分组复用真实路由解析,旧模型池入口高亮独立网关', () => { const h = harness(); - for (const view of ['overview', 'alerts/center', 'traces', 'signals', 'devices']) assert.equal(h.navGroupByView[view], undefined); - assert.equal(h.moduleNavKey['platform/model-pool'], 'platform'); - for (const [request, group] of [['investigate', 'data'], ['signals/panels', 'data'], ['learning', 'data'], ['postgres', 'infra'], ['rules', 'advanced'], ['model-pool', 'advanced']] as const) { + for (const view of ['overview', 'alerts/center', 'traces', 'gateway', 'signals', 'devices']) assert.equal(h.navGroupByView[view], undefined); + assert.equal(h.moduleNavKey['gateway/model-pool'], 'gateway'); + for (const [request, group] of [['investigate', 'data'], ['signals/panels', 'data'], ['learning', 'data'], ['postgres', 'infra'], ['rules', 'advanced']] as const) { vm.runInContext('setView(' + JSON.stringify(request) + ',false)', h.context); assert.equal(h.groups.find(node => node.open)?.dataset.navGroup, group); } + for (const route of ['model-pool', 'platform/model-pool']) { + vm.runInContext('setView(' + JSON.stringify(route) + ',false)', h.context); + assert.equal(h.state.viewSource, 'gateway/model-pool'); + assert.equal(h.groups.some(node => node.open), false); + } vm.runInContext('setView("signals",false)', h.context); assert.equal(h.groups.some(node => node.open), false); assert.equal(h.viewCalls.every(call => call.updateHash === false), true); diff --git a/server/monitoring/observability-page-focus.ts b/server/monitoring/observability-page-focus.ts index 530c781..a47c49b 100644 --- a/server/monitoring/observability-page-focus.ts +++ b/server/monitoring/observability-page-focus.ts @@ -24,7 +24,6 @@ export const OPS_OBSERVABILITY_SCRIPT_FOCUS = ` 'alerts/strategies':'advanced','alerts/metrics':'advanced','alerts/objects':'advanced', 'alerts/channels':'advanced','alerts/silence':'advanced' }); - moduleNavKey['platform/model-pool']='platform'; function syncFocusContext(){ const overview=state.view==='overview'; const incidentFact=$('globalIncidentFact'); diff --git a/server/monitoring/observability-page-gateway.ts b/server/monitoring/observability-page-gateway.ts new file mode 100644 index 0000000..5fde845 --- /dev/null +++ b/server/monitoring/observability-page-gateway.ts @@ -0,0 +1,94 @@ +export const OPS_OBSERVABILITY_GATEWAY_STYLE = ` + .gateway-workspace{display:grid;gap:16px} + .gateway-workspace .gateway-panel{min-width:0;padding:18px} + .gateway-panel h2{margin:0 0 12px;font-size:16px;color:var(--text)} + .gateway-checks{list-style:none;margin:0;padding:0} + .gateway-checks li{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px 16px;align-items:start;padding:12px 0;border-top:1px solid var(--line)} + .gateway-checks p{margin:4px 0 0;color:var(--muted);overflow-wrap:anywhere} + .gateway-checks .gateway-status{display:flex;gap:7px;align-items:center;white-space:nowrap} + .gateway-checks time{color:var(--muted);font-size:12px} + .gateway-checks .gateway-evidence{grid-column:1/-1;justify-self:start} + .gateway-slo{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px} + .gateway-slo article{min-width:0;border-top:1px solid var(--line);padding-top:12px} + .gateway-slo h3{margin:0;color:var(--text);font-size:13px;font-weight:600} + .gateway-slo strong{display:block;margin:7px 0;font-size:22px;font-variant-numeric:tabular-nums} + .gateway-slo small{display:block;color:var(--muted);line-height:1.5} + .gateway-panel>.btn{margin-top:14px} + @media(min-width:1050px){ + .gateway-workspace:has(.gateway-public){grid-template-columns:minmax(0,1fr) minmax(0,1fr);align-items:start} + .gateway-public{grid-column:2;grid-row:1/3} + .gateway-reliability{grid-column:1;grid-row:2} + } + @media(max-width:720px){.gateway-workspace .gateway-panel{padding:14px}.gateway-slo{grid-template-columns:1fr;gap:12px}} +`; + +export const OPS_OBSERVABILITY_GATEWAY_HTML = ` + `; + +export const OPS_OBSERVABILITY_GATEWAY_SCRIPT = String.raw` + const gatewayCheckGroups=[ + ['模型网关', [['agent-model-target-degraded','主备模型目标']]], + ['公网入口', [['public-health','入口健康'],['nginx-5xx-log','Nginx 5xx'],['external-dns','异地 DNS'],['external-tls','异地 TLS']]], + ]; + function gatewayPlatformAvailable(){return !opsTenantMode&&!opsMemberMode&&!adminTenantQuery()} + function gatewayScopeNotice(root){ + OpsUI.state(root,{kind:'empty',title:'网关属于平台视图',hint:'切换到平台范围后查看。'}); + } + function updateGatewayReadError(message){ + state.gatewayReadError=message; + if(state.viewSource==='gateway/overview')renderGatewayOverview(); + } + function renderGatewayOverview(){ + const root=$('gatewayOverviewContent');if(!root)return; + root.replaceChildren(); + if(!gatewayPlatformAvailable()){gatewayScopeNotice(root);return} + if(state.gatewayReadError){ + OpsUI.state(root,{kind:'error',title:'网关状态读取失败',hint:'刷新数据后重新确认当前状态。',retry:()=>loadAll(true)}); + return; + } + if(!state.overview){OpsUI.state(root,{kind:'loading',title:'正在读取网关状态…'});return} + const checks=new Map((state.overview.checks||[]).map(check=>[check.key,check])); + const knownStatuses={...statusNames,observing:'观察中',unknown:'待确认'}; + gatewayCheckGroups.forEach(([title,rows])=>{ + const panel=add(root,'section','panel gateway-panel'+(title==='公网入口'?' gateway-public':''));add(panel,'h2','',title); + const list=add(panel,'ul','gateway-checks'); + rows.forEach(([key,label])=>{ + const check=checks.get(key); + const status=check&&Object.hasOwn(knownStatuses,check.status)?check.status:'unknown'; + const item=add(list,'li','');const body=add(item,'div','');add(body,'strong','',label); + add(body,'p','',check?.summary||'暂无检查回执'); + if(check?.checkedAt){const time=add(body,'time','','最近检查 '+when(check.checkedAt));time.dateTime=check.checkedAt} + const indicator=add(item,'div','gateway-status');add(indicator,'span','state-dot '+status);add(indicator,'span','',knownStatuses[status]); + const def=['agent-model-target-degraded','nginx-5xx-log'].includes(key)&&state.config?.definitions?.find(rule=>rule.key===key); + if(check&&def&&state.config?.rules?.[key]){ + const button=add(item,'button','btn gateway-evidence','查看'+label+'证据');button.type='button'; + button.addEventListener('click',()=>openAlertDetail(def)); + } + }); + }); + const panel=add(root,'section','panel gateway-panel gateway-reliability');add(panel,'h2','','可用性与延迟'); + const metrics=add(panel,'div','gateway-slo'); + const objectives=state.overview.serviceLevels?.objectives||[]; + [['gateway-availability','网关可用性'],['gateway-latency','网关响应时间达标率'],['ai-ttft','Studio AI 首字延迟达标率']].forEach(([key,label])=>{ + const objective=objectives.find(item=>item.key===key); + const card=add(metrics,'article','');add(card,'h3','',label); + if(!objective){add(card,'strong','','暂无读数');return} + const rate=objective.compliancePercent; + const measured=objective.dataAvailable&&Number.isFinite(rate); + add(card,'strong',measured&&ratesetView('service-levels')); + } +`; diff --git a/server/monitoring/observability-page-interaction.test.ts b/server/monitoring/observability-page-interaction.test.ts index db45c6c..57e87d4 100644 --- a/server/monitoring/observability-page-interaction.test.ts +++ b/server/monitoring/observability-page-interaction.test.ts @@ -351,6 +351,7 @@ function setup(): Harness { "renderOperatorMetrics:typeof renderOperatorMetrics!=='undefined'?renderOperatorMetrics:null," + "resolveViewRequest:typeof resolveViewRequest!=='undefined'?resolveViewRequest:null," + "renderSettings:typeof renderSettings!=='undefined'?renderSettings:null," + + "loadModelPool:typeof loadModelPool!=='undefined'?loadModelPool:null," + "renderModelPool:typeof renderModelPool!=='undefined'?renderModelPool:null," + "renderBoardPanels:typeof renderBoardPanels!=='undefined'?renderBoardPanels:null," + "renderObjects:typeof renderObjects!=='undefined'?renderObjects:null," + @@ -446,7 +447,7 @@ test('两级路由:旧 hash 别名规范化为 视图/子模块,未知视图 const resolve = h.obs.resolveViewRequest as (r: string) => Record; assert.equal(typeof resolve, 'function', '应能取到 resolveViewRequest'); const canon = (r: string) => JSON.stringify(resolve(r)); - assert.equal(canon('model-pool'), JSON.stringify({ name: 'platform', child: 'model-pool', source: 'platform/model-pool' })); + assert.equal(canon('model-pool'), JSON.stringify({ name: 'gateway', child: 'model-pool', source: 'gateway/model-pool' })); assert.equal(canon('settings/probing'), JSON.stringify({ name: 'platform', child: 'probing', source: 'platform/probing' })); assert.equal(canon('platform'), JSON.stringify({ name: 'platform', child: 'general', source: 'platform/general' })); assert.equal(canon('alerts'), JSON.stringify({ name: 'alerts', child: 'center', source: 'alerts/center' }), '裸 #alerts 默认落在告警中心(响应队列优先)'); @@ -807,8 +808,8 @@ test('模型池:拓扑与指标条按真实夹具渲染,保存权重走 PUT const h = setup(); const obs = h.obs; assert.equal(typeof obs.renderModelPool, 'function', '应能取到 renderModelPool'); - (obs.setObsState as (p: Record) => unknown)({ modelPool: MODEL_POOL_FIXTURE }); - (obs.renderModelPool as () => void)(); + h.setJsonResponse(MODEL_POOL_FIXTURE); + await (obs.loadModelPool as () => Promise)(); const root = h.byIdNode('modelPoolContent'); assert.ok(root, 'modelPoolContent 应已渲染'); diff --git a/server/monitoring/observability-page-navigation.test.ts b/server/monitoring/observability-page-navigation.test.ts index 93ca9fb..496f78a 100644 --- a/server/monitoring/observability-page-navigation.test.ts +++ b/server/monitoring/observability-page-navigation.test.ts @@ -129,9 +129,9 @@ function setup(options: { tenantToken?: string; session?: string; tenant?: strin return { shell, body, hooks, calls, renders, storage, dispatchDocument, byId: document.getElementById, reloads: () => reloads }; } -test('真实壳保留七个日常入口和三个分类菜单,每个强绑定 ID 唯一存在', () => { +test('真实壳保留八个日常入口和三个分类菜单,每个强绑定 ID 唯一存在', () => { const shell = parseShell(); const primary = shell.querySelector('.nav-main')!; - assert.deepEqual(primary.querySelectorAll('.module-tab[data-view]').map(node => node.dataset.view), ['overview', 'collection/tasks', 'data/assets', 'alerts/center', 'traces', 'signals', 'devices']); + assert.deepEqual(primary.querySelectorAll('.module-tab[data-view]').map(node => node.dataset.view), ['overview', 'collection/tasks', 'data/assets', 'alerts/center', 'traces', 'gateway', 'signals', 'devices']); const groups = shell.querySelectorAll('.nav-group'); assert.deepEqual(groups.map(node => node.dataset.navGroup), ['data', 'infra', 'advanced']); for (const group of groups) { assert.equal(group.tagName, 'DETAILS'); assert.equal(group.id, 'nav-group-' + group.dataset.navGroup); } @@ -152,7 +152,7 @@ test('主导航与更多入口按实际目标高亮,旧深链仍定位正确 ['overview', 'overview', 'overview'], ['alerts', 'alerts/center', 'alerts/center'], ['signals/logs', 'signals', 'signals/logs'], ['agent-traces', 'traces', 'traces/runs'], ['session-traces', 'traces', 'traces/session'], ['signals/panels', 'signals/panels', 'signals/panels'], - ['model-pool', 'platform', 'platform/model-pool'], ['platform/probing', 'platform', 'platform/probing'], + ['model-pool', 'gateway', 'gateway/model-pool'], ['platform/model-pool', 'gateway', 'gateway/model-pool'], ['gateway', 'gateway', 'gateway/overview'], ['platform/probing', 'platform', 'platform/probing'], ['rules', 'alerts/rules', 'alerts/rules'], ['objects', 'alerts/rules', 'alerts/objects'], ['devices/logs', 'devices', 'devices/logs'], ['tenants/create', 'tenants', 'tenants/create'], ]; diff --git a/server/monitoring/observability-page-restraint.test.ts b/server/monitoring/observability-page-restraint.test.ts index aea2c73..0eab7e4 100644 --- a/server/monitoring/observability-page-restraint.test.ts +++ b/server/monitoring/observability-page-restraint.test.ts @@ -184,7 +184,7 @@ function setup(options: { tenantToken?: string; member?: boolean } = {}) { test('实际页面默认只铺开三个查询入口、一个平台配置入口和一个告警入口', () => { const h = setup(); assert.deepEqual(h.directRoutes('signals'), ['signals/metrics', 'signals/logs', 'signals/promql']); - assert.deepEqual(h.directRoutes('platform'), ['platform/model-pool']); + assert.deepEqual(h.directRoutes('platform'), ['platform/general']); assert.deepEqual(h.directRoutes('alerts'), ['alerts/center']); for (const name of ['signals', 'platform', 'alerts']) { const menus = h.list(name).querySelectorAll('details'); assert.equal(menus.length, 1); @@ -242,7 +242,7 @@ test('更多菜单内部可操作,Escape 关闭后焦点回到摘要,外部 test('同一路由轮询保留展开的更多菜单和菜单内焦点,真正换页才关闭', () => { const h = setup(); - for (const [route, name] of [['signals/metrics', 'signals'], ['platform/model-pool', 'platform'], ['alerts/rules', 'alerts']] as const) { + for (const [route, name] of [['signals/metrics', 'signals'], ['platform/general', 'platform'], ['alerts/rules', 'alerts']] as const) { h.hooks.setView(route, false); const menu = h.menu(name); const summary = menu.querySelector('summary')!; const tabs = h.list(name).querySelectorAll('[data-module-tab]'); diff --git a/server/monitoring/observability-page-restraint.ts b/server/monitoring/observability-page-restraint.ts index 6a99224..309676d 100644 --- a/server/monitoring/observability-page-restraint.ts +++ b/server/monitoring/observability-page-restraint.ts @@ -61,7 +61,7 @@ export const OPS_OBSERVABILITY_RESTRAINT_STYLE = ` export const OPS_OBSERVABILITY_SCRIPT_RESTRAINT = OPS_OBSERVABILITY_SCRIPT_OVERVIEW_RESTRAINT + String.raw` const restraintTabGroups=[]; - const restraintPrimaryTabs={signals:['signals/metrics','signals/logs','signals/promql'],platform:['platform/model-pool'],alerts:['alerts/center']}; + const restraintPrimaryTabs={signals:['signals/metrics','signals/logs','signals/promql'],platform:['platform/general'],alerts:['alerts/center']}; function restraintPermissionVisible(node){return !node.hidden&&!node.classList.contains('hidden')&&!node.disabled} function restraintTabVisible(node){ if(!restraintPermissionVisible(node))return false; diff --git a/server/monitoring/observability-page-script-a.ts b/server/monitoring/observability-page-script-a.ts index 2c5ec7b..78d42c8 100644 --- a/server/monitoring/observability-page-script-a.ts +++ b/server/monitoring/observability-page-script-a.ts @@ -4,7 +4,7 @@ export const OPS_OBSERVABILITY_SCRIPT_A = ` (() => { // Canonical views are listed first; legacy names remain parseable so old // bookmarks (#rules/#database/#session-traces) open the corresponding // accordion in the unified workbench instead of falling back to a blank tab. - const viewNames = ['overview','service-levels','operator-metrics','signals','devices','data-health','database','skill-loop','evolution','investigate','alerts','traces','platform','tenants']; + const viewNames = ['overview','service-levels','operator-metrics','signals','devices','data-health','database','skill-loop','evolution','investigate','alerts','traces','gateway','platform','tenants']; const overviewScopedViews = ['overview','traces']; // Keep old deep links usable while the workbench exposes one canonical // set of top-level views. Object/table/learning names were used by the @@ -12,15 +12,15 @@ export const OPS_OBSERVABILITY_SCRIPT_A = ` (() => { // instead of silently falling back to the overview. // 平铺视图已拆成「视图 / 子模块」两级路由:alias 指向 [视图, 默认子模块], // 旧 hash(#model-pool、#metrics…)继续可达并被规范化为层级地址。 - const viewAliases = {metrics:['alerts','metrics'],rules:['alerts','rules'],channels:['alerts','channels'],strategies:['alerts','strategies'],silence:['alerts','silence'],'accounts':['platform','accounts'],objects:['alerts','objects'],object:['alerts','objects'],'alert-objects':['alerts','objects'],growth:['operator-metrics'],'agent-traces':['traces','runs'],'session-traces':['traces','session'],'model-pool':['platform','model-pool'],settings:['platform','general'],'platform-settings':['platform','general'],'skill-flywheel':['skill-loop'],'skill-governance':['skill-loop'],learning:['skill-loop'],skills:['skill-loop'],postgres:['database'],'postgresql':['database']}; + const viewAliases = {metrics:['alerts','metrics'],rules:['alerts','rules'],channels:['alerts','channels'],strategies:['alerts','strategies'],silence:['alerts','silence'],'accounts':['platform','accounts'],objects:['alerts','objects'],object:['alerts','objects'],'alert-objects':['alerts','objects'],growth:['operator-metrics'],'agent-traces':['traces','runs'],'session-traces':['traces','session'],'model-pool':['gateway','model-pool'],'platform/model-pool':['gateway','model-pool'],settings:['platform','general'],'platform-settings':['platform','general'],'skill-flywheel':['skill-loop'],'skill-governance':['skill-loop'],learning:['skill-loop'],skills:['skill-loop'],postgres:['database'],'postgresql':['database']}; // 每个拆分视图的子模块清单;首项是该视图裸 hash(#alerts 等)的默认落地页。 - const viewModuleChildren = {platform:['general','model-pool','probing','logs','heal','accounts'],alerts:['center','rules','strategies','metrics','objects','channels','silence'],signals:['metrics','logs','promql','panels','quality','catalog','tokens'],traces:['runs','session'],devices:['list','logs','register'],tenants:['list','create']}; + const viewModuleChildren = {gateway:['overview','model-pool'],platform:['general','probing','logs','heal','accounts'],alerts:['center','rules','strategies','metrics','objects','channels','silence'],signals:['metrics','logs','promql','panels','quality','catalog','tokens'],traces:['runs','session'],devices:['list','logs','register'],tenants:['list','create']}; // 侧栏高亮回退:同一视图容器上的多个侧栏按钮(模型池 / 系统设置)按子模块区分; // 值必须与侧栏按钮的 data-view 一致。 - const moduleNavKey = {'platform/model-pool':'platform','platform/general':'platform','platform/probing':'platform','platform/logs':'platform','platform/heal':'platform','platform/accounts':'platform','signals/metrics':'signals','signals/logs':'signals','signals/promql':'signals','signals/catalog':'signals','signals/tokens':'signals','traces/runs':'traces','traces/session':'traces','devices/list':'devices','devices/logs':'devices','devices/register':'devices','tenants/list':'tenants','tenants/create':'tenants','alerts/metrics':'alerts/rules','alerts/objects':'alerts/rules'}; - function resolveViewRequest(requested){const raw=String(requested||'overview');const parts=raw.split('/');const head=parts[0];const rest=parts.slice(1).join('/');const alias=viewAliases[head];const name=Array.isArray(alias)?alias[0]:head;const children=viewModuleChildren[name];let child=Array.isArray(alias)&&alias[1]?alias[1]:'';if(rest&&children&&children.includes(rest))child=rest;if(!child&&children)child=children[0];return{name:name,child:child,source:child?name+'/'+child:head}} + const moduleNavKey = {'gateway/overview':'gateway','gateway/model-pool':'gateway','platform/general':'platform','platform/probing':'platform','platform/logs':'platform','platform/heal':'platform','platform/accounts':'platform','signals/metrics':'signals','signals/logs':'signals','signals/promql':'signals','signals/catalog':'signals','signals/tokens':'signals','traces/runs':'traces','traces/session':'traces','devices/list':'devices','devices/logs':'devices','devices/register':'devices','tenants/list':'tenants','tenants/create':'tenants','alerts/metrics':'alerts/rules','alerts/objects':'alerts/rules'}; + function resolveViewRequest(requested){const raw=String(requested||'overview');const parts=raw.split('/');const head=parts[0];const rest=parts.slice(1).join('/');const alias=viewAliases[raw]||viewAliases[head];const name=Array.isArray(alias)?alias[0]:head;const children=viewModuleChildren[name];let child=Array.isArray(alias)&&alias[1]?alias[1]:'';if(rest&&children&&children.includes(rest))child=rest;if(!child&&children)child=children[0];return{name:name,child:child,source:child?name+'/'+child:head}} const state = { overview:null, overviewHours:24, config:null, remediation:null, actions:null, learning:null, operatorMetrics:null, modelPool:null, objects:null, objectSelection:null, objectDetail:null, objectDetailLoading:false, objectSearch:'', objectTeam:'all', objectOwnerTeam:'all', objectLabel:'all', objectType:'all', objectArchived:'all', database:null, databaseHours:24, databaseLoading:false, databaseLoadedAt:0, databaseTableSelection:null, databaseTableDetail:null, databaseTablePage:1, databaseTableLoading:false, databaseTableSortColumn:'', databaseTableSortDirection:'asc', traceEnvironment:null, traceOutcome:null, investigationOverview:null, investigationOutcome:null, investigationQuery:'', pendingRemediate:null, pendingAlertDetail:null, pendingAlertEvidenceAt:null, view:'overview', viewSource:'overview', domain:'cloud', category:'all', statusFilter:'all', search:'', editingKey:null, editorDirty:false, editorReturnFocus:null, templateEditing:false, accessRendered:false }; - const viewMeta = {overview:['可观测中心 / 总览','生产可观测与告警','先判断生产影响,再处理事故、维护告警,最后下钻到链路证据。'],platform:['可观测中心 / 平台配置','平台配置','模型池路由、真实业务拨测、日志签名、自愈策略与全局设置。'],investigate:['可观测中心 / 事故调查','事故调查','关联异常趋势、代表证据与影响范围,形成可复核的根因假设。'],alerts:['可观测中心 / 告警策略','告警策略','管理指标、日志与拨测规则,验证阈值并安全配置通知。'],traces:['可观测中心 / 链路追踪','链路追踪','从原生 Trace 与会话链路定位慢请求、失败步骤和模型路由。'],'operator-metrics':['可观测中心 / 用户增长与活跃','用户增长与活跃','先看新增用户与活跃趋势,再核对对话、运行量和模型消耗。'],'data-health':['可观测中心 / 数据健康','数据健康','检查关键业务数据是否持续入库,并核对数量、趋势与最近写入。'],database:['可观测中心 / 数据库','数据库','从表目录和关系图下钻,并通过脱敏只读查询获取证据。'],'skill-loop':['可观测中心 / 学习与进化','Skill 数据闭环','把埋点采集、运行反馈、候选审核和发布回流放在同一条可追溯链路。'],evolution:['可观测中心 / 学习与进化','每日自我进化','查看证据聚合、质量闸门和可审核候选;候选不会自动上线。'],metrics:['可观测中心 / 告警策略','指标与数据源','核对系统指标的数据源、状态和阈值。'],rules:['可观测中心 / 告警策略','告警策略','按指标、日志和拨测筛选,完成数据源到通知的策略闭环。'],channels:['可观测中心 / 通知模板','通知模板','先确认投递状态,再按需编辑降噪策略与渠道凭据。'],'agent-traces':['可观测中心 / 链路追踪','链路追踪','从运行、模型、工具和关联证据定位单次 Agent / 会话问题。'],'session-traces':['可观测中心 / 链路追踪','会话 Trace','按会话重放用户到 Agent 的完整链路。'],'model-pool':['可观测中心 / 模型池','模型路由池','查看模型健康与路由配置。'],settings:['可观测中心 / 系统设置','系统配置','配置评估器、Canary 真实业务拨测和日志签名。'],'service-levels':['可观测中心 / SLO','SLO 与错误预算','用 SLO 和错误预算衡量用户可感知的可靠性。'],signals:['可观测中心 / 观测查询','观测查询','查询 OTLP 落库的指标与日志,把常用查询保存为自定义面板。'],devices:['可观测中心 / 边缘设备','边缘设备','查看设备状态,通过 SSH 采集端侧运行日志。'],'platform/accounts':['可观测中心 / 平台配置 · 账号行为','账号行为视角','按 SSO 账号聚合 Agent Run、会话用量、配置变更、事故处置与事件流水(只读审计)。'],'platform/model-pool':['可观测中心 / 系统配置 · 模型池','模型路由池','查看模型池目标健康、路由优先级与网关容量。'],'platform/general':['可观测中心 / 平台配置 · 评估器','平台配置 · 评估器','所有规则每分钟独立评估;配置全局开关与环境标签。'],'platform/probing':['可观测中心 / 系统配置 · 业务拨测','真实业务拨测','Canary 账号执行真实登录、AI 对话与只读工具调用。'],'platform/logs':['可观测中心 / 系统配置 · 日志签名','日志错误签名','固定文本匹配识别日志错误;原始日志不会进入通知。'],'platform/heal':['可观测中心 / 系统配置 · 自愈策略','自愈策略','自动自愈按首个匹配剧本执行;未开启时可手动一键自愈。'],'alerts/rules':['可观测中心 / 告警策略 · 策略','告警策略','按指标、日志和拨测筛选,完成数据源到通知的策略闭环。'],'alerts/strategies':['可观测中心 / 自定义策略','自定义策略','面向租户与平台的 PromQL 阈值策略:规则行一对多,持续时长判定触发与恢复。'],'alerts/silence':['可观测中心 / 告警屏蔽','告警屏蔽','计划内维护的屏蔽窗口:屏蔽期间事故照常记录、通知暂停,结束后自动补发。'],"alerts/center":['可观测中心 / 告警中心','告警中心','待认领、处理中与已关闭的处置队列,用 MTTA / MTTR 衡量响应效率。'],'alerts/metrics':['可观测中心 / 告警策略 · 数据源','指标与数据源','核对系统指标的数据源、状态和阈值。'],'alerts/objects':['可观测中心 / 告警策略 · 对象','告警对象','对象注册表与选择入口,查看最近 run、标签与归属。'],'alerts/channels':['可观测中心 / 告警策略 · 通知','通知模板','先确认投递状态,再按需编辑降噪策略与渠道凭据。'],'signals/metrics':['可观测中心 / 观测查询 · 指标','指标查询','查询 OTLP metrics 落库后的时序数据。'],'signals/logs':['可观测中心 / 观测查询 · 日志','日志查询','按服务与级别检索 OTLP logs 落库后的低敏感字段。'],'signals/panels':['可观测中心 / 观测查询 · 看板','自定义看板','把常用指标放在一起,按需查看详细趋势。'],'signals/quality':['可观测中心 / 观测查询 · 质量','质量与反馈','run 级评分与用户反馈的按天趋势。'],'signals/catalog':['可观测中心 / 观测查询 · 字典','指标字典','有哪些指标、什么含义、怎么查;点指标名自动填入查询。'],'signals/tokens':['可观测中心 / 观测查询 · 接入凭据','生态接入凭据','按人/服务/租户签发 OTLP 上报凭据;身份只在凭据层,遥测零 PII。'],'signals/promql':['可观测中心 / 观测查询 · PromQL','PromQL 查询','直接执行 PromQL 查询 Prometheus 深度历史;平台内 OTLP 序列请用指标查询。'],'traces/runs':['可观测中心 / 链路追踪 · 运行','链路追踪','从运行、模型、工具和关联证据定位单次 Agent / 会话问题。'],'traces/session':['可观测中心 / 链路追踪','链路追踪','按会话串联多次运行,展开运行查看调用证据。'],'devices/list':['可观测中心 / 边缘设备 · 清单','设备清单','查看设备在线状态、最近心跳与板级指标。'],'devices/logs':['可观测中心 / 边缘设备 · 日志','RDK 日志调查','平台通过 SSH 实时采集端侧日志,支持筛选、停止和导出。'],'devices/register':['可观测中心 / 边缘设备 · 注册','注册设备','签发设备 token 并部署 edge-agent。'],'tenants/list':['可观测中心 / 租户管理 · 列表','租户列表','查看租户状态、最近上报时间与凭据操作。'],'tenants/create':['可观测中心 / 租户管理 · 创建','创建租户','为新团队创建租户并签发探针 token。']}; + const viewMeta = {overview:['可观测中心 / 总览','生产可观测与告警','先判断生产影响,再处理事故、维护告警,最后下钻到链路证据。'],gateway:['可观测中心 / 网关','网关',''],platform:['可观测中心 / 平台配置','平台配置','真实业务拨测、日志签名、自愈策略与全局设置。'],investigate:['可观测中心 / 事故调查','事故调查','关联异常趋势、代表证据与影响范围,形成可复核的根因假设。'],alerts:['可观测中心 / 告警策略','告警策略','管理指标、日志与拨测规则,验证阈值并安全配置通知。'],traces:['可观测中心 / 链路追踪','链路追踪','从原生 Trace 与会话链路定位慢请求、失败步骤和模型路由。'],'operator-metrics':['可观测中心 / 用户增长与活跃','用户增长与活跃','先看新增用户与活跃趋势,再核对对话、运行量和模型消耗。'],'data-health':['可观测中心 / 数据健康','数据健康','检查关键业务数据是否持续入库,并核对数量、趋势与最近写入。'],database:['可观测中心 / 数据库','数据库','从表目录和关系图下钻,并通过脱敏只读查询获取证据。'],'skill-loop':['可观测中心 / 学习与进化','Skill 数据闭环','把埋点采集、运行反馈、候选审核和发布回流放在同一条可追溯链路。'],evolution:['可观测中心 / 学习与进化','每日自我进化','查看证据聚合、质量闸门和可审核候选;候选不会自动上线。'],metrics:['可观测中心 / 告警策略','指标与数据源','核对系统指标的数据源、状态和阈值。'],rules:['可观测中心 / 告警策略','告警策略','按指标、日志和拨测筛选,完成数据源到通知的策略闭环。'],channels:['可观测中心 / 通知模板','通知模板','先确认投递状态,再按需编辑降噪策略与渠道凭据。'],'agent-traces':['可观测中心 / 链路追踪','链路追踪','从运行、模型、工具和关联证据定位单次 Agent / 会话问题。'],'session-traces':['可观测中心 / 链路追踪','会话 Trace','按会话重放用户到 Agent 的完整链路。'],'model-pool':['可观测中心 / 模型池','模型路由池','查看模型健康与路由配置。'],settings:['可观测中心 / 系统设置','系统配置','配置评估器、Canary 真实业务拨测和日志签名。'],'service-levels':['可观测中心 / SLO','SLO 与错误预算','用 SLO 和错误预算衡量用户可感知的可靠性。'],signals:['可观测中心 / 观测查询','观测查询','查询 OTLP 落库的指标与日志,把常用查询保存为自定义面板。'],devices:['可观测中心 / 边缘设备','边缘设备','查看设备状态,通过 SSH 采集端侧运行日志。'],'platform/accounts':['可观测中心 / 平台配置 · 账号行为','账号行为视角','按 SSO 账号聚合 Agent Run、会话用量、配置变更、事故处置与事件流水(只读审计)。'],'platform/model-pool':['可观测中心 / 系统配置 · 模型池','模型路由池','查看模型池目标健康、路由优先级与网关容量。'],'platform/general':['可观测中心 / 平台配置 · 评估器','平台配置 · 评估器','所有规则每分钟独立评估;配置全局开关与环境标签。'],'platform/probing':['可观测中心 / 系统配置 · 业务拨测','真实业务拨测','Canary 账号执行真实登录、AI 对话与只读工具调用。'],'platform/logs':['可观测中心 / 系统配置 · 日志签名','日志错误签名','固定文本匹配识别日志错误;原始日志不会进入通知。'],'platform/heal':['可观测中心 / 系统配置 · 自愈策略','自愈策略','自动自愈按首个匹配剧本执行;未开启时可手动一键自愈。'],'alerts/rules':['可观测中心 / 告警策略 · 策略','告警策略','按指标、日志和拨测筛选,完成数据源到通知的策略闭环。'],'alerts/strategies':['可观测中心 / 自定义策略','自定义策略','面向租户与平台的 PromQL 阈值策略:规则行一对多,持续时长判定触发与恢复。'],'alerts/silence':['可观测中心 / 告警屏蔽','告警屏蔽','计划内维护的屏蔽窗口:屏蔽期间事故照常记录、通知暂停,结束后自动补发。'],"alerts/center":['可观测中心 / 告警中心','告警中心','待认领、处理中与已关闭的处置队列,用 MTTA / MTTR 衡量响应效率。'],'alerts/metrics':['可观测中心 / 告警策略 · 数据源','指标与数据源','核对系统指标的数据源、状态和阈值。'],'alerts/objects':['可观测中心 / 告警策略 · 对象','告警对象','对象注册表与选择入口,查看最近 run、标签与归属。'],'alerts/channels':['可观测中心 / 告警策略 · 通知','通知模板','先确认投递状态,再按需编辑降噪策略与渠道凭据。'],'signals/metrics':['可观测中心 / 观测查询 · 指标','指标查询','查询 OTLP metrics 落库后的时序数据。'],'signals/logs':['可观测中心 / 观测查询 · 日志','日志查询','按服务与级别检索 OTLP logs 落库后的低敏感字段。'],'signals/panels':['可观测中心 / 观测查询 · 看板','自定义看板','把常用指标放在一起,按需查看详细趋势。'],'signals/quality':['可观测中心 / 观测查询 · 质量','质量与反馈','run 级评分与用户反馈的按天趋势。'],'signals/catalog':['可观测中心 / 观测查询 · 字典','指标字典','有哪些指标、什么含义、怎么查;点指标名自动填入查询。'],'signals/tokens':['可观测中心 / 观测查询 · 接入凭据','生态接入凭据','按人/服务/租户签发 OTLP 上报凭据;身份只在凭据层,遥测零 PII。'],'signals/promql':['可观测中心 / 观测查询 · PromQL','PromQL 查询','直接执行 PromQL 查询 Prometheus 深度历史;平台内 OTLP 序列请用指标查询。'],'traces/runs':['可观测中心 / 链路追踪 · 运行','链路追踪','从运行、模型、工具和关联证据定位单次 Agent / 会话问题。'],'traces/session':['可观测中心 / 链路追踪','链路追踪','按会话串联多次运行,展开运行查看调用证据。'],'devices/list':['可观测中心 / 边缘设备 · 清单','设备清单','查看设备在线状态、最近心跳与板级指标。'],'devices/logs':['可观测中心 / 边缘设备 · 日志','RDK 日志调查','平台通过 SSH 实时采集端侧日志,支持筛选、停止和导出。'],'devices/register':['可观测中心 / 边缘设备 · 注册','注册设备','签发设备 token 并部署 edge-agent。'],'tenants/list':['可观测中心 / 租户管理 · 列表','租户列表','查看租户状态、最近上报时间与凭据操作。'],'tenants/create':['可观测中心 / 租户管理 · 创建','创建租户','为新团队创建租户并签发探针 token。']}; const categoryNames = {metric:'指标',log:'日志',probe:'拨测'}; const statusNames = {healthy:'正常',observing:'Pending',warning:'告警',critical:'严重',stale:'数据过期',disabled:'已停用',open:'进行中',acknowledged:'已确认',silenced:'已静默',resolved:'已恢复',running:'运行中',no_candidate:'暂无候选',candidate_ready:'待审核',rejected:'已拒绝',blocked:'已阻塞',error:'失败',never:'未运行'}; const severityNames = {critical:'严重',warning:'警告'}; @@ -212,7 +212,7 @@ export const OPS_OBSERVABILITY_SCRIPT_A = ` (() => { if(opsTenantMode&&name!=='overview')return setView('overview',updateHash); // SSO 组员模式:放开总览(本租户只读)、租户(owner 管组员 / // member 看本租户名单)与告警中心(本租户事故处置);其余视图属于平台运营域。 - if(opsMemberMode&&name!=='overview'&&name!=='tenants'&&!(name==='alerts'&&(resolved.child==='center'||resolved.child==='strategies')))return setView('overview',updateHash);state.view=name;state.viewSource=source;state.viewChild=resolved.child;updateViewHeader(source,name);syncScopeVisibility(name);openNavGroupForView(name,source);const activeView=document.querySelector('[data-view="'+source+'"]')?source:(moduleNavKey[source]||name);document.querySelectorAll('[data-view]').forEach(button=>{const active=button.dataset.view===activeView;button.classList.toggle('active',active);if(active)button.setAttribute('aria-current','page');else button.removeAttribute('aria-current')});viewNames.forEach(view=>{const node=$('view-'+view);if(node)node.classList.toggle('hidden',view!==name)});if(updateHash)history.replaceState(null,'','#'+source);applyViewModules(name,source);if(name==='investigate'&&typeof renderInvestigation==='function')renderInvestigation(state.investigationOverview||state.overview);if(name==='signals'&&typeof renderSignalsView==='function')renderSignalsView();if(name==='devices'&&resolved.child==='list'&&typeof loadDevicesView==='function')loadDevicesView();if(name==='service-levels')renderServiceLevels();if(name==='operator-metrics'&&typeof loadOperatorMetrics==='function')loadOperatorMetrics(false);if((name==='data-health'||name==='database')&&typeof loadPostgresDashboard==='function')loadPostgresDashboard();if((name==='skill-loop'||name==='evolution')&&typeof renderLearningModules==='function')renderLearningModules();if(name==='alerts'){if(!opsMemberMode){if(typeof renderMetrics==='function')renderMetrics();if(typeof renderObjects==='function')renderObjects();renderRules();renderChannels()}if(resolved.child==='center'&&typeof loadIncidentCenter==='function')loadIncidentCenter();if(resolved.child==='strategies'&&typeof loadStrategyList==='function')loadStrategyList();if(resolved.child==='silence'&&typeof renderSilencePage==='function')renderSilencePage()}if(name==='traces'){if(typeof renderNativeTraces==='function')renderNativeTraces();if(typeof refreshTraceSearch==='function')refreshTraceSearch()}if(name==='tenants'){if(opsMemberMode&&typeof renderObsMemberTenantsView==='function')renderObsMemberTenantsView();else{bindTenantPanel();loadTenants()}}if(name==='platform'){renderSettings();renderEvolution();if(resolved.child==='model-pool'&&typeof renderModelPool==='function')renderModelPool();if(resolved.child==='accounts'&&typeof renderAccountActivity==='function')renderAccountActivity()}} + if(opsMemberMode&&name!=='overview'&&name!=='tenants'&&!(name==='alerts'&&(resolved.child==='center'||resolved.child==='strategies')))return setView('overview',updateHash);state.view=name;state.viewSource=source;state.viewChild=resolved.child;updateViewHeader(source,name);syncScopeVisibility(name);openNavGroupForView(name,source);const activeView=document.querySelector('[data-view="'+source+'"]')?source:(moduleNavKey[source]||name);document.querySelectorAll('[data-view]').forEach(button=>{const active=button.dataset.view===activeView;button.classList.toggle('active',active);if(active)button.setAttribute('aria-current','page');else button.removeAttribute('aria-current')});viewNames.forEach(view=>{const node=$('view-'+view);if(node)node.classList.toggle('hidden',view!==name)});if(updateHash)history.replaceState(null,'','#'+source);applyViewModules(name,source);if(name==='investigate'&&typeof renderInvestigation==='function')renderInvestigation(state.investigationOverview||state.overview);if(name==='signals'&&typeof renderSignalsView==='function')renderSignalsView();if(name==='devices'&&resolved.child==='list'&&typeof loadDevicesView==='function')loadDevicesView();if(name==='service-levels')renderServiceLevels();if(name==='operator-metrics'&&typeof loadOperatorMetrics==='function')loadOperatorMetrics(false);if((name==='data-health'||name==='database')&&typeof loadPostgresDashboard==='function')loadPostgresDashboard();if((name==='skill-loop'||name==='evolution')&&typeof renderLearningModules==='function')renderLearningModules();if(name==='alerts'){if(!opsMemberMode){if(typeof renderMetrics==='function')renderMetrics();if(typeof renderObjects==='function')renderObjects();renderRules();renderChannels()}if(resolved.child==='center'&&typeof loadIncidentCenter==='function')loadIncidentCenter();if(resolved.child==='strategies'&&typeof loadStrategyList==='function')loadStrategyList();if(resolved.child==='silence'&&typeof renderSilencePage==='function')renderSilencePage()}if(name==='traces'){if(typeof renderNativeTraces==='function')renderNativeTraces();if(typeof refreshTraceSearch==='function')refreshTraceSearch()}if(name==='tenants'){if(opsMemberMode&&typeof renderObsMemberTenantsView==='function')renderObsMemberTenantsView();else{bindTenantPanel();loadTenants()}}if(name==='gateway'){if(typeof renderSettings==='function')renderSettings();if(resolved.child==='overview'&&typeof renderGatewayOverview==='function')renderGatewayOverview();if(resolved.child==='model-pool'&&typeof renderModelPool==='function')renderModelPool()}if(name==='platform'){renderSettings();renderEvolution();if(resolved.child==='accounts'&&typeof renderAccountActivity==='function')renderAccountActivity()}} function loadErrorHint(label){const text=String(label||'');if(text.includes('中心库未启用'))return '当前环境尚未配置中心库;完成数据库配置后即可使用租户与组员数据。';if(text.includes('权限'))return '请确认当前账号的运营权限后重试。';return '请检查网络或运营权限后重试。'} // 加载/失败面板统一走 OpsUI.state:失败态 role=alert/assertive + 重试按钮, // 加载态 role=status;结构与类名(panel.load-state)保持不变。 diff --git a/server/monitoring/observability-page-script-b.ts b/server/monitoring/observability-page-script-b.ts index 7a0e9b4..e6a5b68 100644 --- a/server/monitoring/observability-page-script-b.ts +++ b/server/monitoring/observability-page-script-b.ts @@ -127,7 +127,7 @@ selectField(fields,'defaultChannel','默认渠道',c.notification.channel,channe // 带上);组员/owner 管理界面在租户视图里按需加载。平台 config 等域 // 不请求,与探针 token 模式同样避免 403 降级噪音。 if(opsMemberMode){const data=await request('/api/ops/observability/overview?hours='+encodeURIComponent(String(requestedHours)));if(!currentRequest())return;state.accessRendered=false;document.querySelector('[data-access-screen]')?.remove();state.overview=readOverviewPayload(data);state.config=null;state.remediation=null;state.actions=null;state.objects=null;state.objectDetail=null;if(typeof applyOverviewSnapshot==='function')applyOverviewSnapshot(state.overview);else if(typeof renderOverview==='function')renderOverview();if(meta)meta.textContent='组员视图 · '+opsSsoActiveTenant+' · 最近检查 '+when(state.overview.alerting.lastCheckedAt);// 组员可见面:总览 / 租户 / 告警中心(本租户处置);其余视图回落总览。 - if(!(state.view==='overview'||state.view==='tenants'||(state.view==='alerts'&&(state.viewChild==='center'||state.viewChild==='strategies'))))setView('overview',false);return}const results=await Promise.all([request((typeof traceOverviewPath==='function'?traceOverviewPath(requestedHours):'/api/ops/observability/overview?hours='+encodeURIComponent(String(requestedHours)))+adminTenantQuery()),request('/api/ops/observability/config'),request('/api/ops/observability/remediation').catch(()=>null),(typeof actionLoopReadUnavailable==='function'&&actionLoopReadUnavailable()?Promise.resolve(null):request('/api/ops/observability/actions',{headers:actionContextHeaders}).catch(error=>{if(error.status===403&&state.actionLoop){state.actionLoop.accessDenied=true;state.actionLoop.error=actionLoopFriendlyError(error)}return null})),request('/api/ops/observability/objects?limit=200').catch(()=>null),objectSelection?request('/api/ops/observability/objects/'+encodeURIComponent(objectSelection.objectId)+objectDetailQuery).catch(()=>null):Promise.resolve(null)]);if(!currentRequest())return;state.accessRendered=false;document.querySelector('[data-access-screen]')?.remove();state.overview=readOverviewPayload(results[0]);state.config=results[1].config;state.remediation=results[2]?results[2].remediation:null;state.actions=results[3]?results[3].actions:null;state.objects=results[4]?results[4].objects:null;state.objectDetail=results[5]?results[5].detail:null;if(typeof applyOverviewSnapshot==='function')applyOverviewSnapshot(state.overview);else if(typeof renderOverview==='function')renderOverview();if(meta)meta.textContent=(obsAuthState.me&&obsAuthState.me.admin&&obsActiveTenant()?'租户视角 '+obsActiveTenant()+' · ':'')+'每分钟评估 · 最近检查 '+when(state.overview.alerting.lastCheckedAt)+' · 配置更新 '+when(state.config.updatedAt);if(typeof renderEvolution==='function')renderEvolution();if(typeof renderMetrics==='function')renderMetrics();if(typeof renderObjects==='function')renderObjects();if(typeof renderRules==='function')renderRules();if(typeof renderChannels==='function')renderChannels();if(typeof renderSettings==='function')renderSettings();setView(state.viewSource||state.view,false);if(state.pendingRemediate){setView('overview',false);const node=$('remediationSection');if(node)node.scrollIntoView({behavior:'smooth',block:'start'});toast('告警 '+state.pendingRemediate+' 已定位到证据化行动队列,请先完成 evidence proof、提案与审批');state.pendingRemediate=null}if(state.pendingAlertDetail)consumePendingAlertDetail()}catch(error){if(!currentRequest())return;if(error&&error.forbidden){// 403:账号仍在线但权限变了(被移出租户 / 租户停用 / 模块域降级)。 + if(!(state.view==='overview'||state.view==='tenants'||(state.view==='alerts'&&(state.viewChild==='center'||state.viewChild==='strategies'))))setView('overview',false);return}const results=await Promise.all([request((typeof traceOverviewPath==='function'?traceOverviewPath(requestedHours):'/api/ops/observability/overview?hours='+encodeURIComponent(String(requestedHours)))+adminTenantQuery()),request('/api/ops/observability/config'),request('/api/ops/observability/remediation').catch(()=>null),(typeof actionLoopReadUnavailable==='function'&&actionLoopReadUnavailable()?Promise.resolve(null):request('/api/ops/observability/actions',{headers:actionContextHeaders}).catch(error=>{if(error.status===403&&state.actionLoop){state.actionLoop.accessDenied=true;state.actionLoop.error=actionLoopFriendlyError(error)}return null})),request('/api/ops/observability/objects?limit=200').catch(()=>null),objectSelection?request('/api/ops/observability/objects/'+encodeURIComponent(objectSelection.objectId)+objectDetailQuery).catch(()=>null):Promise.resolve(null)]);if(!currentRequest())return;state.accessRendered=false;document.querySelector('[data-access-screen]')?.remove();state.overview=readOverviewPayload(results[0]);state.config=results[1].config;state.gatewayReadError=false;state.remediation=results[2]?results[2].remediation:null;state.actions=results[3]?results[3].actions:null;state.objects=results[4]?results[4].objects:null;state.objectDetail=results[5]?results[5].detail:null;if(typeof applyOverviewSnapshot==='function')applyOverviewSnapshot(state.overview);else if(typeof renderOverview==='function')renderOverview();if(meta)meta.textContent=(obsAuthState.me&&obsAuthState.me.admin&&obsActiveTenant()?'租户视角 '+obsActiveTenant()+' · ':'')+'每分钟评估 · 最近检查 '+when(state.overview.alerting.lastCheckedAt)+' · 配置更新 '+when(state.config.updatedAt);if(typeof renderEvolution==='function')renderEvolution();if(typeof renderMetrics==='function')renderMetrics();if(typeof renderObjects==='function')renderObjects();if(typeof renderRules==='function')renderRules();if(typeof renderChannels==='function')renderChannels();if(typeof renderSettings==='function')renderSettings();setView(state.viewSource||state.view,false);if(state.pendingRemediate){setView('overview',false);const node=$('remediationSection');if(node)node.scrollIntoView({behavior:'smooth',block:'start'});toast('告警 '+state.pendingRemediate+' 已定位到证据化行动队列,请先完成 evidence proof、提案与审批');state.pendingRemediate=null}if(state.pendingAlertDetail)consumePendingAlertDetail()}catch(error){if(!currentRequest())return;if(typeof updateGatewayReadError==='function')updateGatewayReadError(true);if(error&&error.forbidden){// 403:账号仍在线但权限变了(被移出租户 / 租户停用 / 模块域降级)。 // 保留已渲染视图,只更新状态与提示;解释性 toast 已由 request() 发出。 const message=friendlyError(error.message);if(typeof projectTelemetryState==='function')projectTelemetryState('unauthorized');if(meta)meta.textContent='权限已变化:'+message+',可点击“刷新”重试';if(!state.overview&&typeof renderLoadPanel==='function')renderLoadPanel($('overviewContent'),'权限已变化:'+message,true)}else if(error.message!=='not_authorized'){const message=friendlyError(error.message);if(meta)meta.textContent='刷新失败:'+message+',可点击“刷新”重试';console.warn('[d-obs] 刷新异常(数据保持上次成功渲染)',error);if(!state.overview){if(typeof projectTelemetryState==='function')projectTelemetryState('error');if(typeof renderInitialError==='function')renderInitialError(error.message);if(typeof renderLoadPanel==='function')renderLoadPanel($('overviewContent'),'加载失败:'+message,true)}else{toast('加载失败:'+message,false)}}}finally{if(requestToken===state.overviewLoadRequestToken&&refresh){refresh.disabled=false;refresh.removeAttribute('aria-busy');refresh.textContent='刷新数据'}}} `; diff --git a/server/monitoring/observability-page-script-model-pool.ts b/server/monitoring/observability-page-script-model-pool.ts index b8c286b..694eb16 100644 --- a/server/monitoring/observability-page-script-model-pool.ts +++ b/server/monitoring/observability-page-script-model-pool.ts @@ -1,7 +1,30 @@ /** 模型池控制面:路由拓扑可视化 + 权重/备用顺序就地调整;替换与回滚收在高级操作。 */ export const OPS_OBSERVABILITY_SCRIPT_MODEL_POOL = ` + let modelPoolIdentity=null; + let modelPoolPending=null; + let modelPoolReadFailed=false; + function syncModelPoolIdentity(){ + const identity=alertEvidenceIdentityContext(); + if(identity!==modelPoolIdentity){modelPoolIdentity=identity;state.modelPool=null;modelPoolReadFailed=false} + return identity; + } async function loadModelPool(){ - try{const data=await request('/api/ops/observability/model-pool');state.modelPool=data;renderModelPool()}catch(error){if(error.message!=='not_authorized')toast('模型池加载失败:'+friendlyError(error.message),false)}} + if(!gatewayPlatformAvailable())return; + const identity=syncModelPoolIdentity(); + if(modelPoolPending?.identity===identity)return; + const pending={identity};modelPoolPending=pending;modelPoolReadFailed=false; + const current=()=>modelPoolPending===pending&&gatewayPlatformAvailable()&&identity===alertEvidenceIdentityContext(); + try{ + const data=await request('/api/ops/observability/model-pool'); + if(!Array.isArray(data?.health?.targets)||!data?.config?.modelMapping)throw new Error('model_pool_incomplete'); + if(current())state.modelPool=data; + }catch{ + if(current()){state.modelPool=null;modelPoolReadFailed=true} + }finally{ + const render=current();if(modelPoolPending===pending)modelPoolPending=null; + if(render)renderModelPool(); + } + } function modelStateName(value){return ({healthy:'正常',half_open:'半开',cooldown:'冷却',degraded:'退化'})[value]||value||'未知'} function modelStateClass(value){return value==='healthy'?'good':(value==='cooldown'?'bad':(value==='half_open'?'warn':''))} function modelTargetName(target){return (target.frontendModels&&target.frontendModels[0])||target.label||target.model} @@ -115,7 +138,10 @@ export const OPS_OBSERVABILITY_SCRIPT_MODEL_POOL = ` } function renderModelPool(){ const root=$('modelPoolContent');if(!root)return;root.replaceChildren(); - if(!state.modelPool){add(root,'div','empty','正在读取模型池状态…');loadModelPool();return} + syncModelPoolIdentity(); + if(!gatewayPlatformAvailable()){gatewayScopeNotice(root);return} + if(modelPoolReadFailed){OpsUI.state(root,{kind:'error',title:'模型池读取失败',hint:'重试后确认当前模型目标和路由。',retry:()=>{loadModelPool();renderModelPool()}});return} + if(!state.modelPool){OpsUI.state(root,{kind:'loading',title:'正在读取模型池状态…'});loadModelPool();return} const health=state.modelPool.health||{};const config=state.modelPool.config||{};const allTargets=health.targets||[];const summary=health.summary||{};const mapping=config.modelMapping||{};const protectedFrontendModel=state.modelPool.protectedFrontendModel||''; const cleanupTargets=allTargets.filter(modelCleanupCandidate);const filter=state.modelPoolFilter||'all';const targets=filter==='cleanup'?cleanupTargets:filter==='attention'?allTargets.filter(target=>target.state!=='healthy'):allTargets; const head=make('div','model-pool-toolbar');const copy=make('div');add(copy,'h2','','模型池');add(copy,'p','','常用操作直接在列表完成;路由权重与备用顺序在拓扑下方就地调整,替换与回滚收在高级操作。');head.appendChild(copy);const headActions=make('div','model-pool-actions');const refresh=add(headActions,'button','btn','刷新');refresh.type='button';refresh.addEventListener('click',()=>loadModelPool());if(cleanupTargets.length){const cleanAll=add(headActions,'button','btn danger','清理 '+cleanupTargets.length+' 个无用目标');cleanAll.type='button';cleanAll.addEventListener('click',async()=>{if(!window.confirm('确认清理 '+cleanupTargets.length+' 个没有路由引用的模型目标?此操作会从网关模型池移除目标。'))return;cleanAll.disabled=true;let count=0;for(const target of cleanupTargets){if(await cleanupModelTarget(target))count++}toast(count?'已清理 '+count+' 个模型目标':'没有模型被清理',Boolean(count));await loadModelPool()})}head.appendChild(headActions);root.appendChild(head); diff --git a/server/monitoring/observability-page-simple-nav.ts b/server/monitoring/observability-page-simple-nav.ts index bb334de..8f5b98b 100644 --- a/server/monitoring/observability-page-simple-nav.ts +++ b/server/monitoring/observability-page-simple-nav.ts @@ -30,7 +30,7 @@ export const OPS_OBSERVABILITY_SIMPLE_NAV_SCRIPT = String.raw` const nav=document.querySelector('.module-tabs'); if(!nav||nav.dataset.simpleNavVersion==='1')return; if(!nav.id&&!document.getElementById('moduleTabs'))nav.id='moduleTabs'; - const primaryRoutes=['overview','alerts/center','traces','signals','devices']; + const primaryRoutes=['overview','alerts/center','traces','gateway','signals','devices']; const groupedRoutes={ data:['investigate','operator-metrics','signals/panels','signals/quality','service-levels','skill-loop','evolution'], infra:['data-health','database'], @@ -134,7 +134,7 @@ export const OPS_OBSERVABILITY_SIMPLE_NAV_SCRIPT = String.raw` Object.keys(groups).forEach(key=>groups[key].items.querySelectorAll('.module-tab[data-view]').forEach(tab=>{navGroupByView[route(tab)]=key})); } if(typeof moduleNavKey!=='undefined')Object.assign(moduleNavKey,{ - 'platform/model-pool':'platform','platform/general':'platform','platform/probing':'platform', + 'gateway/overview':'gateway','gateway/model-pool':'gateway','platform/general':'platform','platform/probing':'platform', 'platform/logs':'platform','platform/heal':'platform','platform/accounts':'platform', 'signals/metrics':'signals','signals/logs':'signals','signals/promql':'signals', 'signals/catalog':'signals','signals/tokens':'signals', diff --git a/server/monitoring/observability-page-simple-presentation.ts b/server/monitoring/observability-page-simple-presentation.ts index a35de82..a5621a0 100644 --- a/server/monitoring/observability-page-simple-presentation.ts +++ b/server/monitoring/observability-page-simple-presentation.ts @@ -74,7 +74,7 @@ export const OPS_OBSERVABILITY_SIMPLE_PRESENTATION_SCRIPT = ` const body=add(options,'div');body.appendChild(check);add(body,'p','','重新运行巡检。刷新只读取当前数据。'); } } - const simpleTabDefaults={signals:['signals/metrics','signals/logs','signals/promql'],alerts:['alerts/center'],platform:['platform/model-pool'],devices:['devices/list'],tenants:['tenants/list']}; + const simpleTabDefaults={signals:['signals/metrics','signals/logs','signals/promql'],alerts:['alerts/center'],gateway:['gateway/overview','gateway/model-pool'],platform:['platform/general'],devices:['devices/list'],tenants:['tenants/list']}; const simpleTabGroups=[]; function simpleVisibleTab(tab){ if(tab.hidden||tab.disabled||tab.getAttribute('aria-disabled')==='true'||tab.classList.contains('hidden')||tab.classList.contains('simple-role-hidden'))return false; diff --git a/server/monitoring/observability-page-ux.ts b/server/monitoring/observability-page-ux.ts index 473d8e3..907260d 100644 --- a/server/monitoring/observability-page-ux.ts +++ b/server/monitoring/observability-page-ux.ts @@ -88,7 +88,8 @@ export const OPS_OBSERVABILITY_SCRIPT_UX = ` {view:'alerts/silence',label:'告警屏蔽',hint:'计划内维护窗口',keywords:'静默',icon:'◫',group:'管理'}, {view:'signals/tokens',label:'接入凭据',hint:'签发遥测上报凭据',keywords:'生态接入 token OpenTelemetry',icon:'⚙',group:'管理'}, {view:'tenants',label:'租户管理',hint:'团队与组员',keywords:'团队接入 探针 token 停启用',icon:'⧉',group:'管理'}, - {view:'platform/model-pool',label:'模型池',hint:'目标健康与路由',keywords:'优先级 替换',icon:'◈',group:'管理'}, + {view:'gateway',label:'网关',hint:'公网入口、主备与延迟',keywords:'DNS TLS 5xx 模型',icon:'◈',group:'基础设施'}, + {view:'gateway/model-pool',label:'模型池',hint:'目标健康与路由',keywords:'优先级 替换',icon:'◈',group:'管理'}, {view:'platform',label:'平台配置',hint:'评估器与全局设置',icon:'⚙',group:'管理'}, {view:'platform/probing',label:'业务拨测',hint:'Canary 真实探测',icon:'⚙',group:'管理'}, {view:'platform/logs',label:'日志签名',hint:'日志错误识别规则',icon:'⚙',group:'管理'}, diff --git a/server/monitoring/observability-page.ts b/server/monitoring/observability-page.ts index 309b36f..8e6f4a3 100644 --- a/server/monitoring/observability-page.ts +++ b/server/monitoring/observability-page.ts @@ -22,6 +22,7 @@ import { OPS_OBSERVABILITY_SCRIPT_OVERVIEW } from './observability-page-script-o import { OPS_OBSERVABILITY_SCRIPT_B } from './observability-page-script-b.js'; import { OPS_OBSERVABILITY_SCRIPT_C } from './observability-page-script-c.js'; import { OPS_OBSERVABILITY_SCRIPT_SLO } from './observability-page-script-slo.js'; +import { OPS_OBSERVABILITY_GATEWAY_HTML, OPS_OBSERVABILITY_GATEWAY_SCRIPT, OPS_OBSERVABILITY_GATEWAY_STYLE } from './observability-page-gateway.js'; import { OPS_OBSERVABILITY_SCRIPT_MODEL_POOL } from './observability-page-script-model-pool.js'; import { OPS_OBSERVABILITY_SCRIPT_INVESTIGATION } from './observability-page-script-investigation.js'; import { OPS_OBSERVABILITY_SCRIPT_USABILITY } from './observability-page-script-usability.js'; @@ -107,7 +108,7 @@ export const OPS_OBSERVABILITY_HTML = ` } catch (e) { /* localStorage 不可用(隐私模式等)则默认亮色 */ } })(); - + @@ -133,6 +134,7 @@ export const OPS_OBSERVABILITY_HTML = ` + @@ -387,10 +389,10 @@ ${OPS_OBSERVABILITY_SSH_LOGS_HTML}
租户 ID 是标识符不是名字:它会拼进告警键 t.<ID>.<检查项>(点作分隔符),并出现在 URL 与请求头里,因此只能用小写 ASCII 字母/数字/连字符(2–40 字符,需字母开头;platform 等保留字不可用)。中文名请填「显示名称」。
+ ${OPS_OBSERVABILITY_GATEWAY_HTML}