diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 524ee84..5b04fa0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,11 +14,10 @@ concurrency: cancel-in-progress: true jobs: - gates: - name: 门禁 · ${{ matrix.os }} + build: + name: 类型与构建 · ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: - # Windows 是这个产品的主平台,不能只在 Linux 上验过就说能构建 fail-fast: false matrix: os: [ubuntu-latest, windows-latest] @@ -31,95 +30,18 @@ jobs: with: python-version: '3.12' - - name: 装 Python 依赖 - # G3 从 M1 起会真渲染一张图,matplotlib/numpy/seaborn 不能缺; - # jsonschema 也在同一份 requirements 里。 - run: | - python -m pip install --upgrade pip - python -m pip install -r requirements.txt - - name: 准备 Node uses: actions/setup-node@v4 with: node-version: '22' - # CI 不启动窗口,所以跳过 Electron 二进制下载(约 100 MB,纯浪费)。 - # 类型检查需要的 electron 类型仍随 npm 包一起装好。 - # lockfile 提交后这里换成 npm ci。 - name: 安装 JS 依赖 - run: npm install --no-audit --no-fund + run: npm ci --no-audit --no-fund env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 - - name: G1 注册表一致性 - run: node scripts/check-registry.mjs - - - name: G1 反向覆盖(门禁必须能变红) - run: node scripts/check-registry.negative.mjs - - - name: G8 技能规范(SKILL.md 仍是合法 Agent Skills 入口) - run: node scripts/check-skills.mjs - - - name: G8 反向覆盖(6 种破坏必须被抓到) - run: node scripts/check-skills.mjs --self - - - name: G6b 真启动核验器自测 - # 不需要真窗口:它自己造 10 份合成结果,验证「ok=true 但读数不对」「关键断言被删」都会红 - run: npm run verify:window:selftest - - - name: 装排版依赖(G4/G11 全链与 G10 都要真编 PDF,只在 ubuntu 跑) - # 0.2.0 起通道/编排自检覆盖阶段五论文生成,需要 xelatex/pandoc; - # 必须放在 G4 之前。Windows 的 gates job 不装 TeX(体积与时长不划算), - # 下面的 G4/G11/G10 用 MMS_PAPER_SKIP=1 显式跳过排版断言并打印「未验证」。 - if: matrix.os == 'ubuntu-latest' - run: | - sudo apt-get update -q - sudo apt-get install -yq pandoc texlive-xetex texlive-lang-chinese texlive-latex-extra - - - name: G4 通道自检(握手、鉴权、SSE、取消、续传) - # 起真 Python 子进程和本地假 OpenAI 端点;不需要窗口、不联网、不需要 Key - env: - MMS_PAPER_SKIP: ${{ matrix.os == 'windows-latest' && '1' || '' }} - run: python runtime/tests/selfcheck_channel.py - - - name: G4/G5 反向覆盖(坏事件、Key 泄漏、假 provider 关闭) - run: python runtime/tests/selfcheck_channel.py --selftest - - - name: G2 契约校验与版本同源 - run: python scripts/validate-contracts.py - - - name: G3 CLI 退出码契约 - run: python runtime/tests/selfcheck.py - - - name: G11 编排状态机(起题、确认、换一批、选模、全链) - env: - MMS_PAPER_SKIP: ${{ matrix.os == 'windows-latest' && '1' || '' }} - run: python runtime/tests/selfcheck_orchestrator.py - - - name: G11 反向覆盖(默认族写坏、关键词族清空必须变红) - run: python runtime/tests/selfcheck_orchestrator.py --selftest - - - name: G12 长会话 harness(预算、压缩、摘要、锚点、50 轮) - run: python runtime/tests/selfcheck_harness.py - - - name: G12 反向覆盖(拆掉压缩、关掉工具裁剪必须变红) - run: python runtime/tests/selfcheck_harness.py --selftest - - - name: G13 附件 xlsx 读取(工作表、日期、上限与坏文件) - run: npm run check:xlsx - - - name: G9 工作台(真渲两版、回滚、评分) - run: python runtime/tests/selfcheck_workbench.py - - - name: G10 论文排版(xelatex → pandoc → 三道门禁) - # Windows 的 gates job 不装 TeX/MiKTeX(体积与安装时长都不划算),显式跳过并在文档里记成未证; - # 真启动冒烟的 job 在 ubuntu 上有 TeX,G7-9 会真编一遍。 - env: - MMS_PAPER_SKIP: ${{ matrix.os == 'windows-latest' && '1' || '' }} - run: python runtime/tests/selfcheck_paper.py - - - name: 运行时语法检查 - run: python -m compileall -q runtime + - name: 内核语法检查 + run: python -m compileall -q modeling gateway - name: 类型检查 run: npm run typecheck @@ -127,85 +49,40 @@ jobs: - name: 构建 run: npm run build - - name: G6 产物冒烟 - run: node scripts/smoke-dist.mjs - - # M0 的判据是「照手册装完能起一个空窗」。这条 job 真下载 Electron、真启动、真截图并按像素断言, - # 而不是停在「能构建」。gates 那条故意跳过二进制,所以这一段只能在这里补上。 window-smoke: name: 真启动冒烟 · ubuntu runs-on: ubuntu-latest - needs: [] steps: - uses: actions/checkout@v4 - name: 准备 Python - # 主进程用 python3 拉起 runtime/cli.py serve;M4 工作台要真渲图,下面会装 requirements。 uses: actions/setup-python@v5 with: python-version: '3.12' - - name: 装图表依赖(工作台要真渲一张样例图) - run: | - python -m pip install --upgrade pip - python -m pip install -r requirements.txt - - name: 准备 Node uses: actions/setup-node@v4 with: node-version: '22' - name: 安装 JS 依赖(含 Electron 二进制) - run: npm install --no-audit --no-fund + run: npm ci --no-audit --no-fund - name: 构建 run: npm run build - - name: 取回 Electron 二进制并打印实况 - # 上一轮 chmod 报 No such file or directory:npm install 之后 dist/ 里并没有二进制, - # 它是等到首次 npx electron 才懒下载的(那一轮的日志里有 "Downloading Electron binary...")。 - # 所以先把二进制显式取回来,再把目录列出来——下次再挂就知道挂在哪儿,而不是猜。 - # 注意这一步不运行 electron:沙箱助手还没改权限,跑一次就会 FATAL 退出(上一轮就是这么挂的)。 - run: | - # GitHub release 直链偶发 504(2026-11-08 连续多轮挂在同一 URL),重试三次再放弃。 - ok=0 - for attempt in 1 2 3; do - if node node_modules/electron/install.js; then ok=1; break; fi - echo "第 $attempt 次取回 Electron 失败,10 秒后重试" - sleep 10 - done - [ "$ok" = 1 ] || exit 1 - ls -l node_modules/electron/ | head -10 - ls -l node_modules/electron/dist/ | head -12 - - name: 修好 Electron 的 SUID 沙箱助手 - # 不改就会 FATAL:setuid_sandbox_host(chrome-sandbox 需 root:4755)而进程在断言前就死。 - # 用 --no-sandbox 绕过也能跑,但那等于把生产窗口的 sandbox: true 排除在验证之外, - # 所以这里选择把沙箱修好:preload 能在 sandbox 下工作,本身就是被 G7-3 的 IPC 断言验过的。 run: | sudo chown root:root node_modules/electron/dist/chrome-sandbox sudo chmod 4755 node_modules/electron/dist/chrome-sandbox - ls -l node_modules/electron/dist/chrome-sandbox npx electron --version - - name: 准备 Xvfb、中文字体与排版工具 - # fonts-noto-cjk 不是可选装饰:runner 默认没有中文字体,整片界面会渲染成豆腐块, - # 而「非白像素 ≥1%」这种断言照样能过。G7-5 现在会直接问字体在不在。 - # M5 起 G7-9 会真编一篇演示稿,所以 xelatex(texlive-xetex + 中文支持)与 pandoc 也要装。 - run: | - sudo apt-get update -q - sudo apt-get install -yq xvfb fonts-noto-cjk pandoc texlive-xetex texlive-lang-chinese texlive-latex-extra - - - name: G7 无头真启动与像素断言 - # 虚拟屏幕必须大于设计基准:屏幕正好 1440x900 时装不下带边框的窗口, - # 内容区会被钳成 1439x899,于是 G7 的尺寸断言红在一件与产品无关的事上。 - run: xvfb-run -a --server-args="-screen 0 1600x1000x24" npx electron tests/window-smoke.cjs - - - name: G6b 独立核验真启动结果 - # 不靠上面那一步的退出码:上一轮就是 app.exit(1) 被生产入口的 app.quit() 顶掉, - # 10/12 项通过却把 job 跑绿了。这里改读 screenshots/window-smoke.json 并复算读数。 - run: npm run verify:window + - name: 准备 Xvfb 与中文字体 + run: sudo apt-get update -q && sudo apt-get install -yq xvfb fonts-noto-cjk + + - name: 真启动与像素断言 + run: xvfb-run -a --server-args="-screen 0 1600x1000x24" npx electron desktop/tests/window-smoke.cjs - name: 上传截图与结果 if: always() diff --git a/.gitignore b/.gitignore index 217ad36..9c8fd36 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,8 @@ release/ *.log # Python -runtime/.venv/ +modeling/.venv/ +gateway/.venv/ .venv/ __pycache__/ *.py[cod] @@ -24,19 +25,9 @@ vendor/python/ vendor/pandoc/ vendor/*.zip vendor/.downloads/ -# 冒烟产物由 CI 上传为 artifact;只挡这几个具体文件, -# 免得将来要提交的界面截图(screenshots/*.png)被整目录规则一起吞掉 +# 冒烟产物由 CI 上传为 artifact screenshots/window-smoke.png screenshots/window-smoke.json -screenshots/conversation.png -screenshots/settings.png -screenshots/decision.png -screenshots/drawer.png -screenshots/figure.png -screenshots/score.png -screenshots/dropzone.png -screenshots/files.png -screenshots/attachments.png *.7z *.dmg *.exe @@ -55,11 +46,8 @@ open-dev.lnk .env.* !.env.example -# 建模工作区(阶段二产物,用户内容不入库) -workspaces/ -第*题_*/ -# M3 会话状态(SQLite;不含 Key,但属于本机运行数据) +# 无界面运行的默认输出目录(本机运行数据) .mms/ # 编辑器与系统 @@ -68,4 +56,3 @@ workspaces/ .idea/ .DS_Store Thumbs.db -screenshots/paper.png diff --git a/.npmrc b/.npmrc index e3f5dd9..ec500cc 100644 --- a/.npmrc +++ b/.npmrc @@ -1,5 +1,5 @@ # Electron 与 electron-builder 的二进制从 npmmirror 取,避免 github.com/443 在大陆网络下随机翻转。 # 这两行只影响「下载哪个 zip」,不改变依赖解析来源;不在大陆的开发者可直接删掉。 -# 注意信任边界:镜像与官方同源同校验值,但下载通道换成了第三方,见 docs/env-setup.md。 +# 注意信任边界:镜像与官方同源同校验值,但下载通道换成了第三方;下载失败先换源再判死。 electron_mirror=https://npmmirror.com/mirrors/electron/ electron_builder_binaries_mirror=https://npmmirror.com/mirrors/electron-builder-binaries/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 180dada..994d492 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,25 @@ 本项目遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 格式,版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 从 `0.1.0` 起,CLI 参数与退出码、注册表字段、产物路径为 Stable;`--json` 字段顺序与错误措辞仍为 Experimental。 +## Unreleased - 精简 + +### 变更 + +- **目录分层**:`modeling/`(数模领域)、`gateway/`(通用通道)与 `desktop/`(Electron 桌面端)分开,根目录只保留 npm workspace 入口、版本与法务文档;`server` 不再直接 import 流水线,改由入口注入 runner。 +- **技能包归位**:原 `skills/` 恢复到 `modeling/skills/`(core / methods / figure / diagram / paper / deai / score),作为领域资产保留;当前流水线尚未调用。 +- **前端重做(极简聊天式)**:左侧「工作区 → 对话」两级树(多工作区、多对话,本地持久化);首开中部欢迎文案与四步数模引导;中部对话流承载一次完整运行(进度、日志、求解图、PDF/Word)。核心流水线不变。 +- **一键流水线**:题面拆解 → 选模(自动采用推荐)→ 生成 `solution.py` → 运行与修复 ≤3 轮 → 论文生成与排版 ≤3 轮。删除七阶段人审卡、评分、雷达、门禁、会话恢复与工作台七页。 +- **单页界面**:一页三栏「赛题 / 进度 / 结果」,保留设置弹窗、离线模式、产物打开按钮;渲染层去掉 katex、pdfjs、markdown 依赖。 +- **运行时收敛**:删除技能包(`skills/`)、契约 schema、工作台图表/评分、长会话 harness、SQLite 会话库与七个自检;论文骨架与写作规范迁入 `modeling/src/mms_modeling/templates/`。 +- **依赖收敛**:Python 只留 `numpy`、`matplotlib`;Word 由 pandoc 直接转换,不再后处理 DOCX。 +- **通道与安全保留**:127.0.0.1 + Bearer token + Host/Origin 校验;Key 仍用 `safeStorage`,不落盘、不进事件。 + +### 验证(本机 Windows,2026-11-23) + +- `npm run typecheck`、`npm run build` 通过;`npm run smoke:window` 12 项断言全绿(窗口、运行时握手、界面文本、墨迹占比)。 +- 离线全链:无界面 CLI 与桌面界面各跑一遍,5 阶段全通过,R²=0.997,PNG/PDF/SVG 与 paper.pdf/paper.docx 均生成,界面耗时 8.1s。 +- 未证:真实服务商 Key 的联网端到端;安装包未重新构建。 + ## 0.2.0 - 2026-11-15 数模模块真正跑通:七阶段全链由 LLM 驱动(配 Key 时),离线演示与失败回退保留;移除 DSH 双内核,工作台精简。 diff --git a/README.md b/README.md index 60a86b0..7193981 100644 --- a/README.md +++ b/README.md @@ -1,204 +1,92 @@ -

MathModel Studio

+# MathModel Studio -

面向数学建模竞赛的本地桌面 Agent · 关键判断留给你

+桌面端数学建模工作台:输入赛题与数据,自动完成题面拆解、方法选择、求解代码生成与运行、论文排版。界面走极简聊天式:左侧「工作区 → 对话」树,中部对话流与首开欢迎引导,没有多级工作台与人工确认卡。 -

- 从赛题到论文,需要判断的地方都会停下来等你确认:
- 选模理由、方案解释、门禁结论和扣分明细都在界面上,可以追问,也可以回滚。 -

+## 工作流 -

- 版本 - CI - 平台 - 技能 - 许可证 - Python - 桌面端 -

+1. **题面拆解**:模型把赛题拆成子问题;模型不可用时按小节切分。 +2. **方法选择**:模型给出三条候选并标出推荐,直接采用推荐;失败时用内置方法族。 +3. **生成代码**:按题面、所选方法与数据画像生成 `solution.py`,契约固定为 `--data` / `--out`,须写出 `result.json` 与 `figure.png/pdf/svg`。 +4. **运行求解**:执行脚本;失败把 stderr 与上一版代码回喂模型,最多 3 轮。 +5. **论文排版**:按真实 `result.json` 与求解图写 `paper.tex`,xelatex 编译 PDF、pandoc 转 Word;编译失败回喂修复,最多 3 轮。 -

- 简体中文  ·  English -

+所有论文数值只来自本次运行的 `result.json`。没有可用模型时进入离线模式:内置基线脚本 + 样例稿,事件与界面会标明兜底,不冒充按本题生成。 ---- +## 运行方式 -

- MathModel Studio:通用模式欢迎页,底部「通用 | 数模」分段切换 -

- -

通用模式:欢迎页与通用快捷提问,右侧只剩文件页图标

- -> **设计原则**:能自动校验的交给门禁,需要判断的留给人,判断点做成界面。 -> -> 桌面程序内置一组技能(出版级图表、排版规范、AI 痕迹检查、结构自检与评分)。模型由使用者接入,数据不出本机。 - -## 概览 - -MathModel Studio 面向正在推进建模工作、准备交付的参赛者与研究者。它不替使用者做建模判断,但把阶段推进、选模、图表返工、论文排版和交付检查放在同一个工作台里,每一步都有记录。 - -- **本地优先**:桌面端和 Python 运行时都在本机运行,模型 Key 用系统安全存储加密。 -- **人在环**:关键节点会停下来等确认;重启后仍停在原来的决策点。 -- **契约驱动**:技能由注册表、JSON Schema 和 CLI 退出码约束,界面按注册表生成,不写死技能清单。 -- **证据可复核**:每条门禁都有读数,并配反向用例。 - -## 界面 - -截图来自实际界面(1.5 倍像素密度):整行大图来自 1440×900 窗口,面板图裁自 1500×900 窗口。会话内容来自离线演示,没有真实赛题和密钥。 - -

K3 选模卡:五维雷达与字段对照

- -

K3 选模:三条候选附五维雷达(创新、解释、精度、速度、易做),越靠外越好,难度与耗时已反向

- -| 过程总览与产物芯片 | 五维评分与扣分定位 | -| --- | --- | -| 过程总览:七节点管线与产物芯片 | 五维评分与扣分明细 | -| 七阶段管线按状态着色,点芯片直达对应页 | 五维得分、扣分明细和正文定位 | - -

论文排版与页级 PDF 预览

- -

论文:xelatex → pandoc → 三道交付门禁,pdf.js 页级预览

- -

对话:流式回复与工具卡

- -

对话:流式回复、折叠思考与工具卡在同一条时间线上

- -## 当前状态 - -**0.2.0(2026-11-15)**。数模模块真正跑通:配 Key 后七阶段全链由 LLM 驱动——K2 拆题面与核对数据角色、K3 按本题出选模候选(五维雷达对比,难度与耗时反向归一)、阶段四按题面与所选方法生成求解代码并经「代码确认卡」点运行才执行(失败回喂修复 ≤2 轮)、阶段五按真实结果写论文并过三道门禁、阶段六按 rubric 真实评分(总分 <85 回喂修复 ≤3 轮熔断,一票否决直接淘汰)。没有 Key 或模型不可用时回退确定性路径与演示样例,并在对话里明确标注兜底。默认进入通用对话,底部「通用 | 数模」分段切换;单 Python 内核(DSH 双内核已移除)。基础能力:多会话管理、五类模型入口(DeepSeek、通义千问、Kimi、智谱 GLM、OpenAI 格式端点)、200k / 400k / 1m 上下文预算、中 / 高 / 最大思维深度、附件读取与可收起的右侧工作台。 - -论文页完成整条排版链路:xelatex 两遍 → pandoc 转 DOCX → Word 版式后处理 → 去 AI 措辞、结构指标和章节结构三道门禁;PDF 用 pdf.js 逐页预览。论文与评分按会话隔离,构建成功自动推进阶段五。 - -打包已配置完成:electron-builder 把便携 Python 和 pandoc 一起装进安装包;0.2.0 的 NSIS x64 安装包尚未构建,干净机安装仍是未证项。 - -里程碑见 [PLAN.md](docs/PLAN.md) §7;已验证结论与未证事项见 [docs/handoff.md](docs/handoff.md)。 - -## 快速开始 - -```bash -# 安装依赖。大陆网络环境请先阅读 docs/env-setup.md:npm 直连与 github.com 均不稳定 -npm install -python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/ - -# 启动桌面端。无 Key 时可加 MMS_FAKE_PROVIDER=1 使用离线演示 -MMS_FAKE_PROVIDER=1 npm run dev - -# 不接入模型也可验证运行时:列出 25 个模板并渲染一张图(PNG/PDF/SVG) -npm run mms -- templates -npm run mms -- invoke figure paired-raincloud - -# 运行全部本地门禁:注册表、技能规范、反向覆盖、类型检查、构建、产物冒烟、契约、CLI、通道、工作台与论文 -npm run gate -``` - -`npm run gate` 全部通过,表示本地门禁没有问题,且不依赖网络和显示器。论文自检需要本机安装 `xelatex` 和 `pandoc`(见「依赖」)。 - -## 核心能力 - -### 阶段编排与决策点 - -阶段零到阶段六(环境预检、赛题分析、工作目录、算法选择、代码实现、论文输出、评分优化)排成一条状态轨道,当前卡在哪一步可以直接看到。关键节点用决策卡暂停: - -- **K2 赛题与附件确认**:拆出子问题,标明附件用途,逐问对应数据。 -- **K3 选模卡**:2–3 条候选路线,列出核心思路、创新度、可解释性、实现难度、预计耗时和精度预期,附五维雷达对比,可换一批。 -- **K4 就地解释**:打开解释抽屉,待选状态不丢。 -- **K5 图表返工**:换模板、换主题、重渲和回滚;重渲后只显示当前图,旧版本进入历史。 -- **K6 评分与优化轮次**:五维评分、扣分定位、三轮熔断和一票否决。 - -数模模式的右侧工作台默认打开「过程总览」:七阶段管线按状态着色,每个阶段挂一条产物芯片(题面与附件、已选模型、图表版本、论文 PDF/DOCX、评分轮次),点芯片直达对应页;每次切入数模都回到这一页。 - -### 会话与上下文 - -左栏是会话列表:建模会话存在 SQLite,问答会话存在本地;可以新建、切换、单条删除和清空。切换时恢复消息、附件、阶段和待决卡。中栏顶部显示当前会话和上下文用量,按 200k / 400k / 1m 预算从最新消息往回装载。 - -### 模型接入 - -设置页按服务商列出五类入口,模型名可选预设或手动填写。Key 只经主进程 `safeStorage` 加密保存;未配置 Key 时可用离线演示。详见 [docs/providers.md](docs/providers.md)。 - -### 图表与论文 - -图表工作台调用真实渲染器输出 PNG/PDF/SVG,同时保留可复现的命令和运行日志。论文页完成 xelatex、pandoc、Word 版式后处理和三道交付门禁,PDF 用 pdf.js 逐页预览。 - -### 文件与工作区 - -「文件」页列出工作区内容,可以切换目录;工作区默认在桌面「赛题」,首次启动时创建。附件可以直接拖入中栏或粘贴,主进程负责抽取正文(PDF 用 pdfjs,文本和 CSV 直接读取并报告行列,xlsx 按工作表读成表格并识别日期,旧版 .xls 仍需另存)。 - -## 架构 - -

运行时架构

-

阶段轨道与决策点

- -桌面端和 Python 运行时通过本地回环通道(HTTP + SSE)通信,模型 Key 只由主进程加密保存。阶段在 K2–K6 决策点暂停,状态、待决卡和消息历史写入 SQLite,重启后可以恢复。 - -## 技能矩阵 - -技能清单以 [`skills/manifest.json`](skills/manifest.json) 为准;下表行数和徽章计数由 CI 校验,必须一致。 - -| 技能 | 职责 | 状态 | +| 方式 | 命令 | 说明 | | --- | --- | --- | -| [`mathmodel-core`](skills/mathmodel-core/) | 阶段零至阶段六编排与路由 | 内置 | -| [`mathmodel-methods`](skills/mathmodel-methods/) | 建模方法库与选型:问题族索引、选型依据、验证方式 | 内置 | -| [`mathmodel-paper`](skills/mathmodel-paper/) | 论文写作与排版:写作规范、LaTeX 骨架、Word 输出、参考文献 | 内置 | -| [`mathmodel-figure`](skills/mathmodel-figure/) | 数据图表:matplotlib 模板库与 Nature 出图标准 | 内置 | -| [`mathmodel-diagram`](skills/mathmodel-diagram/) | 学术示意图:JSON 驱动版式模板与高保真复刻 | 内置 | -| [`mathmodel-deai`](skills/mathmodel-deai/) | 降 AI 与交付核查:词表级、结构级、字符级三道门禁 | 内置 | -| [`mathmodel-score`](skills/mathmodel-score/) | 结构自检与评分:章节门槛与百分制五维评分卡 | 内置 | +| 桌面开发 | `npm install` → `npm run dev` | 启动 Electron 与本地 Python 运行时 | +| 无界面跑一遍 | `python modeling/cli.py run --problem-file 题面.txt [--data 数据.csv] [--out 目录]` | 事件按 JSON Lines 输出;默认离线模式 | +| 类型检查 | `npm run typecheck` | 主进程、preload、渲染层全覆盖 | +| 构建 | `npm run build` | 产物在 `desktop/out/` | +| 真启动冒烟 | `npm run smoke:window` | 起生产入口,断言窗口、运行时与界面文本 | +| 打包 | `npm run vendor:python`、`npm run vendor:pandoc` → `npm run dist:win` | 随包 Python 与 pandoc,输出 NSIS 安装包 | -七个技能以源码随仓库分发(Apache-2.0),版本和引入记录见 [`skills/VENDOR.md`](skills/VENDOR.md)。运行时只通过 subprocess 调用技能脚本、按退出码判定,因此每个技能也能被 Claude Code 等宿主单独加载。 +## 环境要求 -## 质量门禁与证据 +- Node.js 22 及以上。 +- Python 3.12 及以上,并安装 `modeling/requirements.txt`(`numpy`、`matplotlib`)。 +- 生成 PDF 需要本机 `xelatex`;转 Word 需要 `pandoc`。缺失时求解结果仍保留,论文步骤会明确报缺。 +- 主平台为 Windows;macOS / Linux 可开发运行,未做安装包验证。 -每条门禁都配了反向用例:只会报通过的检查器不算证据。 +## 数据与隐私 -| 门禁 | 判据 | 反向覆盖 | -| --- | --- | --- | -| G1 注册表一致 | 注册表、技能目录、契约词表与两份 README 的技能表及徽章计数一致 | 8 种破坏逐项注入,必须变红(`npm run check:registry:negative`) | -| G8 技能规范 | 每个技能的 `SKILL.md` 为合法 Agent Skills 入口:frontmatter 可解析、名称与目录一致、描述非空且在 1024 字内、无仓库私有字段 | 6 种基于真实文件的破坏必须变红(`npm run check:skills:negative`) | -| G2 契约校验 | 注册表按 JSON Schema Draft 2020-12 校验;`jsonschema` 缺席时降级并说明 | 两份非法注册表必须被拒 | -| G2b 版本同源 | `VERSION`、`package.json`、`pyproject.toml`、`mms/__init__.py` 四处一致 | 任一缺项或取值不同即失败 | -| G3 CLI 契约 | 退出码 0/1/2 均可达;实际调用渲染器并核验 PNG/PDF/SVG 三件产物 | 词表外取值、非法 JSON、空 `MMS_HOME`、未知子命令/模板与渲染器假成功均被拦截(`runtime/tests/selfcheck.py`) | -| G4 事件流 | 握手、Bearer token、回环 Host/Origin 白名单、九类 SSE 事件、续传与取消;覆盖 K2/K3 暂停恢复与进程重启后恢复、思维深度与上下文裁剪、代码确认卡与全链(论文+评分)事件契约(64 条) | 12 种坏事件必须被拒;无 token、错误 Host、无待决恢复均被拒(`python runtime/tests/selfcheck_channel.py --selftest`) | -| G5 provider 离线契约 | 本地假端点覆盖 429 退避、`reasoning_content` 分离、分片 `tool_calls` 拼装、历史消息剥离和 Key 传递边界 | Key 哨兵不得进入事件流与 stderr;未开启离线模式时假 provider 被拒 | -| G6 桌面骨架 | 类型检查、构建,并校验产物包含本项目中文文案与设计令牌 | 断言失败即退出 1(`scripts/smoke-dist.mjs`) | -| G9 工作台 | 真实渲染两版图、版本历史与回滚,未知模板、主题或版本不会写入历史;三轮评分、扣分定位、章节样例和一票否决(19 条) | 未知模板/主题/版本均为反向控制(`runtime/tests/selfcheck_workbench.py`) | -| G10 论文排版 | xelatex 两遍 → pandoc → Word 后处理:PDF/DOCX 文件头与体积、六个步骤、三道门禁、状态写入磁盘(12 条) | 缺件、坏稿、坏 TeX、缺稿件四条反向;`MMS_PAPER_SKIP=1` 才允许跳过并打印未验证 | -| G11 编排状态机 | 起题、K2 确认、K3 换一批与选模、代码确认卡(未确认不执行、失败回喂)、阶段四五六全链(求解→论文 PDF/DOCX+三门禁→真实评分达标/否决);LLM 注入的坏 JSON 回喂与回退、选模落盘(34 条) | 默认方法族写成单元素元组、关键词族被清空两种破坏必须变红(`python runtime/tests/selfcheck_orchestrator.py --selftest`) | -| G12 长会话 harness | 预算核算、工具结果先裁剪再结构化摘要、摘要本身有长度上限、二次压缩并入旧摘要、锚点每轮替换、溢出识别、单条超预算时从最早处丢;50 轮压到预算内且最近 6 条原文保留(14 条) | 拆掉压缩、关掉工具裁剪两种破坏必须变红(`python runtime/tests/selfcheck_harness.py --selftest`) | -| G13 附件 xlsx | 解压工作簿读出全部工作表:共享字符串与富文本、稀疏列、布尔/错误值、公式缓存值、日期与时间格式(含 1904 日期系统);单表最多 300 行 × 60 列(10 条) | 非 ZIP 与缺工作簿两种坏文件必须报错;301 行的表必须截到 300 行(`npm run check:xlsx`) | -| G7 真启动冒烟 | 以生产入口起窗,验证构建产物、1440×900、非白像素、IPC、中文真字形与 Key 不回显;覆盖 K2→K3→解释→选择→代码确认卡→运行、阶段四真跑与自动出图、图表重渲与回滚、评分、论文构建与预览、附件与 xlsx、工作区文件拖入与右键、多会话、五家预设、上下文与思维深度、通用/数模分段切换与按模式记住收合偏好、过程总览默认页与五维雷达、评分示例入口(116 条) | 空白截图、自建窗口、缺字(方框字形)和删除关键断言都会被拦截(`tests/window-smoke.cjs`) | -| G6b 结果核验 | 读取冒烟 JSON 并复算读数:内容尺寸、非白像素、断言下限、关键断言与自述计数 | `--selftest` 用 12 份合成结果证明假通过会被拒(`scripts/check-window-smoke.mjs`) | +- API Key 用系统安全存储(Electron `safeStorage`)加密保存,运行时按次传给本机进程;不落日志、不进事件、不写入运行目录。 +- 每次运行的代码、结果、论文都在用户数据目录的 `runs/<时间戳>/` 下,界面提供「打开 PDF」「打开 Word」「结果文件夹」。 +- 本地通道只绑定 `127.0.0.1`,每个请求校验随机 token 与 Host/Origin;主进程不把端口和 token 交给渲染层。 +- 服务商地址默认 https;自定义端点若用 http,只接受回环地址。 -## 验证状态 +## 配置服务商 -0.2.0 在本机(Windows)验证了类型检查、构建与完整 `npm run gate`(G4 64/64、G11 34/34、G12 14/14、G13 10/10、G9 19/19、G10 12/12):离线全链(fake provider)从题面 → 选模 → 代码确认 → 运行 → 论文 PDF/DOCX + 三门禁 → 评分达标,阶段 0–6 全 passed。G7 真启动本轮被本机环境阻塞(重启后 Electron 渲染进程挂起,疑似终端安全软件拦截),待环境恢复后复跑。 +设置弹窗内置 DeepSeek、通义千问、Kimi、智谱 GLM、OpenAI 格式端点与离线模式。预设模型与地址在 `gateway/src/mms_gateway/providers.json`,可自行增改。 -0.2.0 的 NSIS x64 安装包尚未构建;打包配置已把便携 Python 与 pandoc 接入。 +- 真实服务商需要填写模型名与 API Key。 +- 自定义端点填到 `/v1` 为止,公网必须 https。 +- 离线模式不需要 Key,用于先跑通整条链路。 -未覆盖范围:五家服务商的真实联网端到端(本仓库不包含 Key,需用户配 Key 后自跑)、G7 真启动(环境阻塞)、CI 的 Windows 真起窗、CSP 违规场景的主动探测、安装包在干净机器上的安装与运行。发布记录见 [CHANGELOG.md](CHANGELOG.md),发布格式见 [docs/release.md](docs/release.md)。 - -## 依赖 - -| 用途 | 依赖 | 说明 | -| --- | --- | --- | -| 桌面壳 | Electron、electron-vite、React、TypeScript | 见 `package.json` | -| 运行时 | Python 3.12+ | 通道服务器、SSE 与 provider 客户端仅用标准库;`jsonschema>=4.20` 可选,缺席时契约校验降级 | -| 模型接入 | DeepSeek、通义千问、Kimi、智谱 GLM 与任意 OpenAI 格式端点 | 见 [docs/providers.md](docs/providers.md);Key 经主进程 `safeStorage` 加密 | -| 排版 | xelatex、pandoc、python-docx | xelatex 需本机安装(TeX Live 或 MiKTeX);pandoc 可随包提供,也可放进 PATH、设置 `MMS_PANDOC`,或安装到 `%LOCALAPPDATA%\mms-tools\pandoc.exe` | -| 出图 | matplotlib、numpy、seaborn | 版本下限见 `requirements.txt`,安装使用镜像 | -| 论文预览 | pdfjs-dist | 随 `npm install` 安装,worker 由 Vite 打包,运行时无需网络 | +## 目录 -## 打包与分发 +根目录是 npm workspace,只做脚本转发;数模领域、通用通道与桌面端各自独立。 -打包已配置:内置便携 Python 运行时(python-build-standalone,放在 `vendor/python`,不入库),pandoc 以 `vendor/pandoc/pandoc.exe` 随包放进 `resources/pandoc`;xelatex 仍需本机安装,TeX 没有内置。NSIS x64 配置见 `electron-builder.yml`,随包工具链由 `scripts/prepare-vendor.mjs` 准备。应用、安装器与向导页头/侧栏图共用 `build/icon.svg` 生成的图标;安装包用自签名证书,证书根不受信任,SmartScreen 会提示未知发布者。 - -## 参与贡献 - -欢迎提交 Issue 与 Pull Request。报告问题请写清版本号、Windows 版本、复现步骤与相关日志;改代码或文档前建议先开 Issue 说明意图,避免重复劳动。提交前请在本机跑通 `npm run typecheck`、`npm run build` 与上文「质量门禁与证据」中对应的门禁,并在 PR 描述里写明改动动机与验证方式。本仓库以 AGPL-3.0-only 发布,提交 PR 即表示同意你的贡献按同一许可分发。 - -## 合规声明 - -本工具用于排版、出图、交付前自检和方法选型讨论,不代替建模判断,也不保证获奖。内置评分与结构自检默认采用国赛口径(对齐 2026 格式规范),美赛口径可通过参数切换;AI 痕迹检查仅清理模板腔与不可见字符,不将未完成的工作表述为已完成。伪造结果、编造文献与数据属于硬性红线。请遵守所在赛事对生成式工具的规定。 +``` +. +├─ modeling/ 数模领域(不依赖 GUI) +│ ├─ cli.py serve / run 入口,装配 modeling + gateway +│ ├─ pyproject.toml +│ ├─ requirements.txt +│ ├─ skills/ 技能包:core / methods / figure / diagram / paper / deai / score +│ └─ src/mms_modeling/ +│ ├─ pipeline.py 一键流水线 +│ ├─ baseline.py 数据画像、基线脚本、执行与产物收集 +│ ├─ paper_gen.py / paper_build.py 论文生成与排版 +│ └─ templates/ 论文骨架与写作规范 +│ (skills/ 是领域资产,当前一键流水线尚未调用) +├─ gateway/ 通用通道(不依赖数模) +│ ├─ pyproject.toml +│ └─ src/mms_gateway/ +│ ├─ server.py 本机 HTTP + SSE 通道,runner 由外部注入 +│ ├─ provider.py OpenAI 兼容流式客户端 +│ ├─ llm.py JSON / 文本调用与重试 +│ └─ providers.json 预设服务商与模型 +├─ desktop/ Electron 桌面端 +│ ├─ src/ +│ │ ├─ main/ 通道、设置、文件选择、产物打开 +│ │ ├─ preload/ 窄 IPC 接口 +│ │ ├─ renderer/ 极简聊天式界面(工作区/对话树 + 欢迎引导 + 对话流) +│ │ └─ shared/ 共享类型 +│ ├─ tests/window-smoke.cjs 真启动冒烟 +│ ├─ scripts/prepare-vendor.mjs 随包 Python / pandoc 准备 +│ ├─ build/ 图标与安装向导图 +│ ├─ electron.vite.config.ts +│ ├─ electron-builder.yml +│ ├─ package.json 桌面端依赖与脚本 +│ └─ tsconfig*.json +├─ package.json npm workspace 入口 +├─ VERSION / LICENSE / THIRD_PARTY_NOTICES.md +└─ vendor/ 随包 Python / pandoc(本机生成,不入库) +``` ## 许可 -[AGPL-3.0-only](LICENSE)。本仓库整体以 AGPL-3.0-only 发布;分发本软件或其修改版时,需按该许可提供对应源码。[`skills/`](skills/) 中的 Apache-2.0 文件保留原许可与版权声明,版本与出处记录见 [`skills/VENDOR.md`](skills/VENDOR.md)。 +AGPL-3.0-only。第三方组件与分发说明见 `THIRD_PARTY_NOTICES.md`。 diff --git a/README_EN.md b/README_EN.md deleted file mode 100644 index d857d2e..0000000 --- a/README_EN.md +++ /dev/null @@ -1,200 +0,0 @@ -

MathModel Studio

- -

A local desktop agent for mathematical modeling contests · a human-in-the-loop workbench

- -

- From problem statement to paper, the judgement calls stay with the user:
- model rationale, explanations, gate verdicts and scoring details remain visible, queryable and reversible. -

- -

- version - CI - platform - skills - license - Python - desktop -

- -

- 简体中文  ·  English -

- ---- - -

- MathModel Studio: general-mode welcome with the segmented General / Modeling switch -

- -

General mode: welcome page with generic starters; the workspace pane is down to a files-only icon strip

- -> **Design principle**: anything a machine can verify goes to a gate; anything that requires judgement stays with the user, with each decision point rendered as UI. -> -> This tool integrates a contract-driven skill set (publication-grade figures, typesetting rules, AI-trace checks, structural audit and scoring) into a local desktop program: the model is provided by the user, data stays on the machine, and every step is auditable. - -## Overview - -MathModel Studio targets contestants and researchers who are already working through a modeling problem. It does not replace modeling judgement; it organizes phase progression, model selection, figure rework, paper typesetting and delivery checks into an auditable workflow. - -- **Local first**: the desktop shell and the Python runtime both execute on the local machine; model keys are encrypted with the system secure store. -- **Human in the loop**: phase progression pauses at key decision points and waits for confirmation; pending state survives process restarts. -- **Contract driven**: skills are constrained by a registry, JSON Schemas and CLI exit codes; the UI is generated from the registry rather than a hard-coded skill list. -- **Reviewable evidence**: gates, scoring and CI assertions provide readings and negative coverage. - -## Interface - -Screenshots come from the real UI at 1.5× pixel density: full-row shots come from a 1440×900 window, panel crops come from a 1500×900 window. Conversation content comes from the offline demo and contains no real problem statement or key. - -

K3 model-choice cards: five-dimension radar comparison

- -

K3 model choice: three candidates with a five-dimension radar (innovation, explainability, accuracy, speed, ease); difficulty and effort are inverted so the outer edge is always better

- -| Process overview with artifact chips | Five-dimension score and deduction targets | -| --- | --- | -| Process overview: seven-node pipeline with artifact chips | Five-dimension score and deduction details | -| The seven-phase pipeline is colored by state; chips jump to the matching page | Five dimensions, deductions and in-text targets | - -

Paper typesetting with page-level PDF preview

- -

Paper: xelatex → pandoc → three delivery gates, previewed page by page with pdf.js

- -

Conversation with streamed reply and tool card

- -

Conversation: streamed replies, collapsible thinking and tool cards on one timeline

- -## Status - -**0.2.0 (2026-11-15)**. The modeling module now runs end to end: with an API key configured, the whole seven-phase track is LLM-driven — K2 parses the problem and checks data roles, K3 proposes model candidates for the actual problem (five-dimension radar comparison, difficulty and effort inverted so the outer edge is always better), phase four generates solver code from the problem and chosen method and only executes it after the user clicks Run on a code-confirmation card (failures are fed back for repair, up to 2 rounds), phase five writes the paper from the real results and passes three delivery gates, and phase six scores the paper against the rubric (total <85 feeds deductions back for revision, up to 3 rounds before the breaker; a veto disqualifies immediately). Without a key, or when the model is unavailable, the app falls back to deterministic paths and demo samples, clearly labelled as fallback in the conversation. The app opens in general chat with a "General | Modeling" switch; a single Python kernel remains (the DSH dual-kernel was removed). Core features remain: multi-conversation management, five provider entry types (DeepSeek, Qwen, Kimi, Zhipu GLM and OpenAI-format endpoints), 200k / 400k / 1m context budgets, medium / high / max thinking depth, attachment reading, and a collapsible right-hand workspace. - -The paper tab runs the full typesetting chain: xelatex twice → pandoc to DOCX → Word restyle → de-AI phrasing, structural metrics and chapter-structure gates; PDFs are previewed page by page with pdf.js. Paper and scoring are scoped per conversation, and a successful build advances phase five automatically. - -Packaging is wired up: electron-builder bundles a portable Python and pandoc; the 0.2.0 NSIS x64 installer has not been built yet, and clean-machine installation remains unverified. - -Milestones are listed in [PLAN.md](docs/PLAN.md) §7; verified claims and open items are recorded in [docs/handoff.md](docs/handoff.md). - -## Quick start - -```bash -# Install. On mainland networks read docs/env-setup.md first: direct npm and github.com are both unreliable -npm install -python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/ - -# Launch the desktop app. Without a key, prefix MMS_FAKE_PROVIDER=1 for the offline demo -MMS_FAKE_PROVIDER=1 npm run dev - -# Validate the runtime without a model: list 25 templates and render one figure (PNG/PDF/SVG) -npm run mms -- templates -npm run mms -- invoke figure paired-raincloud - -# Run every local gate: registry, skill spec, negative coverage, typecheck, build, dist smoke, contracts, CLI, channel, workbench and paper -npm run gate -``` - -A passing `npm run gate` means the scaffold is self-consistent and needs neither network nor a display. The paper self-check requires `xelatex` and `pandoc` on the machine (see Dependencies). - -## Capabilities - -### Phase orchestration and decision points - -Phases zero to six (environment preflight, problem analysis, workspace layout, algorithm selection, implementation, paper output, scoring) are mapped onto a status track that shows where the agent is blocked. Key points pause as decision cards: - -- **K2 Problem and attachment confirmation**: subproblem decomposition, attachment and data roles, per-question data mapping. -- **K3 Model-choice cards**: two to three candidates with core idea, novelty, explainability, implementation difficulty, estimated effort and accuracy expectations, plus a five-dimension radar comparison; reroll is supported. -- **K4 In-place explanation**: opens an explanation drawer without clearing the pending choice. -- **K5 Figure rework**: switch template or theme, re-render and roll back; after a re-render only the current version is shown and older versions move into history. -- **K6 Scoring and optimization rounds**: five dimensions, deduction targets, a three-round circuit breaker and a veto example. - -In Modeling mode the workspace pane opens on the process overview by default: the seven-phase pipeline is colored by state, each phase carries an artifact chip (problem and attachments, chosen model, figure versions, paper PDF/DOCX, scoring rounds), and chips jump straight to the matching page; every entry into Modeling mode returns to this page. - -### Conversations and context - -The left rail is a conversation list: modeling sessions are read from SQLite and chat sessions are stored locally; sessions can be created, switched, deleted individually or cleared. Switching restores messages, attachments, phase and pending cards. The chat header shows the active conversation and context usage, loaded backwards from the latest message within a 200k / 400k / 1m budget. - -### Model access - -The settings page organizes five provider types in a list, with preset or manually entered model names. Keys are encrypted by the main process via `safeStorage`; the offline demo runs without a key. See [docs/providers.md](docs/providers.md). - -### Figures and papers - -The figure workbench calls the real renderer to produce PNG/PDF/SVG and keeps the reproducible command and run logs. The paper tab runs xelatex, pandoc, Word restyling and three delivery gates, with a pdf.js page preview. - -### Files and workspace - -The files tab lists the workspace and can switch directories; the default workspace is a `赛题` folder on the Desktop, created on first launch. Attachments can be dropped or pasted into the chat column; the main process extracts their text (pdfjs for PDFs, direct reads for text/CSV with row × column counts, and xlsx read sheet by sheet with date detection; legacy .xls still needs conversion). - -## Architecture - -

Runtime architecture

-

Phase rail and decision points

- -The desktop shell and the Python runtime communicate over a loopback channel (HTTP + SSE); model keys are encrypted by the main process only. Phase progression pauses at K2–K6 decision points, and phase, pending cards and message history are persisted in SQLite so they survive process restarts. - -## Skills - -[`skills/manifest.json`](skills/manifest.json) is the single source of truth; the row count below and the badge count above are enforced equal by CI. - -| Skill | Responsibility | Status | -| --- | --- | --- | -| [`mathmodel-core`](skills/mathmodel-core/) | Orchestration and routing across phases 0–6 | built-in | -| [`mathmodel-methods`](skills/mathmodel-methods/) | Method library and selection: problem-family index, rationale, verification | built-in | -| [`mathmodel-paper`](skills/mathmodel-paper/) | Writing and typesetting: rules, LaTeX skeleton, Word output, references | built-in | -| [`mathmodel-figure`](skills/mathmodel-figure/) | Data figures: matplotlib template library and Nature drawing standard | built-in | -| [`mathmodel-diagram`](skills/mathmodel-diagram/) | Academic diagrams: JSON-driven layout templates and faithful replication | built-in | -| [`mathmodel-deai`](skills/mathmodel-deai/) | De-AI and delivery checks: lexical, structural and character-level gates | built-in | -| [`mathmodel-score`](skills/mathmodel-score/) | Structure audit and scoring: chapter gate and a 100-point five-dimension rubric | built-in | - -The seven skills ship as source with this repository (Apache-2.0); versions and import history are recorded in [`skills/VENDOR.md`](skills/VENDOR.md). The runtime only calls skill scripts via subprocess and reads their exit codes, so each skill remains independently loadable by hosts such as Claude Code. - -## Gates and evidence - -Every gate ships with negative coverage: a checker that only ever returns zero is not evidence. - -| Gate | Criterion | Negative control | -| --- | --- | --- | -| G1 registry consistency | registry, skill directories, contract vocabularies and both README skill tables and badge counts agree | eight seeded breakages, each must turn red (`npm run check:registry:negative`) | -| G8 skill specification | every `SKILL.md` is a valid Agent Skills entry: parseable frontmatter, name matching the directory, non-empty description within 1024 characters, no repository-private fields | six breakages built from the real files must turn red (`npm run check:skills:negative`) | -| G2 contract validation | registry validated against JSON Schema Draft 2020-12; degrades with a printed note when `jsonschema` is absent | two deliberately invalid registries must be rejected | -| G2b version parity | `VERSION`, `package.json`, `pyproject.toml` and `mms/__init__.py` agree | any missing or differing value fails | -| G3 CLI contract | exit codes 0/1/2 are reachable; the renderer is actually invoked and PNG/PDF/SVG artifacts are verified | out-of-vocabulary values, invalid JSON, empty `MMS_HOME`, unknown subcommands/templates and a renderer that fakes success are all rejected (`runtime/tests/selfcheck.py`) | -| G4 event stream | handshake, Bearer token, loopback Host/Origin allow-list, nine SSE event types, replay and cancellation; covers K2/K3 pause-and-resume, cross-process recovery, thinking depth and context trimming, the code-confirmation card and full-chain (paper + scoring) event contracts (64 assertions) | twelve malformed events must be rejected; missing token, wrong Host and resuming without a pending decision are refused (`python runtime/tests/selfcheck_channel.py --selftest`) | -| G5 provider offline contract | a local fake endpoint covers 429 backoff, `reasoning_content` separation, split `tool_calls` assembly, reasoning stripped from history and key transmission boundaries | key sentinels must never reach the event stream or stderr; the fake provider is refused when offline mode is off | -| G6 desktop scaffold | typecheck and build, plus verification that the bundle contains this project's Chinese copy and design tokens | any failed assertion exits 1 (`scripts/smoke-dist.mjs`) | -| G9 workbench | two real renders, version history and rollback, unknown template/theme/version rejected without adding a version; three scoring rounds, deduction targets, chapter sample and veto example (19 assertions) | unknown template/theme/version are negative controls (`runtime/tests/selfcheck_workbench.py`) | -| G10 paper typesetting | xelatex twice → pandoc → Word restyle: PDF/DOCX magic and size, six steps, three gates and persisted state (12 assertions) | four negative controls (missing tools, bad paper, broken TeX, missing source); skipping requires `MMS_PAPER_SKIP=1` and prints that G10 was not verified | -| G11 orchestration state machine | start, K2 confirmation, K3 reroll and choice, the code-confirmation card (no execution before confirmation, failure feedback), and the full phase 4/5/6 chain (solver → paper PDF/DOCX + three gates → real scoring pass/veto); LLM-injection bad-JSON retry and fallback, and persisting the chosen model (34 assertions) | two seeded breakages must turn red: the default family written as a one-element tuple, and the keyword families cleared (`python runtime/tests/selfcheck_orchestrator.py --selftest`) | -| G12 long-session harness | budget accounting, tool-result pruning before a structured summary, a hard size cap on the summary itself, summaries merged across compactions, per-turn anchor replacement, overflow detection, and oldest-first dropping when a single message exceeds the budget; 50 rounds compacted under budget with the last six messages kept verbatim (14 assertions) | disabling compaction or tool pruning must turn red (`python runtime/tests/selfcheck_harness.py --selftest`) | -| G13 attachment xlsx | unzips the workbook and reads every sheet: shared strings and rich text, sparse columns, booleans/errors, cached formula values, date and time formats (including the 1904 date system); at most 300 rows × 60 columns per sheet (10 assertions) | a non-ZIP file and a ZIP without a workbook must be rejected; a 301-row sheet must be cut to 300 rows (`npm run check:xlsx`) | -| G7 real launch | launches the production entry and asserts built artifact, 1440×900, non-white pixels, IPC, real CJK glyphs and that keys are never echoed; covers K2→K3→explain→choose→code-confirmation→run, real phase four and automatic figure registration, figure re-render and rollback, scoring, paper build and preview, attachments and xlsx, workspace-file drag and context menu, multi-conversation, five provider presets, context and thinking depth, the General/Modeling segmented switch with per-mode collapse memory, the process-overview default page, the five-dimension radar and the score demo entry (116 assertions) | blank screenshots, self-built windows, tofu glyphs and deleted key assertions have all been caught (`tests/window-smoke.cjs`) | -| G6b result audit | reads the smoke JSON and recomputes the readings: content size, non-white ratio, assertion floor, key assertions and self-reported counts | `--selftest` with 12 synthetic results proves that fake greens are rejected (`scripts/check-window-smoke.mjs`) | - -## Verification status - -Local verification for 0.2.0 (Windows) covers typecheck, build and the full `npm run gate` (G4 64/64, G11 34/34, G12 14/14, G13 10/10, G9 19/19, G10 12/12): the offline full chain (fake provider) runs problem → model choice → code confirmation → run → paper PDF/DOCX + three gates → scoring pass, with phases 0–6 all passed. The G7 real launch is blocked this round by a local environment issue (Electron renderer processes hang after a reboot; Edge works as a control), to be re-run once the environment is cleared. - -The 0.2.0 NSIS x64 installer has not been built yet; packaging bundles a portable Python and pandoc. - -Not covered: real networked end-to-end runs with any of the five providers (no key is included in this repository — configure your own key to run a real problem), the G7 real launch (environment-blocked), launching a window on Windows in CI, active probing of CSP violations, and installing/running the installer on a clean machine. Release records live in [CHANGELOG.md](CHANGELOG.md); the release format is specified in [docs/release.md](docs/release.md). - -## Dependencies - -| Purpose | Requirement | Note | -| --- | --- | --- | -| Desktop shell | Electron, electron-vite, React, TypeScript | see `package.json` | -| Runtime | Python 3.12+ | the channel server, SSE and provider client are standard-library only; `jsonschema>=4.20` is optional and validation degrades without it | -| Model access | DeepSeek, Qwen, Kimi, Zhipu GLM and any OpenAI-format endpoint | see [docs/providers.md](docs/providers.md); keys are encrypted by the main process via `safeStorage` | -| Typesetting | xelatex, pandoc, python-docx | xelatex requires a local install (TeX Live or MiKTeX); pandoc may be bundled, placed on PATH, pointed to by `MMS_PANDOC`, or installed at `%LOCALAPPDATA%\mms-tools\pandoc.exe` | -| Figures | matplotlib, numpy, seaborn | lower bounds are in `requirements.txt`; install via a mirror | -| Paper preview | pdfjs-dist | installed by `npm install`; the worker is bundled by Vite and needs no network at runtime | - -## Packaging and distribution - -Packaging is decided and wired up: a portable Python runtime is bundled (python-build-standalone under `vendor/python`, not committed), and pandoc ships as `vendor/pandoc/pandoc.exe` under `resources/pandoc`; xelatex still requires a local install and TeX is not bundled. The NSIS x64 configuration lives in `electron-builder.yml`, and the bundled toolchain is prepared by `scripts/prepare-vendor.mjs`. The current installer is unsigned and uses the default Electron icon. - -## Compliance - -This tool assists modeling work that has already been done: typesetting, publication-grade figures, pre-delivery self-audit and method-selection discussion. It does not replace modeling judgement and does not promise an award. The bundled scoring and structure checks default to the Chinese national contest rubric (aligned to the 2026 format rules) and can be switched to MCM/ICM; AI-trace checks only remove template phrasing and invisible characters and never present unperformed work as performed. Fabricating results, references or data is a hard red line. Follow your own contest's rules on generative tools. - -## License - -[AGPL-3.0-only](LICENSE). This repository is released as a whole under AGPL-3.0-only; distributing the software or a modified version requires providing the corresponding source under that license. Files under [`skills/`](skills/) that are Apache-2.0 retain their original license and notices; versions and provenance are recorded in [`skills/VENDOR.md`](skills/VENDOR.md). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index cb2d52e..02dca2e 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -4,7 +4,7 @@ ## 本仓库许可 -本仓库整体以 AGPL-3.0-only 发布,全文见 `LICENSE`;分发本软件或其修改版时,需按 AGPL-3.0 提供对应源码。`skills/` 下的技能文件原以 Apache-2.0 发布,作为整体分发作品的一部分保留原许可与版权声明,出处见 `skills/VENDOR.md`。 +本仓库整体以 AGPL-3.0-only 发布,全文见 `LICENSE`;分发本软件或其修改版时,需按 AGPL-3.0 提供对应源码。 | 组件 | 用途 | 许可 | 来源 | | --- | --- | --- | --- | @@ -12,18 +12,13 @@ | Chromium | Electron 渲染引擎 | BSD-3-Clause 等 | https://www.chromium.org | | Node.js | Electron 内置运行时 | MIT | https://nodejs.org | | React / ReactDOM | 渲染层 | MIT | https://github.com/facebook/react | -| pdfjs-dist | PDF 预览 | Apache-2.0 | https://github.com/mozilla/pdf.js | | Python(python-build-standalone) | 内置解释器 | PSF-2.0 | https://github.com/astral-sh/python-build-standalone | | pandoc | Word 转换 | GPL-2.0-or-later | https://github.com/jgm/pandoc | | matplotlib | 图表渲染 | Matplotlib License(PSF 派生) | https://github.com/matplotlib/matplotlib | | numpy | 数值计算 | BSD-3-Clause | https://github.com/numpy/numpy | -| seaborn | 统计图样式 | BSD-3-Clause | https://github.com/mwaskom/seaborn | -| python-docx | DOCX 后处理 | MIT | https://github.com/python-openxml/python-docx | -| jsonschema | 契约校验 | MIT | https://github.com/python-jsonschema/jsonschema | -| PyMuPDF(fitz) | PDF 文本抽取 | AGPL-3.0 或 Artifex 商业许可(双许可) | https://github.com/pymupdf/PyMuPDF | ## 分发说明 - **Electron / Chromium**:完整许可文本随安装包提供,位于安装目录的 `LICENSE.electron.txt` 与 `LICENSES.chromium.html`。 - **pandoc(GPL-2.0-or-later)**:安装包随附二进制,许可全文见 `licenses/pandoc-COPYING.md`,版权与贡献者信息见 `licenses/pandoc-COPYRIGHT`;对应源码可从上游仓库获取。GPL-2.0-or-later 与 AGPLv3 兼容,随 AGPL-3.0-only 作品分发时保留本许可文本与源码获取方式即可。 -- **PyMuPDF(AGPL-3.0 / 商业许可)**:PyMuPDF 以 AGPL-3.0 或 Artifex 商业许可双许可发布。本仓库整体采用 AGPL-3.0-only,分发安装包时按 AGPL-3.0 提供对应源码(公开仓库与构建脚本即满足该义务);如需在闭源或非 AGPL 条件下分发,应取得 Artifex 商业许可,或改用宽松许可的 PDF 实现。 +- **PDF 排版**:论文 PDF 由系统或随包安装的 xelatex 生成,不随包分发 TeX 发行版;使用环境需自行安装并遵守其许可。 diff --git a/build/icon.ico b/desktop/build/icon.ico similarity index 100% rename from build/icon.ico rename to desktop/build/icon.ico diff --git a/build/icon.png b/desktop/build/icon.png similarity index 100% rename from build/icon.png rename to desktop/build/icon.png diff --git a/build/icon.svg b/desktop/build/icon.svg similarity index 100% rename from build/icon.svg rename to desktop/build/icon.svg diff --git a/build/installer.nsh b/desktop/build/installer.nsh similarity index 100% rename from build/installer.nsh rename to desktop/build/installer.nsh diff --git a/build/installerHeader.bmp b/desktop/build/installerHeader.bmp similarity index 100% rename from build/installerHeader.bmp rename to desktop/build/installerHeader.bmp diff --git a/build/installerSidebar.bmp b/desktop/build/installerSidebar.bmp similarity index 100% rename from build/installerSidebar.bmp rename to desktop/build/installerSidebar.bmp diff --git a/electron-builder.yml b/desktop/electron-builder.yml similarity index 57% rename from electron-builder.yml rename to desktop/electron-builder.yml index 3d9a310..e722535 100644 --- a/electron-builder.yml +++ b/desktop/electron-builder.yml @@ -1,8 +1,8 @@ -# electron-builder 配置(M6) +# electron-builder 配置(桌面端) # -# 资源布局:runtime/skills/schemas/VERSION/python/pandoc 都放在 resources/ 下, -# 与 src/main/runtime-env.ts 的 APP_ROOT 对齐;app.asar 里只放 JS 产物。 -# vendor/python 与 vendor/pandoc 由 scripts/prepare-vendor.mjs 准备,不入库。 +# 资源布局:modeling/gateway/VERSION/python/pandoc 放在 resources/ 下, +# 与 desktop/src/main/runtime-env.ts 的 APP_ROOT 对齐;app.asar 里只放 JS 产物。 +# vendor/python 与 vendor/pandoc 由 scripts/prepare-vendor.mjs 准备到仓库根 vendor/,不入库。 appId: cn.escap1ng.mathmodel-studio productName: MathModel Studio copyright: Copyright © 2026 Escap1ng @@ -19,36 +19,33 @@ electronLanguages: files: - out/**/* - package.json - - node_modules/pdfjs-dist/**/* extraResources: - - from: runtime - to: runtime + - from: ../modeling + to: modeling filter: - "**/*" - "!**/__pycache__/**" - "!**/*.pyc" - - from: skills - to: skills - - from: schemas - to: schemas - - from: VERSION + - from: ../gateway + to: gateway + filter: + - "**/*" + - "!**/__pycache__/**" + - "!**/*.pyc" + - from: ../VERSION to: VERSION - - from: LICENSE + - from: ../LICENSE to: LICENSE.txt - - from: THIRD_PARTY_NOTICES.md + - from: ../THIRD_PARTY_NOTICES.md to: THIRD_PARTY_NOTICES.md - - from: licenses + - from: ../licenses to: licenses - - from: vendor/python + - from: ../vendor/python to: python - - from: vendor/pandoc/pandoc.exe + - from: ../vendor/pandoc/pandoc.exe to: pandoc/pandoc.exe -# 主进程用 createRequire 加载 pdfjs 的 legacy 构建,从 asar 里读 worker/字体不稳。 -asarUnpack: - - node_modules/pdfjs-dist/** - win: target: - target: nsis @@ -60,8 +57,7 @@ nsis: # build/installer.nsh 自动被 include,负责把默认安装目录改成桌面的 MathModel Studio。 installerIcon: build/icon.ico uninstallerIcon: build/icon.ico - # 向导内两张图由 scripts/make-icon.mjs 从 build/icon.svg 生成;assisted 模式下 - # installerHeaderIcon 不生效(只在 oneClick 分支读取),页头图要靠 installerHeader。 + # 页头/侧栏图已入库;assisted 模式只读 installerHeader/installerSidebar。 installerHeader: installerHeader.bmp installerSidebar: installerSidebar.bmp oneClick: false diff --git a/electron.vite.config.ts b/desktop/electron.vite.config.ts similarity index 100% rename from electron.vite.config.ts rename to desktop/electron.vite.config.ts diff --git a/desktop/package.json b/desktop/package.json new file mode 100644 index 0000000..e7ec1e0 --- /dev/null +++ b/desktop/package.json @@ -0,0 +1,32 @@ +{ + "name": "mathmodel-studio", + "version": "0.2.0", + "private": true, + "description": "数学建模桌面工作台:题面 → 选模 → 代码 → 论文", + "author": "Escap1ng", + "license": "AGPL-3.0-only", + "main": "out/main/index.js", + "scripts": { + "dev": "electron-vite dev", + "build": "electron-vite build", + "preview": "electron-vite preview", + "typecheck": "tsc -p tsconfig.node.json --noEmit && tsc -p tsconfig.web.json --noEmit", + "pack:win": "npm run build && electron-builder --win --dir", + "dist:win": "npm run build && electron-builder --win nsis", + "vendor:python": "node scripts/prepare-vendor.mjs python", + "vendor:pandoc": "node scripts/prepare-vendor.mjs pandoc" + }, + "devDependencies": { + "@types/node": "^26.6.5", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "electron": "^44.8.0", + "electron-builder": "^26.18.0", + "electron-vite": "^6.0.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "typescript": "^7.0.2", + "vite": "^8.3.4" + } +} diff --git a/scripts/prepare-vendor.mjs b/desktop/scripts/prepare-vendor.mjs similarity index 95% rename from scripts/prepare-vendor.mjs rename to desktop/scripts/prepare-vendor.mjs index e32e039..584d67e 100644 --- a/scripts/prepare-vendor.mjs +++ b/desktop/scripts/prepare-vendor.mjs @@ -6,9 +6,9 @@ * node scripts/prepare-vendor.mjs pandoc [--force] * * python: python-build-standalone 的解压版解释器(npmmirror 通道)解到 vendor/python, - * 再按 requirements.txt 装依赖,最后逐个 import 自检。 + * 再装 numpy 与 matplotlib,最后逐个 import 自检。 * pandoc: 把本机 pandoc.exe 复制到 vendor/pandoc。pandoc 是 GPL-2.0-or-later, - * 随安装包分发时需要保留上游许可与源码指引(见 docs/env-setup.md)。 + * 随安装包分发时需要保留上游许可与源码指引(见 THIRD_PARTY_NOTICES.md)。 * * 下载地址与版本都在下面常量里,换版本时改这两行;失败先换通道再下结论。 */ @@ -19,7 +19,8 @@ import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') -const VENDOR = join(ROOT, 'vendor') +const REPO = resolve(ROOT, '..') +const VENDOR = join(REPO, 'vendor') const PBS_TAG = process.env['MMS_PBS_TAG'] || '20261026' const PY_VERSION = process.env['MMS_PY_VERSION'] || '3.12.16' @@ -35,7 +36,7 @@ const PY_DIR = join(VENDOR, 'python') const PY_EXE = join(PY_DIR, 'python.exe') const PANDOC_DIR = join(VENDOR, 'pandoc') const PANDOC_EXE = join(PANDOC_DIR, 'pandoc.exe') -const MODULES = ['matplotlib', 'numpy', 'seaborn', 'docx', 'fitz', 'jsonschema'] +const MODULES = ['matplotlib', 'numpy'] function log(message) { console.log(`[vendor] ${message}`) @@ -132,7 +133,7 @@ async function preparePython(force) { const version = run(PY_EXE, ['-c', 'import sys; print(sys.version)'], { stdio: 'pipe' }) log(`解释器就绪:${String(version.stdout).trim().split('\n')[0]}`) - log(`安装 requirements.txt(索引 ${PIP_INDEX})`) + log(`安装 modeling/requirements.txt(索引 ${PIP_INDEX})`) run(PY_EXE, [ '-m', 'pip', @@ -140,7 +141,7 @@ async function preparePython(force) { '--disable-pip-version-check', '--no-warn-script-location', '-r', - join(ROOT, 'requirements.txt'), + join(REPO, 'modeling', 'requirements.txt'), '-i', PIP_INDEX ]) diff --git a/desktop/src/main/channel.ts b/desktop/src/main/channel.ts new file mode 100644 index 0000000..29ac5bd --- /dev/null +++ b/desktop/src/main/channel.ts @@ -0,0 +1,243 @@ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { join } from 'node:path' +import type { RunEvent, RuntimeStatus } from '../shared/api' + +// 与 gateway/src/mms_gateway/server.py 的握手契约。渲染层永远拿不到 port 与 token。 +export interface ChannelHandshake { + port: number + token: string + pid: number + fake: boolean + version: string +} + +export interface RuntimeProvider { + id: string + display: string + models: string[] + model: string + base_url: string + requires_key: boolean + custom: boolean + note?: string +} + +interface RunBody { + problem: string + dataPaths: string[] + provider: { id: string; model: string; baseUrl?: string; apiKey: string } +} + +export class Channel { + private child: ChildProcessWithoutNullStreams | null = null + private handshake: ChannelHandshake | null = null + private status: RuntimeStatus = { state: 'starting' } + private readonly listeners = new Set<(s: RuntimeStatus) => void>() + private startPromise: Promise | null = null + private stopping = false + + constructor( + private readonly root: string, + private readonly python: string, + private readonly dataDir?: string + ) {} + + onStatus(cb: (s: RuntimeStatus) => void): () => void { + this.listeners.add(cb) + return () => this.listeners.delete(cb) + } + + current(): RuntimeStatus { + return this.status + } + + private setStatus(next: RuntimeStatus): void { + this.status = next + for (const cb of this.listeners) cb(next) + } + + start(): Promise { + if (this.handshake) return Promise.resolve() + if (this.startPromise) return this.startPromise + this.stopping = false + this.startPromise = this.launch().finally(() => { + this.startPromise = null + }) + return this.startPromise + } + + async restart(): Promise { + this.stop() + await this.start() + } + + private async launch(): Promise { + this.setStatus({ state: 'starting' }) + const child = spawn(this.python, [join(this.root, 'modeling', 'cli.py'), 'serve', '--port', '0'], { + cwd: this.root, + windowsHide: true, + env: { + ...process.env, + MMS_HOME: this.root, + ...(this.dataDir ? { MMS_DATA_DIR: this.dataDir } : {}), + MMS_PYTHON: this.python, + ...(this.dataDir ? { PYTHONPYCACHEPREFIX: join(this.dataDir, 'pycache') } : {}), + PYTHONIOENCODING: 'utf-8', + PYTHONUTF8: '1' + } + }) + this.child = child + + try { + const handshake = await this.readHandshake(child) + if (this.child !== child) throw new Error('runtime 启动被新的启动请求取代') + this.handshake = handshake + this.setStatus({ state: 'ready', version: handshake.version }) + + child.stdout.on('data', (chunk: Buffer) => { + const text = chunk.toString('utf8').trim() + if (text) console.warn('[runtime stdout]', text.slice(0, 500)) + }) + child.stderr.on('data', (chunk: Buffer) => { + const text = chunk.toString('utf8').trim() + if (text) console.warn('[runtime]', text.slice(0, 500)) + }) + child.on('exit', (code) => { + if (this.child !== child) return + this.child = null + this.handshake = null + if (!this.stopping) { + this.setStatus({ state: 'error', message: `runtime 已退出(code ${code ?? '?'})` }) + } + }) + } catch (err) { + child.kill() + this.child = null + this.handshake = null + const message = err instanceof Error ? err.message : String(err) + if (!this.stopping) this.setStatus({ state: 'error', message }) + throw err + } + } + + private readHandshake(child: ChildProcessWithoutNullStreams): Promise { + return new Promise((resolve, reject) => { + let buffer = '' + const timer = setTimeout(() => { + cleanup() + reject(new Error('runtime 握手超时')) + }, 20_000) + const cleanup = (): void => { + clearTimeout(timer) + child.stdout.off('data', onData) + child.off('exit', onExit) + } + const onData = (chunk: Buffer): void => { + buffer += chunk.toString('utf8') + const index = buffer.indexOf('\n') + if (index < 0) return + const line = buffer.slice(0, index).trim() + cleanup() + try { + resolve(JSON.parse(line) as ChannelHandshake) + } catch { + reject(new Error('runtime 握手不是合法 JSON')) + } + } + const onExit = (code: number | null): void => { + cleanup() + reject(new Error(`runtime 启动即退出(code ${code ?? '?'})`)) + } + child.stdout.on('data', onData) + child.on('exit', onExit) + }) + } + + private async request(method: string, path: string, body?: unknown): Promise { + await this.start() + const handshake = this.handshake + if (!handshake) throw new Error('runtime 未就绪') + const response = await fetch(`http://127.0.0.1:${handshake.port}${path}`, { + method, + headers: { + Authorization: `Bearer ${handshake.token}`, + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) + }, + body: body !== undefined ? JSON.stringify(body) : undefined + }) + const text = await response.text() + let data: unknown + try { + data = JSON.parse(text) + } catch { + throw new Error(`runtime 返回非 JSON(HTTP ${response.status})`) + } + const payload = data as { ok?: boolean; error?: { message?: string } } + if (!response.ok || payload.ok === false) { + throw new Error(payload.error?.message || `HTTP ${response.status}`) + } + return data as T + } + + async providers(): Promise<{ ok: true; providers: RuntimeProvider[] }> { + return this.request('GET', '/providers') + } + + async startRun(body: RunBody): Promise<{ ok: true; runId: string }> { + return this.request('POST', '/runs', body) + } + + async cancelRun(runId: string): Promise<{ ok: true }> { + return this.request('POST', `/runs/${encodeURIComponent(runId)}/cancel`) + } + + async stream(runId: string, cb: (event: RunEvent) => void, signal: AbortSignal): Promise { + await this.start() + const handshake = this.handshake + if (!handshake) throw new Error('runtime 未就绪') + const response = await fetch( + `http://127.0.0.1:${handshake.port}/runs/${encodeURIComponent(runId)}/events`, + { headers: { Authorization: `Bearer ${handshake.token}` }, signal } + ) + if (!response.ok || !response.body) throw new Error(`事件流打开失败(HTTP ${response.status})`) + const reader = response.body.getReader() + const decoder = new TextDecoder() + let buffer = '' + while (true) { + const { done, value } = await reader.read() + if (done) break + buffer += decoder.decode(value, { stream: true }) + let index: number + while ((index = buffer.indexOf('\n\n')) >= 0) { + const frame = buffer.slice(0, index) + buffer = buffer.slice(index + 2) + this.parseFrame(frame, runId, cb) + } + } + } + + private parseFrame(frame: string, runId: string, cb: (event: RunEvent) => void): void { + let id = '0' + let event = 'message' + let data = '' + for (const line of frame.split('\n')) { + if (line.startsWith('id:')) id = line.slice(3).trim() + else if (line.startsWith('event:')) event = line.slice(6).trim() + else if (line.startsWith('data:')) data += line.slice(5).trim() + } + if (!data) return + try { + cb({ runId, id, event, data: JSON.parse(data) as Record }) + } catch { + // 坏帧只跳过,不打断流 + } + } + + stop(): void { + this.stopping = true + const child = this.child + this.child = null + this.handshake = null + if (child) child.kill() + } +} diff --git a/desktop/src/main/files.ts b/desktop/src/main/files.ts new file mode 100644 index 0000000..1215a06 --- /dev/null +++ b/desktop/src/main/files.ts @@ -0,0 +1,30 @@ +import { dialog, type BrowserWindow } from 'electron' +import { readFileSync } from 'node:fs' +import type { ProblemFile } from '../shared/api' + +const MAX_PROBLEM_CHARS = 200_000 + +export async function pickProblemFile(win: BrowserWindow | null): Promise { + const options = { + title: '选择题面文件', + properties: ['openFile' as const], + filters: [{ name: '题面文本', extensions: ['txt', 'md', 'tex'] }] + } + const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options) + if (result.canceled || result.filePaths.length === 0) return null + const path = result.filePaths[0] + const text = readFileSync(path, 'utf8') + if (text.length > MAX_PROBLEM_CHARS) throw new Error('题面文件过大(超过 20 万字符)') + return { path, text } +} + +export async function pickDataFiles(win: BrowserWindow | null): Promise { + const options = { + title: '选择数据文件', + properties: ['openFile' as const], + filters: [{ name: '表格数据', extensions: ['csv', 'tsv'] }] + } + const result = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options) + if (result.canceled) return [] + return result.filePaths.slice(0, 1) +} diff --git a/desktop/src/main/index.ts b/desktop/src/main/index.ts new file mode 100644 index 0000000..b493f77 --- /dev/null +++ b/desktop/src/main/index.ts @@ -0,0 +1,301 @@ +import { app, BrowserWindow, ipcMain, Menu, shell, type WebContents } from 'electron' +import { readFileSync } from 'node:fs' +import { join, relative, isAbsolute } from 'node:path' +import { APP_ROOT, runtimePython } from './runtime-env' +import { Channel, type RuntimeProvider } from './channel' +import { pickDataFiles, pickProblemFile } from './files' +import { + activeProviderId, + apiKeyFor, + clearProviderKey, + publicProviders, + saveProvider +} from './settings' +import type { + ProviderList, + ProviderView, + RunEvent, + RunInput, + RuntimeStatus, + SaveProviderInput +} from '../shared/api' + +// 开发时 electron-vite 会注入 ELECTRON_RENDERER_URL;打包后走 out/renderer/index.html。 +const DEV_SERVER_URL = process.env['ELECTRON_RENDERER_URL'] +const RUNS_ROOT = join(app.getPath('userData'), 'runs') +const channel = new Channel(APP_ROOT, runtimePython(), app.getPath('userData')) +const activeStreams = new Map() + +channel.onStatus((status: RuntimeStatus) => { + for (const win of BrowserWindow.getAllWindows()) { + if (!win.isDestroyed()) win.webContents.send('runtime:status', status) + } +}) + +async function providerViews(): Promise { + const { providers } = await channel.providers() + const saved = publicProviders() + const views: ProviderView[] = providers.map((row: RuntimeProvider) => { + const stored = saved[row.id] + const models = row.models ?? [] + return { + id: row.id, + display: row.display, + models, + model: stored?.model || row.model || models[0] || '', + baseUrl: stored?.baseUrl || row.base_url || '', + requiresKey: Boolean(row.requires_key), + custom: Boolean(row.custom), + configured: row.id === 'fake' || Boolean(stored?.configured), + note: row.note + } + }) + const preferred = activeProviderId() + const active = + views.find((view) => view.id === preferred) ?? + views.find((view) => view.configured) ?? + views[0] + return { ok: true, providers: views, activeProvider: active?.id ?? '' } +} + +function parseSaveInput(raw: unknown): SaveProviderInput { + if (!raw || typeof raw !== 'object') throw new Error('设置格式不对') + const obj = raw as Record + const id = typeof obj.id === 'string' ? obj.id.trim() : '' + const model = typeof obj.model === 'string' ? obj.model.trim() : '' + if (!id) throw new Error('缺少服务商') + if (!model) throw new Error('缺少模型名') + return { + id, + model, + apiKey: typeof obj.apiKey === 'string' ? obj.apiKey : undefined, + baseUrl: typeof obj.baseUrl === 'string' ? obj.baseUrl : undefined + } +} + +function parseRunInput(raw: unknown): RunInput { + if (!raw || typeof raw !== 'object') throw new Error('运行请求格式不对') + const obj = raw as Record + const problem = typeof obj.problem === 'string' ? obj.problem.trim() : '' + const providerId = typeof obj.providerId === 'string' ? obj.providerId.trim() : '' + if (problem.length < 10) throw new Error('题面至少写一句完整的题目描述') + if (problem.length > 200_000) throw new Error('题面过长') + if (!providerId) throw new Error('没有选择服务商') + const dataPaths = Array.isArray(obj.dataPaths) + ? obj.dataPaths.filter((item): item is string => typeof item === 'string' && Boolean(item)).slice(0, 10) + : [] + return { + problem, + dataPaths, + providerId, + model: typeof obj.model === 'string' ? obj.model.trim() : '' + } +} + +function insideRuns(path: string): boolean { + if (!isAbsolute(path)) return false + const rel = relative(RUNS_ROOT, path) + return Boolean(rel) && !rel.startsWith('..') && !isAbsolute(rel) +} + +function attachStream(runId: string, sender: WebContents): void { + const controller = new AbortController() + activeStreams.set(runId, controller) + void channel + .stream( + runId, + (event: RunEvent) => { + if (!sender.isDestroyed()) sender.send('run:event', event) + }, + controller.signal + ) + .catch((err: unknown) => { + if (controller.signal.aborted || sender.isDestroyed()) return + const message = err instanceof Error ? err.message : String(err) + sender.send('run:event', { + runId, + id: '0', + event: 'done', + data: { ok: false, error: message, outputs: {} } + }) + }) + .finally(() => activeStreams.delete(runId)) +} + +function appVersion(): string { + try { + return readFileSync(join(APP_ROOT, 'VERSION'), 'utf8').trim() || app.getVersion() + } catch { + return app.getVersion() + } +} + +ipcMain.handle('app:meta', () => ({ + version: appVersion(), + platform: process.platform, + electron: process.versions.electron, + chrome: process.versions.chrome +})) + +ipcMain.handle('runtime:status', () => channel.current()) + +ipcMain.handle('runtime:restart', async () => { + await channel.restart() + return providerViews() +}) + +ipcMain.handle('providers:list', () => providerViews()) + +ipcMain.handle('providers:save', async (_event, raw: unknown) => { + saveProvider(parseSaveInput(raw)) + return providerViews() +}) + +ipcMain.handle('providers:clear', async (_event, raw: unknown) => { + const id = typeof raw === 'string' ? raw : '' + if (!id) throw new Error('缺少服务商') + clearProviderKey(id) + return providerViews() +}) + +ipcMain.handle('files:pick-problem', (event) => pickProblemFile(BrowserWindow.fromWebContents(event.sender))) + +ipcMain.handle('files:pick-data', (event) => pickDataFiles(BrowserWindow.fromWebContents(event.sender))) + +ipcMain.handle('run:start', async (event, raw: unknown) => { + const input = parseRunInput(raw) + const list = await providerViews() + const view = list.providers.find((item) => item.id === input.providerId) + if (!view) throw new Error('未知服务商') + if (view.custom && !view.baseUrl) throw new Error('自定义端点还没填 base URL') + const apiKey = view.id === 'fake' ? '' : apiKeyFor(view.id) ?? '' + if (view.requiresKey && !apiKey) throw new Error('还没配置 API Key') + const result = await channel.startRun({ + problem: input.problem, + dataPaths: input.dataPaths, + provider: { + id: view.id, + model: input.model || view.model, + baseUrl: view.custom ? view.baseUrl : undefined, + apiKey + } + }) + attachStream(result.runId, event.sender) + return result +}) + +ipcMain.handle('run:cancel', async (_event, raw: unknown) => { + const runId = typeof raw === 'string' ? raw : '' + if (!runId) throw new Error('缺少运行 id') + await channel.cancelRun(runId) + // provider 正在等下一块数据时 cancel 只能等它醒来;2 秒后断开本地流兜底。 + const controller = activeStreams.get(runId) + if (controller) setTimeout(() => controller.abort(), 2000) + return { ok: true } +}) + +ipcMain.handle('run:summary', (_event, raw: unknown) => { + const id = typeof raw === 'string' ? raw : '' + if (!id) return null + const path = join(RUNS_ROOT, id, 'summary.json') + if (!insideRuns(path)) return null + try { + return JSON.parse(readFileSync(path, 'utf8')) as unknown + } catch { + return null + } +}) + +ipcMain.handle('artifact:open', async (_event, raw: unknown) => { + const path = typeof raw === 'string' ? raw : '' + if (!insideRuns(path)) throw new Error('只能打开本次运行的产物') + const error = await shell.openPath(path) + if (error) throw new Error(error) + return { ok: true } +}) + +ipcMain.handle('artifact:reveal', (_event, raw: unknown) => { + const path = typeof raw === 'string' ? raw : '' + if (!insideRuns(path)) throw new Error('只能定位本次运行的产物') + shell.showItemInFolder(path) + return { ok: true } +}) + +ipcMain.handle('artifact:image', (_event, raw: unknown) => { + const path = typeof raw === 'string' ? raw : '' + if (!insideRuns(path)) return null + try { + const bytes = readFileSync(path) + if (!bytes.length || bytes.length > 12 * 1024 * 1024) return null + return `data:image/png;base64,${bytes.toString('base64')}` + } catch { + return null + } +}) + +function createWindow(): BrowserWindow { + const win = new BrowserWindow({ + width: 1280, + height: 860, + useContentSize: true, + minWidth: 980, + minHeight: 640, + show: false, + backgroundColor: '#ffffff', + title: 'MathModel Studio', + webPreferences: { + preload: join(__dirname, '../preload/index.js'), + contextIsolation: true, + nodeIntegration: false, + sandbox: true, + webSecurity: true + } + }) + + win.once('ready-to-show', () => { + win.setContentSize(1280, 860) + win.show() + }) + + if (DEV_SERVER_URL && !app.isPackaged) { + void win.loadURL(DEV_SERVER_URL) + } else { + void win.loadFile(join(__dirname, '../renderer/index.html')) + } + + return win +} + +// 渲染层拿不到 Node 能力,也不该拿到:外部链接一律走 shell.openExternal,且只放 https。 +app.on('web-contents-created', (_event, contents) => { + contents.setWindowOpenHandler(({ url }) => { + if (url.startsWith('https://')) void shell.openExternal(url) + return { action: 'deny' } + }) + contents.on('will-navigate', (event, url) => { + const allowedOrigin = DEV_SERVER_URL ? new URL(DEV_SERVER_URL).origin : 'file:' + const origin = url.startsWith('file://') ? 'file:' : new URL(url).origin + if (origin !== allowedOrigin) event.preventDefault() + }) +}) + +app.whenReady().then(() => { + if (process.platform !== 'darwin') Menu.setApplicationMenu(null) + void channel.start().catch((err: unknown) => { + console.error('[runtime] 启动失败:', err instanceof Error ? err.message : err) + }) + createWindow() + app.on('activate', () => { + if (BrowserWindow.getAllWindows().length === 0) createWindow() + }) +}) + +app.on('will-quit', () => { + for (const controller of activeStreams.values()) controller.abort() + activeStreams.clear() + channel.stop() +}) + +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') app.quit() +}) diff --git a/src/main/runtime-env.ts b/desktop/src/main/runtime-env.ts similarity index 71% rename from src/main/runtime-env.ts rename to desktop/src/main/runtime-env.ts index dea2d3e..3cd2623 100644 --- a/src/main/runtime-env.ts +++ b/desktop/src/main/runtime-env.ts @@ -1,10 +1,11 @@ import { app } from 'electron' import { join } from 'node:path' -// 开发时资源在仓库根;打包后 runtime/skills/schemas/python 放在 resources/ 下—— +// 开发时资源在仓库根(modeling/、gateway/、vendor/);打包后它们放在 resources/ 下—— // app.asar 里的文件 Python 读不到,所以 ROOT 必须指向 resourcesPath 而不是 __dirname 往上找。 export const APP_ROOT = - process.env['MMS_HOME'] || (app.isPackaged ? process.resourcesPath : join(__dirname, '..', '..')) + process.env['MMS_HOME'] || + (app.isPackaged ? process.resourcesPath : join(__dirname, '..', '..', '..')) export function runtimePython(): string { const override = process.env['MMS_PYTHON'] diff --git a/src/main/settings.ts b/desktop/src/main/settings.ts similarity index 51% rename from src/main/settings.ts rename to desktop/src/main/settings.ts index c58a98d..51b3a15 100644 --- a/src/main/settings.ts +++ b/desktop/src/main/settings.ts @@ -1,25 +1,18 @@ import { app, safeStorage } from 'electron' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' -import type { ThinkingDepth } from '../shared/api' +import type { SaveProviderInput } from '../shared/api' -// 磁盘上只有 safeStorage 的密文。safeStorage 不可用时**拒绝保存**, -// 不退回明文——这条比"让用户先存上"重要。 +// 磁盘上只有 safeStorage 的密文。safeStorage 不可用时拒绝保存,不退回明文。 interface StoredProvider { model?: string baseUrl?: string key?: string - context?: number - depth?: ThinkingDepth - sendThinking?: boolean } interface SettingsFile { version: 1 activeProvider?: string - workspace?: string - /** 按赛题分项目文件夹;缺省视为开启 */ - projectFolders?: boolean providers: Record } @@ -33,7 +26,7 @@ function defaults(): SettingsFile { return { version: 1, providers: {} } } -export function loadSettings(): SettingsFile { +function loadSettings(): SettingsFile { if (cache) return cache const path = filePath() if (!existsSync(path)) { @@ -43,12 +36,12 @@ export function loadSettings(): SettingsFile { try { const raw = JSON.parse(readFileSync(path, 'utf8')) as Partial const providers = - raw.providers && typeof raw.providers === 'object' ? (raw.providers as Record) : {} + raw.providers && typeof raw.providers === 'object' + ? (raw.providers as Record) + : {} cache = { version: 1, activeProvider: typeof raw.activeProvider === 'string' ? raw.activeProvider : undefined, - workspace: typeof raw.workspace === 'string' && raw.workspace ? raw.workspace : undefined, - projectFolders: typeof raw.projectFolders === 'boolean' ? raw.projectFolders : undefined, providers } } catch { @@ -68,24 +61,13 @@ export interface PublicProvider { configured: boolean model?: string baseUrl?: string - context?: number - depth?: ThinkingDepth - sendThinking?: boolean } /** 只给渲染层展示用的合并视图,不含密文。 */ export function publicProviders(): Record { - const file = loadSettings() const out: Record = {} - for (const [id, item] of Object.entries(file.providers)) { - out[id] = { - configured: Boolean(item.key), - model: item.model, - baseUrl: item.baseUrl, - context: item.context, - depth: item.depth, - sendThinking: item.sendThinking - } + for (const [id, item] of Object.entries(loadSettings().providers)) { + out[id] = { configured: Boolean(item.key), model: item.model, baseUrl: item.baseUrl } } return out } @@ -94,37 +76,14 @@ export function activeProviderId(): string | undefined { return loadSettings().activeProvider } -export interface SaveProviderInput { - id: string - model: string - apiKey?: string - baseUrl?: string - contextTokens?: number - thinkingDepth?: ThinkingDepth - sendThinking?: boolean -} - -const CONTEXTS = new Set([200_000, 400_000, 1_000_000]) -const DEPTHS = new Set(['medium', 'high', 'max']) - export function saveProvider(input: SaveProviderInput): void { const id = String(input.id || '').trim() const model = String(input.model || '').trim() if (!id) throw new Error('缺少服务商标识') if (!model) throw new Error('缺少模型名') - if (input.contextTokens !== undefined && !CONTEXTS.has(input.contextTokens)) { - throw new Error('上下文预算只能是 200k / 400k / 1m') - } - if (input.thinkingDepth !== undefined && !DEPTHS.has(input.thinkingDepth)) { - throw new Error('思维深度只能是中 / 高 / 最大') - } const file = loadSettings() - const prev = file.providers[id] ?? {} - const next: StoredProvider = { ...prev, model } + const next: StoredProvider = { ...file.providers[id], model } if (typeof input.baseUrl === 'string') next.baseUrl = input.baseUrl.trim() - if (input.contextTokens !== undefined) next.context = input.contextTokens - if (input.thinkingDepth !== undefined) next.depth = input.thinkingDepth - if (typeof input.sendThinking === 'boolean') next.sendThinking = input.sendThinking const apiKey = String(input.apiKey || '').trim() if (apiKey) { if (!safeStorage.isEncryptionAvailable()) { @@ -132,11 +91,7 @@ export function saveProvider(input: SaveProviderInput): void { } next.key = safeStorage.encryptString(apiKey).toString('base64') } - persist({ - ...file, - activeProvider: id, - providers: { ...file.providers, [id]: next } - }) + persist({ ...file, activeProvider: id, providers: { ...file.providers, [id]: next } }) } export function clearProviderKey(id: string): void { @@ -160,25 +115,3 @@ export function apiKeyFor(id: string): string | null { return null } } - -/** 用户自选的工作区目录;未设置时用桌面的「赛题」。 */ -export function savedWorkspace(): string | undefined { - return loadSettings().workspace -} - -export function saveWorkspace(path: string | undefined): void { - const file = loadSettings() - const next: SettingsFile = { ...file } - if (path) next.workspace = path - else delete next.workspace - persist(next) -} - -/** 按赛题分项目文件夹的总开关;未写过时默认开启。 */ -export function projectFoldersEnabled(): boolean { - return loadSettings().projectFolders !== false -} - -export function setProjectFolders(enabled: boolean): void { - persist({ ...loadSettings(), projectFolders: enabled }) -} diff --git a/src/preload/index.d.ts b/desktop/src/preload/index.d.ts similarity index 100% rename from src/preload/index.d.ts rename to desktop/src/preload/index.d.ts diff --git a/desktop/src/preload/index.ts b/desktop/src/preload/index.ts new file mode 100644 index 0000000..b5e25df --- /dev/null +++ b/desktop/src/preload/index.ts @@ -0,0 +1,60 @@ +import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron' +import type { + ProblemFile, + ProviderList, + RunEvent, + RunInput, + RunStartResult, + RunSummary, + RuntimeStatus, + SaveProviderInput, + StudioMeta +} from '../shared/api' + +// 渲染层只能看到这几条窄接口:主进程的 runtime 端口、token 与 API Key 都不经过这里。 +const studioApi = { + meta: (): Promise => ipcRenderer.invoke('app:meta'), + + runtime: { + status: (): Promise => ipcRenderer.invoke('runtime:status'), + restart: (): Promise => ipcRenderer.invoke('runtime:restart'), + onStatus: (cb: (status: RuntimeStatus) => void): (() => void) => { + const handler = (_event: IpcRendererEvent, status: RuntimeStatus): void => cb(status) + ipcRenderer.on('runtime:status', handler) + return () => ipcRenderer.removeListener('runtime:status', handler) + } + }, + + providers: { + list: (): Promise => ipcRenderer.invoke('providers:list'), + save: (payload: SaveProviderInput): Promise => + ipcRenderer.invoke('providers:save', payload), + clear: (id: string): Promise => ipcRenderer.invoke('providers:clear', id) + }, + + files: { + pickProblem: (): Promise => ipcRenderer.invoke('files:pick-problem'), + pickData: (): Promise => ipcRenderer.invoke('files:pick-data') + }, + + run: { + start: (input: RunInput): Promise => ipcRenderer.invoke('run:start', input), + cancel: (runId: string): Promise<{ ok: true }> => ipcRenderer.invoke('run:cancel', runId), + summary: (runId: string): Promise => ipcRenderer.invoke('run:summary', runId), + onEvent: (cb: (event: RunEvent) => void): (() => void) => { + const handler = (_event: IpcRendererEvent, payload: RunEvent): void => cb(payload) + ipcRenderer.on('run:event', handler) + return () => ipcRenderer.removeListener('run:event', handler) + } + }, + + artifacts: { + open: (path: string): Promise<{ ok: true }> => ipcRenderer.invoke('artifact:open', path), + reveal: (path: string): Promise<{ ok: true }> => ipcRenderer.invoke('artifact:reveal', path), + image: (path: string): Promise => ipcRenderer.invoke('artifact:image', path) + } +} + +contextBridge.exposeInMainWorld('studio', studioApi) + +export type StudioApi = typeof studioApi diff --git a/src/renderer/index.html b/desktop/src/renderer/index.html similarity index 93% rename from src/renderer/index.html rename to desktop/src/renderer/index.html index 02b30eb..a422ae7 100644 --- a/src/renderer/index.html +++ b/desktop/src/renderer/index.html @@ -7,7 +7,7 @@ content="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ws://127.0.0.1:* ws://localhost:*" /> - mathmodel-studio + MathModel Studio
diff --git a/desktop/src/renderer/src/App.tsx b/desktop/src/renderer/src/App.tsx new file mode 100644 index 0000000..9e62911 --- /dev/null +++ b/desktop/src/renderer/src/App.tsx @@ -0,0 +1,288 @@ +import { useEffect, useRef, useState, type JSX } from 'react' +import type { + DoneData, + LogData, + PhaseData, + ProviderList, + RunSummary, + RuntimeStatus +} from '../../shared/api' +import Conversation from './components/Conversation' +import { initialPhases, type LiveRun } from './components/RunView' +import SettingsDialog from './components/SettingsDialog' +import Sidebar from './components/Sidebar' +import Welcome from './components/Welcome' +import { + conversationTitle, + loadUi, + saveUi, + uid, + type Conversation as Conv, + type UiState +} from './lib/store' + +function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err) +} + +export default function App(): JSX.Element { + const [ui, setUi] = useState(loadUi) + const [runtime, setRuntime] = useState({ state: 'starting' }) + const [providers, setProviders] = useState(null) + const [settingsOpen, setSettingsOpen] = useState(false) + const [live, setLive] = useState>({}) + const uiRef = useRef(ui) + uiRef.current = ui + + const activeWorkspace = ui.workspaces.find((item) => item.id === ui.activeWorkspaceId) ?? ui.workspaces[0] + const activeConversation = + activeWorkspace?.conversations.find((item) => item.id === ui.activeConversationId) ?? null + const activeProvider = providers?.providers.find((item) => item.id === providers.activeProvider) ?? null + + useEffect(() => saveUi(ui), [ui]) + + useEffect(() => { + void window.studio.runtime.status().then(setRuntime) + return window.studio.runtime.onStatus(setRuntime) + }, []) + + useEffect(() => { + if (runtime.state !== 'ready') return + void window.studio.providers.list().then(setProviders).catch(() => undefined) + }, [runtime.state]) + + function patchConversation(convId: string, patch: Partial): void { + setUi((prev) => ({ + ...prev, + workspaces: prev.workspaces.map((workspace) => ({ + ...workspace, + conversations: workspace.conversations.map((item) => + item.id === convId ? { ...item, ...patch } : item + ) + })) + })) + } + + useEffect(() => { + return window.studio.run.onEvent((payload) => { + const runId = payload.runId + let convId: string | null = null + for (const workspace of uiRef.current.workspaces) { + const found = workspace.conversations.find((item) => item.runId === runId) + if (found) { + convId = found.id + break + } + } + if (!convId) return + + if (payload.event === 'phase') { + const data = payload.data as unknown as PhaseData + setLive((prev) => { + const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null } + return { + ...prev, + [runId]: { + ...run, + phases: { ...run.phases, [data.id]: { label: data.label, status: data.status, detail: data.detail } } + } + } + }) + } else if (payload.event === 'log') { + const data = payload.data as unknown as LogData + setLive((prev) => { + const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null } + return { ...prev, [runId]: { ...run, logs: [...run.logs.slice(-400), data] } } + }) + } else if (payload.event === 'progress') { + const data = payload.data as unknown as { stage?: string; chars?: number } + if (!data.stage) return + setLive((prev) => { + const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null } + return { ...prev, [runId]: { ...run, progress: `${data.stage} · ${data.chars ?? 0} 字` } } + }) + } else if (payload.event === 'done') { + const data = payload.data as unknown as DoneData + setLive((prev) => { + const run = prev[runId] ?? { phases: initialPhases(), logs: [], progress: '', done: null } + return { ...prev, [runId]: { ...run, progress: '', done: data } } + }) + patchConversation(convId, { + status: data.ok ? 'done' : 'error', + outputs: data.outputs, + picked: data.picked, + sources: data.sources, + seconds: data.seconds, + error: data.error + }) + } + }) + }, []) + + useEffect(() => { + const conversation = activeConversation + if (!conversation?.runId || conversation.outputs) return + let alive = true + void window.studio.run.summary(conversation.runId).then((summary: RunSummary | null) => { + if (!alive || !summary) return + patchConversation(conversation.id, { + status: summary.ok ? 'done' : 'error', + outputs: summary.outputs, + picked: summary.picked?.name, + sources: summary.sources, + seconds: summary.seconds, + error: summary.error + }) + }) + return () => { + alive = false + } + }, [ui.activeConversationId]) + + function newConversation(workspaceId?: string, problem = ''): string { + const conversation: Conv = { + id: uid('c'), + title: problem ? conversationTitle(problem) : '新对话', + problem, + dataPaths: [], + status: 'idle', + createdAt: Date.now() + } + setUi((prev) => { + const target = workspaceId ?? prev.activeWorkspaceId + return { + ...prev, + activeWorkspaceId: target, + workspaces: prev.workspaces.map((workspace) => + workspace.id === target + ? { ...workspace, conversations: [conversation, ...workspace.conversations] } + : workspace + ), + activeConversationId: conversation.id + } + }) + return conversation.id + } + + function selectConversation(id: string): void { + const owner = ui.workspaces.find((workspace) => workspace.conversations.some((item) => item.id === id)) + setUi((prev) => ({ + ...prev, + activeWorkspaceId: owner?.id ?? prev.activeWorkspaceId, + activeConversationId: id + })) + } + + function newWorkspace(): void { + const workspace = { id: uid('w'), name: `工作区 ${ui.workspaces.length + 1}`, conversations: [] } + setUi((prev) => ({ + ...prev, + workspaces: [...prev.workspaces, workspace], + activeWorkspaceId: workspace.id, + activeConversationId: null + })) + } + + function selectWorkspace(id: string): void { + const workspace = ui.workspaces.find((item) => item.id === id) + setUi((prev) => ({ + ...prev, + activeWorkspaceId: id, + activeConversationId: workspace?.conversations[0]?.id ?? null + })) + } + + function deleteConversation(id: string): void { + setUi((prev) => ({ + ...prev, + workspaces: prev.workspaces.map((workspace) => ({ + ...workspace, + conversations: workspace.conversations.filter((item) => item.id !== id) + })), + activeConversationId: prev.activeConversationId === id ? null : prev.activeConversationId + })) + } + + async function send(convId: string, problem: string, dataPaths: string[]): Promise { + if (!activeProvider) return + try { + const result = await window.studio.run.start({ + problem, + dataPaths, + providerId: activeProvider.id, + model: activeProvider.model + }) + patchConversation(convId, { + problem, + dataPaths, + title: conversationTitle(problem), + status: 'running', + runId: result.runId, + error: undefined + }) + setLive((prev) => ({ + ...prev, + [result.runId]: { phases: initialPhases(), logs: [], progress: '', done: null } + })) + } catch (err) { + patchConversation(convId, { status: 'idle', error: errorText(err) }) + } + } + + async function cancel(): Promise { + if (activeConversation?.runId) { + await window.studio.run.cancel(activeConversation.runId).catch(() => undefined) + } + } + + async function openArtifact(path?: string): Promise { + if (path) await window.studio.artifacts.open(path).catch(() => undefined) + } + + async function revealArtifact(path?: string): Promise { + if (path) await window.studio.artifacts.reveal(path).catch(() => undefined) + } + + return ( +
+ newConversation(workspaceId)} + onDeleteConversation={deleteConversation} + onOpenSettings={() => setSettingsOpen(true)} + /> +
+ {activeConversation ? ( + void send(activeConversation.id, problem, dataPaths)} + onCancel={() => void cancel()} + onOpen={(path) => void openArtifact(path)} + onReveal={(path) => void revealArtifact(path)} + onNewConversation={() => newConversation()} + /> + ) : ( + newConversation()} + onExample={(problem) => newConversation(undefined, problem)} + /> + )} +
+ setSettingsOpen(false)} + onChanged={setProviders} + /> +
+ ) +} diff --git a/desktop/src/renderer/src/components/Conversation.tsx b/desktop/src/renderer/src/components/Conversation.tsx new file mode 100644 index 0000000..e75b096 --- /dev/null +++ b/desktop/src/renderer/src/components/Conversation.tsx @@ -0,0 +1,132 @@ +import { useEffect, useState, type JSX } from 'react' +import type { Conversation } from '../lib/store' +import RunView, { type LiveRun } from './RunView' + +interface Props { + conversation: Conversation + live?: LiveRun + providerLabel: string + runtimeReady: boolean + onSend: (problem: string, dataPaths: string[]) => void + onCancel: () => void + onOpen: (path?: string) => void + onReveal: (path?: string) => void + onNewConversation: () => void +} + +function baseName(path: string): string { + return path.split(/[\\/]/).pop() || path +} + +export default function Conversation(props: Props): JSX.Element { + const { conversation } = props + const [problem, setProblem] = useState(conversation.problem) + const [dataPaths, setDataPaths] = useState(conversation.dataPaths) + const [error, setError] = useState('') + + useEffect(() => { + setProblem(conversation.problem) + setDataPaths(conversation.dataPaths) + setError(conversation.error ?? '') + }, [conversation.id, conversation.error]) + + async function pickProblem(): Promise { + try { + const file = await window.studio.files.pickProblem() + if (file) setProblem(file.text) + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + } + } + + async function pickData(): Promise { + try { + const paths = await window.studio.files.pickData() + if (paths.length) setDataPaths(paths.slice(0, 1)) + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + } + } + + function send(): void { + if (problem.trim().length < 10) { + setError('先把题目写完整(至少一句描述)。') + return + } + setError('') + props.onSend(problem.trim(), dataPaths) + } + + const idle = conversation.status === 'idle' + const running = conversation.status === 'running' + + return ( +
+
+ {conversation.problem && ( +
+
{conversation.problem}
+ {conversation.dataPaths.length > 0 && ( +
+ {conversation.dataPaths.map((path) => ( + {baseName(path)} + ))} +
+ )} +
+ )} + {(conversation.runId || props.live || conversation.status !== 'idle') && ( +
+ +
+ )} + {idle && !conversation.problem && ( +

写下赛题开始一次建模;一个对话对应一次完整运行。

+ )} +
+ + {idle || running ? ( +
+