Просмотр исходного кода

chore(app): merge origin/qjh into the research workbench

Integrate upstream task center, report reader, recovery and desktop
changes while keeping the compact activity log, results gating and
honest download feedback from the local UI review.
241880436@seecoder.cn 5 дней назад
Родитель
Сommit
abfcdadde3
52 измененных файлов с 4805 добавлено и 1075 удалено
  1. 108 0
      PAAS_OPTIMIZATION_PLAN.zh-CN.md
  2. 2 1
      bun.lock
  3. 145 15
      packages/app/e2e/paas/fixture.tsx
  4. 110 0
      packages/app/e2e/paas/polish.spec.ts
  5. 250 0
      packages/app/e2e/paas/recovery.spec.ts
  6. 167 0
      packages/app/e2e/paas/ux.spec.ts
  7. 1 36
      packages/app/e2e/paas/workbench.spec.ts
  8. 2 0
      packages/app/src/paas.test.ts
  9. 17 5
      packages/app/src/paas.ts
  10. 19 0
      packages/app/src/pages/paas/README.md
  11. 101 19
      packages/app/src/pages/paas/agent-edit.tsx
  12. 155 0
      packages/app/src/pages/paas/chat-cache.test.ts
  13. 182 0
      packages/app/src/pages/paas/chat-cache.ts
  14. 710 0
      packages/app/src/pages/paas/chat-state.ts
  15. 738 587
      packages/app/src/pages/paas/chat.tsx
  16. 20 24
      packages/app/src/pages/paas/controller.ts
  17. 179 146
      packages/app/src/pages/paas/index.tsx
  18. 57 0
      packages/app/src/pages/paas/issue.tsx
  19. 0 20
      packages/app/src/pages/paas/markdown.tsx
  20. 158 0
      packages/app/src/pages/paas/materials.ts
  21. 453 72
      packages/app/src/pages/paas/paas.css
  22. 28 0
      packages/app/src/pages/paas/progress.test.ts
  23. 96 0
      packages/app/src/pages/paas/progress.tsx
  24. 129 0
      packages/app/src/pages/paas/report-reader.tsx
  25. 21 0
      packages/app/src/pages/paas/report.tsx
  26. 82 75
      packages/app/src/pages/paas/run-panel.tsx
  27. 301 0
      packages/app/src/pages/paas/tasks.tsx
  28. 29 7
      packages/desktop/README.md
  29. 3 2
      packages/desktop/package.json
  30. 37 5
      packages/desktop/scripts/native-smoke.cjs
  31. 98 5
      packages/desktop/src/main/ipc.ts
  32. 134 4
      packages/desktop/src/main/paas.test.ts
  33. 92 20
      packages/desktop/src/main/paas.ts
  34. 46 0
      packages/desktop/src/main/report-document.test.ts
  35. 97 0
      packages/desktop/src/main/report-document.ts
  36. 6 0
      packages/desktop/src/preload/index.ts
  37. 2 2
      packages/desktop/src/renderer/i18n/ar.ts
  38. 2 2
      packages/desktop/src/renderer/i18n/br.ts
  39. 2 2
      packages/desktop/src/renderer/i18n/bs.ts
  40. 2 2
      packages/desktop/src/renderer/i18n/da.ts
  41. 2 2
      packages/desktop/src/renderer/i18n/de.ts
  42. 2 2
      packages/desktop/src/renderer/i18n/en.ts
  43. 2 2
      packages/desktop/src/renderer/i18n/es.ts
  44. 2 2
      packages/desktop/src/renderer/i18n/fr.ts
  45. 2 2
      packages/desktop/src/renderer/i18n/ja.ts
  46. 2 2
      packages/desktop/src/renderer/i18n/ko.ts
  47. 2 2
      packages/desktop/src/renderer/i18n/no.ts
  48. 2 2
      packages/desktop/src/renderer/i18n/pl.ts
  49. 2 2
      packages/desktop/src/renderer/i18n/ru.ts
  50. 2 2
      packages/desktop/src/renderer/i18n/uk.ts
  51. 2 2
      packages/desktop/src/renderer/i18n/zh.ts
  52. 2 2
      packages/desktop/src/renderer/i18n/zht.ts

+ 108 - 0
PAAS_OPTIMIZATION_PLAN.zh-CN.md

@@ -90,3 +90,111 @@ bun run package:beta  # 正式签名安装包,需提供对应系统签名、
 - 上述原生验收使用合成 HTTP 平台接口、不调用模型,并替换系统文件对话框的选择结果;真实文件读写和传输未替换。测试脚本为 `packages/desktop/scripts/native-smoke.cjs`,用法:`node scripts/native-smoke.cjs '<应用可执行文件路径>'`。该脚本会启动独立测试实例并在完成后关闭,不应指向已有生产实例。
 - 回归覆盖打包身份配置、响应式数据跨进程克隆、传输、连接存储与初始化;代理克隆测试用 `bun --conditions=browser test src/renderer/paas-bridge.test.ts` 运行,避免 SSR store 隐藏真实代理问题。
 - 当前产物是 macOS Apple Silicon 未签名内测版。网络与打包阻塞已解决;正式公开发行仍需团队签名、公证与真实平台任务验收。未推送代码或发布下载资产,未覆盖已有安装与配置。
+
+## Desktop 交互完整性修复:0.1.0-beta.2(2026-11-28)
+
+本轮针对从连接、提交、等待、反馈到交付的完整使用过程修复,不增加科研内容门禁。
+
+- **后台任务与会话切换**:不同会话可独立执行,同一会话仍避免重复提交。执行中可切换会话、开始其他研究并编辑下一轮草稿。当前 PaaS 没有运行中追加指令接口,因此草稿不会自动注入已有任务,也不会自动发送;当前轮反馈仍通过审批卡片提交。
+- **草稿和材料恢复**:按平台连接身份与窗口保存会话、当前选择、草稿及已上传文件引用,刷新或重新打开后恢复。连接身份采用主进程生成的摘要,不在草稿缓存中写入访问凭证。断线不会自动重发任务;未确认的提交可核对平台任务后恢复原输入,已有新草稿和材料会合并保留。
+- **材料上传**:支持拖放与原生文件选择,逐文件显示传输进度,传输完毕后等待服务器确认。某份材料失败不丢弃其余成功文件,可单独重试或移除。原生路径保留在主进程,通过当前连接绑定的选择编号访问;遵循平台上传额度。
+- **阅读与成果**:报告支持 Markdown、表格、公式和文献链接,提供复制;执行记录默认折叠,历史任务详情按需加载。阅读上方历史时不强制滚到底部,显示“有新进展”入口。完成后自动读取工作文件,文件列表失败不阻断报告阅读。
+- **首次使用与进度**:明确平台地址和凭证来源,默认选中已有智能体,提供只填草稿、不自动执行的研究示例。进度展示真实状态、工具事件、已用时间及最近更新时间,不生成虚假完成百分比。
+- **任务中心与审批**:自动汇总各智能体最近任务,进行中任务优先显示,支持搜索与筛选;后台状态变化提供可跳转提醒。审批卡片展示阶段、请求和成果,原始记录折叠;待审批字段能正确覆盖临时“运行中”状态,终态仍保持优先级。旧响应不得覆盖已结束任务。
+
+### 本轮验证
+
+- App 与 Desktop 类型检查通过,差异格式检查通过。
+- App 数据测试 5 项、桌面原生传输与响应式桥接测试 15 项通过。桥接测试带 `--conditions=browser`,覆盖实际响应式代理序列化。
+- 工作台界面场景共 10 项通过:原有 5 项与新增 5 项。最终全量回归中 9 项通过,通知场景因测试选择器同时匹配“任务通知”和“关闭任务通知”而失败;改为精确匹配后,该场景单独复验通过。覆盖并行会话、草稿与附件恢复、账号隔离、逐文件重试、拖放、未知提交恢复、任务跳转、公式与表格、历史阅读不跳动及后台审批提醒。
+- 修改前后各 5 项生产会话基准通过。四项流式场景改前耗时 48.87–51.73 秒,改后 49.65–51.53 秒;消息行和 Markdown 均无替换,底部漂移次数均为 0。用于回归检查,不据此宣称性能提升。
+- `package:beta --unsigned --mirror` 成功生成 macOS Apple Silicon DMG(约 148.4 MiB)与 ZIP(约 147.7 MiB)。版本为 `0.1.0-beta.2`。
+- 构建目录中的打包应用,以及从只读 DMG 复制到临时 Applications 目录的应用,均通过原生验收:自动连接、实际文件字节上传、刷新后草稿和附件恢复、单次提交、结果显示和成果文件字节落盘。DMG 校验、ZIP 完整性检查通过。
+- 浏览器和原生验收使用合成平台响应,不调用模型;原生测试替换文件对话框的选择结果,保留实际 Electron/preload/IPC、文件读写和传输。未覆盖已有用户安装和配置,未重启现有服务。
+
+安装包位于 `packages/desktop/dist/`,校验和位于 `SHA256SUMS-beta.2.txt`,本轮原始日志与性能数据保存在 `validation-beta.2/`。当前是未签名内测产物,不等同于完成签名、公证和真实模型科研验收的正式公开版本。本轮代码尚未提交、推送或发布发行资产。
+
+
+## Desktop 会话恢复与成果使用:0.1.0-beta.3(2026-11-28)
+
+本轮继续修复用户从打开历史、切换任务、处理断线到使用成果的操作链,不增加科研内容门禁。
+
+- **历史同步**:打开本机缓存会话时补齐平台最新任务与结果,保留草稿、材料及本机未确认提交。按任务编号合并,避免重复显示;同步期间的新状态不会被旧快照覆盖。
+- **切换防串页**:打开任务与会话采用同一导航序号。连续切换、另建会话或发送新任务后,较早的异步读取不能覆盖用户当前选择;任务中心可以定位对应历史成果。
+- **提交回执恢复**:每次提交携带稳定的 `Idempotency-Key`,回执中断后使用 PaaS 既有的按提交编号查询接口找回原任务。未查到不代表未创建,客户端不会因此自动重发;平台不支持查询时显示核对入口。后端无须改动。
+- **增量缓存**:会话索引、草稿元信息与单条消息分开保存。后台运行中的会话和当前会话恢复消息,其余历史在打开时加载;编辑草稿不重写报告。自动迁移旧版缓存,并保留账号、窗口隔离。
+- **成果使用**:报告可导出为 Markdown,保留原文、表格和公式;原生保存对话框选择位置后实际写入文件。报告和工作文件保存后均可打开保存位置。“基于此方案继续”只补入草稿,保留已有要求,不自动执行。
+- **会话整理**:支持按标题搜索、重命名、本机归档和取消归档。归档只整理本机列表,不停止任务,也不调用服务器归档接口。
+
+### 验证记录
+
+- 生产构建界面回归:17 项全部通过,包含历史增量合并、慢请求竞态、丢失回执恢复、归档恢复及报告继续研究等场景。
+- 缓存与平台数据测试:9 项通过,覆盖旧版迁移、延迟加载、增量保存、配额失败后重试及窗口与账号隔离。
+- 使用真实 PaaS 本地服务与持久化层的回执、幂等和权限契约测试:28 项通过;执行器使用合成任务,没有调用真实模型。
+- 本轮只读检查配置中的 PaaS,接口返回 HTTP 502。未重启现有服务,真实模型端到端科研验收暂未完成。
+
+- App、Desktop 类型检查及差异格式检查通过;桌面原生传输与响应式桥接测试 16 项通过。传输测试需要隔离本地监听端口;沙箱内因监听被禁止而失败,允许本地监听后全部通过。
+- 修改前后各 5 项生产会话性能基准通过。四项流式场景改前耗时 52.73–55.86 秒,改后 50.75–53.85 秒;消息行与 Markdown 均未替换。用于确认回归,不据单次样本宣称性能提升。PaaS 会话缓存另由缓存单元测试与界面回归覆盖。
+- 已生成 macOS Apple Silicon 的 `0.1.0-beta.3` DMG(约 148.4 MiB)与 ZIP(约 147.8 MiB),完整性校验通过。
+- 构建目录应用及从只读 DMG 复制到临时 Applications 的应用均通过原生验收,覆盖上传字节、附件与草稿恢复、单次执行、成果下载字节、Markdown 报告导出字节和基于方案继续编辑。使用实际 Electron/preload/IPC 和文件系统;平台响应合成、原生对话框选择结果替换,未调用真实模型,也未覆盖用户已有安装。
+
+原始日志、性能数据及原生截图位于 `packages/desktop/dist/validation-beta.3/`;校验和为 `packages/desktop/dist/SHA256SUMS-beta.3.txt`。当前为未签名内测包,真实服务验收、正式签名及公证仍未完成。代码尚未提交或推送。
+
+## Desktop 真实模型验收(2026-11-28)
+
+使用 beta.3 打包应用、独立真实 PaaS 与执行服务,以及用户授权的 DeepSeek Flash 凭证完成五次运行。文件选择/保存对话框的选择结果由脚本提供,其余 Electron、IPC、文件传输、平台接口和模型请求实际执行,没有模拟平台响应。
+
+- 通过:真实包创建、材料上传、草稿与附件刷新恢复、重命名和归档恢复、历史会话续研、运行中刷新找回、单次提交、报告导出及基于报告继续编辑。五次导出均与服务器原文一致。
+- PaaS 修复:结构化调用的思考与 JSON 协议配置;将失败原文与解析位置传给格式修复;技术中断和修订拒绝显示部分完成;部分关联错误定位到字段;生成视图隔离程序元数据;内置模板取消重复的单次字符门槛;科研配置保存不再使用普通智能体编译路径。
+- 独立真实审阅修复复验通过(9 秒),配置更新 API 返回 200 且回读正确。相关科研流程、模型适配、局部修复、配置保存和内置包回归通过,具体批次见验收报告,批次之间不重复累计测试数量。
+- **完整科研交付仍未通过**:最后一次运行使用 16 次模型调用、599,405 回执 Token,观察耗时约 151 秒,状态为 `partial / needs_revision`。长方案仍可能输出不允许的内部字段,整稿修复达到输出上限后截断,平台保留原稿并如实标注待修订。不能把桌面交互通过计为科研审阅通过。
+- 日常配置指向的 8010 服务没有监听,标准模型凭证未通过鉴权;本次临时环境没有改写日常配置。未重新打包、提交、推送或发布桌面版本,尚不建议据此正式发版。
+
+完整报告与五次运行数据:`/Users/shaoboyuan/seecoder/output/desktop-real-acceptance-20261128/验收报告.html`。最新修复源码位于 `integration/paas-branch-merge`;报告不包含密钥和用户数据库。
+
+## Desktop 科研交付修复复验(2026-11-29)
+
+继续修复后,同一历史科研会话通过真实 DeepSeek Flash 完成两轮检查。任务 `run_49f1618c2ec9` 最终为 `completed / needs_review`,停止原因 `task_deliverables_ready`;两轮 gate 均通过,非轮次或预算截停。这里的待审阅是交付后的人工复核要求,不代表技术执行失败,也不表示科学假设已证实。
+
+- 修复程序任务类型混入模型输出、局部补丁选择被过大的类型 schema 误导、列表单项无法修订,以及补丁格式错误直接退回整稿重写的问题。原始模型回复、失败尝试和既有研究内容均保留。
+- 对明确输出截断的审阅与研究子任务,在总预算内扩大修复输出空间;预算中断如实标为部分完成。
+- 仅规划任务中的待校准参数,必须绑定实际校准行动并明确校准前不作结论,才能作为前置待办交付;报告保留未验证标记。执行任务及未约束的阈值使用仍受检查。
+- 最终完整任务 25 次调用、1,107,976 回执 Token、观察约 233 秒。隔离验收实例预算从默认 100 万提高至 200 万 Token;不能据此宣称原 100 万预算已经足够,日常配置未修改。
+- 桌面恢复同一会话、运行中刷新与草稿恢复、单次提交、报告返回、逐字一致的 Markdown 导出,以及继续编辑不自动执行均通过。
+- 433 项相关回归通过。完整任务后,对无新增问题时的紧凑补丁路由另做真实阶段复验,两次补丁调用完成;该阶段复验不计为另一份完整任务。
+
+完整验收报告与本轮四次真实运行记录:`/Users/shaoboyuan/seecoder/output/desktop-repair-acceptance-20261129/验收报告.html`。先前失败记录未删除或改为成功。本次使用 beta.3 对接隔离后端,修复源码与验收记录随本次提交同步,未重新打包或正式发版;签名、公证与其他平台仍不在本次验收范围。
+
+## 用户交互完善:会话、任务与续研(2026-11-29)
+
+本轮从用户操作路径继续完善,不新增科研内容门禁,也不自动提高调用预算。
+
+- **会话恢复**:单条损坏消息不再使全部会话恢复为空;健康消息、其他会话、草稿与材料保留。导航索引损坏时,从同账号、同缓存来源的会话记录恢复索引;损坏原文保留,不按成功记录处理。
+- **状态稳定**:已确认结束的任务不接受迟到的“开始/运行中”事件回退,避免继续发送入口被误锁定。
+- **任务可达**:配套 PaaS 支持最近历史分页与补全较早活动任务,并保持租户、用户过滤。桌面提供“加载更早任务”,刷新保留已展开记录,较早活动任务结束后补查终态。旧版或远端服务暂不支持完整查询时,明确提示数量范围,不把有限记录冒充全部任务。
+- **研究设置**:从会话直接进入设置,保存或取消后返回原会话,保留草稿。科研智能体可填写计划 Token 预算、累计硬上限、最少/最多轮次与时间上限;保留后端已有的范围及交叉字段约束。目录折叠为高级选项,不在科研设置中展示无效的普通 ReAct 步数等选项;完整 JSON 仍可编辑。
+- **中断后继续**:部分成果可导出或“基于已有成果续研”,报告与新增要求一并填入草稿,不自动提交。设置变更用于后续任务,不声称能改变原任务的额度或恢复任意中断点。
+- **后台负担**:目录刷新从每 2 秒降为每 30 秒;隐藏窗口暂停会话及任务列表轮询,重新可见时立即同步。尚未合并所有状态订阅,不宣称已完成全局事件推送。
+
+验证:App/Desktop 类型检查、E2E 类型检查通过;缓存与平台数据测试 11 项通过,桌面原生传输测试 15 项通过,PaaS 本地服务相关测试 36 项与远端测试 3 项通过。页面交互测试包含 21 个不同场景;新增流程覆盖终态防回退、旧活动任务与历史分页、研究设置返回草稿、部分成果续研。界面验收使用真实组件和合成响应,PaaS 回归使用隔离数据库及测试服务,未调用真实模型。
+
+原始日志和截图:`/Users/shaoboyuan/seecoder/output/desktop-ux-20261129/`。本轮未修改日常服务配置,未重启已有应用/服务,未打包或发布安装包。
+
+性能复验:修改前后各 5 项生产版会话基准通过。四项流式完成耗时改前为 51.78—54.09 秒、改后为 49.60—52.23 秒;消息行和 Markdown 均未重建,底部滚动漂移均为 0。单轮测量仅用于回归检查,不据此宣称性能提升。最终设置页保存返回草稿流程另做复验通过。
+
+
+## Desktop beta.4:完整用户路径优化(2026-11-29)
+
+本轮覆盖首次上手、运行理解、报告交付、续研和异常处理,不增加科研内容门禁,不自动提高调用预算。
+
+- **上手与资源**:连接页面增加三步引导与部署/凭证说明;工作台给出开始研究入口。资源检查可跳过,新增用户主动触发的模型测试及模型/知识库设置入口。保存配置后清除旧检查结果。定时任务未接入,移出主导航。
+- **进展与问题**:直接投影服务的 research.science、usage 和阶段字段,展示已完成轮次、已回传/最终用量、下一步与待办。无回执时不显示虚构零消耗或百分比。错误按账户余额、研究预算、连接、权限、材料与审阅分类,连接和设置入口就地可达。
+- **阅读与交付**:报告独立阅读,与同会话此前报告进行文本差异对比;大差异有计算时间边界。原生导出 Markdown、真实 OOXML Word 及 PDF,支持中文标题、列表与表格。PDF 在禁用脚本、无外网资源的隔离窗口生成,Word 不嵌入可执行 HTML。公式保留原文,图片链接不自动下载。
+- **继续研究**:已有报告以可展开引用保留,输入框只编辑本轮要求;刷新、切换、重复点击不丢内容、不重复附加。确认发送时合并一次上下文,不自动新建任务;此功能不等于运行中热修改或任意检查点恢复。
+- **布局与配置**:缩小输入区、减少顶栏按钮、宽屏展示导航名称;科研设置提供用户主动选择的较充分配置,原值保持不变。统一桌面更新文案中的产品名称;版本升为 0.1.0-beta.4。
+
+本轮界面测试用真实组件与合成服务,25 项通过;桌面传输/连接存储/导出测试 21 项通过,缓存/进展测试 8 项通过。App、Desktop、E2E 类型检查通过。隔离原生应用验收包含材料上传、刷新恢复、文件保存、Markdown/Word/PDF 导出、报告引用及无重复执行。导出 Word 经 LibreOffice 实际渲染,PDF 经文本提取与视觉检查。未修改日常平台配置、未重启已有应用或服务、未使用真实模型密钥。
+
+验收证据:`/Users/shaoboyuan/seecoder/output/desktop-polish-20261129/`。测试应用为 macOS arm64 未签名 Beta;签名公证、自有更新源、Windows/Linux 实机验证仍是正式发布前置工作。后台服务仍需部署,Skill/MCP 完整管理与通用定时调度不在本轮伪装为已完成能力。
+
+最终复验:打包后的 beta.4 通过隔离原生验收,取消 Word 保存保留已有文件。修改前后生产版会话基准各 5 项通过;四项流式完成耗时分别为 53.65/53.16/53.18/57.36 秒与 52.78/51.54/52.93/55.89 秒,消息行与 Markdown 均未重建,底部滚动漂移均为 0。此为单轮合成压力回归,不作为实际用户耗时或性能提升结论。

+ 2 - 1
bun.lock

@@ -381,7 +381,7 @@
     },
     "packages/desktop": {
       "name": "@opencode-ai/desktop",
-      "version": "0.1.0-beta.1",
+      "version": "0.1.0-beta.4",
       "dependencies": {
         "@zip.js/zip.js": "2.7.62",
         "effect": "catalog:",
@@ -390,6 +390,7 @@
         "electron-store": "11.0.2",
         "electron-updater": "6.8.9",
         "electron-window-state": "^5.0.3",
+        "marked": "catalog:",
       },
       "devDependencies": {
         "@actions/artifact": "4.0.0",

+ 145 - 15
packages/app/e2e/paas/fixture.tsx

@@ -2,13 +2,12 @@ import { render } from "solid-js/web"
 import { AppBaseProviders } from "../../src/app"
 import { PlatformProvider, type Platform } from "../../src/context/platform"
 import PaasWorkspace from "../../src/pages/paas"
-import type { PaasPlatform, PaasProgress, PaasRequest } from "../../src/paas"
+import type { PaasPlatform, PaasRequest, PaasProgress, PaasUploadProgress } from "../../src/paas"
 import { PanelFixture } from "./panel-fixture"
 import "../../src/index.css"
 
 // Synthetic transport, real workbench. No model or developer service is started.
 const calls: PaasRequest[] = []
-const progress: Array<(event: PaasProgress) => void> = []
 const agent = { id: "research", name: "科研助手", description: "研究规划与验证", current_version: 1 }
 const run: Record<string, unknown> = {
   run_id: "run_1",
@@ -42,19 +41,156 @@ const run: Record<string, unknown> = {
     { type: "tool_result", tool: "file_search", content: "找到 2 份材料" },
   ],
 }
+const progress = new Set<(event: PaasProgress) => void>()
+const uploads = new Set<(event: PaasUploadProgress) => void>()
+const uxRuns = new Map<string, Record<string, unknown>>()
+const ux = {
+  enabled: new URLSearchParams(location.search).has("ux"),
+  uploads: 0,
+  holdRun: "",
+  holdThread: "",
+  held: false,
+  release: () => {},
+  add: (value: Record<string, unknown>) => uxRuns.set(String(value.run_id), value),
+  update: (id: string, value: Record<string, unknown>) => Object.assign(uxRuns.get(id) || {}, value),
+  progress: (event: PaasProgress) => progress.forEach((listener) => listener(event)),
+  run: (id: string) => uxRuns.get(id),
+}
+Object.assign(window, { paasUX: ux })
+let researchConfig = {
+  researchWorkflow: "research67-scientific-v1",
+  model: { provider: "deepseek", name: "deepseek-chat" },
+  scientific: { token_budget: 500000, max_actual_tokens: 1000000, max_rounds: 4, max_wall_seconds: 3600 },
+}
 const api: PaasPlatform = {
   connect: async (input) => {
     if (!input) throw new Error("No saved connection")
-    return { url: input.url, remembered: true }
+    return { url: input.url, remembered: true, scope: `test-${input.apiKey}` }
   },
   disconnect: async () => {},
-  chooseFiles: async () => [{ file_id: "file_1", name: "材料.pdf" }],
   onProgress: (listener) => {
-    progress.push(listener)
-    return () => progress.splice(progress.indexOf(listener), 1)
+    progress.add(listener)
+    return () => progress.delete(listener)
   },
+  onUploadProgress: (listener) => {
+    uploads.add(listener)
+    return () => uploads.delete(listener)
+  },
+  ...(ux.enabled
+    ? {
+        selectFiles: async () => [
+          { selectionID: "one", name: "成功.txt", size: 10 },
+          { selectionID: "two", name: "重试.txt", size: 10 },
+        ],
+      }
+    : {}),
+  chooseFiles: async () => [{ file_id: "file_1", name: "材料.pdf" }],
   request: async (request) => {
     calls.push(request)
+    if (ux.enabled) {
+      if (request.action === "agent")
+        return { ...agent, config: structuredClone(researchConfig), updated_at: "version-1", can_update_metadata: true }
+      if (request.action === "update-agent") {
+        researchConfig = request.update.config as typeof researchConfig
+        return { saved: true }
+      }
+      if (request.action === "knowledge") return { items: [] }
+      if (request.action === "upload-selected" || request.action === "upload-file") {
+        ux.uploads++
+        uploads.forEach((listener) => listener({ uploadID: request.uploadID!, sent: 10, total: 10 }))
+        if (request.action === "upload-selected" && request.selectionID === "two" && ux.uploads === 2)
+          throw new Error("上传暂时失败")
+        return {
+          file_id: `file_${ux.uploads}`,
+          name:
+            request.action === "upload-file" ? request.name : request.selectionID === "one" ? "成功.txt" : "重试.txt",
+        }
+      }
+      if (request.action === "file-capabilities") return { direct_upload_max_bytes: 100000 }
+      if (request.action === "threads") return { threads: [] }
+      if (request.action === "thread-runs") {
+        const value = structuredClone({
+          thread_id: request.threadID,
+          runs: [...uxRuns.values()].filter((row) => row.thread_id === request.threadID),
+        })
+        if (ux.holdThread === request.threadID) {
+          ux.holdThread = ""
+          ux.held = true
+          await new Promise<void>((resolve) => {
+            ux.release = () => {
+              ux.held = false
+              resolve()
+            }
+          })
+        }
+        return value
+      }
+      if (request.action === "lookup-request") {
+        const run = [...uxRuns.values()].find((row) => row.request_key === request.requestID)
+        return run ? { found: true, run: { ...run } } : { found: false, state: "not_observed", retry_safe: false }
+      }
+      if (request.action === "execute") {
+        if (request.input === "模拟网络中断") throw new Error("连接中断,提交结果未知")
+        const id = `ux_${uxRuns.size + 1}`
+        const value = {
+          run_id: id,
+          thread_id: request.threadID || `thread_${id}`,
+          agent_id: request.agentID,
+          status: "running",
+          input: request.input,
+          output: "",
+          created_at: new Date().toISOString(),
+          request_key: request.requestID,
+        }
+        uxRuns.set(id, value)
+        if (request.input === "回执丢失但任务已创建") throw new Error("连接中断,回执未收到")
+        progress.forEach((listener) =>
+          listener({ executionID: request.executionID!, type: "started", runID: id, threadID: value.thread_id }),
+        )
+        return { ...value }
+      }
+      if (request.action === "history") {
+        const all = [...uxRuns.values()].reverse(),
+          offset = request.offset || 0
+        const recent = all.slice(offset, offset + 20)
+        const active = request.includeActive
+          ? all.filter(
+              (row) =>
+                !["completed", "failed", "partial", "cancelled", "needs_clarification"].includes(String(row.status)),
+            )
+          : []
+        return {
+          runs: [...new Map([...recent, ...active].map((row) => [row.run_id, { ...row }])).values()],
+          pagination_supported: true,
+          active_included: !!request.includeActive,
+          next_offset: offset + 20 < all.length ? offset + 20 : null,
+        }
+      }
+      if (request.action === "run") {
+        const value = structuredClone(uxRuns.get(request.runID))
+        if (ux.holdRun === request.runID) {
+          ux.holdRun = ""
+          ux.held = true
+          await new Promise<void>((resolve) => {
+            ux.release = () => {
+              ux.held = false
+              resolve()
+            }
+          })
+        }
+        return value || {}
+      }
+    }
+    if (request.action === "verify")
+      return { checks: [{ kind: "model", name: "科研模型", status: request.checkModel ? "passed" : "not_checked" }] }
+    if (request.action === "agents") return { agents: [agent] }
+    if (request.action === "run-options") throw new Error("HTTP 404")
+    if (request.action === "threads") return { threads: [{ id: "thread_1", title: "已有研究" }] }
+    if (request.action === "thread-runs") return { thread_id: "thread_1", runs: [{ ...run, input: "分析材料" }] }
+    if (request.action === "execute" && request.input === "持续研究") {
+      run.status = "running"
+      run.pending_approval = null
+    }
     if (request.action === "execute") {
       progress.forEach((listener) =>
         listener({
@@ -73,14 +209,6 @@ const api: PaasPlatform = {
         }),
       )
     }
-    if (request.action === "agents") return { agents: [agent] }
-    if (request.action === "run-options") throw new Error("HTTP 404")
-    if (request.action === "threads") return { threads: [{ id: "thread_1", title: "已有研究" }] }
-    if (request.action === "thread-runs") return { thread_id: "thread_1", runs: [{ ...run, input: "分析材料" }] }
-    if (request.action === "execute" && request.input === "持续研究") {
-      run.status = "running"
-      run.pending_approval = null
-    }
     if (request.action === "execute" || request.action === "run") return { ...run }
     if (request.action === "pause") {
       run.status = "paused"
@@ -102,13 +230,15 @@ const api: PaasPlatform = {
       return { ...run }
     }
     if (request.action === "run-files") return { files: [{ name: "研究计划.pdf", path: "final/研究计划.pdf" }] }
-    if (request.action === "download") return { saved: true }
+    if (request.action === "export-report") return { saved: true, name: `研究报告.${request.format || "md"}`, path: `/tmp/研究报告.${request.format || "md"}` }
+    if (request.action === "download") return { saved: true, name: "研究计划.pdf", path: "/tmp/研究计划.pdf" }
     if (request.action === "history") return { runs: [{ ...run, input: "分析材料" }] }
     return {}
   },
 }
 Object.assign(window, { paasTestCalls: calls })
 const platform: Platform = {
+  revealPath: async () => true,
   platform: "desktop",
   os: "macos",
   paas: api,

+ 110 - 0
packages/app/e2e/paas/polish.spec.ts

@@ -0,0 +1,110 @@
+import { expect, test, type Page } from "@playwright/test"
+
+async function connect(page: Page) {
+  await page.goto("/e2e/paas/index.html?ux")
+  await page.getByLabel("API Key", { exact: true }).fill("polish-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeEnabled()
+}
+
+test("optional resource probes never block research and model invocation is explicit", async ({ page }) => {
+  await connect(page)
+  await expect(page.getByRole("button", { name: "定时任务", exact: true })).toHaveCount(0)
+  await page.getByRole("button", { name: "资源检查", exact: true }).click()
+  await page.getByRole("button", { name: "检查资源", exact: true }).click()
+  await page.getByRole("button", { name: "测试模型连接", exact: true }).click()
+  await page.getByRole("button", { name: "直接开始研究", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeEnabled()
+  const calls = await page.evaluate(() => window.paasTestCalls)
+  expect(calls.filter((c) => c.action === "verify").map((c) => c.checkModel)).toEqual([false, true])
+  expect(calls.filter((c) => c.action === "execute")).toHaveLength(0)
+})
+
+test("continuation keeps a compact reference across reload and submits the original report once", async ({ page }) => {
+  await connect(page)
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("研究初稿")
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+  await page.evaluate(() =>
+    window.paasUX.update("ux_1", { status: "completed", output: "# 原始方案\n证据甲,不可丢失。" }),
+  )
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("补充对照设计")
+  await page.getByRole("button", { name: "基于此方案继续", exact: true }).click()
+  await page.getByRole("button", { name: "基于此方案继续", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("补充对照设计")
+  await expect(page.getByLabel("已引用研究报告")).toHaveCount(1)
+  await page.reload()
+  await page.getByLabel("API Key", { exact: true }).fill("polish-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByLabel("已引用研究报告")).toContainText("证据甲")
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  const calls = await page.evaluate(() => window.paasTestCalls.filter((c) => c.action === "execute"))
+  expect(calls).toHaveLength(1)
+  expect(String(calls[0].input).match(/证据甲/g)).toHaveLength(1)
+  expect(calls[0].input).toContain("补充对照设计")
+  await expect(page.getByLabel("已引用研究报告")).toHaveCount(0)
+})
+
+test("report reader compares versions and passes the selected export format", async ({ page }, info) => {
+  await connect(page)
+  await page.evaluate(() => {
+    window.paasUX.add({
+      run_id: "v1",
+      agent_id: "research",
+      thread_id: "report",
+      input: "版本一",
+      output: "# 方案\n\n旧条件",
+      status: "completed",
+    })
+    window.paasUX.add({
+      run_id: "v2",
+      agent_id: "research",
+      thread_id: "report",
+      input: "版本二",
+      output: "# 方案\n\n新条件",
+      status: "completed",
+    })
+  })
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await page.getByRole("row").filter({ hasText: "版本二" }).getByRole("button", { name: "打开任务" }).click()
+  await page.getByRole("button", { name: "阅读与对比", exact: true }).last().click()
+  const dialog = page.getByRole("dialog")
+  await dialog.getByRole("button", { name: "对比此前报告", exact: true }).click()
+  await expect(dialog.locator('[data-change="added"]')).toContainText("新条件")
+  await expect(dialog.locator('[data-change="removed"]')).toContainText("旧条件")
+  await dialog.getByRole("button", { name: "导出 Word", exact: true }).click()
+  expect(
+    await page.evaluate(() => window.paasTestCalls.filter((c) => c.action === "export-report").at(-1)?.format),
+  ).toBe("docx")
+  await page.screenshot({ path: info.outputPath("report-reader.png"), fullPage: true })
+})
+
+test("research progress displays reported usage and outstanding work without inventing completion", async ({
+  page,
+}, info) => {
+  await connect(page)
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("过程验收")
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+  await page.evaluate(() =>
+    window.paasUX.update("ux_1", {
+      stage_name: "方案审阅",
+      usage: { total_tokens: 42000, usage_complete: false },
+      research: {
+        science: {
+          main_flow: { rounds_completed: 2 },
+          next_step: "补充实验条件",
+          outcome: { sections: [{ title: "已有产物与待办", lines: ["待办:核对适用范围"] }] },
+        },
+      },
+    }),
+  )
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await expect(page.getByLabel("研究进展")).toContainText("42,000")
+  await expect(page.getByLabel("研究进展")).toContainText("方案审阅")
+  await expect(page.getByLabel("研究进展")).toContainText("用量仍在汇总")
+  await page.getByLabel("研究进展").scrollIntoViewIfNeeded()
+  await page.screenshot({ path: info.outputPath("research-progress.png"), fullPage: true })
+})

+ 250 - 0
packages/app/e2e/paas/recovery.spec.ts

@@ -0,0 +1,250 @@
+import { expect, test, type Page } from "@playwright/test"
+declare global {
+  interface Window {
+    paasUX: {
+      update(id: string, value: Record<string, unknown>): void
+      add(value: Record<string, unknown>): void
+      holdRun: string
+      holdThread: string
+      held: boolean
+      release(): void
+    }
+    paasTestCalls: Record<string, unknown>[]
+  }
+}
+async function connect(page: Page) {
+  await page.goto("/e2e/paas/index.html?ux")
+  await page.getByLabel("API Key", { exact: true }).fill("recovery-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeEnabled()
+}
+async function submit(page: Page, input: string) {
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill(input)
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+}
+test("cached conversation merges remote results without replacing draft or attachments", async ({ page }) => {
+  await connect(page)
+  await submit(page, "原始研究")
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("不要覆盖的草稿")
+  await page.getByRole("button", { name: "添加文件", exact: true }).click()
+  await expect(page.getByRole("button", { name: "移除成功.txt", exact: true })).toBeVisible()
+  await page.locator(".paas-chat-header").getByRole("button", { name: "新会话", exact: true }).click()
+  await page.evaluate(() => {
+    window.paasUX.update("ux_1", { status: "completed", output: "远端修订后的结论" })
+    window.paasUX.add({
+      run_id: "external_2",
+      agent_id: "research",
+      thread_id: "thread_ux_1",
+      input: "其他窗口的追加研究",
+      output: "其他窗口的新增成果",
+      status: "completed",
+    })
+  })
+  await page.getByRole("button", { name: /^原始研究/ }).click()
+  await expect(page.getByText("其他窗口的新增成果", { exact: true })).toBeVisible()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("不要覆盖的草稿")
+  await expect(page.getByRole("button", { name: "移除成功.txt", exact: true })).toBeVisible()
+  await page.locator(".paas-chat-header").getByRole("button", { name: "新会话", exact: true }).click()
+  await page.getByRole("button", { name: /^原始研究/ }).click()
+  await expect(page.locator('.paas-chat-message[data-role="assistant"]')).toHaveCount(2)
+})
+
+test("late task open cannot replace the user's newer selected conversation", async ({ page }) => {
+  await connect(page)
+  await page.evaluate(() => {
+    for (const id of ["slow", "fast"])
+      window.paasUX.add({
+        run_id: id,
+        agent_id: "research",
+        thread_id: `thread_${id}`,
+        input: `${id}任务`,
+        output: `${id}结果`,
+        status: "completed",
+      })
+    window.paasUX.holdRun = "slow"
+  })
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await page.getByRole("row").filter({ hasText: "slow任务" }).getByRole("button", { name: "打开任务" }).click()
+  await expect.poll(() => page.evaluate(() => window.paasUX.held)).toBe(true)
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("row").filter({ hasText: "fast任务" }).getByRole("button", { name: "打开任务" }).click()
+  await expect(page.getByText("fast结果", { exact: true })).toBeVisible()
+  await page.evaluate(() => window.paasUX.release())
+  await expect(page.getByText("slow结果", { exact: true })).toHaveCount(0)
+  await expect(page.getByText("fast结果", { exact: true })).toBeVisible()
+})
+
+test("late thread synchronization cannot switch away from a newly created chat", async ({ page }) => {
+  await connect(page)
+  await submit(page, "旧会话")
+  await page.locator(".paas-chat-header").getByRole("button", { name: "新会话", exact: true }).click()
+  await page.evaluate(() => {
+    window.paasUX.holdThread = "thread_ux_1"
+  })
+  await page.getByRole("button", { name: /^旧会话/ }).click()
+  await expect.poll(() => page.evaluate(() => window.paasUX.held)).toBe(true)
+  await page.locator(".paas-chat-header").getByRole("button", { name: "新会话", exact: true }).click()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("新的编辑内容")
+  await page.evaluate(() => window.paasUX.release())
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("新的编辑内容")
+  await expect(page.getByRole("log", { name: "会话消息" })).not.toContainText("旧会话")
+})
+
+test("lost submission receipt recovers the canonical run without issuing another execute", async ({ page }) => {
+  await connect(page)
+  await submit(page, "回执丢失但任务已创建")
+  await expect(page.getByText("已自动找回原任务,未重新提交。", { exact: true })).toBeVisible()
+  const calls = await page.evaluate(() => window.paasTestCalls)
+  const execution = calls.find((call) => call.action === "execute")!
+  expect(execution.requestID).toBeTruthy()
+  expect(calls.filter((call) => call.action === "execute")).toHaveLength(1)
+  expect(calls.find((call) => call.action === "lookup-request")?.requestID).toBe(execution.requestID)
+  await expect(page.locator('.paas-chat-message[data-role="assistant"]')).toHaveCount(1)
+})
+
+test("conversation rename, search and local archive persist without cancelling a running task", async ({ page }) => {
+  await connect(page)
+  await submit(page, "需要整理的任务")
+  await page.getByText("更多操作", { exact: true }).click()
+  await page.getByRole("button", { name: "重命名会话", exact: true }).click()
+  await page.getByRole("textbox", { name: "会话名称", exact: true }).fill("光学研究记录")
+  await page.getByRole("button", { name: "保存名称", exact: true }).click()
+  await page.getByRole("textbox", { name: "搜索会话标题", exact: true }).fill("光学")
+  await expect(page.locator(".paas-session-items").getByRole("button", { name: /光学研究记录/ })).toBeVisible()
+  await page.getByRole("button", { name: "在本机归档", exact: true }).click()
+  await expect(page.locator(".paas-session-items").getByRole("button", { name: /光学研究记录/ })).toHaveCount(0)
+  await page.getByRole("button", { name: "查看本机归档", exact: true }).click()
+  await expect(page.locator(".paas-session-items").getByRole("button", { name: /光学研究记录/ })).toBeVisible()
+  expect(await page.evaluate(() => window.paasTestCalls.some((c) => c.action === "cancel"))).toBe(false)
+  await page.reload()
+  await page.getByLabel("API Key", { exact: true }).fill("recovery-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByRole("heading", { name: "光学研究记录", exact: true })).toBeVisible()
+  await page.getByText("更多操作", { exact: true }).click()
+  await expect(page.getByRole("button", { name: "取消归档", exact: true })).toBeVisible()
+  await page.getByRole("button", { name: "取消归档", exact: true }).click()
+  await expect(page.locator(".paas-session-items").getByRole("button", { name: /光学研究记录/ })).toBeVisible()
+})
+
+test("report export and continuation preserve the report and draft without executing again", async ({ page }) => {
+  await connect(page)
+  await submit(page, "报告导出研究")
+  await page.evaluate(() =>
+    window.paasUX.update("ux_1", { status: "completed", output: "# 可追溯研究方案\n\n保留原始证据。" }),
+  )
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("已有的补充要求")
+  await page.getByRole("button", { name: "导出报告", exact: true }).click()
+  await expect(page.getByText("已导出 研究报告.md", { exact: true })).toBeVisible()
+  await page.getByRole("button", { name: "打开保存位置", exact: true }).click()
+  await page.getByRole("button", { name: "基于此方案继续", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("已有的补充要求")
+  const calls = await page.evaluate(() => window.paasTestCalls)
+  expect(calls.filter((c) => c.action === "execute")).toHaveLength(1)
+  expect(calls.find((c) => c.action === "export-report")?.text).toBe("# 可追溯研究方案\n\n保留原始证据。")
+})
+
+test("reconnecting refreshes the selected conversation while keeping its draft", async ({ page }) => {
+  await connect(page)
+  await submit(page, "断线期间继续研究")
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("仍在编辑的要求")
+  await page.getByRole("button", { name: "平台连接", exact: true }).click()
+  await page.getByRole("button", { name: "断开连接", exact: true }).click()
+  await page.evaluate(() =>
+    window.paasUX.add({
+      run_id: "external_reconnect",
+      agent_id: "research",
+      thread_id: "thread_ux_1",
+      input: "另一端追加的研究",
+      output: "重新连接时同步的新成果",
+      status: "completed",
+    }),
+  )
+  await page.getByLabel("API Key", { exact: true }).fill("recovery-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByText("重新连接时同步的新成果", { exact: true })).toBeVisible()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("仍在编辑的要求")
+})
+
+test("late stream events cannot undo completion or block the next draft", async ({ page }) => {
+  await connect(page)
+  await submit(page, "检查迟到事件")
+  await page.evaluate(() => window.paasUX.update("ux_1", { status: "completed", output: "已交付报告" }))
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await expect(page.getByText("已交付报告", { exact: true })).toBeVisible()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("继续研究")
+  await page.evaluate(() => {
+    const execution = window.paasTestCalls.find((c) => c.action === "execute")!
+    ;(window.paasUX as unknown as { progress(e: unknown): void }).progress({
+      executionID: execution.executionID,
+      type: "started",
+      runID: "ux_1",
+      status: "running",
+    })
+  })
+  await expect(page.getByRole("button", { name: "发送消息", exact: true })).toBeEnabled()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toHaveCount(0)
+})
+
+test("old active tasks remain visible and earlier history can be loaded", async ({ page }) => {
+  await connect(page)
+  await page.evaluate(() => {
+    for (let i = 0; i < 26; i++)
+      window.paasUX.add({
+        run_id: `page_${i}`,
+        agent_id: "research",
+        input: `分页研究${i}`,
+        status: i === 0 ? "paused" : "completed",
+      })
+  })
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await expect(page.getByRole("row").filter({ hasText: "分页研究0" })).toBeVisible()
+  await expect(
+    page
+      .getByRole("row")
+      .filter({ hasText: "分页研究1" })
+      .filter({ hasNotText: /分页研究1\d/ }),
+  ).toHaveCount(0)
+  await page.getByRole("button", { name: "加载更早任务", exact: true }).click()
+  await expect(page.getByRole("row")).toHaveCount(27)
+  await expect(page.getByRole("button", { name: "加载更早任务", exact: true })).toHaveCount(0)
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await expect(page.getByRole("row")).toHaveCount(27)
+})
+
+test("research settings return to the same draft without executing or changing budgets automatically", async ({
+  page,
+}, testInfo) => {
+  await connect(page)
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("保留我的下一轮要求")
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await page.getByLabel("累计 Token 硬上限", { exact: true }).fill("2000000")
+  await page
+    .getByRole("group", { name: "科研预算与迭代", exact: true })
+    .screenshot({ path: testInfo.outputPath("research-settings.png") })
+  await page.getByRole("button", { name: "保存修改", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("保留我的下一轮要求")
+  const calls = await page.evaluate(() => window.paasTestCalls)
+  expect(calls.some((c) => c.action === "execute")).toBe(false)
+  expect(calls.find((c) => c.action === "update-agent")).toMatchObject({
+    update: { config: { scientific: { max_actual_tokens: 2000000, token_budget: 500000 } } },
+  })
+})
+
+test("partial results explain the next step and continuation keeps the user's draft", async ({ page }, testInfo) => {
+  await connect(page)
+  await submit(page, "中断后的继续研究")
+  await page.evaluate(() => window.paasUX.update("ux_1", { status: "partial", output: "已完成的研究依据与初步方案" }))
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await expect(page.getByText(/当前成果已保留,可先导出/)).toBeVisible()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("补充新的实验条件")
+  await page.getByRole("button", { name: "基于已有成果续研", exact: true }).click()
+  const draft = await page.getByRole("textbox", { name: "消息", exact: true }).inputValue()
+  expect(draft).toContain("补充新的实验条件")
+  await expect(page.getByLabel("已引用研究报告")).toContainText("已完成的研究依据与初步方案")
+  expect(await page.evaluate(() => window.paasTestCalls.filter((c) => c.action === "execute").length)).toBe(1)
+  await page.screenshot({ path: testInfo.outputPath("continuation.png"), fullPage: true })
+})

+ 167 - 0
packages/app/e2e/paas/ux.spec.ts

@@ -0,0 +1,167 @@
+import { expect, test, type Page } from "@playwright/test"
+async function connect(page: Page, key = "ux-account") {
+  await page.getByLabel("平台地址", { exact: true }).fill("https://research.example")
+  await page.getByLabel("API Key", { exact: true }).fill(key)
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeEnabled()
+}
+async function run(page: Page, input: string) {
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill(input)
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+}
+
+test("parallel chats preserve next-round drafts, materials and active chat across reload and isolate accounts", async ({
+  page,
+}) => {
+  await page.goto("/e2e/paas/index.html?ux")
+  await connect(page)
+  await run(page, "第一项后台研究")
+  const input = page.getByRole("textbox", { name: "消息", exact: true })
+  await input.fill("第一项下一轮草稿")
+  await expect(page.getByRole("button", { name: "发送消息", exact: true })).toBeDisabled()
+  await page.getByRole("button", { name: "新会话", exact: true }).click()
+  await run(page, "第二项后台研究")
+  await input.fill("第二项下一轮草稿")
+  await page.getByRole("button", { name: /第一项后台研究/ }).click()
+  await expect(input).toHaveValue("第一项下一轮草稿")
+  await page.reload()
+  await connect(page)
+  await expect(input).toHaveValue("第一项下一轮草稿")
+  // Reopening never repeats either execution; unresolved background jobs remain read-only until confirmed.
+  expect(
+    await page.evaluate(
+      () =>
+        (window as unknown as { paasTestCalls: { action: string }[] }).paasTestCalls.filter(
+          (c) => c.action === "execute",
+        ).length,
+    ),
+  ).toBe(0)
+  await page.getByRole("button", { name: "平台连接", exact: true }).click()
+  await page.getByRole("button", { name: "断开连接", exact: true }).click()
+  await connect(page, "other-account")
+  await expect(input).toHaveValue("")
+  await expect(page.getByText("第一项后台研究", { exact: true })).toHaveCount(0)
+})
+
+test("partial upload failure keeps successful materials and retries only the failed file; drop works", async ({
+  page,
+}) => {
+  await page.goto("/e2e/paas/index.html?ux")
+  await connect(page)
+  await page.getByRole("button", { name: "添加文件", exact: true }).click()
+  await expect(page.getByRole("button", { name: "移除成功.txt", exact: true })).toBeVisible()
+  await page.getByRole("button", { name: "重试 重试.txt", exact: true }).click()
+  await expect(page.getByRole("button", { name: "移除重试.txt", exact: true })).toBeVisible()
+  expect(await page.evaluate(() => (window as unknown as { paasUX: { uploads: number } }).paasUX.uploads)).toBe(3)
+  const transfer = await page.evaluateHandle(() => {
+    const data = new DataTransfer()
+    data.items.add(new File(["research"], "拖放.txt", { type: "text/plain" }))
+    return data
+  })
+  await page.locator(".paas-composer").dispatchEvent("drop", { dataTransfer: transfer })
+  await expect(page.getByRole("button", { name: "移除拖放.txt", exact: true })).toBeVisible()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("保留材料的草稿")
+  await page.reload()
+  await connect(page)
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("保留材料的草稿")
+  await expect(page.getByRole("button", { name: "移除成功.txt", exact: true })).toBeVisible()
+  await expect(page.getByRole("button", { name: "移除重试.txt", exact: true })).toBeVisible()
+  await expect(page.getByRole("button", { name: "移除拖放.txt", exact: true })).toBeVisible()
+})
+
+test("unknown submission is recoverable without an automatic duplicate; task index opens the existing run", async ({
+  page,
+}) => {
+  await page.goto("/e2e/paas/index.html?ux")
+  await connect(page)
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("模拟网络中断")
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await page.getByRole("button", { name: "恢复原输入与材料", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("模拟网络中断")
+  await expect(page.getByRole("button", { name: "发送消息", exact: true })).toBeDisabled()
+  await page.getByRole("button", { name: "新会话", exact: true }).click()
+  await run(page, "任务中心可打开的研究")
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await expect(page.getByRole("table")).toContainText("任务中心可打开的研究")
+  await page.getByRole("button", { name: "打开任务", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+  expect(
+    await page.evaluate(
+      () =>
+        (window as unknown as { paasTestCalls: { action: string }[] }).paasTestCalls.filter(
+          (c) => c.action === "execute",
+        ).length,
+    ),
+  ).toBe(2)
+})
+
+test("reports render tables and math; background updates do not pull the reader down", async ({ page }) => {
+  const errors: string[] = []
+  page.on("pageerror", (error) => errors.push(error.message))
+  await page.goto("/e2e/paas/index.html?ux")
+  await connect(page)
+  await run(page, "阅读长报告")
+  await page.evaluate(() => {
+    const control = (window as unknown as { paasUX: { update(id: string, value: Record<string, unknown>): void } })
+      .paasUX
+    control.update("ux_1", {
+      output:
+        "# 研究报告\n\n| 指标 | 结果 |\n|---|---|\n| 样本 | 42 |\n\n$$E=mc^2$$\n\n" +
+        Array.from({ length: 35 }, (_, i) => `第 ${i + 1} 节研究分析。\n\n`).join(""),
+    })
+  })
+  await expect(page.locator(".paas-report table")).toBeVisible({ timeout: 10000 })
+  await expect(page.locator(".paas-report .katex")).toBeVisible()
+  const log = page.getByRole("log", { name: "会话消息" })
+  await log.evaluate((el) => {
+    el.scrollTop = 0
+    el.dispatchEvent(new Event("scroll"))
+  })
+  await page.evaluate(() => {
+    const control = (
+      window as unknown as {
+        paasUX: { update(id: string, value: Record<string, unknown>): void; run(id: string): { output: string } }
+      }
+    ).paasUX
+    control.update("ux_1", { output: control.run("ux_1").output + "\n\n新的研究进展。" })
+  })
+  await expect(page.getByRole("button", { name: "有新进展 · 回到底部", exact: true })).toBeVisible({ timeout: 10000 })
+  expect(await log.evaluate((el) => el.scrollTop)).toBeLessThan(80)
+  await page.getByRole("button", { name: "有新进展 · 回到底部", exact: true }).click()
+  await expect(page.getByRole("button", { name: "有新进展 · 回到底部", exact: true })).toHaveCount(0)
+  expect(errors).toEqual([])
+  await page.screenshot({ path: "/tmp/lambda-desktop-ux-report.png", fullPage: true })
+})
+
+test("background task approval produces a navigable notice and readable confirmation", async ({ page }) => {
+  await page.goto("/e2e/paas/index.html?ux")
+  await connect(page)
+  await run(page, "需要确认的后台研究")
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await expect(page.getByRole("table")).toContainText("运行中")
+  await page.evaluate(() => {
+    const control = (window as unknown as { paasUX: { update(id: string, value: Record<string, unknown>): void } })
+      .paasUX
+    control.update("ux_1", {
+      status: "running",
+      pending_approval: {
+        approval_id: "approve_ux",
+        stage_name: "实验方案审阅",
+        prompt: "请核对实验设置后继续。",
+        artifacts: [{ name: "实验方案.md" }],
+      },
+    })
+  })
+  await expect(page.getByLabel("任务通知", { exact: true })).toContainText("等待人工确认", { timeout: 15000 })
+  await page
+    .getByLabel("任务通知", { exact: true })
+    .getByRole("button", { name: /等待人工确认/ })
+    .click()
+  await expect(page.getByText("当前阶段:实验方案审阅", { exact: true })).toBeVisible()
+  await expect(page.getByText("待确认成果:实验方案.md", { exact: true })).toBeVisible()
+  await expect(page.getByRole("button", { name: "同意并继续", exact: true })).toBeVisible()
+  await expect(page.getByRole("button", { name: "发送消息", exact: true })).toBeDisabled()
+})

+ 1 - 36
packages/app/e2e/paas/workbench.spec.ts

@@ -33,7 +33,7 @@ test("independent workbench connects, uploads, confirms and saves without a deve
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
   await page.getByRole("button", { name: "保存成果", exact: true }).click()
   await expect(page.getByText("文件已保存。", { exact: true })).toBeVisible()
-  await page.getByRole("button", { name: "查看工作文件", exact: true }).click()
+  await page.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
   await page.getByRole("button", { name: "保存文件", exact: true }).click()
   await expect(page.getByText("文件已保存。", { exact: true })).toBeVisible()
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
@@ -73,38 +73,3 @@ test("pause, resume and stop use the existing task without resubmission", async
   expect(calls.find((value) => value.action === "resume")).toMatchObject({ checkpointID: "checkpoint_1" })
   expect(calls.filter((value) => value.action === "run").length).toBeLessThan(12)
 })
-
-test("task detail keeps one snapshot with overview, activity and technical info", async ({ page }) => {
-  const errors: string[] = []
-  page.on("pageerror", (error) => errors.push(error.message))
-  await page.goto("/e2e/paas/index.html")
-  await page.getByLabel("平台地址", { exact: true }).fill("https://research.example")
-  await page.getByLabel("API Key", { exact: true }).fill("test-only")
-  await page.getByRole("button", { name: "连接平台", exact: true }).click()
-  await page.getByRole("button", { name: "平台任务", exact: true }).click()
-  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
-  const row = page.getByRole("row", { name: /分析材料/ })
-  await expect(row).toBeVisible()
-  await row.getByRole("button", { name: "查看详情", exact: true }).click()
-  await expect(page.getByRole("region", { name: "任务详情", exact: true })).toBeVisible()
-  await expect(page.getByRole("region", { name: "任务详情", exact: true })).toHaveCount(1)
-  await expect(page.getByRole("heading", { name: "概览", exact: true })).toBeVisible()
-  await expect(page.getByRole("heading", { name: "活动", exact: true })).toBeVisible()
-  await expect(page.getByRole("heading", { name: "研究计划", exact: true })).toBeVisible()
-  await expect(page.getByText("工具活动 · 2 条", { exact: true })).toBeVisible()
-  await expect(page.getByRole("heading", { name: "成果 · 1", exact: true })).toBeVisible()
-  await expect(page.getByText("研究计划成果.pdf", { exact: true })).toBeVisible()
-  await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
-  await page.getByRole("button", { name: "查看工作文件", exact: true }).click()
-  await expect(page.getByRole("button", { name: "保存文件", exact: true })).toBeVisible()
-  await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
-  await expect(page.getByRole("group", { name: "待确认事项" })).toBeVisible()
-  await expect(page.getByText("是否执行验证?", { exact: true })).toHaveCount(1)
-  await expect(page.getByText("运行快照", { exact: true })).toHaveCount(0)
-  await expect(page.getByText("查看平台原始记录", { exact: true })).toHaveCount(0)
-  await page.getByText("技术信息", { exact: true }).click()
-  await expect(page.locator(".paas-run-technical")).toContainText('"client_detail_source": "detail"')
-  await page.getByRole("button", { name: "收起", exact: true }).click()
-  await expect(page.getByRole("region", { name: "任务详情", exact: true })).toHaveCount(0)
-  expect(errors).toEqual([])
-})

+ 2 - 0
packages/app/src/paas.test.ts

@@ -10,6 +10,8 @@ test("invalid responses are not displayed as empty successful lists", () => {
 
 test("pending confirmation stays actionable even while execution reports running", () => {
   expect(paasStatus({ status: "running", pending_confirmation: { status: "pending" } })).toBe("waiting_confirmation")
+  expect(paasStatus({ status: "running", pending_approval: { approval_id: "a" } })).toBe("waiting_human")
+  expect(paasStatus({ status: "running", pending_approval: { status: "approved" } })).toBe("running")
   expect(paasStatus({ status: "partial" })).toBe("partial")
   expect(paasStatus({})).toBe("unknown")
 })

+ 17 - 5
packages/app/src/paas.ts

@@ -25,18 +25,22 @@ export type PaasDownload = {
   path?: string
 }
 export type PaasRequest =
-  | { action: "detach" }
+  | { action: "detach"; executionID?: string }
   | {
       action: "execute"
       agentID: string
       input: string
       threadID?: string
       executionID?: string
+      requestID?: string
       effort?: PaasEffort
       files?: PaasFile[]
     }
+  | { action: "lookup-request"; agentID: string; requestID: string }
+  | { action: "export-report"; name: string; text: string; format?: "md" | "docx" | "pdf" }
   | PaasDownload
-  | { action: "upload-file"; agentID: string; threadID?: string; name: string; data: Uint8Array }
+  | { action: "upload-file"; agentID: string; threadID?: string; name: string; data: Uint8Array; uploadID?: string }
+  | { action: "upload-selected"; agentID: string; threadID?: string; selectionID: string; uploadID: string }
   | { action: "run-files" | "cancel" | "pause"; agentID: string; runID: string }
   | { action: "resume"; agentID: string; runID: string; checkpointID: string }
   | {
@@ -55,9 +59,9 @@ export type PaasRequest =
   | { action: "agent"; agentID: string }
   | { action: "update-agent"; agentID: string; update: PaasAgentUpdate }
   | { action: "thread-runs"; agentID: string; threadID: string }
-  | { action: "history"; agentID: string }
+  | { action: "history"; agentID: string; offset?: number; includeActive?: boolean }
   | { action: "run"; agentID: string; runID: string }
-  | { action: "verify"; agentID: string }
+  | { action: "verify"; agentID: string; checkModel?: boolean }
 
 export type PaasProgress = {
   executionID: string
@@ -70,13 +74,18 @@ export type PaasProgress = {
   status?: string
 }
 
+export type PaasUploadProgress = { uploadID: string; sent: number; total: number }
+export type PaasSelection = { selectionID: string; name: string; size: number }
+
 export type PaasPlatform = {
+  selectFiles?: () => Promise<PaasSelection[]>
+  onUploadProgress?: (listener: (event: PaasUploadProgress) => void) => () => void
   chooseFiles?: (agentID: string, threadID?: string) => Promise<PaasFile[]>
   connect: (input?: {
     url: string
     apiKey: string
     remember?: boolean
-  }) => Promise<{ url: string; remembered?: boolean }>
+  }) => Promise<{ url: string; remembered?: boolean; scope?: string }>
   onProgress?: (listener: (event: PaasProgress) => void) => () => void
   disconnect: (forget?: boolean) => Promise<void>
   request: (input: PaasRequest) => Promise<unknown>
@@ -122,6 +131,9 @@ export function paasStatus(run: Record<string, unknown>) {
   const status = paasText(run.status)
   if (paasTerminalStatuses.has(status)) return status
   if (paasRecord(run.pending_confirmation)?.status === "pending") return "waiting_confirmation"
+  const approval = paasRecord(run.pending_approval)
+  if (approval && (!approval.status || ["pending", "waiting"].includes(paasText(approval.status))))
+    return "waiting_human"
   return status || "unknown"
 }
 

+ 19 - 0
packages/app/src/pages/paas/README.md

@@ -1,3 +1,22 @@
+# λ-Scientist Desktop 工作台
+
+## 当前版本:0.1.0-beta.4(2026-11-29)
+
+- 独立桌面科研入口:平台连接、智能体目录、会话、材料上传、任务控制、审批、历史恢复与成果下载。
+- 首次使用提供连接说明和开始研究路径。资源预检可跳过;模型连通测试仅在用户点击后调用,可能消耗少量模型额度。
+- 「资源检查」直接进入模型与知识库配置,保存后清除旧检查结果;Skill/MCP 全生命周期管理仍需平台接口与后续界面支持。
+- 运行详情展示服务器返回的阶段、轮次、用量及研究结果分区;未回传的用量不按零处理,未完成汇总的用量有说明,不猜测进度百分比。
+- 报告支持专注阅读、与同会话此前报告进行文本对比,导出 Markdown / Word / PDF。Word/PDF 保留文字、标题、列表和表格;公式保留原文,远程图片不自动下载。
+- 续研以可展开的已有报告引用搭配新增要求,保留原草稿、刷新后恢复,确认发送时才合并上下文。连续点击不会重复附加报告;仍是新请求,不冒充任意检查点恢复。
+- 余额/预算、网络、凭证、权限、材料和审阅问题提供不同的处理建议,既有任务、成果与草稿保留。研究设置提供可选配置建议,不自动调整当前任务限制。
+- 缩小输入区,次要操作归入「更多操作」,宽屏导航显示名称。未实现的定时任务移出主导航。
+
+验收:25 项工作台交互、21 项桌面传输/存储/文档单元测试、8 项缓存/进展测试通过;App、Desktop 与 E2E 类型检查通过。原生测试使用隔离 Electron 与合成 HTTP 服务,核对上传和导出字节;Word 文件经 XML/表格结构检查及 LibreOffice 渲染,PDF 经文本提取与页面渲染检查。本轮不重新评价真实模型科研质量,也不宣称签名公证或跨平台发版完成。
+
+完整进展与历史验证见 [AgentPaaS 优化方案](../../../../../PAAS_OPTIMIZATION_PLAN.zh-CN.md)。以下保留旧阶段记录,不代表当前功能边界。
+
+---
+
 # AgentPaaS 工作台:第一阶段 GUI
 
 入口:新版/旧版首页的 **AgentPaaS 工作台**,路由 `/paas`。

+ 101 - 19
packages/app/src/pages/paas/agent-edit.tsx

@@ -11,6 +11,17 @@ const directories = [
 ] as const
 
 const configuration = [
+  {
+    title: "科研预算与迭代",
+    key: "scientific",
+    fields: [
+      { key: "token_budget", label: "计划 Token 预算(提示用量,不自动中止)", min: 1 },
+      { key: "max_actual_tokens", label: "累计 Token 硬上限", min: 1 },
+      { key: "min_rounds", label: "至少研究轮次", min: 1 },
+      { key: "max_rounds", label: "最多研究轮次", min: 1 },
+      { key: "max_wall_seconds", label: "最长运行时间(秒)", min: 1 },
+    ],
+  },
   {
     title: "模型",
     key: "model",
@@ -77,6 +88,7 @@ export function PaasAgentEdit(props: {
   const lifecycle = { active: true }
   onCleanup(() => (lifecycle.active = false))
   const config = createMemo(() => parseConfig(state.configText))
+  const scientific = () => !!config()?.researchWorkflow || !!paasRecord(config()?.scientific)
   const canEditMetadata = () => state.original?.can_update_metadata === true
   const configField = (value: unknown) => (typeof value === "number" ? String(value) : paasText(value))
   const groupValue = (group: string) => {
@@ -148,6 +160,21 @@ export function PaasAgentEdit(props: {
     const original = state.original
     const current = config()
     if (state.busy || !original || !current) return
+    const research = paasRecord(current.scientific)
+    if (scientific() && research) {
+      const planned = Number(research.token_budget ?? Math.min(200000, Number(research.max_actual_tokens ?? 1000000)))
+      const maximum = Number(research.max_actual_tokens ?? 1000000)
+      if (planned > maximum) {
+        setState("error", "计划 Token 预算不能大于累计硬上限,请调整后保存。")
+        return
+      }
+      const minimumRounds = Number(research.min_rounds ?? 2)
+      const maximumRounds = Number(research.max_rounds ?? 3)
+      if (minimumRounds > maximumRounds) {
+        setState("error", "至少研究轮次不能大于最多研究轮次,请调整后保存。")
+        return
+      }
+    }
     const update: PaasAgentUpdate = { config: { ...current }, expected_updated_at: paasText(original.updated_at) }
     if (canEditMetadata()) {
       const name = state.fields.name.trim()
@@ -187,7 +214,7 @@ export function PaasAgentEdit(props: {
     <section class="paas-agent-edit" aria-label="编辑智能体">
       <div class="paas-agent-edit-heading">
         <button type="button" disabled={state.busy} onClick={props.onClose}>
-          <Icon name="arrow-left" size="small" /> 返回智能体
+          <Icon name="arrow-left" size="small" /> 返回工作台
         </button>
         <h1>编辑智能体</h1>
         <Show when={state.original}>
@@ -238,27 +265,73 @@ export function PaasAgentEdit(props: {
               <p class="paas-muted">当前 PaaS 版本支持保存配置与目录,更新服务后可编辑名称和简介。</p>
             </Show>
           </fieldset>
-          <fieldset class="paas-panel paas-edit-fields" disabled={state.busy}>
-            <legend>目录绑定</legend>
-            <div class="paas-edit-columns">
-              <For each={directories}>
-                {(field) => (
-                  <label>
-                    {field.label}
-                    <input
-                      value={state.fields[field.key]}
-                      onInput={(event) => setState("fields", field.key, event.currentTarget.value)}
-                    />
-                    <small class="paas-muted">{field.hint}</small>
-                  </label>
-                )}
-              </For>
-            </div>
-          </fieldset>
-          <For each={configuration}>
+          <details>
+            <summary>高级:材料与成果目录</summary>
+            <fieldset class="paas-panel paas-edit-fields" disabled={state.busy}>
+              <legend>目录绑定</legend>
+              <div class="paas-edit-columns">
+                <For each={directories}>
+                  {(field) => (
+                    <label>
+                      {field.label}
+                      <input
+                        value={state.fields[field.key]}
+                        onInput={(event) => setState("fields", field.key, event.currentTarget.value)}
+                      />
+                      <small class="paas-muted">{field.hint}</small>
+                    </label>
+                  )}
+                </For>
+              </div>
+            </fieldset>
+          </details>
+          <For
+            each={configuration.filter((group) =>
+              scientific() ? ["scientific", "model"].includes(group.key) : group.key !== "scientific",
+            )}
+          >
             {(group) => (
               <fieldset class="paas-panel paas-edit-fields" disabled={state.busy || !config()}>
                 <legend>{group.title}</legend>
+                <Show when={group.key === "scientific"}>
+                  <p class="paas-muted">
+                    当前值继续有效。计划预算仅提醒;达到硬上限时保留已有成果。以下建议需点击后才填入,保存后仅用于后续任务。
+                  </p>
+                </Show>
+                <Show when={group.key === "scientific"}>
+                  <div class="paas-budget-presets">
+                    <button
+                      type="button"
+                      onClick={() => {
+                        const current = config()
+                        if (current)
+                          setState(
+                            "configText",
+                            JSON.stringify(
+                              {
+                                ...current,
+                                scientific: {
+                                  ...paasRecord(current.scientific),
+                                  token_budget: 500000,
+                                  max_actual_tokens: 2000000,
+                                  min_rounds: 2,
+                                  max_rounds: 6,
+                                  max_wall_seconds: 3600,
+                                },
+                              },
+                              null,
+                              2,
+                            ),
+                          )
+                      }}
+                    >
+                      填入较充分研究配置
+                    </button>
+                    <span class="paas-muted">
+                      最多 6 轮 / 200 万 Token / 60 分钟;满足交付条件可提前结束,可自行调整。
+                    </span>
+                  </div>
+                </Show>
                 <div class="paas-edit-columns">
                   <For each={group.fields}>
                     {(field) => (
@@ -267,6 +340,15 @@ export function PaasAgentEdit(props: {
                         <input
                           type={field.min === undefined ? "text" : "number"}
                           min={field.min}
+                          max={
+                            group.key === "scientific"
+                              ? field.key === "max_wall_seconds"
+                                ? 86400
+                                : field.key.endsWith("rounds")
+                                  ? 8
+                                  : 8000000
+                              : undefined
+                          }
                           step={field.step}
                           value={configField(groupValue(group.key)[field.key])}
                           onInput={(event) => {

+ 155 - 0
packages/app/src/pages/paas/chat-cache.test.ts

@@ -0,0 +1,155 @@
+import { describe, expect, test } from "bun:test"
+import { createChatCache } from "./chat-cache"
+import type { ResearchChat } from "./chat-state"
+function memory() {
+  const data = new Map<string, string>(),
+    reads: string[] = [],
+    writes: string[] = []
+  const fail = { key: "" }
+  const storage: Storage = {
+    get length() {
+      return data.size
+    },
+    clear: () => data.clear(),
+    key: (i) => [...data.keys()][i] || null,
+    getItem: (key) => {
+      reads.push(key)
+      return data.get(key) ?? null
+    },
+    setItem: (key, value) => {
+      if (key === fail.key) throw new Error("quota")
+      writes.push(key)
+      data.set(key, value)
+    },
+    removeItem: (key) => {
+      data.delete(key)
+    },
+  }
+  return { storage, data, reads, writes, fail }
+}
+const chat = (id: string): ResearchChat => ({
+  id,
+  agentID: "a",
+  name: "Assistant",
+  title: id,
+  threadID: id,
+  draft: "草稿",
+  files: [{ file_id: "f", name: "材料.txt" }],
+  messages: [{ id: "m", role: "assistant", status: "completed", text: `报告${id}` }],
+})
+describe("research conversation persistence", () => {
+  test("migrates old drafts and attachments; history bodies load only when selected", () => {
+    const m = memory()
+    m.storage.setItem(
+      "lambda-scientist.chats.v1:s:main",
+      JSON.stringify({ active: "a", chats: [chat("a"), chat("b")] }),
+    )
+    const cache = createChatCache(m.storage, "s", "main", () => {})
+    const legacy = cache.load()
+    legacy.chats.forEach(cache.stage)
+    cache.index(
+      legacy.chats.map((c) => c.id),
+      legacy.active,
+    )
+    cache.close()
+    expect(m.data.has("lambda-scientist.chats.v1:s:main")).toBe(false)
+    m.reads.length = 0
+    const next = createChatCache(m.storage, "s", "main", () => {})
+    const restored = next.load()
+    expect(restored.chats[0].messages[0].text).toBe("报告a")
+    expect(restored.chats[1].messages).toEqual([])
+    expect(m.reads.some((k) => k.includes(":b:message:"))).toBe(false)
+    expect(restored.chats[1].draft).toBe("草稿")
+    expect(restored.chats[1].files[0].file_id).toBe("f")
+    expect(next.hydrate(restored.chats[1])[0].text).toBe("报告b")
+    next.close()
+  })
+  test("draft edits do not rewrite report bodies and reverted edits discard pending values", () => {
+    const m = memory(),
+      cache = createChatCache(m.storage, "s", "main", () => {}),
+      c = chat("a")
+    cache.stage(c)
+    cache.index([c.id], c.id)
+    cache.flush()
+    m.writes.length = 0
+    c.draft = "新草稿"
+    cache.metadata(c)
+    cache.flush()
+    expect(m.writes.some((k) => k.includes(":message:"))).toBe(false)
+    c.draft = "暂时更改"
+    cache.metadata(c)
+    c.draft = "新草稿"
+    cache.metadata(c)
+    cache.close()
+    expect(createChatCache(m.storage, "s", "main", () => {}).load().chats[0].draft).toBe("新草稿")
+  })
+  test("index write failure can be retried without losing existing message bodies", () => {
+    const m = memory(),
+      errors: string[] = [],
+      cache = createChatCache(m.storage, "s", "main", (e) => errors.push(e))
+    m.fail.key = "lambda-scientist.chats.v2:s:main:index"
+    cache.stage(chat("a"))
+    cache.index(["a"], "a")
+    cache.flush()
+    expect(errors.at(-1)).toContain("无法保存")
+    m.fail.key = ""
+    cache.flush()
+    expect(createChatCache(m.storage, "s", "main", () => {}).load().chats[0].messages[0].text).toBe("报告a")
+    expect(errors.at(-1)).toBe("")
+    cache.close()
+  })
+  test("new window preserves unloaded histories and scopes stay isolated", () => {
+    const m = memory(),
+      first = createChatCache(m.storage, "s", "one", () => {})
+    first.stage(chat("a"))
+    first.stage(chat("b"))
+    first.index(["a", "b"], "a")
+    first.close()
+    const second = createChatCache(m.storage, "s", "two", () => {}),
+      restored = second.load()
+    restored.chats.forEach(second.stage)
+    second.index(["a", "b"], "a")
+    second.close()
+    const reopened = createChatCache(m.storage, "s", "two", () => {}),
+      data = reopened.load()
+    expect(reopened.hydrate(data.chats[1])[0].text).toBe("报告b")
+    expect(createChatCache(m.storage, "other", "two", () => {}).load().chats).toEqual([])
+  })
+})
+
+test("one corrupt message preserves other conversations, drafts and healthy messages", () => {
+  const m = memory(),
+    errors: string[] = []
+  const first = createChatCache(m.storage, "s", "main", () => {})
+  const a = chat("a")
+  a.messages.push({ id: "good", role: "assistant", status: "completed", text: "保留的结果" })
+  first.stage(a)
+  first.stage(chat("b"))
+  first.index(["a", "b"], "a")
+  first.close()
+  m.data.set("lambda-scientist.chats.v2:s:main:a:message:m", "{broken")
+  const next = createChatCache(m.storage, "s", "main", (message) => errors.push(message))
+  const restored = next.load()
+  expect(restored.chats.map((c) => c.id)).toEqual(["a", "b"])
+  expect(restored.chats[0].messages.map((m) => m.text)).toEqual(["保留的结果"])
+  expect(restored.chats[1].draft).toBe("草稿")
+  expect(next.hydrate(restored.chats[1])[0].text).toBe("报告b")
+  restored.chats.forEach(next.stage)
+  next.index(["a", "b"], "a")
+  next.close()
+  expect(errors.at(-1)).toContain("损坏")
+  expect(m.data.get("lambda-scientist.chats.v2:s:main:a:message:m")).toBe("{broken")
+})
+
+test("a corrupt navigation index can be rebuilt from healthy conversation records", () => {
+  const m = memory(),
+    first = createChatCache(m.storage, "s", "main", () => {})
+  first.stage(chat("a"))
+  first.stage(chat("b"))
+  first.index(["a", "b"], "a")
+  first.close()
+  m.data.set("lambda-scientist.chats.v2:s:main:index", "{broken")
+  const next = createChatCache(m.storage, "s", "main", () => {})
+  expect(next.load().chats.map((c) => c.id)).toEqual(["a", "b"])
+  next.close()
+})

+ 182 - 0
packages/app/src/pages/paas/chat-cache.ts

@@ -0,0 +1,182 @@
+import type { ResearchChat, ResearchMessage } from "./chat-state"
+
+type Index = { ids: string[]; active: string }
+type Metadata = Omit<ResearchChat, "messages" | "cache"> & { source: string; messageIDs: string[]; live: boolean }
+
+/** Separate small navigation/draft records from report bodies. No credentials are stored. */
+export function createChatCache(storage: Storage, scope: string, windowID: string, onError: (message: string) => void) {
+  const root = `lambda-scientist.chats.v2:${scope}:${windowID}`
+  const latest = `lambda-scientist.chats.v2:${scope}:latest`
+  const pending = new Map<string, string>()
+  const written = new Map<string, string>()
+  const state = {
+    timer: undefined as ReturnType<typeof setTimeout> | undefined,
+    index: { ids: [], active: "" } as Index,
+    indexDirty: false,
+    migrated: false,
+    damaged: false,
+  }
+  const put = (key: string, value: string) => {
+    if (written.get(key) === value) {
+      pending.delete(key)
+      return
+    }
+    pending.set(key, value)
+    clearTimeout(state.timer)
+    state.timer = setTimeout(flush, 250)
+  }
+  function flush() {
+    clearTimeout(state.timer)
+    if (!pending.size && !state.indexDirty) return
+    try {
+      // Bodies before metadata, index last: an index must never reference a body that was not saved.
+      const entries = [...pending].sort(([a], [b]) => Number(a.endsWith(":meta")) - Number(b.endsWith(":meta")))
+      for (const [key, value] of entries) {
+        storage.setItem(key, value)
+        written.set(key, value)
+        pending.delete(key)
+      }
+      storage.setItem(`${root}:index`, JSON.stringify(state.index))
+      storage.setItem(latest, root)
+      state.indexDirty = false
+      if (state.migrated) {
+        storage.removeItem(`lambda-scientist.chats.v1:${scope}:${windowID}`)
+        storage.removeItem(`lambda-scientist.chats.v1:${scope}:latest`)
+        state.migrated = false
+      }
+      if (!state.damaged) onError("")
+    } catch {
+      state.indexDirty = true
+      onError("本机暂时无法保存部分内容,当前窗口中的草稿仍保留,可先导出重要报告。")
+    }
+  }
+  const read = <T>(key: string, fallback: T): T => {
+    const raw = storage.getItem(key)
+    if (!raw) return fallback
+    try {
+      return JSON.parse(raw) as T
+    } catch {
+      state.damaged = true
+      onError("部分本机记录损坏,已保留其他会话与草稿;打开对应会话可补齐平台记录。")
+      return fallback
+    }
+  }
+  function messages(source: string, chatID: string, ids: string[]) {
+    return ids
+      .map((id) => read<ResearchMessage | null>(`${source}:${chatID}:message:${id}`, null))
+      .filter(
+        (message): message is ResearchMessage =>
+          !!message && typeof message.id === "string" && typeof message.text === "string",
+      )
+  }
+  function load(): { chats: ResearchChat[]; active: string } {
+    try {
+      const source = storage.getItem(`${root}:index`) ? root : storage.getItem(latest)
+      if (!source || !source.startsWith(`lambda-scientist.chats.v2:${scope}:`)) {
+        const legacy =
+          read<{ chats?: ResearchChat[]; active?: string } | null>(
+            `lambda-scientist.chats.v1:${scope}:${windowID}`,
+            null,
+          ) ||
+          read<{ chats?: ResearchChat[]; active?: string } | null>(`lambda-scientist.chats.v1:${scope}:latest`, null)
+        state.migrated = !!legacy
+        return { chats: Array.isArray(legacy?.chats) ? legacy.chats : [], active: legacy?.active || "" }
+      }
+      const saved = read<Index | null>(`${source}:index`, null)
+      const index =
+        saved && Array.isArray(saved.ids)
+          ? saved
+          : {
+              ids: Array.from({ length: storage.length }, (_, i) => storage.key(i))
+                .filter((key): key is string => !!key && key.startsWith(`${source}:`) && key.endsWith(":meta"))
+                .map((key) => key.slice(source.length + 1, -5)),
+              active: "",
+            }
+      const chats = (Array.isArray(index.ids) ? index.ids : []).flatMap((id) => {
+        const meta = read<Metadata | null>(`${source}:${id}:meta`, null)
+        if (
+          !meta ||
+          !Array.isArray(meta.messageIDs) ||
+          typeof meta.source !== "string" ||
+          !meta.source.startsWith(`lambda-scientist.chats.v2:${scope}:`)
+        )
+          return []
+        const loaded = id === index.active || meta.live
+        return [
+          {
+            ...meta,
+            messages: loaded ? messages(meta.source, id, meta.messageIDs) : [],
+            cache: { source: meta.source, ids: meta.messageIDs, loaded },
+          },
+        ]
+      })
+      return { chats, active: index.active }
+    } catch {
+      onError("本机历史缓存读取不完整,平台历史会话仍可打开。")
+      return { chats: [], active: "" }
+    }
+  }
+  function hydrate(chat: ResearchChat) {
+    if (!chat.cache || chat.cache.loaded) return chat.messages
+    return messages(chat.cache.source, chat.id, chat.cache.ids)
+  }
+  function metadata(chat: ResearchChat) {
+    const loaded = chat.cache?.loaded !== false
+    const value: Metadata = {
+      id: chat.id,
+      agentID: chat.agentID,
+      name: chat.name,
+      title: chat.title,
+      titleManual: chat.titleManual,
+      archived: chat.archived,
+      threadID: chat.threadID,
+      draft: chat.draft,
+      reference: chat.reference,
+      files: chat.files,
+      effort: chat.effort,
+      source: loaded ? root : chat.cache!.source,
+      messageIDs: loaded ? chat.messages.map((m) => m.id) : chat.cache!.ids,
+      live:
+        loaded &&
+        chat.messages.some(
+          (m) =>
+            m.role === "assistant" &&
+            m.status &&
+            !["completed", "partial", "needs_clarification", "cancelled", "failed"].includes(m.status),
+        ),
+    }
+    put(`${root}:${chat.id}:meta`, JSON.stringify(value))
+  }
+  function message(chatID: string, id: string, serialized: string) {
+    put(`${root}:${chatID}:message:${id}`, serialized)
+  }
+  function index(ids: string[], active: string) {
+    if (
+      state.index.active === active &&
+      state.index.ids.length === ids.length &&
+      ids.every((id, i) => state.index.ids[i] === id)
+    )
+      return
+    state.index = { ids, active }
+    state.indexDirty = true
+    clearTimeout(state.timer)
+    state.timer = setTimeout(flush, 250)
+  }
+  function stage(chat: ResearchChat) {
+    if (chat.cache?.loaded !== false) chat.messages.forEach((m) => message(chat.id, m.id, JSON.stringify(m)))
+    metadata(chat)
+  }
+  return {
+    load,
+    hydrate,
+    metadata,
+    message,
+    index,
+    stage,
+    flush,
+    close: () => {
+      flush()
+      clearTimeout(state.timer)
+    },
+  }
+}

+ 710 - 0
packages/app/src/pages/paas/chat-state.ts

@@ -0,0 +1,710 @@
+import { createEffect, createMemo, mapArray, on, onCleanup, onMount, untrack } from "solid-js"
+import { createChatCache } from "./chat-cache"
+import { createStore, reconcile, unwrap } from "solid-js/store"
+import {
+  paasRecord,
+  paasRows,
+  paasRunDetail,
+  paasRun,
+  paasStatus,
+  paasTerminalStatuses,
+  paasText,
+  type PaasFile,
+  type PaasPlatform,
+  type PaasProgress,
+  type PaasEffort,
+} from "@/paas"
+
+export type ResearchMessage = {
+  id: string
+  role: "user" | "assistant"
+  text: string
+  status?: string
+  runID?: string
+  requestID?: string
+  replyTo?: string
+  recovery?: string
+  executionID?: string
+  activity?: PaasProgress[]
+  started?: number
+  updated?: number
+  submitted?: { input: string; files: PaasFile[] }
+  error?: string
+}
+export type ResearchChat = {
+  id: string
+  agentID: string
+  name: string
+  title: string
+  threadID: string
+  draft: string
+  reference?: { messageID: string; text: string }
+  files: PaasFile[]
+  effort?: PaasEffort
+  messages: ResearchMessage[]
+  cache?: { source: string; ids: string[]; loaded: boolean }
+  titleManual?: boolean
+  archived?: boolean
+}
+export const working = (message?: ResearchMessage) => !!message?.status && !paasTerminalStatuses.has(message.status)
+
+export function createResearchChats(props: {
+  api?: PaasPlatform
+  connected: boolean
+  scope?: string
+  windowID?: string
+  onNotice?: (notice: { chatID: string; title: string; body: string }) => void
+}) {
+  const [state, setState] = createStore({
+    chats: [] as ResearchChat[],
+    active: "",
+    error: "",
+    storageError: "",
+    restored: false,
+    focusRun: "",
+    syncing: "",
+    cacheVersion: 0,
+  })
+  const life = {
+    active: true,
+    epoch: 0,
+    key: "",
+    polling: false,
+    navigation: 0,
+  }
+  const current = createMemo(() => state.chats.find((chat) => chat.id === state.active))
+  const job = (chat = current()) =>
+    chat?.messages.findLast((message) => message.role === "assistant" && working(message))
+  const persistence: { current?: ReturnType<typeof createChatCache> } = {}
+  const save = () => {
+    if (current()) persistence.current?.stage(current()!)
+    persistence.current?.index(
+      state.chats.map((c) => c.id),
+      state.active,
+    )
+    persistence.current?.flush()
+  }
+  const hydrate = (chat: ResearchChat) => {
+    if (chat.cache?.loaded !== false || !persistence.current) return
+    try {
+      const messages = persistence.current.hydrate(chat)
+      setState("chats", (c) => c.id === chat.id, { messages, cache: { ...chat.cache, loaded: true } })
+    } catch {
+      setState("storageError", "该会话的本机缓存读取失败,可同步平台记录;草稿仍保留。")
+    }
+  }
+  const beginNavigation = () => ({ epoch: life.epoch, revision: ++life.navigation })
+  const selected = (ticket: ReturnType<typeof beginNavigation>) =>
+    life.active && ticket.epoch === life.epoch && ticket.revision === life.navigation
+  const show = (id: string) => {
+    const chat = state.chats.find((c) => c.id === id)
+    if (chat) hydrate(chat)
+    setState({ active: id, error: "", focusRun: "", syncing: "" })
+    save()
+  }
+  const activate = (id: string) => {
+    const ticket = beginNavigation()
+    const chat = state.chats.find((c) => c.id === id)
+    if (!chat) return
+    show(id)
+    if (chat.threadID && props.connected)
+      void loadThread({ id: chat.agentID, name: chat.name }, chat.threadID, chat.title, ticket)
+  }
+  const update = (chatID: string, messageID: string, run: Record<string, unknown>, notify = true) => {
+    const chat = state.chats.find((c) => c.id === chatID)
+    const previous = chat?.messages.find((m) => m.id === messageID)
+    if (!previous) return
+    const status = paasStatus(run)
+    if (paasTerminalStatuses.has(previous.status || "") && !paasTerminalStatuses.has(status)) return
+    const text = paasText(run.output) || previous.text
+    const error = paasText(run.error_message)
+    const changed = status !== previous.status || text !== previous.text || error !== previous.error
+    if (changed) {
+      const before = previous.status
+      setState(
+        "chats",
+        (c) => c.id === chatID,
+        "messages",
+        (m) => m.id === messageID,
+        { status, text, error, updated: Date.now() },
+      )
+      if (notify && before && before !== status && (paasTerminalStatuses.has(status) || status.startsWith("waiting")))
+        props.onNotice?.({
+          chatID,
+          title: status.startsWith("waiting") ? "研究任务需要确认" : "研究任务已有结果",
+          body: chat?.title || "打开会话查看",
+        })
+    }
+    const thread = paasText(run.thread_id) || paasText(run.session_id)
+    if (thread && chat?.threadID !== thread) setState("chats", (c) => c.id === chatID, "threadID", thread)
+  }
+  const lookups = new Map<string, number>()
+  async function lookup(chatID: string, messageID: string) {
+    const chat = state.chats.find((c) => c.id === chatID)
+    const message = chat?.messages.find((m) => m.id === messageID)
+    if (
+      !chat ||
+      !message?.requestID ||
+      message.runID ||
+      !props.connected ||
+      !props.api ||
+      lookups.get(messageID) === life.epoch
+    )
+      return
+    const epoch = life.epoch
+    lookups.set(messageID, epoch)
+    try {
+      const receipt = paasRecord(
+        await props.api.request({ action: "lookup-request", agentID: chat.agentID, requestID: message.requestID }),
+      )
+      if (!life.active || epoch !== life.epoch || !working(message)) return
+      if (receipt?.found !== true) {
+        if (receipt?.found !== false) throw new Error("平台未返回有效的提交回执。")
+        setState(
+          "chats",
+          (c) => c.id === chatID,
+          "messages",
+          (m) => m.id === messageID,
+          "recovery",
+          "平台暂未查到记录,将继续自动核对,不会自动重复执行。",
+        )
+        return
+      }
+      const run = paasRun(receipt.run)
+      if (run.agent_id && run.agent_id !== chat.agentID) throw new Error("提交回执的智能体不匹配。")
+      // A history refresh can discover this run before receipt recovery. Keep the original message and draft backup.
+      const duplicate = chat.messages.find(
+        (m) => m.role === "assistant" && m.id !== messageID && m.runID === run.run_id,
+      )
+      if (duplicate) {
+        const index = chat.messages.findIndex((m) => m.id === duplicate.id)
+        const userID =
+          duplicate.replyTo || (chat.messages[index - 1]?.role === "user" ? chat.messages[index - 1].id : "")
+        setState(
+          "chats",
+          (c) => c.id === chatID,
+          "messages",
+          (rows) => rows.filter((m) => m.id !== duplicate.id && m.id !== userID),
+        )
+      }
+      setState(
+        "chats",
+        (c) => c.id === chatID,
+        "messages",
+        (m) => m.id === messageID,
+        { runID: run.run_id, recovery: "已自动找回原任务,未重新提交。" },
+      )
+      update(chatID, messageID, run)
+      save()
+    } catch (error) {
+      if (life.active && epoch === life.epoch)
+        setState(
+          "chats",
+          (c) => c.id === chatID,
+          "messages",
+          (m) => m.id === messageID,
+          "recovery",
+          error instanceof Error && /HTTP (404|405)\b/.test(error.message)
+            ? "当前平台不支持按提交编号核对,可在任务中心检查;客户端不会自动重发。"
+            : "暂时无法核对提交回执,连接恢复后将继续查询。",
+        )
+    } finally {
+      if (lookups.get(messageID) === epoch) lookups.delete(messageID)
+    }
+  }
+  async function refresh() {
+    if (life.polling || !props.connected || !props.api) return
+    life.polling = true
+    const epoch = life.epoch
+    try {
+      const unresolved = state.chats.flatMap((chat) =>
+        chat.messages
+          .filter((m) => m.status === "unknown" && !m.runID && m.requestID && !m.recovery?.startsWith("当前平台不支持"))
+          .map((message) => ({ chatID: chat.id, messageID: message.id })),
+      )
+      for (let start = 0; start < unresolved.length; start += 4)
+        await Promise.all(unresolved.slice(start, start + 4).map((task) => lookup(task.chatID, task.messageID)))
+      if (!life.active || epoch !== life.epoch) return
+      const tasks = state.chats.flatMap((chat) =>
+        chat.messages
+          .filter((m) => working(m) && m.runID)
+          .map((message) => ({
+            chatID: chat.id,
+            agentID: chat.agentID,
+            messageID: message.id,
+            runID: message.runID!,
+            updated: message.updated,
+          })),
+      )
+      for (let start = 0; start < tasks.length; start += 4) {
+        await Promise.all(
+          tasks.slice(start, start + 4).map(async (task) => {
+            try {
+              const run = await paasRunDetail(props.api!, task.agentID, task.runID)
+              if (
+                life.active &&
+                epoch === life.epoch &&
+                state.chats.find((c) => c.id === task.chatID)?.messages.find((m) => m.id === task.messageID)
+                  ?.updated === task.updated
+              )
+                update(task.chatID, task.messageID, run)
+            } catch {
+              /* Preserve the last confirmed state; panels expose retry details. */
+            }
+          }),
+        )
+      }
+    } finally {
+      if (epoch === life.epoch) life.polling = false
+    }
+  }
+  createEffect(
+    on([() => props.scope, () => props.connected], ([scope, connected]) => {
+      life.epoch++
+      life.navigation++
+      setState("syncing", "")
+      life.polling = false
+      save()
+      if (!connected) {
+        setState(
+          "chats",
+          () => true,
+          "messages",
+          (m) => working(m) && !m.runID,
+          { status: "unknown", error: "连接中断,提交结果尚未确认,请先核对平台任务。" },
+        )
+        save()
+        return
+      }
+      const key = scope ? `lambda-scientist.chats.v2:${scope}:${props.windowID || "main"}` : ""
+      if (key !== life.key || !state.restored) {
+        persistence.current?.close()
+        life.key = key
+        persistence.current = scope
+          ? createChatCache(localStorage, scope, props.windowID || "main", (message) =>
+              setState("storageError", message),
+            )
+          : undefined
+        const data = persistence.current?.load() || { chats: [], active: "" }
+        const chats = Array.isArray(data.chats)
+          ? data.chats
+              .filter(
+                (c) => c && typeof c.id === "string" && typeof c.agentID === "string" && Array.isArray(c.messages),
+              )
+              .map((c) => ({
+                ...c,
+                name: typeof c.name === "string" ? c.name : "研究助手",
+                title: typeof c.title === "string" ? c.title : "历史会话",
+                threadID: typeof c.threadID === "string" ? c.threadID : "",
+                draft: typeof c.draft === "string" ? c.draft : "",
+                files: Array.isArray(c.files)
+                  ? c.files.filter((f) => f && typeof f.file_id === "string" && typeof f.name === "string")
+                  : [],
+                messages: c.messages
+                  .filter(
+                    (m) =>
+                      m &&
+                      typeof m.id === "string" &&
+                      typeof m.text === "string" &&
+                      ["user", "assistant"].includes(m.role),
+                  )
+                  .map((m) =>
+                    working(m) && !m.runID
+                      ? { ...m, status: "unknown", error: "上次提交结果尚未确认,请先核对平台任务。" }
+                      : m,
+                  ),
+              }))
+          : []
+        // Stage migration bodies before publishing the new index. Unloaded histories retain their source.
+        chats.forEach((chat) => persistence.current?.stage(chat))
+        setState("chats", reconcile(chats))
+        setState("cacheVersion", (version) => version + 1)
+        setState({
+          active: chats.some((c) => c.id === data.active) ? data.active! : chats[0]?.id || "",
+          restored: true,
+          error: "",
+        })
+      }
+      void refresh()
+      const chat = current()
+      if (chat?.threadID)
+        void loadThread({ id: chat.agentID, name: chat.name }, chat.threadID, chat.title, beginNavigation())
+    }),
+  )
+  createEffect(
+    mapArray(
+      () => state.chats,
+      (chat) => {
+        createEffect(() => {
+          state.cacheVersion
+          persistence.current?.metadata(chat)
+        })
+        createEffect(
+          mapArray(
+            () => chat.messages,
+            (message) => {
+              createEffect(() => {
+                state.cacheVersion
+                const serialized = JSON.stringify(message)
+                untrack(() => persistence.current?.message(chat.id, message.id, serialized))
+              })
+              return message.id
+            },
+          ),
+        )
+        return chat.id
+      },
+    ),
+  )
+  createEffect(() => {
+    state.cacheVersion
+    persistence.current?.index(
+      state.chats.map((c) => c.id),
+      state.active,
+    )
+  })
+  onMount(() => {
+    const unsubscribe = props.api?.onProgress?.((event) => {
+      if (!props.connected) return
+      const chat = state.chats.find((c) => c.messages.some((m) => m.executionID === event.executionID))
+      const message = chat?.messages.find((m) => m.executionID === event.executionID)
+      if (!chat || !message) return
+      const next =
+        event.type === "approval_required"
+          ? "waiting_human"
+          : event.type === "started"
+            ? "running"
+            : event.status || message.status
+      // A late event from the original stream must not undo a newer terminal snapshot.
+      if (paasTerminalStatuses.has(message.status || "") && !paasTerminalStatuses.has(next || "")) return
+      if (next && next !== message.status && (paasTerminalStatuses.has(next) || next.startsWith("waiting")))
+        props.onNotice?.({
+          chatID: chat.id,
+          title: next.startsWith("waiting") ? "研究任务需要确认" : "研究任务已有结果",
+          body: chat.title,
+        })
+      setState(
+        "chats",
+        (c) => c.id === chat.id,
+        "messages",
+        (m) => m.id === message.id,
+        {
+          ...(event.runID ? { runID: event.runID } : {}),
+          updated: Date.now(),
+          status: next,
+          activity: [...(message.activity || []).slice(-79), event],
+        },
+      )
+      if (event.threadID) setState("chats", (c) => c.id === chat.id, "threadID", event.threadID)
+      if (event.runID) save()
+    })
+    const timer = setInterval(() => {
+      if (!document.hidden) void refresh()
+    }, 5000)
+    const visible = () => {
+      if (!document.hidden) void refresh()
+    }
+    document.addEventListener("visibilitychange", visible)
+    window.addEventListener("pagehide", save)
+    onCleanup(() => {
+      unsubscribe?.()
+      clearInterval(timer)
+      document.removeEventListener("visibilitychange", visible)
+      window.removeEventListener("pagehide", save)
+    })
+  })
+  onCleanup(() => {
+    save()
+    persistence.current?.close()
+    life.active = false
+    life.epoch++
+  })
+
+  function choose(agent: Record<string, unknown>, fresh = false) {
+    const agentID = paasText(agent.id)
+    const existing = state.chats.find((c) => c.agentID === agentID && !c.archived)
+    if (!fresh && existing) {
+      activate(existing.id)
+      return
+    }
+    const chat: ResearchChat = {
+      id: crypto.randomUUID(),
+      agentID,
+      name: paasText(agent.name),
+      title: "新会话",
+      threadID: "",
+      draft: "",
+      files: [],
+      messages: [],
+    }
+    setState("chats", (chats) => [...chats, chat])
+    activate(chat.id)
+  }
+  function mergeRuns(chatID: string, runs: Record<string, unknown>[], observed: Map<string, number | undefined>) {
+    for (const source of runs) {
+      const run: Record<string, unknown> = paasRun(source)
+      const chat = state.chats.find((c) => c.id === chatID)!
+      if (paasText(run.agent_id) && run.agent_id !== chat.agentID) throw new Error("会话记录的智能体不匹配。")
+      const existing = chat.messages.find((m) => m.role === "assistant" && m.runID === run.run_id)
+      if (existing) {
+        if (observed.has(existing.id) && existing.updated !== observed.get(existing.id)) continue
+        update(chatID, existing.id, run, false)
+        continue
+      }
+      const userID = crypto.randomUUID()
+      const status = paasStatus(run)
+      setState(
+        "chats",
+        (c) => c.id === chatID,
+        "messages",
+        (rows) => [
+          ...rows,
+          { id: userID, role: "user" as const, text: paasText(run.input), runID: paasText(run.run_id) },
+          {
+            id: crypto.randomUUID(),
+            role: "assistant" as const,
+            replyTo: userID,
+            runID: paasText(run.run_id),
+            text: paasText(run.output),
+            status,
+            started:
+              !paasTerminalStatuses.has(status) || run.completed_at || run.updated_at
+                ? Date.parse(paasText(run.created_at)) || undefined
+                : undefined,
+            updated: Date.parse(paasText(run.completed_at) || paasText(run.updated_at)) || undefined,
+          },
+        ],
+      )
+    }
+  }
+  async function loadThread(
+    agent: Record<string, unknown>,
+    threadID: string,
+    title: string,
+    ticket: ReturnType<typeof beginNavigation>,
+    focusRun = "",
+  ) {
+    const existing = state.chats.find((c) => c.agentID === agent.id && c.threadID === threadID)
+    if (existing) hydrate(existing)
+    const observed = new Map(existing?.messages.map((m) => [m.id, m.updated]))
+    if (existing && selected(ticket)) show(existing.id)
+    setState("syncing", threadID)
+    try {
+      const result = await props.api!.request({ action: "thread-runs", agentID: paasText(agent.id), threadID })
+      if (!selected(ticket)) return
+      if (paasRecord(result)?.thread_id !== threadID) throw new Error("会话编号不匹配,请刷新历史。")
+      const runs = paasRows(result, "runs")
+      // Validate the full response before touching a cached conversation.
+      runs.forEach((run) => {
+        const value = paasRun(run)
+        if (value.agent_id && value.agent_id !== agent.id) throw new Error("会话记录的智能体不匹配。")
+      })
+      const chat = state.chats.find((c) => c.agentID === agent.id && c.threadID === threadID)
+      const id = chat?.id || crypto.randomUUID()
+      if (!chat)
+        setState("chats", (rows) => [
+          ...rows,
+          {
+            id,
+            agentID: paasText(agent.id),
+            name: paasText(agent.name),
+            title,
+            threadID,
+            draft: "",
+            files: [],
+            messages: [],
+          },
+        ])
+      if (chat?.cache?.loaded === false) setState("chats", (c) => c.id === id, "cache", { ...chat.cache, loaded: true })
+      mergeRuns(id, runs, observed)
+      show(id)
+      setState("focusRun", focusRun)
+      save()
+    } catch (error) {
+      if (selected(ticket)) setState("error", error instanceof Error ? error.message : "会话读取失败,本地草稿仍保留。")
+    } finally {
+      if (selected(ticket)) setState("syncing", "")
+    }
+  }
+  async function restore(agent: Record<string, unknown>, threadID: string, title: string) {
+    return loadThread(agent, threadID, title, beginNavigation())
+  }
+  async function openTask(agent: Record<string, unknown>, runID: string) {
+    const ticket = beginNavigation()
+    setState({ error: "", focusRun: "" })
+    try {
+      const run: Record<string, unknown> = await paasRunDetail(props.api!, paasText(agent.id), runID)
+      if (!selected(ticket)) return
+      const thread = paasText(run.thread_id) || paasText(run.session_id)
+      if (thread) return loadThread(agent, thread, paasText(run.input) || "研究任务", ticket, runID)
+      const existing = state.chats.find((c) => c.agentID === agent.id && c.messages.some((m) => m.runID === runID))
+      const id = existing?.id || crypto.randomUUID()
+      if (!existing)
+        setState("chats", (rows) => [
+          ...rows,
+          {
+            id,
+            agentID: paasText(agent.id),
+            name: paasText(agent.name),
+            title: paasText(run.input) || "研究任务",
+            threadID: "",
+            draft: "",
+            files: [],
+            messages: [],
+          },
+        ])
+      mergeRuns(id, [run], new Map(existing?.messages.map((m) => [m.id, m.updated])))
+      show(id)
+      setState("focusRun", runID)
+    } catch (error) {
+      if (selected(ticket)) setState("error", error instanceof Error ? error.message : "无法打开任务")
+    }
+  }
+  async function send() {
+    const chat = current()
+    if (!chat || (!chat.draft.trim() && !chat.reference?.text) || job(chat) || !props.connected || !props.api) return
+    const input = chat.reference?.text
+      ? `${chat.draft.trim() || "请继续完善研究方案。"}\n\n引用已有研究报告:\n${chat.reference.text}`
+      : chat.draft.trim()
+    if (input.length > 100000) {
+      setState("error", "单次任务最多支持 100000 个字符,可将较长内容作为研究材料上传。")
+      return
+    }
+    life.navigation++
+    setState("syncing", "")
+    const epoch = life.epoch
+    const files = structuredClone(unwrap(chat.files)),
+      executionID = crypto.randomUUID(),
+      id = crypto.randomUUID(),
+      userID = crypto.randomUUID()
+    const threadID = chat.threadID,
+      agentID = chat.agentID,
+      chatID = chat.id
+    setState("chats", (c) => c.id === chatID, {
+      draft: "",
+      reference: undefined,
+      files: [],
+      title: chat.messages.length || chat.titleManual ? chat.title : input.slice(0, 32),
+      messages: [
+        ...chat.messages,
+        { id: userID, role: "user", text: input },
+        {
+          id,
+          role: "assistant",
+          text: "",
+          status: "submitting",
+          executionID,
+          requestID: executionID,
+          replyTo: userID,
+          started: Date.now(),
+          updated: Date.now(),
+          submitted: { input, files },
+          activity: [],
+        },
+      ],
+    })
+    save()
+    try {
+      const result = paasRecord(
+        await props.api.request({
+          action: "execute",
+          agentID,
+          input,
+          files,
+          threadID: threadID || undefined,
+          executionID,
+          requestID: executionID,
+          effort: chat.effort,
+        }),
+      )
+      if (!life.active || epoch !== life.epoch) return
+      if (!result) throw new Error("平台未返回有效记录,请核对任务状态。")
+      const runID = paasText(result.run_id) || paasText(result.id)
+      if (runID)
+        setState(
+          "chats",
+          (c) => c.id === chatID,
+          "messages",
+          (m) => m.id === id,
+          "runID",
+          runID,
+        )
+      update(chatID, id, result)
+    } catch (error) {
+      if (life.active && epoch === life.epoch)
+        setState(
+          "chats",
+          (c) => c.id === chatID,
+          "messages",
+          (m) => m.id === id,
+          {
+            status:
+              error instanceof Error && /HTTP (400|401|403|404|413|422)\b/.test(error.message) ? "failed" : "unknown",
+            error: error instanceof Error ? error.message : "提交状态未确认,请核对平台任务。",
+            updated: Date.now(),
+          },
+        )
+    } finally {
+      if (life.active && epoch === life.epoch) {
+        save()
+        const message = state.chats.find((c) => c.id === chatID)?.messages.find((m) => m.id === id)
+        if (message?.status === "unknown" && !message.runID) void lookup(chatID, id)
+      }
+    }
+  }
+  function recover(message: ResearchMessage) {
+    const chat = current()
+    if (!chat || !message.submitted) return
+    setState("chats", (c) => c.id === chat.id, {
+      draft: !chat.draft
+        ? message.submitted.input
+        : chat.draft.includes(message.submitted.input)
+          ? chat.draft
+          : `${message.submitted.input}\n\n补充要求:\n${chat.draft}`,
+      files: [
+        ...chat.files,
+        ...structuredClone(unwrap(message.submitted.files)).filter(
+          (file) => !chat.files.some((existing) => existing.file_id === file.file_id),
+        ),
+      ],
+    })
+    save()
+  }
+  function rename(title: string) {
+    const chat = current()
+    if (!chat || !title.trim()) return
+    setState("chats", (c) => c.id === chat.id, { title: title.trim(), titleManual: true })
+    save()
+  }
+  function archive() {
+    const chat = current()
+    if (!chat) return
+    setState("chats", (c) => c.id === chat.id, "archived", !chat.archived)
+    save()
+  }
+  function continueFrom(message: ResearchMessage) {
+    const chat = current()
+    if (!chat || !message.text) return
+    setState("chats", (c) => c.id === chat.id, "reference", { messageID: message.id, text: message.text })
+    save()
+  }
+  return {
+    state,
+    setState,
+    current,
+    job,
+    choose,
+    activate,
+    restore,
+    openTask,
+    lookup,
+    send,
+    refresh,
+    update,
+    recover,
+    rename,
+    archive,
+    continueFrom,
+    save,
+  }
+}

Разница между файлами не показана из-за своего большого размера
+ 738 - 587
packages/app/src/pages/paas/chat.tsx


+ 20 - 24
packages/app/src/pages/paas/controller.ts

@@ -1,6 +1,6 @@
 import { createMemo, onCleanup, onMount } from "solid-js"
 import { createStore, reconcile } from "solid-js/store"
-import { paasRecord, paasRows, paasRun, paasStatus, paasText, type PaasPlatform } from "@/paas"
+import { paasRecord, paasRows, paasRun, paasRunDetail, paasStatus, paasText, type PaasPlatform } from "@/paas"
 
 export function createPaasWorkspace(api: PaasPlatform | undefined) {
   const [state, setState] = createStore({
@@ -9,6 +9,7 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
     apiKey: "",
     remember: true,
     remembered: false,
+    scope: "",
     connected: false,
     busy: "",
     error: "",
@@ -43,7 +44,7 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
           lifecycle.polling = false
         })
     }
-    const timer = window.setInterval(() => void refresh(), 2000)
+    const timer = window.setInterval(() => void refresh(), 30000)
     const visible = () => void refresh()
     document.addEventListener("visibilitychange", visible)
     onCleanup(() => {
@@ -113,7 +114,13 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
       })
       if (!connection) return
       if (!lifecycle.active) return
-      setState({ connected: true, url: connection.url, remembered: !!connection.remembered, page: "chat" })
+      setState({
+        connected: true,
+        scope: connection.scope || "",
+        url: connection.url,
+        remembered: !!connection.remembered,
+        page: "chat",
+      })
       await catalog().catch((error: unknown) => {
         if (lifecycle.active) setState("catalogError", error instanceof Error ? error.message : "目录读取失败。")
       })
@@ -161,29 +168,18 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
         if (!lifecycle.active || state.agentID !== agentID) return
         setState({ runs, historyLoaded: true, updated: new Date().toLocaleTimeString(), selected: undefined })
       }),
-    selectRun: (id: string) => {
-      const run = state.runs.find((row) => (paasText(row.run_id) || paasText(row.id)) === id)
-      setState("selected", run ? { ...run, run_id: id } : { run_id: id })
-    },
-    updateRun: (run: Record<string, unknown>) => {
-      const id = paasText(run.run_id) || paasText(run.id)
-      if (!id) return
-      const merge = (row: Record<string, unknown>) => ({
-        ...row,
-        ...run,
-        input: paasText(run.input) || paasText(row.input),
-      })
-      setState("runs", (rows) =>
-        rows.map((row) => ((paasText(row.run_id) || paasText(row.id)) === id ? merge(row) : row)),
-      )
-      const selected = state.selected
-      if (selected && (paasText(selected.run_id) || paasText(selected.id)) === id) setState("selected", merge(selected))
-    },
-    verify: () =>
-      perform("检查资源", async () => {
+    detail: (id: string) =>
+      perform("读取详情", async () => {
+        setState("selected", undefined)
+        const agentID = state.agentID
+        const result = await paasRunDetail(api!, agentID, id)
+        if (lifecycle.active && state.agentID === agentID) setState("selected", result)
+      }),
+    verify: (checkModel = false) =>
+      perform(checkModel ? "测试模型连接" : "检查资源", async () => {
         setState({ checks: [], verified: false })
         const agentID = state.agentID
-        const result = await api!.request({ action: "verify", agentID }).catch((error: unknown) => {
+        const result = await api!.request({ action: "verify", agentID, checkModel }).catch((error: unknown) => {
           if (error instanceof Error && /HTTP 404\b/.test(error.message))
             throw new Error(
               "当前平台未提供资源检查接口(verify)。Skill / MCP 管理需使用平台管理页面;此处不能判断资源是否可用。",

+ 179 - 146
packages/app/src/pages/paas/index.tsx

@@ -4,7 +4,7 @@ import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu"
 import { Icon } from "@opencode-ai/ui/icon"
 import { base64Encode } from "@opencode-ai/core/util/encode"
 import { A, useNavigate } from "@solidjs/router"
-import { For, Match, Show, Switch, onCleanup } from "solid-js"
+import { For, Match, Show, Switch, createEffect, on, onCleanup } from "solid-js"
 import { createStore } from "solid-js/store"
 import { useGlobal } from "@/context/global"
 import { usePlatform } from "@/context/platform"
@@ -14,10 +14,11 @@ import { useTabs } from "@/context/tabs"
 import { paasRecord, paasStatus, paasStatuses, paasText } from "@/paas"
 import { showToast } from "@/utils/toast"
 import { createPaasWorkspace } from "./controller"
-import { PaasRunPanel } from "./run-panel"
 import { PaasChat } from "./chat"
+import { createTaskIndex, PaasTasks } from "./tasks"
 import { PaasAgentEdit } from "./agent-edit"
 import { PaasPacks } from "./packs"
+import { ResearchIssue } from "./issue"
 import "./paas.css"
 
 const pages = [
@@ -25,9 +26,8 @@ const pages = [
   { id: "overview", icon: "prompt", name: "工作台" },
   { id: "agents", icon: "brain", name: "智能体" },
   { id: "tasks", icon: "task", name: "平台任务" },
-  { id: "resources", icon: "mcp", name: "Skill / MCP" },
+  { id: "resources", icon: "mcp", name: "资源检查" },
   { id: "connection", icon: "server", name: "平台连接" },
-  { id: "schedules", icon: "reset", name: "定时任务" },
 ] as const
 
 export default function PaasWorkspace(props: { standalone?: boolean; onOpenDeveloper?: () => void } = {}) {
@@ -41,7 +41,49 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
   const workspace = createPaasWorkspace(platform.paas)
   const state = workspace.state
   const disabled = () => !!state.busy || !state.connected
-  const [ui, setUI] = createStore({ chatAgentID: "", openingWorkspace: false, editAgentID: "" })
+  const [ui, setUI] = createStore({
+    notices: [] as Record<string, unknown>[],
+    chatTask: undefined as Record<string, unknown> | undefined,
+    chatAgentID: "",
+    openingWorkspace: false,
+    editAgentID: "",
+    editReturn: "agents",
+  })
+  const tasks = createTaskIndex({
+    api: platform.paas,
+    onNotice: (run) => {
+      setUI("notices", (rows) => [
+        ...rows.filter((row) => row.run_id !== run.run_id || row.agent_id !== run.agent_id).slice(-9),
+        run,
+      ])
+      if (document.hidden && state.page !== "chat")
+        void platform
+          .notify(
+            paasStatus(run).startsWith("waiting") ? "研究任务需要确认" : "研究任务已有结果",
+            paasText(run.input) || "打开任务查看",
+            () => {
+              setUI("chatTask", run)
+              workspace.setState("page", "chat")
+            },
+          )
+          .catch(() => undefined)
+    },
+    get connected() {
+      return state.connected
+    },
+    get scope() {
+      return state.scope
+    },
+    get agents() {
+      return state.agents
+    },
+  })
+  createEffect(
+    on(
+      () => state.scope,
+      () => setUI({ notices: [], chatTask: undefined }),
+    ),
+  )
   const lifecycle = { active: true }
   onCleanup(() => (lifecycle.active = false))
 
@@ -156,6 +198,17 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
       <main class="paas-main">
         <header class="paas-topbar">
           <span>{state.page === "edit-agent" ? "编辑智能体" : pages.find((page) => page.id === state.page)?.name}</span>
+          <Show when={state.connected}>
+            <button
+              class="paas-task-shortcut"
+              onClick={() => {
+                workspace.setState("page", "tasks")
+                void tasks.refresh()
+              }}
+            >
+              {tasks.running().length} 进行中 · {tasks.waiting().length} 待确认
+            </button>
+          </Show>
           <button
             class="paas-topbar-connection"
             aria-label="查看平台连接状态"
@@ -166,15 +219,42 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
           </button>
         </header>
         <div class="paas-content">
+          <Show when={state.connected && ui.notices.length && state.page !== "chat"}>
+            <div class="paas-global-notices" aria-label="任务通知">
+              <For each={ui.notices}>
+                {(run) => (
+                  <div role="status">
+                    <button
+                      onClick={() => {
+                        setUI("chatTask", run)
+                        workspace.setState("page", "chat")
+                        setUI("notices", (rows) => rows.filter((row) => row !== run))
+                      }}
+                    >
+                      {paasStatuses[paasStatus(run)] || "任务更新"} · {paasText(run.input) || "研究任务"}
+                    </button>
+                    <button
+                      aria-label="关闭任务通知"
+                      onClick={() => setUI("notices", (rows) => rows.filter((row) => row !== run))}
+                    >
+                      ×
+                    </button>
+                  </div>
+                )}
+              </For>
+            </div>
+          </Show>
           <Show when={!platform.paas}>
             <div class="paas-notice">
               请在桌面客户端中连接平台。当前 Web 页面可查看工作台入口,尚未接入平台传输服务。
             </div>
           </Show>
           <Show when={state.error}>
-            <div role="alert" class="paas-error">
-              {state.error}
-            </div>
+            <ResearchIssue
+              message={state.error}
+              onConnection={() => workspace.setState("page", "connection")}
+              onTasks={() => workspace.setState("page", "tasks")}
+            />
           </Show>
           <Show when={state.busy}>
             <p role="status" class="paas-muted">
@@ -186,12 +266,25 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
             <PaasChat
               api={platform.paas}
               connected={state.connected}
+              scope={state.scope}
+              onOpenTasks={() => {
+                workspace.setState("page", "tasks")
+                void tasks.refresh()
+              }}
+              onShowChat={() => workspace.setState("page", "chat")}
+              onConnection={() => workspace.setState("page", "connection")}
+              openTask={ui.chatTask}
+              onTaskOpened={() => setUI("chatTask", undefined)}
               visible={state.page === "chat"}
               agents={state.agents}
               openAgentID={ui.chatAgentID}
               onAgentOpened={() => setUI("chatAgentID", "")}
               onOpenAgentPacks={openAgentPacks}
               onOpenWorkspace={platform.paas ? openAgentWorkspace : undefined}
+              onEditAgent={(id) => {
+                setUI({ editAgentID: id, editReturn: "chat" })
+                workspace.setState("page", "edit-agent")
+              }}
               workspaceDisabled={ui.openingWorkspace || (!props.standalone && !localServer())}
             />
           </div>
@@ -200,13 +293,19 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
               <div class="paas-section-title">
                 <div>
                   <h1>平台连接</h1>
-                  <p>管理当前窗口使用的 AgentPaaS 连接。</p>
+                  <p>连接团队平台,选择智能体,即可开始研究。</p>
                 </div>
               </div>
+              <ol class="paas-start-steps" aria-label="开始研究的三个步骤">
+                <li data-ready={state.connected}>1 · 连接平台</li>
+                <li data-ready={state.connected && !!state.agents.length}>2 · 选择智能体</li>
+                <li>3 · 添加材料,开始研究</li>
+              </ol>
               <section class="paas-panel paas-connect paas-connection-page" aria-label="平台连接">
                 <div>
                   <strong>{state.connected ? "连接信息" : "连接你的 AgentPaaS"}</strong>
-                  <p>支持连接本机或远程平台。记住连接后,下次打开可自动连接。</p>
+                  <p>填写管理员提供的平台地址与访问凭证,即可开始研究。已有本机平台服务可直接一键连接。</p>
+                  <p class="paas-muted">桌面端不会自动安装平台服务。记住连接后,下次打开可自动进入工作台。</p>
                 </div>
                 <Show
                   when={!state.connected}
@@ -255,7 +354,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                         checked={state.remember}
                         onChange={(event) => workspace.setState("remember", event.currentTarget.checked)}
                       />
-                      记住连接(系统安全存储可用时加密保存)
+                      记住连接(加密保存凭证)
                     </label>
                     <button class="paas-primary" type="submit" disabled={!platform.paas || !!state.busy}>
                       连接平台
@@ -271,6 +370,12 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 </Show>
               </section>
 
+              <details class="paas-panel">
+                <summary>还没有平台地址,或本机连接失败?</summary>
+                <p>使用团队服务时,请向管理员获取平台地址和平台访问凭证;这里填写的不是模型 API Key。</p>
+                <p>已有本机部署时,先启动 AgentPaaS 服务,再点击“一键连接本机”。桌面端不会替你安装后台服务。</p>
+                <p>模型、工具和知识库在智能体设置中管理。资源检查可帮助定位问题,不是开始研究的必经审批。</p>
+              </details>
               <Show when={state.connected}>
                 <p class="paas-muted">已加载 {state.agents.length} 个智能体。重新连接后可继续查看平台历史会话。</p>
                 <button onClick={() => workspace.setState("page", "chat")}>进入会话</button>
@@ -281,6 +386,28 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 <h1>今天想探索什么?</h1>
                 <p>从科研探索或数据问答开始。</p>
               </div>
+              <section class="paas-panel paas-start-card">
+                <h2>开始一次研究</h2>
+                <p>
+                  {state.connected
+                    ? "平台已连接。选择智能体后,描述目标或上传资料即可开始;也可以先检查模型与资源。"
+                    : "先连接已部署的平台,再选择适合任务的智能体。"}
+                </p>
+                <div class="paas-actions">
+                  <button
+                    class="paas-primary"
+                    onClick={() => workspace.setState("page", state.connected ? "agents" : "connection")}
+                  >
+                    {state.connected ? "选择智能体" : "连接平台"}
+                  </button>
+                  <button disabled={!state.connected} onClick={() => workspace.setState("page", "resources")}>
+                    检查资源(可选)
+                  </button>
+                  <button disabled={!state.connected} onClick={() => workspace.setState("page", "chat")}>
+                    继续研究
+                  </button>
+                </div>
+              </section>
               <div class="paas-scenarios">
                 <For
                   each={[
@@ -377,7 +504,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                       function openTasks() {
                         workspace.selectAgent(id())
                         workspace.setState("page", "tasks")
-                        void workspace.history()
+                        void tasks.refresh()
                       }
 
                       function openResources() {
@@ -436,7 +563,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                               disabled={disabled()}
                               aria-label={`编辑 ${name()}`}
                               onClick={() => {
-                                setUI("editAgentID", id())
+                                setUI({ editAgentID: id(), editReturn: "agents" })
                                 workspace.setState("page", "edit-agent")
                               }}
                             >
@@ -457,9 +584,9 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 <PaasAgentEdit
                   api={api}
                   agentID={ui.editAgentID}
-                  onClose={() => workspace.setState("page", "agents")}
+                  onClose={() => workspace.setState("page", ui.editReturn)}
                   onSaved={async () => {
-                    workspace.setState("page", "agents")
+                    workspace.setState({ page: ui.editReturn, verified: false, checks: [] })
                     showToast({ title: "智能体配置已保存" })
                     await workspace.catalog()
                   }}
@@ -467,15 +594,21 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
               )}
             </Match>
 
-            <Match when={state.page === "tasks" || state.page === "resources"}>
+            <Match when={state.page === "tasks"}>
+              <PaasTasks
+                index={tasks}
+                connected={state.connected}
+                onOpen={(run) => {
+                  setUI("chatTask", run)
+                  workspace.setState("page", "chat")
+                }}
+              />
+            </Match>
+            <Match when={state.page === "resources"}>
               <div class="paas-section-title">
                 <div>
-                  <h1>{state.page === "tasks" ? "平台任务" : "Skill / MCP 资源"}</h1>
-                  <p>
-                    {state.page === "tasks"
-                      ? "按智能体读取平台返回的历史记录,打开任务查看最新快照。"
-                      : "检查智能体当前的必需与可选依赖,不会调用模型或运行任务。"}
-                  </p>
+                  <h1>资源检查</h1>
+                  <p>核对模型、知识库与 Skill / MCP 的可用状态;检查不会创建研究任务。</p>
                 </div>
               </div>
               <div class="paas-toolbar">
@@ -486,118 +619,46 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                     disabled={disabled()}
                     onChange={(event) => workspace.selectAgent(event.currentTarget.value)}
                   >
-                    <option value="">请选择智能体</option>
                     <For each={state.agents}>
                       {(agent) => <option value={paasText(agent.id)}>{paasText(agent.name)}</option>}
                     </For>
                   </select>
                 </label>
+                <button disabled={disabled() || !state.agentID} onClick={() => void workspace.verify()}>
+                  检查资源
+                </button>
+                <button disabled={disabled() || !state.agentID} onClick={() => void workspace.verify(true)}>
+                  测试模型连接
+                </button>
                 <button
-                  class="paas-primary"
                   disabled={disabled() || !state.agentID}
-                  onClick={() => (state.page === "tasks" ? workspace.history() : workspace.verify())}
+                  onClick={() => {
+                    setUI({ editAgentID: state.agentID, editReturn: "resources" })
+                    workspace.setState("page", "edit-agent")
+                  }}
                 >
-                  {state.page === "tasks" ? "刷新任务" : "检查资源"}
+                  配置模型与知识库
                 </button>
-                <Show when={state.page === "tasks" && state.updated}>
-                  <small>列表同步于 {state.updated} · 手动刷新</small>
-                </Show>
-              </div>
-              <Show when={state.page === "tasks"}>
-                <div class="paas-toolbar">
-                  <label>
-                    搜索当前列表
-                    <input
-                      type="search"
-                      placeholder="任务编号、问题或状态"
-                      value={state.search}
-                      onInput={(event) => workspace.setState("search", event.currentTarget.value)}
-                    />
-                  </label>
-                  <label>
-                    任务状态
-                    <select
-                      value={state.filter}
-                      onChange={(event) => workspace.setState("filter", event.currentTarget.value)}
-                    >
-                      <option value="all">全部状态</option>
-                      <For each={Object.entries(paasStatuses)}>
-                        {([id, label]) => <option value={id}>{label}</option>}
-                      </For>
-                    </select>
-                  </label>
-                </div>
-                <Show
-                  when={workspace.filtered().length}
-                  fallback={
-                    <Empty
-                      title={state.historyLoaded ? "没有匹配的任务" : "选择智能体后刷新任务"}
-                      text={
-                        state.historyLoaded
-                          ? "仅展示此次平台返回的记录。可调整筛选或再次刷新。"
-                          : "任务查询不会重新执行或取消远端任务。"
-                      }
-                    />
-                  }
+                <button
+                  disabled={disabled() || !state.agentID}
+                  onClick={() => {
+                    setUI("chatAgentID", state.agentID)
+                    workspace.setState("page", "chat")
+                  }}
                 >
-                  <div class="paas-table-wrap">
-                    <table>
-                      <thead>
-                        <tr>
-                          <th>任务 / 问题</th>
-                          <th>状态</th>
-                          <th>操作</th>
-                        </tr>
-                      </thead>
-                      <tbody>
-                        <For each={workspace.filtered()}>
-                          {(run) => (
-                            <tr>
-                              <td>
-                                <strong>{paasText(run.input) || paasText(run.run_id) || "任务编号未提供"}</strong>
-                                <code>{paasText(run.run_id)}</code>
-                              </td>
-                              <td>
-                                <Status run={run} />
-                              </td>
-                              <td>
-                                <button
-                                  disabled={!!state.busy || !paasText(run.run_id)}
-                                  onClick={() => workspace.selectRun(paasText(run.run_id))}
-                                >
-                                  查看详情
-                                </button>
-                              </td>
-                            </tr>
-                          )}
-                        </For>
-                      </tbody>
-                    </table>
-                  </div>
-                </Show>
-                <Show when={state.selected}>
-                  {(run) => (
-                    <Show when={platform.paas}>
-                      <PaasRunPanel
-                        api={platform.paas!}
-                        agentID={state.agentID}
-                        runID={paasText(run().run_id)}
-                        initial={run()}
-                        showGoal
-                        onUpdate={workspace.updateRun}
-                        onClose={() => workspace.setState("selected", undefined)}
-                      />
-                    </Show>
-                  )}
-                </Show>
-              </Show>
+                  直接开始研究
+                </button>
+              </div>
+              <p class="paas-muted">
+                “检查资源”不调用模型;“测试模型连接”会发送少量测试请求,消耗模型额度。可跳过检查,直接开始研究。
+              </p>
               <Show when={state.page === "resources"}>
                 <Show
                   when={state.verified}
                   fallback={
                     <Empty
                       title="先检查智能体资源"
-                      text="这里展示平台预检查报告。资源的编辑、发布和绑定管理尚未接入。"
+                      text="选择智能体后可检查绑定资源;模型配置与知识库绑定可在上方设置入口修改。"
                     />
                   }
                 >
@@ -633,26 +694,6 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 </Show>
               </Show>
             </Match>
-
-            <Match when={state.page === "schedules"}>
-              <div class="paas-heading">
-                <span class="paas-eyebrow">持续跟进</span>
-                <h1>定时任务</h1>
-                <p>让平台按计划执行科研跟进与数据分析。</p>
-              </div>
-              <Empty
-                title="定时调度尚未接入"
-                text="当前桥接没有可用的定时任务管理接口。这里不会保存仅在本机计时的规则,也不会承诺关闭客户端后自动运行。"
-              />
-              <div class="paas-panel">
-                <h2>接入后将支持</h2>
-                <ul>
-                  <li>按时区和频率配置任务,预览下次触发时间</li>
-                  <li>固定智能体、材料与 Skill / MCP 配置</li>
-                  <li>查看每次运行、失败原因与待审批事项</li>
-                </ul>
-              </div>
-            </Match>
           </Switch>
         </div>
       </main>
@@ -671,11 +712,3 @@ function Empty(props: { title: string; text: string }) {
     </div>
   )
 }
-
-function Status(props: { run: Record<string, unknown> }) {
-  return (
-    <span class="paas-badge" data-status={paasStatus(props.run)}>
-      {paasStatuses[paasStatus(props.run)] || `状态待核查 (${paasStatus(props.run)})`}
-    </span>
-  )
-}

+ 57 - 0
packages/app/src/pages/paas/issue.tsx

@@ -0,0 +1,57 @@
+import { Show } from "solid-js"
+
+export function researchIssue(message: string) {
+  if (/insufficient.balance|余额|欠费/i.test(message))
+    return { title: "模型账户额度不足", help: "检查模型账户余额后再继续;已生成的内容可先保存。", action: "settings" }
+  if (/budget|token.*limit|额度|预算|上限/i.test(message))
+    return {
+      title: "本次任务达到资源边界",
+      help: "先查看已有成果;需要继续时调整研究设置,再基于成果续研。",
+      action: "settings",
+    }
+  if (/401|凭证|API.?Key/i.test(message))
+    return { title: "需要更新平台连接", help: "核对平台地址与访问凭证,重新连接后可同步原任务。", action: "connection" }
+  if (/403|权限|ACTIVE_PROBE_FORBIDDEN/i.test(message))
+    return { title: "当前账号无此操作权限", help: "其他可用功能不受影响;请联系管理员开通所需权限。", action: "" }
+  if (/429|频繁|rate.limit/i.test(message))
+    return { title: "平台暂时繁忙", help: "稍后重试;发送结果不确定时先核对任务,避免重复执行。", action: "tasks" }
+  if (/parse|解析|格式|文档|材料|文件.*(失败|超过)/i.test(message))
+    return { title: "需要检查输入材料", help: "检查文件格式、大小或内容;已成功上传的材料可以保留。", action: "" }
+  if (/network|fetch|timeout|连接|网络|超时|中断|503|502/i.test(message))
+    return {
+      title: "暂时无法同步平台",
+      help: "草稿与已有成果仍保留。先核对原任务状态,连接恢复后继续。",
+      action: "tasks",
+    }
+  if (/revision|review|校验|修订|审阅/i.test(message))
+    return { title: "方案还有待处理事项", help: "查看审阅意见,可导出当前成果或补充要求后继续研究。", action: "" }
+  return { title: "本次操作未完成", help: "当前内容不会自动清空,请查看详情后重试。", action: "" }
+}
+
+export function ResearchIssue(props: {
+  message: string
+  onSettings?: () => void
+  onConnection?: () => void
+  onTasks?: () => void
+}) {
+  const issue = () => researchIssue(props.message)
+  return (
+    <div class="paas-notice paas-issue" role="alert">
+      <strong>{issue().title}</strong>
+      <p>{issue().help}</p>
+      <Show when={issue().action === "settings" && props.onSettings}>
+        <button onClick={props.onSettings}>调整研究设置</button>
+      </Show>
+      <Show when={issue().action === "connection" && props.onConnection}>
+        <button onClick={props.onConnection}>检查平台连接</button>
+      </Show>
+      <Show when={issue().action === "tasks" && props.onTasks}>
+        <button onClick={props.onTasks}>核对原任务</button>
+      </Show>
+      <details>
+        <summary>查看错误详情</summary>
+        <p>{props.message}</p>
+      </details>
+    </div>
+  )
+}

+ 0 - 20
packages/app/src/pages/paas/markdown.tsx

@@ -1,20 +0,0 @@
-import { Markdown } from "@opencode-ai/session-ui/markdown"
-import { usePlatform } from "@/context/platform"
-
-export function PaasMarkdown(props: { text: string; class?: string }) {
-  const platform = usePlatform()
-  return (
-    <Markdown
-      class={props.class ?? "paas-markdown"}
-      text={props.text}
-      onClick={(event) => {
-        const anchor = event.target instanceof Element ? event.target.closest("a[href]") : null
-        if (!(anchor instanceof HTMLAnchorElement)) return
-        event.preventDefault()
-        const url = new URL(anchor.href)
-        if (url.protocol !== "http:" && url.protocol !== "https:") return
-        platform.openExternal(url.toString())
-      }}
-    />
-  )
-}

+ 158 - 0
packages/app/src/pages/paas/materials.ts

@@ -0,0 +1,158 @@
+import { createEffect, on, onCleanup, onMount } from "solid-js"
+import { createStore } from "solid-js/store"
+import { paasRecord, type PaasFile, type PaasPlatform } from "@/paas"
+
+type Upload = {
+  id: string
+  chatID: string
+  agentID: string
+  threadID: string
+  name: string
+  size: number
+  selectionID?: string
+  state: "queued" | "uploading" | "done" | "failed"
+  sent: number
+  error: string
+}
+export function createMaterials(props: {
+  api?: PaasPlatform
+  scope?: string
+  connected: boolean
+  onFile: (chatID: string, file: PaasFile) => void
+}) {
+  const [state, setState] = createStore({ uploads: [] as Upload[], error: "" })
+  const sources = new Map<string, File>()
+  const life = { epoch: 0, active: true }
+  createEffect(
+    on(
+      () => props.scope,
+      () => {
+        life.epoch++
+        sources.clear()
+        setState({ uploads: [], error: "" })
+      },
+    ),
+  )
+  createEffect(
+    on(
+      () => props.connected,
+      (connected) => {
+        if (!connected) {
+          life.epoch++
+          setState("uploads", (row) => ["queued", "uploading"].includes(row.state), {
+            state: "failed",
+            error: "连接已中断,重新连接后可重试上传。",
+          })
+        }
+      },
+    ),
+  )
+  onMount(() => {
+    const off = props.api?.onUploadProgress?.((event) =>
+      setState("uploads", (row) => row.id === event.uploadID, "sent", event.sent),
+    )
+    onCleanup(() => off?.())
+  })
+  onCleanup(() => {
+    life.active = false
+    sources.clear()
+  })
+  async function upload(id: string) {
+    const row = state.uploads.find((item) => item.id === id)
+    if (!row || row.state === "uploading" || !props.api || !props.connected) return
+    const epoch = life.epoch
+    setState("uploads", (item) => item.id === id, { state: "uploading", sent: 0, error: "" })
+    try {
+      const capabilities = paasRecord(await props.api.request({ action: "file-capabilities" }).catch(() => undefined))
+      const limit = Number(capabilities?.direct_upload_max_bytes) || 256 * 1024 * 1024
+      if (row.size > limit)
+        throw new Error(`超过平台直接上传额度(${Math.floor(limit / 1024 / 1024)} MB),可压缩材料后重选。`)
+      if (!life.active || epoch !== life.epoch) return
+      const file = sources.get(id)
+      const data = file ? new Uint8Array(await file.arrayBuffer()) : undefined
+      if (!life.active || epoch !== life.epoch || !props.connected) return
+      const request = row.selectionID
+        ? {
+            action: "upload-selected" as const,
+            agentID: row.agentID,
+            threadID: row.threadID || undefined,
+            selectionID: row.selectionID,
+            uploadID: id,
+          }
+        : {
+            action: "upload-file" as const,
+            agentID: row.agentID,
+            threadID: row.threadID || undefined,
+            name: row.name,
+            data: data!,
+            uploadID: id,
+          }
+      if (!row.selectionID && !data) throw new Error("本地文件选择已失效,请重新拖入材料。")
+      const result = paasRecord(await props.api.request(request))
+      if (!life.active || epoch !== life.epoch) return
+      if (!result || typeof result.file_id !== "string") throw new Error("平台未返回材料编号,请重试。")
+      props.onFile(row.chatID, {
+        ...result,
+        file_id: result.file_id,
+        name: typeof result.name === "string" ? result.name : row.name,
+      })
+      setState("uploads", (item) => item.id === id, { state: "done", sent: row.size })
+      sources.delete(id)
+    } catch (error) {
+      if (life.active && epoch === life.epoch)
+        setState("uploads", (item) => item.id === id, {
+          state: "failed",
+          error: error instanceof Error ? error.message : "上传失败,请重试。",
+        })
+    }
+  }
+  async function add(chat: { id: string; agentID: string; threadID: string }, dropped?: File[]) {
+    if (!props.connected || !props.api) return
+    const epoch = life.epoch
+    setState("error", "")
+    try {
+      if (!dropped && !props.api.selectFiles) {
+        const files = await props.api.chooseFiles?.(chat.agentID, chat.threadID || undefined)
+        if (life.active && epoch === life.epoch) files?.forEach((file) => props.onFile(chat.id, file))
+        return
+      }
+      const selected = dropped || (await props.api.selectFiles!())
+      if (!life.active || epoch !== life.epoch) return
+      const rows = selected.map((file) => {
+        const id = crypto.randomUUID()
+        if (file instanceof File) sources.set(id, file)
+        return {
+          id,
+          chatID: chat.id,
+          agentID: chat.agentID,
+          threadID: chat.threadID,
+          name: file.name,
+          size: file.size,
+          selectionID: "selectionID" in file ? file.selectionID : undefined,
+          state: "queued" as const,
+          sent: 0,
+          error: "",
+        }
+      })
+      setState("uploads", (previous) => [...previous, ...rows])
+      for (const row of rows) {
+        if (!life.active || epoch !== life.epoch || !props.connected) break
+        await upload(row.id)
+      }
+    } catch (error) {
+      if (life.active && epoch === life.epoch)
+        setState("error", error instanceof Error ? error.message : "选择材料失败")
+    }
+  }
+  return {
+    state,
+    add,
+    upload,
+    busy: (chatID: string) =>
+      state.uploads.some((row) => row.chatID === chatID && ["queued", "uploading"].includes(row.state)),
+    remove: (id: string) => {
+      sources.delete(id)
+      setState("uploads", (rows) => rows.filter((row) => row.id !== id))
+    },
+  }
+}

+ 453 - 72
packages/app/src/pages/paas/paas.css

@@ -386,12 +386,7 @@
   background: #b8452915;
   color: #b04b38;
 }
-.paas-detail {
-  margin-top: 24px;
-}
-.paas-run-section,
-.paas-run-results,
-.paas-run-technical {
+.paas-run-results {
   margin-top: 20px;
 }
 .paas-run-files {
@@ -400,35 +395,11 @@
 .paas-run-file {
   margin-top: 8px;
 }
-.paas-run-section > h3,
 .paas-run-results > h3 {
   font-size: 14px;
   font-weight: 600;
   margin: 0 0 8px;
 }
-.paas-run-goal {
-  white-space: pre-wrap;
-  overflow-wrap: anywhere;
-  margin: 0 0 10px;
-}
-.paas-run-section .paas-markdown {
-  font-size: 15px;
-}
-.paas-run-technical dl {
-  display: grid;
-  grid-template-columns: max-content minmax(0, 1fr);
-  gap: 6px 14px;
-  margin: 10px 0 12px;
-  font-size: 13px;
-}
-.paas-run-technical dt {
-  color: var(--text-weak);
-}
-.paas-run-technical dd {
-  margin: 0;
-  min-width: 0;
-  overflow-wrap: anywhere;
-}
 .paas-workspace pre {
   white-space: pre-wrap;
   overflow-wrap: anywhere;
@@ -1853,48 +1824,6 @@
 }
 
 /* Markdown replies reuse the session renderer with the PaaS reading scale. */
-.paas-markdown {
-  width: 100%;
-  min-width: 0;
-  font-size: 16px;
-  line-height: 1.7;
-  color: var(--text-base);
-}
-.paas-markdown h1 {
-  font-size: 22px;
-  margin: 24px 0 10px;
-}
-.paas-markdown h2 {
-  font-size: 20px;
-  margin: 22px 0 10px;
-}
-.paas-markdown h3 {
-  font-size: 17px;
-  margin: 18px 0 8px;
-}
-.paas-markdown h4,
-.paas-markdown h5,
-.paas-markdown h6 {
-  font-size: 16px;
-}
-.paas-markdown p {
-  margin-bottom: 10px;
-}
-.paas-markdown a {
-  color: light-dark(#315fce, #83a8ff);
-  text-decoration: underline;
-  text-decoration-color: color-mix(in srgb, light-dark(#315fce, #83a8ff) 35%, transparent);
-  text-underline-offset: 2px;
-}
-.paas-markdown a:hover {
-  text-decoration-color: currentColor;
-}
-.paas-markdown table {
-  font-size: 15px;
-}
-.paas-markdown .shiki {
-  font-size: 13px;
-}
 .paas-workspace [data-component="markdown"] pre {
   max-height: 420px;
   white-space: pre;
@@ -1948,3 +1877,455 @@
   max-height: 280px;
   font-size: 12px;
 }
+/* Research chat keeps the composer available while background work progresses. */
+.paas-conversation {
+  position: relative;
+}
+.paas-chat-messages {
+  overflow-anchor: none;
+}
+.paas-chat-messages > div {
+  display: flex;
+  flex-direction: column;
+  gap: 22px;
+}
+.paas-chat-message {
+  min-width: 0;
+}
+.paas-report {
+  min-width: 0;
+  overflow-wrap: anywhere;
+  line-height: 1.7;
+}
+.paas-report [data-component="markdown"] {
+  font-size: 14px;
+}
+.paas-report :is(table, pre, .katex-display) {
+  max-width: 100%;
+  overflow-x: auto;
+}
+.paas-report table {
+  display: block;
+  width: max-content;
+  max-width: 100%;
+  border-collapse: collapse;
+}
+.paas-report :is(td, th) {
+  padding: 8px 12px;
+  border: 1px solid var(--border-weak-base);
+}
+.paas-report a {
+  text-decoration: underline;
+  text-underline-offset: 3px;
+}
+.paas-report pre {
+  padding: 12px;
+  border-radius: 8px;
+  background: var(--background-weak);
+}
+.paas-task-summary,
+.paas-task-counts {
+  display: flex;
+  align-items: center;
+  flex-wrap: wrap;
+  gap: 8px 16px;
+  margin: 10px 0;
+}
+.paas-task-summary {
+  color: var(--text-weak);
+  font-size: 12px;
+}
+.paas-task-summary strong {
+  color: var(--text-base);
+  font-size: 13px;
+}
+.paas-result-panel {
+  margin-top: 12px;
+}
+.paas-result-panel > summary {
+  cursor: pointer;
+  padding: 8px 0;
+  font-weight: 600;
+}
+.paas-result-panel > section {
+  margin-top: 8px;
+}
+.paas-result-panel details pre {
+  max-height: 240px;
+  overflow: auto;
+}
+.paas-suggestions {
+  display: grid;
+  gap: 10px;
+  max-width: 550px;
+  margin: 22px auto;
+}
+.paas-suggestions button {
+  text-align: left;
+  padding: 12px 16px;
+}
+.paas-upload-row {
+  display: flex;
+  align-items: center;
+  flex-wrap: wrap;
+  gap: 8px;
+  margin: 8px 0;
+}
+.paas-upload-row > span {
+  overflow-wrap: anywhere;
+  max-width: 100%;
+}
+.paas-upload-row progress {
+  width: 100px;
+  accent-color: var(--paas-directory-accent);
+}
+.paas-upload-row small {
+  color: var(--text-weak);
+}
+.paas-composer {
+  max-height: 48vh;
+  overflow-y: auto;
+  flex-shrink: 0;
+}
+.paas-composer.paas-dragging {
+  outline: 2px dashed var(--paas-directory-accent);
+  outline-offset: 3px;
+}
+.paas-composer footer {
+  align-items: center;
+  flex-wrap: wrap;
+}
+.paas-composer footer label {
+  display: flex;
+  align-items: center;
+  gap: 5px;
+  font-size: 12px;
+}
+.paas-composer footer select {
+  max-width: 180px;
+  background: transparent;
+  padding: 5px;
+}
+.paas-composer footer .paas-primary {
+  margin-left: auto;
+}
+.paas-draft-hint {
+  font-size: 12px;
+  color: var(--text-weak);
+  margin: 6px 0;
+  line-height: 1.6;
+}
+.paas-running-dot {
+  color: var(--paas-directory-accent);
+  font-size: 11px;
+}
+.paas-session-items button small {
+  margin-left: 6px;
+  color: var(--text-weak);
+}
+.paas-notifications {
+  flex-shrink: 0;
+  max-height: 100px;
+  overflow: auto;
+  padding: 0 20px;
+}
+.paas-notifications > div {
+  display: flex;
+  justify-content: space-between;
+  gap: 8px;
+  margin: 4px 0;
+}
+.paas-notifications button:first-child {
+  text-align: left;
+  flex: 1;
+}
+.paas-new-progress {
+  align-self: center;
+  flex-shrink: 0;
+  margin: 6px auto;
+  box-shadow: 0 2px 8px #0001;
+}
+.paas-task-shortcut {
+  margin-left: auto;
+  font-size: 12px;
+}
+.paas-topbar .paas-topbar-connection {
+  margin-left: 8px;
+}
+.paas-task-counts {
+  padding: 12px 0;
+}
+.paas-task-counts small {
+  color: var(--text-weak);
+}
+.paas-global-notices {
+  margin-bottom: 12px;
+}
+.paas-global-notices > div {
+  display: flex;
+  gap: 8px;
+  margin: 4px 0;
+}
+.paas-global-notices button:first-child {
+  flex: 1;
+  text-align: left;
+}
+@media (max-width: 720px) {
+  .paas-chat-header {
+    align-items: flex-start;
+    flex-wrap: wrap;
+    gap: 8px;
+  }
+  .paas-chat-header-actions {
+    justify-content: flex-start;
+  }
+  .paas-composer footer select {
+    max-width: 140px;
+  }
+  .paas-task-shortcut {
+    font-size: 11px;
+    padding: 3px;
+  }
+}
+
+.paas-chat-search {
+  width: calc(100% - 16px);
+  margin: 8px;
+  padding: 8px;
+  border: 1px solid var(--border-base);
+  border-radius: 6px;
+}
+.paas-archive-toggle {
+  margin: 0 8px 8px;
+  font-size: 12px;
+}
+.paas-chat-rename {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 8px;
+  padding: 8px 16px;
+}
+.paas-chat-rename input {
+  flex: 1;
+  min-width: 120px;
+  padding: 6px;
+  border: 1px solid var(--border-base);
+}
+.paas-chat-header h1 {
+  overflow-wrap: anywhere;
+}
+
+/* Keep research content primary; secondary controls remain discoverable. */
+.paas-start-steps {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 12px;
+  list-style: none;
+  padding: 0;
+  margin: 12px 0 24px;
+}
+.paas-start-steps li {
+  padding: 10px 16px;
+  border-radius: 10px;
+  background: var(--background-weak);
+  border: 1px solid var(--border-weak-base);
+}
+.paas-start-steps li[data-ready="true"] {
+  border-color: #5b9c85;
+}
+.paas-start-card {
+  margin-bottom: 22px;
+}
+.paas-more-actions {
+  position: relative;
+}
+.paas-more-actions > summary {
+  cursor: pointer;
+  padding: 7px 12px;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 8px;
+}
+.paas-more-actions[open] {
+  padding: 6px;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 8px;
+  background: var(--background-base);
+}
+.paas-more-actions[open] button {
+  display: block;
+  width: 100%;
+  margin-top: 5px;
+  text-align: left;
+}
+.paas-workspace .paas-chat-header {
+  padding-block: 14px;
+  gap: 12px;
+}
+.paas-chat-header h1 {
+  font-size: 20px;
+}
+.paas-workspace .paas-composer {
+  padding: 12px 16px;
+  max-height: 34vh;
+  border-radius: 18px;
+}
+.paas-workspace .paas-composer textarea {
+  min-height: 54px;
+  max-height: 96px;
+  padding-block: 10px;
+}
+.paas-workspace .paas-composer > .paas-actions button {
+  padding: 5px 10px;
+}
+.paas-composer .paas-reference {
+  display: flex;
+  align-items: start;
+  gap: 10px;
+  background: var(--background-weak);
+  border-radius: 8px;
+  padding: 8px;
+  margin-top: 8px;
+}
+.paas-reference details {
+  flex: 1;
+  min-width: 0;
+}
+.paas-reference summary {
+  cursor: pointer;
+  font-size: 13px;
+}
+.paas-reference pre {
+  max-height: 140px;
+  overflow: auto;
+  white-space: pre-wrap;
+  font-size: 12px;
+}
+.paas-reference button {
+  flex-shrink: 0;
+}
+.paas-research-progress {
+  margin: 12px 0;
+}
+.paas-progress-metrics {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 12px;
+}
+.paas-progress-metrics > span {
+  display: grid;
+  min-width: 110px;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 8px;
+  padding: 8px 12px;
+  font-size: 12px;
+}
+.paas-progress-metrics strong {
+  font-size: 16px;
+}
+.paas-progress-sections {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+  gap: 8px;
+}
+.paas-progress-sections details {
+  border: 1px solid var(--border-weak-base);
+  border-radius: 8px;
+  padding: 10px;
+}
+.paas-progress-sections summary {
+  cursor: pointer;
+}
+.paas-progress-sections ul {
+  padding-left: 20px;
+}
+.paas-issue p {
+  margin: 5px 0;
+}
+.paas-issue details {
+  margin-top: 8px;
+  font-size: 12px;
+  overflow-wrap: anywhere;
+}
+.paas-report-reader {
+  display: block;
+  overflow: auto;
+  height: auto;
+  max-height: 78vh;
+  padding: 16px 28px 32px;
+}
+.paas-report-reader .paas-actions {
+  position: sticky;
+  top: 0;
+  background: var(--background-base);
+  padding: 8px 0;
+  z-index: 1;
+}
+.paas-report-reader .paas-report {
+  max-width: 900px;
+  margin: 20px auto;
+}
+.paas-report-reader .paas-report [data-component="markdown"] {
+  font-size: 16px;
+  line-height: 1.9;
+}
+.paas-report-diff pre {
+  margin: 0;
+  white-space: pre-wrap;
+  overflow-wrap: anywhere;
+  padding: 4px 10px;
+  font: 14px/1.7 inherit;
+}
+.paas-report-diff [data-change="added"] {
+  background: light-dark(#e6f5ec, #173d29);
+}
+.paas-report-diff [data-change="removed"] {
+  background: light-dark(#fdeceb, #4c2527);
+  text-decoration: line-through;
+}
+.paas-budget-presets {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 8px;
+  margin-bottom: 12px;
+}
+@media (min-width: 1100px) {
+  .paas-workspace .paas-sidebar {
+    width: 106px;
+    padding-inline: 8px;
+  }
+  .paas-sidebar nav button {
+    width: 90px;
+    height: 62px;
+    display: flex;
+    flex-direction: column;
+    gap: 4px;
+  }
+  .paas-sidebar nav .paas-nav-label {
+    position: static;
+    transform: none;
+    visibility: visible;
+    opacity: 1;
+    border: 0;
+    padding: 0;
+    background: transparent;
+    box-shadow: none;
+    font-size: 12px;
+  }
+}
+@media (max-width: 700px) {
+  .paas-workspace .paas-chat-header {
+    flex-wrap: wrap;
+  }
+  .paas-workspace .paas-composer {
+    max-height: 40vh;
+    padding: 8px 10px;
+  }
+  .paas-report-reader {
+    padding: 12px;
+  }
+}
+
+.paas-workspace .paas-composer textarea { height:64px; min-height:44px; }
+.paas-workspace .paas-composer footer label { display:flex; flex-direction:row; align-items:center; gap:8px; }
+.paas-workspace .paas-composer .paas-draft-hint { margin:4px 0; }
+.paas-workspace .paas-composer footer label { white-space: nowrap; }

+ 28 - 0
packages/app/src/pages/paas/progress.test.ts

@@ -0,0 +1,28 @@
+import { expect, test } from "bun:test"
+import { researchProgress } from "./progress"
+import { researchIssue } from "./issue"
+
+test("unknown usage is not presented as zero and server research outcomes remain distinct", () => {
+  expect(researchProgress({ usage: { total_tokens: 0, usage_complete: false } }).tokens).toBeUndefined()
+  const view = researchProgress({
+    usage: { total_tokens: 12345, usage_complete: true },
+    research: {
+      science: {
+        main_flow: { rounds_completed: 3 },
+        next_step: "人工复核方案",
+        outcome: { sections: [{ title: "已有产物与待办", lines: ["待验证光学条件"], omitted: 2 }] },
+      },
+    },
+  })
+  expect(view).toMatchObject({ rounds: 3, tokens: 12345, complete: true, next: "人工复核方案" })
+  expect(view.sections[0].lines).toEqual(["待验证光学条件"])
+  expect(researchProgress({ usage: { total_tokens: -1 } }).tokens).toBeUndefined()
+})
+
+test("account balance, research budget, network and permissions suggest different recovery paths", () => {
+  expect(researchIssue("Insufficient Balance").title).toBe("模型账户额度不足")
+  expect(researchIssue("model_budget_exhausted").action).toBe("settings")
+  expect(researchIssue("HTTP 401").action).toBe("connection")
+  expect(researchIssue("HTTP 403").action).toBe("")
+  expect(researchIssue("连接中断").action).toBe("tasks")
+})

+ 96 - 0
packages/app/src/pages/paas/progress.tsx

@@ -0,0 +1,96 @@
+import { For, Show } from "solid-js"
+import { paasRecord, paasText } from "@/paas"
+
+/** Only project server-owned observations; missing measurements are not zero progress. */
+export function researchProgress(run: Record<string, unknown>) {
+  const science = paasRecord(paasRecord(run.research)?.science) || {}
+  const flow = paasRecord(science.main_flow) || {}
+  const outcome = paasRecord(science.outcome) || {}
+  const usage = paasRecord(run.usage) || {}
+  const count = (value: unknown) =>
+    typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined
+  const rounds =
+    count(flow.rounds_completed) ?? (Array.isArray(science.rounds) ? science.rounds.length : count(science.rounds))
+  const tokens = count(usage.total_tokens)
+  const calls = count(usage.tool_calls)
+  const sections = Array.isArray(outcome.sections)
+    ? outcome.sections.flatMap((v) => {
+        const row = paasRecord(v)
+        if (!row || !Array.isArray(row.lines)) return []
+        return [
+          {
+            title: paasText(row.title),
+            lines: row.lines.filter((line): line is string => typeof line === "string"),
+            omitted: count(row.omitted) || 0,
+          },
+        ]
+      })
+    : []
+  return {
+    rounds,
+    tokens: (tokens && tokens > 0) || usage.usage_complete === true ? tokens : undefined,
+    complete: usage.usage_complete === true,
+    calls: calls && calls > 0 ? calls : undefined,
+    stage: paasText(run.stage_name) || paasText(run.current_stage),
+    next: paasText(science.next_step),
+    sections,
+  }
+}
+
+export function ResearchProgress(props: { run: Record<string, unknown> }) {
+  const data = () => researchProgress(props.run)
+  return (
+    <section class="paas-research-progress" aria-label="研究进展">
+      <div class="paas-progress-metrics">
+        <Show when={data().stage}>
+          <span>
+            当前阶段<strong>{data().stage}</strong>
+          </span>
+        </Show>
+        <Show when={data().rounds !== undefined}>
+          <span>
+            完成研究轮次<strong>{data().rounds}</strong>
+          </span>
+        </Show>
+        <Show when={data().tokens !== undefined}>
+          <span>
+            {data().complete ? "累计 Token" : "已回传 Token"}
+            <strong>{data().tokens?.toLocaleString()}</strong>
+          </span>
+        </Show>
+        <Show when={data().calls !== undefined}>
+          <span>
+            工具调用<strong>{data().calls}</strong>
+          </span>
+        </Show>
+      </div>
+      <Show when={data().tokens === undefined}>
+        <p class="paas-muted">平台尚未回传用量;不表示本次没有消耗。</p>
+      </Show>
+      <Show when={data().tokens !== undefined && !data().complete}>
+        <p class="paas-muted">用量仍在汇总,以最终回执为准。</p>
+      </Show>
+      <Show when={data().next}>
+        <p>
+          <strong>下一步:</strong>
+          {data().next}
+        </p>
+      </Show>
+      <div class="paas-progress-sections">
+        <For each={data().sections}>
+          {(section) => (
+            <details open={section.title.includes("下一步")}>
+              <summary>{section.title}</summary>
+              <ul>
+                <For each={section.lines}>{(line) => <li>{line}</li>}</For>
+              </ul>
+              <Show when={section.omitted}>
+                <small>另有 {section.omitted} 项,见完整报告。</small>
+              </Show>
+            </details>
+          )}
+        </For>
+      </div>
+    </section>
+  )
+}

+ 129 - 0
packages/app/src/pages/paas/report-reader.tsx

@@ -0,0 +1,129 @@
+import { For, Show, createResource } from "solid-js"
+import { createStore } from "solid-js/store"
+import { Dialog } from "@opencode-ai/ui/dialog"
+import { ResearchReport } from "./report"
+import { usePlatform } from "@/context/platform"
+import type { ResearchMessage } from "./chat-state"
+
+export function ReportReader(props: {
+  message: ResearchMessage
+  earlier: ResearchMessage[]
+  onExport: (format: "md" | "docx" | "pdf") => Promise<{ saved: boolean; name?: string; error?: string } | undefined>
+}) {
+  const platform = usePlatform()
+  const [state, setState] = createStore({
+    busy: false,
+    note: "",
+    compare: false,
+    previous: props.earlier.at(-1)?.id || "",
+  })
+  async function save(format: "md" | "docx" | "pdf") {
+    if (state.busy) return
+    setState({ busy: true, note: "" })
+    try {
+      const result = await props.onExport(format)
+      setState(
+        "note",
+        result?.error || (result?.saved ? `已导出 ${result.name || "研究报告"}` : "已取消导出,报告仍保留。"),
+      )
+    } catch {
+      setState("note", "导出未完成,请重试或先导出 Markdown。")
+    } finally {
+      setState("busy", false)
+    }
+  }
+  const previous = () => props.earlier.find((item) => item.id === state.previous)
+  const oversized = () => (previous()?.text.length || 0) + props.message.text.length > 200000
+  const [changes] = createResource(
+    () => (state.compare && previous() && !oversized() ? [previous()!.text, props.message.text] : undefined),
+    async (texts) => (await import("diff")).diffLines(texts[0], texts[1], { timeout: 250 }),
+  )
+  return (
+    <Dialog title="研究报告" size="x-large">
+      <div class="paas-workspace paas-report-reader">
+        <div class="paas-actions">
+          <button aria-pressed={!state.compare} onClick={() => setState("compare", false)}>
+            阅读全文
+          </button>
+          <button
+            disabled={!props.earlier.length}
+            aria-pressed={state.compare}
+            onClick={() => setState("compare", true)}
+          >
+            对比此前报告
+          </button>
+          <button disabled={state.busy} onClick={() => void save("docx")}>
+            导出 Word
+          </button>
+          <button disabled={state.busy} onClick={() => void save("pdf")}>
+            导出 PDF
+          </button>
+          <button disabled={state.busy} onClick={() => void save("md")}>
+            导出 Markdown
+          </button>
+        </div>
+        <Show when={state.note}>
+          <p role="status">{state.note}</p>
+        </Show>
+        <p class="paas-muted">Word / PDF 保留文字、标题、列表和表格;公式按原文导出,图片链接不自动下载。</p>
+        <Show
+          when={state.compare}
+          fallback={
+            <div
+              class="paas-report"
+              onClick={(event) => {
+                const link = (event.target as HTMLElement).closest("a")
+                if (link && /^https?:/.test(link.href)) {
+                  event.preventDefault()
+                  platform.openExternal(link.href)
+                }
+              }}
+            >
+              <ResearchReport text={props.message.text} />
+            </div>
+          }
+        >
+          <label>
+            对比版本
+            <select
+              aria-label="对比版本"
+              value={state.previous}
+              onChange={(e) => setState("previous", e.currentTarget.value)}
+            >
+              <For each={props.earlier}>
+                {(message, i) => (
+                  <option value={message.id}>
+                    此前报告 {i() + 1}
+                    {message.runID ? ` · ${message.runID}` : ""}
+                  </option>
+                )}
+              </For>
+            </select>
+          </label>
+          <p>绿色为新增,红色删除线为移除;仅显示文本变化,不代表科学结论改善。</p>
+          <Show when={oversized()}>
+            <p>报告较长,请分别导出后对比,以保持阅读流畅。</p>
+          </Show>
+          <Show when={changes.loading}>
+            <p role="status">正在对比…</p>
+          </Show>
+          <Show when={!oversized() && !changes.loading && !changes()}>
+            <p>本次差异较多,请分别阅读或导出报告后对比。</p>
+          </Show>
+          <Show when={!oversized() && !changes.loading}>
+            <div class="paas-report-diff">
+              <For each={changes()}>
+                {(part) => (
+                  <pre data-change={part.added ? "added" : part.removed ? "removed" : "same"}>
+                    {part.added ? "+ " : part.removed ? "− " : ""}
+                    {part.value}
+                  </pre>
+                )}
+              </For>
+            </div>
+          </Show>
+        </Show>
+      </div>
+    </Dialog>
+  )
+}

+ 21 - 0
packages/app/src/pages/paas/report.tsx

@@ -0,0 +1,21 @@
+import { createMemo } from "solid-js"
+import { Markdown } from "@opencode-ai/session-ui/markdown"
+
+/** Normalize display delimiters for the shared renderer; leave code literals intact. */
+export function researchMarkdown(text: string) {
+  return text
+    .split(/(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]*`)/g)
+    .map((part, index) => {
+      if (index % 2) return part
+      return part.replace(
+        /\$\$([\s\S]*?)\$\$|\\\[([\s\S]*?)\\\]/g,
+        (_, dollars: string | undefined, brackets: string | undefined) =>
+          `\n\n$$\n${(dollars ?? brackets ?? "").trim()}\n$$\n\n`,
+      )
+    })
+    .join("")
+}
+export function ResearchReport(props: { text: string }) {
+  const text = createMemo(() => researchMarkdown(props.text))
+  return <Markdown text={text()} />
+}

+ 82 - 75
packages/app/src/pages/paas/run-panel.tsx

@@ -1,7 +1,9 @@
 import { For, Show, createEffect, on, onCleanup } from "solid-js"
+import { ResearchReport } from "./report"
+import { ResearchProgress } from "./progress"
+import { ResearchIssue } from "./issue"
+import { usePlatform } from "@/context/platform"
 import { createStore, reconcile } from "solid-js/store"
-import { PaasActivity, paasActivityItems } from "./activity"
-import { PaasMarkdown } from "./markdown"
 import {
   paasRecord,
   paasRows,
@@ -32,12 +34,10 @@ export function PaasRunPanel(props: {
   api: PaasPlatform
   agentID: string
   runID: string
-  initial?: Record<string, unknown>
-  showGoal?: boolean
-  showResult?: boolean
+  hideOutput?: boolean
   onUpdate?: (run: Record<string, unknown>) => void
-  onClose?: () => void
 }) {
+  const platform = usePlatform()
   const [state, setState] = createStore({
     run: {} as Record<string, unknown>,
     files: [] as Record<string, unknown>[],
@@ -46,6 +46,7 @@ export function PaasRunPanel(props: {
     syncError: "",
     note: "",
     message: "",
+    savedPath: "",
     filesLoaded: false,
   })
   const status = () => paasStatus(state.run)
@@ -55,8 +56,7 @@ export function PaasRunPanel(props: {
     if (value?.status && !["pending", "waiting"].includes(paasText(value.status))) return undefined
     return value
   }
-  const rawEvents = () => (Array.isArray(state.run.events) ? state.run.events : state.run.activity)
-  const lifecycle = { active: true, epoch: 0, request: 0, pending: 0 }
+  const lifecycle = { active: true, epoch: 0, request: 0, pending: 0, filesFor: "" }
   onCleanup(() => {
     lifecycle.active = false
   })
@@ -73,6 +73,10 @@ export function PaasRunPanel(props: {
         setState("run", reconcile(run))
         setState("syncError", "")
         props.onUpdate?.(run)
+        if (paasTerminalStatuses.has(paasStatus(run)) && lifecycle.filesFor !== props.runID) {
+          lifecycle.filesFor = props.runID
+          void loadFiles()
+        }
       }
     } catch {
       if (lifecycle.active && epoch === lifecycle.epoch && request === lifecycle.request)
@@ -85,8 +89,18 @@ export function PaasRunPanel(props: {
   createEffect(
     on([() => props.api, () => props.agentID, () => props.runID], () => {
       lifecycle.epoch++
-      setState({ files: [], filesLoaded: false, busy: "", error: "", syncError: "", note: "", message: "" })
-      setState("run", reconcile(props.initial ?? {}))
+      lifecycle.filesFor = ""
+      setState({
+        files: [],
+        filesLoaded: false,
+        busy: "",
+        error: "",
+        syncError: "",
+        note: "",
+        message: "",
+        savedPath: "",
+      })
+      setState("run", reconcile({}))
       void refresh(true)
       const timer = window.setInterval(() => {
         if (!document.hidden && !state.busy && (active.has(status()) || state.syncError)) void refresh()
@@ -102,6 +116,23 @@ export function PaasRunPanel(props: {
     }),
   )
 
+  async function loadFiles() {
+    const epoch = lifecycle.epoch
+    try {
+      const result = await props.api.request({ action: "run-files", agentID: props.agentID, runID: props.runID })
+      if (lifecycle.active && epoch === lifecycle.epoch)
+        setState({ files: paasRows(result, "files"), filesLoaded: true })
+    } catch {
+      /* File listing is optional; the report remains readable and can be retried. */
+    }
+  }
+  createEffect(
+    on(
+      () => paasText(approval()?.approval_id) || paasText(approval()?.id),
+      () => setState("note", ""),
+    ),
+  )
+
   async function perform(label: string, request: PaasRequest) {
     if (state.busy) return
     const epoch = lifecycle.epoch
@@ -114,7 +145,9 @@ export function PaasRunPanel(props: {
       if (!lifecycle.active || epoch !== lifecycle.epoch) return
       if (request.action === "run-files") setState({ files: paasRows(result, "files"), filesLoaded: true })
       else if (request.action === "download") {
-        setState("message", paasRecord(result)?.saved ? "文件已保存。" : "平台未返回保存确认,请检查下载目录。")
+        if (paasRecord(result)?.saved)
+          setState({ message: "文件已保存。", savedPath: paasText(paasRecord(result)?.path) })
+        else setState({ message: "平台未返回保存确认,请检查下载目录。", savedPath: "" })
       } else {
         setState("message", "操作已提交,正在同步任务状态。")
         await refresh(true)
@@ -157,11 +190,7 @@ export function PaasRunPanel(props: {
     })
 
   return (
-    <section
-      class="paas-panel"
-      classList={{ "paas-detail": !!props.showGoal }}
-      aria-label={props.showGoal ? "任务详情" : "任务进度与成果"}
-    >
+    <section class="paas-panel" aria-label="任务进度与成果">
       <div class="paas-actions">
         <strong>{paasStatuses[status()] || "正在同步任务"}</strong>
         <button type="button" disabled={!!state.busy} onClick={() => void refresh()}>
@@ -193,41 +222,44 @@ export function PaasRunPanel(props: {
             继续执行
           </button>
         </Show>
-        <Show when={props.onClose}>
-          <button type="button" onClick={props.onClose}>
-            收起
-          </button>
-        </Show>
       </div>
+      <ResearchProgress run={state.run} />
       <Show when={state.busy}>
         <p role="status">{state.busy}…</p>
       </Show>
       <Show when={state.error}>
-        <p role="alert" class="paas-notice">
-          {state.error}
-        </p>
+        <ResearchIssue message={state.error} />
       </Show>
       <Show when={state.syncError}>
         <p role="alert" class="paas-notice">
           {state.syncError}
         </p>
       </Show>
-      <Show when={state.run.client_detail_source === "history"}>
-        <p class="paas-notice">
-          当前平台未提供单条任务详情,此处展示刚刚读取的最近任务记录。成果与审批信息可能不包含在列表中。
-        </p>
-      </Show>
       <Show when={status() === "failed" && paasText(state.run.error_message)}>
-        <p role="alert" class="paas-notice">
-          {paasText(state.run.error_message)}
-        </p>
+        <ResearchIssue message={paasText(state.run.error_message)} />
       </Show>
       <Show when={state.message}>
         <p role="status">{state.message}</p>
+        <Show when={state.savedPath && platform.revealPath}>
+          <button
+            onClick={async () => {
+              try {
+                if (!(await platform.revealPath!(state.savedPath))) throw new Error()
+              } catch {
+                setState("error", `无法打开保存位置,文件保存在:${state.savedPath}`)
+              }
+            }}
+          >
+            打开保存位置
+          </button>
+        </Show>
       </Show>
       <Show when={approval()}>
         {(item) => (
           <div class="paas-notice paas-approval" role="group" aria-label="待确认事项">
+            <Show when={paasText(item().stage_name)}>
+              <p class="paas-muted">当前阶段:{paasText(item().stage_name)}</p>
+            </Show>
             <p class="paas-approval-question">
               {paasText(item().message) ||
                 paasText(item().prompt) ||
@@ -235,6 +267,9 @@ export function PaasRunPanel(props: {
                 paasText(item().summary) ||
                 "请核对以下内容,再决定是否继续。"}
             </p>
+            <For each={Array.isArray(item().artifacts) ? paasRows(item(), "artifacts") : []}>
+              {(file) => <p>待确认成果:{paasText(file.name) || paasText(file.path) || paasText(file.artifact_id)}</p>}
+            </For>
             <details class="paas-approval-detail">
               <summary>技术详情</summary>
               <pre>{JSON.stringify(item(), null, 2)}</pre>
@@ -257,28 +292,21 @@ export function PaasRunPanel(props: {
           </div>
         )}
       </Show>
-      <Show when={props.showGoal}>
-        <section class="paas-run-section" aria-label="概览">
-          <h3>概览</h3>
-          <Show when={paasText(state.run.input)}>
-            <p class="paas-run-goal">{paasText(state.run.input)}</p>
-          </Show>
-          <Show when={paasText(state.run.output)} fallback={<p class="paas-muted">平台暂未返回文本结果。</p>}>
-            <PaasMarkdown text={paasText(state.run.output)} />
-          </Show>
-        </section>
-        <section class="paas-run-section" aria-label="活动">
-          <h3>活动</h3>
-          <PaasActivity
-            items={paasActivityItems(rawEvents())}
-            empty="当前任务快照未包含工具事件;执行期间的实时活动显示在会话中。"
-          />
-        </section>
-      </Show>
-      <Show when={!props.showGoal && props.showResult && paasText(state.run.output)}>
-        <details class="paas-run-output">
+      <Show when={!props.hideOutput && paasText(state.run.output)}>
+        <details>
           <summary>查看最新结果</summary>
-          <PaasMarkdown text={paasText(state.run.output)} />
+          <div
+            class="paas-report"
+            onClick={(event) => {
+              const link = (event.target as HTMLElement).closest("a")
+              if (link && /^https?:/.test(link.href)) {
+                event.preventDefault()
+                platform.openExternal(link.href)
+              }
+            }}
+          >
+            <ResearchReport text={paasText(state.run.output)} />
+          </div>
         </details>
       </Show>
       <Show when={artifacts().length}>
@@ -326,10 +354,7 @@ export function PaasRunPanel(props: {
         {(file) => (
           <div class="paas-actions paas-run-file">
             <span>{file.name}</span>
-            <Show
-              when={file.path}
-              fallback={<span class="paas-muted">平台未返回可下载路径。</span>}
-            >
+            <Show when={file.path} fallback={<span class="paas-muted">平台未返回可下载路径。</span>}>
               <button
                 type="button"
                 disabled={!!state.busy}
@@ -349,24 +374,6 @@ export function PaasRunPanel(props: {
           </div>
         )}
       </For>
-      <details class="paas-run-technical">
-        <summary>技术信息</summary>
-        <dl>
-          <dt>任务编号</dt>
-          <dd>
-            <code>{props.runID}</code>
-          </dd>
-          <dt>智能体</dt>
-          <dd>
-            <code>{props.agentID}</code>
-          </dd>
-          <Show when={paasText(state.run.client_detail_source)}>
-            <dt>快照来源</dt>
-            <dd>{state.run.client_detail_source === "history" ? "最近任务列表" : "单条任务详情"}</dd>
-          </Show>
-        </dl>
-        <pre>{JSON.stringify(state.run, null, 2)}</pre>
-      </details>
     </section>
   )
 }

+ 301 - 0
packages/app/src/pages/paas/tasks.tsx

@@ -0,0 +1,301 @@
+import { For, Show, createEffect, createMemo, on, onCleanup } from "solid-js"
+import { createStore, reconcile } from "solid-js/store"
+import {
+  paasRecord,
+  paasRows,
+  paasRunDetail,
+  paasStatus,
+  paasStatuses,
+  paasTerminalStatuses,
+  paasText,
+  type PaasPlatform,
+} from "@/paas"
+
+/** Persistent task index: navigation never owns or cancels a remote execution. */
+export function createTaskIndex(props: {
+  api?: PaasPlatform
+  connected: boolean
+  scope: string
+  agents: Record<string, unknown>[]
+  onNotice?: (run: Record<string, unknown>) => void
+}) {
+  const [state, setState] = createStore({
+    rows: [] as Record<string, unknown>[],
+    loading: false,
+    loaded: false,
+    error: "",
+    updated: "",
+    next: {} as Record<string, number | null>,
+    limited: [] as string[],
+    expanded: [] as string[],
+  })
+  const life = { epoch: 0, active: true, request: 0 }
+  async function refresh(more = false) {
+    if (!props.connected || !props.api || state.loading) return
+    const epoch = life.epoch,
+      request = ++life.request
+    setState("loading", true)
+    const agents = props.agents.filter((a) => !more || typeof state.next[paasText(a.id)] === "number")
+    const results: Record<string, unknown>[] = []
+    const failures: string[] = []
+    try {
+      for (let start = 0; start < agents.length; start += 4) {
+        await Promise.all(
+          agents.slice(start, start + 4).map(async (agent) => {
+            const id = paasText(agent.id)
+            try {
+              const offset = more ? state.next[id]! : 0
+              const response = await props.api!.request({
+                action: "history",
+                agentID: id,
+                offset,
+                includeActive: !more,
+              })
+              if (!life.active || epoch !== life.epoch) return
+              const rows = paasRows(response, "runs")
+              const page = paasRecord(response)
+              if (!more && page?.active_included !== true && !state.limited.includes(id))
+                setState("limited", (ids) => [...ids, id])
+              if (!more && page?.active_included === true)
+                setState("limited", (ids) => ids.filter((value) => value !== id))
+              if (more || !state.expanded.includes(id)) {
+                const next = page?.next_offset
+                setState(
+                  "next",
+                  id,
+                  page?.pagination_supported === true && typeof next === "number" && next > offset ? next : null,
+                )
+              }
+              if (more && !state.expanded.includes(id)) setState("expanded", (ids) => [...ids, id])
+              results.push(
+                ...rows.map((run) => ({
+                  ...run,
+                  run_id: paasText(run.run_id) || paasText(run.id),
+                  agent_id: id,
+                  agent_name: paasText(agent.name),
+                })),
+              )
+            } catch {
+              failures.push(paasText(agent.name))
+              results.push(...state.rows.filter((row) => row.agent_id === id))
+            }
+          }),
+        )
+        if (!life.active || epoch !== life.epoch) return
+      }
+      // A formerly active task may have ended outside the most recent history page.
+      if (!more) {
+        const missing = state.rows.filter(
+          (row) =>
+            !paasTerminalStatuses.has(paasStatus(row)) &&
+            !results.some((run) => run.agent_id === row.agent_id && run.run_id === row.run_id),
+        )
+        for (let start = 0; start < missing.length; start += 4) {
+          await Promise.all(
+            missing.slice(start, start + 4).map(async (row) => {
+              try {
+                const run = await paasRunDetail(props.api!, paasText(row.agent_id), paasText(row.run_id))
+                results.push({ ...row, ...run })
+              } catch {
+                failures.push(paasText(row.agent_name))
+              }
+            }),
+          )
+          if (!life.active || epoch !== life.epoch) return
+        }
+      }
+      if (life.active && epoch === life.epoch && request === life.request) {
+        results.forEach((run) => {
+          const previous = state.rows.find((row) => row.agent_id === run.agent_id && row.run_id === run.run_id)
+          const status = paasStatus(run)
+          if (
+            previous &&
+            paasStatus(previous) !== status &&
+            (paasTerminalStatuses.has(status) || status.startsWith("waiting"))
+          )
+            props.onNotice?.(run)
+        })
+        const merged = new Map(state.rows.map((run) => [`${run.agent_id}:${run.run_id}`, run]))
+        results.forEach((run) => merged.set(`${run.agent_id}:${run.run_id}`, run))
+        setState("rows", reconcile([...merged.values()], { key: null }))
+        setState({
+          loaded: true,
+          error: failures.length ? `${failures.join("、")}暂未同步,保留上次记录,稍后自动重试。` : "",
+          updated: new Date().toLocaleTimeString(),
+        })
+      }
+    } finally {
+      if (life.active && epoch === life.epoch && request === life.request) setState("loading", false)
+    }
+  }
+  createEffect(
+    on([() => props.connected, () => props.scope, () => props.agents.map((a) => a.id).join("|")], () => {
+      life.epoch++
+      setState({ rows: [], loaded: false, loading: false, error: "", updated: "", limited: [], expanded: [] })
+      setState("next", reconcile({}))
+      if (props.connected) void refresh()
+    }),
+  )
+  const timer = setInterval(() => {
+    if (!document.hidden) void refresh()
+  }, 10000)
+  const visible = () => {
+    if (!document.hidden) void refresh()
+  }
+  document.addEventListener("visibilitychange", visible)
+  onCleanup(() => {
+    life.active = false
+    clearInterval(timer)
+    document.removeEventListener("visibilitychange", visible)
+  })
+  const waiting = createMemo(() => state.rows.filter((row) => paasStatus(row).startsWith("waiting")))
+  const running = createMemo(() =>
+    state.rows.filter((row) => !paasTerminalStatuses.has(paasStatus(row)) && !paasStatus(row).startsWith("waiting")),
+  )
+  return {
+    state,
+    refresh,
+    waiting,
+    running,
+    more: () => refresh(true),
+    hasMore: () => Object.values(state.next).some((value) => typeof value === "number"),
+  }
+}
+
+export function PaasTasks(props: {
+  index: ReturnType<typeof createTaskIndex>
+  connected: boolean
+  onOpen: (run: Record<string, unknown>) => void
+}) {
+  const [filters, setFilters] = createStore({ search: "", agent: "", status: "all" })
+  const rows = createMemo(() =>
+    props.index.state.rows
+      .filter((row) => {
+        const status = paasStatus(row)
+        return (
+          (!filters.agent || row.agent_id === filters.agent) &&
+          `${paasText(row.input)} ${paasText(row.run_id)} ${paasText(row.agent_name)}`
+            .toLowerCase()
+            .includes(filters.search.toLowerCase()) &&
+          (filters.status === "all" ||
+            (filters.status === "active" ? !paasTerminalStatuses.has(status) : status.startsWith("waiting")))
+        )
+      })
+      .sort(
+        (a, b) =>
+          Number(paasTerminalStatuses.has(paasStatus(a))) - Number(paasTerminalStatuses.has(paasStatus(b))) ||
+          (Date.parse(paasText(b.created_at)) || 0) - (Date.parse(paasText(a.created_at)) || 0),
+      ),
+  )
+  const agents = createMemo(() => [
+    ...new Map(props.index.state.rows.map((row) => [paasText(row.agent_id), paasText(row.agent_name)])).entries(),
+  ])
+  return (
+    <section aria-label="平台任务列表">
+      <div class="paas-section-title">
+        <div>
+          <h1>平台任务</h1>
+          <p>汇总活动任务与最近记录,支持加载更早历史。打开任务可查看成果或处理确认。</p>
+        </div>
+        <button disabled={!props.connected || props.index.state.loading} onClick={() => void props.index.refresh()}>
+          刷新任务
+        </button>
+      </div>
+      <div class="paas-task-counts">
+        <span>{props.index.running().length} 个进行中</span>
+        <span>{props.index.waiting().length} 个待确认</span>
+        <small>
+          {props.index.state.updated ? `同步于 ${props.index.state.updated} · 每 10 秒更新` : "正在读取任务…"}
+        </small>
+      </div>
+      <Show when={props.index.state.error}>
+        <p class="paas-notice" role="status">
+          {props.index.state.error}
+        </p>
+      </Show>
+      <Show when={props.index.state.limited.length}>
+        <p class="paas-muted">部分平台仅提供最近记录,活动任务数量可能不完整;升级对应服务后可补齐。</p>
+      </Show>
+      <div class="paas-toolbar">
+        <label>
+          搜索任务
+          <input
+            type="search"
+            placeholder="问题、智能体或任务编号"
+            value={filters.search}
+            onInput={(event) => setFilters("search", event.currentTarget.value)}
+          />
+        </label>
+        <label>
+          智能体
+          <select value={filters.agent} onChange={(event) => setFilters("agent", event.currentTarget.value)}>
+            <option value="">全部智能体</option>
+            <For each={agents()}>{([id, name]) => <option value={id}>{name}</option>}</For>
+          </select>
+        </label>
+        <label>
+          任务状态
+          <select value={filters.status} onChange={(event) => setFilters("status", event.currentTarget.value)}>
+            <option value="all">全部状态</option>
+            <option value="active">进行中与待确认</option>
+            <option value="waiting">待确认</option>
+          </select>
+        </label>
+      </div>
+      <Show
+        when={rows().length}
+        fallback={
+          <p class="paas-muted">
+            {!props.connected
+              ? "连接平台后自动加载任务。"
+              : props.index.state.loaded
+                ? "没有匹配的任务,可调整筛选或开始新的研究。"
+                : "正在读取最近任务…"}
+          </p>
+        }
+      >
+        <div class="paas-table-wrap">
+          <table>
+            <thead>
+              <tr>
+                <th>任务 / 问题</th>
+                <th>智能体</th>
+                <th>状态</th>
+                <th>操作</th>
+              </tr>
+            </thead>
+            <tbody>
+              <For each={rows()}>
+                {(run) => (
+                  <tr>
+                    <td>
+                      <strong>{paasText(run.input) || "研究任务"}</strong>
+                      <code>{paasText(run.run_id)}</code>
+                    </td>
+                    <td>{paasText(run.agent_name)}</td>
+                    <td>
+                      <span class="paas-badge" data-status={paasStatus(run)}>
+                        {paasStatuses[paasStatus(run)] || "状态待同步"}
+                      </span>
+                    </td>
+                    <td>
+                      <button disabled={!props.connected || !paasText(run.run_id)} onClick={() => props.onOpen(run)}>
+                        {paasStatus(run).startsWith("waiting") ? "处理确认" : "打开任务"}
+                      </button>
+                    </td>
+                  </tr>
+                )}
+              </For>
+            </tbody>
+          </table>
+        </div>
+      </Show>
+      <Show when={props.index.hasMore()}>
+        <button disabled={!props.connected || props.index.state.loading} onClick={() => void props.index.more()}>
+          {props.index.state.loading ? "正在读取…" : "加载更早任务"}
+        </button>
+      </Show>
+      <p class="paas-muted">刷新只同步记录,不会重新执行任务。搜索范围为已加载的记录。</p>
+    </section>
+  )
+}

+ 29 - 7
packages/desktop/README.md

@@ -1,19 +1,41 @@
-# OpenCode Desktop
+# λ-Scientist Desktop
 
-The OpenCode Desktop app, built with Electron.
+基于 Electron 的科研工作台,保留 OpenCode 开发工作区入口。当前版本为 `0.1.0-beta.4`。
 
-## Development
+## 使用与功能
+
+先连接已部署的 AgentPaaS 服务,再选择智能体、上传材料并提交研究。桌面端支持运行控制、人工确认、历史恢复、报告阅读与对比,以及 Markdown / Word / PDF 导出。模型检查需用户主动触发,资源预检可以跳过。模型、工具及知识资源由平台提供;客户端不自动安装后台服务。
+
+Word/PDF 保留文字、标题、列表、表格及引用目标地址;公式以原文保存,不自动下载图片。报告导出通过本机文件保存对话框进行,不向外部文档服务上传内容。
+
+## 开发
 
 ```bash
 bun install
 bun dev
 ```
 
-## Build
+## 构建与内测
+
+```bash
+OPENCODE_CHANNEL=beta bun run build
+bun run package:beta --unsigned --mirror --dir
+```
 
-Run the `build` script to build the app's JS assets, then `package` to
-bundle the assets as an application. The resulting app will be in `dist/`.
+`package:beta` 包含构建步骤;`--dir` 生成应用目录,用于独立验收。正式分发应完成签名、公证、目标系统验证,且使用新的版本号。
+
+只有配置自有 HTTPS `LAMBDA_SCIENTIST_UPDATE_URL` 时才启用自动更新;没有更新源时保持禁用。不要把上游更新源用作 λ-Scientist 发布源。
+
+## 验证
+
+从各包目录运行类型检查与测试;不得在仓库根目录运行测试。
 
 ```bash
-bun run build && bun run package
+bun typecheck
+bun test src/main/report-document.test.ts src/main/paas.test.ts src/main/paas-connection-storage.test.ts
+node scripts/native-smoke.cjs '/path/to/λ-Scientist Beta.app/Contents/MacOS/λ-Scientist Beta'
 ```
+
+原生脚本使用独立用户目录和合成 HTTP 服务,验证真实 Electron、preload、IPC 与文件读写;系统文件对话框的选择由测试替代,不调用真实模型。它不会重启或覆盖日常应用。
+
+工作台功能与历史验收见 [优化方案](../../PAAS_OPTIMIZATION_PLAN.zh-CN.md)。

+ 3 - 2
packages/desktop/package.json

@@ -1,7 +1,7 @@
 {
   "name": "@opencode-ai/desktop",
   "private": true,
-  "version": "0.1.0-beta.1",
+  "version": "0.1.0-beta.4",
   "type": "module",
   "license": "MIT",
   "author": {
@@ -29,7 +29,8 @@
     "electron-log": "^5",
     "electron-store": "11.0.2",
     "electron-updater": "6.8.9",
-    "electron-window-state": "^5.0.3"
+    "electron-window-state": "^5.0.3",
+    "marked": "catalog:"
   },
   "devDependencies": {
     "@actions/artifact": "4.0.0",

+ 37 - 5
packages/desktop/scripts/native-smoke.cjs

@@ -9,7 +9,8 @@ const path = require("node:path")
   if (!process.argv[2]) throw new Error("Usage: node scripts/native-smoke.cjs <packaged executable>")
   const root = await fs.mkdtemp(path.join(require("node:os").tmpdir(), "lambda-native-"))
   const material = path.join(root, "material.txt"),
-    saved = path.join(root, "research-plan.txt")
+    saved = path.join(root, "research-plan.txt"),
+    report = path.join(root, "research-report.md")
   await fs.writeFile(material, "Native desktop research material")
   const calls = []
   const run = {
@@ -17,7 +18,8 @@ const path = require("node:path")
     agent_id: "research",
     thread_id: "thread_native",
     status: "completed",
-    output: "Native research plan completed",
+    output:
+      "# 科研方案验收\n\nNative research plan completed\n\n## 对照与判断\n\n1. 明确适用条件。\n2. 保留引用与验证步骤。\n\n| 方案 | 样本量 |\n|---|---|\n| 对照组 | 20 |\n| 实验组 | 20 |\n\n待验证公式:$\\delta > 0$。\n\n## 后续研究\n\n本文件为桌面导出测试材料,不代表真实实验结果。",
   }
   const server = http.createServer(async (request, response) => {
     const url = new URL(request.url, "http://localhost")
@@ -73,21 +75,51 @@ const path = require("node:path")
     await window.getByRole("button", { name: "智能体", exact: true }).click()
     await window.getByRole("button", { name: "与 科研助手 对话", exact: true }).click()
     await app.evaluate(
-      ({ dialog }, { material, saved }) => {
+      ({ dialog }, { material, saved, report }) => {
         dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [material] })
-        dialog.showSaveDialog = async () => ({ canceled: false, filePath: saved })
+        dialog.showSaveDialog = async (options) => ({
+          canceled: false,
+          filePath:
+            options.title === "导出研究报告" ? report.replace(/\.md$/, "." + options.filters[0].extensions[0]) : saved,
+        })
       },
-      { material, saved },
+      { material, saved, report },
     )
     await window.getByRole("button", { name: "添加研究材料", exact: true }).click()
     await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
     await window.getByRole("textbox", { name: "消息", exact: true }).fill("Create a research plan")
+    await window.reload()
+    await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("Create a research plan", {
+      timeout: 30000,
+    })
+    await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
     await window.getByRole("textbox", { name: "消息", exact: true }).press("Enter")
     await expect(window.getByText("Native research plan completed", { exact: true }).first()).toBeVisible()
     await window.getByRole("button", { name: "查看工作文件", exact: true }).click()
     await window.getByRole("button", { name: "保存文件", exact: true }).click()
     await expect(window.getByText("文件已保存。", { exact: true })).toBeVisible()
     if ((await fs.readFile(saved, "utf8")) !== "Saved from native IPC") throw new Error("Downloaded bytes mismatch")
+    await window.getByRole("button", { name: "导出报告", exact: true }).click()
+    await expect(window.getByText("已导出 research-report.md", { exact: true })).toBeVisible()
+    if ((await fs.readFile(report, "utf8")) !== run.output) throw new Error("Exported report mismatch")
+    await expect(window.getByRole("button", { name: "打开保存位置", exact: true }).first()).toBeVisible()
+    await window.getByRole("button", { name: "基于此方案继续", exact: true }).click()
+    await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("")
+    await expect(window.getByLabel("已引用研究报告")).toContainText(run.output)
+    await window.getByRole("button", { name: "阅读与对比", exact: true }).click()
+    await window.getByRole("button", { name: "导出 Word", exact: true }).click()
+    await expect(window.getByRole("dialog").getByText("已导出 research-report.docx", { exact: true })).toBeVisible()
+    const word = await fs.readFile(report.replace(/\.md$/, ".docx"))
+    if (word.subarray(0, 2).toString() !== "PK") throw new Error("Invalid DOCX container")
+    await window.getByRole("button", { name: "导出 PDF", exact: true }).click()
+    await expect(window.getByRole("dialog").getByText("已导出 research-report.pdf", { exact: true })).toBeVisible()
+    const pdf = await fs.readFile(report.replace(/\.md$/, ".pdf"))
+    if (pdf.subarray(0, 5).toString() !== "%PDF-") throw new Error("Invalid PDF")
+    await app.evaluate(({ dialog }) => { dialog.showSaveDialog = async () => ({ canceled: true }) })
+    await window.getByRole("button", { name: "导出 Word", exact: true }).click()
+    await expect(window.getByRole("dialog").getByText("已取消导出,报告仍保留。", { exact: true })).toBeVisible()
+    if (!(await fs.readFile(report.replace(/\.md$/, ".docx"))).equals(word)) throw new Error("Cancelled export changed original file")
+    await window.keyboard.press("Escape")
     const execute = calls.filter((c) => c.path.endsWith("/run/stream"))
     if (execute.length !== 1 || JSON.parse(execute[0].body).input_files[0].file_id !== "native_file")
       throw new Error("Task/file binding mismatch")

+ 98 - 5
packages/desktop/src/main/ipc.ts

@@ -1,5 +1,5 @@
 import { execFile } from "node:child_process"
-import { stat, readFile, rename, rm } from "node:fs/promises"
+import { stat, readFile, writeFile, rename, rm } from "node:fs/promises"
 import { createWriteStream } from "node:fs"
 import { Readable } from "node:stream"
 import { pipeline } from "node:stream/promises"
@@ -57,6 +57,7 @@ type Deps = {
 
 export function registerIpcHandlers(deps: Deps) {
   const paas = createPaasConnections()
+  const selections = new Map<number, Map<string, { path: string; connection: unknown }>>()
   const connectionStorage = createPaasConnectionStorage({
     secure: () =>
       safeStorage.isEncryptionAvailable() &&
@@ -74,6 +75,7 @@ export function registerIpcHandlers(deps: Deps) {
       owners.add(owner)
       event.sender.once("destroyed", () => {
         paas.disconnect(owner)
+        selections.delete(owner)
         owners.delete(owner)
       })
     }
@@ -84,8 +86,27 @@ export function registerIpcHandlers(deps: Deps) {
   })
   ipcMain.handle("paas-disconnect", (event, forget) => {
     paas.disconnect(event.sender.id)
+    selections.delete(event.sender.id)
     if (forget === true) connectionStorage.clear()
   })
+  ipcMain.handle("paas-select-files", async (event) => {
+    const owner = event.sender.id
+    const connection = paas.identity(owner)
+    if (!connection) throw new Error("请先连接平台。")
+    const selected = await dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], title: "选择研究材料" })
+    if (selected.canceled) return []
+    if (paas.identity(owner) !== connection) throw new Error("连接已改变,请重新选择材料。")
+    const owned = selections.get(owner) || new Map<string, { path: string; connection: unknown }>()
+    selections.set(owner, owned)
+    return Promise.all(
+      selected.filePaths.map(async (path) => {
+        const size = (await stat(path)).size
+        const selectionID = crypto.randomUUID()
+        owned.set(selectionID, { path, connection })
+        return { selectionID, name: basename(path), size }
+      }),
+    )
+  })
   ipcMain.handle("paas-upload-files", async (event, input) => {
     const connection = paas.identity(event.sender.id)
     const selected = await dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], title: "选择研究材料" })
@@ -118,6 +139,71 @@ export function registerIpcHandlers(deps: Deps) {
     return files
   })
   ipcMain.handle("paas-request", async (event, input) => {
+    if (input?.action === "export-report") {
+      if (typeof input.text !== "string" || typeof input.name !== "string") throw new Error("报告内容无效。")
+      const format: string = input.format ?? "md"
+      if (!["md", "docx", "pdf"].includes(format)) throw new Error("不支持的报告格式。")
+      const selected = await dialog.showSaveDialog({
+        title: "导出研究报告",
+        defaultPath: `${basename(input.name).replace(/\.(md|docx|pdf)$/i, "") || "研究报告"}.${format}`,
+        filters: [
+          { name: format === "docx" ? "Word 文档" : format === "pdf" ? "PDF 文档" : "Markdown", extensions: [format] },
+        ],
+      })
+      if (selected.canceled || !selected.filePath) return { saved: false }
+      const temporary = `${selected.filePath}.${crypto.randomUUID()}.export`
+      try {
+        const contents = await (async () => {
+          if (format === "md") return input.text
+          const { reportDOCX, reportHTML } = await import("./report-document")
+          if (format === "docx") return reportDOCX(input.name, input.text)
+          const preview = new BrowserWindow({
+            show: false,
+            webPreferences: {
+              sandbox: true,
+              contextIsolation: true,
+              nodeIntegration: false,
+              javascript: false,
+              partition: `report-${crypto.randomUUID()}`,
+            },
+          })
+          preview.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
+          preview.webContents.on("will-navigate", (event) => event.preventDefault())
+          try {
+            await preview.loadURL(
+              `data:text/html;charset=utf-8,${encodeURIComponent(reportHTML(input.name, input.text))}`,
+            )
+            return await preview.webContents.printToPDF({
+              pageSize: "A4",
+              printBackground: true,
+              margins: { top: 0.55, bottom: 0.55, left: 0.6, right: 0.6 },
+            })
+          } finally {
+            preview.destroy()
+          }
+        })()
+        await writeFile(temporary, contents, { flag: "wx" })
+        await rename(temporary, selected.filePath)
+      } finally {
+        await rm(temporary, { force: true })
+      }
+      return { saved: true, name: basename(selected.filePath), path: selected.filePath }
+    }
+    if (input?.action === "upload-selected") {
+      const selected = selections.get(event.sender.id)?.get(input.selectionID)
+      if (!selected || paas.identity(event.sender.id) !== selected.connection)
+        throw new Error("该材料的本地选择已失效,请重新选择文件。")
+      const capabilities = await paas.request(event.sender.id, { action: "file-capabilities" }).catch(() => undefined)
+      const advertised =
+        capabilities && typeof capabilities === "object" && "direct_upload_max_bytes" in capabilities
+          ? Number(capabilities.direct_upload_max_bytes)
+          : 256 * 1024 * 1024
+      const maximum = Number.isFinite(advertised) && advertised > 0 ? advertised : 256 * 1024 * 1024
+      if ((await stat(selected.path)).size > maximum) throw new Error("该文件超过当前平台直接上传额度。")
+      const data = new Uint8Array(await readFile(selected.path))
+      if (paas.identity(event.sender.id) !== selected.connection) throw new Error("平台连接已改变,请重新选择材料。")
+      input = { ...input, action: "upload-file", name: basename(selected.path), data }
+    }
     if (input?.action === "download") {
       const connection = paas.identity(event.sender.id)
       const selected = await dialog.showSaveDialog({
@@ -138,11 +224,18 @@ export function registerIpcHandlers(deps: Deps) {
       } finally {
         await rm(temporary, { force: true })
       }
-      return { saved: true, name: basename(selected.filePath) }
+      return { saved: true, name: basename(selected.filePath), path: selected.filePath }
     }
-    return paas.request(event.sender.id, input, (progress) => {
-      if (!event.sender.isDestroyed()) event.sender.send("paas-progress", progress)
-    })
+    return paas.request(
+      event.sender.id,
+      input,
+      (progress) => {
+        if (!event.sender.isDestroyed()) event.sender.send("paas-progress", progress)
+      },
+      (progress) => {
+        if (!event.sender.isDestroyed()) event.sender.send("paas-upload-progress", progress)
+      },
+    )
   })
   const updaterSubscriptions = createUpdaterSubscriptions()
   app.once("will-quit", updaterSubscriptions.clear)

+ 134 - 4
packages/desktop/src/main/paas.test.ts

@@ -21,7 +21,7 @@ test("desktop transport isolates windows and only checks resources without invok
   })
   try {
     const connections = createPaasConnections()
-    expect(await connections.connect(1, { url: server.url.origin, apiKey: "test-only" })).toEqual({
+    expect(await connections.connect(1, { url: server.url.origin, apiKey: "test-only" })).toMatchObject({
       url: server.url.origin,
     })
     await expect(connections.request(2, { action: "agents" })).rejects.toThrow("请先连接")
@@ -33,6 +33,8 @@ test("desktop transport isolates windows and only checks resources without invok
       body: JSON.stringify({ check_model: false, knowledge_query: "" }),
       auth: "Bearer test-only",
     })
+    await connections.request(1, { action: "verify", agentID: "ag_data", checkModel: true })
+    expect(JSON.parse(requests[2].body)).toEqual({ check_model: true, knowledge_query: "" })
     connections.disconnect(1)
     await expect(connections.request(1, { action: "agents" })).rejects.toThrow("请先连接")
   } finally {
@@ -114,9 +116,9 @@ test("chat executes the selected agent, preserves thread identity and rejects du
       (event) => events.push(event),
     )
     await started.promise
-    await expect(connections.request(1, { action: "execute", agentID: "a1", input: "again" })).rejects.toThrow(
-      "正在执行",
-    )
+    await expect(
+      connections.request(1, { action: "execute", agentID: "a1", threadID: "thread_1", input: "again" }),
+    ).rejects.toThrow("正在执行")
     gate.resolve()
     expect(await result).toMatchObject({ output: "done", thread_id: "thread_1" })
     expect(events.map((event) => event.type)).toEqual(["started", "tool_call", "done"])
@@ -361,3 +363,131 @@ test("detaching closes only the subscription and keeps the backend job alive", a
     await server.stop(true)
   }
 })
+
+test("separate conversations execute concurrently and detach only their own stream", async () => {
+  const events: PaasProgress[] = []
+  const server = Bun.serve({
+    port: 0,
+    fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
+      return new Response(
+        new ReadableStream({
+          start(controller) {
+            controller.enqueue(new TextEncoder().encode('event: started\ndata: {"run_id":"run_parallel"}\n\n'))
+          },
+        }),
+        { headers: { "Content-Type": "text/event-stream" } },
+      )
+    },
+  })
+  const api = createPaasConnections()
+  try {
+    const first = await api.connect(1, { url: server.url.origin, apiKey: "account-a" })
+    expect(first.scope).toMatch(/^[a-f0-9]{64}$/)
+    const one = api.request(
+      1,
+      { action: "execute", agentID: "a", input: "one", threadID: "one", executionID: "one" },
+      (e) => events.push(e),
+    )
+    const two = api.request(
+      1,
+      { action: "execute", agentID: "a", input: "two", threadID: "two", executionID: "two" },
+      (e) => events.push(e),
+    )
+    for (let i = 0; i < 100 && events.length < 2; i++) await Bun.sleep(5)
+    expect(events.map((e) => e.executionID).sort()).toEqual(["one", "two"])
+    await api.request(1, { action: "detach", executionID: "one" })
+    await one
+    await expect(
+      api.request(1, { action: "execute", agentID: "a", input: "duplicate", threadID: "two", executionID: "three" }),
+    ).rejects.toThrow("已有任务")
+    api.disconnect(1)
+    await two
+    const second = await api.connect(1, { url: server.url.origin, apiKey: "account-b" })
+    expect(second.scope).not.toBe(first.scope)
+  } finally {
+    api.disconnect(1)
+    await server.stop(true)
+  }
+})
+
+test("upload progress reports consumed bytes without changing file contents", async () => {
+  const updates: number[] = []
+  const bytes = new Uint8Array(140000).fill(17)
+  const server = Bun.serve({
+    port: 0,
+    async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
+      expect(new Uint8Array(await request.arrayBuffer())).toEqual(bytes)
+      return Response.json({ file_id: "uploaded", name: "data.bin" })
+    },
+  })
+  try {
+    const api = createPaasConnections()
+    await api.connect(1, { url: server.url.origin, apiKey: "test-only" })
+    await api.request(
+      1,
+      { action: "upload-file", name: "data.bin", agentID: "a", data: bytes, uploadID: "upload-1" },
+      undefined,
+      (e) => updates.push(e.sent),
+    )
+    expect(updates).toEqual([65536, 131072, 140000])
+  } finally {
+    await server.stop(true)
+  }
+})
+
+test("submission identity travels in the stream header and receipt lookup never repeats execution", async () => {
+  const requests: { path: string; method: string; key: string | null }[] = []
+  const server = Bun.serve({
+    port: 0,
+    fetch(request) {
+      const path = new URL(request.url).pathname
+      requests.push({ path, method: request.method, key: request.headers.get("Idempotency-Key") })
+      if (path === "/api/v1/agents") return Response.json({ agents: [] })
+      if (path.endsWith("/requests/stable-request"))
+        return Response.json({
+          found: true,
+          run: { run_id: "canonical", agent_id: "research", status: "completed", output: "recovered" },
+        })
+      return new Response('event: started\ndata: {"run_id":"canonical"}\n\n', {
+        headers: { "Content-Type": "text/event-stream" },
+      })
+    },
+  })
+  try {
+    const transport = createPaasConnections()
+    await transport.connect(1, { url: server.url.toString(), apiKey: "fixture" })
+    expect(
+      await transport.request(1, {
+        action: "execute",
+        agentID: "research",
+        input: "plan",
+        requestID: "stable-request",
+      }),
+    ).toMatchObject({ status: "unknown" })
+    expect(
+      await transport.request(1, { action: "lookup-request", agentID: "research", requestID: "stable-request" }),
+    ).toMatchObject({ found: true, run: { run_id: "canonical" } })
+    expect(requests.filter((request) => request.method === "POST")).toEqual([
+      { path: "/api/v1/agents/research/run/stream", method: "POST", key: "stable-request" },
+    ])
+    expect(requests.at(-1)?.method).toBe("GET")
+  } finally {
+    await server.stop(true)
+  }
+})
+
+test("history paging carries the active-task option and rejects invalid offsets", async () => {
+  const paths: string[] = []
+  const fetcher = (async (url: string | URL | Request) => {
+    paths.push(String(url))
+    return Response.json(String(url).endsWith("/agents") ? { agents: [] } : { runs: [] })
+  }) as typeof fetch
+  const connection = createPaasConnections(fetcher)
+  await connection.connect(1, { url: "http://localhost:8000", apiKey: "test-only" })
+  await connection.request(1, { action: "history", agentID: "a", includeActive: true, offset: 20 })
+  expect(paths.at(-1)).toBe("http://localhost:8000/api/v1/agents/a/runs?offset=20&include_active=true")
+  await expect(connection.request(1, { action: "history", agentID: "a", offset: -1 })).rejects.toThrow("页码无效")
+  connection.disconnect(1)
+})

+ 92 - 20
packages/desktop/src/main/paas.ts

@@ -1,7 +1,8 @@
+import { createHash } from "node:crypto"
 import { readFile, stat } from "node:fs/promises"
 import { homedir } from "node:os"
 import { isAbsolute, join } from "node:path"
-import { paasRecord, type PaasProgress, type PaasRequest } from "@opencode-ai/app/paas"
+import { paasRecord, type PaasProgress, type PaasRequest, type PaasUploadProgress } from "@opencode-ai/app/paas"
 
 function endpoint(value: string) {
   const url = new URL(value.trim())
@@ -39,9 +40,13 @@ function identifier(value: unknown) {
 /** Each renderer owns a separate, in-memory connection. No credential is persisted. */
 export function createPaasConnections(fetcher: typeof fetch = fetch) {
   const connections = new Map<number, { url: string; apiKey: string }>()
-  const executing = new Set<number>()
+  const executing = new Set<string>()
   const pending = new Map<number, symbol>()
-  const streams = new Map<number, AbortController>()
+  const streams = new Map<number, Map<string, AbortController>>()
+  const abortStreams = (owner: number) => {
+    streams.get(owner)?.forEach((controller) => controller.abort())
+    streams.delete(owner)
+  }
 
   async function request(
     connection: { url: string; apiKey: string },
@@ -51,26 +56,48 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
     timeout = 30000,
     method = body ? "POST" : "GET",
     raw = false,
+    upload?: (sent: number, total: number) => void,
+    requestID?: string,
   ) {
     const timer = stream ? setTimeout(() => stream.controller.abort(), timeout) : undefined
+    const bytes = body instanceof Uint8Array ? body : undefined
+    const offset = { value: 0 }
+    const uploadBody =
+      bytes && upload
+        ? new ReadableStream<Uint8Array>({
+            pull(controller) {
+              if (offset.value === bytes.byteLength) {
+                controller.close()
+                return
+              }
+              const end = Math.min(offset.value + 65536, bytes.byteLength)
+              controller.enqueue(bytes.slice(offset.value, end))
+              offset.value = end
+              upload(end, bytes.byteLength)
+            },
+          })
+        : undefined
     const response = await fetcher(`${connection.url}/api/v1${path}`, {
       method,
       redirect: "error",
       headers: {
         Authorization: `Bearer ${connection.apiKey}`,
         Accept: stream ? "text/event-stream" : "application/json",
+        ...(requestID ? { "Idempotency-Key": requestID } : {}),
         ...(body instanceof Uint8Array
-          ? { "Content-Type": "application/octet-stream" }
+          ? { "Content-Type": "application/octet-stream", "Content-Length": String(body.byteLength) }
           : body && !(body instanceof FormData)
             ? { "Content-Type": "application/json" }
             : {}),
       },
+      ...(uploadBody ? { duplex: "half" as const } : {}),
       body:
-        body instanceof Uint8Array
+        uploadBody ||
+        (body instanceof Uint8Array
           ? new Uint8Array(body)
           : body instanceof FormData
             ? body
-            : body && JSON.stringify(body),
+            : body && JSON.stringify(body)),
       signal: stream?.controller.signal ?? AbortSignal.timeout(timeout),
     })
       .catch(() => {
@@ -78,6 +105,9 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
       })
       .finally(() => clearTimeout(timer))
     if (!response.ok) {
+      if (response.status === 401) throw new Error("AgentPaaS 返回 HTTP 401:平台凭证已失效,请在平台连接页重新填写。")
+      if (response.status === 429)
+        throw new Error("AgentPaaS 返回 HTTP 429:请求过于频繁,请稍后重试;已有任务可在任务中心查看。")
       if (response.status === 413) throw new Error("文件超过当前平台的上传额度,请调整材料或联系平台管理员。")
       if (response.status === 403)
         throw new Error("AgentPaaS 返回 HTTP 403:当前账号没有执行此操作的权限,其他功能仍可使用。")
@@ -98,7 +128,7 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
   return {
     identity: (owner: number) => connections.get(owner),
     async connect(owner: number, input?: { url: string; apiKey: string }) {
-      streams.get(owner)?.abort()
+      abortStreams(owner)
       connections.delete(owner)
       const attempt = Symbol()
       pending.set(owner, attempt)
@@ -113,34 +143,51 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
       if (!result || typeof result !== "object" || !("agents" in result) || !Array.isArray(result.agents))
         throw new Error("平台未返回智能体目录,请确认这是 AgentPaaS 地址。")
       connections.set(owner, connection)
-      return { url: connection.url }
+      return {
+        url: connection.url,
+        scope: createHash("sha256")
+          .update(connection.url + "\0" + connection.apiKey)
+          .digest("hex"),
+      }
     },
     disconnect: (owner: number) => {
-      streams.get(owner)?.abort()
+      abortStreams(owner)
       streams.delete(owner)
       connections.delete(owner)
       pending.delete(owner)
     },
-    async request(owner: number, input: PaasRequest, emit?: (event: PaasProgress) => void) {
+    async request(
+      owner: number,
+      input: PaasRequest,
+      emit?: (event: PaasProgress) => void,
+      upload?: (event: PaasUploadProgress) => void,
+    ) {
       const connection = connections.get(owner)
       if (!connection) throw new Error("请先连接 AgentPaaS。")
       if (input?.action === "detach") {
-        streams.get(owner)?.abort()
+        if (input.executionID) streams.get(owner)?.get(input.executionID)?.abort()
+        else abortStreams(owner)
         return { detached: true }
       }
+      if (input?.action === "lookup-request")
+        return request(connection, `/agents/${identifier(input.agentID)}/requests/${identifier(input.requestID)}`)
       if (input?.action === "execute") {
+        if (input.requestID !== undefined) identifier(input.requestID)
         if (typeof input.input !== "string" || !input.input.trim() || input.input.length > 100000)
           throw new Error("请输入 1 到 100000 个字符的任务内容。")
         if (input.threadID !== undefined && (typeof input.threadID !== "string" || input.threadID.length > 512))
           throw new Error("会话编号无效。")
         if (input.effort !== undefined && !["low", "medium", "high"].includes(input.effort))
           throw new Error("模型推理强度无效。")
-        if (executing.has(owner)) throw new Error("当前窗口已有任务正在执行。")
+        const executionID = input.executionID || "legacy"
+        const key = `${owner}:${input.agentID}:${input.threadID || executionID}`
+        if (executing.has(key)) throw new Error("该会话已有任务正在执行,请在其他会话继续或先保存草稿。")
         const path = `/agents/${identifier(input.agentID)}/run/stream`
-        executing.add(owner)
-        const executionID = input.executionID
+        executing.add(key)
         const controller = new AbortController()
-        streams.set(owner, controller)
+        if (!streams.has(owner)) streams.set(owner, new Map())
+        const owned = streams.get(owner)!
+        owned.set(executionID, controller)
         return request(
           connection,
           path,
@@ -162,9 +209,14 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
                 emit?.({ ...event, executionID })
             },
           },
+          undefined,
+          undefined,
+          false,
+          undefined,
+          input.requestID,
         ).finally(() => {
-          executing.delete(owner)
-          if (streams.get(owner) === controller) streams.delete(owner)
+          executing.delete(key)
+          if (owned.get(executionID) === controller) owned.delete(executionID)
         })
       }
       if (input?.action === "file-capabilities") return request(connection, "/files/capabilities")
@@ -175,7 +227,20 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
           agent_id: input.agentID,
           session_id: input.threadID || "",
         })
-        return request(connection, `/files?${query}`, input.data, undefined, 120000)
+        return request(
+          connection,
+          `/files?${query}`,
+          input.data,
+          undefined,
+          120000,
+          "POST",
+          false,
+          input.uploadID
+            ? (sent, total) => {
+                if (connections.get(owner) === connection) upload?.({ uploadID: input.uploadID!, sent, total })
+              }
+            : undefined,
+        )
       }
       if (["run-files", "download", "cancel", "pause", "resume", "confirm"].includes(input?.action)) {
         if (!("agentID" in input) || !("runID" in input)) throw new Error("缺少任务编号。")
@@ -252,8 +317,15 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
         throw new Error("不支持的平台操作。")
       const base = `/agents/${identifier("agentID" in input ? input.agentID : undefined)}`
       if (input.action === "verify")
-        return request(connection, `${base}/verify`, { check_model: false, knowledge_query: "" })
-      if (input.action === "history") return request(connection, `${base}/runs`)
+        return request(connection, `${base}/verify`, { check_model: input.checkModel === true, knowledge_query: "" })
+      if (input.action === "history") {
+        if (input.offset !== undefined && (!Number.isSafeInteger(input.offset) || input.offset < 0))
+          throw new Error("历史页码无效,请刷新任务列表。")
+        const query = new URLSearchParams()
+        if (input.offset !== undefined) query.set("offset", String(input.offset))
+        if (input.includeActive) query.set("include_active", "true")
+        return request(connection, `${base}/runs${query.size ? `?${query}` : ""}`)
+      }
       if (input.action === "run-options") return request(connection, `${base}/run-options`)
       if (input.action === "threads") return request(connection, `${base}/threads`)
       if (input.action === "thread-runs")

+ 46 - 0
packages/desktop/src/main/report-document.test.ts

@@ -0,0 +1,46 @@
+import { expect, test } from "bun:test"
+import { ZipReader, Uint8ArrayReader, TextWriter } from "@zip.js/zip.js"
+import { reportDOCX, reportHTML } from "./report-document"
+
+test("Word export has document relationships, headings, Chinese content and a real table", async () => {
+  const bytes = await reportDOCX(
+    "研究 & 验证",
+    "# 研究方案\n\n1. 保留依据\n2. 检验假设\n\n| 项目 | 数值 |\n|---|---|\n| 样本 | 20 |\n\n```python\nx < 2\n```",
+  )
+  const reader = new ZipReader(new Uint8ArrayReader(bytes))
+  const entries = await reader.getEntries()
+  const read = async (name: string) => {
+    const entry = entries.find((e) => e.filename === name)
+    if (!entry || entry.directory) throw new Error(`Missing ${name}`)
+    return entry.getData!(new TextWriter())
+  }
+  const document = await read("word/document.xml")
+  expect(document).toContain('w:val="Heading1"')
+  expect(document).toContain("研究方案")
+  expect(document).toContain("<w:tbl>")
+  expect(document).toContain("1. 保留依据")
+  expect(document).toContain("x &lt; 2")
+  expect(await read("docProps/core.xml")).toContain("研究 &amp; 验证")
+  expect(await read("word/_rels/document.xml.rels")).toContain('Target="styles.xml"')
+  await reader.close()
+})
+
+test("PDF source never executes raw HTML or loads remote images", () => {
+  const output = reportHTML(
+    "恶意 </title>",
+    '<script>fetch("https://example.com")</script>\n\n![图](https://example.com/a.png)\n\n[链接](javascript:alert(1))',
+  )
+  expect(output).not.toContain("<script>")
+  expect(output).not.toContain("<img")
+  expect(output).not.toContain('href="javascript:')
+  expect(output).toContain("default-src 'none'")
+  expect(output).toContain("&lt;script&gt;")
+})
+
+
+test("export retains citation destinations without activating external resources", () => {
+  const html = reportHTML("参考文献", "依据[论文](https://doi.org/10.1234/example)与[审阅记录](review.json)。")
+  expect(html).toContain("论文 (https://doi.org/10.1234/example)")
+  expect(html).toContain("审阅记录 (review.json)")
+  expect(html).not.toContain("<a")
+})

+ 97 - 0
packages/desktop/src/main/report-document.ts

@@ -0,0 +1,97 @@
+import { lexer, type Token, type Tokens } from "marked"
+import { ZipWriter, Uint8ArrayWriter, TextReader } from "@zip.js/zip.js"
+
+const escape = (text: string) =>
+  text
+    .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "")
+    .replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[c]!)
+
+/** Export a conservative document tree. Raw HTML, scripts and remote images never execute. */
+export function reportBlocks(text: string) {
+  type Block = { kind: "heading" | "paragraph" | "code" | "table"; text?: string; level?: number; rows?: string[][] }
+  const plain = (tokens: Token[]): string =>
+    tokens
+      .map((t): string => {
+        if (t.type === "br") return "\n"
+        if (t.type === "link") {
+          const link = t as Tokens.Link
+          const label = plain(link.tokens)
+          return label === link.href || /^(javascript|data):/i.test(link.href) ? label : `${label} (${link.href})`
+        }
+        if (t.type === "image") {
+          const picture = t as Tokens.Image
+          return `${picture.text}${/^https?:/i.test(picture.href) ? ` (${picture.href})` : ""}`
+        }
+        if ("tokens" in t && t.tokens) return plain(t.tokens as Token[])
+        if ("text" in t) return String(t.text)
+        return t.raw
+      })
+      .join("")
+  const visit = (tokens: Token[]): Block[] =>
+    tokens.flatMap((t): Block[] => {
+      if (t.type === "space" || t.type === "hr") return []
+      if (t.type === "heading") return [{ kind: "heading", text: plain(t.tokens || []), level: t.depth }]
+      if (t.type === "code") return [{ kind: "code", text: t.text }]
+      if (t.type === "table") {
+        const table = t as Tokens.Table
+        return [
+          { kind: "table", rows: [table.header, ...table.rows].map((row) => row.map((cell) => plain(cell.tokens))) },
+        ]
+      }
+      if (t.type === "list")
+        return (t as Tokens.List).items.flatMap((item, i) => {
+          const blocks = visit(item.tokens)
+          const first = blocks[0]
+          if (first?.text !== undefined)
+            first.text = `${t.ordered ? `${Number(t.start) + i}.` : "•"} ${item.task ? (item.checked ? "☑ " : "☐ ") : ""}${first.text}`
+          return blocks
+        })
+      if (t.type === "blockquote") return visit(t.tokens || [])
+      return [
+        {
+          kind: "paragraph",
+          text: "tokens" in t && t.tokens ? plain(t.tokens as Token[]) : "text" in t ? String(t.text) : t.raw,
+        },
+      ]
+    })
+  return visit(lexer(text))
+}
+
+export function reportHTML(title: string, text: string) {
+  const body = reportBlocks(text)
+    .map((b) => {
+      if (b.kind === "table")
+        return `<table>${b.rows!.map((r, i) => `<tr>${r.map((v) => `<${i ? "td" : "th"}>${escape(v)}</${i ? "td" : "th"}>`).join("")}</tr>`).join("")}</table>`
+      const tag = b.kind === "heading" ? `h${b.level}` : b.kind === "code" ? "pre" : "p"
+      return `<${tag}>${escape(b.text || "")}</${tag}>`
+    })
+    .join("")
+  return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><title>${escape(title)}</title><style>body{font:11pt/1.75 'PingFang SC','Microsoft YaHei',sans-serif;color:#18283c}h1{font-size:20pt}h2{font-size:16pt}h3{font-size:13pt}h1,h2,h3,h4{break-after:avoid}p,pre{white-space:pre-wrap;overflow-wrap:anywhere}pre{background:#f2f5f9;padding:12px;font-size:9pt}table{border-collapse:collapse;width:100%;margin:12px 0;table-layout:fixed}th,td{border:1px solid #b6c5d6;padding:7px;overflow-wrap:anywhere;white-space:pre-wrap}th{background:#edf3fa}tr{break-inside:avoid}img{display:none}</style><body>${body}</body></html>`
+}
+
+export async function reportDOCX(title: string, text: string) {
+  const paragraph = (value: string, style = "Normal") =>
+    `<w:p><w:pPr><w:pStyle w:val="${style}"/></w:pPr><w:r>${value
+      .split("\n")
+      .map((line, i) => `${i ? "<w:br/>" : ""}<w:t xml:space="preserve">${escape(line)}</w:t>`)
+      .join("")}</w:r></w:p>`
+  const body = reportBlocks(text)
+    .map((b) => {
+      if (b.kind === "table")
+        return `<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/><w:tblBorders>${["top", "left", "bottom", "right", "insideH", "insideV"].map((side) => `<w:${side} w:val="single" w:sz="4" w:color="B6C5D6"/>`).join("")}</w:tblBorders></w:tblPr><w:tblGrid>${b.rows![0].map(() => `<w:gridCol w:w="${Math.floor(9638 / b.rows![0].length)}"/>`).join("")}</w:tblGrid>${b.rows!.map((r, i) => `<w:tr>${i ? "" : "<w:trPr><w:tblHeader/></w:trPr>"}${r.map((v) => `<w:tc>${paragraph(v)}</w:tc>`).join("")}</w:tr>`).join("")}</w:tbl>`
+      return paragraph(b.text || "", b.kind === "heading" ? `Heading${b.level}` : b.kind === "code" ? "Code" : "Normal")
+    })
+    .join("")
+  const xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
+  const zip = new ZipWriter(new Uint8ArrayWriter())
+  const files: Record<string, string> = {
+    "[Content_Types].xml": `${xml}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>`,
+    "_rels/.rels": `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/></Relationships>`,
+    "docProps/core.xml": `${xml}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>${escape(title)}</dc:title><dc:creator>λ-Scientist</dc:creator></cp:coreProperties>`,
+    "word/_rels/document.xml.rels": `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`,
+    "word/styles.xml": `${xml}<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:eastAsia="微软雅黑"/><w:sz w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="300" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>${[1, 2, 3, 4, 5, 6].map((level) => `<w:style w:type="paragraph" w:styleId="Heading${level}"><w:name w:val="heading ${level}"/><w:basedOn w:val="Normal"/><w:pPr><w:keepNext/><w:outlineLvl w:val="${level - 1}"/></w:pPr><w:rPr><w:b/><w:sz w:val="${42 - level * 4}"/></w:rPr></w:style>`).join("")}<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/><w:rPr><w:rFonts w:ascii="Consolas"/><w:sz w:val="18"/></w:rPr></w:style></w:styles>`,
+    "word/document.xml": `${xml}<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1134" w:bottom="1134" w:left="1134" w:right="1134"/></w:sectPr></w:body></w:document>`,
+  }
+  for (const [name, contents] of Object.entries(files)) await zip.add(name, new TextReader(contents))
+  return zip.close()
+}

+ 6 - 0
packages/desktop/src/preload/index.ts

@@ -12,6 +12,12 @@ const updaterHandler = (_: unknown, state: UpdaterState) => {
 
 const api: ElectronAPI = {
   paas: {
+    selectFiles: () => ipcRenderer.invoke("paas-select-files"),
+    onUploadProgress: (listener) => {
+      const handler: Parameters<typeof ipcRenderer.on>[1] = (_event, progress) => listener(progress)
+      ipcRenderer.on("paas-upload-progress", handler)
+      return () => ipcRenderer.removeListener("paas-upload-progress", handler)
+    },
     chooseFiles: (agentID, threadID) => ipcRenderer.invoke("paas-upload-files", { agentID, threadID }),
     onProgress: (listener) => {
       const handler: Parameters<typeof ipcRenderer.on>[1] = (_event, progress) => listener(progress)

+ 2 - 2
packages/desktop/src/renderer/i18n/ar.ts

@@ -11,11 +11,11 @@ export const dict = {
   "desktop.updater.checkFailed.title": "فشل التحقق من التحديثات",
   "desktop.updater.checkFailed.message": "فشل التحقق من وجود تحديثات",
   "desktop.updater.none.title": "لا توجد تحديثات متاحة",
-  "desktop.updater.none.message": "أنت تستخدم بالفعل أحدث إصدار من OpenCode",
+  "desktop.updater.none.message": "أنت تستخدم بالفعل أحدث إصدار من λ-Scientist",
   "desktop.updater.downloadFailed.title": "فشل التحديث",
   "desktop.updater.downloadFailed.message": "فشل تنزيل التحديث",
   "desktop.updater.downloaded.title": "تم تنزيل التحديث",
-  "desktop.updater.downloaded.prompt": "تم تنزيل إصدار {{version}} من OpenCode، هل ترغب في تثبيته وإعادة تشغيله؟",
+  "desktop.updater.downloaded.prompt": "تم تنزيل إصدار {{version}} من λ-Scientist، هل ترغب في تثبيته وإعادة تشغيله؟",
   "desktop.updater.installFailed.title": "فشل التحديث",
   "desktop.updater.installFailed.message": "فشل تثبيت التحديث",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/br.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Falha ao verificar atualizações",
   "desktop.updater.checkFailed.message": "Falha ao verificar atualizações",
   "desktop.updater.none.title": "Nenhuma atualização disponível",
-  "desktop.updater.none.message": "Você já está usando a versão mais recente do OpenCode",
+  "desktop.updater.none.message": "Você já está usando a versão mais recente do λ-Scientist",
   "desktop.updater.downloadFailed.title": "Falha na atualização",
   "desktop.updater.downloadFailed.message": "Falha ao baixar a atualização",
   "desktop.updater.downloaded.title": "Atualização baixada",
   "desktop.updater.downloaded.prompt":
-    "A versão {{version}} do OpenCode foi baixada. Você gostaria de instalá-la e reiniciar?",
+    "A versão {{version}} do λ-Scientist foi baixada. Você gostaria de instalá-la e reiniciar?",
   "desktop.updater.installFailed.title": "Falha na atualização",
   "desktop.updater.installFailed.message": "Falha ao instalar a atualização",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/bs.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Provjera ažuriranja nije uspjela",
   "desktop.updater.checkFailed.message": "Nije moguće provjeriti ažuriranja",
   "desktop.updater.none.title": "Nema dostupnog ažuriranja",
-  "desktop.updater.none.message": "Već koristiš najnoviju verziju OpenCode-a",
+  "desktop.updater.none.message": "Već koristiš najnoviju verziju λ-Scientist-a",
   "desktop.updater.downloadFailed.title": "Ažuriranje nije uspjelo",
   "desktop.updater.downloadFailed.message": "Neuspjelo preuzimanje ažuriranja",
   "desktop.updater.downloaded.title": "Ažuriranje preuzeto",
   "desktop.updater.downloaded.prompt":
-    "Verzija {{version}} OpenCode-a je preuzeta. Želiš li da je instaliraš i ponovo pokreneš aplikaciju?",
+    "Verzija {{version}} λ-Scientist-a je preuzeta. Želiš li da je instaliraš i ponovo pokreneš aplikaciju?",
   "desktop.updater.installFailed.title": "Ažuriranje nije uspjelo",
   "desktop.updater.installFailed.message": "Neuspjela instalacija ažuriranja",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/da.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Opdateringstjek mislykkedes",
   "desktop.updater.checkFailed.message": "Kunne ikke tjekke for opdateringer",
   "desktop.updater.none.title": "Ingen opdatering tilgængelig",
-  "desktop.updater.none.message": "Du bruger allerede den nyeste version af OpenCode",
+  "desktop.updater.none.message": "Du bruger allerede den nyeste version af λ-Scientist",
   "desktop.updater.downloadFailed.title": "Opdatering mislykkedes",
   "desktop.updater.downloadFailed.message": "Kunne ikke downloade opdateringen",
   "desktop.updater.downloaded.title": "Opdatering downloadet",
   "desktop.updater.downloaded.prompt":
-    "Version {{version}} af OpenCode er blevet downloadet. Vil du installere den og genstarte?",
+    "Version {{version}} af λ-Scientist er blevet downloadet. Vil du installere den og genstarte?",
   "desktop.updater.installFailed.title": "Opdatering mislykkedes",
   "desktop.updater.installFailed.message": "Kunne ikke installere opdateringen",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/de.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Updateprüfung fehlgeschlagen",
   "desktop.updater.checkFailed.message": "Updates konnten nicht geprüft werden",
   "desktop.updater.none.title": "Kein Update verfügbar",
-  "desktop.updater.none.message": "Sie verwenden bereits die neueste Version von OpenCode",
+  "desktop.updater.none.message": "Sie verwenden bereits die neueste Version von λ-Scientist",
   "desktop.updater.downloadFailed.title": "Update fehlgeschlagen",
   "desktop.updater.downloadFailed.message": "Update konnte nicht heruntergeladen werden",
   "desktop.updater.downloaded.title": "Update heruntergeladen",
   "desktop.updater.downloaded.prompt":
-    "Version {{version}} von OpenCode wurde heruntergeladen. Möchten Sie sie installieren und neu starten?",
+    "Version {{version}} von λ-Scientist wurde heruntergeladen. Möchten Sie sie installieren und neu starten?",
   "desktop.updater.installFailed.title": "Update fehlgeschlagen",
   "desktop.updater.installFailed.message": "Update konnte nicht installiert werden",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/en.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Update Check Failed",
   "desktop.updater.checkFailed.message": "Failed to check for updates",
   "desktop.updater.none.title": "No Update Available",
-  "desktop.updater.none.message": "You are already using the latest version of OpenCode",
+  "desktop.updater.none.message": "You are already using the latest version of λ-Scientist",
   "desktop.updater.downloadFailed.title": "Update Failed",
   "desktop.updater.downloadFailed.message": "Failed to download update",
   "desktop.updater.downloaded.title": "Update Downloaded",
   "desktop.updater.downloaded.prompt":
-    "Version {{version}} of OpenCode has been downloaded, would you like to install it and relaunch?",
+    "Version {{version}} of λ-Scientist has been downloaded, would you like to install it and relaunch?",
   "desktop.updater.installFailed.title": "Update Failed",
   "desktop.updater.installFailed.message": "Failed to install update",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/es.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Comprobación de actualizaciones fallida",
   "desktop.updater.checkFailed.message": "No se pudieron buscar actualizaciones",
   "desktop.updater.none.title": "No hay actualizaciones disponibles",
-  "desktop.updater.none.message": "Ya estás usando la versión más reciente de OpenCode",
+  "desktop.updater.none.message": "Ya estás usando la versión más reciente de λ-Scientist",
   "desktop.updater.downloadFailed.title": "Actualización fallida",
   "desktop.updater.downloadFailed.message": "No se pudo descargar la actualización",
   "desktop.updater.downloaded.title": "Actualización descargada",
   "desktop.updater.downloaded.prompt":
-    "Se ha descargado la versión {{version}} de OpenCode. ¿Quieres instalarla y reiniciar?",
+    "Se ha descargado la versión {{version}} de λ-Scientist. ¿Quieres instalarla y reiniciar?",
   "desktop.updater.installFailed.title": "Actualización fallida",
   "desktop.updater.installFailed.message": "No se pudo instalar la actualización",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/fr.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Échec de la vérification des mises à jour",
   "desktop.updater.checkFailed.message": "Impossible de vérifier les mises à jour",
   "desktop.updater.none.title": "Aucune mise à jour disponible",
-  "desktop.updater.none.message": "Vous utilisez déjà la dernière version d'OpenCode",
+  "desktop.updater.none.message": "Vous utilisez déjà la dernière version d'λ-Scientist",
   "desktop.updater.downloadFailed.title": "Échec de la mise à jour",
   "desktop.updater.downloadFailed.message": "Impossible de télécharger la mise à jour",
   "desktop.updater.downloaded.title": "Mise à jour téléchargée",
   "desktop.updater.downloaded.prompt":
-    "La version {{version}} d'OpenCode a été téléchargée. Voulez-vous l'installer et redémarrer ?",
+    "La version {{version}} d'λ-Scientist a été téléchargée. Voulez-vous l'installer et redémarrer ?",
   "desktop.updater.installFailed.title": "Échec de la mise à jour",
   "desktop.updater.installFailed.message": "Impossible d'installer la mise à jour",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/ja.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "アップデートの確認に失敗しました",
   "desktop.updater.checkFailed.message": "アップデートを確認できませんでした",
   "desktop.updater.none.title": "利用可能なアップデートはありません",
-  "desktop.updater.none.message": "すでに最新バージョンの OpenCode を使用しています",
+  "desktop.updater.none.message": "すでに最新バージョンの λ-Scientist を使用しています",
   "desktop.updater.downloadFailed.title": "アップデートに失敗しました",
   "desktop.updater.downloadFailed.message": "アップデートをダウンロードできませんでした",
   "desktop.updater.downloaded.title": "アップデートをダウンロードしました",
   "desktop.updater.downloaded.prompt":
-    "OpenCode のバージョン {{version}} がダウンロードされました。インストールして再起動しますか?",
+    "λ-Scientist のバージョン {{version}} がダウンロードされました。インストールして再起動しますか?",
   "desktop.updater.installFailed.title": "アップデートに失敗しました",
   "desktop.updater.installFailed.message": "アップデートをインストールできませんでした",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/ko.ts

@@ -11,11 +11,11 @@ export const dict = {
   "desktop.updater.checkFailed.title": "업데이트 확인 실패",
   "desktop.updater.checkFailed.message": "업데이트를 확인하지 못했습니다",
   "desktop.updater.none.title": "사용 가능한 업데이트 없음",
-  "desktop.updater.none.message": "이미 최신 버전의 OpenCode를 사용하고 있습니다",
+  "desktop.updater.none.message": "이미 최신 버전의 λ-Scientist를 사용하고 있습니다",
   "desktop.updater.downloadFailed.title": "업데이트 실패",
   "desktop.updater.downloadFailed.message": "업데이트를 다운로드하지 못했습니다",
   "desktop.updater.downloaded.title": "업데이트 다운로드 완료",
-  "desktop.updater.downloaded.prompt": "OpenCode {{version}} 버전을 다운로드했습니다. 설치하고 다시 실행할까요?",
+  "desktop.updater.downloaded.prompt": "λ-Scientist {{version}} 버전을 다운로드했습니다. 설치하고 다시 실행할까요?",
   "desktop.updater.installFailed.title": "업데이트 실패",
   "desktop.updater.installFailed.message": "업데이트를 설치하지 못했습니다",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/no.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Oppdateringssjekk mislyktes",
   "desktop.updater.checkFailed.message": "Kunne ikke se etter oppdateringer",
   "desktop.updater.none.title": "Ingen oppdatering tilgjengelig",
-  "desktop.updater.none.message": "Du bruker allerede den nyeste versjonen av OpenCode",
+  "desktop.updater.none.message": "Du bruker allerede den nyeste versjonen av λ-Scientist",
   "desktop.updater.downloadFailed.title": "Oppdatering mislyktes",
   "desktop.updater.downloadFailed.message": "Kunne ikke laste ned oppdateringen",
   "desktop.updater.downloaded.title": "Oppdatering lastet ned",
   "desktop.updater.downloaded.prompt":
-    "Versjon {{version}} av OpenCode er lastet ned. Vil du installere den og starte på nytt?",
+    "Versjon {{version}} av λ-Scientist er lastet ned. Vil du installere den og starte på nytt?",
   "desktop.updater.installFailed.title": "Oppdatering mislyktes",
   "desktop.updater.installFailed.message": "Kunne ikke installere oppdateringen",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/pl.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Nie udało się sprawdzić aktualizacji",
   "desktop.updater.checkFailed.message": "Nie udało się sprawdzić aktualizacji",
   "desktop.updater.none.title": "Brak dostępnych aktualizacji",
-  "desktop.updater.none.message": "Korzystasz już z najnowszej wersji OpenCode",
+  "desktop.updater.none.message": "Korzystasz już z najnowszej wersji λ-Scientist",
   "desktop.updater.downloadFailed.title": "Aktualizacja nie powiodła się",
   "desktop.updater.downloadFailed.message": "Nie udało się pobrać aktualizacji",
   "desktop.updater.downloaded.title": "Aktualizacja pobrana",
   "desktop.updater.downloaded.prompt":
-    "Pobrano wersję {{version}} OpenCode. Czy chcesz ją zainstalować i uruchomić ponownie?",
+    "Pobrano wersję {{version}} λ-Scientist. Czy chcesz ją zainstalować i uruchomić ponownie?",
   "desktop.updater.installFailed.title": "Aktualizacja nie powiodła się",
   "desktop.updater.installFailed.message": "Nie udało się zainstalować aktualizacji",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/ru.ts

@@ -11,11 +11,11 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Не удалось проверить обновления",
   "desktop.updater.checkFailed.message": "Не удалось проверить обновления",
   "desktop.updater.none.title": "Обновлений нет",
-  "desktop.updater.none.message": "Вы уже используете последнюю версию OpenCode",
+  "desktop.updater.none.message": "Вы уже используете последнюю версию λ-Scientist",
   "desktop.updater.downloadFailed.title": "Обновление не удалось",
   "desktop.updater.downloadFailed.message": "Не удалось скачать обновление",
   "desktop.updater.downloaded.title": "Обновление загружено",
-  "desktop.updater.downloaded.prompt": "Версия OpenCode {{version}} загружена. Хотите установить и перезапустить?",
+  "desktop.updater.downloaded.prompt": "Версия λ-Scientist {{version}} загружена. Хотите установить и перезапустить?",
   "desktop.updater.installFailed.title": "Обновление не удалось",
   "desktop.updater.installFailed.message": "Не удалось установить обновление",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/uk.ts

@@ -11,12 +11,12 @@ export const dict = {
   "desktop.updater.checkFailed.title": "Не вдалося перевірити оновлення",
   "desktop.updater.checkFailed.message": "Не вдалося перевірити наявність оновлень",
   "desktop.updater.none.title": "Немає доступних оновлень",
-  "desktop.updater.none.message": "Ви вже використовуєте найновішу версію OpenCode",
+  "desktop.updater.none.message": "Ви вже використовуєте найновішу версію λ-Scientist",
   "desktop.updater.downloadFailed.title": "Помилка оновлення",
   "desktop.updater.downloadFailed.message": "Не вдалося завантажити оновлення",
   "desktop.updater.downloaded.title": "Оновлення завантажено",
   "desktop.updater.downloaded.prompt":
-    "Версію {{version}} OpenCode завантажено. Бажаєте встановити її та перезапустити?",
+    "Версію {{version}} λ-Scientist завантажено. Бажаєте встановити її та перезапустити?",
   "desktop.updater.installFailed.title": "Помилка оновлення",
   "desktop.updater.installFailed.message": "Не вдалося встановити оновлення",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/zh.ts

@@ -11,11 +11,11 @@ export const dict = {
   "desktop.updater.checkFailed.title": "检查更新失败",
   "desktop.updater.checkFailed.message": "无法检查更新",
   "desktop.updater.none.title": "没有可用更新",
-  "desktop.updater.none.message": "你已经在使用最新版本的 OpenCode",
+  "desktop.updater.none.message": "你已经在使用最新版本的 λ-Scientist",
   "desktop.updater.downloadFailed.title": "更新失败",
   "desktop.updater.downloadFailed.message": "无法下载更新",
   "desktop.updater.downloaded.title": "更新已下载",
-  "desktop.updater.downloaded.prompt": "已下载 OpenCode {{version}} 版本,是否安装并重启?",
+  "desktop.updater.downloaded.prompt": "已下载 λ-Scientist {{version}} 版本,是否安装并重启?",
   "desktop.updater.installFailed.title": "更新失败",
   "desktop.updater.installFailed.message": "无法安装更新",
 

+ 2 - 2
packages/desktop/src/renderer/i18n/zht.ts

@@ -11,11 +11,11 @@ export const dict = {
   "desktop.updater.checkFailed.title": "檢查更新失敗",
   "desktop.updater.checkFailed.message": "無法檢查更新",
   "desktop.updater.none.title": "沒有可用更新",
-  "desktop.updater.none.message": "你已在使用最新版的 OpenCode",
+  "desktop.updater.none.message": "你已在使用最新版的 λ-Scientist",
   "desktop.updater.downloadFailed.title": "更新失敗",
   "desktop.updater.downloadFailed.message": "無法下載更新",
   "desktop.updater.downloaded.title": "更新已下載",
-  "desktop.updater.downloaded.prompt": "已下載 OpenCode {{version}} 版本,是否安裝並重新啟動?",
+  "desktop.updater.downloaded.prompt": "已下載 λ-Scientist {{version}} 版本,是否安裝並重新啟動?",
   "desktop.updater.installFailed.title": "更新失敗",
   "desktop.updater.installFailed.message": "無法安裝更新",
 

Некоторые файлы не были показаны из-за большого количества измененных файлов