Procházet zdrojové kódy

feat(paas): route new research from user goals

241880436@seecoder.cn před 4 dny
rodič
revize
85bd0a72d5

+ 18 - 2
packages/app/e2e/paas/project-workflow.spec.ts

@@ -1,5 +1,19 @@
 import { expect, test } from "@playwright/test"
 
+test("automatic route selects data analysis and hides internal roles", async ({ page }) => {
+  await page.goto("/e2e/paas/index.html?agent-groups")
+  await page.getByLabel("API Key", { exact: true }).fill("automatic-route")
+  await page.getByRole("button", { name: "连接平台", exact: true }).click()
+  await page.getByRole("textbox", { name: "消息", exact: true }).fill("合并 CSV 并画趋势图")
+  const route = page.locator(".paas-agent-route > summary")
+  await expect(route).toContainText("自动 · data67")
+  await route.click()
+  const select = page.getByLabel("选择执行角色", { exact: true })
+  const options = await select.locator("option").allTextContents()
+  expect(options).toContain("data67")
+  expect(options).not.toContain("本体证据补全员")
+})
+
 test("agent directory separates direct roles from internal subagents", async ({ page }) => {
   await page.goto("/e2e/paas/index.html?agent-groups")
   await page.getByLabel("API Key", { exact: true }).fill("agent-groups")
@@ -20,7 +34,8 @@ test("workspace assistant requires and forwards the project folder", async ({ pa
   await page.goto("/e2e/paas/index.html?workspace")
   await page.getByLabel("API Key", { exact: true }).fill("workspace-context")
   await page.getByRole("button", { name: "连接平台", exact: true }).click()
-  await page.getByLabel("选择智能体", { exact: true }).selectOption({ label: "工作区助手" })
+  await page.locator(".paas-agent-route > summary").click()
+  await page.getByLabel("选择执行角色", { exact: true }).selectOption({ label: "工作区助手" })
   await page.getByRole("textbox", { name: "消息", exact: true }).fill("整理这个文件夹")
   await page.getByRole("textbox", { name: "消息", exact: true }).press("Enter")
   await expect(page.getByText("需要绑定项目工作文件夹", { exact: true })).toBeVisible()
@@ -34,7 +49,8 @@ test("workspace assistant requires and forwards the project folder", async ({ pa
   await page.getByLabel("项目名称", { exact: true }).fill("工作区研究")
   await page.getByRole("button", { name: "创建项目", exact: true }).click()
   await page.getByRole("button", { name: "绑定工作文件夹", exact: true }).click()
-  await page.getByLabel("选择智能体", { exact: true }).selectOption({ label: "工作区助手" })
+  await page.locator(".paas-agent-route > summary").click()
+  await page.getByLabel("选择执行角色", { exact: true }).selectOption({ label: "工作区助手" })
   await page.getByRole("textbox", { name: "消息", exact: true }).fill("整理这个文件夹并改 README")
   await page.getByRole("textbox", { name: "消息", exact: true }).press("Enter")
   await expect

+ 1 - 1
packages/app/e2e/paas/studio.spec.ts

@@ -27,7 +27,7 @@ test("small windows keep writing, agent selection and send reachable", async ({
   await page.getByLabel("API Key", { exact: true }).fill("studio-narrow")
   await page.getByRole("button", { name: "连接平台", exact: true }).click()
   await expect(page.getByRole("textbox", { name: "消息", exact: true })).toBeInViewport()
-  await expect(page.getByRole("combobox", { name: "选择智能体", exact: true })).toBeInViewport()
+  await expect(page.locator(".paas-agent-route > summary")).toBeInViewport()
   await expect(page.getByRole("button", { name: "发送消息", exact: true })).toBeInViewport()
   expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(520)
 })

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

@@ -160,7 +160,6 @@ test("wide layout keeps messages and composer on one reading axis", async ({ pag
   }
   const content = await box(".paas-chat-messages > div")
   const composer = await box(".paas-composer")
-  expect((await box(".paas-agent-picker select"))?.width).toBeGreaterThan(200)
   expect(composer).toEqual(content)
   expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(1707)
   await page.getByRole("textbox", { name: "消息", exact: true }).fill("分析材料并制定研究计划")

+ 38 - 0
packages/app/src/pages/paas/agent-routing.test.ts

@@ -0,0 +1,38 @@
+import { expect, test } from "bun:test"
+import { routeAgent } from "./agent-routing"
+
+const agents = [
+  { id: "research67", name: "research67" },
+  { id: "data67", name: "data67" },
+  { id: "workspace", name: "工作区助手" },
+  { id: "reviewer", name: "顶刊审稿助手" },
+  { id: "internal", name: "本体证据补全员" },
+]
+
+test("explicit direct agent wins", () => {
+  expect(routeAgent({ goal: "用顶刊审稿助手评审这篇论文", agents })).toMatchObject({
+    agentID: "reviewer",
+    confidence: "high",
+  })
+})
+
+test("spreadsheets route to data analysis", () => {
+  expect(routeAgent({ goal: "合并并画趋势图", files: [{ name: "sales.csv" }], agents })).toMatchObject({
+    agentID: "data67",
+  })
+  expect(routeAgent({ goal: "合并 CSV 并画趋势图", agents })).toMatchObject({ agentID: "data67" })
+})
+
+test("workspace edits require a bound folder and use workspace assistant", () => {
+  expect(routeAgent({ goal: "整理这个文件夹并改 README", workspace: "D:/Research", agents })).toMatchObject({
+    agentID: "workspace",
+  })
+  expect(routeAgent({ goal: "整理这个文件夹并改 README", agents }).agentID).not.toBe("workspace")
+})
+
+test("default research tasks route to research67", () => {
+  expect(routeAgent({ goal: "从零制定一份研究计划", agents })).toMatchObject({
+    agentID: "research67",
+    confidence: "low",
+  })
+})

+ 43 - 0
packages/app/src/pages/paas/agent-routing.ts

@@ -0,0 +1,43 @@
+import { resolveAgentProfile } from "./agent-profiles"
+
+type Agent = Record<string, unknown>
+
+export type RouteInput = {
+  goal: string
+  files?: { name: string }[]
+  workspace?: string
+  agents: Agent[]
+}
+
+export type RouteResult = {
+  agentID: string
+  reason: string
+  confidence: "high" | "medium" | "low"
+}
+
+const byID = (agents: Agent[], id: string) => agents.find((agent) => agent.id === id)
+const byName = (agents: Agent[], name: string) => agents.find((agent) => agent.name === name)
+const workspaceAgent = (agents: Agent[]) => agents.find((agent) => resolveAgentProfile(agent).requiresWorkspace)
+const nameHit = (goal: string, agents: Agent[]) =>
+  agents.find((agent) => typeof agent.name === "string" && goal.includes(agent.name))
+
+export function routeAgent(input: RouteInput): RouteResult {
+  const named = nameHit(input.goal, input.agents)
+  if (named) return { agentID: String(named.id), reason: "你明确指定了该智能体", confidence: "high" }
+  const data = byID(input.agents, "data67") || byName(input.agents, "data67")
+  if (
+    (input.files?.some((file) => /\.(csv|tsv|xlsx?)$/i.test(file.name)) ||
+      /(csv|表格|趋势图|统计|数据清洗)/i.test(input.goal)) &&
+    data
+  )
+    return { agentID: String(data.id), reason: "检测到表格文件和数据分析需求", confidence: "high" }
+  const workspace = workspaceAgent(input.agents)
+  if (input.workspace && /文件夹|目录|README|代码|脚本|批量|整理|重命名|修改文件/i.test(input.goal) && workspace)
+    return { agentID: String(workspace.id), reason: "检测到当前项目文件夹中的文件操作", confidence: "high" }
+  const reviewer = byName(input.agents, "顶刊审稿助手")
+  if (/评审|审稿|审阅意见/i.test(input.goal) && reviewer)
+    return { agentID: String(reviewer.id), reason: "检测到论文评审意图", confidence: "medium" }
+  const research = byID(input.agents, "research67") || byName(input.agents, "research67")
+  if (research) return { agentID: String(research.id), reason: "默认交给通用科研助手", confidence: "low" }
+  return { agentID: String(input.agents[0]?.id || ""), reason: "回退到第一个可用智能体", confidence: "low" }
+}

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

@@ -64,6 +64,7 @@ export function createResearchChats(props: {
   legacyScope?: string
   windowID?: string
   projectID: () => string
+  agents: () => Record<string, unknown>[]
   onNotice?: (notice: { chatID: string; title: string; body: string }) => void
 }) {
   const [state, setState] = createStore({
@@ -716,12 +717,25 @@ export function createResearchChats(props: {
     setState("chats", (c) => c.id === chat.id, "reference", { messageID: message.id, text: message.text })
     save()
   }
+  function route(agentID: string) {
+    const chat = current()
+    const agent = props.agents().find((item) => item.id === agentID)
+    if (!chat || !agent || chat.messages.length || chat.threadID) return false
+    setState("chats", (item) => item.id === chat.id, {
+      agentID,
+      name: paasText(agent.name),
+    })
+    save()
+    return true
+  }
+
   return {
     state,
     setState,
     current,
     job,
     choose,
+    route,
     activate,
     restore,
     openTask,

+ 56 - 19
packages/app/src/pages/paas/chat.tsx

@@ -8,7 +8,8 @@ import { researchElapsed } from "./progress"
 import { externalToolPhase, researchToolLabel } from "./tool-label"
 import { useDialog } from "@opencode-ai/ui/context/dialog"
 import { ResearchIssue } from "./issue"
-import { resolveAgentProfile } from "./agent-profiles"
+import { directAgents, resolveAgentProfile } from "./agent-profiles"
+import { routeAgent } from "./agent-routing"
 import { ReportReader } from "./report-reader"
 import { Icon } from "@opencode-ai/ui/icon"
 import { usePlatform } from "@/context/platform"
@@ -84,6 +85,7 @@ export function PaasChat(props: {
     expandedGroups: {} as Record<string, boolean>,
     renaming: false,
     title: "",
+    agentOverride: "",
     exporting: "",
     saved: "",
     savedPath: "",
@@ -103,6 +105,7 @@ export function PaasChat(props: {
       return props.legacyScope
     },
     projectID: () => props.projectID,
+    agents: () => props.agents,
     windowID: platform.windowID,
     onNotice: (notice) => {
       setUI("notices", (rows) => [
@@ -120,6 +123,25 @@ export function PaasChat(props: {
   })
   const { state, setState, current } = model
   const currentAgent = createMemo(() => props.agents.find((agent) => agent.id === current()?.agentID))
+  const blank = () => !!current() && !current()!.messages.length && !current()!.threadID
+  const routed = createMemo(() =>
+    routeAgent({
+      goal: current()?.draft || "",
+      files: current()?.files,
+      workspace: props.workspace,
+      agents: directAgents(props.agents),
+    }),
+  )
+  const routedAgent = createMemo(() => props.agents.find((agent) => paasText(agent.id) === routed().agentID))
+  const overrideAgent = createMemo(() => props.agents.find((agent) => paasText(agent.id) === ui.agentOverride))
+  const activeAgent = createMemo(() => (blank() ? overrideAgent() || routedAgent() : currentAgent()))
+  const routeLabel = createMemo(() => paasText(activeAgent()?.name) || "自动选择")
+  createEffect(
+    on(
+      () => current()?.id,
+      () => setUI("agentOverride", ""),
+    ),
+  )
   const currentTitle = createMemo(() => current()?.title || paasText(currentAgent()?.name) || "科研工作台")
   createEffect(
     on(
@@ -352,12 +374,15 @@ export function PaasChat(props: {
     if (id) setState("chats", (c) => c.id === id, "draft", value)
   }
   const send = () => {
-    const profile = currentAgent() ? resolveAgentProfile(currentAgent()!) : undefined
+    const target = blank() ? activeAgent() : currentAgent()
+    const profile = target ? resolveAgentProfile(target) : undefined
     if (profile?.requiresWorkspace && !props.workspace) {
       setState("error", "工作区助手需要先为当前项目绑定工作文件夹。")
       return
     }
     if (current() && !materials.busy(current()!.id)) {
+      const agentID = target ? paasText(target.id) : ""
+      if (blank() && agentID) model.route(agentID)
       bottom()
       void model.send(profile?.requiresWorkspace ? props.workspace : undefined)
     }
@@ -1104,22 +1129,34 @@ export function PaasChat(props: {
             }}
           />
           <footer>
-            <label class="paas-agent-picker">
-              智能体
-              <select
-                aria-label="选择智能体"
-                title={currentAgent()?.name ? paasText(currentAgent()?.name) : undefined}
-                value={current()?.agentID || ""}
-                onChange={(event) => {
-                  const agent = props.agents.find((a) => a.id === event.currentTarget.value)
-                  if (agent) model.choose(agent)
-                }}
-              >
-                <For each={props.agents}>
-                  {(agent) => <option value={paasText(agent.id)}>{paasText(agent.name)}</option>}
-                </For>
-              </select>
-            </label>
+            <details class="paas-agent-route">
+              <summary title={routeLabel()}>
+                {blank() ? (overrideAgent() ? "指定" : "自动") : "当前"} · {routeLabel()}
+              </summary>
+              <div class="paas-agent-route-panel">
+                <p class="paas-muted">
+                  {blank() ? routed().reason : "已有会话沿用当前智能体;新会话会按目标自动选择。"}
+                </p>
+                <select
+                  aria-label="选择执行角色"
+                  disabled={!blank()}
+                  value={activeAgent() ? paasText(activeAgent()!.id) : routed().agentID}
+                  onInput={(event) => {
+                    const value = event.currentTarget.value
+                    if (!model.route(value)) {
+                      setState("error", "已有会话不能切换智能体,请新建会话后再选择。")
+                      return
+                    }
+                    setUI("agentOverride", value)
+                    event.currentTarget.closest("details")?.removeAttribute("open")
+                  }}
+                >
+                  <For each={directAgents(props.agents)}>
+                    {(agent) => <option value={paasText(agent.id)}>{paasText(agent.name)}</option>}
+                  </For>
+                </select>
+              </div>
+            </details>
             <Show when={ui.efforts.length}>
               <label>
                 推理强度
@@ -1145,7 +1182,7 @@ export function PaasChat(props: {
               aria-label="发送消息"
               disabled={
                 !props.connected ||
-                !currentAgent() ||
+                !activeAgent() ||
                 (!current()?.draft.trim() && !current()?.reference?.text) ||
                 !!model.job() ||
                 (!!current() && materials.busy(current()!.id))

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

@@ -766,3 +766,56 @@
 .paas-agent-internal[open] > summary {
   margin-bottom: 16px;
 }
+
+/* Goal-first routing: show the selected role, keep manual override secondary. */
+.paas-agent-route {
+  position: relative;
+  min-width: 0;
+  flex-shrink: 1;
+}
+.paas-agent-route > summary {
+  display: flex;
+  align-items: center;
+  max-width: 240px;
+  padding: 6px 8px;
+  border-radius: 7px;
+  color: var(--text-weak);
+  font-size: var(--paas-type-meta);
+  line-height: 1.4;
+  cursor: pointer;
+  list-style: none;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.paas-agent-route > summary::-webkit-details-marker {
+  display: none;
+}
+.paas-agent-route > summary:hover,
+.paas-agent-route[open] > summary {
+  background: var(--background-weak);
+  color: var(--text-base);
+}
+.paas-agent-route-panel {
+  position: absolute;
+  bottom: calc(100% + 8px);
+  left: 0;
+  z-index: 20;
+  display: grid;
+  gap: 6px;
+  width: min(280px, 70vw);
+  padding: 10px;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 10px;
+  background: var(--paas-surface);
+  box-shadow: var(--paas-shadow);
+}
+.paas-agent-route-panel > p {
+  margin: 0;
+  font-size: var(--paas-type-meta);
+  line-height: 1.5;
+}
+.paas-agent-route-panel > select {
+  width: 100%;
+  min-width: 0;
+}