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

fix(app): improve inbox navigation and unread state reliability

邵勃源 4 дней назад
Родитель
Сommit
e9a4c58241

+ 2 - 0
packages/app/e2e/paas/fixture.tsx

@@ -77,6 +77,7 @@ const ux = {
   uploads: 0,
   holdRun: "",
   holdThread: "",
+  threadError: "",
   held: false,
   connectError: "",
   catalogError: "",
@@ -165,6 +166,7 @@ const api: PaasPlatform = {
       if (request.action === "file-capabilities") return { direct_upload_max_bytes: 100000 }
       if (request.action === "threads") return { threads: [] }
       if (request.action === "thread-runs") {
+        if (ux.threadError) throw new Error(ux.threadError)
         const value = structuredClone({
           thread_id: request.threadID,
           runs: [...uxRuns.values()].filter((row) => row.thread_id === request.threadID),

+ 73 - 0
packages/app/e2e/paas/inbox.spec.ts

@@ -124,3 +124,76 @@ test("completed unread stays read after a reload", async ({ page }) => {
   await expect(page.getByRole("heading", { name: "研究计划", exact: true })).toBeVisible()
   await expect(page.getByRole("button", { name: /待处理/ })).toHaveCount(0)
 })
+
+for (const width of [360, 520]) {
+  test(`inbox stays within a ${width}px window and restores focus when closed`, async ({ page }) => {
+    await page.goto("/e2e/paas/index.html?completed")
+    await page.getByLabel("API Key", { exact: true }).fill(`inbox-width-${width}`)
+    await page.getByRole("button", { name: "连接平台", exact: true }).click()
+    await page
+      .getByRole("button", { name: /已有研究/ })
+      .first()
+      .click()
+    await page.setViewportSize({ width, height: 650 })
+    const toggle = page.getByRole("button", { name: "待处理 1 项", exact: true })
+    await toggle.click()
+    const panel = page.getByRole("dialog", { name: "待处理" })
+    const bounds = await panel.boundingBox()
+    expect(bounds!.x).toBeGreaterThanOrEqual(0)
+    expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(width)
+    expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(650)
+    await page.getByRole("button", { name: "关闭待处理", exact: true }).click()
+    await expect(panel).toHaveCount(0)
+    await expect(toggle).toBeFocused()
+  })
+}
+
+test("unloaded inbox results stay unread after a failed fetch, then open the exact run on retry", async ({ page }) => {
+  await page.goto("/e2e/paas/index.html?ux")
+  await page.getByLabel("API Key", { exact: true }).fill("inbox-load")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("最初的研究")
+  await page.getByRole("button", { name: "发送消息", exact: true }).click()
+  await expect(page.getByRole("button", { name: "暂停", exact: true })).toBeVisible()
+  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 }).first()).toBeVisible()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("保留的草稿")
+  await page.evaluate(() => {
+    window.paasUX.add({
+      run_id: "external_result",
+      agent_id: "research",
+      thread_id: "thread_ux_1",
+      status: "completed",
+      input: "另一轮研究",
+      output: "# 新增研究成果\n\n完成证据核验。",
+      updated_at: "2026-11-30T12:00:00Z",
+    })
+    Object.assign(window.paasUX, { threadError: "模拟会话读取失败" })
+  })
+  await page.getByRole("button", { name: "平台任务", exact: true }).click()
+  const toggle = page.getByRole("button", { name: "待处理 2 项", exact: true })
+  await expect(toggle).toBeVisible()
+  await toggle.click()
+  await page
+    .getByRole("dialog", { name: "待处理" })
+    .getByRole("button", { name: /另一轮研究/ })
+    .click()
+  await expect(page.getByRole("alert")).toBeVisible()
+  await page.getByText("查看错误详情", { exact: true }).click()
+  await expect(page.getByText("模拟会话读取失败", { exact: true })).toBeVisible()
+  await expect(toggle).toBeVisible()
+  await page.evaluate(() => Object.assign(window.paasUX, { threadError: "" }))
+  await toggle.click()
+  await page
+    .getByRole("dialog", { name: "待处理" })
+    .getByRole("button", { name: /另一轮研究/ })
+    .click()
+  const target = page.locator('.paas-chat-message[data-run-id="external_result"]')
+  await expect(target).toBeFocused()
+  await expect(target).toContainText("新增研究成果")
+  await expect(page.getByRole("textbox", { name: "消息", exact: true })).toHaveValue("保留的草稿")
+  await expect(page.getByRole("button", { name: "待处理 1 项", exact: true })).toBeVisible()
+})

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

@@ -115,13 +115,14 @@ export function createResearchChats(props: {
     setState({ active: id, error: "", focusRun: "", syncing: "" })
     save()
   }
-  const activate = (id: string) => {
+  const activate = (id: string, focusRun = "") => {
     const ticket = beginNavigation()
     const chat = state.chats.find((c) => c.id === id)
     if (!chat) return
     show(id)
+    setState("focusRun", focusRun)
     if (chat.threadID && props.connected)
-      void loadThread({ id: chat.agentID, name: chat.name }, chat.threadID, chat.title, ticket)
+      void loadThread({ id: chat.agentID, name: chat.name }, chat.threadID, chat.title, ticket, focusRun)
   }
   const update = (chatID: string, messageID: string, run: Record<string, unknown>, notify = true) => {
     const chat = state.chats.find((c) => c.id === chatID)
@@ -515,7 +516,10 @@ export function createResearchChats(props: {
     const existing = state.chats.find((c) => c.agentID === agent.id && c.threadID === threadID)
     if (existing) hydrate(existing)
     const observed = new Map(existing?.messages.map((m) => [m.id, m.updated]))
-    if (existing && selected(ticket)) show(existing.id)
+    if (existing && selected(ticket)) {
+      show(existing.id)
+      setState("focusRun", focusRun)
+    }
     setState("syncing", threadID)
     try {
       const result = await props.api!.request({ action: "thread-runs", agentID: paasText(agent.id), threadID })

+ 24 - 11
packages/app/src/pages/paas/chat.tsx

@@ -93,6 +93,7 @@ export function PaasChat(props: {
     renaming: false,
     title: "",
     agentOverride: "",
+    pendingRead: undefined as InboxItem | undefined,
     exporting: "",
     saved: "",
     savedPath: "",
@@ -130,8 +131,7 @@ export function PaasChat(props: {
   })
   const { state, setState, current } = model
   const [seenVersion, setSeenVersion] = createSignal(0)
-  const seenKey = (projectID: string) =>
-    inboxSeenKey(props.scope || "local", platform.windowID || "main", projectID)
+  const seenKey = (projectID: string) => inboxSeenKey(props.scope || "local", platform.windowID || "main", projectID)
   const seen = createMemo(() => {
     seenVersion()
     return new Map(props.projects.map((project) => [project.id, readInboxSeen(localStorage, seenKey(project.id))]))
@@ -145,17 +145,10 @@ export function PaasChat(props: {
     }),
   )
   const openInboxItem = (item: InboxItem) => {
-    model.activate(item.chatID)
+    setUI("pendingRead", item.kind === "unread" ? item : undefined)
+    model.activate(item.chatID, item.runID)
     props.onProjectChange(item.projectID)
     props.onShowChat?.()
-    // Approvals and failures stay actionable, so only completed results are marked seen.
-    if (item.kind !== "unread") return
-    try {
-      markInboxSeen(localStorage, seenKey(item.projectID), item.id)
-      setSeenVersion((value) => value + 1)
-    } catch {
-      // Storage can be unavailable in restricted webviews; keep the item until the session ends.
-    }
   }
   const currentAgent = createMemo(() => props.agents.find((agent) => agent.id === current()?.agentID))
   const blank = () => !!current() && !current()!.messages.length && !current()!.threadID
@@ -285,10 +278,29 @@ export function PaasChat(props: {
       (runID) => {
         if (!runID) return
         queueMicrotask(() => {
+          if (!life.active || !props.visible || state.focusRun !== runID) return
           const row = elements.messages?.querySelector<HTMLElement>(`[data-run-id="${CSS.escape(runID)}"]`)
           if (!row || !elements.messages) return
           setUI({ follow: false, unread: false })
           elements.messages.scrollTop += row.getBoundingClientRect().top - elements.messages.getBoundingClientRect().top
+          row.focus({ preventScroll: true })
+          const pending = ui.pendingRead
+          const message = current()?.messages.find((message) => message.role === "assistant" && message.runID === runID)
+          // Only acknowledge a result that has actually loaded into the selected conversation.
+          if (
+            pending?.chatID !== current()?.id ||
+            pending?.runID !== runID ||
+            !message?.text ||
+            !["completed", "partial"].includes(message.status || "")
+          )
+            return
+          try {
+            markInboxSeen(localStorage, seenKey(pending.projectID), pending.id)
+            setSeenVersion((value) => value + 1)
+          } catch {
+            // Keep the unread item when its acknowledgement cannot be persisted.
+          }
+          setUI("pendingRead", undefined)
         })
       },
     ),
@@ -886,6 +898,7 @@ export function PaasChat(props: {
                       class="paas-chat-message"
                       data-role={message.role}
                       data-run-id={message.role === "assistant" ? message.runID : undefined}
+                      tabIndex={message.role === "assistant" ? -1 : undefined}
                     >
                       <strong>{message.role === "user" ? "你" : current()?.name}</strong>
                       <Show when={message.text}>

+ 23 - 5
packages/app/src/pages/paas/inbox-panel.tsx

@@ -2,8 +2,9 @@ import { Index, Show, onCleanup, onMount } from "solid-js"
 import { ResearchIcon } from "./research-icon"
 import { createInboxOpenState } from "./inbox-panel-state"
 import type { InboxItem } from "./inbox"
+import { Icon } from "@opencode-ai/ui/icon"
 
-const labels = { approval: "待确认", failed: "失败", unread: "未读结果" }
+const labels = { approval: "待确认", clarification: "待补充", failed: "执行失败", unread: "未读结果" }
 
 const stamp = (at: number) => {
   if (!at) return ""
@@ -52,8 +53,21 @@ export function InboxPanel(props: { items: InboxItem[]; onOpen: (item: InboxItem
         </summary>
         <section class="paas-inbox-panel" role="dialog" aria-label="待处理">
           <header>
-            <strong>待处理</strong>
-            <span>{props.items.length} 项</span>
+            <div>
+              <strong>待处理</strong>
+              <span>{props.items.length} 项 · 所有项目</span>
+            </div>
+            <button
+              type="button"
+              class="paas-icon-action"
+              aria-label="关闭待处理"
+              onClick={() => {
+                setOpen(false)
+                root?.querySelector("summary")?.focus()
+              }}
+            >
+              <Icon name="close" size="small" />
+            </button>
           </header>
           <Index each={props.items}>
             {(item) => {
@@ -67,8 +81,12 @@ export function InboxPanel(props: { items: InboxItem[]; onOpen: (item: InboxItem
                     props.onOpen(item())
                   }}
                 >
-                  <span>{labels[item().kind]}</span>
-                  <span class="paas-inbox-project">{item().projectName}</span>
+                  <span class="paas-inbox-meta">
+                    <span class="paas-inbox-kind">{labels[item().kind]}</span>
+                    <span class="paas-inbox-project" title={item().projectName}>
+                      {item().projectName}
+                    </span>
+                  </span>
                   <strong>{item().title}</strong>
                   <small>{item().detail}</small>
                   <Show when={stamp(at())}>

+ 35 - 3
packages/app/src/pages/paas/inbox.test.ts

@@ -39,9 +39,7 @@ test("builds approvals, failures and unread completions across projects", () =>
         { id: "m2", role: "assistant", runID: "run-b", status: "failed", text: "", error: "失败" },
         { id: "m3", role: "assistant", runID: "run-c", status: "completed", text: "完成报告" },
       ]),
-      chat("b", "p2", [
-        { id: "m4", role: "assistant", runID: "run-d", status: "waiting_human", text: "其他项目" },
-      ]),
+      chat("b", "p2", [{ id: "m4", role: "assistant", runID: "run-d", status: "waiting_human", text: "其他项目" }]),
       chat("c", "p3", [{ id: "m5", role: "assistant", runID: "run-e", status: "failed", text: "" }]),
     ],
     tasks: [],
@@ -111,3 +109,37 @@ test("archived chats contribute no inbox items, including task-index rows", () =
   })
   expect(items).toEqual([])
 })
+
+test("stale task-index reminders do not override a loaded conversation", () => {
+  const items = buildInbox({
+    projects,
+    seen: new Map([["p1", new Set(["unread:read"])]]),
+    chats: [
+      chat("a", "p1", [
+        { id: "m1", role: "assistant", runID: "resumed", status: "running" },
+        { id: "m2", role: "assistant", runID: "cancelled", status: "cancelled" },
+        { id: "m3", role: "assistant", runID: "read", status: "completed", text: "已读报告" },
+      ]),
+    ],
+    tasks: ["resumed", "cancelled", "read"].map((run_id) => ({
+      run_id,
+      thread_id: "thread-a",
+      status: "waiting_human",
+    })),
+  })
+  expect(items).toEqual([])
+})
+
+test("clarification requests remain actionable in both conversations and the task index", () => {
+  const items = buildInbox({
+    projects,
+    seen: new Map(),
+    chats: [
+      chat("a", "p1", [
+        { id: "m1", role: "assistant", runID: "clarify-a", status: "needs_clarification", text: "请提供数据" },
+      ]),
+    ],
+    tasks: [{ run_id: "clarify-b", thread_id: "thread-a", status: "needs_clarification" }],
+  })
+  expect(items.map((item) => item.kind)).toEqual(["clarification", "clarification"])
+})

+ 34 - 5
packages/app/src/pages/paas/inbox.ts

@@ -1,6 +1,6 @@
 import { paasStatus, paasText } from "@/paas"
 
-export type InboxKind = "approval" | "failed" | "unread"
+export type InboxKind = "approval" | "clarification" | "failed" | "unread"
 export type InboxProject = { id: string; name: string }
 
 export type InboxItem = {
@@ -53,6 +53,7 @@ export function buildInbox(input: {
   const threads = new Map<string, Chat>()
   for (const chat of chats) if (chat.threadID && !threads.has(chat.threadID)) threads.set(chat.threadID, chat)
   const items = new Map<string, InboxItem>()
+  const observed = new Set<string>()
   const add = (item: InboxItem) => {
     const key = item.runID || item.id
     if (!items.has(key)) items.set(key, item)
@@ -65,6 +66,9 @@ export function buildInbox(input: {
     const seen = seenFor(projectID)
     for (const message of chat.messages) {
       if (message.role !== "assistant" || !message.runID) continue
+      // The loaded conversation takes precedence over the task index, including
+      // states that no longer need an inbox entry (running, cancelled or read).
+      if (message.status) observed.add(message.runID)
       const at = message.updated || message.started || 0
       if (["waiting_human", "waiting_confirmation"].includes(message.status || ""))
         add({
@@ -78,6 +82,18 @@ export function buildInbox(input: {
           runID: message.runID,
           at,
         })
+      else if (message.status === "needs_clarification")
+        add({
+          id: `clarification:${message.runID}`,
+          kind: "clarification",
+          title: chat.title,
+          detail: "需要补充信息后才能继续",
+          projectID,
+          projectName,
+          chatID: chat.id,
+          runID: message.runID,
+          at,
+        })
       else if (message.status === "failed")
         add({
           id: `failed:${message.runID}`,
@@ -99,7 +115,8 @@ export function buildInbox(input: {
           id: `unread:${message.runID}`,
           kind: "unread",
           title: chat.title,
-          detail: chat.name,
+          detail:
+            chat.messages.find((source) => source.role === "user" && source.runID === message.runID)?.text || chat.name,
           projectID,
           projectName,
           chatID: chat.id,
@@ -113,7 +130,7 @@ export function buildInbox(input: {
     const runID = paasText(task.run_id) || paasText(task.id)
     const threadID = paasText(task.thread_id) || paasText(task.session_id)
     const chat = threadID ? threads.get(threadID) : undefined
-    if (!runID || !chat || items.has(runID) || !chat.projectID) continue
+    if (!runID || !chat || observed.has(runID) || items.has(runID) || !chat.projectID) continue
     const projectID = chat.projectID
     const projectName = projectNames.get(projectID)!
     const seen = seenFor(projectID)
@@ -131,6 +148,18 @@ export function buildInbox(input: {
         runID,
         at,
       })
+    else if (status === "needs_clarification")
+      add({
+        id: `clarification:${runID}`,
+        kind: "clarification",
+        title: chat.title,
+        detail: "需要补充信息后才能继续",
+        projectID,
+        projectName,
+        chatID: chat.id,
+        runID,
+        at,
+      })
     else if (status === "failed")
       add({
         id: `failed:${runID}`,
@@ -148,7 +177,7 @@ export function buildInbox(input: {
         id: `unread:${runID}`,
         kind: "unread",
         title: chat.title,
-        detail: chat.name,
+        detail: paasText(task.input) || chat.name,
         projectID,
         projectName,
         chatID: chat.id,
@@ -157,6 +186,6 @@ export function buildInbox(input: {
       })
   }
 
-  const priority: Record<InboxKind, number> = { approval: 0, failed: 1, unread: 2 }
+  const priority: Record<InboxKind, number> = { approval: 0, clarification: 1, failed: 2, unread: 3 }
   return [...items.values()].sort((a, b) => priority[a.kind] - priority[b.kind] || b.at - a.at)
 }

+ 1 - 0
packages/app/src/pages/paas/index.tsx

@@ -401,6 +401,7 @@ export default function PaasWorkspace(
   const goPage = (page: string) => {
     setUI("navOpen", false)
     workspace.setState("page", page)
+    if (page === "tasks") void tasks.refresh()
   }
   props.registerMenuCommand?.((id) => {
     if (id === "settings.open") {

+ 66 - 0
packages/app/src/pages/paas/studio.css

@@ -964,3 +964,69 @@
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
 }
+
+/* Keep the global inbox inside the window beside crowded chat actions. */
+.paas-inbox-panel {
+  overscroll-behavior: contain;
+}
+.paas-inbox-panel > header {
+  align-items: center;
+  position: sticky;
+  top: -12px;
+  z-index: 1;
+  margin: -12px -12px 0;
+  padding: 12px;
+  background: var(--paas-surface);
+  border-bottom: 1px solid var(--border-weak-base);
+}
+.paas-inbox-panel > header > div {
+  display: grid;
+  gap: 3px;
+}
+.paas-inbox-panel > header strong {
+  color: var(--text-base);
+  font-size: var(--paas-type-caption);
+}
+.paas-inbox-item {
+  min-width: 0;
+}
+.paas-inbox-item > .paas-inbox-meta {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  min-width: 0;
+  color: var(--text-weak);
+}
+.paas-inbox-kind {
+  flex-shrink: 0;
+  padding: 2px 6px;
+  border-radius: 5px;
+  background: var(--background-weak);
+}
+.paas-inbox-item:is(.is-approval, .is-clarification) .paas-inbox-kind {
+  color: var(--paas-accent);
+}
+.paas-inbox-project {
+  min-width: 0;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.paas-inbox-item > strong {
+  font-size: var(--paas-type-caption);
+  line-height: 1.5;
+  display: -webkit-box;
+  overflow: hidden;
+  -webkit-box-orient: vertical;
+  -webkit-line-clamp: 2;
+}
+@media (max-width: 620px) {
+  .paas-inbox-panel {
+    position: fixed;
+    top: 66px;
+    left: 12px;
+    right: 12px;
+    width: auto;
+    max-height: calc(100dvh - 82px);
+  }
+}

+ 1 - 0
packages/app/test-browser/paas-inbox-panel.test.ts

@@ -12,6 +12,7 @@ const item: InboxItem = {
   title: "研究计划",
   detail: "科研助手",
   projectID: "project_1",
+  projectName: "测试项目",
   chatID: "chat_1",
   runID: "run_1",
   at: 1,