Sfoglia il codice sorgente

fix(desktop): preserve research context across developer handoff

邵勃源 5 giorni fa
parent
commit
11f5144f0e

+ 25 - 6
PAAS_OPTIMIZATION_PLAN.zh-CN.md

@@ -217,12 +217,12 @@ bun run package:beta  # 正式签名安装包,需提供对应系统签名、
 |UX-07|1|已修复|取消保存被误报为平台未返回确认。明确显示已取消保存,平台文件仍保留;原生验收验证取消时不创建本地文件。|
 |UX-07|1|已修复|取消保存被误报为平台未返回确认。明确显示已取消保存,平台文件仍保留;原生验收验证取消时不创建本地文件。|
 |UX-08|1|已修复|平台目录可访问但执行服务不可用时提示笼统。真实 HTTP 复现 LOCAL_SERVICE_UNAVAILABLE。主进程识别执行服务未就绪,任务详情保留原始诊断,不再统一吞成网络错误。|
 |UX-08|1|已修复|平台目录可访问但执行服务不可用时提示笼统。真实 HTTP 复现 LOCAL_SERVICE_UNAVAILABLE。主进程识别执行服务未就绪,任务详情保留原始诊断,不再统一吞成网络错误。|
 |UX-09|1|已修复|原生验收脚本沿用旧界面按钮名称。适配“添加文件”和自动加载后的“刷新工作文件”,新增取消下载检查;重新运行打包应用验收。|
 |UX-09|1|已修复|原生验收脚本沿用旧界面按钮名称。适配“添加文件”和自动加载后的“刷新工作文件”,新增取消下载检查;重新运行打包应用验收。|
-|UX-10|2|待优化|科研工作台与 OpenCode 开发区还未形成顺畅往返。独立模式“打开工作区”调用 openPath,打开的是系统文件管理器;切入开发区会卸载独立工作台。需明确“查看目录”与“在开发区继续”,并设计返回原研究会话路径。|
-|UX-11|2|待优化|研究设置的未保存编辑可能随离开而丢失。配置页把编辑保存在局部状态,侧栏换页/关闭会卸载;下一轮保留草稿并提供恢复,不为每次离开新增强制审批。|
-|UX-12|2|已复现,待优化|行内数学公式仍显示源文本。打包截图中的 $\delta > 0$ 未渲染;当前归一化主要处理块公式。需补行内公式与代码/金额边界回归,保持流式阅读稳定。|
-|UX-13|2|待优化|报告版本与导出的研究语义仍不足。对比范围是同会话已交付报告,版本标签主要是序号/任务 ID;Word/PDF 公式保持源文本、图片不嵌入。需增加可辨识的版本时间/目标、明确导出范围,再完善科研排版。|
-|UX-14|2|待优化|任务控制能力与后端状态依赖仍需更直观。暂停/恢复按钮主要依赖运行状态与 checkpoint;远端目录在本机不可打开。应按后端能力说明操作条件,提供可用的导出/查看替代路径。|
-|UX-15|2|待专项验收|凭证轮换与长任务恢复仍有需要验收的边界。当前缓存 scope 由地址与 API Key 派生;同一用户更换 Key 后会进入新缓存分区,需设计可靠的账户身份映射,避免跨账户混用。同时补测大量工具回执、目录变动与大历史,不把基础性能测试等同于生产长任务验收。|
+|UX-10|2|已修复|科研工作台与 OpenCode 开发区还未形成顺畅往返。科研工作台与开发区均保留挂载状态,支持直接返回原会话;本机目录经主进程校验后登记为 OpenCode 项目并打开开发草稿。交接等待首次启动完成,返回入口不被启动遮罩挡住。|
+|UX-11|2|已修复|研究设置的未保存编辑可能随离开而丢失。设置草稿按账号缓存分区和智能体分别保存在当前窗口内存;切页恢复、明确放弃、保存后清理。保留原配置版本以阻止覆盖别人更新的设置;读取失败不删除既有草稿。不持久化可能包含密钥的配置。|
+|UX-12|2|已修复|行内数学公式仍显示源文本。补齐 $...$ 行内数学公式,保留块公式、代码与金额文本;浏览器验收验证实际 KaTeX 渲染。|
+|UX-13|2|版本展示已优化;导出排版待增强|报告版本与导出的研究语义仍不足。报告标签增加标题、记录时间、任务状态和任务编号后缀;明确对比同会话不同任务的报告,不是任务内部研究轮次。Word/PDF 仍保留公式源码、图片链接不自动下载,后续另做科研排版。|
+|UX-14|2|状态提示已优化;能力协商待补齐|任务控制能力与后端状态依赖仍需更直观。仅运行中任务显示暂停;暂停请求中及缺少恢复点有明确说明。远程工作区提前说明无法在本机直开,并提示先下载工作文件;不影响发送研究任务。跨运行时的暂停能力仍由后端最终确认,尚无统一能力协议。|
+|UX-15|2|身份与交互边界已验收;真实长任务待复验|凭证轮换与长任务恢复仍有需要验收的边界。同地址、租户、用户、角色和权限集的凭证轮换共用会话分区;旧 Key 分区按当前已认证凭证迁移,先复制正文,保持账号/权限隔离。不支持身份端点的旧服务继续按 Key 隔离。工具活动折叠后不渲染全文,展开先显示最近50条、可加载此前记录;明确本机最近80条事件限制。目录排序变化不再重置任务索引。真实模型长任务留待第三轮。|
 |UX-16|3|待优化|首次安装不包含后台与模型的一站式配置。桌面仍需可访问的 PaaS、Local/Remote Agent Service 与模型配置。“目录连接成功”不是执行就绪。下一轮提供分层诊断与部署指引,可跳过,不强制所有资源都通过。|
 |UX-16|3|待优化|首次安装不包含后台与模型的一站式配置。桌面仍需可访问的 PaaS、Local/Remote Agent Service 与模型配置。“目录连接成功”不是执行就绪。下一轮提供分层诊断与部署指引,可跳过,不强制所有资源都通过。|
 |UX-17|3|待优化|资源管理入口还不是完整平台管理能力。资源页是检查与配置入口;Skill/MCP 全生命周期、通用定时任务尚未实现,远端 Pack 创建/管理存在浏览器交接。需区分普通用户与管理员任务,逐步补齐。|
 |UX-17|3|待优化|资源管理入口还不是完整平台管理能力。资源页是检查与配置入口;Skill/MCP 全生命周期、通用定时任务尚未实现,远端 Pack 创建/管理存在浏览器交接。需区分普通用户与管理员任务,逐步补齐。|
 |UX-18|3|待发布验收|正式分发与真实模型完整体验尚未完成本轮复验。本轮为 macOS arm64 未签名内测;未覆盖签名、公证、自有更新源、Windows/Linux、全键盘可达性及真实模型全链路长任务。当前测试结果不能替代这些发布条件。|
 |UX-18|3|待发布验收|正式分发与真实模型完整体验尚未完成本轮复验。本轮为 macOS arm64 未签名内测;未覆盖签名、公证、自有更新源、Windows/Linux、全键盘可达性及真实模型全链路长任务。当前测试结果不能替代这些发布条件。|
@@ -239,3 +239,22 @@ bun run package:beta  # 正式签名安装包,需提供对应系统签名、
 证据目录:`/Users/shaoboyuan/seecoder/output/desktop-round1-20261129/`。第二、三轮尚未实施;第一轮仅改善状态、连接恢复与成果获取,不改变科研执行算法。
 证据目录:`/Users/shaoboyuan/seecoder/output/desktop-round1-20261129/`。第二、三轮尚未实施;第一轮仅改善状态、连接恢复与成果获取,不改变科研执行算法。
 
 
 本轮性能复验:修改前后各 5 项生产基准通过,消息行和 Markdown 无重建,底部滚动漂移均为 0。四项流式完成时间改前 52.26 / 54.24 / 54.58 / 54.65 秒,改后 54.52 / 51.64 / 52.47 / 55.71 秒;单次合成 CPU 压力测量不作为用户实际速度或性能提升结论。最终仅对连接提示去重,未改变基准所覆盖的会话时间线,并单独复验连接流程。
 本轮性能复验:修改前后各 5 项生产基准通过,消息行和 Markdown 无重建,底部滚动漂移均为 0。四项流式完成时间改前 52.26 / 54.24 / 54.58 / 54.65 秒,改后 54.52 / 51.64 / 52.47 / 55.71 秒;单次合成 CPU 压力测量不作为用户实际速度或性能提升结论。最终仅对连接提示去重,未改变基准所覆盖的会话时间线,并单独复验连接流程。
+
+## 第二轮:科研与开发衔接、草稿与报告可恢复性(2026-11-29)
+
+本轮在 `qjh` 第一轮提交 `e6bb09b00` 之上修改;上方问题清单为当前状态,第一轮记录中的“第二轮尚未实施”为历史快照。
+
+- 科研与开发区保留挂载,返回时保留原会话、草稿和附件。本机目录经主进程校验后登记为 OpenCode 项目并打开开发草稿;等待首次启动完成再交接。返回入口始终可用。截图检查发现并修复父容器布局裁切开发输入区的问题。
+- 研究设置按账号缓存分区和智能体保留当前窗口的未保存草稿,支持恢复、放弃、保存后清理;配置读取失败不删除旧草稿。后台版本变化时保留原始 expected_updated_at,阻止覆盖他人更新。配置草稿可能含凭证,仅保存在内存,不写明文缓存。
+- 报告补齐行内数学公式、保留代码和金额;版本标签增加标题、记录时间、任务状态和编号,明确不同任务报告与内部研究轮次的区别。折叠工具活动不渲染全文,展开先展示最近50条,再加载更早项;仍保留原有80条本机事件上限,并说明范围。
+- 仅运行中任务提供暂停,暂停请求中与缺少检查点有说明;远端目录提示先下载文件再进入开发区,不阻断研究任务。运行时是否支持暂停仍由后端确认。
+- `/auth/me` 返回的地址、租户、用户、角色与权限集形成稳定缓存分区。相同身份和权限换Key后可延续会话;当前凭证的旧分区先完整复制后迁移。旧服务仍按Key隔离,不能凭新Key任意推断已丢失旧Key的缓存归属。
+- 智能体目录仅顺序变化时,不再清空任务索引和已展开记录。不增加强制资源预检、不自动提高预算、不自动重发任务。
+
+验证:完整界面回归42项通过;最后补充设置异常草稿恢复,6项专项复验通过,共覆盖43个不同场景。桌面传输/连接存储/导出23项,缓存与进展9项通过;App、Desktop、E2E类型检查通过。实际Desktop传输连接隔离真实PaaS与Local Agent Service,13项HTTP检查通过,包含身份轮换和文件字节传输;运行记录预置,模型调用0。原生包验收覆盖科研/开发往返、指定目录与可见可编辑的开发输入、附件恢复、文件保存与取消、Markdown/Word/PDF导出;HTTP和原生文件选择使用测试夹具。
+
+修改前后各5项生产基准通过。四项流式时间改前52.45 / 52.47 / 50.94 / 51.96秒,改后49.26 / 48.85 / 50.16 / 51.42秒;消息行和Markdown均未重建,底部滚动漂移为0。单轮合成压力测试不作为性能提升结论。
+
+报告:`/Users/shaoboyuan/seecoder/output/desktop-round2-20261129/Desktop第二轮验收报告.html`。未重启日常应用或服务。本轮尚未推送。内部包为macOS arm64未签名Beta,不构成正式发布。
+
+第三轮继续处理部署就绪诊断、资源管理与管理员交接、真实模型完整流程及发布条件。Word/PDF公式仍以源码导出,图片不自动下载;跨运行时暂停能力协商、签名公证及Windows/Linux实机验收尚未完成。

+ 10 - 1
packages/app/e2e/paas/fixture.tsx

@@ -53,6 +53,8 @@ const ux = {
   connectError: "",
   connectError: "",
   catalogError: "",
   catalogError: "",
   emptyCatalog: false,
   emptyCatalog: false,
+  configVersion: "version-1",
+  configError: false,
   release: () => {},
   release: () => {},
   add: (value: Record<string, unknown>) => uxRuns.set(String(value.run_id), value),
   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),
   update: (id: string, value: Record<string, unknown>) => Object.assign(uxRuns.get(id) || {}, value),
@@ -94,9 +96,16 @@ const api: PaasPlatform = {
     if (request.action === "agents" && ux.catalogError) throw new Error(ux.catalogError)
     if (request.action === "agents" && ux.catalogError) throw new Error(ux.catalogError)
     if (request.action === "agents" && ux.emptyCatalog) return { agents: [] }
     if (request.action === "agents" && ux.emptyCatalog) return { agents: [] }
     if (ux.enabled) {
     if (ux.enabled) {
+      if (request.action === "agent" && ux.configError) throw new Error("配置服务暂时不可用")
       if (request.action === "agent")
       if (request.action === "agent")
-        return { ...agent, config: structuredClone(researchConfig), updated_at: "version-1", can_update_metadata: true }
+        return {
+          ...agent,
+          config: structuredClone(researchConfig),
+          updated_at: ux.configVersion,
+          can_update_metadata: true,
+        }
       if (request.action === "update-agent") {
       if (request.action === "update-agent") {
+        if (request.update.expected_updated_at !== ux.configVersion) throw new Error("配置版本已更新,请重新读取。")
         researchConfig = request.update.config as typeof researchConfig
         researchConfig = request.update.config as typeof researchConfig
         return { saved: true }
         return { saved: true }
       }
       }

+ 11 - 0
packages/app/e2e/paas/panel.spec.ts

@@ -116,3 +116,14 @@ test("task sync preserves execution-service diagnostics and recovers on retry",
   await page.getByRole("button", { name: "刷新状态" }).click()
   await page.getByRole("button", { name: "刷新状态" }).click()
   await expect(page.getByRole("alert")).toHaveCount(0)
   await expect(page.getByRole("alert")).toHaveCount(0)
 })
 })
+
+test("queued tasks cannot request an unsupported pause and missing checkpoints explain recovery", async ({ page }) => {
+  await page.evaluate(() => window.paasPanelTest.update({ status: "queued" }))
+  await page.getByRole("button", { name: "刷新状态" }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toHaveCount(0)
+  await expect(page.getByRole("button", { name: "停止任务", exact: true })).toBeVisible()
+  await page.evaluate(() => window.paasPanelTest.update({ status: "paused" }))
+  await page.getByRole("button", { name: "刷新状态" }).click()
+  await expect(page.getByText(/平台尚未返回恢复点/)).toBeVisible()
+  await expect(page.getByRole("button", { name: "继续执行", exact: true })).toHaveCount(0)
+})

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

@@ -10,6 +10,9 @@ declare global {
       connectError: string
       connectError: string
       catalogError: string
       catalogError: string
       emptyCatalog: boolean
       emptyCatalog: boolean
+      configVersion: string
+      configError: boolean
+      progress(event: import("../../src/paas").PaasProgress): void
       release(): void
       release(): void
     }
     }
     paasTestCalls: Record<string, unknown>[]
     paasTestCalls: Record<string, unknown>[]

+ 118 - 0
packages/app/e2e/paas/round2.spec.ts

@@ -0,0 +1,118 @@
+import { expect, test, type Page } from "@playwright/test"
+
+async function connect(page: Page) {
+  await page.goto("/e2e/paas/index.html?ux")
+  await page.getByLabel("API Key", { exact: true }).fill("round2-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeEnabled()
+}
+
+test("settings survive navigation, stay unapplied until saved, and can be discarded", async ({ page }) => {
+  await connect(page)
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  const rounds = page.getByLabel("最多研究轮次", { exact: true })
+  await expect(rounds).toHaveValue("4")
+  await rounds.fill("8")
+  await page.getByRole("button", { name: "返回工作台" }).click()
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await expect(rounds).toHaveValue("8")
+  await expect(page.getByText(/已恢复未保存的修改/)).toBeVisible()
+  expect(await page.evaluate(() => window.paasTestCalls.filter((c) => c.action === "update-agent"))).toHaveLength(0)
+  await page.getByRole("button", { name: "放弃草稿并读取最新配置" }).click()
+  await expect(rounds).toHaveValue("4")
+  await rounds.fill("7")
+  await page.getByRole("button", { name: /保存修改/ }).click()
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await expect(rounds).toHaveValue("7")
+  await expect(page.getByText(/已恢复未保存的修改/)).toHaveCount(0)
+})
+
+test("settings from an older version are retained but cannot silently overwrite newer settings", async ({ page }) => {
+  await connect(page)
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await page.getByLabel("最多研究轮次", { exact: true }).fill("8")
+  await page.getByRole("button", { name: "返回工作台" }).click()
+  await page.evaluate(() => {
+    window.paasUX.configVersion = "version-2"
+  })
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await expect(page.getByLabel("最多研究轮次", { exact: true })).toHaveValue("8")
+  await expect(page.getByText(/平台配置已更新,已保留你的草稿/)).toBeVisible()
+  await page.getByRole("button", { name: /保存修改/ }).click()
+  await expect(page.getByText(/配置版本已更新/)).toBeVisible()
+})
+
+test("report renders inline math without rewriting currency and code", async ({ page }, info) => {
+  await connect(page)
+  await page.evaluate(() =>
+    window.paasUX.add({
+      run_id: "math",
+      agent_id: "research",
+      thread_id: "math",
+      input: "公式验收",
+      status: "completed",
+      output:
+        "# 数学报告\n\n判断 $\\delta > 0$,区间 \\(x \\in [0,1]\\)。\n\n$$x^2 + y^2 = 1$$\n\n预算 $5 和 $10。\n\n`$raw$`\n\n```text\n$literal$\n```",
+    }),
+  )
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await page.getByRole("row").filter({ hasText: "公式验收" }).getByRole("button", { name: "打开任务" }).click()
+  await page.getByRole("button", { name: "阅读与对比", exact: true }).click()
+  const dialog = page.getByRole("dialog")
+  await expect(dialog.locator(".katex")).toHaveCount(3)
+  await expect(dialog).toContainText("预算 $5 和 $10")
+  await expect(dialog.locator("code").filter({ hasText: "$raw$" })).toBeVisible()
+  await expect(dialog).toContainText("$literal$")
+  await page.screenshot({ path: info.outputPath("math-report.png"), fullPage: true })
+})
+
+test("long tool activity loads recent entries first and retains access to older entries", async ({ page }) => {
+  await connect(page)
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("长任务")
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+  await page.evaluate(() => {
+    const executionID = String(window.paasTestCalls.find((c) => c.action === "execute")?.executionID)
+    for (let i = 0; i < 123; i++)
+      window.paasUX.progress({ executionID, type: "tool_result", tool: "lookup", content: `活动记录 ${i + 1}` })
+  })
+  const activity = page.locator(".paas-activity").first()
+  await expect(activity.locator("li")).toHaveCount(0)
+  await activity.locator("summary").first().click()
+  await expect(activity.locator("li")).toHaveCount(50)
+  await expect(activity).toContainText("活动记录 123")
+  await activity.getByRole("button", { name: /加载更早活动/ }).click()
+  await expect(activity.locator("li")).toHaveCount(80)
+  await expect(activity).toContainText("活动记录 44")
+  await expect(activity.getByRole("button", { name: /加载更早活动/ })).toHaveCount(0)
+})
+
+test("remote workspaces explain downloading files instead of offering a broken local open", async ({ page }) => {
+  await page.goto("/e2e/paas/index.html?ux")
+  await page.getByLabel("平台地址", { exact: true }).fill("https://remote.example")
+  await page.getByLabel("API Key", { exact: true }).fill("round2-test")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await page.locator(".paas-more-actions > summary").click()
+  await expect(page.getByRole("button", { name: "在开发区打开工作区", exact: true })).toBeDisabled()
+  await expect(page.getByText(/远程目录不能直接在本机打开/)).toBeVisible()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeEnabled()
+})
+
+test("a failed settings reload does not erase the retained draft", async ({ page }) => {
+  await connect(page)
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await page.getByLabel("最多研究轮次", { exact: true }).fill("9")
+  await page.getByRole("button", { name: "返回工作台" }).click()
+  await page.evaluate(() => {
+    window.paasUX.configError = true
+  })
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await expect(page.getByText("配置服务暂时不可用")).toBeVisible()
+  await page.getByRole("button", { name: "返回工作台" }).click()
+  await page.evaluate(() => {
+    window.paasUX.configError = false
+  })
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await expect(page.getByLabel("最多研究轮次", { exact: true })).toHaveValue("9")
+})

+ 17 - 1
packages/app/src/app.tsx

@@ -34,6 +34,7 @@ import {
   type JSX,
   type JSX,
   lazy,
   lazy,
   onCleanup,
   onCleanup,
+  onMount,
   type ParentProps,
   type ParentProps,
   Show,
   Show,
 } from "solid-js"
 } from "solid-js"
@@ -634,11 +635,26 @@ function Routes(props: { serverScoped?: JSX.Element }) {
         <Route path="/server/:serverKey/session/:id" component={TargetSessionRoute} />
         <Route path="/server/:serverKey/session/:id" component={TargetSessionRoute} />
       </Show>
       </Show>
       <Route path="/new-session" component={DraftRoute} />
       <Route path="/new-session" component={DraftRoute} />
-      <Route path="/paas" component={() => <PaasWorkspace />} />
+      <Route path="/paas" component={ResearchWorkspaceRoute} />
     </>
     </>
   )
   )
 }
 }
 
 
+function ResearchWorkspaceRoute() {
+  const platform = usePlatform()
+  const navigate = useNavigate()
+  onMount(() => {
+    if (!platform.openResearchWorkspace) return
+    navigate("/", { replace: true })
+    platform.openResearchWorkspace()
+  })
+  return (
+    <Show when={!platform.openResearchWorkspace}>
+      <PaasWorkspace />
+    </Show>
+  )
+}
+
 function NewLayoutLegacySessionRedirect() {
 function NewLayoutLegacySessionRedirect() {
   const server = useServer()
   const server = useServer()
   const tabs = useTabs()
   const tabs = useTabs()

+ 1 - 0
packages/app/src/context/platform.tsx

@@ -30,6 +30,7 @@ export type FatalRendererErrorLog = {
 
 
 type PlatformBase = {
 type PlatformBase = {
   paas?: PaasPlatform
   paas?: PaasPlatform
+  openResearchWorkspace?: () => void
   /** App version */
   /** App version */
   version?: string
   version?: string
 
 

+ 1 - 1
packages/app/src/paas.ts

@@ -85,7 +85,7 @@ export type PaasPlatform = {
     url: string
     url: string
     apiKey: string
     apiKey: string
     remember?: boolean
     remember?: boolean
-  }) => Promise<{ url: string; remembered?: boolean; scope?: string }>
+  }) => Promise<{ url: string; remembered?: boolean; scope?: string; legacyScope?: string }>
   onProgress?: (listener: (event: PaasProgress) => void) => () => void
   onProgress?: (listener: (event: PaasProgress) => void) => () => void
   disconnect: (forget?: boolean) => Promise<void>
   disconnect: (forget?: boolean) => Promise<void>
   request: (input: PaasRequest) => Promise<unknown>
   request: (input: PaasRequest) => Promise<unknown>

+ 35 - 26
packages/app/src/pages/paas/activity.tsx

@@ -1,4 +1,5 @@
-import { For, Show } from "solid-js"
+import { For, Show, createMemo } from "solid-js"
+import { createStore } from "solid-js/store"
 import { paasRecord, paasText } from "@/paas"
 import { paasRecord, paasText } from "@/paas"
 
 
 export type PaasActivityItem = { kind: string; tool: string; content: string }
 export type PaasActivityItem = { kind: string; tool: string; content: string }
@@ -21,33 +22,41 @@ export function paasActivityItems(value: unknown): PaasActivityItem[] {
 }
 }
 
 
 export function PaasActivity(props: { items: PaasActivityItem[]; raw?: unknown; empty?: string }) {
 export function PaasActivity(props: { items: PaasActivityItem[]; raw?: unknown; empty?: string }) {
+  const [state, setState] = createStore({ open: false, count: 50, raw: false })
+  const items = createMemo(() => props.items.slice(-state.count))
   return (
   return (
-    <Show
-      when={props.items.length}
-      fallback={props.empty ? <p class="paas-muted">{props.empty}</p> : null}
-    >
-      <details class="paas-activity">
+    <Show when={props.items.length} fallback={props.empty ? <p class="paas-muted">{props.empty}</p> : null}>
+      <details class="paas-activity" onToggle={(event) => setState("open", event.currentTarget.open)}>
         <summary>工具活动 · {props.items.length} 条</summary>
         <summary>工具活动 · {props.items.length} 条</summary>
-        <ol class="paas-activity-list">
-          <For each={props.items}>
-            {(item) => (
-              <li>
-                <strong>
-                  {item.kind}
-                  {item.tool ? ` · ${item.tool}` : ""}
-                </strong>
-                <Show when={item.content}>
-                  <pre class="paas-activity-content">{item.content}</pre>
-                </Show>
-              </li>
-            )}
-          </For>
-        </ol>
-        <Show when={props.raw !== undefined}>
-          <details class="paas-activity-raw">
-            <summary>技术信息</summary>
-            <pre>{JSON.stringify(props.raw, null, 2)}</pre>
-          </details>
+        <Show when={state.open}>
+          <Show when={props.items.length > state.count}>
+            <button type="button" onClick={() => setState("count", (value) => value + 50)}>
+              加载更早活动(还有 {props.items.length - state.count} 条)
+            </button>
+          </Show>
+          <ol class="paas-activity-list" start={Math.max(1, props.items.length - state.count + 1)}>
+            <For each={items()}>
+              {(item) => (
+                <li>
+                  <strong>
+                    {item.kind}
+                    {item.tool ? ` · ${item.tool}` : ""}
+                  </strong>
+                  <Show when={item.content}>
+                    <pre class="paas-activity-content">{item.content}</pre>
+                  </Show>
+                </li>
+              )}
+            </For>
+          </ol>
+          <Show when={props.raw !== undefined}>
+            <details class="paas-activity-raw" onToggle={(event) => setState("raw", event.currentTarget.open)}>
+              <summary>技术信息</summary>
+              <Show when={state.raw}>
+                <pre>{JSON.stringify(props.raw, null, 2)}</pre>
+              </Show>
+            </details>
+          </Show>
         </Show>
         </Show>
       </details>
       </details>
     </Show>
     </Show>

+ 64 - 4
packages/app/src/pages/paas/agent-edit.tsx

@@ -1,5 +1,5 @@
 import { For, Show, createMemo, onCleanup, onMount } from "solid-js"
 import { For, Show, createMemo, onCleanup, onMount } from "solid-js"
-import { createStore } from "solid-js/store"
+import { createStore, unwrap } from "solid-js/store"
 import { Icon } from "@opencode-ai/ui/icon"
 import { Icon } from "@opencode-ai/ui/icon"
 import { paasRecord, paasRows, paasText, type PaasAgentUpdate, type PaasPlatform } from "@/paas"
 import { paasRecord, paasRows, paasText, type PaasAgentUpdate, type PaasPlatform } from "@/paas"
 
 
@@ -68,11 +68,28 @@ function parseConfig(text: string) {
   }
   }
 }
 }
 
 
+export type AgentEditDraft = {
+  original: Record<string, unknown>
+  fields: {
+    name: string
+    description: string
+    source_dir: string
+    work_dir: string
+    run_dir: string
+    agent_dir: string
+  }
+  configText: string
+  kbIDs: string[]
+  kbMode: string
+}
+
 export function PaasAgentEdit(props: {
 export function PaasAgentEdit(props: {
   api: PaasPlatform
   api: PaasPlatform
   agentID: string
   agentID: string
   onClose: () => void
   onClose: () => void
   onSaved: () => Promise<void>
   onSaved: () => Promise<void>
+  draft?: AgentEditDraft
+  onDraft?: (draft?: AgentEditDraft) => void
 }) {
 }) {
   const [state, setState] = createStore({
   const [state, setState] = createStore({
     original: undefined as Record<string, unknown> | undefined,
     original: undefined as Record<string, unknown> | undefined,
@@ -84,9 +101,27 @@ export function PaasAgentEdit(props: {
     kbMode: "",
     kbMode: "",
     busy: false,
     busy: false,
     error: "",
     error: "",
+    restored: false,
+  })
+  const lifecycle = { active: true, saved: false, baseline: "" }
+  const snapshot = (): AgentEditDraft | undefined =>
+    state.original
+      ? structuredClone(
+          unwrap({
+            original: state.original,
+            fields: state.fields,
+            configText: state.configText,
+            kbIDs: state.kbIDs,
+            kbMode: state.kbMode,
+          }),
+        )
+      : undefined
+  const changed = () => !!state.original && JSON.stringify(snapshot()) !== lifecycle.baseline
+  onCleanup(() => {
+    lifecycle.active = false
+    if (!state.original) return
+    props.onDraft?.(!lifecycle.saved && changed() ? snapshot() : undefined)
   })
   })
-  const lifecycle = { active: true }
-  onCleanup(() => (lifecycle.active = false))
   const config = createMemo(() => parseConfig(state.configText))
   const config = createMemo(() => parseConfig(state.configText))
   const scientific = () => !!config()?.researchWorkflow || !!paasRecord(config()?.scientific)
   const scientific = () => !!config()?.researchWorkflow || !!paasRecord(config()?.scientific)
   const canEditMetadata = () => state.original?.can_update_metadata === true
   const canEditMetadata = () => state.original?.can_update_metadata === true
@@ -114,7 +149,7 @@ export function PaasAgentEdit(props: {
     setState("configText", JSON.stringify({ ...current, [group]: section }, null, 2))
     setState("configText", JSON.stringify({ ...current, [group]: section }, null, 2))
   }
   }
 
 
-  async function load() {
+  async function load(restore = true) {
     setState({ busy: true, error: "", knowledgeError: "" })
     setState({ busy: true, error: "", knowledgeError: "" })
     const agent = props.api
     const agent = props.api
       .request({ action: "agent", agentID: props.agentID })
       .request({ action: "agent", agentID: props.agentID })
@@ -137,7 +172,14 @@ export function PaasAgentEdit(props: {
           configText: JSON.stringify(settings, null, 2),
           configText: JSON.stringify(settings, null, 2),
           kbIDs: Array.isArray(record.kb_ids) ? record.kb_ids.filter((id): id is string => typeof id === "string") : [],
           kbIDs: Array.isArray(record.kb_ids) ? record.kb_ids.filter((id): id is string => typeof id === "string") : [],
           kbMode: paasText(record.kb_search_mode),
           kbMode: paasText(record.kb_search_mode),
+          restored: false,
         })
         })
+        lifecycle.baseline = JSON.stringify(snapshot())
+        if (restore && props.draft) {
+          setState({ ...structuredClone(props.draft), restored: true })
+          if (props.draft.original.updated_at !== record.updated_at)
+            setState("error", "平台配置已更新,已保留你的草稿。请先复制需要的修改,再点击「放弃草稿并读取最新配置」。")
+        }
       })
       })
       .catch((error: unknown) => {
       .catch((error: unknown) => {
         if (lifecycle.active) setState("error", error instanceof Error ? error.message : "无法读取智能体配置。")
         if (lifecycle.active) setState("error", error instanceof Error ? error.message : "无法读取智能体配置。")
@@ -200,6 +242,8 @@ export function PaasAgentEdit(props: {
     await props.api
     await props.api
       .request({ action: "update-agent", agentID: props.agentID, update })
       .request({ action: "update-agent", agentID: props.agentID, update })
       .then(async () => {
       .then(async () => {
+        lifecycle.saved = true
+        props.onDraft?.(undefined)
         if (lifecycle.active) await props.onSaved()
         if (lifecycle.active) await props.onSaved()
       })
       })
       .catch((error: unknown) => {
       .catch((error: unknown) => {
@@ -225,6 +269,22 @@ export function PaasAgentEdit(props: {
           )}
           )}
         </Show>
         </Show>
       </div>
       </div>
+      <Show when={state.original}>
+        <p class="paas-muted" role="status">
+          {state.restored ? "已恢复未保存的修改。" : ""}
+          离开页面时修改保留在当前窗口,点击保存后才会应用;关闭窗口后草稿不保留。
+        </p>
+        <button
+          type="button"
+          disabled={state.busy}
+          onClick={() => {
+            props.onDraft?.(undefined)
+            void load(false)
+          }}
+        >
+          放弃草稿并读取最新配置
+        </button>
+      </Show>
       <Show
       <Show
         when={state.original}
         when={state.original}
         fallback={
         fallback={

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

@@ -153,3 +153,26 @@ test("a corrupt navigation index can be rebuilt from healthy conversation record
   expect(next.load().chats.map((c) => c.id)).toEqual(["a", "b"])
   expect(next.load().chats.map((c) => c.id)).toEqual(["a", "b"])
   next.close()
   next.close()
 })
 })
+
+test("authenticated legacy migration copies all report bodies without crossing identity scopes", () => {
+  const m = memory(),
+    oldScope = "a".repeat(64),
+    newScope = "b".repeat(64)
+  const old = createChatCache(m.storage, oldScope, "first", () => {})
+  old.stage(chat("a"))
+  old.stage(chat("b"))
+  old.index(["a", "b"], "a")
+  old.close()
+  const next = createChatCache(m.storage, newScope, "first", () => {}, oldScope)
+  const migrated = next.load()
+  expect(migrated.chats.map((c) => c.messages[0].text)).toEqual(["报告a", "报告b"])
+  next.close()
+  // The old key cache can be removed without breaking the migrated histories.
+  for (const key of [...m.data.keys()]) if (key.includes(oldScope)) m.data.delete(key)
+  const rotated = createChatCache(m.storage, newScope, "second", () => {}, "c".repeat(64))
+  const restored = rotated.load()
+  expect(restored.chats[0].draft).toBe("草稿")
+  expect(rotated.hydrate(restored.chats[1])[0].text).toBe("报告b")
+  expect(createChatCache(m.storage, "other-user", "first", () => {}).load().chats).toEqual([])
+  rotated.close()
+})

+ 22 - 1
packages/app/src/pages/paas/chat-cache.ts

@@ -4,7 +4,13 @@ type Index = { ids: string[]; active: string }
 type Metadata = Omit<ResearchChat, "messages" | "cache"> & { source: string; messageIDs: string[]; live: boolean }
 type Metadata = Omit<ResearchChat, "messages" | "cache"> & { source: string; messageIDs: string[]; live: boolean }
 
 
 /** Separate small navigation/draft records from report bodies. No credentials are stored. */
 /** 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) {
+export function createChatCache(
+  storage: Storage,
+  scope: string,
+  windowID: string,
+  onError: (message: string) => void,
+  legacyScope?: string,
+) {
   const root = `lambda-scientist.chats.v2:${scope}:${windowID}`
   const root = `lambda-scientist.chats.v2:${scope}:${windowID}`
   const latest = `lambda-scientist.chats.v2:${scope}:latest`
   const latest = `lambda-scientist.chats.v2:${scope}:latest`
   const pending = new Map<string, string>()
   const pending = new Map<string, string>()
@@ -72,6 +78,21 @@ export function createChatCache(storage: Storage, scope: string, windowID: strin
   function load(): { chats: ResearchChat[]; active: string } {
   function load(): { chats: ResearchChat[]; active: string } {
     try {
     try {
       const source = storage.getItem(`${root}:index`) ? root : storage.getItem(latest)
       const source = storage.getItem(`${root}:index`) ? root : storage.getItem(latest)
+      if (!source && legacyScope && legacyScope !== scope && /^[a-f0-9]{64}$/.test(legacyScope)) {
+        // Only the authenticated native transport supplies this alias for the current key.
+        // Hydrate before copying so no new record points into a different identity partition.
+        const old = createChatCache(storage, legacyScope, windowID, onError)
+        const saved = old.load()
+        const chats = saved.chats.map((chat) => ({ ...chat, messages: old.hydrate(chat), cache: undefined }))
+        old.close()
+        chats.forEach(stage)
+        if (chats.length) {
+          state.index = { ids: chats.map((chat) => chat.id), active: saved.active }
+          state.indexDirty = true
+          flush()
+        }
+        return { chats, active: saved.active }
+      }
       if (!source || !source.startsWith(`lambda-scientist.chats.v2:${scope}:`)) {
       if (!source || !source.startsWith(`lambda-scientist.chats.v2:${scope}:`)) {
         const legacy =
         const legacy =
           read<{ chats?: ResearchChat[]; active?: string } | null>(
           read<{ chats?: ResearchChat[]; active?: string } | null>(

+ 7 - 2
packages/app/src/pages/paas/chat-state.ts

@@ -52,6 +52,7 @@ export function createResearchChats(props: {
   api?: PaasPlatform
   api?: PaasPlatform
   connected: boolean
   connected: boolean
   scope?: string
   scope?: string
+  legacyScope?: string
   windowID?: string
   windowID?: string
   onNotice?: (notice: { chatID: string; title: string; body: string }) => void
   onNotice?: (notice: { chatID: string; title: string; body: string }) => void
 }) {
 }) {
@@ -281,8 +282,12 @@ export function createResearchChats(props: {
         persistence.current?.close()
         persistence.current?.close()
         life.key = key
         life.key = key
         persistence.current = scope
         persistence.current = scope
-          ? createChatCache(localStorage, scope, props.windowID || "main", (message) =>
-              setState("storageError", message),
+          ? createChatCache(
+              localStorage,
+              scope,
+              props.windowID || "main",
+              (message) => setState("storageError", message),
+              props.legacyScope,
             )
             )
           : undefined
           : undefined
         const data = persistence.current?.load() || { chats: [], active: "" }
         const data = persistence.current?.load() || { chats: [], active: "" }

+ 13 - 1
packages/app/src/pages/paas/chat.tsx

@@ -28,6 +28,7 @@ export function PaasChat(props: {
   connected: boolean
   connected: boolean
   visible: boolean
   visible: boolean
   scope?: string
   scope?: string
+  legacyScope?: string
   agents: Record<string, unknown>[]
   agents: Record<string, unknown>[]
   openAgentID: string
   openAgentID: string
   onAgentOpened: () => void
   onAgentOpened: () => void
@@ -38,6 +39,7 @@ export function PaasChat(props: {
   onOpenWorkspace?: (agentID: string) => Promise<void>
   onOpenWorkspace?: (agentID: string) => Promise<void>
   onEditAgent?: (agentID: string) => void
   onEditAgent?: (agentID: string) => void
   workspaceDisabled: boolean
   workspaceDisabled: boolean
+  workspaceHint?: string
   openTask?: Record<string, unknown>
   openTask?: Record<string, unknown>
   onTaskOpened?: () => void
   onTaskOpened?: () => void
   historyMount?: HTMLElement
   historyMount?: HTMLElement
@@ -75,6 +77,9 @@ export function PaasChat(props: {
     get scope() {
     get scope() {
       return props.scope
       return props.scope
     },
     },
+    get legacyScope() {
+      return props.legacyScope
+    },
     windowID: platform.windowID,
     windowID: platform.windowID,
     onNotice: (notice) => {
     onNotice: (notice) => {
       setUI("notices", (rows) => [
       setUI("notices", (rows) => [
@@ -473,10 +478,14 @@ export function PaasChat(props: {
                 <Show when={currentAgent() && props.onOpenWorkspace}>
                 <Show when={currentAgent() && props.onOpenWorkspace}>
                   <button
                   <button
                     disabled={props.workspaceDisabled}
                     disabled={props.workspaceDisabled}
+                    title={props.workspaceHint || "在 OpenCode 中继续处理本机研究产物"}
                     onClick={() => void props.onOpenWorkspace?.(current()!.agentID)}
                     onClick={() => void props.onOpenWorkspace?.(current()!.agentID)}
                   >
                   >
-                    打开工作区
+                    在开发区打开工作区
                   </button>
                   </button>
+                  <Show when={props.workspaceHint}>
+                    <p class="paas-muted">{props.workspaceHint}</p>
+                  </Show>
                 </Show>
                 </Show>
               </div>
               </div>
             </details>
             </details>
@@ -711,6 +720,9 @@ export function PaasChat(props: {
                         </Show>
                         </Show>
                         <Show when={message.activity?.length}>
                         <Show when={message.activity?.length}>
                           <PaasActivity items={paasActivityItems(message.activity)} raw={message.activity} />
                           <PaasActivity items={paasActivityItems(message.activity)} raw={message.activity} />
+                          <Show when={(message.activity?.length || 0) >= 80}>
+                            <p class="paas-muted">本机保留最近 80 条执行事件;更早的记录请查看平台任务日志。</p>
+                          </Show>
                         </Show>
                         </Show>
                         <Show when={message.runID && props.api}>
                         <Show when={message.runID && props.api}>
                           <ResearchRunDetails
                           <ResearchRunDetails

+ 2 - 0
packages/app/src/pages/paas/controller.ts

@@ -10,6 +10,7 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
     remember: true,
     remember: true,
     remembered: false,
     remembered: false,
     scope: "",
     scope: "",
+    legacyScope: "",
     connected: false,
     connected: false,
     busy: "",
     busy: "",
     error: "",
     error: "",
@@ -128,6 +129,7 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
       setState({
       setState({
         connected: true,
         connected: true,
         scope: connection.scope || "",
         scope: connection.scope || "",
+        legacyScope: connection.legacyScope || "",
         url: connection.url,
         url: connection.url,
         remembered: !!connection.remembered,
         remembered: !!connection.remembered,
         apiKey: "",
         apiKey: "",

+ 28 - 5
packages/app/src/pages/paas/index.tsx

@@ -16,7 +16,7 @@ import { showToast } from "@/utils/toast"
 import { createPaasWorkspace } from "./controller"
 import { createPaasWorkspace } from "./controller"
 import { PaasChat } from "./chat"
 import { PaasChat } from "./chat"
 import { createTaskIndex, PaasTasks } from "./tasks"
 import { createTaskIndex, PaasTasks } from "./tasks"
-import { PaasAgentEdit } from "./agent-edit"
+import { PaasAgentEdit, type AgentEditDraft } from "./agent-edit"
 import { PaasPacks } from "./packs"
 import { PaasPacks } from "./packs"
 import { ResearchIssue } from "./issue"
 import { ResearchIssue } from "./issue"
 import "./paas.css"
 import "./paas.css"
@@ -28,7 +28,9 @@ const pages = [
   { id: "connection", icon: "server", name: "平台设置" },
   { id: "connection", icon: "server", name: "平台设置" },
 ] as const
 ] as const
 
 
-export default function PaasWorkspace(props: { standalone?: boolean; onOpenDeveloper?: () => void } = {}) {
+export default function PaasWorkspace(
+  props: { standalone?: boolean; onOpenDeveloper?: (directory?: string) => void } = {},
+) {
   const platform = usePlatform()
   const platform = usePlatform()
   const dialog = useDialog()
   const dialog = useDialog()
   const global = props.standalone ? undefined : useGlobal()
   const global = props.standalone ? undefined : useGlobal()
@@ -36,6 +38,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
   const settings = props.standalone ? undefined : useSettings()
   const settings = props.standalone ? undefined : useSettings()
   const tabs = props.standalone ? undefined : useTabs()
   const tabs = props.standalone ? undefined : useTabs()
   const navigate = props.standalone ? undefined : useNavigate()
   const navigate = props.standalone ? undefined : useNavigate()
+  const drafts = new Map<string, AgentEditDraft>()
   const workspace = createPaasWorkspace(platform.paas)
   const workspace = createPaasWorkspace(platform.paas)
   const state = workspace.state
   const state = workspace.state
   const disabled = () => !!state.busy || !state.connected
   const disabled = () => !!state.busy || !state.connected
@@ -134,6 +137,14 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
     </div>
     </div>
   )
   )
 
 
+  const remoteWorkspace = () => {
+    try {
+      return !["localhost", "127.0.0.1", "[::1]"].includes(new URL(state.url).hostname)
+    } catch {
+      return false
+    }
+  }
+
   async function openAgentWorkspace(agentID: string) {
   async function openAgentWorkspace(agentID: string) {
     if (!platform.paas || !state.connected || ui.openingWorkspace) return
     if (!platform.paas || !state.connected || ui.openingWorkspace) return
     const conn = localServer()
     const conn = localServer()
@@ -146,7 +157,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
         const directory = paasText(paasRecord(result)?.directory)
         const directory = paasText(paasRecord(result)?.directory)
         if (!directory) throw new Error("平台没有返回可用的工作区目录。")
         if (!directory) throw new Error("平台没有返回可用的工作区目录。")
         if (props.standalone) {
         if (props.standalone) {
-          await platform.openPath?.(directory)
+          props.onOpenDeveloper?.(directory)
           return
           return
         }
         }
         if (!conn || !global || !settings || !tabs || !server || !navigate) return
         if (!conn || !global || !settings || !tabs || !server || !navigate) return
@@ -234,7 +245,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
           <Show
           <Show
             when={!props.standalone}
             when={!props.standalone}
             fallback={
             fallback={
-              <button type="button" aria-label="开发工作区" onClick={props.onOpenDeveloper}>
+              <button type="button" aria-label="开发工作区" onClick={() => props.onOpenDeveloper?.()}>
                 <Icon name="arrow-left" size="normal" />
                 <Icon name="arrow-left" size="normal" />
                 <span class="paas-nav-label">开发工作区</span>
                 <span class="paas-nav-label">开发工作区</span>
               </button>
               </button>
@@ -356,6 +367,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
               api={platform.paas}
               api={platform.paas}
               connected={state.connected}
               connected={state.connected}
               scope={state.scope}
               scope={state.scope}
+              legacyScope={state.legacyScope}
               onOpenTasks={() => {
               onOpenTasks={() => {
                 workspace.setState("page", "tasks")
                 workspace.setState("page", "tasks")
                 void tasks.refresh()
                 void tasks.refresh()
@@ -375,7 +387,10 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 setUI({ editAgentID: id, editReturn: "chat" })
                 setUI({ editAgentID: id, editReturn: "chat" })
                 workspace.setState("page", "edit-agent")
                 workspace.setState("page", "edit-agent")
               }}
               }}
-              workspaceDisabled={ui.openingWorkspace || (!props.standalone && !localServer())}
+              workspaceHint={
+                remoteWorkspace() ? "远程目录不能直接在本机打开;可在任务中下载工作文件,再进入开发区。" : undefined
+              }
+              workspaceDisabled={remoteWorkspace() || ui.openingWorkspace || (!props.standalone && !localServer())}
             />
             />
           </div>
           </div>
           <Switch>
           <Switch>
@@ -622,6 +637,14 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 <PaasAgentEdit
                 <PaasAgentEdit
                   api={api}
                   api={api}
                   agentID={ui.editAgentID}
                   agentID={ui.editAgentID}
+                  draft={drafts.get(`${state.scope}:${ui.editAgentID}`)}
+                  onDraft={(() => {
+                    const key = `${state.scope}:${ui.editAgentID}`
+                    return (draft?: AgentEditDraft) => {
+                      if (draft) drafts.set(key, draft)
+                      else drafts.delete(key)
+                    }
+                  })()}
                   onClose={() => workspace.setState("page", ui.editReturn)}
                   onClose={() => workspace.setState("page", ui.editReturn)}
                   onSaved={async () => {
                   onSaved={async () => {
                     workspace.setState({ page: ui.editReturn, verified: false, checks: [] })
                     workspace.setState({ page: ui.editReturn, verified: false, checks: [] })

+ 10 - 6
packages/app/src/pages/paas/report-reader.tsx

@@ -3,6 +3,7 @@ import { createStore } from "solid-js/store"
 import { Dialog } from "@opencode-ai/ui/dialog"
 import { Dialog } from "@opencode-ai/ui/dialog"
 import { ResearchReport } from "./report"
 import { ResearchReport } from "./report"
 import { usePlatform } from "@/context/platform"
 import { usePlatform } from "@/context/platform"
+import { paasStatuses } from "@/paas"
 import type { ResearchMessage } from "./chat-state"
 import type { ResearchMessage } from "./chat-state"
 
 
 export function ReportReader(props: {
 export function ReportReader(props: {
@@ -32,6 +33,12 @@ export function ReportReader(props: {
       setState("busy", false)
       setState("busy", false)
     }
     }
   }
   }
+  const label = (message: ResearchMessage, index?: number) => {
+    const heading = message.text.match(/^#{1,6}\s+(.+)$/m)?.[1]?.slice(0, 60) || "研究报告"
+    const timestamp = message.updated || message.started
+    const date = timestamp ? new Date(timestamp).toLocaleString() : "时间未记录"
+    return `${index === undefined ? "当前报告" : `报告 ${index + 1}`} · ${heading} · ${timestamp ? `记录时间 ${date}` : date}${message.status ? ` · ${paasStatuses[message.status] || message.status}` : ""}${message.runID ? ` · ${message.runID.slice(-12)}` : ""}`
+  }
   const previous = () => props.earlier.find((item) => item.id === state.previous)
   const previous = () => props.earlier.find((item) => item.id === state.previous)
   const oversized = () => (previous()?.text.length || 0) + props.message.text.length > 200000
   const oversized = () => (previous()?.text.length || 0) + props.message.text.length > 200000
   const [changes] = createResource(
   const [changes] = createResource(
@@ -65,6 +72,7 @@ export function ReportReader(props: {
         <Show when={state.note}>
         <Show when={state.note}>
           <p role="status">{state.note}</p>
           <p role="status">{state.note}</p>
         </Show>
         </Show>
+        <p class="paas-muted">{label(props.message)}</p>
         <p class="paas-muted">Word / PDF 保留文字、标题、列表和表格;公式按原文导出,图片链接不自动下载。</p>
         <p class="paas-muted">Word / PDF 保留文字、标题、列表和表格;公式按原文导出,图片链接不自动下载。</p>
         <Show
         <Show
           when={state.compare}
           when={state.compare}
@@ -91,15 +99,11 @@ export function ReportReader(props: {
               onChange={(e) => setState("previous", e.currentTarget.value)}
               onChange={(e) => setState("previous", e.currentTarget.value)}
             >
             >
               <For each={props.earlier}>
               <For each={props.earlier}>
-                {(message, i) => (
-                  <option value={message.id}>
-                    此前报告 {i() + 1}
-                    {message.runID ? ` · ${message.runID}` : ""}
-                  </option>
-                )}
+                {(message, i) => <option value={message.id}>{label(message, i())}</option>}
               </For>
               </For>
             </select>
             </select>
           </label>
           </label>
+          <p class="paas-muted">对比同一会话中不同任务的报告,不代表一次任务内部的研究轮次。</p>
           <p>绿色为新增,红色删除线为移除;仅显示文本变化,不代表科学结论改善。</p>
           <p>绿色为新增,红色删除线为移除;仅显示文本变化,不代表科学结论改善。</p>
           <Show when={oversized()}>
           <Show when={oversized()}>
             <p>报告较长,请分别导出后对比,以保持阅读流畅。</p>
             <p>报告较长,请分别导出后对比,以保持阅读流畅。</p>

+ 3 - 3
packages/app/src/pages/paas/report.tsx

@@ -8,9 +8,9 @@ export function researchMarkdown(text: string) {
     .map((part, index) => {
     .map((part, index) => {
       if (index % 2) return part
       if (index % 2) return part
       return part.replace(
       return part.replace(
-        /\$\$([\s\S]*?)\$\$|\\\[([\s\S]*?)\\\]/g,
-        (_, dollars: string | undefined, brackets: string | undefined) =>
-          `\n\n$$\n${(dollars ?? brackets ?? "").trim()}\n$$\n\n`,
+        /\$\$([\s\S]*?)\$\$|\\\[([\s\S]*?)\\\]|(?<![\\$])\$(?!\$)([^\s$](?:[^$\n]*?[^\s$])?)\$(?![\d$])/g,
+        (_, dollars: string | undefined, brackets: string | undefined, inline: string | undefined) =>
+          inline !== undefined ? `\\(${inline}\\)` : `\n\n$$\n${(dollars ?? brackets ?? "").trim()}\n$$\n\n`,
       )
       )
     })
     })
     .join("")
     .join("")

+ 17 - 2
packages/app/src/pages/paas/run-panel.tsx

@@ -208,8 +208,13 @@ export function PaasRunPanel(props: {
         <button type="button" disabled={!!state.busy} onClick={() => void refresh()}>
         <button type="button" disabled={!!state.busy} onClick={() => void refresh()}>
           刷新状态
           刷新状态
         </button>
         </button>
-        <Show when={["running", "queued", "pending", "resuming"].includes(status())}>
-          <button type="button" disabled={!!state.busy} onClick={() => void control("pause")}>
+        <Show when={status() === "running"}>
+          <button
+            type="button"
+            disabled={!!state.busy}
+            title="请求在可恢复点暂停;是否支持由执行服务确认"
+            onClick={() => void control("pause")}
+          >
             暂停
             暂停
           </button>
           </button>
         </Show>
         </Show>
@@ -235,6 +240,16 @@ export function PaasRunPanel(props: {
           </button>
           </button>
         </Show>
         </Show>
       </div>
       </div>
+      <Show when={status() === "pause_requested"}>
+        <p role="status" class="paas-muted">
+          已请求暂停,正在等待执行服务保存进度;任务尚未停止。
+        </p>
+      </Show>
+      <Show when={status() === "paused" && !paasText(state.run.checkpoint_id)}>
+        <p role="status" class="paas-muted">
+          任务已暂停,平台尚未返回恢复点。可刷新状态或联系管理员核对,暂不重复提交任务。
+        </p>
+      </Show>
       <ResearchProgress run={state.run} />
       <ResearchProgress run={state.run} />
       <Show when={state.busy}>
       <Show when={state.busy}>
         <p role="status">{state.busy}…</p>
         <p role="status">{state.busy}…</p>

+ 17 - 6
packages/app/src/pages/paas/tasks.tsx

@@ -129,12 +129,23 @@ export function createTaskIndex(props: {
     }
     }
   }
   }
   createEffect(
   createEffect(
-    on([() => props.connected, () => props.scope, () => props.agents.map((a) => a.id).join("|")], () => {
-      life.epoch++
-      setState({ rows: [], loaded: false, loading: false, error: "", updated: "", limited: [], expanded: [] })
-      setState("next", reconcile({}))
-      if (props.connected) void refresh()
-    }),
+    on(
+      [
+        () => props.connected,
+        () => props.scope,
+        () =>
+          props.agents
+            .map((a) => a.id)
+            .sort()
+            .join("|"),
+      ],
+      () => {
+        life.epoch++
+        setState({ rows: [], loaded: false, loading: false, error: "", updated: "", limited: [], expanded: [] })
+        setState("next", reconcile({}))
+        if (props.connected) void refresh()
+      },
+    ),
   )
   )
   const timer = setInterval(() => {
   const timer = setInterval(() => {
     if (!document.hidden) void refresh()
     if (!document.hidden) void refresh()

+ 36 - 3
packages/desktop/scripts/native-smoke.cjs

@@ -31,6 +31,7 @@ const path = require("node:path")
     const send = (value) => response.end(JSON.stringify(value))
     const send = (value) => response.end(JSON.stringify(value))
     if (url.pathname === "/api/v1/agents")
     if (url.pathname === "/api/v1/agents")
       return send({ agents: [{ id: "research", name: "科研助手", current_version: 1 }] })
       return send({ agents: [{ id: "research", name: "科研助手", current_version: 1 }] })
+    if (url.pathname === "/api/v1/agents/research") return send({ id: "research", name: "科研助手", work_dir: root })
     if (url.pathname.endsWith("/run-options")) return send({ efforts: [] })
     if (url.pathname.endsWith("/run-options")) return send({ efforts: [] })
     if (url.pathname.endsWith("/threads")) return send({ threads: [] })
     if (url.pathname.endsWith("/threads")) return send({ threads: [] })
     if (url.pathname.endsWith("/files/capabilities")) return send({ direct_upload_max_bytes: 268435456 })
     if (url.pathname.endsWith("/files/capabilities")) return send({ direct_upload_max_bytes: 268435456 })
@@ -93,6 +94,29 @@ const path = require("node:path")
       timeout: 30000,
       timeout: 30000,
     })
     })
     await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
     await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
+    await window.getByRole("button", { name: "开发工作区", exact: true }).click()
+    await expect(window.getByRole("button", { name: "← 返回科研工作台", exact: true })).toBeVisible()
+    await window.getByRole("button", { name: "← 返回科研工作台", exact: true }).click()
+    await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("Create a research plan")
+    await expect(window.getByRole("button", { name: "移除material.txt", exact: true })).toBeVisible()
+    await window.locator(".paas-more-actions > summary").click()
+    await window.getByRole("button", { name: "在开发区打开工作区", exact: true }).click()
+    await expect(window.getByRole("button", { name: "← 返回科研工作台", exact: true })).toBeVisible()
+    await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toBeVisible({
+      timeout: 30000,
+    })
+    await expect(window.getByText(path.basename(root), { exact: true }).first()).toBeVisible({ timeout: 10000 })
+    await window
+      .locator('[data-component="prompt-input"][contenteditable="true"]')
+      .fill("检查工作目录中的成果,不自动执行")
+    await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toContainText(
+      "检查工作目录中的成果,不自动执行",
+    )
+    await expect(window.locator('[data-component="prompt-input"][contenteditable="true"]')).toBeInViewport()
+    await expect(window.getByText(path.basename(root), { exact: true }).first()).toBeInViewport()
+    await window.screenshot({ path: path.join(root, "developer-handoff.png") })
+    await window.getByRole("button", { name: "← 返回科研工作台", exact: true }).click()
+    await expect(window.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("Create a research plan")
     await window.getByRole("textbox", { name: "消息", exact: true }).press("Enter")
     await window.getByRole("textbox", { name: "消息", exact: true }).press("Enter")
     await expect(window.getByText("Native research plan completed", { exact: true }).first()).toBeVisible()
     await expect(window.getByText("Native research plan completed", { exact: true }).first()).toBeVisible()
     await window.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
     await window.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
@@ -105,7 +129,13 @@ const path = require("node:path")
     })
     })
     await window.getByRole("button", { name: "保存文件", exact: true }).click()
     await window.getByRole("button", { name: "保存文件", exact: true }).click()
     await expect(window.getByText("已取消保存,文件仍保留在平台。", { exact: true })).toBeVisible()
     await expect(window.getByText("已取消保存,文件仍保留在平台。", { exact: true })).toBeVisible()
-    if (await fs.stat(saved).then(() => true, () => false)) throw new Error("Cancelled download created a file")
+    if (
+      await fs.stat(saved).then(
+        () => true,
+        () => false,
+      )
+    )
+      throw new Error("Cancelled download created a file")
     await window.getByRole("button", { name: "保存文件", exact: true }).click()
     await window.getByRole("button", { name: "保存文件", exact: true }).click()
     await expect(window.getByText("文件已保存。", { exact: true })).toBeVisible()
     await expect(window.getByText("文件已保存。", { exact: true })).toBeVisible()
     if ((await fs.readFile(saved, "utf8")) !== "Saved from native IPC") throw new Error("Downloaded bytes mismatch")
     if ((await fs.readFile(saved, "utf8")) !== "Saved from native IPC") throw new Error("Downloaded bytes mismatch")
@@ -125,10 +155,13 @@ const path = require("node:path")
     await expect(window.getByRole("dialog").getByText("已导出 research-report.pdf", { exact: true })).toBeVisible()
     await expect(window.getByRole("dialog").getByText("已导出 research-report.pdf", { exact: true })).toBeVisible()
     const pdf = await fs.readFile(report.replace(/\.md$/, ".pdf"))
     const pdf = await fs.readFile(report.replace(/\.md$/, ".pdf"))
     if (pdf.subarray(0, 5).toString() !== "%PDF-") throw new Error("Invalid PDF")
     if (pdf.subarray(0, 5).toString() !== "%PDF-") throw new Error("Invalid PDF")
-    await app.evaluate(({ dialog }) => { dialog.showSaveDialog = async () => ({ canceled: true }) })
+    await app.evaluate(({ dialog }) => {
+      dialog.showSaveDialog = async () => ({ canceled: true })
+    })
     await window.getByRole("button", { name: "导出 Word", exact: true }).click()
     await window.getByRole("button", { name: "导出 Word", exact: true }).click()
     await expect(window.getByRole("dialog").getByText("已取消导出,报告仍保留。", { exact: true })).toBeVisible()
     await expect(window.getByRole("dialog").getByText("已取消导出,报告仍保留。", { exact: true })).toBeVisible()
-    if (!(await fs.readFile(report.replace(/\.md$/, ".docx"))).equals(word)) throw new Error("Cancelled export changed original file")
+    if (!(await fs.readFile(report.replace(/\.md$/, ".docx"))).equals(word))
+      throw new Error("Cancelled export changed original file")
     await window.keyboard.press("Escape")
     await window.keyboard.press("Escape")
     const execute = calls.filter((c) => c.path.endsWith("/run/stream"))
     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")
     if (execute.length !== 1 || JSON.parse(execute[0].body).input_files[0].file_id !== "native_file")

+ 45 - 0
packages/desktop/src/main/paas.test.ts

@@ -7,6 +7,7 @@ test("a reachable control plane distinguishes an unavailable execution service",
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     fetch(request) {
     fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       if (new URL(request.url).pathname === "/api/v1/agents") return Response.json({ agents: [] })
       if (new URL(request.url).pathname === "/api/v1/agents") return Response.json({ agents: [] })
       return Response.json(
       return Response.json(
         { detail: { code: "LOCAL_SERVICE_UNAVAILABLE", message: "Local Agent Service is required" } },
         { detail: { code: "LOCAL_SERVICE_UNAVAILABLE", message: "Local Agent Service is required" } },
@@ -32,6 +33,7 @@ test("desktop transport isolates windows and only checks resources without invok
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     async fetch(request) {
     async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       requests.push({
       requests.push({
         path: new URL(request.url).pathname,
         path: new URL(request.url).pathname,
         method: request.method,
         method: request.method,
@@ -70,6 +72,7 @@ test("failed replacement clears the old account and does not expose server error
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     fetch(request) {
     fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       if (request.headers.get("Authorization") === "Bearer old") return Response.json({ agents: [] })
       if (request.headers.get("Authorization") === "Bearer old") return Response.json({ agents: [] })
       return new Response("secret credentials", { status: 401 })
       return new Response("secret credentials", { status: 401 })
     },
     },
@@ -113,6 +116,7 @@ test("chat executes the selected agent, preserves thread identity and rejects du
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     async fetch(request) {
     async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
       if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
       received.push({ path: new URL(request.url).pathname, method: request.method, body: await request.json() })
       received.push({ path: new URL(request.url).pathname, method: request.method, body: await request.json() })
       started.resolve()
       started.resolve()
@@ -212,6 +216,7 @@ test("thread history and AgentPack operations use the platform's typed routes",
     port: 0,
     port: 0,
     hostname: "127.0.0.1",
     hostname: "127.0.0.1",
     async fetch(request) {
     async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       const path = new URL(request.url).pathname
       const path = new URL(request.url).pathname
       requests.push({
       requests.push({
         path,
         path,
@@ -253,6 +258,7 @@ test("resolves only the selected agent’s existing work directory", async () =>
     port: 0,
     port: 0,
     hostname: "127.0.0.1",
     hostname: "127.0.0.1",
     fetch(request) {
     fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       const route = new URL(request.url).pathname
       const route = new URL(request.url).pathname
       if (route === "/api/v1/agents") return Response.json({ agents: [] })
       if (route === "/api/v1/agents") return Response.json({ agents: [] })
       if (route === "/api/v1/agents/a1") return Response.json({ id: "a1", work_dir: tmpdir(), run_dir: "/" })
       if (route === "/api/v1/agents/a1") return Response.json({ id: "a1", work_dir: tmpdir(), run_dir: "/" })
@@ -295,6 +301,7 @@ test("task controls, input files and downloads use the authenticated platform ro
     port: 0,
     port: 0,
     hostname: "127.0.0.1",
     hostname: "127.0.0.1",
     async fetch(request) {
     async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       const path = new URL(request.url).pathname
       const path = new URL(request.url).pathname
       expect(request.headers.get("Authorization")).toBe("Bearer test-only")
       expect(request.headers.get("Authorization")).toBe("Bearer test-only")
       requests.push({ path, method: request.method, body: await request.text() })
       requests.push({ path, method: request.method, body: await request.text() })
@@ -356,6 +363,7 @@ test("detaching closes only the subscription and keeps the backend job alive", a
     port: 0,
     port: 0,
     hostname: "127.0.0.1",
     hostname: "127.0.0.1",
     async fetch(request) {
     async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       requests.push(new URL(request.url).pathname)
       requests.push(new URL(request.url).pathname)
       if (request.method === "GET") return Response.json({ agents: [] })
       if (request.method === "GET") return Response.json({ agents: [] })
       const body = await request.json()
       const body = await request.json()
@@ -393,6 +401,7 @@ test("separate conversations execute concurrently and detach only their own stre
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     fetch(request) {
     fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
       if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
       return new Response(
       return new Response(
         new ReadableStream({
         new ReadableStream({
@@ -441,6 +450,7 @@ test("upload progress reports consumed bytes without changing file contents", as
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     async fetch(request) {
     async fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
       if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
       expect(new Uint8Array(await request.arrayBuffer())).toEqual(bytes)
       expect(new Uint8Array(await request.arrayBuffer())).toEqual(bytes)
       return Response.json({ file_id: "uploaded", name: "data.bin" })
       return Response.json({ file_id: "uploaded", name: "data.bin" })
@@ -466,6 +476,7 @@ test("submission identity travels in the stream header and receipt lookup never
   const server = Bun.serve({
   const server = Bun.serve({
     port: 0,
     port: 0,
     fetch(request) {
     fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
       const path = new URL(request.url).pathname
       const path = new URL(request.url).pathname
       requests.push({ path, method: request.method, key: request.headers.get("Idempotency-Key") })
       requests.push({ path, method: request.method, key: request.headers.get("Idempotency-Key") })
       if (path === "/api/v1/agents") return Response.json({ agents: [] })
       if (path === "/api/v1/agents") return Response.json({ agents: [] })
@@ -515,3 +526,37 @@ test("history paging carries the active-task option and rejects invalid offsets"
   await expect(connection.request(1, { action: "history", agentID: "a", offset: -1 })).rejects.toThrow("页码无效")
   await expect(connection.request(1, { action: "history", agentID: "a", offset: -1 })).rejects.toThrow("页码无效")
   connection.disconnect(1)
   connection.disconnect(1)
 })
 })
+
+test("authenticated identity keeps equal-permission key rotations together and other users isolated", async () => {
+  const server = Bun.serve({
+    port: 0,
+    hostname: "127.0.0.1",
+    fetch(request) {
+      if (new URL(request.url).pathname.endsWith("/agents")) return Response.json({ agents: [] })
+      const key = request.headers.get("authorization")
+      if (key?.includes("legacy")) return new Response("missing", { status: 404 })
+      return Response.json({
+        tenant_id: "t",
+        user_id: key?.includes("other") ? "other" : "same",
+        role: "researcher",
+        permissions: key?.includes("limited") ? ["agents:read"] : ["agents:execute", "agents:read"],
+      })
+    },
+  })
+  const api = createPaasConnections()
+  try {
+    const connect = (apiKey: string) => api.connect(1, { url: server.url.origin, apiKey })
+    const before = await connect("old")
+    const after = await connect("new")
+    expect(after.scope).toBe(before.scope)
+    expect(after.legacyScope).not.toBe(before.legacyScope)
+    expect((await connect("other")).scope).not.toBe(before.scope)
+    expect((await connect("limited")).scope).not.toBe(before.scope)
+    const legacy = await connect("legacy")
+    expect(legacy.legacyScope).toBeUndefined()
+    expect(legacy.scope).toMatch(/^[a-f0-9]{64}$/)
+  } finally {
+    api.disconnect(1)
+    await server.stop(true)
+  }
+})

+ 32 - 6
packages/desktop/src/main/paas.ts

@@ -150,13 +150,39 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
       if (pending.get(owner) !== attempt) throw new Error("连接请求已取消。")
       if (pending.get(owner) !== attempt) throw new Error("连接请求已取消。")
       if (!result || typeof result !== "object" || !("agents" in result) || !Array.isArray(result.agents))
       if (!result || typeof result !== "object" || !("agents" in result) || !Array.isArray(result.agents))
         throw new Error("平台未返回智能体目录,请确认这是 AgentPaaS 地址。")
         throw new Error("平台未返回智能体目录,请确认这是 AgentPaaS 地址。")
+      // Identity comes from the authenticated service, never from user-entered account labels.
+      // Older services retain key-based isolation. Narrower permissions get their own cache.
+      const identity = paasRecord(
+        await request(connection, "/auth/me", undefined, undefined, 3000).catch(() => undefined),
+      )
+      if (pending.get(owner) !== attempt) throw new Error("连接请求已取消。")
+      const legacyScope = createHash("sha256")
+        .update(connection.url + "\0" + connection.apiKey)
+        .digest("hex")
+      const identified =
+        typeof identity?.tenant_id === "string" &&
+        !!identity.tenant_id &&
+        typeof identity.user_id === "string" &&
+        !!identity.user_id &&
+        typeof identity.role === "string" &&
+        Array.isArray(identity.permissions) &&
+        identity.permissions.every((permission) => typeof permission === "string")
+      const scope = identified
+        ? createHash("sha256")
+            .update(
+              JSON.stringify([
+                "identity-v1",
+                connection.url,
+                identity.tenant_id,
+                identity.user_id,
+                identity.role,
+                [...new Set(identity.permissions as string[])].sort(),
+              ]),
+            )
+            .digest("hex")
+        : legacyScope
       connections.set(owner, connection)
       connections.set(owner, connection)
-      return {
-        url: connection.url,
-        scope: createHash("sha256")
-          .update(connection.url + "\0" + connection.apiKey)
-          .digest("hex"),
-      }
+      return { url: connection.url, scope, legacyScope: identified ? legacyScope : undefined }
     },
     },
     disconnect: (owner: number) => {
     disconnect: (owner: number) => {
       abortStreams(owner)
       abortStreams(owner)

+ 73 - 7
packages/desktop/src/renderer/index.tsx

@@ -11,6 +11,9 @@ import {
   PlatformProvider,
   PlatformProvider,
   ServerConnection,
   ServerConnection,
   useCommand,
   useCommand,
+  useServer,
+  useSettings,
+  useTabs,
   useWslServers,
   useWslServers,
 } from "@opencode-ai/app"
 } from "@opencode-ai/app"
 import PaasWorkspace from "@opencode-ai/app/paas-workspace"
 import PaasWorkspace from "@opencode-ai/app/paas-workspace"
@@ -19,7 +22,7 @@ import { createStore } from "solid-js/store"
 import type { UpdaterState } from "@opencode-ai/app/updater"
 import type { UpdaterState } from "@opencode-ai/app/updater"
 import * as Sentry from "@sentry/solid"
 import * as Sentry from "@sentry/solid"
 import type { AsyncStorage } from "@solid-primitives/storage"
 import type { AsyncStorage } from "@solid-primitives/storage"
-import { createMemoryHistory, MemoryRouter, type BaseRouterProps } from "@solidjs/router"
+import { createMemoryHistory, MemoryRouter, type BaseRouterProps, useNavigate } from "@solidjs/router"
 import { createEffect, createMemo, createResource, createSignal, onCleanup, Show } from "solid-js"
 import { createEffect, createMemo, createResource, createSignal, onCleanup, Show } from "solid-js"
 import { render } from "solid-js/web"
 import { render } from "solid-js/web"
 import pkg from "../../package.json"
 import pkg from "../../package.json"
@@ -330,7 +333,16 @@ function LoadingSplash() {
 
 
 function DesktopRoot(props: { windowState: DesktopWindowState }) {
 function DesktopRoot(props: { windowState: DesktopWindowState }) {
   const platform = createPlatform(props.windowState)
   const platform = createPlatform(props.windowState)
-  const [view, setView] = createStore({ developer: false })
+  const [view, setView] = createStore({ developer: false, mounted: false, directory: "", request: 0, error: "" })
+  platform.openResearchWorkspace = () => setView("developer", false)
+  const openDeveloper = (directory?: string) =>
+    setView({
+      developer: true,
+      mounted: true,
+      directory: directory || "",
+      request: view.request + 1,
+      error: "",
+    })
   const loadLocale = async () => {
   const loadLocale = async () => {
     const current = await platform.storage?.("opencode.global.dat").getItem("language")
     const current = await platform.storage?.("opencode.global.dat").getItem("language")
     const legacy = current ? undefined : await platform.storage?.().getItem("language.v1")
     const legacy = current ? undefined : await platform.storage?.().getItem("language.v1")
@@ -354,6 +366,43 @@ function DesktopRoot(props: { windowState: DesktopWindowState }) {
   const onboarding = Promise.withResolvers<void>()
   const onboarding = Promise.withResolvers<void>()
 
 
   function Inner() {
   function Inner() {
+    const server = useServer()
+    const tabs = useTabs()
+    const settings = useSettings()
+    const navigate = useNavigate()
+    createEffect(() => {
+      const request = view.request
+      const directory = view.directory
+      if (!directory) return
+      let active = true
+      onCleanup(() => {
+        active = false
+      })
+      void (async () => {
+        await Promise.all([server.ready.promise, tabs.ready.promise, onboarding.promise])
+        if (!active || request !== view.request) return
+        const local = server.list.find(ServerConnection.builtin) ?? server.list.find(ServerConnection.local)
+        if (!local) throw new Error("开发服务尚未就绪。可返回科研工作台继续研究,稍后再打开工作区。")
+        const key = ServerConnection.key(local)
+        const projects = server.projects.forServer(key)
+        projects.open(directory)
+        projects.touch(directory)
+        if (settings.general.newLayoutDesigns()) {
+          const tab = await tabs.newDraft({ server: key, directory })
+          if (active) tabs.select(tab)
+        } else {
+          server.setActive(key)
+          const encoded = btoa(String.fromCharCode(...new TextEncoder().encode(directory)))
+            .replace(/\+/g, "-")
+            .replace(/\//g, "_")
+            .replace(/=+$/, "")
+          navigate(`/${encoded}`)
+        }
+        if (active) setView("directory", "")
+      })().catch((error: unknown) => {
+        if (active) setView("error", error instanceof Error ? error.message : "工作区未能打开,请稍后重试。")
+      })
+    })
     const cmd = useCommand()
     const cmd = useCommand()
     menuTrigger = (id) => cmd.trigger(id)
     menuTrigger = (id) => cmd.trigger(id)
 
 
@@ -424,11 +473,28 @@ function DesktopRoot(props: { windowState: DesktopWindowState }) {
   return (
   return (
     <PlatformProvider value={platform}>
     <PlatformProvider value={platform}>
       <AppBaseProviders locale={locale.latest}>
       <AppBaseProviders locale={locale.latest}>
-        <Show
-          when={view.developer}
-          fallback={<PaasWorkspace standalone onOpenDeveloper={() => setView("developer", true)} />}
-        >
-          <App />
+        <div style={{ display: view.developer ? "none" : "contents" }}>
+          <PaasWorkspace standalone onOpenDeveloper={openDeveloper} />
+        </div>
+        <Show when={view.mounted}>
+          <div
+            style={{
+              display: view.developer ? "flex" : "none",
+              "flex-direction": "column",
+              height: "100dvh",
+              position: "relative",
+            }}
+          >
+            <div class="desktop-research-return">
+              <button type="button" onClick={() => setView("developer", false)}>
+                ← 返回科研工作台
+              </button>
+              <Show when={view.error}>
+                <span role="alert">{view.error}</span>
+              </Show>
+            </div>
+            <App />
+          </div>
         </Show>
         </Show>
       </AppBaseProviders>
       </AppBaseProviders>
     </PlatformProvider>
     </PlatformProvider>

+ 19 - 0
packages/desktop/src/renderer/styles.css

@@ -0,0 +1,19 @@
+.desktop-research-return {
+  position: fixed;
+  bottom: 12px;
+  left: 12px;
+  z-index: 10010;
+  display: flex;
+  align-items: center;
+  gap: 12px;
+  max-width: calc(100vw - 24px);
+  padding: 8px 12px;
+  border: 1px solid var(--border-base, #667085);
+  border-radius: 8px;
+  background: var(--background-base, #fff);
+  box-shadow: 0 2px 8px #0002;
+}
+.desktop-research-return button {
+  cursor: pointer;
+  white-space: nowrap;
+}