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

fix(desktop): 完善科研会话恢复与成果使用体验

科研任务跨刷新和导航继续执行时,需要可靠恢复提交回执、附件与草稿,并让用户直接使用交付成果。本次整合已验收的桌面交互修复及真实科研交付记录。

- 支持任务中心、增量会话缓存、历史同步和切换竞态保护,保留账号与窗口隔离
- 补齐提交幂等编号与回执恢复、上传进度和失败重试,避免断线后自动重复提交
- 支持报告导出、打开保存位置、基于方案继续编辑,以及会话搜索、重命名与本机归档
- 同步 beta.3 版本、原生验收脚本和界面回归,保留构建与会话性能验证记录
- 记录真实 DeepSeek 两轮规划交付、导出一致性及待人工审阅边界;本次不发布安装包
邵勃源 5 дней назад
Родитель
Сommit
6088601250

+ 74 - 0
PAAS_OPTIMIZATION_PLAN.zh-CN.md

@@ -90,3 +90,77 @@ 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 对接隔离后端,修复源码与验收记录随本次提交同步,未重新打包或正式发版;签名、公证与其他平台仍不在本次验收范围。

+ 1 - 1
bun.lock

@@ -381,7 +381,7 @@
     },
     "packages/desktop": {
       "name": "@opencode-ai/desktop",
-      "version": "0.1.0-beta.1",
+      "version": "0.1.0-beta.3",
       "dependencies": {
         "@zip.js/zip.js": "2.7.62",
         "effect": "catalog:",

+ 108 - 3
packages/app/e2e/paas/fixture.tsx

@@ -2,7 +2,7 @@ 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, PaasRequest } from "../../src/paas"
+import type { PaasPlatform, PaasRequest, PaasProgress, PaasUploadProgress } from "../../src/paas"
 import { PanelFixture } from "./panel-fixture"
 import "../../src/index.css"
 
@@ -17,15 +17,118 @@ const run: Record<string, unknown> = {
   output: "待核对研究计划",
   pending_approval: { approval_id: "approval_1", prompt: "是否执行验证?" },
 }
+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 })
 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 () => {},
+  onProgress: (listener) => {
+    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 === "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") return { runs: [...uxRuns.values()] }
+      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 === "agents") return { agents: [agent] }
     if (request.action === "run-options") throw new Error("HTTP 404")
     if (request.action === "threads") return { threads: [{ id: "thread_1", title: "已有研究" }] }
@@ -55,13 +158,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 === "download" || request.action === "export-report")
+      return { saved: true, name: "研究报告.md", path: "/tmp/研究报告.md" }
     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,

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

@@ -0,0 +1,169 @@
+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.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 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(
+    /已有的补充要求[\s\S]*可追溯研究方案/,
+  )
+  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("仍在编辑的要求")
+})

+ 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()
+})

+ 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")
 })

+ 15 - 3
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 }
   | 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 }
   | {
@@ -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"
 }
 

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

@@ -0,0 +1,118 @@
+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([])
+  })
+})

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

@@ -0,0 +1,165 @@
+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,
+  }
+  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
+      }
+      onError("")
+    } catch {
+      state.indexDirty = true
+      onError("本机暂时无法保存部分内容,当前窗口中的草稿仍保留,可先导出重要报告。")
+    }
+  }
+  const read = <T>(key: string, fallback: T): T => {
+    const raw = storage.getItem(key)
+    if (!raw) return fallback
+    return JSON.parse(raw) as T
+  }
+  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 index = read<Index>(`${source}:index`, { ids: [], 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,
+      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)
+    },
+  }
+}

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

@@ -0,0 +1,703 @@
+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
+  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
+      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(() => 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() || job(chat) || !props.connected || !props.api) return
+    if (chat.draft.trim().length > 100000) {
+      setState("error", "单次任务最多支持 100000 个字符,可将较长内容作为研究材料上传。")
+      return
+    }
+    life.navigation++
+    setState("syncing", "")
+    const epoch = life.epoch
+    const input = chat.draft.trim(),
+      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: "",
+      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
+    const context = `请基于以下方案继续研究:\n\n${message.text}`
+    setState("chats", (c) => c.id === chat.id, "draft", chat.draft.trim() ? `${chat.draft}\n\n${context}` : context)
+    save()
+  }
+  return {
+    state,
+    setState,
+    current,
+    job,
+    choose,
+    activate,
+    restore,
+    openTask,
+    lookup,
+    send,
+    refresh,
+    update,
+    recover,
+    rename,
+    archive,
+    continueFrom,
+    save,
+  }
+}

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


+ 8 - 1
packages/app/src/pages/paas/controller.ts

@@ -9,6 +9,7 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
     apiKey: "",
     remember: true,
     remembered: false,
+    scope: "",
     connected: false,
     busy: "",
     error: "",
@@ -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 : "目录读取失败。")
       })

+ 107 - 190
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,8 +14,8 @@ 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 "./paas.css"
@@ -41,7 +41,48 @@ 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: "",
+  })
+  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 +197,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,6 +218,31 @@ 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 页面可查看工作台入口,尚未接入平台传输服务。
@@ -186,6 +263,14 @@ 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")}
+              openTask={ui.chatTask}
+              onTaskOpened={() => setUI("chatTask", undefined)}
               visible={state.page === "chat"}
               agents={state.agents}
               openAgentID={ui.chatAgentID}
@@ -206,7 +291,8 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
               <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 +341,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}>
                       连接平台
@@ -377,7 +463,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() {
@@ -467,15 +553,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>Skill / MCP 资源</h1>
+                  <p>检查智能体的资源连接,不会运行研究任务。</p>
                 </div>
               </div>
               <div class="paas-toolbar">
@@ -486,111 +578,15 @@ 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
-                  class="paas-primary"
-                  disabled={disabled() || !state.agentID}
-                  onClick={() => (state.page === "tasks" ? workspace.history() : workspace.verify())}
-                >
-                  {state.page === "tasks" ? "刷新任务" : "检查资源"}
+                <button disabled={disabled() || !state.agentID} onClick={() => void workspace.verify()}>
+                  检查资源
                 </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
-                          ? "仅展示此次平台返回的记录。可调整筛选或再次刷新。"
-                          : "任务查询不会重新执行或取消远端任务。"
-                      }
-                    />
-                  }
-                >
-                  <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.detail(paasText(run.run_id))}
-                                >
-                                  查看详情
-                                </button>
-                              </td>
-                            </tr>
-                          )}
-                        </For>
-                      </tbody>
-                    </table>
-                  </div>
-                </Show>
-                <Show when={state.selected}>
-                  {(run) => (
-                    <>
-                      <RunDetail
-                        run={run()}
-                        close={() => workspace.setState("selected", undefined)}
-                        refresh={() => workspace.detail(paasText(run().run_id))}
-                        busy={!!state.busy}
-                      />
-                      <Show when={platform.paas}>
-                        <PaasRunPanel api={platform.paas!} agentID={state.agentID} runID={paasText(run().run_id)} />
-                      </Show>
-                    </>
-                  )}
-                </Show>
-              </Show>
               <Show when={state.page === "resources"}>
                 <Show
                   when={state.verified}
@@ -671,82 +667,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>
-  )
-}
-
-function RunDetail(props: {
-  run: Record<string, unknown>
-  close: () => void
-  refresh: () => Promise<void>
-  busy: boolean
-}) {
-  const artifacts = () =>
-    Array.isArray(props.run.artifacts)
-      ? props.run.artifacts.flatMap((item) => (paasRecord(item) ? [paasRecord(item)!] : []))
-      : []
-  return (
-    <section class="paas-panel paas-detail" aria-label="任务详情">
-      <div class="paas-section-title">
-        <div>
-          <span class="paas-eyebrow">运行快照</span>
-          <h2>{paasText(props.run.run_id)}</h2>
-        </div>
-        <div class="paas-actions">
-          <button disabled={props.busy} onClick={props.refresh}>
-            刷新详情
-          </button>
-          <button onClick={props.close}>收起</button>
-        </div>
-      </div>
-      <Status run={props.run} />
-      <Show when={props.run.client_detail_source === "history"}>
-        <p class="paas-notice">
-          当前平台未提供单条任务详情,此处展示刚刚读取的最近任务记录。成果与审批信息可能不包含在列表中。
-        </p>
-      </Show>
-      <p class="paas-muted">执行完成不代表科研结论已验证。关闭详情不会停止远端任务。</p>
-      <Show when={paasText(props.run.input)}>
-        <h3>任务目标</h3>
-        <p class="paas-output">{paasText(props.run.input)}</p>
-      </Show>
-      <h3>执行结果</h3>
-      <p class="paas-output">{paasText(props.run.output) || "平台暂未返回文本结果。"}</p>
-      <Show when={props.run.error_message}>
-        <p class="paas-error">{paasText(props.run.error_message)}</p>
-      </Show>
-      <For each={["pending_approval", "pending_confirmation"]}>
-        {(key) => (
-          <Show when={paasRecord(props.run[key])}>
-            {(approval) => (
-              <div class="paas-notice">
-                <h3>待处理材料</h3>
-                <p>请在下方任务面板中核对并提交确认。</p>
-                <pre>{JSON.stringify(approval(), null, 2)}</pre>
-              </div>
-            )}
-          </Show>
-        )}
-      </For>
-      <h3>成果清单 · {artifacts().length}</h3>
-      <For each={artifacts()} fallback={<p class="paas-muted">平台尚未登记成果文件。</p>}>
-        {(artifact) => (
-          <div class="paas-artifact">
-            <strong>{paasText(artifact.name) || "成果文件"}</strong>
-            <code>{paasText(artifact.artifact_id)}</code>
-            <small>可在下方任务面板中保存成果和工作文件。</small>
-          </div>
-        )}
-      </For>
-      <details>
-        <summary>查看平台原始记录</summary>
-        <pre>{JSON.stringify(props.run, null, 2)}</pre>
-      </details>
-    </section>
-  )
-}

+ 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))
+    },
+  }
+}

+ 238 - 0
packages/app/src/pages/paas/paas.css

@@ -1699,3 +1699,241 @@
   flex-basis: 100%;
   margin: 0;
 }
+
+/* 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;
+}

+ 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()} />
+}

+ 74 - 7
packages/app/src/pages/paas/run-panel.tsx

@@ -1,4 +1,6 @@
 import { For, Show, createEffect, on, onCleanup } from "solid-js"
+import { ResearchReport } from "./report"
+import { usePlatform } from "@/context/platform"
 import { createStore, reconcile } from "solid-js/store"
 import {
   paasRecord,
@@ -30,8 +32,10 @@ export function PaasRunPanel(props: {
   api: PaasPlatform
   agentID: string
   runID: string
+  hideOutput?: boolean
   onUpdate?: (run: Record<string, unknown>) => void
 }) {
+  const platform = usePlatform()
   const [state, setState] = createStore({
     run: {} as Record<string, unknown>,
     files: [] as Record<string, unknown>[],
@@ -40,6 +44,7 @@ export function PaasRunPanel(props: {
     syncError: "",
     note: "",
     message: "",
+    savedPath: "",
     filesLoaded: false,
   })
   const status = () => paasStatus(state.run)
@@ -49,7 +54,7 @@ export function PaasRunPanel(props: {
     if (value?.status && !["pending", "waiting"].includes(paasText(value.status))) return undefined
     return value
   }
-  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
   })
@@ -66,6 +71,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)
@@ -78,7 +87,17 @@ export function PaasRunPanel(props: {
   createEffect(
     on([() => props.api, () => props.agentID, () => props.runID], () => {
       lifecycle.epoch++
-      setState({ files: [], filesLoaded: false, busy: "", error: "", syncError: "", note: "", message: "" })
+      lifecycle.filesFor = ""
+      setState({
+        files: [],
+        filesLoaded: false,
+        busy: "",
+        error: "",
+        syncError: "",
+        note: "",
+        message: "",
+        savedPath: "",
+      })
       setState("run", reconcile({}))
       void refresh(true)
       const timer = window.setInterval(() => {
@@ -95,6 +114,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
@@ -107,7 +143,8 @@ 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") {
-        if (paasRecord(result)?.saved) setState("message", "文件已保存。")
+        if (paasRecord(result)?.saved)
+          setState({ message: "文件已保存。", savedPath: paasText(paasRecord(result)?.path) })
       } else {
         setState("message", "操作已提交,正在同步任务状态。")
         await refresh(true)
@@ -195,11 +232,27 @@ export function PaasRunPanel(props: {
       </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">
             <strong>需要你的确认</strong>
+            <Show when={paasText(item().stage_name)}>
+              <p>当前阶段:{paasText(item().stage_name)}</p>
+            </Show>
             <p>
               {paasText(item().message) ||
                 paasText(item().prompt) ||
@@ -207,12 +260,15 @@ 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>
-              <summary>查看待确认内容</summary>
+              <summary>查看原始确认记录</summary>
               <pre>{JSON.stringify(item(), null, 2)}</pre>
             </details>
             <label>
-              反馈意见(可选)
+              本轮反馈意见(可选)
               <textarea value={state.note} onInput={(event) => setState("note", event.currentTarget.value)} />
             </label>
             <div class="paas-actions">
@@ -226,10 +282,21 @@ export function PaasRunPanel(props: {
           </div>
         )}
       </Show>
-      <Show when={paasText(state.run.output)}>
+      <Show when={!props.hideOutput && paasText(state.run.output)}>
         <details>
           <summary>查看最新结果</summary>
-          <p class="paas-output">{paasText(state.run.output)}</p>
+          <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>
       <For each={artifacts()}>

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

@@ -0,0 +1,221 @@
+import { For, Show, createEffect, createMemo, on, onCleanup } from "solid-js"
+import { createStore, reconcile } from "solid-js/store"
+import { paasRows, 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: "",
+  })
+  const life = { epoch: 0, active: true, request: 0 }
+  async function refresh() {
+    if (!props.connected || !props.api || state.loading) return
+    const epoch = life.epoch,
+      request = ++life.request
+    setState("loading", true)
+    const agents = props.agents.slice()
+    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 response = await props.api!.request({ action: "history", agentID: id })
+              results.push(
+                ...paasRows(response, "runs").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
+      }
+      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)
+        })
+        setState("rows", reconcile(results, { 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: "" })
+      if (props.connected) void refresh()
+    }),
+  )
+  const timer = setInterval(() => void refresh(), 10000)
+  onCleanup(() => {
+    life.active = false
+    clearInterval(timer)
+  })
+  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 }
+}
+
+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>
+      <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>
+      <p class="paas-muted">展示平台返回的最近记录;状态变化不会重新执行任务。</p>
+    </section>
+  )
+}

+ 1 - 1
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.3",
   "type": "module",
   "license": "MIT",
   "author": {

+ 19 - 4
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 = {
@@ -73,21 +74,35 @@ 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 : 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(new RegExp(run.output))
     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")

+ 65 - 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,38 @@ 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 selected = await dialog.showSaveDialog({
+        title: "导出研究报告",
+        defaultPath: `${basename(input.name).replace(/\.md$/i, "") || "研究报告"}.md`,
+        filters: [{ name: "Markdown", extensions: ["md"] }],
+      })
+      if (selected.canceled || !selected.filePath) return { saved: false }
+      const temporary = `${selected.filePath}.${crypto.randomUUID()}.export`
+      try {
+        await writeFile(temporary, input.text, { encoding: "utf8", 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 +191,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)

+ 118 - 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("请先连接")
@@ -114,9 +114,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 +361,117 @@ 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)
+  }
+})

+ 80 - 18
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(() => {
@@ -98,7 +125,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 +140,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 +206,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 +224,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("缺少任务编号。")

+ 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)

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