🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(mobile): bring desktop surfaces to the mobile web (#21503)
Lobehub Coderba0f48575606
diff --git a/.agents/skills/lobe-design/CHANGELOG.md b/.agents/skills/lobe-design/CHANGELOG.mdindex f1350c86903..658507f502c 100644--- a/.agents/skills/lobe-design/CHANGELOG.md+++ b/.agents/skills/lobe-design/CHANGELOG.md@@ -2,6 +2,51 @@版本规则见 learnings/README.md §6(patch 修误报 / minor 加规则或 WARN→FAIL / major 改 stage 与路由)。+## 5.8.0 — 2026-10-23++一批设计思路(minor:新增 reference 编号 C-19、C-20;不删编号,不改 stage 与路由)。++- **M-01 判据 3**:先问题,后组件;不从现有页面、截图或组件清单出发修补。+- **SKILL.md 输出契约 · 示意图**:只画被讨论的模块,编号标注设计理由,低密度。+- **C-17**:状态由值本身表达,不加复述的 badge;关闭 / 恢复默认是同一控件里的选择;按功能分组命名;与已有设置页一致。+- **新增 C-19**(web / desktop / mobile):滚动边缘的模糊与淡出是为了扩大可读区域,只藏在框架身后,淡出到背景 token(web:`ProgressiveBlur`);无模糊能力时只淡出、框架实底。C-02 布局行同步。+- **新增 C-20**(仅 mobile):导航与输入浮在内容上,内容用满屏幕。+- **30-structure** 登记 C-19、C-20;`refs:meta` 补触发词;tests 加 `wording:` 断言。learnings:LRN-20261023-01..04。++## 5.7.0 — 2026-10-22++按环境绑定的凭证先按环境分组(minor:新增 reference 编号 C-18;不删编号,不改 stage 与路由)。++- **新增 C-18**(`references/components.md`):Vercel 环境变量、QStash、Redis 这类按环境配置的凭证 / 密钥 / secret / 环境变量,环境做顶层分组,每个环境下列出它的凭证(层级清楚用 `Tree`,环境少用 `Accordion`);同名 key 在每个环境下各列一次;只有一个环境时不造分组。不要把 env 做成平铺表里的一列。+- **30-structure**:「只加载」与「症状 → 规则」登记 C-18;`components.md` 的 `refs:meta` 加 C-18 触发词(凭证、环境、env、token、密钥、secret、环境变量、轮换、作用域)。+- learnings:LRN-20261022-01。++## 5.6.0 — 2026-10-19++React Native 宿主上 5.5.0 的遗留问题(minor:托管块新增精简模式并改为默认、新增 `lint-allow`;不删编号,不改 stage 与路由)。Fixes [#2](https://github.com/lobehub/lobe-design-skill/issues/2)。++- **`LOBE-RN-DOM-UI` 只报组件导入**:从 `@lobehub/ui` 根入口、组件子入口(`/form`、`/pro-table`、`/dashboard`、`/mobile`…)或 `@lobehub/ui/es/<Component>` 导入 PascalCase 名字(具名 / 默认 / `default as` / 命名空间)才报;`@lobehub/ui/es/hooks/*`、`Markdown/plugins/*`、`styles`、`utils`、`types`、`locale` 等工具子路径,以及 `useTheme` / `cssVar` 这类小写导出、`import type`、副作用导入不再误报(宿主实测 9 处误报)。+- **`lint-allow:`**(`product.md`,可多行):`lint-allow: LOBE-RN-DOM-UI src/components/hooks/**, src/components/styles/**` 按路径(相对项目根的 glob)关掉指定规则;报告头显示生效的 allow。+- **托管块精简模式 + 宿主语言**:`bootstrap.mjs` 新增 `--compact`(默认,~16 行:入口、先读项目层、平台、优先级、lint、沉淀、升级)/ `--full`(原完整中文块)与 `--lang zh|en`(默认按宿主 `AGENTS.md` 块外文本判断,不足时看 README)。块内第一行写 `<!-- lobe-design:mode=… lang=… -->`,重跑沿用、flag 覆盖;BEGIN / END 标记不变,≤ 5.5.0 的旧块重跑时换成默认精简块。`--check` 同时识别 `skill 版本` 与 `skill version`。+- **平台中立措辞**:SKILL.md frontmatter `description` 改为「原子层取自宿主组件库(web:`@lobehub/ui` + `cssVar`;React Native:项目组件库如 `@lobehub/ui-rn` + `useTheme()` token)」;`stages/50-visual.md` 取值规则按平台分写;`10-decode`、`30-structure`(硬性前提标注 web 作用域)、SKILL.md C-11 段、`references/design.md` D-01 同步。+- **`LOBE-ICON-BUTTON-LABEL`**:mobile 规则集的提示只写 `accessibilityLabel`(非按钮可点元素补 `accessibilityRole="button"`),web 提示仍是 `title` / `aria-label`。+- **tests**:RN fixture 增加 `@lobehub/ui/es` 工具导入(Markdown 插件、hooks、颜色种子);`bad-rn.tsx` 增加 `es/Markdown` 组件导入与缺 `accessibilityLabel` 的图标按钮;新增 `== issue #2 (RN follow-ups)` 一节(组件导入判定、`lint-allow`、精简 / 语言 / 沿用 / 旧块迁移 / 幂等 / `--check`、措辞断言、RN 图标按钮提示)。++## 5.5.0 — 2026-10-16++05-init 识别出的平台真正生效(minor:新增 RN 专属 WARN 规则 `LOBE-RN-DOM-UI`、规则平台作用域与项目层适用性开关;不删编号,不改 stage 与路由)。Fixes [#1](https://github.com/lobehub/lobe-design-skill/issues/1)。++- **lint 平台门控**:新增 `scripts/platform.mjs`(lint / bootstrap / project-scan 共用)。平台来源:`--platform` / 文件内 `lobe-design-platform:` 注释 / `*.native|ios|android.tsx` → `.agents/ux/product.md` 的 `平台:` 行 → `package.json`(`react-native` / `expo` / `@lobehub/ui-rn` → mobile)。每条规则声明 `platforms`(`--rules` 显示);mobile 跳过 web 专属规则(`LOBE-ANTD-IMPORT`、`LOBE-FORM-ENTRY`、`LOBE-ANT-ICONS`、`LOBE-CREATE-STYLES`、`LOBE-I18N-PROVIDER`、`LOBE-CSS-LINE-COMMENT`、`LOBE-ANT-CLASS`、`LOBE-ANT-VAR-OVERRIDE`、`LOBE-REIMPLEMENT-ATOM`、`LOBE-FONT-FAMILY`、`LOBE-EYEBROW`、`LOBE-BLUR-CARD`、`LOBE-SIDE-STRIPE`、`LOBE-GLOW`、`LOBE-GRADIENT-TEXT`、`LOBE-OUTLINE-NONE`、`LOBE-IMG-ALT`、`LOBE-DIV-CLICK`、`LOBE-GRADIENT-ANIMATION-OVERUSE`);`LOBE-RAW-COLOR` 在 mobile 上给 RN 主题 token 的修法而不是 `cssVar`。新增 `--platform` / `--root`,报告头显示 `platform=…(来源)`。+- **项目层适用性关规则**:`product.md` 里标「不适用 / N/A」那一行的规则编号(含区间 `C-01..C-11`)与 lint id、以及 `lint-off: LOBE-XXX, D-01` 行,关掉对应 lint 规则(按 id 或其引用编号)。+- **新增 `LOBE-RN-DOM-UI`**(WARN,C-01,仅 mobile):RN 界面导入 `@lobehub/ui` / `antd` 这类 DOM 组件库(`import type` 不报)。fixtures:`bad-rn.tsx` / `good-rn.tsx`。+- **误报**:`LOBE-ICON-BUTTON-LABEL`(K-07)接受 `accessibilityLabel`;`LOBE-REDUCED-MOTION` 接受 `isReduceMotionEnabled` / `ReduceMotion`。+- **优先级改写**:删掉托管块的「冲突时以 skill 为准」,改为「项目层的平台与适用性优先于 skill 通用规则;其余冲突以 skill 为准;项目层违背通用原则须写明理由」。SKILL.md、`references/init.md`(新增 I-10)、`references/components.md` C-01(标注平台作用域 web / desktop)同步。+- **托管块按平台生成**:mobile 时加「平台:mobile(React Native)」一节(原子层用项目 RN 组件库、不改用 `@lobehub/ui`、web 专属条目不适用、可达性照常),lint 指令改为按 mobile 规则集、按项目主题修。skill 内文件统一写 `$LOBE_DESIGN/scripts/…`;尚不存在的项目层文件不再写成代码样式路径(宿主路径检查不再报死链)。+- **Round 2 / project-scan 平台感知**:输出 `stack.platform`、`primaryUi`(mobile 时为 RN 组件库,含 tsconfig alias,如 `@lobehub/ui-rn → src/components`)、`depOnlyUi`(mobile 上的 `@lobehub/ui` 等 DOM 库只算依赖)、`navigation`(`expo-router` / `@react-navigation/*`)、`componentScheme` 与逐文件启发式初分 `componentClasses`。mobile 分类为「项目原子层 / 薄包装 / 业务组件」,不再出现「改用 lobe-ui」。05-init 与 I-08 同步。+- **75-copy 路由分区按路径段匹配**:`refs.mjs` 新增 `matchRoute`:`/api-keys` 命中 `/:wsSlug/api-keys`(任意位置的连续段),不再被 `/api-keys-legacy` 这类前缀误命中;支持 `/*/api-keys`(一段)、`/admin/**`(任意多段)、`^/admin`(从根);多条命中取更具体的;新增 `--page <路由>`。+- **文档**:`install.sh` 在 skill 仓库根目录(不在 `skills/lobe-design/` 下),`references/init.md` 与托管块的安装说明写明。+- **tests**:新增 RN fixture 项目 `tests/fixtures/rn-project/`(expo + react-native + `@lobehub/ui-rn` alias,`StyleSheet` 组件)与 `== platform (mobile / RN)` 一节:0 web-only FAIL、强制 web 时仍报(门控而非失效)、`product.md` 平台 / 适用性、托管块无 web 专属指令与新优先级、project-scan 分类;75-copy 路由段匹配用例。`check-learnings` 读 fixtures 时跳过子目录。+## 5.4.2 — 2026-10-16`--copy` 重装时不再把备份留在宿主项目里(patch:不改规则通过条件)。diff --git a/.agents/skills/lobe-design/SKILL.md b/.agents/skills/lobe-design/SKILL.mdindex 99a2fb8e7c3..c90216d2353 100644--- a/.agents/skills/lobe-design/SKILL.md+++ b/.agents/skills/lobe-design/SKILL.md@@ -1,6 +1,6 @@---name: lobe-design-version: 5.4.2+version: 5.8.0description: >Single entry for LobeHub UI design work. Routes any instruction — macro ("重做这个后台", "整体打磨一下"),medium ("把列表页的交互和空态补齐") or fine ("这个按钮颜色不对", "修 K-07") — into a business-first, layered@@ -9,9 +9,11 @@ description: >portfolio / campaign), polishing existing product UI, admin consoles / dashboards / forms / workflows,design-system unification, screenshot restoration, pre-launch audit, and project bootstrap (AGENTS.md).Grounded in classic analysis models (double diamond, Gestalt, Nielsen heuristics, Kano, peak-end, Fogg,- journey map, cognitive load) and in a layered component boundary: take atoms from @lobehub/ui,- build business composites yourself. Built on @lobehub/ui, @lobehub/ui/form, @lobehub/ui/pro-table, cssVar- tokens, @lobehub/charts / icons / fluent-emoji / streamdown, with runnable lint, route, refs and+ journey map, cognitive load) and in a layered component boundary: take atoms from the host's component+ library and build business composites yourself. Platform-aware (web / desktop / mobile, read from the+ project layer): web takes atoms from @lobehub/ui (/form, /pro-table) with cssVar tokens; React Native takes+ them from the project's own library (e.g. @lobehub/ui-rn) with useTheme() tokens. Web ecosystem:+ @lobehub/charts / icons / fluent-emoji / streamdown. Runnable lint (platform-gated), route, refs andbootstrap checks; in-product UI copy by product profile (consumer / SaaS / admin / developer), withzh-CN typography. Trigger on lobe-design, lobe-ui, lobehub, LobeChat UI, 控制台, 后台, 看板, 落地页, 官网,截图还原, 设计稿, 设计系统统一, 打磨, polish, refine, 审查, 上线前检查, 组件选择, 设计准则, AI 味, 文案, 措辞, 中英文空格, 初始化, AGENTS.md.@@ -22,6 +24,7 @@ description: >一个入口,按需展开。本文件只负责四件事:**先理解业务、识别场景、决定跑哪些 stage、规定每一步的输出**。具体规则在 `stages/` 和 `references/` 里,进入某个 stage 时才读取,不要一开始就全部读完。**宿主项目已安装时**:把 `.agents/ux/product.md`(产品画像与适用性)和 `.agents/ux/components.md`(组件用法)当作本 skill 的一等输入——**先读它们,再进 stage**。没有这两份时,先跑 `05-init`(装完 / 升级后也应重跑)。+**优先级**:`product.md` 里的平台与适用性(标为「不适用」的规则、按平台限定的规则)优先于本 skill 的通用规则;其余冲突以 skill 为准;项目层要违背通用原则(可达性、P-xx)必须写明理由([init.md](references/init.md) I-10)。**平台是 mobile(React Native)时**,本文件与 references 里 web 专属的条目(`@lobehub/ui` 原子层、`cssVar` / `createStaticStyles`、antd、CSS 类名、`outline`、`font-family`)不适用:原子层是项目自己的 RN 组件库(如 `@lobehub/ui-rn`),`lint-lobe.mjs` 按平台自动跳过这些规则。## 为什么这样分层@@ -76,22 +79,22 @@ description: >| 层 | 例子 | 怎么办 || --- | --- | --- |-| 原子层 | `Button` `Input` `Modal` `Table` `Tag` | **必须**从 `@lobehub/ui` 取用(C-01 硬性规则,lint 兜底) |+| 原子层 | `Button` `Input` `Modal` `Table` `Tag` | web:**必须**从 `@lobehub/ui` 取用(C-01 硬性规则,lint 兜底);mobile:用项目的 RN 组件库(如 `@lobehub/ui-rn`) || 皮肤层 | `Block` `Surface` `ConsoleShell` `PageHeader` | 用 lobe-ui / dashboard 现成的 || 组合层 | 会话区、消息体、工作流画布、业务卡片簇 | **优先自建**,用原子层 + 皮肤层拼 || 领域层 | Agent 会话、模型调用、审批流 | **必须自建** |判据:布局由业务语义决定 → 自建;需要跨页复用 → 自建一个项目内组件;只是为了外观相近 → 用现成件。反过来,把 `Table` / `Modal` / `Input` 在项目里重写一遍同样是错的(`LOBE-REIMPLEMENT-ATOM`)。-自建件内部只能用原子层和皮肤层,取值仍走 `cssVar`,并且**不要改 lobe-ui 源码**。`chat` 系列是这条边界的参照实现。+自建件内部只能用原子层和皮肤层,取值仍走主题 token(web:`cssVar`;RN:`useTheme()` 的 token),并且**不要改组件库源码**。`chat` 系列是这条边界的参照实现。### 3. 项目接入与两轮自迭代(`stages/05-init.md`,`scripts/bootstrap.mjs`,`scripts/project-scan.mjs`)**装完或升级后先跑 05**(或对 Agent 说「初始化 / 升级后刷新」):-1. **接入**:探测 `AGENTS.md` → `CLAUDE.md` → 都没有就建立,把入口、触发、纪律、自迭代写进托管块(块外一字不改;`--print` 后再写)。+1. **接入**:探测 `AGENTS.md` → `CLAUDE.md` → 都没有就建立,把入口、触发、纪律、自迭代写进托管块(块外一字不改;`--print` 后再写)。默认写精简块并跟随宿主语言(`--full` / `--lang zh|en` 覆盖,见 [init.md](references/init.md) I-04)。2. **Round 1 产品画像**:`project-scan.mjs` 收集确定性事实 → 写 `.agents/ux/product.md`(平台、产品类型、用户、核心任务、规则适用性、文案 profile)。-3. **Round 2 组件盘点**:扫描项目组件 → 写 `.agents/ux/components.md`(薄包装 / 与 lobe-ui 重复 / 业务组件用法;无实现细节)。+3. **Round 2 组件盘点**:扫描项目组件 → 写 `.agents/ux/components.md`(web:薄包装 / 与 lobe-ui 重复 / 业务组件;mobile:项目原子层 / 薄包装 / 业务组件;无实现细节)。项目层在 `.agents/ux/`,**不进**已安装 skill,重装不覆盖。日常 UI 任务**先读** `product.md` 与 `components.md`,再按 stage 加载。`--check` / `project-scan --check` 发现缺失或过期时重跑两轮。@@ -221,6 +224,10 @@ brief:<一行摘要>学习候选:<本次被用户纠正的地方 → `node scripts/check-learnings.mjs --new` 生成条目,按 learnings/README.md 选层回写>```+### 示意图++给用户看方案时,示意图只画正在讨论的那个模块,用编号标注讲清为什么这样设计,保持低密度,让人一眼看到要比较的地方,而不是整个应用。+## 资产目录(都由本入口按需引用,不是独立的 skill)```diff --git a/.agents/skills/lobe-design/learnings/LOG.md b/.agents/skills/lobe-design/learnings/LOG.mdindex a77d6a538dd..d9d68a4c7b9 100644--- a/.agents/skills/lobe-design/learnings/LOG.md+++ b/.agents/skills/lobe-design/learnings/LOG.md@@ -619,3 +619,143 @@ artifacts: stages/75-copy.md, scripts/pipeline.json, scripts/refs.mjs, scripts/cregression: tests/route-cases.json, tests/fixtures/bad-copy.tsxversion: 5.4.0```++## LRN-20261016-03 · init 识别出 mobile,lint 与托管块仍按 Web 执行(5.5.0)++```learning+id: LRN-20261016-03+date: 2026-10-16+status: landed+symptom: React Native / Expo 项目跑完 05-init 后,lint 仍报 603 FAIL(cssVar、createStaticStyles、把 @lobehub/ui-rn 当成重写原子层);托管块「冲突时以 skill 为准」让 product.md 的「不适用」失效;Round 2 分类要求整个 RN 组件库改用 @lobehub/ui+source: user-correction+scenario: bootstrap+stage: 05-init+occurrences: 1+previous_layer:+root_cause: 平台只写进 product.md 的文字,脚本与托管块都不读它;lint 规则没有平台作用域,项目层适用性也没有机读入口;优先级一句话把项目层的裁剪压回通用规则+layer: lint+layer_reason: 平台与适用性都能机械读取(product.md 的平台行 / 不适用行 / lint-off、package.json 依赖),由 scripts/platform.mjs 统一解析,lint 规则声明 platforms,托管块与 project-scan 按平台输出;RN fixture 项目锁住 0 web-only FAIL+artifacts: LOBE-RN-DOM-UI, scripts/platform.mjs, scripts/lint-lobe.mjs, scripts/bootstrap.mjs, scripts/project-scan.mjs, references/init.md+regression: tests/fixtures/bad-rn.tsx+version: 5.5.0+```++## LRN-20261019-01 · RN 宿主里工具函数被当成 DOM 组件,托管块篇幅与语言不贴宿主(5.6.0)++```learning+id: LRN-20261019-01+date: 2026-10-19+status: landed+symptom: 5.5.0 在 RN 项目里把 @lobehub/ui/es 下的 Markdown 插件、hooks、颜色种子报成 LOBE-RN-DOM-UI(9 处);托管块 88 行中文写进英文 AGENTS.md,每次会话都加载;SKILL.md 描述与 50-visual 仍把 @lobehub/ui / cssVar 写成通用做法;RN 上的图标按钮提示还提 aria-label+source: user-correction+scenario: bootstrap+stage: 05-init+occurrences: 1+previous_layer:+root_cause: LOBE-RN-DOM-UI 按导入来源判断而不是按导入的是不是组件;托管块只有一种完整中文写法;入口文档的 web 写法没有标平台作用域+layer: lint+layer_reason: 组件导入可按来源子路径 + PascalCase 名字机械判断,路径放行由 product.md 的 lint-allow 声明;托管块模式与语言写进块内模式行,由 bootstrap 测试锁住幂等与旧块迁移;措辞由测试断言+artifacts: LOBE-RN-DOM-UI, scripts/lint-lobe.mjs, scripts/platform.mjs, scripts/bootstrap.mjs, SKILL.md, stages/50-visual.md+regression: tests/fixtures/bad-rn.tsx+version: 5.6.0+```++## LRN-20261022-01 · 按环境配置的凭证平铺成一张表,看不出归属(5.7.0)++```learning+id: LRN-20261022-01+date: 2026-10-22+status: landed+symptom: 轮换 Vercel / QStash / Redis 这类按环境配置的 token 时,凭证页是一张平铺的表,env 只是其中一列,同名 token 一行一行排下来,看不出哪个 token 属于哪个环境+source: user-correction+scenario: operate-build+stage: 30-structure+occurrences: 1+previous_layer:+root_cause: 规则缺失:C-08 只管表格选型,P-05 只说按影响范围分组,没有「环境 / 作用域是顶层分组」的判据+layer: rule+layer_reason: 是否按环境分组、同名 key 是否在各环境下分别列出要读页面结构判断,无法用正则确定性识别;落 C-18 并在 30-structure 症状表登记+artifacts: references/components.md, C-18, stages/30-structure.md+regression: scripts/check-structure.mjs no-dangling-ids+version: 5.7.0+```++## LRN-20261023-01 · 从现有页面和组件清单出发修补(5.8.0)++```learning+id: LRN-20261023-01+date: 2026-10-23+status: landed+symptom: 改界面时先在现有页面或组件清单上改几处,说不出用户要理解或决定什么+source: user-correction+scenario: product-polish+stage: 00-brief+occurrences: 1+previous_layer:+root_cause: 规则太模糊:M-01 没讲「问题 → 呈现 → 组件」的先后+layer: rule+layer_reason: 起点对不对要读方案判断;合并进 M-01 判据 3+artifacts: references/models.md, M-01+regression: scripts/check-structure.mjs no-dangling-ids+version: 5.8.0+```++## LRN-20261023-02 · 示意图画整个应用、密度高(5.8.0)++```learning+id: LRN-20261023-02+date: 2026-10-23+status: landed+symptom: 给用户看的示意图画整个 app,信息密,设计理由靠猜+source: user-correction+scenario: product-polish+stage: 40-flow+occurrences: 1+previous_layer:+root_cause: 规则缺失:输出契约没讲讲方案用的示意图+layer: structure+layer_reason: 示意图是各 stage 都会交付的产物,放进 SKILL.md 输出契约,wording 测试锁住约定存在+artifacts: SKILL.md+regression: tests/run.mjs wording: SKILL.md 输出契约有示意图约定+version: 5.8.0+```++## LRN-20261023-03 · 设置页用 badge 和额外按钮复述状态(5.8.0)++```learning+id: LRN-20261023-03+date: 2026-10-23+status: landed+symptom: 设置项旁挂复述值的 badge、另加开关或恢复按钮;按默认值而非功能分组;布局和其他设置页不一致+source: user-correction+scenario: product-polish+stage: 30-structure+occurrences: 1+previous_layer:+root_cause: 规则缺失:C-17 只讲就地编辑和回显+layer: rule+layer_reason: 是否复述状态要读结构判断;合并进 C-17+artifacts: references/components.md, C-17+regression: scripts/check-structure.mjs no-dangling-ids+version: 5.8.0+```++## LRN-20261023-04 · 滚动边缘的模糊吃进正文;移动端被实底栏框住(5.8.0)++```learning+id: LRN-20261023-04+date: 2026-10-23+status: landed+symptom: 模糊带压进正文、用黑色或硬切遮罩、半透明盖在文字上;移动端上下两条实底栏占掉屏幕+source: user-correction+scenario: product-polish+stage: 30-structure+occurrences: 1+previous_layer:+root_cause: 规则缺失:没有滚动边缘与移动端悬浮框架的判据+layer: rule+layer_reason: 要看渲染与结构判断;落 C-19(web 用 ProgressiveBlur)与 C-20(仅 mobile)+artifacts: references/components.md, C-19, C-20, C-02, stages/30-structure.md+regression: tests/run.mjs wording: C-19 / C-20+version: 5.8.0+```diff --git a/.agents/skills/lobe-design/references/components.md b/.agents/skills/lobe-design/references/components.mdindex cde0e927d8a..2b35e032c4e 100644--- a/.agents/skills/lobe-design/references/components.md+++ b/.agents/skills/lobe-design/references/components.md@@ -22,7 +22,10 @@ entries:C-11 | deep | 自建,组合组件,业务组件,分层,原子层,chat,自研,封装C-12 | deep | 可访问名,aria,读屏,无名,switch,checkbox,图标按钮C-15 | deep | confirmmodal,确认弹窗,菜单,popover,浮层,二级菜单- C-17 | deep | 表单,设置页,重置,就地编辑,短表单+ C-17 | deep | 表单,设置页,重置,就地编辑,短表单,默认值,恢复默认,badge+ C-18 | deep | 凭证,环境,env,token,密钥,secret,环境变量,轮换,作用域,分组+ C-19 | deep | 滚动边缘,渐进模糊,progressiveblur,模糊,淡出,遮罩,liquid glass,降低透明度+ C-20 | deep | 移动端,悬浮,胶囊,导航栏,顶栏,输入框,mobile-->物料清单只说「有什么」。这份文件说「什么时候该用,什么时候不该用」。@@ -33,6 +36,8 @@ entries:## C-01 原子层从 `@lobehub/ui` 取用(硬性规则,只管原子层)+**平台作用域:web / desktop。** mobile(React Native)项目的原子层是项目自己的 RN 组件库(如 `@lobehub/ui-rn`),本条不适用(`@lobehub/ui` 是 DOM 组件库);见 [init.md](init.md) I-10。+**先看 C-11 的分层。** 本条的硬约束只覆盖**原子层**(按钮、输入、表格、弹层这类不可再分的零件)。组件从 `@lobehub/ui` 根入口导入(基于 `@base-ui/react`)。独立入口只有这几个:表单 `@lobehub/ui/form`、请求驱动的表格 `@lobehub/ui/pro-table`、控制台 `@lobehub/ui/dashboard`,其余见 C-06。样式 API(`createStaticStyles` · `cssVar` · `cx` · `css` · `keyframes` · `responsive` · `useTheme` · `useThemeMode` · `lobeStaticStylish`)同样从 `@lobehub/ui` 导入。@@ -147,7 +152,7 @@ const form = useForm<Values>({ schema, initialValues, onSubmit });| 固定窄导航栏 | `SideNav`(`avatar` + `topActions` + `bottomActions`) || 可伸缩侧栏容器 | `DraggableSideNav`(仅左右,折叠宽度 = `minWidth`,默认 64px) || 自定义滚动条 | `ScrollArea`(`scrollFade`) |-| 滚动到边缘的渐隐 | `ScrollShadow`(保留原生滚动)或 `MaskShadow`(单边静态遮罩) |+| 滚动到边缘的渐隐 | `ScrollShadow`(保留原生滚动)或 `MaskShadow`(单边静态遮罩);内容从顶栏 / 输入框后面滚过用 `ProgressiveBlur`(C-19) || 页内目录 | `Anchor`(滚动监听) || 移动端汉堡菜单 | `Burger`(打开抽屉里的 `List`,或全屏大字) |@@ -420,4 +425,35 @@ BackBottom ← 浮层,指向滚动容器- 对象的属性就地编辑:左边标题加一句说明,右边是控件,底栏保存。不要画成只读的键值卡再打开编辑弹窗。没有权限的项显示为文字或 `Snippet`,不要一排灰掉的输入框。- 登录、改密码这类短表单字段排得紧,间距只留在字段之间;设置页的分组表单保留分割线和组间距。- 重置和稍后才到的已保存值都要回显到控件上;保存成功后控件显示的就是刚保存的值。+- 设置项的状态由值本身表达:控件里显示的就是当前生效的值(跟随默认时显示跟随的是谁),再挂一个复述它的 badge 只是噪音。关闭和恢复默认是同一个控件里的选择,不需要另加开关或按钮。+- 按功能分组、按功能命名,让人看出每一项管什么,而不是它跟随了哪个默认值。+- 和产品里已有的设置页保持一致(web 上是 `@lobehub/ui/form` 的分组表单),不要照着设计稿另画一套。++## C-18 按环境绑定的凭证:先按环境分组,再列凭证++适用:按环境(或作用域)分别配置的凭证与变量,例如 Vercel 的环境变量、QStash 的签名密钥与 token、Redis 的连接串与 token;任何「同一个 key 在开发 / 预览 / 生产各有一份值」的密钥、secret、环境变量列表,以及轮换凭证的页面。按项目、团队、区域划分的作用域同理。++| 场景 | 用 | 注意 |+| --- | --- | --- |+| 凭证按环境区分,需要逐个环境核对、复制或轮换 | 环境做顶层分组,每个环境下列出它的凭证。层级要清楚、需要展开收起时用 `@lobehub/ui` 的 `Tree`(环境是父节点,凭证是子节点);环境少、每组只有几条时用 `Accordion`,一个环境一节,节内是凭证列表 | 分组标题写环境名和凭证数;环境顺序固定(如 开发 → 预览 → 生产),各页一致 |+| 同一个 key 名出现在多个环境 | 在每个环境下各列一次 | 不要合并成一行再用标签罗列环境:值、更新时间、轮换动作都属于它所在的那个环境 |+| 只有一个环境,或凭证本身不分环境 | 普通列表 / 表格即可 | 不要为了形式造一层只有一个子项的分组 |++- 要:先看到「生产环境下有哪些凭证」,再看每条凭证的状态和操作。+- 不要:一张平铺的表,env 只是其中一列,同名 token 一行一行排下来,看不出哪个 token 属于哪个环境。++核对:随手指一条凭证,不读 env 列也能说出它属于哪个环境;同名 key 在每个环境下各出现一次。++## C-19 滚动边缘:让可读区域更大,而不是更小++**平台作用域:web / desktop / mobile。**++内容从顶栏、输入框这类界面框架后面滚过时,边缘的模糊和淡出是为了让正文一直用到屏幕边缘,所以模糊只该藏在框架身后,不能吃进正文。淡出到所在表面的背景色(`colorBgLayout` / `colorBgContainer`),不要用黑色或一刀切的遮罩。web 上用 `ProgressiveBlur`。++内容快碰到浮动的输入框之前就该淡出:即使有系统玻璃(如 iOS 26 的 Liquid Glass),文字压在玻璃后面照样难读。没有模糊或透明能力时(不支持 backdrop-filter、用户开了降低透明度),退回到单纯淡出加实底框架;任何时候都不要让半透明的东西盖在文字上。++## C-20 移动端:界面框架浮在内容上++**平台作用域:mobile。** web / desktop 不适用。+返回、标题、输入这些框架做成浮在内容上的胶囊,而不是上下两条实底栏,内容就能用满整个屏幕,不被框架框住。胶囊背后的边缘处理按 C-19;不支持模糊时胶囊改实底。diff --git a/.agents/skills/lobe-design/references/design.md b/.agents/skills/lobe-design/references/design.mdindex ee1e5af5be5..f493a33410e 100644--- a/.agents/skills/lobe-design/references/design.md+++ b/.agents/skills/lobe-design/references/design.md@@ -25,6 +25,8 @@ entries:## D-01 唯一事实源是 cssVar+> 平台作用域:web / desktop。RN 项目的唯一事实源是项目主题(`useTheme()` token),写法见 50-visual;原则相同:组件里不写裸值。+```tsimport { createStaticStyles } from '@lobehub/ui';diff --git a/.agents/skills/lobe-design/references/init.md b/.agents/skills/lobe-design/references/init.mdindex 8d89535b774..23f106e9b2d 100644--- a/.agents/skills/lobe-design/references/init.md+++ b/.agents/skills/lobe-design/references/init.md@@ -69,6 +69,10 @@ scope: 项目接入;AGENTS.md 探测、托管块、产品画像与组件盘点| `node scripts/bootstrap.mjs --check` | 只检查,不写;块缺失或版本落后即失败;项目层缺失 / 过期打 WARN | 0 / 1 || `node scripts/bootstrap.mjs --print` | 打印将要写入的块,不落盘 | 0 || `node scripts/bootstrap.mjs --root <dir>` | 指定项目根目录(默认当前目录) | — |+| `node scripts/bootstrap.mjs --compact \| --full` | 精简块(~16 行:入口、先读项目层、平台、优先级、lint、沉淀、升级;**默认**)\| 完整块(含自迭代与回流细则,中文) | 0 |+| `node scripts/bootstrap.mjs --lang zh\|en` | 精简块的语言;默认按宿主 `AGENTS.md`(块外、去掉代码后中文字符多于英文单词 → zh),内容不足时看 `README.md`,都判不了用 zh | 0 / 2 |++**默认与沿用(5.6.0)**:托管块每次会话都会加载,所以默认写精简块,并用宿主的语言,避免在英文的 `AGENTS.md` 里塞几十行中文。块内第一行记下 `<!-- lobe-design:mode=<compact|full> lang=<zh|en> -->`;之后不带参数重跑会沿用它(幂等),显式 `--compact` / `--full` / `--lang` 覆盖并改写这一行。≤ 5.5.0 写入的旧块没有这一行,重跑时按默认换成精简块;首尾 `BEGIN` / `END` 标记不变,旧安装照常识别、整块替换。自迭代与回流的细则在精简模式下由 skill 自己的 `learnings/README.md`、`CONTRIBUTING.md` 承载。`node scripts/project-scan.mjs`(只读,不落盘):@@ -89,7 +93,7 @@ scope: 项目接入;AGENTS.md 探测、托管块、产品画像与组件盘点- `bootstrap.mjs` **不写** `.agents/ux/` 下的内容(只探测是否存在);`product.md` / `components.md` 由 05-init 的 Agent 两轮写入(I-07 / I-08)。- **不改应用代码、不跑 build、不记录组件实现细节**——只写设计规则与用法指引。- 不在没有写权限或用户没确认时落盘。-- **已安装的 skill 目录保持通用**:项目画像与组件盘点不写进 `$LOBE_DESIGN/`,重装 / `install.sh --copy` 不会冲掉项目层。+- **已安装的 skill 目录保持通用**:项目画像与组件盘点不写进 `$LOBE_DESIGN/`,重装 / 仓库根的 `./install.sh --copy` 不会冲掉项目层。## I-06 项目层规范指针(`.agents/ux/`)@@ -109,12 +113,12 @@ scope: 项目接入;AGENTS.md 探测、托管块、产品画像与组件盘点| 字段 | 写什么 || --- | --- |-| 平台 | `web` / `desktop` / `mobile` / `mix`(可多选,说明主次) |+| 平台 | 一行机读:`平台:web` / `desktop` / `mobile` / `mix`(可多选,第一个为主)。`lint-lobe.mjs`、`bootstrap.mjs` 读这一行决定规则集与托管块(I-10) || 产品类型 | 消费级聊天、管理后台、开发者平台、评测/训练控制台、营销站、文档站… || 用户 | 角色、权限边界、使用频率 || 核心任务 | 3–7 条动词开头的主路径 |-| 适用性 | 哪些 P-xx 原型 / 规则**强调**、哪些**不适用**(例:触控为主 → hover-only 交互 N/A;高密度后台 → P-01 强调) |-| 文案 profile | 一行机读:`copy-profile: <consumer\|saas\|admin\|devtool>`,可按路由分区(`copy-profile: consumer; /admin → admin`);再写人称(无主语 / 你 / 您)与术语表位置。75-copy 据此只加载一份 profile;判断不了时写 `copy-profile: 待确认` |+| 适用性 | 哪些 P-xx 原型 / 规则**强调**、哪些**不适用**(例:触控为主 → hover-only 交互 N/A;高密度后台 → P-01 强调)。**一行一条**写成表格行或 `lint-off: LOBE-XXX, D-01` 行;标「不适用 / N/A」那一行里的规则编号(含区间 `C-01..C-11`)和 lint id 会被 `lint-lobe.mjs` 关掉,所以不要把「强调」和「不适用」写在同一行 |+| 文案 profile | 一行机读:`copy-profile: <consumer\|saas\|admin\|devtool>`,可按路由分区(`copy-profile: consumer; /admin → admin`;按路径段匹配,`/api-keys` 命中 `/:wsSlug/api-keys`,也可写 `/*/api-keys`,见 75-copy);再写人称(无主语 / 你 / 您)与术语表位置。75-copy 据此只加载一份 profile;判断不了时写 `copy-profile: 待确认` |文件头必须带 init meta(供 `--check` 判过期):@@ -126,7 +130,9 @@ scope: 项目接入;AGENTS.md 探测、托管块、产品画像与组件盘点## I-08 第二轮:组件盘点(Round 2)-在 Round 1 之后,扫描项目自己的组件目录(`src/components`、`features`、shared UI、对 lobe-ui 的包装等),写入 `.agents/ux/components.md`:+在 Round 1 之后,扫描项目自己的组件目录(`src/components`、`features`、shared UI、对 lobe-ui 的包装等),写入 `.agents/ux/components.md`。`project-scan.mjs` 会按平台给出分类方案和逐文件初分(启发式,需复核)。++**web / desktop**:| 分类 | 判据 | 写法 || --- | --- | --- |@@ -134,16 +140,44 @@ scope: 项目接入;AGENTS.md 探测、托管块、产品画像与组件盘点| 与 lobe-ui 重复 | 自建原子层(Button/Modal/Table…) | 标注「改用 lobe-ui」,不要扩写实现 || 业务组件 | 带领域语义、值得保留 | **场景 + 注意点**(何时用、何时不用、和别的件怎么配合);**不写**内部实现、props 清单、源码路径细节 |+**mobile(React Native)**:项目自己的组件库就是原子层,**不出现「改用 lobe-ui」**(`@lobehub/ui` 是 DOM 库,RN 里用不了)。++| 分类 | 判据 | 写法 |+| --- | --- | --- |+| 项目原子层 | 项目 RN 组件库(如 `@lobehub/ui-rn`,常经 alias 指向 `src/components`)里基于 `react-native` 原语的件 | 列出可用件与选型注意点;新界面从这里取,不自建同名件 |+| 薄包装 | 几乎只是透传项目原子层 | 标注「优先用原子层件」 |+| 业务组件 | 带领域语义、值得保留(列表行、会话卡片…) | 同上:场景 + 注意点 |++另记导航(`expo-router` / `@react-navigation/*`)与平台原生能力(`Alert.alert`、ActionSheet、Haptics)的用法约定。+同样带 init meta;可顺手把项目层规则里与组件选型相关的强调写进 `lobe-design-rules.md`(续编号,不改 skill)。重跑更新,不重复追加。## I-09 触发、升级与过期| 时机 | 做什么 || --- | --- |-| 首次 `install.sh` / 拷贝安装之后 | install 输出提示跑 bootstrap + 对 Agent 说「初始化」;05 写托管块并完成两轮 |+| 首次安装(skill 仓库根目录的 `./install.sh`,即 `~/lobe-design/install.sh` 这类 clone 路径;它不在 `skills/lobe-design/` 里)/ 拷贝安装之后 | install 输出提示跑 bootstrap + 对 Agent 说「初始化」;05 写托管块并完成两轮 || skill 升级之后(版本号变了) | 重跑 bootstrap(更新托管块)+ 重跑两轮(刷新 meta 里的 version) || 仓库结构大变(新框架、大目录搬迁) | `project-scan` 指纹变 → `--check` WARN → 重跑两轮 || 日常 UI 任务 | **不**重跑两轮;只**读**已有 `product.md` / `components.md` |`bootstrap.mjs --check` 在托管块 OK 时仍会打印项目层缺失 / 过期的 WARN(不因此单独把已接入判成 FAIL)。`project-scan.mjs --check`:缺文件 → exit 1;仅过期 → WARN + exit 0。++## I-10 平台门控与优先级(5.5.0)++Round 1 写下的平台不只是描述,它决定脚本和托管块的行为:++| 来源(由强到弱) | 读法 |+| --- | --- |+| `lint-lobe.mjs --platform <p>` / 文件内 `lobe-design-platform: mobile` 注释 / `*.native|ios|android.tsx` | 显式指定 |+| `.agents/ux/product.md` 的 `平台:…` 行 | 第一个为主平台 |+| `package.json` 依赖 | `react-native` / `expo` / `@lobehub/ui-rn` → mobile;`electron` / tauri → desktop;其余 web |++- **lint**:每条规则声明 `platforms`(`--rules` 可见)。mobile 跳过 web 专属规则(antd / `@lobehub/ui` 导入入口、`createStyles`→`createStaticStyles`、CSS 注释与 `.ant-` 类名、主题变量覆盖、`REIMPLEMENT-ATOM`、`font-family`、`outline`、`<img alt>`、`div onClick`、`backdrop-filter`、光晕阴影、渐变文字、eyebrow、侧边竖条、`gradientAnimation`),另跑 RN 专属的 `LOBE-RN-DOM-UI`;`RAW-COLOR` 照常报,但修法指向项目主题 token;K-07 图标按钮接受 `accessibilityLabel`。+- **适用性**:`product.md` 里标「不适用 / N/A」的行中出现的规则编号(含区间)与 lint id,以及 `lint-off:` 行,关掉对应 lint 规则(按 lint id 或其引用的规则编号)。+- **按路径放行(5.6.0)**:`lint-allow: <规则 id…> <glob…>`(可多行),例如 `lint-allow: LOBE-RN-DOM-UI src/components/hooks/**, src/components/styles/**`。glob 相对项目根,`**` 跨目录、`*` 不跨,以 `/` 结尾表示整个目录;只关列出的规则,行内没有规则 id 时整行忽略(不支持「全部规则」)。+- **`LOBE-RN-DOM-UI` 只报组件导入(5.6.0)**:从 `@lobehub/ui` 根入口、已知组件子入口(`/form`、`/pro-table`、`/dashboard`、`/mobile`…)或 `@lobehub/ui/es/<Component>` 导入 PascalCase 名字(具名 / 默认 / 命名空间)才报;`hooks/`、`Markdown/plugins/`、`styles`、`utils`、`types`、`locale` 等平台无关的工具子路径与 `useTheme` 这类小写导出不报。+- **托管块**:mobile 时加「平台:mobile」一节,lint 指令改为按 mobile 规则集、按项目主题修;不出现要求改用 `@lobehub/ui` / `cssVar` 的指令。+- **优先级**:项目层的平台与适用性 **优先于** skill 的通用规则;其余冲突以 skill 为准。项目层要违背通用原则(可达性、P-xx 原型)时必须在项目层写明理由——「不适用」改的是**写法**,不是原则(例如 RN 仍要 `accessibilityLabel`)。+- **Round 2**:分类方案与「UI 库」字段按平台(I-08);mobile 时 `project-scan` 把 RN 组件库(含 tsconfig alias)列为主 UI 库,`@lobehub/ui` 等 DOM 库标为「仅依赖」。diff --git a/.agents/skills/lobe-design/references/models.md b/.agents/skills/lobe-design/references/models.mdindex f078a917b34..8f3fac5c77f 100644--- a/.agents/skills/lobe-design/references/models.md+++ b/.agents/skills/lobe-design/references/models.md@@ -5,7 +5,7 @@ tier: indexscope: 经典分析模型;把模糊问题拆成可回答的问题entries:index | always | 模型索引与挂载表- M-01 | deep | 双钻,业务分析,问题定义,方案发散+ M-01 | deep | 双钻,业务分析,问题定义,方案发散,问题优先,修补M-02 | deep | 格式塔,分组,接近性,相似性M-03 | deep | 尼尔森,启发式,可用性诊断M-04 | deep | kano,必备,期望,兴奋,信息优先级@@ -40,10 +40,11 @@ entries:| Develop 发展 | 有哪几条解法 | L2 区域方案(给 2 个互斥候选)· L3 主链路 || Deliver 交付 | 做到什么程度算完成 | L5 状态清单 · L6 验收标准 |-**两个判据(防止停在第一个钻):**+**三个判据(防止停在第一个钻):**1. 写不出「这次不解决什么」→ Define 没完成。非目标是模型给出的强制字段。2. **Develop 必须给出 2 个互斥候选**(不是同一方案的两套措辞)。只有一个方案说明还在第一个钻里。+3. **先问题,后组件。** 先想清楚用户要理解什么、决定什么,再找读起来最省力的呈现方式,最后才挑组件。从现有页面、截图或组件清单出发修修补补,得到的往往是同一个问题换了个样子(截图还原除外)。**常见误用:**把双钻当成流程节点逐步汇报。它是收敛工具——探索阶段的产物必须被「决定」这一步砍掉一半。diff --git a/.agents/skills/lobe-design/scripts/bootstrap.mjs b/.agents/skills/lobe-design/scripts/bootstrap.mjsindex 519483e1232..d9c401ec7d0 100644--- a/.agents/skills/lobe-design/scripts/bootstrap.mjs+++ b/.agents/skills/lobe-design/scripts/bootstrap.mjs@@ -12,6 +12,7 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';+import { projectContext } from './platform.mjs';const skillDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');const SKILL_VERSION = readFileSync(join(skillDir, 'SKILL.md'), 'utf8').match(/^version:\s*(\S+)/m)?.[1] ?? '0.0.0';@@ -28,19 +29,36 @@ export const LOCAL_SKILL = '.agents/skills/lobe-design';export const UX_DIR = '.agents/ux';export const UX_FILES = [['product.md', '产品画像:平台、产品类型、用户、核心任务、规则适用性、文案 profile(05-init Round 1)'],- ['components.md', '组件盘点:薄包装 / 与 lobe-ui 重复 / 业务组件用法(05-init Round 2)'],+ ['components.md', '组件盘点:按平台分类(web:薄包装 / 与 lobe-ui 重复 / 业务组件;mobile:项目原子层 / 薄包装 / 业务组件)(05-init Round 2)'],['lobe-design-rules.md', '项目层规则:skill 没收录的编号(`C-` / `D-` / `K-` / `E-`)按 id 查,不要整份读'],['cases.md', '本项目的实例与判例'],['stack.md', '本项目的技术栈与组件来源'],['audit/', '审查记录'],];-/** 探测 root 下的安装位置与项目层规范。只看是否存在,不读内容。 */+/** 探测 root 下的安装位置、项目层规范与平台。项目层只看是否存在;平台读 product.md 的「平台:」行或 package.json。 */export function detectContext(root) {const localSkill = existsSync(join(root, LOCAL_SKILL));const uxRoot = join(root, UX_DIR);const ux = existsSync(uxRoot) ? UX_FILES.map(([f]) => f).filter((f) => existsSync(join(uxRoot, f.replace(/\/$/, '')))) : null;- return { localSkill, ux };+ const { platform } = projectContext(root);+ return { localSkill, ux, platform };+}++// 优先级(5.5.0):项目层的平台与适用性 > skill 通用规则 > 其余冲突以 skill 为准+export const PRECEDENCE = '**优先级**:本项目 `product.md` 里的平台与适用性(标为「不适用」的规则、按平台限定的规则)优先于 skill 的通用规则;其余冲突以 skill 为准。项目层规则要违背通用原则(可达性、P-xx 原型)时,必须在项目层写明理由。';++/** mobile(React Native)项目的平台说明:替代 web 专属指令。 */+function renderPlatform(platform) {+ if (platform !== 'mobile') return '';+ return `++### 平台:mobile(React Native)++- 原子层用本项目的组件库(\`components.md\` 里记录的那一套,例如 \`@lobehub/ui-rn\`)和 \`react-native\` 原语;**不要**改用 \`@lobehub/ui\`(DOM 组件库)。+- 样式用项目自己的主题与 \`StyleSheet\`;skill 里 \`cssVar\`、\`createStaticStyles\`、antd、CSS 类名、\`outline\`、\`font-family\`、\`<img>\` 等 web 专属条目在本项目不适用。+- 可达性照常要求:图标按钮写 \`accessibilityLabel\`,可点元素写 \`accessibilityRole\`。+- \`lint-lobe.mjs\` 自动识别平台(product.md 的「平台:」或 react-native / expo 依赖),只跑适用于 mobile 的规则。`;}/** 轻量检查项目层是否齐全(详细指纹过期见 project-scan.mjs --check)。 */@@ -73,7 +91,7 @@ export LOBE_DESIGN="./${LOCAL_SKILL}": `skill 装在自己机器上,下面所有命令都相对它执行:\`\`\`bash-# 按你的安装方式二选一(install.sh 默认装到前者)+# 按你的安装方式二选一(skill 仓库根目录的 ./install.sh 默认装到前者)export LOBE_DESIGN="\${HOME}/.claude/skills/lobe-design"# export LOBE_DESIGN="./${LOCAL_SKILL}"\`\`\``;@@ -91,12 +109,15 @@ function renderUx(ux) {const brief = hasProduct? `- 宏观指令(「整体打磨」「重做这页」)和新页面从 stage \`00-brief\` 开始:先读 \`${UX_DIR}/product.md\`,写出后续 stage 消费的页面简报;纯视觉或文案修正跳过。`: `- 宏观指令(「整体打磨」「重做这页」)和新页面从 stage \`00-brief\` 开始,写出后续 stage 消费的页面简报;纯视觉或文案修正跳过。`;- const initHint = `- **装完或升级 skill 后**:跑 stage \`05-init\`(或说「初始化 / 升级后刷新」)完成两轮自迭代——Round 1 产品画像 → \`${UX_DIR}/product.md\`,Round 2 组件盘点 → \`${UX_DIR}/components.md\`。可用 \`node "$LOBE_DESIGN/scripts/project-scan.mjs" --check\` 检查是否缺失或过期。`;+ const ref = (f) => (ux.includes(f) ? `\`${UX_DIR}/${f}\`` : `${UX_DIR}/${f}(待生成)`);+ const initHint = `- **装完或升级 skill 后**:跑 stage \`05-init\`(或说「初始化 / 升级后刷新」)完成两轮自迭代——Round 1 产品画像 → ${ref('product.md')},Round 2 组件盘点 → ${ref('components.md')}。可用 \`node "$LOBE_DESIGN/scripts/project-scan.mjs" --check\` 检查是否缺失或过期。`;return `### 项目层规范(\`${UX_DIR}/\`)-本项目的事实和补充规则放在 \`${UX_DIR}/\`,与 skill 共存:skill 管通用判据,这里管本项目;冲突时以 skill 为准。**重装 / 升级不会覆盖本目录。**+本项目的事实和补充规则放在 \`${UX_DIR}/\`,与 skill 共存:skill 管通用判据,这里管本项目。**重装 / 升级不会覆盖本目录。**++${PRECEDENCE}${lines.join('\n')}${initHint}@@ -113,20 +134,117 @@ export function findGuideFile(root) {}/** 生成托管块内容(不含首尾 marker)。 */-export function renderBlock(version = SKILL_VERSION, repo = REPO, marker = 'scripts/bootstrap.mjs', ctx = {}) {- const { localSkill = false, ux = null } = ctx;- const rulesFile = ux ? `\`${UX_DIR}/lobe-design-rules.md\`` : '项目自己的规则文件(建议 `.agents/ux/lobe-design-rules.md`)';+// ---- 5.6.0:精简模式与宿主语言 ----+// 托管块第一行记下模式与语言(块内注释,BEGIN / END 标记不变,旧安装照常识别)。有这一行时重跑沿用它;+// 没有(≤ 5.5.0 的旧块或新接入)时按默认:精简 + 宿主语言。--compact / --full / --lang 覆盖。+export const MODE_RE = /<!--\s*lobe-design:mode=(compact|full)\s+lang=(zh|en)\s*-->/;+export const modeLine = (mode, lang) => `<!-- lobe-design:mode=${mode} lang=${lang} -->`;+export function readBlockMode(fileText) {+ const i = fileText.indexOf(BEGIN), j = fileText.indexOf(END);+ if (i === -1 || j <= i) return null;+ const m = fileText.slice(i, j).match(MODE_RE);+ return m ? { mode: m[1], lang: m[2] } : null;+}+/** 宿主文本(去掉托管块与代码块)里中文字符多于英文单词 → zh,否则 en;文本太少返回 null。 */+export function detectLang(text) {+ if (!text) return null;+ const i = text.indexOf(BEGIN), j = text.indexOf(END);+ let t = i !== -1 && j > i ? text.slice(0, i) + text.slice(j + END.length) : text;+ t = t.replace(/```[\s\S]*?```/g, ' ').replace(/`[^`\n]*`/g, ' ').replace(/<!--[\s\S]*?-->/g, ' ').replace(/https?:\/\/\S+/g, ' ');+ const cjk = (t.match(/[\u3400-\u9fff]/g) ?? []).length;+ const words = (t.match(/[A-Za-z]{2,}/g) ?? []).length;+ if (cjk + words < 8) return null;+ return cjk >= words ? 'zh' : 'en';+}+/** CLI 的默认解析:flags > 已有块的模式行 > 默认(精简 + 宿主语言;宿主 AGENTS.md 内容不足时看 README;都判不了用 zh)。 */+export function resolveMode({ guideText = '', readmeText = '', compact, full, lang } = {}) {+ const prev = readBlockMode(guideText);+ const outLang = lang ?? prev?.lang ?? detectLang(guideText) ?? detectLang(readmeText) ?? 'zh';+ const outCompact = compact ? true : full ? false : prev ? prev.mode === 'compact' : true;+ return { compact: outCompact, lang: outLang };+}++const T = {+ zh: {+ title: '## UI 设计工作指南(lobe-design · 精简)',+ intro: (repo, v) => `界面相关工作(新页面、交互、视觉、设计系统、还原设计稿、上线前审查)走 **lobe-design**:\`${repo}\`(skill 版本 ${v})。`,+ local: `export LOBE_DESIGN="./${LOCAL_SKILL}" # 改用全局安装时:\${HOME}/.claude/skills/lobe-design`,+ global: `export LOBE_DESIGN="\${HOME}/.claude/skills/lobe-design" # 装在本仓库时:./${LOCAL_SKILL}`,+ entry: '- **入口**:读 `$LOBE_DESIGN/SKILL.md`;先跑 `node "$LOBE_DESIGN/scripts/route.mjs" "<指令原文>"`,一次只进一个 stage,只读它列出的条目。',+ layer: (p, c) => p || c+ ? `- **先读项目层**:${[p && `\`${UX_DIR}/product.md\`(平台与适用性)`, c && `\`${UX_DIR}/components.md\`(用哪个组件)`].filter(Boolean).join('、')};缺的那份跑 05-init 补上。`+ : '- **先读项目层**:还没有时先跑 05-init,生成 .agents/ux/ 下的 product.md(平台与适用性)与 components.md(用哪个组件)。',+ web: '- **平台:web**:原子层取自 `@lobehub/ui`,取值走 `cssVar`。',+ mobile: '- **平台:mobile(React Native)**:原子层用项目组件库(如 `@lobehub/ui-rn`)与 `react-native` 原语,取值走 `useTheme()` token;skill 里 web 专属的条目(`@lobehub/ui` 原子层、`cssVar`、`createStaticStyles`、antd、CSS 类名)在本项目不适用。',+ precedence: () => `- ${PRECEDENCE}`,+ lint: (m) => `- **改完代码**:跑 \`node "$LOBE_DESIGN/scripts/lint-lobe.mjs" <改动路径>\`(按 product.md 的平台自动选规则集),FAIL 必须修${m ? ',修法用本项目的主题与组件库' : ''}。`,+ learn: (rules) => `- **纠正要沉淀**:写进${rules};判据、选层与回流见 \`$LOBE_DESIGN/learnings/README.md\`、\`$LOBE_DESIGN/CONTRIBUTING.md\`。`,+ init: '- **装完 / 升级后**:跑 05-init 两轮;`node "$LOBE_DESIGN/scripts/project-scan.mjs" --check` 查项目层是否缺失或过期。',+ rulesHas: ` \`${UX_DIR}/lobe-design-rules.md\``,+ rulesNew: '项目自己的规则文件(建议新建 .agents/ux/lobe-design-rules.md)',+ footer: (marker) => `> 本块由 \`${marker}\` 维护,重新运行可更新;加 \`--full\` 输出完整版(含自迭代与回流细则)。`,+ },+ en: {+ title: '## UI design guide (lobe-design · compact)',+ intro: (repo, v) => `UI work (new pages, interaction, visuals, design-system cleanup, screenshot restore, pre-launch review) goes through **lobe-design**: \`${repo}\` (skill version ${v}).`,+ local: `export LOBE_DESIGN="./${LOCAL_SKILL}" # global install: \${HOME}/.claude/skills/lobe-design`,+ global: `export LOBE_DESIGN="\${HOME}/.claude/skills/lobe-design" # installed in this repo: ./${LOCAL_SKILL}`,+ entry: '- **Entry**: read `$LOBE_DESIGN/SKILL.md`; run `node "$LOBE_DESIGN/scripts/route.mjs" "<request verbatim>"` first, then enter one stage at a time and load only what it lists.',+ layer: (p, c) => p || c+ ? `- **Read the project layer first**: ${[p && `\`${UX_DIR}/product.md\` (platform and applicability)`, c && `\`${UX_DIR}/components.md\` (which component to use)`].filter(Boolean).join(', ')}; run 05-init to create any missing one.`+ : '- **Read the project layer first**: if it does not exist yet, run 05-init to create product.md (platform and applicability) and components.md (which component to use) under .agents/ux/.',+ web: '- **Platform: web**: atoms come from `@lobehub/ui`; values come from `cssVar` tokens.',+ mobile: '- **Platform: mobile (React Native)**: atoms come from the project component library (e.g. `@lobehub/ui-rn`) and `react-native` primitives; values come from `useTheme()` tokens. Web-only skill items (`@lobehub/ui` atoms, `cssVar`, `createStaticStyles`, antd, CSS class names) do not apply here.',+ precedence: () => '- **Precedence**: platform and applicability in `product.md` (rules marked not applicable, platform-scoped rules) override the skill\'s generic rules; other conflicts follow the skill. A project rule that contradicts a universal principle (accessibility, P-xx archetypes) must state its reason.',+ lint: (m) => `- **After code changes**: run \`node "$LOBE_DESIGN/scripts/lint-lobe.mjs" <changed paths>\` (rule set follows the platform in product.md); every FAIL must be fixed${m ? ' using the project theme and component library' : ''}.`,+ learn: (rules) => `- **Record corrections**: in ${rules}; criteria, layering and upstreaming are in \`$LOBE_DESIGN/learnings/README.md\` and \`$LOBE_DESIGN/CONTRIBUTING.md\`.`,+ init: '- **After install or upgrade**: run 05-init (two rounds); `node "$LOBE_DESIGN/scripts/project-scan.mjs" --check` reports a missing or stale project layer.',+ rulesHas: `\`${UX_DIR}/lobe-design-rules.md\``,+ rulesNew: 'the project rules file (suggested: create .agents/ux/lobe-design-rules.md)',+ footer: (marker) => `> Managed by \`${marker}\`; rerun to update. Pass \`--full\` for the detailed (Chinese) version with self-iteration and upstreaming rules.`,+ },+};++/** 精简托管块(~16 行):入口、先读项目层、平台与适用性、优先级、lint、沉淀、升级。 */+export function renderCompact(version, repo, marker, ctx = {}) {+ const { localSkill = false, ux = null, platform = 'web', lang = 'zh' } = ctx;+ const L = T[lang] ?? T.zh, mobile = platform === 'mobile';+ const rules = ux?.includes('lobe-design-rules.md') ? L.rulesHas : L.rulesNew;+ return [+ modeLine('compact', lang in T ? lang : 'zh'),+ L.title, '', L.intro(repo, version), '',+ '```bash', localSkill ? L.local : L.global, '```', '',+ L.entry, L.layer(ux?.includes('product.md'), ux?.includes('components.md')),+ mobile ? L.mobile : L.web, L.precedence(), L.lint(mobile), L.learn(rules), L.init, '',+ L.footer(marker),+ ].join('\n');+}++export function renderBlock(version = SKILL_VERSION, repo = REPO, marker = '$LOBE_DESIGN/scripts/bootstrap.mjs', ctx = {}) {+ if (ctx.compact) return renderCompact(version, repo, marker, ctx);+ const { localSkill = false, ux = null, platform = 'web' } = ctx;+ const mobile = platform === 'mobile';+ // 尚不存在的项目层文件不写成代码样式的路径(宿主的路径检查会把它当成死链)+ const rulesFile = ux?.includes('lobe-design-rules.md') ? `\`${UX_DIR}/lobe-design-rules.md\`` : '项目自己的规则文件(建议新建 .agents/ux/lobe-design-rules.md)';+ const hasP = ux?.includes('product.md'), hasC = ux?.includes('components.md');+ const lintLine = mobile+ ? `- 改过代码的 stage,结束前跑 \`node "$LOBE_DESIGN/scripts/lint-lobe.mjs" <改动路径>\`(按 mobile 规则集运行),FAIL 必须修;修法用本项目的主题与组件库,不要改成 web 写法。`+ : `- 改过代码的 stage,结束前跑 \`node "$LOBE_DESIGN/scripts/lint-lobe.mjs" <改动路径>\`,FAIL 必须修。`;+ const readLayer = hasP || hasC+ ? `- **做界面前先读项目层**:${[hasP && `\`${UX_DIR}/product.md\`(画像与适用性)`, hasC && `\`${UX_DIR}/components.md\`(用哪个组件)`].filter(Boolean).join('、')};缺的那份先跑 05-init 补上。`+ : '- **做界面前先读项目层**:还没有项目层时,先跑 05-init 生成 .agents/ux/ 下的 product.md(画像与适用性)与 components.md(用哪个组件)。';const initLine = ux? '': `-> **装完或升级后先初始化**:对 Agent 说「把项目接上 lobe-design」或跑 bootstrap 场景,完成 AGENTS.md 托管块 + 两轮项目层画像(\`.agents/ux/product.md\` / \`components.md\`)。可用 \`node "$LOBE_DESIGN/scripts/project-scan.mjs" --check\` 检查项目层。+> **装完或升级后先初始化**:对 Agent 说「把项目接上 lobe-design」或跑 bootstrap 场景,完成 AGENTS.md 托管块 + 两轮项目层画像(.agents/ux/ 下的 product.md / components.md)。可用 \`node "$LOBE_DESIGN/scripts/project-scan.mjs" --check\` 检查项目层。`;- return `## UI 设计工作指南(lobe-design)+ // 完整版只有中文;ctx.mode 存在(CLI 路径)时写模式行,便于重跑沿用+ return `${ctx.mode ? `${modeLine('full', 'zh')}\n` : ''}## UI 设计工作指南(lobe-design)本项目在做界面相关工作(新增页面、改交互、调视觉、统一设计系统、还原设计稿、上线前审查)时,走 **lobe-design** 这条单入口 pipeline。安装:\`${repo}\`(skill 版本 ${version})。${initLine}-${renderInstall(localSkill)}${renderUx(ux)}+${renderInstall(localSkill)}${renderUx(ux)}${renderPlatform(platform)}### 1. 入口与顺序@@ -135,11 +253,11 @@ ${renderInstall(localSkill)}${renderUx(ux)}node "$LOBE_DESIGN/scripts/route.mjs" "<用户指令原文>" # 场景 / 颗粒度 / stage 序列node "$LOBE_DESIGN/scripts/refs.mjs" "<用户指令原文>" # 每个 stage 该读哪些条目\`\`\`-- 路由器读取 \`scripts/pipeline.json\`(唯一事实源)。结果是默认值;结合上下文调整时要在输出里说明理由。+- 路由器读取 \`$LOBE_DESIGN/scripts/pipeline.json\`(唯一事实源)。结果是默认值;结合上下文调整时要在输出里说明理由。- **一次只进一个 stage。** 进入时才读它「只加载」列出的条目,不要一开始就把 references 读完。- 每个 stage 只回答一个问题。看到别的问题,只记一行 \`遗留 → <stage>\`,不要顺手改。-- 改过代码的 stage,结束前跑 \`node "$LOBE_DESIGN/scripts/lint-lobe.mjs" <改动路径>\`,FAIL 必须修。-- **做界面前先读项目层**(若已有):\`${UX_DIR}/product.md\`(画像与适用性)、\`${UX_DIR}/components.md\`(用哪个组件);没有则先跑 05-init。+${lintLine}+${readLayer}${ux ? '' : `\n- ${PRECEDENCE}`}### 2. 什么时候用@@ -185,20 +303,6 @@ ${renderInstall(localSkill)}${renderUx(ux)}/** 把托管块插入 / 替换到 fileText,返回 { text, action }。块外内容不变。 */-// 比较托管块内容时只抹平格式化工具(prettier、remark 等)会做的改写:行首尾空白、空行、连续空白、-// 表格单元格两侧的补齐空格与分隔线长度、中点写法(· / ・)、中文与其他字符之间的空格(remark 的中英文间距)。-// 两个 ASCII 字符之间的空白保留:命令里删掉空格仍算漂移。-export function blockMatches(fileText, block) {- const start = fileText.indexOf(BEGIN);- const end = fileText.indexOf(END);- if (start === -1 || end === -1 || end < start) return false;- const norm = (s) => s.split('\n')- .map((l) => l.trim().replace(/\s+/g, ' ').replace(/ ?\| ?/g, '|').replace(/-{3,}/g, '---').replace(/ ?[·・] ?/g, '·').replace(/ (?=[^\x00-\x7f])|(?<=[^\x00-\x7f]) /g, ''))- .filter(Boolean)- .join('\n');- return norm(fileText.slice(start + BEGIN.length, end)) === norm(block);-}-export function applyBlock(fileText, block) {const managed = `${BEGIN}\n${block}\n${END}`;const start = fileText.indexOf(BEGIN);@@ -220,9 +324,15 @@ function main() {用法node scripts/bootstrap.mjs 探测并写入托管块(已有内容不动)- node scripts/bootstrap.mjs --check 只检查,不写;块缺失、版本落后或内容过期 → exit 1;项目层缺失/过期 → WARN+ node scripts/bootstrap.mjs --check 只检查,不写;块缺失或版本落后 → exit 1;项目层缺失/过期 → WARNnode scripts/bootstrap.mjs --print 打印将要写入的内容,不落盘node scripts/bootstrap.mjs --root <dir> 指定项目根目录(默认当前目录)+ --compact | --full 精简块(~16 行,默认)| 完整块(含自迭代 / 回流细则,中文)+ --lang zh|en 精简块的语言;默认按宿主 AGENTS.md(不足时看 README)的语言++默认与沿用+ 新接入或 ≤ 5.5.0 的旧块:精简 + 宿主语言。块内第一行记下 <!-- lobe-design:mode=… lang=… -->,+ 之后重跑沿用它;显式 --compact / --full / --lang 覆盖并改写这一行。BEGIN / END 标记不变。--json JSON 输出托管块@@ -232,7 +342,7 @@ function main() {退出码0 成功 / 已是最新(项目层 WARN 不改变退出码)- 1 --check 失败(未接入、版本落后或托管块内容过期)+ 1 --check 失败(未接入或版本落后)2 用法错误`);process.exit(0);}@@ -240,26 +350,30 @@ function main() {const json = args.includes('--json');if (!existsSync(root)) { console.error(`用法错误:目录不存在:${root}`); process.exit(2); }+ const lang = args.includes('--lang') ? args[args.indexOf('--lang') + 1] : undefined;+ if (lang && !['zh', 'en'].includes(lang)) { console.error(`用法错误:--lang 只支持 zh | en(收到 ${lang})`); process.exit(2); }+ if (args.includes('--compact') && args.includes('--full')) { console.error('用法错误:--compact 与 --full 只能选一个'); process.exit(2); }const guide = findGuideFile(root);- const block = renderBlock(SKILL_VERSION, REPO, 'scripts/bootstrap.mjs', detectContext(root));const before = guide.existed ? readFileSync(guide.path, 'utf8') : '';+ const readmePath = ['README.md', 'readme.md'].map((f) => join(root, f)).find((f) => existsSync(f));+ const mode = resolveMode({ guideText: before, readmeText: readmePath ? readFileSync(readmePath, 'utf8') : '', compact: args.includes('--compact'), full: args.includes('--full'), lang });+ if (!mode.compact && mode.lang === 'en') console.warn('提示:完整版托管块只有中文;英文请用精简模式(默认)。');+ const block = renderBlock(SKILL_VERSION, REPO, '$LOBE_DESIGN/scripts/bootstrap.mjs', { ...detectContext(root), ...mode, mode: true });const { text, action } = applyBlock(before, block);- const versionLine = before.match(/skill 版本 (\S+?)[))]/)?.[1];+ const versionLine = before.match(/skill (?:版本|version) (\S+?)[))]/)?.[1];const upToDate = action === 'unchanged' && versionLine === SKILL_VERSION;const projectLayer = detectProjectLayer(root);if (args.includes('--print')) { console.log(block); process.exit(0); }if (args.includes('--check')) {- // --check 的语义是「已接入且托管块最新」:文件不存在、块缺失、版本落后、块内容与当前渲染结果不一致都算没接入。+ // --check 的语义是「已接入且版本最新」:文件不存在、块缺失、版本落后都算没接入。// 项目层缺失 / 过期只 WARN,不单独把已接入判成 FAIL(由 project-scan --check 严格查)。- const blockCurrent = blockMatches(before, block);- const ok = Boolean(guide.existed) && before.includes(BEGIN) && versionLine === SKILL_VERSION && blockCurrent;- const out = { root, file: guide.name, existed: guide.existed, action, version: SKILL_VERSION, foundVersion: versionLine ?? null, blockCurrent, ok, projectLayer };+ const ok = Boolean(guide.existed) && before.includes(BEGIN) && versionLine === SKILL_VERSION;+ const out = { root, file: guide.name, existed: guide.existed, action, version: SKILL_VERSION, foundVersion: versionLine ?? null, ok, projectLayer };if (json) console.log(JSON.stringify(out, null, 2));else {if (ok) console.log(`OK ${guide.name} 已接入(skill ${SKILL_VERSION},托管块最新)`);- else if (before.includes(BEGIN) && versionLine === SKILL_VERSION) console.error(`FAIL ${guide.name} 托管块内容已过期(与当前渲染结果不一致,例如项目层变化后未重跑)。运行 node scripts/bootstrap.mjs 修复。`);else console.error(`FAIL ${guide.name} 未接入或版本落后(当前 ${versionLine ?? '无托管块'} → ${SKILL_VERSION})。运行 node scripts/bootstrap.mjs 修复。`);if (projectLayer.missing.length) console.warn(`WARN 项目层缺失:${projectLayer.missing.join(', ')}(对 Agent 说「初始化 lobe-design」跑 05-init 两轮)`);for (const s of projectLayer.stale) console.warn(`WARN 项目层过期:${s}`);@@ -271,10 +385,10 @@ function main() {mkdirSync(dirname(guide.path), { recursive: true });writeFileSync(guide.path, text);}- const result = { root, file: guide.name, action, version: SKILL_VERSION, created: !guide.existed, projectLayer };+ const result = { root, file: guide.name, action, version: SKILL_VERSION, created: !guide.existed, mode: mode.compact ? 'compact' : 'full', lang: mode.compact ? mode.lang : 'zh', projectLayer };if (json) console.log(JSON.stringify(result, null, 2));else {- console.log(`${guide.existed ? '更新' : '建立'} ${guide.name}:托管块 ${action}(skill ${SKILL_VERSION})\n块外内容未改动。`);+ console.log(`${guide.existed ? '更新' : '建立'} ${guide.name}:托管块 ${action}(skill ${SKILL_VERSION},${mode.compact ? `精简 · ${mode.lang}` : '完整 · zh'})\n块外内容未改动。`);if (projectLayer.missing.length) console.log(`提示:项目层尚未建立(缺 ${projectLayer.missing.join(', ')})。请让 Agent 跑 05-init 两轮,或 node "$LOBE_DESIGN/scripts/project-scan.mjs" --check。`);}}diff --git a/.agents/skills/lobe-design/scripts/check-detail.mjs b/.agents/skills/lobe-design/scripts/check-detail.mjsindex 5798f7411de..5a61967b8be 100755--- a/.agents/skills/lobe-design/scripts/check-detail.mjs+++ b/.agents/skills/lobe-design/scripts/check-detail.mjs@@ -3,10 +3,9 @@// Usage: node scripts/check-detail.mjs <path...> [--json] (see --help)// Per-file heuristics: "if the file does X, it must also handle Y". FAIL only for loading / error;// everything else is WARN because it is a heuristic and may be handled in a parent component.-import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs';+import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';import { extname, join, relative } from 'node:path';import { fileURLToPath } from 'node:url';-import { ignores } from './lint-lobe.mjs';const FETCH = /\b(useSWR\w*|useQuery|useInfiniteQuery|useRequest|useClientDataSWR|\.useQuery\(|fetch\(|axios\.|lambdaClient\.|trpc\.)/;const LOADING = /\b(isLoading|loading|isFetching|isValidating|Skeleton|Spin|LoadingDots|pending|isPending)\b/;@@ -48,24 +47,18 @@ ${CHECKS.map((c) => ` ${c.level.padEnd(4)} ${c.id.padEnd(27)} ${c.ref.padEnd(6)豁免:文件内写 // lobe-design-ignore DETAIL-NO-EMPTY: <理由>(例如空态由父组件处理)`;const EXTS = new Set(['.tsx', '.jsx']);-// 与 lint-lobe 一致:遍历中遇到的软链目录跳过,避免重复扫描-function walk(p, out = [], top = true) {- if (!top && lstatSync(p).isSymbolicLink() && statSync(p).isDirectory()) return out;+function walk(p, out = []) {const st = statSync(p);- if (st.isDirectory()) { for (const n of readdirSync(p)) if (!['node_modules', '.git', 'dist', '.backup'].includes(n)) walk(join(p, n), out, false); }+ if (st.isDirectory()) { for (const n of readdirSync(p)) if (!['node_modules', '.git', 'dist', '.backup'].includes(n)) walk(join(p, n), out); }else if (EXTS.has(extname(p)) && !/\.(test|spec|stories)\.[jt]sx?$/.test(p)) out.push(p);return out;}-// 豁免必须是注释里的 `lobe-design-ignore ID[,ID]: <理由>`;没写理由不生效(解析与 lint-lobe 共用)-const suppressedIds = (raw) => new Set(raw.split('\n').flatMap((l) => ignores(l).filter((g) => g.reason).flatMap((g) => g.ids)));-export function checkText(raw, file = '<text>') {const findings = [];- const suppressed = suppressedIds(raw);const text = raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');for (const c of CHECKS) {- if (suppressed.has(c.id)) continue;+ if (raw.includes(`lobe-design-ignore ${c.id}`)) continue;if (c.when.test(text) && !c.need.test(text)) findings.push({ file, id: c.id, level: c.level, ref: c.ref, dim: c.dim, msg: c.msg });}return findings;diff --git a/.agents/skills/lobe-design/scripts/check-learnings.mjs b/.agents/skills/lobe-design/scripts/check-learnings.mjsindex e5e56bac4fe..9b981c3d035 100755--- a/.agents/skills/lobe-design/scripts/check-learnings.mjs+++ b/.agents/skills/lobe-design/scripts/check-learnings.mjs@@ -68,7 +68,7 @@ function definedRefIds() {function fixtureExpectations() {const map = new Map(); // id -> [file:line]const dir = join(skillDir, 'tests/fixtures');- for (const f of readdirSync(dir)) {+ for (const f of readdirSync(dir, { withFileTypes: true }).filter((d) => d.isFile()).map((d) => d.name)) {const lines = readFileSync(join(dir, f), 'utf8').split('\n');lines.forEach((l, i) => {const m = l.match(/expect(?:-file)?:\s*([A-Z0-9\- ]+)/);diff --git a/.agents/skills/lobe-design/scripts/lint-lobe.mjs b/.agents/skills/lobe-design/scripts/lint-lobe.mjsindex 6879af3c00e..dbad2fcc1fa 100755--- a/.agents/skills/lobe-design/scripts/lint-lobe.mjs+++ b/.agents/skills/lobe-design/scripts/lint-lobe.mjs@@ -4,12 +4,37 @@// Exit 1 when any FAIL. Suppress a finding with a comment on the same or previous line:// // lobe-design-ignore LOBE-RAW-COLOR: <reason>// Every rule names the reference rule it enforces, so a finding routes to exactly one stage.-import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs';-import { extname, join, relative } from 'node:path';+import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';+import { extname, join, relative, sep } from 'node:path';import { fileURLToPath } from 'node:url';+import { findProjectRoot, projectContext } from './platform.mjs';// lobe-ui 应用不依赖 antd / antd-style:组件与样式 API 都从 @lobehub/ui 取。const ANTD_SOURCE = /^(?:antd|antd-style)(?:\/[^'"]*)?$/;+// 平台作用域:每条规则声明 platforms(缺省 = 全平台)。web 专属的是 CSS / DOM / lobe-ui(DOM) / antd 相关检查;+// RN / mobile 项目跳过它们(见 scripts/platform.mjs 与 references/init.md I-10)。+export const WEB = ['web', 'desktop'];+export const ALL = ['web', 'desktop', 'mobile'];+// LOBE-RN-DOM-UI(5.6.0):只报「组件导入」——从组件入口导入 PascalCase 名字(具名 / 默认 / 命名空间)。+// 平台无关的工具(hooks、Markdown 插件、styles / 颜色种子、utils、types、locale)不报:RN 复用它们是正当的。+const DOM_UI_SRC = /^(?:@lobehub\/ui|antd)(?:\/(.*))?$/;+const DOM_UTIL_SEG = /^(?:hooks?|utils?|plugins?|styles?|types?|locales?|i18n|helpers?|constants?|theme|colou?rs?|seeds?|interface|const|tokens?)$|^use[A-Z]|\.(?:css|less|json)$/;+const DOM_UI_ENTRIES = new Set(['form', 'pro-table', 'dashboard', 'mobile', 'awesome', 'chat', 'icons', 'base-ui', 'mdx', 'brand']);+const isPascal = (n) => /^[A-Z][A-Za-z0-9]*$/.test(n);+export function isDomComponentImport(src, clause) {+ const m = src.match(DOM_UI_SRC);+ if (!m || !clause?.trim()) return false; // 副作用导入(css)不算组件+ const segs = (m[1] ?? '').split('/').filter(Boolean);+ const rest = /^(?:es|lib|esm|cjs)$/.test(segs[0] ?? '') ? segs.slice(1) : segs;+ if (rest.some((x) => DOM_UTIL_SEG.test(x))) return false;+ // 子路径必须是组件入口:已知入口(form / pro-table…)或 es/<PascalCase>[/index]+ if (rest.length && !(DOM_UI_ENTRIES.has(rest[0]) || (isPascal(rest[0]) && rest.slice(1).every((x) => x === 'index'))) ) return false;+ const named = clause.match(/\{([^}]*)\}/)?.[1] ?? '';+ const head = clause.replace(/\{[^}]*\}/, '').split(',').map((x) => x.trim()).filter(Boolean);+ if (head.some((h) => /^\*\s+as\s+/.test(h) || isPascal(h))) return true; // 默认 / 命名空间+ return named.split(',').map((x) => x.trim()).filter((x) => x && !/^type\s/.test(x)).some((x) => { const n = x.split(/\s+as\s+/)[0]; return n === 'default' || isPascal(n); });+}+const PURPLE_NAMES = /\b(purple|violet|indigo|fuchsia)\b/i;function hexHue(hex) {@@ -73,21 +98,6 @@ function fontFamilyViolation(l) {return !branches.every((b) => FONT_OK.test(b.trim().replace(/[;,]$/, '')));}-// LOBE-RAW-COLOR:只报会被渲染出来的颜色。全透明(alpha 为 0,如 rgba(0,0,0,0) / #0000)不报,-// 它等同 transparent,常作「无背景」哨兵值;作为 === / !== 比较操作数的颜色字符串也不报,它是输入判断不是样式。-const RAW_HEX = /(^|[^&\w])#([0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b/g;-const RAW_RGB = /\brgba?\(\s*\d[^)]*\)?/g;-const COLOR_COMPARE = /[!=]==?\s*(['"`])(?:#|rgba?\()[^'"`]*\1|(['"`])(?:#|rgba?\()[^'"`]*\2\s*[!=]==?/g;-function rawColorViolation(l) {- if (/^\s*import\b/.test(l)) return false;- const rest = l.replace(COLOR_COMPARE, '');- const hexes = [...rest.matchAll(RAW_HEX)].map((m) => m[2]);- const rgbs = [...rest.matchAll(RAW_RGB)].map((m) => m[0]);- const transparentHex = (h) => (h.length === 4 && h[3] === '0') || (h.length === 8 && h.slice(6) === '00');- const transparentRgb = (c) => { const p = c.replace(/^rgba?\(|\)$/g, '').split(/[\s,/]+/).filter(Boolean); return p.length === 4 && parseFloat(p[3]) === 0; };- return hexes.some((h) => !transparentHex(h)) || rgbs.some((c) => !transparentRgb(c));-}-// LOBE-OUTLINE-NONE:只在可能被键盘聚焦的元素上报。看所在样式块(css`` 模板,或前后 12 行):// - 块里是不可聚焦的 SVG 图形(path / Geography 等)且没有 tabIndex、交互元素时,不报;// - 块里有 :focus-visible / focus 态的可见替代(box-shadow、border、非 none 的 outline)时,不报。@@ -119,23 +129,23 @@ function outlineNoneHits(text) {export const RULES = [// ---- 30-structure (C-/D-01/K-10) ----- { id: 'LOBE-ANTD-IMPORT', level: 'FAIL', ref: 'C-01', stage: '30-structure', kind: 'text',+ { id: 'LOBE-ANTD-IMPORT', platforms: WEB, level: 'FAIL', ref: 'C-01', stage: '30-structure', kind: 'text',msg: 'lobe-ui 应用不用 antd / antd-style:组件从 @lobehub/ui 导入(提示用 toast),createStaticStyles / cssVar / cx / useTheme 也从 @lobehub/ui 导入',test: (t) => [...t.matchAll(/import\s+(?:type\s+)?[^;'"]*?\bfrom\s*['"]([^'"]+)['"]/g)].filter((m) => ANTD_SOURCE.test(m[1])).map((m) => ({ index: m.index, match: m[0].replace(/\s+/g, ' ') })) },- { id: 'LOBE-FORM-ENTRY', level: 'FAIL', ref: 'C-02', stage: '30-structure', kind: 'text',+ { id: 'LOBE-FORM-ENTRY', platforms: WEB, level: 'FAIL', ref: 'C-02', stage: '30-structure', kind: 'text',msg: 'Form 从 @lobehub/ui/form 导入(根入口的 Form 不带校验)',test: (t) => [...t.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@lobehub\/ui['"]/g)].filter((m) => m[1].split(',').map((s) => s.trim().split(/\s+as\s+/)[0]).includes('Form')).map((m) => ({ index: m.index, match: m[0].replace(/\s+/g, ' ') })) },- { id: 'LOBE-ANT-ICONS', level: 'FAIL', ref: 'C-01', stage: '30-structure', kind: 'line',+ { id: 'LOBE-ANT-ICONS', platforms: WEB, level: 'FAIL', ref: 'C-01', stage: '30-structure', kind: 'line',msg: '图标用 lucide-react + Icon,不用 @ant-design/icons', test: (l) => /from\s*['"]@ant-design\/icons/.test(l) },- { id: 'LOBE-CREATE-STYLES', level: 'FAIL', ref: 'D-01', stage: '30-structure', kind: 'line',+ { id: 'LOBE-CREATE-STYLES', platforms: WEB, level: 'FAIL', ref: 'D-01', stage: '30-structure', kind: 'line',msg: '样式用 createStaticStyles + cssVar(从 @lobehub/ui 导入),不用 createStyles', test: (l) => /\bcreateStyles\b/.test(l) },- { id: 'LOBE-I18N-PROVIDER', level: 'WARN', ref: 'C-01', stage: '30-structure', kind: 'line',+ { id: 'LOBE-I18N-PROVIDER', platforms: WEB, level: 'WARN', ref: 'C-01', stage: '30-structure', kind: 'line',msg: '不要嵌套 I18nProvider;文案通过 ConfigProvider 的 resources 提供', test: (l) => /<I18nProvider\b/.test(l) },- { id: 'LOBE-CSS-LINE-COMMENT', level: 'FAIL', ref: 'K-10', stage: '30-structure', kind: 'text', raw: true,+ { id: 'LOBE-CSS-LINE-COMMENT', platforms: WEB, level: 'FAIL', ref: 'K-10', stage: '30-structure', kind: 'text', raw: true,msg: 'css 模板里 // 不是注释;改用 /* */',test: (t) => {const out = [];@@ -145,19 +155,20 @@ export const RULES = [}return out;} },- { id: 'LOBE-ANT-CLASS', level: 'WARN', ref: 'D-10', stage: '30-structure', kind: 'line',+ { id: 'LOBE-ANT-CLASS', platforms: WEB, level: 'WARN', ref: 'D-10', stage: '30-structure', kind: 'line',msg: '写了 .ant- 类名(lobe-ui 不渲染这类类名);用 className / classNames 槽位、组件文档里的 data-* 属性,不对就修上游', test: (l) => /\.ant-[a-z]/.test(l) },- { id: 'LOBE-ANT-VAR-OVERRIDE', level: 'FAIL', ref: 'D-07', stage: '30-structure', kind: 'line',+ { id: 'LOBE-ANT-VAR-OVERRIDE', platforms: WEB, level: 'FAIL', ref: 'D-07', stage: '30-structure', kind: 'line',msg: '用 !important 覆盖了主题变量;品牌走 data-primary-color / data-neutral-color(setLobeTheme / LobeThemeScript / ThemeScope)', test: (l) => /--(?:ant|lobe)-[\w-]+\s*:[^;]*!important/.test(l) },- { id: 'LOBE-REIMPLEMENT-ATOM', level: 'WARN', ref: 'C-11', stage: '30-structure', kind: 'line', since: '3.0.0',+ { id: 'LOBE-REIMPLEMENT-ATOM', platforms: WEB, level: 'WARN', ref: 'C-11', stage: '30-structure', kind: 'line', since: '3.0.0',msg: '在项目里重新实现了原子层组件(Button/Modal/Table/Input…);原子层必须从 @lobehub/ui 取用,业务组合才自建',test: (l) => /^\s*(export\s+)?(const|function)\s+(Button|Modal|Drawer|Table|Input|Select|Checkbox|Radio|Switch|Tabs|Tooltip|Popover|Tag|Badge|Avatar|Skeleton|Pagination|Divider|Progress|Spin|Empty)\b/.test(l) },// ---- 50-visual (D-/K-/A-) ----{ id: 'LOBE-RAW-COLOR', level: 'FAIL', ref: 'D-10', stage: '50-visual', kind: 'line',msg: '裸 hex / rgba;改用 cssVar token,找不到就按 D-11 写缺口',- test: (l) => rawColorViolation(l) },- { id: 'LOBE-FONT-FAMILY', level: 'FAIL', ref: 'K-02', stage: '50-visual', kind: 'line',+ msgMobile: '裸 hex / rgba;改用项目主题 token(RN:useTheme() / theme.colorXxx,来自项目自己的主题或 @lobehub/ui-rn),找不到就按 D-11 写缺口',+ test: (l) => !/^\s*import\b/.test(l) && (/(^|[^&\w])#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b/.test(l) || /\brgba?\(\s*\d/.test(l)) },+ { id: 'LOBE-FONT-FAMILY', platforms: WEB, level: 'FAIL', ref: 'K-02', stage: '50-visual', kind: 'line',msg: '组件里写了 font-family;字体由主题提供(theme.css,自定义字体走 ConfigProvider customFonts;代码用 cssVar.fontFamilyCode)',test: (l) => fontFamilyViolation(l) },{ id: 'LOBE-TRANSITION-ALL', level: 'WARN', ref: 'K-06', stage: '50-visual', kind: 'line',@@ -182,18 +193,18 @@ export const RULES = [{ id: 'LOBE-PURPLE-GRADIENT', level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',msg: '紫 / 靛起手渐变(AI 味);品牌时刻用 gradientAnimation,其余用中性底',test: (l) => /gradient\(/.test(l) && (PURPLE_NAMES.test(l) || [...l.matchAll(/#[0-9a-fA-F]{3,8}\b/g)].some((m) => isPurpleish(m[0]))) },- { id: 'LOBE-GRADIENT-TEXT', level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',+ { id: 'LOBE-GRADIENT-TEXT', platforms: WEB, level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',msg: '渐变文字(AI 味);标题用实色,强调靠字号和字重', test: (l) => /background-clip\s*:\s*text|[bB]ackgroundClip\s*:\s*['"]text/.test(l) },- { id: 'LOBE-EYEBROW', level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',+ { id: 'LOBE-EYEBROW', platforms: WEB, level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',msg: 'eyebrow / kicker 小标签(AI 味);删掉或并入标题', test: (l) => /class(Name)?=\s*[{'"`][^>]*\b(eyebrow|kicker)\b/i.test(l) },{ id: 'LOBE-UPPERCASE', level: 'WARN', ref: 'K-02', stage: '50-visual', kind: 'line',msg: '中文界面不用 uppercase 标签', test: (l) => /text-transform\s*:\s*uppercase|textTransform\s*:\s*['"]uppercase/.test(l) },- { id: 'LOBE-GLOW', level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',+ { id: 'LOBE-GLOW', platforms: WEB, level: 'FAIL', ref: 'A-04', stage: '50-visual', kind: 'line',msg: '0 偏移彩色光晕阴影(AI 味);阴影按档位',test: (l) => /box-?[sS]hadow\s*:\s*['"`]?\s*0(px)?\s+0(px)?\s+\d+px[^;'"`]*(#[0-9a-fA-F]{3,8}|rgba?\(\s*(?!0\s*,\s*0\s*,\s*0)|cssVar\.color(Primary|Info|Success|Warning|Error))/.test(l) },- { id: 'LOBE-BLUR-CARD', level: 'WARN', ref: 'K-04', stage: '50-visual', kind: 'line',+ { id: 'LOBE-BLUR-CARD', platforms: WEB, level: 'WARN', ref: 'K-04', stage: '50-visual', kind: 'line',msg: 'backdrop-filter:确认它是浮层或贴顶表面,否则删掉(玻璃只给浮层)', test: (l) => /backdrop-filter|backdropFilter/.test(l) },- { id: 'LOBE-SIDE-STRIPE', level: 'WARN', ref: 'A-04', stage: '50-visual', kind: 'line',+ { id: 'LOBE-SIDE-STRIPE', platforms: WEB, level: 'WARN', ref: 'A-04', stage: '50-visual', kind: 'line',msg: '>1px 的彩色侧边竖条;用 Alert type 或 图标 + 文字', test: (l) => /border-(left|inline-start)\s*:\s*([2-9]|\d{2,})px/.test(l) },{ id: 'LOBE-EMOJI-ICON', level: 'WARN', ref: 'A-04', stage: '50-visual', kind: 'line',msg: 'emoji 当图标 / 列表符号;用 lucide-react + Icon', test: (l) => />\s*\p{Extended_Pictographic}/u.test(l) },@@ -201,17 +212,18 @@ export const RULES = [msg: '占位文案;用贴近真实业务的数据', test: (l) => /lorem ipsum|示例数据|功能名称|示例文本/i.test(l) },// ---- 70-detail (K-05/K-07/W-) ----- { id: 'LOBE-OUTLINE-NONE', level: 'FAIL', ref: 'K-07', stage: '70-detail', kind: 'text',+ { id: 'LOBE-OUTLINE-NONE', platforms: WEB, level: 'FAIL', ref: 'K-07', stage: '70-detail', kind: 'text',msg: 'outline: none 抹掉了全局焦点环;需要退出时用 data-lobe-focus-ring="off" 并补等价指示(不可聚焦的 SVG 图形、同一块里有 :focus-visible 替代指示时不报)',test: (t) => outlineNoneHits(t) },- { id: 'LOBE-IMG-ALT', level: 'FAIL', ref: 'K-07', stage: '70-detail', kind: 'text',+ { id: 'LOBE-IMG-ALT', platforms: WEB, level: 'FAIL', ref: 'K-07', stage: '70-detail', kind: 'text',msg: '<img> 缺少 alt', test: (t) => [...t.matchAll(/<img\b(?![^>]*\balt=)[^>]*>/g)].map((m) => ({ index: m.index, match: m[0] })) },- { id: 'LOBE-DIV-CLICK', level: 'WARN', ref: 'K-07', stage: '70-detail', kind: 'text',+ { id: 'LOBE-DIV-CLICK', platforms: WEB, level: 'WARN', ref: 'K-07', stage: '70-detail', kind: 'text',msg: 'div/span 绑定 onClick 但没有 role;优先用 button,或补 role + 键盘处理',test: (t) => [...t.matchAll(/<(div|span)\b(?![^>]*\brole=)[^>]*\bonClick=/g)].map((m) => ({ index: m.index, match: m[0] })) },{ id: 'LOBE-ICON-BUTTON-LABEL', level: 'WARN', ref: 'K-07', stage: '70-detail', kind: 'text',msg: '只有图标的按钮缺少 title / aria-label',- test: (t) => openTags(t, /<(ActionIcon|Button)\b/g).filter((o) => /\bicon=/.test(o.tag) && !/\b(title|aria-label)=/.test(o.tag) && (o.selfClosing || /^\s*<\//.test(t.slice(o.end)))).map((o) => ({ index: o.index, match: o.tag.slice(0, 80) })) },+ msgMobile: '只有图标的按钮缺少 accessibilityLabel;不是按钮的可点元素再补 accessibilityRole="button"',+ test: (t) => openTags(t, /<(ActionIcon|Button)\b/g).filter((o) => /\bicon=/.test(o.tag) && !/\b(title|aria-label|accessibilityLabel)=/.test(o.tag) && (o.selfClosing || /^\s*<\//.test(t.slice(o.end)))).map((o) => ({ index: o.index, match: o.tag.slice(0, 80) })) },{ id: 'LOBE-VAGUE-ERROR', level: 'WARN', ref: 'W-05', stage: '70-detail', kind: 'line',msg: '模糊错误文案;说清发生了什么 / 为什么 / 怎么办', test: (l) => /['"`>]\s*(操作失败|出错了|发生错误|请求失败|something went wrong|error occurred)\s*[!!。.]?\s*['"`<]/i.test(l) },{ id: 'LOBE-BARE-EMPTY', level: 'WARN', ref: 'W-04', stage: '70-detail', kind: 'line',@@ -258,9 +270,9 @@ export const RULES = [msg: '定义了动画 / @keyframes 但文件内没有处理 prefers-reduced-motion',test: (t) => {const i = t.search(/@keyframes|\banimation\s*:|\bkeyframes`/);- return i >= 0 && !/prefers-reduced-motion|useReducedMotion|reducedMotion/.test(t) ? [{ index: i, match: 'animation / @keyframes' }] : [];+ return i >= 0 && !/prefers-reduced-motion|useReducedMotion|reducedMotion|isReduceMotionEnabled|ReduceMotion/.test(t) ? [{ index: i, match: 'animation / @keyframes' }] : [];} },- { id: 'LOBE-GRADIENT-ANIMATION-OVERUSE', level: 'WARN', ref: 'A-07', stage: '50-visual', kind: 'text', since: '2.1.0',+ { id: 'LOBE-GRADIENT-ANIMATION-OVERUSE', platforms: WEB, level: 'WARN', ref: 'A-07', stage: '50-visual', kind: 'text', since: '2.1.0',msg: 'gradientAnimation 一页 > 2 处,品牌时刻失去意义',test: (t) => {const hits = [...t.matchAll(/\bgradientAnimation\b/g)].filter((m) => !/^\s*import\b/.test(t.slice(t.lastIndexOf('\n', m.index) + 1, m.index + 1)));@@ -283,46 +295,51 @@ export const RULES = [msg: '写死了 ≥ 480px 的 width / min-width,390px 视口会横向溢出;用 max-width / 百分比 / responsive 断点',test: (l) => !/matchMedia|@media|\(\s*(min|max)-width/.test(l)&& [...l.matchAll(/(?<![-\w])(width|min-width|minWidth)\s*:\s*['"`]?(\d+)px\b/g)].some((m) => +m[2] >= 480) },+ // ---- 5.5.0:RN / mobile 专属 ----+ { id: 'LOBE-RN-DOM-UI', level: 'WARN', ref: 'C-01', stage: '30-structure', kind: 'text', since: '5.5.0', platforms: ['mobile'],+ msg: 'RN 界面里导入了 DOM 组件库(@lobehub/ui / antd);RN 的原子层用项目组件库(如 @lobehub/ui-rn)与 react-native 原语',+ test: (t) => [...t.matchAll(/import\s+(type\s+)?([^;'"]*?)\s*\bfrom\s*['"]([^'"]+)['"]/g)]+ .filter((m) => !m[1] && isDomComponentImport(m[3], m[2]))+ .map((m) => ({ index: m.index, match: m[0].replace(/\s+/g, ' ') })) },];// Meta rule: implemented inside lintText (needs every line), listed here so --rules / --only see it.RULES.push({ id: 'LOBE-IGNORE-NO-REASON', level: 'FAIL', ref: 'L-06', stage: 'learnings', kind: 'meta', since: '2.1.0',msg: '豁免注释没有写理由,豁免不生效', test: () => [] });-for (const r of RULES) r.since ??= '2.0.0';+for (const r of RULES) { r.since ??= '2.0.0'; r.platforms ??= ALL; }const EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.css', '.less', '.scss']);// zh-CN 语言包(locales/zh-CN/*.json、zh_CN.json、zh-Hans…)只跑 locale: true 的文案规则export const isZhLocaleJson = (p) => extname(p) === '.json' && /(?:^|[\\/._-])zh[-_]?(?:cn|hans)(?:[\\/._-]|$)/i.test(p);const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.backup']);-// 显式传入的路径可以是软链;遍历中遇到的软链目录跳过(如 .claude/skills → .agents/skills),避免重复扫描或扫出目标树-function walk(p, out = [], top = true) {- if (!top && lstatSync(p).isSymbolicLink() && statSync(p).isDirectory()) return out;+function walk(p, out = []) {const st = statSync(p);if (st.isDirectory()) {- for (const name of readdirSync(p)) if (!SKIP_DIRS.has(name)) walk(join(p, name), out, false);+ for (const name of readdirSync(p)) if (!SKIP_DIRS.has(name)) walk(join(p, name), out);} else if ((EXTS.has(extname(p)) || isZhLocaleJson(p)) && !/\.(test|spec|stories)\.[jt]sx?$/.test(p)) out.push(p);return out;}const isCommentLine = (l) => /^\s*(\/\/|\/\*|\*)/.test(l);// A suppression only counts when it carries a reason: `lobe-design-ignore ID[,ID]: <reason>`.-// 只认真正的注释:标记前要有 // 或 /*(或块注释续行的 *),且注释起点之前的引号成对(不在字符串里)。-// 理由要有实际文字:冒号后到行尾 / */ 之间至少一个字母或数字。-const IGNORE_RE = /lobe-design-ignore(-file)?[ \t]+([A-Z0-9-]+(?:[ \t]*,[ \t]*[A-Z0-9-]+)*)([ \t]*:([^\n]*))?/g;-const inComment = (line, idx) => {- const prefix = line.slice(0, idx);- if (/^\s*\*/.test(prefix)) return true;- const opener = Math.max(prefix.lastIndexOf('//'), prefix.lastIndexOf('/*'));- if (opener === -1) return false;- const code = prefix.slice(0, opener).replace(/\\./g, '');- return ["'", '"', '`'].every((q) => code.split(q).length % 2 === 1);-};-export const ignores = (line) => [...(line ?? '').matchAll(IGNORE_RE)]- .filter((m) => inComment(line, m.index))- .map((m) => ({ file: !!m[1], ids: m[2].split(/\s*,\s*/), reason: m[3] !== undefined && /[\p{L}\p{N}]/u.test(m[4].split('*/')[0]) }));+const IGNORE_RE = /lobe-design-ignore(-file)?\s+([A-Z0-9-]+(?:\s*,\s*[A-Z0-9-]+)*)(\s*:\s*\S.*)?/g;+const ignores = (line) => [...(line ?? '').matchAll(IGNORE_RE)].map((m) => ({ file: !!m[1], ids: m[2].split(/\s*,\s*/), reason: !!m[3] }));const ignoredOn = (line, id) => ignores(line).some((g) => !g.file && g.reason && g.ids.includes(id));-export function lintText(text, file = '<text>') {+// 单文件平台:文件内 `lobe-design-platform: mobile` 注释 > *.native|ios|android.* 后缀 > opts.platform > web+const PLATFORM_PRAGMA = /lobe-design-platform\s*:\s*(web|desktop|mobile)\b/;+export function filePlatform(text, file, platform) {+ const m = text.match(PLATFORM_PRAGMA);+ if (m) return m[1];+ if (/\.(native|ios|android)\.[jt]sx?$/.test(file)) return 'mobile';+ return platform ?? 'web';+}+// 规则是否被项目层适用性关掉(按 lint id 或它引用的规则编号)+export const ruleOff = (rule, off) => !!off && (off.has(rule.id) || off.has(rule.ref));+export const ruleApplies = (rule, platform, off) => rule.platforms.includes(platform) && !ruleOff(rule, off);++export function lintText(text, file = '<text>', { platform, off } = {}) {+ const plat = filePlatform(text, file, platform);const lines = text.split('\n');const lineOf = (idx) => text.slice(0, idx).split('\n').length;const findings = [];@@ -334,11 +351,13 @@ export function lintText(text, file = '<text>') {const cur = lines[lineNo - 1] ?? '', prev = lines[lineNo - 2] ?? '';if (ignoredOn(cur, rule.id) || ignoredOn(prev, rule.id)) return;if (fileIgnored.has(rule.id)) return;- findings.push({ file, line: lineNo, level: rule.level, id: rule.id, ref: rule.ref, stage: rule.stage, msg: rule.msg, match: String(match).trim().slice(0, 100) });+ const msg = plat === 'mobile' && rule.msgMobile ? rule.msgMobile : rule.msg;+ findings.push({ file, line: lineNo, level: rule.level, id: rule.id, ref: rule.ref, stage: rule.stage, msg, match: String(match).trim().slice(0, 100) });};const json = extname(file) === '.json';for (const rule of RULES) {if (json && !rule.locale) continue;+ if (rule.kind === 'meta' || !ruleApplies(rule, plat, off)) continue;if (rule.kind === 'line') {lines.forEach((l, i) => { if (!isCommentLine(l) && rule.test(l)) push(rule, i + 1, l); });} else {@@ -352,14 +371,25 @@ export function lintText(text, file = '<text>') {return findings.sort((a, b) => a.line - b.line);}-export function lintPaths(paths) {+// opts: { platform: 'auto'|'web'|'desktop'|'mobile', root }。auto(默认)= 从目标路径向上找项目根,+// 读 .agents/ux/product.md 的平台与适用性(不适用 / lint-off),没有就看 package.json 依赖。+export function lintPaths(paths, { platform = 'auto', root } = {}) {const files = paths.flatMap((p) => walk(p));- const findings = files.flatMap((f) => lintText(readFileSync(f, 'utf8'), f));- return { files, findings };+ const projRoot = root ?? (paths[0] ? findProjectRoot(paths[0]) : null);+ const ctx = projectContext(projRoot, { platform });+ // product.md 的 lint-allow:按路径(相对项目根)关掉指定规则+ const offFor = (f) => {+ if (!ctx.allow.length || !projRoot) return ctx.off;+ const rel = relative(projRoot, f).split(sep).join('/');+ const ids = ctx.allow.filter((a) => a.globs.some((g) => g.test(rel))).flatMap((a) => a.rules);+ return ids.length ? new Set([...ctx.off, ...ids]) : ctx.off;+ };+ const findings = files.flatMap((f) => lintText(readFileSync(f, 'utf8'), f, { ...ctx, off: offFor(f) }));+ return { files, findings, ctx };}-function report({ files, findings }, cwd) {- const out = [`LOBE-DESIGN · LINT ${files.length} file(s)`];+function report({ files, findings, ctx }, cwd) {+ const out = [`LOBE-DESIGN · LINT ${files.length} file(s) platform=${ctx.platform}(${ctx.source})${ctx.off.size ? ` 项目层不适用:${[...ctx.off].join(', ')}` : ''}${ctx.allow?.length ? ` lint-allow:${ctx.allow.map((a) => a.raw).join(' | ')}` : ''}`];for (const level of ['FAIL', 'WARN']) {const list = findings.filter((f) => f.level === level);if (!list.length) continue;@@ -382,6 +412,18 @@ const HELP = `lobe-design lint — LobeUI 架构 / 审美(反 AI 味)/ a11y--json 以 JSON 输出 findings--stage <id> 只跑某个 stage 的规则(30-structure | 40-flow | 50-visual | 70-detail | 75-copy)--only <ID,ID> 只跑指定规则+ --platform <p> auto(默认)| web | desktop | mobile。auto 读项目根 .agents/ux/product.md 的「平台:」,+ 没有就看 package.json(react-native / expo / @lobehub/ui-rn → mobile)+ --root <dir> 项目根(默认从目标路径向上找 package.json / .agents/ux)++平台与项目层适用性+ 每条规则声明 platforms(--rules 可见)。mobile 跳过 web 专属检查(cssVar / createStaticStyles / antd /+ CSS 类名 / outline / font-family / <img> / div onClick 等),K-07 图标按钮接受 accessibilityLabel,+ @lobehub/ui-rn 是 RN 的原子层,不算「重新实现」。+ product.md 里 \`lint-allow: LOBE-RN-DOM-UI src/components/hooks/**, src/shared/markdown/*.ts\` 按路径(相对项目根,+ * 不跨目录、** 跨目录)关掉指定规则,可写多行;行内至少要有一个规则 id。+ product.md 里标「不适用 / N/A」的规则编号(C-01、C-01..C-11)或 lint id,以及 \`lint-off: LOBE-XXX, D-01\` 行,+ 都会关掉对应规则。单文件可写注释 lobe-design-platform: mobile;*.native|ios|android.tsx 视为 mobile。--rules 列出全部规则(级别 / id / 引用的 reference 规则 / stage / 引入版本)-h, --help 显示本帮助@@ -400,22 +442,21 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {const args = process.argv.slice(2);if (args.includes('-h') || args.includes('--help')) { console.log(HELP); process.exit(0); }if (args.includes('--rules')) {- for (const r of RULES) console.log(`${r.level.padEnd(4)} ${r.id.padEnd(32)} ${r.ref.padEnd(5)} ${r.stage.padEnd(13)} v${r.since.padEnd(6)} ${r.msg}`);+ for (const r of RULES) console.log(`${r.level.padEnd(4)} ${r.id.padEnd(32)} ${r.ref.padEnd(5)} ${r.stage.padEnd(13)} v${r.since.padEnd(6)} ${(r.platforms === ALL ? 'all' : r.platforms.join('/')).padEnd(12)} ${r.msg}`);console.log(`TOTAL: ${RULES.length} rules`);process.exit(0);}const optVal = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);const stage = optVal('--stage'), only = optVal('--only')?.split(',');- const paths = args.filter((a, i) => !a.startsWith('-') && !['--stage', '--only'].includes(args[i - 1]));+ const platform = optVal('--platform') ?? 'auto', rootOpt = optVal('--root');+ if (!['auto', 'web', 'desktop', 'mobile'].includes(platform)) { console.error(`用法错误:未知平台:${platform}(auto | web | desktop | mobile)`); process.exit(2); }+ const paths = args.filter((a, i) => !a.startsWith('-') && !['--stage', '--only', '--platform', '--root'].includes(args[i - 1]));if (!paths.length) { console.error('用法错误:缺少目标路径。\n\n' + HELP); process.exit(2); }const missing = paths.filter((p) => !existsSync(p));if (missing.length) { console.error(`用法错误:路径不存在:${missing.join(', ')}`); process.exit(2); }const unknown = (only ?? []).filter((id) => !RULES.some((r) => r.id === id));if (unknown.length) { console.error(`用法错误:未知规则:${unknown.join(', ')}(--rules 查看全部)`); process.exit(2); }- // stage 拼错会把所有结果过滤掉并 exit 0,等于跳过检查;只接受规则里出现过的 stage- const stages = [...new Set(RULES.map((r) => r.stage))];- if (stage !== undefined && !stages.includes(stage)) { console.error(`用法错误:未知 stage:${stage}(可用:${stages.join(', ')})`); process.exit(2); }- const res = lintPaths(paths);+ const res = lintPaths(paths, { platform, root: rootOpt });res.findings = res.findings.filter((f) => (!stage || f.stage === stage) && (!only || only.includes(f.id)));if (args.includes('--json')) {console.log(JSON.stringify(res.findings, null, 2));diff --git a/.agents/skills/lobe-design/scripts/pipeline.json b/.agents/skills/lobe-design/scripts/pipeline.jsonindex 0dabf3f6180..5e7a30c2e37 100644--- a/.agents/skills/lobe-design/scripts/pipeline.json+++ b/.agents/skills/lobe-design/scripts/pipeline.json@@ -1,5 +1,5 @@{- "version": "5.4.2",+ "version": "5.8.0","$comment": "Single source of truth for routing (route.mjs), progressive disclosure (refs.mjs) and isolation checks (check-structure.mjs). Edit here first, then the matching stage file.","stageOrder": ["00-brief",diff --git a/.agents/skills/lobe-design/scripts/platform.mjs b/.agents/skills/lobe-design/scripts/platform.mjsnew file mode 100644index 00000000000..c7bfe814bc2--- /dev/null+++ b/.agents/skills/lobe-design/scripts/platform.mjs@@ -0,0 +1,116 @@+// lobe-design 平台与项目层适用性:lint / bootstrap / project-scan 共用。零依赖。+// 平台来源(由强到弱):显式参数 → .agents/ux/product.md 的「平台:」行 → package.json 依赖。+// 适用性:product.md 里标「不适用 / N/A」的规则编号(C-01、C-01..C-11)或 lint id(LOBE-XXX),+// 以及显式的 `lint-off: LOBE-XXX, D-01` 行,都会让 lint 跳过对应规则(项目层优先于通用规则)。+import { existsSync, readFileSync, statSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';++export const PLATFORMS = ['web', 'desktop', 'mobile'];+export const MOBILE_DEPS = ['react-native', 'expo', '@lobehub/ui-rn', '@capacitor/core', '@ionic/react'];+export const RN_UI_DEPS = ['@lobehub/ui-rn', 'react-native-paper', 'tamagui', '@rneui/themed', 'native-base', '@gluestack-ui/themed', 'react-native-ui-lib'];+export const RN_NAV_DEPS = ['expo-router', '@react-navigation/native', '@react-navigation/native-stack', '@react-navigation/bottom-tabs', '@react-navigation/stack', '@react-navigation/drawer'];++const read = (p) => { try { return readFileSync(p, 'utf8'); } catch { return null; } };+const json = (p) => { const t = read(p); if (!t) return null; try { return JSON.parse(t); } catch { return null; } };+export const depsOf = (pkg) => ({ ...(pkg?.dependencies ?? {}), ...(pkg?.devDependencies ?? {}), ...(pkg?.peerDependencies ?? {}) });+const hasDep = (all, d) => Object.keys(all).some((n) => n === d || n.startsWith(`${d}/`));++/** 从 product.md 文本读平台(「平台:mobile」「platform: mobile, web」「| 平台 | mobile |」)。 */+export function parsePlatform(text) {+ if (!text) return null;+ const m = text.match(/^[\s>*|-]*(?:\*\*)?(?:平台|platform)(?:\*\*)?\s*(?:[::]|\|)\s*`?([^\n`|]+)/im);+ if (!m) return null;+ const found = PLATFORMS.filter((p) => new RegExp(`\\b${p}\\b`, 'i').test(m[1]));+ if (/\bmix\b/i.test(m[1]) && !found.length) return 'mix';+ if (!found.length) return null;+ // 多选时第一个出现的为主平台+ return found.sort((a, b) => m[1].toLowerCase().indexOf(a) - m[1].toLowerCase().indexOf(b))[0];+}++/** 从依赖推断平台:react-native / expo / ui-rn → mobile。 */+export function platformFromDeps(all) {+ if (MOBILE_DEPS.some((d) => hasDep(all, d))) return 'mobile';+ if (['electron', '@tauri-apps/api'].some((d) => hasDep(all, d))) return 'desktop';+ if (Object.keys(all).length) return 'web';+ return null;+}++const ID = '[A-Z]{1,2}-\\d{2}';+/** 展开 C-01..C-11 / C-01~C-11 / C-01–C-11 区间。 */+function expandIds(s) {+ const out = new Set();+ for (const m of s.matchAll(new RegExp(`(${ID})\\s*(?:\\.\\.|~|–|—|到)\\s*(${ID})`, 'g'))) {+ const [p1, n1] = m[1].split('-'), [p2, n2] = m[2].split('-');+ if (p1 !== p2) continue;+ for (let i = +n1; i <= +n2; i++) out.add(`${p1}-${String(i).padStart(2, '0')}`);+ }+ for (const m of s.matchAll(new RegExp(`\\b${ID}\\b`, 'g'))) out.add(m[0]);+ for (const m of s.matchAll(/\bLOBE-[A-Z0-9-]+\b/g)) out.add(m[0]);+ return out;+}++const NA = /不适用|n\/a|not applicable|关闭|停用/i;+/** 读项目层的适用性:返回被标为不适用的规则编号 / lint id。 */+export function parseApplicability(text) {+ const off = new Set();+ if (!text) return off;+ for (const line of text.split('\n')) {+ const lo = line.match(/lint-off\s*[::]\s*`?([^`\n]+)/i);+ if (lo) { for (const id of expandIds(lo[1])) off.add(id); continue; }+ if (!NA.test(line)) continue;+ // 表格行:只看标「不适用」的那一行;普通行:只看「不适用」前后同一句+ for (const id of expandIds(line)) off.add(id);+ }+ return off;+}++/** glob → RegExp(相对项目根的 posix 路径):** 跨目录,* 与 ? 不跨 /;以 / 结尾视为整个目录。 */+export function globToRe(g) {+ let x = g.trim().replace(/^\.\//, '');+ if (x.endsWith('/')) x += '**';+ let re = '';+ for (let i = 0; i < x.length; i++) {+ const c = x[i];+ if (c === '*' && x[i + 1] === '*') { i++; if (x[i + 1] === '/') { i++; re += '(?:.*/)?'; } else re += '.*'; }+ else if (c === '*') re += '[^/]*';+ else if (c === '?') re += '[^/]';+ else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');+ }+ return new RegExp(`^${re}$`);+}+const RULE_TOKEN = /^(?:LOBE-[A-Z0-9-]+|[A-Z]{1,2}-\d{2})$/;+/** `lint-allow: LOBE-RN-DOM-UI src/hooks/**, src/styles/**`(可多行)→ [{ rules, globs }]。没有规则 id 的行忽略。 */+export function parseAllow(text) {+ const out = [];+ for (const m of (text ?? '').matchAll(/lint-allow\s*[::]\s*`?([^`\n]+)/gi)) {+ const toks = m[1].split(/[\s,,]+/).filter(Boolean);+ const rules = toks.filter((t) => RULE_TOKEN.test(t)), globs = toks.filter((t) => !RULE_TOKEN.test(t));+ if (rules.length && globs.length) out.push({ rules, globs: globs.map(globToRe), raw: m[1].trim() });+ }+ return out;+}++/** 从 start 向上找项目根(有 package.json 或 .agents/ux 的最近目录)。 */+export function findProjectRoot(start) {+ let d = resolve(start);+ try { if (!statSync(d).isDirectory()) d = dirname(d); } catch { return null; }+ for (;;) {+ if (existsSync(join(d, '.agents', 'ux', 'product.md')) || existsSync(join(d, 'package.json'))) return d;+ if (existsSync(join(d, '.git'))) return null; // 不越过仓库边界+ const up = dirname(d);+ if (up === d) return null;+ d = up;+ }+}++/** 项目上下文:{ root, platform, source, off:Set, uiLibs } */+export function projectContext(root, { platform } = {}) {+ const product = root ? read(join(root, '.agents', 'ux', 'product.md')) : null;+ const all = root ? depsOf(json(join(root, 'package.json'))) : {};+ let source = 'default';+ let p = platform && platform !== 'auto' ? (source = 'flag', platform) : null;+ if (!p) { const x = parsePlatform(product); if (x) { p = x; source = 'product.md'; } }+ if (!p) { const x = platformFromDeps(all); if (x) { p = x; source = 'package.json'; } }+ if (p === 'mix') p = platformFromDeps(all) ?? 'web';+ return { root, platform: p ?? 'web', source, off: parseApplicability(product), allow: parseAllow(product), rnUi: RN_UI_DEPS.filter((d) => hasDep(all, d)) };+}diff --git a/.agents/skills/lobe-design/scripts/project-scan.mjs b/.agents/skills/lobe-design/scripts/project-scan.mjsindex 03a8c15642d..3eb870232bb 100755--- a/.agents/skills/lobe-design/scripts/project-scan.mjs+++ b/.agents/skills/lobe-design/scripts/project-scan.mjs@@ -8,6 +8,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';import { dirname, join, relative, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { createHash } from 'node:crypto';+import { RN_NAV_DEPS, RN_UI_DEPS } from './platform.mjs';const skillDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');const SKILL_VERSION = readFileSync(join(skillDir, 'SKILL.md'), 'utf8').match(/^version:\s*(\S+)/m)?.[1] ?? '0.0.0';@@ -34,6 +35,7 @@ const FRAMEWORK_DEPS = [];const UI_DEPS = [+ ...RN_UI_DEPS,'@lobehub/ui','antd','@ant-design/pro-components',@@ -90,8 +92,7 @@ function listFiles(root, rel, max = 40) {const walk = (dir, prefix) => {if (out.length >= max) return;let entries;- // 按名字排序再截断:样本进指纹,不能依赖文件系统的 readdir 顺序- try { entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); } catch { return; }+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }for (const e of entries) {if (out.length >= max) break;if (e.name.startsWith('.') || e.name === 'node_modules') continue;@@ -104,27 +105,6 @@ function listFiles(root, rel, max = 40) {return out.sort();}-// 不设上限地列出源码文件:样本有上限,但指纹要靠全量的数量与相对路径才能发现增删和改名-function allFiles(root, rel) {- const out = [];- const walk = (dir, prefix) => {- let entries;- try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }- for (const e of entries) {- if (e.name.startsWith('.') || e.name === 'node_modules') continue;- const relPath = prefix ? `${prefix}/${e.name}` : e.name;- if (e.isDirectory()) walk(join(dir, e.name), relPath);- else if (/\.(tsx?|jsx?|vue|svelte)$/.test(e.name)) out.push(relPath);- }- };- walk(join(root, rel), '');- return out.sort();-}-const fileFacts = (root, rel) => {- const all = allFiles(root, rel);- return { fileCount: all.length, filesHash: createHash('sha256').update(all.join('\n')).digest('hex').slice(0, 12) };-};-function depsOf(pkg) {return {...(pkg?.dependencies ?? {}),@@ -153,17 +133,90 @@ export function detectStack(root) {}const uiLibs = UI_DEPS.filter((d) => all[d] || depNames.some((n) => n === d || n.startsWith(`${d}/`)));const scripts = Object.keys(pkg.scripts ?? {}).sort();+ // 主平台:mobile 信号优先(RN 项目常同时依赖 web 工具链)+ const platform = platforms.has('mobile') ? 'mobile' : platforms.has('desktop') && !platforms.has('web') ? 'desktop' : platforms.size ? 'web' : null;+ const aliases = readAliases(root);+ const rnUi = uiLibs.filter((d) => RN_UI_DEPS.includes(d));+ // 项目内组件库:alias 名是 RN UI 库名(如 @lobehub/ui-rn → src/components),或依赖里有 ui-rn+ for (const [name, target] of Object.entries(aliases)) {+ if (RN_UI_DEPS.includes(name) && !rnUi.includes(name)) rnUi.unshift(name);+ }+ const domUi = uiLibs.filter((d) => !RN_UI_DEPS.includes(d));+ const primaryUi = platform === 'mobile'+ ? (rnUi[0] ? { name: rnUi[0], alias: aliases[rnUi[0]] ?? null, role: 'RN 原子层' } : null)+ : (domUi[0] ? { name: domUi[0], alias: null, role: '原子层' } : null);return {name: pkg.name ?? null,description: pkg.description ?? null,frameworks,platforms: [...platforms].sort(),- uiLibs,+ platform,+ uiLibs: platform === 'mobile' ? [...new Set([...rnUi, ...uiLibs])] : uiLibs,+ primaryUi,+ // mobile 上 DOM 组件库(@lobehub/ui / antd)只是依赖,不是 RN 界面库+ depOnlyUi: platform === 'mobile' ? domUi : [],+ navigation: RN_NAV_DEPS.filter((d) => all[d]),+ aliases,scripts,hasTypeScript: existsSync(join(root, 'tsconfig.json')) || depNames.includes('typescript'),};}+/** tsconfig / jsconfig 的 paths:{ '@lobehub/ui-rn': 'src/components' }(去掉 /* 与 ./)。 */+export function readAliases(root) {+ const out = {};+ for (const f of ['tsconfig.json', 'jsconfig.json']) {+ const t = safeRead(join(root, f));+ if (!t) continue;+ let cfg;+ try { cfg = JSON.parse(t.replace(/^\s*\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1')); } catch { continue; }+ for (const [k, v] of Object.entries(cfg?.compilerOptions?.paths ?? {})) {+ const name = k.replace(/\/\*$/, '');+ const target = String(Array.isArray(v) ? v[0] : v).replace(/\/\*$/, '').replace(/^\.\//, '').replace(/\/index\.[jt]sx?$/, '');+ if (name && target) out[name] = target;+ }+ }+ return out;+}++// ---- Round 2 组件分类(平台感知)----+export const COMPONENT_SCHEMES = {+ web: ['薄包装', '与 lobe-ui 重复', '业务组件'],+ mobile: ['项目原子层', '薄包装', '业务组件'],+};+const ATOM_NAME = /^\s*export\s+(?:default\s+)?(?:const|function)\s+(Button|Modal|Drawer|Table|Input|TextInput|Select|Checkbox|Radio|Switch|Tabs|Tooltip|Popover|Tag|Badge|Avatar|Skeleton|Divider|Progress|Spin|Empty|Text|Icon|ActionIcon|Sheet|BottomSheet|Toast|Card|List|ListItem|Flexbox|Center)\b/m;+const RN_PRIMITIVE = /from\s*['"]react-native['"]/;+const importsFrom = (text, names) => names.some((n) => new RegExp(`from\\s*['"]${n.replace(/[/.]/g, (c) => `\\${c}`)}(?:/[^'"]*)?['"]`).test(text));++/** 单文件分类。platform = 'mobile' 时用「项目原子层 / 薄包装 / 业务组件」,不出现「改用 lobe-ui」。 */+export function classifyComponent(rel, text, stack) {+ const mobile = stack.platform === 'mobile';+ const body = text.split('\n').filter((l) => l.trim() && !/^\s*(import|\/\/|\*|\/\*)/.test(l));+ const ui = mobile ? [stack.primaryUi?.name, ...Object.keys(stack.aliases ?? {}).filter((a) => a === stack.primaryUi?.name)].filter(Boolean) : ['@lobehub/ui'];+ const atomDir = mobile ? stack.primaryUi?.alias : null;+ const inAtomDir = !!atomDir && (`${rel}/`).startsWith(`${atomDir}/`);+ const thin = body.length <= 12 && importsFrom(text, ui) && !(mobile && RN_PRIMITIVE.test(text));+ if (thin) return '薄包装';+ if (mobile) {+ if (inAtomDir || (ATOM_NAME.test(text) && RN_PRIMITIVE.test(text) && !/features?\//.test(rel))) return '项目原子层';+ return '业务组件';+ }+ if (ATOM_NAME.test(text) && !importsFrom(text, ui)) return '与 lobe-ui 重复';+ return '业务组件';+}++export function classifyComponents(root, stack, dirs, max = 80) {+ const seen = new Set(), out = [];+ for (const d of dirs) for (const f of listFiles(root, d.dir, 50)) {+ const rel = `${d.dir}/${f}`;+ if (seen.has(rel) || out.length >= max) continue;+ seen.add(rel);+ const text = safeRead(join(root, rel)) ?? '';+ out.push({ file: rel, class: classifyComponent(rel, text, stack) });+ }+ return out;+}+export function detectRoutes(root) {const found = [];for (const rel of ROUTE_DIR_CANDIDATES) {@@ -182,7 +235,7 @@ export function detectComponentDirs(root) {const files = listFiles(root, rel, 50);found.push({dir: rel,- ...fileFacts(root, rel),+ fileCount: files.length,sampleFiles: files.slice(0, 20),});}@@ -194,7 +247,7 @@ export function detectComponentDirs(root) {if (COMPONENT_DIR_CANDIDATES.includes(rel)) continue;if (!existsSync(join(root, rel))) continue;const files = listFiles(root, rel, 30);- found.push({ dir: rel, ...fileFacts(root, rel), sampleFiles: files.slice(0, 15) });+ found.push({ dir: rel, fileCount: files.length, sampleFiles: files.slice(0, 15) });}}return found;@@ -244,9 +297,8 @@ export function fingerprintOf(facts) {frameworks: facts.stack?.frameworks,platforms: facts.stack?.platforms,uiLibs: facts.stack?.uiLibs,- // 带上全量文件路径的哈希与路由子目录:文件数不变的改名 / 替换也要让指纹变化- componentDirs: (facts.components ?? []).map((c) => [c.dir, c.fileCount, c.filesHash]),- routeDirs: (facts.routes ?? []).map((r) => [r.dir, r.subdirs]),+ componentDirs: (facts.components ?? []).map((c) => [c.dir, c.fileCount]),+ routeDirs: (facts.routes ?? []).map((r) => r.dir),i18n: facts.docs?.i18nDirs,};return createHash('sha256').update(JSON.stringify(slim)).digest('hex').slice(0, 12);@@ -267,7 +319,9 @@ export function scanProject(root) {};const productText = ux.product ? safeRead(join(uxRoot, PRODUCT_FILE)) : null;const componentsText = ux.components ? safeRead(join(uxRoot, COMPONENTS_FILE)) : null;- const facts = { root, skillVersion: SKILL_VERSION, stack, routes, components, docs, ux };+ const scheme = COMPONENT_SCHEMES[stack.platform === 'mobile' ? 'mobile' : 'web'];+ const componentClasses = classifyComponents(root, stack, components);+ const facts = { root, skillVersion: SKILL_VERSION, stack, routes, components, componentScheme: scheme, componentClasses, docs, ux };const fingerprint = fingerprintOf(facts);facts.fingerprint = fingerprint;facts.productMeta = parseInitMeta(productText);@@ -308,7 +362,12 @@ function renderHuman(facts) {if (facts.stack.description) lines.push(`描述:${facts.stack.description}`);lines.push(`平台:${facts.stack.platforms.join(', ') || '未判定'}`);lines.push(`框架:${facts.stack.frameworks.join(', ') || '未判定'}`);- lines.push(`UI 库:${facts.stack.uiLibs.join(', ') || '未发现'}`);+ const pu = facts.stack.primaryUi;+ lines.push(`UI 库:${pu ? `${pu.name}${pu.alias ? `(alias → ${pu.alias})` : ''} · ${pu.role}` : facts.stack.uiLibs.join(', ') || '未发现'}`);+ const others = facts.stack.uiLibs.filter((d) => d !== pu?.name && !facts.stack.depOnlyUi.includes(d));+ if (others.length) lines.push(` 其他 UI 依赖:${others.join(', ')}`);+ if (facts.stack.depOnlyUi.length) lines.push(` 仅依赖、不是 RN 界面库:${facts.stack.depOnlyUi.join(', ')}(DOM 组件库,RN 界面不从这里取原子层)`);+ if (facts.stack.navigation.length) lines.push(`导航:${facts.stack.navigation.join(', ')}`);lines.push(`TypeScript:${facts.stack.hasTypeScript ? '是' : '否'}`);if (facts.docs.readmeTitle) lines.push(`README:${facts.docs.readmeTitle}`);if (facts.docs.readmeLead) lines.push(` ${facts.docs.readmeLead}`);@@ -326,6 +385,10 @@ function renderHuman(facts) {lines.push(` ${c.dir}/ ~${c.fileCount} 文件`);if (c.sampleFiles.length) lines.push(` 样例:${c.sampleFiles.slice(0, 6).join(', ')}`);}+ if (facts.componentClasses.length) {+ const count = Object.fromEntries(facts.componentScheme.map((c) => [c, facts.componentClasses.filter((x) => x.class === c).length]));+ lines.push(`组件初分(启发式,Round 2 复核):${facts.componentScheme.map((c) => `${c} ${count[c]}`).join(' · ')}`);+ }lines.push('');lines.push('项目层:');lines.push(` ${UX_DIR}/${PRODUCT_FILE}:${facts.ux.product ? '有' : '缺'}`);@@ -333,7 +396,7 @@ function renderHuman(facts) {lines.push('');lines.push('下一步(由 Agent 执行,本脚本不落盘):');lines.push(' Round 1 → 写/更新 .agents/ux/product.md(平台、产品类型、用户、核心任务、适用性、copy-profile)');- lines.push(' Round 2 → 写/更新 .agents/ux/components.md(薄包装 / 重复 / 业务组件用法)');+ lines.push(` Round 2 → 写/更新 .agents/ux/components.md(${facts.componentScheme.join(' / ')})${facts.stack.platform === 'mobile' ? ';mobile:项目组件库就是原子层,不要求改用 @lobehub/ui' : ''}`);lines.push(` 文件头写入:${renderInitMeta(facts.skillVersion, facts.fingerprint)}`);return lines.join('\n');}diff --git a/.agents/skills/lobe-design/scripts/refs.mjs b/.agents/skills/lobe-design/scripts/refs.mjsindex ae36b43da10..80cd3d591b2 100755--- a/.agents/skills/lobe-design/scripts/refs.mjs+++ b/.agents/skills/lobe-design/scripts/refs.mjs@@ -68,23 +68,49 @@ export function readCopyProfile(root) {const areas = [];let def = null;for (const p of parts) {- // 一个 profile 可以对应多条路由:`/settings, /resource → saas`- const m = p.match(/^(\S.*?)\s*(?:→|->|=>|:)\s*([a-z-]+)$/);- if (m) for (const path of m[1].split(/[,,\s]+/).filter(Boolean)) areas.push({ path, id: m[2] });+ const m = p.match(/^(\S+)\s*(?:→|->|=>|:)\s*([a-z-]+)$/);+ if (m) areas.push({ path: m[1], id: m[2] });else if (!def && /^[a-z-]+$/.test(p)) def = p;}return { default: def, areas };}// 选出这次要加载的 profile id 列表-export function selectProfiles(metas, text, { profile, root } = {}) {+// 路由分区匹配(5.5.0):按路径段匹配,不按字符串前缀,所以带动态段的完整 URL 也能命中。+// `/api-keys` → 任意位置连续出现该段序列:/api-keys、/acme/api-keys、/:wsSlug/api-keys/new 都命中;/api-keys-old 不命中+// `/*/api-keys` → `*` 匹配恰好一段(含 :param / [param] 这类动态段)+// `/admin/**` → `**` 匹配任意多段(含 0 段)+// `^/admin` → 只从根开始匹配(真正的前缀)+// 多条命中时取更具体的(字面段多者优先)。+const segs = (p) => p.replace(/[?#].*$/, '').split('/').filter(Boolean).map((x) => x.toLowerCase());+function matchAt(pat, url, i, j) {+ if (i === pat.length) return true;+ if (pat[i] === '**') { for (let k = j; k <= url.length; k++) if (matchAt(pat, url, i + 1, k)) return true; return false; }+ if (j >= url.length) return false;+ if (pat[i] === '*' || /^(?::\w+|\[[^\]]+\])$/.test(pat[i]) || pat[i] === url[j]) return matchAt(pat, url, i + 1, j + 1);+ return false;+}+export function matchRoute(pattern, url) {+ const anchored = pattern.startsWith('^');+ const pat = segs(pattern.replace(/^\^/, '')), u = segs(url.replace(/^https?:\/\/[^/]+/i, ''));+ if (!pat.length) return false;+ for (let j = 0; j <= (anchored ? 0 : u.length - 1); j++) if (matchAt(pat, u, 0, j)) return true;+ return false;+}+export const routesIn = (text) => [...text.matchAll(/(?:https?:\/\/[^\s/]+)?(?:\/[\w:.*\[\]@~-]+)+\/?/g)].map((m) => m[0]);+export function matchArea(areas, routes) {+ const score = (p) => segs(p.replace(/^\^/, '')).filter((x) => x !== '*' && x !== '**').length;+ return areas.filter((a) => routes.some((r) => matchRoute(a.path, r))).sort((a, b) => score(b.path) - score(a.path))[0] ?? null;+}++export function selectProfiles(metas, text, { profile, root, page } = {}) {const profs = [...metas.values()].filter((m) => m?.tier === 'profile');const ids = new Set(profs.map((m) => m.profile));if (profile) return ids.has(profile) ? { selected: [profile], source: 'flag' } : { selected: [], source: 'flag', error: `未知 profile:${profile}(可用:${[...ids].join(', ')})` };const hitIds = profs.filter((m) => (m.triggers ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean).some((t) => text.includes(t))).map((m) => m.profile);const proj = root ? readCopyProfile(root) : null;if (proj && (proj.default || proj.areas.length)) {- const area = proj.areas.find((a) => text.includes(a.path.toLowerCase()) && ids.has(a.id));+ const area = matchArea(proj.areas.filter((a) => ids.has(a.id)), page ? [page] : routesIn(text));if (area) return { selected: [area.id], source: `product.md(${area.path})` };const cands = [proj.default, ...proj.areas.map((a) => a.id)].filter((id) => id && ids.has(id));const byTrigger = cands.find((id) => hitIds.includes(id));@@ -116,7 +142,7 @@ export function planRef(meta, text, chosen = []) {}// 给定指令(可选指定 stage),产出每个 stage 的加载清单-export function resolveRefs(instruction, { stage, profile, root } = {}) {+export function resolveRefs(instruction, { stage, profile, root, page } = {}) {const metas = allMeta();const r = route(instruction);const text = instruction.toLowerCase();@@ -126,7 +152,7 @@ export function resolveRefs(instruction, { stage, profile, root } = {}) {? [{ stage, file: PIPELINE.stages[stage]?.file, refs: PIPELINE.stages[stage]?.loads ?? [] }]: r.loads;if (stage && !PIPELINE.stages[stage]) return { instruction, scenario: r.scenario, granularity: r.granularity, stages: [], budget: ALWAYS_BUDGET, error: `未知 stage:${stage}` };- const copyProfile = selectProfiles(metas, text, { profile, root });+ const copyProfile = selectProfiles(metas, text, { profile, root, page });const out = [];for (const st of plan) {if (!st.file) continue;@@ -166,7 +192,9 @@ const HELP = `lobe-design refs — 渐进式披露解析器(零依赖)node scripts/refs.mjs "<指令>" --stage 50-visual 只看某个 stagenode scripts/refs.mjs "<指令>" --json JSON 输出node scripts/refs.mjs "<指令>" --profile admin 75-copy:指定文案 profile(consumer | saas | admin | devtool)- node scripts/refs.mjs "<指令>" --root <项目根> 75-copy:从 .agents/ux/product.md 的 copy-profile 选 profile(默认当前目录)+ node scripts/refs.mjs "<指令>" --root <项目根> 75-copy:从 .agents/ux/product.md 的 copy-profile 选 profile+ node scripts/refs.mjs "<指令>" --root <根> --page /acme/api-keys 指定当前页面路由(默认从指令里提取路径)+ 路由分区按路径段匹配:\`/api-keys\` 命中 /:wsSlug/api-keys;\`/*/api-keys\` 的 * 是一段;\`/admin/**\` 任意多段;\`^/admin\` 只从根匹配node scripts/refs.mjs --audit 审计全部 reference 的 tier / always 预算tier@@ -193,15 +221,15 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {const json = args.includes('--json');const stage = args.includes('--stage') ? args[args.indexOf('--stage') + 1] : undefined;const profile = args.includes('--profile') ? args[args.indexOf('--profile') + 1] : undefined;- // 不带 --root 时默认当前目录,和 bootstrap / project-scan 一致:项目根下运行即可读到 .agents/ux/product.md- const root = args.includes('--root') ? args[args.indexOf('--root') + 1] : process.cwd();- const instruction = args.filter((a, i) => !a.startsWith('--') && !['--stage', '--profile', '--root'].includes(args[i - 1])).join(' ');+ const root = args.includes('--root') ? args[args.indexOf('--root') + 1] : undefined;+ const page = args.includes('--page') ? args[args.indexOf('--page') + 1] : undefined;+ const instruction = args.filter((a, i) => !a.startsWith('--') && !['--stage', '--profile', '--root', '--page'].includes(args[i - 1])).join(' ');if (!instruction) { console.error(`用法错误:缺少指令。\n\n${HELP}`); process.exit(2); }if (stage && !PIPELINE.stages[stage]) {console.error(`用法错误:未知 stage:${stage}\n可用:${Object.keys(PIPELINE.stages).join(', ')}`);process.exit(2);}- const res = resolveRefs(instruction, { stage, profile, root });+ const res = resolveRefs(instruction, { stage, profile, root, page });if (res.copyProfile?.error) { console.error(`用法错误:${res.copyProfile.error}`); process.exit(2); }if (json) console.log(JSON.stringify(res, null, 2));else console.log(format(res));diff --git a/.agents/skills/lobe-design/stages/05-init.md b/.agents/skills/lobe-design/stages/05-init.mdindex d0de1cedf22..d871650d6ce 100644--- a/.agents/skills/lobe-design/stages/05-init.md+++ b/.agents/skills/lobe-design/stages/05-init.md@@ -12,10 +12,11 @@- 判断是「建立」还是「追加托管块」;已有内容一律保留- 写入入口与顺序、触发条件、执行纪律、自迭代规则;托管块提醒「装完 / 升级后先跑两轮」(I-02)- **Round 1 产品画像**:扫描仓库 → 写 `.agents/ux/product.md`(平台、产品类型、用户、核心任务、适用性、**文案 profile**)(I-07)-- **Round 2 组件盘点**:扫描项目组件 → 写 `.agents/ux/components.md`(薄包装 / 重复 / 业务组件用法)(I-08)+- **Round 2 组件盘点**:扫描项目组件 → 写 `.agents/ux/components.md`(web:薄包装 / 重复 / 业务组件;mobile:项目原子层 / 薄包装 / 业务组件)(I-08)- 项目层落在 `.agents/ux/`,**不改**已安装 skill;重装不覆盖(I-05)- 自迭代分两层:宿主项目记进项目层规则文件,通用经验回流后才在 skill 仓库里走版本 / CHANGELOG / LOG / 测试(I-03)- 幂等:重跑更新,不追加重复块;`--check` 发现缺失或过期(I-04 / I-09)+- **平台门控**:Round 1 的 `平台:` 行决定 lint 规则集、托管块与 Round 2 分类;项目层「不适用」优先于 skill 通用规则(I-10)## 不负责@@ -34,7 +35,7 @@## 只加载-- [init.md](../references/init.md):I-01..I-09+- [init.md](../references/init.md):I-01..I-10## 步骤@@ -49,12 +50,12 @@5. 跑 `node scripts/project-scan.mjs --root <根>`(或 `--json`)收集事实。6. 结合 README、路由、i18n、已有 docs,判断平台 / 产品类型 / 用户 / 核心任务;据此定**文案 profile**(`consumer` / `saas` / `admin` / `devtool`,可按路由分区)与人称(无主语 / 你 / 您),写成一行 `copy-profile: …`(I-07)。-7. 对照 skill 的 P-xx 与关键规则,标出**强调**与**不适用**(适用性表)。+7. 对照 skill 的 P-xx 与关键规则,标出**强调**与**不适用**(适用性表,一行一条;mobile 项目把 web 专属规则标为不适用)。平台写成机读一行 `平台:<web|desktop|mobile>`(I-10)。8. 起草 `.agents/ux/product.md`(文件头带 `<!-- lobe-design-init: version=… fingerprint=… -->`),给用户看后写入。已有文件则**整份更新**,不追加第二份。### C. Round 2 · 组件盘点-9. 按 scan 给出的组件目录,把现有组件分成:薄包装、与 lobe-ui 重复、业务组件。+9. 按 scan 给出的组件目录与分类方案(`componentScheme` / 逐文件初分),把现有组件分成:web —— 薄包装、与 lobe-ui 重复、业务组件;mobile —— 项目原子层、薄包装、业务组件(不写「改用 lobe-ui」)。10. 起草 `.agents/ux/components.md`(同样带 init meta):只写「哪个场景用哪个 + 注意点」。11. 若有需要长期记住的选型强调,续写 `.agents/ux/lobe-design-rules.md`(不改 `$LOBE_DESIGN`)。12. 跑 `node scripts/project-scan.mjs --check --root <根>`,确认文件齐全且指纹匹配。@@ -69,8 +70,8 @@2. 写入前给用户看过内容,且得到确认。3. **托管块之外的内容零改动**——这是硬保证。4. 块内含入口、触发(含升级后重跑)、纪律(含先读项目层)、自迭代。-5. `product.md` 含平台、产品类型、用户、核心任务、适用性表、`copy-profile:` 行,且带 init meta。-6. `components.md` 三类分清,无实现细节,且带 init meta。+5. `product.md` 含机读的 `平台:` 行、产品类型、用户、核心任务、适用性表、`copy-profile:` 行,且带 init meta。+6. `components.md` 按平台的三类分清,无实现细节,且带 init meta。7. 未改应用代码、未跑 build。8. `bootstrap.mjs --check` 与 `project-scan.mjs --check` 均通过(后者允许仅 WARN 过期已在本轮刷新后消失)。9. 重复运行:托管块 `unchanged`;两份 ux 文件是更新而非重复章节。@@ -82,7 +83,7 @@探测:<AGENTS.md | CLAUDE.md | 未找到 → 建立 AGENTS.md>操作:<建立 | 追加托管块 | 替换托管块> 块外改动:无Round 1:.agents/ux/product.md 平台=<…> 类型=<…> 文案 profile=<…> 适用性=<强调 N / N/A M>-Round 2:.agents/ux/components.md 薄包装=<n> 重复=<n> 业务=<n>+Round 2:.agents/ux/components.md <web:薄包装=n 重复=n 业务=n | mobile:原子层=n 薄包装=n 业务=n>脚本:bootstrap --check → <OK/FAIL>;project-scan --check → <OK/FAIL/WARN>遗留:<→ 00 / 80>```diff --git a/.agents/skills/lobe-design/stages/10-decode.md b/.agents/skills/lobe-design/stages/10-decode.mdindex dd653d62d2d..6cd03248e76 100644--- a/.agents/skills/lobe-design/stages/10-decode.md+++ b/.agents/skills/lobe-design/stages/10-decode.md@@ -1,6 +1,6 @@# Stage 10 · 截图解析(decode)-> 只回答一个问题:**这张图里有什么结构、什么取值,它们分别映射到哪个 lobe-ui 组件和哪个 token。**+> 只回答一个问题:**这张图里有什么结构、什么取值,它们分别映射到宿主组件库的哪个组件(web:lobe-ui;RN:项目组件库,如 `@lobehub/ui-rn`)和哪个主题 token。**> 只在 screenshot-restore 场景运行。产出两张表,30 和 50 照着表执行,不再回头凭感觉看图。还原失败通常有两种:一是逐像素抄 hex 和 px,绕过了设计系统;二是凭印象「差不多」,丢掉了图里真正的层级。本 stage 把图拆成可执行的清单,避免这两种失败。diff --git a/.agents/skills/lobe-design/stages/30-structure.md b/.agents/skills/lobe-design/stages/30-structure.mdindex 5996740fb87..e0e7de86ad8 100644--- a/.agents/skills/lobe-design/stages/30-structure.md+++ b/.agents/skills/lobe-design/stages/30-structure.md@@ -29,14 +29,16 @@## 只加载(只读和本次改动相关的条目)-- [components.md](../references/components.md):C-01 原子层从 `@lobehub/ui` 取用(硬性规则)· **C-11 分层边界:原子层取用,组合层自建** · C-02 按需求查 · C-03 易混组件 · C-04 对话界面组合顺序 · C-05 库里没有的组件 · C-06 其他命名空间 · C-07 控制台套件 · C-08 控制台按场景选组件 · C-09 `TitleWithTips` · C-10 `BarList`+- [components.md](../references/components.md):C-01 原子层从 `@lobehub/ui` 取用(web 硬性规则;RN 用项目组件库)· **C-11 分层边界:原子层取用,组合层自建** · C-02 按需求查 · C-03 易混组件 · C-04 对话界面组合顺序 · C-05 库里没有的组件 · C-06 其他命名空间 · C-07 控制台套件 · C-08 控制台按场景选组件 · C-09 `TitleWithTips` · C-10 `BarList` · C-18 按环境分组的凭证 · C-19 滚动边缘 · C-20 移动端悬浮框架(仅 mobile)- [ecosystem.md](../references/ecosystem.md):E-01 图表 · E-03 模型徽标 · E-04 emoji · E-05 流式 markdown · E-06 边界- [design.md](../references/design.md):D-01 cssVar 是唯一事实源(写法层面) · D-06 复用现成表面工艺 · D-07 品牌气质走主题(**定制色板 / 换品牌主色** → lobe-ui [`tuning-color-palettes`](https://github.com/lobehub/lobe-ui/tree/master/.agents/skills/tuning-color-palettes),本机已安装则按名调用)- [craft.md](../references/craft.md):K-10 编码陷阱## 硬性前提(由 `scripts/lint-lobe.mjs` 机械校验,规则 id 见括号)-**这些约束只覆盖原子层**(按钮、输入、表格、弹层这类不可再分的零件)。业务组合件按 C-11 自建,不受下面这些条目的限制——但仍要遵守「取值走 cssVar」。+**平台作用域:以下 1–3 条是 web / desktop 的写法。** mobile(React Native)项目的原子层取自项目组件库(`components.md` 记录的那一套,如 `@lobehub/ui-rn`)与 `react-native` 原语,样式用 `StyleSheet` / 项目主题的 `useTheme()` token;`lint-lobe.mjs` 按 `product.md` 的平台自动跳过这些 web 规则。++**这些约束只覆盖原子层**(按钮、输入、表格、弹层这类不可再分的零件)。业务组合件按 C-11 自建,不受下面这些条目的限制——但仍要遵守「取值走主题 token」(web:`cssVar`;RN:`useTheme()`)。1. 组件从 `@lobehub/ui` 导入,表单从 `@lobehub/ui/form`、请求驱动的表格从 `@lobehub/ui/pro-table` 导入;应用里不用 `antd` / `antd-style`(`LOBE-ANTD-IMPORT`、`LOBE-FORM-ENTRY`);操作结果提示用 `toast`;图标用 `lucide-react` + `Icon`(`LOBE-ANT-ICONS`)。2. 样式只写 `createStaticStyles` + `cssVar`(从 `@lobehub/ui` 导入),不用 `createStyles`(`LOBE-CREATE-STYLES`)。css 模板里注释只用 `/* */`(`LOBE-CSS-LINE-COMMENT`)。@@ -86,7 +88,7 @@ import '@lobehub/ui/style.css';4. 每个短文本、图标、按钮都按语义选组件,易混组件按 C-03 区分。5. 卡片、表面、加载形用现成组件,不手写底色和边框。6. 同类需求不引入第二个依赖(例如第二个图表库、远程抓 SVG 徽标)。-7. **分层判断过一遍(C-11)**:原子层和皮肤层没有被重写;业务组合件没有硬套库里不贴合的通用组件。自建的组合件内部只用原子层和皮肤层,取值仍走 `cssVar`。+7. **分层判断过一遍(C-11)**:原子层和皮肤层没有被重写;业务组合件没有硬套库里不贴合的通用组件。自建的组合件内部只用原子层和皮肤层,取值仍走主题 token(web:`cssVar`;RN:`useTheme()`)。## 症状 → 规则@@ -104,6 +106,9 @@ import '@lobehub/ui/style.css';| 图标按钮、开关或下拉在读屏里没有名字,或名字读两遍 | C-12 || 确认按钮是英文 OK 或「确定」;请求还没完成弹窗就关了,失败落在弹窗外 | C-15 || 对象属性画成只读键值卡,改一个值要另开编辑弹窗;重置后控件仍显示旧值 | C-17 |+| 按环境配置的 token / 密钥平铺成一张表,env 只是其中一列,看不出哪个凭证属于哪个环境 | C-18 |+| 滚动边缘的模糊吃进正文,或用黑色渐变、硬切;半透明盖在文字上 | C-19 |+| 移动端上下两条实底栏把内容框住 | C-20 || 想要命令面板,却找不到组件或自己重写了一个 | C-05 || 面板里的卡片或代码块高度为 0,列不再滚动 | K-10 || 厂商徽标是灰色插头,或换成了别的品牌 | E-03 |diff --git a/.agents/skills/lobe-design/stages/50-visual.md b/.agents/skills/lobe-design/stages/50-visual.mdindex b70b8114181..4b8ec1774ad 100644--- a/.agents/skills/lobe-design/stages/50-visual.md+++ b/.agents/skills/lobe-design/stages/50-visual.md@@ -4,7 +4,9 @@## 聚焦-- 取值:颜色、圆角、阴影、字体都走 `cssVar`;状态色从基础 token 派生+- 取值:颜色、圆角、阴影、字体都走主题 token,状态色从基础 token 派生。按平台(`product.md` 的 `平台:`):+ - **web / desktop**:`cssVar`(从 `@lobehub/ui` 导入;字体由 `theme.css` 提供)+ - **mobile(React Native)**:项目主题的 `useTheme()` token(如 `theme.colorText`、`theme.borderRadius`),写进 `StyleSheet` / 项目的 `createStyles`;字体用项目主题里的字体 token- **主题色本身要改时**(换品牌 / primary、定制色板、重调状态色阶):不要在本 stage 手改 hex——改去 lobe-ui 的 [`tuning-color-palettes`](https://github.com/lobehub/lobe-ui/tree/master/.agents/skills/tuning-color-palettes)(本机已安装则按名调用)。本 stage 只决定如何**用**已有 token(克制、对比、反 AI 味)- 间距与对齐:4 的倍数;区块之间的间距要大于区块内部的间距;对齐线要少- 排版:字阶、字重、中文排版、等宽数字@@ -14,7 +16,7 @@## 不负责(重要)-- **不评估组件选型,也不评估项目是否符合 LobeUI 架构。** 硬性架构规则由 `lint-lobe.mjs` 兜底,本 stage 只需要跑一下脚本,不需要把架构规范读进上下文。看到选型问题,记 `遗留 → 30`。+- **不评估组件选型,也不评估项目是否符合宿主组件库的架构(web:LobeUI;RN:项目组件库)。** 硬性架构规则由 `lint-lobe.mjs` 兜底,本 stage 只需要跑一下脚本,不需要把架构规范读进上下文。看到选型问题,记 `遗留 → 30`。- 不改信息层级、区域顺序 → 40;不改文案措辞 → 75- 不补状态和边界 → 70- 不重新定方向(0→1 页面的方向卡由 20 产出,本 stage 只执行)diff --git a/.agents/skills/lobe-design/stages/75-copy.md b/.agents/skills/lobe-design/stages/75-copy.mdindex 3107c599845..b653da1e957 100644--- a/.agents/skills/lobe-design/stages/75-copy.md+++ b/.agents/skills/lobe-design/stages/75-copy.md@@ -26,7 +26,7 @@## 选 profile(渐进式披露)-1. 读 `product.md` 的 `copy-profile:`。可以有多个,用路由区分:`copy-profile: consumer; /admin → admin`。按当前页面所在路由取一个。+1. 读 `product.md` 的 `copy-profile:`。可以有多个,用路由区分:`copy-profile: consumer; /admin → admin`。按当前页面所在路由取一个。路由按**路径段**匹配,不是字符串前缀:`/api-keys` 命中 `/:wsSlug/api-keys`、`/acme/api-keys/new`,不命中 `/api-keys-legacy`;`/*/api-keys` 的 `*` 恰好一段,`/admin/**` 任意多段,`^/admin` 只从根匹配;多条命中取字面段多的。`refs.mjs --page <路由>` 可直接指定当前页面。2. 没写 → 按 product.md 的「产品类型」推断:消费级聊天 / 社区 → `consumer`;团队协作 / SaaS / 专业工具 → `saas`;管理后台 / 运营 / 审批 / ops → `admin`;开发者平台 / API 控制台 → `devtool`。3. 没有 product.md → 问一句「这页的主要用户是:个人用户 / 团队用户 / 内部运营 / 开发者?」。不能问时按路由和页面内容推断,在输出里写明「profile 为推断」,并记 `遗留 → 05`。4. `node scripts/refs.mjs "<指令>" --stage 75-copy [--profile <id> | --root <项目根>]` 列出要读的文件:copy-core 与 copy 整份,profile 文件**只读选中的那一份**,其余跳过。diff --git a/.agents/skills/lobe-design/tests/fixtures/bad-rn.tsx b/.agents/skills/lobe-design/tests/fixtures/bad-rn.tsxnew file mode 100644index 00000000000..40e4c106e0e--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/bad-rn.tsx@@ -0,0 +1,19 @@+// lobe-design-platform: mobile+// RN 回归:web 专属规则不报;RN 专属与跨平台规则照常报+import { Button } from '@lobehub/ui'; // expect: LOBE-RN-DOM-UI+import Markdown from '@lobehub/ui/es/Markdown'; // expect: LOBE-RN-DOM-UI+import { StyleSheet, View } from 'react-native';+import { ActionIcon } from '@lobehub/ui-rn';+import { Trash2 } from 'lucide-react-native';++const styles = StyleSheet.create({+ root: { backgroundColor: '#ff0000' }, // expect: LOBE-RAW-COLOR+});++export const Bad = () => (+ <View style={styles.root}>+ <Button>清除缓存</Button>+ <Markdown>{'**hi**'}</Markdown>+ <ActionIcon icon={Trash2} /> {/* expect: LOBE-ICON-BUTTON-LABEL */}+ </View>+);diff --git a/.agents/skills/lobe-design/tests/fixtures/good-rn.tsx b/.agents/skills/lobe-design/tests/fixtures/good-rn.tsxnew file mode 100644index 00000000000..9d0a1c82d5b--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/good-rn.tsx@@ -0,0 +1,29 @@+// lobe-design-platform: mobile+// RN:createStyles 来自项目主题、fontFamily / outline 是 RN 样式、ui-rn 是原子层、图标按钮用 accessibilityLabel+import { ActionIcon, Button } from '@lobehub/ui-rn';+import type { ThemeConfig } from '@lobehub/ui';+import { useTheme as useWebTheme } from '@lobehub/ui';+import { colorScales } from '@lobehub/ui/es/styles';+import { preprocessMarkdownContent } from '@lobehub/ui/es/hooks/useMarkdown/utils';+import { Trash2 } from 'lucide-react-native';+import { StyleSheet, Text, View } from 'react-native';++import { createStyles, useTheme } from '@/theme';++const useStyles = createStyles((token) => ({+ title: { color: token.colorText, fontFamily: 'PingFang SC' },+}));++const styles = StyleSheet.create({ row: { gap: 8, outline: 'none', padding: 12 } });++export const Modal = ({ onClear, theme }: { onClear: () => void; theme?: ThemeConfig }) => {+ const s = useStyles();+ const t = useTheme();+ return (+ <View style={[styles.row, { borderColor: t.colorBorder }]}>+ <Text style={s.title}>会话</Text>+ <ActionIcon accessibilityLabel="删除会话" icon={Trash2} />+ <Button onPress={onClear}>清除缓存</Button>+ </View>+ );+};diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/package.json b/.agents/skills/lobe-design/tests/fixtures/rn-project/package.jsonnew file mode 100644index 00000000000..7ad693be5e1--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/package.json@@ -0,0 +1,14 @@+{+ "name": "rn-demo",+ "private": true,+ "main": "expo-router/entry",+ "dependencies": {+ "@lobehub/ui": "^2.0.0",+ "@lobehub/ui-rn": "workspace:*",+ "@react-navigation/native": "^7.0.0",+ "expo": "~52.0.0",+ "expo-router": "~4.0.0",+ "react": "18.3.1",+ "react-native": "0.76.0"+ }+}diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/Button.tsx b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/Button.tsxnew file mode 100644index 00000000000..388960cb660--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/Button.tsx@@ -0,0 +1,21 @@+import { Pressable, StyleSheet, Text } from 'react-native';++import { createStyles, useTheme } from '@/theme';++const useStyles = createStyles((token) => ({+ label: { color: token.colorTextLightSolid, fontFamily: 'PingFang SC', fontSize: token.fontSize },+}));++const styles = StyleSheet.create({+ root: { alignItems: 'center', borderRadius: 8, outline: 'none', paddingHorizontal: 16, paddingVertical: 8 },+});++export const Button = ({ children, onPress }: { children: string; onPress?: () => void }) => {+ const theme = useTheme();+ const s = useStyles();+ return (+ <Pressable accessibilityRole="button" onPress={onPress} style={[styles.root, { backgroundColor: theme.colorPrimary }]}>+ <Text style={s.label}>{children}</Text>+ </Pressable>+ );+};diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/IconButton.tsx b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/IconButton.tsxnew file mode 100644index 00000000000..b311fe7c747--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/IconButton.tsx@@ -0,0 +1,5 @@+import { ActionIcon } from '@lobehub/ui-rn';++export const IconButton = (props: { icon: any; label: string; onPress?: () => void }) => (+ <ActionIcon accessibilityLabel={props.label} icon={props.icon} onPress={props.onPress} />+);diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/hooks/useMarkdown/useMarkdownPlugins.ts b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/hooks/useMarkdown/useMarkdownPlugins.tsnew file mode 100644index 00000000000..d42c0bf9b52--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/hooks/useMarkdown/useMarkdownPlugins.ts@@ -0,0 +1,6 @@+// RN 复用 web 包里平台无关的 Markdown 插件与工具(#2:不是 DOM 组件,不报 LOBE-RN-DOM-UI)+import { rehypeKatexDir } from '@lobehub/ui/es/Markdown/plugins/rehypeKatexDir';+import { remarkCustomFootnotes } from '@lobehub/ui/es/Markdown/plugins/remarkCustomFootnotes';+import { preprocessMarkdownContent } from '@lobehub/ui/es/hooks/useMarkdown/utils';++export const useMarkdownPlugins = () => ({ preprocess: preprocessMarkdownContent, rehype: [rehypeKatexDir], remark: [remarkCustomFootnotes] });diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/styles/theme/seeds.ts b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/styles/theme/seeds.tsnew file mode 100644index 00000000000..b35ee0a096f--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/components/styles/theme/seeds.ts@@ -0,0 +1,3 @@+import { colorScales, neutralColorScales } from '@lobehub/ui/es/styles';++export const seeds = { colorScales, neutralColorScales };diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/src/features/ChatList/index.tsx b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/features/ChatList/index.tsxnew file mode 100644index 00000000000..c96835add27--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/src/features/ChatList/index.tsx@@ -0,0 +1,32 @@+import { ActionIcon, Button } from '@lobehub/ui-rn';+import { Trash2 } from 'lucide-react-native';+import { FlatList, StyleSheet, Text, View } from 'react-native';++import { createStyles } from '@/theme';++const useStyles = createStyles((token) => ({+ title: { color: token.colorText, fontFamily: 'Inter', fontSize: token.fontSizeLG },+}));++const styles = StyleSheet.create({+ row: { flexDirection: 'row', gap: 8, padding: 12 },+});++export const ChatList = ({ items, onClear }: { items: { id: string; title: string }[]; onClear: () => void }) => {+ const s = useStyles();+ return (+ <View>+ <FlatList+ data={items}+ keyExtractor={(i) => i.id}+ renderItem={({ item }) => (+ <View style={styles.row}>+ <Text style={s.title}>{item.title}</Text>+ <ActionIcon accessibilityLabel="删除会话" icon={Trash2} />+ </View>+ )}+ />+ <Button onPress={onClear}>清除缓存</Button>+ </View>+ );+};diff --git a/.agents/skills/lobe-design/tests/fixtures/rn-project/tsconfig.json b/.agents/skills/lobe-design/tests/fixtures/rn-project/tsconfig.jsonnew file mode 100644index 00000000000..fcf03faa63f--- /dev/null+++ b/.agents/skills/lobe-design/tests/fixtures/rn-project/tsconfig.json@@ -0,0 +1,10 @@+{+ // RN 项目把自己的组件库通过 alias 暴露成 @lobehub/ui-rn+ "compilerOptions": {+ "strict": true,+ "paths": {+ "@/*": ["./src/*"],+ "@lobehub/ui-rn": ["./src/components"]+ }+ }+}diff --git a/.agents/skills/lobe-design/tests/run.mjs b/.agents/skills/lobe-design/tests/run.mjsindex c64a4fa412b..e81a9edb1d1 100644--- a/.agents/skills/lobe-design/tests/run.mjs+++ b/.agents/skills/lobe-design/tests/run.mjs@@ -7,14 +7,15 @@ import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { route } from '../scripts/route.mjs';-import { isZhLocaleJson, lintText } from '../scripts/lint-lobe.mjs';+import { isDomComponentImport, isZhLocaleJson, lintPaths, lintText, RULES } from '../scripts/lint-lobe.mjs';+import { globToRe, parseAllow, parseApplicability, parsePlatform, projectContext } from '../scripts/platform.mjs';const lintPathsHas = (p) => isZhLocaleJson(p);import { checkText } from '../scripts/check-detail.mjs';import { checkLearnings } from '../scripts/check-learnings.mjs';import { translate } from '../scripts/intent.mjs';-import { allMeta, resolveRefs } from '../scripts/refs.mjs';-import { applyBlock, detectContext, detectProjectLayer, findGuideFile, renderBlock } from '../scripts/bootstrap.mjs';-import { assessProjectLayer, fingerprintOf, parseInitMeta, renderInitMeta, scanProject } from '../scripts/project-scan.mjs';+import { allMeta, matchRoute, resolveRefs } from '../scripts/refs.mjs';+import { applyBlock, BEGIN, detectContext, detectLang, detectProjectLayer, END, findGuideFile, readBlockMode, renderBlock, resolveMode } from '../scripts/bootstrap.mjs';+import { assessProjectLayer, classifyComponent, fingerprintOf, parseInitMeta, renderInitMeta, scanProject } from '../scripts/project-scan.mjs';import { assess } from '../scripts/upstream.mjs';const dir = dirname(fileURLToPath(import.meta.url));@@ -100,39 +101,6 @@ const got = checkText(detailBad, 'detail-bad.tsx').map((f) => f.id);for (const id of want) t(`detail-bad.tsx → ${id}`, got.includes(id));t('detail-bad.tsx has no unexpected findings', got.every((id) => want.includes(id)), got.filter((id) => !want.includes(id)).join(','));const detailGood = checkText(readFileSync(join(fx, 'detail-good.tsx'), 'utf8'), 'detail-good.tsx');-{- const fetchSrc = 'const X = () => { fetch("/api"); return <div />; };\n';- const ids = (src) => checkText(src, 'x.tsx').map((f) => f.id);- t('detail: 没写理由的豁免不生效', ids(`// lobe-design-ignore DETAIL-NO-LOADING\n${fetchSrc}`).includes('DETAIL-NO-LOADING'));- t('detail: 字符串里出现的豁免文字不生效', ids(`const s = 'lobe-design-ignore DETAIL-NO-LOADING: x';\n${fetchSrc}`).includes('DETAIL-NO-LOADING'));- t('detail: 块注释里冒号后为空不算理由', ids(`/* lobe-design-ignore DETAIL-NO-LOADING: */\n${fetchSrc}`).includes('DETAIL-NO-LOADING'));- t('detail: 冒号后为空不会借用下一行当理由', ids(`// lobe-design-ignore DETAIL-NO-LOADING:\nexport ${fetchSrc}`).includes('DETAIL-NO-LOADING'));- t('detail: 理由只有注释符不算', ids(`// lobe-design-ignore DETAIL-NO-LOADING: //\n${fetchSrc}`).includes('DETAIL-NO-LOADING'));- t('detail: 带理由的注释豁免生效', !ids(`// lobe-design-ignore DETAIL-NO-LOADING, DETAIL-NO-ERROR: 由父组件处理\n${fetchSrc}`).some((x) => x === 'DETAIL-NO-LOADING' || x === 'DETAIL-NO-ERROR'));-}-{- const raw = (src) => lintText(src, 'src/x.ts').map((f) => f.id);- t('lint: 字符串里的整文件豁免不生效', raw("const docs = 'lobe-design-ignore-file LOBE-RAW-COLOR: example';\nconst c = '#1677ff';\n").includes('LOBE-RAW-COLOR'));- t('lint: 字符串里没理由的豁免文字不报 IGNORE-NO-REASON', !raw("const docs = 'lobe-design-ignore LOBE-RAW-COLOR';\n").includes('LOBE-IGNORE-NO-REASON'));- t('lint: 行尾注释豁免仍生效', !raw("const c = '#1677ff'; // lobe-design-ignore LOBE-RAW-COLOR: 品牌色由设计稿指定\n").includes('LOBE-RAW-COLOR'));- t('lint: 块注释豁免冒号后为空 → IGNORE-NO-REASON 且不生效', (() => { const r = raw("/* lobe-design-ignore LOBE-RAW-COLOR: */\nconst c = '#1677ff';\n"); return r.includes('LOBE-IGNORE-NO-REASON') && r.includes('LOBE-RAW-COLOR'); })());- t('lint: 注释在字符串之后仍识别', !raw("const a = 'x'; const c = '#1677ff'; // lobe-design-ignore LOBE-RAW-COLOR: 演示\n").includes('LOBE-RAW-COLOR'));-}-{- // 遍历时跳过软链目录:同一份文件只扫一次- const tmp = mkdtempSync(join(tmpdir(), 'ld-symlink-'));- try {- mkdirSync(join(tmp, 'real'));- writeFileSync(join(tmp, 'real', 'a.tsx'), 'const a = { color: \'#1677ff\' };\nconst X = () => { fetch("/api"); return <div />; };\n');- symlinkSync(join(tmp, 'real'), join(tmp, 'alias'), 'dir');- const lint = spawnSync(process.execPath, [join(skill, 'scripts', 'lint-lobe.mjs'), tmp, '--json'], { encoding: 'utf8' });- const detail = spawnSync(process.execPath, [join(skill, 'scripts', 'check-detail.mjs'), tmp, '--json'], { encoding: 'utf8' });- const lintFiles = new Set(JSON.parse(lint.stdout).findings?.map?.((f) => f.file) ?? JSON.parse(lint.stdout).map((f) => f.file));- const detailHits = JSON.parse(detail.stdout).filter((f) => f.id === 'DETAIL-NO-LOADING').length;- t('lint-lobe: 不进入软链目录', lintFiles.size === 1, [...lintFiles].join(','));- t('check-detail: 不进入软链目录', detailHits === 1, String(detailHits));- } finally { rmSync(tmp, { recursive: true, force: true }); }-}t('detail-good.tsx has 0 findings', detailGood.length === 0, detailGood.map((f) => f.id).join(','));// 5b) 3.0.0 · 抽象指令翻译:归一化成可执行表述,或转成追问(不猜着动手)@@ -208,32 +176,24 @@ console.log('== copy profiles');const e = resolveRefs('把 /admin 下的提示文案改一下', { stage: '75-copy', root });t('copy: product.md 按路由分区选 profile', JSON.stringify(loaded(e)) === '["admin"]', JSON.stringify(e.copyProfile));const f2 = resolveRefs('把开发者 api 页的文案改一下', { stage: '75-copy', root });- writeFileSync(join(root, '.agents', 'ux', 'product.md'), '# 产品画像\n\ncopy-profile: consumer; /settings, /resource → saas\n');- const g = resolveRefs('把 /resource 页的文案改一下', { stage: '75-copy', root });- t('copy: 一条分区可列多条路由', JSON.stringify(loaded(g)) === '["saas"]' && g.copyProfile.source.includes('/resource'), JSON.stringify(g.copyProfile));t('copy: product.md 存在时不被列表外的触发词带偏', JSON.stringify(loaded(f2)) === '["consumer"]', JSON.stringify(f2.copyProfile));+ // 5.5.0:路由分区按路径段匹配(动态段 / 通配)+ writeFileSync(join(root, '.agents', 'ux', 'product.md'), '# 产品画像\n\ncopy-profile: saas; /api-keys → devtool; /*/billing → admin; ^/admin → admin\n');+ const g = resolveRefs('把 /:wsSlug/api-keys 页的提示文案改一下', { stage: '75-copy', root });+ t('copy: /api-keys 命中带动态段的 /:wsSlug/api-keys', JSON.stringify(loaded(g)) === '["devtool"]', JSON.stringify(g.copyProfile));+ t('copy: --page 指定路由', JSON.stringify(loaded(resolveRefs('改下文案', { stage: '75-copy', root, page: '/acme/billing' }))) === '["admin"]');+ t('copy: /*/billing 命中 /:wsSlug/billing', JSON.stringify(loaded(resolveRefs('改下文案', { stage: '75-copy', root, page: '/:wsSlug/billing' }))) === '["admin"]');+ t('copy: 段不匹配时回落默认 profile', JSON.stringify(loaded(resolveRefs('改下文案', { stage: '75-copy', root, page: '/billing-old' }))) === '["saas"]');+ t('copy: matchRoute 按段匹配', matchRoute('/*/api-keys', '/:wsSlug/api-keys') && !matchRoute('/*/api-keys', '/api-keys') && matchRoute('/admin/**', '/admin')+ && !matchRoute('/admin', '/administrators') && !matchRoute('/api-keys', '/api-keys-legacy') && !matchRoute('^/admin', '/ws/admin') && matchRoute('^/admin', '/admin/users') && matchRoute('/api-keys', 'https://x.dev/acme/api-keys?tab=1'));} finally { rmSync(root, { recursive: true, force: true }); }t('copy: 其他 stage 不加载 profile 文件', resolveRefs('把列表页的间距调一下').stages.every((s) => s.stage === '75-copy' || !s.refs.some((x) => x.tier === 'profile')));- {- const cwdRoot = mkdtempSync(join(tmpdir(), 'ld-copy-cwd-'));- try {- mkdirSync(join(cwdRoot, '.agents', 'ux'), { recursive: true });- writeFileSync(join(cwdRoot, '.agents', 'ux', 'product.md'), '# 产品画像\n\ncopy-profile: consumer\n');- const r = spawnSync(process.execPath, [join(skill, 'scripts', 'refs.mjs'), '把提示文案改一下', '--stage', '75-copy', '--json'], { encoding: 'utf8', cwd: cwdRoot });- const cp = r.status === 0 ? JSON.parse(r.stdout).copyProfile : null;- t('refs.mjs 不带 --root 时读当前目录的 product.md', JSON.stringify(cp?.selected) === '["consumer"]' && cp?.source === 'product.md', r.stderr || JSON.stringify(cp));- } finally { rmSync(cwdRoot, { recursive: true, force: true }); }- }t('refs.mjs --profile 未知 → exit 2', run('refs.mjs', ['改文案', '--stage', '75-copy', '--profile', 'nope']).status === 2);// zh-CN 语言包:只跑 locale 规则;同样内容的 tsx 会跑全部规则const zh = '{\n "save": "已保存API密钥",\n "fail": "保存失败,请重试",\n "ok": "已保存 API 密钥",\n "color": "#ff0000"\n}\n';const zf = lintText(zh, 'locales/zh-CN/common.json').map((x) => `${x.line}:${x.id}`);t('copy: zh-CN 语言包报 CJK 留白与半角标点', JSON.stringify(zf) === '["2:LOBE-CJK-LATIN-SPACE","3:LOBE-HALFWIDTH-PUNCT"]', zf.join(','));t('copy: 语言包不跑非文案规则(#ff0000 不报 RAW-COLOR)', !zf.some((x) => x.includes('RAW-COLOR')));- const rawColor = (src) => lintText(src, 'src/x.ts').filter((x) => x.id === 'LOBE-RAW-COLOR').map((x) => x.line);- t('RAW-COLOR: 全透明哨兵值不报', rawColor("const BLANK = new Set(['transparent', 'rgba(0,0,0,0)', '#0000', '#00000000']);\n").length === 0);- t('RAW-COLOR: 颜色作为比较操作数不报', rawColor("if (bg === 'rgba(0, 0, 0, 0.5)' || '#fff' !== fg) return;\n").length === 0);- t('RAW-COLOR: 半透明 / 不透明颜色照报', JSON.stringify(rawColor("const a = { color: 'rgba(0,0,0,0.45)' };\nconst b = { color: '#1677ff' };\nconst c = { color: x === 'a' ? '#fff' : '#000' };\n")) === '[1,2,3]');t('copy: 非 zh-CN 的 json 不被扫描', !lintPathsHas('locales/en-US/common.json') && lintPathsHas('locales/zh-CN/common.json') && lintPathsHas('src/locales/zh_CN.json'));}@@ -289,21 +249,11 @@ console.log('== bootstrap');t('bootstrap fs: 重复运行文件不变(幂等)', readFileSync(guide, 'utf8') === once);// --check 语义t('bootstrap fs: --check 已接入 → 0', run('bootstrap.mjs', ['--check', '--root', tmp]).status === 0);- // 格式化工具只改空白 / 表格分隔线时不算过期;托管块内容真正变了才算- const fmt = readFileSync(guide, 'utf8').replace(/\| --- \|/g, '| ------ |').replace(/ \|\n/g, ' |\n').replace('修误报 · minor', '修误报・minor').replace('入口与顺序', '入口 与顺序');- writeFileSync(guide, fmt);- t('bootstrap fs: --check 只是重新格式化 → 0', run('bootstrap.mjs', ['--check', '--root', tmp]).status === 0);- writeFileSync(guide, once.replace('node "$LOBE_DESIGN/scripts/route.mjs"', 'node"$LOBE_DESIGN/scripts/route.mjs"'));- t('bootstrap fs: --check 命令里删掉空格算过期 → 1', run('bootstrap.mjs', ['--check', '--root', tmp]).status === 1);- writeFileSync(guide, once.replace('## 1.', '## 1. 过期'));- const drift = run('bootstrap.mjs', ['--check', '--json', '--root', tmp]);- t('bootstrap fs: --check 托管块内容过期 → 1', drift.status === 1 && JSON.parse(drift.stdout).blockCurrent === false, drift.stdout);- writeFileSync(guide, once);const fresh = mkdtempSync(join(tmpdir(), 'lobe-fresh-'));t('bootstrap fs: --check 未接入 → 1', run('bootstrap.mjs', ['--check', '--root', fresh]).status === 1);rmdirSync(fresh, { recursive: true });// 版本落后时 --check 必须失败(否则升级不会被发现)- writeFileSync(guide, readFileSync(guide, 'utf8').replace(/skill 版本 [\d.]+/, 'skill 版本 1.0.0'));+ writeFileSync(guide, readFileSync(guide, 'utf8').replace(/skill (版本|version) [\d.]+/, 'skill $1 1.0.0'));t('bootstrap fs: --check 版本落后 → 1', run('bootstrap.mjs', ['--check', '--root', tmp]).status === 1);// CLAUDE.md 兜底:没有 AGENTS.md 时写入 CLAUDE.mdconst tmp2 = mkdtempSync(join(tmpdir(), 'lobe-claude-'));@@ -321,10 +271,10 @@ console.log('== bootstrap');writeFileSync(join(tmp3, 'AGENTS.md'), '# host\n');const ctx3 = detectContext(tmp3);t('bootstrap fs: 探测到仓库内安装与 ux 文件(固定顺序)', ctx3.localSkill && JSON.stringify(ctx3.ux) === JSON.stringify(['product.md', 'lobe-design-rules.md', 'audit/']), JSON.stringify(ctx3));- t('bootstrap fs: 无 .agents 时上下文为空', JSON.stringify(detectContext(join(tmp3, '.agents/ux/audit'))) === JSON.stringify({ localSkill: false, ux: null }));+ t('bootstrap fs: 无 .agents 时上下文为空', JSON.stringify(detectContext(join(tmp3, '.agents/ux/audit'))) === JSON.stringify({ localSkill: false, ux: null, platform: 'web' }));run('bootstrap.mjs', ['--root', tmp3]);const host1 = readFileSync(join(tmp3, 'AGENTS.md'), 'utf8');- t('bootstrap fs: 宿主项目块指向仓库内安装与 ux', host1.includes('export LOBE_DESIGN="./.agents/skills/lobe-design"\n') && host1.includes('.agents/ux/product.md') && host1.startsWith('# host\n'));+ t('bootstrap fs: 宿主项目块指向仓库内安装与 ux', /^export LOBE_DESIGN="\.\/\.agents\/skills\/lobe-design"(?:\s|$)/m.test(host1) && host1.includes('.agents/ux/product.md') && host1.startsWith('# host\n'));const r3 = run('bootstrap.mjs', ['--root', tmp3, '--json']);t('bootstrap fs: 宿主项目重复运行 unchanged', JSON.parse(r3.stdout).action === 'unchanged' && readFileSync(join(tmp3, 'AGENTS.md'), 'utf8') === host1);rmSync(tmp3, { recursive: true, force: true });@@ -355,29 +305,6 @@ console.log('== project-scan');t('project-scan: 发现组件目录', facts.components.some((c) => c.dir === 'src/components'));t('project-scan: 发现路由目录', facts.routes.some((r) => r.dir === 'app'));t('project-scan: 指纹稳定', fingerprintOf(facts) === facts.fingerprint && facts.fingerprint.length === 12);- // 组件目录超过样本上限后,增删文件仍要改变指纹- for (let i = 0; i < 60; i++) writeFileSync(join(tmp, `src/components/Gen${i}.tsx`), 'export {};\n');- const many = scanProject(tmp);- writeFileSync(join(tmp, 'src/components/Gen60.tsx'), 'export {};\n');- const more = scanProject(tmp);- t('project-scan: 超过样本上限时文件数仍计全量且影响指纹', more.components.find((c) => c.dir === 'src/components')?.fileCount === 62 && more.fingerprint !== many.fingerprint, JSON.stringify(more.components));- for (let i = 0; i <= 60; i++) unlinkSync(join(tmp, `src/components/Gen${i}.tsx`));- // 文件数不变的改名 / 路由子目录替换也要改变指纹- const base = scanProject(tmp).fingerprint;- writeFileSync(join(tmp, 'src/components/Bar.tsx'), 'export {};\n'); unlinkSync(join(tmp, 'src/components/Foo.tsx'));- const renamed = scanProject(tmp).fingerprint;- rmdirSync(join(tmp, 'app/settings')); mkdirSync(join(tmp, 'app/profile'));- const rerouted = scanProject(tmp).fingerprint;- t('project-scan: 同数量改名 / 路由替换改变指纹', base !== renamed && renamed !== rerouted, `${base} ${renamed} ${rerouted}`);- writeFileSync(join(tmp, 'src/components/Foo.tsx'), 'export const Foo = () => null;\n'); unlinkSync(join(tmp, 'src/components/Bar.tsx'));- // 超过样本上限的目录里,样本之外的同数量改名也要改变指纹- for (let i = 0; i < 30; i++) writeFileSync(join(tmp, `src/components/F${String(i).padStart(2, '0')}.tsx`), 'export {};\n');- const before30 = scanProject(tmp).fingerprint;- unlinkSync(join(tmp, 'src/components/F25.tsx')); writeFileSync(join(tmp, 'src/components/Z25.tsx'), 'export {};\n');- t('project-scan: 样本之外的改名也改变指纹', scanProject(tmp).fingerprint !== before30);- for (let i = 0; i < 30; i++) if (i !== 25) unlinkSync(join(tmp, `src/components/F${String(i).padStart(2, '0')}.tsx`));- unlinkSync(join(tmp, 'src/components/Z25.tsx'));- rmdirSync(join(tmp, 'app/profile')); mkdirSync(join(tmp, 'app/settings'));t('project-scan --check 缺文件 → 1', run('project-scan.mjs', ['--check', '--root', tmp]).status === 1);const layer0 = detectProjectLayer(tmp);@@ -404,7 +331,6 @@ console.log('== project-scan');run('bootstrap.mjs', ['--root', tmp]);// 恢复齐全 meta 后缺 components 应 WARNunlinkSync(join(tmp, '.agents/ux/components.md'));- run('bootstrap.mjs', ['--root', tmp]);const bchk = run('bootstrap.mjs', ['--check', '--root', tmp]);t('bootstrap --check 已接入但缺 components → 0 + WARN', bchk.status === 0 && /WARN/.test(bchk.stderr + bchk.stdout), bchk.stderr + bchk.stdout);@@ -417,14 +343,162 @@ console.log('== project-scan');}}+// 5d2b) 5.5.0 · 平台门控(#1):RN / mobile 项目不跑 web 专属规则;项目层「不适用」关掉规则;托管块与 Round 2 按平台+console.log('== platform (mobile / RN)');+{+ const rn = join(fx, 'rn-project');+ const WEB_ONLY = new Set(RULES.filter((r) => !r.platforms.includes('mobile')).map((r) => r.id));+ t('platform: 每条规则声明 platforms', RULES.every((r) => Array.isArray(r.platforms) && r.platforms.length));+ t('platform: web 专属规则含 cssVar / createStaticStyles / antd / outline / font-family 类', ['LOBE-CREATE-STYLES', 'LOBE-ANTD-IMPORT', 'LOBE-ANT-CLASS', 'LOBE-OUTLINE-NONE', 'LOBE-FONT-FAMILY', 'LOBE-REIMPLEMENT-ATOM'].every((id) => WEB_ONLY.has(id)));+ const ctx = projectContext(rn);+ t('platform: RN 依赖 → mobile(package.json)', ctx.platform === 'mobile' && ctx.source === 'package.json', JSON.stringify({ ...ctx, off: [...ctx.off] }));+ const auto = lintPaths([join(rn, 'src')]);+ const webOnlyFail = auto.findings.filter((f) => f.level === 'FAIL' && WEB_ONLY.has(f.id));+ t('platform: RN fixture auto → 0 web-only FAIL', webOnlyFail.length === 0, webOnlyFail.map((f) => `${f.id}@${f.file}:${f.line}`).join(', '));+ t('platform: RN fixture auto → 0 FAIL', auto.findings.filter((f) => f.level === 'FAIL').length === 0, auto.findings.map((f) => f.id).join(','));+ t('platform: RN fixture 不报 REIMPLEMENT-ATOM(ui-rn 是原子层)', !auto.findings.some((f) => f.id === 'LOBE-REIMPLEMENT-ATOM'));+ const forced = lintPaths([join(rn, 'src')], { platform: 'web' });+ t('platform: 同一 fixture 强制 web 仍报 web 规则(门控生效而非规则失效)', forced.findings.some((f) => f.id === 'LOBE-CREATE-STYLES') && forced.findings.some((f) => f.id === 'LOBE-FONT-FAMILY'));+ t('platform: K-07 图标按钮接受 accessibilityLabel', !forced.findings.some((f) => f.id === 'LOBE-ICON-BUTTON-LABEL'));+ t('platform: *.native.tsx 视为 mobile', !lintText("const s = createStyles(() => ({}));\n", 'x.native.tsx').some((f) => f.id === 'LOBE-CREATE-STYLES'));+ t('platform: mobile 上 RAW-COLOR 给 RN 修法(不提 cssVar)', lintText("const c = '#ff0000';\n", 'a.tsx', { platform: 'mobile' }).every((f) => f.id !== 'LOBE-RAW-COLOR' || !f.msg.includes('cssVar')));+ // product.md:平台与适用性+ t('platform: parsePlatform 中文 / 英文 / 表格', parsePlatform('平台:mobile(主),web') === 'mobile' && parsePlatform('platform: web') === 'web' && parsePlatform('| 平台 | mobile |') === 'mobile');+ const off = parseApplicability('| C-01..C-03 | 不适用 | RN |\n| P-01 | 强调 |\nlint-off: LOBE-RAW-COLOR, D-11\n');+ t('platform: 适用性表展开区间 + lint-off', ['C-01', 'C-02', 'C-03', 'LOBE-RAW-COLOR', 'D-11'].every((x) => off.has(x)) && !off.has('P-01'), [...off].join(','));+ const tmp = mkdtempSync(join(tmpdir(), 'ld-rn-'));+ try {+ cpSync(rn, tmp, { recursive: true });+ writeFileSync(join(tmp, 'src/components/Raw.tsx'), "export const c = { color: '#ff0000' };\n");+ t('platform: 未标不适用时 RAW-COLOR 照常 FAIL', lintPaths([join(tmp, 'src')]).findings.some((f) => f.id === 'LOBE-RAW-COLOR'));+ mkdirSync(join(tmp, '.agents/ux'), { recursive: true });+ writeFileSync(join(tmp, '.agents/ux/product.md'), '# 产品画像\n平台:mobile\n\n| 规则 | 适用性 | 理由 |\n| --- | --- | --- |\n| D-10 | 不适用 | 颜色走 RN 主题,迁移中 |\n');+ const pc = projectContext(tmp);+ t('platform: product.md 平台优先于依赖', pc.platform === 'mobile' && pc.source === 'product.md');+ t('platform: product.md 标 D-10 不适用 → RAW-COLOR 不报', !lintPaths([join(tmp, 'src')]).findings.some((f) => f.id === 'LOBE-RAW-COLOR'));+ const cli = spawnSync(process.execPath, [join(skill, 'scripts/lint-lobe.mjs'), 'src'], { encoding: 'utf8', cwd: tmp });+ t('platform: lint CLI 在 RN 项目 auto → exit 0 并显示 platform=mobile', cli.status === 0 && /platform=mobile/.test(cli.stdout), cli.stdout.slice(-300));+ t('lint-lobe.mjs --platform 未知 → exit 2', run('lint-lobe.mjs', ['tests/fixtures/good.tsx', '--platform', 'tv']).status === 2);+ // 托管块:按平台生成,mobile 无 web 专属指令;优先级改写+ writeFileSync(join(tmp, '.agents/ux/components.md'), '# 组件盘点\n');+ const mb = renderBlock('5.5.0', undefined, undefined, detectContext(tmp));+ t('bootstrap: mobile 托管块有平台节', mb.includes('平台:mobile') && mb.includes('@lobehub/ui-rn'));+ t('bootstrap: mobile 托管块不指示 web 写法(web 专属词只出现在「不适用」句)', mb.split('\n').filter((l) => /cssVar|createStaticStyles|antd|font-family/.test(l)).every((l) => l.includes('不适用')), mb);+ t('bootstrap: 不再写「冲突时以 skill 为准」,项目层适用性优先', !mb.includes('冲突时以 skill 为准') && mb.includes('优先于 skill 的通用规则') && mb.includes('写明理由'));+ const wb = renderBlock('5.5.0', undefined, undefined, { ux: ['product.md'] });+ t('bootstrap: web 托管块无 mobile 节、同样用新优先级', !wb.includes('平台:mobile') && !wb.includes('冲突时以 skill 为准') && wb.includes('优先于 skill 的通用规则'));+ t('bootstrap: skill 内文件写成 $LOBE_DESIGN/scripts/…,缺的项目层文件不写成代码路径', wb.includes('`$LOBE_DESIGN/scripts/pipeline.json`') && !wb.includes('`scripts/pipeline.json`') && !wb.includes('`.agents/ux/lobe-design-rules.md`') && !wb.includes('`.agents/ux/components.md`'));+ } finally { rmSync(tmp, { recursive: true, force: true }); }+ // project-scan:Round 2 分类与 UI 库字段按平台+ const facts = scanProject(rn);+ t('project-scan: RN → platform mobile', facts.stack.platform === 'mobile' && facts.stack.platforms.includes('mobile'));+ t('project-scan: RN 主 UI 库 = @lobehub/ui-rn(alias → src/components)', facts.stack.primaryUi?.name === '@lobehub/ui-rn' && facts.stack.primaryUi?.alias === 'src/components', JSON.stringify(facts.stack.primaryUi));+ t('project-scan: @lobehub/ui 标为仅依赖', facts.stack.depOnlyUi.includes('@lobehub/ui'));+ t('project-scan: 识别导航库', facts.stack.navigation.includes('expo-router') && facts.stack.navigation.includes('@react-navigation/native'));+ t('project-scan: mobile 分类方案无「与 lobe-ui 重复」', JSON.stringify(facts.componentScheme) === '["项目原子层","薄包装","业务组件"]');+ const cls = Object.fromEntries(facts.componentClasses.map((c) => [c.file, c.class]));+ t('project-scan: RN 组件分类', cls['src/components/Button.tsx'] === '项目原子层' && cls['src/components/IconButton.tsx'] === '薄包装' && cls['src/features/ChatList/index.tsx'] === '业务组件', JSON.stringify(cls));+ const scanOut = run('project-scan.mjs', ['--root', rn]).stdout;+ t('project-scan: 人读输出不把 @lobehub/ui 当 RN 界面库', /UI 库:@lobehub\/ui-rn/.test(scanOut) && /仅依赖、不是 RN 界面库:@lobehub\/ui/.test(scanOut) && !/与 lobe-ui 重复/.test(scanOut), scanOut);+ const webStack = { platform: 'web', aliases: {} };+ t('project-scan: web 分类不变(自建 Button → 与 lobe-ui 重复)', classifyComponent('src/components/Button.tsx', 'export const Button = () => <button />;\n', webStack) === '与 lobe-ui 重复'+ && classifyComponent('src/components/X.tsx', "import { Button } from '@lobehub/ui';\nexport const X = (p) => <Button {...p} />;\n", webStack) === '薄包装');+}++// 5d2c) 5.6.0 · #2:DOM-UI 只报组件导入、lint-allow、托管块精简 / 宿主语言、平台中立措辞、RN 图标按钮提示+console.log('== issue #2 (RN follow-ups)');+{+ const rn = join(fx, 'rn-project');+ // 1) LOBE-RN-DOM-UI 只报组件导入+ t('dom-ui: @lobehub/ui/es 下的 hooks / Markdown 插件 / styles 不报', ['@lobehub/ui/es/hooks/useMarkdown/utils', '@lobehub/ui/es/Markdown/plugins/rehypeX', '@lobehub/ui/es/styles'].every((src) => !isDomComponentImport(src, '{ fooBar }')));+ t('dom-ui: 根入口的工具(useTheme / cssVar)与 import type 不报', !isDomComponentImport('@lobehub/ui', '{ useTheme, cssVar }') && !isDomComponentImport('@lobehub/ui', '{ type ThemeConfig }') && !isDomComponentImport('@lobehub/ui/theme.css', ''));+ t('dom-ui: 组件导入照报(根入口 PascalCase / es/<Component> 默认 / 子入口 / antd / 命名空间)', isDomComponentImport('@lobehub/ui', '{ Button }') && isDomComponentImport('@lobehub/ui/es/Markdown', 'Markdown') && isDomComponentImport('@lobehub/ui/es/Markdown/index', '{ default as Md }') && isDomComponentImport('@lobehub/ui/form', '{ Form }') && isDomComponentImport('antd', '{ Button }') && isDomComponentImport('@lobehub/ui', '* as UI'));+ const rnLint = lintPaths([join(rn, 'src')]);+ t('dom-ui: RN fixture 的工具导入(hooks / plugins / seeds)0 finding', rnLint.findings.length === 0 && rnLint.files.some((f) => f.includes('seeds.ts')), rnLint.findings.map((f) => `${f.id}@${f.file}`).join(','));+ // lint-allow+ const al = parseAllow('lint-allow: LOBE-RN-DOM-UI src/legacy/**, src/web/*.tsx\nlint-allow: src/no-rule/**\n');+ t('lint-allow: 解析规则 id 与 glob;没有规则 id 的行忽略', al.length === 1 && al[0].rules[0] === 'LOBE-RN-DOM-UI' && al[0].globs.length === 2);+ t('lint-allow: glob 语义(** 跨目录,* 不跨)', globToRe('src/legacy/**').test('src/legacy/a/b.tsx') && globToRe('src/web/*.tsx').test('src/web/a.tsx') && !globToRe('src/web/*.tsx').test('src/web/x/a.tsx') && globToRe('src/legacy/').test('src/legacy/a.ts'));+ const tmp = mkdtempSync(join(tmpdir(), 'ld-allow-'));+ try {+ cpSync(rn, tmp, { recursive: true });+ mkdirSync(join(tmp, 'src/legacy'), { recursive: true });+ const domFile = "import { Button } from '@lobehub/ui';\nexport const X = () => <Button>保存草稿</Button>;\n";+ writeFileSync(join(tmp, 'src/legacy/Old.tsx'), domFile);+ writeFileSync(join(tmp, 'src/features/New.tsx'), domFile);+ const ids = (r) => r.findings.filter((f) => f.id === 'LOBE-RN-DOM-UI').map((f) => f.file.split(/[\\/]/).slice(-2).join('/'));+ t('lint-allow: 未配置时两处都报', ids(lintPaths([join(tmp, 'src')])).length === 2);+ mkdirSync(join(tmp, '.agents/ux'), { recursive: true });+ writeFileSync(join(tmp, '.agents/ux/product.md'), '# 产品画像\n平台:mobile\n\nlint-allow: LOBE-RN-DOM-UI src/legacy/**\n');+ const after = ids(lintPaths([join(tmp, 'src')]));+ t('lint-allow: 白名单路径关掉该规则,其余路径照报', JSON.stringify(after) === '["features/New.tsx"]', JSON.stringify(after));+ t('lint-allow: 只关指定规则(同路径的 RAW-COLOR 仍报)', (() => { writeFileSync(join(tmp, 'src/legacy/Raw.tsx'), "export const c = '#ff0000';\n"); return lintPaths([join(tmp, 'src')]).findings.some((f) => f.id === 'LOBE-RAW-COLOR' && f.file.includes('legacy')); })());+ } finally { rmSync(tmp, { recursive: true, force: true }); }++ // 4) RN 图标按钮提示只写 accessibilityLabel+ const ib = lintText('<ActionIcon icon={Trash2} />\n', 'x.tsx', { platform: 'mobile' }).find((f) => f.id === 'LOBE-ICON-BUTTON-LABEL');+ t('icon-label: mobile 提示只写 accessibilityLabel / accessibilityRole', ib && /accessibilityLabel/.test(ib.msg) && !/aria-label|title/.test(ib.msg), ib?.msg);+ const ibw = lintText('<ActionIcon icon={Trash2} />\n', 'x.tsx').find((f) => f.id === 'LOBE-ICON-BUTTON-LABEL');+ t('icon-label: web 提示仍是 title / aria-label', ibw && /aria-label/.test(ibw.msg) && !/accessibilityLabel/.test(ibw.msg));++ // 2) 托管块:精简 + 宿主语言,模式行沿用,旧块兼容+ t('bootstrap lang: 英文宿主 → en,中文宿主 → zh,内容不足 → null', detectLang('# Host\n\nThis repo uses pnpm and runs tests before every commit.\n') === 'en' && detectLang('# 项目指南\n\n本仓库使用 pnpm,提交前跑测试。\n') === 'zh' && detectLang('# x\n') === null);+ t('bootstrap mode: 默认精简;已有模式行沿用;flag 覆盖', resolveMode({}).compact && resolveMode({ guideText: `${BEGIN}\n<!-- lobe-design:mode=full lang=zh -->\n${END}` }).compact === false && resolveMode({ guideText: `${BEGIN}\n<!-- lobe-design:mode=full lang=zh -->\n${END}`, compact: true, lang: 'en' }).lang === 'en');+ const ce = renderBlock('5.6.0', undefined, undefined, { compact: true, lang: 'en', ux: ['product.md', 'components.md'], platform: 'mobile' });+ t('bootstrap compact: ≤ 20 行', ce.split('\n').length <= 20, `${ce.split('\n').length} lines`);+ t('bootstrap compact en: 无中文', !/[\u3400-\u9fff]/.test(ce), ce);+ t('bootstrap compact: 保留入口 / 项目层 / 平台 / 优先级 / lint / 版本', ['$LOBE_DESIGN/SKILL.md', 'route.mjs', '.agents/ux/product.md', 'Platform: mobile', 'Precedence', 'lint-lobe.mjs', 'skill version 5.6.0'].every((x) => ce.includes(x)));+ t('bootstrap compact mobile: web 专属词只出现在「不适用」句', ce.split('\n').filter((l) => /cssVar|createStaticStyles|antd/.test(l)).every((l) => /do not apply/.test(l)));+ const cz = renderBlock('5.6.0', undefined, undefined, { compact: true, lang: 'zh' });+ t('bootstrap compact zh: 中文、web 平台行、优先级', cz.includes('精简') && cz.includes('平台:web') && cz.includes('优先于 skill 的通用规则') && cz.split('\n').length <= 20);+ const tmpB = mkdtempSync(join(tmpdir(), 'ld-compact-'));+ try {+ const guide = join(tmpB, 'AGENTS.md');+ const host = '# Agent guide\n\nThis repository uses pnpm. Keep rules terse and run the test suite before every commit.\n';+ // 旧版(5.5.0 完整中文、无模式行)的块:重跑换成精简 + 英文,标记兼容、块外不动+ writeFileSync(guide, applyBlock(host, renderBlock('5.5.0')).text);+ t('bootstrap legacy: 旧块无模式行', readBlockMode(readFileSync(guide, 'utf8')) === null);+ const r1 = run('bootstrap.mjs', ['--root', tmpB, '--json']);+ const a1 = readFileSync(guide, 'utf8');+ t('bootstrap legacy → 精简 + en,替换而非追加', JSON.parse(r1.stdout).action === 'replaced' && (a1.match(/lobe-design:begin/g) ?? []).length === 1 && a1.includes('lobe-design:mode=compact lang=en') && a1.startsWith(host), r1.stdout + r1.stderr);+ const blockLines = a1.slice(a1.indexOf(BEGIN), a1.indexOf(END) + END.length).split('\n').length;+ t('bootstrap: 精简块(含首尾标记)≤ 22 行', blockLines <= 22, `${blockLines}`);+ t('bootstrap compact: 重跑幂等', JSON.parse(run('bootstrap.mjs', ['--root', tmpB, '--json']).stdout).action === 'unchanged' && readFileSync(guide, 'utf8') === a1);+ t('bootstrap compact en: --check 识别版本 → 0', run('bootstrap.mjs', ['--check', '--root', tmpB]).status === 0);+ run('bootstrap.mjs', ['--root', tmpB, '--full']);+ const a2 = readFileSync(guide, 'utf8');+ t('bootstrap --full: 完整块 + 模式行', a2.includes('lobe-design:mode=full lang=zh') && a2.includes('### 3. 自迭代') && a2.startsWith(host));+ t('bootstrap --full: 不带 flag 重跑沿用 full(幂等)', JSON.parse(run('bootstrap.mjs', ['--root', tmpB, '--json']).stdout).action === 'unchanged');+ run('bootstrap.mjs', ['--root', tmpB, '--compact', '--lang', 'zh']);+ t('bootstrap --compact --lang zh 覆盖', readFileSync(guide, 'utf8').includes('lobe-design:mode=compact lang=zh'));+ t('bootstrap --lang 未知 → exit 2', run('bootstrap.mjs', ['--root', tmpB, '--lang', 'fr']).status === 2);+ t('bootstrap --compact 与 --full 同时 → exit 2', run('bootstrap.mjs', ['--root', tmpB, '--compact', '--full']).status === 2);+ } finally { rmSync(tmpB, { recursive: true, force: true }); }++ // 3) 平台中立的描述与 stage 措辞+ const skillMd = readFileSync(join(skill, 'SKILL.md'), 'utf8');+ const desc = skillMd.match(/^description:\s*>?\s*\n([\s\S]*?)\n---/m)?.[1] ?? '';+ t('wording: SKILL.md description 不把 @lobehub/ui / cssVar 当通用', desc.length > 0 && !/take atoms from @lobehub\/ui/.test(desc) && /React Native/.test(desc) && /useTheme\(\)/.test(desc)+ && desc.split(/(?<=[.;])\s/).filter((x) => /cssVar|@lobehub\/ui\b(?!-rn)/.test(x)).every((x) => /web/i.test(x)), desc);+ const visual = readFileSync(join(skill, 'stages/50-visual.md'), 'utf8');+ t('wording: 50-visual 取值按平台分(web cssVar / RN useTheme)', /\*\*web \/ desktop\*\*:`cssVar`/.test(visual) && /React Native.*useTheme\(\)/.test(visual) && !/都走 `cssVar`/.test(visual));+ const stagesText = readdirSync(join(skill, 'stages')).map((f) => readFileSync(join(skill, 'stages', f), 'utf8')).join('\n') + skillMd;+ t('wording: SKILL.md 输出契约有示意图约定', /### 示意图\n/.test(skillMd) && /编号标注/.test(skillMd));+ const comps = readFileSync(join(skill, 'references/components.md'), 'utf8');+ const c19 = comps.split('## C-19')[1]?.split('\n## ')[0] ?? '';+ const c20 = comps.split('## C-20')[1]?.split('\n## ')[0] ?? '';+ t('wording: C-19 用 ProgressiveBlur + 背景 token 淡出 + 降级', /ProgressiveBlur/.test(c19) && /colorBgLayout/.test(c19) && /降低透明度/.test(c19) && /平台作用域/.test(c19));+ t('wording: C-20 标注平台作用域 mobile', /\*\*平台作用域:mobile。\*\*/.test(c20));+ t('wording: stage / 入口文档没有「取值走 cssVar」这类不分平台的说法', !/(?:都走|仍走|仍要遵守「取值走) `?cssVar/.test(stagesText) && !/映射到哪个 lobe-ui 组件/.test(stagesText));+}+// 5d3) 5.4.2 · install.sh:--copy 重装备份到 cache,不在项目内留 *.bak.*console.log('== install.sh backup');{const repoRoot = join(skill, '..', '..');const installSh = join(repoRoot, 'install.sh');if (!existsSync(installSh)) {- // 以 install.sh --copy 装进项目(.agents/skills/lobe-design)时没有 skill 仓库根的 install.sh,跳过- console.log(`SKIP install.sh 不在 ${installSh}(非 skill 源仓库布局)`);+ t('install.sh present at repo root', false, installSh);} else {const cacheHome = mkdtempSync(join(tmpdir(), 'ld-xdg-'));const proj = mkdtempSync(join(tmpdir(), 'my-app-'));@@ -577,8 +651,6 @@ t('check-learnings.mjs missing log → exit 2', run('check-learnings.mjs', ['--lfor (const s of ['refs.mjs', 'intent.mjs', 'bootstrap.mjs', 'upstream.mjs', 'project-scan.mjs']) {t(`${s} --help → exit 0`, run(s, ['--help']).status === 0, `exit ${run(s, ['--help']).status}`);}-t('lint-lobe.mjs 未知 --stage → exit 2', run('lint-lobe.mjs', ['tests/fixtures/bad-visual.tsx', '--stage', '50-visua']).status === 2);-t('lint-lobe.mjs 合法 --stage 照常报 FAIL', run('lint-lobe.mjs', ['tests/fixtures/bad-visual.tsx', '--stage', '50-visual']).status === 1);t('refs.mjs (no instruction) → exit 2', run('refs.mjs', []).status === 2);t('intent.mjs (no instruction) → exit 2', run('intent.mjs', []).status === 2);t('refs.mjs --audit → exit 0', run('refs.mjs', ['--audit']).status === 0);diff --git a/.agents/skills/spa-routes/SKILL.md b/.agents/skills/spa-routes/SKILL.mdindex 28dd0f97834..3bb0aef5f43 100644--- a/.agents/skills/spa-routes/SKILL.md+++ b/.agents/skills/spa-routes/SKILL.md@@ -79,7 +79,8 @@ Each feature should:5. **Register the route in the correct definition layer**- **Shared Web/Electron route:** add the segment once in `desktopRouter.shared.tsx` with `dynamicElement` / `dynamicLayout`. Put its `preloadId` there as part of the shared lazy-loader definition.- **Web-only or Electron-only route:** add it to the corresponding thin `desktopRouter.config.tsx` adapter. Keep platform-only differences explicit and small.- - **Mobile-only flow:** use `mobileRouter.config.tsx`; mobile does not consume the shared desktop tree.+ - **Mobile counterpart (required for every desktop main-area route):** see §3c. `mobileRouter.parity.test.ts` fails until the mobile router resolves the new URL to the same pattern, or the route is listed in `MOBILE_UNSUPPORTED` with a reason.+ - **Mobile-only flow:** use `mobileRouter.config.tsx`.6. **Register a route skeleton (REQUIRED for every lazy route)**- Every lazy route inside the main area renders `RouteSegmentSkeleton` (`src/components/Skeleton/RouteSegment.tsx`) while its chunk loads. It resolves via `handle.meta.Skeleton` only (deepest match wins, walking up through parent routes). Omitting `Skeleton` renders a blank pane — use `NoRouteSkeleton` when that is intentional.@@ -103,7 +104,7 @@ Each feature should:| `desktopRouter.config.tsx` | Thin Web adapter: mounts the common content tree at `/` and adds Web-only routes. || `desktopRouter.config.desktop.tsx` | Thin Electron adapter: injects per-tab Home behavior, TabHost root stubs, and the Electron-only `/desktop-onboarding` local setup. |-Add or remove common routes only in `desktopRouter.shared.tsx`, or in a subtree module it imports (`taskWorkspaceRoutes.tsx`, `workspaceSettingsRoutes.tsx` for the padded `/:slug/settings/*` tabs) — the shared file is over the 1200-line limit, so large subtrees move out instead of growing it. Add any new subtree module to `readRouterSources` in `desktopRouter.sync.test.tsx`. Keep `desktopRouter.sync.test.tsx` passing so path behavior, lazy boundaries, preload ownership, and the intentional platform differences remain verified.+Add or remove common routes only in `desktopRouter.shared.tsx`, or in a subtree module it imports (`taskWorkspaceRoutes.tsx`, `projectWorkspaceRoutes.tsx`, `agentPageRoutes.tsx`, `memoryRoutes.tsx`, `resourceRoutes.tsx`, `workspaceSettingsRoutes.tsx` for the padded `/:slug/settings/*` tabs) — the shared file is over the 1200-line limit, so large subtrees move out instead of growing it. Add any new subtree module to `readRouterSources` in `desktopRouter.sync.test.tsx`. Keep `desktopRouter.sync.test.tsx` passing so path behavior, lazy boundaries, preload ownership, and the intentional platform differences remain verified.---@@ -128,6 +129,22 @@ Known variants today:---+## 3c. Mobile counterparts of desktop routes++The mobile web build has its own router (`mobileRouter.config.tsx`, `__MOBILE__`), but it mounts the **same page segments** as desktop. Do not copy a desktop route into the mobile files: reuse the subtree module and adjust only what differs with `overlayRoutes` (`routeOverlay.ts`; `withHandle`, `dropRoute`, or a mobile `element`).++| Mobile file | Reuses |+| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |+| `mobileAgentRoutes.tsx` | `agentPageChildren` under the agent scope layout; group profile / permission |+| `mobileWorkspaceRoutes.tsx` | `createTaskWorkspaceChildren`, `projectWorkspaceRoute`, `resourceRoute`, `memoryChildren`, inside the mobile page layout |+| `mobileWorkspaceSettingsRoutes.tsx` | `workspaceSettingsContentRoute` children plus the mobile settings menu and full-bleed tabs |++- A desktop subtree added to one of those modules reaches mobile automatically. A new top-level desktop surface needs one entry in the matching mobile file; wrap full-screen pages in `pageLayout` (`(mobile)/_page-layout`).+- Mobile `NavHeader` draws back + the route's `NavPanelPortal` sidebar as a drawer, and falls back to the route `titleKey` when the page header has no title. A page that paints no `NavHeader` gets one from the route handle `mobileShellHeader: true | 'untitled'` (and `mobileShellTitle` for a record name). Do not add a second back button inside the page; opt out with `showTogglePanelButton={false}` when the page keeps its own.+- Desktop-only surfaces go in `mobileUnsupportedRoutes` and `MOBILE_UNSUPPORTED` in `mobileRouter.parity.test.ts`, so they redirect home instead of being read as a `/:workspaceSlug`.++---+## 4. How to Divide Files (route vs feature)| Question | Put in `src/routes/` | Put in `src/features/` |diff --git a/.agents/ux/components.md b/.agents/ux/components.mdindex 9788a3f3b8b..d794a3c8a2b 100644--- a/.agents/ux/components.md+++ b/.agents/ux/components.md@@ -1,4 +1,4 @@-<!-- lobe-design-init: version=5.4.2 fingerprint=ae4aaf7a1e72 -->+<!-- lobe-design-init: version=5.8.0 fingerprint=29ef977ba7e7 --># 组件盘点(lobe-design・Round 2)@@ -53,6 +53,19 @@| `components/Skeleton`、`ListSkeleton` | 路由级骨架和列表占位 | 骨架形状要贴近真实布局;路由骨架登记方式见 `spa-routes` skill || `features/CommandMenu` | 全局命令面板 | 新的全局动作登记进来,不另做搜索弹窗 |+#### mobile 外壳(桌面页面在 mobile 全屏打开)++mobile 与 web 是同一套 DOM 组件;分类同 web(薄包装 / 重复 / 业务组件),没有单独的 RN 原子层。++| 组件 | 什么时候用 | 注意点 |+| ------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `NavHeader`(mobile 分支) | mobile 上的桌面页面页头 | 左侧自动是返回 + 侧栏抽屉(菜单图标);不传 `left` 且没有中间内容时补路由标题,`left={null}` 关掉。不要再在页面里加返回或左栏开关。面板头(`showTogglePanelButton={false}`)不出返回 |+| `features/MobileShell` 的 `PageLayout`(路由 handle `mobileShellHeader`) | 页面自己不画页头时(项目首页、Docs Works) | 在路由上声明,不改页面;页面开头已有大标题时用 `'untitled'`;标题应是记录名(如项目名)时加 `mobileShellTitle`(lazy 组件) |+| `MobileShell` 的 `AgentScopeLayout` / `GroupScopeLayout` | `/agent/:aid/*`、`/group/:gid/*` 的公共外层 | 只放初始化与 id 同步;404 守卫放在各自的页头下面,缺失时仍有返回 |+| `features/MobileHome/FeatureNav` | mobile 首页的功能入口 | 条目来自 `useNavLayout`,跟随桌面侧栏的实验 / 开关 / 工作区规则;不要在这里另写一份入口列表。一行横滑链接,不做宫格,避免把 agent 列表挤出首屏 |+| `features/RightPanel`(mobile) | 桌面右侧面板在 mobile 的形态 | 自动变成全屏抽屉、进页面时收起;新的侧面板用 `RightPanel`,不要直接用 `DraggablePanel` |+| `features/WorkspaceSetting/MobileCategory` | mobile 工作区设置菜单 | 读 `useWorkspaceSettingCategory`,权限与实验开关与桌面一致 |+### 对话与 Agent| 组件 | 什么时候用 | 注意点 |diff --git a/.agents/ux/product.md b/.agents/ux/product.mdindex 83e84e2b301..c234f15e633 100644--- a/.agents/ux/product.md+++ b/.agents/ux/product.md@@ -1,4 +1,4 @@-<!-- lobe-design-init: version=5.4.2 fingerprint=ae4aaf7a1e72 -->+<!-- lobe-design-init: version=5.8.0 fingerprint=29ef977ba7e7 --># 产品画像(lobe-design・Round 1)@@ -18,7 +18,9 @@ LobeHub 是开源的 AI Agent 工作空间:用户创建和组织 Agent,与 A| mobile | 次 | `src/spa/router/mobileRouter.config.tsx`,路由段在 `src/routes/(mobile)` | **触控为主**,窄屏单栏,以点按为主,不依赖悬停 || popup | 辅 | `src/routes/(popup)` | 独立小窗:单个 Agent / 群组 / 进程,信息只保留当前任务 |-`project-scan` 只识别到 web;desktop 与 mobile 来自上表的目录,判断时以本表为准。web 与 desktop 共用 `desktopRouter.shared.tsx`,平台差异只放在 `desktopRouter.config*.tsx`(见 `spa-routes` skill)。+平台:web, desktop, mobile++`project-scan` 只识别到 web;desktop 与 mobile 来自上表的目录,判断时以本表为准。**mobile 是同一套 DOM SPA 的移动入口**(`src/spa/entry.mobile.tsx`,原子层同样取自 `@lobehub/ui`),不是 React Native:RN 专属规则不适用,web 的组件与 lint 规则照常适用;C-20 这类「仅 mobile」的规则指的就是这个入口。web 与 desktop 共用 `desktopRouter.shared.tsx`,平台差异只放在 `desktopRouter.config*.tsx`(见 `spa-routes` skill)。## 产品类型@@ -44,22 +46,25 @@ LobeHub 是开源的 AI Agent 工作空间:用户创建和组织 Agent,与 A## 适用性-| 规则 / 原型 | 结论 | 说明 |-| ------------------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| C-04 对话界面的组合顺序 | 强调 | 对话是主路径;新对话类页面先对照 C-04 |-| E-03 `@lobehub/icons`、E-05 `@lobehub/streamdown` | 强调 | 模型与厂商徽标、流式 markdown 是高频件 |-| K-05 / X-1 状态与反馈 | 强调 | 流式生成、工具运行、任务执行都有长时间中间态;加载 / 失败 / 空态要齐 |-| D-08 暗色模式、D-07 主题声明 | 强调 | 主色与中性色由用户配置(见 `DESIGN.md`),一律走 `cssVar`,不写死色值 |-| D-09 / X-6 响应式 | 强调 | 同一功能常有 web 与 mobile 两套入口;改 web 页时确认 mobile 对应页是否受影响 |-| X-5 / K-07 可访问性 | 强调 | 键盘可达(desktop 快捷键重度使用,见 `hotkey` skill)、触控目标 ≥ 44px(mobile) |-| hover-only 交互(只在悬停时出现的操作、悬停展开的菜单、悬停才显示的说明) | mobile **N/A** | mobile 以点按为主:操作要常驻或放进点按打开的菜单;`Tooltip` 不能承载必要信息。web /desktop 可用悬停作为增强,但不能是唯一入口 |-| P-02 列表 / 搜索 / 筛选、P-03 详情、P-05 配置 / 设置 | 适用 | 资源、Agent、任务、设置页 |-| P-04 新建 / 编辑表单 | 适用 | Agent 配置、模型服务商配置;就地编辑优先(C-17) |-| P-08 计费 / 用量 | 部分适用 | 只有用量统计类页面;不新造计费后台 |-| P-01 总览看板、P-07 监控 / 日志 | 部分适用 | 仅 dashboard、任务与设备状态等少数页面;不是主形态 |-| P-06 审批队列、P-09 评测对比 | 少量 | 工具调用审批是对话内组件,不做成独立队列页;评测页面向开发者,按 saas 处理 |-| C-07 / C-08 控制台套件、高密度后台(A-08 后台档) | 不作为默认 | 主界面按消费级密度;只有设置与资源类页面可取更高密度 |-| 20 视觉方向 / 落地页类场景 | 少量 | 本仓库没有营销站;仅 onboarding、空态和分享页有「记忆点」需求 |+| 规则 / 原型 | 结论 | 说明 |+| ------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| C-04 对话界面的组合顺序 | 强调 | 对话是主路径;新对话类页面先对照 C-04 |+| E-03 `@lobehub/icons`、E-05 `@lobehub/streamdown` | 强调 | 模型与厂商徽标、流式 markdown 是高频件 |+| K-05 / X-1 状态与反馈 | 强调 | 流式生成、工具运行、任务执行都有长时间中间态;加载 / 失败 / 空态要齐 |+| D-08 暗色模式、D-07 主题声明 | 强调 | 主色与中性色由用户配置(见 `DESIGN.md`),一律走 `cssVar`,不写死色值 |+| D-09 / X-6 响应式 | 强调 | 同一功能常有 web 与 mobile 两套入口;改 web 页时确认 mobile 对应页是否受影响 |+| X-5 / K-07 可访问性 | 强调 | 键盘可达(desktop 快捷键重度使用,见 `hotkey` skill)、触控目标 ≥ 44px(mobile) |+| hover-only 交互(只在悬停时出现的操作、悬停展开的菜单、悬停才显示的说明) | mobile **N/A** | mobile 以点按为主:操作要常驻或放进点按打开的菜单;`Tooltip` 不能承载必要信息。web /desktop 可用悬停作为增强,但不能是唯一入口 |+| P-02 列表 / 搜索 / 筛选、P-03 详情、P-05 配置 / 设置 | 适用 | 资源、Agent、任务、设置页 |+| P-04 新建 / 编辑表单 | 适用 | Agent 配置、模型服务商配置;就地编辑优先(C-17) |+| P-08 计费 / 用量 | 部分适用 | 只有用量统计类页面;不新造计费后台 |+| P-01 总览看板、P-07 监控 / 日志 | 部分适用 | 仅 dashboard、任务与设备状态等少数页面;不是主形态 |+| P-06 审批队列、P-09 评测对比 | 少量 | 工具调用审批是对话内组件,不做成独立队列页;评测页面向开发者,按 saas 处理 |+| C-07 / C-08 控制台套件、高密度后台(A-08 后台档) | 不作为默认 | 主界面按消费级密度;只有设置与资源类页面可取更高密度 |+| 20 视觉方向 / 落地页类场景 | 少量 | 本仓库没有营销站;仅 onboarding、空态和分享页有「记忆点」需求 |+| mobile 外壳:桌面页面在 mobile 全屏打开 | 强调 | 页头左侧是返回(无历史时回首页)与侧栏抽屉(桌面 `NavPanelPortal` 的内容),不写死桌面的左栏开关;右侧面板在 mobile 是全屏抽屉,默认收起 |+| C-19 滚动边缘、C-20 mobile 浮动框架 | 待定 | 采用需要把各页的滚动容器改成从屏幕顶端开始(内容从框架后面滚过),并把 `@lobehub/ui` 升到 ^6.9(`ProgressiveBlur`);在此之前 mobile 保持实底页头,新页面不要半套用胶囊样式 |+| LOBE-RN-DOM-UI 与 React Native 专属条目 | 不适用 | mobile 是 DOM SPA,不是 RN |## 文案diff --git a/AGENTS.md b/AGENTS.mdindex c3dee7147d4..fe147b0e838 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -115,10 +115,12 @@ When designing or reviewing user-facing flows (empty/loading/error states, confi<!-- lobe-design:begin · managed by scripts/bootstrap.mjs · 不要手动编辑本块 -->+<!-- lobe-design:mode=full lang=zh -->+## UI 设计工作指南(lobe-design)本项目在做界面相关工作(新增页面、改交互、调视觉、统一设计系统、还原设计稿、上线前审查)时,-走 **lobe-design** 这条单入口 pipeline。安装:`https://github.com/lobehub/lobe-design-skill`(skill 版本 5.4.2)。+走 **lobe-design** 这条单入口 pipeline。安装:`https://github.com/lobehub/lobe-design-skill`(skill 版本 5.8.0)。skill 装在本仓库的 `.agents/skills/lobe-design`,下面所有命令都相对它执行:@@ -129,10 +131,12 @@ export LOBE_DESIGN="./.agents/skills/lobe-design"### 项目层规范(`.agents/ux/`)-本项目的事实和补充规则放在 `.agents/ux/`,与 skill 共存:skill 管通用判据,这里管本项目;冲突时以 skill 为准。**重装 / 升级不会覆盖本目录。**+本项目的事实和补充规则放在 `.agents/ux/`,与 skill 共存:skill 管通用判据,这里管本项目。**重装 / 升级不会覆盖本目录。**++**优先级**:本项目 `product.md` 里的平台与适用性(标为「不适用」的规则、按平台限定的规则)优先于 skill 的通用规则;其余冲突以 skill 为准。项目层规则要违背通用原则(可达性、P-xx 原型)时,必须在项目层写明理由。- `.agents/ux/product.md`:产品画像:平台、产品类型、用户、核心任务、规则适用性、文案 profile(05-init Round 1)-- `.agents/ux/components.md`:组件盘点:薄包装 / 与 lobe-ui 重复 / 业务组件用法(05-init Round 2)+- `.agents/ux/components.md`:组件盘点:按平台分类(web:薄包装 / 与 lobe-ui 重复 / 业务组件;mobile:项目原子层 / 薄包装 / 业务组件)(05-init Round 2)- **装完或升级 skill 后**:跑 stage `05-init`(或说「初始化 / 升级后刷新」)完成两轮自迭代 ——Round 1 产品画像 → `.agents/ux/product.md`,Round 2 组件盘点 → `.agents/ux/components.md`。可用 `node "$LOBE_DESIGN/scripts/project-scan.mjs" --check` 检查是否缺失或过期。- **日常任何 UI 任务**:先读 `.agents/ux/product.md` 与 `.agents/ux/components.md`,再按 stage 加载 skill 规则。- 宏观指令(「整体打磨」「重做这页」)和新页面从 stage `00-brief` 开始:先读 `.agents/ux/product.md`,写出后续 stage 消费的页面简报;纯视觉或文案修正跳过。@@ -144,11 +148,11 @@ export LOBE_DESIGN="./.agents/skills/lobe-design"node "$LOBE_DESIGN/scripts/route.mjs" "<用户指令原文>" # 场景 / 颗粒度 / stage 序列node "$LOBE_DESIGN/scripts/refs.mjs" "<用户指令原文>" # 每个 stage 该读哪些条目```-- 路由器读取 `scripts/pipeline.json`(唯一事实源)。结果是默认值;结合上下文调整时要在输出里说明理由。+- 路由器读取 `$LOBE_DESIGN/scripts/pipeline.json`(唯一事实源)。结果是默认值;结合上下文调整时要在输出里说明理由。- **一次只进一个 stage。** 进入时才读它「只加载」列出的条目,不要一开始就把 references 读完。- 每个 stage 只回答一个问题。看到别的问题,只记一行 `遗留 → <stage>`,不要顺手改。- 改过代码的 stage,结束前跑 `node "$LOBE_DESIGN/scripts/lint-lobe.mjs" <改动路径>`,FAIL 必须修。-- **做界面前先读项目层**(若已有):`.agents/ux/product.md`(画像与适用性)、`.agents/ux/components.md`(用哪个组件);没有则先跑 05-init。+- **做界面前先读项目层**:`.agents/ux/product.md`(画像与适用性)、`.agents/ux/components.md`(用哪个组件);缺的那份先跑 05-init 补上。### 2. 什么时候用@@ -167,7 +171,7 @@ export LOBE_DESIGN="./.agents/skills/lobe-design"### 3. 自迭代:纠正要沉淀下来- **何时记**:用户纠正了一次输出;80 审查发现同类问题本轮复发;60 或 lint 扫描发现可机械识别的漂移 ≥ 2 处。-- **在本项目里记**:写进 `.agents/ux/lobe-design-rules.md`,续编号,删除的编号不复用;新的产品事实写 `product.md`,组件用法写 `components.md`,一次性决定不记。+- **在本项目里记**:写进 项目自己的规则文件(建议新建 .agents/ux/lobe-design-rules.md),续编号,删除的编号不复用;新的产品事实写 `product.md`,组件用法写 `components.md`,一次性决定不记。不改 `$LOBE_DESIGN` 下的 skill 文件(重装会覆盖),也不在本项目里 bump skill 版本或写 skill 的 `learnings/LOG.md`。- **选层(由强到弱,选当前可行的最强一层)**:`structure > lint > rule > style`- 能用「出现了 X」「做了 X 却没有 Y」或数数描述 → **lint**@@ -188,7 +192,7 @@ export LOBE_DESIGN="./.agents/skills/lobe-design"- 本地先跑 `node "$LOBE_DESIGN/scripts/upstream.mjs" --from <你的 learnings/LOG.md>` 提取候选条目。- 回流的是**判据**(可机械校验的规则、可复用的 stage 契约),不是本项目的具体取值。-> 本节由 `scripts/bootstrap.mjs` 维护。块外内容属于项目自己,不会被本脚本改写。+> 本节由 `$LOBE_DESIGN/scripts/bootstrap.mjs` 维护。块外内容属于项目自己,不会被本脚本改写。> 重新运行 `node "$LOBE_DESIGN/scripts/bootstrap.mjs"` 可把本块更新到最新版本。<!-- lobe-design:end -->diff --git a/e2e/src/steps/community/detail-pages.steps.ts b/e2e/src/steps/community/detail-pages.steps.tsindex b4723bd609b..ccf8fd226fb 100644--- a/e2e/src/steps/community/detail-pages.steps.ts+++ b/e2e/src/steps/community/detail-pages.steps.ts@@ -36,22 +36,36 @@ When('I click the back button', async function (this: CustomWorld) {const backButtonVisible = await backButton.isVisible().catch(() => false);console.log(` 📍 Back button visible: ${backButtonVisible}`);+ // The click has its own short timeout: the default (30s) equals the step+ // timeout, so a click Playwright keeps retrying (e.g. the target is briefly+ // covered or re-rendered) used to fail the whole step instead of falling back.+ let clicked = false;if (backButtonVisible) {// Click the parent element if it's an SVG iconconst tagName = await backButton.evaluate((el) => el.tagName.toLowerCase());- if (tagName === 'svg') {- await backButton.locator('..').click();- } else {- await backButton.click();- }- console.log(' 📍 Clicked back button');- } else {+ const target = tagName === 'svg' ? backButton.locator('..') : backButton;+ clicked = await target+ .click({ timeout: 4000 })+ .then(() => true)+ .catch(() => false);+ console.log(` 📍 Clicked back button: ${clicked}`);+ }++ const leftDetail = () =>+ this.page+ .waitForURL((url) => url.href !== currentUrl, { timeout: 4000 })+ .then(() => true)+ .catch(() => false);++ if (!clicked || !(await leftDetail())) {// Use browser back as fallbackconsole.log(' 📍 Using browser goBack()');- await this.page.goBack();+ await this.page.goBack({ timeout: 8000 });}- await this.page.waitForLoadState('domcontentloaded', { timeout: 30_000 });+ // Worst case stays inside the 30s step timeout: 4s click + 4s URL wait ++ // 8s goBack + 5s load.+ await this.page.waitForLoadState('domcontentloaded', { timeout: 5000 });await this.page.waitForTimeout(500);const newUrl = this.page.url();diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 87c7406426e..c530fa3ed75 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -350,6 +350,7 @@"navPanel.library": "Library","navPanel.moveDown": "Move Down","navPanel.moveUp": "Move Up",+ "navPanel.openMenu": "Open menu","navPanel.pinned": "Pinned","navPanel.privateAgents": "Private","navPanel.publicAgents": "Workspace",@@ -358,6 +359,7 @@"navPanel.searchProject": "Search projects...","navPanel.searchRecent": "Search Recent...","navPanel.searchResultEmpty": "No search results found",+ "navPanel.shortcuts": "Shortcuts","navPanel.show": "Show","navPanel.switcherAll": "All","navPanel.switcherRecent": "Recent",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 973eca7b3f4..036a011d9df 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -350,6 +350,7 @@"navPanel.library": "资源库","navPanel.moveDown": "下移","navPanel.moveUp": "上移",+ "navPanel.openMenu": "打开菜单","navPanel.pinned": "已固定","navPanel.privateAgents": "私人","navPanel.publicAgents": "工作区",@@ -358,6 +359,7 @@"navPanel.searchProject": "搜索项目…","navPanel.searchRecent": "搜索最近…","navPanel.searchResultEmpty": "暂无搜索结果",+ "navPanel.shortcuts": "快捷入口","navPanel.show": "显示","navPanel.switcherAll": "全部","navPanel.switcherRecent": "最近",diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex eebcb1f1a6d..2d09adb5390 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -427,6 +427,8 @@ export default {'navPanel.agent': 'Agents','navPanel.bottomDivider': 'Items below anchor to bottom','navPanel.customizeSidebar': 'Customize Sidebar',+ 'navPanel.openMenu': 'Open menu',+ 'navPanel.shortcuts': 'Shortcuts','navPanel.displayItems': 'Display Items','navPanel.resetDefault': 'Reset to Default','navPanel.hidden': 'Hidden',diff --git a/src/features/AgentBreadcrumb/index.tsx b/src/features/AgentBreadcrumb/index.tsxindex 2df961d7f33..ce476832918 100644--- a/src/features/AgentBreadcrumb/index.tsx+++ b/src/features/AgentBreadcrumb/index.tsx@@ -59,7 +59,14 @@ const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, extraItems, title{title: (<Link to={agentHomePath}>- <Text ellipsis as={'span'} color={'inherit'} style={{ maxWidth: 200 }} weight={500}>+ {/* Viewport-capped so the section crumb keeps its line on a phone. */}+ <Text+ ellipsis+ as={'span'}+ color={'inherit'}+ style={{ maxWidth: 'min(200px, 30vw)' }}+ weight={500}+ >{displayTitle}</Text></Link>@@ -70,7 +77,7 @@ const AgentBreadcrumb = memo<AgentBreadcrumbProps>(({ agentId, extraItems, title: [{title: (- <Text as={'span'} color={'inherit'} weight={500}>+ <Text as={'span'} color={'inherit'} style={{ whiteSpace: 'nowrap' }} weight={500}>{title}</Text>),diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxindex 2cee7dfd695..43ad887881c 100644--- a/src/features/AgentGoals/AgentGoalsPage.tsx+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -8,6 +8,7 @@ import {cssVar,Empty,Flexbox,+ ScrollShadow,Segmented,Text,} from '@lobehub/ui';@@ -308,14 +309,24 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {</Flexbox>)}<Flexbox gap={10}>- <Flexbox horizontal align={'center'} justify={'space-between'}>- <Flexbox horizontal align={'center'} gap={8}>+ {/* Wraps so the filters drop below the title on a phone instead of crushing it. */}+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>+ <Flexbox horizontal align={'center'} flex={'none'} gap={8}><Text fontSize={16} weight={600}>{t('goalPage.listTitle')}</Text><span className={styles.countBadge}>{visibleGoalCount}</span></Flexbox>- <Flexbox horizontal align={'center'} gap={8}>+ {/* On a phone the filters can outgrow the row; the edge fade shows it scrolls. */}+ <ScrollShadow+ hideScrollBar+ horizontal+ align={'center'}+ gap={8}+ orientation={'horizontal'}+ size={24}+ style={{ maxWidth: '100%' }}+ >{isGlobal && (<GoalAgentFilteroptions={agentFilterOptions}@@ -362,7 +373,7 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {variant={viewMode === 'card' ? 'filled' : 'borderless'}onClick={() => setViewMode('card')}/>- </Flexbox>+ </ScrollShadow></Flexbox><div className={viewMode === 'card' ? styles.list : styles.listRows}>{isTabError ? (diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex e8750e06419..8d821de226f 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -543,7 +543,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {<Flexbox horizontal align={'center'} gap={8} justify={'space-between'}><Flexbox horizontal align={'center'} gap={8}><Icon color={cssVar.colorTextTertiary} icon={ShieldCheck} size={16} />- <Text fontSize={13} weight={600}>+ <Text fontSize={13} style={{ flex: 'none' }} weight={600}>{t('createGoal.criteriaTitle')}</Text><Text className={styles.sectionHint} fontSize={12}>diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsxindex 73dd3c0f435..fa42774391e 100644--- a/src/features/AgentGoals/GoalListItem.tsx+++ b/src/features/AgentGoals/GoalListItem.tsx@@ -28,6 +28,21 @@ const styles = createStaticStyles(({ css }) => ({&[data-popup-open] {background: ${cssVar.colorFillQuaternary};}++ /* A phone row wraps: the title takes the first line, agent / progress / menu+ the second. Same breakpoint as GoalProgress. */+ @media (width <= 767px) {+ flex-wrap: wrap;+ row-gap: 6px;+ }+ `,+ title: css`+ flex: 1;+ min-width: 0;++ @media (width <= 767px) {+ flex-basis: 100%;+ }`,}));@@ -72,7 +87,7 @@ export const GoalListItem = memo<GoalItemProps>(({ globalScopeId, goal: item, pronClick={handleClick}onKeyDown={handleKeyDown}>- <Flexbox gap={4} style={{ flex: 1, minWidth: 0 }}>+ <Flexbox className={styles.title} gap={4}><Flexbox horizontal align={'center'} gap={7}><GoalStatusGlyph size={13} status={goal.status} /><Text ellipsis fontSize={15} weight={600}>diff --git a/src/features/AgentGoals/GoalProgress.tsx b/src/features/AgentGoals/GoalProgress.tsxindex fd184c9bf84..d3d1640dc76 100644--- a/src/features/AgentGoals/GoalProgress.tsx+++ b/src/features/AgentGoals/GoalProgress.tsx@@ -30,6 +30,18 @@ const styles = createStaticStyles(({ css }) => ({width: min(100%, 390px);min-width: 390px;++ /* On a phone the fixed width would crush the goal title beside it. The+ metrics take what is left on the row's second line (beside the agent+ and the menu), and the duration / cost cells shrink to their content. */+ @media (width <= 767px) {+ grid-template-columns: minmax(0, 1fr) auto auto;+ flex: 1 1 0;+ column-gap: 8px;++ width: auto;+ min-width: 0;+ }`,needsYou: css`flex: none;diff --git a/src/features/AgentGoals/GoalWorkspaceBreadcrumb.tsx b/src/features/AgentGoals/GoalWorkspaceBreadcrumb.tsxindex 14257b087f6..03fdd4183a6 100644--- a/src/features/AgentGoals/GoalWorkspaceBreadcrumb.tsx+++ b/src/features/AgentGoals/GoalWorkspaceBreadcrumb.tsx@@ -26,7 +26,8 @@ const GoalWorkspaceBreadcrumb = memo<GoalWorkspaceBreadcrumbProps>(({ title }) =const titleCrumb = {key: 'goal',title: (- <Text ellipsis color={'inherit'} style={{ maxWidth: 320 }} weight={500}>+ // Viewport-capped so the crumb fits beside the back button on a phone.+ <Text ellipsis color={'inherit'} style={{ maxWidth: 'min(320px, 45vw)' }} weight={500}>{title}</Text>),@@ -43,7 +44,7 @@ const GoalWorkspaceBreadcrumb = memo<GoalWorkspaceBreadcrumbProps>(({ title }) =key: 'goals',title: (<WorkspaceLink to={'/goals'}>- <Text color={'inherit'} weight={500}>+ <Text color={'inherit'} style={{ whiteSpace: 'nowrap' }} weight={500}>{t('goalList.title')}</Text></WorkspaceLink>diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsxindex 90246ba0ed1..35fee6d91d8 100644--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx@@ -1316,7 +1316,7 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,return (<Flexbox gap={4}>{overview}- <Flexbox horizontal align={'center'} justify={'space-between'} paddingBlock={4}>+ <Flexbox horizontal align={'center'} justify={'space-between'} paddingBlock={4} wrap={'wrap'}><Flexbox horizontal align={'center'} gap={12}>{titleAndViews}</Flexbox>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsxindex d6c9c28df34..1da6032e6f1 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskGoalBar.tsx@@ -7,8 +7,6 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';-import { hasGoalPage } from './goalPageLink';-/** "Part of goal" link back to the goal that drives this task, mirroring the parent-task bar. */const TaskGoalBar = memo(() => {const { t } = useTranslation('chat');@@ -22,29 +20,19 @@ const TaskGoalBar = memo(() => {<Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>{t('taskDetail.partOfGoal')}</Text>- {!hasGoalPage() ? (- // The mobile router has no goal page, so name the goal without linking it.- <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>- <Icon icon={TargetIcon} size={16} style={{ flex: 'none' }} />- <Text ellipsis style={{ minWidth: 0 }} weight={500}>- {goal.title}- </Text>- </Flexbox>- ) : (- <Button- icon={<Icon icon={TargetIcon} size={16} />}- size={'small'}- style={{ maxWidth: '100%', minWidth: 0 }}- type={'text'}- // The agent-less route: the goal's supervising agent may be private to its- // creator or gated by Agent Lab, while the goal itself stays readable.- onClick={() => navigate(`/goal/${goal.id}`)}- >- <Text ellipsis style={{ minWidth: 0 }} weight={500}>- {goal.title}- </Text>- </Button>- )}+ <Button+ icon={<Icon icon={TargetIcon} size={16} />}+ size={'small'}+ style={{ maxWidth: '100%', minWidth: 0 }}+ type={'text'}+ // The agent-less route: the goal's supervising agent may be private to its+ // creator or gated by Agent Lab, while the goal itself stays readable.+ onClick={() => navigate(`/goal/${goal.id}`)}+ >+ <Text ellipsis style={{ minWidth: 0 }} weight={500}>+ {goal.title}+ </Text>+ </Button></Flexbox>);});diff --git a/src/features/AgentTasks/AgentTaskDetail/goalPageLink.test.ts b/src/features/AgentTasks/AgentTaskDetail/goalPageLink.test.tsdeleted file mode 100644index fd0a0db6cdb..00000000000--- a/src/features/AgentTasks/AgentTaskDetail/goalPageLink.test.ts+++ /dev/null@@ -1,19 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest';--import { hasGoalPage } from './goalPageLink';--describe('hasGoalPage', () => {- afterEach(() => {- vi.unstubAllGlobals();- });-- it('is true on the desktop/web bundle', () => {- vi.stubGlobal('__MOBILE__', false);- expect(hasGoalPage()).toBe(true);- });-- it('is false on the mobile bundle regardless of viewport width', () => {- vi.stubGlobal('__MOBILE__', true);- expect(hasGoalPage()).toBe(false);- });-});diff --git a/src/features/AgentTasks/AgentTaskDetail/goalPageLink.ts b/src/features/AgentTasks/AgentTaskDetail/goalPageLink.tsdeleted file mode 100644index 0640cb9fbe2..00000000000--- a/src/features/AgentTasks/AgentTaskDetail/goalPageLink.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * Whether this bundle registers the agent-less `/goal/:goalId` page. The mobile- * router does not, and it is chosen by the bundle (`entry.mobile.tsx`), not by the- * viewport — a landscape phone above the mobile breakpoint is still the mobile- * router. Read per call so a test can stub `__MOBILE__`.- */-export const hasGoalPage = () => !(typeof __MOBILE__ !== 'undefined' && __MOBILE__);diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.tsindex 7de6448d49b..6d9affd1f7f 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.test.ts@@ -261,6 +261,32 @@ describe('AgentTasksPage', () => {});});+ it('drops the scoped breadcrumb on the mobile surface, where back and the drawer lead to the scope', () => {+ expect(+ getTaskPageHeaderVisibility({+ agentId: 'agent-1',+ isEmptyHero: false,+ isMobile: true,+ mobileSurface: true,+ }).showBreadcrumb,+ ).toBe(false);+ expect(+ getTaskPageHeaderVisibility({+ isEmptyHero: false,+ isMobile: true,+ mobileSurface: true,+ projectId: 'p-1',+ }).showBreadcrumb,+ ).toBe(false);+ });++ it('keeps the scoped breadcrumb in a narrow desktop window, which has no mobile back button', () => {+ expect(+ getTaskPageHeaderVisibility({ agentId: 'agent-1', isEmptyHero: false, isMobile: true })+ .showBreadcrumb,+ ).toBe(true);+ });+it('keeps the breadcrumb for a project scope and drops it for the global list', () => {expect(getTaskPageHeaderVisibility({ isEmptyHero: false, isMobile: false, projectId: 'p-1' }),diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex c22732e827e..c215ec4bbf2 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -27,6 +27,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { useTaskStore } from '@/store/task';import { taskListSelectors } from '@/store/task/selectors';import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';+import { isMobileSurface } from '@/utils/mobileSurface';import { createTaskModal } from '../CreateTaskModal';import Breadcrumb from '../shared/Breadcrumb';@@ -64,6 +65,8 @@ interface TaskPageHeaderVisibilityParams {agentId?: string;isEmptyHero: boolean;isMobile: boolean;+ /** The mobile bundle, whose header already leads back to the scope. */+ mobileSurface?: boolean;projectId?: string;}@@ -71,6 +74,7 @@ export const getTaskPageHeaderVisibility = ({agentId,isEmptyHero,isMobile,+ mobileSurface = false,projectId,}: TaskPageHeaderVisibilityParams) => {// The global page's own crumb is the `tasks` tab, so the breadcrumb only@@ -79,7 +83,10 @@ export const getTaskPageHeaderVisibility = ({const isGlobalEmpty = !isScoped && isEmptyHero;return {- showBreadcrumb: isScoped,+ // The mobile header only fits the tabs; its back button and the agent /+ // project drawer already lead to the scope the breadcrumb names. A narrow+ // desktop window has neither, so it keeps the breadcrumb.+ showBreadcrumb: isScoped && !mobileSurface,showTaskAgentPanelToggle: !isGlobalEmpty && shouldRenderTaskAgentPanelToggle(isMobile),showViewOptions: !isGlobalEmpty,};@@ -403,6 +410,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {isOrdinaryCollection,}),isMobile,+ mobileSurface: isMobileSurface(),projectId,});diff --git a/src/features/AgentTasks/shared/Breadcrumb.test.tsx b/src/features/AgentTasks/shared/Breadcrumb.test.tsxindex 42a2b2b359a..b63fd3094bc 100644--- a/src/features/AgentTasks/shared/Breadcrumb.test.tsx+++ b/src/features/AgentTasks/shared/Breadcrumb.test.tsx@@ -66,6 +66,21 @@ describe('Breadcrumb', () => {afterEach(() => {cleanup();+ vi.unstubAllGlobals();+ });++ it('keeps the all-tasks root crumb on desktop', () => {+ render(<Breadcrumb taskId="T-child" />);++ expect(screen.getByRole('link', { name: 'taskList.all' })).toHaveAttribute('href', '/tasks');+ });++ it('drops the all-tasks root crumb on mobile, where the back button leads up', () => {+ vi.stubGlobal('__MOBILE__', true);+ render(<Breadcrumb taskId="T-child" />);++ expect(screen.queryByText('taskList.all')).not.toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'T-parent' })).toBeInTheDocument();});it('uses the ancestor owner agent when building breadcrumb links', () => {diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsxindex dc0ffc3b606..3ea7dabac98 100644--- a/src/features/AgentTasks/shared/Breadcrumb.tsx+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx@@ -8,6 +8,7 @@ import { useShallow } from 'zustand/react/shallow';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useTaskStore } from '@/store/task';+import { isMobileSurface } from '@/utils/mobileSurface';import { styles } from './style';import { taskDetailPath } from './taskDetailPath';@@ -47,7 +48,7 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {);const allTasksLabel = (- <Text color={'inherit'} weight={500}>+ <Text color={'inherit'} style={{ whiteSpace: 'nowrap' }} weight={500}>{t('taskList.all')}</Text>);@@ -133,14 +134,20 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {className={styles.breadcrumb}separator={<Icon icon={ChevronRight} />}items={[- {- title:- taskId || agentCrumbNode ? (- <WorkspaceLink to={'/tasks'}>{allTasksLabel}</WorkspaceLink>- ) : (- allTasksLabel- ),- },+ // On a phone the header's back button already leads up, and there is+ // no room for the root crumb beside the task title.+ ...(isMobileSurface() && (taskId || agentCrumbNode)+ ? []+ : [+ {+ title:+ taskId || agentCrumbNode ? (+ <WorkspaceLink to={'/tasks'}>{allTasksLabel}</WorkspaceLink>+ ) : (+ allTasksLabel+ ),+ },+ ]),...(agentCrumbNode ? [agentCrumbNode] : []),...ancestorCrumbs,...(currentTaskCrumb ? [currentTaskCrumb] : []),diff --git a/src/features/Dashboard/BoardPage.tsx b/src/features/Dashboard/BoardPage.tsxindex f77af45b3cb..f29618aaabe 100644--- a/src/features/Dashboard/BoardPage.tsx+++ b/src/features/Dashboard/BoardPage.tsx@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';import NavHeader from '@/features/NavHeader';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';+import { isMobileSurface } from '@/utils/mobileSurface';import DashboardBoard from './Board';import DashboardActionsMenu from './DashboardActionsMenu';@@ -32,6 +33,9 @@ const BoardPageHeader = memo<DashboardBoardPageProps>(return (<NavHeader+ // The board's own back leads to its list; on mobile it replaces the+ // generic back button instead of sitting beside a second one.+ showTogglePanelButton={!isMobileSurface()}left={<Flexbox horizontal align={'center'} gap={6}><ActionIcondiff --git a/src/features/MemoryEntities/states.tsx b/src/features/MemoryEntities/states.tsxindex d9df860bf60..79e2687c587 100644--- a/src/features/MemoryEntities/states.tsx+++ b/src/features/MemoryEntities/states.tsx@@ -19,17 +19,26 @@ const styles = stylex.create({flexDirection: 'column',gap: '32px',justifyContent: 'center',+ // A flex item grows to its widest line by default; let it shrink to a phone.+ minWidth: 0,paddingBlock: '48px',paddingInline: '24px',},- intro: { display: 'flex', flexDirection: 'column', gap: '8px', maxWidth: '440px', textAlign: 'center' },+ intro: {+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ maxWidth: '440px',+ textAlign: 'center',+ },title: { fontSize: '20px', fontWeight: 600, margin: 0 },desc: { color: cssVar.colorTextSecondary, fontSize: '14px', lineHeight: '22px', margin: 0 },analysis: { maxWidth: '320px', width: '100%' },kinds: {display: 'grid',gap: '8px',- gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',+ // `min()` lets a phone fall back to one column instead of overflowing.+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(180px, 100%), 1fr))',maxWidth: '600px',width: '100%',},@@ -76,27 +85,27 @@ const styles = stylex.create({export const FirstRunState = memo(() => {const format = useEntityFormat();return (- <div {...stylex.props(styles.center)}>- <div {...stylex.props(styles.intro)}>- <h2 {...stylex.props(styles.title)}>{format.t('entity.firstRun.title')}</h2>- <p {...stylex.props(styles.desc)}>{format.t('entity.firstRun.desc')}</p>- </div>- <div {...stylex.props(styles.kinds)}>- {CONTEXT_KINDS.map((kind) => (- <div key={kind} {...stylex.props(styles.kind)}>- <KindIcon kind={kind} />- <span {...stylex.props(styles.kindText)}>- <span {...stylex.props(styles.kindLabel)}>{format.kind(kind)}</span>- <span {...stylex.props(styles.kindExample)}>{format.kindExample(kind)}</span>- </span>- </div>- ))}- </div>- <div {...stylex.props(styles.analysis)}>- <MemoryAnalysis />+ <div {...stylex.props(styles.center)}>+ <div {...stylex.props(styles.intro)}>+ <h2 {...stylex.props(styles.title)}>{format.t('entity.firstRun.title')}</h2>+ <p {...stylex.props(styles.desc)}>{format.t('entity.firstRun.desc')}</p>+ </div>+ <div {...stylex.props(styles.kinds)}>+ {CONTEXT_KINDS.map((kind) => (+ <div key={kind} {...stylex.props(styles.kind)}>+ <KindIcon kind={kind} />+ <span {...stylex.props(styles.kindText)}>+ <span {...stylex.props(styles.kindLabel)}>{format.kind(kind)}</span>+ <span {...stylex.props(styles.kindExample)}>{format.kindExample(kind)}</span>+ </span>+ </div>+ ))}+ </div>+ <div {...stylex.props(styles.analysis)}>+ <MemoryAnalysis />+ </div></div>- </div>-);+ );});FirstRunState.displayName = 'FirstRunState';@@ -104,17 +113,19 @@ FirstRunState.displayName = 'FirstRunState';export const ErrorState = memo<{ onRetry: () => void }>(({ onRetry }) => {const { t } = useTranslation('memory');return (- <div {...stylex.props(styles.center)}>- <Empty- description={t('entity.error.desc')}- icon={CloudOffIcon}- title={t('entity.error.title')}- action={- <Button type={'primary'} onClick={onRetry}>{t('entity.error.retry')}</Button>- }- />- </div>-);+ <div {...stylex.props(styles.center)}>+ <Empty+ description={t('entity.error.desc')}+ icon={CloudOffIcon}+ title={t('entity.error.title')}+ action={+ <Button type={'primary'} onClick={onRetry}>+ {t('entity.error.retry')}+ </Button>+ }+ />+ </div>+ );});ErrorState.displayName = 'ErrorState';diff --git a/src/features/MemoryRules/DetailPanel.tsx b/src/features/MemoryRules/DetailPanel.tsxindex 6c23f66c918..5dc28b80ad4 100644--- a/src/features/MemoryRules/DetailPanel.tsx+++ b/src/features/MemoryRules/DetailPanel.tsx@@ -696,6 +696,7 @@ interface DetailPanelProps extends Omit<RuleDocumentProps, 'rule' | 'code'> {*/const DetailPanel = ({ code, onClose, rule, ...rest }: DetailPanelProps) => (<RightPanel+ expandFollowsSelectiondefaultWidth={440}expand={Boolean(rule)}maxWidth={760}diff --git a/src/features/MobileGroupChat/Layout.tsx b/src/features/MobileGroupChat/Layout.tsxindex 979da96e2ed..b159d7abc42 100644--- a/src/features/MobileGroupChat/Layout.tsx+++ b/src/features/MobileGroupChat/Layout.tsx@@ -2,22 +2,16 @@ import { Outlet } from 'react-router';import MobileContentLayout from '@/components/server/MobileNavLayout';import { GroupNotFoundGuard } from '@/features/GroupNotFound';-import { useInitGroupConfig } from '@/hooks/useInitGroupConfig';-import GroupIdSync from '@/routes/(main)/group/_layout/GroupIdSync';import { MobileGroupHeader } from './Header';-export const MobileGroupLayout = () => {- useInitGroupConfig();-- return (- <>- <MobileContentLayout header={<MobileGroupHeader />} style={{ overflowY: 'hidden' }}>- <GroupNotFoundGuard>- <Outlet />- </GroupNotFoundGuard>- </MobileContentLayout>- <GroupIdSync />- </>- );-};+// Group init and id sync live one level up in the group scope layout+// (`MobileShell/GroupScopeLayout`), which the chat shares with the profile and+// permission pages.+export const MobileGroupLayout = () => (+ <MobileContentLayout header={<MobileGroupHeader />} style={{ overflowY: 'hidden' }}>+ <GroupNotFoundGuard>+ <Outlet />+ </GroupNotFoundGuard>+ </MobileContentLayout>+);diff --git a/src/features/MobileHome/FeatureNav.tsx b/src/features/MobileHome/FeatureNav.tsxnew file mode 100644index 00000000000..30bcf791f5d--- /dev/null+++ b/src/features/MobileHome/FeatureNav.tsx@@ -0,0 +1,85 @@+'use client';++import { Icon, ScrollShadow } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import WorkspaceLink from '@/features/Workspace/WorkspaceLink';++import { useFeatureNavItems } from './useFeatureNavItems';++const styles = stylex.create({+ chip: {+ alignItems: 'center',+ backgroundColor: { 'default': cssVar.colorFillTertiary, ':active': cssVar.colorFillSecondary },+ borderRadius: 999,+ color: cssVar.colorText,+ display: 'flex',+ fontSize: 13,+ gap: 6,+ height: 36,+ paddingInline: 12,+ transitionDuration: '150ms',+ transitionProperty: 'background-color',+ transitionTimingFunction: cssVar.motionEaseOut,+ whiteSpace: 'nowrap',+ },+ // The link is the 44px touch target; the pill inside stays light.+ link: {+ // Rounded so the keyboard focus ring follows the pill.+ borderRadius: 999,+ color: 'inherit',+ display: 'flex',+ flex: 'none',+ paddingBlock: 4,+ },+ row: {+ gap: 8,+ paddingBlock: 4,+ paddingInline: 12,+ },+});++/**+ * The desktop sidebar's destinations as one scrollable row of links above the+ * mobile agent list: findable from home without pushing the agent list — the+ * page's main job — below the fold.+ */+const FeatureNav = memo(() => {+ const { t } = useTranslation('common');+ const items = useFeatureNavItems();++ if (items.length === 0) return null;++ return (+ <nav aria-label={t('navPanel.shortcuts')}>+ <ScrollShadow+ hideScrollBar+ horizontal+ className={stylex.props(styles.row).className}+ orientation={'horizontal'}+ size={24}+ >+ {items.map((item) => (+ <WorkspaceLink+ className={stylex.props(styles.link).className}+ data-testid={`mobile-feature-nav-${item.key}`}+ key={item.key}+ to={item.url!}+ >+ <span {...stylex.props(styles.chip)}>+ <Icon icon={item.icon} size={16} />+ {item.title}+ </span>+ </WorkspaceLink>+ ))}+ </ScrollShadow>+ </nav>+ );+});++FeatureNav.displayName = 'MobileHomeFeatureNav';++export default FeatureNav;diff --git a/src/features/MobileHome/SessionListContent/DefaultMode.tsx b/src/features/MobileHome/SessionListContent/DefaultMode.tsxindex acfa3194973..04ca0762559 100644--- a/src/features/MobileHome/SessionListContent/DefaultMode.tsx+++ b/src/features/MobileHome/SessionListContent/DefaultMode.tsx@@ -15,6 +15,7 @@ import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';import { SessionDefaultGroup } from '@/types/session';+import FeatureNav from '../FeatureNav';import CollapseGroup, { type CollapseGroupItem } from './CollapseGroup';import Actions from './CollapseGroup/Actions';import Inbox from './Inbox';@@ -92,6 +93,7 @@ const DefaultMode = memo(() => {return (<>+ <FeatureNav /><Inbox /><CollapseGroupactiveKey={sessionGroupKeys}diff --git a/src/features/MobileHome/useFeatureNavItems.test.ts b/src/features/MobileHome/useFeatureNavItems.test.tsnew file mode 100644index 00000000000..a285eeecd30--- /dev/null+++ b/src/features/MobileHome/useFeatureNavItems.test.ts@@ -0,0 +1,76 @@+import { renderHook } from '@testing-library/react';+import { FileText, HomeIcon, ListTodo, SearchIcon, Target } from 'lucide-react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useFeatureNavItems } from './useFeatureNavItems';++const mocks = vi.hoisted(() => ({+ enableProjects: false,+ workspaceSlug: null as null | string,+}));++vi.mock('@/hooks/useNavLayout', () => ({+ useNavLayout: () => ({+ bottomMenuItems: [+ { icon: FileText, key: 'community', title: 'Community', url: '/community' },+ { icon: FileText, key: 'pages', title: 'Pages', url: '/page' },+ ],+ topNavItems: [+ { icon: SearchIcon, key: 'search', onClick: vi.fn(), title: 'Search' },+ { icon: HomeIcon, key: 'home', title: 'Home', url: '/' },+ { icon: ListTodo, key: 'tasks', title: 'Tasks', url: '/tasks' },+ // `useNavLayout` hides goals while the lab is off.+ { hidden: true, icon: Target, key: 'goals', title: 'Goals', url: '/goals' },+ ],+ }),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ useActiveWorkspaceSlug: () => mocks.workspaceSlug,+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),+}));++vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: { enableProjects: () => mocks.enableProjects },+}));++const keysOf = () => renderHook(() => useFeatureNavItems()).result.current.map((i) => i.key);++beforeEach(() => {+ mocks.enableProjects = false;+ mocks.workspaceSlug = null;+});++describe('useFeatureNavItems', () => {+ it('keeps the desktop destinations the tab bar does not cover, in sidebar order', () => {+ // Search has the home search bar; home / community live in the tab bar;+ // items desktop hides stay hidden.+ expect(keysOf()).toEqual(['tasks', 'pages']);+ });++ it('adds projects only while the projects lab is on', () => {+ mocks.enableProjects = true;++ expect(keysOf()).toEqual(['tasks', 'projects', 'pages']);+ });++ it('adds the workspace settings entry inside a workspace', () => {+ mocks.workspaceSlug = 'acme';++ expect(keysOf()).toEqual(['tasks', 'pages', 'settings']);+ });++ it('gives every item a destination the shortcut can navigate to', () => {+ mocks.enableProjects = true;+ mocks.workspaceSlug = 'acme';++ const items = renderHook(() => useFeatureNavItems()).result.current;++ expect(items.every((item) => typeof item.url === 'string' && item.url.startsWith('/'))).toBe(+ true,+ );+ });+});diff --git a/src/features/MobileHome/useFeatureNavItems.ts b/src/features/MobileHome/useFeatureNavItems.tsnew file mode 100644index 00000000000..9685c1133fb--- /dev/null+++ b/src/features/MobileHome/useFeatureNavItems.ts@@ -0,0 +1,57 @@+import { FolderClosed, Settings } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { type NavItem, useNavLayout } from '@/hooks/useNavLayout';+import { SidebarTabKey } from '@/store/global/initialState';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++// The tab bar already covers home / chat / community, and the home page has+// its own search bar.+const HIDDEN_KEYS = new Set<string>([+ 'search',+ SidebarTabKey.Home,+ SidebarTabKey.Community,+ SidebarTabKey.Chat,+]);++/**+ * The desktop sidebar's destinations (tasks, goals, resources, pages, memory,+ * generation, …) for the mobile home shortcuts. Built from `useNavLayout`, so+ * the lab, feature-flag and workspace rules that hide an item on desktop hide+ * it here too.+ */+export const useFeatureNavItems = (): NavItem[] => {+ const { t } = useTranslation(['common', 'electron']);+ const { topNavItems, bottomMenuItems } = useNavLayout();+ const enableProjects = useUserStore(labPreferSelectors.enableProjects);+ const activeWorkspaceSlug = useActiveWorkspaceSlug();++ return useMemo(() => {+ const navItems: NavItem[] = [...topNavItems, ...bottomMenuItems].filter(+ (item) => !item.hidden && item.url && !HIDDEN_KEYS.has(item.key),+ );++ if (enableProjects)+ navItems.splice(1, 0, {+ icon: FolderClosed,+ key: 'projects',+ title: t('navigation.projects', { ns: 'electron' }),+ url: '/projects',+ });++ // Personal settings live under the Me tab; a workspace's own settings+ // have no other mobile entry.+ if (activeWorkspaceSlug)+ navItems.push({+ icon: Settings,+ key: SidebarTabKey.Setting,+ title: t('tab.setting'),+ url: '/settings',+ });++ return navItems;+ }, [activeWorkspaceSlug, bottomMenuItems, enableProjects, t, topNavItems]);+};diff --git a/src/features/MobileShell/AgentPagesLayout.tsx b/src/features/MobileShell/AgentPagesLayout.tsxnew file mode 100644index 00000000000..ca0b76dd600--- /dev/null+++ b/src/features/MobileShell/AgentPagesLayout.tsx@@ -0,0 +1,19 @@+'use client';++import { type FC } from 'react';+import { Outlet } from 'react-router';++import { AgentNotFoundGuard } from '@/features/AgentNotFound';++import MobilePageLayout from './PageLayout';++/** Full-screen agent sub-pages (profile, docs, …) with the agent 404 fallback. */+const MobileAgentPagesLayout: FC = () => (+ <MobilePageLayout>+ <AgentNotFoundGuard>+ <Outlet />+ </AgentNotFoundGuard>+ </MobilePageLayout>+);++export default MobileAgentPagesLayout;diff --git a/src/features/MobileShell/AgentScopeLayout.tsx b/src/features/MobileShell/AgentScopeLayout.tsxnew file mode 100644index 00000000000..2f3d3960dcf--- /dev/null+++ b/src/features/MobileShell/AgentScopeLayout.tsx@@ -0,0 +1,30 @@+'use client';++import { type FC } from 'react';+import { Outlet } from 'react-router';++import AgentSidebar from '@/features/AgentSidebar';+import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';+import AgentIdSync from '@/routes/(main)/agent/_layout/AgentIdSync';++/**+ * Owns the routed agent for every mobile `/agent/:aid/*` page: the chat (which+ * brings its own chat header) and the full-screen sub-pages (profile, docs,+ * topics, …, which bring their own page header). The desktop agent sidebar is+ * registered so those sub-pages can open it from their header. The 404 guard+ * sits below each header (chat layout, page layout) so a missing agent keeps+ * the way back.+ */+const AgentScopeLayout: FC = () => {+ useInitAgentConfig();++ return (+ <>+ <AgentSidebar />+ <Outlet />+ <AgentIdSync />+ </>+ );+};++export default AgentScopeLayout;diff --git a/src/features/MobileShell/GroupPagesLayout.tsx b/src/features/MobileShell/GroupPagesLayout.tsxnew file mode 100644index 00000000000..1c4f868049d--- /dev/null+++ b/src/features/MobileShell/GroupPagesLayout.tsx@@ -0,0 +1,19 @@+'use client';++import { type FC } from 'react';+import { Outlet } from 'react-router';++import { GroupNotFoundGuard } from '@/features/GroupNotFound';++import MobilePageLayout from './PageLayout';++/** Full-screen group sub-pages (profile, permission) with the group 404 fallback. */+const MobileGroupPagesLayout: FC = () => (+ <MobilePageLayout>+ <GroupNotFoundGuard>+ <Outlet />+ </GroupNotFoundGuard>+ </MobilePageLayout>+);++export default MobileGroupPagesLayout;diff --git a/src/features/MobileShell/GroupScopeLayout.tsx b/src/features/MobileShell/GroupScopeLayout.tsxnew file mode 100644index 00000000000..1a3b54e4a71--- /dev/null+++ b/src/features/MobileShell/GroupScopeLayout.tsx@@ -0,0 +1,26 @@+'use client';++import { type FC } from 'react';+import { Outlet } from 'react-router';++import { useInitGroupConfig } from '@/hooks/useInitGroupConfig';+import GroupIdSync from '@/routes/(main)/group/_layout/GroupIdSync';+import GroupSidebar from '@/routes/(main)/group/_layout/Sidebar';++/**+ * The group counterpart of {@link AgentScopeLayout}: chat and sub-pages share+ * it; the 404 guard sits below each header.+ */+const GroupScopeLayout: FC = () => {+ useInitGroupConfig();++ return (+ <>+ <GroupSidebar />+ <Outlet />+ <GroupIdSync />+ </>+ );+};++export default GroupScopeLayout;diff --git a/src/features/MobileShell/PageLayout.tsx b/src/features/MobileShell/PageLayout.tsxnew file mode 100644index 00000000000..cf90e41d424--- /dev/null+++ b/src/features/MobileShell/PageLayout.tsx@@ -0,0 +1,89 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { type ComponentType, type FC, type PropsWithChildren, Suspense, useMemo } from 'react';+import { Outlet, useMatches } from 'react-router';++import MobileContentLayout from '@/components/server/MobileNavLayout';+import NavHeader from '@/features/NavHeader';+import { findRouteTitleKey } from '@/features/NavHeader/routeTitle';+import { useRouteTitle } from '@/features/NavHeader/useRouteTitle';++export interface MobileShellHandle {+ /**+ * The page renders no `NavHeader` of its own (desktop gives it the sidebar+ * and titlebar instead), so the mobile shell adds one: back button, sidebar+ * drawer and the route title — or no title (`'untitled'`) when the page+ * opens with its own heading.+ */+ mobileShellHeader?: boolean | 'untitled';+ /** Replaces the static route title when the header should name the record. */+ mobileShellTitle?: ComponentType;+}++const getShellHandle = (handle: unknown): MobileShellHandle =>+ handle && typeof handle === 'object' ? (handle as MobileShellHandle) : {};++interface ShellHeader {+ Title?: ComponentType;+ titleKey: string | null;+}++const useShellHeader = (): ShellHeader | undefined => {+ const matches = useMatches();++ return useMemo(() => {+ const { mobileShellHeader, mobileShellTitle } = getShellHandle(matches.at(-1)?.handle);+ if (!mobileShellHeader) return undefined;+ if (mobileShellHeader === 'untitled') return { titleKey: null };++ return {+ Title: mobileShellTitle,+ titleKey: findRouteTitleKey(matches.map((match) => match.handle)) ?? null,+ };+ }, [matches]);+};++/**+ * Full-screen host for a desktop page mounted on mobile. Pages normally render+ * their own `NavHeader`, which on mobile carries the back button and the+ * sidebar drawer; routes flagged `mobileShellHeader` get one from here.+ */+const MobilePageLayout: FC<PropsWithChildren> = ({ children }) => {+ const header = useShellHeader();+ const title = useRouteTitle(header?.titleKey ?? undefined);++ const content = children ?? <Outlet />;+ const staticTitle = title ? (+ <Text ellipsis weight={500}>+ {title}+ </Text>+ ) : null;++ return (+ <MobileContentLayout style={{ overflowY: 'hidden' }}>+ {header === undefined ? (+ content+ ) : (+ <Flexbox height={'100%'} style={{ minHeight: 0 }} width={'100%'}>+ <NavHeader+ left={+ header.Title ? (+ <Suspense fallback={null}>+ <header.Title />+ </Suspense>+ ) : (+ staticTitle+ )+ }+ />+ <Flexbox flex={1} style={{ minHeight: 0, overflowY: 'auto' }}>+ {content}+ </Flexbox>+ </Flexbox>+ )}+ </MobileContentLayout>+ );+};++export default MobilePageLayout;diff --git a/src/features/MobileShell/ResourceLayout.tsx b/src/features/MobileShell/ResourceLayout.tsxnew file mode 100644index 00000000000..85120d7fe98--- /dev/null+++ b/src/features/MobileShell/ResourceLayout.tsx@@ -0,0 +1,22 @@+'use client';++import { type FC } from 'react';+import { Outlet } from 'react-router';++import { DndContextWrapper } from '@/features/ResourceManager/DndContextWrapper';++import MobilePageLayout from './PageLayout';++/**+ * Resource explorer rows and library tree nodes read the drag context and throw+ * without it. Desktop provides it from the root layout; mobile only needs it here.+ */+const MobileResourceLayout: FC = () => (+ <DndContextWrapper>+ <MobilePageLayout>+ <Outlet />+ </MobilePageLayout>+ </DndContextWrapper>+);++export default MobileResourceLayout;diff --git a/src/features/NavHeader/MobileBackButton.tsx b/src/features/NavHeader/MobileBackButton.tsxnew file mode 100644index 00000000000..d6e9265f88c--- /dev/null+++ b/src/features/NavHeader/MobileBackButton.tsx@@ -0,0 +1,38 @@+'use client';++import { ActionIcon } from '@lobehub/ui';+import { ChevronLeft } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';++import { useMobileBack } from './useMobileBack';++interface MobileBackButtonProps {+ /** Workspace-aware path used when the page was opened directly. */+ fallback?: string;+}++/**+ * The mobile shell has no left panel, so page headers that would show the+ * panel toggle show this instead — it is the only way off a full-screen page.+ */+const MobileBackButton = memo<MobileBackButtonProps>(({ fallback }) => {+ const { t } = useTranslation('common');+ const back = useMobileBack(fallback);++ return (+ <ActionIcon+ aria-label={t('back')}+ icon={ChevronLeft}+ size={MOBILE_HEADER_ICON_SIZE}+ title={t('back')}+ onClick={back}+ />+ );+});++MobileBackButton.displayName = 'MobileBackButton';++export default MobileBackButton;diff --git a/src/features/NavHeader/MobileHeaderNav.tsx b/src/features/NavHeader/MobileHeaderNav.tsxnew file mode 100644index 00000000000..cae135e1a5c--- /dev/null+++ b/src/features/NavHeader/MobileHeaderNav.tsx@@ -0,0 +1,22 @@+'use client';++import { memo } from 'react';++import MobileBackButton from './MobileBackButton';+import MobileNavPanelButton from './MobileNavPanelButton';++/**+ * What a page header shows on mobile where desktop shows the left panel+ * toggle: a back button, and the route's sidebar as a drawer when it has one.+ * Use it in custom page headers that do not go through `NavHeader`.+ */+const MobileHeaderNav = memo(() => (+ <>+ <MobileBackButton />+ <MobileNavPanelButton />+ </>+));++MobileHeaderNav.displayName = 'MobileHeaderNav';++export default MobileHeaderNav;diff --git a/src/features/NavHeader/MobileNavPanelButton.tsx b/src/features/NavHeader/MobileNavPanelButton.tsxnew file mode 100644index 00000000000..f98654c2a01--- /dev/null+++ b/src/features/NavHeader/MobileNavPanelButton.tsx@@ -0,0 +1,67 @@+'use client';++import { ActionIcon, cssVar, Drawer } from '@lobehub/ui';+import { MenuIcon } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useLocation } from 'react-router';++import { MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';+import { MobileNavDrawerContext } from '@/features/NavPanel/MobileDrawerContext';++import { useNavPanelDrawerContent } from './useNavPanelDrawerContent';++const DRAWER_WIDTH = 300;++/**+ * Desktop pages publish their sidebar (section nav, lists, pickers) through+ * `NavPanelPortal`, and only the desktop shell reads it. On mobile the same+ * registered content opens in a left drawer, so a page keeps its sub-navigation+ * without a mobile copy of every sidebar.+ */+const MobileNavPanelButton = memo(() => {+ const { t } = useTranslation('common');+ const { pathname, search } = useLocation();+ const [open, setOpen] = useState(false);+ const close = useCallback(() => setOpen(false), []);++ const content = useNavPanelDrawerContent();++ // Sidebar items navigate; picking one should reveal the page it opened.+ useEffect(() => {+ setOpen(false);+ }, [pathname, search]);++ if (!content) return null;++ return (+ <>+ <ActionIcon+ aria-label={t('navPanel.openMenu')}+ icon={MenuIcon}+ size={MOBILE_HEADER_ICON_SIZE}+ title={t('navPanel.openMenu')}+ onClick={() => setOpen(true)}+ />+ <Drawer+ noHeader+ closable={false}+ open={open}+ placement={'left'}+ styles={{ bodyContent: { padding: 0 } }}+ width={DRAWER_WIDTH}+ style={{+ background: cssVar.colorBgLayout,+ borderRight: `1px solid ${cssVar.colorSplit}`,+ }}+ onClose={close}+ >+ <MobileNavDrawerContext value={close}>{content}</MobileNavDrawerContext>+ </Drawer>+ </>+ );+});++MobileNavPanelButton.displayName = 'MobileNavPanelButton';++export default MobileNavPanelButton;diff --git a/src/features/NavHeader/MobileRouteTitle.tsx b/src/features/NavHeader/MobileRouteTitle.tsxnew file mode 100644index 00000000000..c5bbe789890--- /dev/null+++ b/src/features/NavHeader/MobileRouteTitle.tsx@@ -0,0 +1,30 @@+'use client';++import { Text } from '@lobehub/ui';+import { memo, useMemo } from 'react';+import { useMatches } from 'react-router';++import { findRouteTitleKey } from './routeTitle';+import { useRouteTitle } from './useRouteTitle';++/**+ * On desktop the sidebar tells the user where they are; a full-screen mobile+ * page whose header has no title of its own names the route instead.+ */+const MobileRouteTitle = memo(() => {+ const matches = useMatches();+ const titleKey = useMemo(() => findRouteTitleKey(matches.map((m) => m.handle)), [matches]);+ const title = useRouteTitle(titleKey);++ if (!title) return null;++ return (+ <Text ellipsis weight={500}>+ {title}+ </Text>+ );+});++MobileRouteTitle.displayName = 'MobileRouteTitle';++export default MobileRouteTitle;diff --git a/src/features/NavHeader/index.tsx b/src/features/NavHeader/index.tsxindex 82261951443..547910f0dbc 100644--- a/src/features/NavHeader/index.tsx+++ b/src/features/NavHeader/index.tsx@@ -6,6 +6,11 @@ import { memo } from 'react';import ToggleLeftPanelButton, { isMacDesktop } from '@/features/NavPanel/ToggleLeftPanelButton';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { isMobileSurface } from '@/utils/mobileSurface';++import { getNavHeaderLeading } from './leading';+import MobileHeaderNav from './MobileHeaderNav';+import MobileRouteTitle from './MobileRouteTitle';export interface NavHeaderProps extends Omit<FlexboxProps, 'children'> {children?: ReactNode;@@ -37,11 +42,15 @@ const NavHeader = memo<NavHeaderProps>(}) => {const expand = useGlobalStore(systemStatusSelectors.showLeftPanel);- const noContent = !left && !right && !children;+ const leading = getNavHeaderLeading({+ expand: !!expand,+ isMacDesktop,+ mobile: isMobileSurface(),+ noContent: !left && !right && !children,+ showTogglePanelButton,+ });- // When empty, this header only rendered to host the collapse toggle. Hide it- // when expanded, and also on macOS desktop where the toggle moved to the titlebar.- if (noContent && (expand || isMacDesktop)) return;+ if (leading === 'hidden') return;return (<Flexbox@@ -66,8 +75,10 @@ const NavHeader = memo<NavHeaderProps>(justify={'flex-start'}style={styles?.left}>- {showTogglePanelButton && !expand && <ToggleLeftPanelButton />}- {left}+ {leading === 'mobile' && <MobileHeaderNav />}+ {leading === 'toggle' && <ToggleLeftPanelButton />}+ {/* `left={null}` opts a mobile header out of the route-title fallback. */}+ {left === undefined && leading === 'mobile' && !children ? <MobileRouteTitle /> : left}</Flexbox>{children && (<Flexbox className={slotClassNames?.center} flex={1} style={styles?.center}>diff --git a/src/features/NavHeader/leading.test.ts b/src/features/NavHeader/leading.test.tsnew file mode 100644index 00000000000..5438352e94e--- /dev/null+++ b/src/features/NavHeader/leading.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { getNavHeaderLeading, type NavHeaderLeadingInput } from './leading';++const input = (overrides: Partial<NavHeaderLeadingInput>): NavHeaderLeadingInput => ({+ expand: false,+ isMacDesktop: false,+ mobile: false,+ noContent: false,+ showTogglePanelButton: true,+ ...overrides,+});++describe('getNavHeaderLeading', () => {+ describe('desktop', () => {+ it('shows the panel toggle while the left panel is collapsed', () => {+ expect(getNavHeaderLeading(input({}))).toBe('toggle');+ });++ it('drops the toggle while the left panel is open', () => {+ expect(getNavHeaderLeading(input({ expand: true }))).toBe('none');+ });++ it('hides an empty header that only hosted the toggle', () => {+ expect(getNavHeaderLeading(input({ expand: true, noContent: true }))).toBe('hidden');+ expect(getNavHeaderLeading(input({ isMacDesktop: true, noContent: true }))).toBe('hidden');+ });+ });++ describe('mobile', () => {+ it('replaces the panel toggle with the back + drawer pair', () => {+ expect(getNavHeaderLeading(input({ mobile: true }))).toBe('mobile');+ // The desktop panel state is irrelevant: there is no left panel.+ expect(getNavHeaderLeading(input({ expand: true, mobile: true }))).toBe('mobile');+ });++ it('keeps a content-less page header so the page still has a way back', () => {+ expect(getNavHeaderLeading(input({ expand: true, mobile: true, noContent: true }))).toBe(+ 'mobile',+ );+ });++ it('leaves panel headers that opt out of the toggle without a back button', () => {+ expect(getNavHeaderLeading(input({ mobile: true, showTogglePanelButton: false }))).toBe(+ 'none',+ );+ expect(+ getNavHeaderLeading(input({ mobile: true, noContent: true, showTogglePanelButton: false })),+ ).toBe('hidden');+ });+ });+});diff --git a/src/features/NavHeader/leading.ts b/src/features/NavHeader/leading.tsnew file mode 100644index 00000000000..3ae166c691e--- /dev/null+++ b/src/features/NavHeader/leading.ts@@ -0,0 +1,40 @@+export interface NavHeaderLeadingInput {+ /** The desktop left panel is open (the toggle is then redundant). */+ expand: boolean;+ /** macOS Electron, where the toggle lives in the titlebar. */+ isMacDesktop: boolean;+ /** The mobile SPA bundle, which has no left panel. */+ mobile: boolean;+ /** The header was given no left / right / center content. */+ noContent: boolean;+ showTogglePanelButton: boolean;+}++/**+ * What a `NavHeader` puts before its own content:+ * - `hidden`: render no header at all,+ * - `mobile`: back button + the route sidebar drawer,+ * - `toggle`: the desktop left panel toggle,+ * - `none`: nothing extra.+ */+export type NavHeaderLeading = 'hidden' | 'mobile' | 'none' | 'toggle';++export const getNavHeaderLeading = ({+ expand,+ isMacDesktop,+ mobile,+ noContent,+ showTogglePanelButton,+}: NavHeaderLeadingInput): NavHeaderLeading => {+ if (mobile) {+ // A full-screen mobile page always needs a way back; a panel header that+ // opts out of the toggle and has nothing to show stays hidden.+ if (!showTogglePanelButton) return noContent ? 'hidden' : 'none';+ return 'mobile';+ }++ // When empty, the header only exists to host the collapse toggle: hide it+ // while the panel is open and on macOS desktop, where the toggle is in the titlebar.+ if (noContent && (expand || isMacDesktop)) return 'hidden';+ return showTogglePanelButton && !expand ? 'toggle' : 'none';+};diff --git a/src/features/NavHeader/routeTitle.test.ts b/src/features/NavHeader/routeTitle.test.tsnew file mode 100644index 00000000000..01a06f563c6--- /dev/null+++ b/src/features/NavHeader/routeTitle.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { findRouteTitleKey, getRouteTitleNamespaces } from './routeTitle';++describe('findRouteTitleKey', () => {+ it('takes the deepest route that declares a title', () => {+ expect(+ findRouteTitleKey([+ { meta: { titleKey: 'navigation.memory' } },+ { meta: {} },+ { meta: { titleKey: 'navigation.memoryIdentities' } },+ undefined,+ ]),+ ).toBe('navigation.memoryIdentities');+ });++ it('is undefined when no route in the chain has a title', () => {+ expect(findRouteTitleKey([undefined, { meta: {} }, { other: true }])).toBeUndefined();+ });+});++describe('getRouteTitleNamespaces', () => {+ it('loads the namespace a prefixed title names', () => {+ expect(getRouteTitleNamespaces('project:sections.home')).toEqual(['electron', 'project']);+ });++ it('defaults to the electron namespace', () => {+ expect(getRouteTitleNamespaces('navigation.memory')).toEqual(['electron']);+ expect(getRouteTitleNamespaces(undefined)).toEqual(['electron']);+ });+});diff --git a/src/features/NavHeader/routeTitle.ts b/src/features/NavHeader/routeTitle.tsnew file mode 100644index 00000000000..5889323c11d--- /dev/null+++ b/src/features/NavHeader/routeTitle.ts@@ -0,0 +1,20 @@+import { getRouteMetaFromHandle } from '@/spa/router/routeMeta';++/** The deepest route title in a match chain (`useMatches()` handles). */+export const findRouteTitleKey = (handles: readonly unknown[]): string | undefined => {+ for (let i = handles.length - 1; i >= 0; i -= 1) {+ const titleKey = getRouteMetaFromHandle(handles[i])?.titleKey;+ if (titleKey) return titleKey;+ }+ return undefined;+};++/**+ * Namespaces a route title needs loaded. Titles default to `electron`; a+ * `project:sections.home` style key names its own namespace, which a mobile+ * page may not have loaded yet.+ */+export const getRouteTitleNamespaces = (titleKey: string | undefined): string[] => {+ const separator = titleKey?.indexOf(':') ?? -1;+ return separator > 0 ? ['electron', titleKey!.slice(0, separator)] : ['electron'];+};diff --git a/src/features/NavHeader/useMobileBack.test.ts b/src/features/NavHeader/useMobileBack.test.tsnew file mode 100644index 00000000000..40d71ef081e--- /dev/null+++ b/src/features/NavHeader/useMobileBack.test.ts@@ -0,0 +1,53 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { canGoBackInApp, useMobileBack } from './useMobileBack';++const navigate = vi.fn();++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => navigate,+}));++beforeEach(() => {+ navigate.mockClear();+ window.history.replaceState(null, '');+});++describe('canGoBackInApp', () => {+ it('is false on the entry page of the session', () => {+ window.history.replaceState({ idx: 0 }, '');+ expect(canGoBackInApp()).toBe(false);+ });++ it('is false without router history state (deep link before the router wrote any)', () => {+ expect(canGoBackInApp()).toBe(false);+ });++ it('is true once the user navigated in-app', () => {+ window.history.replaceState({ idx: 3 }, '');+ expect(canGoBackInApp()).toBe(true);+ });+});++describe('useMobileBack', () => {+ it('goes back in history when the page was reached in-app', () => {+ window.history.replaceState({ idx: 1 }, '');++ renderHook(() => useMobileBack()).result.current();++ expect(navigate).toHaveBeenCalledWith(-1);+ });++ it('falls back to home for a page opened directly', () => {+ renderHook(() => useMobileBack()).result.current();++ expect(navigate).toHaveBeenCalledWith('/');+ });++ it('uses the given fallback', () => {+ renderHook(() => useMobileBack('/tasks')).result.current();++ expect(navigate).toHaveBeenCalledWith('/tasks');+ });+});diff --git a/src/features/NavHeader/useMobileBack.ts b/src/features/NavHeader/useMobileBack.tsnew file mode 100644index 00000000000..26b85517c1d--- /dev/null+++ b/src/features/NavHeader/useMobileBack.ts@@ -0,0 +1,24 @@+import { useCallback } from 'react';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++/**+ * react-router records the session-history index in `history.state.idx`; `0`+ * means this page was the entry point (deep link, refresh, new tab), so there is+ * no in-app page to go back to.+ */+export const canGoBackInApp = () => {+ if (typeof window === 'undefined') return false;+ const idx = (window.history.state as { idx?: number } | null)?.idx;+ return typeof idx === 'number' && idx > 0;+};++/** Back for a full-screen mobile page: history when reached in-app, else `fallback`. */+export const useMobileBack = (fallback = '/') => {+ const navigate = useWorkspaceAwareNavigate();++ return useCallback(() => {+ if (canGoBackInApp()) navigate(-1);+ else navigate(fallback);+ }, [fallback, navigate]);+};diff --git a/src/features/NavHeader/useNavPanelDrawerContent.test.ts b/src/features/NavHeader/useNavPanelDrawerContent.test.tsnew file mode 100644index 00000000000..60d197e64f5--- /dev/null+++ b/src/features/NavHeader/useNavPanelDrawerContent.test.ts@@ -0,0 +1,59 @@+import { act, renderHook } from '@testing-library/react';+import { createElement } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ clearNavPanelRegistry,+ registerNavPanelContent,+ unregisterNavPanelContent,+} from '@/features/NavPanel/registry';++import { useNavPanelDrawerContent } from './useNavPanelDrawerContent';++const mocks = vi.hoisted(() => ({ navKey: 'memory' }));++vi.mock('@/features/NavPanel/useActiveNavKey', () => ({+ useActiveNavKey: () => mocks.navKey,+}));++beforeEach(() => {+ mocks.navKey = 'memory';+ clearNavPanelRegistry();+});++describe('useNavPanelDrawerContent', () => {+ it('is empty until the route registers its sidebar', () => {+ const owner = Symbol('memory-sidebar');+ const sidebar = createElement('nav', null, 'memory sections');+ const { result } = renderHook(() => useNavPanelDrawerContent());++ expect(result.current).toBeUndefined();++ act(() => registerNavPanelContent('memory', owner, sidebar));+ expect(result.current).toBe(sidebar);++ act(() => unregisterNavPanelContent('memory', owner));+ expect(result.current).toBeUndefined();+ });++ it('ignores sidebars other routes registered', () => {+ registerNavPanelContent('resource', Symbol('resource-sidebar'), 'resource sidebar');++ expect(renderHook(() => useNavPanelDrawerContent()).result.current).toBeUndefined();+ });++ // `useNavPanelDrawerContent` skips `home` on purpose (`navKey === 'home'`): the+ // home route's registered sidebar is the agent list mobile already renders+ // as the page itself.+ it('skips the home route sidebar while serving other routes from the same registry', () => {+ mocks.navKey = 'home';+ registerNavPanelContent('home', Symbol('home-sidebar'), 'agent list');+ registerNavPanelContent('memory', Symbol('memory-sidebar'), 'memory sections');++ expect(renderHook(() => useNavPanelDrawerContent()).result.current).toBeUndefined();++ // The same registry still serves another route's sidebar.+ mocks.navKey = 'memory';+ expect(renderHook(() => useNavPanelDrawerContent()).result.current).toBe('memory sections');+ });+});diff --git a/src/features/NavHeader/useNavPanelDrawerContent.ts b/src/features/NavHeader/useNavPanelDrawerContent.tsnew file mode 100644index 00000000000..6f5f4c858e7--- /dev/null+++ b/src/features/NavHeader/useNavPanelDrawerContent.ts@@ -0,0 +1,21 @@+import { type ReactNode, useSyncExternalStore } from 'react';++import {+ getNavPanelRegistrySnapshot,+ subscribeNavPanelRegistry,+} from '@/features/NavPanel/registry';+import { useActiveNavKey } from '@/features/NavPanel/useActiveNavKey';++/**+ * The sidebar the active route registered through `NavPanelPortal`, for the+ * mobile drawer. `home` is the desktop agent list, which mobile already shows+ * as its home page, so it never opens as a drawer.+ */+export const useNavPanelDrawerContent = (): ReactNode | undefined => {+ const navKey = useActiveNavKey();++ const getContent = () =>+ navKey === 'home' ? undefined : getNavPanelRegistrySnapshot().get(navKey)?.node;++ return useSyncExternalStore(subscribeNavPanelRegistry, getContent, getContent);+};diff --git a/src/features/NavHeader/useRouteTitle.ts b/src/features/NavHeader/useRouteTitle.tsnew file mode 100644index 00000000000..c29a969ae42--- /dev/null+++ b/src/features/NavHeader/useRouteTitle.ts@@ -0,0 +1,16 @@+import { useTranslation } from 'react-i18next';++import { getRouteTitleNamespaces } from './routeTitle';++/**+ * Translates a route `titleKey`, loading the namespace it names. Undefined+ * until that namespace is ready, so the header never flashes the raw key.+ */+export const useRouteTitle = (titleKey: string | undefined): string | undefined => {+ const { ready, t } = useTranslation(+ // A route title names its namespace in the key, so it is only known at runtime.+ getRouteTitleNamespaces(titleKey) as Parameters<typeof useTranslation>[0],+ );++ return titleKey && ready ? t(titleKey as any) : undefined;+};diff --git a/src/features/NavPanel/MobileDrawerContext.ts b/src/features/NavPanel/MobileDrawerContext.tsnew file mode 100644index 00000000000..bdf66bc0037--- /dev/null+++ b/src/features/NavPanel/MobileDrawerContext.ts@@ -0,0 +1,10 @@+import { createContext, use } from 'react';++/**+ * Set while a route's sidebar is shown inside the mobile nav drawer+ * (`NavHeader/MobileNavPanelButton`). Sidebar controls that would collapse the+ * desktop left panel close the drawer instead.+ */+export const MobileNavDrawerContext = createContext<(() => void) | null>(null);++export const useCloseMobileNavDrawer = () => use(MobileNavDrawerContext);diff --git a/src/features/NavPanel/ToggleLeftPanelButton.tsx b/src/features/NavPanel/ToggleLeftPanelButton.tsxindex f9b0f73f1d3..399d3238af6 100644--- a/src/features/NavPanel/ToggleLeftPanelButton.tsx+++ b/src/features/NavPanel/ToggleLeftPanelButton.tsx@@ -15,6 +15,8 @@ import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';import { isMacOS } from '@/utils/platform';+import { useCloseMobileNavDrawer } from './MobileDrawerContext';+export const TOGGLE_BUTTON_ID = 'toggle_left_panel_button';// On macOS desktop a persistent toggle lives in the titlebar (NavigationBar),@@ -47,11 +49,24 @@ const ToggleLeftPanelButton = memo<ToggleLeftPanelButtonProps>(s.toggleLeftPanel,]);const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleLeftPanel));+ const closeMobileDrawer = useCloseMobileNavDrawer();const { t } = useTranslation(['chat', 'hotkey']);if (isMacDesktop && !forceVisible) return null;+ // Inside the mobile nav drawer there is no left panel to toggle: the+ // sidebar is the drawer, so the collapse button closes it.+ if (closeMobileDrawer)+ return (+ <ActionIcon+ icon={PanelLeftClose}+ size={size || DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={title || t('toggleLeftPanel.title', { ns: 'hotkey' })}+ onClick={closeMobileDrawer}+ />+ );+return (<ActionIconactive={showActive ? expand : undefined}diff --git a/src/features/Pages/MobilePageLayout.tsx b/src/features/Pages/MobilePageLayout.tsxnew file mode 100644index 00000000000..faef941f835--- /dev/null+++ b/src/features/Pages/MobilePageLayout.tsx@@ -0,0 +1,24 @@+'use client';++import { type FC } from 'react';+import { Outlet } from 'react-router';++import MobilePageLayout from '@/features/MobileShell/PageLayout';++import DataSync from './PageLayout/DataSync';++/**+ * Mobile `/page/*`: `DataSync` hands the page store its router `navigate`, which+ * create/select use to open the new page. The desktop sidebar is left out —+ * on mobile the list is the `/page` index itself.+ */+const MobilePagesLayout: FC = () => (+ <>+ <MobilePageLayout>+ <Outlet />+ </MobilePageLayout>+ <DataSync />+ </>+);++export default MobilePagesLayout;diff --git a/src/features/Pages/MobilePageList.tsx b/src/features/Pages/MobilePageList.tsxnew file mode 100644index 00000000000..90d789b1226--- /dev/null+++ b/src/features/Pages/MobilePageList.tsx@@ -0,0 +1,35 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import NavHeader from '@/features/NavHeader';++import Body from './PageLayout/Body';+import AddButton from './PageLayout/Header/AddButton';++/**+ * Mobile `/page`: the desktop index is a "create a page" placeholder beside the+ * sidebar list. Mobile has no sidebar, so the list itself is the page.+ */+const MobilePageList = memo(() => {+ const { t } = useTranslation('common');++ return (+ <Flexbox height={'100%'} width={'100%'}>+ <NavHeader+ showTogglePanelButton+ left={<Text weight={500}>{t('tab.pages')}</Text>}+ right={<AddButton />}+ />+ <Flexbox flex={1} paddingBlock={8} style={{ overflowY: 'auto' }}>+ <Body />+ </Flexbox>+ </Flexbox>+ );+});++MobilePageList.displayName = 'MobilePageList';++export default MobilePageList;diff --git a/src/features/Projects/Acceptance/Detail.tsx b/src/features/Projects/Acceptance/Detail.tsxindex 0c51ce227a9..d5c4e550cc5 100644--- a/src/features/Projects/Acceptance/Detail.tsx+++ b/src/features/Projects/Acceptance/Detail.tsx@@ -12,6 +12,7 @@ import {} from '@/features/Acceptance';import TopicPanel from '@/features/Acceptance/Viewer/Conversation/TopicPanel';import NavHeader from '@/features/NavHeader';+import { isMobileSurface } from '@/utils/mobileSurface';/** `project/:projectId/acceptance/:acceptanceId` — one acceptance, back to the project's list. */const ProjectAcceptanceDetail = () => {@@ -22,6 +23,9 @@ const ProjectAcceptanceDetail = () => {return (<Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}><NavHeader+ // The page's own back leads to its list; mobile drops the shell's+ // history back so there is one.+ showTogglePanelButton={!isMobileSurface()}left={<Flexbox horizontal align={'center'} gap={6}><ActionIcondiff --git a/src/features/Projects/Conversation/Mobile.tsx b/src/features/Projects/Conversation/Mobile.tsxnew file mode 100644index 00000000000..2d8146f1b83--- /dev/null+++ b/src/features/Projects/Conversation/Mobile.tsx@@ -0,0 +1,57 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { memo } from 'react';++import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';+import NavHeader from '@/features/NavHeader';+import ChatHydration from '@/routes/(main)/agent/features/Conversation/ChatHydration';+import ConversationArea from '@/routes/(main)/agent/features/Conversation/ConversationArea';+import PortalPanel from '@/routes/(main)/agent/features/Portal/features/PortalPanel';++import ProjectTopicActions from './ProjectTopicActions';+import { useProjectConversation } from './useProjectConversation';++/**+ * Mobile has no working/terminal side panels: the project topic runs in the+ * same conversation stack as a mobile agent chat, under the page header.+ */+const MobileProjectConversation = memo(() => {+ const { fallback, getConversationPath, getTopicPath, restageDraft, stage, title, topic } =+ useProjectConversation();++ if (fallback) return fallback;++ return (+ <Flexbox height={'100%'} style={{ minHeight: 0 }} width={'100%'}>+ <NavHeader+ right={topic && <ProjectTopicActions topic={topic} />}+ left={+ <Text ellipsis weight={600}>+ {title}+ </Text>+ }+ />+ {stage === 'ready' ? (+ <>+ <ChatHydration getConversationPath={getConversationPath} getTopicPath={getTopicPath} />+ <Flexbox+ flex={1}+ style={{ minHeight: 0, minWidth: 0, position: 'relative' }}+ onFocusCapture={restageDraft}+ onPointerDownCapture={restageDraft}+ >+ <ConversationArea />+ </Flexbox>+ </>+ ) : (+ <ConversationSegmentSkeleton />+ )}+ <PortalPanel mobile />+ </Flexbox>+ );+});++MobileProjectConversation.displayName = 'MobileProjectConversation';++export default MobileProjectConversation;diff --git a/src/features/Projects/Conversation/ProjectTopicActions.tsx b/src/features/Projects/Conversation/ProjectTopicActions.tsxnew file mode 100644index 00000000000..072bd983cab--- /dev/null+++ b/src/features/Projects/Conversation/ProjectTopicActions.tsx@@ -0,0 +1,24 @@+'use client';++import { useTranslation } from 'react-i18next';++import TopicActions from '@/features/AgentSidebar/Topic/List/Item/Actions';++import type { useProjectConversation } from './useProjectConversation';++type ProjectConversationTopic = NonNullable<ReturnType<typeof useProjectConversation>['topic']>;++const ProjectTopicActions = ({ topic }: { topic: ProjectConversationTopic }) => {+ const { t } = useTranslation('project');++ return (+ <TopicActions+ completionLabel={t(topic.status === 'completed' ? 'topics.resume' : 'topics.complete')}+ id={topic.id}+ status={topic.status}+ title={topic.title}+ />+ );+};++export default ProjectTopicActions;diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsxindex 9b0c6703eca..43d479460d4 100644--- a/src/features/Projects/Conversation/index.tsx+++ b/src/features/Projects/Conversation/index.tsx@@ -1,159 +1,24 @@'use client';-import { Center, Flexbox, Spin, Text } from '@lobehub/ui';-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';-import { useTranslation } from 'react-i18next';-import { Navigate, useParams, useSearchParams } from 'react-router';+import { Flexbox, Text } from '@lobehub/ui';+import { memo } from 'react';-import AsyncError from '@/components/AsyncError';import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';-import TopicActions from '@/features/AgentSidebar/Topic/List/Item/Actions';import ConversationWorkspace from '@/features/Conversation/Workspace';import NavHeader from '@/features/NavHeader';-import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';import ChatConversation from '@/routes/(main)/agent/features/Conversation';import ChatHydration from '@/routes/(main)/agent/features/Conversation/ChatHydration';import TerminalPanelToggle from '@/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle';import WorkingPanelToggle from '@/routes/(main)/agent/features/Conversation/Header/WorkingPanelToggle';-import { useAgentStore } from '@/store/agent';-import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';-import { useCurrentProjectDetail, useProjectStore } from '@/store/project';-import {- useProjectDirectories,- useProjectDirectoryStore,- useProjectTopics,-} from '@/store/projectWorkingDirectory';-import { getProjectTopicPath } from '../Layout/navigation';-import { freshProjectTopicAgentId } from './freshProjectTopicAgentId';-import { projectConversationStage } from './projectConversationStage';-import { useMarkProjectTopicRead } from './useMarkProjectTopicRead';-import { useProjectDraftStaging } from './useProjectDraftStaging';-import { useRevalidateWhileUnlisted } from './useRevalidateWhileUnlisted';+import ProjectTopicActions from './ProjectTopicActions';+import { useProjectConversation } from './useProjectConversation';const ProjectConversation = memo(() => {- const { t } = useTranslation('project');- const { projectId, topicId } = useParams<{ projectId: string; topicId?: string }>();- const detail = useCurrentProjectDetail(projectId);- const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);- const topicsRequest = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(- detail?.project.id,- );- const topics = useProjectTopics(detail?.project.id);- const selectedTopic = topics.find((topic) => topic.id === topicId);- const projectSlug = detail?.project.slug ?? projectId;- const storedTopic = useChatStore((s) =>- topicId ? topicSelectors.getTopicById(topicId)(s) : undefined,- );- // A sidebar "+" opens a blank draft instead of creating a row (see- // `startProjectTopicDraft`). The draft rides in this pane's route, so split- // panes keep their own; the first message creates the topic.- const [searchParams] = useSearchParams();- const draftAgentParam = topicId ? null : searchParams.get('agent');- const draftDirectoryParam = topicId ? null : searchParams.get('dir');- const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(- detail?.project.id,- );- const directories = useProjectDirectories(detail?.project.id);- const directoryIds = useMemo(() => new Set(directories.map((d) => d.id)), [directories]);- const draft = useMemo(- () =>- draftAgentParam && draftDirectoryParam && directoryIds.has(draftDirectoryParam)- ? { agentId: draftAgentParam, projectWorkingDirectoryId: draftDirectoryParam }- : undefined,- [draftAgentParam, draftDirectoryParam, directoryIds],- );- const draftAgentId = draft?.agentId;- const restageDraft = useProjectDraftStaging(draft, directoryIds);- const chatAgentId = useChatStore((s) => s.activeAgentId);- // Keep the conversation on its agent instead of flashing "not found" while- // the project list catches up with a topic the first send just created.- const freshOwnerRef = useRef<{ agentId: string; topicId: string }>(undefined);- const freshTopicAgentId = freshProjectTopicAgentId({- listed: !!selectedTopic,- projectId: detail?.project.id,- rememberedOwner: freshOwnerRef.current,- storedTopic,- topicId,- });- useEffect(() => {- if (freshTopicAgentId && topicId)- freshOwnerRef.current = { agentId: freshTopicAgentId, topicId };- }, [freshTopicAgentId, topicId]);- const isFreshTopic = !!freshTopicAgentId;- const conversationAgentId = topicId- ? (selectedTopic?.agentId ?? freshTopicAgentId)- : draftAgentId;- useRevalidateWhileUnlisted(isFreshTopic, topicId, topicsRequest.revalidate);- const topicTitle = storedTopic?.title;-- const agent = useInitAgentConfig(conversationAgentId);- const topicDetail = useChatStore((s) => s.useFetchTopicDetail)(selectedTopic?.id);- useMarkProjectTopicRead(detail?.project.id, selectedTopic);-- useLayoutEffect(() => {- if (!conversationAgentId) return;-- useAgentStore.setState(- { activeAgentId: conversationAgentId },- false,- 'ProjectConversation/syncAgentId',- );- useChatStore.setState(- { activeAgentId: conversationAgentId },- false,- 'ProjectConversation/syncAgentId',- );- }, [conversationAgentId]);-- const getConversationPath = useCallback(() => getProjectTopicPath(projectSlug!), [projectSlug]);- const getTopicPath = useCallback(- (_agentId: string, topicId: string) => getProjectTopicPath(projectSlug!, topicId),- [projectSlug],- );+ const { fallback, getConversationPath, getTopicPath, restageDraft, stage, title, topic } =+ useProjectConversation();- if (topicDetail.error)- return <AsyncError error={topicDetail.error} variant="page" onRetry={topicDetail.revalidate} />;- if (agent.error) return <AsyncError error={agent.error} variant="page" onRetry={agent.mutate} />;- if (topicsRequest.error)- return (- <AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />- );- if (!topicId && !draftAgentId) {- // A draft's directory list may still be loading; wait for it rather than- // sending the draft away.- if (draftAgentParam && !directoriesRequest.hasData)- return (- <Center height="100%" width="100%">- <Spin size="small" />- </Center>- );- // Other new project conversations start from the project home composer.- return <Navigate replace relative="path" to=".." />;- }- if (topicId && topicsRequest.hasData && !selectedTopic && !isFreshTopic)- return (- <Center height="100%">- <Text>{t('topics.notFound')}</Text>- </Center>- );- if (detailSWR.error && !detail) {- return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.revalidate} />;- }- const stage = projectConversationStage({- agentConfigLoading: !!agent.isLoading,- chatAgentId,- conversationAgentId,- hasProject: !!detail,- });- if (stage === 'loading') {- return (- <Center height="100%" width="100%">- <Spin size="small" />- </Center>- );- }+ if (fallback) return fallback;return (<ConversationWorkspace@@ -161,23 +26,14 @@ const ProjectConversation = memo(() => {<NavHeaderleft={<Text ellipsis weight={600}>- {topicTitle || selectedTopic?.title || t('sidebar.newConversation')}+ {title}</Text>}right={<Flexbox horizontal align="center" gap={4}><TerminalPanelToggle /><WorkingPanelToggle />- {topicId && (- <TopicActions- id={topicId}- status={selectedTopic?.status}- title={topicTitle || selectedTopic?.title || t('directories.untitled')}- completionLabel={t(- selectedTopic?.status === 'completed' ? 'topics.resume' : 'topics.complete',- )}- />- )}+ {topic && <ProjectTopicActions topic={topic} />}</Flexbox>}/>diff --git a/src/features/Projects/Conversation/useProjectConversation.tsx b/src/features/Projects/Conversation/useProjectConversation.tsxnew file mode 100644index 00000000000..6d231d56950--- /dev/null+++ b/src/features/Projects/Conversation/useProjectConversation.tsx@@ -0,0 +1,172 @@+'use client';++import { Center, Spin, Text } from '@lobehub/ui';+import { type ReactElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { Navigate, useParams, useSearchParams } from 'react-router';++import AsyncError from '@/components/AsyncError';+import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';+import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';+import {+ useProjectDirectories,+ useProjectDirectoryStore,+ useProjectTopics,+} from '@/store/projectWorkingDirectory';++import { getProjectTopicPath } from '../Layout/navigation';+import { freshProjectTopicAgentId } from './freshProjectTopicAgentId';+import { projectConversationStage } from './projectConversationStage';+import { useMarkProjectTopicRead } from './useMarkProjectTopicRead';+import { useProjectDraftStaging } from './useProjectDraftStaging';+import { useRevalidateWhileUnlisted } from './useRevalidateWhileUnlisted';++const loading = (+ <Center height="100%" width="100%">+ <Spin size="small" />+ </Center>+);++/**+ * Route, store and agent wiring for a project conversation, shared by the+ * desktop workspace and the mobile page. `fallback` is set until the pane can+ * render at all (error, redirect, not-found or loading).+ */+export const useProjectConversation = () => {+ const { t } = useTranslation('project');+ const { projectId, topicId } = useParams<{ projectId: string; topicId?: string }>();+ const detail = useCurrentProjectDetail(projectId);+ const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);+ const topicsRequest = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(+ detail?.project.id,+ );+ const topics = useProjectTopics(detail?.project.id);+ const selectedTopic = topics.find((topic) => topic.id === topicId);+ const projectSlug = detail?.project.slug ?? projectId;+ const storedTopic = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s) : undefined,+ );+ // A sidebar "+" opens a blank draft instead of creating a row (see+ // `startProjectTopicDraft`). The draft rides in this pane's route, so split+ // panes keep their own; the first message creates the topic.+ const [searchParams] = useSearchParams();+ const draftAgentParam = topicId ? null : searchParams.get('agent');+ const draftDirectoryParam = topicId ? null : searchParams.get('dir');+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(+ detail?.project.id,+ );+ const directories = useProjectDirectories(detail?.project.id);+ const directoryIds = useMemo(() => new Set(directories.map((d) => d.id)), [directories]);+ const draft = useMemo(+ () =>+ draftAgentParam && draftDirectoryParam && directoryIds.has(draftDirectoryParam)+ ? { agentId: draftAgentParam, projectWorkingDirectoryId: draftDirectoryParam }+ : undefined,+ [draftAgentParam, draftDirectoryParam, directoryIds],+ );+ const draftAgentId = draft?.agentId;+ const restageDraft = useProjectDraftStaging(draft, directoryIds);+ const chatAgentId = useChatStore((s) => s.activeAgentId);+ // Keep the conversation on its agent instead of flashing "not found" while+ // the project list catches up with a topic the first send just created.+ const freshOwnerRef = useRef<{ agentId: string; topicId: string }>(undefined);+ const freshTopicAgentId = freshProjectTopicAgentId({+ listed: !!selectedTopic,+ projectId: detail?.project.id,+ rememberedOwner: freshOwnerRef.current,+ storedTopic,+ topicId,+ });+ useEffect(() => {+ if (freshTopicAgentId && topicId)+ freshOwnerRef.current = { agentId: freshTopicAgentId, topicId };+ }, [freshTopicAgentId, topicId]);+ const isFreshTopic = !!freshTopicAgentId;+ const conversationAgentId = topicId+ ? (selectedTopic?.agentId ?? freshTopicAgentId)+ : draftAgentId;+ useRevalidateWhileUnlisted(isFreshTopic, topicId, topicsRequest.revalidate);+ const topicTitle = storedTopic?.title;++ const agent = useInitAgentConfig(conversationAgentId);+ const topicDetail = useChatStore((s) => s.useFetchTopicDetail)(selectedTopic?.id);+ useMarkProjectTopicRead(detail?.project.id, selectedTopic);++ useLayoutEffect(() => {+ if (!conversationAgentId) return;++ useAgentStore.setState(+ { activeAgentId: conversationAgentId },+ false,+ 'ProjectConversation/syncAgentId',+ );+ useChatStore.setState(+ { activeAgentId: conversationAgentId },+ false,+ 'ProjectConversation/syncAgentId',+ );+ }, [conversationAgentId]);++ const getConversationPath = useCallback(() => getProjectTopicPath(projectSlug!), [projectSlug]);+ const getTopicPath = useCallback(+ (_agentId: string, topicId: string) => getProjectTopicPath(projectSlug!, topicId),+ [projectSlug],+ );+ const stage = projectConversationStage({+ agentConfigLoading: !!agent.isLoading,+ chatAgentId,+ conversationAgentId,+ hasProject: !!detail,+ });++ let fallback: ReactElement | undefined;+ if (topicDetail.error)+ fallback = (+ <AsyncError error={topicDetail.error} variant="page" onRetry={topicDetail.revalidate} />+ );+ else if (agent.error)+ fallback = <AsyncError error={agent.error} variant="page" onRetry={agent.mutate} />;+ else if (topicsRequest.error)+ fallback = (+ <AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />+ );+ else if (!topicId && !draftAgentId) {+ // A draft's directory list may still be loading; wait for it rather than+ // sending the draft away. Other new project conversations start from the+ // project home composer.+ fallback =+ draftAgentParam && !directoriesRequest.hasData ? (+ loading+ ) : (+ <Navigate replace relative="path" to=".." />+ );+ } else if (topicId && topicsRequest.hasData && !selectedTopic && !isFreshTopic)+ fallback = (+ <Center height="100%">+ <Text>{t('topics.notFound')}</Text>+ </Center>+ );+ else if (detailSWR.error && !detail)+ fallback = <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.revalidate} />;+ else if (stage === 'loading') fallback = loading;++ return {+ fallback,+ getConversationPath,+ getTopicPath,+ restageDraft,+ /** `agentPending` keeps the header mounted while only the conversation waits. */+ stage,+ title: topicTitle || selectedTopic?.title || t('sidebar.newConversation'),+ topic: topicId+ ? {+ id: topicId,+ status: selectedTopic?.status,+ title: topicTitle || selectedTopic?.title || t('directories.untitled'),+ }+ : undefined,+ };+};diff --git a/src/features/Projects/List/index.tsx b/src/features/Projects/List/index.tsxindex 3220f10231a..63c7d23c8b1 100644--- a/src/features/Projects/List/index.tsx+++ b/src/features/Projects/List/index.tsx@@ -275,11 +275,12 @@ const ProjectListPage = memo(() => {<SearchBarallowClearplaceholder={t('list.searchPlaceholder')}- style={{ maxWidth: 280 }}+ // Natural width as before on wide screens; only shrinks when the row is tight.+ style={{ flex: '0 1 auto', maxWidth: 280, minWidth: 0 }}value={keyword}onChange={(event) => setKeyword(event.target.value)}/>- <Button icon={PlusIcon} onClick={() => openCreateProjectModal()}>+ <Button icon={PlusIcon} style={{ flex: 'none' }} onClick={() => openCreateProjectModal()}>{t('create.action')}</Button></Flexbox>diff --git a/src/features/Projects/MobileShellTitle.tsx b/src/features/Projects/MobileShellTitle.tsxnew file mode 100644index 00000000000..a595a071131--- /dev/null+++ b/src/features/Projects/MobileShellTitle.tsx@@ -0,0 +1,26 @@+'use client';++import { Text } from '@lobehub/ui';+import { useParams } from 'react-router';++import { useCurrentProjectDetail } from '@/store/project';++/**+ * Mobile shell header title for the project home. Desktop names the project in+ * the sidebar, which mobile hides in a drawer, so the header carries the name.+ * Empty until the project loads, rather than a generic label that then changes.+ */+const ProjectMobileShellTitle = () => {+ const { projectId } = useParams<{ projectId: string }>();+ const name = useCurrentProjectDetail(projectId)?.project.name;++ if (!name) return null;++ return (+ <Text ellipsis weight={500}>+ {name}+ </Text>+ );+};++export default ProjectMobileShellTitle;diff --git a/src/features/Projects/WorkingDirectories/Page.tsx b/src/features/Projects/WorkingDirectories/Page.tsxindex 63e3bd3b6e8..0a0687fb843 100644--- a/src/features/Projects/WorkingDirectories/Page.tsx+++ b/src/features/Projects/WorkingDirectories/Page.tsx@@ -7,6 +7,7 @@ import AsyncError from '@/components/AsyncError';import { RouteLoading } from '@/components/Skeleton/RouteSegment';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';+import { useIsMobile } from '@/hooks/useIsMobile';import { useCurrentProjectDetail, useProjectStore } from '@/store/project';import { ProjectKnowledgeBaseSettings } from '../KnowledgeBases';@@ -33,6 +34,7 @@ export function ProjectDirectoriesPage() {const { error, revalidate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);const canManage = useCanManageProject();const detail = useCurrentProjectDetail(projectId);+ const isMobile = useIsMobile();if (error && !detail) return <AsyncError error={error} variant="page" onRetry={revalidate} />;if (!detail) return <RouteLoading />;@@ -86,7 +88,7 @@ export function ProjectDirectoriesPage() {const activeSection = sections.find((item) => item.key === section) ?? sections[0];return (- <Flexbox flex={1} padding={32} style={{ overflow: 'auto' }}>+ <Flexbox flex={1} padding={isMobile ? 16 : 32} style={{ overflow: 'auto' }}><Flexbox gap={28} style={{ width: '100%', maxWidth: 800, marginInline: 'auto' }}><Text fontSize={24} weight={600}>{t('settings.title')}diff --git a/src/features/ResourceHome/Home/HomeList.tsx b/src/features/ResourceHome/Home/HomeList.tsxindex 6a8bd0d8635..0801dbf42da 100644--- a/src/features/ResourceHome/Home/HomeList.tsx+++ b/src/features/ResourceHome/Home/HomeList.tsx@@ -26,6 +26,9 @@ import { docsFilePath, docsPagePath } from '../paths';/** Title, location, owner, created, updated — the time columns stay fixed-width. */const COLUMNS = 'minmax(0, 3fr) minmax(0, 1.4fr) minmax(0, 1.1fr) 132px 132px';+/** A phone keeps title and updated; five columns would wrap the headers letter by letter. */+const PHONE = '@media (width <= 767px)';+const PHONE_COLUMNS = 'minmax(0, 1fr) 96px';const styles = stylex.create({cell: {@@ -36,7 +39,7 @@ const styles = stylex.create({},header: {display: 'grid',- gridTemplateColumns: COLUMNS,+ gridTemplateColumns: { default: COLUMNS, [PHONE]: PHONE_COLUMNS },gap: '16px',paddingBlock: '8px',paddingInline: '12px',@@ -46,6 +49,10 @@ const styles = stylex.create({fontSize: '12px',color: cssVar.colorTextTertiary,},+ // `contents` keeps the wrapped cell a direct grid item on wider screens.+ desktopOnly: {+ display: { default: 'contents', [PHONE]: 'none' },+ },meta: {fontSize: '13px',color: cssVar.colorTextSecondary,@@ -57,7 +64,7 @@ const styles = stylex.create({row: {cursor: 'pointer',display: 'grid',- gridTemplateColumns: COLUMNS,+ gridTemplateColumns: { default: COLUMNS, [PHONE]: PHONE_COLUMNS },gap: '16px',alignItems: 'center',width: '100%',@@ -189,9 +196,11 @@ const HomeList = memo<HomeListProps>(({ onTabChange, tab }) => {<div><div {...stylex.props(styles.header)}><span>{t('docs.home.columns.title')}</span>- <span>{t('docs.home.columns.location')}</span>- <span>{t('docs.home.columns.owner')}</span>- <span>{t('docs.home.columns.createdAt')}</span>+ <span {...stylex.props(styles.desktopOnly)}>+ <span>{t('docs.home.columns.location')}</span>+ <span>{t('docs.home.columns.owner')}</span>+ <span>{t('docs.home.columns.createdAt')}</span>+ </span><span>{t('docs.home.columns.updatedAt')}</span></div><AsyncBoundary@@ -237,21 +246,23 @@ const HomeList = memo<HomeListProps>(({ onTabChange, tab }) => {{row.name || t('pageList.untitled')}</span></Flexbox>- <Location libraryNames={libraryNames} myId={myId} row={row} />- <Flexbox- horizontal- align={'center'}- gap={6}- {...stylex.props(styles.cell, styles.meta)}- >- {row.owner && (- <>- <Avatar avatar={row.owner.avatar || row.owner.name} size={18} />- <span {...stylex.props(styles.cell)}>{row.owner.name}</span>- </>- )}- </Flexbox>- <span {...stylex.props(styles.meta)}>{formatTime(row.createdAt)}</span>+ <span {...stylex.props(styles.desktopOnly)}>+ <Location libraryNames={libraryNames} myId={myId} row={row} />+ <Flexbox+ horizontal+ align={'center'}+ gap={6}+ {...stylex.props(styles.cell, styles.meta)}+ >+ {row.owner && (+ <>+ <Avatar avatar={row.owner.avatar || row.owner.name} size={18} />+ <span {...stylex.props(styles.cell)}>{row.owner.name}</span>+ </>+ )}+ </Flexbox>+ <span {...stylex.props(styles.meta)}>{formatTime(row.createdAt)}</span>+ </span><span {...stylex.props(styles.meta)}>{formatTime(row.updatedAt)}</span></button>))}diff --git a/src/features/ResourceManager/components/Editor/index.tsx b/src/features/ResourceManager/components/Editor/index.tsxindex 6d47be56326..f5a47c8932d 100644--- a/src/features/ResourceManager/components/Editor/index.tsx+++ b/src/features/ResourceManager/components/Editor/index.tsx@@ -12,6 +12,7 @@ import FileDetailComponent from '@/features/ResourceManager/FileDetail';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { fileManagerSelectors, useFileStore } from '@/store/file';import { downloadFile } from '@/utils/client/downloadFile';+import { isMobileSurface } from '@/utils/mobileSurface';import FileContent from './FileContent';@@ -69,6 +70,9 @@ const FileEditorCanvas = memo<FileEditorProps>(({ onBack }) => {<Flexbox horizontal height={'100%'} style={{ minHeight: 0 }} width={'100%'}><Flexbox flex={1} height={'100%'} style={{ minHeight: 0 }}><NavHeader+ // The page's own back leads to its list; mobile drops the shell's+ // history back so there is one.+ showTogglePanelButton={!isMobileSurface()}left={<Flexboxhorizontaldiff --git a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsxindex a2d771b0dfe..b5e4489e1e2 100644--- a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx+++ b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.tsx@@ -118,7 +118,8 @@ const EmptyPlaceholder = () => {<Text as={'h4'}>{t('FileManager.emptyStatus.title')}</Text><Text type={'secondary'}>{t('FileManager.emptyStatus.or')}</Text></Flexbox>- <Flexbox horizontal gap={12}>+ {/* Wraps so the three 200px cards stack on a phone instead of clipping. */}+ <Flexbox horizontal gap={12} justify={'center'} paddingInline={16} wrap={'wrap'}>{!libraryId && (<FlexboxclassName={styles.card}diff --git a/src/features/ResourceManager/components/Explorer/Header/index.tsx b/src/features/ResourceManager/components/Explorer/Header/index.tsxindex 268f302ea7f..d6af4ffa14d 100644--- a/src/features/ResourceManager/components/Explorer/Header/index.tsx+++ b/src/features/ResourceManager/components/Explorer/Header/index.tsx@@ -11,6 +11,7 @@ import NavHeader from '@/features/NavHeader';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { getExplorerSelectedCount } from '@/features/ResourceManager/store/selectors';import { openWorkspaceDeleteAllModal } from '@/features/WorkspaceDeleteAllModal';+import { useIsMobile } from '@/hooks/useIsMobile';import { usePermission } from '@/hooks/usePermission';import { useFileStore } from '@/store/file';@@ -50,6 +51,7 @@ const Header = memo(() => {s.viewMode,]);const { allowed: canEditResources, reason } = usePermission('edit_own_content');+ const isMobile = useIsMobile();const total = useFileStore((s) => s.total);const selectCount = getExplorerSelectedCount({selectAllState,@@ -163,7 +165,7 @@ const Header = memo(() => {/></Flexbox>) : !libraryId ? (- <Flexbox style={{ marginLeft: 4 }}>+ <Flexbox style={{ marginLeft: 4, minWidth: 0 }}><DriveCategoryTabs /></Flexbox>) : (@@ -189,8 +191,9 @@ const Header = memo(() => {<SortDropdown /><BatchActionsDropdown selectCount={selectCount} onActionClick={onActionClick} /><ViewSwitcher />- <Flexbox style={{ marginLeft: 8 }}>- <AddButton />+ <Flexbox style={{ marginLeft: isMobile ? 4 : 8 }}>+ {/* A phone header has no room for the labelled button. */}+ <AddButton iconOnly={isMobile} /></Flexbox></>}diff --git a/src/features/RightPanel/index.tsx b/src/features/RightPanel/index.tsxindex e2f521a7381..b13dd9253cc 100644--- a/src/features/RightPanel/index.tsx+++ b/src/features/RightPanel/index.tsx@@ -1,10 +1,13 @@-import { DraggablePanel, type DraggablePanelProps } from '@lobehub/ui';+import { DraggablePanel, type DraggablePanelProps, Drawer } from '@lobehub/ui';import { cssVar } from '@lobehub/ui';import { memo, Suspense, useState } from 'react';import SurfaceSkeleton from '@/components/Skeleton/Surface';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { isMobileSurface } from '@/utils/mobileSurface';++import { useMobilePanelExpand } from './useMobilePanelExpand';export interface Size {height?: string | number;@@ -22,6 +25,13 @@ interface RightPanelProps extends Omit<* surface (Page editor, Task layout, etc.) own an independent visibility state.*/expand?: boolean;+ /**+ * `expand` mirrors a selection made on this page (e.g. the picked record), not+ * a saved open/closed preference. Mobile closes a panel that mounts open,+ * since a saved desktop preference would otherwise cover the phone page; a+ * fresh selection must stay open.+ */+ expandFollowsSelection?: boolean;onExpandChange?: (expand: boolean) => void;onSizeChange?: (size?: Size) => void;/**@@ -39,6 +49,7 @@ const RightPanel = memo<RightPanelProps>(children,defaultWidth = 360,expand: expandProp,+ expandFollowsSelection,onExpandChange,onSizeChange,width: widthProp,@@ -54,6 +65,29 @@ const RightPanel = memo<RightPanelProps>(const [internalWidth, setInternalWidth] = useState<string | number>(defaultWidth);const width = widthProp ?? internalWidth;+ const mobile = isMobileSurface();++ useMobilePanelExpand({+ expand: !!expand,+ expandFollowsSelection,+ mobile,+ onExpandChange: handleExpandChange,+ });++ if (mobile)+ return (+ <Drawer+ open={expand}+ placement={'right'}+ styles={{ bodyContent: { padding: 0 } }}+ width={'100%'}+ onClose={() => handleExpandChange(false)}+ >+ <Suspense fallback={<SurfaceSkeleton header={false} variant={'list'} />}>+ {children}+ </Suspense>+ </Drawer>+ );return (<DraggablePaneldiff --git a/src/features/RightPanel/useMobilePanelExpand.test.ts b/src/features/RightPanel/useMobilePanelExpand.test.tsnew file mode 100644index 00000000000..3b7eb63bad8--- /dev/null+++ b/src/features/RightPanel/useMobilePanelExpand.test.ts@@ -0,0 +1,49 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useMobilePanelExpand } from './useMobilePanelExpand';++describe('useMobilePanelExpand', () => {+ it('closes a persisted open panel when a mobile page mounts', () => {+ const onExpandChange = vi.fn();++ renderHook(() => useMobilePanelExpand({ expand: true, mobile: true, onExpandChange }));++ expect(onExpandChange).toHaveBeenCalledWith(false);+ });++ it('keeps a panel that mounts open because the user just selected something', () => {+ const onExpandChange = vi.fn();++ renderHook(() =>+ useMobilePanelExpand({+ expand: true,+ expandFollowsSelection: true,+ mobile: true,+ onExpandChange,+ }),+ );++ expect(onExpandChange).not.toHaveBeenCalled();+ });++ it('leaves the desktop preference alone', () => {+ const onExpandChange = vi.fn();++ renderHook(() => useMobilePanelExpand({ expand: true, mobile: false, onExpandChange }));++ expect(onExpandChange).not.toHaveBeenCalled();+ });++ it('does not fight the user once they open the panel on mobile', () => {+ const onExpandChange = vi.fn();+ const { rerender } = renderHook(+ ({ expand }) => useMobilePanelExpand({ expand, mobile: true, onExpandChange }),+ { initialProps: { expand: false } },+ );++ rerender({ expand: true });++ expect(onExpandChange).not.toHaveBeenCalled();+ });+});diff --git a/src/features/RightPanel/useMobilePanelExpand.ts b/src/features/RightPanel/useMobilePanelExpand.tsnew file mode 100644index 00000000000..0c9878057de--- /dev/null+++ b/src/features/RightPanel/useMobilePanelExpand.ts@@ -0,0 +1,27 @@+import { useEffect } from 'react';++interface MobilePanelExpandParams {+ expand: boolean;+ /** `expand` mirrors a selection made on this page rather than a saved preference. */+ expandFollowsSelection?: boolean;+ mobile: boolean;+ onExpandChange: (expand: boolean) => void;+}++/**+ * A side panel's open state is usually a persisted desktop preference. On a+ * phone the panel covers the whole page, so it starts closed there and opens+ * only on an explicit toggle or selection made on this page. A panel whose open+ * state is that selection stays as it mounted.+ */+export const useMobilePanelExpand = ({+ expand,+ expandFollowsSelection,+ mobile,+ onExpandChange,+}: MobilePanelExpandParams) => {+ useEffect(() => {+ if (mobile && !expandFollowsSelection && expand) onExpandChange(false);+ // Mount only: later `expand` changes are the user's own toggles.+ }, []);+};diff --git a/src/features/Settings/index.tsx b/src/features/Settings/index.tsxindex 024adf92705..ff17b65ce1a 100644--- a/src/features/Settings/index.tsx+++ b/src/features/Settings/index.tsx@@ -4,6 +4,7 @@ import { memo } from 'react';import { useMatches, useParams } from 'react-router';import { SettingsTabs } from '@/store/global/initialState';+import { isMobileSurface } from '@/utils/mobileSurface';import SettingsContent from './features/SettingsContent';import { type LayoutProps } from './Layout/type';@@ -32,9 +33,11 @@ const Layout = memo<LayoutProps>(() => {getSettingsTabFromMatches(matches) ||SettingsTabs.Profile;- return <SettingsContent activeTab={activeTab} mobile={false} />;+ // The mobile settings layout already owns the header and back button; the+ // mobile branch renders the tab body only.+ return <SettingsContent activeTab={activeTab} mobile={isMobileSurface()} />;});-Layout.displayName = 'DesktopSettingsLayout';+Layout.displayName = 'SettingsLayout';export default Layout;diff --git a/src/features/Settings/skill/features/LeftPanel.tsx b/src/features/Settings/skill/features/LeftPanel.tsxindex ab971779048..22566889974 100644--- a/src/features/Settings/skill/features/LeftPanel.tsx+++ b/src/features/Settings/skill/features/LeftPanel.tsx@@ -45,6 +45,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface LeftPanelProps {+ /** Fill the page instead of sitting as a 300px column beside the detail (mobile). */+ fullWidth?: boolean;onDeleteSelected: () => void;onSelect: (identifier: string, type: ToolDetailType) => void;selectedIdentifier?: string;@@ -52,7 +54,7 @@ interface LeftPanelProps {}const LeftPanel = memo<LeftPanelProps>(- ({ onDeleteSelected, onSelect, selectedIdentifier, viewMode }) => {+ ({ fullWidth, onDeleteSelected, onSelect, selectedIdentifier, viewMode }) => {const { t } = useTranslation('setting');const [showAddConnector, setShowAddConnector] = useState(false);@@ -64,7 +66,10 @@ const LeftPanel = memo<LeftPanelProps>(return (<>- <div className={styles.root}>+ <div+ className={styles.root}+ style={fullWidth ? { borderInlineEnd: 'none', width: '100%' } : undefined}+ ><div className={styles.header}><Text strong style={{ fontSize: 14 }}>{isConnectorViewdiff --git a/src/features/Settings/skill/index.tsx b/src/features/Settings/skill/index.tsxindex 964fd47a0c2..54109b0dbc6 100644--- a/src/features/Settings/skill/index.tsx+++ b/src/features/Settings/skill/index.tsx@@ -1,17 +1,25 @@'use client';-import { createStaticStyles } from '@lobehub/ui';+import { ActionIcon, createStaticStyles, Flexbox } from '@lobehub/ui';import isEqual from 'fast-deep-equal';-import { memo, useEffect, useState } from 'react';-import { useSearchParams } from 'react-router';+import { ChevronLeft } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useLocation, useNavigate, useSearchParams } from 'react-router';import NavHeader from '@/features/NavHeader';import { useToolStore } from '@/store/tool';import { agentSkillsSelectors, builtinToolSelectors } from '@/store/tool/selectors';+import { isMobileSurface } from '@/utils/mobileSurface';import LeftPanel from './features/LeftPanel';import SkillDetail, { type ToolDetailType } from './features/SkillDetail';import { type SkillViewMode } from './features/SkillList';+import {+ encodeMobileSelection,+ MOBILE_SELECTION_PARAM,+ parseMobileSelection,+} from './mobileSelection';export interface SelectedTool {identifier: string;@@ -40,10 +48,51 @@ interface ToolSettingsProps {viewMode: SkillViewMode;}+const PUSHED_DETAIL_STATE = 'skillDetailPushed';+export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {- const [searchParams] = useSearchParams();+ const { t } = useTranslation('common');+ const mobile = isMobileSurface();+ const [searchParams, setSearchParams] = useSearchParams();const querySkillIdentifier = searchParams.get('skill');const [selected, setSelected] = useState<SelectedTool | null>(null);+ const mobileSelected = mobile+ ? parseMobileSelection(searchParams.get(MOBILE_SELECTION_PARAM))+ : undefined;++ // Mobile: opening a detail is a history entry, so back returns to the list.+ const openMobileDetail = useCallback(+ (next: SelectedTool, replace = false) =>+ setSearchParams(+ (prev) => {+ const params = new URLSearchParams(prev);+ params.set(MOBILE_SELECTION_PARAM, encodeMobileSelection(next));+ params.delete('skill');+ return params;+ },+ // A pushed detail remembers it, so closing it can step back to the list.+ { replace, state: replace ? undefined : { [PUSHED_DETAIL_STATE]: true } },+ ),+ [setSearchParams],+ );+ const location = useLocation();+ const navigate = useNavigate();+ const closeMobileDetail = () => {+ // Pop the entry this page pushed, so history keeps one list entry; a+ // deep-linked detail has none to pop and is replaced by the list instead.+ if ((location.state as Record<string, unknown> | null)?.[PUSHED_DETAIL_STATE]) {+ navigate(-1);+ return;+ }+ setSearchParams(+ (prev) => {+ const params = new URLSearchParams(prev);+ params.delete(MOBILE_SELECTION_PARAM);+ return params;+ },+ { replace: true },+ );+ };const builtinTools = useToolStore((s) => s.builtinTools, isEqual);const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);@@ -55,6 +104,9 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {);useEffect(() => {+ // Mobile shows one pane at a time and opens on the list, so nothing is+ // pre-selected there.+ if (mobile) return;if (selected) return;if (viewMode === 'skill' && querySkillIdentifier) return;if (viewMode === 'connector') {@@ -70,7 +122,15 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {setSelected({ identifier: firstSkill.identifier, type: 'builtin-skill' });}}- }, [builtinTools, builtinSkills, installedBuiltinIds, querySkillIdentifier, selected, viewMode]);+ }, [+ builtinTools,+ builtinSkills,+ installedBuiltinIds,+ mobile,+ querySkillIdentifier,+ selected,+ viewMode,+ ]);useEffect(() => {if (viewMode !== 'skill' || !querySkillIdentifier) return;@@ -78,13 +138,50 @@ export const ToolSettings = memo<ToolSettingsProps>(({ viewMode }) => {const skill = [...marketAgentSkills, ...userAgentSkills].find((item) => item.identifier === querySkillIdentifier,);- if (skill) setSelected({ identifier: skill.id, type: 'agent-skill' });- }, [marketAgentSkills, querySkillIdentifier, userAgentSkills, viewMode]);+ if (!skill) return;+ // Mobile turns the deep link into the detail entry once (dropping `skill`),+ // so a later store refresh cannot reopen a detail the user closed.+ if (mobile) openMobileDetail({ identifier: skill.id, type: 'agent-skill' }, true);+ else setSelected({ identifier: skill.id, type: 'agent-skill' });+ }, [+ marketAgentSkills,+ mobile,+ openMobileDetail,+ querySkillIdentifier,+ userAgentSkills,+ viewMode,+ ]);const handleSelect = (identifier: string, type: ToolDetailType) => {- setSelected({ identifier, type });+ if (mobile) openMobileDetail({ identifier, type });+ else setSelected({ identifier, type });};+ // Mobile: the settings layout owns the header; list and detail take turns+ // full-width instead of a 300px list squeezing the detail.+ if (mobile)+ return mobileSelected ? (+ <Flexbox className={styles.detail}>+ <Flexbox horizontal align={'center'} paddingBlock={4} paddingInline={8}>+ <ActionIcon icon={ChevronLeft} title={t('back')} onClick={closeMobileDetail} />+ </Flexbox>+ <SkillDetail+ identifier={mobileSelected.identifier}+ type={mobileSelected.type}+ onDelete={closeMobileDetail}+ />+ </Flexbox>+ ) : (+ <div className={styles.root}>+ <LeftPanel+ fullWidth+ viewMode={viewMode}+ onDeleteSelected={closeMobileDetail}+ onSelect={handleSelect}+ />+ </div>+ );+return (<><NavHeader />diff --git a/src/features/Settings/skill/mobileSelection.test.ts b/src/features/Settings/skill/mobileSelection.test.tsnew file mode 100644index 00000000000..2109336008d--- /dev/null+++ b/src/features/Settings/skill/mobileSelection.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { encodeMobileSelection, parseMobileSelection } from './mobileSelection';++describe('mobile skill selection param', () => {+ it('round-trips a selection, including identifiers that contain a colon', () => {+ const selection = { identifier: 'lobehub:web-search', type: 'builtin' as const };++ expect(parseMobileSelection(encodeMobileSelection(selection))).toEqual(selection);+ });++ it('shows the list for a missing or malformed value', () => {+ expect(parseMobileSelection(null)).toBeUndefined();+ expect(parseMobileSelection('builtin')).toBeUndefined();+ expect(parseMobileSelection('unknown:web-search')).toBeUndefined();+ expect(parseMobileSelection('builtin:')).toBeUndefined();+ });+});diff --git a/src/features/Settings/skill/mobileSelection.ts b/src/features/Settings/skill/mobileSelection.tsnew file mode 100644index 00000000000..1b665cb70f8--- /dev/null+++ b/src/features/Settings/skill/mobileSelection.ts@@ -0,0 +1,38 @@+import type { ToolDetailType } from './features/SkillDetail';++/**+ * Mobile shows the skill list and one skill's detail as separate screens. The+ * open detail lives in this search param so the phone's back gesture returns to+ * the list instead of leaving the settings page.+ */+export const MOBILE_SELECTION_PARAM = 'open';++const DETAIL_TYPES = new Set<ToolDetailType>([+ 'agent-connector',+ 'agent-skill',+ 'builtin',+ 'builtin-skill',+ 'lobehub-connector',+ 'mcp-connector',+ 'plugin',+]);++export interface MobileSelection {+ identifier: string;+ type: ToolDetailType;+}++export const encodeMobileSelection = ({ identifier, type }: MobileSelection) =>+ `${type}:${identifier}`;++/** Undefined for a missing or malformed value, which shows the list. */+export const parseMobileSelection = (value: string | null): MobileSelection | undefined => {+ const separator = value?.indexOf(':') ?? -1;+ if (!value || separator <= 0) return undefined;++ const type = value.slice(0, separator) as ToolDetailType;+ const identifier = value.slice(separator + 1);+ if (!DETAIL_TYPES.has(type) || !identifier) return undefined;++ return { identifier, type };+};diff --git a/src/features/WorkspaceSetting/MobileCategory.tsx b/src/features/WorkspaceSetting/MobileCategory.tsxnew file mode 100644index 00000000000..799474a19bb--- /dev/null+++ b/src/features/WorkspaceSetting/MobileCategory.tsx@@ -0,0 +1,65 @@+'use client';++import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { UserCircle } from 'lucide-react';+import { Fragment, memo } from 'react';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import Cell from '@/components/Cell';+import Divider from '@/components/Cell/Divider';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { WorkspaceSettingsTabs } from '@/types/workspaceSettings';++import { useWorkspaceSettingCategory } from './hooks/useCategory';+import { getWorkspaceSettingsTabUrl } from './hooks/useSettingsSearchScope';++const styles = stylex.create({+ groupTitle: {+ color: cssVar.colorTextSecondary,+ fontSize: 12,+ fontWeight: 500,+ paddingBlockStart: '16px',+ paddingBlockEnd: '4px',+ paddingInline: 16,+ },+});++/**+ * Mobile `/:workspaceSlug/settings`: the desktop settings sidebar as a list.+ * It reads the same category hook, so the permission and lab gates that hide a+ * tab on desktop hide it here too.+ */+const MobileWorkspaceSettingCategory = memo(() => {+ const groups = useWorkspaceSettingCategory();+ const navigate = useWorkspaceAwareNavigate();+ const slug = useActiveWorkspaceSlug();++ // Only mounted under `/:workspaceSlug/settings`; same guard as the desktop sidebar.+ if (!slug) return null;++ return (+ <>+ {groups.map((group, groupIndex) => (+ <Fragment key={group.key}>+ {groupIndex > 0 && <Divider />}+ <div {...stylex.props(styles.groupTitle)}>{group.title}</div>+ {group.items.map((item) => (+ <Cell+ // The profile row carries the user's avatar (or nothing); cells take icon components.+ icon={item.key === WorkspaceSettingsTabs.Profile ? UserCircle : item.icon}+ key={item.key}+ label={item.label}+ // Same URL builder as the desktop sidebar and settings search.+ onClick={() => navigate(getWorkspaceSettingsTabUrl(slug, item.key))}+ />+ ))}+ </Fragment>+ ))}+ </>+ );+});++MobileWorkspaceSettingCategory.displayName = 'MobileWorkspaceSettingCategory';++export default MobileWorkspaceSettingCategory;diff --git a/src/hooks/useMobileNavigation.ts b/src/hooks/useMobileNavigation.tsindex b71faeba85e..df9f789179d 100644--- a/src/hooks/useMobileNavigation.ts+++ b/src/hooks/useMobileNavigation.ts@@ -10,6 +10,7 @@ const MOBILE_NAV_ROUTES = new Set(['/community/plugin','/community/model','/community/provider',+ '/community/skill','/me',]);diff --git a/src/routes/(main)/community/(detail)/group_agent/index.tsx b/src/routes/(main)/community/(detail)/group_agent/index.tsxindex 34c55e7b860..fb3a3831769 100644--- a/src/routes/(main)/community/(detail)/group_agent/index.tsx+++ b/src/routes/(main)/community/(detail)/group_agent/index.tsx@@ -109,4 +109,8 @@ const GroupAgentDetailPage = memo<GroupAgentDetailPageProps>(({ mobile }) => {);});+export const MobileGroupAgentDetailPage = (_props: { mobile?: boolean }) => {+ return <GroupAgentDetailPage mobile={true} />;+};+export default GroupAgentDetailPage;diff --git a/src/routes/(main)/community/features/useNav.tsx b/src/routes/(main)/community/features/useNav.tsxindex b5d9af0ed39..9f055f3ffe4 100644--- a/src/routes/(main)/community/features/useNav.tsx+++ b/src/routes/(main)/community/features/useNav.tsx@@ -1,5 +1,6 @@import { MCP } from '@lobehub/icons';import { Icon } from '@lobehub/ui';+import { SkillsIcon } from '@lobehub/ui/icons';import { Bot, Brain, BrainCircuit, House } from 'lucide-react';import { type ReactNode } from 'react';import { useMemo } from 'react';@@ -38,6 +39,11 @@ export const useNav = () => {key: DiscoverTab.Assistants,label: <div style={{ color: 'inherit', display: 'inline' }}>{t('tab.assistant')}</div>,},+ {+ icon: <Icon icon={SkillsIcon} size={ICON_SIZE} />,+ key: DiscoverTab.Skills,+ label: <div style={{ color: 'inherit', display: 'inline' }}>{t('tab.skill')}</div>,+ },{icon: <MCP className={'anticon'} size={ICON_SIZE} />,key: DiscoverTab.Mcp,diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/index.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/index.tsxindex 5376ee36829..5b4e8a945be 100644--- a/src/routes/(main)/group/profile/features/AgentBuilder/index.tsx+++ b/src/routes/(main)/group/profile/features/AgentBuilder/index.tsx@@ -1,8 +1,8 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import { cssVar, DraggablePanel } from '@lobehub/ui';import { memo } from 'react';import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';+import RightPanel from '@/features/RightPanel';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';@@ -26,19 +26,15 @@ const AgentBuilder = memo(() => {useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.groupAgentBuilder);return (- <DraggablePanel- backgroundColor={cssVar.colorBgContainer}+ // RightPanel: the same draggable side panel on desktop, a full-screen+ // drawer on mobile instead of a fixed-width column over the profile.+ <RightPanelexpand={chatPanelExpanded}- expandable={false}maxWidth={600}minWidth={360}- placement="right"- size={{- height: '100%',- width,- }}+ width={width}onExpandChange={setChatPanelExpanded}- onSizeChange={(_, size) => {+ onSizeChange={(size) => {if (size?.width) {const w = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;if (!!w) updateSystemStatus({ groupAgentBuilderPanelWidth: w });@@ -52,7 +48,7 @@ const AgentBuilder = memo(() => {) : (<ConversationSegmentSkeleton />)}- </DraggablePanel>+ </RightPanel>);});diff --git a/src/routes/(main)/group/profile/features/Header/index.tsx b/src/routes/(main)/group/profile/features/Header/index.tsxindex db911d2c85e..d60a43adce8 100644--- a/src/routes/(main)/group/profile/features/Header/index.tsx+++ b/src/routes/(main)/group/profile/features/Header/index.tsx@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';import AddGroupMemberModal from '@/features/AddAgentMemberModal';+import MobileHeaderNav from '@/features/NavHeader/MobileHeaderNav';import ToggleLeftPanelButton from '@/features/NavPanel/ToggleLeftPanelButton';import { usePermission } from '@/hooks/usePermission';import { parseAsString, useQueryState } from '@/hooks/useQueryParam';@@ -15,6 +16,7 @@ import { useAgentGroupStore } from '@/store/agentGroup';import { agentGroupSelectors } from '@/store/agentGroup/selectors';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { isMobileSurface } from '@/utils/mobileSurface';import AgentBuilderToggle from './AgentBuilderToggle';import { type ChromeTabItem } from './ChromeTabs';@@ -129,7 +131,7 @@ const Header = memo(() => {return (<><Flexbox horizontal align="center" className={styles.header} gap={4} justify="space-between">- {!showLeftPanel && <ToggleLeftPanelButton />}+ {isMobileSurface() ? <MobileHeaderNav /> : !showLeftPanel && <ToggleLeftPanelButton />}<div className={styles.tabsWrapper}><ChromeTabsactiveId={selectedTabId}diff --git a/src/routes/(mobile)/[workspaceSlug]/settings/index.tsx b/src/routes/(mobile)/[workspaceSlug]/settings/index.tsxnew file mode 100644index 00000000000..bd6dbc776ed--- /dev/null+++ b/src/routes/(mobile)/[workspaceSlug]/settings/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/WorkspaceSetting/MobileCategory';diff --git a/src/routes/(mobile)/_layout/index.tsx b/src/routes/(mobile)/_layout/index.tsxindex c23725e7ba5..55d51f4b5ac 100644--- a/src/routes/(mobile)/_layout/index.tsx+++ b/src/routes/(mobile)/_layout/index.tsx@@ -8,6 +8,7 @@ import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';import Loading from '@/components/Loading/BrandTextLoading';import { RouteMetaBridge } from '@/features/RouteMeta';import { useMobileNavigation } from '@/hooks/useMobileNavigation';+import CmdkLazy from '@/layout/GlobalProvider/CmdkLazy';import dynamic from '@/libs/next/dynamic';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';@@ -26,6 +27,8 @@ const MobileMainLayout: FC = () => {<Outlet />{showNav && <NavBar />}</Suspense>+ {/* Global search: the sidebars mobile opens as drawers trigger it. */}+ <CmdkLazy /></WorkspaceContextSlot>);};diff --git a/src/routes/(mobile)/_page-layout/index.tsx b/src/routes/(mobile)/_page-layout/index.tsxnew file mode 100644index 00000000000..abc0e3efb5a--- /dev/null+++ b/src/routes/(mobile)/_page-layout/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MobileShell/PageLayout';diff --git a/src/routes/(mobile)/agent/_layout/index.tsx b/src/routes/(mobile)/agent/_layout/index.tsxnew file mode 100644index 00000000000..050c2c8a44c--- /dev/null+++ b/src/routes/(mobile)/agent/_layout/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MobileShell/AgentScopeLayout';diff --git a/src/routes/(mobile)/agent/_pages/index.tsx b/src/routes/(mobile)/agent/_pages/index.tsxnew file mode 100644index 00000000000..859d73ba5e8--- /dev/null+++ b/src/routes/(mobile)/agent/_pages/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MobileShell/AgentPagesLayout';diff --git a/src/routes/(mobile)/chat/_layout/index.tsx b/src/routes/(mobile)/chat/_layout/index.tsxindex 0429a0a7453..e5b82f83f72 100644--- a/src/routes/(mobile)/chat/_layout/index.tsx+++ b/src/routes/(mobile)/chat/_layout/index.tsx@@ -5,27 +5,20 @@ import { Outlet } from 'react-router';import MobileContentLayout from '@/components/server/MobileNavLayout';import { AgentNotFoundGuard } from '@/features/AgentNotFound';-import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';-import AgentIdSync from '@/routes/(main)/agent/_layout/AgentIdSync';import ChatHeader from '@/routes/(mobile)/chat/features/ChatHeader';import { styles } from './style';-const Layout: FC = () => {- useInitAgentConfig();-- return (- <>- <MobileContentLayout className={styles.mainContainer} header={<ChatHeader />}>- {/* Same 404 fallback as the desktop agent layout: only the content- area collapses when the routed agent is gone or turned private. */}- <AgentNotFoundGuard>- <Outlet />- </AgentNotFoundGuard>- </MobileContentLayout>- <AgentIdSync />- </>- );-};+// Agent init and id sync live one level up in the agent scope layout+// (`(mobile)/agent/_layout`), which the chat shares with the sub-pages.+const Layout: FC = () => (+ <MobileContentLayout className={styles.mainContainer} header={<ChatHeader />}>+ {/* Same 404 fallback as the desktop agent layout: only the content area+ collapses when the routed agent is gone or turned private. */}+ <AgentNotFoundGuard>+ <Outlet />+ </AgentNotFoundGuard>+ </MobileContentLayout>+);export default Layout;diff --git a/src/routes/(mobile)/chat/settings/index.tsx b/src/routes/(mobile)/chat/settings/index.tsxindex c9c030aa918..7e01f0854cf 100644--- a/src/routes/(mobile)/chat/settings/index.tsx+++ b/src/routes/(mobile)/chat/settings/index.tsx@@ -2,6 +2,7 @@import { cssVar, Tabs } from '@lobehub/ui';import { memo, useState } from 'react';+import { useNavigate } from 'react-router';import MobileContentLayout from '@/components/server/MobileNavLayout';import { useCategory } from '@/features/AgentSetting/AgentCategory/useCategory';@@ -15,8 +16,15 @@ import { agentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';export default memo(() => {- const [tab, setTab] = useState(ChatSettingsTabs.Prompt);const cateItems = useCategory();+ const navigate = useNavigate();+ // The agent profile (identity, model, instructions) is edited on the profile+ // page; the settings sheet only renders the tabs below it.+ const [tab, setTab] = useState(+ () =>+ (cateItems?.find((item) => item?.key !== ChatSettingsTabs.Prompt)?.key ??+ ChatSettingsTabs.Opening) as ChatSettingsTabs,+ );const id = useAgentStore((s) => s.activeAgentId);const { allowed: canEdit } = usePermission('edit_own_content');const { canEditResource, isAccessResolved } = useResourceAccess('agent', id);@@ -38,7 +46,13 @@ export default memo(() => {style={{borderBottom: `1px solid ${cssVar.colorBorderSecondary}`,}}- onChange={(value) => setTab(value as ChatSettingsTabs)}+ onChange={(value) => {+ if (value === ChatSettingsTabs.Prompt) {+ navigate('../profile', { relative: 'path' });+ return;+ }+ setTab(value as ChatSettingsTabs);+ }}/><AgentSettingsconfig={config}diff --git a/src/routes/(mobile)/group/_pages/index.tsx b/src/routes/(mobile)/group/_pages/index.tsxnew file mode 100644index 00000000000..e10548cfb89--- /dev/null+++ b/src/routes/(mobile)/group/_pages/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MobileShell/GroupPagesLayout';diff --git a/src/routes/(mobile)/group/_scope/index.tsx b/src/routes/(mobile)/group/_scope/index.tsxnew file mode 100644index 00000000000..fbe3421d6b8--- /dev/null+++ b/src/routes/(mobile)/group/_scope/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MobileShell/GroupScopeLayout';diff --git a/src/routes/(mobile)/page/_layout/index.tsx b/src/routes/(mobile)/page/_layout/index.tsxnew file mode 100644index 00000000000..3fac75057d5--- /dev/null+++ b/src/routes/(mobile)/page/_layout/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/Pages/MobilePageLayout';diff --git a/src/routes/(mobile)/page/index.tsx b/src/routes/(mobile)/page/index.tsxnew file mode 100644index 00000000000..1a89502fae4--- /dev/null+++ b/src/routes/(mobile)/page/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/Pages/MobilePageList';diff --git a/src/routes/(mobile)/project/[projectId]/topic/index.tsx b/src/routes/(mobile)/project/[projectId]/topic/index.tsxnew file mode 100644index 00000000000..335d8b14b43--- /dev/null+++ b/src/routes/(mobile)/project/[projectId]/topic/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/Projects/Conversation/Mobile';diff --git a/src/routes/(mobile)/resource/_layout/index.tsx b/src/routes/(mobile)/resource/_layout/index.tsxnew file mode 100644index 00000000000..142618920f4--- /dev/null+++ b/src/routes/(mobile)/resource/_layout/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/MobileShell/ResourceLayout';diff --git a/src/routes/(mobile)/settings/_layout/Header.test.tsx b/src/routes/(mobile)/settings/_layout/Header.test.tsxindex 076b859597b..fd1c580ec2b 100644--- a/src/routes/(mobile)/settings/_layout/Header.test.tsx+++ b/src/routes/(mobile)/settings/_layout/Header.test.tsx@@ -1,6 +1,6 @@// @vitest-environment happy-domimport { fireEvent, render, screen, within } from '@testing-library/react';-import { MemoryRouter } from 'react-router';+import { MemoryRouter, Route, Routes } from 'react-router';import { beforeEach, describe, expect, it, vi } from 'vitest';import Header from './Header';@@ -38,6 +38,9 @@ describe('mobile settings Header', () => {['devices', 'setting:tab.devices'],['service-model', 'setting:tab.serviceModel'],['chat-preference', 'setting:tab.chatPreference'],+ // No explicit entry: the kebab-case slug maps onto the camelCase key.+ ['subscription-accounts', 'setting:tab.subscriptionAccounts'],+ ['oauth-apps', 'auth:tab.oauthApps'],])('resolves the workspace %s title', (tab, title) => {renderHeader(tab);@@ -67,4 +70,54 @@ describe('mobile settings Header', () => {// user lands on the workspace provider list instead of personal settings.expect(navigateMock).toHaveBeenCalledWith('/settings/provider');});++ it.each([+ ['statistics', 'auth:tab.stats'],+ ['credential', 'setting:tab.creds'],+ ['skill', 'setting:workspaceSetting.tab.skill'],+ ['connector', 'setting:workspaceSetting.tab.connector'],+ ])('titles the workspace %s tab mobile now mounts', (tab, title) => {+ renderHeader(tab);++ expect(within(screen.getByRole('banner')).getByText(title)).toBeInTheDocument();+ });++ it('titles a personal tab served by a static route (no `:tab` param)', () => {+ render(+ <MemoryRouter initialEntries={['/settings/memory']}>+ <Routes>+ <Route element={<Header />} path={'/settings/memory'} />+ </Routes>+ </MemoryRouter>,+ );++ expect(within(screen.getByRole('banner')).getByText('setting:tab.memory')).toBeInTheDocument();+ });+});++describe('mobile settings Header back navigation inside a workspace', () => {+ const renderWorkspaceHeader = (pathname: string) =>+ render(+ <MemoryRouter initialEntries={[pathname]}>+ <Routes>+ <Route element={<Header />} path={'/:workspaceSlug/settings/*'} />+ </Routes>+ </MemoryRouter>,+ );++ it('goes from a workspace tab back to the workspace settings menu', () => {+ renderWorkspaceHeader('/acme/settings/members');++ fireEvent.click(within(screen.getByRole('banner')).getByRole('button'));++ expect(navigateMock).toHaveBeenCalledWith('/settings');+ });++ it('goes from the workspace settings menu back to the workspace', () => {+ renderWorkspaceHeader('/acme/settings');++ fireEvent.click(within(screen.getByRole('banner')).getByRole('button'));++ expect(navigateMock).toHaveBeenCalledWith('/');+ });});diff --git a/src/routes/(mobile)/settings/_layout/Header.tsx b/src/routes/(mobile)/settings/_layout/Header.tsxindex 204df9f38a8..01f2fea74dc 100644--- a/src/routes/(mobile)/settings/_layout/Header.tsx+++ b/src/routes/(mobile)/settings/_layout/Header.tsx@@ -30,19 +30,33 @@ const TAB_TITLE_KEY: Partial<Record<SettingsTabs, string>> = {};const WORKSPACE_TAB_TITLE_KEY: Record<string, string> = {+ 'audit-log': 'setting:workspaceSetting.tab.auditLog','budget': 'subscription:tab.budget','chat-preference': 'setting:tab.chatPreference',+ 'connector': 'setting:workspaceSetting.tab.connector',+ 'credential': 'setting:tab.creds','general': 'setting:workspaceSetting.tab.general',+ 'labels': 'setting:workspaceSetting.tab.labels','members': 'setting:workspaceSetting.tab.members',+ 'oauth-apps': 'auth:tab.oauthApps',+ 'skill': 'setting:workspaceSetting.tab.skill',+ 'statistics': 'auth:tab.stats',+ 'teams': 'setting:workspaceSetting.tab.teams',};+/** URL slugs are kebab-case (`subscription-accounts`); `setting:tab.*` keys are camelCase. */+const camelCaseSlug = (slug: string) =>+ slug.replaceAll(/-([a-z])/g, (_, char) => char.toUpperCase());+const Header = memo(() => {const { t } = useTranslation(['setting', 'auth', 'labs', 'subscription']);const showMobileWorkspace = useShowMobileWorkspace();const navigate = useWorkspaceAwareNavigate();- const params = useParams<{ providerId?: string; tab?: string }>();+ const params = useParams<{ providerId?: string; tab?: string; workspaceSlug?: string }>();const [searchParams] = useSearchParams();const workspaceSettingsMatch = useMatch('/:workspaceSlug/settings/:workspaceTab/*');+ // Known tabs are static routes (no `:tab` param), so read the tab off the URL.+ const personalSettingsMatch = useMatch('/settings/:tab/*');const isAgentActive = useAgentStore((s) => !!s.activeAgentId);// Personal provider details carry the id in the path; the workspace provider@@ -61,15 +75,22 @@ const Header = memo(() => {// Query-selected provider (workspace form): back to the workspace// provider list instead of escaping to personal settings.navigate('/settings/provider');+ } else if (params.workspaceSlug) {+ // Workspace tabs go back to the workspace settings menu; the menu goes+ // back to the workspace. Workspace-aware paths keep the slug.+ navigate(workspaceSettingsMatch ? '/settings' : '/');} else {navigate('/me/settings', { escape: true });}};const workspaceTab = workspaceSettingsMatch?.params.workspaceTab;- const tab = (params.tab ?? workspaceTab) as SettingsTabs | undefined;+ const tab = (params.tab ?? personalSettingsMatch?.params.tab ?? workspaceTab) as+ SettingsTabs | undefined;const tabTitleKey = tab- ? (WORKSPACE_TAB_TITLE_KEY[workspaceTab ?? ''] ?? TAB_TITLE_KEY[tab] ?? `setting:tab.${tab}`)+ ? (WORKSPACE_TAB_TITLE_KEY[workspaceTab ?? ''] ??+ TAB_TITLE_KEY[tab] ??+ `setting:tab.${camelCaseSlug(tab)}`): 'setting:tab.all';// i18next's strict key union rejects dynamic strings. `Parameters<typeof t>[0]` would push TS// onto the wrong overload and infer the return as `unknown`, so we fall back to `as any`.diff --git a/src/spa/router/agentPageRoutes.tsx b/src/spa/router/agentPageRoutes.tsxnew file mode 100644index 00000000000..59144b6935b--- /dev/null+++ b/src/spa/router/agentPageRoutes.tsx@@ -0,0 +1,215 @@+import type { RouteObject } from 'react-router';++import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';+import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/routeMeta';+import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';+import {+ agentChannelDetailRouteMeta,+ agentChannelRouteMeta,+ agentPermissionRouteMeta,+ agentProfileRouteMeta,+ agentSelfLearningRouteMeta,+ agentShareRouteMeta,+ agentStatisticsRouteMeta,+ topicsRouteMeta,+} from '@/routes/(main)/agent/features/routeMeta';+import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';+import { channelDataLoader } from '@/spa/router/channelDataLoader';+import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';+import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';+import { dynamicElement, dynamicLayout, redirectElement } from '@/utils/router';++/**+ * The full-page agent surfaces under `/agent/:aid` beside the chat: docs,+ * goals, profile, channels, topics, statistics, share, self-evolving,+ * permission and tasks. Mounted by the desktop router under the agent layout+ * and reused by the mobile router (`mobileAgentRoutes.tsx`).+ */+export const agentPageChildren: RouteObject[] = [+ {+ children: [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/docs'),+ 'Desktop > Chat > DocumentsIndex',+ ),+ handle: { meta: routeMeta({ Skeleton: NoRouteSkeleton }) },+ index: true,+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/docs/[docId]'),+ 'Desktop > Chat > Document',+ ),+ handle: { meta: agentDocumentRouteMeta },+ path: ':docId',+ },+ ],+ element: dynamicLayout(+ () => import('@/routes/(main)/agent/docs/_layout'),+ 'Desktop > Chat > DocumentLayout',+ ),+ // Seed the persisted document list before the docs sidebar paints.+ loader: agentDocumentListLoader,+ path: 'docs',+ },+ {+ element: dynamicElement(() => import('@/routes/(main)/agent/goals'), 'Desktop > Chat > Goals'),+ handle: { meta: goalsRouteMeta },+ path: 'goals',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/goal/[goalId]'),+ 'Desktop > Chat > Goal Detail',+ ),+ handle: { meta: goalDetailRouteMeta },+ path: 'goal/:goalId',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/profile'),+ 'Desktop > Chat > Profile',+ ),+ handle: { meta: agentProfileRouteMeta },+ path: 'profile',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/channel'),+ 'Desktop > Chat > Channel',+ ),+ handle: { meta: agentChannelRouteMeta },+ loader: channelDataLoader,+ path: 'channel',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/channel/[platform]'),+ 'Desktop > Chat > Channel Platform',+ ),+ handle: { meta: agentChannelDetailRouteMeta },+ loader: channelDataLoader,+ path: 'channel/:platform',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/topics'),+ 'Desktop > Chat > Topics',+ ),+ handle: { meta: topicsRouteMeta },+ path: 'topics',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/statistics'),+ 'Desktop > Chat > Statistics',+ ),+ handle: { meta: agentStatisticsRouteMeta },+ path: 'statistics',+ },+ {+ element: dynamicElement(() => import('@/routes/(main)/agent/share'), 'Desktop > Chat > Share'),+ handle: { meta: agentShareRouteMeta },+ path: 'share',+ },+ // Legacy `/agent/:aid/stats` URLs — kept for deep-links.+ {+ element: redirectElement('../statistics'),+ path: 'stats',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning'),+ 'Desktop > Chat > Self Learning',+ ),+ handle: { meta: agentSelfLearningRouteMeta },+ path: 'self-evolving',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning/new'),+ 'Desktop > Chat > Self Learning > Create',+ ),+ handle: { meta: agentSelfLearningRouteMeta },+ path: 'self-evolving/new',+ },+ // 单个方向的成长画像。做成路由而不是页内状态,深链才打得开。+ {+ children: [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning/[domainId]'),+ 'Desktop > Chat > Self Learning > Domain',+ ),+ handle: { meta: agentSelfLearningRouteMeta },+ index: true,+ },+ // 一个方向的全部经验(不折叠的完整清单)和单条经验详情。+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning/[domainId]/experience'),+ 'Desktop > Chat > Self Learning > Domain > Experience',+ ),+ handle: { meta: agentSelfLearningRouteMeta },+ path: 'experience',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]'),+ 'Desktop > Chat > Self Learning > Domain > Lesson',+ ),+ handle: { meta: agentSelfLearningRouteMeta },+ path: 'experience/:lessonId',+ },+ // Legacy `/rules` deep-links — kept so old links keep opening.+ {+ element: redirectElement('../experience'),+ path: 'rules',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]'),+ 'Desktop > Chat > Self Learning > Domain > Legacy Rule',+ ),+ handle: { meta: routeMeta({ Skeleton: NoRouteSkeleton }) },+ path: 'rules/:lessonId',+ },+ ],+ path: 'self-evolving/:domainId',+ },+ // Legacy `/self-learning` deep-links keep their remaining path when redirected.+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/self-learning/legacy'),+ 'Desktop > Chat > Legacy Self Learning Redirect',+ ),+ handle: { meta: routeMeta({ Skeleton: NoRouteSkeleton }) },+ path: 'self-learning/*',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/permission'),+ 'Desktop > Chat > Permission',+ ),+ handle: { meta: agentPermissionRouteMeta },+ path: 'permission',+ },+ {+ element: dynamicElement(() => import('@/routes/(main)/agent/tasks'), 'Desktop > Chat > Tasks'),+ handle: { meta: tasksRouteMeta },+ loader: scheduledTaskListLoader,+ path: 'tasks',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/task/[taskId]'),+ 'Desktop > Chat > Task Detail',+ ),+ handle: { meta: taskRouteMeta },+ // `:slug?` is the readable title tail (Linear-style). It is never+ // resolved against — `:taskId` alone identifies the task — so the+ // optional segment keeps every pre-slug link working.+ path: 'task/:taskId/:slug?',+ },+];diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 2427e1a945d..4af668f3259 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -1,15 +1,6 @@'use client';-import {- BrainCircuit,- Download,- HomeIcon,- Image,- Scale,- Settings,- ShapesIcon,- Video,-} from 'lucide-react';+import { Download, HomeIcon, Image, Settings, ShapesIcon, Video } from 'lucide-react';import { createElement, type ReactElement } from 'react';import type { RouteObject } from 'react-router';@@ -25,14 +16,10 @@ import ConversationLayoutSkeleton from '@/components/Skeleton/Conversation/Layouimport ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';import { delayed } from '@/components/Skeleton/Delayed';import GenerationSkeleton from '@/components/Skeleton/Generation';-import MemorySkeleton from '@/components/Skeleton/Memory';import ProviderSettingsSkeleton, {ProviderDetailSkeleton,} from '@/components/Skeleton/Settings/Provider';import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';-import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';-import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/routeMeta';-import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/routeMeta';import { pageRouteMeta } from '@/features/Pages/routeMeta';@@ -41,17 +28,7 @@ import ResourceCategorySkeleton from '@/features/ResourceHome/Skeleton';import { createSettingsRouteMeta, settingsRouteMeta } from '@/features/Settings/features/routeMeta';import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';-import {- agentChannelDetailRouteMeta,- agentChannelRouteMeta,- agentChatDesktopRouteMeta,- agentPermissionRouteMeta,- agentProfileRouteMeta,- agentSelfLearningRouteMeta,- agentShareRouteMeta,- agentStatisticsRouteMeta,- topicsRouteMeta,-} from '@/routes/(main)/agent/features/routeMeta';+import { agentChatDesktopRouteMeta } from '@/routes/(main)/agent/features/routeMeta';import {groupPermissionRouteMeta,groupProfileRouteMeta,@@ -59,19 +36,15 @@ import {} from '@/routes/(main)/group/features/routeMeta';import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';-import { activityListLoader } from '@/spa/router/activityListLoader';import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';-import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';-import { channelDataLoader } from '@/spa/router/channelDataLoader';-import { identitiesListLoader } from '@/spa/router/identitiesListLoader';+import { agentPageChildren } from '@/spa/router/agentPageRoutes';+import { memoryChildren } from '@/spa/router/memoryRoutes';import { onboardingRoute } from '@/spa/router/onboardingRoute';import { pageListLoader } from '@/spa/router/pageListLoader';-import { preferenceListLoader } from '@/spa/router/preferenceListLoader';import { projectWorkspaceRoute } from '@/spa/router/projectWorkspaceRoutes';import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';import { resourceRoute } from '@/spa/router/resourceRoutes';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';-import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';import { taskWorkspaceChildren } from '@/spa/router/taskWorkspaceRoutes';import { withSegmentFallback } from '@/spa/router/withSegmentFallback';import { workspaceSettingsContentRoute } from '@/spa/router/workspaceSettingsRoutes';@@ -141,202 +114,7 @@ export const sharedMainAreaChildren: RouteObject[] = [{ fallback: delayed(<AgentConversationLayoutSkeleton />), preloadId: 'agent' },),},- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/agent/docs'),- 'Desktop > Chat > DocumentsIndex',- ),- handle: { meta: routeMeta({ Skeleton: NoRouteSkeleton }) },- index: true,- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/docs/[docId]'),- 'Desktop > Chat > Document',- ),- handle: { meta: agentDocumentRouteMeta },- path: ':docId',- },- ],- element: dynamicLayout(- () => import('@/routes/(main)/agent/docs/_layout'),- 'Desktop > Chat > DocumentLayout',- ),- // Seed the persisted document list before the docs sidebar paints.- loader: agentDocumentListLoader,- path: 'docs',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/goals'),- 'Desktop > Chat > Goals',- ),- handle: { meta: goalsRouteMeta },- path: 'goals',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/goal/[goalId]'),- 'Desktop > Chat > Goal Detail',- ),- handle: { meta: goalDetailRouteMeta },- path: 'goal/:goalId',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/profile'),- 'Desktop > Chat > Profile',- ),- handle: { meta: agentProfileRouteMeta },- path: 'profile',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/channel'),- 'Desktop > Chat > Channel',- ),- handle: { meta: agentChannelRouteMeta },- loader: channelDataLoader,- path: 'channel',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/channel/[platform]'),- 'Desktop > Chat > Channel Platform',- ),- handle: { meta: agentChannelDetailRouteMeta },- loader: channelDataLoader,- path: 'channel/:platform',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/topics'),- 'Desktop > Chat > Topics',- ),- handle: { meta: topicsRouteMeta },- path: 'topics',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/statistics'),- 'Desktop > Chat > Statistics',- ),- handle: { meta: agentStatisticsRouteMeta },- path: 'statistics',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/share'),- 'Desktop > Chat > Share',- ),- handle: { meta: agentShareRouteMeta },- path: 'share',- },- // Legacy `/agent/:aid/stats` URLs — kept for deep-links.- {- element: redirectElement('../statistics'),- path: 'stats',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/self-learning'),- 'Desktop > Chat > Self Learning',- ),- handle: { meta: agentSelfLearningRouteMeta },- path: 'self-evolving',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/self-learning/new'),- 'Desktop > Chat > Self Learning > Create',- ),- handle: { meta: agentSelfLearningRouteMeta },- path: 'self-evolving/new',- },- // 单个方向的成长画像。做成路由而不是页内状态,深链才打得开。- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/agent/self-learning/[domainId]'),- 'Desktop > Chat > Self Learning > Domain',- ),- handle: { meta: agentSelfLearningRouteMeta },- index: true,- },- // 一个方向的全部经验(不折叠的完整清单)和单条经验详情。- {- element: dynamicElement(- () => import('@/routes/(main)/agent/self-learning/[domainId]/experience'),- 'Desktop > Chat > Self Learning > Domain > Experience',- ),- handle: { meta: agentSelfLearningRouteMeta },- path: 'experience',- },- {- element: dynamicElement(- () =>- import('@/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]'),- 'Desktop > Chat > Self Learning > Domain > Lesson',- ),- handle: { meta: agentSelfLearningRouteMeta },- path: 'experience/:lessonId',- },- // Legacy `/rules` deep-links — kept so old links keep opening.- {- element: redirectElement('../experience'),- path: 'rules',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]'),- 'Desktop > Chat > Self Learning > Domain > Legacy Rule',- ),- handle: { meta: routeMeta({ Skeleton: NoRouteSkeleton }) },- path: 'rules/:lessonId',- },- ],- path: 'self-evolving/:domainId',- },- // Legacy `/self-learning` deep-links keep their remaining path when redirected.- {- element: dynamicElement(- () => import('@/routes/(main)/agent/self-learning/legacy'),- 'Desktop > Chat > Legacy Self Learning Redirect',- ),- handle: { meta: routeMeta({ Skeleton: NoRouteSkeleton }) },- path: 'self-learning/*',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/permission'),- 'Desktop > Chat > Permission',- ),- handle: { meta: agentPermissionRouteMeta },- path: 'permission',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/tasks'),- 'Desktop > Chat > Tasks',- ),- handle: { meta: tasksRouteMeta },- loader: scheduledTaskListLoader,- path: 'tasks',- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/task/[taskId]'),- 'Desktop > Chat > Task Detail',- ),- handle: { meta: taskRouteMeta },- // `:slug?` is the readable title tail (Linear-style). It is never- // resolved against — `:taskId` alone identifies the task — so the- // optional segment keeps every pre-slug link working.- path: 'task/:taskId/:slug?',- },+ ...agentPageChildren,],element: dynamicLayout(() => import('@/routes/(main)/agent/_layout'),@@ -615,80 +393,7 @@ export const sharedMainAreaChildren: RouteObject[] = [// Memory routes{- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/memory/(home)'),- 'Desktop > Memory > Home',- { preloadId: 'memory' },- ),- handle: {- meta: routeMeta({- icon: BrainCircuit,- Skeleton: MemorySkeleton,- titleKey: 'navigation.memory',- }),- },- index: true,- },- {- element: dynamicElement(- () => import('@/routes/(main)/memory/identities'),- 'Desktop > Memory > Identities',- ),- handle: {- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),- },- // Seed the persisted identity list before the page paints, so a cold- // start shows the local copy instead of a loading state.- loader: identitiesListLoader,- path: 'identities',- },- {- element: dynamicElement(- () => import('@/routes/(main)/memory/contexts'),- 'Desktop > Memory > Contexts',- ),- handle: {- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),- },- path: 'contexts',- },- {- element: dynamicElement(- () => import('@/routes/(main)/memory/preferences'),- 'Desktop > Memory > Preferences',- ),- handle: {- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),- },- loader: preferenceListLoader,- path: 'preferences',- },- {- element: dynamicElement(- () => import('@/routes/(main)/memory/rules'),- 'Desktop > Memory > Rules',- ),- handle: {- // Same icon the memory sidebar uses, so a desktop tab and the nav item agree.- meta: routeMeta({ icon: Scale, titleKey: 'navigation.memoryRules' }),- },- path: 'rules',- },- {- element: dynamicElement(- () => import('@/routes/(main)/memory/activities'),- 'Desktop > Memory > Activities',- ),- handle: {- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),- },- // Seed the persisted head page before the page paints (see `activityListLoader`).- loader: activityListLoader,- path: 'activities',- },- ],+ children: memoryChildren,element: dynamicLayout(() => import('@/routes/(main)/memory/_layout'),'Desktop > Memory > Layout',diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex fcb26e6174b..7f9cf7a321a 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -83,6 +83,8 @@ async function readRouterSources() {'taskWorkspaceRoutes.tsx','workspaceSettingsRoutes.tsx','resourceRoutes.tsx',+ 'agentPageRoutes.tsx',+ 'memoryRoutes.tsx','onboardingRoute.tsx',].map((filename) => readFile(path.join(process.cwd(), 'src/spa/router', filename), 'utf8')),);@@ -739,12 +741,13 @@ describe('desktop router shared definition', () => {});it('keeps business resource and task routes in the shared definition', async () => {- const [sharedSource, , , , , , resourceSource] = await readRouterSources();+ const [sharedSource, , , , , , resourceSource, agentPageSource] = await readRouterSources();expect(sharedSource).toContain('resourceRoute,');expect(resourceSource).toContain('...BusinessResourceRoutes');expect(sharedSource).toContain("import('@/routes/(main)/(task-workspace)/_layout')");- expect(sharedSource).toContain("import('@/routes/(main)/agent/task/[taskId]')");+ expect(sharedSource).toContain('...agentPageChildren,');+ expect(agentPageSource).toContain("import('@/routes/(main)/agent/task/[taskId]')");expect(sharedSource).not.toContain("import('@/routes/(main)/task-workspace/_layout')");expect(sharedSource).not.toContain("import('@/routes/(main)/tasks/_layout')");expect(sharedSource).not.toContain("import('@/routes/(main)/task/_layout')");diff --git a/src/spa/router/memoryRoutes.tsx b/src/spa/router/memoryRoutes.tsxnew file mode 100644index 00000000000..f2ae694c496--- /dev/null+++ b/src/spa/router/memoryRoutes.tsx@@ -0,0 +1,88 @@+import { BrainCircuit, Scale } from 'lucide-react';+import type { RouteObject } from 'react-router';++import MemorySkeleton from '@/components/Skeleton/Memory';+import { activityListLoader } from '@/spa/router/activityListLoader';+import { identitiesListLoader } from '@/spa/router/identitiesListLoader';+import { preferenceListLoader } from '@/spa/router/preferenceListLoader';+import { routeMeta } from '@/spa/router/routeMeta';+import { dynamicElement } from '@/utils/router';++/**+ * `/memory` sections. Mounted by the desktop router under the memory layout+ * and reused by the mobile router (`mobileWorkspaceRoutes.tsx`).+ */+export const memoryChildren: RouteObject[] = [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/(home)'),+ 'Desktop > Memory > Home',+ { preloadId: 'memory' },+ ),+ handle: {+ meta: routeMeta({+ icon: BrainCircuit,+ Skeleton: MemorySkeleton,+ titleKey: 'navigation.memory',+ }),+ },+ index: true,+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/identities'),+ 'Desktop > Memory > Identities',+ ),+ handle: {+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),+ },+ // Seed the persisted identity list before the page paints, so a cold+ // start shows the local copy instead of a loading state.+ loader: identitiesListLoader,+ path: 'identities',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/contexts'),+ 'Desktop > Memory > Contexts',+ ),+ handle: {+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),+ },+ path: 'contexts',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/preferences'),+ 'Desktop > Memory > Preferences',+ ),+ handle: {+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),+ },+ loader: preferenceListLoader,+ path: 'preferences',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/rules'),+ 'Desktop > Memory > Rules',+ ),+ handle: {+ // Same icon the memory sidebar uses, so a desktop tab and the nav item agree.+ meta: routeMeta({ icon: Scale, titleKey: 'navigation.memoryRules' }),+ },+ path: 'rules',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/memory/activities'),+ 'Desktop > Memory > Activities',+ ),+ handle: {+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),+ },+ // Seed the persisted head page before the page paints (see `activityListLoader`).+ loader: activityListLoader,+ path: 'activities',+ },+];diff --git a/src/spa/router/mobileAgentRoutes.tsx b/src/spa/router/mobileAgentRoutes.tsxnew file mode 100644index 00000000000..cb1f5f71e34--- /dev/null+++ b/src/spa/router/mobileAgentRoutes.tsx@@ -0,0 +1,168 @@+'use client';++import type { RouteObject } from 'react-router';++import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';+import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';+import {+ groupPermissionRouteMeta,+ groupProfileRouteMeta,+ groupRouteMeta,+} from '@/routes/(main)/group/features/routeMeta';+import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';+import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';+import { agentPageChildren } from '@/spa/router/agentPageRoutes';+import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';+import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';+import { dropRoute, overlayRoutes } from '@/spa/router/routeOverlay';+import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';++const mobileChatElement = dynamicElement(+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/chat')),+ 'Mobile > Chat',+ { preloadId: 'mobile-agent' },+);++const mobileGroupChatElement = (name: string) =>+ dynamicElement(+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/group')),+ name,+ { preloadId: 'mobile-group' },+ );++/**+ * Desktop agent pages mounted full-screen on mobile. Each renders its own+ * `NavHeader`, which carries the mobile back button and the agent sidebar+ * drawer. Static paths outrank the chat's `:topicId`, so these stop opening the+ * chat with the page name as a topic id.+ */+const agentSubPages = overlayRoutes(agentPageChildren, {+ // The empty state renders no header; the shell adds back + the docs drawer.+ 'docs/index': (route) => ({+ ...route,+ handle: {+ meta: routeMeta({ Skeleton: NoRouteSkeleton, titleKey: 'navigation.document' }),+ mobileShellHeader: true,+ },+ }),+ // Served from the task workspace (`mobileWorkspaceRoutes.tsx`) on mobile.+ 'task/:taskId/:slug?': dropRoute,+});++export const mobileAgentRoute: RouteObject = {+ children: [+ {+ element: redirectElement('..'),+ index: true,+ },+ {+ children: [+ {+ children: [+ {+ element: mobileChatElement,+ handle: { meta: agentRouteMeta },+ index: true,+ loader: agentChatTopicListLoader,+ },+ {+ element: mobileChatElement,+ handle: { meta: agentRouteMeta },+ loader: agentChatTopicListLoader,+ path: ':topicId',+ },+ ],+ element: dynamicLayout(+ () => import('@/routes/(mobile)/chat/_layout'),+ 'Mobile > Chat > Layout',+ { preloadId: 'mobile-agent' },+ ),+ },+ {+ children: [+ // Settings brings its own header, so it sits beside the chat layout+ // instead of stacking under the chat header.+ {+ element: dynamicElement(+ () => import('@/routes/(mobile)/chat/settings'),+ 'Mobile > Chat > Settings',+ ),+ handle: { meta: mobileAgentSettingsRouteMeta },+ path: 'settings',+ },+ ...agentSubPages,+ ],+ element: dynamicLayout(+ () => import('@/routes/(mobile)/agent/_pages'),+ 'Mobile > Agent > Page Layout',+ ),+ },+ ],+ element: dynamicLayout(+ () => import('@/routes/(mobile)/agent/_layout'),+ 'Mobile > Agent > Layout',+ { preloadId: 'mobile-agent' },+ ),+ errorElement: <ErrorBoundary />,+ // Seed the persisted access record before the config gates decide.+ loader: agentAccessLoader,+ path: ':aid',+ },+ ],+ path: 'agent',+};++export const mobileGroupRoute: RouteObject = {+ children: [+ { element: redirectElement('..'), index: true },+ {+ children: [+ {+ children: [+ { element: mobileGroupChatElement('Mobile > Group'), index: true },+ { element: mobileGroupChatElement('Mobile > Group > Topic'), path: ':topicId' },+ ],+ element: dynamicLayout(+ () => import('@/routes/(mobile)/group/_layout'),+ 'Mobile > Group > Layout',+ { preloadId: 'mobile-group' },+ ),+ },+ {+ children: [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/group/profile'),+ 'Mobile > Group > Profile',+ ),+ handle: { meta: groupProfileRouteMeta },+ path: 'profile',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/group/permission'),+ 'Mobile > Group > Permission',+ ),+ handle: { meta: groupPermissionRouteMeta },+ path: 'permission',+ },+ ],+ element: dynamicLayout(+ () => import('@/routes/(mobile)/group/_pages'),+ 'Mobile > Group > Page Layout',+ ),+ },+ ],+ element: dynamicLayout(+ () => import('@/routes/(mobile)/group/_scope'),+ 'Mobile > Group > Scope',+ { preloadId: 'mobile-group' },+ ),+ errorElement: <ErrorBoundary />,+ handle: { meta: groupRouteMeta },+ loader: agentGroupAccessLoader,+ path: ':gid',+ },+ ],+ path: 'group',+};diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex fdb2b9812f2..5f1b16e12b4 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -11,21 +11,32 @@ import CommunityListSkeleton from '@/components/Skeleton/CommunityList';import { delayed } from '@/components/Skeleton/Delayed';import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';-import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';-import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';-import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';-import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';-import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';-import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';-import { agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';+import { mobileAgentRoute, mobileGroupRoute } from '@/spa/router/mobileAgentRoutes';+import { mobileUnsupportedRoutes, mobileWorkspaceRoutes } from '@/spa/router/mobileWorkspaceRoutes';+import { mobileWorkspaceSettingsChildren } from '@/spa/router/mobileWorkspaceSettingsRoutes';import { routeMeta } from '@/spa/router/routeMeta';+import { SettingsTabs } from '@/store/global/initialState';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';-const mobileChatElement = dynamicElement(- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/chat')),- 'Mobile > Chat',- { preloadId: 'mobile-agent' },+// One element per shape, shared by every tab: switching tabs keeps the page+// mounted instead of swapping in a new lazy component.+const settingsTabElement = dynamicElement(+ () => import('@/routes/(main)/settings'),+ 'Mobile > Settings > Tab',+ { preloadId: 'mobile-settings' },);+const settingsTabSubElement = dynamicElement(+ () => import('@/routes/(main)/settings'),+ 'Mobile > Settings > Tab > Sub',+ { preloadId: 'mobile-settings' },+);++const personalSettingsTabRoutes: RouteObject[] = [...new Set(Object.values(SettingsTabs))]+ .filter((tab) => tab !== SettingsTabs.Provider && tab !== SettingsTabs.Creds)+ .flatMap((tab) => [+ { element: settingsTabElement, handle: { settingsTab: tab }, path: tab },+ { element: settingsTabSubElement, handle: { settingsTab: tab }, path: `${tab}/:sub` },+ ]);// Mobile owns its home layout; it has no persistent desktop Home outside the outlet.const mobileHomeRoute: RouteObject = {@@ -50,81 +61,8 @@ const mobileHomeRoute: RouteObject = {* mirrors the subset of routes it actually supports — settings / me stay personal-only.*/export const sharedMainAreaChildren: RouteObject[] = [- // Chat routes- {- children: [- {- element: redirectElement('..'),- index: true,- },- {- children: [- {- element: mobileChatElement,- handle: { meta: agentRouteMeta },- index: true,- loader: agentChatTopicListLoader,- },- {- element: mobileChatElement,- handle: { meta: agentRouteMeta },- loader: agentChatTopicListLoader,- path: ':topicId',- },- {- element: dynamicElement(- () => import('@/routes/(mobile)/chat/settings'),- 'Mobile > Chat > Settings',- ),- handle: { meta: mobileAgentSettingsRouteMeta },- path: 'settings',- },- ],- element: dynamicLayout(- () => import('@/routes/(mobile)/chat/_layout'),- 'Mobile > Chat > Layout',- { preloadId: 'mobile-agent' },- ),- errorElement: <ErrorBoundary />,- path: ':aid',- },- ],- path: 'agent',- },-- {- path: 'group',- children: [- { index: true, element: redirectElement('..') },- {- path: ':gid',- loader: agentGroupAccessLoader,- element: dynamicLayout(- () => import('@/routes/(mobile)/group/_layout'),- 'Mobile > Group > Layout',- { preloadId: 'mobile-group' },- ),- handle: { meta: groupRouteMeta },- errorElement: <ErrorBoundary />,- children: [- {- index: true,- element: dynamicElement(- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/group')),- 'Mobile > Group',- ),- },- {- path: ':topicId',- element: dynamicElement(- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/group')),- 'Mobile > Group > Topic',- ),- },- ],- },- ],- },+ mobileAgentRoute,+ mobileGroupRoute,// Discover routes with nested structure{@@ -187,6 +125,13 @@ export const sharedMainAreaChildren: RouteObject[] = [},],},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/community/(list)/skill'),+ 'Mobile > Discover > List > Skill',+ ),+ path: 'skill',+ },{element: dynamicElement(() =>@@ -244,6 +189,24 @@ export const sharedMainAreaChildren: RouteObject[] = [),path: 'mcp/:slug',},+ {+ element: dynamicElement(+ () =>+ import('@/routes/(main)/community/(detail)/skill').then((m) => m.MobileSkillPage),+ 'Mobile > Discover > Detail > Skill',+ ),+ path: 'skill/:slug',+ },+ {+ element: dynamicElement(+ () =>+ import('@/routes/(main)/community/(detail)/group_agent').then(+ (m) => m.MobileGroupAgentDetailPage,+ ),+ 'Mobile > Discover > Detail > Group Agent',+ ),+ path: 'group_agent/:slug',+ },{element: dynamicElement(() =>@@ -295,72 +258,9 @@ export const sharedMainAreaChildren: RouteObject[] = [path: 'agents',},- // Task workspace routes (cross-agent)- {- children: [- {- children: [- {- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Mobile > Tasks', {- preloadId: 'mobile-tasks',- }),- index: true,- },- ],- errorElement: <ErrorBoundary resetPath=".." />,- path: 'tasks',- },- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/task/[taskId]'),- 'Mobile > Task Detail',- ),- // Optional readable title tail; `:taskId` alone resolves the task.- path: ':taskId/:slug?',- },- ],- errorElement: <ErrorBoundary resetPath="../tasks" />,- path: 'task',- },- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/agent/task/[taskId]'),- 'Mobile > Agent Task Detail',- ),- path: ':aid/task/:taskId/:slug?',- },- ],- errorElement: <ErrorBoundary resetPath="../tasks" />,- path: 'agent',- },- ],- element: dynamicLayout(- () => import('@/routes/(main)/(task-workspace)/_layout'),- 'Mobile > Task Workspace > Layout',- { preloadId: 'mobile-tasks' },- ),- },-- // Page detail. Mobile has no page list, so `/page` itself goes home; without- // these routes `/page/:id` fell through to the `*` redirect.- {- children: [- {- element: redirectElement('..'),- index: true,- },- {- element: dynamicElement(() => import('@/routes/(mobile)/page/[id]'), 'Mobile > Page'),- path: ':id',- },- ],- errorElement: <ErrorBoundary />,- path: 'page',- },+ // Tasks, goals, projects, resources, memory, pages, generation, dashboards+ ...mobileWorkspaceRoutes,+ ...mobileUnsupportedRoutes,...BusinessMobileRoutesWithMainLayout,];@@ -417,23 +317,13 @@ export const mobileRoutes: RouteObject[] = [element: redirectElement('/settings/credential'),path: 'creds',},+ // Every known tab gets a static segment: `/settings/memory` and+ // `/:workspaceSlug/memory` (or `/agent`, `/image`, …) tie on route+ // score, and the workspace tree would read `settings` as a slug.+ ...personalSettingsTabRoutes,// Other settings tabs (common, agent, memory, tts, about, etc.)- {- element: dynamicElement(- () => import('@/routes/(main)/settings'),- 'Mobile > Settings > Tab',- { preloadId: 'mobile-settings' },- ),- path: ':tab',- },- {- element: dynamicElement(- () => import('@/routes/(main)/settings'),- 'Mobile > Settings > Tab > Sub',- { preloadId: 'mobile-settings' },- ),- path: ':tab/:sub',- },+ { element: settingsTabElement, path: ':tab' },+ { element: settingsTabSubElement, path: ':tab/:sub' },],element: dynamicLayout(() => import('@/routes/(mobile)/settings/_layout'),@@ -510,200 +400,7 @@ export const mobileRoutes: RouteObject[] = [// settings chrome (header + content wrapper) for now; a dedicated// mobile workspace sidebar is follow-up work.{- children: [- { element: redirectElement('general'), index: true },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/general'),- 'Mobile > Workspace > Settings > General',- ),- path: 'general',- },- // Account-level tabs mirrored inside the workspace (see the- // desktop router); the pages are the personal settings pages.- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/profile'),- 'Mobile > Workspace > Settings > Profile',- ),- path: 'profile',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/appearance'),- 'Mobile > Workspace > Settings > Appearance',- ),- path: 'appearance',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/hotkey'),- 'Mobile > Workspace > Settings > Hotkey',- ),- path: 'hotkey',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/chat-preference'),- 'Mobile > Workspace > Settings > Chat Preference',- ),- path: 'chat-preference',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/messenger'),- 'Mobile > Workspace > Settings > Messenger',- ),- path: 'messenger',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/messenger'),- 'Mobile > Workspace > Settings > Messenger > Platform',- ),- path: 'messenger/:sub',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/advanced'),- 'Mobile > Workspace > Settings > Advanced',- ),- path: 'advanced',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/labs'),- 'Mobile > Workspace > Settings > Labs',- ),- path: 'labs',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/about'),- 'Mobile > Workspace > Settings > About',- ),- path: 'about',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/members'),- 'Mobile > Workspace > Settings > Members',- ),- path: 'members',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/teams'),- 'Mobile > Workspace > Settings > Teams',- ),- path: 'teams',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/teams'),- 'Mobile > Workspace > Settings > Teams > Detail',- ),- path: 'teams/:teamId',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),- 'Mobile > Workspace > Settings > Notification',- ),- path: 'notification',- },- // Channel detail level of the two-level notification settings —- // the page reads the channel id from the `sub` route param.- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),- 'Mobile > Workspace > Settings > Notification > Channel',- ),- path: 'notification/:sub',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/labels'),- 'Mobile > Workspace > Settings > Labels',- ),- path: 'labels',- },- {- element: dynamicElement(- () =>- import('@/routes/(main)/[workspaceSlug]/settings/provider').then(- (m) => m.WorkspaceProviderSettingMobile,- ),- 'Mobile > Workspace > Settings > Provider',- ),- path: 'provider',- },- // Path-shaped provider deep-links (`/:slug/settings/provider/:id`)- // redirect to the query form the workspace provider page uses, so- // they don't fall through to the catch-all and leave the workspace.- // Static element: the redirect is tiny and lazy-loading it would- // flash the generic brand loader before redirecting.- {- element: <WorkspaceProviderRedirect />,- path: 'provider/:providerId',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),- 'Mobile > Workspace > Settings > Plans',- ),- path: 'plans',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),- 'Mobile > Workspace > Settings > Billing',- ),- path: 'billing',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/budget'),- 'Mobile > Workspace > Settings > Budget',- ),- path: 'budget',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),- 'Mobile > Workspace > Settings > Credits',- ),- path: 'credits',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),- 'Mobile > Workspace > Settings > Usage',- ),- path: 'usage',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/audit-log'),- 'Mobile > Workspace > Settings > Audit Log',- ),- path: 'audit-log',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),- 'Mobile > Workspace > Settings > OAuth Apps',- ),- path: 'oauth-apps',- },- {- element: dynamicElement(- () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),- 'Mobile > Workspace > Settings > OAuth App Detail',- ),- path: 'oauth-apps/:sub',- },- ],+ children: mobileWorkspaceSettingsChildren,element: dynamicLayout(() => import('@/routes/(mobile)/settings/_layout'),'Mobile > Workspace > Settings > Layout',diff --git a/src/spa/router/mobileRouter.parity.test.ts b/src/spa/router/mobileRouter.parity.test.tsnew file mode 100644index 00000000000..a705b6aecd7--- /dev/null+++ b/src/spa/router/mobileRouter.parity.test.ts@@ -0,0 +1,70 @@+import type { RouteObject } from 'react-router';+import { matchRoutes } from 'react-router';+import { describe, expect, it } from 'vitest';++import { mainAreaMetaRoutes } from './desktopRouter.config';+import { mobileRoutes } from './mobileRouter.config';++/** Every leaf path pattern of a route tree, joined from the root. */+const collectLeafPatterns = (routes: RouteObject[], prefix = ''): string[] =>+ routes.flatMap((route) => {+ const path = route.path+ ? route.path.startsWith('/')+ ? route.path+ : `${prefix.replace(/\/$/, '')}/${route.path}`+ : prefix;+ return route.children?.length ? collectLeafPatterns(route.children, path) : [path || '/'];+ });++/** A concrete URL for a pattern: params become sample values, optional tails drop. */+const toSampleUrl = (pattern: string) =>+ pattern+ .replaceAll(/\/:[A-Z]+\?/gi, '')+ .replaceAll(':workspaceSlug', 'acme')+ .replaceAll(/:([A-Z]+)/gi, 'sample_$1')+ .replaceAll('/*', '/rest')+ .replaceAll(/\/+/g, '/');++/** The route pattern a URL resolved to, e.g. `agent/:aid/profile` or `:workspaceSlug`. */+const resolvedPattern = (routes: RouteObject[], url: string) =>+ (matchRoutes(routes, url) ?? [])+ .map((match) => match.route.path)+ .filter((path): path is string => !!path && path !== '/')+ .join('/')+ .replaceAll(/\/+/g, '/')+ .replace(/^\//, '');++// Desktop surfaces mobile intentionally leaves out. They redirect home instead+// of being read as a workspace slug.+const MOBILE_UNSUPPORTED = [/^\/(acme\/)?eval(\/|$)/];++const desktopUrls = [...new Set(collectLeafPatterns(mainAreaMetaRoutes).map(toSampleUrl))]+ .filter((url) => url !== '/rest')+ .sort();++describe('mobile router parity with the desktop main area', () => {+ it('covers a meaningful slice of the desktop tree', () => {+ expect(desktopUrls.length).toBeGreaterThan(150);+ });++ it.each(desktopUrls.filter((url) => !MOBILE_UNSUPPORTED.some((re) => re.test(url))))(+ 'resolves %s to the same route pattern as desktop',+ (url) => {+ // A mismatch means mobile hit the `*` catch-all, read a reserved path as+ // `:workspaceSlug`, or swallowed a page name into a dynamic segment such+ // as the chat's `:topicId`.+ expect(resolvedPattern(mobileRoutes, url)).toBe(resolvedPattern(mainAreaMetaRoutes, url));+ },+ );++ it.each(desktopUrls.filter((url) => MOBILE_UNSUPPORTED.some((re) => re.test(url))))(+ 'keeps desktop-only %s out of the workspace slug',+ (url) => {+ const matches = matchRoutes(mobileRoutes, url) ?? [];+ const isWorkspaceUrl = url.startsWith('/acme/');++ expect(matches.at(-1)?.route.path).toBe('eval/*');+ expect(matches.some((match) => match.route.path === ':workspaceSlug')).toBe(isWorkspaceUrl);+ },+ );+});diff --git a/src/spa/router/mobileRouter.test.tsx b/src/spa/router/mobileRouter.test.tsxindex ed644303b27..b60aeffa4aa 100644--- a/src/spa/router/mobileRouter.test.tsx+++ b/src/spa/router/mobileRouter.test.tsx@@ -50,30 +50,29 @@ describe('mobileRouter agent share route', () => {});describe('mobileRouter task routes', () => {- it('registers task list and detail routes under the shared workspace layout', async () => {- const source = await readFile(- path.join(process.cwd(), 'src/spa/router/mobileRouter.config.tsx'),- 'utf8',- );-- expect(source).toContain("import('@/routes/(main)/(task-workspace)/_layout')");- expect(source).toContain("import('@/routes/(main)/tasks')");- expect(source).toContain("import('@/routes/(main)/task/[taskId]')");- expect(source).toContain("import('@/routes/(main)/agent/task/[taskId]')");- expect(source).toContain("path: 'tasks'");- expect(source).toContain("path: 'task'");+ it.each([+ ['/tasks', {}],+ ['/goals', {}],+ ['/task/tsk_1', { taskId: 'tsk_1' }],// The `:slug?` tail is the readable title segment; it never resolves the// task, so pre-slug links keep matching the same route.- expect(source).toContain("path: ':taskId/:slug?'");- expect(source).toContain("path: ':aid/task/:taskId/:slug?'");- expect(source).not.toContain("import('@/routes/(main)/tasks/_layout')");+ ['/task/tsk_1/fix-login', { slug: 'fix-login', taskId: 'tsk_1' }],+ ['/goal/gol_1', { goalId: 'gol_1' }],+ ['/agent/agt_1/task/tsk_1', { aid: 'agt_1', taskId: 'tsk_1' }],+ ])('mounts %s under the shared task workspace layout', (pathname, params) => {+ const taskWorkspace = matchRoutes(mobileRoutes, '/tasks')!.at(-3)!.route;+ const matches = matchRoutes(mobileRoutes, pathname)!;++ expect(matches.some((match) => match.route === taskWorkspace)).toBe(true);+ expect(matches.at(-1)?.route.path).not.toBe('*');+ expect(matches.at(-1)?.params).toMatchObject(params);});});describe('mobileRouter workspace provider routes', () => {it('registers workspace provider list and path-shaped deep-link redirect', async () => {const source = await readFile(- path.join(process.cwd(), 'src/spa/router/mobileRouter.config.tsx'),+ path.join(process.cwd(), 'src/spa/router/mobileWorkspaceSettingsRoutes.tsx'),'utf8',);@@ -161,3 +160,14 @@ describe('mobileRouter acceptance routes', () => {expect(check?.at(-1)?.params).toMatchObject({ acceptanceId: 'acc_1', checkId: 'chk_1' });});});++describe('mobileRouter Docs routes', () => {+ it('reuses the desktop Docs subtree and gives the header-less Works view a shell header', () => {+ const works = matchRoutes(mobileRoutes, '/resource/works')!.at(-1)!.route;+ const drive = matchRoutes(mobileRoutes, '/resource/drive/images')!.at(-1)!.route;++ expect((works.handle as { mobileShellHeader?: boolean }).mobileShellHeader).toBe(true);+ expect((drive.handle as { mobileShellHeader?: boolean }).mobileShellHeader).toBeUndefined();+ expect(getRouteMetaFromHandle(works.handle)?.titleKey).toBe('navigation.resourceWorks');+ });+});diff --git a/src/spa/router/mobileWorkspaceRoutes.tsx b/src/spa/router/mobileWorkspaceRoutes.tsxnew file mode 100644index 00000000000..d975620b8f7--- /dev/null+++ b/src/spa/router/mobileWorkspaceRoutes.tsx@@ -0,0 +1,260 @@+'use client';++import { FilePenIcon, Image, Video } from 'lucide-react';+import { lazy } from 'react';+import type { RouteObject } from 'react-router';++import GenerationSkeleton from '@/components/Skeleton/Generation';+import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';+import { taskRouteMeta } from '@/features/AgentTasks/routeMeta';+import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/routeMeta';+import { pageRouteMeta } from '@/features/Pages/routeMeta';+import { projectsRouteMeta } from '@/features/Projects/routeMeta';+import { memoryChildren } from '@/spa/router/memoryRoutes';+import { pageListLoader } from '@/spa/router/pageListLoader';+import { projectWorkspaceRoute } from '@/spa/router/projectWorkspaceRoutes';+import { resourceRoute as desktopResourceRoute } from '@/spa/router/resourceRoutes';+import { routeMeta } from '@/spa/router/routeMeta';+import { overlayRoutes, withHandle } from '@/spa/router/routeOverlay';+import { createTaskWorkspaceChildren } from '@/spa/router/taskWorkspaceRoutes';+import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';++/**+ * The desktop workspace surfaces (tasks, goals, projects, resources, memory,+ * pages, generation, dashboards) mounted on mobile. Every page reuses its+ * desktop segment; desktop layouts that only paint a sidebar are kept because+ * the sidebar they register opens from the mobile page header as a drawer.+ * Mounted under both `/` and `/:workspaceSlug` by `mobileRouter.config.tsx`.+ */++// Reads the project store, so keep it out of the router's entry graph.+const ProjectMobileShellTitle = lazy(() => import('@/features/Projects/MobileShellTitle'));++const pageLayout = (name: string) =>+ dynamicLayout(() => import('@/routes/(mobile)/_page-layout'), name);++const taskWorkspaceRoute: RouteObject = {+ children: [+ ...createTaskWorkspaceChildren({ label: 'Mobile', preloadId: 'mobile-tasks' }),+ // Desktop serves this under the agent layout; mobile keeps it in the task+ // workspace so the task detail gets the workspace's task sidebar drawer.+ {+ children: [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agent/task/[taskId]'),+ 'Mobile > Agent Task Detail',+ ),+ handle: { meta: taskRouteMeta },+ path: ':aid/task/:taskId/:slug?',+ },+ ],+ errorElement: <ErrorBoundary resetPath="../tasks" />,+ path: 'agent',+ },+ ],+ element: dynamicLayout(+ () => import('@/routes/(main)/(task-workspace)/_layout'),+ 'Mobile > Task Workspace > Layout',+ { preloadId: 'mobile-tasks' },+ ),+};++const projectRoutes: RouteObject[] = [+ {+ children: [+ {+ element: dynamicElement(() => import('@/routes/(main)/projects'), 'Mobile > Projects'),+ handle: { meta: projectsRouteMeta },+ index: true,+ },+ ],+ element: pageLayout('Mobile > Projects > Layout'),+ errorElement: <ErrorBoundary resetPath=".." />,+ path: 'projects',+ },+ // The desktop project workspace (home, topics, tasks, settings, goals,+ // dashboards, acceptance) inside the mobile page layout. Its layout gates on+ // `enableProjects`, loads the project and registers the project sidebar,+ // which mobile opens as a drawer.+ {+ children: [+ {+ ...projectWorkspaceRoute,+ children: overlayRoutes(projectWorkspaceRoute.children ?? [], {+ 'index': withHandle({+ mobileShellHeader: true,+ mobileShellTitle: ProjectMobileShellTitle,+ }),+ // The settings page opens with its own "Project settings" heading.+ 'settings/:section?': withHandle({ mobileShellHeader: 'untitled' }),+ 'topic/:topicId?': (route) => ({+ ...route,+ element: dynamicElement(+ () => import('@/routes/(mobile)/project/[projectId]/topic'),+ 'Mobile > Project Topic',+ ),+ }),+ }),+ errorElement: undefined,+ path: undefined,+ } as RouteObject,+ ],+ element: pageLayout('Mobile > Project > Page Layout'),+ errorElement: <ErrorBoundary resetPath=".." />,+ path: 'project/:projectId',+ },+];++// The shared Docs subtree (home, drive, works, library gallery, libraries)+// wrapped in the mobile page layout with the drag context its rows need. Reused+// rather than copied, so the mobile tree follows every desktop route change.+// Works paints no page header, so the shell adds one there.+const resourceRoute: RouteObject = {+ children: overlayRoutes([{ ...desktopResourceRoute, path: undefined }], {+ works: withHandle({ mobileShellHeader: true }),+ }),+ element: dynamicLayout(+ () => import('@/routes/(mobile)/resource/_layout'),+ 'Mobile > Resource > Layout',+ ),+ errorElement: <ErrorBoundary />,+ path: 'resource',+};++const memoryRoute: RouteObject = {+ children: [+ {+ // The contexts page (entity list + page) paints no header of its own.+ children: overlayRoutes(memoryChildren, {+ contexts: withHandle({ mobileShellHeader: true }),+ }),+ // Section nav sidebar (opened as a drawer on mobile).+ element: dynamicLayout(+ () => import('@/routes/(main)/memory/_layout'),+ 'Mobile > Memory > Layout',+ ),+ },+ ],+ element: pageLayout('Mobile > Memory > Page Layout'),+ errorElement: <ErrorBoundary />,+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },+ path: 'memory',+};++const pageRoute: RouteObject = {+ children: [+ {+ element: dynamicElement(() => import('@/routes/(mobile)/page'), 'Mobile > Page List'),+ handle: {+ meta: routeMeta({+ icon: FilePenIcon,+ Skeleton: createSurfaceSkeleton('list'),+ titleKey: 'navigation.pages',+ }),+ },+ index: true,+ },+ {+ element: dynamicElement(() => import('@/routes/(mobile)/page/[id]'), 'Mobile > Page'),+ handle: { meta: pageRouteMeta },+ path: ':id',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/page/[id]/permission'),+ 'Mobile > Page > Permission',+ ),+ handle: { meta: pageRouteMeta },+ path: ':id/permission',+ },+ ],+ element: dynamicLayout(() => import('@/routes/(mobile)/page/_layout'), 'Mobile > Page > Layout'),+ errorElement: <ErrorBoundary />,+ loader: pageListLoader,+ path: 'page',+};++const generationRoute = (kind: 'image' | 'video'): RouteObject => ({+ children: [+ {+ children: [+ {+ element:+ kind === 'image'+ ? dynamicElement(() => import('@/routes/(main)/(create)/image'), 'Mobile > Image')+ : dynamicElement(() => import('@/routes/(main)/(create)/video'), 'Mobile > Video'),+ handle: {+ meta: routeMeta(+ kind === 'image'+ ? { icon: Image, titleKey: 'navigation.image' }+ : { icon: Video, titleKey: 'navigation.video' },+ ),+ },+ index: true,+ },+ ],+ // Topic URL sync plus the topic sidebar (opened as a drawer on mobile).+ element:+ kind === 'image'+ ? dynamicLayout(+ () => import('@/routes/(main)/(create)/image/_layout'),+ 'Mobile > Image > Layout',+ )+ : dynamicLayout(+ () => import('@/routes/(main)/(create)/video/_layout'),+ 'Mobile > Video > Layout',+ ),+ },+ ],+ element: pageLayout(`Mobile > ${kind} > Page Layout`),+ errorElement: <ErrorBoundary />,+ handle: { meta: routeMeta({ Skeleton: GenerationSkeleton }) },+ path: kind,+});++const dashboardRoute: RouteObject = {+ children: [+ {+ children: [+ {+ element: dynamicElement(() => import('@/routes/(main)/dashboard'), 'Mobile > Dashboards'),+ handle: { meta: dashboardsRouteMeta },+ index: true,+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/dashboard/[dashboardId]'),+ 'Mobile > Dashboard Detail',+ ),+ handle: { meta: dashboardRouteMeta },+ path: ':dashboardId',+ },+ ],+ // Personal-only, and off unless the `dashboard` feature flag is on.+ element: dynamicLayout(+ () => import('@/routes/(main)/dashboard/_layout'),+ 'Mobile > Dashboards > Gate',+ ),+ },+ ],+ element: pageLayout('Mobile > Dashboards > Page Layout'),+ errorElement: <ErrorBoundary resetPath=".." />,+ path: 'dashboard',+};++export const mobileWorkspaceRoutes: RouteObject[] = [+ taskWorkspaceRoute,+ ...projectRoutes,+ resourceRoute,+ memoryRoute,+ pageRoute,+ generationRoute('image'),+ generationRoute('video'),+ dashboardRoute,+];++/** Desktop-only surfaces (no mobile entry on desktop either) leave for home instead of being read as a workspace slug. */+export const mobileUnsupportedRoutes: RouteObject[] = [+ { element: redirectElement('..'), path: 'eval/*' },+];diff --git a/src/spa/router/mobileWorkspaceSettingsRoutes.tsx b/src/spa/router/mobileWorkspaceSettingsRoutes.tsxnew file mode 100644index 00000000000..9f909dbad21--- /dev/null+++ b/src/spa/router/mobileWorkspaceSettingsRoutes.tsx@@ -0,0 +1,53 @@+'use client';++import type { RouteObject } from 'react-router';++import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';+import { workspaceSettingsContentRoute } from '@/spa/router/workspaceSettingsRoutes';+import { dynamicElement } from '@/utils/router';++/**+ * `/:slug/settings/*` on mobile: the mobile settings menu, then every padded+ * desktop tab from `workspaceSettingsContentRoute` (so a tab added there is+ * mounted here too), then the full-bleed tabs desktop mounts beside them.+ * Mobile renders them under the mobile settings header instead of the desktop+ * sidebar + content layout.+ */+export const mobileWorkspaceSettingsChildren: RouteObject[] = [+ {+ element: dynamicElement(+ () => import('@/routes/(mobile)/[workspaceSlug]/settings'),+ 'Mobile > Workspace > Settings > Index',+ ),+ index: true,+ },+ ...(workspaceSettingsContentRoute.children ?? []),+ {+ element: dynamicElement(+ () =>+ import('@/routes/(main)/[workspaceSlug]/settings/provider').then(+ (m) => m.WorkspaceProviderSettingMobile,+ ),+ 'Mobile > Workspace > Settings > Provider',+ ),+ path: 'provider',+ },+ // Path-shaped provider deep-links (`/:slug/settings/provider/:id`) redirect+ // to the query form the workspace provider page uses. Static element: the+ // redirect is tiny and lazy-loading it would flash the brand loader first.+ { element: <WorkspaceProviderRedirect />, path: 'provider/:providerId' },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/skill'),+ 'Mobile > Workspace > Settings > Skill',+ ),+ path: 'skill',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/connector'),+ 'Mobile > Workspace > Settings > Connector',+ ),+ path: 'connector',+ },+];diff --git a/src/spa/router/routeOverlay.test.ts b/src/spa/router/routeOverlay.test.tsnew file mode 100644index 00000000000..921448bb2f9--- /dev/null+++ b/src/spa/router/routeOverlay.test.ts@@ -0,0 +1,36 @@+import type { RouteObject } from 'react-router';+import { describe, expect, it } from 'vitest';++import { dropRoute, overlayRoutes, withHandle } from './routeOverlay';++const tree: RouteObject[] = [+ {+ children: [{ handle: { meta: 'docs' }, index: true }, { path: ':docId' }],+ path: 'docs',+ },+ // Pathless layout: its children keep the parent's base.+ { children: [{ path: 'goals' }, { path: 'task/:taskId' }] },+];++describe('overlayRoutes', () => {+ it('adjusts routes by their path from the tree root, index routes as <parent>/index', () => {+ const result = overlayRoutes(tree, {+ 'docs/index': withHandle({ mobileShellHeader: true }),+ 'task/:taskId': dropRoute,+ });++ expect(result[0].children?.[0].handle).toEqual({ meta: 'docs', mobileShellHeader: true });+ expect(result[1].children?.map((route) => route.path)).toEqual(['goals']);+ });++ it('returns the source routes untouched without overlays', () => {+ const result = overlayRoutes(tree, {});++ expect(result).toEqual(tree);+ expect(result[0].children?.[1]).toBe(tree[0].children?.[1]);+ });++ it('throws when a key matches no route, so a renamed source route cannot slip past', () => {+ expect(() => overlayRoutes(tree, { 'docs/:id': dropRoute })).toThrow('docs/:id');+ });+});diff --git a/src/spa/router/routeOverlay.ts b/src/spa/router/routeOverlay.tsnew file mode 100644index 00000000000..a1db2c36cbf--- /dev/null+++ b/src/spa/router/routeOverlay.ts@@ -0,0 +1,59 @@+import type { RouteObject } from 'react-router';++/** Rewrites one route of a reused tree; `null` drops it. */+export type RouteOverlay = (route: RouteObject) => RouteObject | null;++const joinKey = (base: string, segment: string) => (base ? `${base}/${segment}` : segment);++const applyOverlays = (+ routes: readonly RouteObject[],+ overlays: Readonly<Record<string, RouteOverlay>>,+ used: Set<string>,+ base: string,+): RouteObject[] =>+ routes.flatMap((route) => {+ const childBase = route.path ? joinKey(base, route.path) : base;+ const next = (+ route.children+ ? { ...route, children: applyOverlays(route.children, overlays, used, childBase) }+ : route+ ) as RouteObject;+ const key = route.index ? joinKey(base, 'index') : route.path ? childBase : undefined;+ const overlay = key === undefined ? undefined : overlays[key];+ if (!overlay) return [next];++ used.add(key!);+ const result = overlay(next);+ return result ? [result] : [];+ });++/**+ * Reuse a route tree defined for another router (desktop → mobile) and adjust+ * only the routes that differ, so the copy cannot drift from its source.+ *+ * Overlay keys are paths relative to the tree root; an index route is+ * `<parent>/index` (`index` at the root). Pathless layout routes have no key.+ * A key that matches no route throws: the source tree renamed or removed that+ * route, and the adjustment would otherwise stop applying without a trace.+ */+export const overlayRoutes = (+ routes: readonly RouteObject[],+ overlays: Readonly<Record<string, RouteOverlay>>,+): RouteObject[] => {+ const used = new Set<string>();+ const result = applyOverlays(routes, overlays, used, '');+ const unused = Object.keys(overlays).filter((key) => !used.has(key));+ if (unused.length > 0)+ throw new Error(`overlayRoutes: no route matches overlay key(s) ${unused.join(', ')}`);++ return result;+};++/** Overlay that merges extra fields into the route's `handle`. */+export const withHandle =+ (extra: Record<string, unknown>): RouteOverlay =>+ (route) =>+ ({ ...route, handle: { ...(route.handle as object), ...extra } }) as RouteObject;++/** Overlay that drops the route. */+export const dropRoute: RouteOverlay = () => null;diff --git a/src/spa/router/taskWorkspaceRoutes.tsx b/src/spa/router/taskWorkspaceRoutes.tsxindex 329a65f1d98..48a9d055ee2 100644--- a/src/spa/router/taskWorkspaceRoutes.tsx+++ b/src/spa/router/taskWorkspaceRoutes.tsx@@ -5,17 +5,28 @@ import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';import { dynamicElement, ErrorBoundary } from '@/utils/router';+interface TaskWorkspaceOptions {+ /** Debug-name prefix of the lazy segments (`Desktop`, `Mobile`). */+ label: string;+ /** Route-preload task the task list warms (each platform has its own list). */+ preloadId: string;+}+/*** The cross-agent task workspace: `/tasks` and `/goals`, and the bare- * `/task/:taskId` and `/goal/:goalId` details they open. Mounted under the- * workspace layout in `desktopRouter.shared.tsx`.+ * `/task/:taskId` and `/goal/:goalId` details they open. Desktop mounts it+ * under the workspace layout in `desktopRouter.shared.tsx`; mobile mounts the+ * same tree from `mobileWorkspaceRoutes.tsx`.*/-export const taskWorkspaceChildren: RouteObject[] = [+export const createTaskWorkspaceChildren = ({+ label,+ preloadId,+}: TaskWorkspaceOptions): RouteObject[] => [{children: [{- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks', {- preloadId: 'tasks',+ element: dynamicElement(() => import('@/routes/(main)/tasks'), `${label} > Tasks`, {+ preloadId,}),handle: { meta: tasksRouteMeta },index: true,@@ -28,7 +39,7 @@ export const taskWorkspaceChildren: RouteObject[] = [{children: [{- element: dynamicElement(() => import('@/routes/(main)/goals'), 'Desktop > Goals'),+ element: dynamicElement(() => import('@/routes/(main)/goals'), `${label} > Goals`),handle: { meta: goalsRouteMeta },index: true,},@@ -41,7 +52,7 @@ export const taskWorkspaceChildren: RouteObject[] = [{element: dynamicElement(() => import('@/routes/(main)/task/[taskId]'),- 'Desktop > Task Detail',+ `${label} > Task Detail`,),handle: { meta: taskRouteMeta },// Optional readable title tail — see the agent-scoped `task/:taskId/:slug?`@@ -57,7 +68,7 @@ export const taskWorkspaceChildren: RouteObject[] = [{element: dynamicElement(() => import('@/routes/(main)/goal/[goalId]'),- 'Desktop > Goal Detail',+ `${label} > Goal Detail`,),handle: { meta: goalDetailRouteMeta },path: ':goalId',@@ -67,3 +78,8 @@ export const taskWorkspaceChildren: RouteObject[] = [path: 'goal',},];++export const taskWorkspaceChildren = createTaskWorkspaceChildren({+ label: 'Desktop',+ preloadId: 'tasks',+});diff --git a/src/utils/mobileSurface.ts b/src/utils/mobileSurface.tsnew file mode 100644index 00000000000..8260124203b--- /dev/null+++ b/src/utils/mobileSurface.ts@@ -0,0 +1,7 @@+/**+ * Whether this bundle is the mobile SPA (`entry.mobile.tsx`). The router is+ * chosen by the bundle, not by the viewport — a landscape phone above the mobile+ * breakpoint still runs the mobile router. Read per call so tests can stub+ * `__MOBILE__`.+ */+export const isMobileSurface = () => typeof __MOBILE__ !== 'undefined' && __MOBILE__;