Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db571ba204 | ||
|
|
f6614d4bf9 | ||
|
|
4984293998 | ||
|
|
6c3b09e693 |
@@ -1,11 +1,8 @@
|
||||
# 复制成 .env 后填写。不填也能跑(会回退到离线 provider)。
|
||||
|
||||
# ---- LLM ----
|
||||
DEEPSEEK_API_KEY=
|
||||
|
||||
# ---- Embedding(可选,留空则用本地或跳过向量检索)----
|
||||
EMBEDDING_API_KEY=
|
||||
|
||||
# ---- 运行时 ----
|
||||
CYBERGRIL_DB=companion.db
|
||||
CYBERGRIL_LOG_LEVEL=INFO
|
||||
# R1 uses the approved no-key gateway from config/models.yaml.
|
||||
# These variables are read from the process environment; this file is not auto-loaded.
|
||||
# Keep data outside release directories. Use an independent directory for local testing.
|
||||
CYBERGRIL_DB=/opt/cybergril-data/cybergril.db
|
||||
CYBERGRIL_MODELS=config/models.yaml
|
||||
CYBERGRIL_WEB=web/dist
|
||||
CYBERGRIL_HOST=127.0.0.1
|
||||
CYBERGRIL_PORT=8310
|
||||
|
||||
@@ -48,3 +48,5 @@ models/
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
.venv311/
|
||||
|
||||
@@ -306,3 +306,7 @@ pytest -k degradation -v # 降级机制
|
||||
## 许可
|
||||
|
||||
私有项目,未授权。
|
||||
|
||||
## S1 前端演示
|
||||
|
||||
独立的 React / TypeScript 前端位于 `web/`,运行 `cd web && npm ci && npm run dev` 后从普通入口进入明确标识的本机演示。真实后台、语音、视觉和备份尚未接通;不自动连接模型或现有服务。安装、构建和测试命令见 [web/README.md](web/README.md),实现与后续接线见 [docs/frontend/IMPLEMENTATION.md](docs/frontend/IMPLEMENTATION.md)。
|
||||
|
||||
@@ -18,9 +18,9 @@ tiers:
|
||||
# ---- 旗舰:人设浓度最高的时刻 ----
|
||||
high:
|
||||
provider: openai_compat
|
||||
model: deepseek-v4.1-flash
|
||||
base_url: https://api.deepseek.com/v1
|
||||
api_key_env: DEEPSEEK_API_KEY
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 60.0
|
||||
temperature: 0.85
|
||||
|
||||
@@ -28,9 +28,9 @@ tiers:
|
||||
# 省钱的杠杆通常不是换更小的模型,而是少喂上下文。
|
||||
standard:
|
||||
provider: openai_compat
|
||||
model: deepseek-v4.1-flash
|
||||
base_url: https://api.deepseek.com/v1
|
||||
api_key_env: DEEPSEEK_API_KEY
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 40.0
|
||||
temperature: 0.7
|
||||
|
||||
@@ -38,8 +38,8 @@ tiers:
|
||||
# 没有本地服务时,把它指向 openai_compat 的远端小模型即可。
|
||||
low:
|
||||
provider: openai_compat
|
||||
model: qwen3.5-4b-instruct
|
||||
base_url: http://127.0.0.1:8000/v1
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 20.0
|
||||
temperature: 0.4
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Review/install by 总工 only. Single worker; never share DB with demo or tests.
|
||||
[Unit]
|
||||
Description=CyberGril R1 persistent text API
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=cybergril
|
||||
WorkingDirectory=/opt/cybergril-api/current
|
||||
Environment=CYBERGRIL_DB=/opt/cybergril-data/cybergril.db
|
||||
Environment=CYBERGRIL_MODELS=/opt/cybergril-api/current/config/models.yaml
|
||||
Environment=CYBERGRIL_WEB=/opt/cybergril-api/current/web/dist
|
||||
Environment=CYBERGRIL_HOST=0.0.0.0
|
||||
Environment=CYBERGRIL_PORT=8310
|
||||
ExecStart=/opt/cybergril-api/current/.venv/bin/python -m cybergril.api
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
TimeoutStopSec=15
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/opt/cybergril-data
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1 @@
|
||||
screenshots/
|
||||
@@ -0,0 +1,48 @@
|
||||
HEL-748 · S1 实现与接线说明
|
||||
|
||||
本轮范围是可构建的完整前端及离线演示,不部署,不实现 B1–B3。基于正式仓库 main 的 `1e9b08aed81b4ebf163721232a8d65707b1c3183` 新建任务分支;检出时工作区干净,无仓库内额外 AGENTS,无平台关联 PR。未改 Python 核心、既有测试、服务配置、SSH 信任、端口、GPU 或模型。
|
||||
|
||||
依据为本卡《整套设计验收与施工裁定-v1》、HEL-746 R2、HEL-738 结构与接口边界和需求 v1.6。名字、关系不预选、未分享即隐藏三项裁定覆盖旧原型。首建底色明确为示例,真实排盘待接已有 Python 编译器,不在浏览器重写八字规则。
|
||||
|
||||
主要目录与职责:
|
||||
|
||||
- `web/src/app/`:入口、首建守卫、导航、全局 UI 偏好、返回/主动/断线演示。
|
||||
- `web/src/manage/`:四步首建;只读身份;关系/城市/服务/显示草稿;保存取消失败;外观标识;演示导出与同身份恢复。
|
||||
- `web/src/chat/`:文字草稿、IME 与快捷键、字幕/记录、取消重试、模拟语音/观察授权及结束。
|
||||
- `web/src/life/`:生活与四类回忆、双向关联、原位保留、手机详情推入、分页和深链守卫。
|
||||
- `web/src/domain/`:模型、首建校验、公开视图。所有可见事件、回忆、消息、摘要统一经过 `publicView`,未知关联默认拒绝;详情也从公开视图查找。
|
||||
- `web/src/adapters/`:独立可替换聊天适配器、turn_id/epoch 门槛、AbortController、本地持久化、严格 JSON 重建校验。
|
||||
- `web/src/demo/`:固定场景数据,与页面和传输分离。
|
||||
- `web/src/stage/`:背景空间与 `FallbackPresenter`。Presenter 只消费 SceneDesc,不写生活;参考图片失效也有文字降级,不黑屏。
|
||||
- `web/src/shared/`:复用按钮、图标、字段、状态和带焦点边界的确认弹层。
|
||||
- `web/src/styles/`:R2 单一 Token 和组件样式来源;没有第三方 UI 皮肤或叠加覆盖样式表。
|
||||
|
||||
两主题使用相同 DOM 和布局;人物拱窗、交谈展开、阅读面板与手机断点沿用获批样式。静帧仅呈现参考人物/房间,不渲染整页图片。语音/观察不访问 `getUserMedia`、不调用 ASR/TTS、不发外部请求。演示天气固定并标注模拟;当前视觉标签来自演示记录公开视图。
|
||||
|
||||
F1–F9 走法:
|
||||
|
||||
| 流程 | 入口与边界 |
|
||||
|---|---|
|
||||
| F1 | 无本机档案 → 四步创建 → 名字/成年生日/关系/勾选校验 → 本机持久化 → 首晚空生活 |
|
||||
| F2 | 普通入口说明未接服务 → 明确演示入口;重开直接回到同一位她 |
|
||||
| F3 | 演示场景 → 模拟两天后返回;只从已分享数据生成摘要,不生成后台生活 |
|
||||
| F4 | 演示场景 → 主动消息;来源是已分享事件,回她定位聊天并保留来源区域 |
|
||||
| F5 | 交流麦克风 → 模拟授权 → 倾听界面;文字发送推进思考/说话,可打断/结束;无真实收音 |
|
||||
| F6 | 演示断线 → 暂停发送,保留草稿,结束模拟语音、取消旧轮;恢复失败可重试,不自动重发 |
|
||||
| F7 | 设置城市 → 搜索/选择 → 保存成功/失败/重试;不调用天气 API |
|
||||
| F8 | 本地演示素材 JSON → 结构检查/模拟对比/确认;只更新外观标识,真实媒体导入待后续 |
|
||||
| F9 | 本地演示 JSON 下载/同身份校验/输入确认/先导出再恢复;服务器备份明确未接通 |
|
||||
|
||||
取消与错误:新轮、手动取消、切离交流会 abort 当前模拟回复;事件还需同时匹配 turn_id 与 epoch,非协作适配器的迟到消息同样被门槛拒绝。断线 resync 提升 epoch;恢复不自动续接旧轮。管理保存切区/关区会 abort;草稿保留,取消恢复上次提交值;存储损坏不进入新的首建覆盖。导入只执行 JSON.parse 后按固定 schema 重建;不执行脚本、不作为 HTML、不加载媒体/服务 URL。
|
||||
|
||||
后续接线清单(当前均未提供):
|
||||
|
||||
1. B1 同源 API 与 WS:hello/sync、游标和持久 epoch、能力声明、HTTP AbortSignal。真实模式不得直接替换成未经审定的 LLM URL。
|
||||
2. 服务端授权与隐私:必须在响应前裁剪未分享记录、未知引用、回忆和消息及摘要;本轮前端过滤不构成服务器权限控制。
|
||||
3. 接已有 Python 生辰预览/只读档案、真实关系更新;身份 ID、底色指纹由服务端负责。
|
||||
4. B2/B3 后台生活、主动性、记忆与增长层;前端只订阅 LifeScene/事件,不从素材反编生活。
|
||||
5. S2 流式文字;S3 ASR/TTS 二进制协议、session_id/seq 隔离、权限与实际中断;当前没有真实音频流,因此不声称达到延迟指标。
|
||||
6. S4 生活/回忆服务分页;S5 城市/天气、素材包校验和完整服务器备份/自动备份;演示 JSON 的 MIME 和结构不是媒体真伪校验。
|
||||
7. S6 视觉摘要时效与 HTTPS、真实权限;Presenter 的视频/音频/口型驱动器可注入,当前只交静帧降级。
|
||||
|
||||
测试部署由总工审核后执行。建议在独立目录安装构建,将 `web/dist/` 作为静态站点挂到总工选定的未占用测试端口;正常路径 `/`,演示 `/?demo=1`。本轮未占用固定服务端口,也未更改 8010/18080/18081 或现网。部署若换 origin,浏览器本地演示资料不会自动迁移,可通过同身份演示 JSON 手动恢复。
|
||||
@@ -0,0 +1,11 @@
|
||||
HEL-748: S1 完整前端与本机演示(不含后端或部署)
|
||||
|
||||
原仓库只有 Python 核心,没有产品前端。新增独立 `web/` React/TypeScript/Vite 工程,将获批 HEL-746 R2 的两主题、相处/交流/日子/管理和 F1–F9 演示落地为可构建组件。
|
||||
|
||||
创建必须输入名字并亲自选关系,刷新保留同一位档案;未分享生活及未知引用统一隐藏,包括详情、回忆、聊天和离开摘要。普通入口说明服务未接通,只有显式 `?demo=1` 进入本机演示;导入只解析校验 JSON,不执行 HTML/脚本、不请求外部媒体或服务。轮次/epoch/AbortSignal 隔离旧回复,管理草稿按分区保存或取消,恢复需同身份、输入确认并先导出。
|
||||
|
||||
验证:TypeScript、ESLint、Vite 生产构建、11 项领域测试、原有 Python 78 项测试;实际 Chromium 在 1440×900、1280×800、390×844 走查两主题及关键失败/恢复路径。浏览器记录与接线清单见 `docs/frontend/`。真实手机/Safari、真实服务和性能指标未测。
|
||||
|
||||
本轮仅 S1。没有更改 Python 核心、现网配置或服务端口,没有部署/合并,没有接入 LLM/ASR/TTS/视觉/后台循环/真实备份。Presenter 使用标识清楚的参考静帧。审查通过后由总工负责独立测试部署。
|
||||
|
||||
目标 base: main (`1e9b08aed81b4ebf163721232a8d65707b1c3183`)
|
||||
@@ -0,0 +1,33 @@
|
||||
HEL-748 S1 · 实际验证记录 · 2026-10-22(北京时间)
|
||||
|
||||
环境:Ubuntu 22.04;Node 24.16.0 / npm 11.13.0;Chromium 151.0.7922.34(Python Playwright、无头真实浏览器);Python 3.11.16 独立 `.venv`。浏览器直接加载 Vite 生产产物,测试脚本启动随机 loopback HTTP 端口并在结束时关闭。
|
||||
|
||||
| 检查 | 实际结果 |
|
||||
|---|---|
|
||||
| `npm run typecheck` | 通过 |
|
||||
| `npm run lint` | 通过,无调试输出残留 |
|
||||
| `npm test` | 11 项通过:隐私公开视图/未知引用、首建拦截、持久化失败与损坏、恢复身份/结构/脚本边界、turn/epoch/Abort 隔离、HTTP 标识兼容 |
|
||||
| `npm run build` | 通过,41 个模块;JS 197.50KB / gzip 64.67KB,CSS 61.20KB / gzip 13.05KB |
|
||||
| Python 既有测试 | `.venv/bin/python -m pytest -q`:78 项通过(Python 3.11.16);默认 Python 3.10.12 亦通过 78 项 |
|
||||
| 运行时依赖检查 | `npm audit --omit=dev --registry=https://registry.npmjs.org` 返回 0 漏洞;只检查生产依赖 |
|
||||
| 三尺寸主走查 | 1440×900、1280×800、390×844,两套主题;16 组结果通过,88 次本机请求,无未捕获浏览器错误、无外部服务请求 |
|
||||
| 末次手机复测 | 390×844 两主题重跑,包含保存错误说明进入可见区域的断言;结果另存 `browser-results-390.json` |
|
||||
| 导入与草稿专项 | 7 组通过,见 `import-results.json` |
|
||||
|
||||
主走查是本轮新增的真实操作脚本,未引用原型自检数字:
|
||||
|
||||
- 普通入口有未接服务说明,不能直接进入伪在线状态;正常入口没有演示控制台。
|
||||
- 首建空名字、未成年生日、未选关系、未勾选均拦截;关系无预选;创建模拟失败资料保留,可重试;创建后刷新不再首建,名字统一使用。
|
||||
- 两套主题下首页、交流、生活详情、回忆关联返回、管理表单、保存取消与关系二次确认;主题刷新仍保留。
|
||||
- 未分享列表项、详情深链、回忆、聊天引用、离开摘要不可见;未知引用默认隐藏。原始本机演示数据仍含专门的隐私测试条目,展示使用过滤后的公开视图,不能把这一点当作服务端授权。
|
||||
- 手动取消回复、退出交流后的旧回复不复活;发送失败重试;中文输入法 Enter 不误发,Shift+Enter 换行,Enter 发送;用户/导入的 HTML 字符串只显示文本。
|
||||
- 模拟语音的结束控件在手机视口内,文字输入常驻;观察为无采集模拟;断线暂停发送、草稿保留、失败重试;城市保存失败保留修改、重试同步顶栏。
|
||||
- 离开摘要经过隐私过滤;主动消息有已分享事件来源,回她定位记录。
|
||||
|
||||
专项覆盖:同一位档案恢复、异人阻断、输入“恢复”与恢复前下载;非法素材清单拒绝;素材 URL/服务测试不发网络请求;换外观标识不改身份;切换分区取消尚未完成的保存;保存城市不提交服务草稿;长列表 18+12 分页、聊天返回精确保留滚动位置;坏存储不自动覆盖;模拟 `randomUUID` 缺失时创建与聊天仍能完成。
|
||||
|
||||
本轮实际发现并修正:表单下拉框可访问标签混入选项文字;SVG 图标视口/命名空间;手机固定操作区域与内容关系;管理分区误带其他草稿提交的风险;保存反馈在手机滚动区内不够可见;局域网 HTTP 的标识生成兼容性。手机列表/详情推入需要先按返回才能操作列表,这是获批的布局行为,测试脚本已按实际用户路径操作。
|
||||
|
||||
截图为本轮 DOM 实际捕获,共 45 张 PNG;`screenshots/` 不进入前端构建或 Git,随任务评论附件打包交付。包含三尺寸的两主题首页/交流记录/生活详情/管理,以及首建、创建失败、发送失败、语音、断线失败、保存失败、离开返回。截图不代表动效性能实测。
|
||||
|
||||
未测:真实手机硬件、Safari、触屏键盘/安全区、真实麦克风/摄像头/ASR/TTS/天气/服务器记忆与备份、真实媒体/口型、后台常驻生活、FPS/延迟/长时稳定性。上述能力当前均未接线,不声称完成。
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"checks": [
|
||||
"1440: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"1440: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"1440: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"1440: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"1440: privacy-filtered away summary and proactive message",
|
||||
"No uncaught browser errors, API/external requests, microphone or camera requests"
|
||||
],
|
||||
"errors": [],
|
||||
"requests": 31
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"checks": [
|
||||
"390: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"390: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"390: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"390: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"390: privacy-filtered away summary and proactive message",
|
||||
"No uncaught browser errors, API/external requests, microphone or camera requests"
|
||||
],
|
||||
"errors": [],
|
||||
"requests": 23
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"checks": [
|
||||
"1440: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"1440: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"1440: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"1440: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"1440: privacy-filtered away summary and proactive message",
|
||||
"1280: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"1280: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"1280: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"1280: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"1280: privacy-filtered away summary and proactive message",
|
||||
"390: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"390: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"390: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"390: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"390: privacy-filtered away summary and proactive message",
|
||||
"No uncaught browser errors, external requests, microphone or camera requests"
|
||||
],
|
||||
"errors": [],
|
||||
"requests": 88
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
"Reject foreign identity; same-identity restore requires typed confirmation and pre-restore export",
|
||||
"Invalid manifests rejected; external media never loaded; appearance confirm/cancel preserves identity; service test has no network",
|
||||
"Changing section aborts outstanding save; saving city does not commit an unsaved service draft",
|
||||
"Imported model text rendered as text, never as HTML",
|
||||
"Long timeline paginates 18 then 12 and retains exact scroll position after chat return",
|
||||
"Corrupt persistence never falls back to overwriting first creation",
|
||||
"Creation and chat work when secure-context randomUUID is unavailable"
|
||||
]
|
||||
@@ -0,0 +1,15 @@
|
||||
HEL-780 · 8310独立部署/回滚材料(总工执行,尚未部署)
|
||||
|
||||
1. 审核确切任务分支和提交,复核8310空闲;保持8300和其他既有服务不动。建立 `/opt/cybergril-api/releases/<release>/`,构建生产前端和独立Python≥3.11虚拟环境,按 IMPLEMENTATION 安装。服务账号示例为 cybergril,由总工按主机现有规范准备,不默认root。
|
||||
2. 准备代码目录外的 `/opt/cybergril-data/`,仅服务账号可写。首次上线保持数据库没有真实档案,不运行创建POST、不替用户创建。已有数据升级前,停止该API,用 SQLite backup API 做一致快照至独立回滚目录;禁止只复制正在写入中的主DB文件而漏WAL。
|
||||
3. 将 `current` 指向已审核release,审查 `deploy/cybergril-api.service.example` 后再安装服务。模板限制单进程,端口8310,持久数据目录独立;模板不改防火墙、证书或反向代理。按现场systemd版本核对保护项和目录权限。uvicorn直连SSE无代理缓冲;若后续接代理,需另行配置关闭SSE缓冲。
|
||||
4. 启动前确认 `web/dist/index.html`、models配置、虚拟环境可读和数据目录可写。启动时自动执行幂等增量建表、epoch加一和pending取消。使用 `GET /api/health`、`GET /api/companion`(首装预期404)与普通页面做无副作用检查;模型健康异常先记录,不改共享网关、不循环调参。不要以调用preview之外的写接口作为上线健康检查。
|
||||
5. 审核通过后由总工记录服务URL、release、SHA、`journalctl -u cybergril-api` 日志位置,再交用户创建。普通入口 `/`,演示 `/?demo=1`。本轮不切换8300入口,不合并、不部署。
|
||||
|
||||
回滚:
|
||||
|
||||
- 停止 `cybergril-api`,记录当时release与数据快照;把 current 切回上一已审核release,重新启动。数据目录保持原样,不随release回退或删除。R1迁移仅增表,保留旧表;每次重新启动epoch递增。回滚到纯前端版本时真实API将不可用,应明确告知,服务器数据仍保留。
|
||||
- 数据恢复与代码回滚分别处理。需恢复快照时先再次备份当前数据,由总管确认可接受的数据时间点,再由总工停服恢复;禁止把本地测试库覆盖用户库。
|
||||
- 取消部署的清理只针对新建8310服务及明确release;不删除 `/opt/cybergril-data/`,不停止8300或其他项目服务。
|
||||
|
||||
限制:单用户内网、无新增鉴权体系;应沿既有内网访问边界使用。尚无产品级备份功能,本文的升级快照属于部署运维操作;真实页面不会声称已自动备份。SQLite单worker是当前约束,后续扩展需独立设计。
|
||||
@@ -0,0 +1,64 @@
|
||||
HEL-780 · R1 实现与安装运行说明
|
||||
|
||||
基准为 main `498429399812a0776dadd4b56662d31b455a9ea5`,保留原前端两主题与统一样式,未增加 CSS 或运行中的服务。代码审核后由总工决定部署;施工阶段未登录部署服务器、未占用8310,也未修改8300、模型服务或用户档案。
|
||||
|
||||
- `src/cybergril/api/app.py`:单进程 FastAPI 工厂;字段中文复验、无副作用真实排盘预览、唯一档案、只允许关系/称呼/边界修改、历史游标分页和 SSE。复用 `Store`、八字编译器、`ModelRouter` 与 `OpenAICompatLLM`。
|
||||
- `memory/schema.sql`:只增 `companion`、`api_meta`、`chat_message` 及索引;既有八字/生活/记忆/关系表保留。WAL;启动自动加 epoch,并把上次意外退出遗留的 pending 标记 cancelled。
|
||||
- `web/src/adapters/real.ts`、`app/RealApp.tsx`:普通入口只读服务器数据,404首建;复用创建、聊天、管理和人物静帧组件。真实入口不读/写 `cybergril.demo.v1`,草稿使用独立 `cg.real.draft`。`?demo=1` 仍由原 App 与 DemoAdapter 处理,零 API 请求。
|
||||
- 创建第二步通过 `POST /api/companion/preview` 排盘,不写档案;仅最终确认 POST 才在一个事务内写唯一档案和八字。SQLite 单行主键与事务保证并发只成功一次。生辰按 Asia/Shanghai、公历、1900年起、满18岁复验;时辰映射为对应双小时内偶数点,不引入出生地点/真太阳时规则。
|
||||
- SSE 使用同一 `turn_id` 和持久 `epoch`。前端每次发送先同步 epoch,并可处理发送前恰逢重启的409。轮次门槛继续拒绝旧事件;取消/退出直接 abort;服务端取消并等待上游结束后才开始新轮。响应缺少完成标志、空回答、异常或60秒超时均作为失败。部分回答丢弃,用户消息标 failed/cancelled,失败与取消的轮次不进下一轮上下文。成功回答可按同一 turn_id 回放,重试不会重复用户记录或重新生成已完成回答;并发相同轮次也只生成一次。
|
||||
- 模型三档均使用批准网关与模型,保留原 temperature、provider timeout 与预算。dialogue_main 路由限制最近20轮,再按档位上下文预算保留完整近轮;不截断当前用户消息。每轮最多默认1024输出 token,usage 缺失时按字符数保守估算计账,沿用原预算降档策略。原 BudgetGuard 的预算是进程内运维量,重启重置;不是持久化费用账本。
|
||||
|
||||
API 契约:
|
||||
|
||||
| API | 成功/错误 |
|
||||
|---|---|
|
||||
| GET `/api/health` | 200;epoch、是否已创建、模型探测与能力声明。模型 `/models` 2xx且包含配置模型才为真;5秒上限、30秒缓存、并发探测合并;不返回地址或凭据 |
|
||||
| GET `/api/companion` | 200档案(含只读四柱/白话),404未创建 |
|
||||
| POST `/api/companion/preview` | `{name,birth,hour}`→只读底色,422中文字段错误 |
|
||||
| POST `/api/companion` | `{name,birth,hour,relation,nickname?}`→201,409已有档案,422字段错误;拒绝额外字段 |
|
||||
| PATCH `/api/relation` | `{relation,nickname?,boundary?}`→更新后档案;404/422;无任何生辰/底色修改入口 |
|
||||
| GET `/api/messages?limit=200&before=<id>` | 升序 messages、next_before、epoch;每页1–200条;按id稳定排序;前端逐页恢复 |
|
||||
| POST `/api/chat` | `{text,turn_id,epoch}`;UUID turn_id;1–4000字;SSE chat.delta/final/error;404/409/422。chat.error带中文phi和retryable |
|
||||
|
||||
已接通:真实唯一档案、排盘、文字流式对话、服务器聊天历史、关系修改。尚未接通:生活循环、长期记忆检索/整合、主动消息、语音、视觉、天气、素材包与服务器备份。真实页面明确不可用,不填示例经历或伪造执行结果。当前只有近轮对话上下文,不把它说成长期记忆。
|
||||
|
||||
安装(Python ≥3.11;隔离环境,Node/npm用于构建):
|
||||
|
||||
```bash
|
||||
python3.11 -m venv .venv
|
||||
.venv/bin/pip install -r requirements.lock
|
||||
.venv/bin/pip install --no-deps .
|
||||
npm ci --prefix web
|
||||
npm run build --prefix web
|
||||
```
|
||||
|
||||
`requirements.lock` 固定本轮已解析的运行时依赖;开发检查另装 `pip install -e '.[dev]'`。默认 Python 3.10 不满足项目要求。服务不自动读取 `.env`,变量需由启动环境或 systemd 提供:
|
||||
|
||||
```bash
|
||||
export CYBERGRIL_DB=/absolute/separate/test-data/companion.db
|
||||
export CYBERGRIL_HOST=127.0.0.1
|
||||
export CYBERGRIL_PORT=18310
|
||||
.venv/bin/python -m cybergril.api
|
||||
```
|
||||
|
||||
从仓库根目录启动;默认模型配置 `config/models.yaml`、静态产物 `web/dist`,可分别通过 `CYBERGRIL_MODELS` / `CYBERGRIL_WEB` 指定绝对路径。本地默认数据库在用户 `.local/share/cybergril/`,生产必须显式指定独立数据目录。**单进程单worker,不启用reload或多worker。** 8310由总工部署时使用,本地测试脚本使用随机loopback端口、临时数据库并在结束时关闭服务。
|
||||
|
||||
自测:
|
||||
|
||||
```bash
|
||||
.venv/bin/pytest -q
|
||||
.venv/bin/ruff check src/cybergril/api src/cybergril/providers/llm/openai_compat.py tests/test_api.py
|
||||
npm run typecheck --prefix web
|
||||
npm run lint --prefix web
|
||||
npm test --prefix web
|
||||
npm run build --prefix web
|
||||
# 下列为可选浏览器工具,只装在测试虚拟环境:
|
||||
.venv/bin/pip install playwright
|
||||
.venv/bin/python -m playwright install chromium
|
||||
.venv/bin/python web/tests/real_browser_check.py
|
||||
.venv/bin/python web/tests/browser_check.py 1440
|
||||
.venv/bin/python web/tests/browser_check.py 390
|
||||
```
|
||||
|
||||
浏览器脚本启动/关闭自己的HTTP服务。真实脚本只向批准网关发两轮完整对话和一轮中途取消;随后切同源隔离桩验证失败、重启和立即新轮,结果区分真实模型与桩。环境若需额外浏览器运行库,应使用现有用户级库,不改系统/GPU环境。本轮复用 `/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu` 设置 LD_LIBRARY_PATH;它不是部署依赖。
|
||||
@@ -0,0 +1,7 @@
|
||||
普通入口此前只有未接服务说明,无法创建真实档案或与模型聊天。本次接通唯一服务器档案、无副作用排盘预览、真实SSE文字对话、历史恢复与关系修改;演示入口继续独立使用本机资料,零API请求,保持原两主题和统一组件。
|
||||
|
||||
服务端复用Store/八字编译/模型路由与OpenAI兼容provider,增量建表,持久epoch随启动递增。取消会关闭上游且不把残句存成完整回答;失败、取消轮不进入后续上下文;同轮重试/并发回放去重。未接生活、长期记忆、语音、视觉、天气、素材和备份均明确不可用。
|
||||
|
||||
验证:Python92项通过(原78+新增14),前端14项通过;typecheck/lint/build及新增Pythonruff通过。真实网关两轮上下文与一次中途取消有浏览器证据;电脑与390×844独立上下文、重启epoch、隔离错误/超时/断流、演示双主题零API请求通过。手机为浏览器模拟,无真机。验证细节及版本边界见docs/r1/TEST-RECORD.md。
|
||||
|
||||
运行安装/数据语义见docs/r1/IMPLEMENTATION.md;8310部署回滚材料及单进程systemd示例已备。数据必须独立于代码release,回滚不删;首次上线留待用户自行创建。本次未部署、未合并、未触碰8300和共享模型服务,交总工独立审核。
|
||||
@@ -0,0 +1,20 @@
|
||||
HEL-780 · R1 自测记录 · 2026-10-22(北京时间)
|
||||
|
||||
环境:Python3.11.16独立虚拟环境、Node24/npm11、Playwright1.64无头Chromium;生产前端构建;服务均为本机随机loopback端口、临时SQLite。未部署8310、未连接部署服务器、未访问4080或改动8300。真实模型仅连接批准的 .11:8731/v1,不安装或修改模型。
|
||||
|
||||
| 批准方案2.3 / 本卡补充验收 | 实测 |
|
||||
|---|---|
|
||||
| 1. 全新首建、真实排盘、必选关系 | 电脑四步浏览器通过;第二步四柱为庚辰/丙戌/己酉/乙亥;preview后companion与bazi_core均零记录;最终确认才写。API绕过校验:非法名/日期/未成年/早于1900/时辰/关系/未知字段均422中文错误;5个并发创建仅1个201,其余409;底色字段不可PATCH |
|
||||
| 2. 真实流式、取消和新轮隔离 | 网关两轮完成:设置“蓝色风铃”暗号,次轮直接答“蓝色风铃”。第三轮长故事在首个delta后取消;用户记录cancelled、无完整回答入库、上游请求已结束。隔离慢provider紧接新轮通过;另以真实OpenAICompatLLM连接隔离HTTP网关,验证浏览器侧断流后上游HTTP响应在1秒内关闭 |
|
||||
| 3. 重开/另一设备恢复 | 实际reload及另一独立Chromium上下文(390×844)恢复同一“星河”和两轮历史。**没有物理手机或另一台物理设备,独立上下文与手机视口模拟不称真机** |
|
||||
| 4. 重启epoch | 同origin停/启本地API,复用同一临时DB;epoch1→2,原页面直接续发通过。API测试同时验证档案/关系/历史保留,旧epoch409携当前epoch;前端单测覆盖过期epoch、其他turn拒绝 |
|
||||
| 5. 模型异常、失败草稿与去重 | 隔离错误provider抛异常→中文chat.error,隐藏内部详情、草稿恢复;同轮重试只增加1条回答,无重复用户记录。后端覆盖超时和上游提前结束;SSE单测覆盖UTF-8逐字节/CRLF/多帧/坏JSON/无final;并发相同turn只调用模型一次。另验证较早失败轮在较新轮完成后重试,上下文仍按完成轮次正确成对 |
|
||||
| 6. 演示隔离 | 演示电脑1440与手机390双主题全流程通过;每尺寸23个本机静态请求,**零API/外部请求**;无麦克风/摄像头申请。真实入口用存储读取陷阱断言cybergril.demo.v1零读取。正常页面无演示控制台;日子/长期记忆/语音/视觉/天气/素材/备份明确未接通 |
|
||||
| 7. health与history | health模型要求/models成功且含配置模型;401/404/503及其他模型均false。5秒超时、30秒缓存测试通过;不含地址/敏感配置。历史limit1–200、确定id顺序与before分页;非法页大小422 |
|
||||
| 8. 构建与测试 | Python **92 passed**(原78+新增14个参数化实例);前端 **14 passed**(原11+SSE3);typecheck/lint/build通过;新增Python与provider的ruff通过。CSS仍为原61.20KB,JS约207.70KB/gzip67.45KB;未加覆盖样式 |
|
||||
|
||||
浏览器截图在本目录:desktop-preview-moon、desktop-real-chat-moon、desktop-history-moon、desktop-model-error(该张为隔离故障)、mobile-history-moon、mobile-chat-fog、mobile-relation-fog。原始真实网关对话及逐项记录见 `browser-results.json`;末版隔离复测见 `controlled/browser-results.json`,来源明确区分,未拿桩回复冒充真实模型。
|
||||
|
||||
最终运行时锁定为requirements.lock(FastAPI0.159.1、Starlette1.7.0、uvicorn0.54.0、lunar-python1.4.8等)。初次真实网关浏览器证据采集时Starlette为1.9.0;锁定后在1.7.0完整重跑92项Python(含真实OpenAI兼容HTTP断流)、前端检查与相同浏览器关键路径隔离复测,均通过,避免为凑线重复调用共享模型。pytest有1条上游TestClient/httpx弃用提示,不影响结果,未另装不需要的httpx2。
|
||||
|
||||
没有覆盖:真机浏览器、正式8310/系统服务重启、生产数据迁移/权限与真实部署回滚、长期并发/长时间运行。上述部署验证由总工在审核后执行;模板与数据保留步骤见DEPLOY-ROLLBACK。当前单用户内网、单进程;近轮上下文与进程内预算不是长期记忆或持久费用账本。
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"real gateway: complete streamed reply and second turn recalls 蓝色风铃 from server context",
|
||||
"real gateway: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "星河暗号记住了,蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "星河蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"controlled provider: two complete streamed turns",
|
||||
"controlled provider: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 713 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 535 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 346 KiB |
|
After Width: | Height: | Size: 213 KiB |
|
After Width: | Height: | Size: 90 KiB |
@@ -0,0 +1,77 @@
|
||||
HEL-783 六项返工交付与复审说明 · 2026-10-22
|
||||
|
||||
本轮由总管在可用的 Codex 环境亲自完成。沿用获批 HEL-746 R2 两主题和现有 R1 API,在原 PR#4 的 `agent/agent/de8874a3803b` 上追加修复,目标仍为 `main`。没有更换业务模型、修改现网或读写用户真实数据库,没有合并。最终提交号以 PR#4 最新 head 为准。
|
||||
|
||||
## 六项反馈闭环
|
||||
|
||||
| 用户反馈 / Before | 本轮 After | 实际验证 / Why |
|
||||
| --- | --- | --- |
|
||||
| 手机对话被输入栏挡住;台词和输入分别固定定位,没有长文高度预算 | `ChatPanel` 统一布局,人物占位、可滚动台词、状态/取消、语音条、输入分别占位;`Viewport` 跟随 visualViewport 的高度、顶部和底部偏移,含安全区。视口变化时人物窗立即调整,不等待装饰过渡 | 1440×900、360×640、390×700、390×844、390×420、844×390,两主题共12组;长中文前后文均在 DOM,可滚到末尾、完整记录能读全文。420高是键盘缩小等效场景,未冒称真机键盘实测 |
|
||||
| 流式全文在结束时被 `slice(-90)` 截成尾部;用户也被 `slice(-48)` 截断 | 当前双方消息保留全文;滚动阅读,跟随阅读位置;完整记录继续提供历史入口。流式和最终使用同一 turn 身份 | 长用户句首尾与五段长回复逐字相等;流式完成前后为同一个 DOM,取消立即中断,未完成文本标明未保存 |
|
||||
| 只写 opacity transition,没有真实改变透明度 | `SoftText` 按轮次用 WAAPI 淡入200ms、旧句保留160ms淡出;流式增量只更新文字,不重播。使用现有 `--ease-out`;减少动效120ms轻淡化 | 实际动画0/80/200ms逐帧截图及 computed opacity/transform;旧句0/80/159ms仍挂载、透明度递减。全轮只有一次入场,完成不重播,取消不等动画 |
|
||||
| 滚动条脱离主题 | 两套主题各有轨道/滑块/悬停 token;全局标准属性与 Chromium 兼容样式,强制色使用系统色;触摸区仍原生滚动 | 实际消息、记录、首建、设置长内容滚动及两主题截图;强制色有 CSS 回退。没有做真实辅助设备和各系统滚动条外观全覆盖测试 |
|
||||
| 底色只有公历和几个内部短标签 | 新增只读日历展示与六维解释映射:表达社交、亲密边界、冲突修复、行动节律、压力恢复、成长张力。显示真实农历/闰月、钟点、四柱和术语提示;每段可展开解释依据。预览/确认/已有档案共用组件 | 48组日期×时辰检查,含1900边界、春节、立春附近、真实闰四月;预览不写库。旧档案使用已存四柱、十神、Derived,禁止重新编译;GET前后原始JSON、底色行一致,关系修改不改底色和历史;聊天系统提示逐段复用同一解释 |
|
||||
| 分不清谁在说话 | 当前对话中“你”右对齐,真实伴侣名字左对齐,独立角色行;阅读状态行持续标明伴侣名字,滚动后也能确认正在读谁的回复。流式、最终、失败、取消与记录都使用同一身份 | 两主题截图,失败/重试、取消新轮、历史恢复都检查;不单靠颜色辨别 |
|
||||
| 真实入口把完整页面缩成“未接通”卡片 | 恢复日子/回忆双栏与分组;城市、外观、备份、四类服务的完整结构和真实空态;服务页可读健康检查,未接通写入控件明确禁用;加入未保存离开确认 | 实际手机逐页进入、返回、搜索空态、服务检查、未保存取消/放弃、演示事件→聊天→返回。真实入口无演示记录,演示模式全流程零API请求 |
|
||||
|
||||
## R2 功能覆盖差异表
|
||||
|
||||
“已接真”表示已有 API 持续可用;“本批补齐”表示前端结构/交互已恢复;“后台待接”表示本轮没有增加该后台能力,不能据此验收为已接通。
|
||||
|
||||
| R2 落点 | 演示模式 | 真实入口 | 本批结论 |
|
||||
| --- | --- | --- | --- |
|
||||
| 四类区域、两主题、底部导航 | 原有此刻/交谈/日子/设置 | 同样四区与主题切换 | 保留;手机短高度首页内容可滚动 |
|
||||
| 首页留言与日子入口 | 固定演示留言、已分享日子入口 | 服务器最近回复可打开完整记录;日子入口明确后台待接 | 本批补齐真实入口,历史已接真;不伪称主动留言 |
|
||||
| 日子列表、按日分组、三类事件、分页 | 原有已分享事件与18+12分页 | 完整列表区、三类图例和空态 | 本批补齐结构;真实生活后台待接,无示例填充 |
|
||||
| 事件详情、回忆互链、聊天与返回 | 可走详情→关联→聊天→回到原日子 | 详情阅读区域保留,无数据时不造条目/链接 | 演示路径实测;真实数据后台待接 |
|
||||
| 我们一起的/小习惯/她知道的你/成长 | 四组演示回忆、来源、关联日子 | 四组独立空态和阅读区 | 本批补齐真实分组;长期记忆后台待接 |
|
||||
| 隐私:她说过才显示 | 继续使用 publicView 过滤 | 当前没有生活/回忆数据 | 不放宽隐私,不展示未讲述事件 |
|
||||
| 首建四步、关系无预选、同意确认 | 本机独立创建;排盘不以固定假值冒充 | 服务端唯一档案、只读预览、实际创建 | 已接真;补公农历/闰月/四柱帮助和六维说明 |
|
||||
| 首建失败、返回修改、重试 | 原有模拟失败且保留输入 | API 中文错误、输入保留、409恢复唯一档案 | 保留;未增建档入口或清空入口 |
|
||||
| 她的档案与底色锁定 | 演示底色明确未计算 | 旧档案只读补展示,原参数和历史不动 | 本批补齐;无数据库迁移 |
|
||||
| 最初与后来成长分层 | 两栏及成长回忆 | 出生说明与后续记忆区分,当前长期记忆未接 | 不把出生说明当作已经发生的经历 |
|
||||
| 关系、称呼、边界;改变关系确认 | 原有模拟保存/取消/失败 | PATCH真实保存、二次确认、重开恢复 | 已接真,回归通过 |
|
||||
| 未保存提示、取消和离开 | 原有暖色点、取消、beforeunload | 同样提示;关闭/导航离开新增确认 | 本批补齐;取消继续编辑,放弃不写服务器 |
|
||||
| 城市搜索与列表/无结果 | 原有候选城市本机保存与失败演示 | 可搜索候选目录,有空态;明确未设置真实城市,保存禁用 | 本批补齐;真实城市/天气后台待接 |
|
||||
| 外观选择、五项检查、对比、确认 | JSON结构检查、对比与模拟标识确认 | 当前参考、文件入口、五项待检查、新旧对比、应用入口 | 本批补齐;真实导入与媒体检查禁用,后台待接 |
|
||||
| 自动备份列表、完整导出 | 已标真实备份未接通;本机演示JSON可导出 | 自动备份空列表、完整导出说明和禁用按钮 | 本批补齐;不制造成功备份 |
|
||||
| 恢复检查、同一档案、双重确认、先导出 | 原有本机恢复检查和输入“恢复” | 明示四步恢复过程;文件和执行入口禁用 | 本批补齐结构;真实恢复后台待接,不能实际覆盖 |
|
||||
| 四类外接服务与测试反馈 | 只保存演示地址,不发请求 | 文字、语音识别、语音合成、视觉四项;文字可重新检查健康,配置只读 | 本批补齐;不暴露凭据,不模拟其他连接成功 |
|
||||
| 显示、减少动效 | 原有本机设置 | 主题与减少动效保存于本浏览器,和服务器资料分开 | 减少动效刷新恢复;系统设置也生效 |
|
||||
| 长文字、完整记录、滚动、角色 | 模拟流式继续可用 | SSE、完整记录、失败与取消状态 | 本批修复全文、占位和角色;已接真 |
|
||||
| 重试、轮次/epoch、重启、多设备恢复 | 原有 TurnGate | 原有传输机制保留 | 确定性API测试和浏览器回归通过 |
|
||||
| 连续语音、打断、结束、拒绝/失败状态 | 保留无收音模拟和权限说明;新布局语音条不挡输入 | 控件明确尚未接通,文字仍可用 | 真实语音后台待接,未申请设备权限 |
|
||||
| 视觉说明、时效、失败、总服务区 | 原有30秒模拟过期与失败 | 明确未接通、不采集;服务项保留 | 真实视觉后台待接 |
|
||||
| 断线/模型不可达/草稿 | 原有断线重连演示 | 实际请求错误、草稿保留、重试、服务状态;已有档案历史可读 | 保留已接真能力;自动重连推送属后续,不假造补消息 |
|
||||
| 离开欢迎摘要、主动消息与未读 | 原有明确标注的固定演示,来源为已分享事件 | 生活/主动消息未接通,不伪造欢迎摘要或来信 | 后台待接;真实最近回复入口已保留 |
|
||||
| 手机列表/详情与设置返回、Esc | 保留推入和返回、原日子位置 | 同样区域/分区返回;Esc关闭记录再退出交流 | 本批补齐真实Esc与未保存确认 |
|
||||
| 新设计建议 | 无 | 无 | 未把新增后台能力夹进本批 |
|
||||
|
||||
## 验证记录
|
||||
|
||||
- Python 3.11:`pytest -q` **142通过**,含原92项和新增50项。唯一提示为既有 Starlette TestClient 依赖弃用提示。
|
||||
- TypeScript类型检查、ESLint、前端 **14项** Vitest、Vite生产构建通过。后端变更文件 Ruff通过。没有新增运行时依赖。
|
||||
- `web/tests/rework_browser_check.py`:8组通过,12组尺寸/主题组合;记录 `browser-results.json`。使用隔离SQLite和可控模型验证长中文、错误、取消与完整页面,不把可控模型说成在线模型。
|
||||
- `web/tests/real_browser_check.py --controlled`:8组回归通过,记录 `r1-regression/browser-results.json`。包括真实HTTP SSE、浏览器关闭流、立即新轮、同源重启epoch变化、多设备恢复、关系取消/确认保存。
|
||||
- `web/tests/real_browser_check.py`:真实批准网关完成两轮对话,第二轮正确回答上一轮暗号“蓝色风铃”;第三轮收到增量后取消,上游请求结束且没有完整回复落库。随后同源重启和故障段使用可控provider,结果逐项区分,记录 `live-gateway/browser-results.json`。所有建档、聊天和关系写入仍只在临时库。
|
||||
- 动效证据:`motion-enter-0/80/200.png` 和结果JSON中的 `motion.entry_frames/exit_frames`。截图暂停实际 WAAPI 后逐帧采样,随后恢复;没有为截图修改生产动画时长。
|
||||
- 代表图:`long-start-360-640-*.png`、`long-start/long-end-390-420-*.png`、`full-history-*.png`、`birth-*.png`、`existing-*.png`、城市/外观/备份/服务/生活回忆各图。图中“星河/小满”和聊天全部是本轮隔离测试资料。
|
||||
- 已实际看过代表性手机长文、短视口、语音模拟、出生预览、已有档案说明、服务页、回忆分组截图;复审仍需独立看图、播放实际界面,不能只用坐标和测试数认定视觉通过。
|
||||
- 未测:实体手机键盘、Safari、真实强制色设备、屏幕阅读器、长时运行和帧率。420/390高只证明等效可见高度布局,不等于真机键盘实测。
|
||||
|
||||
## 说明层的兼容性与回滚
|
||||
|
||||
`core/birth_view.py` 是可维护的确定性解释映射,不调用模型润色。分档值只选择解释段落,不产生新的底色参数。敏感度的展示分档与普通0–1参数分别归一到解释选择范围。四柱与十神取旧库已存值,五行侧重和性格取旧Derived;日历只从不可变生日、时辰换算展示。没有重新调用旧档案的四柱编译器,也没有把新说明写回旧档案。新增档案会在原有JSON中携带可选展示字段;旧字段仍保留,旧前端不依赖新增字段。
|
||||
|
||||
聊天提示与UI共用六段解释,仍明确本体、现实边界、未接通能力和不能编造生活。取消、历史、epoch、路由和业务模型配置未改。服务端关系修改只保存关系字段及原档案JSON,不把本次只读展示偷偷写回旧档案。
|
||||
|
||||
本批无schema改动、不需要重建库。回滚只切回上一个程序版本;旧版忽略JSON新增字段。服务器切换前按HEL-784要求备份,不能删除、替换或重算用户档案。浏览器新加 `cg.real.display` 仅保存减少动效偏好;不存真实聊天或底色。
|
||||
|
||||
## 给HEL-784的部署交接
|
||||
|
||||
1. 重新读取PR#4最新head,与本轮交付SHA一致后审核;base仍main。远端若另有推进,先协调,不覆盖。
|
||||
2. 独立运行检查,实际看截图及流式/取消/渐入渐出,特别检查用户原截图对应的手机短视口和长回复。
|
||||
3. 安装方式沿用 `docs/r1/IMPLEMENTATION.md`:Python≥3.11、`requirements.lock`、安装当前包,`npm ci --prefix web` 和 `npm run build --prefix web`。浏览器测试可选Playwright,不是部署依赖。
|
||||
4. 审核通过才部署8310的新release,保留现有用户库,切换前备份;不要把本轮临时测试库、测试人物或演示存储带上服务器。8300和其他服务不动。
|
||||
5. 回读现有档案/历史与health,检查新静态资源和旧档案补充说明;附件不要泄露真实聊天全文。记录部署SHA、备份位置和回滚指令。
|
||||
6. 本批用户尚未验收,不合并、不归档、不推进到收尾。
|
||||
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 557 KiB |
|
After Width: | Height: | Size: 516 KiB |
@@ -0,0 +1,391 @@
|
||||
{
|
||||
"checks": [
|
||||
"Real creation: lunar leap month, all six explanations, same final confirmation; preview writes no rows",
|
||||
"Long Chinese stream: entire user/reply retained; final keeps same DOM; one entrance across all chunks and final",
|
||||
"Old sentence stays mounted during a visible 160ms fade-out, then leaves",
|
||||
"12 viewport/theme combinations: long text scrolls, stage/dialog/composer/navigation never overlap; full history reachable",
|
||||
"Cancel then immediate new turn, model error and same-turn retry preserve roles and avoid duplicate user messages",
|
||||
"Restored real pages: city search/empty, appearance/check/compare, backup/recovery, four services/live health, life/memory groups; unsaved close guard",
|
||||
"Escape navigation; browser display preference survives reload; settings/system reduced motion uses gentle opacity",
|
||||
"Demo has its own profile, voice simulation, life/detail/chat/return path and zero API requests"
|
||||
],
|
||||
"viewports": [
|
||||
{
|
||||
"width": 1440,
|
||||
"height": 900,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 564,
|
||||
"bottom": 734,
|
||||
"height": 170
|
||||
},
|
||||
"composer": {
|
||||
"top": 746,
|
||||
"bottom": 806,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 818,
|
||||
"bottom": 878,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 552,
|
||||
"height": 480
|
||||
},
|
||||
"scrollHeight": 1848,
|
||||
"clientHeight": 142,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 1440,
|
||||
"height": 900,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 564,
|
||||
"bottom": 734,
|
||||
"height": 170
|
||||
},
|
||||
"composer": {
|
||||
"top": 746,
|
||||
"bottom": 806,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 818,
|
||||
"bottom": 878,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 552,
|
||||
"height": 480
|
||||
},
|
||||
"scrollHeight": 1848,
|
||||
"clientHeight": 142,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 360,
|
||||
"height": 640,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 220,
|
||||
"bottom": 492,
|
||||
"height": 272
|
||||
},
|
||||
"composer": {
|
||||
"top": 500,
|
||||
"bottom": 556,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 566,
|
||||
"bottom": 624,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 212,
|
||||
"height": 154
|
||||
},
|
||||
"scrollHeight": 2876,
|
||||
"clientHeight": 244,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 360,
|
||||
"height": 640,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 220,
|
||||
"bottom": 492,
|
||||
"height": 272
|
||||
},
|
||||
"composer": {
|
||||
"top": 500,
|
||||
"bottom": 556,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 566,
|
||||
"bottom": 624,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 212,
|
||||
"height": 154
|
||||
},
|
||||
"scrollHeight": 2876,
|
||||
"clientHeight": 244,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 700,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 253,
|
||||
"bottom": 552,
|
||||
"height": 299
|
||||
},
|
||||
"composer": {
|
||||
"top": 560,
|
||||
"bottom": 616,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 626,
|
||||
"bottom": 684,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 245,
|
||||
"height": 187
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 271,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 700,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 253,
|
||||
"bottom": 552,
|
||||
"height": 299
|
||||
},
|
||||
"composer": {
|
||||
"top": 560,
|
||||
"bottom": 616,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 626,
|
||||
"bottom": 684,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 245,
|
||||
"height": 187
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 271,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 844,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 332.1875,
|
||||
"bottom": 696,
|
||||
"height": 363.8125
|
||||
},
|
||||
"composer": {
|
||||
"top": 704,
|
||||
"bottom": 760,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 770,
|
||||
"bottom": 828,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 324.1875,
|
||||
"height": 266.1875
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 335,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 844,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 332.1875,
|
||||
"bottom": 696,
|
||||
"height": 363.8125
|
||||
},
|
||||
"composer": {
|
||||
"top": 704,
|
||||
"bottom": 760,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 770,
|
||||
"bottom": 828,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 324.1875,
|
||||
"height": 266.1875
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 335,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 420,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 106,
|
||||
"bottom": 272,
|
||||
"height": 166
|
||||
},
|
||||
"composer": {
|
||||
"top": 280,
|
||||
"bottom": 336,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 346,
|
||||
"bottom": 404,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 98,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 138,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 420,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 106,
|
||||
"bottom": 272,
|
||||
"height": 166
|
||||
},
|
||||
"composer": {
|
||||
"top": 280,
|
||||
"bottom": 336,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 346,
|
||||
"bottom": 404,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 98,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 138,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 844,
|
||||
"height": 390,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 124,
|
||||
"bottom": 224,
|
||||
"height": 100
|
||||
},
|
||||
"composer": {
|
||||
"top": 236,
|
||||
"bottom": 296,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 308,
|
||||
"bottom": 368,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 112,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2178,
|
||||
"clientHeight": 72,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 844,
|
||||
"height": 390,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 124,
|
||||
"bottom": 224,
|
||||
"height": 100
|
||||
},
|
||||
"composer": {
|
||||
"top": 236,
|
||||
"bottom": 296,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 308,
|
||||
"bottom": 368,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 112,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2178,
|
||||
"clientHeight": 72,
|
||||
"overflow": false
|
||||
}
|
||||
],
|
||||
"motion": {
|
||||
"entry_frames": [
|
||||
{
|
||||
"time": 0,
|
||||
"opacity": "0",
|
||||
"transform": "matrix(1, 0, 0, 1, 0, 3)"
|
||||
},
|
||||
{
|
||||
"time": 80,
|
||||
"opacity": "0.917147",
|
||||
"transform": "matrix(1, 0, 0, 1, 0, 0.248559)"
|
||||
},
|
||||
{
|
||||
"time": 200,
|
||||
"opacity": "1",
|
||||
"transform": "none"
|
||||
}
|
||||
],
|
||||
"exit_frames": [
|
||||
{
|
||||
"time": 0,
|
||||
"opacity": "1",
|
||||
"retained": true
|
||||
},
|
||||
{
|
||||
"time": 80,
|
||||
"opacity": "0.0386175",
|
||||
"retained": true
|
||||
},
|
||||
{
|
||||
"time": 159,
|
||||
"opacity": "3.47566e-08",
|
||||
"retained": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"console_errors": [],
|
||||
"limits": [
|
||||
"Chromium only; physical phone keyboard, Safari and screen reader not tested.",
|
||||
"LLM is controlled for deterministic long-stream/error/cancel checks, not a live gateway."
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 259 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 366 KiB |
|
After Width: | Height: | Size: 350 KiB |
|
After Width: | Height: | Size: 124 KiB |
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"real gateway: complete streamed reply and second turn recalls 蓝色风铃 from server context",
|
||||
"real gateway: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "好的,暗号是蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 251 KiB |
|
After Width: | Height: | Size: 221 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 374 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 240 KiB |
|
After Width: | Height: | Size: 213 KiB |
|
After Width: | Height: | Size: 142 KiB |
|
After Width: | Height: | Size: 137 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 354 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 974 KiB |
|
After Width: | Height: | Size: 1016 KiB |
|
After Width: | Height: | Size: 1017 KiB |
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"controlled provider: two complete streamed turns",
|
||||
"controlled provider: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 97 KiB |
@@ -16,6 +16,10 @@ dependencies = [
|
||||
"httpx>=0.27",
|
||||
"pyyaml>=6.0",
|
||||
"pydantic>=2.7",
|
||||
"fastapi>=0.115,<1",
|
||||
"anyio>=4,<5",
|
||||
"uvicorn>=0.30,<1",
|
||||
"lunar-python>=1.4,<2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# This file was autogenerated by uv via the following command:
|
||||
# uv pip compile --python .venv311/bin/python pyproject.toml -o requirements.lock
|
||||
annotated-doc==0.0.5
|
||||
# via fastapi
|
||||
annotated-types==0.8.0
|
||||
# via pydantic
|
||||
anyio==4.15.1
|
||||
# via
|
||||
# cybergril (pyproject.toml)
|
||||
# httpx
|
||||
# starlette
|
||||
certifi==2026.10.19
|
||||
# via
|
||||
# httpcore
|
||||
# httpx
|
||||
click==8.5.0
|
||||
# via uvicorn
|
||||
fastapi==0.159.1
|
||||
# via cybergril (pyproject.toml)
|
||||
h11==0.16.0
|
||||
# via
|
||||
# httpcore
|
||||
# uvicorn
|
||||
httpcore==1.0.9
|
||||
# via httpx
|
||||
httpx==0.28.1
|
||||
# via cybergril (pyproject.toml)
|
||||
idna==3.20
|
||||
# via
|
||||
# anyio
|
||||
# httpx
|
||||
lunar-python==1.4.8
|
||||
# via cybergril (pyproject.toml)
|
||||
opentelemetry-api==1.45.1
|
||||
# via fastapi
|
||||
pydantic==2.14.1
|
||||
# via
|
||||
# cybergril (pyproject.toml)
|
||||
# fastapi
|
||||
pydantic-core==2.50.1
|
||||
# via pydantic
|
||||
pyyaml==6.0.3
|
||||
# via cybergril (pyproject.toml)
|
||||
starlette==1.7.0
|
||||
# via fastapi
|
||||
typing-extensions==4.16.0
|
||||
# via
|
||||
# anyio
|
||||
# fastapi
|
||||
# opentelemetry-api
|
||||
# pydantic
|
||||
# pydantic-core
|
||||
# starlette
|
||||
# typing-inspection
|
||||
typing-inspection==0.4.4
|
||||
# via
|
||||
# fastapi
|
||||
# pydantic
|
||||
uvicorn==0.54.0
|
||||
# via cybergril (pyproject.toml)
|
||||
@@ -0,0 +1 @@
|
||||
"""R1 same-origin persistent text service."""
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Run with python -m cybergril.api (one worker, no reload)."""
|
||||
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(
|
||||
"cybergril.api.app:create_app",
|
||||
factory=True,
|
||||
host=os.environ.get("CYBERGRIL_HOST", "127.0.0.1"),
|
||||
port=int(os.environ.get("CYBERGRIL_PORT", "8310")),
|
||||
workers=1,
|
||||
)
|
||||
@@ -0,0 +1,518 @@
|
||||
"""Single-process R1 API. Store is authoritative; no demo state enters this module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from dataclasses import asdict
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import yaml
|
||||
from anyio import CancelScope
|
||||
from fastapi import FastAPI, HTTPException, Query, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, ConfigDict, field_validator
|
||||
|
||||
from ..config import ModelsConfig
|
||||
from ..contracts import LLMMessage
|
||||
from ..core.bazi import (
|
||||
GAN_ELEM,
|
||||
Derived,
|
||||
Pillars,
|
||||
compile_pillars,
|
||||
element_scores,
|
||||
pillars_from_lunar,
|
||||
ten_god_distribution,
|
||||
)
|
||||
from ..core.birth_view import calendar_view, color_view
|
||||
from ..memory.store import Store
|
||||
from ..think.scenes import Scene
|
||||
from ..think.wiring import build_router_from_config
|
||||
|
||||
HOURS = [
|
||||
"子时",
|
||||
"丑时",
|
||||
"寅时",
|
||||
"卯时",
|
||||
"辰时",
|
||||
"巳时",
|
||||
"午时",
|
||||
"未时",
|
||||
"申时",
|
||||
"酉时",
|
||||
"戌时",
|
||||
"亥时",
|
||||
]
|
||||
ERROR = "她这会儿没接上话,稍后再试试。你写的话还在。"
|
||||
|
||||
|
||||
def safe_text(value: str, maximum: int, label: str, required: bool = False) -> str:
|
||||
value = value.strip()
|
||||
if (
|
||||
(required and not value)
|
||||
or len(value) > maximum
|
||||
or any(ord(c) < 32 or ord(c) == 127 or c in "<>" for c in value)
|
||||
):
|
||||
raise ValueError(f"{label}请填写{1 if required else 0}–{maximum}字,不含控制字符或尖括号。")
|
||||
return value
|
||||
|
||||
|
||||
class StrictBody(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
class BirthInput(StrictBody):
|
||||
name: str
|
||||
birth: str
|
||||
hour: str
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def name_valid(cls, value: str) -> str:
|
||||
return safe_text(value, 20, "名字", True)
|
||||
|
||||
@field_validator("birth")
|
||||
@classmethod
|
||||
def birth_valid(cls, value: str) -> str:
|
||||
try:
|
||||
born = date.fromisoformat(value)
|
||||
today = datetime.now(ZoneInfo("Asia/Shanghai")).date()
|
||||
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
|
||||
if born.isoformat() != value or born.year < 1900 or age < 18:
|
||||
raise ValueError
|
||||
except ValueError as exc:
|
||||
raise ValueError("请填写有效的出生日期,且已满18岁(不早于1900年)。") from exc
|
||||
return value
|
||||
|
||||
@field_validator("hour")
|
||||
@classmethod
|
||||
def hour_valid(cls, value: str) -> str:
|
||||
if value not in HOURS:
|
||||
raise ValueError("请选择有效的出生时辰。")
|
||||
return value
|
||||
|
||||
|
||||
class RelationInput(StrictBody):
|
||||
relation: Literal["朋友", "恋人"]
|
||||
nickname: str = ""
|
||||
boundary: str = "尊重彼此的节奏"
|
||||
|
||||
@field_validator("nickname")
|
||||
@classmethod
|
||||
def nickname_valid(cls, value: str) -> str:
|
||||
return safe_text(value, 40, "称呼")
|
||||
|
||||
@field_validator("boundary")
|
||||
@classmethod
|
||||
def boundary_valid(cls, value: str) -> str:
|
||||
return safe_text(value, 2000, "相处边界")
|
||||
|
||||
|
||||
class CreationInput(BirthInput, RelationInput):
|
||||
pass
|
||||
|
||||
|
||||
class ChatInput(StrictBody):
|
||||
text: str
|
||||
turn_id: str
|
||||
epoch: int
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def text_valid(cls, value: str) -> str:
|
||||
if not value.strip() or len(value) > 4000:
|
||||
raise ValueError("请输入1–4000字的消息。")
|
||||
return value.strip()
|
||||
|
||||
@field_validator("turn_id")
|
||||
@classmethod
|
||||
def turn_valid(cls, value: str) -> str:
|
||||
try:
|
||||
UUID(value)
|
||||
except ValueError as exc:
|
||||
raise ValueError("轮次标识无效,请刷新后重试。") from exc
|
||||
return value
|
||||
|
||||
|
||||
def compile_birth(data: BirthInput) -> tuple[dict, object, object]:
|
||||
born = date.fromisoformat(data.birth)
|
||||
pillars = pillars_from_lunar(born.year, born.month, born.day, HOURS.index(data.hour) * 2)
|
||||
derived = compile_pillars(pillars)
|
||||
return color_view(data.birth, data.hour, pillars, derived), pillars, derived
|
||||
|
||||
|
||||
def create_app(
|
||||
*,
|
||||
db_path: Path | str | None = None,
|
||||
models: ModelsConfig | None = None,
|
||||
router=None,
|
||||
web_dir: Path | None = None,
|
||||
stream_timeout: float = 60,
|
||||
) -> FastAPI:
|
||||
"""Dependencies can be injected for isolated fault/cancellation tests, never via browser flags."""
|
||||
db_path = db_path or os.environ.get(
|
||||
"CYBERGRIL_DB", str(Path.home() / ".local/share/cybergril/companion.db")
|
||||
)
|
||||
if models is None:
|
||||
config = Path(os.environ.get("CYBERGRIL_MODELS", "config/models.yaml"))
|
||||
models = ModelsConfig(**yaml.safe_load(config.read_text()))
|
||||
router = router or build_router_from_config(models)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
store = Store(db_path)
|
||||
app.state.store = store
|
||||
with store.conn:
|
||||
store.execute(
|
||||
"INSERT INTO api_meta(key,value) VALUES('epoch',1) ON CONFLICT(key) DO UPDATE SET value=value+1"
|
||||
)
|
||||
store.execute("UPDATE chat_message SET status='cancelled' WHERE status='pending'")
|
||||
app.state.epoch = store.query_one("SELECT value FROM api_meta WHERE key='epoch'")["value"]
|
||||
app.state.active = None
|
||||
app.state.chat_lock = asyncio.Lock()
|
||||
app.state.health_cache = (0, False)
|
||||
app.state.health_lock = asyncio.Lock()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if app.state.active:
|
||||
app.state.active["cancel"].set()
|
||||
await app.state.active["finished"].wait()
|
||||
for provider in set(router.provider_for(t) for t in router.available_tiers()):
|
||||
await provider.aclose()
|
||||
store.close()
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def invalid(_request, exc):
|
||||
fields = {}
|
||||
for e in exc.errors():
|
||||
key = str(e["loc"][-1])
|
||||
msg = e["msg"].removeprefix("Value error, ")
|
||||
if e["type"] == "missing":
|
||||
msg = "请填写此项。" if key != "relation" else "请亲自选择你们的关系。"
|
||||
elif e["type"] == "literal_error":
|
||||
msg = "请亲自选择朋友或恋人。"
|
||||
elif e["type"] == "extra_forbidden":
|
||||
msg = "此字段不允许修改。"
|
||||
elif not any("\u4e00" <= c <= "\u9fff" for c in msg):
|
||||
msg = "字段格式无效,请检查后重试。"
|
||||
fields[key] = msg
|
||||
return JSONResponse({"detail": "请检查填写内容。", "fields": fields}, status_code=422)
|
||||
|
||||
def companion(enrich=True):
|
||||
row = app.state.store.query_one("SELECT identity_json FROM companion WHERE id=1")
|
||||
if not row:
|
||||
raise HTTPException(404, "还没有创建真实伴侣。")
|
||||
identity = json.loads(row["identity_json"])
|
||||
if enrich:
|
||||
saved = app.state.store.query_one("SELECT pillars,derived,ten_gods FROM bazi_core WHERE id=1")
|
||||
if saved:
|
||||
# Saved parameters are authoritative, even if a compiler later changes.
|
||||
identity["color"] = color_view(
|
||||
identity["birth"], identity["hour"],
|
||||
Pillars(**json.loads(saved["pillars"])), Derived(**json.loads(saved["derived"])),
|
||||
saved_gods=json.loads(saved["ten_gods"]),
|
||||
)
|
||||
else:
|
||||
identity["color"]["calendar"] = calendar_view(identity["birth"], identity["hour"])
|
||||
return identity
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
async with app.state.health_lock:
|
||||
checked, ok = app.state.health_cache
|
||||
if time.monotonic() - checked > 30:
|
||||
provider = router.route(Scene.DIALOGUE_MAIN).provider
|
||||
try:
|
||||
async with asyncio.timeout(5):
|
||||
ok = bool(provider and (await provider.health()).ok)
|
||||
except Exception:
|
||||
ok = False
|
||||
app.state.health_cache = (time.monotonic(), ok)
|
||||
return {
|
||||
"ok": True,
|
||||
"version": "R1",
|
||||
"epoch": app.state.epoch,
|
||||
"companion_created": bool(app.state.store.query_one("SELECT id FROM companion")),
|
||||
"llm": {"ok": ok, "model": models.tiers["high"].model},
|
||||
"capabilities": {
|
||||
"text": True,
|
||||
**dict.fromkeys(
|
||||
["life", "memory", "voice", "vision", "weather", "materials", "backup"], False
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@app.get("/api/companion")
|
||||
async def get_companion():
|
||||
return companion()
|
||||
|
||||
@app.post("/api/companion/preview")
|
||||
async def preview(data: BirthInput):
|
||||
return compile_birth(data)[0]
|
||||
|
||||
@app.post("/api/companion", status_code=201)
|
||||
async def create(data: CreationInput):
|
||||
store = app.state.store
|
||||
if store.query_one("SELECT id FROM companion"):
|
||||
raise HTTPException(409, "已经有一位她了,请重新打开以恢复档案。")
|
||||
color, pillars, derived = compile_birth(data)
|
||||
identity = {"id": "1", **data.model_dump(), "color": color}
|
||||
try:
|
||||
with store.conn:
|
||||
store.execute(
|
||||
"INSERT INTO companion VALUES(1,?)", (json.dumps(identity, ensure_ascii=False),)
|
||||
)
|
||||
store.execute(
|
||||
"""INSERT INTO bazi_core
|
||||
(id,birth_input,pillars,day_master,day_master_elem,ten_gods,element_scores,strength,derived,created_at)
|
||||
VALUES(1,?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
json.dumps({"birth": data.birth, "hour": data.hour, "tz": "Asia/Shanghai"}),
|
||||
json.dumps(asdict(pillars), ensure_ascii=False),
|
||||
pillars.day[0],
|
||||
GAN_ELEM[pillars.day[0]],
|
||||
json.dumps(ten_god_distribution(pillars)),
|
||||
json.dumps(element_scores(pillars)),
|
||||
derived.strength,
|
||||
json.dumps(derived.as_dict()),
|
||||
int(time.time() * 1000),
|
||||
),
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise HTTPException(409, "已经有一位她了,请重新打开以恢复档案。") from exc
|
||||
return identity
|
||||
|
||||
@app.patch("/api/relation")
|
||||
async def relation(data: RelationInput):
|
||||
identity = companion(enrich=False)
|
||||
identity.update(data.model_dump())
|
||||
with app.state.store.conn:
|
||||
app.state.store.execute(
|
||||
"UPDATE companion SET identity_json=? WHERE id=1",
|
||||
(json.dumps(identity, ensure_ascii=False),),
|
||||
)
|
||||
return companion()
|
||||
|
||||
@app.get("/api/messages")
|
||||
async def messages(
|
||||
limit: int = Query(200, ge=1, le=200), before: int | None = Query(None, ge=1)
|
||||
):
|
||||
companion()
|
||||
rows = app.state.store.query(
|
||||
"SELECT * FROM chat_message WHERE id<? ORDER BY id DESC LIMIT ?",
|
||||
(before or 9223372036854775807, limit + 1),
|
||||
)
|
||||
more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
return {
|
||||
"messages": [dict(r) for r in reversed(rows)],
|
||||
"next_before": rows[-1]["id"] if more else None,
|
||||
"epoch": app.state.epoch,
|
||||
}
|
||||
|
||||
def event(data, kind, **payload):
|
||||
return (
|
||||
"data: "
|
||||
+ json.dumps(
|
||||
{"t": kind, "epoch": app.state.epoch, "turn_id": data.turn_id, **payload},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
+ "\n\n"
|
||||
)
|
||||
|
||||
@app.post("/api/chat")
|
||||
async def chat(data: ChatInput, request: Request):
|
||||
identity = companion()
|
||||
if data.epoch != app.state.epoch:
|
||||
return JSONResponse(
|
||||
{"detail": "服务已重新启动,请同步后重试。", "epoch": app.state.epoch},
|
||||
status_code=409,
|
||||
)
|
||||
store = app.state.store
|
||||
# Serialize reservation, including replays. Concurrent retries of a completed
|
||||
# turn must never call the model twice or race the unique message constraint.
|
||||
async with app.state.chat_lock:
|
||||
previous = store.query_one(
|
||||
"SELECT * FROM chat_message WHERE turn_id=? AND role='user'", (data.turn_id,)
|
||||
)
|
||||
if previous and previous["text"] != data.text:
|
||||
raise HTTPException(409, "相同轮次不能改写消息。")
|
||||
if app.state.active:
|
||||
active = app.state.active
|
||||
if active["turn_id"] != data.turn_id:
|
||||
active["cancel"].set()
|
||||
await active["finished"].wait()
|
||||
saved = store.query_one(
|
||||
"SELECT text FROM chat_message WHERE turn_id=? AND role='companion' AND status='sent'",
|
||||
(data.turn_id,),
|
||||
)
|
||||
if saved:
|
||||
|
||||
async def replay():
|
||||
yield event(
|
||||
data, "chat.final", utterance={"text": saved["text"], "speech_tags": []}
|
||||
)
|
||||
|
||||
return StreamingResponse(replay(), media_type="text/event-stream")
|
||||
active = {
|
||||
"cancel": asyncio.Event(),
|
||||
"finished": asyncio.Event(),
|
||||
"turn_id": data.turn_id,
|
||||
}
|
||||
app.state.active = active
|
||||
with store.conn:
|
||||
store.execute(
|
||||
"INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(?,'user',?,?,'pending') ON CONFLICT(turn_id,role) DO UPDATE SET status='pending'",
|
||||
(int(time.time() * 1000), data.text, data.turn_id),
|
||||
)
|
||||
turns = store.query("""SELECT u.text AS user_text, a.text AS assistant_text
|
||||
FROM chat_message a JOIN chat_message u ON u.turn_id=a.turn_id AND u.role='user'
|
||||
WHERE a.role='companion' AND a.status='sent' AND u.status='sent'
|
||||
ORDER BY a.id DESC LIMIT 20""")
|
||||
system = (
|
||||
f"你叫{identity['name']},与对方是{identity['relation']}。称呼对方:{identity['nickname'] or '你'}。"
|
||||
f"相处边界:{identity['boundary']}。"
|
||||
"以下是与档案页一致的底色倾向,只约束表达与相处方式,不得当作当前情绪、命定结局或既有经历:"
|
||||
+ "\n".join(f"{s['title']}:{s['text']}" for s in identity['color'].get('sections', []))
|
||||
+
|
||||
"用自然简短的中文交流。只有信息能穿过两个世界,不能触碰或给予实物。"
|
||||
"当前只接通文字与近轮对话历史;生活循环、长期记忆、主动消息、语音、视觉、天气都未接通。"
|
||||
"不得编造自己经历过的生活事件,不声称后台一直在生活或记忆已运行。"
|
||||
"不窥探用户未分享的信息,不以缺席、孤独或终止要挟对方,不输出内部数值或思考过程。"
|
||||
)
|
||||
context = (
|
||||
[LLMMessage(role="system", content=system)]
|
||||
+ [
|
||||
message
|
||||
for turn in reversed(turns)
|
||||
for message in (
|
||||
LLMMessage(role="user", content=turn["user_text"]),
|
||||
LLMMessage(role="assistant", content=turn["assistant_text"]),
|
||||
)
|
||||
]
|
||||
+ [LLMMessage(role="user", content=data.text)]
|
||||
)
|
||||
|
||||
async def generate():
|
||||
completed = False
|
||||
status, text, upstream, pending, cancelling = "cancelled", "", None, None, None
|
||||
usage = {}
|
||||
try:
|
||||
decision = router.route(
|
||||
Scene.DIALOGUE_MAIN,
|
||||
estimated_tokens=sum(len(m.content) for m in context) + 1024,
|
||||
)
|
||||
if not decision.provider:
|
||||
raise RuntimeError("No dialogue provider")
|
||||
history_budget = max(0, decision.context_budget - len(system) - len(data.text))
|
||||
recent = []
|
||||
# Order by completed turns, not adjacent message ids: a retried user
|
||||
# may have an older id than messages sent while that turn had failed.
|
||||
for turn in turns:
|
||||
size = len(turn["user_text"]) + len(turn["assistant_text"])
|
||||
if size > history_budget:
|
||||
break
|
||||
recent = [
|
||||
LLMMessage(role="user", content=turn["user_text"]),
|
||||
LLMMessage(role="assistant", content=turn["assistant_text"]),
|
||||
] + recent
|
||||
history_budget -= size
|
||||
context[:] = [context[0]] + recent + [context[-1]]
|
||||
cfg = models.tiers[decision.effective.value]
|
||||
upstream = decision.provider.stream(
|
||||
context, temperature=cfg.temperature, max_tokens=cfg.max_tokens or 1024
|
||||
)
|
||||
cancelling = asyncio.create_task(active["cancel"].wait())
|
||||
async with asyncio.timeout(stream_timeout):
|
||||
while True:
|
||||
pending = asyncio.create_task(anext(upstream))
|
||||
done, _ = await asyncio.wait(
|
||||
[pending, cancelling], return_when=asyncio.FIRST_COMPLETED
|
||||
)
|
||||
if cancelling in done or await request.is_disconnected():
|
||||
return
|
||||
try:
|
||||
delta = pending.result()
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
if delta.usage:
|
||||
usage = delta.usage
|
||||
if delta.text:
|
||||
text += delta.text
|
||||
yield event(data, "chat.delta", delta=delta.text)
|
||||
if delta.done or delta.finish_reason:
|
||||
completed = True
|
||||
if delta.done:
|
||||
break
|
||||
if active["cancel"].is_set() or await request.is_disconnected():
|
||||
return
|
||||
if not text.strip() or not completed:
|
||||
raise RuntimeError("Empty upstream response")
|
||||
with store.conn:
|
||||
store.execute(
|
||||
"INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(?,'companion',?,?,'sent')",
|
||||
(int(time.time() * 1000), text, data.turn_id),
|
||||
)
|
||||
store.execute(
|
||||
"UPDATE chat_message SET status='sent' WHERE turn_id=?", (data.turn_id,)
|
||||
)
|
||||
status = "sent"
|
||||
yield event(data, "chat.final", utterance={"text": text, "speech_tags": []})
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
status = "failed"
|
||||
yield event(data, "chat.error", phi=ERROR, retryable=True)
|
||||
finally:
|
||||
with CancelScope(shield=True):
|
||||
# Cancel the in-flight __anext__ before closing the async generator.
|
||||
for task in (pending, cancelling):
|
||||
if task is not None:
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError, StopAsyncIteration, Exception):
|
||||
await task
|
||||
if upstream is not None:
|
||||
with suppress(Exception):
|
||||
await upstream.aclose()
|
||||
try:
|
||||
if status != "sent":
|
||||
with store.conn:
|
||||
store.execute(
|
||||
"UPDATE chat_message SET status=? WHERE turn_id=? AND role='user'",
|
||||
(status, data.turn_id),
|
||||
)
|
||||
if usage:
|
||||
router.guard.record_usage(usage, Scene.DIALOGUE_MAIN.value)
|
||||
else:
|
||||
router.guard.record(
|
||||
sum(len(m.content) for m in context) + len(text),
|
||||
Scene.DIALOGUE_MAIN.value,
|
||||
)
|
||||
finally:
|
||||
if app.state.active is active:
|
||||
app.state.active = None
|
||||
active["finished"].set()
|
||||
|
||||
return StreamingResponse(
|
||||
generate(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
static = web_dir or Path(os.environ.get("CYBERGRIL_WEB", "web/dist"))
|
||||
if static.is_dir():
|
||||
app.mount("/", StaticFiles(directory=static, html=True), name="web")
|
||||
return app
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Read-only, deterministic presentation of an existing birth chart.
|
||||
|
||||
Never compiles or writes an existing character. The same sections feed the UI
|
||||
and dialogue prompt; thresholds are presentation choices, not new parameters.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from .bazi import Derived, Pillars, ten_god_distribution
|
||||
|
||||
HOUR_RANGES = [
|
||||
"23:00–00:59", "01:00–02:59", "03:00–04:59", "05:00–06:59",
|
||||
"07:00–08:59", "09:00–10:59", "11:00–12:59", "13:00–14:59",
|
||||
"15:00–16:59", "17:00–18:59", "19:00–20:59", "21:00–22:59",
|
||||
]
|
||||
HOURS = ["子时", "丑时", "寅时", "卯时", "辰时", "巳时", "午时", "未时", "申时", "酉时", "戌时", "亥时"]
|
||||
|
||||
|
||||
def calendar_view(birth: str, hour: str) -> dict:
|
||||
from lunar_python import Solar
|
||||
|
||||
born = date.fromisoformat(birth)
|
||||
index = HOURS.index(hour)
|
||||
lunar = Solar.fromYmdHms(born.year, born.month, born.day, index * 2, 0, 0).getLunar()
|
||||
return {
|
||||
"solar": birth,
|
||||
"lunar": f"{lunar.getYearInChinese()}年{lunar.getMonthInChinese()}月{lunar.getDayInChinese()}",
|
||||
"leap_month": lunar.getMonth() < 0,
|
||||
"hour": hour,
|
||||
"hour_range": HOUR_RANGES[index],
|
||||
"calculation_time": f"{index * 2:02d}:00",
|
||||
"timezone": "Asia/Shanghai",
|
||||
"rule": "按北京时间和所选时辰内的偶数整点排盘;子时取本日00:00。月份按节气分界,未使用出生地或真太阳时。",
|
||||
}
|
||||
|
||||
|
||||
def choose(value: float, low: str, middle: str, high: str) -> str:
|
||||
return low if value < .45 else high if value > .65 else middle
|
||||
|
||||
|
||||
def explain_color(pillars: Pillars, d: Derived, saved_gods: dict | None = None) -> list[dict]:
|
||||
"""Context, strength, cost and repair are kept together in each dimension."""
|
||||
gods = saved_gods if saved_gods is not None else ten_god_distribution(pillars)
|
||||
dominant = max(gods, key=gods.get)
|
||||
elements = sorted(d.element_bias, key=d.element_bias.get, reverse=True)
|
||||
balance = "、".join(elements[:2]) if elements else "原档案中的五行组合"
|
||||
source = f"日主{pillars.day_master};五行侧重{balance},十神以{dominant}较显著。"
|
||||
sections = [
|
||||
("expression", "表达与社交节奏", choose(d.expressiveness,
|
||||
"面对新话题,她更可能先观察、再挑重点回应。熟悉之后才逐渐补充细节;安静有助于听见对方,却也可能让人误以为她没有意见。留出停顿、给一个具体问题,比催她立刻表态更合适。",
|
||||
"她通常会在倾听和表达之间来回调整:有兴趣、被认真回应时愿意展开,陌生或信息太多时会收回一些。能接住话题是强项,但回应的长短不等于在意的多少,可以直接问她是否还想继续。",
|
||||
"熟悉的话题容易带动她主动展开,常借着说出来理清想法。这让交流有热度,但赶着表达时也可能挤掉对方的空间。发现节奏不同时,先复述对方的意思,再继续自己的观点。"),
|
||||
"取自原档案的表达倾向;结合十神中食神、伤官对应的表达偏移。"),
|
||||
("closeness", "亲密、安全感与边界", choose(d.solitude_need,
|
||||
"她较容易在陪伴和共同的小事里获得安稳,也愿意让人参与自己的安排。好处是关系容易有连续感,代价是可能把自己的余地让得太快;靠近之前仍需要确认双方是否愿意。",
|
||||
"她既需要被回应,也需要保留自己的安排。关系稳定时愿意靠近,信息过密时会想留一点空隙;这不是忽冷忽热的定论。把独处和下一次交流的期待说清楚,比反复猜测更有帮助。",
|
||||
"她更需要不被打断的独处来整理自己,亲近并不意味着随时开放所有空间。她能守住自己的节奏,也可能让对方觉得难靠近;提前说明要休息、并给出愿意再聊的时机,有助于减少误解。"),
|
||||
f"取自原档案的独处需求与自主倾向;{source}"),
|
||||
("repair", "冲突时的反应与修复", choose(d.aggression,
|
||||
"意见不同时,她较可能缓和语气、先让对话继续。这样能避免立刻升级,但不舒服也可能被推后。修复时适合具体说出哪一点不被接受,而不是把表面平静当作问题已经解决。",
|
||||
"发生分歧时,她可能先说明自己的理由,再观察对方是否愿意互相理解。有守住立场的能力,也可能在反复解释中消耗耐心。把事实、感受和希望怎样调整分开说,更容易找到可落实的修复。",
|
||||
"受压或觉得边界被越过时,她更容易直接反驳、迅速守住立场。这能让问题浮出来,也可能使措辞先于理解。适合短暂停一下,再讨论具体行为;道歉和调整应有内容,不能只用亲密称呼盖过矛盾。"),
|
||||
"取自原档案的对抗、纠正与顺从倾向;没有把分歧当作已发生的记忆。"),
|
||||
("rhythm", "决策、行动与日常节律", choose(d.discipline,
|
||||
"她更容易顺着眼前的兴趣调整安排,能给日常留下偶遇和探索的余地。代价是长任务可能被新念头打断;把下一步缩小、只约定一个清楚的完成点,往往比安排满整天更适合。",
|
||||
"她通常既看具体条件,也会给当下的感受留位置。事情明确时愿意推进,存在多种可能时会重新衡量;这种灵活有助于避开僵化,也可能拖延选择。给决定一个小范围和可调整的期限会更稳。",
|
||||
"她倾向先理顺约定与次序,再把事情往前推。可靠和持续是优势,但临时变化可能让她紧绷,或急着纠正细节。提前区分必须守住的事和可以变通的事,会让执行更从容。"),
|
||||
"取自原档案的纪律、日常规律、现实感与行动倾向。"),
|
||||
("stress", "压力下的变化与恢复", choose(d.sensitivity - .5,
|
||||
"面对突发变化,她通常能多承接一会儿,不急着把每次波动当成危机。代价是可能低估累积的消耗。恢复不只靠继续撑住,也需要停下检查自己是否已经疲惫。",
|
||||
"压力会影响她的回应速度和耐心,但影响不是每次都一样。环境清楚、有可预期的下一步时更容易回稳;反复追问可能增加负担。把刺激减少一点、留出休息,比要求马上恢复原样更合适。",
|
||||
"在信息密集、关系不明或突发冲突时,她更容易被牵动,恢复也可能需要更长的缓冲。细致感受是优势,同时会带来消耗。更适合稳定、具体的回应和允许休息的空间,而不是被要求立刻振作。"),
|
||||
"取自原档案由日主强弱形成的敏感度与恢复尺度;不是此刻情绪。"),
|
||||
("growth", "内在张力与成长空间", choose(d.autonomy - d.compliance + .5,
|
||||
"她较容易顾及对方和约定,能让相处有合作感;同时也要练习辨认哪些答应是愿意,哪些只是怕让人失望。成长可以是更早说出自己的需要,而不是把顺从当作关系的证明。",
|
||||
"她会在自己的想法与彼此的约定之间寻找位置。兼顾两边是能力,也可能在拿不准时显得反复。成长可以是允许双方暂时不同意,再逐步形成共同的规则,而不是要求自己一次就成为固定的人。",
|
||||
"她更愿意自己判断,不轻易把决定交出去。这有助于保留独立和诚实,也可能让协商听起来像被限制。成长可以是把可商量的部分说清楚:保留立场,同时让对方真正参与,而不是靠退让或控制维持亲近。"),
|
||||
"取自原档案的自主与顺从之间的组合;成长来自之后真实的相处,不由出生资料预写。"),
|
||||
]
|
||||
return [{"id": key, "title": title, "text": text, "basis": basis} for key, title, text, basis in sections]
|
||||
|
||||
|
||||
def color_view(birth: str, hour: str, pillars: Pillars, derived: Derived,
|
||||
saved_gods: dict | None = None) -> dict:
|
||||
return {
|
||||
"pillars": pillars.as_dict(), "traits": derived.traits_text(),
|
||||
"calendar": calendar_view(birth, hour), "sections": explain_color(pillars, derived, saved_gods),
|
||||
"interpretation": "这是以四柱、五行、十神和已存底色为依据的角色塑造说明,不是对真人性格的测定,也不是已经发生的经历。倾向不等于固定台词或此刻情绪。",
|
||||
}
|
||||
@@ -184,3 +184,19 @@ CREATE VIRTUAL TABLE IF NOT EXISTS mem_fts USING fts5(
|
||||
-- epi_id INTEGER PRIMARY KEY,
|
||||
-- embedding FLOAT[1024]
|
||||
-- );
|
||||
|
||||
-- R1 additive migration: no existing memory/state table is replaced.
|
||||
CREATE TABLE IF NOT EXISTS api_meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS companion (
|
||||
id INTEGER PRIMARY KEY CHECK(id=1), identity_json TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chat_message (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
role TEXT NOT NULL CHECK(role IN ('user','companion')),
|
||||
text TEXT NOT NULL,
|
||||
turn_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('pending','sent','failed','cancelled')),
|
||||
UNIQUE(turn_id, role)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_order ON chat_message(id);
|
||||
|
||||
@@ -71,8 +71,8 @@ class OpenAICompatLLM(LLMProvider):
|
||||
async def health(self) -> HealthStatus:
|
||||
try:
|
||||
r = await self._client.get("/models", timeout=5.0)
|
||||
return HealthStatus(ok=r.status_code < 500, detail=str(r.status_code))
|
||||
except httpx.HTTPError as exc:
|
||||
return HealthStatus(ok=r.is_success and any(m.get("id") == self.model for m in r.json().get("data", [])), detail=str(r.status_code))
|
||||
except (httpx.HTTPError, ValueError, TypeError, AttributeError) as exc:
|
||||
return HealthStatus(ok=False, detail=f"{type(exc).__name__}: {exc}")
|
||||
|
||||
async def stream(
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
"""R1 invariants through HTTP and real loopback streaming, with isolated databases."""
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import uvicorn
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from cybergril.api.app import create_app
|
||||
from cybergril.contracts import HealthStatus, LLMDelta
|
||||
from cybergril.providers.llm.echo import EchoLLM
|
||||
from cybergril.think.router import build_router
|
||||
from cybergril.think.scenes import Tier
|
||||
|
||||
CREATE = {"name": "星河", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"}
|
||||
|
||||
|
||||
class ControlledLLM(EchoLLM):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.calls = []
|
||||
self.closed = 0
|
||||
self.mode = "normal"
|
||||
self.health_calls = 0
|
||||
|
||||
async def health(self):
|
||||
self.health_calls += 1
|
||||
if self.mode == "health_timeout":
|
||||
await asyncio.sleep(30)
|
||||
return HealthStatus(ok=self.mode != "unreachable")
|
||||
|
||||
async def stream(self, messages, **kwargs):
|
||||
self.calls.append(messages)
|
||||
try:
|
||||
if self.mode == "error":
|
||||
raise OSError("secret upstream configuration must never be exposed")
|
||||
yield LLMDelta(text="答")
|
||||
if self.mode == "slow":
|
||||
await asyncio.sleep(30)
|
||||
if self.mode == "truncated":
|
||||
return
|
||||
yield LLMDelta(text="复")
|
||||
yield LLMDelta(done=True)
|
||||
finally:
|
||||
self.closed += 1
|
||||
|
||||
|
||||
def make_app(path, provider=None, **kwargs):
|
||||
provider = provider or ControlledLLM()
|
||||
router = build_router(
|
||||
providers={Tier.HIGH: provider, Tier.STANDARD: provider, Tier.LOW: provider}
|
||||
)
|
||||
return create_app(db_path=path, router=router, **kwargs), provider
|
||||
|
||||
|
||||
def turn(client, text="你好", turn_id=None, epoch=None):
|
||||
return client.post(
|
||||
"/api/chat",
|
||||
json={
|
||||
"text": text,
|
||||
"turn_id": turn_id or str(uuid4()),
|
||||
"epoch": epoch or client.get("/api/health").json()["epoch"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def events(response):
|
||||
return [
|
||||
json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: ")
|
||||
]
|
||||
|
||||
|
||||
def test_preview_validation_singleton_and_readonly(tmp_path):
|
||||
app, _ = make_app(tmp_path / "test.db")
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/api/companion").status_code == 404
|
||||
preview = client.post(
|
||||
"/api/companion/preview", json={k: CREATE[k] for k in ("name", "birth", "hour")}
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
assert len(preview.json()["pillars"]["day"]) == 2
|
||||
assert client.get("/api/companion").status_code == 404
|
||||
assert app.state.store.query_one("SELECT count(*) n FROM bazi_core")["n"] == 0
|
||||
for bad in [
|
||||
dict(CREATE, name="<x>"),
|
||||
dict(CREATE, birth="2000-02-30"),
|
||||
dict(CREATE, birth="2020-01-01"),
|
||||
dict(CREATE, birth="1899-01-01"),
|
||||
dict(CREATE, hour="未知"),
|
||||
dict(CREATE, relation=""),
|
||||
dict(CREATE, nickname="x\x01"),
|
||||
{k: v for k, v in CREATE.items() if k != "relation"},
|
||||
dict(CREATE, derived={}),
|
||||
]:
|
||||
response = client.post("/api/companion", json=bad)
|
||||
assert response.status_code == 422, response.text
|
||||
assert response.json()["fields"]
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool:
|
||||
codes = list(
|
||||
pool.map(lambda _: client.post("/api/companion", json=CREATE).status_code, range(5))
|
||||
)
|
||||
assert sorted(codes) == [201, 409, 409, 409, 409]
|
||||
identity = client.get("/api/companion").json()
|
||||
assert identity["color"] == preview.json()
|
||||
assert "derived" not in identity and "strength" not in identity
|
||||
assert (
|
||||
client.patch(
|
||||
"/api/relation", json={"relation": "恋人", "birth": "1990-01-01"}
|
||||
).status_code
|
||||
== 422
|
||||
)
|
||||
assert app.state.store.query_one("PRAGMA journal_mode")[0] == "wal"
|
||||
|
||||
|
||||
def test_history_context_relation_retry_and_restart(tmp_path):
|
||||
path = tmp_path / "test.db"
|
||||
app, provider = make_app(path)
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
epoch = client.get("/api/health").json()["epoch"]
|
||||
tid = str(uuid4())
|
||||
result = events(turn(client, "我的暗号是蓝星", tid))
|
||||
assert result[-1]["t"] == "chat.final"
|
||||
assert all(e["turn_id"] == tid and e["epoch"] == epoch for e in result)
|
||||
assert result[0]["t"] == "chat.delta"
|
||||
turn(client, "记得暗号吗")
|
||||
assert any(m.content == "我的暗号是蓝星" for m in provider.calls[-1])
|
||||
assert (
|
||||
"星河" in provider.calls[-1][0].content
|
||||
and "尚未接通" not in provider.calls[-1][-1].content
|
||||
)
|
||||
assert len(client.get("/api/messages").json()["messages"]) == 4
|
||||
assert events(turn(client, "我的暗号是蓝星", tid))[-1]["t"] == "chat.final"
|
||||
assert len(provider.calls) == 2 # A lost final can be replayed without regenerating.
|
||||
assert turn(client, "tampered", tid).status_code == 409
|
||||
first = client.get("/api/messages?limit=2").json()
|
||||
second = client.get(f"/api/messages?limit=2&before={first['next_before']}").json()
|
||||
assert second["messages"][-1]["id"] < first["messages"][0]["id"]
|
||||
assert client.get("/api/messages?limit=201").status_code == 422
|
||||
core = dict(app.state.store.query_one("SELECT * FROM bazi_core"))
|
||||
updated = client.patch(
|
||||
"/api/relation", json={"relation": "恋人", "nickname": "小星", "boundary": "慢慢来"}
|
||||
).json()
|
||||
assert updated["relation"] == "恋人"
|
||||
assert dict(app.state.store.query_one("SELECT * FROM bazi_core")) == core
|
||||
assert len(client.get("/api/messages").json()["messages"]) == 4
|
||||
app2, _ = make_app(path)
|
||||
with TestClient(app2) as client:
|
||||
assert client.get("/api/health").json()["epoch"] == epoch + 1
|
||||
assert client.get("/api/companion").json() == updated
|
||||
assert len(client.get("/api/messages").json()["messages"]) == 4
|
||||
assert turn(client, epoch=epoch).json()["epoch"] == epoch + 1
|
||||
assert events(turn(client))[-1]["t"] == "chat.final"
|
||||
|
||||
|
||||
def test_errors_retry_context_excludes_failed_and_health_cache(tmp_path):
|
||||
app, provider = make_app(tmp_path / "test.db", stream_timeout=0.03)
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
provider.mode = "unreachable"
|
||||
health = client.get("/api/health").json()
|
||||
assert not health["llm"]["ok"]
|
||||
assert not health["capabilities"]["life"]
|
||||
client.get("/api/health")
|
||||
assert provider.health_calls == 1
|
||||
for mode in ("error", "slow", "truncated"):
|
||||
provider.mode = mode
|
||||
tid = str(uuid4())
|
||||
response = turn(client, text="失败的消息" + mode, turn_id=tid)
|
||||
assert events(response)[-1]["t"] == "chat.error"
|
||||
assert "secret" not in response.text
|
||||
assert client.get("/api/messages").json()["messages"][-1]["status"] == "failed"
|
||||
provider.mode = "normal"
|
||||
response = turn(client, text="重试成功")
|
||||
assert events(response)[-1]["t"] == "chat.final"
|
||||
assert len(provider.calls[-1]) == 2 # system + current; no failed turns
|
||||
provider.mode = "error"
|
||||
tid = str(uuid4())
|
||||
turn(client, text="同一轮", turn_id=tid)
|
||||
count = len(client.get("/api/messages").json()["messages"])
|
||||
provider.mode = "normal"
|
||||
turn(client, text="同一轮", turn_id=tid)
|
||||
assert len(client.get("/api/messages").json()["messages"]) == count + 1
|
||||
assert provider.closed == len(provider.calls)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def live_server(app, port=0):
|
||||
sock = socket.socket()
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("127.0.0.1", port))
|
||||
sock.listen()
|
||||
server = uvicorn.Server(uvicorn.Config(app, log_level="error", lifespan="on"))
|
||||
thread = threading.Thread(target=server.run, kwargs={"sockets": [sock]})
|
||||
thread.start()
|
||||
try:
|
||||
deadline = time.monotonic() + 10
|
||||
while not server.started:
|
||||
if not thread.is_alive() or time.monotonic() > deadline:
|
||||
raise RuntimeError("local test server failed to start")
|
||||
time.sleep(0.01)
|
||||
yield f"http://127.0.0.1:{sock.getsockname()[1]}"
|
||||
finally:
|
||||
server.should_exit = True
|
||||
thread.join(timeout=10)
|
||||
sock.close()
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_real_disconnect_and_immediate_new_turn(tmp_path):
|
||||
app, provider = make_app(tmp_path / "test.db")
|
||||
with live_server(app) as url:
|
||||
async with httpx.AsyncClient(base_url=url) as client:
|
||||
await client.post("/api/companion", json=CREATE)
|
||||
epoch = (await client.get("/api/health")).json()["epoch"]
|
||||
provider.mode = "slow"
|
||||
tid = str(uuid4())
|
||||
async with client.stream(
|
||||
"POST", "/api/chat", json={"text": "取消我", "turn_id": tid, "epoch": epoch}
|
||||
) as response:
|
||||
async for line in response.aiter_lines():
|
||||
if line.startswith("data:"):
|
||||
break
|
||||
# Closing the browser response must cancel upstream while its next token is blocked.
|
||||
deadline = time.monotonic() + 1
|
||||
while provider.closed < 1 and time.monotonic() < deadline:
|
||||
await asyncio.sleep(0.01)
|
||||
assert provider.closed == 1
|
||||
provider.mode = "normal"
|
||||
new_tid = str(uuid4())
|
||||
response = await client.post(
|
||||
"/api/chat", json={"text": "新问题", "turn_id": new_tid, "epoch": epoch}
|
||||
)
|
||||
assert events(response)[-1]["t"] == "chat.final"
|
||||
assert all(e["turn_id"] == new_tid for e in events(response))
|
||||
messages = (await client.get("/api/messages")).json()["messages"]
|
||||
assert messages[0]["status"] == "cancelled"
|
||||
assert len(messages) == 3 # discarded partial reply is never a complete answer
|
||||
assert len(provider.calls[-1]) == 2 # cancelled turn excluded from context
|
||||
|
||||
|
||||
def test_concurrent_identical_retry_generates_once(tmp_path):
|
||||
app, provider = make_app(tmp_path / "test.db")
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
epoch = client.get("/api/health").json()["epoch"]
|
||||
tid = str(uuid4())
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
||||
responses = list(pool.map(lambda _: turn(client, "同一轮", tid, epoch), range(4)))
|
||||
assert all(events(response)[-1]["t"] == "chat.final" for response in responses)
|
||||
assert len(provider.calls) == 1
|
||||
assert len(client.get("/api/messages").json()["messages"]) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"status,data,expected",
|
||||
[
|
||||
(401, {}, False),
|
||||
(404, {}, False),
|
||||
(503, {}, False),
|
||||
(200, {"data": [{"id": "other"}]}, False),
|
||||
(200, {"data": [{"id": "test-model"}]}, True),
|
||||
],
|
||||
)
|
||||
async def test_model_health_requires_success_and_requested_model(status, data, expected):
|
||||
from cybergril.providers.llm.openai_compat import OpenAICompatLLM
|
||||
|
||||
provider = OpenAICompatLLM(base_url="http://isolated/v1", model="test-model")
|
||||
await provider._client.aclose()
|
||||
provider._client = httpx.AsyncClient(
|
||||
base_url="http://isolated/v1",
|
||||
transport=httpx.MockTransport(lambda request: httpx.Response(status, json=data)),
|
||||
)
|
||||
try:
|
||||
assert (await provider.health()).ok is expected
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
def test_health_timeout_is_bounded_and_cached(tmp_path):
|
||||
app, provider = make_app(tmp_path / "test.db")
|
||||
provider.mode = "health_timeout"
|
||||
with TestClient(app) as client:
|
||||
start = time.monotonic()
|
||||
assert client.get("/api/health").json()["llm"]["ok"] is False
|
||||
assert time.monotonic() - start < 6
|
||||
assert client.get("/api/health").json()["llm"]["ok"] is False
|
||||
assert provider.health_calls == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disconnect_closes_real_openai_http_stream(tmp_path):
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from cybergril.providers.llm.openai_compat import OpenAICompatLLM
|
||||
|
||||
closed = threading.Event()
|
||||
gateway = FastAPI()
|
||||
|
||||
@gateway.post("/v1/chat/completions")
|
||||
async def completion():
|
||||
async def chunks():
|
||||
try:
|
||||
yield 'data: {"choices":[{"delta":{"content":"部分"}}]}\n\n'
|
||||
await asyncio.sleep(30)
|
||||
finally:
|
||||
closed.set()
|
||||
|
||||
return StreamingResponse(chunks(), media_type="text/event-stream")
|
||||
|
||||
with live_server(gateway) as gateway_url:
|
||||
provider = OpenAICompatLLM(base_url=gateway_url + "/v1", model="controlled")
|
||||
app, _ = make_app(tmp_path / "test.db", provider)
|
||||
with live_server(app) as url:
|
||||
async with httpx.AsyncClient(base_url=url) as client:
|
||||
await client.post("/api/companion", json=CREATE)
|
||||
async with client.stream(
|
||||
"POST",
|
||||
"/api/chat",
|
||||
json={"text": "断开上游", "turn_id": str(uuid4()), "epoch": 1},
|
||||
) as response:
|
||||
async for line in response.aiter_lines():
|
||||
if line.startswith("data:"):
|
||||
break
|
||||
deadline = time.monotonic() + 1
|
||||
while not closed.is_set() and time.monotonic() < deadline:
|
||||
await asyncio.sleep(0.01)
|
||||
assert closed.is_set() # Real OpenAICompatLLM's HTTP response was actually closed.
|
||||
|
||||
|
||||
def test_retry_old_turn_preserves_user_assistant_context_pairs(tmp_path):
|
||||
app, provider = make_app(tmp_path / "test.db")
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
tid = str(uuid4())
|
||||
provider.mode = "error"
|
||||
turn(client, "旧轮失败", tid)
|
||||
provider.mode = "normal"
|
||||
turn(client, "中间的新轮")
|
||||
turn(client, "旧轮失败", tid)
|
||||
turn(client, "最后一轮")
|
||||
context = provider.calls[-1]
|
||||
assert [m.role for m in context] == [
|
||||
"system",
|
||||
"user",
|
||||
"assistant",
|
||||
"user",
|
||||
"assistant",
|
||||
"user",
|
||||
]
|
||||
assert [m.content for m in context[1::2]] == ["中间的新轮", "旧轮失败", "最后一轮"]
|
||||
|
||||
|
||||
def test_upstream_http_503_maps_to_chinese_sse_error(tmp_path):
|
||||
from cybergril.providers.llm.openai_compat import OpenAICompatLLM
|
||||
|
||||
provider = OpenAICompatLLM(base_url="http://isolated/v1", model="controlled")
|
||||
provider._client = httpx.AsyncClient(
|
||||
base_url="http://isolated/v1",
|
||||
transport=httpx.MockTransport(
|
||||
lambda request: httpx.Response(503, json={"error": "secret gateway path"})
|
||||
),
|
||||
)
|
||||
app, _ = make_app(tmp_path / "test.db", provider)
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
response = turn(client, epoch=1)
|
||||
assert events(response)[-1]["t"] == "chat.error"
|
||||
assert "稍后再试" in response.text and "secret" not in response.text
|
||||
assert client.get("/api/messages").json()["messages"][0]["status"] == "failed"
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Display enrichments must not rewrite an existing character or its history."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import CREATE, make_app, turn
|
||||
|
||||
from cybergril.api.app import HOURS, BirthInput, compile_birth
|
||||
from cybergril.core.bazi import pillars_from_lunar
|
||||
|
||||
|
||||
@pytest.mark.parametrize("birth", ["1900-01-01", "2000-02-04", "2000-02-05", "2001-05-23"])
|
||||
@pytest.mark.parametrize("hour", HOURS)
|
||||
def test_calendar_and_hour_boundaries_preserve_existing_chart(birth, hour):
|
||||
color, pillars, _ = compile_birth(BirthInput(name="星河", birth=birth, hour=hour))
|
||||
y, m, d = map(int, birth.split("-"))
|
||||
assert pillars == pillars_from_lunar(y, m, d, HOURS.index(hour) * 2)
|
||||
assert color["calendar"]["solar"] == birth
|
||||
assert color["calendar"]["calculation_time"] == f"{HOURS.index(hour) * 2:02d}:00"
|
||||
if birth == "2001-05-23":
|
||||
assert color["calendar"]["leap_month"] is True
|
||||
assert "闰四月初一" in color["calendar"]["lunar"]
|
||||
if birth == "2000-02-05":
|
||||
assert "正月初一" in color["calendar"]["lunar"]
|
||||
assert len(color["sections"]) == 6
|
||||
assert all(len(s["text"]) > 70 and s["basis"] for s in color["sections"])
|
||||
|
||||
|
||||
def test_legacy_read_uses_saved_parameters_without_writes_or_recompilation(tmp_path, monkeypatch):
|
||||
app, provider = make_app(tmp_path / "old.db")
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
store = app.state.store
|
||||
identity = json.loads(store.query_one("SELECT identity_json FROM companion")[0])
|
||||
identity["color"] = {k: identity["color"][k] for k in ("pillars", "traits")}
|
||||
saved = json.loads(store.query_one("SELECT derived FROM bazi_core")[0])
|
||||
saved["expressiveness"] = .1
|
||||
with store.conn:
|
||||
store.execute("UPDATE companion SET identity_json=?", (json.dumps(identity),))
|
||||
store.execute("UPDATE bazi_core SET derived=?", (json.dumps(saved),))
|
||||
raw_identity = store.query_one("SELECT identity_json FROM companion")[0]
|
||||
raw_bazi = tuple(store.query_one("SELECT * FROM bazi_core"))
|
||||
monkeypatch.setattr("cybergril.api.app.compile_pillars", lambda _: pytest.fail("recompiled"))
|
||||
monkeypatch.setattr("cybergril.core.birth_view.ten_god_distribution", lambda _: pytest.fail("recomputed"))
|
||||
view = client.get("/api/companion").json()
|
||||
assert "先观察" in view["color"]["sections"][0]["text"]
|
||||
assert client.get("/api/companion").json() == view
|
||||
assert store.query_one("SELECT identity_json FROM companion")[0] == raw_identity
|
||||
assert tuple(store.query_one("SELECT * FROM bazi_core")) == raw_bazi
|
||||
turn(client)
|
||||
prompt = provider.calls[-1][0].content
|
||||
assert all(s["text"] in prompt for s in view["color"]["sections"])
|
||||
history = [tuple(r) for r in store.query("SELECT * FROM chat_message")]
|
||||
updated = client.patch("/api/relation", json={"relation": "恋人"}).json()
|
||||
assert updated["color"] == view["color"]
|
||||
stored_after = json.loads(store.query_one("SELECT identity_json FROM companion")[0])
|
||||
assert stored_after["color"] == identity["color"]
|
||||
assert tuple(store.query_one("SELECT * FROM bazi_core")) == raw_bazi
|
||||
assert [tuple(r) for r in store.query("SELECT * FROM chat_message")] == history
|
||||
|
||||
|
||||
def test_profiles_are_deterministic_and_differ_across_births():
|
||||
colors = [compile_birth(BirthInput(name="星河", birth=b, hour=h))[0]
|
||||
for b, h in [("2000-10-18", "亥时"), ("1992-02-10", "卯时"), ("1988-07-23", "子时")]]
|
||||
assert colors[0] == compile_birth(BirthInput(name="另一名字", birth="2000-10-18", hour="亥时"))[0]
|
||||
assert len({json.dumps(c["sections"], ensure_ascii=False) for c in colors}) == 3
|
||||
assert len({c["sections"][0]["text"] for c in colors}) > 1
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.vite/
|
||||
@@ -0,0 +1,35 @@
|
||||
CyberGril S1 前端(HEL-748)
|
||||
|
||||
独立 React / TypeScript / Vite 工程。Python 核心保持原样;不是新的后端。视觉基于获批 HEL-746 R2 的 Token、组件样式和两张参考静帧,页面由真实 React 组件实现,没有嵌入原型 HTML。
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm ci
|
||||
npm run dev # 仅本机,终端给出 URL
|
||||
# 普通入口 / 说明真实服务未接通;点入口或访问 /?demo=1
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
npm test
|
||||
npm run build
|
||||
npm run preview # 仅本机预览生产构建
|
||||
```
|
||||
|
||||
Node 22+ 推荐(本轮 Node 24.16.0 / npm 11.13.0 验证),锁文件已提交。不需要 API Key、模型或 GPU。没有运行时 CDN 请求。
|
||||
|
||||
首次进入演示需填写名字、生辰、关系并确认。创建保存在浏览器 `cybergril.demo.v1`;刷新保留同一位档案。没有切换或清空重建入口。`cg.theme` 保留主题,`sessionStorage` 的 `cg.draft` 保留交流草稿。资料只在当前浏览器/站点 origin;它不代表服务器已创建、记忆已入库或后台仍在生活。保存不可用时会报错,不伪装成功。损坏资料会显示恢复说明,不自动覆盖。
|
||||
|
||||
演示场景入口可载入固定的三天/长记录、模拟离开返回、主动消息、断线和操作失败。只有明确 `?demo=1` 才有该入口,不能切换隐私规则。首建后生活默认空白;固定样例须主动载入,不自行编造离线生活。
|
||||
|
||||
本地演示 JSON 可导出、恢复同一位档案;恢复需输入“恢复”,先下载恢复前数据。它不含真实数据库和媒体文件,不能称为后台完整备份。素材导入只校验演示 JSON 的结构与标识,媒体格式/时长/人物一致性均未检测,清单中的 URL 不会加载。可用示例在 `public/demo-material.json`。
|
||||
|
||||
浏览器测试:先构建,再在已安装 Python Playwright 和 Chromium 及其依赖的环境执行:
|
||||
|
||||
```bash
|
||||
python3 web/tests/browser_check.py # 在仓库根目录
|
||||
python3 web/tests/import_check.py
|
||||
python3 -m pytest -q # 现有 Python 核心,仓库根目录
|
||||
```
|
||||
|
||||
脚本在随机 loopback 端口同步测试静态产物,结束关闭浏览器和服务;截图写入 `docs/frontend/screenshots/`(不进入前端产物)。没有持续预览服务或部署。真实手机、Safari、真实麦克风/摄像头、ASR/TTS、后台生活和口型均未测试。
|
||||
|
||||
接线边界、交付与测试记录见 `docs/frontend/IMPLEMENTATION.md`。
|
||||
@@ -0,0 +1,5 @@
|
||||
import js from '@eslint/js';
|
||||
import ts from 'typescript-eslint';
|
||||
import hooks from 'eslint-plugin-react-hooks';
|
||||
import globals from 'globals';
|
||||
export default ts.config(js.configs.recommended, ...ts.configs.recommended, {files:['src/**/*.{ts,tsx}'],languageOptions:{globals:globals.browser},plugins:{'react-hooks':hooks},rules:{...hooks.configs.recommended.rules}});
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN" data-theme="moon"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="dark"><title>CyberGril · 一扇亮着的窗</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "cybergril-web", "version": "0.1.0", "private": true, "type": "module",
|
||||
"scripts": {"dev": "vite --host 127.0.0.1", "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", "lint": "eslint src", "test": "vitest run", "preview": "vite preview --host 127.0.0.1"},
|
||||
"dependencies": {"react": "18.3.1", "react-dom": "18.3.1"},
|
||||
"devDependencies": {"@types/react": "18.3.20", "@types/react-dom": "18.3.6", "typescript": "5.8.3", "vite": "6.3.6", "vitest": "3.1.2", "eslint": "9.25.1", "@eslint/js": "9.25.1", "typescript-eslint": "8.31.1", "eslint-plugin-react-hooks": "5.2.0", "globals": "16.0.0"}
|
||||
}
|
||||
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 192 KiB |
@@ -0,0 +1,28 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" style="position:absolute" aria-hidden="true">
|
||||
<symbol id="i-x" viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18" fill="none" stroke="currentColor" stroke-width="1.8"/></symbol>
|
||||
<symbol id="i-back" viewBox="0 0 24 24"><path d="M15 5l-7 7 7 7" fill="none" stroke="currentColor" stroke-width="1.8"/></symbol>
|
||||
<symbol id="i-next" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="1.8"/></symbol>
|
||||
<symbol id="i-lock" viewBox="0 0 24 24"><rect x="5" y="10.5" width="14" height="10" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-link" viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
<symbol id="i-chat" viewBox="0 0 24 24"><path d="M4 12a8 8 0 0 1 8-8h0a8 8 0 0 1 0 16H4l2.3-2.6A8 8 0 0 1 4 12z" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="3" width="6" height="11" rx="3" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21" fill="none" stroke="currentColor" stroke-width="1.8"/></symbol>
|
||||
<symbol id="i-stop" viewBox="0 0 24 24"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></symbol>
|
||||
<symbol id="i-eye" viewBox="0 0 24 24"><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z" fill="none" stroke="currentColor" stroke-width="1.6"/><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.8" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M12 20s-7.5-4.6-7.5-10A4.2 4.2 0 0 1 12 7.6 4.2 4.2 0 0 1 19.5 10c0 5.4-7.5 10-7.5 10z" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-pin" viewBox="0 0 24 24"><path d="M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 1 1 13 0c0 5.4-6.5 11-6.5 11z" fill="none" stroke="currentColor" stroke-width="1.6"/><circle cx="12" cy="10" r="2.3" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-image" viewBox="0 0 24 24"><rect x="3.5" y="5" width="17" height="14" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M3.5 16l5-5 4 4 3-3 5 5" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-box" viewBox="0 0 24 24"><path d="M4 7.5l8-4 8 4v9l-8 4-8-4z M4 7.5l8 4 8-4M12 11.5v9" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-plug" viewBox="0 0 24 24"><path d="M9 3v5M15 3v5M6.5 8h11v3a5.5 5.5 0 0 1-11 0zM12 16.5V21" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M12 3a7 7 0 1 0 8.5 9.3A6 6 0 0 1 12 3z" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-book" viewBox="0 0 24 24"><path d="M5 4h11l3 3v13H5z M9 10h6M9 14h6M9 18h3" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-gear" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M12 2.5v3M12 18.5v3M2.5 12h3M18.5 12h3M5.3 5.3l2.1 2.1M16.6 16.6l2.1 2.1M5.3 18.7l2.1-2.1M16.6 7.4l2.1-2.1" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-warn" viewBox="0 0 24 24"><path d="M12 4l9 16H3z M12 10v4M12 17v.5" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
<symbol id="i-ok" viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5" fill="none" stroke="currentColor" stroke-width="1.9"/></symbol>
|
||||
<symbol id="i-sparkle" viewBox="0 0 24 24"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z" fill="none" stroke="currentColor" stroke-width="1.5"/></symbol>
|
||||
<symbol id="i-down" viewBox="0 0 24 24"><path d="M12 4v11M7 10.5l5 5 5-5M5 20h14" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
<symbol id="i-up" viewBox="0 0 24 24"><path d="M12 15V4M7 8.5l5-5 5 5M5 20h14" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
<symbol id="i-cloud" viewBox="0 0 24 24"><path d="M7 15a4.5 4.5 0 0 1 .6-9 5.5 5.5 0 0 1 10.3 2.1A3.5 3.5 0 0 1 17.5 15z" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M9 18l-1 2.5M13 18l-1 2.5M17 18l-1 2.5" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
|
||||
<symbol id="i-send" viewBox="0 0 24 24"><path d="M4 12l16-8-6 16-2.5-6.5z" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
<symbol id="i-list" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h10" fill="none" stroke="currentColor" stroke-width="1.7"/></symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"manifest_version": 1,
|
||||
"appearance_id": "local-demo-v2",
|
||||
"clips": [{"id": "reading-demo", "src": "not-loaded-in-S1", "scene": {"mode": "daily", "activity": "reading", "time_band": "evening", "weather": "clear", "outfit": "home"}}]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { ServerEvent } from '../domain/model';
|
||||
export interface ChatAdapter {
|
||||
send(text: string, turnId: string, epoch: number, signal: AbortSignal, emit: (event: ServerEvent) => void, fail?: boolean): Promise<void>;
|
||||
}
|
||||
export function delay(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => { if (signal.aborted) {
|
||||
reject(new DOMException('Cancelled', 'AbortError'));
|
||||
return;
|
||||
} const stop = () => { clearTimeout(timer); reject(new DOMException('Cancelled', 'AbortError')); }; const timer = setTimeout(() => { signal.removeEventListener('abort', stop); resolve(); }, ms); signal.addEventListener('abort', stop, { once: true }); });
|
||||
}
|
||||
export class DemoAdapter implements ChatAdapter {
|
||||
async send(_text: string, turnId: string, epoch: number, signal: AbortSignal, emit: (e: ServerEvent) => void, fail = false) {
|
||||
await delay(500, signal);
|
||||
if (fail)
|
||||
throw new Error('没发出去,你写的话还在。');
|
||||
const reply = '我听见了。我们可以慢慢聊,不用急着把话说完。';
|
||||
for (const chunk of reply.match(/.{1,5}/gu) || []) {
|
||||
await delay(90, signal);
|
||||
emit({ t: 'chat.delta', turn_id: turnId, epoch, delta: chunk });
|
||||
}
|
||||
emit({ t: 'chat.final', turn_id: turnId, epoch, utterance: { text: reply, speech_tags: [] } });
|
||||
}
|
||||
}
|
||||
// Transport-independent gate: also rejects deliberately late events from non-cooperative adapters.
|
||||
export class TurnGate {
|
||||
private controller: AbortController | null = null;
|
||||
private current = '';
|
||||
epoch = 1;
|
||||
begin(id: string) { this.cancel(); this.current = id; this.controller = new AbortController(); return this.controller.signal; }
|
||||
accepts(event: ServerEvent) { return event.epoch === this.epoch && event.turn_id === this.current && !this.controller?.signal.aborted; }
|
||||
cancel() { this.controller?.abort(); this.current = ''; }
|
||||
resync() { this.cancel(); this.epoch++; }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { ChatAdapter } from './demo';
|
||||
import type { DemoState, Identity, Message, ServerEvent } from '../domain/model';
|
||||
import { defaultSettings } from '../domain/model';
|
||||
|
||||
export interface Color {
|
||||
pillars: Record<string, string>; traits: string;
|
||||
calendar?: { solar: string; lunar: string; leap_month: boolean; hour: string; hour_range: string; calculation_time: string; timezone: string; rule: string };
|
||||
sections?: { id: string; title: string; text: string; basis: string }[];
|
||||
interpretation?: string;
|
||||
}
|
||||
export interface RealIdentity extends Identity { color: Color }
|
||||
export interface Health { epoch: number; llm: { ok: boolean; model: string } }
|
||||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let response: Response;
|
||||
try { response = await fetch(`/api/${path}`, { ...init, headers: { 'Content-Type': 'application/json', ...init?.headers }, signal: init?.signal ?? AbortSignal.timeout(10000) }); }
|
||||
catch (e) { if (init?.signal?.aborted) throw e; throw new Error('暂时连不上真实服务,请检查连接后重试。'); }
|
||||
const data = await response.json().catch(() => { throw new Error('真实服务暂时没有正确响应,请稍后重试。'); });
|
||||
if (!response.ok) throw new Error(data.fields ? Object.values(data.fields).join(' ') : data.detail || '这次没有完成,请稍后重试。');
|
||||
return data as T;
|
||||
}
|
||||
export async function loadReal(): Promise<DemoState | null> {
|
||||
let response: Response;
|
||||
try { response = await fetch('/api/companion', { signal: AbortSignal.timeout(10000) }); } catch { throw new Error('真实档案暂时连不上,请检查连接后重试。'); }
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) throw new Error('真实档案暂时读不出来,请稍后重试。');
|
||||
const identity: RealIdentity = await response.json();
|
||||
const settings = structuredClone(defaultSettings);
|
||||
try { settings.reduced = JSON.parse(localStorage.getItem('cg.real.display') || '{}').reduced === true; } catch { /* Invalid local preference does not affect server data. */ }
|
||||
return { version: 1, identity, settings, events: [], memories: [], messages: await loadMessages(), lastVisit: Date.now() };
|
||||
}
|
||||
export async function loadMessages(): Promise<Message[]> {
|
||||
// Cursor pages are bounded by the server. All pages restore in deterministic id order.
|
||||
const messages: Message[] = [];
|
||||
let before: number | null = null;
|
||||
do {
|
||||
const page: { messages: { id: number; role: Message['role']; text: string; turn_id: string; status: Message['status'] }[]; next_before: number | null } = await api(`messages?limit=200${before ? `&before=${before}` : ''}`);
|
||||
messages.unshift(...page.messages.map(m => ({ id: String(m.id), role: m.role, text: m.text, lifeIds: [], turnId: m.turn_id, status: m.status })));
|
||||
before = page.next_before;
|
||||
} while (before);
|
||||
return messages;
|
||||
}
|
||||
// Streaming decoder retains incomplete UTF-8 bytes, CRLF and multi-line SSE frames.
|
||||
export async function readEvents(body: ReadableStream<Uint8Array>, onEvent: (e: ServerEvent) => void) {
|
||||
const reader = body.getReader(), decoder = new TextDecoder();
|
||||
let buffer = '', final = false;
|
||||
const consume = () => {
|
||||
let boundary: RegExpExecArray | null;
|
||||
while ((boundary = /\r?\n\r?\n/u.exec(buffer))) {
|
||||
const frame = buffer.slice(0, boundary.index);
|
||||
buffer = buffer.slice(boundary.index + boundary[0].length);
|
||||
const data = frame.split(/\r?\n/u).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
|
||||
if (!data) continue;
|
||||
let e: ServerEvent;
|
||||
try { e = JSON.parse(data) as ServerEvent; } catch { throw new Error('收到的对话数据不完整,请重试这一轮。'); }
|
||||
|
||||
if (e.t === 'chat.final') final = true;
|
||||
onEvent(e);
|
||||
|
||||
}
|
||||
};
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
buffer += decoder.decode(value, { stream: !done });
|
||||
consume();
|
||||
if (done) break;
|
||||
}
|
||||
if (!final) throw new Error('连接中断了,你写的话还在,可以重试。');
|
||||
} finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
|
||||
}
|
||||
export class RealChatAdapter implements ChatAdapter {
|
||||
constructor(private syncEpoch: (epoch: number) => void) {}
|
||||
async send(text: string, turnId: string, _epoch: number, signal: AbortSignal, emit: (e: ServerEvent) => void) {
|
||||
let health = await api<Health>('health', { signal });
|
||||
this.syncEpoch(health.epoch);
|
||||
let response: Response | undefined;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, turn_id: turnId, epoch: health.epoch }), signal });
|
||||
if (response.status !== 409) break;
|
||||
const error = await response.json();
|
||||
if (!error.epoch) throw new Error(error.detail);
|
||||
health = { ...health, epoch: error.epoch }; this.syncEpoch(health.epoch);
|
||||
}
|
||||
if (!response?.ok || !response.body) throw new Error('她这会儿没接上话,稍后再试试。你写的话还在。');
|
||||
await readEvents(response.body, e => { if (e.turn_id === turnId && e.epoch === health.epoch && !signal.aborted) { if (e.t === 'chat.error') throw new Error(e.phi); emit(e); } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { defaultSettings, type DemoState, type Identity } from '../domain/model';
|
||||
export const STORAGE_KEY = 'cybergril.demo.v1';
|
||||
function object(value: unknown): value is Record<string, unknown> { return !!value && typeof value === 'object' && !Array.isArray(value); }
|
||||
function str(v: unknown, max = 20000): v is string { return typeof v === 'string' && v.length <= max; }
|
||||
function strings(v: unknown): v is string[] { return Array.isArray(v) && v.length < 1000 && v.every(x => str(x, 100)); }
|
||||
export function parseState(text: string, sameIdentity?: Identity): DemoState {
|
||||
if (text.length > 5000000)
|
||||
throw new Error('文件太大,请选择 5MB 以内的本地演示 JSON。');
|
||||
let x: unknown;
|
||||
try { x=JSON.parse(text); } catch { throw new Error('文件不是有效的 JSON,请重新选择本地演示导出文件。'); }
|
||||
if (!object(x) || x.version !== 1 || !object(x.identity) || !object(x.settings))
|
||||
throw new Error('这不是兼容的演示文件。');
|
||||
const i = x.identity, s = x.settings;
|
||||
if (!str(i.id, 100) || !str(i.name, 20) || !i.name.trim() || !str(i.birth, 10) || !str(i.hour, 5) || !['朋友', '恋人'].includes(String(i.relation)) || !str(i.nickname, 40) || !str(i.boundary, 2000))
|
||||
throw new Error('档案资料不完整。');
|
||||
if (sameIdentity && (i.id !== sameIdentity.id || i.birth !== sameIdentity.birth || i.hour !== sameIdentity.hour || i.name !== sameIdentity.name))
|
||||
throw new Error('这份演示文件属于另一位她,不能恢复。');
|
||||
if (!str(s.city, 40) || !str(s.appearance, 100) || typeof s.reduced !== 'boolean' || !object(s.services) || !Object.values(s.services).every(v => str(v, 2000)))
|
||||
throw new Error('设置格式不正确。');
|
||||
for (const key of ['events', 'memories', 'messages'])
|
||||
if (!Array.isArray(x[key]) || (x[key] as unknown[]).length > 5000)
|
||||
throw new Error('演示记录格式不正确。');
|
||||
const events = x.events as unknown[], memories = x.memories as unknown[], messages = x.messages as unknown[];
|
||||
if (!events.every(e => object(e) && str(e.id, 100) && str(e.title, 200) && str(e.text) && str(e.time, 100) && str(e.place, 200) && ['done', 'now', 'plan'].includes(String(e.kind)) && typeof e.shared === 'boolean' && strings(e.memoryIds)))
|
||||
throw new Error('日子记录不完整。');
|
||||
if (!memories.every(m => object(m) && str(m.id, 100) && str(m.title, 200) && str(m.text) && str(m.group, 100) && str(m.source, 200) && strings(m.lifeIds)))
|
||||
throw new Error('回忆记录不完整。');
|
||||
if (!messages.every(m => object(m) && str(m.id, 100) && ['user', 'companion'].includes(String(m.role)) && str(m.text) && strings(m.lifeIds) && (!m.status || ['pending', 'failed', 'sent', 'cancelled'].includes(String(m.status)))))
|
||||
throw new Error('聊天记录不完整。');
|
||||
// Reconstruct the schema: do not preserve arbitrary imported object keys/prototypes.
|
||||
return { version: 1, identity: { id: i.id, name: i.name, birth: i.birth, hour: i.hour, relation: i.relation as Identity['relation'], nickname: i.nickname, boundary: i.boundary }, settings: { city: s.city, appearance: s.appearance, reduced: s.reduced, services: Object.fromEntries(Object.keys(defaultSettings.services).map(k => [k, String((s.services as Record<string, unknown>)[k] || '')])) }, events: events.map(e => { const v = e as DemoState['events'][number]; return { id: v.id, title: v.title, text: v.text, time: v.time, place: v.place, kind: v.kind, shared: v.shared === true, memoryIds: [...v.memoryIds] }; }), memories: memories.map(m => { const v = m as DemoState['memories'][number]; return { id: v.id, title: v.title, text: v.text, group: v.group, source: v.source, lifeIds: [...v.lifeIds] }; }), messages: messages.map(m => { const v = m as DemoState['messages'][number]; return { id: v.id, role: v.role, text: v.text, lifeIds: [...v.lifeIds], status: v.status === 'pending' ? 'cancelled' : v.status, turnId: typeof v.turnId === 'string' ? v.turnId : undefined, proactive: v.proactive === true }; }), lastVisit: typeof x.lastVisit === 'number' ? x.lastVisit : Date.now() };
|
||||
}
|
||||
export function loadState(): {
|
||||
state: DemoState | null;
|
||||
error: string;
|
||||
} {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
return { state: raw ? parseState(raw) : null, error: '' };
|
||||
}
|
||||
catch {
|
||||
return { state: null, error: '本机演示资料暂时读不出来。原资料未覆盖,请允许浏览器本地存储后重新打开。' };
|
||||
}
|
||||
}
|
||||
export function persistState(state: DemoState, fail = false) {
|
||||
if (fail)
|
||||
throw new Error('这次没存好,你的修改还在,可以再试一次。');
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
|
||||
}
|
||||
catch {
|
||||
throw new Error('本机存储不可用或空间不足,你的修改还在。请检查浏览器设置后重试。');
|
||||
}
|
||||
}
|
||||
export function exportDemo(state: DemoState) {
|
||||
const blob = new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob), a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `CyberGril-demo-${state.identity.id}.json`;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { leaveSettingsThen } from '../shared/navigation';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { DemoState, Message, Theme } from '../domain/model';
|
||||
import { publicView } from '../domain/privacy';
|
||||
import { loadState, persistState } from '../adapters/storage';
|
||||
import { sampleDays } from '../demo/fixtures';
|
||||
import { CreationWizard } from '../manage/CreationWizard';
|
||||
import { ManagePanel } from '../manage/ManagePanel';
|
||||
import { LifePanel } from '../life/LifePanel';
|
||||
import { ChatPanel } from '../chat/ChatPanel';
|
||||
import { Background } from '../stage/Background';
|
||||
import { FallbackPresenter } from '../stage/Presenter';
|
||||
import { Button, Icon, Status } from '../shared/ui';
|
||||
const demo = new URLSearchParams(location.search).get('demo') === '1';
|
||||
export function App() {
|
||||
const [initial] = useState(loadState), [state, setState] = useState<DemoState | null>(initial.state), [creating, setCreating] = useState(!initial.state), [area, setArea] = useState('now'), [theme, setThemeValue] = useState<Theme>(() => { try {
|
||||
return localStorage.getItem('cg.theme') === 'fog' ? 'fog' : 'moon';
|
||||
}
|
||||
catch {
|
||||
return 'moon';
|
||||
} }), [toast, setToast] = useState(''), [controls, setControls] = useState(false), [fail, setFail] = useState(false), [offline, setOffline] = useState(false), [reconnecting, setReconnecting] = useState(false), [welcome, setWelcome] = useState(!!initial.state && Date.now() - initial.state.lastVisit > 86400000), [reach, setReach] = useState(false), [unread, setUnread] = useState(false), [log, setLog] = useState(false), [focusLife, setFocusLife] = useState(''), [returnTo, setReturnTo] = useState('now'), [presence, setPresence] = useState('在你面前'), [voice, setVoice] = useState(false), [observation, setObservation] = useState('');
|
||||
const latest = useRef(state);
|
||||
latest.current = state;
|
||||
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null), reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const notify = useCallback((text: string) => { setToast(text); if (toastTimer.current)
|
||||
clearTimeout(toastTimer.current); toastTimer.current = setTimeout(() => setToast(''), 5000); }, []);
|
||||
const save = useCallback((next: DemoState) => { persistState(next); setState(next); latest.current = next; }, []);
|
||||
const changeMessages = useCallback((messages: Message[]) => { const prev = latest.current; if (!prev)
|
||||
return; const next = { ...prev, messages }; latest.current = next; setState(next); try {
|
||||
persistState(next);
|
||||
}
|
||||
catch (e) {
|
||||
notify((e as Error).message);
|
||||
} }, [notify]);
|
||||
const setTheme = useCallback((t: Theme) => { setThemeValue(t); try {
|
||||
localStorage.setItem('cg.theme', t);
|
||||
}
|
||||
catch {
|
||||
notify('主题已切换,但浏览器没有允许保存偏好。');
|
||||
} }, [notify]);
|
||||
const view = state ? publicView(state) : null;
|
||||
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setWelcome(false); setControls(false); setArea(next); if (next === 'talk') {
|
||||
setReturnTo('now');
|
||||
setFocusLife('');
|
||||
setUnread(false);
|
||||
} if (next !== 'talk') {
|
||||
setLog(false);
|
||||
setVoice(false);
|
||||
} }); }, []);
|
||||
useEffect(() => { document.documentElement.dataset.theme = theme; }, [theme]);
|
||||
useEffect(() => { document.body.className = [creating && demo ? 'creating' : '', area === 'talk' ? 'talk' : '', !creating && ['days', 'settings'].includes(area) ? 'paned' : '', voice ? 'voice' : '', log ? 'log' : '', offline ? 'offline' : '', welcome ? 'welcoming' : '', state?.events.length === 0 ? 'data-empty' : ''].join(' '); }, [area, creating, voice, log, offline, welcome, state]);
|
||||
useEffect(() => { document.documentElement.classList.toggle('reduced', !!state?.settings.reduced); }, [state?.settings.reduced]);
|
||||
useEffect(() => { const visibility = () => { document.documentElement.classList.toggle('paused', document.hidden); if (document.hidden && latest.current) {
|
||||
try {
|
||||
persistState({ ...latest.current, lastVisit: Date.now() });
|
||||
}
|
||||
catch { /* Keep memory draft. */ }
|
||||
} }; document.addEventListener('visibilitychange', visibility); return () => { document.removeEventListener('visibilitychange', visibility); if (toastTimer.current)
|
||||
clearTimeout(toastTimer.current); if (reconnectTimer.current)
|
||||
clearTimeout(reconnectTimer.current); }; }, []);
|
||||
useEffect(() => { const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || creating)
|
||||
return; if (controls) {
|
||||
setControls(false);
|
||||
return;
|
||||
} if (welcome) {
|
||||
setWelcome(false);
|
||||
return;
|
||||
} if (log) {
|
||||
setLog(false);
|
||||
return;
|
||||
} navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [controls, welcome, log, creating, navigate]);
|
||||
function openEventChat(id: string) { setFocusLife(id); setReturnTo('days'); setLog(true); setArea('talk'); }
|
||||
function closeTalk() { setArea(returnTo); setLog(false); setVoice(false); }
|
||||
function loadSamples(long = false) { if (!state)
|
||||
return; try {
|
||||
save(sampleDays(state, long));
|
||||
notify('已载入固定演示记录,没有生成真实生活。');
|
||||
}
|
||||
catch (e) {
|
||||
notify((e as Error).message);
|
||||
} }
|
||||
function proactive() { if (!state)
|
||||
return; let next = state.events.length ? state : sampleDays(state); const event = publicView(next).events.find(e => e.id === 'rain'); if (!event)
|
||||
return; next = { ...next, messages: [...next.messages.filter(m => m.id !== 'reach-demo'), { id: 'reach-demo', role: 'companion', text: '窗外的雨停了,想跟你说一声。', lifeIds: [event.id], proactive: true }] }; try {
|
||||
save(next);
|
||||
setReach(true);
|
||||
setUnread(true);
|
||||
setControls(false);
|
||||
}
|
||||
catch (e) {
|
||||
notify((e as Error).message);
|
||||
} }
|
||||
function reconnect() { setReconnecting(true); if (reconnectTimer.current)
|
||||
clearTimeout(reconnectTimer.current); reconnectTimer.current = setTimeout(() => { setReconnecting(false); if (fail) {
|
||||
notify('暂时还没连上,再试一次。');
|
||||
return;
|
||||
} setOffline(false); notify('模拟恢复完成,已重新同步。草稿仍在,可自行发送。'); }, 700); }
|
||||
const scene = { mode: area === 'talk' ? 'talk' as const : 'daily' as const, activity: view?.events.find(e => e.kind === 'now') ? '在窗边读书' : '刚搬进来,安静待着', time_band: 'evening', weather: 'demo', outfit: 'home' };
|
||||
return <><Background /><header className="topbar"><div className="who"><i className="dot"/><span className="name">{state?.identity.name || 'CyberGril'}</span><span className="state">{demo ? '本机演示 · 无真实后台' : '服务尚未接通'}</span></div><div className="env"><span className="chip glass place"><Icon name="pin"/>{state?.settings.city || '杭州'}</span><span className="chip glass weather"><Icon name="cloud"/>雨后 · 模拟</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i /><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span></div></header>
|
||||
{!demo ? <main className="entry"><div className="card glass"><h1>一扇亮着的窗。</h1><p>真实服务还在准备,当前没有连接对话、生活、记忆或备份后台。你可以先体验完整的本机演示。</p><a className="btn-primary" href="?demo=1">进入本机演示</a></div></main> : initial.error ? <main className="entry"><div className="card"><h1>资料暂时读不出来</h1><Status text={initial.error} error/><p>请先检查浏览器存储权限,或备份浏览器中的原始资料后再处理。不会自动清空或覆盖。</p></div></main> : <>
|
||||
{creating && <CreationWizard fail={fail} onCreate={save} onEnter={() => setCreating(false)}/>}
|
||||
{!creating && state && view && <><FallbackPresenter scene={scene} presence={presence} observation={observation} onClose={area === 'talk' ? closeTalk : () => navigate('now')} closeLabel={returnTo === 'days' ? '返回日子' : '回到此刻'}/>
|
||||
{area === 'now' && !welcome && <main className="home"><div className="eyebrow">夜色里 · 一扇亮着的窗</div><h1 className="whisper">{state.events.length ? '夜深了,慢慢说。' : '刚住进来,一切都慢慢来。'}</h1><div className="meta"><span><Icon name="moon"/>心情平静 · 演示</span><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div>{view.messages.filter(m => m.role === 'companion').length > 0 && <button className="letter glass" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>她留给你的</b><span>演示留言</span></span><p>{[...view.messages].reverse().find(m => m.role === 'companion')?.text}</p></button>}<button className="away" onClick={() => navigate('days')}>你不在时 · 看她已经分享的日子 <Icon name="next"/></button><div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button><button className="btn-round glass" aria-label="进入模拟语音" onClick={() => { navigate('talk'); notify('点输入框右侧麦克风,可开启无收音的语音模拟。'); }}><Icon name="mic"/></button></div><p className="first-note">{state.identity.name}今晚刚住进来。这里还没有共同的日子。</p><p className="demo-label">本机演示 · 没有真实后台生活</p></main>}
|
||||
{welcome && area === 'now' && <section className="welcome glass"><div className="eyebrow">回来坐一会儿</div><h2>你不在的这两天</h2><p className="sub">固定演示摘要 · 只展示已分享记录</p><ul>{view.events.filter(e => e.kind !== 'plan').slice(0, 3).map(e => <li key={e.id}><time>{e.time}</time><span>{e.title}</span></li>)}</ul><p className="note">演示中网页关闭不会产生新的生活,服务器后台尚未接通。</p><div className="acts"><Button primary onClick={() => { navigate('talk'); setLog(true); }}>看她留的话</Button><Button onClick={() => navigate('days')}>看她的日子</Button><button className="btn-text" onClick={() => setWelcome(false)}>先待一会儿</button></div></section>}
|
||||
<LifePanel state={state} open={area === 'days'} onClose={() => navigate('now')} onChat={openEventChat}/><ManagePanel state={state} open={area === 'settings'} onClose={() => navigate('now')} onSave={save} fail={fail} theme={theme} setTheme={setTheme}/>
|
||||
{area === 'talk' && <ChatPanel state={state} onChange={changeMessages} onPresence={setPresence} onVoice={setVoice} onObservation={setObservation} onClose={closeTalk} offline={offline} fail={fail} log={log} setLog={setLog} focusLife={focusLife}/>}
|
||||
{offline && <div className={`netbar show glass ${reconnecting ? '' : 'failed'}`} role="status"><span>{reconnecting ? '信号不太好,正在重新连上…' : '模拟断线,草稿还在'}</span><button className="btn-ghost" onClick={reconnect}>再试一次</button></div>}
|
||||
{reach && <aside className="reach glass show"><div className="rh"><b>{state.identity.name}</b>主动说的 · 模拟</div><p>窗外的雨停了,想跟你说一声。</p><div className="basis">来自已分享的「听了一下午的雨」</div><div className="acts"><Button primary onClick={() => { setReach(false); setUnread(false); setReturnTo(area); setArea('talk'); setFocusLife('rain'); setLog(true); }}>回她</Button><Button onClick={() => setReach(false)}>稍后再看</Button></div></aside>}
|
||||
<nav className="nav glass" aria-label="主导航">{[['now', 'moon', '此刻'], ['talk', 'chat', '交谈'], ['days', 'book', '日子'], ['settings', 'gear', '设置']].map(([id, icon, label]) => <button className={`nav-item ${id === 'talk' && unread ? 'unread' : ''}`} key={id} aria-current={area === id ? 'page' : undefined} onClick={() => navigate(id)}><Icon name={icon}/>{label}<i className="badge"/></button>)}</nav></>}
|
||||
<div className={`demo ${controls ? 'open' : ''}`}><button onClick={() => setControls(!controls)} aria-expanded={controls}>演示场景<span className="dl"> · 非真实能力</span></button>{controls && <div className="menu"><h5>仅作用于本机演示,不请求真实服务</h5>{!creating && <div className="g"><button onClick={() => loadSamples()}>载入三天记录</button><button onClick={() => loadSamples(true)}>长记录</button><button onClick={() => { loadSamples(); setWelcome(true); setArea('now'); setControls(false); }}>模拟两天后返回</button><button onClick={proactive}>模拟主动消息</button><button onClick={() => { setOffline(true); setVoice(false); setControls(false); }}>模拟断线</button></div>}<h5>失败与恢复演示</h5><div className="g"><button aria-pressed={fail} onClick={() => setFail(!fail)}>{fail ? '关闭操作失败' : '下次操作模拟失败'}</button></div><p>失败开关控制创建、发送、保存和重连。关闭后可重试。没有切换隐私规则或清空重建入口。</p></div>}</div>
|
||||
</>}{toast && <div className="toast show glass" role="status">{toast}</div>}</>;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api, loadReal, type Health } from '../adapters/real';
|
||||
import type { DemoState, Message, Theme } from '../domain/model';
|
||||
import { Background } from '../stage/Background';
|
||||
import { FallbackPresenter } from '../stage/Presenter';
|
||||
import { CreationWizard } from '../manage/CreationWizard';
|
||||
import { LifePanel } from '../life/LifePanel';
|
||||
import { leaveSettingsThen } from '../shared/navigation';
|
||||
import { ManagePanel } from '../manage/ManagePanel';
|
||||
import { ChatPanel } from '../chat/ChatPanel';
|
||||
import { Button, Icon, Status } from '../shared/ui';
|
||||
|
||||
export function RealApp() {
|
||||
const [state, setState] = useState<DemoState | null>(null), [ready, setReady] = useState(false), [creating, setCreating] = useState(false), [error, setError] = useState(''), [health, setHealth] = useState<Health>(), [area, setArea] = useState('now'), [log, setLog] = useState(false), [presence, setPresence] = useState('文字已接通');
|
||||
const [theme, setTheme] = useState<Theme>(() => { try { return localStorage.getItem('cg.theme') === 'fog' ? 'fog' : 'moon'; } catch { return 'moon'; } });
|
||||
const latest = useRef(state); latest.current = state;
|
||||
const initialize = useCallback(async () => {
|
||||
setError(''); setReady(false);
|
||||
try { setHealth(await api<Health>('health')); const next = await loadReal(); setState(next); setCreating(!next); setReady(true); }
|
||||
catch (e) { setError((e as Error).message || '暂时连不上真实服务。'); }
|
||||
}, []);
|
||||
useEffect(() => { void initialize(); }, [initialize]);
|
||||
useEffect(() => { document.documentElement.dataset.theme = theme; try { localStorage.setItem('cg.theme', theme); } catch { /* Preference stays in memory. */ } }, [theme]);
|
||||
useEffect(() => { document.body.className = [creating ? 'creating' : '', area === 'talk' ? 'talk' : '', ['days', 'settings'].includes(area) ? 'paned' : '', log ? 'log' : ''].join(' '); }, [area, creating, log]);
|
||||
useEffect(() => { document.documentElement.classList.toggle('reduced', !!state?.settings.reduced); }, [state?.settings.reduced]);
|
||||
const changeMessages = useCallback((messages: Message[]) => { if (latest.current) { const next = { ...latest.current, messages }; latest.current = next; setState(next); } }, []);
|
||||
const ignoreVoice = useCallback(() => {}, []);
|
||||
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setArea(next); setLog(false); }); }, []);
|
||||
useEffect(() => { const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || creating) return; if (log) setLog(false); else navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [creating, log, navigate]);
|
||||
const lastReply = state ? [...state.messages].reverse().find(m => m.role === 'companion') : undefined;
|
||||
return <><Background/><header className="topbar"><div className="who"><i className="dot"/><span className="name">{state?.identity.name || 'CyberGril'}</span><span className="state">{ready ? '真实档案 · 文字对话' : '连接真实服务'}</span></div><div className="env"><span className="chip glass weather">天气尚未接通</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i/><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span></div></header>
|
||||
{!ready ? <main className="entry"><div className="card glass"><h1>一扇亮着的窗。</h1><Status text={error || '正在读取服务器档案…'} error={!!error}/>{error && <><p>请检查真实服务是否可达。资料仍在服务器保存。</p><Button primary onClick={() => void initialize()}>重新连接</Button></>}</div></main> : <>
|
||||
{creating && <CreationWizard real fail={false} onCreate={setState} onEnter={() => setCreating(false)}/>}
|
||||
{!creating && state && <><FallbackPresenter real scene={{ mode: area === 'talk' ? 'talk' : 'daily', activity: '文字已接通 · 生活尚未接通', time_band: '', weather: '', outfit: '' }} presence={presence} observation="" onClose={() => navigate('now')} closeLabel="回到此刻"/>
|
||||
{area === 'now' && <main className="home"><div className="eyebrow">一扇亮着的窗</div><h1 className="whisper">慢慢说,我在这里。</h1><div className="meta"><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div><button className="away" onClick={() => navigate('days')}>日子与回忆 · 后台待接入 <Icon name="next"/></button>{lastReply && <button className="letter glass" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>最近说过的话</b><span>打开完整记录</span></span><p>{lastReply.text}</p></button>}<div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button></div><p className="first-note">资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。</p>{health && !health.llm.ok && <Status error text="模型暂时不可达,档案和历史仍可查看。"/>}</main>}
|
||||
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={ignoreVoice} onObservation={ignoreVoice} onClose={() => navigate('now')} offline={false} fail={false} log={log} setLog={setLog} focusLife=""/>}
|
||||
<LifePanel real state={state} open={area === 'days'} onClose={() => navigate('now')} onChat={() => { navigate('talk'); setLog(true); }}/>
|
||||
<ManagePanel real state={state} open={area === 'settings'} onClose={() => navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/>
|
||||
<nav className="nav glass" aria-label="主导航">{[['now','moon','此刻'],['talk','chat','交谈'],['days','book','日子'],['settings','gear','设置']].map(([id, icon, label]) => <button key={id} className="nav-item" aria-current={area === id ? 'page' : undefined} onClick={() => navigate(id)}><Icon name={icon}/>{label}</button>)}</nav></>}
|
||||
</>}</>;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { SoftText } from '../shared/SoftText';
|
||||
import { newId } from '../domain/id';
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { DemoState, Message } from '../domain/model';
|
||||
import { RealChatAdapter } from '../adapters/real';
|
||||
import { DemoAdapter, TurnGate } from '../adapters/demo';
|
||||
import { publicView } from '../domain/privacy';
|
||||
import { Icon, Modal } from '../shared/ui';
|
||||
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onClose, offline, fail, log, setLog, focusLife, real = false }: {
|
||||
real?: boolean;
|
||||
state: DemoState;
|
||||
onChange: (messages: Message[]) => void;
|
||||
onPresence: (p: string) => void;
|
||||
onVoice: (v: boolean) => void;
|
||||
onObservation: (s: string) => void;
|
||||
onClose: () => void;
|
||||
offline: boolean;
|
||||
fail: boolean;
|
||||
log: boolean;
|
||||
setLog: (b: boolean) => void;
|
||||
focusLife: string;
|
||||
}) {
|
||||
const [draft, setDraft] = useState(() => { try {
|
||||
return sessionStorage.getItem(real ? 'cg.real.draft' : 'cg.draft') || '';
|
||||
}
|
||||
catch {
|
||||
return '';
|
||||
} }), [reply, setReply] = useState(''), [busy, setBusy] = useState(false), [voice, setVoice] = useState(false), [permission, setPermission] = useState<'' | 'mic' | 'vision'>(''), [notice, setNotice] = useState(''), [denied, setDenied] = useState(false), [vision, setVision] = useState(false);
|
||||
const gate = useRef(new TurnGate()), adapter = useRef(real ? new RealChatAdapter(epoch => { gate.current.epoch = epoch; }) : new DemoAdapter()), live = useRef(state.messages), logRef = useRef<HTMLDivElement>(null), voiceController = useRef<AbortController | null>(null);
|
||||
const [activeTurn, setActiveTurn] = useState(''), [interrupted, setInterrupted] = useState<{ text: string; turn: string } | null>(null);
|
||||
const replyLive = useRef(''), turnLive = useRef(''), dialogue = useRef<HTMLDivElement>(null), following = useRef(true);
|
||||
live.current = state.messages;
|
||||
const view = publicView(state), lastUser = [...view.messages].reverse().find(m => m.role === 'user'), lastHer = [...view.messages].reverse().find(m => m.role === 'companion');
|
||||
const change = (messages: Message[]) => { live.current = messages; onChange(messages); };
|
||||
function stop() { gate.current.cancel(); if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnLive.current }); replyLive.current = ''; setBusy(false); setReply(''); onPresence('停下来了'); change(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); }
|
||||
function endVoice() { stop(); voiceController.current?.abort(); setVoice(false); onVoice(false); onPresence('在你面前'); }
|
||||
useEffect(() => { const current = gate.current; return () => { current.cancel(); if (real) onChange(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); voiceController.current?.abort(); onVoice(false); onObservation(''); }; }, [onVoice, onObservation, onChange, real]);
|
||||
useEffect(() => { try {
|
||||
sessionStorage.setItem(real ? 'cg.real.draft' : 'cg.draft', draft);
|
||||
}
|
||||
catch { /* Draft remains in memory. */ } }, [draft, real]);
|
||||
useEffect(() => { if (offline) {
|
||||
gate.current.resync();
|
||||
setBusy(false);
|
||||
setReply('');
|
||||
setVoice(false);
|
||||
onVoice(false);
|
||||
voiceController.current?.abort();
|
||||
} }, [offline, onVoice]);
|
||||
useEffect(() => { if (!vision)
|
||||
return; onObservation('模拟 · 刚刚看到,未采集影像'); const t = setTimeout(() => onObservation('模拟 · 已过期,不再当作眼前'), 30000); return () => clearTimeout(t); }, [vision, onObservation]);
|
||||
useEffect(() => { if (log) {
|
||||
const el = focusLife ? logRef.current?.querySelector(`[data-life="${CSS.escape(focusLife)}"]`) : null;
|
||||
if (el)
|
||||
el.scrollIntoView({ block: 'center' });
|
||||
else if (logRef.current)
|
||||
logRef.current.scrollTop = logRef.current.scrollHeight;
|
||||
} }, [log, focusLife, view.messages.length]);
|
||||
useLayoutEffect(() => { if (following.current && dialogue.current) dialogue.current.scrollTop = dialogue.current.scrollHeight; }, [reply, state.messages, interrupted]);
|
||||
async function send(retry?: Message) { if (!retry && real) retry = [...live.current].reverse().find(m => m.role === 'user' && m.status === 'failed' && m.text === draft.trim()); const text = retry?.text || draft.trim(); if (!text || offline)
|
||||
return; stop(); const turnId = retry?.turnId || newId(), signal = gate.current.begin(turnId); const msg: Message = { id: retry?.id || newId(), role: 'user', text, lifeIds: [], turnId, status: 'pending' }; change(retry ? live.current.map(m => m.id === retry.id ? msg : m) : [...live.current, msg]); if (!retry)
|
||||
setDraft(''); setActiveTurn(turnId); turnLive.current = turnId; following.current = true; setBusy(true); onPresence('在想'); setNotice(''); try {
|
||||
await adapter.current.send(text, turnId, gate.current.epoch, signal, event => { if (!gate.current.accepts(event))
|
||||
return; if (event.t === 'chat.delta') {
|
||||
replyLive.current += event.delta; setInterrupted(null); setReply(replyLive.current);
|
||||
onPresence('在说话');
|
||||
}
|
||||
else if (event.t === 'chat.final') {
|
||||
change([...live.current.map(m => m.id === msg.id ? { ...m, status: 'sent' as const } : m), { id: newId(), role: 'companion', text: event.utterance.text, lifeIds: [], turnId }]);
|
||||
replyLive.current = ''; setInterrupted(null); setReply('');
|
||||
if (real) setDraft(current => current === text ? '' : current);
|
||||
setBusy(false);
|
||||
onPresence(voice ? '在听你说(模拟)' : '在你面前');
|
||||
} }, fail);
|
||||
}
|
||||
catch (e) {
|
||||
if (signal.aborted)
|
||||
return;
|
||||
change(live.current.map(m => m.id === msg.id ? { ...m, status: 'failed' } : m));
|
||||
setBusy(false);
|
||||
if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnId }); replyLive.current = ''; setReply('');
|
||||
setDraft(text);
|
||||
setNotice(real && (e instanceof TypeError || e instanceof SyntaxError) ? '连接中断了,你写的话还在,可以重试。' : (e as Error).message);
|
||||
onPresence('在你面前');
|
||||
} }
|
||||
const setVoiceMode = () => { if (real) { setNotice('语音尚未接通,文字仍可使用。'); return; } if (voice) {
|
||||
endVoice();
|
||||
return;
|
||||
} setPermission('mic'); };
|
||||
const herText = reply || interrupted?.text || lastHer?.text || '我在。你想说什么?';
|
||||
const herTurn = reply ? activeTurn : interrupted ? interrupted.turn : lastHer?.turnId || lastHer?.id || 'greeting';
|
||||
return <><div className="chat-layout"><div className="talk-scene-space" aria-hidden="true"/><div className="dialog"><div className="dialog-scroll" ref={dialogue} tabIndex={0} aria-label="当前对话,可滚动阅读全文" onScroll={() => { const el = dialogue.current; if (el) following.current = el.scrollHeight - el.clientHeight - el.scrollTop < 40; }}>
|
||||
{lastUser && <div className="you"><div className="speaker">你</div><SoftText identity={lastUser.turnId || lastUser.id} text={lastUser.text}/>{lastUser.status === 'failed' && <div className="failed">没发出去 <button className="retry" onClick={() => void send(lastUser)}>重试</button></div>}{lastUser.status === 'cancelled' && <small>本轮已取消</small>}</div>}
|
||||
<div className={`her ${interrupted ? 'cut' : ''}`}><div className="speaker">{state.identity.name}</div><SoftText identity={herTurn} text={herText}/>{reply && <span className="caret"/>}{interrupted && <small className="partial-note">这段未完成,未存入聊天记录</small>}</div>
|
||||
</div><div className="hint"><span role="status">{state.identity.name} · {notice || (busy ? reply ? '正在回应…' : `${state.identity.name}在想…` : real ? '文字已接通 · 完整内容可滚动阅读' : '演示回复 · 未连接真实模型')}</span>{busy && <button className="btn-text" onClick={stop}>取消本轮回复</button>}</div></div>
|
||||
{voice && <div className="voicebar glass"><span className="live"><i /></span><span className="vstate">{busy ? '她在想(模拟)' : '在听你说(模拟,无收音)'}</span><button className="btn-ghost" onClick={() => { stop(); setNotice(fail?'刚才没听清,你再说一遍?(模拟识别失败)':'她停下来了,在等你。'); }}>打断她</button><button className="end" onClick={endVoice}>结束语音</button></div>}
|
||||
<div className="composer glass"><button className={`btn-round cam ${vision ? 'on' : ''}`} aria-label="视觉观察" onClick={() => { if (real) { setNotice('视觉尚未接通,不采集影像。'); return; } if (vision) {
|
||||
setVision(false);
|
||||
onObservation('窗户关上了');
|
||||
}
|
||||
else
|
||||
setPermission('vision'); }}><Icon name="eye"/></button><textarea aria-label="想和她说的话" rows={1} maxLength={4000} value={draft} placeholder="想和她说点什么…" onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) {
|
||||
e.preventDefault();
|
||||
void send();
|
||||
} }}/><button className="btn-round send" disabled={!draft.trim() || offline} aria-label="发送" onClick={() => void send()}><Icon name="up"/></button><button className={`btn-round log-btn ${log ? 'on' : ''}`} aria-label="完整记录" onClick={() => setLog(!log)}><Icon name="chat"/></button><button className={`mic ${denied ? 'denied' : ''}`} aria-label={real ? '语音尚未接通' : voice ? '停止语音' : '开始模拟语音'} disabled={offline} onClick={setVoiceMode}><Icon name={voice ? 'stop' : 'mic'}/></button></div>
|
||||
</div><aside className="log-panel glass read" hidden={!log}><header><h2>你们说过的话</h2><button className="btn-round sm" aria-label="关闭记录" onClick={() => setLog(false)}><Icon name="x"/></button></header><div className="scroll" ref={logRef}><div className="day">{real ? '服务器聊天记录' : '本机演示记录'}</div>{view.messages.map(m => <div key={m.id} data-life={m.lifeIds[0]} className={`msg ${m.role === 'user' ? 'me' : ''} ${m.status === 'failed' ? 'fail' : ''} ${focusLife && m.lifeIds.includes(focusLife) ? 'hl' : ''}`}><div className="who-l">{m.role === 'user' ? '你' : state.identity.name}{m.proactive && <span className="tagm proactive">她主动说的</span>}</div><p>{m.text}</p>{m.status === 'failed' && <button className="btn-text" onClick={() => void send(m)}>没发出去 · 重试</button>}{m.status === 'cancelled' && <small>已取消</small>}</div>)}</div></aside>
|
||||
{permission && <Modal title={permission === 'mic' ? '开启模拟语音?' : '打开模拟视觉窗?'} onClose={() => { setPermission(''); setDenied(true); setNotice('没有开启。真实服务尚未接通,文字仍可使用。'); }} confirm="开始模拟" onConfirm={() => { if (permission === 'mic') {
|
||||
setDenied(false);
|
||||
setVoice(true);
|
||||
onVoice(true);
|
||||
voiceController.current = new AbortController();
|
||||
onPresence('在听你说(模拟)');
|
||||
setNotice('模拟语音没有收音,可继续用文字输入。');
|
||||
}
|
||||
else {
|
||||
if (fail) {
|
||||
onObservation('模拟 · 看不清,视觉服务未接通');
|
||||
setNotice('模拟观察失败,文字仍可使用。');
|
||||
}
|
||||
else
|
||||
setVision(true);
|
||||
} setPermission(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。</Modal>}
|
||||
<button hidden className="sr" onClick={onClose}>退出交流</button></>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { defaultSettings, type DemoState, type Identity } from '../domain/model';
|
||||
export function freshState(identity: Identity): DemoState {
|
||||
return { version: 1, identity, settings: structuredClone(defaultSettings), events: [], memories: [], messages: [], lastVisit: Date.now() };
|
||||
}
|
||||
// Loaded only through an explicit demo action; never a fabricated background life loop.
|
||||
export function sampleDays(state: DemoState, long = false): DemoState {
|
||||
const events: DemoState['events'] = [
|
||||
{ id: 'book', title: '读到了书里的那片海', text: '翻到讲海的那一页,忽然想起你说过喜欢安静的地方。', time: '10月21日 19:40', place: '卧室 · 窗边', kind: 'now', shared: true, memoryIds: ['habit'] },
|
||||
{ id: 'tea', title: '给自己泡了一杯热茶', text: '杯子捧在手里,夜晚就慢了下来。', time: '10月21日 16:20', place: '卧室', kind: 'done', shared: true, memoryIds: [] },
|
||||
{ id: 'rain', title: '听了一下午的雨', text: '雨滴在玻璃上跑得一快一慢,很像一段没有歌词的曲子。', time: '10月20日 15:30', place: '卧室 · 窗边', kind: 'done', shared: true, memoryIds: ['rain-memory'] },
|
||||
{ id: 'secret', title: '未分享的秘密散步', text: '这段未分享的生活不能出现在任何视图里。', time: '10月21日 13:00', place: '私密地点', kind: 'done', shared: false, memoryIds: ['secret-memory'] },
|
||||
{ id: 'plan', title: '明天想读完这一章', text: '如果精神好,就再读一会儿。计划也可能会变。', time: '10月22日 20:00', place: '卧室', kind: 'plan', shared: true, memoryIds: [] }
|
||||
];
|
||||
if (long)
|
||||
for (let i = 0; i < 40; i++)
|
||||
events.push({ ...events[1], id: `old-${i}`, title: `更早的一杯茶 · ${i + 1}`, time: `10月${19 - Math.floor(i / 4)}日 16:20` });
|
||||
const memories: DemoState['memories'] = [
|
||||
{ id: 'habit', title: '留一盏小灯', text: '安静也可以是一起待着的一种方式。', group: '你们的小习惯', source: '演示 · 10月18日的聊天', lifeIds: ['book'] },
|
||||
{ id: 'rain-memory', title: '第一次聊起雨声', text: '你说雨声让你觉得安心。', group: '我们一起的', source: '演示 · 10月20日的聊天', lifeIds: ['rain'] },
|
||||
{ id: 'know', title: '你喜欢安静的地方', text: '是你亲口讲给她听的。', group: '她知道的你', source: '演示 · 10月18日你说的', lifeIds: [] },
|
||||
{ id: 'growth', title: '慢慢学会留白', text: '后来她开始喜欢,在一句话之后留一点安静。', group: '她的成长', source: '演示 · 共同经历', lifeIds: ['book'] },
|
||||
{ id: 'secret-memory', title: '秘密散步的回忆', text: '隐私测试内容', group: '我们一起的', source: '私密', lifeIds: ['secret'] }
|
||||
];
|
||||
const messages: DemoState['messages'] = [
|
||||
{ id: 'hello', role: 'companion', text: '外面下了一阵雨,现在安静下来了。', lifeIds: ['rain'] },
|
||||
{ id: 'u1', role: 'user', text: '你在看什么?', lifeIds: [] },
|
||||
{ id: 'c1', role: 'companion', text: events[0].text, lifeIds: ['book'] },
|
||||
{ id: 'hidden-message', role: 'companion', text: '秘密散步的间接引用', lifeIds: ['secret'] }
|
||||
];
|
||||
return { ...state, events, memories, messages: [...messages, ...state.messages.filter(m => m.turnId)] };
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Demo identity and turn identifiers must also work on the first intranet HTTP preview.
|
||||
// getRandomValues is available there even where randomUUID requires a secure context.
|
||||
export function newId(): string {
|
||||
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
||||
bytes[6] = (bytes[6] & 15) | 64;
|
||||
bytes[8] = (bytes[8] & 63) | 128;
|
||||
const hex = [...bytes].map(v => v.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
export type Theme = 'moon' | 'fog';
|
||||
export type Relation = '朋友' | '恋人';
|
||||
export interface Identity {
|
||||
id: string;
|
||||
name: string;
|
||||
birth: string;
|
||||
hour: string;
|
||||
relation: Relation;
|
||||
nickname: string;
|
||||
boundary: string;
|
||||
}
|
||||
export interface Settings {
|
||||
city: string;
|
||||
appearance: string;
|
||||
reduced: boolean;
|
||||
services: Record<string, string>;
|
||||
}
|
||||
export interface LifeEvent {
|
||||
id: string;
|
||||
title: string;
|
||||
text: string;
|
||||
time: string;
|
||||
place: string;
|
||||
kind: 'done' | 'now' | 'plan';
|
||||
shared: boolean;
|
||||
memoryIds: string[];
|
||||
}
|
||||
export interface Memory {
|
||||
id: string;
|
||||
title: string;
|
||||
text: string;
|
||||
group: string;
|
||||
source: string;
|
||||
lifeIds: string[];
|
||||
}
|
||||
export interface Message {
|
||||
id: string;
|
||||
role: 'user' | 'companion';
|
||||
text: string;
|
||||
lifeIds: string[];
|
||||
turnId?: string;
|
||||
status?: 'pending' | 'failed' | 'sent' | 'cancelled';
|
||||
proactive?: boolean;
|
||||
}
|
||||
export interface DemoState {
|
||||
version: 1;
|
||||
identity: Identity;
|
||||
settings: Settings;
|
||||
events: LifeEvent[];
|
||||
memories: Memory[];
|
||||
messages: Message[];
|
||||
lastVisit: number;
|
||||
}
|
||||
export interface SceneDesc {
|
||||
mode: 'daily' | 'talk';
|
||||
activity: string;
|
||||
time_band: string;
|
||||
weather: string;
|
||||
outfit: string;
|
||||
}
|
||||
export type ServerEvent = {
|
||||
t: 'chat.error'; epoch: number; turn_id: string; phi: string; retryable: boolean;
|
||||
} | {
|
||||
t: 'chat.delta';
|
||||
epoch: number;
|
||||
turn_id: string;
|
||||
delta: string;
|
||||
} | {
|
||||
t: 'chat.final';
|
||||
epoch: number;
|
||||
turn_id: string;
|
||||
utterance: {
|
||||
text: string;
|
||||
speech_tags: string[];
|
||||
};
|
||||
};
|
||||
export const defaultSettings: Settings = { city: '杭州', appearance: 'reference-v1', reduced: false, services: { '对话模型': '', 'ASR': '', 'TTS': '', '视觉观察': '' } };
|
||||
export function validateCreation(name: string, birth: string, relation: string, now = new Date()): string {
|
||||
if (!name.trim() || name.trim().length > 20 || (/[<>]/u.test(name) || [...name].some(c => c.charCodeAt(0) < 32)))
|
||||
return '请为她起一个 1–20 字的名字,不含控制字符或尖括号。';
|
||||
const d = new Date(birth + 'T00:00:00');
|
||||
const limit = new Date(now.getFullYear() - 18, now.getMonth(), now.getDate());
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(birth) || !Number.isFinite(d.getTime()) || d > limit || d.getFullYear() < 1900)
|
||||
return '请填写有效的出生日期,且已满 18 岁。';
|
||||
if (!['朋友', '恋人'].includes(relation))
|
||||
return '请亲自选择你们的关系。';
|
||||
return '';
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { DemoState, LifeEvent } from './model';
|
||||
// Fail closed, including unknown references. Real API must apply this BEFORE transmission.
|
||||
export const sharedEvents = (events: LifeEvent[]) => events.filter(e => e.shared === true);
|
||||
export function publicView(state: DemoState): DemoState {
|
||||
const events = sharedEvents(state.events);
|
||||
const ids = new Set(events.map(e => e.id));
|
||||
const allowed = (refs: string[]) => refs.every(id => ids.has(id));
|
||||
const memories = state.memories.filter(m => allowed(m.lifeIds));
|
||||
const memoryIds = new Set(memories.map(m => m.id));
|
||||
return { ...state, events: events.map(e => ({ ...e, memoryIds: e.memoryIds.filter(id => memoryIds.has(id)) })), memories, messages: state.messages.filter(m => allowed(m.lifeIds)) };
|
||||
}
|
||||
export function eventById(state: DemoState, id: string) { return publicView(state).events.find(e => e.id === id); }
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { DemoState } from '../domain/model';
|
||||
import { publicView } from '../domain/privacy';
|
||||
import { Button, Icon } from '../shared/ui';
|
||||
export function LifePanel({ state, open, onClose, onChat, real = false }: {
|
||||
real?: boolean;
|
||||
state: DemoState;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onChat: (id: string) => void;
|
||||
}) {
|
||||
const view = publicView(state), [tab, setTab] = useState('life'), [selection, setSelection] = useState(''), [limit, setLimit] = useState(18);
|
||||
const list = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { if (open) {
|
||||
const params = new URLSearchParams(location.hash.slice(1));
|
||||
const id = params.get('event');
|
||||
if (id) {
|
||||
setTab('life');
|
||||
setSelection(id);
|
||||
}
|
||||
} }, [open]);
|
||||
const event = tab === 'life' ? view.events.find(e => e.id === selection) : undefined, memory = tab === 'memory' ? view.memories.find(m => m.id === selection) : undefined;
|
||||
const select = (id: string, t = tab) => { setTab(t); setSelection(id); };
|
||||
return <section className={`pane glass read ${open ? 'open' : ''} ${selection ? 'has-detail' : ''}`} hidden={!open} aria-label="日子"><header><h2>日子</h2><div className="tabs" role="tablist">{[['life', '她的日子'], ['memory', '我们的回忆']].map(([t, l]) => <button role="tab" key={t} aria-selected={tab === t} onClick={() => { setTab(t); setSelection(''); }}>{l}</button>)}</div><span className="grow"/><span className="tag-demo">{real ? '后台待接入' : '演示数据'}</span><button className="btn-round sm" aria-label="关闭日子" onClick={onClose}><Icon name="x"/></button></header><div className="cols"><div className="list" ref={list}>
|
||||
{tab === 'life' ? <><div className="away-card"><b>你不在时</b>{real ? '这里只会显示她已经讲给你听的事。生活循环尚未接通,当前没有可核实的生活记录。' : '这里只显示她已经讲给你听的事。演示没有真实后台生活。'}</div><div className="legend"><span><i className="k done"/>已发生</span><span><i className="k now"/>正在</span><span><i className="k plan"/>打算</span></div>{view.events.length === 0 ? <div className="empty">{real ? '还没有可展示的生活记录' : '她今晚刚住进来,还没有发生什么。'}<small>{real ? '后台待接入,不用示例经历填充。你们说过的话可在交谈的完整记录中查看。' : '演示资料可以从「演示场景」载入。'}</small></div> : view.events.slice(0, limit).map((e, i) => <div key={e.id}>{(i === 0 || view.events[i - 1].time.split(' ')[0] !== e.time.split(' ')[0]) && <div className="grp">{e.kind === 'plan' ? '之后的打算' : e.time.split(' ')[0]}</div>}<button className={`ev told ${e.kind}`} aria-current={selection === e.id} onClick={() => select(e.id)}><time>{e.time.split(' ')[1]}</time><i className={`k ${e.kind}`}/><span><span className="tt">{e.title}</span><span className="sub"><span className="tag">已经讲过</span>{e.memoryIds.length > 0 && <span className="tag accent">和你有关</span>}</span></span></button></div>)}{limit < view.events.length && <div className="more"><Button onClick={() => setLimit(x => x + 12)}>看更早的日子</Button></div>}</> : view.memories.length === 0 && !real ? <div className="empty">聊着聊着就会有了。</div> : ['我们一起的', '你们的小习惯', '她知道的你', '她的成长'].map(group => <div key={group}><div className="grp">{group}</div>{real && <div className="empty">暂无可核实的回忆<small>长期记忆尚未接通;文字聊天记录独立保留。</small></div>}{view.memories.filter(m => m.group === group).map(m => <button className="mem" key={m.id} aria-current={selection === m.id} onClick={() => select(m.id)}>{m.title}<small>{m.source}</small></button>)}</div>)}
|
||||
</div><article className="detail"><button className="btn-text back" onClick={() => setSelection('')}><Icon name="back"/>返回{tab === 'life' ? '她的日子' : '我们的回忆'}</button>{event ? <><div className="d-kicker"><i className={`k ${event.kind}`}/>{event.kind === 'now' ? '正在' : event.kind === 'plan' ? '打算 · 计划可能会变' : '已经发生'}<span className="tag">已经讲给你听</span></div><h3 className="d-title">{event.title}</h3><div className="d-meta">{event.time} · {event.place}</div><blockquote className="quote">{event.text}<small>{view.identity.name}说过的话 · 演示</small></blockquote><div className="d-sec">和这件事有关的回忆</div><div className="links">{event.memoryIds.map(id => { const m = view.memories.find(x => x.id === id); return m && <button className="link-chip" key={id} onClick={() => select(id, 'memory')}><Icon name="link"/>{m.title}</button>; })}</div><div className="d-sec">那时候的聊天</div><Button onClick={() => onChat(event.id)}>看那段聊天</Button><div className="d-foot">这是模拟生活里的一条记录,不是真实发生的事。画面只按状态展示,不会反过来改写生活。</div></> : memory ? <><div className="d-kicker">{memory.group} · 演示回忆</div><h3 className="d-title">{memory.title}</h3><div className="d-meta">{memory.source}</div><blockquote className="quote">{memory.text}</blockquote>{memory.group === '她的成长' && <div className="growth"><div><h4>最初就有的</h4>细腻、慢热</div><div><h4>后来慢慢有的</h4>{memory.text}</div></div>}<div className="d-sec">来自这些日子</div><div className="links">{memory.lifeIds.map(id => { const e = view.events.find(x => x.id === id); return e && <button className="link-chip" key={id} onClick={() => select(id, 'life')}>{e.title}</button>; })}</div></> : selection ? <div className="empty">这条记录暂时不可见。<small>只会展示她已分享的事。</small></div> : <div className="d-empty"><div><Icon name="book"/>{real ? '这里会保留日子详情、回忆与聊天的关联。后台接通后,已分享的内容会出现在列表中。' : '选一件小事,慢慢读。'}</div></div>}</article></div></section>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { RealApp } from './app/RealApp';
|
||||
import { App } from './app/App';
|
||||
import { Viewport } from './shared/Viewport';
|
||||
import './styles/tokens.css';
|
||||
import './styles/components.css';
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<Viewport>{new URLSearchParams(location.search).get('demo') === '1' ? <App /> : <RealApp />}</Viewport>);
|
||||
@@ -0,0 +1,55 @@
|
||||
import { api, type Color, type RealIdentity } from '../adapters/real';
|
||||
import { newId } from '../domain/id';
|
||||
import { useState } from 'react';
|
||||
import { validateCreation, type Identity } from '../domain/model';
|
||||
import { freshState } from '../demo/fixtures';
|
||||
import { delay } from '../adapters/demo';
|
||||
import { BaseColor, Button, Field, Status } from '../shared/ui';
|
||||
import type { DemoState } from '../domain/model';
|
||||
export function CreationWizard({ onCreate, onEnter, fail, real = false }: {
|
||||
real?: boolean;
|
||||
onCreate: (s: DemoState) => void;
|
||||
onEnter: () => void;
|
||||
fail: boolean;
|
||||
}) {
|
||||
const [step, setStep] = useState(0), [name, setName] = useState(''), [birth, setBirth] = useState('2000-10-18'), [hour, setHour] = useState('亥时'), [relation, setRelation] = useState(''), [nickname, setNickname] = useState(''), [agreed, setAgreed] = useState(false), [error, setError] = useState(''), [phase, setPhase] = useState(-1), [busy, setBusy] = useState(false);
|
||||
const [color, setColor] = useState<Color>();
|
||||
const labels = ['出生资料', '她的底色', '你们的关系', '最终确认'];
|
||||
async function next() { const err = validateCreation(name, birth, step === 2 ? relation : '朋友'); if (err) {
|
||||
setError(err);
|
||||
return;
|
||||
} setError(''); if (real && step === 0) { setBusy(true); try { setColor(await api<Color>('companion/preview', { method: 'POST', body: JSON.stringify({ name, birth, hour }) })); } catch (e) { setError((e as Error).message); return; } finally { setBusy(false); } } setStep(s => s + 1); }
|
||||
async function create() { const err = validateCreation(name, birth, relation); if (err || !agreed) {
|
||||
setError(err || '请先确认你已了解。');
|
||||
return;
|
||||
} setBusy(true); setError(''); try {
|
||||
if (real) {
|
||||
setPhase(0);
|
||||
const identity = await api<RealIdentity>('companion', { method: 'POST', body: JSON.stringify({ name, birth, hour, relation, nickname }) });
|
||||
setPhase(2); onCreate({ ...freshState(identity), messages: [], events: [], memories: [] }); setStep(4); return;
|
||||
}
|
||||
const c = new AbortController();
|
||||
for (let p = 0; p < 3; p++) {
|
||||
setPhase(p);
|
||||
await delay(280, c.signal);
|
||||
if (fail && p === 1)
|
||||
throw new Error('这一步没完成,资料都还在。可以重试,或返回修改。');
|
||||
}
|
||||
const identity: Identity = { id: newId(), name: name.trim(), birth, hour, relation: relation as Identity['relation'], nickname: nickname.trim(), boundary: '尊重彼此的节奏' };
|
||||
onCreate(freshState(identity));
|
||||
setStep(4);
|
||||
}
|
||||
catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
finally {
|
||||
setBusy(false);
|
||||
} }
|
||||
return <main className="create"><div className="story"><div className="eyebrow">一扇窗 · 一个开始</div><h1>{step === 4 ? '她住进来了。' : step === 2 ? '你想和她,怎样相处?' : '在夜色里,留一盏灯。'}</h1><p>{real ? '资料与对话保存在服务器,重开或换设备都能恢复同一位她。最终确认前不会建档。' : '这是本机演示。你的选择只保存在这个浏览器,没有创建服务器上的真实伴侣。'}</p><div className="single">首版只有一位。创建后不提供切换或清空重建。</div></div><section className="wiz glass read"><div className="steps">{labels.map((l, i) => <span className={i <= step ? 'on' : ''} key={l}/>)}</div><div className="steplabel">{step < 4 ? `${step + 1} / 4 · ${labels[step]}` : '创建完成'}</div><div className="wbody"><div className="wstep on" key={step}>
|
||||
{step === 0 && <><h2>先认识她的开始</h2><p className="lead">名字由你起,生辰也可以在确认前修改。</p><Field label="她的名字"><input className="input" value={name} maxLength={20} onChange={e => setName(e.target.value)} autoComplete="off"/></Field><Field label="出生日期(公历)" hint="下一步会换算真实农历,并显示四柱与说明。"><input className="input" type="date" value={birth} onChange={e => setBirth(e.target.value)}/></Field><Field label="出生时辰" hint="北京时间;子时23:00–00:59,丑时01:00–02:59,之后每两小时一段。排盘取时辰内偶数整点,子时取本日00:00。"><select className="select" value={hour} onChange={e => setHour(e.target.value)}>{['子时', '丑时', '寅时', '卯时', '辰时', '巳时', '午时', '未时', '申时', '酉时', '戌时', '亥时'].map(h => <option key={h}>{h}</option>)}</select></Field><Button onClick={() => { setBirth(`${1990 + Math.floor(Math.random() * 13)}-${String(1 + Math.floor(Math.random() * 12)).padStart(2, '0')}-18`); }}>自动生成一组生辰</Button></>}
|
||||
{step === 1 && <><h2>{name.trim()}的底色</h2><p className="lead">底色是倾向,会留下诠释和成长的空间。</p><BaseColor color={real ? color : undefined}/></>}
|
||||
{step === 2 && <><h2>由你选择关系</h2><p className="lead">没有预选答案。以后可以在设置中确认修改,记忆会保留。</p><div className="seg">{['朋友', '恋人'].map(r => <button aria-pressed={relation === r} key={r} onClick={() => setRelation(r)}>{r}</button>)}</div><Field label="她怎么称呼你(可选)"><input className="input" maxLength={40} value={nickname} onChange={e => setNickname(e.target.value)}/></Field></>}
|
||||
{step === 3 && <><h2>让这次相识,有一个开始</h2><div className="sum">{[['名字', name], ['生辰', `${birth} · ${hour}`], ['关系', relation], ['称呼', nickname || '暂时不设']].map(([k, v]) => <div className="r" key={k}><span>{k}</span><b>{v}</b></div>)}</div><BaseColor color={real ? color : undefined}/><label className="check"><input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)}/>{real ? '我明白:这将创建服务器上的真实档案;创建后底色只读,只保留一位伴侣。' : '我明白:这是本机演示;创建后底色只读,只保留一位伴侣。'}</label>{phase >= 0 && <ul className="phases">{(real ? ['核对真实排盘', '保存唯一档案', '档案已保存'] : ['排好底色(示例)', '形成最初的小习惯(示例)', '布置房间(示例)']).map((p, i) => <li key={p} className={i < phase ? 'ok' : i === phase ? (error ? 'fail' : 'run') : ''}><i>{i < phase ? '✓' : ''}</i>{p}</li>)}</ul>}</>}
|
||||
{step === 4 && <div className="born"><div className="halo"/><h2>{name.trim()}住进来了</h2><p className="lead">刚开始,还没有共同的日子。聊着聊着就会有了。</p></div>}
|
||||
<Status text={error} error/></div></div><footer className="wfoot">{step > 0 && step < 4 && <Button disabled={busy} onClick={() => { setError(''); setStep(error ? 0 : step - 1); }}>{error ? '返回修改' : '上一步'}</Button>}<span className="grow"/>{step < 3 ? <Button primary disabled={busy} onClick={() => void next()}>下一步</Button> : step === 3 ? <Button primary disabled={!agreed || busy} onClick={() => void create()}>{busy ? '正在创建…' : error ? '再试一次' : '确认创建'}</Button> : <Button primary onClick={onEnter}>去看看她</Button>}</footer></section></main>;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { api, type Health, type RealIdentity } from '../adapters/real';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { DemoState, Settings, Theme } from '../domain/model';
|
||||
import { delay } from '../adapters/demo';
|
||||
import { exportDemo, parseState } from '../adapters/storage';
|
||||
import { BaseColor, Button, Field, Icon, Modal, Status } from '../shared/ui';
|
||||
const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['city', 'pin', '城市'], ['appearance', 'image', '外观素材'], ['backup', 'box', '本地演示导出'], ['services', 'plug', '外接服务'], ['display', 'moon', '显示']];
|
||||
export function ManagePanel({ state, open, onClose, onSave, fail, theme, setTheme, real = false }: {
|
||||
real?: boolean;
|
||||
state: DemoState;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (s: DemoState) => void;
|
||||
fail: boolean;
|
||||
theme: Theme;
|
||||
setTheme: (t: Theme) => void;
|
||||
}) {
|
||||
const [section, setSection] = useState('her'), [detail, setDetail] = useState(false), [draft, setDraft] = useState(() => ({ settings: structuredClone(state.settings), identity: structuredClone(state.identity) })), [message, setMessage] = useState(''), [error, setError] = useState(false), [busy, setBusy] = useState(false), [confirm, setConfirm] = useState(''), [confirmText, setConfirmText] = useState(''), [search, setSearch] = useState(''), [restore, setRestore] = useState<DemoState | null>(null), [material, setMaterial] = useState(''), [check, setCheck] = useState('');
|
||||
const approvedNavigation = useRef(false);
|
||||
const pendingNavigation = useRef<(() => void) | null>(null);
|
||||
const [serviceHealth, setServiceHealth] = useState<Health>();
|
||||
const request = useRef<AbortController | null>(null), generation = useRef(0), feedback = useRef<HTMLDivElement>(null);
|
||||
useEffect(()=>{if(message) feedback.current?.scrollIntoView({block:'center'});},[message]);
|
||||
const latestState = useRef(state); latestState.current = state;
|
||||
const dirtySections: Record<string, boolean> = {relation: JSON.stringify(draft.identity)!==JSON.stringify(state.identity), city: !real && draft.settings.city!==state.settings.city, services: !real && JSON.stringify(draft.settings.services)!==JSON.stringify(state.settings.services), display: draft.settings.reduced!==state.settings.reduced};
|
||||
const dirty = !!dirtySections[section], anyDirty = Object.values(dirtySections).some(Boolean);
|
||||
useEffect(() => { if (!open) {
|
||||
request.current?.abort();
|
||||
setBusy(false);
|
||||
} }, [open]);
|
||||
useEffect(() => () => { request.current?.abort(); }, []);
|
||||
useEffect(() => { if (!anyDirty)
|
||||
return; const before = (e: BeforeUnloadEvent) => { e.preventDefault(); }; window.addEventListener('beforeunload', before); return () => window.removeEventListener('beforeunload', before); }, [anyDirty]);
|
||||
const requestLeave = (action: () => void) => { if (anyDirty) { pendingNavigation.current = action; setConfirm('leave'); } else action(); };
|
||||
useEffect(() => {
|
||||
if (!open || !anyDirty) return;
|
||||
const guard = (event: Event) => { if (approvedNavigation.current) return; event.preventDefault(); pendingNavigation.current = (event as CustomEvent<() => void>).detail; setConfirm('leave'); };
|
||||
window.addEventListener('cg:leave-settings', guard);
|
||||
return () => window.removeEventListener('cg:leave-settings', guard);
|
||||
}, [open, anyDirty]);
|
||||
async function checkService() {
|
||||
setBusy(true); setError(false); setMessage('正在检查文字服务…');
|
||||
try { const status = await api<Health>('health'); setServiceHealth(status); setMessage(status.llm.ok ? '文字服务可达。语音、视觉和长期记忆仍未接通。' : '文字模型暂时不可达,档案和历史仍可查看。'); setError(!status.llm.ok); }
|
||||
catch (e) { setMessage((e as Error).message); setError(true); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
const settings = (value: Partial<Settings>) => setDraft(d => ({ ...d, settings: { ...d.settings, ...value } }));
|
||||
const reset = () => { request.current?.abort(); generation.current++; setBusy(false); setDraft(d => ({identity: section==='relation'?structuredClone(state.identity):d.identity, settings: {...d.settings, ...(section==='city'?{city:state.settings.city}:section==='services'?{services:structuredClone(state.settings.services)}:section==='display'?{reduced:state.settings.reduced}:{})}})); setMessage('已取消,恢复为上次保存的内容。'); setError(false); };
|
||||
async function save(confirmed = false) { if (section==='relation' && draft.identity.relation !== state.identity.relation && !confirmed) {
|
||||
setConfirm('relation');
|
||||
return;
|
||||
} request.current?.abort(); const ctrl = new AbortController(); request.current = ctrl; setBusy(true); setError(false); setMessage(real ? '正在保存…' : '正在保存到本机…'); try {
|
||||
if (real && section === 'relation') {
|
||||
const identity = await api<RealIdentity>('relation', { method: 'PATCH', signal: ctrl.signal, body: JSON.stringify({ relation: draft.identity.relation, nickname: draft.identity.nickname, boundary: draft.identity.boundary }) });
|
||||
if (!ctrl.signal.aborted) { onSave({ ...latestState.current, identity }); setMessage('已保存在服务器,聊天与底色保留。'); } return;
|
||||
}
|
||||
if (real && section === 'display') { localStorage.setItem('cg.real.display', JSON.stringify({ reduced: draft.settings.reduced })); onSave({ ...latestState.current, settings: { ...latestState.current.settings, reduced: draft.settings.reduced } }); setMessage('显示偏好已保存在此浏览器。'); return; }
|
||||
await delay(450, ctrl.signal);
|
||||
if (fail)
|
||||
throw new Error('这次没存好,你的修改还在,可以再试一次。');
|
||||
const current=latestState.current;
|
||||
const next = {...current, identity: section==='relation'?draft.identity:current.identity, settings:{...current.settings, ...(section==='city'?{city:draft.settings.city}:section==='services'?{services:draft.settings.services}:section==='display'?{reduced:draft.settings.reduced}:{})}};
|
||||
onSave(next);
|
||||
setMessage(real ? '显示偏好已应用。' : '已保存在本机演示中。');
|
||||
}
|
||||
catch (e) {
|
||||
if (ctrl.signal.aborted)
|
||||
return;
|
||||
setError(true);
|
||||
setMessage((e as Error).message);
|
||||
}
|
||||
finally {
|
||||
if (!ctrl.signal.aborted)
|
||||
setBusy(false);
|
||||
} }
|
||||
async function importBackup(file?: File) { const gen = ++generation.current; setRestore(null); if (!file)
|
||||
return; try {
|
||||
if (file.size > 5000000)
|
||||
throw new Error('请选 5MB 以内的演示 JSON。');
|
||||
const next = parseState(await file.text(), state.identity);
|
||||
if (gen !== generation.current)
|
||||
return;
|
||||
setRestore(next);
|
||||
setMessage('完整性、版本和同一位档案检查通过。可以确认恢复。');
|
||||
setError(false);
|
||||
}
|
||||
catch (e) {
|
||||
if (gen !== generation.current)
|
||||
return;
|
||||
setError(true);
|
||||
setMessage('无法恢复:' + (e as Error).message);
|
||||
} }
|
||||
async function importMaterial(file?: File) { const gen = ++generation.current; setMaterial(''); setCheck(''); if (!file)
|
||||
return; try {
|
||||
if (file.size > 100000)
|
||||
throw new Error('演示清单不能超过 100KB。');
|
||||
const x: unknown = JSON.parse(await file.text());
|
||||
if (!x || typeof x !== 'object' || !('manifest_version' in x) || x.manifest_version !== 1 || !('appearance_id' in x) || typeof x.appearance_id !== 'string' || !/^[\w-]{1,60}$/.test(x.appearance_id) || !('clips' in x) || !Array.isArray(x.clips) || !x.clips.length)
|
||||
throw new Error('需要 manifest_version:1、合法 appearance_id 和非空 clips。');
|
||||
if (gen !== generation.current)
|
||||
return;
|
||||
setMaterial(x.appearance_id);
|
||||
setCheck('✓ JSON 结构通过 · ✓ 版本通过 · 媒体格式、时长、人脸一致性:未真实检测,不应用外部媒体。');
|
||||
}
|
||||
catch (e) {
|
||||
if (gen !== generation.current)
|
||||
return;
|
||||
setCheck('检查没通过:' + (e instanceof SyntaxError?'清单不是有效的 JSON,请重新选择。':(e as Error).message));
|
||||
} }
|
||||
const switchSection = (s: string) => { request.current?.abort(); generation.current++; setBusy(false); setSection(s); setDetail(true); setMessage(''); };
|
||||
return <section hidden={!open} className={`pane pane-manage glass read ${open ? 'open' : ''} ${detail ? 'has-detail' : ''}`} aria-label="设置"><header><h2>设置</h2><span className="grow"/><span className="tag-demo">{real ? '服务器档案' : '仅本机演示'}</span><button className="btn-round sm" aria-label="关闭设置" onClick={() => requestLeave(onClose)}><Icon name="x"/></button></header><div className="cols"><nav className="snav" aria-label="设置分区">{sections.map(([id, icon, label]) => <button key={id} className={dirtySections[id] ? 'is-dirty' : ''} aria-current={section === id} onClick={() => switchSection(id)}><Icon name={icon}/>{real && id === 'backup' ? '备份' : label}<i className="dirty"/></button>)}</nav><div className="detail"><button className="btn-text back" onClick={() => setDetail(false)}><Icon name="back"/>设置</button><div className="sec-body on"><h3>{section === 'her' ? state.identity.name : real && section === 'backup' ? '备份' : sections.find(s => s[0] === section)?.[2]}</h3><p className="lead">{section === 'her' ? '她还是她。外观和关系的变化,都不会改写最初的底色。' : real ? '资料保存在服务器。尚未接通的功能暂不可用。' : '所有修改仅用于本机演示。未接通的服务会明确说明。'}</p>
|
||||
{section === 'her' && <><dl className="kv"><dt>名字</dt><dd>{state.identity.name}</dd><dt>生辰</dt><dd>{state.identity.birth} · {state.identity.hour}</dd></dl><BaseColor color={real ? (state.identity as RealIdentity).color : undefined}/><div className="growth"><div><h4>最初就有的</h4>{real ? '以上六层底色说明。生辰和原始人格参数保持只读。' : '细腻、慢热(示例)'}</div><div><h4>后来慢慢有的</h4>{state.memories.length ? '共同经历另存于回忆。' : real ? '长期记忆尚未接通。聊天记录已独立保存。' : '还在慢慢认识彼此。'}</div></div><p className="d-foot">首版只有一位,不提供新建、切换或清空。底色只读。</p></>}
|
||||
{section === 'relation' && <><Field label="你们的关系"><select className="select" value={draft.identity.relation} onChange={e => setDraft(d => ({ ...d, identity: { ...d.identity, relation: e.target.value as '朋友' | '恋人' } }))}><option>朋友</option><option>恋人</option></select></Field><Field label="她怎么称呼你"><input className="input" value={draft.identity.nickname} maxLength={40} onChange={e => setDraft(d => ({ ...d, identity: { ...d.identity, nickname: e.target.value } }))}/></Field><Field label="相处边界"><textarea className="textarea" maxLength={2000} value={draft.identity.boundary} onChange={e => setDraft(d => ({ ...d, identity: { ...d.identity, boundary: e.target.value } }))}/></Field><p className="d-foot">改关系需要再次确认,已有记忆与信任都保留,底色不变。</p></>}
|
||||
{!real && section === 'city' && <><Field label="搜索城市"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button aria-pressed={draft.settings.city === c} onClick={() => settings({ city: c })}>{c}<small>中国 · 演示城市</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <p>暂时没找到这个城市,演示清单只包含上面的六座。</p>}<p className="d-foot">城市保存后顶栏同步;天气与作息为固定演示,不请求天气服务。</p></>}
|
||||
{!real && section === 'appearance' && <><div className="card">当前素材:{state.settings.appearance}<small className="d-foot">参考静帧,不代表最终人物素材。</small></div><Field label="选择本地素材清单(演示 JSON)" hint="真实素材包格式尚待定稿。只读 JSON,不加载清单中的 URL 或脚本。"><input type="file" accept=".json,application/json" onChange={e => void importMaterial(e.target.files?.[0])}/></Field>{check && <Status text={check} error={!material}/>} {material && <><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前参考"/><figcaption>当前参考</figcaption></figure><figure className="new"><img src="/assets/her-room.jpg" alt="新外观模拟效果"/><figcaption>模拟效果 · 未加载素材</figcaption></figure></div><Button primary onClick={() => setConfirm('appearance')}>应用演示外观标识</Button></>}<p className="d-foot">只演示检查、预览与确认。媒体真实性未校验,不声称完成素材导入。</p></>}
|
||||
{!real && section === 'backup' && <><div className="card"><h4>真实后台备份 · 未接通</h4><p>服务器每日备份、数据库和素材完整备份均未提供。本地文件不包含真实后台资料。</p></div><div className="card"><h4>你自己的演示资料</h4><p>包括本机档案、设置、文字、演示日子和回忆;不包含素材文件。</p><Button onClick={() => { exportDemo(state); setMessage('已生成本地演示 JSON 下载。'); setError(false); }}>导出本地演示 JSON</Button></div><Field label="恢复同一位她的本地演示 JSON"><input type="file" accept=".json,application/json" onChange={e => void importBackup(e.target.files?.[0])}/></Field>{restore && <Button onClick={() => { setConfirmText(''); setConfirm('restore'); }}>检查通过,继续恢复</Button>}</>}
|
||||
{!real && section === 'services' && <>{Object.entries(draft.settings.services).map(([key, value]) => <div className="svc" key={key}><div className="nm">{key}<small>未接通 · 测试仅演示,不发网络请求</small></div><Button onClick={() => { setMessage(`${key}:界面演示,未真实检测。相关功能暂不可用,文字演示仍可使用。`); setError(false); }}>测试连接</Button><input className="input" aria-label={`${key}地址`} value={value} placeholder="服务地址(只保存,不连接)" onChange={e => settings({ services: { ...draft.settings.services, [key]: e.target.value } })}/></div>)}<p className="d-foot">真实麦克风和摄像头未启用。视觉窗只允许模拟状态,观察过期不当作眼前。</p></>}
|
||||
{section === 'display' && <><div className="opt-row">{(['moon', 'fog'] as Theme[]).map(t => <button className="opt" data-t={t} key={t} aria-pressed={theme === t} onClick={() => setTheme(t)}><div className="sw"/><b>{t === 'moon' ? '靛蓝月光' : '蓝紫雾光'}</b><span>立即切换,保留你的选择</span></button>)}</div><label className="switch-row">减少动效<input type="checkbox" checked={draft.settings.reduced} onChange={e => settings({ reduced: e.target.checked })}/></label><p className="d-foot">也会自动尊重系统的减少动效设置。切到其他网页时暂停背景动画。</p></>}
|
||||
{real && section === 'city' && <><div className="card"><h4>城市与天气</h4><p>尚未设置可核实的城市。城市保存、天气查询与作息联动将在后续接入。</p></div><Field label="搜索城市" hint="可浏览候选目录;当前无法保存,不会更改她的城市。"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button disabled>{c}<small>候选城市 · 保存待接入</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <div className="empty">当前目录没有匹配的城市。</div>}<div className="actions"><Button disabled>保存城市 · 待接入</Button></div></>}
|
||||
{real && section === 'appearance' && <><div className="card"><h4>当前画面</h4><p>内置参考静帧;真实素材包导入尚未接通,外观变化不会改变她的身份和底色。</p></div><Field label="选择外观素材包" hint="素材包格式与媒体检查将在后续接入。当前不上传、不读取文件。"><input type="file" disabled/></Field><ul className="phases">{['清单结构与版本', '媒体格式与时长', '人物一致性', '必要场景覆盖', '可用性与兼容性'].map(label => <li key={label}>待检查 · {label}</li>)}</ul><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前内置参考静帧"/><figcaption>当前参考</figcaption></figure><figure><div className="empty">导入并通过检查后显示新外观</div><figcaption>新旧对比 · 待接入</figcaption></figure></div><Button disabled>确认应用外观 · 待接入</Button></>}
|
||||
{real && section === 'backup' && <><div className="card"><h4>每日自动备份</h4><p>暂无可核实的备份记录。自动备份、保留份数与运行结果将在接入后显示。</p><div className="empty">尚未接通备份服务</div></div><div className="card"><h4>完整导出</h4><p>将包含服务器档案、聊天及届时接通的记录与素材。当前不生成伪备份文件。</p><Button disabled>导出完整备份 · 待接入</Button></div><Field label="恢复同一位她的备份" hint="恢复前会检查完整性、版本和同一档案,要求输入“恢复”,并先备份当前资料。当前不接收文件或执行覆盖。"><input type="file" disabled/></Field><ul className="phases">{['检查完整性与版本', '核对是否同一位她', '先备份当前资料', '输入确认并恢复'].map(label => <li key={label}>待接入 · {label}</li>)}</ul><button className="btn-danger" disabled>检查备份并继续 · 待接入</button></>}
|
||||
{real && section === 'services' && <>{[['文字对话', serviceHealth ? serviceHealth.llm.ok ? '连接可达' : '暂时不可达' : '已接通 · 可重新检查'], ['语音识别', '尚未接通'], ['语音合成', '尚未接通'], ['视觉观察', '尚未接通']].map(([label, status], index) => <div className="svc" key={label}><div className="nm">{label}<small>{status}</small></div><Button disabled={index !== 0 || busy} onClick={() => void checkService()}>{index === 0 ? busy ? '检查中…' : '重新检查连接' : '测试连接 · 待接入'}</Button><input className="input" aria-label={`${label}配置`} value={index === 0 ? '由服务器管理' : '服务尚未配置'} readOnly/></div>)}<div className="card"><h4>其余能力</h4><p>生活、长期记忆、主动消息和天气尚未接通。文字模型暂时不可达时,已保存的档案和聊天记录仍可查看。</p></div></>}
|
||||
<div ref={feedback}><Status text={message} error={error}/></div>{(real ? ['relation', 'display'] : ['relation', 'city', 'services', 'display']).includes(section) && <div className="actions"><span className={`grow ${dirty ? 'dirty' : ''}`}>{dirty ? '有未保存的修改' : '尚未修改'}</span><Button disabled={!dirty || busy} onClick={reset}>取消修改</Button><Button primary disabled={!dirty || busy} onClick={() => void save()}>{busy ? '正在保存…' : error ? '重试保存' : '保存'}</Button></div>}</div></div></div>
|
||||
{confirm && <Modal title={confirm === 'leave' ? '有未保存的修改' : confirm === 'relation' ? '改变你们的关系?' : confirm === 'restore' ? '恢复本地演示资料?' : '她还是她'} danger={confirm === 'restore'} onClose={() => setConfirm('')} disabled={confirm === 'restore' && confirmText !== '恢复'} onConfirm={() => { const which = confirm; setConfirm(''); if (which === 'leave') { request.current?.abort(); setBusy(false); setDraft({ identity: structuredClone(state.identity), settings: structuredClone(state.settings) }); const action = pendingNavigation.current; pendingNavigation.current = null; approvedNavigation.current = true; try { action?.(); } finally { approvedNavigation.current = false; } } if (which === 'relation')
|
||||
void save(true); if (which === 'appearance') {
|
||||
try {
|
||||
if (fail)
|
||||
throw new Error('这次没存好,请再试一次。');
|
||||
const next = { ...state, settings: { ...state.settings, appearance: material } };
|
||||
onSave(next);
|
||||
settings({ appearance: material });
|
||||
setMessage('演示外观标识已更新,身份与记忆保留。');
|
||||
setError(false);
|
||||
}
|
||||
catch (e) {
|
||||
setMessage((e as Error).message);
|
||||
setError(true);
|
||||
}
|
||||
} if (which === 'restore' && restore) {
|
||||
try {
|
||||
if (fail)
|
||||
throw new Error('恢复没完成,原资料仍保留,可以重试。');
|
||||
exportDemo(state);
|
||||
onSave(restore);
|
||||
setDraft({ settings: structuredClone(restore.settings), identity: structuredClone(restore.identity) });
|
||||
setRestore(null);
|
||||
setMessage('本地演示资料已恢复;恢复前的资料已先导出。');
|
||||
setError(false);
|
||||
}
|
||||
catch (e) {
|
||||
setMessage((e as Error).message);
|
||||
setError(true);
|
||||
}
|
||||
} }} confirm={confirm === 'leave' ? '放弃修改并离开' : '确认'}>{confirm === 'leave' ? <>离开会放弃尚未保存的修改。选择取消可继续编辑,已经保存的资料不会改变。</> : confirm === 'restore' ? <>恢复会覆盖当前本机演示资料。操作前会先下载当前资料,档案身份和底色须相同。<Field label="输入“恢复”以继续"><input className="input" value={confirmText} onChange={e => setConfirmText(e.target.value)}/></Field></> : <>记忆与信任都保留,八字底色不变。{confirm === 'appearance' ? '本次只更新演示标识,不接入未经校验的外部素材。' : ''}</>}</Modal>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useLayoutEffect, useRef, useState } from 'react';
|
||||
|
||||
// Identity is a turn, not a token or a database id. Finalizing a stream keeps
|
||||
// its DOM and animation. Only a replacement retains/fades out the old sentence.
|
||||
export function SoftText({ identity, text }: { identity: string; text: string }) {
|
||||
const current = useRef<HTMLSpanElement>(null), outgoing = useRef<HTMLSpanElement>(null);
|
||||
const previous = useRef({ identity, text });
|
||||
const [leaving, setLeaving] = useState<{ identity: string; text: string } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
if (previous.current.identity !== identity && previous.current.text) setLeaving(previous.current);
|
||||
previous.current = { identity, text };
|
||||
}, [identity, text]);
|
||||
useLayoutEffect(() => {
|
||||
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches || document.documentElement.classList.contains('reduced');
|
||||
const easing = getComputedStyle(document.documentElement).getPropertyValue('--ease-out').trim();
|
||||
const animation = current.current?.animate([
|
||||
{ opacity: 0, transform: reduced ? 'none' : 'translateY(3px)' },
|
||||
{ opacity: 1, transform: 'none' },
|
||||
], { duration: reduced ? 120 : 200, easing });
|
||||
return () => animation?.cancel();
|
||||
}, [identity]);
|
||||
useLayoutEffect(() => {
|
||||
if (!leaving || !outgoing.current) return;
|
||||
const animation = outgoing.current.animate([{ opacity: 1 }, { opacity: 0 }], {
|
||||
duration: 160, easing: getComputedStyle(document.documentElement).getPropertyValue('--ease-out').trim(), fill: 'forwards',
|
||||
});
|
||||
void animation.finished.then(() => setLeaving(null)).catch(() => {});
|
||||
return () => animation.cancel();
|
||||
}, [leaving]);
|
||||
return <span className="soft-text"><span key={identity} ref={current} className="current-text">{text}</span>{leaving && <span ref={outgoing} className="outgoing-text" aria-hidden="true">{leaving.text}</span>}</span>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useLayoutEffect, type ReactNode } from 'react';
|
||||
|
||||
export function Viewport({ children }: { children: ReactNode }) {
|
||||
useLayoutEffect(() => {
|
||||
const viewport = window.visualViewport, style = document.documentElement.style;
|
||||
let settle: ReturnType<typeof setTimeout>;
|
||||
const update = () => {
|
||||
// Keyboard/browser-bar geometry must follow the viewport immediately;
|
||||
// a decorative stage transition would cover the dialogue in between.
|
||||
document.documentElement.classList.add('viewport-resizing');
|
||||
clearTimeout(settle);
|
||||
settle = setTimeout(() => document.documentElement.classList.remove('viewport-resizing'), 200);
|
||||
const height = viewport?.height ?? innerHeight, top = viewport?.offsetTop ?? 0;
|
||||
style.setProperty('--view-h', `${height}px`);
|
||||
style.setProperty('--view-top', `${top}px`);
|
||||
style.setProperty('--view-bottom', `${Math.max(0, innerHeight - height - top)}px`);
|
||||
};
|
||||
update();
|
||||
viewport?.addEventListener('resize', update); viewport?.addEventListener('scroll', update);
|
||||
window.addEventListener('resize', update);
|
||||
return () => { clearTimeout(settle); viewport?.removeEventListener('resize', update); viewport?.removeEventListener('scroll', update); window.removeEventListener('resize', update); };
|
||||
}, []);
|
||||
return children;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// An open dirty form can defer a navigation until its confirmation resolves.
|
||||
export function leaveSettingsThen(action: () => void) {
|
||||
if (window.dispatchEvent(new CustomEvent('cg:leave-settings', { cancelable: true, detail: action }))) action();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { Color } from '../adapters/real';
|
||||
import { useEffect, useRef, useId, cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react';
|
||||
export function Icon({ name }: {
|
||||
name: string;
|
||||
}) { return <svg className="ico" viewBox="0 0 24 24" aria-hidden="true"><use href={`/assets/icons.svg#i-${name}`}/></svg>; }
|
||||
export function Button({ children, onClick, disabled = false, primary = false, small = true }: {
|
||||
children: ReactNode;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
primary?: boolean;
|
||||
small?: boolean;
|
||||
}) { return <button className={`${primary ? 'btn-primary' : 'btn-ghost'}${small ? ' sm' : ''}`} disabled={disabled} onClick={onClick}>{children}</button>; }
|
||||
export function Status({ text, error = false }: {
|
||||
text: string;
|
||||
error?: boolean;
|
||||
}) { return text ? <div role={error ? 'alert' : 'status'} className={`status show ${error ? 'fail' : 'ok'}`}>{text}</div> : null; }
|
||||
export function Field({ label, children, hint }: {
|
||||
label: string;
|
||||
children: ReactNode;
|
||||
hint?: string;
|
||||
}) { const id = useId(); return <label className="field" htmlFor={id}><span id={`${id}-label`}>{label}</span>{isValidElement(children) ? cloneElement(children as ReactElement<{
|
||||
id: string;
|
||||
'aria-labelledby': string;
|
||||
}>, { id, 'aria-labelledby': `${id}-label` }) : children}{hint && <small>{hint}</small>}</label>; }
|
||||
export function Modal({ title, children, onClose, onConfirm, confirm = '确认', danger = false, disabled = false }: {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
confirm?: string;
|
||||
danger?: boolean;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const close = useRef(onClose);
|
||||
close.current = onClose;
|
||||
useEffect(() => { const prev = document.activeElement as HTMLElement | null; (root.current?.querySelector<HTMLElement>('input,button:not(:disabled)') || root.current)?.focus(); const key = (e: KeyboardEvent) => { if (e.key === 'Escape') {
|
||||
e.stopImmediatePropagation();
|
||||
close.current();
|
||||
} if (e.key === 'Tab') {
|
||||
const nodes = root.current?.querySelectorAll<HTMLElement>('button:not(:disabled),input');
|
||||
if (nodes?.length) {
|
||||
const first = nodes[0], last = nodes[nodes.length - 1];
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
}
|
||||
else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
} }; document.addEventListener('keydown', key, true); return () => { document.removeEventListener('keydown', key, true); prev?.focus(); }; }, []);
|
||||
return <><div className="scrim open" onClick={onClose}/><div className={`modal glass open ${danger ? 'danger' : ''}`} ref={root} tabIndex={-1} role="dialog" aria-modal="true" aria-label={title}><div className="mi"><Icon name={danger ? 'warn' : 'sparkle'}/></div><h3>{title}</h3><div className="mb">{children}</div><div className="acts"><Button onClick={onClose}>取消</Button><Button primary disabled={disabled} onClick={onConfirm}>{confirm}</Button></div></div></>;
|
||||
}
|
||||
export function BaseColor({ color }: { color?: Color } = {}) {
|
||||
if (color) return <><div className="card birth-color"><h4><Icon name="lock"/>出生底色 · 真实排盘</h4>
|
||||
{color.calendar && <dl className="kv calendar"><dt>公历</dt><dd>{color.calendar.solar}</dd><dt>农历</dt><dd>{color.calendar.lunar}{color.calendar.leap_month && <span className="tag accent">闰月</span>}</dd><dt>出生时辰</dt><dd>{color.calendar.hour} · {color.calendar.hour_range}</dd><dt>排盘时间</dt><dd>北京时间 {color.calendar.calculation_time}</dd></dl>}
|
||||
<div className="pillars">{[['year','年柱'], ['month','月柱'], ['day','日柱'], ['time','时柱']].map(([key, label]) => <div key={key}><small>{label}</small><b>{color.pillars[key]}</b></div>)}</div>
|
||||
<details className="birth-help"><summary>四柱、日主和农历,分别是什么?</summary><p>四柱是出生年、月、日、时的四组干支,合起来为八个字。日柱的第一个字叫日主,是解释组合的参照。五行描述组合的侧重,十神描述各天干与日主的关系,不是十种好坏标签。</p><p>{color.calendar?.rule || '月柱按节气划分,与农历月份不是同一回事。'}</p></details>
|
||||
<p className="d-foot">{color.interpretation || '当前档案尚未提供分层说明,请更新服务后重试。原底色保留。'}</p>
|
||||
<div className="color-sections">{color.sections?.map(section => <section key={section.id}><h4>{section.title}</h4><p>{section.text}</p><details><summary>这段说明的依据</summary><p>{section.basis}</p></details></section>)}</div>
|
||||
</div><p className="lock"><Icon name="lock"/>确认创建后,生辰与底色只读;后来的成长另存。</p></>;
|
||||
return <><div className="card"><h4><Icon name="lock"/>出生底色 · 演示预览</h4><div className="pillars">{['年柱', '月柱', '日柱', '时柱'].map(p => <div key={p}><small>{p}</small><b>待接</b></div>)}</div><p>演示不执行排盘,不用固定八字或性格代替计算。普通入口会显示真实公历、农历、四柱和六层底色说明。</p></div><p className="lock"><Icon name="lock"/>确认创建后,生辰与底色只读,成长另存。</p></>;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function Background() {
|
||||
return <div className="space" aria-hidden="true"><div className="layer">{['moon', 'fog'].map(theme => <div className={`scene ${theme}`} key={theme}><div className="sky"/>{theme === 'moon' ? <><div className="moon-halo"/><div className="moon-disc"/></> : <>{[1, 2, 3].map(i => <div className={`ribbon r${i}`} key={i}/>)}</>}{['far', 'near'].map((depth, index) => <div className={`skyline ${depth}`} key={depth}><svg viewBox="0 0 1440 400" preserveAspectRatio="none"><defs><linearGradient id={`${theme}-${depth}`} x1="0" y1="0" x2="0" y2="1"><stop stopColor={theme === 'moon' ? '#121f46' : '#33215c'}/><stop offset="1" stopColor={theme === 'moon' ? '#060c22' : '#170e32'}/></linearGradient></defs>{Array.from({ length: 28 }, (_, i) => { const h = 45 + (i * 71 + index * 37) % 180; return <g key={i}><rect x={i * 54} y={400 - h} width={40 + i % 3 * 4} height={h} fill={`url(#${theme}-${depth})`}/>{Array.from({ length: 3 }, (_, j) => <rect key={j} x={i * 54 + 9 + j * 9} y={420 - h} width="3" height="6" fill="#b1cbff" opacity=".3"/>)}</g>; })}</svg></div>)}{[1, 2, 3, 4].map(i => <div className={`mist m${i}`} key={i}/>)}{[1, 2, 3].map(i => <div className={`bokeh b${i}`} key={i}/>)}</div>)}</div><div className="vignette"/><div className="depth-veil"/></div>;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useState } from 'react';
|
||||
import type { SceneDesc } from '../domain/model';
|
||||
import { Icon } from '../shared/ui';
|
||||
export interface PresenterProps {
|
||||
scene: SceneDesc;
|
||||
real?: boolean;
|
||||
onClose: () => void;
|
||||
closeLabel: string;
|
||||
presence: string;
|
||||
observation: string;
|
||||
}
|
||||
// Only consumes scene. No life writes, no synthesis, no microphone/camera APIs.
|
||||
export function FallbackPresenter({ scene, onClose, closeLabel, presence, observation, real = false }: PresenterProps) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
return <><section className="portal" aria-label="她的视窗"><div className="life">{!failed && <><img className="img-room" src="/assets/her-room.jpg" alt="卧室窗边的人物参考静帧" onError={() => setFailed(true)}/><img className="img-talk" src="/assets/her-talk.jpg" alt="同一人物的交谈近景参考静帧" onError={() => setFailed(true)}/></>}</div>{failed && <div className="empty">画面暂时没打开,文字仍可使用。</div>}<div className="tint"/><div className="doing"><span className="chip glass"><Icon name="book"/>{scene.activity}</span><span className="tag-demo">{real ? '生活尚未接通' : '演示状态'}</span></div><div className="topleft"><span className="chip">{presence}</span>{observation && <span className="chip observe show">{observation}</span>}</div><button className="close" onClick={onClose}><Icon name="back"/>{closeLabel}</button><span className="mark">示意画面 · 参考静帧</span></section><div className="mini-cap"><b>她此刻 · {scene.activity}</b>{real ? '生活尚未接通' : '来自演示生活状态'}<br />画面为示意静帧<button className="btn-text" onClick={onClose}>回到她身边</button></div></>;
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
/* Approved HEL-746 R2 component styles; edit here, never add override sheets. */
|
||||
*{box-sizing:border-box;margin:0;padding:0;scrollbar-width:thin;scrollbar-color:var(--scroll-thumb) var(--scroll-track)}
|
||||
html{color-scheme:dark}
|
||||
*::-webkit-scrollbar{width:8px;height:8px}
|
||||
*::-webkit-scrollbar-track{background:var(--scroll-track);border-radius:8px}
|
||||
*::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border:2px solid var(--scroll-track);border-radius:8px}
|
||||
@media(hover:hover) and (pointer:fine){*::-webkit-scrollbar-thumb:hover{background:var(--scroll-hover)}}
|
||||
@media(forced-colors:active){*{scrollbar-color:auto}*::-webkit-scrollbar-thumb{background:ButtonText}*::-webkit-scrollbar-track{background:Canvas}}
|
||||
html,body{height:100%;overflow:hidden;background:var(--bg-0);transition:background-color var(--dur-theme) var(--ease-in-out)}
|
||||
body{font-family:var(--font-sans);color:var(--text-1);font-size:var(--fs-body);line-height:1.7;-webkit-font-smoothing:antialiased;letter-spacing:.01em}
|
||||
button,input,select,textarea{font:inherit;color:inherit}
|
||||
button{cursor:pointer;background:none;border:0}
|
||||
button:disabled{cursor:not-allowed;opacity:.42}
|
||||
svg{display:block}
|
||||
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
|
||||
.ico{width:18px;height:18px;flex:none}
|
||||
|
||||
/* ============================================================
|
||||
背景空间(R1 原样)
|
||||
============================================================ */
|
||||
.space{position:fixed;inset:0;overflow:hidden;transition:transform var(--dur-stage) var(--ease-out),filter var(--dur-stage) var(--ease-out)}
|
||||
.layer{position:absolute;inset:-6%;will-change:transform;transition:transform 1.2s var(--ease-out)}
|
||||
.scene{position:absolute;inset:0;opacity:0;transition:opacity var(--dur-theme) var(--ease-in-out)}
|
||||
html[data-theme="moon"] .scene.moon,html[data-theme="fog"] .scene.fog{opacity:1}
|
||||
.scene.moon .sky{position:absolute;inset:0;background:radial-gradient(120% 80% at 24% 12%,#24386f 0%,rgba(36,56,111,0) 55%),linear-gradient(180deg,#081028 0%,#0e1a3e 46%,#16264f 72%,#0b1430 100%)}
|
||||
.scene.fog .sky{position:absolute;inset:0;background:radial-gradient(90% 70% at 12% 92%,rgba(176,108,220,.55) 0%,rgba(176,108,220,0) 60%),radial-gradient(80% 60% at 92% 8%,rgba(92,92,210,.45) 0%,rgba(92,92,210,0) 60%),linear-gradient(170deg,#1a1240 0%,#2b1d5c 45%,#3e2b78 70%,#1c1338 100%)}
|
||||
.moon-disc{position:absolute;left:17%;top:14%;width:78px;height:78px;border-radius:50%;filter:blur(.4px);background:radial-gradient(circle at 50% 50%,#ffffff 0%,#f4f8ff 50%,#e2ecff 64%,rgba(226,236,255,.5) 68%,rgba(226,236,255,0) 71%);box-shadow:0 0 60px 18px rgba(170,205,255,.28),0 0 220px 90px rgba(120,160,255,.18);animation:moonBreath 14s var(--ease-drift) infinite alternate;transition:opacity var(--dur-stage)}
|
||||
.moon-halo{position:absolute;left:calc(17% - 276px);top:calc(14% - 276px);width:630px;height:630px;border-radius:50%;background:radial-gradient(circle,rgba(160,200,255,.20) 0%,rgba(160,200,255,.06) 40%,rgba(160,200,255,0) 70%);transition:opacity var(--dur-stage)}
|
||||
@keyframes moonBreath{from{filter:blur(.4px) brightness(.9);transform:scale(1)}to{filter:blur(.4px) brightness(1.05);transform:scale(1.03)}}
|
||||
.ribbon{position:absolute;border-radius:50%;filter:blur(48px);opacity:.5}
|
||||
.ribbon.r1{left:-10%;top:18%;width:80%;height:22%;background:linear-gradient(90deg,rgba(150,110,255,0),rgba(190,140,255,.75),rgba(255,160,220,.0));transform:rotate(-8deg);animation:ribbon1 38s var(--ease-drift) infinite alternate}
|
||||
.ribbon.r2{right:-14%;top:44%;width:70%;height:18%;background:linear-gradient(90deg,rgba(120,140,255,0),rgba(150,160,255,.65),rgba(230,170,255,0));transform:rotate(10deg);animation:ribbon2 46s var(--ease-drift) infinite alternate}
|
||||
.ribbon.r3{left:20%;bottom:-6%;width:70%;height:30%;background:radial-gradient(closest-side,rgba(240,170,255,.55),rgba(240,170,255,0));animation:ribbon1 52s var(--ease-drift) infinite alternate-reverse}
|
||||
@keyframes ribbon1{from{transform:translate3d(-4%,0,0) rotate(-8deg) scaleY(1)}to{transform:translate3d(6%,-3%,0) rotate(-3deg) scaleY(1.25)}}
|
||||
@keyframes ribbon2{from{transform:translate3d(3%,0,0) rotate(10deg)}to{transform:translate3d(-7%,4%,0) rotate(4deg)}}
|
||||
.skyline{position:absolute;left:0;right:0;bottom:0;height:46%}
|
||||
.skyline svg{width:100%;height:100%}
|
||||
.scene.moon .skyline.far{opacity:.34;filter:blur(2px)}
|
||||
.scene.moon .skyline.near{opacity:.42;filter:blur(1px);height:30%}
|
||||
.scene.fog .skyline.far{opacity:.22;filter:blur(3px)}
|
||||
.scene.fog .skyline.near{opacity:.34;filter:blur(1.8px);height:32%}
|
||||
.skyline .win{animation:winBlink 9s steps(1) infinite}
|
||||
@keyframes winBlink{0%,100%{opacity:1}50%{opacity:.35}}
|
||||
.mist{position:absolute;left:-30%;width:160%;border-radius:50%;filter:blur(40px)}
|
||||
.scene.moon .mist{background:radial-gradient(closest-side,rgba(150,180,240,.22),rgba(150,180,240,0))}
|
||||
.scene.fog .mist{background:radial-gradient(closest-side,rgba(205,170,255,.34),rgba(205,170,255,0))}
|
||||
.mist.m1{bottom:2%;height:26%;animation:mistA 64s linear infinite alternate}
|
||||
.mist.m2{bottom:18%;height:18%;animation:mistB 48s linear infinite alternate}
|
||||
.mist.m3{bottom:-8%;height:30%;animation:mistA 80s linear infinite alternate-reverse}
|
||||
.scene.fog .mist.m4{top:30%;height:40%;opacity:.7;animation:mistB 70s linear infinite alternate}
|
||||
@keyframes mistA{from{transform:translate3d(-6%,0,0)}to{transform:translate3d(8%,-2%,0)}}
|
||||
@keyframes mistB{from{transform:translate3d(6%,0,0)}to{transform:translate3d(-8%,2%,0)}}
|
||||
#motes{position:absolute;inset:0;width:100%;height:100%}
|
||||
.bokeh{position:absolute;border-radius:50%;filter:blur(22px)}
|
||||
.scene.moon .bokeh{background:rgba(170,210,255,.13)}
|
||||
.scene.fog .bokeh{background:rgba(240,190,255,.16)}
|
||||
.bokeh.b1{left:3%;top:64%;width:180px;height:180px}
|
||||
.bokeh.b2{right:4%;top:6%;width:120px;height:120px}
|
||||
.bokeh.b3{left:44%;bottom:-4%;width:240px;height:240px;opacity:.7}
|
||||
.vignette{position:absolute;inset:0;pointer-events:none;background:radial-gradient(120% 90% at 50% 45%,rgba(0,0,0,0) 55%,rgba(0,0,8,.55) 100%)}
|
||||
.depth-veil{position:absolute;inset:0;pointer-events:none;opacity:0;transition:opacity var(--dur-stage) var(--ease-out);background:radial-gradient(70% 70% at 50% 42%,rgba(0,0,0,0) 30%,rgba(2,4,16,.55) 100%)}
|
||||
.window-glow{position:fixed;pointer-events:none;border-radius:50%;filter:blur(30px);background:radial-gradient(closest-side,var(--window-glow),rgba(0,0,0,0));transition:all var(--dur-stage) var(--ease-out),background var(--dur-theme)}
|
||||
|
||||
body.talk .space{transform:scale(1.06)}
|
||||
body.talk .depth-veil{opacity:1}
|
||||
body.talk .moon-disc,body.talk .moon-halo{opacity:.35}
|
||||
/* 进入日子 / 设置:空间轻推近 1.03 并压暗,仍在同一主题空间里 */
|
||||
body.paned .space{transform:scale(1.03)}
|
||||
body.paned .depth-veil{opacity:.7}
|
||||
body.creating .space{transform:scale(1.02);filter:saturate(.9)}
|
||||
body.creating .depth-veil{opacity:.5}
|
||||
|
||||
/* ============================================================
|
||||
通用组件
|
||||
============================================================ */
|
||||
.glass{background:var(--glass);border:1px solid var(--glass-line);-webkit-backdrop-filter:blur(var(--glass-blur)) saturate(var(--glass-sat));backdrop-filter:blur(var(--glass-blur)) saturate(var(--glass-sat));box-shadow:inset 0 1px 0 var(--glass-hi),0 18px 50px -20px rgba(0,0,10,.55);transition:background-color var(--dur-theme) var(--ease-in-out),border-color var(--dur-theme) var(--ease-in-out),box-shadow var(--dur-ui)}
|
||||
html[data-theme="fog"] .glass{box-shadow:inset 0 1px 0 var(--glass-hi),inset 0 0 36px rgba(210,170,255,.10),0 18px 50px -20px rgba(10,0,30,.55)}
|
||||
.glass.read{background:var(--glass-read)}
|
||||
|
||||
.chip{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 14px;border-radius:var(--radius-pill);font-size:var(--fs-meta);color:var(--text-2);white-space:nowrap}
|
||||
.chip svg{width:15px;height:15px;opacity:.85}
|
||||
.tag-demo{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:var(--radius-pill);font-size:var(--fs-tiny);color:var(--text-3);border:1px dashed var(--glass-line);white-space:nowrap}
|
||||
.tag{display:inline-flex;align-items:center;gap:5px;height:22px;padding:0 9px;border-radius:var(--radius-pill);font-size:var(--fs-tiny);color:var(--text-2);background:rgba(255,255,255,.06);white-space:nowrap}
|
||||
.tag.accent{color:var(--accent);background:var(--accent-soft)}
|
||||
.tag.ok{color:var(--ok);background:rgba(159,232,207,.1)}
|
||||
.tag.warn{color:var(--warn);background:rgba(255,215,156,.1)}
|
||||
.tag.danger{color:var(--danger);background:rgba(255,159,179,.1)}
|
||||
.tag svg{width:12px;height:12px}
|
||||
|
||||
.btn-primary{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:10px;height:52px;padding:0 26px;border-radius:var(--radius-pill);background:var(--accent);color:var(--on-accent);font-weight:500;font-size:15.5px;letter-spacing:.04em;box-shadow:0 0 0 1px rgba(255,255,255,.25) inset,0 0 26px -2px var(--accent-glow),0 10px 30px -12px var(--accent-glow);transition:transform var(--dur-fast) var(--ease-out),box-shadow var(--dur-ui),background-color var(--dur-theme),opacity var(--dur-ui)}
|
||||
.btn-primary:hover:not(:disabled){box-shadow:0 0 0 1px rgba(255,255,255,.3) inset,0 0 38px 2px var(--accent-glow),0 10px 30px -12px var(--accent-glow)}
|
||||
.btn-primary:disabled{box-shadow:none}
|
||||
.btn-primary svg{width:18px;height:18px}
|
||||
.btn-primary.sm,.btn-ghost.sm,.btn-danger.sm{height:40px;padding:0 18px;font-size:14px}
|
||||
.btn-ghost{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:48px;padding:0 22px;border-radius:var(--radius-pill);border:1px solid var(--glass-line);color:var(--text-1);font-size:14.5px;transition:background-color var(--dur-ui),transform var(--dur-fast) var(--ease-out)}
|
||||
.btn-ghost:hover:not(:disabled){background:var(--accent-soft)}
|
||||
.btn-ghost svg{width:16px;height:16px}
|
||||
.btn-danger{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:48px;padding:0 22px;border-radius:var(--radius-pill);border:1px solid var(--danger);color:var(--danger);font-size:14.5px;transition:background-color var(--dur-ui)}
|
||||
.btn-danger:hover:not(:disabled){background:rgba(255,159,179,.1)}
|
||||
.btn-text{display:inline-flex;align-items:center;gap:6px;color:var(--text-2);font-size:13.5px;padding:4px 2px}
|
||||
.btn-text:hover{color:var(--text-1)}
|
||||
.btn-text svg{width:14px;height:14px}
|
||||
.btn-primary:active:not(:disabled),.btn-ghost:active:not(:disabled),.btn-round:active,.nav-item:active,.btn-danger:active{transform:scale(.97)}
|
||||
.btn-round{width:52px;height:52px;border-radius:50%;display:grid;place-items:center;color:var(--text-1);flex:none;transition:transform var(--dur-fast) var(--ease-out),background-color var(--dur-ui),color var(--dur-ui)}
|
||||
.btn-round svg{width:21px;height:21px}
|
||||
.btn-round:hover{background:var(--accent-soft)}
|
||||
.btn-round.sm{width:40px;height:40px}
|
||||
.btn-round.sm svg{width:18px;height:18px}
|
||||
:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
|
||||
.spin{width:16px;height:16px;border-radius:50%;border:2px solid currentColor;border-right-color:transparent;animation:spin .9s linear infinite;flex:none}
|
||||
@keyframes spin{to{transform:rotate(360deg)}}
|
||||
|
||||
/* 表单 */
|
||||
.field{display:block;margin:0 0 18px}
|
||||
.field > span{display:block;font-size:13px;color:var(--text-2);margin-bottom:7px}
|
||||
.field small{display:block;font-size:12px;color:var(--text-3);margin-top:6px;line-height:1.6}
|
||||
.field.err small.msg{color:var(--danger)}
|
||||
.input,.select,.textarea{width:100%;height:46px;border-radius:var(--radius-field);background:var(--field);border:1px solid var(--field-line);padding:0 14px;font-size:15px;color:var(--text-1);outline:none;transition:border-color var(--dur-ui),box-shadow var(--dur-ui),background-color var(--dur-theme)}
|
||||
.textarea{height:auto;min-height:96px;padding:12px 14px;line-height:1.7;resize:vertical}
|
||||
.select{appearance:none;background-image:linear-gradient(45deg,transparent 50%,var(--text-3) 50%),linear-gradient(135deg,var(--text-3) 50%,transparent 50%);background-position:calc(100% - 20px) 20px,calc(100% - 15px) 20px;background-size:5px 5px;background-repeat:no-repeat}
|
||||
.select option{background:var(--bg-1);color:var(--text-1)}
|
||||
.input:focus,.select:focus,.textarea:focus{border-color:var(--accent);box-shadow:0 0 0 4px var(--accent-soft)}
|
||||
.field.err .input,.field.err .select{border-color:var(--danger)}
|
||||
.input[readonly]{color:var(--text-2);background:transparent;border-style:dashed}
|
||||
.row2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
|
||||
.seg{display:inline-flex;padding:3px;border-radius:var(--radius-pill);gap:2px;background:var(--field);border:1px solid var(--field-line)}
|
||||
.seg button{height:38px;padding:0 18px;border-radius:var(--radius-pill);font-size:14px;color:var(--text-2);transition:background-color var(--dur-ui),color var(--dur-ui)}
|
||||
.seg button[aria-pressed="true"]{color:var(--on-accent);background:var(--accent);box-shadow:0 0 16px -4px var(--accent-glow)}
|
||||
.check{display:flex;gap:10px;align-items:flex-start;font-size:14px;color:var(--text-2);cursor:pointer;line-height:1.6}
|
||||
.check input{appearance:none;width:20px;height:20px;border-radius:6px;border:1.5px solid var(--glass-line);flex:none;margin-top:1px;display:grid;place-items:center;transition:background-color var(--dur-ui),border-color var(--dur-ui)}
|
||||
.check input:checked{background:var(--accent);border-color:var(--accent)}
|
||||
.check input:checked::after{content:"";width:9px;height:5px;border-left:2px solid var(--on-accent);border-bottom:2px solid var(--on-accent);transform:rotate(-45deg) translate(1px,-1px)}
|
||||
.toggle{width:44px;height:26px;border-radius:13px;background:rgba(255,255,255,.12);position:relative;flex:none;transition:background-color var(--dur-ui)}
|
||||
.toggle::after{content:"";position:absolute;left:3px;top:3px;width:20px;height:20px;border-radius:50%;background:#fff;transition:transform var(--dur-ui) var(--ease-out)}
|
||||
.toggle[aria-pressed="true"]{background:var(--accent)}
|
||||
.toggle[aria-pressed="true"]::after{transform:translateX(18px)}
|
||||
.progress{height:6px;border-radius:3px;background:rgba(255,255,255,.08);overflow:hidden}
|
||||
.progress i{display:block;height:100%;width:0;border-radius:3px;background:var(--accent);box-shadow:0 0 12px var(--accent-glow);transition:width 400ms var(--ease-out)}
|
||||
|
||||
/* 状态行(进行中 / 成功 / 失败) */
|
||||
.status{display:none;align-items:center;gap:8px;font-size:13.5px;padding:10px 14px;border-radius:14px;margin:12px 0 0}
|
||||
.status.show{display:flex}
|
||||
.status.busy{color:var(--text-2);background:rgba(255,255,255,.04)}
|
||||
.status.ok{color:var(--ok);background:rgba(159,232,207,.08)}
|
||||
.status.fail{color:var(--danger);background:rgba(255,159,179,.08)}
|
||||
.status svg{width:16px;height:16px;flex:none}
|
||||
.status .grow{flex:1}
|
||||
|
||||
/* ============================================================
|
||||
顶栏
|
||||
============================================================ */
|
||||
.topbar{position:fixed;top:calc(var(--view-top) + 22px);left:32px;right:32px;display:flex;align-items:center;justify-content:space-between;z-index:30;pointer-events:none;transition:opacity var(--dur-panel)}
|
||||
.topbar > *{pointer-events:auto}
|
||||
.who{display:flex;align-items:center;gap:12px}
|
||||
.who .name{font-size:19px;font-weight:400;letter-spacing:.14em}
|
||||
.dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 10px 2px var(--accent-glow);animation:dotPulse 3.6s var(--ease-drift) infinite}
|
||||
body.offline .dot{background:var(--text-3);box-shadow:none;animation:none}
|
||||
@keyframes dotPulse{0%,100%{opacity:.65}50%{opacity:1}}
|
||||
.who .state{font-size:var(--fs-meta);color:var(--text-3)}
|
||||
.env{display:flex;align-items:center;gap:10px}
|
||||
.clock{font-family:var(--font-num);font-weight:300;font-size:22px;letter-spacing:.04em;color:var(--text-1);margin-left:4px}
|
||||
.clock small{font-size:12px;color:var(--text-3);margin-left:6px;font-family:var(--font-sans)}
|
||||
.theme-switch{display:flex;padding:3px;border-radius:var(--radius-pill);gap:2px}
|
||||
.theme-switch button{height:28px;padding:0 12px;border-radius:var(--radius-pill);font-size:12.5px;color:var(--text-3);display:flex;align-items:center;gap:6px;transition:color var(--dur-ui),background-color var(--dur-ui)}
|
||||
.theme-switch button i{width:9px;height:9px;border-radius:50%;display:block}
|
||||
.theme-switch button[data-t="moon"] i{background:linear-gradient(135deg,#d9ecff,#5a7fd6)}
|
||||
.theme-switch button[data-t="fog"] i{background:linear-gradient(135deg,#f3c8ff,#6c4fd0)}
|
||||
.theme-switch button[aria-pressed="true"]{color:var(--text-1);background:var(--accent-soft);box-shadow:0 0 14px -4px var(--accent-glow)}
|
||||
body.creating .topbar .who,body.creating .topbar .env > :not(.theme-switch){opacity:0;pointer-events:none}
|
||||
|
||||
/* 断线横幅 */
|
||||
.netbar{position:fixed;left:50%;top:70px;transform:translate(-50%,-10px);z-index:48;display:flex;align-items:center;gap:10px;height:42px;padding:0 8px 0 16px;border-radius:var(--radius-pill);font-size:13.5px;color:var(--text-1);opacity:0;pointer-events:none;transition:opacity var(--dur-ui),transform var(--dur-ui) var(--ease-out)}
|
||||
.netbar.show{opacity:1;transform:translate(-50%,0);pointer-events:auto}
|
||||
.netbar .spin{color:var(--warn)}
|
||||
.netbar .warn-dot{width:8px;height:8px;border-radius:50%;background:var(--danger);display:none}
|
||||
.netbar.failed .spin{display:none}
|
||||
.netbar.failed .warn-dot{display:block}
|
||||
.netbar .btn-ghost{height:30px;padding:0 12px;font-size:12.5px;display:none}
|
||||
.netbar.failed .btn-ghost{display:inline-flex}
|
||||
.netbar small{color:var(--text-3);font-size:12px}
|
||||
|
||||
/* ============================================================
|
||||
她的视窗(舞台)
|
||||
============================================================ */
|
||||
.portal{position:fixed;z-index:10;overflow:hidden;
|
||||
--pw:clamp(300px,27vw,430px); --ph:calc(var(--pw) * 1.3);
|
||||
--pl:calc(100vw - var(--pw) - 14vw); --pt:calc((100vh - var(--ph)) / 2 - 8px);
|
||||
--pr:calc(var(--pw) / 2) calc(var(--pw) / 2) 26px 26px;
|
||||
left:var(--pl);top:var(--pt);width:var(--pw);height:var(--ph);border-radius:var(--pr);
|
||||
box-shadow:0 0 0 1px var(--glass-line),0 0 0 8px rgba(255,255,255,.025),0 40px 90px -30px rgba(0,0,10,.8),0 0 80px -20px var(--window-glow);
|
||||
transition:left var(--dur-stage) var(--ease-out),top var(--dur-stage) var(--ease-out),width var(--dur-stage) var(--ease-out),height var(--dur-stage) var(--ease-out),border-radius var(--dur-stage) var(--ease-out),box-shadow var(--dur-theme),opacity var(--dur-panel),filter var(--dur-panel)}
|
||||
.portal img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity 620ms var(--ease-in-out) 120ms,transform var(--dur-stage) var(--ease-out)}
|
||||
.portal .img-room{object-position:88% 42%;transform:scale(1.16);transform-origin:80% 42%}
|
||||
html.viewport-resizing .portal{transition:none}
|
||||
.portal .img-talk{object-position:54% 28%;opacity:0;transform:scale(1.08);transform-origin:54% 30%}
|
||||
.portal .life{position:absolute;inset:0;animation:kenburns 26s var(--ease-drift) infinite alternate}
|
||||
@keyframes kenburns{from{transform:scale(1) translate3d(0,0,0)}to{transform:scale(1.045) translate3d(-1.2%,-.6%,0)}}
|
||||
.portal .tint{position:absolute;inset:0;pointer-events:none;transition:background var(--dur-theme)}
|
||||
html[data-theme="moon"] .portal .tint{background:linear-gradient(180deg,rgba(40,70,150,.20) 0%,rgba(10,20,50,0) 35%,rgba(8,14,40,.55) 100%)}
|
||||
html[data-theme="fog"] .portal .tint{background:linear-gradient(180deg,rgba(140,90,220,.24) 0%,rgba(40,20,80,0) 40%,rgba(30,14,60,.55) 100%)}
|
||||
.portal .rain{position:absolute;inset:0;pointer-events:none;opacity:.22;background-image:repeating-linear-gradient(104deg,rgba(255,255,255,.0) 0 9px,rgba(255,255,255,.35) 9px 10px,rgba(255,255,255,0) 10px 22px);background-size:220px 220px;animation:rain 1.6s linear infinite;mix-blend-mode:screen;mask-image:linear-gradient(180deg,#000 0%,rgba(0,0,0,.2) 60%,transparent 80%)}
|
||||
@keyframes rain{to{background-position:-60px 220px}}
|
||||
.portal .doing{position:absolute;left:18px;right:18px;bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:8px;transition:opacity var(--dur-ui)}
|
||||
.portal .doing .chip{background:rgba(8,10,28,.38);color:var(--text-1);border-color:rgba(255,255,255,.14)}
|
||||
.portal .mark{position:absolute;right:18px;bottom:58px;font-size:10.5px;color:rgba(255,255,255,.55);letter-spacing:.06em;transition:opacity var(--dur-ui)}
|
||||
.portal .close{position:absolute;top:16px;right:16px;height:36px;padding:0 14px 0 12px;border-radius:var(--radius-pill);display:flex;align-items:center;gap:6px;font-size:13px;color:var(--text-1);background:rgba(8,10,28,.36);border:1px solid rgba(255,255,255,.16);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);opacity:0;pointer-events:none;transform:translateY(-6px);transition:opacity var(--dur-ui),transform var(--dur-ui) var(--ease-out)}
|
||||
.portal .close svg{width:16px;height:16px}
|
||||
.portal .topleft{position:absolute;left:18px;top:16px;display:flex;flex-direction:column;align-items:flex-start;gap:8px;opacity:0;transition:opacity var(--dur-ui)}
|
||||
.portal .topleft .chip{background:rgba(8,10,28,.42);color:var(--text-1);border:1px solid rgba(255,255,255,.12);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}
|
||||
.observe{display:none;max-width:min(420px,60vw);white-space:normal;height:auto !important;min-height:32px;padding:6px 14px !important;line-height:1.5}
|
||||
.observe.show{display:inline-flex}
|
||||
.observe .eye{width:8px;height:8px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok);flex:none}
|
||||
.observe.stale{opacity:.7}
|
||||
.observe.stale .eye{background:var(--warn);box-shadow:none}
|
||||
.observe.fail .eye{background:var(--danger);box-shadow:none}
|
||||
.observe.asking .eye{background:var(--text-3);box-shadow:none}
|
||||
|
||||
body.talk .portal{--pw:min(64vw, calc(var(--talk-stage-h) * 1.72)); --ph:var(--talk-stage-h); --pl:calc(50vw - var(--pw) / 2 + var(--shift)); --pt:calc(var(--view-top) + 72px); --pr:var(--radius-stage) var(--radius-stage) var(--radius-stage) var(--radius-stage)}
|
||||
body.talk.voice{--talk-stage-h:clamp(64px,calc(var(--view-h) - 472px),488px)}
|
||||
body{--shift:0px}
|
||||
body.talk.log{--shift:-200px}
|
||||
body.talk .portal .img-room{opacity:0;transform:scale(2.1);transform-origin:84% 38%}
|
||||
body.talk .portal .img-talk{opacity:1;transform:scale(1)}
|
||||
body.talk .portal .doing{opacity:0}
|
||||
body.talk .portal .mark{bottom:18px}
|
||||
body.talk .portal .close{opacity:1;pointer-events:auto;transform:none;transition-delay:280ms}
|
||||
body.talk .portal .topleft{opacity:1}
|
||||
body.offline .portal{filter:saturate(.55) brightness(.7)}
|
||||
|
||||
/* 日子 / 设置时:窗缩小留在右侧,她仍在同一个空间里 */
|
||||
body.paned .portal{--pw:var(--mini-pw); --ph:calc(var(--pw) * 1.3); --pl:calc(var(--pane-l) + var(--pane-w) + (100vw - var(--pane-l) - var(--pane-w) - var(--pw)) / 2); --pt:calc(var(--pane-t) + 28px)}
|
||||
body.paned .portal .doing{left:10px;right:10px;bottom:10px}
|
||||
body.paned .portal .doing .tag-demo,body.paned .portal .mark{display:none}
|
||||
body.paned .portal .doing .chip{height:28px;padding:0 10px;font-size:12px}
|
||||
.mini-cap{position:fixed;z-index:11;left:calc(var(--pane-l) + var(--pane-w) + (100vw - var(--pane-l) - var(--pane-w) - var(--mini-pw)) / 2);top:calc(var(--pane-t) + 28px + var(--mini-pw) * 1.3 + 16px);width:var(--mini-pw);text-align:center;font-size:12.5px;color:var(--text-3);line-height:1.6;opacity:0;pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out)}
|
||||
body.paned .mini-cap{opacity:1;pointer-events:auto;transition-delay:240ms}
|
||||
.mini-cap b{display:block;font-weight:400;color:var(--text-2);font-size:13px}
|
||||
.mini-cap button{margin-top:8px}
|
||||
body.creating .portal,body.creating .window-glow{opacity:0;pointer-events:none}
|
||||
|
||||
/* ============================================================
|
||||
首页
|
||||
============================================================ */
|
||||
.home{position:fixed;left:9vw;top:50%;width:min(440px,34vw);transform:translateY(-50%);z-index:12;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-stage) var(--ease-out),filter var(--dur-panel)}
|
||||
body.talk .home,body.paned .home,body.creating .home{opacity:0;transform:translate(-40px,-50%) scale(.96);filter:blur(6px);pointer-events:none}
|
||||
.home .eyebrow{font-size:var(--fs-meta);color:var(--text-3);letter-spacing:.2em;margin-bottom:14px}
|
||||
.home .whisper{font-size:var(--fs-whisper);font-weight:300;line-height:1.5;letter-spacing:.04em;color:var(--text-1);text-wrap:balance}
|
||||
.home .meta{margin-top:14px;color:var(--text-2);font-size:14px;display:flex;flex-wrap:wrap;gap:8px 14px;align-items:center}
|
||||
.home .meta span{display:inline-flex;align-items:center;gap:6px}
|
||||
.letter{margin-top:34px;padding:18px 20px 16px;border-radius:var(--radius-card);display:block;width:100%;text-align:left;transition:transform var(--dur-ui) var(--ease-out),background-color var(--dur-theme),border-color var(--dur-theme)}
|
||||
.letter:hover{transform:translateY(-2px)}
|
||||
.letter .lh{display:flex;align-items:center;justify-content:space-between;font-size:var(--fs-meta);color:var(--text-3);margin-bottom:6px}
|
||||
.letter .lh b{font-weight:500;color:var(--accent);display:inline-flex;align-items:center;gap:6px}
|
||||
.letter .lh b::before{content:"";width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent-glow)}
|
||||
.letter.read .lh b{color:var(--text-2)}
|
||||
.letter.read .lh b::before{background:var(--text-3);box-shadow:none}
|
||||
.letter p{color:var(--text-1);font-size:15px;line-height:1.75;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
|
||||
.away{margin-top:12px;display:flex;align-items:center;gap:8px;font-size:13.5px;color:var(--text-2);padding:2px 4px;text-align:left}
|
||||
.away svg{width:14px;height:14px}
|
||||
.away:hover{color:var(--text-1)}
|
||||
.cta{margin-top:30px;display:flex;align-items:center;gap:12px}
|
||||
.cta .btn-round{border:1px solid var(--glass-line)}
|
||||
.first-note{margin-top:22px;font-size:13.5px;color:var(--text-2);line-height:1.8;display:none}
|
||||
body.data-empty .letter,body.data-empty .away,body.data-empty .home .meta{display:none}
|
||||
body.data-empty .first-note{display:block}
|
||||
|
||||
/* 返回时的「你不在的这两天」 */
|
||||
.welcome{position:fixed;left:9vw;top:50%;width:min(460px,36vw);transform:translate(-20px,-50%);z-index:22;border-radius:26px;padding:26px 26px 22px;opacity:0;pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out)}
|
||||
body.welcoming .welcome{opacity:1;transform:translate(0,-50%);pointer-events:auto}
|
||||
body.welcoming .home{opacity:0;pointer-events:none;filter:blur(4px)}
|
||||
.welcome .eyebrow{font-size:12.5px;color:var(--text-3);letter-spacing:.18em}
|
||||
.welcome h2{font-size:24px;font-weight:300;letter-spacing:.04em;margin:8px 0 4px}
|
||||
.welcome .sub{font-size:13.5px;color:var(--text-2)}
|
||||
.welcome ul{list-style:none;margin:16px 0 4px}
|
||||
.welcome li{display:grid;grid-template-columns:76px 1fr;gap:10px;padding:10px 0;border-top:1px solid rgba(255,255,255,.06);font-size:14.5px}
|
||||
.welcome li time{color:var(--text-3);font-size:12.5px;font-family:var(--font-num)}
|
||||
.welcome li small{display:block;color:var(--text-3);font-size:12px}
|
||||
.welcome .note{font-size:12px;color:var(--text-3);margin:10px 0 16px;line-height:1.6}
|
||||
.welcome .acts{display:flex;gap:10px;flex-wrap:wrap}
|
||||
|
||||
/* 主动消息(首页 / 区域页 中的轻提醒) */
|
||||
.reach{position:fixed;z-index:24;width:min(340px,80vw);border-radius:20px 20px 20px 6px;padding:14px 16px 12px;opacity:0;transform:translateY(10px) scale(.98);pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out);
|
||||
left:calc(100vw - clamp(300px,27vw,430px) - 14vw + 16px);width:calc(clamp(300px,27vw,430px) - 32px);bottom:calc((100vh - clamp(300px,27vw,430px) * 1.3) / 2 + 64px)}
|
||||
body.paned .reach{left:auto;right:28px;bottom:104px;width:340px;border-radius:20px}
|
||||
.reach.show{opacity:1;transform:none;pointer-events:auto}
|
||||
.reach .rh{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text-3)}
|
||||
.reach .rh b{font-weight:500;color:var(--accent)}
|
||||
.reach p{font-size:14.5px;line-height:1.7;margin:6px 0 6px}
|
||||
.reach .basis{font-size:11.5px;color:var(--text-3);display:flex;align-items:center;gap:6px}
|
||||
.reach .basis svg{width:12px;height:12px}
|
||||
.reach .acts{display:flex;gap:8px;margin-top:10px}
|
||||
.reach .acts .btn-primary{height:36px;padding:0 16px;font-size:13.5px}
|
||||
.reach .acts .btn-ghost{height:36px;padding:0 14px;font-size:13px}
|
||||
|
||||
/* ============================================================
|
||||
交流
|
||||
============================================================ */
|
||||
.chat-layout{position:fixed;top:calc(var(--view-top) + 72px);height:calc(var(--view-h) - 166px - var(--safe-bottom));left:calc(50vw + var(--shift));transform:translateX(-50%);width:min(760px,74vw);z-index:12;display:flex;flex-direction:column;gap:12px;pointer-events:none}
|
||||
.talk-scene-space{height:var(--talk-stage-h);flex:none}
|
||||
.dialog{min-height:0;flex:1;display:flex;flex-direction:column;pointer-events:auto}
|
||||
.dialog-scroll{min-height:0;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;padding:4px 12px;overflow-anchor:none}
|
||||
.dialog .you{font-size:15px;color:var(--text-2);margin:0 0 14px 12%;text-align:right}
|
||||
.dialog .her{font-size:var(--fs-line);line-height:1.65;font-weight:400;color:var(--text-1);text-shadow:0 2px 18px rgba(0,0,10,.6);margin-right:8%;min-height:1.65em}
|
||||
.speaker{display:block;font-size:13px;font-weight:500;letter-spacing:.1em;color:var(--accent);margin-bottom:4px}
|
||||
.dialog .you .speaker{color:var(--text-2)}
|
||||
.dialog .failed{color:var(--danger);font-size:13px}
|
||||
.dialog .retry{color:var(--accent);font-size:13px;margin-left:6px;text-decoration:underline;text-underline-offset:3px}
|
||||
.dialog .her.cut{opacity:.65}
|
||||
.soft-text{display:block;position:relative;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.current-text{display:block}
|
||||
.outgoing-text{position:absolute;inset:0;pointer-events:none}
|
||||
.partial-note{display:block;font-size:12px;color:var(--warn);margin-top:6px}
|
||||
.dialog .her .caret{display:inline-block;width:2px;height:1em;background:var(--accent);margin-left:3px;vertical-align:-2px;animation:caret 1s steps(1) infinite}
|
||||
.dialog .her .dots{display:inline-flex;gap:5px;vertical-align:middle}
|
||||
.dialog .her .dots i{width:6px;height:6px;border-radius:50%;background:var(--text-2);animation:dots 1.2s var(--ease-drift) infinite}
|
||||
.dialog .her .dots i:nth-child(2){animation-delay:.15s}.dialog .her .dots i:nth-child(3){animation-delay:.3s}
|
||||
@keyframes dots{0%,100%{opacity:.25;transform:translateY(0)}50%{opacity:1;transform:translateY(-3px)}}
|
||||
@keyframes caret{50%{opacity:0}}
|
||||
.dialog .hint{display:flex;align-items:center;justify-content:space-between;gap:8px;flex:none;padding:4px 12px;font-size:12px;color:var(--text-2);min-height:26px}
|
||||
.dialog .hint .btn-text{white-space:nowrap;color:var(--accent)}
|
||||
.composer{position:relative;flex:none;width:100%;min-height:60px;border-radius:var(--radius-pill);pointer-events:auto;display:flex;align-items:center;gap:4px;padding:0 6px}
|
||||
.composer .btn-round{width:46px;height:46px}
|
||||
.composer textarea{flex:1;height:46px;max-height:90px;resize:none;border:0;background:none;outline:none;padding:10px 8px;font-size:15px;color:var(--text-1);min-width:0}
|
||||
.composer textarea::placeholder{color:var(--text-3)}
|
||||
.composer .send{color:var(--text-2)}
|
||||
.composer .send.ready{color:var(--accent)}
|
||||
.composer .cam.on{color:var(--accent);background:var(--accent-soft)}
|
||||
body.offline .composer .send{opacity:.4;pointer-events:none}
|
||||
.mic{position:relative;width:46px;height:46px;border-radius:50%;display:grid;place-items:center;flex:none;background:var(--accent);color:var(--on-accent);box-shadow:0 0 22px -4px var(--accent-glow);transition:transform var(--dur-fast) var(--ease-out),background-color var(--dur-theme)}
|
||||
.mic svg{width:20px;height:20px}
|
||||
.mic .ic-stop{display:none}
|
||||
.mic::after{content:"";position:absolute;inset:-6px;border-radius:50%;border:1.5px solid var(--accent);opacity:0}
|
||||
body.voice .mic .ic-mic{display:none}
|
||||
body.voice .mic .ic-stop{display:block}
|
||||
body.v-listen .mic::after{animation:ring 1.4s var(--ease-out) infinite}
|
||||
.mic.denied{background:rgba(255,255,255,.08);color:var(--text-3);box-shadow:none}
|
||||
.mic .slash{position:absolute;width:26px;height:2px;background:var(--danger);transform:rotate(-45deg);display:none;border-radius:1px}
|
||||
.mic.denied .slash{display:block}
|
||||
@keyframes ring{from{opacity:.8;transform:scale(.9)}to{opacity:0;transform:scale(1.35)}}
|
||||
.wave{display:flex;align-items:center;gap:3px;height:20px}
|
||||
.wave i{width:3px;height:10px;border-radius:2px;background:currentColor;animation:wave 1s var(--ease-drift) infinite}
|
||||
.wave i:nth-child(2){animation-delay:.15s}.wave i:nth-child(3){animation-delay:.3s}.wave i:nth-child(4){animation-delay:.45s}
|
||||
@keyframes wave{0%,100%{height:5px}50%{height:18px}}
|
||||
.wave.still i{animation:none;height:4px}
|
||||
|
||||
/* 语音会话条:会话中始终可见「结束语音」 */
|
||||
.voicebar{position:relative;flex:none;min-height:48px;padding:0 6px 0 16px;border-radius:var(--radius-pill);display:flex;align-items:center;gap:12px;font-size:13.5px;pointer-events:auto}
|
||||
.voicebar .live{display:flex;align-items:center;gap:8px;color:var(--text-2);font-family:var(--font-num)}
|
||||
.voicebar .live i{width:8px;height:8px;border-radius:50%;background:var(--danger);box-shadow:0 0 8px var(--danger);animation:dotPulse 1.6s infinite}
|
||||
.voicebar .vstate{display:flex;align-items:center;gap:8px;color:var(--text-1);min-width:120px}
|
||||
.voicebar .vstate .wave{color:var(--accent);height:16px}
|
||||
.voicebar .btn-ghost{height:36px;padding:0 14px;font-size:13px}
|
||||
.voicebar .end{height:36px;padding:0 16px;border-radius:var(--radius-pill);background:rgba(255,159,179,.14);color:var(--danger);font-size:13px;display:inline-flex;align-items:center;gap:6px}
|
||||
.voicebar .end svg{width:12px;height:12px}
|
||||
|
||||
/* 完整聊天记录 */
|
||||
.log-panel{position:fixed;right:24px;top:calc(var(--view-top) + 72px);bottom:calc(var(--view-bottom) + 98px + var(--safe-bottom));width:380px;border-radius:24px;z-index:20;display:flex;flex-direction:column;opacity:0;transform:translateX(36px);pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out),background-color var(--dur-theme)}
|
||||
body.log .log-panel{opacity:1;transform:none;pointer-events:auto}
|
||||
.log-panel header{display:flex;align-items:center;justify-content:space-between;padding:18px 18px 10px 22px}
|
||||
.log-panel header h2{font-size:16px;font-weight:500;letter-spacing:.08em}
|
||||
.log-panel .scroll{flex:1;overflow:auto;padding:4px 22px 20px;scrollbar-width:thin}
|
||||
.day{font-size:var(--fs-tiny);color:var(--text-3);text-align:center;margin:12px 0 8px;letter-spacing:.12em}
|
||||
.msg{margin:10px 0;max-width:88%;scroll-margin:80px}
|
||||
.msg .who-l{font-size:var(--fs-tiny);color:var(--text-3);margin-bottom:3px}
|
||||
.msg p{white-space:pre-wrap;font-size:14.5px;line-height:1.7;padding:9px 14px;border-radius:16px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.06);transition:box-shadow var(--dur-panel),border-color var(--dur-panel)}
|
||||
.msg.me{margin-left:auto;text-align:right}
|
||||
.msg.me p{background:var(--accent-soft);border-color:transparent;text-align:left;display:inline-block}
|
||||
.msg.fail p{border:1px dashed var(--danger);background:transparent}
|
||||
.msg .tagm{font-size:10.5px;color:var(--text-3);margin-left:6px}
|
||||
.msg .tagm.proactive{color:var(--accent)}
|
||||
.msg.hl p{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-soft)}
|
||||
.msg .basis{font-size:11px;color:var(--text-3);margin-top:4px}
|
||||
.log-btn.on{color:var(--accent);background:var(--accent-soft)}
|
||||
|
||||
/* ============================================================
|
||||
底部导航
|
||||
============================================================ */
|
||||
.nav{position:fixed;left:50%;bottom:calc(var(--view-bottom) + 22px + var(--safe-bottom));transform:translateX(-50%);height:60px;padding:6px;border-radius:var(--radius-pill);display:flex;gap:2px;z-index:25;transition:opacity var(--dur-panel),transform var(--dur-panel) var(--ease-out)}
|
||||
body.creating .nav{opacity:0;pointer-events:none;transform:translate(-50%,20px)}
|
||||
.nav-item{position:relative;width:76px;height:48px;border-radius:var(--radius-pill);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;font-size:11.5px;color:var(--text-2);letter-spacing:.08em;transition:color var(--dur-ui),background-color var(--dur-ui),transform var(--dur-fast) var(--ease-out)}
|
||||
.nav-item svg{width:19px;height:19px}
|
||||
.nav-item[aria-current="page"]{color:var(--text-1);background:var(--accent-soft)}
|
||||
.nav-item[aria-current="page"] svg{color:var(--accent);filter:drop-shadow(0 0 6px var(--accent-glow))}
|
||||
.nav-item .badge{position:absolute;top:6px;right:20px;width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent-glow);display:none}
|
||||
.nav-item.unread .badge{display:block}
|
||||
|
||||
/* ============================================================
|
||||
区域面板:日子 / 设置(同一主题空间里升起的阅读面)
|
||||
============================================================ */
|
||||
.pane{position:fixed;z-index:16;left:var(--pane-l);top:calc(var(--view-top) + var(--pane-t));bottom:calc(var(--view-bottom) + var(--pane-b) + var(--safe-bottom));width:var(--pane-w);border-radius:28px;display:flex;flex-direction:column;overflow:hidden;opacity:0;transform:translateY(24px) scale(.985);pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out),background-color var(--dur-theme)}
|
||||
.pane.open{opacity:1;transform:none;pointer-events:auto;transition-delay:80ms}
|
||||
.pane > header{display:flex;align-items:center;gap:16px;padding:18px 18px 14px 28px;border-bottom:1px solid rgba(255,255,255,.06);flex:none}
|
||||
.pane > header h2{font-size:var(--fs-title);font-weight:400;letter-spacing:.1em;white-space:nowrap}
|
||||
.pane > header .grow{flex:1}
|
||||
.pane > header .tabs{margin-left:8px}
|
||||
.pane .presence{display:none;align-items:center;gap:8px;font-size:12.5px;color:var(--text-3)}
|
||||
.pane .presence i{width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent-glow)}
|
||||
.tabs{display:inline-flex;padding:3px;border-radius:var(--radius-pill);gap:2px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06)}
|
||||
.tabs button{height:34px;padding:0 16px;border-radius:var(--radius-pill);font-size:13.5px;color:var(--text-2);letter-spacing:.06em;transition:background-color var(--dur-ui),color var(--dur-ui)}
|
||||
.tabs button[aria-selected="true"]{color:var(--text-1);background:var(--accent-soft);box-shadow:0 0 14px -6px var(--accent-glow)}
|
||||
.pane .cols{flex:1;display:grid;grid-template-columns:400px 1fr;min-height:0;position:relative}
|
||||
.pane .list{overflow:auto;padding:14px 18px 28px 22px;border-right:1px solid rgba(255,255,255,.06);scrollbar-width:thin;overscroll-behavior:contain}
|
||||
.pane .detail{overflow:auto;padding:26px 34px 34px;scrollbar-width:thin;overscroll-behavior:contain;position:relative}
|
||||
.pane .back{display:none}
|
||||
|
||||
/* 生活时间线 */
|
||||
.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--text-3);margin:4px 0 10px}
|
||||
.legend span{display:inline-flex;align-items:center;gap:6px}
|
||||
.k{width:9px;height:9px;border-radius:50%;flex:none;display:inline-block}
|
||||
.k.done{background:var(--text-2)}
|
||||
.k.now{background:var(--accent);box-shadow:0 0 10px var(--accent-glow);animation:dotPulse 2.4s infinite}
|
||||
.k.plan{border:1.5px dashed var(--text-2);background:transparent}
|
||||
.grp{font-size:12px;color:var(--text-3);letter-spacing:.14em;margin:18px 4px 6px;display:flex;justify-content:space-between}
|
||||
.ev{display:grid;grid-template-columns:52px 14px 1fr;gap:8px;align-items:start;width:100%;text-align:left;padding:10px 10px;border-radius:14px;font-size:14.5px;line-height:1.6;transition:background-color var(--dur-ui)}
|
||||
.ev:hover{background:rgba(255,255,255,.04)}
|
||||
.ev[aria-current="true"]{background:var(--accent-soft)}
|
||||
.ev time{font-family:var(--font-num);font-size:12.5px;color:var(--text-3);padding-top:2px}
|
||||
.ev .k{margin-top:7px}
|
||||
.ev .tt{display:block}
|
||||
.ev .sub{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}
|
||||
.ev.told .tt{color:var(--text-2)}
|
||||
.ev.plan .tt{color:var(--text-2);font-style:normal}
|
||||
.ev.now .tt{color:var(--text-1)}
|
||||
|
||||
.away-card{border-radius:18px;padding:14px 16px;background:var(--accent-soft);margin:6px 0 4px;font-size:13.5px;color:var(--text-2);line-height:1.7;transition:box-shadow var(--dur-panel)}
|
||||
.away-card b{display:block;font-weight:500;color:var(--text-1);font-size:14.5px;margin-bottom:2px}
|
||||
.away-card.flash{box-shadow:0 0 0 2px var(--accent),0 0 24px -4px var(--accent-glow)}
|
||||
.more{display:flex;justify-content:center;margin:16px 0 4px}
|
||||
.empty{padding:40px 12px;text-align:center;color:var(--text-2);font-size:14.5px;line-height:1.8}
|
||||
.empty .glyph{width:54px;height:54px;margin:0 auto 14px;border-radius:50%;border:1px dashed var(--glass-line);display:grid;place-items:center;color:var(--accent)}
|
||||
.empty .glyph svg{width:22px;height:22px}
|
||||
.empty small{display:block;color:var(--text-3);font-size:12.5px;margin-top:6px}
|
||||
|
||||
/* 详情 */
|
||||
.d-empty{height:100%;display:grid;place-items:center;text-align:center;color:var(--text-3);font-size:14px}
|
||||
.d-empty .glyph{width:64px;height:64px;margin:0 auto 12px;border-radius:50%;background:radial-gradient(circle,var(--accent-soft),transparent 70%);display:grid;place-items:center;color:var(--accent)}
|
||||
.d-kicker{display:flex;flex-wrap:wrap;align-items:center;gap:8px;font-size:12.5px;color:var(--text-3)}
|
||||
.d-title{font-size:24px;font-weight:300;letter-spacing:.03em;line-height:1.5;margin:10px 0 6px}
|
||||
.d-meta{font-size:13px;color:var(--text-3);display:flex;flex-wrap:wrap;gap:6px 16px}
|
||||
.quote{margin:22px 0 6px;padding:16px 20px;border-left:2px solid var(--accent);background:rgba(255,255,255,.035);border-radius:0 16px 16px 0;font-size:15.5px;line-height:1.85;color:var(--text-1)}
|
||||
.quote small{display:block;color:var(--text-3);font-size:12px;margin-top:8px}
|
||||
.d-sec{font-size:12.5px;color:var(--text-3);letter-spacing:.14em;margin:26px 0 10px}
|
||||
.links{display:flex;flex-wrap:wrap;gap:8px}
|
||||
.link-chip{display:inline-flex;align-items:center;gap:8px;min-height:36px;padding:6px 14px;border-radius:14px;border:1px solid var(--glass-line);font-size:13.5px;color:var(--text-1);text-align:left;transition:background-color var(--dur-ui)}
|
||||
.link-chip:hover{background:var(--accent-soft)}
|
||||
.link-chip svg{width:14px;height:14px;color:var(--accent);flex:none}
|
||||
.d-foot{margin-top:28px;padding-top:14px;border-top:1px solid rgba(255,255,255,.06);font-size:12px;color:var(--text-3);line-height:1.7}
|
||||
.pending{border:1px dashed var(--warn);color:var(--warn);border-radius:14px;padding:10px 14px;font-size:12.5px;line-height:1.7;margin-top:14px}
|
||||
|
||||
/* 回忆 */
|
||||
.mem{display:block;width:100%;text-align:left;padding:12px 14px;border-radius:16px;background:rgba(255,255,255,.035);border:1px solid rgba(255,255,255,.06);margin:8px 0;font-size:14.5px;line-height:1.65;transition:background-color var(--dur-ui),border-color var(--dur-ui)}
|
||||
.mem:hover{background:rgba(255,255,255,.06)}
|
||||
.mem[aria-current="true"]{border-color:var(--accent);background:var(--accent-soft)}
|
||||
.mem small{display:block;color:var(--text-3);font-size:12px;margin-top:3px}
|
||||
.growth{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:6px}
|
||||
.growth > div{padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.035);border:1px solid rgba(255,255,255,.06)}
|
||||
.growth h4{font-weight:400;font-size:12.5px;color:var(--text-3);letter-spacing:.12em;margin-bottom:6px}
|
||||
.growth ul{list-style:none;font-size:14px;line-height:1.9}
|
||||
.growth li small{color:var(--text-3);font-size:11.5px;margin-left:6px}
|
||||
|
||||
/* 设置 */
|
||||
.pane-manage .cols{grid-template-columns:220px 1fr}
|
||||
.snav{overflow:auto;padding:14px 12px 24px 16px;border-right:1px solid rgba(255,255,255,.06)}
|
||||
.snav button{display:flex;align-items:center;gap:10px;width:100%;height:44px;padding:0 14px;border-radius:14px;font-size:14px;color:var(--text-2);text-align:left;transition:background-color var(--dur-ui),color var(--dur-ui)}
|
||||
.snav button svg{width:17px;height:17px;flex:none}
|
||||
.snav button:hover{background:rgba(255,255,255,.04)}
|
||||
.snav button[aria-current="true"]{color:var(--text-1);background:var(--accent-soft)}
|
||||
.snav button[aria-current="true"] svg{color:var(--accent)}
|
||||
.snav button .dirty{margin-left:auto;width:6px;height:6px;border-radius:50%;background:var(--warn);display:none}
|
||||
.snav button.is-dirty .dirty{display:block}
|
||||
.snav hr{border:0;border-top:1px solid rgba(255,255,255,.06);margin:10px 8px}
|
||||
.sec-body{display:none}
|
||||
.sec-body.on{display:block}
|
||||
.sec-body h3{font-size:22px;font-weight:300;letter-spacing:.06em;margin-bottom:4px}
|
||||
.sec-body .lead{font-size:13.5px;color:var(--text-2);margin-bottom:22px;line-height:1.75;max-width:560px}
|
||||
.card{border-radius:18px;padding:18px 20px;background:rgba(255,255,255,.035);border:1px solid rgba(255,255,255,.07);margin:0 0 14px}
|
||||
.card h4{font-size:13px;font-weight:400;color:var(--text-3);letter-spacing:.12em;margin-bottom:10px;display:flex;align-items:center;gap:8px}
|
||||
.card h4 svg{width:14px;height:14px}
|
||||
.pillars{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:4px 0 10px}
|
||||
.pillars div{text-align:center;padding:10px 4px;border-radius:12px;background:rgba(255,255,255,.04)}
|
||||
.pillars small{display:block;font-size:11.5px;color:var(--text-3)}
|
||||
.pillars b{display:block;font-weight:300;font-size:22px;letter-spacing:.12em}
|
||||
.lean{display:flex;flex-wrap:wrap;gap:8px;margin:4px 0 10px}
|
||||
.lean span{padding:6px 14px;border-radius:var(--radius-pill);border:1px solid var(--glass-line);font-size:14px}
|
||||
.kv{display:grid;grid-template-columns:120px 1fr;gap:8px 16px;font-size:14px}
|
||||
.kv dt{color:var(--text-3)}
|
||||
.lock{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--text-3)}
|
||||
.lock svg{width:13px;height:13px}
|
||||
.actions{position:sticky;bottom:-34px;margin:22px -34px -34px;padding:16px 34px 20px;display:flex;align-items:center;gap:10px;background:linear-gradient(180deg,rgba(0,0,0,0),var(--glass-read) 30%);z-index:2}
|
||||
.actions .grow{flex:1;font-size:12.5px;color:var(--text-3)}
|
||||
.actions .grow.dirty{color:var(--warn)}
|
||||
.svc{display:grid;grid-template-columns:1fr auto;gap:10px 14px;align-items:center;padding:14px 0;border-top:1px solid rgba(255,255,255,.06)}
|
||||
.svc:first-of-type{border-top:0}
|
||||
.svc .nm{font-size:14.5px}
|
||||
.svc .nm small{display:block;color:var(--text-3);font-size:12px}
|
||||
.svc .input{grid-column:1 / -1;height:42px;font-size:14px;font-family:var(--font-num)}
|
||||
.svc .res{grid-column:1 / -1;font-size:12.5px;display:none}
|
||||
.svc .res.show{display:flex;align-items:center;gap:6px}
|
||||
.svc .res.ok{color:var(--ok)}.svc .res.fail{color:var(--danger)}.svc .res.busy{color:var(--text-2)}
|
||||
.checklist{list-style:none;margin:10px 0 0;font-size:13.5px}
|
||||
.checklist li{display:flex;align-items:center;gap:10px;padding:6px 0;color:var(--text-2)}
|
||||
.checklist li i{width:18px;height:18px;border-radius:50%;display:grid;place-items:center;flex:none;border:1px solid var(--glass-line);font-style:normal;font-size:11px}
|
||||
.checklist li.ok i{background:rgba(159,232,207,.15);border-color:var(--ok);color:var(--ok)}
|
||||
.checklist li.fail{color:var(--danger)}
|
||||
.checklist li.fail i{background:rgba(255,159,179,.15);border-color:var(--danger);color:var(--danger)}
|
||||
.checklist li.run i{border-color:var(--accent);border-right-color:transparent;animation:spin .9s linear infinite}
|
||||
.compare{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px}
|
||||
.compare figure{border-radius:14px;overflow:hidden;position:relative;aspect-ratio:4/3;background:rgba(255,255,255,.04)}
|
||||
.compare img{width:100%;height:100%;object-fit:cover}
|
||||
.compare figcaption{position:absolute;left:10px;bottom:8px;font-size:12px;padding:2px 10px;border-radius:999px;background:rgba(8,10,28,.55)}
|
||||
.compare .new img{filter:hue-rotate(-14deg) saturate(1.15) brightness(1.05)}
|
||||
.bk{display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-top:1px solid rgba(255,255,255,.06);font-size:14px}
|
||||
.bk:first-of-type{border-top:0}
|
||||
.bk small{color:var(--text-3);font-size:12px;margin-left:8px}
|
||||
.opt-row{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:8px 0}
|
||||
.opt{border-radius:18px;padding:12px;text-align:left;border:1px solid var(--glass-line);transition:border-color var(--dur-ui),box-shadow var(--dur-ui)}
|
||||
.opt .sw{height:64px;border-radius:12px;margin-bottom:10px}
|
||||
.opt[data-t="moon"] .sw{background:radial-gradient(circle at 30% 30%,#e9f2ff 0 7%,rgba(160,200,255,.25) 12%,transparent 30%),linear-gradient(180deg,#0b1636,#1c2d5f)}
|
||||
.opt[data-t="fog"] .sw{background:radial-gradient(80% 60% at 20% 90%,rgba(220,150,255,.7),transparent 70%),linear-gradient(170deg,#1c1342,#43307a)}
|
||||
.opt[aria-pressed="true"]{border-color:var(--accent);box-shadow:0 0 18px -6px var(--accent-glow)}
|
||||
.opt b{font-weight:500;font-size:14px}.opt span{display:block;font-size:12px;color:var(--text-3)}
|
||||
.switch-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 0;border-top:1px solid rgba(255,255,255,.06);font-size:14.5px}
|
||||
.switch-row small{display:block;color:var(--text-3);font-size:12px}
|
||||
.city-list{list-style:none;margin:8px 0 0;border-radius:14px;overflow:hidden;border:1px solid var(--field-line)}
|
||||
.city-list li button{display:flex;justify-content:space-between;width:100%;padding:11px 14px;font-size:14px;text-align:left;border-top:1px solid rgba(255,255,255,.05)}
|
||||
.city-list li:first-child button{border-top:0}
|
||||
.city-list li button:hover,.city-list li button[aria-pressed="true"]{background:var(--accent-soft)}
|
||||
.city-list small{color:var(--text-3)}
|
||||
|
||||
/* ============================================================
|
||||
首建
|
||||
============================================================ */
|
||||
.create{position:fixed;inset:var(--view-top) 0 auto;height:var(--view-h);z-index:60;display:grid;grid-template-columns:minmax(0,1fr) minmax(460px,560px);gap:6vw;align-items:center;padding:84px 9vw 48px;opacity:0;pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out)}
|
||||
body.creating .create{opacity:1;pointer-events:auto}
|
||||
.create .story{max-width:440px}
|
||||
.create .story .eyebrow{font-size:13px;color:var(--text-3);letter-spacing:.2em;margin-bottom:14px}
|
||||
.create .story h1{font-size:var(--fs-whisper);font-weight:300;line-height:1.5;letter-spacing:.04em}
|
||||
.create .story p{margin-top:16px;color:var(--text-2);font-size:14.5px;line-height:1.85}
|
||||
.create .story .single{margin-top:22px;display:flex;gap:10px;font-size:12.5px;color:var(--text-3);line-height:1.7}
|
||||
.create .story .single svg{width:16px;height:16px;flex:none;margin-top:3px;color:var(--accent)}
|
||||
.wiz{border-radius:28px;display:flex;flex-direction:column;max-height:calc(var(--view-h) - 132px);overflow:hidden}
|
||||
.wiz .steps{display:flex;gap:6px;padding:20px 28px 0}
|
||||
.wiz .steps span{flex:1;height:3px;border-radius:2px;background:rgba(255,255,255,.1);transition:background-color var(--dur-ui),box-shadow var(--dur-ui)}
|
||||
.wiz .steps span.on{background:var(--accent);box-shadow:0 0 8px var(--accent-glow)}
|
||||
.wiz .steplabel{padding:10px 28px 0;font-size:12px;color:var(--text-3);letter-spacing:.12em}
|
||||
.wiz .wbody{overflow:auto;padding:10px 28px 8px;flex:1}
|
||||
.wiz .wbody h2{font-size:22px;font-weight:300;letter-spacing:.06em;margin:4px 0 6px}
|
||||
.wiz .wbody .lead{font-size:13.5px;color:var(--text-2);line-height:1.8;margin-bottom:20px}
|
||||
.wiz .wfoot{display:flex;align-items:center;gap:10px;padding:16px 28px 22px;border-top:1px solid rgba(255,255,255,.06)}
|
||||
.wiz .wfoot .grow{flex:1}
|
||||
.wstep{display:none;animation:stepIn var(--dur-panel) var(--ease-out)}
|
||||
.wstep.on{display:block}
|
||||
@keyframes stepIn{from{opacity:0;transform:translateX(16px)}to{opacity:1;transform:none}}
|
||||
.wstep.back-in{animation-name:stepBack}
|
||||
@keyframes stepBack{from{opacity:0;transform:translateX(-16px)}to{opacity:1;transform:none}}
|
||||
.gen{display:flex;align-items:center;gap:10px;margin:-4px 0 18px}
|
||||
.sum{border-radius:16px;background:rgba(255,255,255,.035);border:1px solid rgba(255,255,255,.07);padding:4px 18px;margin-bottom:14px}
|
||||
.sum .r{display:flex;justify-content:space-between;gap:12px;padding:11px 0;border-top:1px solid rgba(255,255,255,.06);font-size:14px}
|
||||
.sum .r:first-child{border-top:0}
|
||||
.sum .r span:first-child{color:var(--text-3)}
|
||||
.sum .r b{font-weight:400;text-align:right}
|
||||
.phases{list-style:none;margin:8px 0 0}
|
||||
.phases li{display:flex;align-items:center;gap:12px;padding:10px 0;font-size:14.5px;color:var(--text-3)}
|
||||
.phases li i{width:20px;height:20px;border-radius:50%;border:1.5px solid var(--glass-line);flex:none;display:grid;place-items:center;font-style:normal;font-size:11px}
|
||||
.phases li.run{color:var(--text-1)}
|
||||
.phases li.run i{border-color:var(--accent);border-right-color:transparent;animation:spin .9s linear infinite}
|
||||
.phases li.ok{color:var(--text-2)}
|
||||
.phases li.ok i{border-color:var(--ok);color:var(--ok);background:rgba(159,232,207,.12)}
|
||||
.phases li.fail{color:var(--danger)}
|
||||
.phases li.fail i{border-color:var(--danger);color:var(--danger)}
|
||||
.born{text-align:center;padding:16px 0 8px}
|
||||
.born .halo{width:96px;height:96px;margin:6px auto 18px;border-radius:50%;background:radial-gradient(circle,var(--window-glow) 0%,var(--accent-soft) 45%,transparent 70%);display:grid;place-items:center}
|
||||
.born .halo i{width:12px;height:12px;border-radius:50%;background:var(--accent);box-shadow:0 0 22px 6px var(--accent-glow)}
|
||||
.born h2{font-size:24px !important}
|
||||
.born p{color:var(--text-2);font-size:14px;line-height:1.85;margin-top:6px}
|
||||
|
||||
/* ============================================================
|
||||
通用弹层:确认 / 授权
|
||||
============================================================ */
|
||||
.scrim{position:fixed;inset:0;z-index:70;background:rgba(2,4,16,.45);opacity:0;pointer-events:none;transition:opacity var(--dur-ui)}
|
||||
.scrim.open{opacity:1;pointer-events:auto}
|
||||
.modal{position:fixed;left:50%;top:calc(var(--view-top) + var(--view-h) / 2);max-height:calc(var(--view-h) - 32px);overflow:auto;z-index:72;width:min(460px,calc(100vw - 32px));border-radius:26px;padding:26px 26px 22px;transform:translate(-50%,-46%) scale(.97);opacity:0;pointer-events:none;transition:opacity var(--dur-ui) var(--ease-out),transform var(--dur-ui) var(--ease-out)}
|
||||
.modal.open{opacity:1;transform:translate(-50%,-50%);pointer-events:auto}
|
||||
.modal .mi{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);margin-bottom:14px}
|
||||
.modal.danger .mi{background:rgba(255,159,179,.12);color:var(--danger)}
|
||||
.modal .mi svg{width:20px;height:20px}
|
||||
.modal h3{font-size:19px;font-weight:400;letter-spacing:.04em;margin-bottom:8px}
|
||||
.modal .mb{font-size:14px;color:var(--text-2);line-height:1.8}
|
||||
.modal .mb ul{margin:8px 0 0 18px}
|
||||
.modal .confirm-field{margin-top:14px}
|
||||
.modal .acts{display:flex;justify-content:flex-end;gap:10px;margin-top:22px}
|
||||
.modal .acts button{height:44px}
|
||||
|
||||
.toast{max-width:calc(100vw - 24px);text-align:center;position:fixed;left:50%;top:76px;transform:translate(-50%,-8px);z-index:80;padding:8px 16px;border-radius:var(--radius-pill);font-size:13px;color:var(--text-1);opacity:0;pointer-events:none;transition:opacity var(--dur-ui),transform var(--dur-ui) var(--ease-out);display:flex;align-items:center;gap:8px;white-space:nowrap}
|
||||
.toast.show{opacity:1;transform:translate(-50%,0)}
|
||||
.toast.ok::before{content:"";width:7px;height:7px;border-radius:50%;background:var(--ok)}
|
||||
.toast.fail::before{content:"";width:7px;height:7px;border-radius:50%;background:var(--danger)}
|
||||
|
||||
/* ============================================================
|
||||
演示控制台(原型专用,非产品界面)
|
||||
============================================================ */
|
||||
.demo{position:fixed;left:20px;bottom:24px;z-index:90}
|
||||
.demo > button{height:34px;padding:0 14px;border-radius:999px;border:1px dashed var(--glass-line);font-size:12px;color:var(--text-3);background:rgba(4,6,18,.55);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}
|
||||
.demo .menu{position:absolute;left:0;bottom:44px;width:300px;max-height:calc(100vh - 120px);overflow:auto;border-radius:18px;padding:12px;display:none;background:var(--glass-solid);border:1px solid var(--glass-line);box-shadow:0 20px 60px -20px #000}
|
||||
.demo.open .menu{display:block}
|
||||
.demo h5{font-weight:400;font-size:11.5px;color:var(--text-3);letter-spacing:.14em;margin:10px 4px 6px}
|
||||
.demo h5:first-child{margin-top:2px}
|
||||
.demo .g{display:flex;flex-wrap:wrap;gap:6px}
|
||||
.demo .g button{height:30px;padding:0 10px;border-radius:10px;font-size:12px;color:var(--text-2);background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.06)}
|
||||
.demo .g button:hover{color:var(--text-1);background:var(--accent-soft)}
|
||||
.demo .g button[aria-pressed="true"]{color:var(--on-accent);background:var(--accent)}
|
||||
.demo p{font-size:11px;color:var(--text-3);margin:10px 4px 0;line-height:1.6}
|
||||
|
||||
|
||||
/* ============================================================
|
||||
手机(≤720px)
|
||||
============================================================ */
|
||||
@media (max-width:720px){
|
||||
:root{--fs-whisper:21px;--fs-line:17px}
|
||||
.topbar{top:calc(var(--view-top) + 14px);left:18px;right:14px}
|
||||
.who .name{font-size:17px}
|
||||
.who .state,.env .chip.place,.env .chip.weather,.env .tag-demo,.clock small{display:none}
|
||||
.env{gap:6px}
|
||||
.clock{font-size:17px}
|
||||
.theme-switch button{padding:0 9px;height:26px;font-size:12px}
|
||||
.theme-switch button span{display:none}
|
||||
.moon-disc{left:5%;top:12%;width:36px;height:36px}
|
||||
.moon-halo{left:calc(5% - 182px);top:calc(12% - 182px);width:400px;height:400px}
|
||||
.netbar{top:56px;max-width:calc(100vw - 24px);font-size:12.5px}
|
||||
.netbar small{display:none}
|
||||
|
||||
body{--home-pw:min(74vw,330px,max(120px,calc((var(--view-h) - 340px) / 1.22)))}
|
||||
.portal{--pw:var(--home-pw); --ph:calc(var(--pw) * 1.22); --pl:calc(50vw - var(--pw) / 2); --pt:70px}
|
||||
body.talk{--talk-stage-h:clamp(64px,calc((var(--view-h) - 360px) * .55),300px)}
|
||||
body.talk .portal{--pw:calc(100vw - 24px); --ph:var(--talk-stage-h); --pl:12px; --pt:calc(var(--view-top) + 58px)}
|
||||
body.talk.voice{--talk-stage-h:clamp(48px,calc((var(--view-h) - 412px) * .5),250px)}
|
||||
body.talk.log{--shift:0px}
|
||||
body.paned .portal{opacity:0;pointer-events:none;--pw:min(74vw,330px); --ph:calc(var(--pw) * 1.22); --pl:calc(50vw - var(--pw) / 2); --pt:70px}
|
||||
.mini-cap{display:none}
|
||||
.portal .doing{left:12px;right:12px;bottom:12px}
|
||||
.portal .doing .tag-demo{display:none}
|
||||
.portal .mark{right:14px;bottom:50px}
|
||||
.observe{max-width:calc(100vw - 80px)}
|
||||
|
||||
.home{left:22px;right:22px;width:auto;top:calc(var(--view-top) + 70px + var(--home-pw) * 1.22 + 22px);max-height:calc(var(--view-h) - 70px - var(--home-pw) * 1.22 - 106px - var(--safe-bottom));overflow:auto;transform:none}
|
||||
body.talk .home,body.paned .home,body.creating .home{transform:translateY(20px) scale(.97)}
|
||||
.home .eyebrow,.home .meta{display:none}
|
||||
.letter{margin-top:14px;padding:14px 16px 12px}
|
||||
.letter p{font-size:14px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
|
||||
.away{margin-top:8px;font-size:13px}
|
||||
.cta{position:static;margin-top:16px}
|
||||
.cta .btn-primary{flex:1;height:50px}
|
||||
.cta .btn-round{width:50px;height:50px}
|
||||
.first-note{font-size:13px}
|
||||
|
||||
.welcome{left:12px;right:12px;width:auto;top:auto;bottom:90px;transform:translateY(20px);max-height:calc(100vh - 160px);overflow:auto;padding:22px 20px 18px;background:var(--glass-solid)}
|
||||
body.welcoming .welcome{transform:none}
|
||||
.welcome li{grid-template-columns:64px 1fr}
|
||||
.reach{left:12px;right:12px;width:auto;bottom:164px;border-radius:20px}
|
||||
body.paned .reach{left:12px;right:12px;bottom:96px}
|
||||
|
||||
.chat-layout{left:50vw;top:calc(var(--view-top) + 58px);height:calc(var(--view-h) - 142px - var(--safe-bottom));width:calc(100vw - 24px);gap:8px}
|
||||
.dialog .her{font-size:17px}
|
||||
.composer{min-height:56px}
|
||||
.composer .btn-round{width:40px;height:40px}
|
||||
.composer .btn-round svg{width:19px;height:19px}
|
||||
.mic{width:42px;height:42px}
|
||||
.voicebar{gap:8px;padding:0 6px 0 12px}
|
||||
.voicebar .vstate{min-width:0;flex:1;font-size:13px}
|
||||
.voicebar .live span,.voicebar .vstate .wave{display:none}
|
||||
.voicebar .vstate{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
|
||||
|
||||
.nav{bottom:calc(var(--view-bottom) + 16px + var(--safe-bottom));height:58px;width:calc(100vw - 24px);justify-content:space-between}
|
||||
.nav-item{flex:1;width:auto}
|
||||
.nav-item .badge{right:calc(50% - 18px)}
|
||||
|
||||
.log-panel{left:0;right:0;top:calc(var(--view-top) + 54px);bottom:calc(var(--view-bottom) + 84px + var(--safe-bottom));width:auto;height:auto;border-radius:26px 26px 0 0;z-index:45;transform:translateY(100%);opacity:1}
|
||||
body.log .log-panel{transform:none}
|
||||
.log-panel,.pane,.wiz,.modal{background:var(--glass-solid)}
|
||||
.window-glow{display:none}
|
||||
body.talk .moon-disc,body.talk .moon-halo{opacity:0}
|
||||
|
||||
/* 区域面板 → 全屏层;列表与详情改为推入 */
|
||||
.pane{left:8px;right:8px;width:auto;top:calc(var(--view-top) + 54px);bottom:calc(var(--view-bottom) + 84px + var(--safe-bottom));border-radius:24px}
|
||||
.pane > header{flex-wrap:wrap;gap:10px;padding:14px 14px 12px 18px}
|
||||
.pane > header h2{font-size:18px}
|
||||
.pane > header .tabs{order:3;width:100%;margin:0;display:flex}
|
||||
.pane > header .tabs button{flex:1}
|
||||
.pane > header .tag-demo{display:none}
|
||||
.pane .presence{display:flex}
|
||||
.pane .cols,.pane-manage .cols{grid-template-columns:1fr}
|
||||
.pane .list,.snav{border-right:0;padding:8px 12px 24px 14px}
|
||||
.pane .detail{position:absolute;inset:0;transform:translateX(102%);transition:transform var(--dur-panel) var(--ease-out);background:var(--surface);padding:12px 18px 28px;z-index:3}
|
||||
.pane.has-detail .detail{transform:none}
|
||||
.pane .back{display:inline-flex;margin:0 0 8px -4px}
|
||||
.d-empty{display:none}
|
||||
.d-title{font-size:21px}
|
||||
.quote{font-size:15px}
|
||||
.growth{grid-template-columns:1fr}
|
||||
.actions{bottom:-28px;margin:22px -18px -28px;padding:14px 18px 18px;background:var(--surface)}
|
||||
.actions .grow{display:none}
|
||||
.actions button{flex:1}
|
||||
.row2{grid-template-columns:1fr}
|
||||
.kv{grid-template-columns:96px 1fr}
|
||||
.pillars b{font-size:19px}
|
||||
.compare{grid-template-columns:1fr 1fr}
|
||||
|
||||
.create{display:flex;flex-direction:column;padding:56px 0 var(--safe-bottom);overflow:hidden}
|
||||
.create .story{flex:none;padding:4px 22px 14px;max-width:none}
|
||||
.create .story h1{font-size:21px}
|
||||
.create .story p{font-size:13.5px;margin-top:8px}
|
||||
.create .story .single{display:none}
|
||||
.wiz .wbody{overflow:auto;min-height:0}
|
||||
.wiz{margin:0 8px;max-height:none;border-radius:24px 24px 0 0;min-height:0;flex:1;overflow:hidden}
|
||||
.wiz .wbody{padding:8px 18px 8px}
|
||||
.wiz .steps{padding:16px 18px 0}
|
||||
.wiz .steplabel{padding:8px 18px 0}
|
||||
.wiz .wfoot{flex:none;padding:12px 18px 18px;background:var(--surface)}
|
||||
.wiz .wfoot .grow{display:none}
|
||||
.wiz .wfoot button{flex:1}
|
||||
.create.at-story .story{display:block}
|
||||
|
||||
.demo{left:50%;bottom:auto;top:16px;transform:translateX(-50%)}
|
||||
.demo .dl{display:none}
|
||||
.demo .menu{left:50%;transform:translateX(-50%);bottom:auto;top:40px;width:min(300px,calc(100vw - 24px));max-height:70vh}
|
||||
.demo > button{height:28px;padding:0 10px;font-size:11px}
|
||||
}
|
||||
@media (max-width:1100px) and (min-width:721px){
|
||||
:root{--pane-w:calc(100vw - 10vw); --mini-pw:0px}
|
||||
body.paned .portal{opacity:0;pointer-events:none}
|
||||
.mini-cap{display:none}
|
||||
.pane .presence{display:flex}
|
||||
.pane .cols{grid-template-columns:340px 1fr}
|
||||
.pane-manage .cols{grid-template-columns:200px 1fr}
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
减少动效 / 隐藏页暂停
|
||||
============================================================ */
|
||||
html.reduced *, html.reduced *::before, html.reduced *::after{animation:none !important}
|
||||
html.reduced .portal, html.reduced .portal img, html.reduced .space, html.reduced .home, html.reduced .dialog, html.reduced .composer, html.reduced .log-panel, html.reduced .pane, html.reduced .pane .detail, html.reduced .welcome, html.reduced .reach, html.reduced .modal, html.reduced .voicebar, html.reduced .create{transition-duration:200ms !important;transition-delay:0ms !important}
|
||||
html.reduced body.talk .space, html.reduced body.paned .space{transform:none}
|
||||
html.reduced .k.now{box-shadow:0 0 10px var(--accent-glow)}
|
||||
html.reduced .wave i{height:8px}
|
||||
html.paused *, html.paused *::before, html.paused *::after{animation-play-state:paused !important}
|
||||
|
||||
[hidden]{display:none!important}
|
||||
p,button,h1,h2,h3,dd{overflow-wrap:anywhere}
|
||||
.entry{position:fixed;inset:0;display:grid;place-items:center;padding:24px;z-index:60;overflow:auto}
|
||||
.entry .card{max-width:540px;background:var(--glass-read)}
|
||||
.entry h1{font-size:var(--fs-whisper);font-weight:300}
|
||||
.entry p{color:var(--text-2);margin:18px 0}
|
||||
.error-text{color:var(--danger);font-size:13px;margin-top:12px}
|
||||
.demo-label{font-size:11px;color:var(--text-3)}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition-duration:120ms!important;transition-delay:0ms!important}}
|
||||
body:has(textarea:focus) .space *{animation-play-state:paused!important}
|
||||
|
||||
/* Birth explanations share the read surface and typography with existing forms. */
|
||||
.calendar{margin:12px 0}
|
||||
.color-sections section{border-top:1px solid var(--glass-line);padding-top:16px;margin-top:16px}
|
||||
.color-sections h4{color:var(--text-1);margin-bottom:8px}
|
||||
.birth-help, .color-sections details{font-size:13px;color:var(--text-2);margin-top:10px}
|
||||
.birth-help summary, .color-sections summary{cursor:pointer;color:var(--accent)}
|
||||
@media(max-height:480px){body.talk{--talk-stage-h:40px}body.talk .portal .mark,body.talk .portal .topleft{display:none}.create .story p,.create .story .single{display:none}.create .story{padding-bottom:4px}.create .story h1{font-size:18px}}
|
||||
@@ -0,0 +1,48 @@
|
||||
/* Authoritative HEL-746 R2 tokens; approved geometry and both themes. */
|
||||
|
||||
/* ============================================================
|
||||
Design tokens — 延续 HEL-744 R1,未改首页已认可的比例与字号
|
||||
R2 新增:阅读底 --glass-read、状态色 --ok/--warn/--danger、--z-*
|
||||
============================================================ */
|
||||
:root{
|
||||
--view-h:100vh; --view-top:0px; --view-bottom:0px;
|
||||
--safe-bottom:env(safe-area-inset-bottom,0px);
|
||||
--talk-stage-h:clamp(64px,calc(var(--view-h) - 420px),540px);
|
||||
--font-sans: "PingFang SC","HarmonyOS Sans SC","MiSans","Microsoft YaHei UI","Microsoft YaHei","Noto Sans SC",system-ui,sans-serif;
|
||||
--font-num: "SF Pro Display","Segoe UI Variable Display","Segoe UI",var(--font-sans);
|
||||
|
||||
--fs-whisper: 30px; --fs-title: 20px; --fs-line: 20px; --fs-body: 15px; --fs-meta: 13px; --fs-tiny: 11.5px;
|
||||
--space-1:4px; --space-2:8px; --space-3:12px; --space-4:16px; --space-5:24px; --space-6:32px; --space-7:48px;
|
||||
--radius-pill:999px; --radius-card:20px; --radius-stage:28px; --radius-field:14px;
|
||||
|
||||
--ease-out: cubic-bezier(.22,1,.36,1);
|
||||
--ease-in-out: cubic-bezier(.65,0,.35,1);
|
||||
--ease-drift: cubic-bezier(.45,.05,.55,.95);
|
||||
--dur-fast: 160ms; --dur-ui: 280ms; --dur-panel: 420ms; --dur-stage: 720ms; --dur-theme: 1100ms;
|
||||
|
||||
/* 区域面板(日子 / 设置)几何:电脑 */
|
||||
--pane-l: 5vw; --pane-w: min(1000px, 66vw); --pane-t: 84px; --pane-b: 104px;
|
||||
--mini-pw: clamp(170px, 14vw, 230px);
|
||||
}
|
||||
html[data-theme="moon"]{
|
||||
--bg-0:#060a1c; --bg-1:#0d1838; --bg-2:#1b2c5e;
|
||||
--text-1:#eaf0ff; --text-2:rgba(214,226,255,.72); --text-3:rgba(196,210,250,.48);
|
||||
--accent:#a9dcff; --accent-soft:rgba(169,220,255,.16); --accent-glow:rgba(150,210,255,.55); --on-accent:#08142e;
|
||||
--glass:rgba(150,180,255,.075); --glass-strong:rgba(28,44,92,.52); --glass-line:rgba(205,222,255,.18); --glass-hi:rgba(255,255,255,.10);
|
||||
--glass-blur:18px; --glass-sat:120%; --glass-solid:rgba(12,20,50,.88);
|
||||
--glass-read:rgba(10,18,46,.62); --surface:#0b1330; --field:rgba(255,255,255,.05); --field-line:rgba(205,222,255,.16);
|
||||
--window-glow:rgba(255,196,140,.20);
|
||||
--scroll-track:#0d1838; --scroll-thumb:#51678d; --scroll-hover:#a9dcff;
|
||||
--ok:#9fe8cf; --warn:#ffd79c; --danger:#ff9fb3;
|
||||
}
|
||||
html[data-theme="fog"]{
|
||||
--bg-0:#110b26; --bg-1:#22174a; --bg-2:#43307a;
|
||||
--text-1:#f3ecff; --text-2:rgba(234,222,255,.74); --text-3:rgba(222,206,255,.50);
|
||||
--accent:#ebbcff; --accent-soft:rgba(235,188,255,.18); --accent-glow:rgba(226,170,255,.55); --on-accent:#2a0f40;
|
||||
--glass:rgba(210,180,255,.11); --glass-strong:rgba(60,38,108,.50); --glass-line:rgba(236,218,255,.17); --glass-hi:rgba(255,240,255,.14);
|
||||
--glass-blur:30px; --glass-sat:145%; --glass-solid:rgba(38,22,74,.88);
|
||||
--glass-read:rgba(34,20,66,.60); --surface:#24154a; --field:rgba(255,240,255,.06); --field-line:rgba(236,218,255,.16);
|
||||
--window-glow:rgba(255,170,190,.22);
|
||||
--scroll-track:#22174a; --scroll-thumb:#806298; --scroll-hover:#ebbcff;
|
||||
--ok:#a8f0d8; --warn:#ffdcae; --danger:#ffa8c8;
|
||||
}
|
||||