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

fix(desktop): 完善历史恢复与科研续研交互

缓存损坏和迟到事件可能让会话消失或误阻断发送,科研预算与中断续研也缺少直接入口。本次围绕保留成果、找回任务和继续研究完善用户操作链。

- 隔离损坏缓存并恢复健康会话,避免迟到运行事件覆盖终态
- 支持较早活动任务与历史分页,旧服务明确提示查询范围
- 会话内编辑科研预算及轮次,返回原草稿;目录折叠,常用设置优先
- 部分成果续研保留原报告与新增要求,不自动重跑或提高预算
- 降低目录轮询频率,隐藏窗口暂停会话和任务列表轮询
- 21 个界面场景完成复验,数据缓存 11 项、桌面传输 15 项通过;类型检查及修改前后各 5 项生产性能基准通过
邵勃源 5 дней назад
Родитель
Сommit
bc83de2554

+ 17 - 0
PAAS_OPTIMIZATION_PLAN.zh-CN.md

@@ -164,3 +164,20 @@ bun run package:beta  # 正式签名安装包,需提供对应系统签名、
 - 433 项相关回归通过。完整任务后,对无新增问题时的紧凑补丁路由另做真实阶段复验,两次补丁调用完成;该阶段复验不计为另一份完整任务。
 
 完整验收报告与本轮四次真实运行记录:`/Users/shaoboyuan/seecoder/output/desktop-repair-acceptance-20261129/验收报告.html`。先前失败记录未删除或改为成功。本次使用 beta.3 对接隔离后端,修复源码与验收记录随本次提交同步,未重新打包或正式发版;签名、公证与其他平台仍不在本次验收范围。
+
+## 用户交互完善:会话、任务与续研(2026-11-29)
+
+本轮从用户操作路径继续完善,不新增科研内容门禁,也不自动提高调用预算。
+
+- **会话恢复**:单条损坏消息不再使全部会话恢复为空;健康消息、其他会话、草稿与材料保留。导航索引损坏时,从同账号、同缓存来源的会话记录恢复索引;损坏原文保留,不按成功记录处理。
+- **状态稳定**:已确认结束的任务不接受迟到的“开始/运行中”事件回退,避免继续发送入口被误锁定。
+- **任务可达**:配套 PaaS 支持最近历史分页与补全较早活动任务,并保持租户、用户过滤。桌面提供“加载更早任务”,刷新保留已展开记录,较早活动任务结束后补查终态。旧版或远端服务暂不支持完整查询时,明确提示数量范围,不把有限记录冒充全部任务。
+- **研究设置**:从会话直接进入设置,保存或取消后返回原会话,保留草稿。科研智能体可填写计划 Token 预算、累计硬上限、最少/最多轮次与时间上限;保留后端已有的范围及交叉字段约束。目录折叠为高级选项,不在科研设置中展示无效的普通 ReAct 步数等选项;完整 JSON 仍可编辑。
+- **中断后继续**:部分成果可导出或“基于已有成果续研”,报告与新增要求一并填入草稿,不自动提交。设置变更用于后续任务,不声称能改变原任务的额度或恢复任意中断点。
+- **后台负担**:目录刷新从每 2 秒降为每 30 秒;隐藏窗口暂停会话及任务列表轮询,重新可见时立即同步。尚未合并所有状态订阅,不宣称已完成全局事件推送。
+
+验证:App/Desktop 类型检查、E2E 类型检查通过;缓存与平台数据测试 11 项通过,桌面原生传输测试 15 项通过,PaaS 本地服务相关测试 36 项与远端测试 3 项通过。页面交互测试包含 21 个不同场景;新增流程覆盖终态防回退、旧活动任务与历史分页、研究设置返回草稿、部分成果续研。界面验收使用真实组件和合成响应,PaaS 回归使用隔离数据库及测试服务,未调用真实模型。
+
+原始日志和截图:`/Users/shaoboyuan/seecoder/output/desktop-ux-20261129/`。本轮未修改日常服务配置,未重启已有应用/服务,未打包或发布安装包。
+
+性能复验:修改前后各 5 项生产版会话基准通过。四项流式完成耗时改前为 51.78—54.09 秒、改后为 49.60—52.23 秒;消息行和 Markdown 均未重建,底部滚动漂移均为 0。单轮测量仅用于回归检查,不据此宣称性能提升。最终设置页保存返回草稿流程另做复验通过。

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

@@ -33,6 +33,11 @@ const ux = {
   run: (id: string) => uxRuns.get(id),
 }
 Object.assign(window, { paasUX: ux })
+let researchConfig = {
+  researchWorkflow: "research67-scientific-v1",
+  model: { provider: "deepseek", name: "deepseek-chat" },
+  scientific: { token_budget: 500000, max_actual_tokens: 1000000, max_rounds: 4, max_wall_seconds: 3600 },
+}
 const api: PaasPlatform = {
   connect: async (input) => {
     if (!input) throw new Error("No saved connection")
@@ -59,6 +64,13 @@ const api: PaasPlatform = {
   request: async (request) => {
     calls.push(request)
     if (ux.enabled) {
+      if (request.action === "agent")
+        return { ...agent, config: structuredClone(researchConfig), updated_at: "version-1", can_update_metadata: true }
+      if (request.action === "update-agent") {
+        researchConfig = request.update.config as typeof researchConfig
+        return { saved: true }
+      }
+      if (request.action === "knowledge") return { items: [] }
       if (request.action === "upload-selected" || request.action === "upload-file") {
         ux.uploads++
         uploads.forEach((listener) => listener({ uploadID: request.uploadID!, sent: 10, total: 10 }))
@@ -113,7 +125,23 @@ const api: PaasPlatform = {
         )
         return { ...value }
       }
-      if (request.action === "history") return { runs: [...uxRuns.values()] }
+      if (request.action === "history") {
+        const all = [...uxRuns.values()].reverse(),
+          offset = request.offset || 0
+        const recent = all.slice(offset, offset + 20)
+        const active = request.includeActive
+          ? all.filter(
+              (row) =>
+                !["completed", "failed", "partial", "cancelled", "needs_clarification"].includes(String(row.status)),
+            )
+          : []
+        return {
+          runs: [...new Map([...recent, ...active].map((row) => [row.run_id, { ...row }])).values()],
+          pagination_supported: true,
+          active_included: !!request.includeActive,
+          next_offset: offset + 20 < all.length ? offset + 20 : null,
+        }
+      }
       if (request.action === "run") {
         const value = structuredClone(uxRuns.get(request.runID))
         if (ux.holdRun === request.runID) {

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

@@ -167,3 +167,84 @@ test("reconnecting refreshes the selected conversation while keeping its draft",
   await expect(page.getByText("重新连接时同步的新成果", { exact: true })).toBeVisible()
   await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("仍在编辑的要求")
 })
+
+test("late stream events cannot undo completion or block the next draft", async ({ page }) => {
+  await connect(page)
+  await submit(page, "检查迟到事件")
+  await page.evaluate(() => window.paasUX.update("ux_1", { status: "completed", output: "已交付报告" }))
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await expect(page.getByText("已交付报告", { exact: true })).toBeVisible()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("继续研究")
+  await page.evaluate(() => {
+    const execution = window.paasTestCalls.find((c) => c.action === "execute")!
+    ;(window.paasUX as unknown as { progress(e: unknown): void }).progress({
+      executionID: execution.executionID,
+      type: "started",
+      runID: "ux_1",
+      status: "running",
+    })
+  })
+  await expect(page.getByRole("button", { name: "发送消息", exact: true })).toBeEnabled()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toHaveCount(0)
+})
+
+test("old active tasks remain visible and earlier history can be loaded", async ({ page }) => {
+  await connect(page)
+  await page.evaluate(() => {
+    for (let i = 0; i < 26; i++)
+      window.paasUX.add({
+        run_id: `page_${i}`,
+        agent_id: "research",
+        input: `分页研究${i}`,
+        status: i === 0 ? "paused" : "completed",
+      })
+  })
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await expect(page.getByRole("row").filter({ hasText: "分页研究0" })).toBeVisible()
+  await expect(
+    page
+      .getByRole("row")
+      .filter({ hasText: "分页研究1" })
+      .filter({ hasNotText: /分页研究1\d/ }),
+  ).toHaveCount(0)
+  await page.getByRole("button", { name: "加载更早任务", exact: true }).click()
+  await expect(page.getByRole("row")).toHaveCount(27)
+  await expect(page.getByRole("button", { name: "加载更早任务", exact: true })).toHaveCount(0)
+  await page.getByRole("button", { name: "刷新任务", exact: true }).click()
+  await expect(page.getByRole("row")).toHaveCount(27)
+})
+
+test("research settings return to the same draft without executing or changing budgets automatically", async ({
+  page,
+}, testInfo) => {
+  await connect(page)
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("保留我的下一轮要求")
+  await page.getByRole("button", { name: "研究设置", exact: true }).click()
+  await page.getByLabel("累计 Token 硬上限", { exact: true }).fill("2000000")
+  await page
+    .getByRole("group", { name: "科研预算与迭代", exact: true })
+    .screenshot({ path: testInfo.outputPath("research-settings.png") })
+  await page.getByRole("button", { name: "保存修改", exact: true }).click()
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("保留我的下一轮要求")
+  const calls = await page.evaluate(() => window.paasTestCalls)
+  expect(calls.some((c) => c.action === "execute")).toBe(false)
+  expect(calls.find((c) => c.action === "update-agent")).toMatchObject({
+    update: { config: { scientific: { max_actual_tokens: 2000000, token_budget: 500000 } } },
+  })
+})
+
+test("partial results explain the next step and continuation keeps the user's draft", async ({ page }, testInfo) => {
+  await connect(page)
+  await submit(page, "中断后的继续研究")
+  await page.evaluate(() => window.paasUX.update("ux_1", { status: "partial", output: "已完成的研究依据与初步方案" }))
+  await page.getByRole("button", { name: "刷新状态", exact: true }).click()
+  await expect(page.getByText(/当前成果已保留,可先导出/)).toBeVisible()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("补充新的实验条件")
+  await page.getByRole("button", { name: "基于已有成果续研", exact: true }).click()
+  const draft = await page.getByRole("textbox", { name: "消息", exact: true }).inputValue()
+  expect(draft).toContain("补充新的实验条件")
+  expect(draft).toContain("已完成的研究依据与初步方案")
+  expect(await page.evaluate(() => window.paasTestCalls.filter((c) => c.action === "execute").length)).toBe(1)
+  await page.screenshot({ path: testInfo.outputPath("continuation.png"), fullPage: true })
+})

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

@@ -59,7 +59,7 @@ export type PaasRequest =
   | { action: "agent"; agentID: string }
   | { action: "update-agent"; agentID: string; update: PaasAgentUpdate }
   | { action: "thread-runs"; agentID: string; threadID: string }
-  | { action: "history"; agentID: string }
+  | { action: "history"; agentID: string; offset?: number; includeActive?: boolean }
   | { action: "run"; agentID: string; runID: string }
   | { action: "verify"; agentID: string }
 

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

@@ -11,6 +11,17 @@ const directories = [
 ] as const
 
 const configuration = [
+  {
+    title: "科研预算与迭代",
+    key: "scientific",
+    fields: [
+      { key: "token_budget", label: "计划 Token 预算(提示用量,不自动中止)", min: 1 },
+      { key: "max_actual_tokens", label: "累计 Token 硬上限", min: 1 },
+      { key: "min_rounds", label: "至少研究轮次", min: 1 },
+      { key: "max_rounds", label: "最多研究轮次", min: 1 },
+      { key: "max_wall_seconds", label: "最长运行时间(秒)", min: 1 },
+    ],
+  },
   {
     title: "模型",
     key: "model",
@@ -77,6 +88,7 @@ export function PaasAgentEdit(props: {
   const lifecycle = { active: true }
   onCleanup(() => (lifecycle.active = false))
   const config = createMemo(() => parseConfig(state.configText))
+  const scientific = () => !!config()?.researchWorkflow || !!paasRecord(config()?.scientific)
   const canEditMetadata = () => state.original?.can_update_metadata === true
   const configField = (value: unknown) => (typeof value === "number" ? String(value) : paasText(value))
   const groupValue = (group: string) => {
@@ -148,6 +160,21 @@ export function PaasAgentEdit(props: {
     const original = state.original
     const current = config()
     if (state.busy || !original || !current) return
+    const research = paasRecord(current.scientific)
+    if (scientific() && research) {
+      const planned = Number(research.token_budget ?? Math.min(200000, Number(research.max_actual_tokens ?? 1000000)))
+      const maximum = Number(research.max_actual_tokens ?? 1000000)
+      if (planned > maximum) {
+        setState("error", "计划 Token 预算不能大于累计硬上限,请调整后保存。")
+        return
+      }
+      const minimumRounds = Number(research.min_rounds ?? 2)
+      const maximumRounds = Number(research.max_rounds ?? 3)
+      if (minimumRounds > maximumRounds) {
+        setState("error", "至少研究轮次不能大于最多研究轮次,请调整后保存。")
+        return
+      }
+    }
     const update: PaasAgentUpdate = { config: { ...current }, expected_updated_at: paasText(original.updated_at) }
     if (canEditMetadata()) {
       const name = state.fields.name.trim()
@@ -187,7 +214,7 @@ export function PaasAgentEdit(props: {
     <section class="paas-agent-edit" aria-label="编辑智能体">
       <div class="paas-agent-edit-heading">
         <button type="button" disabled={state.busy} onClick={props.onClose}>
-          <Icon name="arrow-left" size="small" /> 返回智能体
+          <Icon name="arrow-left" size="small" /> 返回工作台
         </button>
         <h1>编辑智能体</h1>
         <Show when={state.original}>
@@ -238,27 +265,39 @@ export function PaasAgentEdit(props: {
               <p class="paas-muted">当前 PaaS 版本支持保存配置与目录,更新服务后可编辑名称和简介。</p>
             </Show>
           </fieldset>
-          <fieldset class="paas-panel paas-edit-fields" disabled={state.busy}>
-            <legend>目录绑定</legend>
-            <div class="paas-edit-columns">
-              <For each={directories}>
-                {(field) => (
-                  <label>
-                    {field.label}
-                    <input
-                      value={state.fields[field.key]}
-                      onInput={(event) => setState("fields", field.key, event.currentTarget.value)}
-                    />
-                    <small class="paas-muted">{field.hint}</small>
-                  </label>
-                )}
-              </For>
-            </div>
-          </fieldset>
-          <For each={configuration}>
+          <details>
+            <summary>高级:材料与成果目录</summary>
+            <fieldset class="paas-panel paas-edit-fields" disabled={state.busy}>
+              <legend>目录绑定</legend>
+              <div class="paas-edit-columns">
+                <For each={directories}>
+                  {(field) => (
+                    <label>
+                      {field.label}
+                      <input
+                        value={state.fields[field.key]}
+                        onInput={(event) => setState("fields", field.key, event.currentTarget.value)}
+                      />
+                      <small class="paas-muted">{field.hint}</small>
+                    </label>
+                  )}
+                </For>
+              </div>
+            </fieldset>
+          </details>
+          <For
+            each={configuration.filter((group) =>
+              scientific() ? ["scientific", "model"].includes(group.key) : group.key !== "scientific",
+            )}
+          >
             {(group) => (
               <fieldset class="paas-panel paas-edit-fields" disabled={state.busy || !config()}>
                 <legend>{group.title}</legend>
+                <Show when={group.key === "scientific"}>
+                  <p class="paas-muted">
+                    留空使用平台默认值。计划预算用于提醒;硬上限限制实际消耗,触顶时保留已有成果。修改用于后续任务,不会自动重跑或改变正在运行的任务。
+                  </p>
+                </Show>
                 <div class="paas-edit-columns">
                   <For each={group.fields}>
                     {(field) => (
@@ -267,6 +306,15 @@ export function PaasAgentEdit(props: {
                         <input
                           type={field.min === undefined ? "text" : "number"}
                           min={field.min}
+                          max={
+                            group.key === "scientific"
+                              ? field.key === "max_wall_seconds"
+                                ? 86400
+                                : field.key.endsWith("rounds")
+                                  ? 8
+                                  : 8000000
+                              : undefined
+                          }
                           step={field.step}
                           value={configField(groupValue(group.key)[field.key])}
                           onInput={(event) => {

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

@@ -116,3 +116,40 @@ describe("research conversation persistence", () => {
     expect(createChatCache(m.storage, "other", "two", () => {}).load().chats).toEqual([])
   })
 })
+
+test("one corrupt message preserves other conversations, drafts and healthy messages", () => {
+  const m = memory(),
+    errors: string[] = []
+  const first = createChatCache(m.storage, "s", "main", () => {})
+  const a = chat("a")
+  a.messages.push({ id: "good", role: "assistant", status: "completed", text: "保留的结果" })
+  first.stage(a)
+  first.stage(chat("b"))
+  first.index(["a", "b"], "a")
+  first.close()
+  m.data.set("lambda-scientist.chats.v2:s:main:a:message:m", "{broken")
+  const next = createChatCache(m.storage, "s", "main", (message) => errors.push(message))
+  const restored = next.load()
+  expect(restored.chats.map((c) => c.id)).toEqual(["a", "b"])
+  expect(restored.chats[0].messages.map((m) => m.text)).toEqual(["保留的结果"])
+  expect(restored.chats[1].draft).toBe("草稿")
+  expect(next.hydrate(restored.chats[1])[0].text).toBe("报告b")
+  restored.chats.forEach(next.stage)
+  next.index(["a", "b"], "a")
+  next.close()
+  expect(errors.at(-1)).toContain("损坏")
+  expect(m.data.get("lambda-scientist.chats.v2:s:main:a:message:m")).toBe("{broken")
+})
+
+test("a corrupt navigation index can be rebuilt from healthy conversation records", () => {
+  const m = memory(),
+    first = createChatCache(m.storage, "s", "main", () => {})
+  first.stage(chat("a"))
+  first.stage(chat("b"))
+  first.index(["a", "b"], "a")
+  first.close()
+  m.data.set("lambda-scientist.chats.v2:s:main:index", "{broken")
+  const next = createChatCache(m.storage, "s", "main", () => {})
+  expect(next.load().chats.map((c) => c.id)).toEqual(["a", "b"])
+  next.close()
+})

+ 19 - 3
packages/app/src/pages/paas/chat-cache.ts

@@ -14,6 +14,7 @@ export function createChatCache(storage: Storage, scope: string, windowID: strin
     index: { ids: [], active: "" } as Index,
     indexDirty: false,
     migrated: false,
+    damaged: false,
   }
   const put = (key: string, value: string) => {
     if (written.get(key) === value) {
@@ -43,7 +44,7 @@ export function createChatCache(storage: Storage, scope: string, windowID: strin
         storage.removeItem(`lambda-scientist.chats.v1:${scope}:latest`)
         state.migrated = false
       }
-      onError("")
+      if (!state.damaged) onError("")
     } catch {
       state.indexDirty = true
       onError("本机暂时无法保存部分内容,当前窗口中的草稿仍保留,可先导出重要报告。")
@@ -52,7 +53,13 @@ export function createChatCache(storage: Storage, scope: string, windowID: strin
   const read = <T>(key: string, fallback: T): T => {
     const raw = storage.getItem(key)
     if (!raw) return fallback
-    return JSON.parse(raw) as T
+    try {
+      return JSON.parse(raw) as T
+    } catch {
+      state.damaged = true
+      onError("部分本机记录损坏,已保留其他会话与草稿;打开对应会话可补齐平台记录。")
+      return fallback
+    }
   }
   function messages(source: string, chatID: string, ids: string[]) {
     return ids
@@ -75,7 +82,16 @@ export function createChatCache(storage: Storage, scope: string, windowID: strin
         state.migrated = !!legacy
         return { chats: Array.isArray(legacy?.chats) ? legacy.chats : [], active: legacy?.active || "" }
       }
-      const index = read<Index>(`${source}:index`, { ids: [], active: "" })
+      const saved = read<Index | null>(`${source}:index`, null)
+      const index =
+        saved && Array.isArray(saved.ids)
+          ? saved
+          : {
+              ids: Array.from({ length: storage.length }, (_, i) => storage.key(i))
+                .filter((key): key is string => !!key && key.startsWith(`${source}:`) && key.endsWith(":meta"))
+                .map((key) => key.slice(source.length + 1, -5)),
+              active: "",
+            }
       const chats = (Array.isArray(index.ids) ? index.ids : []).flatMap((id) => {
         const meta = read<Metadata | null>(`${source}:${id}:meta`, null)
         if (

+ 5 - 1
packages/app/src/pages/paas/chat-state.ts

@@ -374,6 +374,8 @@ export function createResearchChats(props: {
           : event.type === "started"
             ? "running"
             : event.status || message.status
+      // A late event from the original stream must not undo a newer terminal snapshot.
+      if (paasTerminalStatuses.has(message.status || "") && !paasTerminalStatuses.has(next || "")) return
       if (next && next !== message.status && (paasTerminalStatuses.has(next) || next.startsWith("waiting")))
         props.onNotice?.({
           chatID: chat.id,
@@ -395,7 +397,9 @@ export function createResearchChats(props: {
       if (event.threadID) setState("chats", (c) => c.id === chat.id, "threadID", event.threadID)
       if (event.runID) save()
     })
-    const timer = setInterval(() => void refresh(), 5000)
+    const timer = setInterval(() => {
+      if (!document.hidden) void refresh()
+    }, 5000)
     const visible = () => {
       if (!document.hidden) void refresh()
     }

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

@@ -30,6 +30,7 @@ export function PaasChat(props: {
   onOpenTasks?: () => void
   onShowChat?: () => void
   onOpenWorkspace?: (agentID: string) => Promise<void>
+  onEditAgent?: (agentID: string) => void
   workspaceDisabled: boolean
   openTask?: Record<string, unknown>
   onTaskOpened?: () => void
@@ -395,6 +396,11 @@ export function PaasChat(props: {
             </span>
           </div>
           <div class="paas-chat-header-actions">
+            <Show when={currentAgent() && props.onEditAgent}>
+              <button disabled={!props.connected} onClick={() => props.onEditAgent?.(current()!.agentID)}>
+                研究设置
+              </button>
+            </Show>
             <Show when={current()}>
               <button onClick={() => setUI({ renaming: true, title: current()!.title })}>重命名会话</button>
               <button title="仅整理本机列表,不会停止后台任务" onClick={() => model.archive()}>
@@ -559,6 +565,11 @@ export function PaasChat(props: {
                             {message.error}
                           </p>
                         </Show>
+                        <Show when={message.status === "partial"}>
+                          <p class="paas-notice">
+                            当前成果已保留,可先导出,或调整研究设置后基于已有成果继续。续研会填入草稿,由你确认发送,不会自动重跑。
+                          </p>
+                        </Show>
                         <Show when={message.text}>
                           <div class="paas-actions">
                             <button onClick={() => void copy(message)}>
@@ -573,7 +584,7 @@ export function PaasChat(props: {
                                 elements.input?.focus()
                               }}
                             >
-                              基于此方案继续
+                              {message.status === "partial" ? "基于已有成果续研" : "基于此方案继续"}
                             </button>
                           </div>
                         </Show>

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

@@ -44,7 +44,7 @@ export function createPaasWorkspace(api: PaasPlatform | undefined) {
           lifecycle.polling = false
         })
     }
-    const timer = window.setInterval(() => void refresh(), 2000)
+    const timer = window.setInterval(() => void refresh(), 30000)
     const visible = () => void refresh()
     document.addEventListener("visibilitychange", visible)
     onCleanup(() => {

+ 8 - 3
packages/app/src/pages/paas/index.tsx

@@ -47,6 +47,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
     chatAgentID: "",
     openingWorkspace: false,
     editAgentID: "",
+    editReturn: "agents",
   })
   const tasks = createTaskIndex({
     api: platform.paas,
@@ -277,6 +278,10 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
               onAgentOpened={() => setUI("chatAgentID", "")}
               onOpenAgentPacks={openAgentPacks}
               onOpenWorkspace={platform.paas ? openAgentWorkspace : undefined}
+              onEditAgent={(id) => {
+                setUI({ editAgentID: id, editReturn: "chat" })
+                workspace.setState("page", "edit-agent")
+              }}
               workspaceDisabled={ui.openingWorkspace || (!props.standalone && !localServer())}
             />
           </div>
@@ -522,7 +527,7 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                               disabled={disabled()}
                               aria-label={`编辑 ${name()}`}
                               onClick={() => {
-                                setUI("editAgentID", id())
+                                setUI({ editAgentID: id(), editReturn: "agents" })
                                 workspace.setState("page", "edit-agent")
                               }}
                             >
@@ -543,9 +548,9 @@ export default function PaasWorkspace(props: { standalone?: boolean; onOpenDevel
                 <PaasAgentEdit
                   api={api}
                   agentID={ui.editAgentID}
-                  onClose={() => workspace.setState("page", "agents")}
+                  onClose={() => workspace.setState("page", ui.editReturn)}
                   onSaved={async () => {
-                    workspace.setState("page", "agents")
+                    workspace.setState("page", ui.editReturn)
                     showToast({ title: "智能体配置已保存" })
                     await workspace.catalog()
                   }}

+ 91 - 11
packages/app/src/pages/paas/tasks.tsx

@@ -1,6 +1,15 @@
 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"
+import {
+  paasRecord,
+  paasRows,
+  paasRunDetail,
+  paasStatus,
+  paasStatuses,
+  paasTerminalStatuses,
+  paasText,
+  type PaasPlatform,
+} from "@/paas"
 
 /** Persistent task index: navigation never owns or cancels a remote execution. */
 export function createTaskIndex(props: {
@@ -16,14 +25,17 @@ export function createTaskIndex(props: {
     loaded: false,
     error: "",
     updated: "",
+    next: {} as Record<string, number | null>,
+    limited: [] as string[],
+    expanded: [] as string[],
   })
   const life = { epoch: 0, active: true, request: 0 }
-  async function refresh() {
+  async function refresh(more = false) {
     if (!props.connected || !props.api || state.loading) return
     const epoch = life.epoch,
       request = ++life.request
     setState("loading", true)
-    const agents = props.agents.slice()
+    const agents = props.agents.filter((a) => !more || typeof state.next[paasText(a.id)] === "number")
     const results: Record<string, unknown>[] = []
     const failures: string[] = []
     try {
@@ -32,9 +44,31 @@ export function createTaskIndex(props: {
           agents.slice(start, start + 4).map(async (agent) => {
             const id = paasText(agent.id)
             try {
-              const response = await props.api!.request({ action: "history", agentID: id })
+              const offset = more ? state.next[id]! : 0
+              const response = await props.api!.request({
+                action: "history",
+                agentID: id,
+                offset,
+                includeActive: !more,
+              })
+              if (!life.active || epoch !== life.epoch) return
+              const rows = paasRows(response, "runs")
+              const page = paasRecord(response)
+              if (!more && page?.active_included !== true && !state.limited.includes(id))
+                setState("limited", (ids) => [...ids, id])
+              if (!more && page?.active_included === true)
+                setState("limited", (ids) => ids.filter((value) => value !== id))
+              if (more || !state.expanded.includes(id)) {
+                const next = page?.next_offset
+                setState(
+                  "next",
+                  id,
+                  page?.pagination_supported === true && typeof next === "number" && next > offset ? next : null,
+                )
+              }
+              if (more && !state.expanded.includes(id)) setState("expanded", (ids) => [...ids, id])
               results.push(
-                ...paasRows(response, "runs").map((run) => ({
+                ...rows.map((run) => ({
                   ...run,
                   run_id: paasText(run.run_id) || paasText(run.id),
                   agent_id: id,
@@ -49,6 +83,27 @@ export function createTaskIndex(props: {
         )
         if (!life.active || epoch !== life.epoch) return
       }
+      // A formerly active task may have ended outside the most recent history page.
+      if (!more) {
+        const missing = state.rows.filter(
+          (row) =>
+            !paasTerminalStatuses.has(paasStatus(row)) &&
+            !results.some((run) => run.agent_id === row.agent_id && run.run_id === row.run_id),
+        )
+        for (let start = 0; start < missing.length; start += 4) {
+          await Promise.all(
+            missing.slice(start, start + 4).map(async (row) => {
+              try {
+                const run = await paasRunDetail(props.api!, paasText(row.agent_id), paasText(row.run_id))
+                results.push({ ...row, ...run })
+              } catch {
+                failures.push(paasText(row.agent_name))
+              }
+            }),
+          )
+          if (!life.active || epoch !== life.epoch) return
+        }
+      }
       if (life.active && epoch === life.epoch && request === life.request) {
         results.forEach((run) => {
           const previous = state.rows.find((row) => row.agent_id === run.agent_id && row.run_id === run.run_id)
@@ -60,7 +115,9 @@ export function createTaskIndex(props: {
           )
             props.onNotice?.(run)
         })
-        setState("rows", reconcile(results, { key: null }))
+        const merged = new Map(state.rows.map((run) => [`${run.agent_id}:${run.run_id}`, run]))
+        results.forEach((run) => merged.set(`${run.agent_id}:${run.run_id}`, run))
+        setState("rows", reconcile([...merged.values()], { key: null }))
         setState({
           loaded: true,
           error: failures.length ? `${failures.join("、")}暂未同步,保留上次记录,稍后自动重试。` : "",
@@ -74,20 +131,35 @@ export function createTaskIndex(props: {
   createEffect(
     on([() => props.connected, () => props.scope, () => props.agents.map((a) => a.id).join("|")], () => {
       life.epoch++
-      setState({ rows: [], loaded: false, loading: false, error: "", updated: "" })
+      setState({ rows: [], loaded: false, loading: false, error: "", updated: "", limited: [], expanded: [] })
+      setState("next", reconcile({}))
       if (props.connected) void refresh()
     }),
   )
-  const timer = setInterval(() => void refresh(), 10000)
+  const timer = setInterval(() => {
+    if (!document.hidden) void refresh()
+  }, 10000)
+  const visible = () => {
+    if (!document.hidden) void refresh()
+  }
+  document.addEventListener("visibilitychange", visible)
   onCleanup(() => {
     life.active = false
     clearInterval(timer)
+    document.removeEventListener("visibilitychange", visible)
   })
   const waiting = createMemo(() => state.rows.filter((row) => paasStatus(row).startsWith("waiting")))
   const running = createMemo(() =>
     state.rows.filter((row) => !paasTerminalStatuses.has(paasStatus(row)) && !paasStatus(row).startsWith("waiting")),
   )
-  return { state, refresh, waiting, running }
+  return {
+    state,
+    refresh,
+    waiting,
+    running,
+    more: () => refresh(true),
+    hasMore: () => Object.values(state.next).some((value) => typeof value === "number"),
+  }
 }
 
 export function PaasTasks(props: {
@@ -123,7 +195,7 @@ export function PaasTasks(props: {
       <div class="paas-section-title">
         <div>
           <h1>平台任务</h1>
-          <p>自动汇总各智能体最近任务,执行中的任务优先显示。打开任务可继续查看成果或提交确认。</p>
+          <p>汇总活动任务与最近记录,支持加载更早历史。打开任务可查看成果或处理确认。</p>
         </div>
         <button disabled={!props.connected || props.index.state.loading} onClick={() => void props.index.refresh()}>
           刷新任务
@@ -141,6 +213,9 @@ export function PaasTasks(props: {
           {props.index.state.error}
         </p>
       </Show>
+      <Show when={props.index.state.limited.length}>
+        <p class="paas-muted">部分平台仅提供最近记录,活动任务数量可能不完整;升级对应服务后可补齐。</p>
+      </Show>
       <div class="paas-toolbar">
         <label>
           搜索任务
@@ -215,7 +290,12 @@ export function PaasTasks(props: {
           </table>
         </div>
       </Show>
-      <p class="paas-muted">展示平台返回的最近记录;状态变化不会重新执行任务。</p>
+      <Show when={props.index.hasMore()}>
+        <button disabled={!props.connected || props.index.state.loading} onClick={() => void props.index.more()}>
+          {props.index.state.loading ? "正在读取…" : "加载更早任务"}
+        </button>
+      </Show>
+      <p class="paas-muted">刷新只同步记录,不会重新执行任务。搜索范围为已加载的记录。</p>
     </section>
   )
 }

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

@@ -475,3 +475,17 @@ test("submission identity travels in the stream header and receipt lookup never
     await server.stop(true)
   }
 })
+
+test("history paging carries the active-task option and rejects invalid offsets", async () => {
+  const paths: string[] = []
+  const fetcher = (async (url: string | URL | Request) => {
+    paths.push(String(url))
+    return Response.json(String(url).endsWith("/agents") ? { agents: [] } : { runs: [] })
+  }) as typeof fetch
+  const connection = createPaasConnections(fetcher)
+  await connection.connect(1, { url: "http://localhost:8000", apiKey: "test-only" })
+  await connection.request(1, { action: "history", agentID: "a", includeActive: true, offset: 20 })
+  expect(paths.at(-1)).toBe("http://localhost:8000/api/v1/agents/a/runs?offset=20&include_active=true")
+  await expect(connection.request(1, { action: "history", agentID: "a", offset: -1 })).rejects.toThrow("页码无效")
+  connection.disconnect(1)
+})

+ 8 - 1
packages/desktop/src/main/paas.ts

@@ -315,7 +315,14 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
       const base = `/agents/${identifier("agentID" in input ? input.agentID : undefined)}`
       if (input.action === "verify")
         return request(connection, `${base}/verify`, { check_model: false, knowledge_query: "" })
-      if (input.action === "history") return request(connection, `${base}/runs`)
+      if (input.action === "history") {
+        if (input.offset !== undefined && (!Number.isSafeInteger(input.offset) || input.offset < 0))
+          throw new Error("历史页码无效,请刷新任务列表。")
+        const query = new URLSearchParams()
+        if (input.offset !== undefined) query.set("offset", String(input.offset))
+        if (input.includeActive) query.set("include_active", "true")
+        return request(connection, `${base}/runs${query.size ? `?${query}` : ""}`)
+      }
       if (input.action === "run-options") return request(connection, `${base}/run-options`)
       if (input.action === "threads") return request(connection, `${base}/threads`)
       if (input.action === "thread-runs")