refactor: 全面改名为 HologramAgent + 提示词技术内容下沉到 skill/工具描述 + 修 21 处乱码

## ① 全面改名 HomeAgent → HologramAgent

仓库已改名,但代码与文档里仍有大量旧名。本次按"用户能看到的优先"全量替换:

- 用户可见:登录页标题/页脚、默认人格第一句、CLI 状态输出、启动日志、
  plugin_install 的工具描述、AI 图片插件的 User-Agent
- 文档与脚本:README、assets/docs、docs/zh、deploy/*.sh、.github/workflows
- 鸿蒙工程:cmd/ohos/HomeAgent → cmd/ohos/HologramAgent(git mv)
  目录内的 module/app 描述同步;**证书路径原样保留**
  (default_HomeAgent_xxx.cer/p7b/p12 是签名材料的实际文件名,改了会找不到证书)
- 插件元数据:plugin.json 的 author

★ 必须保持原样的两处(改了会坏):
  · legacySeededPromptSignature = "你是 HomeAgent 的看板娘「小宅」…"
    —— 那是识别历史播种人格卡的**原文锚点**,改了就识别不出旧数据
  · 公开 SDK 的 ProxyAuthHomeAgent = "homeagent"
    —— 那是 SDK 契约里的值,属独立仓库,本仓不改

## ② 修 21 处乱码(U+FFFD)

这些是历史编辑留下的编码破坏,全在注释里,例如:
  「赌注重下���遍」→「赌注重下一遍」
  「「不��滤」」  →「「不过滤」」
  「**待��退场**」→「**待退场**」

★ 保留 providers/chineseclip/tokenizer.go 里的 2 处:那是**故意**用
  U+FFFD 演示"非法 UTF-8 字节被归一成 U+FFFD",不是乱码。

## ③ 提示词技术内容下沉(用户:技术性内容应该收敛到 skill 与 -help 中)

实测系统提示词 2309 字,其中两段几乎全是**模型无法据以行动的实现细节**:

  【工具执行顺序】1272 字(ParallelSafe 声明、批内降级、batchRunnable 判据…)
  【三层记忆】   1069 字(L1/L2/L3 编号、消费式删除、向量空间、指纹…)

收敛后 **2309 → 1723 字(-25%)**,保留的全是"模型据此做什么不同的事":

  工具顺序:默认并行 / 不要依赖先后 / 同通道保序 / 写类工具可能串行
  三层记忆:时序里能看最近 / doc_query 把历史事件按原始时间戳插回时序 /
           关系用 memory_recall / 成文知识用 knowledge_search

判断口径写进判据:新加一段提示词前先问"模型会据此做什么不同的事",
答不上来就该进 skill 或工具描述。

## 判据

prompt_memory_test.go 新增 2 条:
- TestSystemPromptHasNoImplementationJargon
  黑名单:ParallelSafe / batchRunnable / 消费式 / DenseCosine / fingerprint /
  向量空间 / 批内降级 / 自激
- TestSystemPromptStaysCompact:上限 2000 字(当前 1723)

变异:把 "ParallelSafe 声明、批内降级" 加回工具顺序段 ⇒ 第一条立刻红。

## 验证

- go build ./... / go vet ./... 干净
- go test ./... -count=1:58 包 0 失败
- make check-client-versions:客户端与内核版本一致
This commit is contained in:
JianFeeeee
2026-10-22 20:49:44 +08:00
parent 6bea130639
commit f256098c9f
204 changed files with 310 additions and 252 deletions

View File

@ -0,0 +1,207 @@
import { connStore } from '../common/ConnStore';
import { registerNavStack, unregisterNavStack } from '../common/NavStackRegistry';
import { ChatAttachment } from '../model/Model';
import { ThemePalette, DARK_PALETTE, LIGHT_PALETTE, WIDE_NAV_BAR_WIDTH, WIDE_MIN_CONTENT } from '../common/Constants';
import { ChatStream } from '../components/ChatStream';
import { ChatComposer } from '../components/ChatComposer';
import { SubPageLayer, markSubPageOpen, subPageParam } from '../components/SubPage';
import { AttachmentDetailContent } from '../components/Attachment';
import { chatStore } from '../common/ChatStore';
/** 二级页面标识:附件(图片/文件)详情 */
const SUB_NONE: string = '';
const SUB_ATTACHMENT: string = 'attachment';
/**
* 聊天页:只做"页面壳"。
*
* 拆分后的分工(拆分前这里是 1962 行的单文件):
* - 消息流状态机(SSE / 历史 / 新消息动画)→ common/ChatStore.ets
* - SSE 事件翻译 → common/ChatSse.ets
* - 发送与中断 → common/ChatSession.ets
* - 消息列表 + 滚动 → components/ChatStream.ets
* - 气泡(含思考卡/工具卡) → components/ChatBubble.ets
* - 悬浮输入区 + 附件选择/上传 → components/ChatComposer.ets
* 本文件保留:导航栈与附件详情二级页、以及"列表底部留白"这个
* 输入区与列表之间的耦合点(所以三个相关标志位用 @Link 与输入区共享)。
*/
@Component
export struct ChatPage {
@StorageProp('themeIsDark') private isDark: boolean = true;
/** 宽屏:左边聊天流(含底部导航栏),右边附件详情 */
@StorageProp('isWideScreen') private isWide: boolean = false;
/** 当前在右栏/二级页展示的附件;未打开时为 undefined */
@State activeAtt: ChatAttachment | undefined = undefined;
@State activeSub: string = SUB_NONE;
/** 以下三项影响列表底部留白,与输入区共享(输入区负责改) */
@State inputMultiLine: boolean = false;
@State attachMenuOpen: boolean = false;
@State pendingName: string = '';
private navStack: NavPathStack = new NavPathStack();
aboutToAppear(): void {
// 把本页导航栈登记给 Index:返回手势/三键返回按当前 Tab 精确派发到这里
registerNavStack(0, this.navStack, () => {
this.activeSub = SUB_NONE;
this.activeAtt = undefined;
});
chatStore.init();
const cur = connStore.getCurrentConnection();
if (cur !== null) {
chatStore.loadHistory();
chatStore.connect();
}
}
aboutToDisappear(): void {
unregisterNavStack(0);
chatStore.disconnect();
}
private palette(): ThemePalette {
return this.isDark ? DARK_PALETTE : LIGHT_PALETTE;
}
/**
* 消息列表底部留白:悬浮输入区(导航栏上方 94 + 输入行 44 ≈ 138)
* 之上再留 ~72 的安全间距,保证最后一条气泡的思考卡/工具卡/附件
* 不被遮挡;加号菜单与待发送附件预览展开时再加高。
*/
private listBottomPad(): number {
let pad: number = 210;
if (this.inputMultiLine) {
pad += 60;
}
if (this.attachMenuOpen) {
pad += 70;
}
if (this.pendingName.length > 0) {
pad += 46;
}
return pad;
}
// ===================== 二级页面:附件详情 =====================
/**
* 打开附件详情。
* WebGUI 点图片是新开浏览器标签、点文件是直接下载;
* 移动端没有"标签页",改成一个二级页面:大图预览 + 元信息 + 保存。
*/
private openAttachment(att: ChatAttachment): void {
this.activeAtt = att;
this.activeSub = SUB_ATTACHMENT;
if (this.isWide && this.navStack.size() > 0) {
this.navStack.replacePathByName(SUB_ATTACHMENT, subPageParam(SUB_ATTACHMENT), false);
} else {
this.navStack.pushPathByName(SUB_ATTACHMENT, subPageParam(SUB_ATTACHMENT), true);
}
}
private closeAttachment(): void {
this.navStack.pop();
this.activeSub = SUB_NONE;
this.activeAtt = undefined;
}
build() {
// 宽屏:左栏聊天流(含底部导航与输入区),右栏附件详情。
// 窄屏:附件详情整屏覆盖,系统返回手势直接作用于 navStack。
Navigation(this.navStack) {
this.ChatBody()
}
.navDestination(this.SubDestination)
.mode(this.isWide ? NavigationMode.Split : NavigationMode.Stack)
.navBarPosition(NavBarPosition.Start)
.navBarWidth(WIDE_NAV_BAR_WIDTH)
.minContentWidth(WIDE_MIN_CONTENT)
.hideTitleBar(true)
.hideToolBar(true)
.hideBackButton(true)
.width('100%')
.height('100%')
.onNavBarStateChange((isVisible: boolean) => {
markSubPageOpen(this.isWide || !isVisible);
})
.onNavigationModeChange((mode: NavigationMode) => {
if (mode === NavigationMode.Split) {
markSubPageOpen(true);
// 右栏不能空白:有附件就展示最近一个,没有则由 SubDestination 显示空态
if (this.navStack.size() === 0) {
const a: ChatAttachment | undefined = chatStore.latestAttachment();
this.activeAtt = a;
this.activeSub = SUB_ATTACHMENT;
this.navStack.pushPathByName(SUB_ATTACHMENT, subPageParam(SUB_ATTACHMENT), false);
}
} else {
this.navStack.clear(false);
this.activeSub = SUB_NONE;
markSubPageOpen(false);
}
})
}
/** 附件详情二级页面 */
@Builder
SubDestination(name: string, param: object) {
NavDestination() {
if (name === SUB_ATTACHMENT) {
SubPageLayer({
title: '附件详情',
tab: 0,
onBack: () => {
this.closeAttachment();
},
}) {
this.AttachmentPane()
}
}
}
.hideTitleBar(true)
.backgroundColor(Color.Transparent)
}
@Builder
AttachmentPane() {
if (this.activeAtt !== undefined) {
AttachmentDetailContent({ att: this.activeAtt })
} else {
// 宽屏右栏空态:聊天里还没有任何图片/文件
Column({ space: 8 }) {
Image($r('app.media.ic_file'))
.width(38)
.height(38)
.fillColor(this.palette().textMuted)
.draggable(false)
Text('选择聊天中的图片或文件查看详情')
.fontSize(13)
.fontColor(this.palette().textMuted)
}
.width('100%')
.padding({ top: 60 })
.alignItems(HorizontalAlign.Center)
}
}
@Builder
ChatBody() {
Stack({ alignContent: Alignment.Bottom }) {
// 层1~1.6:消息流 + 顶栏遮罩 + 底部淡出遮罩
ChatStream({
bottomPad: this.listBottomPad(),
onOpenAttachment: (att: ChatAttachment) => {
this.openAttachment(att);
},
})
// 层2:悬浮输入区(导航栏上方,与导航栏左右平齐,各组件独立不共框)
ChatComposer({
inputMultiLine: $inputMultiLine,
attachMenuOpen: $attachMenuOpen,
pendingName: $pendingName,
})
}
.width('100%')
.height('100%')
}
}

View File

@ -0,0 +1,307 @@
import { deviceBridge } from '../common/DeviceBridge';
import { connStore } from '../common/ConnStore';
import { apiClient } from '../common/ApiClient';
import { handleNavOnScroll } from '../common/NavBarController';
import { registerNavStack, unregisterNavStack } from '../common/NavStackRegistry';
import { DeviceInfo } from '../model/Model';
import { ThemePalette, DARK_PALETTE, LIGHT_PALETTE, WIDE_NAV_BAR_WIDTH,
WIDE_MIN_CONTENT, ANIM_NORMAL, ANIM_ENTER } from '../common/Constants';
import { deviceGatewayUrl } from '../common/DeviceBridgeSession';
import { DeviceRootEntries } from '../components/DeviceRootEntries';
import { DeviceLocalPane, DeviceCapsPane, DeviceGatewayPane, DeviceListPane } from '../components/DevicePanes';
import { PageTopBar, NavFloatOverlay, NavFloatRow, FloatIconButton } from '../components/PageTopBar';
import { markSubPageOpen, subPageParam } from '../components/SubPage';
import { parseOnlineDevices, resolveDeviceId, SUB_CAPS, SUB_GATEWAY, SUB_LIST,
SUB_LOCAL, SUB_NONE } from '../common/DeviceModel';
/**
* 设备页:只做"页面壳"。
*
* 拆分后的分工(拆分前这里是 560 行的单文件):
* - 一级入口列表(本机/通道两组) → components/DeviceRootEntries.ets
* - 四个二级页面内容(本机/能力/通道/列表)→ components/DevicePanes.ets
* - device_id 兜底与在线设备解析 → common/DeviceModel.ets(路由 id 也在那)
* 本文件保留:导航栈与二级页分发、授权开关、toast、设备列表拉取与生命周期。
*/
@Component
export struct DevicePage {
@StorageProp('themeIsDark') private isDark: boolean = true;
@StorageProp('navVisible') private navVisible: boolean = true;
@StorageProp('currentTab') private currentTab: number = 0;
/** 宽屏:左边一级界面(含底部导航栏),右边二级界面 */
@StorageProp('isWideScreen') private isWide: boolean = false;
/** 当前右栏展示的二级页面 id,用于宽屏下高亮左侧入口行 */
@State activeSub: string = SUB_NONE;
@StorageProp('deviceBridgeConnected') private bridgeConnected: boolean = false;
@State bridgeUrl: string = '';
@State bridgeToken: string = '';
@State deviceId: string = '';
@State authorized: boolean = false;
@State devices: DeviceInfo[] = [];
@State loadingDevices: boolean = false;
@State toastMsg: string = '';
@State toastIsError: boolean = false;
/** 二级页面导航栈:系统返回手势/三键返回直接作用于它 */
private navStack: NavPathStack = new NavPathStack();
aboutToAppear(): void {
// id 判定顺序:桥里的 id 优先于持久化的 id,都没有才生成并落盘
this.deviceId = resolveDeviceId(deviceBridge.getDeviceId());
this.authorized = connStore.getDeviceAuth();
// Gateway URL derives from current connection
const cur = connStore.getCurrentConnection();
if (cur !== null) {
this.bridgeUrl = deviceGatewayUrl(cur.url);
this.bridgeToken = cur.apiKey;
}
this.refreshDevices();
// 登记导航栈:返回手势由 Index.onBackPress 按当前 Tab 精确派发过来
registerNavStack(2, this.navStack, () => {
this.activeSub = SUB_NONE;
});
}
aboutToDisappear(): void {
unregisterNavStack(2);
}
private palette(): ThemePalette {
return this.isDark ? DARK_PALETTE : LIGHT_PALETTE;
}
/**
* 打开二级页面。
*
* 窄屏(Stack 模式):push 一层,整屏覆盖,系统侧滑返回可退。
* 宽屏(Split 模式):左栏一级列表常驻,右栏只应有一页,
* 所以用 replace 换页而不是叠栈 —— 否则返回手势要一层层退回去。
*/
private openSub(id: string): void {
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.activeSub = id;
});
if (this.isWide && this.navStack.size() > 0) {
this.navStack.replacePathByName(id, subPageParam(id), false);
} else {
this.navStack.pushPathByName(id, subPageParam(id), true);
}
}
/** 二级页面返回键:宽屏下左栏常驻可见,SubPageLayer 已隐藏返回键 */
private closeSub(): void {
this.navStack.pop();
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.activeSub = SUB_NONE;
});
}
/** Toggle local authorization flag; hello 同步到网关。 */
private toggleAuthorized(on: boolean): void {
this.authorized = on;
try {
connStore.saveDeviceAuth(on);
} catch (e) {
// ignore persist failure
}
deviceBridge.updateAuthorized(on);
this.showToast(on ? '已授权,agent 可下发能力命令' : '已取消授权', false);
}
private showToast(msg: string, isError: boolean): void {
// 颜色标记必须在动画闭包外先落定,否则第一帧用的还是上一条 toast 的配色
this.toastIsError = isError;
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.toastMsg = msg;
});
setTimeout(() => {
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.toastMsg = '';
});
}, 2500);
}
/** 拉取网关在线设备列表(经 webui 反代)。 */
private async refreshDevices(): Promise<void> {
this.loadingDevices = true;
try {
// apiClient 已自动前置 /api/v1,这里只写其后的部分,
// 否则会拼成 /api/v1/api/v1/device/online 并 404。
const resp = await apiClient.get('/device/online');
if (resp.status >= 200 && resp.status < 300) {
const parsed: Record<string, Object> = JSON.parse(resp.body) as Record<string, Object>;
const list: DeviceInfo[] = parseOnlineDevices(parsed);
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.devices = list;
});
} else {
this.devices = [];
}
} catch (e) {
// 网络失败保持静默,不打扰用户
}
this.loadingDevices = false;
}
build() {
// Navigation 提供真实导航栈:系统侧滑返回 / 三键返回都会自动 pop
Navigation(this.navStack) {
Stack({ alignContent: Alignment.Bottom }) {
Column() {
Scroll() {
Column() {
DeviceRootEntries({
activeSub: this.activeSub,
deviceId: this.deviceId,
bridgeConnected: this.bridgeConnected,
bridgeUrl: this.bridgeUrl,
loadingDevices: this.loadingDevices,
deviceCount: this.devices.length,
onOpen: (id: string) => {
this.openSub(id);
},
})
}
.width('100%')
.padding({ left: 16, right: 16, top: 76, bottom: 174 })
}
.width('100%')
.height('100%')
.scrollBar(BarState.Off)
.align(Alignment.Top)
.onDidScroll((xOffset: number, yOffset: number, state: ScrollState) => {
handleNavOnScroll(state);
})
}
.width('100%')
.height('100%')
PageTopBar({ title: '设备' })
// 一级悬浮区:只留刷新(网关状态徽标按用户要求去掉,
// 状态已经在页面内的网关卡片里如实展示)
NavFloatOverlay({ tab: 2 }) {
NavFloatRow() {
FloatIconButton({
icon: $r('app.media.ic_refresh'),
onTap: () => {
this.refreshDevices();
},
})
}
}
this.Toast()
}
.width('100%')
.height('100%')
.backgroundColor(Color.Transparent)
}
.navDestination(this.SubDestination)
// 宽屏(>=600vp)用 Split:navBar(一级列表 + 底部悬浮导航栏)常驻左栏,
// NavDestination(二级页面)渲染在右栏,两栏同时可见。
.mode(this.isWide ? NavigationMode.Split : NavigationMode.Stack)
.navBarPosition(NavBarPosition.Start)
.navBarWidth(WIDE_NAV_BAR_WIDTH)
.minContentWidth(WIDE_MIN_CONTENT)
.hideTitleBar(true)
.hideToolBar(true)
.hideBackButton(true)
.width('100%')
.height('100%')
// Split 模式下 navBar 常驻,此回调不再触发;宽屏一律锁住主 Tab 横滑
.onNavBarStateChange((isVisible: boolean) => {
markSubPageOpen(this.isWide || !isVisible);
})
// 模式初始化与切换:Split 右栏不能空白,自动填入默认二级页面;
// 退回 Stack 时清栈,否则会残留一个整屏覆盖的二级页面。
.onNavigationModeChange((mode: NavigationMode) => {
if (mode === NavigationMode.Split) {
markSubPageOpen(true);
if (this.navStack.size() === 0) {
this.openSub(SUB_LOCAL);
}
} else {
this.navStack.clear(false);
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.activeSub = SUB_NONE;
});
markSubPageOpen(false);
}
})
}
/**
* 二级页面路由表。
* 每个面板自带 SubPageLayer 外壳(标题/所属 Tab/返回/刷新),这里只做分发。
*/
@Builder
SubDestination(name: string, param: object) {
NavDestination() {
if (name === SUB_LOCAL) {
DeviceLocalPane({
deviceId: this.deviceId,
authorized: this.authorized,
onBack: () => {
this.closeSub();
},
onToggleAuth: (on: boolean) => {
this.toggleAuthorized(on);
},
})
} else if (name === SUB_CAPS) {
DeviceCapsPane({
onBack: () => {
this.closeSub();
},
})
} else if (name === SUB_GATEWAY) {
DeviceGatewayPane({
bridgeUrl: this.bridgeUrl,
bridgeToken: this.bridgeToken,
bridgeConnected: this.bridgeConnected,
onBack: () => {
this.closeSub();
},
onRefresh: () => {
this.refreshDevices();
},
})
} else if (name === SUB_LIST) {
DeviceListPane({
devices: this.devices,
onBack: () => {
this.closeSub();
},
onRefresh: () => {
this.refreshDevices();
},
})
}
}
.hideTitleBar(true)
.backgroundColor(Color.Transparent)
}
@Builder
Toast() {
if (this.toastMsg.length > 0) {
Row() {
Text(this.toastMsg)
.fontSize(13)
.fontColor(this.toastIsError ? this.palette().toastErrorText : this.palette().toastText)
.padding({ left: 20, right: 20, top: 10, bottom: 10 })
.borderRadius(RADIUS_MD)
.backgroundColor(this.toastIsError ? this.palette().toastErrorBg : this.palette().toastBg)
}
.width('100%')
.justifyContent(FlexAlign.End)
.padding({ right: 20 })
.margin({ bottom: 166 })
.transition(TransitionEffect.OPACITY
.combine(TransitionEffect.translate({ y: 12 }))
.animation({ duration: ANIM_NORMAL, curve: Curve.EaseOut }))
}
}
}
const RADIUS_MD: number = 10;

View File

@ -0,0 +1,421 @@
import { ChatPage } from './ChatPage';
import { PluginsPage } from './PluginsPage';
import { DevicePage } from './DevicePage';
import { SettingsPage } from './SettingsPage';
import { connStore } from '../common/ConnStore';
import { apiClient } from '../common/ApiClient';
import { navBar } from '../common/NavBarController';
import { handleBackPress } from '../common/NavStackRegistry';
import { ConnectionConfig } from '../model/Model';
import { ThemePalette, DARK_PALETTE, LIGHT_PALETTE, WIDE_MIN_WIDTH, WIDE_NAV_BAR_WIDTH, K_HAS_CONN, K_REQUESTED_TAB, K_SETTINGS_SUB } from '../common/Constants';
import { ANIM_NORMAL, ANIM_SLOW } from '../common/Constants';
import { MotionBase } from '../components/MotionBase';
import { GradientBackground } from '../components/GradientBackground';
import { ScreensuePage } from '../components/ScreensuePage';
import { registerScreensueHandler } from '../common/BridgeRouter';
import { markForegroundBridgeUIReady } from '../common/DeviceBridgeSession';
import { snapshotComponentId } from '../common/BridgeCaps';
import { ScreensuePayload } from '../common/ScreensueHtml';
import { window, display } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
interface TabItem {
icon: Resource;
label: string;
pageId: string;
}
/**
* 底部导航单项:矢量图标 + 文字。
* active 必须 @Prop 才能在父组件 currentTab 变化时刷新高亮。
*/
@Component
export struct RailTab {
icon: Resource = $r('app.media.ic_tab_chat');
@Prop label: string = '';
@Prop active: boolean = false;
@Prop accent: string = '';
@Prop muted: string = '';
build() {
// 底部导航按压反馈:交给 MotionBase 统一(flexWeight 由外层调用点的
// .layoutWeight(1) 负责,这里内部只需撑满自己那一格)。
MotionBase({ pressEnabled: true }) {
Column({ space: 3 }) {
Image(this.icon)
.width(22)
.height(22)
.fillColor(this.active ? this.accent : this.muted)
// 选中态的颜色迁移必须写在子节点上:父容器的 .animation()
// 只驱动它自己的属性,不会下传给 Image / Text。
.animation({ duration: ANIM_NORMAL, curve: Curve.EaseOut })
.draggable(false)
Text(this.label)
.fontSize(10)
// fontWeight 不可插值,切换时仍是跳变,只对颜色做过渡
.fontWeight(this.active ? FontWeight.Medium : FontWeight.Normal)
.fontColor(this.active ? this.accent : this.muted)
.animation({ duration: ANIM_NORMAL, curve: Curve.EaseOut })
.maxLines(1)
}
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.height(48)
}
}
}
@Entry
@Component
struct Index {
@Watch('onTabChanged') @State currentTab: number = 0;
@StorageProp('navVisible') private navVisible: boolean = true;
/** 二级页面打开时锁住 Swiper 横滑,避免误切换主 Tab */
@StorageProp('subPageOpen') private subPageOpen: boolean = false;
/** 宽屏(>=600vp):一级界面在左、二级界面在右,导航栏跟随左侧一级界面 */
@StorageProp('isWideScreen') private isWide: boolean = false;
@State screensueVisible: boolean = false;
@State screensueText: string = '';
@State screensueCountdown: number = 0;
/** 状态栏避让高度(vp),从窗口 avoid area 动态获取;默认 44 兜底 */
@State topInset: number = 44;
/** 底部手势条高度(vp) */
@State bottomGesture: number = 16;
@StorageProp('themeIsDark') @Watch('onThemeChanged') private isDark: boolean = true;
/** 外部请求切换主 Tab(未连接时聊天空态的“去设置连接”用) */
@StorageProp(K_REQUESTED_TAB) @Watch('onRequestedTab') private requestedTab: number = -1;
private swiper: SwiperController = new SwiperController();
private screensueTimer: number = -1;
private snapshotBuilder: CustomBuilder = (): void => { }; // 由 @Builder 传入的实际锚点
// 「状态」Tab 已删除:运行状态并入设置页(顶部摘要卡 + 二级明细页),
// 底部导航只保留四项,胶囊内每项更宽、点按更好命中。
private tabs: TabItem[] = [
{ icon: $r('app.media.ic_tab_chat'), label: '聊天', pageId: 'chat' },
{ icon: $r('app.media.ic_tab_plugins'), label: '插件', pageId: 'plugins' },
{ icon: $r('app.media.ic_tab_devices'), label: '设备', pageId: 'devices' },
{ icon: $r('app.media.ic_tab_settings'), label: '设置', pageId: 'settings' },
];
aboutToAppear(): void {
const cur: ConnectionConfig | null = connStore.getCurrentConnection();
if (cur !== null) {
apiClient.setConnection(cur);
}
// 后端连接状态广播:聊天空态根据它决定是否显示“去设置连接”。
// Index.aboutToAppear 在 EntryAbility 等 connStore.init 之后才跑,
// 所以此处读到的连接状态就是真实的启动态。
AppStorage.setOrCreate<boolean>(K_HAS_CONN, apiClient.hasConnection());
AppStorage.setOrCreate<number>(K_REQUESTED_TAB, -1);
AppStorage.setOrCreate<string>(K_SETTINGS_SUB, '');
// 种子化自定义背景图状态到 AppStorage,GradientBackground 响应读取
const st = connStore.getSettings();
AppStorage.setOrCreate<string>('bgImage', st.bgImage ?? '');
AppStorage.setOrCreate<number>('bgOpacity', st.bgOpacity ?? 0.25);
AppStorage.setOrCreate<boolean>('navVisible', true);
AppStorage.setOrCreate<boolean>('subPageOpen', false);
AppStorage.setOrCreate<boolean>('isWideScreen', false);
// 启动时按当前主题刷新一次系统栏(EntryAbility 已设过,这里兜底对齐)
this.syncSystemBar();
// 动态读取状态栏/导航栏避让区,实现真正的沉浸式布局(替换硬编码 top:44)
this.resolveSafeArea();
// 根 UI 只负责 screensue 呈现;命令路由由前台全局设备桥安装。
registerScreensueHandler((payload: ScreensuePayload) => {
this.showScreensue(payload);
});
markForegroundBridgeUIReady(getContext(this) as common.UIAbilityContext);
}
/** agent 下发的 screensue 内容展示(窄屏整页、宽屏右栏;0=常驻)。 */
private showScreensue(payload: ScreensuePayload): void {
this.screensueText = payload.content;
this.screensueCountdown = payload.duration;
this.screensueVisible = true;
if (this.screensueTimer >= 0) {
clearInterval(this.screensueTimer);
this.screensueTimer = -1;
}
if (payload.duration > 0) {
this.screensueTimer = setInterval(() => {
if (this.screensueCountdown <= 1) {
clearInterval(this.screensueTimer);
this.screensueTimer = -1;
this.screensueVisible = false;
} else {
this.screensueCountdown = this.screensueCountdown - 1;
}
}, 1000);
}
}
private closeScreensue(): void {
if (this.screensueTimer >= 0) {
clearInterval(this.screensueTimer);
this.screensueTimer = -1;
}
this.screensueVisible = false;
}
/** 主题翻转时同步系统栏前景/背景色,避免浅色页面配黑状态栏。 */
private onThemeChanged(): void {
this.syncSystemBar();
}
/** 通过窗口 avoid area 计算状态栏与底部手势区高度(vp),失败时保留默认值。 */
private resolveSafeArea(): void {
try {
const ctx = getContext(this) as common.UIAbilityContext;
window.getLastWindow(ctx).then((win: window.Window) => {
const prop = win.getWindowProperties();
const isLayoutFull = prop.isLayoutFullScreen === true;
if (!isLayoutFull) {
return; // 非全屏模式下系统自动避让
}
const density = display.getDefaultDisplaySync().densityPixels > 0
? display.getDefaultDisplaySync().densityPixels : 3;
const topArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
const bottomArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
if (topArea.topRect.height > 0) {
this.topInset = Math.ceil(topArea.topRect.height / density);
}
// 底部手势条:有值时取其高度的一半作为悬浮导航的下边距基准,最小 8 最大 24
if (bottomArea.bottomRect.height > 0) {
const h: number = Math.ceil(bottomArea.bottomRect.height / density);
this.bottomGesture = Math.min(24, Math.max(8, h));
} else {
this.bottomGesture = 16;
}
}).catch(() => {
// ignore, keep defaults
});
} catch (e) {
// ignore
}
AppStorage.set<number>('currentTab', 0);
}
private onTabChanged(): void {
AppStorage.set<number>('currentTab', this.currentTab);
}
/**
* 响应外部切 Tab 请求(聊天空态的“去设置连接”)。
*
* 为什么不能直接改 AppStorage 的 currentTab:Index 的 currentTab 是
* @State,Swiper.index() 只认它;外部写 AppStorage 不会驱动 Swiper。
* 所以用独立请求键 + @Watch 把请求转成自己的状态变更。
*/
private onRequestedTab(): void {
const t: number = this.requestedTab;
AppStorage.set<number>(K_REQUESTED_TAB, -1);
if (t < 0 || t >= this.tabs.length) {
return;
}
this.currentTab = t;
navBar.setVisible(true);
}
private syncSystemBar(): void {
const dark: boolean = this.isDark;
const bg: string = dark ? '#000000' : '#F1F3F5';
const fg: string = dark ? '#FFFFFF' : '#191919';
try {
window.getLastWindow(getContext(this) as common.UIAbilityContext).then((win: window.Window) => {
win.setWindowSystemBarProperties({
statusBarColor: bg,
statusBarContentColor: fg,
navigationBarColor: bg,
});
win.setWindowBackgroundColor(bg);
}).catch(() => {
// ignore
});
} catch (e) {
// ignore
}
}
private palette(): ThemePalette {
// 引用 this.isDark 建立响应式依赖:主题切换时整个组件树重渲染
return this.isDark ? DARK_PALETTE : LIGHT_PALETTE;
}
/** 宽屏判定:窗口宽度 >= 600vp(与 Navigation Auto 模式的分栏阈值一致) */
private updateWideScreen(w: number): void {
const wide: boolean = w >= WIDE_MIN_WIDTH;
if (wide !== this.isWide) {
AppStorage.set<boolean>('isWideScreen', wide);
}
}
/**
* 统一的返回处理:把返回事件精确派发给【当前 Tab】的那个 Navigation 栈。
*
* 四个页面各自持有 Navigation(宽屏需要"左一级右二级"),它们在 Swiper 里
* 同时存活,系统返回落到哪个栈并不确定 —— 这就是"有的页面无法使用返回手势"
* 的根因。这里按 currentTab 显式选栈,行为对所有页面一致。
*/
onBackPress(): boolean {
if (this.screensueVisible) {
this.closeScreensue();
return true;
}
return handleBackPress(this.currentTab, this.isWide);
}
build() {
// alignContent Bottom:悬浮导航停靠底部,而不是被 Stack 居中。
// 导航胶囊用左右 6% padding 保持"宽度占 88% 居中"的原样视觉;
// 宽屏下胶囊自然被限制在左侧一级界面栏内,不会横跨二级界面。
Stack({ alignContent: Alignment.Bottom }) {
// 渐变氛围背景
GradientBackground()
// 页面内容:Swiper 支持左右滑动切换;$$ 双向同步索引
Swiper(this.swiper) {
ChatPage()
PluginsPage()
DevicePage()
SettingsPage()
}
.index(this.currentTab)
.indicator(false)
.loop(false)
.duration(300)
.curve(Curve.FastOutSlowIn)
.vertical(false)
.cachedCount(2)
.disableSwipe(this.subPageOpen)
.onChange((idx: number) => {
this.currentTab = idx;
navBar.setVisible(true);
})
.width('100%')
.height('100%')
// top 让出状态栏;bottom:所有页面统一为0,导航栏浮在内容之上
.padding({
top: this.topInset,
bottom: 0
})
// 悬浮气态玻璃底部导航(三层:半透明底 -> 高光渐变 -> 内容)
// 外层 Row 负责水平定位:窄屏居中;宽屏靠左,只落在一级界面栏范围内。
Row() {
Stack() {
// 层1:玻璃底 —— 半透明背景(无 backdropBlur 以避免矩形模糊伪影)
Column()
.width('100%')
.height('100%')
.backgroundColor(this.palette().navBarBg)
// 层2:玻璃高光渐变,模拟光从上方照射的质感
Row()
.width('100%')
.height('100%')
.linearGradient({
direction: GradientDirection.Top,
colors: [
[this.palette().navBarGradientStart, 0.0],
[this.palette().navBarGradientEnd, 1.0],
],
})
// 层3:导航项
Row({ space: 2 }) {
ForEach(this.tabs, (tab: TabItem, index: number) => {
RailTab({
icon: tab.icon,
label: tab.label,
active: this.currentTab === index,
accent: this.palette().accent,
muted: this.palette().textMuted,
})
.layoutWeight(1)
.onClick(() => {
this.currentTab = index;
navBar.setVisible(true);
})
}, (item: TabItem, index: number) => item.pageId + index.toString())
}
.width('100%')
.height(62)
.padding({ left: 14, right: 14 })
.alignItems(VerticalAlign.Center)
}
// 宽屏:胶囊宽度锁在左侧一级界面栏内(左右各留 24vp 余量)
.width(this.isWide ? WIDE_NAV_BAR_WIDTH - 48 : '88%')
.height(62)
.borderRadius(28)
.clip(true)
.border({
width: { left: 1, top: 1, right: 1, bottom: 1 },
color: this.palette().navBarBorder,
})
.shadow({
radius: 24,
color: this.palette().shadow,
offsetY: 8,
})
}
.width('100%')
.height(62)
.padding({ left: this.isWide ? 24 : 0 })
.justifyContent(this.isWide ? FlexAlign.Start : FlexAlign.Center)
.margin({ bottom: this.bottomGesture + 6 })
// 所有页面滑动时隐藏导航栏
.translate({ y: !this.navVisible ? 130 : 0 })
.opacity(!this.navVisible ? 0 : 1)
.animation({ duration: ANIM_SLOW, curve: Curve.EaseOut })
// 导航栏本身不吃触摸空白区,避免遮住下层内容点击
.hitTestBehavior(HitTestMode.Transparent)
// screensue 是前台内容页:窄屏覆盖整页;宽屏仅覆盖右侧内容栏,
// 左侧一级页面与主导航保持可见、可操作。
if (this.screensueVisible) {
if (this.isWide) {
Row() {
Column()
.width(WIDE_NAV_BAR_WIDTH)
.height('100%')
.hitTestBehavior(HitTestMode.None)
ScreensuePage({
pushedText: this.screensueText,
countdown: this.screensueCountdown,
onClose: () => {
this.closeScreensue();
},
})
.layoutWeight(1)
.height('100%')
.padding({ top: this.topInset })
}
.width('100%')
.height('100%')
.hitTestBehavior(HitTestMode.Transparent)
} else {
ScreensuePage({
pushedText: this.screensueText,
countdown: this.screensueCountdown,
onClose: () => {
this.closeScreensue();
},
})
.width('100%')
.height('100%')
.padding({ top: this.topInset })
}
}
}
.width('100%')
.height('100%')
.id(snapshotComponentId())
// 实时跟随窗口宽度:平板旋转、折叠展开、分屏、自由窗口拖拽都会回调,
// 比启动时查一次 display 更可靠(不会漏掉运行中的尺寸变化)。
.onAreaChange((oldValue: Area, newValue: Area) => {
this.updateWideScreen(newValue.width as number);
})
}
}

View File

@ -0,0 +1,374 @@
import { apiClient } from '../common/ApiClient';
import { userMessage } from '../common/UserError';
import { handleNavOnScroll } from '../common/NavBarController';
import { registerNavStack, unregisterNavStack } from '../common/NavStackRegistry';
import { PluginRow, PluginDetail, emptyPluginDetail } from '../model/Model';
import { ThemePalette, DARK_PALETTE, LIGHT_PALETTE, WIDE_NAV_BAR_WIDTH, WIDE_MIN_CONTENT } from '../common/Constants';
import { ANIM_NORMAL, ANIM_ENTER } from '../common/Constants';
import { PageTopBar, NavFloatOverlay, NavFloatRow, FloatIconButton } from '../components/PageTopBar';
import { SubPageLayer, markSubPageOpen, subPageParam } from '../components/SubPage';
import { PluginDetailPane } from '../components/PluginDetailPane';
import { PluginListView } from '../components/PluginListView';
import { PluginInstallForm } from '../components/PluginsOverlays';
import { ToastBar } from '../components/ToastBar';
import { fetchPluginRows, fetchPluginDetail } from '../common/PluginApi';
/** 二级页面标识:插件详情 */
const SUB_NONE: string = '';
const SUB_DETAIL: string = 'detail';
interface InstallBody {
url: string;
}
@Component
export struct PluginsPage {
@StorageProp('themeIsDark') private isDark: boolean = true;
@StorageProp('navVisible') private navVisible: boolean = true;
@StorageProp('currentTab') private currentTab: number = 0;
/** 宽屏:左边插件列表(含底部导航栏),右边插件详情 */
@StorageProp('isWideScreen') private isWide: boolean = false;
@State plugins: PluginRow[] = [];
@State loading: boolean = false;
@State showInstallForm: boolean = false;
@State installUrl: string = '';
@State toastMsg: string = '';
@State toastIsError: boolean = false;
/** 当前查看详情的插件名,用于宽屏下高亮左侧列表项 */
@State activeName: string = '';
/** 详情页数据(GET /plugins/{name}) */
@State detail: PluginDetail = emptyPluginDetail();
@State detailLoading: boolean = false;
@State detailError: string = '';
/** 二级页面导航栈:系统返回手势/三键返回直接作用于它 */
private navStack: NavPathStack = new NavPathStack();
aboutToAppear(): void {
// 登记导航栈:返回手势由 Index.onBackPress 按当前 Tab 精确派发过来
registerNavStack(1, this.navStack, () => {
this.activeName = '';
});
this.loadPlugins();
}
aboutToDisappear(): void {
unregisterNavStack(1);
}
private palette(): ThemePalette {
// 引用 this.isDark 建立响应式依赖:主题切换时整个组件树重渲染
return this.isDark ? DARK_PALETTE : LIGHT_PALETTE;
}
/** 取数口径见 common/PluginApi.ets;这里只负责把结果落到 @State。 */
private async loadPlugins(): Promise<void> {
if (!apiClient.hasConnection()) {
return;
}
this.loading = true;
try {
const rows: PluginRow[] = await fetchPluginRows();
// 列表整体重建(ForEach key 含 loaded/disabled,启停会整行重挂载):
// 放进 animateTo 让新旧行走 transition 交叉淡入,而不是硬切一帧。
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.plugins = rows;
});
} catch (e) {
this.showToast(userMessage('plugins.load', e), true);
}
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.loading = false;
});
}
private async togglePlugin(plugin: PluginRow): Promise<void> {
const name: string = plugin.name;
const action: string = plugin.disabled ? 'enable' : 'disable';
try {
await apiClient.post('/plugins/' + name + '/' + action, null);
this.showToast('已' + (plugin.disabled ? '启用' : '禁用') + '插件: ' + name, false);
this.loadPlugins();
} catch (e) {
this.showToast(userMessage('plugins.toggle', e), true);
}
}
private async removePlugin(plugin: PluginRow): Promise<void> {
const name: string = plugin.name;
try {
await apiClient.request('/plugins/' + name, 'DELETE', '', 8000);
this.showToast('已卸载插件: ' + name, false);
this.loadPlugins();
} catch (e) {
this.showToast(userMessage('plugins.remove', e), true);
}
}
private async installPlugin(): Promise<void> {
const url: string = this.installUrl.trim();
if (url.length === 0) {
return;
}
try {
const bodyObj: InstallBody = { url: url };
// 后端没有 /plugins/install 这个路由:安装就是 POST /plugins,body 带 url。
await apiClient.post('/plugins', bodyObj);
this.showToast('安装请求已发送', false);
this.installUrl = '';
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.showInstallForm = false;
});
this.loadPlugins();
} catch (e) {
this.showToast(userMessage('plugins.install', e), true);
}
}
// ===================== 二级页面:插件详情 =====================
/**
* 打开插件详情。
*
* 窄屏(Stack):push 一层整屏覆盖,系统侧滑返回可退。
* 宽屏(Split):左栏列表常驻,右栏换页而不叠栈。
*/
private openDetail(name: string): void {
this.activeName = name;
this.loadDetail(name);
if (this.isWide && this.navStack.size() > 0) {
this.navStack.replacePathByName(SUB_DETAIL, subPageParam(SUB_DETAIL), false);
} else {
this.navStack.pushPathByName(SUB_DETAIL, subPageParam(SUB_DETAIL), true);
}
}
private closeDetail(): void {
this.navStack.pop();
this.activeName = '';
}
/**
* 详情数据落地。
* 内置插件不在 /plugins 里,取不到详情时退回用列表已有的信息。
*/
private async loadDetail(name: string): Promise<void> {
this.detailLoading = true;
this.detailError = '';
try {
const d: PluginDetail = await fetchPluginDetail(name);
// 详情字段一次性落地:条件卡片在 animateTo 帧内挂载,V1 给它们默认透明度过渡
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.detail = d;
});
} catch (e) {
// 内置插件没有清单,属于预期情况,不当成错误刷红
const row: PluginRow | null = this.findRow(name);
const d: PluginDetail = emptyPluginDetail();
d.name = name;
if (row !== null) {
d.version = row.version ?? '';
d.description = row.description ?? '';
}
const errText: string = (row !== null && row.external) ? userMessage('plugins.detail', e) : '';
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.detail = d;
this.detailError = errText;
});
}
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.detailLoading = false;
});
}
private findRow(name: string): PluginRow | null {
for (let i = 0; i < this.plugins.length; i++) {
if (this.plugins[i].name === name) {
return this.plugins[i];
}
}
return null;
}
/** 详情页正在展示的那一行(供二级页面里的操作按钮使用) */
private activeRow(): PluginRow | null {
return this.findRow(this.activeName);
}
private async reloadPlugins(): Promise<void> {
try {
await apiClient.post('/plugins/reload', null);
this.showToast('插件已重载', false);
this.loadPlugins();
} catch (e) {
this.showToast(userMessage('plugins.reload', e), true);
}
}
private showToast(msg: string, isError: boolean): void {
// 颜色标志必须在 animateTo 闭包之外先落地,否则第一帧配色是上一次的
this.toastIsError = isError;
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.toastMsg = msg;
});
setTimeout(() => {
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.toastMsg = '';
});
}, 2500);
}
build() {
// 宽屏(>=600vp)走 Split:navBar(左栏 = 插件列表 + 底部导航栏)常驻,
// NavDestination(右栏 = 插件详情)与之并列;窄屏则是整屏覆盖的二级页面。
Navigation(this.navStack) {
Stack({ alignContent: Alignment.Bottom }) {
Column() {
Scroll() {
Column() {
PluginListView({
plugins: this.plugins,
busy: this.loading,
activeName: this.activeName,
hasConn: apiClient.hasConnection(),
onSelect: (name: string) => {
this.openDetail(name);
},
})
}
.width('100%')
.padding({ left: 16, right: 16, top: 76, bottom: 174 })
}
.width('100%')
.height('100%')
.scrollBar(BarState.Off)
.align(Alignment.Top)
.onDidScroll((xOffset: number, yOffset: number, state: ScrollState) => {
handleNavOnScroll(state);
})
}
.width('100%')
.height('100%')
// 顶栏遮罩(自身撑满并顶部对齐,全链路 hitTest None,触摸完全穿透到滚动区)
PageTopBar({ title: '插件' })
// 悬浮操作区:安装(悬浮主按钮)+ 重载。
// 安装表单以悬浮卡形式浮在按钮上方,不再占用列表顶部一行。
NavFloatOverlay({ tab: 1 }) {
if (this.showInstallForm) {
PluginInstallForm({
url: this.installUrl,
onUrlChange: (v: string) => {
this.installUrl = v;
},
onInstall: () => {
this.installPlugin();
},
})
}
NavFloatRow() {
FloatIconButton({
icon: $r('app.media.ic_reload'),
onTap: () => {
this.reloadPlugins();
},
})
Button() {
Image($r('app.media.ic_plus'))
.width(20)
.height(20)
.fillColor(Color.White)
.rotate({ angle: this.showInstallForm ? 45 : 0 })
.animation({ duration: ANIM_NORMAL, curve: Curve.EaseOut })
}
.width(50)
.height(50)
.type(ButtonType.Circle)
.backgroundColor(this.palette().accent)
.shadow({ radius: 24, color: this.palette().shadow, offsetY: 8 })
.onClick(() => {
this.getUIContext().animateTo({ duration: ANIM_ENTER, curve: Curve.EaseOut }, () => {
this.showInstallForm = !this.showInstallForm;
});
})
}
}
ToastBar({ msg: this.toastMsg, isError: this.toastIsError, bordered: true })
}
.width('100%')
.height('100%')
.backgroundColor(Color.Transparent)
}
.navDestination(this.SubDestination)
.mode(this.isWide ? NavigationMode.Split : NavigationMode.Stack)
.navBarPosition(NavBarPosition.Start)
.navBarWidth(WIDE_NAV_BAR_WIDTH)
.minContentWidth(WIDE_MIN_CONTENT)
.hideTitleBar(true)
.hideToolBar(true)
.hideBackButton(true)
.width('100%')
.height('100%')
// Split 模式下 navBar 常驻,此回调不再触发;宽屏一律锁住主 Tab 横滑
.onNavBarStateChange((isVisible: boolean) => {
markSubPageOpen(this.isWide || !isVisible);
})
// 模式初始化与切换:Split 右栏不能空白,自动选中第一个插件;
// 退回 Stack 时清栈,否则会残留一个整屏覆盖的详情页。
.onNavigationModeChange((mode: NavigationMode) => {
if (mode === NavigationMode.Split) {
markSubPageOpen(true);
if (this.navStack.size() === 0 && this.plugins.length > 0) {
this.openDetail(this.plugins[0].name);
}
} else {
this.navStack.clear(false);
this.activeName = '';
markSubPageOpen(false);
}
})
}
/** 二级页面路由表:插件详情 */
@Builder
SubDestination(name: string, param: object) {
NavDestination() {
if (name === SUB_DETAIL) {
SubPageLayer({
title: this.activeName.length > 0 ? this.activeName : '插件详情',
tab: 1,
onBack: () => {
this.closeDetail();
},
showRefresh: true,
onRefresh: () => {
this.loadDetail(this.activeName);
},
}) {
PluginDetailPane({
detail: this.detail,
activeName: this.activeName,
busy: this.detailLoading,
errorText: this.detailError,
row: this.activeRow() ?? undefined,
onToggle: () => {
const r: PluginRow | null = this.activeRow();
if (r !== null) {
this.togglePlugin(r);
}
},
onRemove: () => {
const r: PluginRow | null = this.activeRow();
if (r !== null) {
this.removePlugin(r);
}
},
})
}
}
}
.hideTitleBar(true)
.backgroundColor(Color.Transparent)
}
}

View File

@ -0,0 +1,434 @@
import { apiClient } from '../common/ApiClient';
import { userMessage, noConnectionMessage } from '../common/UserError';
import { connStore } from '../common/ConnStore';
import { registerNavStack, unregisterNavStack } from '../common/NavStackRegistry';
import { ConnectionConfig, AppSettings } from '../model/Model';
import { ThemePalette, DARK_PALETTE, LIGHT_PALETTE, WIDE_NAV_BAR_WIDTH, WIDE_MIN_CONTENT, K_HAS_CONN, K_SETTINGS_SUB } from '../common/Constants';
import { RADIUS_MD, ANIM_NORMAL, ANIM_ENTER } from '../common/Constants';
import { SubPageLayer, markSubPageOpen, subPageParam } from '../components/SubPage';
import { StatusDetailContent } from '../components/StatusCards';
import { SettingsHome } from '../components/SettingsHome';
import { ConnectionsPane } from '../components/ConnectionsPane';
import { AppearancePane } from '../components/AppearancePane';
import { BackendSectionsPane, SectionEntriesPane } from '../components/BackendSettingsPane';
import {
SettingEntry, SettingsSection, SettingMetaRaw, ParsedSettings, SectionStats,
parseSettingsPayload, buildSections, pickInitialSection, buildEntries, withEntryMarked,
SUB_NONE, SUB_STATUS, SUB_CONNECTIONS, SUB_APPEARANCE, SUB_BACKEND, SUB_SECTION,
} from '../common/SettingsModel';
import { statusStore } from '../common/StatusStore';
import { stageTrail } from '../common/StageTrail';
interface SaveSettingBody {
key: string;
value: string;
}
@Component
export struct SettingsPage {
@StorageProp('themeIsDark') private isDark: boolean = true;
@StorageProp('navVisible') private navVisible: boolean = true;
@StorageProp('currentTab') private currentTab: number = 0;
/** 宽屏:左边一级界面(含底部导航栏),右边二级界面 */
@StorageProp('isWideScreen') private isWide: boolean = false;
/** 当前右栏展示的二级页面 id,用于宽屏下高亮左侧入口行 */
@State activeSub: string = SUB_NONE;
@State connections: ConnectionConfig[] = [];
@State currentId: string = '';
@State themeMode: string = 'system';
@State lang: string = 'zh';
@State bgImage: string = '';
@State bgOpacity: number = 0.25;
/** 二级页面导航栈:系统返回手势/三键返回直接作用于它 */
private navStack: NavPathStack = new NavPathStack();
/** 未连接时是否已自动弹过连接页——避免用户关掉后又被 onNavigationModeChange 弹回来 */
private autoOpenedConn: boolean = false;
/** 外部请求打开某个二级页(聊天空态的“去设置连接”用) */
@StorageProp(K_SETTINGS_SUB) @Watch('onSubRequest') private subRequest: string = '';
// ===== backend key/value editor state =====
@State sections: SettingsSection[] = [];
/** plugin.* 配置项总数与涉及的插件个数(只用于在设置里给出去向提示) */
@State pluginKeyCount: number = 0;
@State pluginConfigCount: number = 0;
@State activeSection: string = 'core';
@State entries: SettingEntry[] = [];
@State loadingSettings: boolean = false;
@State settingsError: string = '';
@State savingCount: number = 0;
private metaStore: Record<string, SettingMetaRaw> = {};
private valuesStore: Record<string, string> = {};
@State toastMsg: string = '';
@State toastIsError: boolean = false;
aboutToAppear(): void {
// 登记导航栈:返回手势由 Index.onBackPress 按当前 Tab 精确派发过来
registerNavStack(3, this.navStack, () => {
this.activeSub = SUB_NONE;
});
const s: AppSettings = connStore.getSettings();
this.themeMode = s.theme.length > 0 ? s.theme : 'system';
this.lang = s.lang;
this.bgImage = s.bgImage ?? '';
this.bgOpacity = s.bgOpacity ?? 0.25;
this.loadConnections();
this.loadBackendSettings();
// 状态 Tab 已删除,运行状态并入本页:顶部摘要卡 + 二级明细页
statusStore.init();
// 阶段轨迹由 SSE 喂入,与状态轮询是两条独立的数据源
stageTrail.init();
statusStore.refresh();
}
aboutToDisappear(): void {
unregisterNavStack(3);
}
private loadConnections(): void {
this.connections = connStore.getConnections();
const cur = connStore.getCurrentConnection();
this.currentId = cur !== null ? cur.id : '';
// 广播连接状态:聊天空态据此显示“去设置连接”
AppStorage.setOrCreate<boolean>(K_HAS_CONN, apiClient.hasConnection());
// 可能从聊天空态带着“打开连接页”的请求进来(本页尚未挂载时请求已写入)
const pending: string = AppStorage.get<string>(K_SETTINGS_SUB) ?? '';
if (pending.length > 0) {
AppStorage.set<string>(K_SETTINGS_SUB, '');
this.autoOpenedConn = true;
setTimeout(() => {
this.openSub(pending);
}, 0);
}
}
/**
* 宽屏右栏默认该展示哪一页:没连上就把“后端连接”给出来。
*
* 为什么不能只靠一级入口行:入口行在列表里,用户很容易略过;
* 而“未连接”恰恰是最需要直接看到连接表单的时刻。窄屏同理,
* 在 onNavigationModeChange(Stack) 里会把连接页直接推到面前。
*/
private initialSub(): string {
return apiClient.hasConnection() ? SUB_STATUS : SUB_CONNECTIONS;
}
/** 外部请求打开二级页(“去设置连接”) */
private onSubRequest(): void {
const id: string = this.subRequest;
if (id.length === 0) {
return;
}
AppStorage.set<string>(K_SETTINGS_SUB, '');
this.autoOpenedConn = true;
this.openSub(id);
}
private palette(): ThemePalette {
// 引用 this.isDark 建立响应式依赖:主题切换时整个组件树重渲染
return this.isDark ? DARK_PALETTE : LIGHT_PALETTE;
}
// ===================== 二级页面导航 =====================
/**
* 打开二级页面。
*
* 窄屏(Stack 模式):push 一层,整屏覆盖,系统侧滑返回可退。
* 宽屏(Split 模式):左栏一级列表常驻,右栏只应有一页,
* 所以用 replace 换页而不是叠栈 —— 否则返回手势要一层层退回去。
*/
private openSub(id: string): void {
this.activeSub = id;
if (this.isWide && this.navStack.size() > 0) {
this.navStack.replacePathByName(id, subPageParam(id), false);
} else {
this.navStack.pushPathByName(id, subPageParam(id), true);
}
}
/** 二级页面返回键:宽屏下左栏常驻可见,SubPageLayer 已隐藏返回键 */
private closeSub(): void {
this.navStack.pop();
this.activeSub = SUB_NONE;
}
private currentConnName(): string {
for (let i = 0; i < this.connections.length; i++) {
if (this.connections[i].id === this.currentId) {
return this.connections[i].name;
}
}
return '未配置';
}
private themeLabel(): string {
if (this.themeMode === 'dark') {
return '深色';
}
if (this.themeMode === 'light') {
return '浅色';
}
return '跟随系统';
}
/** 核心 + 其他(不含 plugin.*,那些在插件详情页里) */
private coreKeyCount(): number {
let n: number = 0;
for (let i = 0; i < this.sections.length; i++) {
n = n + this.sections[i].count;
}
return n;
}
// ===================== backend kv editor =====================
private async loadBackendSettings(): Promise<void> {
if (!apiClient.hasConnection()) {
this.settingsError = noConnectionMessage();
return;
}
this.loadingSettings = true;
this.settingsError = '';
try {
const resp = await apiClient.getWithTimeout('/settings', 15000);
const parsed: ParsedSettings = parseSettingsPayload(resp.body);
this.metaStore = parsed.meta;
this.valuesStore = parsed.values;
const stats: SectionStats = buildSections(this.valuesStore, this.metaStore);
this.sections = stats.sections;
this.pluginKeyCount = stats.pluginKeyCount;
this.pluginConfigCount = stats.pluginConfigCount;
this.selectSection(pickInitialSection(this.sections));
} catch (e) {
this.settingsError = userMessage('settings.load', e);
}
this.loadingSettings = false;
}
private selectSection(secId: string): void {
this.activeSection = secId;
this.entries = buildEntries(this.valuesStore, this.metaStore, secId);
}
private findEntry(key: string): SettingEntry | undefined {
for (let i = 0; i < this.entries.length; i++) {
if (this.entries[i].key === key) {
return this.entries[i];
}
}
return undefined;
}
/** Persist one key via PUT /settings. bool is sent as "true"/"false" strings like the GUI. */
private async saveSetting(key: string, newValue: string): Promise<void> {
const entry: SettingEntry | undefined = this.findEntry(key);
if (entry === undefined) {
return;
}
let payload: string = newValue.trim();
if (entry.type === 'bool') {
payload = newValue === 'true' ? 'true' : 'false';
}
this.savingCount = this.savingCount + 1;
try {
const body: SaveSettingBody = { key: entry.key, value: payload };
await apiClient.request('/settings', 'PUT', JSON.stringify(body), 10000);
this.valuesStore[entry.key] = payload;
this.markEntry(entry.key, payload, false);
this.showToast('已保存: ' + entry.displayName, false);
} catch (e) {
this.showToast(userMessage('settings.save', e), true);
}
this.savingCount = this.savingCount - 1;
}
/** 已保存:读当前编辑值再落库(输入类控件的"保存"按钮) */
private saveCurrentValue(key: string): void {
this.saveSetting(key, this.currentValueOf(key));
}
private markEntry(key: string, value: string, dirty: boolean): void {
this.entries = withEntryMarked(this.entries, key, value, dirty);
}
private updateEntryValue(key: string, value: string): void {
const original: string = this.valuesStore[key] ?? '';
this.markEntry(key, value, value !== original);
}
private currentValueOf(key: string): string {
// read latest edited value from entries store (markEntry keeps copies)
const e: SettingEntry | undefined = this.findEntry(key);
return e !== undefined ? e.value : '';
}
private showToast(msg: string, isError: boolean): void {
// 颜色标记必须在 animateTo 之外先定好,否则第一帧会用上一条 toast 的配色
this.toastIsError = isError;
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.toastMsg = msg;
});
setTimeout(() => {
this.getUIContext().animateTo({ duration: ANIM_NORMAL, curve: Curve.EaseOut }, () => {
this.toastMsg = '';
});
}, 2500);
}
build() {
// Navigation 提供真实导航栈:系统侧滑返回 / 三键返回 / 无障碍返回
// 都会自动 pop 当前 NavDestination,无需自己拦 onBackPress。
//
// 宽屏(>=600vp)改用 Split 模式:navBar(这里的一级入口列表,含底部悬浮导航栏)
// 常驻左栏,NavDestination(二级页面)渲染在右栏,两栏同时可见。
Navigation(this.navStack) {
SettingsHome({
connCount: this.connections.length,
connName: this.currentConnName(),
sectionCount: this.sections.length,
coreKeys: this.coreKeyCount(),
busy: this.loadingSettings,
errorText: this.settingsError,
themeLabel: this.themeLabel(),
activeSub: this.activeSub,
isWide: this.isWide,
savingCount: this.savingCount,
toastMsg: this.toastMsg,
toastIsError: this.toastIsError,
onOpen: (id: string) => {
this.openSub(id);
},
})
}
.navDestination(this.SubDestination)
.mode(this.isWide ? NavigationMode.Split : NavigationMode.Stack)
.navBarPosition(NavBarPosition.Start)
.navBarWidth(WIDE_NAV_BAR_WIDTH)
.minContentWidth(WIDE_MIN_CONTENT)
.hideTitleBar(true)
.hideToolBar(true)
.hideBackButton(true)
.width('100%')
.height('100%')
// Split 模式下 navBar 常驻可见,onNavBarStateChange 不再触发,
// 所以在这里统一维护"横滑锁":宽屏一律锁住(靠点击导航栏切换 Tab,
// 避免在右栏操作时误触发主 Tab 切换)。
.onNavBarStateChange((isVisible: boolean) => {
markSubPageOpen(this.isWide || !isVisible);
})
// 模式初始化与切换的唯一钩子:Split 右栏不能空白,自动填入默认二级页面;
// 退回 Stack 时清栈,否则会残留一个整屏覆盖的二级页面。
.onNavigationModeChange((mode: NavigationMode) => {
if (mode === NavigationMode.Split) {
markSubPageOpen(true);
if (this.navStack.size() === 0) {
this.openSub(this.initialSub());
}
} else {
this.navStack.clear(false);
this.activeSub = SUB_NONE;
markSubPageOpen(false);
// 窄屏:未配置后端时直接推连接页,保证“设置里一定能找到连后端的入口”。
if (!this.autoOpenedConn && !apiClient.hasConnection()) {
this.autoOpenedConn = true;
this.openSub(SUB_CONNECTIONS);
}
}
})
}
/**
* 二级页面路由表:name 由 pushPathByName 传入。
* 各页面的外壳(SubPageLayer)与其内容一起放在对应组件里,
* 这里只做 id → 组件的分发。
*/
@Builder
SubDestination(name: string, param: object) {
NavDestination() {
if (name === SUB_STATUS) {
SubPageLayer({
title: '运行状态',
tab: 3,
onBack: () => {
this.closeSub();
},
showRefresh: true,
onRefresh: () => {
statusStore.refresh();
},
}) {
StatusDetailContent()
}
} else if (name === SUB_CONNECTIONS) {
ConnectionsPane({
connections: $connections,
currentId: $currentId,
onBack: () => {
this.closeSub();
},
onToast: (msg: string, isError: boolean) => {
this.showToast(msg, isError);
},
})
} else if (name === SUB_APPEARANCE) {
AppearancePane({
themeMode: $themeMode,
bgImage: $bgImage,
bgOpacity: $bgOpacity,
onBack: () => {
this.closeSub();
},
onToast: (msg: string, isError: boolean) => {
this.showToast(msg, isError);
},
})
} else if (name === SUB_BACKEND) {
BackendSectionsPane({
sections: this.sections,
pluginKeyCount: this.pluginKeyCount,
pluginConfigCount: this.pluginConfigCount,
busy: this.loadingSettings,
errorText: this.settingsError,
activeSection: this.activeSection,
highlightRows: this.isWide && this.activeSub === SUB_SECTION,
onBack: () => {
this.closeSub();
},
onRefresh: () => {
this.loadBackendSettings();
},
onOpenSection: (id: string) => {
this.selectSection(id);
this.openSub(SUB_SECTION);
},
})
} else if (name === SUB_SECTION) {
SectionEntriesPane({
sections: this.sections,
activeSection: this.activeSection,
entries: this.entries,
busy: this.loadingSettings,
onBack: () => {
this.closeSub();
},
onRefresh: () => {
this.loadBackendSettings();
},
onSaveValue: (key: string, value: string) => {
this.saveSetting(key, value);
},
onSaveCurrent: (key: string) => {
this.saveCurrentValue(key);
},
onEdit: (key: string, value: string) => {
this.updateEntryValue(key, value);
},
})
}
}
.hideTitleBar(true)
.backgroundColor(Color.Transparent)
}
}