diff --git a/CHANGELOG.md b/CHANGELOG.md index 93a19fc243..1a0dd92cba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,23 @@ ## [Unreleased] +## [1.0.3b7] - 2026-11-17 + +### 新增 +- 托管专家可选会话模式,并能使用连接器、知识库、专家回调和已启用的插件 +- 云服务器页的地域筛选改为按大区分组的下拉面板 + +### 变更 +- 工具调用上限只拦截连续的相同调用 +- 云服务器页侧栏折叠、字号和未授权提示与对话页对齐 + +### 修复 +- Docker 部署时仍可将宿主机目录挂进 Docker 专家 +- Telegram 回复本机器人时保留引用;记忆列表不再被过期响应覆盖 +- PostgreSQL 清理孤儿 checkpoint 时只统计,不再误删其他智能体的对话 +- 带路径的 MCP OAuth 按规范发现授权信息 +- 窄屏下 Word / PDF 左侧可以滚到;新手引导遮罩铺满窗口 + ## [1.0.3b6] - 2026-11-15 ### 新增 diff --git a/README.md b/README.md index a00f12febb..b09fe64747 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@

Python 3.12+ License: MIT - Version + Version PyPI Code Style: Ruff GitHub stars diff --git a/README_CN.md b/README_CN.md index 3dc81548c3..06fedae361 100644 --- a/README_CN.md +++ b/README_CN.md @@ -15,7 +15,7 @@

Python 3.12+ License: MIT - Version + Version PyPI Code Style: Ruff GitHub stars diff --git a/dashboard/src/api/modules/acp.ts b/dashboard/src/api/modules/acp.ts index 120fbcd778..46914df02c 100644 --- a/dashboard/src/api/modules/acp.ts +++ b/dashboard/src/api/modules/acp.ts @@ -46,6 +46,53 @@ export interface AcpHostRequest { env: Record; } +export interface AcpSessionMode { + id: string; + name_zh: string; + name_en: string; + hint_zh: string; + hint_en: string; +} + +export function acpSessionModeText( + mode: AcpSessionMode, + language: string, + field: "name" | "hint", +): string { + const zh = language.toLowerCase().startsWith("zh"); + return zh ? mode[`${field}_zh`] : mode[`${field}_en`]; +} + +/** Same ids the harness treats as unattended. */ +export function isUnattendedSessionMode(modeId: string): boolean { + const folded = modeId.toLowerCase(); + return ( + folded.includes("yolo") || + folded.includes("bypass") || + folded.includes("full-access") || + folded.includes("fullaccess") || + folded.includes("auto-accept") || + folded.includes("autoaccept") || + folded.includes("unrestricted") || + folded.includes("danger") + ); +} + +export function catalogOffersUnattendedMode(modes: { id: string }[]): boolean { + return modes.some((mode) => isUnattendedSessionMode(mode.id)); +} + +/** Approval stored with a managed expert. A published unattended mode wins. */ +export function permissionForSessionMode( + modes: { id: string }[], + sessionMode: string, + yoloSwitch: boolean, +): "ask" | "yolo" { + if (isUnattendedSessionMode(sessionMode)) return "yolo"; + if (catalogOffersUnattendedMode(modes)) return "ask"; + return yoloSwitch ? "yolo" : "ask"; +} + export const acpApi = { /** Global runner definitions (shared by all agents for the current user). */ getGlobalRunners: (agentId?: string | null) => @@ -63,6 +110,11 @@ export const acpApi = { headers: optionalAgentHeaders(agentId), }), + sessionModes: (runner: string) => + request<{ runner: string; modes: AcpSessionMode[] }>( + `/acp/session-modes?runner=${encodeURIComponent(runner)}`, + ), + getRunner: (runnerName: string) => request(`/acp/${encodeURIComponent(runnerName)}`), diff --git a/dashboard/src/api/modules/managedAgents.ts b/dashboard/src/api/modules/managedAgents.ts index c37370bf99..ad332f7e2e 100644 --- a/dashboard/src/api/modules/managedAgents.ts +++ b/dashboard/src/api/modules/managedAgents.ts @@ -42,6 +42,10 @@ export interface ManagedAgentCreate { group_ids?: string[]; quick_prompts?: ManagedQuickPrompt[]; file_overrides?: ManagedWorkspaceFile[]; + skill_package_ids?: string[]; + knowledge_base_ids?: string[]; + mcp_servers?: string[]; + permission_mode?: "ask" | "yolo"; } export const managedAgentsApi = { diff --git a/dashboard/src/api/modules/octopThreads.ts b/dashboard/src/api/modules/octopThreads.ts index 7f5d39ff0b..e942170073 100644 --- a/dashboard/src/api/modules/octopThreads.ts +++ b/dashboard/src/api/modules/octopThreads.ts @@ -57,6 +57,7 @@ export interface OctopThread { reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; conversation_mode?: "ask" | "plan" | "craft" | null; + session_mode?: string | null; pending_plan_path?: string | null; hitl_policy?: HitlSessionPolicy | null; /** Legacy path list (compat). Prefer ``artifact_refs`` when present. */ @@ -92,6 +93,7 @@ export interface OctopThreadHistory { reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; conversation_mode?: "ask" | "plan" | "craft" | null; + session_mode?: string | null; pending_plan_path?: string | null; hitl_policy?: HitlSessionPolicy | null; has_more?: boolean; @@ -126,6 +128,7 @@ export interface OctopThreadPatch { reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; conversation_mode?: "ask" | "plan" | "craft" | null; + session_mode?: string | null; hitl_policy?: HitlSessionPolicy | null; } @@ -251,6 +254,7 @@ export const octopThreadsApi = { reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; conversation_mode?: "ask" | "plan" | "craft" | null; + session_mode?: string | null; pending_plan_path?: string | null; hitl_policy?: HitlSessionPolicy | null; }>( diff --git a/dashboard/src/api/modules/teams.ts b/dashboard/src/api/modules/teams.ts index 99533a7398..9158adef65 100644 --- a/dashboard/src/api/modules/teams.ts +++ b/dashboard/src/api/modules/teams.ts @@ -9,6 +9,8 @@ export interface TeamMemberSummary { state?: string; is_shared?: boolean; user_id?: number | null; + kind?: string | null; + managed_runner?: string | null; } export interface TeamRecord { diff --git a/dashboard/src/components/AgentProfileDrawer.tsx b/dashboard/src/components/AgentProfileDrawer.tsx index 6146382c4c..9671b1c64e 100644 --- a/dashboard/src/components/AgentProfileDrawer.tsx +++ b/dashboard/src/components/AgentProfileDrawer.tsx @@ -13,6 +13,7 @@ import { request } from "../api/request"; import { withFromWorkspace } from "../utils/fromWorkspace"; import type { OctopAgent } from "../context/AgentContext"; import { useAgent } from "../context/AgentContext"; +import { useCurrentUser } from "../hooks/useCurrentUser"; import { isAgentChatReady } from "../utils/agentError"; import { isTeamAgent } from "../utils/teamAgent"; import { @@ -26,6 +27,8 @@ import { ExpertIcon, metaForFile, } from "../pages/Experts/components/iconForName"; +import { ManagedAvatarMark } from "../pages/Experts/components/ManagedAvatarMark"; +import { incomingShareProps, SharedAvatarMark } from "./SharedResourceBadge"; import { fetchConfigMdFiles } from "../pages/Experts/components/expertFileGroups"; import { useSkillDisplayName } from "../pages/Agent/Skills/skillDisplayNames"; import { DEFAULT_SKILL_EMOJI } from "../pages/Agent/Skills/skillMarkdown"; @@ -114,6 +117,7 @@ export default function AgentProfileDrawer({ }: AgentProfileDrawerProps) { const { t } = useTranslation(); const { agents } = useAgent(); + const viewerId = useCurrentUser()?.id; const skillDisplayName = useSkillDisplayName(); const [loading, setLoading] = useState(false); const [filesLoading, setFilesLoading] = useState(false); @@ -145,6 +149,12 @@ export default function AgentProfileDrawer({ icon_name: found.icon_name ?? member.icon_name, icon_url: found.icon_url ?? member.icon_url, state: found.state || member.state, + kind: found.kind || member.kind, + managed_runner: + (found.kind === "managed" && + typeof found.config?.managed_runner === "string" + ? found.config.managed_runner + : null) || member.managed_runner, }; }), [teamMembers, agents], @@ -409,23 +419,39 @@ export default function AgentProfileDrawer({ visibleTeamMembers.map((member) => { const accent = member.color || "#0d9488"; const stateKey = member.state || "unknown"; + const memberAgent = agents.find( + (item) => item.agent_id === member.agent_id, + ); + const shareSource = + memberAgent ?? + (member.user_id != null && viewerId != null + ? { + is_shared: member.is_shared, + is_owner: Number(member.user_id) === Number(viewerId), + user_id: member.user_id, + } + : null); return ( - - + + +

+ +
+ + } title={member.name} trailing={ diff --git a/dashboard/src/components/AgentSelector.test.tsx b/dashboard/src/components/AgentSelector.test.tsx index 6e43d87cdc..c945a16b22 100644 --- a/dashboard/src/components/AgentSelector.test.tsx +++ b/dashboard/src/components/AgentSelector.test.tsx @@ -122,6 +122,24 @@ describe("AgentSelector groups", () => { expect(screen.queryByRole("combobox")).not.toBeInTheDocument(); }); + it("hides managed experts when the page does not use them", () => { + const hosted = fakeAgent({ + agent_id: "hosted", + name: "托管写手", + kind: "managed", + }); + state.agents = [writer, hosted]; + state.activeAgentId = "hosted"; + render(); + const chips = within(screen.getByTestId("agent-selector-chips")); + expect(chips.getByText("写手")).toBeInTheDocument(); + expect(chips.queryByText("托管写手")).not.toBeInTheDocument(); + expect( + screen.getByText("当前是托管专家「托管写手」,此页请选择其他专家"), + ).toBeInTheDocument(); + expect(setActiveAgent).not.toHaveBeenCalled(); + }); + it("keeps a hidden team selection and asks the user to pick an expert", () => { state.activeAgentId = "crew"; render(); diff --git a/dashboard/src/components/AgentSelector.tsx b/dashboard/src/components/AgentSelector.tsx index e6412415ce..e87d1e4122 100644 --- a/dashboard/src/components/AgentSelector.tsx +++ b/dashboard/src/components/AgentSelector.tsx @@ -16,6 +16,11 @@ import { } from "../utils/agentSelector"; import { isTeamAgent } from "../utils/teamAgent"; import { ExpertIcon } from "../pages/Experts/components/iconForName"; +import { + ManagedAvatarMark, + managedRunnerId, +} from "../pages/Experts/components/ManagedAvatarMark"; +import { incomingShareProps, SharedAvatarMark } from "./SharedResourceBadge"; import RemoteExpertHint from "../pages/Chat/components/RemoteExpertHint"; import styles from "./AgentSelector.module.less"; @@ -30,6 +35,8 @@ interface AgentSelectorProps { * expert-only. */ showTeams?: boolean; + /** Tools / plugins / MBTI pages do not list managed experts. */ + hideManaged?: boolean; /** * 受控模式:只改这个面板自己的专家,不写入全局当前 Agent。 * 传入 onChange 即生效。 @@ -57,13 +64,17 @@ function AgentIcon({ }) { const photo = Boolean(agent.icon_url?.trim()); return ( - - - + + + + + + + ); } @@ -168,6 +179,7 @@ export default function AgentSelector({ variant = "auto", showLabel = true, showTeams = false, + hideManaged = false, value, onChange, }: AgentSelectorProps) { @@ -179,7 +191,13 @@ export default function AgentSelector({ if (onChange) onChange(id); else setActiveAgent(id); }; - const soloSelectable = useMemo(() => ownedSoloExperts(agents), [agents]); + const soloSelectable = useMemo( + () => + ownedSoloExperts(agents).filter( + (agent) => !hideManaged || agent.kind !== "managed", + ), + [agents, hideManaged], + ); const allTeams = useMemo(() => ownedTeamAgents(agents), [agents]); const teamSelectable = useMemo( () => (showTeams ? allTeams : []), @@ -222,6 +240,9 @@ export default function AgentSelector({ const activeIsHiddenTeam = Boolean( activeAgent && isTeamAgent(activeAgent) && !showTeams, ); + const activeIsHiddenManaged = Boolean( + hideManaged && activeAgent?.kind === "managed", + ); const useBar = variant !== "select"; const currentId = chosenId ?? (controlled ? undefined : selectable[0]?.agent_id); @@ -274,7 +295,13 @@ export default function AgentSelector({ ); } - if (selectable.length === 0 && allTeams.length === 0) return null; + if ( + selectable.length === 0 && + allTeams.length === 0 && + !activeIsHiddenManaged + ) { + return null; + } const disconnectedLabel = t("agentSelector.disconnected"); const selectOptions: DefaultOptionType[] = showGroupLabels @@ -292,6 +319,11 @@ export default function AgentSelector({ name: activeAgent?.name ?? "", defaultValue: "当前是团队「{{name}}」,此页请选择专家", }) + : activeIsHiddenManaged + ? t("agentSelector.managedNeedsExpert", { + name: activeAgent?.name ?? "", + defaultValue: "当前是托管专家「{{name}}」,此页请选择其他专家", + }) : soloSelectable.length === 0 && allTeams.length > 0 ? t("agentSelector.expertsRequired", "此页需要专家") : null; diff --git a/dashboard/src/components/DocumentPreviewCore.module.less b/dashboard/src/components/DocumentPreviewCore.module.less index 973f85e3b4..0385c3a655 100644 --- a/dashboard/src/components/DocumentPreviewCore.module.less +++ b/dashboard/src/components/DocumentPreviewCore.module.less @@ -55,6 +55,22 @@ overscroll-behavior: contain; } +/* + * docx-preview centres pages with `align-items: center` on its flex wrapper. + * A page wider than the preview (phones, the chat side panel) then overflows + * to both sides, and the left overflow can never be scrolled into view. + * Start-align and centre with auto margins instead: they centre while the page + * fits and fall back to 0 once it overflows, so the extra width scrolls right. + */ +.docxWrap :global(.docx-doc-wrapper) { + align-items: flex-start; +} + +.docxWrap :global(.docx-doc-wrapper > section.docx-doc) { + margin-left: auto; + margin-right: auto; +} + .pptxWrap { flex: 1; min-height: 0; diff --git a/dashboard/src/components/DocumentPreviewCore.narrowLayout.test.ts b/dashboard/src/components/DocumentPreviewCore.narrowLayout.test.ts new file mode 100644 index 0000000000..d96542f435 --- /dev/null +++ b/dashboard/src/components/DocumentPreviewCore.narrowLayout.test.ts @@ -0,0 +1,105 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { renderAsync } from "docx-preview"; +import JSZip from "jszip"; +import { describe, expect, it, vi } from "vitest"; + +import { DOCX_RENDER_OPTIONS } from "./DocumentPreviewCore"; + +// pdf.js needs DOMMatrix, which jsdom lacks; the Word path never touches it. +vi.mock("react-pdf", () => ({ + Document: () => null, + Page: () => null, + pdfjs: { GlobalWorkerOptions: { workerSrc: "" } }, +})); + +const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; + +/** Smallest Word file docx-preview accepts: one paragraph on an A4 page. */ +async function a4Docx(): Promise { + const zip = new JSZip(); + zip.file( + "[Content_Types].xml", + '' + + '' + + '' + + '' + + "", + ); + zip.file( + "_rels/.rels", + '' + + '' + + "", + ); + zip.file( + "word/document.xml", + `` + + "Left edge" + + '' + + "", + ); + return zip.generateAsync({ type: "arraybuffer" }); +} + +/** Body of the first rule whose selector is exactly ``selector``. */ +function ruleBody(css: string, selector: string): string { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const match = css.match(new RegExp(`(?:^|\\n)${escaped}\\s*\\{([^}]*)\\}`)); + if (!match) throw new Error(`missing rule: ${selector}`); + return match[1]; +} + +// A page wider than the preview must overflow to the right (scrollable), not +// to both sides: centring the flex item puts its left part out of reach +// (#1262). Auto margins keep pages centred whenever they fit. +describe("document previews on narrow screens", () => { + it("keeps the left edge of Word pages reachable", () => { + const css = readFileSync( + resolve(__dirname, "DocumentPreviewCore.module.less"), + "utf8", + ); + expect(ruleBody(css, ".docxWrap :global(.docx-doc-wrapper)")).toMatch( + /align-items:\s*flex-start/, + ); + const page = ruleBody( + css, + ".docxWrap :global(.docx-doc-wrapper > section.docx-doc)", + ); + expect(page).toMatch(/margin-left:\s*auto/); + expect(page).toMatch(/margin-right:\s*auto/); + }); + + it("targets the wrapper and pages docx-preview actually renders", async () => { + const host = document.createElement("div"); + await renderAsync(await a4Docx(), host, undefined, DOCX_RENDER_OPTIONS); + + // Pages keep their real paper width (A4 = 595.3pt ≈ 794px), wider than a phone. + const page = host.querySelector( + ".docx-doc-wrapper > section.docx-doc", + ); + expect(page).not.toBeNull(); + expect(page!.style.width).toBe("595.3pt"); + + // docx-preview's own stylesheet is what centres (and so clips) the page. + const injected = Array.from(host.querySelectorAll("style")) + .map((style) => style.textContent ?? "") + .join("\n"); + expect(injected).toMatch( + /\.docx-doc-wrapper\s*\{[^}]*align-items:\s*center/, + ); + }); + + it("keeps the left edge of zoomed-in PDF pages reachable", () => { + const css = readFileSync( + resolve(__dirname, "PdfDocumentPreview.module.less"), + "utf8", + ); + const doc = ruleBody(css, ".pdfDocument"); + expect(doc).toMatch(/align-items:\s*flex-start/); + expect(doc).not.toMatch(/align-items:\s*center/); + const slot = ruleBody(css, ".pdfPageSlot"); + expect(slot).toMatch(/margin-left:\s*auto/); + expect(slot).toMatch(/margin-right:\s*auto/); + }); +}); diff --git a/dashboard/src/components/DocumentPreviewCore.tsx b/dashboard/src/components/DocumentPreviewCore.tsx index 30359ef903..8d144ce754 100644 --- a/dashboard/src/components/DocumentPreviewCore.tsx +++ b/dashboard/src/components/DocumentPreviewCore.tsx @@ -138,6 +138,16 @@ async function extractXlsxMediaDataUrls( return items; } +/** docx-preview options; the narrow-layout CSS targets the DOM they produce. */ +export const DOCX_RENDER_OPTIONS = { + className: "docx-doc", + inWrapper: true, + breakPages: true, + ignoreWidth: false, + ignoreHeight: false, + useBase64URL: true, +}; + /** Absolute lengths beyond this (≈ 27″) are treated as corrupt DOCX metrics. */ const DOCX_MAX_LENGTH_PT = 2000; @@ -441,14 +451,12 @@ export default function DocumentPreviewCore({ } const { renderAsync } = await import("docx-preview"); if (containerRef.current && !cancelled) { - await renderAsync(buf, containerRef.current, undefined, { - className: "docx-doc", - inWrapper: true, - breakPages: true, - ignoreWidth: false, - ignoreHeight: false, - useBase64URL: true, - }); + await renderAsync( + buf, + containerRef.current, + undefined, + DOCX_RENDER_OPTIONS, + ); if (!cancelled && containerRef.current) { neutralizeDocxPreviewChrome(containerRef.current); sanitizeDocxPreviewLayout(containerRef.current); diff --git a/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less b/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less index f807dfa5df..a231468ec7 100644 --- a/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less +++ b/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less @@ -52,8 +52,9 @@ box-shadow: 0 0 0 0 color-mix(in srgb, var(--fn-color-brand) 45%, transparent); } + // Stays inside the tour's 6px spotlight gap, so the mask never clips it. 70% { - box-shadow: 0 0 0 10px + box-shadow: 0 0 0 5px color-mix(in srgb, var(--fn-color-brand) 0%, transparent); } 100% { @@ -112,6 +113,7 @@ font-size: 14px; line-height: 22px; color: var(--fn-text-secondary); + text-wrap: pretty; animation: fadeUp 0.45s @ease-out 0.14s both; } @@ -227,9 +229,12 @@ /* ---------- tour card ---------- */ -.tour { +/* rootClassName also lands on the mask, so size only the card. */ +.tour:global(.octop-tour) { width: min(360px, calc(100vw - 32px)); +} +.tour { :global(.octop-tour-content) { width: 100%; } @@ -340,6 +345,8 @@ > :first-child { margin-right: auto; + // Line the "Skip" text up with the card content, not its button padding. + margin-left: -7px; } } diff --git a/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx b/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx index 0e72d97958..d3cb7fbf69 100644 --- a/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx +++ b/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx @@ -6,7 +6,7 @@ import { type CSSProperties, type ComponentType, } from "react"; -import { Button, Modal, Tour, type TourStepProps } from "antd"; +import { Button, Modal, Tour, theme, type TourStepProps } from "antd"; import { ArrowLeft, ArrowRight, @@ -59,6 +59,20 @@ function navTarget(step: OnboardingStep): HTMLElement | null { return document.querySelector(`[data-nav-key="${step.navKey}"]`); } +/** + * Side placement for a step's card. antd shifts an overflowing card back + * into view flush with the window edge, so align it to the top or bottom of + * targets near those edges instead. + */ +function sidePlacement(step: OnboardingStep): TourStepProps["placement"] { + const rect = navTarget(step)?.getBoundingClientRect(); + if (!rect) return "right"; + const middle = rect.top + rect.height / 2; + if (middle < window.innerHeight / 3) return "rightTop"; + if (middle > (window.innerHeight * 2) / 3) return "rightBottom"; + return "right"; +} + /** * Welcome guide: an intro card, a spotlight tour that opens each page and * highlights its sidebar entry, then a short wrap-up. @@ -73,10 +87,13 @@ export default function OnboardingGuide({ const { t } = useTranslation(); const navigate = useNavigate(); const isMobile = useIsMobile(); + const { token } = theme.useToken(); const user = useCurrentUser(); const steps = useMemo(() => buildOnboardingSteps(user), [user]); const [phase, setPhase] = useState("intro"); const [current, setCurrent] = useState(0); + // True once the wrap-up modal has finished opening. + const [doneSettled, setDoneSettled] = useState(false); useEffect(() => { if (!open) return; @@ -137,7 +154,7 @@ export default function OnboardingGuide({ return { // Mobile keeps the nav in a closed drawer, so the card stays centered. target: isMobile ? null : () => navTarget(s) as HTMLElement, - placement: isMobile ? "center" : "right", + placement: isMobile ? "center" : sidePlacement(s), title: (
@@ -176,6 +193,9 @@ export default function OnboardingGuide({ width={isMobile ? "calc(100vw - 32px)" : 560} centered destroyOnHidden + // The tour mask appears at once; fading this one out over it would + // briefly double the dim. + maskTransitionName={phase === "tour" ? "" : undefined} className={styles.modal} >
@@ -230,6 +250,9 @@ export default function OnboardingGuide({ steps={tourSteps} rootClassName={styles.tour} disabledInteraction + // Same dim as the intro and wrap-up modals, so switching between them + // does not flicker (Tour's own mask is a fixed 50% black). + mask={{ color: token.colorBgMask }} gap={{ offset: 6, radius: 10 }} indicatorsRender={(cur, total) => (
@@ -279,6 +302,10 @@ export default function OnboardingGuide({ width={isMobile ? "calc(100vw - 32px)" : 440} centered destroyOnHidden + // The tour mask goes at once; fading this one in would flash the + // page. Closing still fades. + maskTransitionName={doneSettled ? undefined : ""} + afterOpenChange={setDoneSettled} className={styles.modal} >
diff --git a/dashboard/src/components/PdfDocumentPreview.module.less b/dashboard/src/components/PdfDocumentPreview.module.less index f47c136a01..30b5ce8255 100644 --- a/dashboard/src/components/PdfDocumentPreview.module.less +++ b/dashboard/src/components/PdfDocumentPreview.module.less @@ -193,16 +193,22 @@ overscroll-behavior: contain; } +/* + * Start-align and centre each page with auto margins: `align-items: center` + * would push a zoomed-in page past the left edge, where it can't be scrolled. + */ .pdfDocument { display: flex; flex-direction: column; - align-items: center; + align-items: flex-start; gap: 12px; } .pdfPageSlot { position: relative; flex: 0 0 auto; + margin-left: auto; + margin-right: auto; overflow: hidden; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08); background: #fff; diff --git a/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less b/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less index 7ecba4b5f0..9dcfac40df 100644 --- a/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less +++ b/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less @@ -41,6 +41,12 @@ line-height: 0; } +/* Sit above a managed-runner mark so both stay visible on the right edge. */ +.avatarHost:has([data-managed-avatar-mark]) > .avatarMark { + bottom: max(38%, 11px); + z-index: 2; +} + .avatarMark { position: absolute; right: -8%; diff --git a/dashboard/src/components/SharedResourceBadge/index.tsx b/dashboard/src/components/SharedResourceBadge/index.tsx index 3414d64aed..544f23c906 100644 --- a/dashboard/src/components/SharedResourceBadge/index.tsx +++ b/dashboard/src/components/SharedResourceBadge/index.tsx @@ -3,6 +3,10 @@ import { Share2 } from "lucide-react"; import { Tooltip } from "antd"; import { useTranslation } from "react-i18next"; import cx from "classnames"; +import { + isSharedExpertViewer, + type SharedExpertAccess, +} from "../../utils/sharedExpert"; import styles from "./SharedResourceBadge.module.less"; type Props = { @@ -45,6 +49,18 @@ export function SharedResourceBadge({ ); } +/** Props for the incoming-share pip. Owners who shared outward get no avatar mark. */ +export function incomingShareProps( + agent?: (SharedExpertAccess & { owner_username?: string | null }) | null, +): { shared: boolean; owned: boolean; ownerName?: string | null } { + const incoming = Boolean(agent && isSharedExpertViewer(agent)); + return { + shared: incoming, + owned: !incoming, + ownerName: agent?.owner_username, + }; +} + /** Avatar with a pip when the resource was shared to the current user. */ export function SharedAvatarMark({ shared, diff --git a/dashboard/src/hooks/useAcpSessionModes.ts b/dashboard/src/hooks/useAcpSessionModes.ts new file mode 100644 index 0000000000..f62c982faa --- /dev/null +++ b/dashboard/src/hooks/useAcpSessionModes.ts @@ -0,0 +1,31 @@ +import { useEffect, useState } from "react"; +import { acpApi, type AcpSessionMode } from "../api/modules/acp"; + +/** Modes the selected underlying agent documents. Empty when it has no catalog. */ +export function useAcpSessionModes( + runner: string | null | undefined, +): AcpSessionMode[] { + const [modes, setModes] = useState([]); + + useEffect(() => { + const name = (runner ?? "").trim(); + if (!name) { + setModes([]); + return; + } + let cancelled = false; + acpApi + .sessionModes(name) + .then((data) => { + if (!cancelled) setModes(data.modes ?? []); + }) + .catch(() => { + if (!cancelled) setModes([]); + }); + return () => { + cancelled = true; + }; + }, [runner]); + + return modes; +} diff --git a/dashboard/src/hooks/useDashboardPushToast.tsx b/dashboard/src/hooks/useDashboardPushToast.tsx index eca8e5b0ce..7008a115c6 100644 --- a/dashboard/src/hooks/useDashboardPushToast.tsx +++ b/dashboard/src/hooks/useDashboardPushToast.tsx @@ -5,8 +5,16 @@ import { useTranslation } from "react-i18next"; import { useNavigate } from "react-router-dom"; import { buildDashboardNotifyWsUrl } from "../api/modules/wsNotifications"; import { getAuthToken } from "../api/request"; -import { useAgent } from "../context/AgentContext"; +import { useAgent, type OctopAgent } from "../context/AgentContext"; import { ExpertIcon } from "../pages/Experts/components/iconForName"; +import { + ManagedAvatarMark, + managedRunnerId, +} from "../pages/Experts/components/ManagedAvatarMark"; +import { + incomingShareProps, + SharedAvatarMark, +} from "../components/SharedResourceBadge"; import { emitSessionEvent, invalidateHistory, @@ -61,20 +69,24 @@ function systemNotifyOptions( }; } -function PushToastIcon({ - iconUrl, - iconName, -}: { - iconUrl?: string | null; - iconName?: string | null; -}) { +function PushToastIcon({ agent }: { agent?: OctopAgent }) { + const icon = + agent?.icon_url || agent?.icon_name ? ( + + ) : ( + + ); return ( - {iconUrl || iconName ? ( - - ) : ( - - )} + + + {icon} + + ); } @@ -149,10 +161,7 @@ export function useDashboardPushToast(): void { }, message: ( - + {pushTitle(parsed)} ), diff --git a/dashboard/src/layouts/PageShell.tsx b/dashboard/src/layouts/PageShell.tsx index e06a5381f7..95d0313d1a 100644 --- a/dashboard/src/layouts/PageShell.tsx +++ b/dashboard/src/layouts/PageShell.tsx @@ -39,6 +39,8 @@ interface PageShellProps { agentScoped?: boolean; /** Include team hosts in the agent picker (memory / channels). */ showTeams?: boolean; + /** Omit managed experts from the agent picker (tools / plugins / MBTI). */ + hideManaged?: boolean; /** When true, the content area does not scroll; children fill remaining height. */ fill?: boolean; children: React.ReactNode; @@ -96,6 +98,7 @@ function PageShell({ pathTabs, agentScoped, showTeams, + hideManaged, fill, children, }: PageShellProps) { @@ -179,7 +182,7 @@ function PageShell({ {agentScoped && (
- +
)} diff --git a/dashboard/src/locales/en.json b/dashboard/src/locales/en.json index e4ecedf234..7346f3dbc1 100644 --- a/dashboard/src/locales/en.json +++ b/dashboard/src/locales/en.json @@ -199,7 +199,7 @@ "SKILL_PACKAGE_NOT_FOUND": "Skill package not found.", "SKILL_PACKAGE_NAME_TAKEN": "Skill package {{name}} already exists.", "SKILL_PACKAGE_BACKEND_UNSUPPORTED": "Skill packages currently support only “Full local environment (filesystem + shell)” or “Local filesystem (no shell commands)”, with storage root / (POSIX) or the agent workspace root (Windows default).", - "ACP_BACKEND_UNSUPPORTED": "This agent has a sandbox enabled, so external runners can’t be enabled or edited here. The outbound acp_runner tool toggle is unaffected; connecting via IDE / octop acp is also unaffected.", + "ACP_BACKEND_UNSUPPORTED": "This agent has a sandbox enabled, so external agents can’t be enabled or edited here. External agent collaboration for this expert is unaffected; connecting via IDE / octop acp is also unaffected.", "PUBLISHED_EXPERT_SLUG_TAKEN": "Published expert slug {{slug}} already exists.", "PUBLISHED_EXPERT_ALREADY_EXISTS": "This agent is already published as “{{name}}”. Refresh the published template instead.", "OIDC_BAD_REQUEST": "Invalid OIDC request: {{detail}}", @@ -283,7 +283,7 @@ "tasks": "Automation", "connectors": "Connectors", "bridge": "Cloud collab", - "acp": "ACP Collaboration", + "acp": "Agent collaboration", "agents": "Agents", "providers": "Providers", "models": "Model Configuration", @@ -1171,6 +1171,7 @@ "defaultModeHint": "Ask / Plan / Craft mode for new conversations; Craft is the full-execution mode. Existing conversations are unaffected.", "skillPackagesLabel": "Optional Skill Packages", "skillPackagesHint": "Mount packages at create time (local storage with root /).", + "managedSkillPackagesHint": "Selected packages are linked into this agent's skill directory. If two packages share a skill name, the first one is kept.", "skillPackagesUnsupportedHint": "This sandbox cannot mount skill-package directories directly. You can still use Copy skills to create independent workspace copies.", "skillPackagesClearFailed": "Backend settings saved, but clearing mounted skill packages failed", "skillPackagesPlaceholder": "Select skill packages", @@ -1239,8 +1240,8 @@ "backendRootDirPlaceholder": "Browse and select a directory", "backendRootDirDesc": "Defaults to the filesystem root (`/` on POSIX, the home drive on Windows). You may also browse and pick another directory.", "backendRootDirDescContainer": "Running in a container: defaults to the filesystem root `/` (the container is already the isolation boundary). You may still browse and pick another directory.", - "backendRootDirJailHint": "Saving to a non-root directory enables a sandbox and confines the AI filesystem to that folder. External ACP runners can’t be used with this setup; connecting via IDE / octop acp is unaffected.", - "backendRootDirPathLimitHint": "Saving to a non-root directory limits the AI’s file access to that folder, but this host provides no OS-level sandbox — the AI process still runs with the service account’s own permissions. External ACP runners can’t be used with this setup; connecting via IDE / octop acp is unaffected.", + "backendRootDirJailHint": "Saving to a non-root directory enables a sandbox and confines the AI filesystem to that folder. External agents can’t be used with this setup; connecting via IDE / octop acp is unaffected.", + "backendRootDirPathLimitHint": "Saving to a non-root directory limits the AI’s file access to that folder, but this host provides no OS-level sandbox — the AI process still runs with the service account’s own permissions. External agents can’t be used with this setup; connecting via IDE / octop acp is unaffected.", "backendRootDirImmutableHint": "Cannot be changed after creation.", "workspaceDir": "Workspace directory", "workspaceDirDesc": "Filled with this expert's server default directory. You can choose another one.", @@ -1269,7 +1270,7 @@ "backendAllowedEmpty": "Allowed: {{types}}. No storage connection of those types exists yet. Create one under Storage backends first.", "backendPathMappings": "Path Mappings (optional)", "addPathMapping": "Add path mapping", - "advancedOptions": "Advanced options", + "advancedOptions": "Runtime parameters", "temperature": "Temperature", "temperatureTooltip": "Sampling temperature — higher values produce more varied output", "topP": "Top P", @@ -1344,20 +1345,24 @@ "managed": { "create": "Create", "createTitle": "New managed expert", + "editTitle": "Edit managed expert", "badge": "Managed", "name": "Name", "nameRequired": "Enter a name", "runner": "Managed agent", - "manageAcp": "Manage ACP", + "manageAcp": "Manage agent collaboration", "runnerRequired": "Choose a managed agent", - "noRunners": "Enable a runner on the ACP page first.", + "noRunners": "Enable an agent on the Agent collaboration page first.", "runnerSearch": "Search managed agents", "runnerSearchEmpty": "No matching managed agents", "workspaceRequired": "Choose a working directory", "description": "Description", - "loadFailed": "Could not load ACP runners", + "loadFailed": "Could not load external agents", "templateFailed": "Could not load the default prompts. Built-in files are still copied on create.", - "createFailed": "Could not create the managed expert" + "createFailed": "Could not create the managed expert", + "yolo": "YOLO", + "yoloHint": "New chats skip approval. The underlying agent runs actions directly, including file edits and commands. A chat can still switch back to asking every time.", + "sessionModeHint": "Modes come from the managed agent. New chats start here, and a chat can still switch." } }, "subagents": { @@ -1450,6 +1455,7 @@ "insufficient_balance": "The model provider rejected this request due to insufficient balance or quota. Top up or upgrade the plan for this API key, then try again.", "context_length": "This conversation is too long for the model's context window. Start a new chat, or shorten the history and try again.", "recursion_limit": "The agent hit its max iteration / recursion limit before finishing. Open Configuration and raise Max Iterations, then try again.", + "tool_call_repeat": "\"{{tool}}\" was called {{count}} times in a row with the same arguments and reached the limit of {{limit}}, so this turn stopped. Try a different approach, or open Configuration, raise Repeated calls in a row, and reload the expert.", "timeout_network": "Connecting to the model timed out or the network failed. Check your network and retry. If you use a proxy or self-hosted endpoint, confirm it is reachable.", "provider_unavailable": "The model provider is temporarily unavailable. Retry later, or switch to another model.", "invalid_request": "This endpoint may reject the live-token field. Turn off “Show live token count in chat” and retry. If it still fails, check whether the model supports tool calling.", @@ -1468,7 +1474,7 @@ "manageToast": "This is a peer expert. Manage skills, models, knowledge bases, and related settings on the peer Octop.", "editBanner": "You are editing a peer expert. Changes are saved on the peer Octop.", "editSkillPackages": "Skill packages stay on this instance and cannot be installed onto a peer expert. That tab is hidden.", - "editTools": "ACP runners execute on the peer. Plugin icons that are local files on the peer may not preview here.", + "editTools": "External agents run on the peer. Plugin icons that are local files on the peer may not preview here.", "editPlugins": "You can toggle plugins already installed on the peer. Install, uninstall, and marketplace stay on the peer Octop.", "editChannels": "QR login and bot-creator flows run on the peer machine, not this browser.", "editTasks": "Tasks use the peer timezone. Model and connector options come from the peer; install new connectors there.", @@ -1480,7 +1486,7 @@ "reconnect": "Reconnect", "openBridge": "View connection", "peerOnlyTitle": "This page stays on this instance", - "peerOnlyAcp": "ACP runners listed here belong to this Octop. Pick a local expert to toggle its ACP tool, or open the peer expert’s Tools tab to manage the peer.", + "peerOnlyAcp": "External agents listed here belong to this Octop. Open the peer expert’s Tools tab to toggle external agent collaboration.", "peerOnlyBrowser": "This page controls the browser on this host. For a peer expert, open the browser dock in chat instead." }, "pushToast": { @@ -1613,6 +1619,13 @@ "executeUtterance": "Execute {{path}}", "keepEditing": "Keep editing" }, + "managedApproval": { + "picker": "Approval mode", + "ask": "Ask every time", + "askHint": "Confirm each action from the underlying agent before it runs.", + "yolo": "YOLO", + "yoloHint": "Skip approval. The underlying agent runs actions directly, including file edits and commands." + }, "errorOccurred": "An error occurred", "imageLoadFailed": "Image failed to load", "mediaLoadFailed": "Unable to load media", @@ -2067,7 +2080,7 @@ "ask_agent": "Ask expert", "call_agent": "Call expert", "call_deferred_tool": "Call on demand", - "acp_runner": "ACP external agent", + "acp_runner": "External agent collaboration", "external-agent": "Managed agent", "browser_use": "Use browser", "browser_control": "Browser control", @@ -2089,6 +2102,7 @@ "toolSettings": { "title": "Tool settings", "hint": "Turn off built-in tools you do not want the model to call. Required system tools cannot be disabled.", + "hintManaged": "Only tools Octop can attach are listed. Files, shell, and web tools belong to the external agent. A switch stays off until memory is enabled, a knowledge base is selected, or another expert can be called.", "hintPlugin": "Turn off plugin tools you do not want the model to call. Unloaded plugins must be enabled under Plugins first.", "empty": "No tools available", "emptyPlugin": "No plugin tools yet. Enable plugins for this agent on the Plugins tab first.", @@ -2104,7 +2118,7 @@ "pluginToolCount": "{{count}} tools", "tabs": { "builtin": "Built-in tools", - "acp": "ACP Collaboration tools", + "acp": "Agent collaboration", "plugin": "Plugin tools" }, "categories": { @@ -4236,10 +4250,10 @@ "noActiveAgent": "Select an agent first", "retryDelayBelowInitial": "Maximum delay must be at least the initial delay", "toolCallLimit": { - "enabled": "Limit tool calls per turn", - "enabledTooltip": "Cap how many times tools can be called in one user turn. The turn ends when the cap is reached. Turn this off for no cap. Saving reloads this expert.", - "runLimit": "Tool calls per turn", - "runLimitTooltip": "Maximum tool calls in one user turn. Empty uses 40.", + "enabled": "Limit repeated tool calls", + "enabledTooltip": "Count a streak of the same tool called with the same arguments. A different tool or different arguments starts the count over. The turn ends when the streak reaches the limit. Turn this off for no cap. Saving reloads this expert.", + "runLimit": "Repeated calls in a row", + "runLimitTooltip": "How many times the same tool may be called in a row with the same arguments. Other tools and other arguments are not counted. Empty uses 40.", "runLimitPlaceholder": "40" }, "modelRetry": { @@ -4413,6 +4427,7 @@ }, "upload": { "tooltip": "Upload files or a folder. You can also drop them on the input.", + "action": "Upload", "files": "Files", "folder": "Folder", "dropHint": "Drop files or a folder to upload", @@ -6244,6 +6259,7 @@ "remoteKindGroup": "{{name}}·{{kind}}", "more": "More", "teamNeedsExpert": "\"{{name}}\" is a team. Choose an expert for this page.", + "managedNeedsExpert": "\"{{name}}\" is a managed expert. Choose another expert for this page.", "expertsRequired": "This page needs an expert" }, "login": { @@ -7304,11 +7320,11 @@ "pickAgent": "Select an Agent first" }, "acp": { - "description": "Connect external ACP-compatible coding agents. Runner settings are shared across all your agents; enable the acp_runner tool per agent below.", - "globalRunnersHint": "Runner configuration below applies to all agents for your account.", - "toolEnabledHint": "The acp_runner tool is enabled per agent — switch the agent above to configure the current one.", - "toolEnabled": "Enable outbound delegation (acp_runner)", - "outboundBlockedHint": "This agent has a sandbox enabled, so external runners can’t be enabled or edited here. The outbound acp_runner tool toggle is unaffected; connecting via IDE / octop acp is also unaffected.", + "description": "Connect external ACP-compatible coding agents. Agent settings are shared across all your experts; enable external agent collaboration for the current expert below.", + "globalRunnersHint": "The agent configuration below applies to every expert on this account.", + "toolEnabledHint": "The external agent collaboration tool is enabled per expert. Switch the expert above to configure the current one.", + "toolEnabled": "Enable external agent collaboration for this expert", + "outboundBlockedHint": "This expert has a sandbox enabled, so external agents can’t be enabled or edited here. External agent collaboration for this expert is unaffected; connecting via IDE / octop acp is also unaffected.", "outboundBlockedTooltip": "Unavailable to enable or edit in sandbox", "runnerUnavailable": "Unavailable", "builtin": "Built-in", @@ -7327,16 +7343,16 @@ "intro_kimi_code": "Moonshot Kimi Code CLI — run kimi acp after kimi login.", "intro_cursor_cli": "Cursor CLI agent — run agent acp after agent login or set CURSOR_API_KEY.", "intro_pi": "Pi coding agent via pi-acp bridge (npx -y pi-acp).", - "intro_custom": "Custom runner: {{command}}", + "intro_custom": "Custom agent: {{command}}", "runnerNeedsConfig": "Enabled — configure command", "clickCardToConfigure": "Click the card to set the launch command first", - "create": "Add runner", - "createTitle": "Add ACP runner", - "editTitle": "Edit runner", - "runnerKey": "Runner ID", - "runnerKeyRequired": "Runner ID is required", + "create": "Add agent", + "createTitle": "Add external agent", + "editTitle": "Edit agent", + "runnerKey": "Agent ID", + "runnerKeyRequired": "Agent ID is required", "runnerKeyInvalid": "Use letters, numbers, underscore or hyphen only", - "runnerKeyExists": "This runner ID is already in use. Open that card to edit it. A custom runner can be deleted from its editor.", + "runnerKeyExists": "This agent ID is already in use. Open that card to edit it. A custom agent can be deleted from its editor.", "command": "Command", "commandRequired": "Command is required", "args": "Arguments", @@ -7347,7 +7363,7 @@ "askHint": "Sends who are you? over ACP and shows the reply above the buttons.", "askResult": "Reply to who are you?", "askFailed": "The probe did not return a reply", - "trusted": "Trusted runner", + "trusted": "Trusted agent", "toolParseMode": "Tool parse mode", "stdioBufferLimit": "Stdio buffer limit (bytes)", "notSet": "Not set", @@ -7356,13 +7372,13 @@ "saveNeedsInstall": "Not saved: {{status}}", "saveNeedsInstallDetail": "Not saved: {{status}}. {{detail}}", "configFailed": "Failed to save ACP config", - "createSuccess": "Runner created", + "createSuccess": "Agent created", "deleteTitle": "Delete {{name}}?", - "deleteConfirm": "This custom runner will be removed.", - "deleteSuccess": "Runner deleted", - "docsHint": "Install an ACP-compatible agent locally (opencode, codebuddy --acp, etc.) before enabling a runner.", + "deleteConfirm": "This custom agent will be removed.", + "deleteSuccess": "Agent deleted", + "docsHint": "Install an ACP-compatible agent locally (opencode, codebuddy --acp, etc.) before enabling it.", "chatPermissionTitle": "External agent permission required", - "runnerReenabled": "This runner was disabled. It has been updated and turned back on.", + "runnerReenabled": "This agent was disabled. It has been updated and turned back on.", "installOnHost": "Install on the machine that runs Octop", "host": { "title": "Host probe", @@ -7411,7 +7427,7 @@ } }, "advanced": "Advanced", - "disableKeepsRunner": "Turning a runner off keeps its settings. The ID stays reserved. Delete a custom runner from this editor to free the ID." + "disableKeepsRunner": "Turning an agent off keeps its settings. The ID stays reserved. Delete a custom agent from this editor to free the ID." }, "plugins": { "loadError": "Failed to load plugins", @@ -7569,8 +7585,8 @@ "subtitle": "Connect docs, cloud storage, and email, then use them in chat as needed" }, "acp": { - "title": "ACP Collaboration", - "subtitle": "Configure external coding-agent runners and enable them per expert" + "title": "Agent collaboration", + "subtitle": "Configure external agents and enable collaboration on this expert" }, "skills": { "title": "Skills", @@ -7906,6 +7922,14 @@ "notAuthorized": "Not authorized", "remaining": "Remaining", "regionPlaceholder": "Regions (all by default)", + "regionAll": "All regions", + "regionRecent": "Recently used", + "regionAllAreas": "All areas", + "regionOtherArea": "Other areas", + "regionOthers": "Others ({{count}})", + "regionSelectedMulti": "{{name}} +{{count}}", + "regionSelectedTotal": "{{count}} selected", + "regionClear": "Clear filter", "refresh": "Refresh", "renew": "Renew", "manageAuth": "Manage", diff --git a/dashboard/src/locales/zh.json b/dashboard/src/locales/zh.json index bdd15364a7..d003cf6df2 100644 --- a/dashboard/src/locales/zh.json +++ b/dashboard/src/locales/zh.json @@ -199,7 +199,7 @@ "SKILL_PACKAGE_NOT_FOUND": "未找到技能包。", "SKILL_PACKAGE_NAME_TAKEN": "技能包 {{name}} 已存在。", "SKILL_PACKAGE_BACKEND_UNSUPPORTED": "技能包目前仅支持「本地完整环境(文件系统+指令执行)」或「本地文件系统(不能执行指令)」,且存储根目录须为 /(POSIX)或专家的工作区根目录(Windows 默认)。", - "ACP_BACKEND_UNSUPPORTED": "当前专家已启用沙箱环境,不可启用或编辑外部 Runner。启用向外委托(acp_runner)不受影响;通过 IDE / octop acp 接入也不受影响。", + "ACP_BACKEND_UNSUPPORTED": "当前专家已启用沙箱环境,不可启用或编辑外部智能体。在当前专家中启用外部智能体协作不受影响;通过 IDE / octop acp 接入也不受影响。", "PUBLISHED_EXPERT_SLUG_TAKEN": "已存在发布专家 slug:{{slug}}。", "PUBLISHED_EXPERT_ALREADY_EXISTS": "该专家已发布为「{{name}}」,请改为刷新已发布模板。", "OIDC_BAD_REQUEST": "OIDC 请求无效:{{detail}}", @@ -283,7 +283,7 @@ "tasks": "自动化", "connectors": "连接器", "bridge": "云端协同", - "acp": "ACP 协作", + "acp": "智能体协作", "agents": "专家", "providers": "供应商", "models": "模型配置", @@ -1171,6 +1171,7 @@ "defaultModeHint": "新建对话时使用的 Ask / Plan / Craft 模式;Craft 为完整执行模式。已有对话不受影响。", "skillPackagesLabel": "可选技能包", "skillPackagesHint": "创建时挂载选中的技能包(需本地存储,且根目录为 /)。", + "managedSkillPackagesHint": "选中的技能包会放进这个智能体的技能目录。同名技能以先选中的包为准。", "skillPackagesUnsupportedHint": "当前沙箱无法直接挂载技能包目录,但仍可使用“复制技能”在工作区创建独立副本。", "skillPackagesClearFailed": "已保存后端设置,但清除已挂载技能包失败", "skillPackagesPlaceholder": "选择技能包", @@ -1240,8 +1241,8 @@ "backendRootDirPlaceholder": "浏览并选择目录", "backendRootDirDesc": "默认使用文件系统的根目录(POSIX 为 `/`,Windows 为所在盘符)。也可浏览并选择其他目录。", "backendRootDirDescContainer": "当前运行在容器环境中,默认使用文件系统根目录 `/`(容器本身已是隔离边界)。也可浏览并选择其他目录。", - "backendRootDirJailHint": "保存至非根目录时,会启用沙箱环境并将 AI 文件系统限制在该目录内。此配置下无法调用外部 ACP Runner;通过 IDE / octop acp 接入不受影响。", - "backendRootDirPathLimitHint": "保存至非根目录时,会将 AI 的文件访问限制在该目录内;但当前系统未提供操作系统级沙箱,AI 进程仍以服务账号自身的权限运行。此配置下无法调用外部 ACP Runner;通过 IDE / octop acp 接入不受影响。", + "backendRootDirJailHint": "保存至非根目录时,会启用沙箱环境并将 AI 文件系统限制在该目录内。此配置下无法调用外部智能体;通过 IDE / octop acp 接入不受影响。", + "backendRootDirPathLimitHint": "保存至非根目录时,会将 AI 的文件访问限制在该目录内;但当前系统未提供操作系统级沙箱,AI 进程仍以服务账号自身的权限运行。此配置下无法调用外部智能体;通过 IDE / octop acp 接入不受影响。", "backendRootDirImmutableHint": "创建后不可更改。", "workspaceDir": "工作区目录", "workspaceDirDesc": "已填入系统为这位专家分配的默认目录,也可以改成其他目录。", @@ -1289,7 +1290,7 @@ }, "backendPathMappings": "路径映射(可选)", "addPathMapping": "添加路径映射", - "advancedOptions": "高级选项", + "advancedOptions": "运行参数", "temperature": "温度 (temperature)", "temperatureTooltip": "采样温度,越高输出越随机", "topP": "Top P", @@ -1344,20 +1345,24 @@ "managed": { "create": "创建", "createTitle": "新建托管专家", + "editTitle": "编辑托管专家", "badge": "托管", "name": "名称", "nameRequired": "请填写名称", "runner": "托管智能体", - "manageAcp": "管理 ACP", + "manageAcp": "管理智能体协作", "runnerRequired": "请选择一个托管智能体", - "noRunners": "请先在 ACP 页面启用一个 Runner。", + "noRunners": "请先在智能体协作页面启用一个智能体。", "runnerSearch": "搜索托管智能体", "runnerSearchEmpty": "没有匹配的托管智能体", "workspaceRequired": "请选择工作目录", "description": "描述", - "loadFailed": "无法加载 ACP Runner", + "loadFailed": "无法加载外部智能体", "templateFailed": "默认提示词加载失败,创建时仍会写入内置内容", - "createFailed": "创建托管专家失败" + "createFailed": "创建托管专家失败", + "yolo": "YOLO", + "yoloHint": "新会话默认不审批。底层智能体会直接执行,包括改文件和运行命令。对话里仍可改回每次审批。", + "sessionModeHint": "按当前托管智能体提供的模式。新对话默认用这里的选择,单个对话里还可以改。" } }, "subagents": { @@ -1450,6 +1455,7 @@ "insufficient_balance": "模型服务返回余额或额度不足。请为该 API Key 对应的账户充值或升级套餐后再试。", "context_length": "对话上下文过长,超出模型限制。请新开会话,或精简历史后再试。", "recursion_limit": "智能体已达到最大迭代次数(递归上限),任务尚未完成。请前往「运行配置」调高「最大迭代次数」后重试。", + "tool_call_repeat": "工具「{{tool}}」带着相同参数已连续调用 {{count}} 次,达到上限 {{limit}},本轮已停止。请换一种做法,或前往「运行配置」调高「连续相同调用上限」,保存后重新加载该专家。", "timeout_network": "连接模型服务超时或网络异常。请检查网络后重试;若使用代理或自建服务,请确认其可达。", "provider_unavailable": "模型服务暂时不可用。请稍后重试,或切换其他模型。", "invalid_request": "该接口可能不接受用量字段。可关闭「聊天里显示实时 Token」后重试;若仍失败,请确认模型是否支持工具调用。", @@ -1468,7 +1474,7 @@ "manageToast": "当前是对端专家,技能 / 模型 / 知识库等请在对端 Octop 上管理", "editBanner": "正在编辑对端专家,改动会保存到对端 Octop。", "editSkillPackages": "技能包属于本机用户资源,无法安装到对端专家,该页签已隐藏。", - "editTools": "ACP 运行器在对端执行。插件图标若是对端本地文件,这里可能无法预览。", + "editTools": "外部智能体在对端执行。插件图标若是对端本地文件,这里可能无法预览。", "editPlugins": "此处只能开关对端已安装的插件;安装、卸载和市场请在对端进行。", "editChannels": "扫码登录和机器人创建会在对端机器上执行,而不是这台浏览器。", "editTasks": "任务按对端时区运行。模型与连接器选项来自对端,新增连接器请在对端安装。", @@ -1480,7 +1486,7 @@ "reconnect": "去重连", "openBridge": "查看连接", "peerOnlyTitle": "此页只管理本机", - "peerOnlyAcp": "这里的 ACP 运行器属于本机 Octop。要开关对端专家的 ACP 工具,请打开该专家的「工具」页签。", + "peerOnlyAcp": "这里的外部智能体属于本机 Octop。要开关对端专家的外部智能体协作工具,请打开该专家的「工具」页签。", "peerOnlyBrowser": "此页控制本机浏览器。对端专家请在聊天侧栏打开浏览器面板。" }, "pushToast": { @@ -1613,6 +1619,13 @@ "executeUtterance": "请按 {{path}} 执行", "keepEditing": "继续改计划" }, + "managedApproval": { + "picker": "审批模式", + "ask": "每次审批", + "askHint": "底层智能体每次执行操作前都需要确认。", + "yolo": "YOLO", + "yoloHint": "不需要审批。底层智能体会直接执行,包括改文件和运行命令。" + }, "errorOccurred": "出现错误", "imageLoadFailed": "图片加载失败", "mediaLoadFailed": "无法加载媒体", @@ -2067,7 +2080,7 @@ "ask_agent": "咨询专家", "call_agent": "调用专家", "call_deferred_tool": "按需调用", - "acp_runner": "ACP 外部专家", + "acp_runner": "外部智能体协作", "external-agent": "托管智能体", "browser_use": "使用浏览器", "browser_control": "浏览器控制", @@ -2089,6 +2102,7 @@ "toolSettings": { "title": "工具设置", "hint": "关闭后模型将无法调用该内置工具。系统必需工具不可关闭。", + "hintManaged": "这里只列出 Octop 能挂上的工具。文件、命令和网页由外部智能体自己提供。记忆未开启、没有知识库或没有其他专家时,对应开关不可用。", "hintPlugin": "关闭后模型将无法调用该插件工具。未挂载的插件需先在「插件管理」中启用。", "empty": "暂无工具", "emptyPlugin": "暂无插件工具。请先在「插件」页为当前智能体启用插件。", @@ -2104,7 +2118,7 @@ "pluginToolCount": "{{count}} 个工具", "tabs": { "builtin": "内置工具", - "acp": "ACP 协作工具", + "acp": "智能体协作", "plugin": "插件工具" }, "categories": { @@ -4236,10 +4250,10 @@ "noActiveAgent": "请先选择一个专家", "retryDelayBelowInitial": "最大间隔不能小于初始间隔", "toolCallLimit": { - "enabled": "限制单轮工具调用", - "enabledTooltip": "限制一次用户请求里工具被调用的总次数。达到上限后结束本轮。关闭后不限制。保存后重新加载该专家。", - "runLimit": "单轮工具调用上限", - "runLimitTooltip": "一次用户请求里最多调用多少次工具。留空为 40。", + "enabled": "限制连续相同工具调用", + "enabledTooltip": "同一个工具带着相同参数连续调用时计数。换成别的工具或参数后重新计数。达到上限后结束本轮。关闭后不限制。保存后重新加载该专家。", + "runLimit": "连续相同调用上限", + "runLimitTooltip": "同一个工具、同一组参数最多连续调用多少次。不同工具或不同参数不累计。留空为 40。", "runLimitPlaceholder": "40" }, "modelRetry": { @@ -4413,6 +4427,7 @@ }, "upload": { "tooltip": "上传文件或文件夹。也可拖到输入框。", + "action": "上传", "files": "文件", "folder": "文件夹", "dropHint": "松开以上传文件或文件夹", @@ -6244,6 +6259,7 @@ "remoteKindGroup": "{{name}}·{{kind}}", "more": "更多", "teamNeedsExpert": "当前是团队「{{name}}」,此页请选择专家", + "managedNeedsExpert": "当前是托管专家「{{name}}」,此页请选择其他专家", "expertsRequired": "此页需要专家" }, "login": { @@ -7304,11 +7320,11 @@ "pickAgent": "请先选择一个专家" }, "acp": { - "description": "连接支持 ACP 协议的外部编程专家。Runner 配置对该账号下所有专家共享;可在下方按专家单独开启 acp_runner 工具。", - "globalRunnersHint": "以下 Runner 配置对该账号下所有专家生效。", - "toolEnabledHint": "acp_runner 工具需按专家单独开启,切换上方专家后为当前专家配置。", - "toolEnabled": "启用向外委托(acp_runner)", - "outboundBlockedHint": "当前专家已启用沙箱环境,不可启用或编辑外部 Runner。启用向外委托(acp_runner)不受影响;通过 IDE / octop acp 接入也不受影响。", + "description": "连接支持 ACP 协议的外部编程智能体。智能体配置对该账号下所有专家共享;可在下方为当前专家启用外部智能体协作。", + "globalRunnersHint": "以下智能体配置对该账号下所有专家生效。", + "toolEnabledHint": "外部智能体协作工具需按专家单独开启,切换上方专家后为当前专家配置。", + "toolEnabled": "在当前专家中启用外部智能体协作", + "outboundBlockedHint": "当前专家已启用沙箱环境,不可启用或编辑外部智能体。在当前专家中启用外部智能体协作不受影响;通过 IDE / octop acp 接入也不受影响。", "outboundBlockedTooltip": "沙箱环境下不可启用或编辑", "runnerUnavailable": "不可用", "builtin": "内置", @@ -7327,16 +7343,16 @@ "intro_kimi_code": "月之暗面 Kimi Code CLI,先 kimi 登录后使用 kimi acp 启动。", "intro_cursor_cli": "Cursor CLI agent,先 agent login 或设置 CURSOR_API_KEY 后使用 agent acp 启动。", "intro_pi": "Pi 编程专家,通过 pi-acp 桥接(npx -y pi-acp)接入 ACP。", - "intro_custom": "自定义 Runner:{{command}}", + "intro_custom": "自定义智能体:{{command}}", "runnerNeedsConfig": "已启用,待配置命令", "clickCardToConfigure": "请先点击卡片配置启动命令", - "create": "添加 Runner", - "createTitle": "添加 ACP Runner", - "editTitle": "编辑 Runner", - "runnerKey": "Runner ID", - "runnerKeyRequired": "请填写 Runner ID", + "create": "添加智能体", + "createTitle": "添加外部智能体", + "editTitle": "编辑智能体", + "runnerKey": "智能体 ID", + "runnerKeyRequired": "请填写智能体 ID", "runnerKeyInvalid": "仅允许字母、数字、下划线和连字符", - "runnerKeyExists": "该 Runner ID 已被占用。请打开对应卡片编辑;自定义 Runner 可在编辑里删除。", + "runnerKeyExists": "该智能体 ID 已被占用。请打开对应卡片编辑;自定义智能体可在编辑里删除。", "command": "启动命令", "commandRequired": "请填写启动命令", "args": "参数", @@ -7347,7 +7363,7 @@ "askHint": "向 ACP 发送 who are you?,回复显示在按钮上方。", "askResult": "who are you? 的回复", "askFailed": "探测没有得到回复", - "trusted": "受信任 Runner", + "trusted": "受信任智能体", "toolParseMode": "工具解析模式", "stdioBufferLimit": "Stdio 缓冲上限(字节)", "notSet": "未设置", @@ -7356,13 +7372,13 @@ "configFailed": "保存 ACP 配置失败", "saveNeedsInstall": "未保存:{{status}}", "saveNeedsInstallDetail": "未保存:{{status}}。{{detail}}", - "createSuccess": "Runner 已创建", + "createSuccess": "智能体已创建", "deleteTitle": "删除 {{name}}?", - "deleteConfirm": "将移除此自定义 Runner。", - "deleteSuccess": "Runner 已删除", - "docsHint": "请先在本地安装并配置好 ACP 专家(如 opencode、codebuddy --acp)后再启用 Runner。", + "deleteConfirm": "将移除此自定义智能体。", + "deleteSuccess": "智能体已删除", + "docsHint": "请先在本地安装并配置好外部智能体(如 opencode、codebuddy --acp)后再启用。", "chatPermissionTitle": "外部专家需要权限确认", - "runnerReenabled": "该 Runner 之前是关闭状态,已按本次填写更新并重新启用。", + "runnerReenabled": "该智能体之前是关闭状态,已按本次填写更新并重新启用。", "installOnHost": "在运行 Octop 的机器上安装", "host": { "title": "本机探测", @@ -7411,7 +7427,7 @@ } }, "advanced": "高级设置", - "disableKeepsRunner": "卡片上的开关只是关闭,配置仍保留,ID 也不会释放。要腾出 ID,请在此删除自定义 Runner。" + "disableKeepsRunner": "卡片上的开关只是关闭,配置仍保留,ID 也不会释放。要腾出 ID,请在此删除自定义智能体。" }, "plugins": { "loadError": "加载插件失败", @@ -7569,8 +7585,8 @@ "subtitle": "连接文档、网盘与邮箱,并在对话中按需使用" }, "acp": { - "title": "ACP 协作", - "subtitle": "配置外部编程专家 Runner,并按专家开启协作" + "title": "智能体协作", + "subtitle": "配置外部智能体,并在当前专家中开启协作" }, "skills": { "title": "技能", @@ -7906,6 +7922,14 @@ "notAuthorized": "未授权", "remaining": "剩余", "regionPlaceholder": "选择地域(默认全部)", + "regionAll": "全部地域", + "regionRecent": "最近访问", + "regionAllAreas": "全部地区", + "regionOtherArea": "其他地区", + "regionOthers": "其它地域({{count}})", + "regionSelectedMulti": "{{name}} 等 {{count}} 个", + "regionSelectedTotal": "已选 {{count}} 个地域", + "regionClear": "清空筛选", "refresh": "刷新", "renew": "续期", "manageAuth": "管理授权", diff --git a/dashboard/src/pages/Agent/Memory/AtomsList.tsx b/dashboard/src/pages/Agent/Memory/AtomsList.tsx index bf65ba8d97..fed415e7e5 100644 --- a/dashboard/src/pages/Agent/Memory/AtomsList.tsx +++ b/dashboard/src/pages/Agent/Memory/AtomsList.tsx @@ -5,7 +5,13 @@ * star importance, percentage confidence, relative timestamps, and no raw metadata IDs. */ -import { useCallback, useEffect, useState } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; import { Button, Progress, @@ -33,6 +39,7 @@ import MemoryPipelineEmpty from "./shared/MemoryPipelineEmpty"; import { confirmDeprecateAtom } from "./shared/deprecateAtom"; import { confirmEditAtom } from "./shared/editAtom"; import CreateAtomModal from "./shared/createAtom"; +import { useMemoryRequestGate } from "./shared/useMemoryRequestGate"; const PAGE_SIZE = 20; @@ -69,8 +76,30 @@ export default function AtomsList({ agentId }: Props) { const [hoveredId, setHoveredId] = useState(null); const [entities, setEntities] = useState([]); const [createOpen, setCreateOpen] = useState(false); + const listGate = useMemoryRequestGate( + JSON.stringify([agentId, page, kind, importance]), + ); + const entityGate = useMemoryRequestGate(agentId); + const actionModal = useRef<{ destroy: () => void } | null>(null); + + useLayoutEffect(() => { + setItems([]); + setTotal(0); + setPage(1); + setLoading(Boolean(agentId)); + setSelected(null); + setHoveredId(null); + setEntities([]); + setCreateOpen(false); + return () => { + actionModal.current?.destroy(); + actionModal.current = null; + }; + }, [agentId]); const load = useCallback(async () => { + const isCurrent = listGate.begin(); + if (!isCurrent) return; setLoading(true); const body: ListAtomsBody = { offset: (page - 1) * PAGE_SIZE, @@ -80,44 +109,66 @@ export default function AtomsList({ agentId }: Props) { if (importance) body.importance_min = importance; try { const r = await memoryDashboardApi.listAtoms(agentId, body); + if (!isCurrent()) return; setItems(r.items); setTotal(r.total); + } catch (error) { + if (isCurrent()) throw error; } finally { - setLoading(false); + if (isCurrent()) setLoading(false); } - }, [agentId, page, kind, importance]); + }, [agentId, page, kind, importance, listGate]); + const reload = useRef(load); + useLayoutEffect(() => { + reload.current = load; + }, [load]); + + const loadEntities = useCallback( + async (clearOnError: boolean) => { + const isCurrent = entityGate.begin(); + if (!isCurrent) return; + try { + const r = await memoryDashboardApi.listEntities(agentId, { + limit: 200, + order_by: "atom_count", + order: "desc", + }); + if (isCurrent()) setEntities(r.items); + } catch { + if (isCurrent() && clearOnError) setEntities([]); + } + }, + [agentId, entityGate], + ); useEffect(() => { if (!agentId) return; void load(); - void memoryDashboardApi - .listEntities(agentId, { - limit: 200, - order_by: "atom_count", - order: "desc", - }) - .then((r) => setEntities(r.items)) - .catch(() => setEntities([])); - }, [agentId, load]); + void loadEntities(true); + }, [agentId, load, loadEntities]); const handleDeprecate = (atom: AtomItem) => { - confirmDeprecateAtom({ + actionModal.current = confirmDeprecateAtom({ agentId, atom, + isActive: entityGate.isActive, onSuccess: () => { + if (!entityGate.isActive()) return; setSelected(null); - void load(); + void reload.current(); }, }); }; const handleEdit = (atom: AtomItem) => { - confirmEditAtom({ + actionModal.current = confirmEditAtom({ agentId, atom, + isActive: entityGate.isActive, onSuccess: (next) => { + if (!entityGate.isActive()) return; setSelected(next); - void load(); + void reload.current(); }, }); }; @@ -316,17 +367,14 @@ export default function AtomsList({ agentId }: Props) { open={createOpen} agentId={agentId} entities={entities} - onClose={() => setCreateOpen(false)} + isActive={entityGate.isActive} + onClose={() => { + if (entityGate.isActive()) setCreateOpen(false); + }} onSuccess={() => { - void load(); - void memoryDashboardApi - .listEntities(agentId, { - limit: 200, - order_by: "atom_count", - order: "desc", - }) - .then((r) => setEntities(r.items)) - .catch(() => undefined); + if (!entityGate.isActive()) return; + void reload.current(); + void loadEntities(false); }} /> diff --git a/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx b/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx index 08c4d8a880..21a79c7726 100644 --- a/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx +++ b/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx @@ -19,7 +19,13 @@ * - the candidate diff view (vs existing atoms) — covered elsewhere. */ -import { useCallback, useEffect, useState } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; import { Alert, Button, @@ -48,6 +54,7 @@ import { type ListCandidatesBody, } from "../../../api/modules/memoryDashboard"; import { useIsMobile } from "../../../hooks/useIsMobile"; +import { useMemoryRequestGate } from "./shared/useMemoryRequestGate"; import styles from "./CandidatesReview.module.less"; const PAGE_SIZE = 20; @@ -92,8 +99,26 @@ export default function CandidatesReview({ agentId }: Props) { // per-row pending state so the spinning button is local, not global const [busyId, setBusyId] = useState(null); + const listGate = useMemoryRequestGate( + JSON.stringify([agentId, page, status, kind]), + ); + const agentGate = useMemoryRequestGate(agentId); + + useLayoutEffect(() => { + setItems([]); + setTotal(0); + setPage(1); + setLoading(Boolean(agentId)); + setSelected(null); + setRejectTarget(null); + setRejectReason(""); + setRejecting(false); + setBusyId(null); + }, [agentId]); const load = useCallback(async () => { + const isCurrent = listGate.begin(); + if (!isCurrent) return; setLoading(true); const body: ListCandidatesBody = { offset: (page - 1) * PAGE_SIZE, @@ -103,17 +128,22 @@ export default function CandidatesReview({ agentId }: Props) { if (kind) body.candidate_type = kind; try { const r = await memoryDashboardApi.listCandidates(agentId, body); + if (!isCurrent()) return; setItems(r.items); setTotal(r.total); } catch (e) { - message.error((e as Error).message ?? "load failed"); + if (isCurrent()) message.error((e as Error).message ?? "load failed"); } finally { - setLoading(false); + if (isCurrent()) setLoading(false); } // ``t`` is intentionally NOT a dependency — the i18n hook returns // a fresh ``t`` ref on every render, which would re-fire the load // effect on every keystroke / hover. - }, [agentId, page, status, kind]); + }, [agentId, page, status, kind, listGate]); + const reload = useRef(load); + useLayoutEffect(() => { + reload.current = load; + }, [load]); useEffect(() => { if (!agentId) return; @@ -121,9 +151,11 @@ export default function CandidatesReview({ agentId }: Props) { }, [agentId, load]); const handlePromote = async (c: CandidateItem) => { + if (!agentGate.isActive()) return; setBusyId(c.id); try { const r = await memoryDashboardApi.promoteCandidate(agentId, c.id); + if (!agentGate.isActive()) return; const detail = r.merged > 0 ? `与现有记忆合并 ${r.merged} 条` @@ -133,29 +165,32 @@ export default function CandidatesReview({ agentId }: Props) { message.success( t("memory.candidates.promoteOk", "已采纳") + ` · ${detail}`, ); - void load(); + void reload.current(); } catch (e) { - message.error((e as Error).message ?? "操作失败"); + if (agentGate.isActive()) + message.error((e as Error).message ?? "操作失败"); } finally { - setBusyId(null); + if (agentGate.isActive()) setBusyId(null); } }; const handleReject = async () => { - if (!rejectTarget) return; + if (!rejectTarget || !agentGate.isActive()) return; setRejecting(true); try { await memoryDashboardApi.rejectCandidate(agentId, rejectTarget.id, { reason: rejectReason.trim() || undefined, }); + if (!agentGate.isActive()) return; message.success(t("memory.candidates.rejectOk", "已忽略")); setRejectTarget(null); setRejectReason(""); - void load(); + void reload.current(); } catch (e) { - message.error((e as Error).message ?? "操作失败"); + if (agentGate.isActive()) + message.error((e as Error).message ?? "操作失败"); } finally { - setRejecting(false); + if (agentGate.isActive()) setRejecting(false); } }; diff --git a/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx b/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx index 1aa821969b..c5f43a0439 100644 --- a/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx +++ b/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx @@ -37,6 +37,7 @@ import { } from "../../../utils/messageParser"; import { useIsMobile } from "../../../hooks/useIsMobile"; import { useServerTimezone } from "../../../hooks/useServerTimezone"; +import { useMemoryRequestGate } from "./shared/useMemoryRequestGate"; import { confirmDeleteConversation, deleteConversation, @@ -174,20 +175,28 @@ export default function ConversationRecords({ const [deletingId, setDeletingId] = useState(null); const [cardPage, setCardPage] = useState(1); const [cardPageSize, setCardPageSize] = useState(THREAD_LIST_PAGE_SIZE); + const listGate = useMemoryRequestGate(agentId); + const deleteModal = useRef | null>(null); const loadThreads = useCallback(async () => { + const isCurrent = listGate.begin(); + if (!isCurrent) return; setListLoading(true); try { const list = await octopThreadsApi.list(agentId, 100); + if (!isCurrent()) return; list.sort((a, b) => b.last_active - a.last_active); setThreads(list); } catch { + if (!isCurrent()) return; setThreads([]); message.error(t("memory.loadFailed")); } finally { - setListLoading(false); + if (isCurrent()) setListLoading(false); } - }, [agentId, t]); + }, [agentId, t, listGate]); const resetHistoryState = useCallback(() => { setMessages([]); @@ -197,13 +206,25 @@ export default function ConversationRecords({ scrollHeightBeforePrependRef.current = null; }, []); - useEffect(() => { + useLayoutEffect(() => { + setThreads([]); + setListLoading(Boolean(agentId)); setSelectedThread(null); setDrawerOpen(false); resetHistoryState(); + setHistoryLoading(false); + setDeletingId(null); setCardPage(1); + return () => { + deleteModal.current?.destroy(); + deleteModal.current = null; + }; + }, [agentId, resetHistoryState]); + + useEffect(() => { + if (!agentId) return; void loadThreads(); - }, [agentId, loadThreads, resetHistoryState]); + }, [agentId, loadThreads]); const fetchThreadHistory = useCallback( async (threadId: string, offset: number) => { @@ -302,7 +323,10 @@ export default function ConversationRecords({ const confirmDelete = useCallback( (thread: OctopThread) => { - confirmDeleteConversation(t, async (compact) => { + if (!listGate.isActive()) return; + deleteModal.current?.destroy(); + deleteModal.current = confirmDeleteConversation(t, async (compact) => { + if (!listGate.isActive()) return; setDeletingId(thread.thread_id); try { const deleted = await deleteConversation( @@ -310,7 +334,9 @@ export default function ConversationRecords({ thread.thread_id, compact, t, + listGate.isActive, ); + if (!listGate.isActive()) return; if (deleted !== true) return deleted; if (selectedThread?.thread_id === thread.thread_id) { closeDrawer(); @@ -319,11 +345,11 @@ export default function ConversationRecords({ prev.filter((row) => row.thread_id !== thread.thread_id), ); } finally { - setDeletingId(null); + if (listGate.isActive()) setDeletingId(null); } }); }, - [agentId, closeDrawer, selectedThread?.thread_id, t], + [agentId, closeDrawer, selectedThread?.thread_id, t, listGate], ); const roleLabel = (role: string) => { @@ -523,7 +549,12 @@ export default function ConversationRecords({ scroll={{ x: 980 }} locale={{ emptyText: t("memory.noConversations") }} pagination={{ - defaultPageSize: THREAD_LIST_PAGE_SIZE, + current: cardPage, + pageSize: cardPageSize, + onChange: (page, size) => { + setCardPage(size !== cardPageSize ? 1 : page); + setCardPageSize(size); + }, showSizeChanger: true, pageSizeOptions: THREAD_LIST_PAGE_SIZE_OPTIONS.map(String), showTotal: threadPaginationTotal, diff --git a/dashboard/src/pages/Agent/Memory/EpisodesList.tsx b/dashboard/src/pages/Agent/Memory/EpisodesList.tsx index ef95478b7e..776a2e143e 100644 --- a/dashboard/src/pages/Agent/Memory/EpisodesList.tsx +++ b/dashboard/src/pages/Agent/Memory/EpisodesList.tsx @@ -6,7 +6,13 @@ * compact intensity bar while hiding raw IDs. */ -import { useCallback, useEffect, useMemo, useState } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useState, +} from "react"; import { Card, Drawer, @@ -24,6 +30,7 @@ import { type EpisodeItem, } from "../../../api/modules/memoryDashboard"; import { useServerTimezone } from "../../../hooks/useServerTimezone"; +import { useMemoryRequestGate } from "./shared/useMemoryRequestGate"; import { calendarDaysAgo, formatServerHourMinute, @@ -45,20 +52,34 @@ export default function EpisodesList({ agentId }: Props) { const [page, setPage] = useState(1); const [loading, setLoading] = useState(true); const [selected, setSelected] = useState(null); + const listGate = useMemoryRequestGate(JSON.stringify([agentId, page])); + + useLayoutEffect(() => { + setItems([]); + setTotal(0); + setPage(1); + setLoading(Boolean(agentId)); + setSelected(null); + }, [agentId]); const load = useCallback(async () => { + const isCurrent = listGate.begin(); + if (!isCurrent) return; setLoading(true); try { const r = await memoryDashboardApi.listEpisodes(agentId, { offset: (page - 1) * PAGE_SIZE, limit: PAGE_SIZE, }); + if (!isCurrent()) return; setItems(r.items); setTotal(r.total); + } catch (error) { + if (isCurrent()) throw error; } finally { - setLoading(false); + if (isCurrent()) setLoading(false); } - }, [agentId, page]); + }, [agentId, page, listGate]); useEffect(() => { if (!agentId) return; diff --git a/dashboard/src/pages/Agent/Memory/JournalList.tsx b/dashboard/src/pages/Agent/Memory/JournalList.tsx index 80b535189c..ad0d1d689e 100644 --- a/dashboard/src/pages/Agent/Memory/JournalList.tsx +++ b/dashboard/src/pages/Agent/Memory/JournalList.tsx @@ -6,7 +6,13 @@ * while key events such as promote/reject/deprecate remain standalone. */ -import { useCallback, useEffect, useMemo, useState } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useState, +} from "react"; import { Card, Empty, Pagination, Select, Skeleton, Space, Tag } from "antd"; import { ChevronDown, ChevronRight } from "lucide-react"; @@ -17,6 +23,7 @@ import { type ListJournalBody, } from "../../../api/modules/memoryDashboard"; import { useServerTimezone } from "../../../hooks/useServerTimezone"; +import { useMemoryRequestGate } from "./shared/useMemoryRequestGate"; import { calendarDaysAgo, formatServerHourMinute, @@ -81,8 +88,21 @@ export default function JournalList({ agentId }: Props) { const [loading, setLoading] = useState(true); const [action, setAction] = useState(""); const [expanded, setExpanded] = useState>({}); + const listGate = useMemoryRequestGate( + JSON.stringify([agentId, page, action]), + ); + + useLayoutEffect(() => { + setItems([]); + setTotal(0); + setPage(1); + setLoading(Boolean(agentId)); + setExpanded({}); + }, [agentId]); const load = useCallback(async () => { + const isCurrent = listGate.begin(); + if (!isCurrent) return; setLoading(true); const body: ListJournalBody = { offset: (page - 1) * PAGE_SIZE, @@ -91,12 +111,15 @@ export default function JournalList({ agentId }: Props) { if (action) body.action = action; try { const r = await memoryDashboardApi.listJournal(agentId, body); + if (!isCurrent()) return; setItems(r.items); setTotal(r.total); + } catch (error) { + if (isCurrent()) throw error; } finally { - setLoading(false); + if (isCurrent()) setLoading(false); } - }, [agentId, page, action]); + }, [agentId, page, action, listGate]); useEffect(() => { if (!agentId) return; diff --git a/dashboard/src/pages/Agent/Memory/MemoryActions.test.tsx b/dashboard/src/pages/Agent/Memory/MemoryActions.test.tsx new file mode 100644 index 0000000000..ccbf6791cc --- /dev/null +++ b/dashboard/src/pages/Agent/Memory/MemoryActions.test.tsx @@ -0,0 +1,334 @@ +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Modal, type ModalFuncProps } from "antd"; +import { makeAtom, makeEntity } from "../../../test/memoryFixtures"; + +const mocks = vi.hoisted(() => ({ + atoms: vi.fn(), + entities: vi.fn(), + replace: vi.fn(), + deprecate: vi.fn(), + create: vi.fn(), + threads: vi.fn(), + history: vi.fn(), + remove: vi.fn(), + error: vi.fn(), + success: vi.fn(), + loading: vi.fn(), + closeLoading: vi.fn(), + mobile: false, + t: (key: string, fallback?: unknown) => + typeof fallback === "string" ? fallback : key, +})); + +vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: mocks.t }) })); +vi.mock("../../../i18n", () => ({ default: { t: mocks.t } })); +vi.mock("../../../utils/antdMessage", () => ({ + message: { + error: mocks.error, + success: mocks.success, + loading: mocks.loading, + }, +})); +vi.mock("../../../hooks/useIsMobile", () => ({ + useIsMobile: () => mocks.mobile, +})); +vi.mock("../../../hooks/useServerTimezone", () => ({ + useServerTimezone: () => "UTC", +})); +vi.mock("../../../api/modules/memoryDashboard", () => ({ + memoryDashboardApi: { + listAtoms: mocks.atoms, + listEntities: mocks.entities, + replaceAtom: mocks.replace, + deprecateAtom: mocks.deprecate, + createAtom: mocks.create, + }, + isAtomDeprecated: () => false, +})); +vi.mock("../../../api/modules/octopThreads", () => ({ + CHAT_HISTORY_PAGE_SIZE: 50, + octopThreadsApi: { + list: mocks.threads, + history: mocks.history, + delete: mocks.remove, + }, +})); +vi.mock("./shared/LineageStrip", () => ({ default: () => null })); +vi.mock("./shared/MemoryPipelineEmpty", () => ({ default: () => null })); +vi.mock("../../../components/Markdown/LazyMarkdown", () => ({ + default: () => null, +})); + +// Keep the mutation helpers and conversation confirmation real: replacing them +// with callback-only mocks hides stale toasts and dialogs mounted outside the list. +import AtomsList from "./AtomsList"; +import ConversationRecords from "./ConversationRecords"; + +let restoreConfirm: (() => void) | undefined; +const originalWidth = window.innerWidth; + +function deferred() { + let resolve!: (value: unknown) => void; + let reject!: (reason: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +beforeEach(() => { + vi.clearAllMocks(); + for (const mutation of [ + mocks.replace, + mocks.deprecate, + mocks.create, + mocks.remove, + ]) { + mutation.mockReset(); + } + mocks.mobile = false; + mocks.atoms.mockResolvedValue({ + items: [makeAtom({ assertion: "visible atom" })], + total: 1, + }); + mocks.entities.mockResolvedValue({ items: [], total: 0 }); + mocks.threads.mockResolvedValue([ + { + thread_id: "same-id", + title: "visible conversation", + channel_type: "web", + created_at: 1, + last_active: 2, + }, + ]); + mocks.history.mockResolvedValue({ messages: [], has_more: false }); + mocks.loading.mockReturnValue(mocks.closeLoading); +}); + +afterEach(async () => { + cleanup(); + restoreConfirm?.(); + restoreConfirm = undefined; + window.innerWidth = originalWidth; + act(() => Modal.destroyAll()); + await waitFor(() => + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(), + ); +}); + +async function openAtomAction(action: "edit" | "deprecate") { + let confirmProps: ModalFuncProps | undefined; + const destroy = vi.fn(); + const spy = vi.spyOn(Modal, "confirm").mockImplementation((props) => { + confirmProps = props; + return { destroy, update: vi.fn() }; + }); + restoreConfirm = () => spy.mockRestore(); + const view = render(); + fireEvent.click(await screen.findByText("visible atom")); + fireEvent.click( + await screen.findByRole("button", { + name: action === "edit" ? "编辑这条记忆" : "弃用这条记忆", + }), + ); + expect(confirmProps).toBeDefined(); + return { ...view, confirm: () => confirmProps!.onOk?.(), destroy }; +} + +describe.each(["edit", "deprecate"] as const)( + "%s with the real helper", + (action) => { + const mutation = action === "edit" ? mocks.replace : mocks.deprecate; + + it.each([ + ["switch", "resolve"], + ["switch", "reject"], + ["revisit", "resolve"], + ["revisit", "reject"], + ["unmount", "resolve"], + ["unmount", "reject"], + ])("ignores obsolete feedback after %s and %s", async (change, outcome) => { + const pending = deferred(); + mutation.mockReturnValueOnce(pending.promise); + const { rerender, unmount, confirm, destroy } = await openAtomAction( + action, + ); + const completion = Promise.resolve(confirm()); + expect(mutation).toHaveBeenCalledOnce(); + if (change === "unmount") unmount(); + else { + await act(async () => rerender()); + if (change === "revisit") + await act(async () => rerender()); + } + expect(destroy).toHaveBeenCalledOnce(); + const calls = mocks.atoms.mock.calls.length; + await act(async () => { + if (outcome === "resolve") pending.resolve({ atom: makeAtom() }); + else pending.reject(new Error("old operation failed")); + await completion; + }); + expect(mocks.success).not.toHaveBeenCalled(); + expect(mocks.error).not.toHaveBeenCalled(); + expect(mocks.atoms).toHaveBeenCalledTimes(calls); + }); + + it.each(["resolve", "reject"])( + "preserves current %s feedback", + async (outcome) => { + const error = new Error("current failure"); + if (outcome === "resolve") + mutation.mockResolvedValue({ atom: makeAtom() }); + else mutation.mockRejectedValue(error); + const { confirm } = await openAtomAction(action); + const calls = mocks.atoms.mock.calls.length; + await act(async () => { + if (outcome === "resolve") await confirm(); + else await expect(confirm()).rejects.toThrow(error); + }); + if (outcome === "resolve") { + expect(mocks.success).toHaveBeenCalledOnce(); + expect(mocks.atoms).toHaveBeenCalledTimes(calls + 1); + } else { + expect(mocks.error).toHaveBeenCalledOnce(); + expect(mocks.atoms).toHaveBeenCalledTimes(calls); + } + }, + ); + }, +); + +describe("create atom", () => { + it.each(["resolve", "reject"])( + "ignores an old %s without closing the new form", + async (outcome) => { + const pending = deferred(); + mocks.create.mockReturnValueOnce(pending.promise); + const { rerender } = render(); + await screen.findByText("visible atom"); + fireEvent.click(screen.getByRole("button", { name: "新建记忆" })); + fireEvent.change(await screen.findByLabelText("主题名称"), { + target: { value: "old topic" }, + }); + fireEvent.change(screen.getByLabelText("记忆内容"), { + target: { value: "old assertion" }, + }); + fireEvent.click(screen.getByRole("button", { name: /保\s*存/ })); + await waitFor(() => expect(mocks.create).toHaveBeenCalledOnce()); + await act(async () => rerender()); + await waitFor(() => + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(), + ); + fireEvent.click(screen.getByRole("button", { name: "新建记忆" })); + await screen.findByRole("dialog"); + const calls = mocks.atoms.mock.calls.length; + await act(async () => { + if (outcome === "resolve") + pending.resolve({ + atom: makeAtom(), + entity: makeEntity(), + created_entity: true, + }); + else pending.reject(new Error("old create failed")); + }); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + expect(mocks.success).not.toHaveBeenCalled(); + expect(mocks.error).not.toHaveBeenCalled(); + expect(mocks.atoms).toHaveBeenCalledTimes(calls); + }, + ); +}); + +describe.each([false, true])("conversation deletion (mobile: %s)", (mobile) => { + async function openDelete() { + mocks.mobile = mobile; + window.innerWidth = mobile ? 390 : 1200; + const view = render(); + await screen.findByText("visible conversation"); + fireEvent.click(screen.getByRole("button", { name: "common.delete" })); + await screen.findByRole("dialog"); + return view; + } + + it.each(["switch", "unmount"])( + "destroys the confirmation on %s", + async (change) => { + const { rerender, unmount } = await openDelete(); + if (change === "unmount") unmount(); + else await act(async () => rerender()); + await waitFor(() => + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(), + ); + expect(mocks.remove).not.toHaveBeenCalled(); + }, + ); + + it.each(["resolve", "reject"])( + "ignores stale delete %s after A/B/A", + async (outcome) => { + const pending = deferred(); + mocks.remove.mockReturnValueOnce(pending.promise); + const { rerender } = await openDelete(); + fireEvent.click( + screen.getByRole("button", { name: "chat.deleteSessionOnly" }), + ); + await waitFor(() => + expect(mocks.remove).toHaveBeenCalledWith("A", "same-id", false), + ); + await act(async () => rerender()); + await act(async () => rerender()); + await act(async () => { + if (outcome === "resolve") pending.resolve({ compacted: false }); + else pending.reject(new Error("old delete failed")); + }); + expect(screen.getByText("visible conversation")).toBeInTheDocument(); + expect(mocks.success).not.toHaveBeenCalled(); + expect(mocks.error).not.toHaveBeenCalled(); + }, + ); + + it("keeps a current 409 confirmation open and allows retry with compact", async () => { + mocks.remove.mockRejectedValueOnce( + new Error( + `Request failed: 409 Conflict - ${JSON.stringify({ + error: { code: "THREAD_TURN_ACTIVE", message: "Reply in progress" }, + })}`, + ), + ); + await openDelete(); + fireEvent.click( + screen.getByRole("button", { name: "chat.deleteSessionOnly" }), + ); + await waitFor(() => + expect(mocks.error).toHaveBeenCalledWith("apiErrors.THREAD_TURN_ACTIVE"), + ); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + expect(screen.getByText("visible conversation")).toBeInTheDocument(); + mocks.remove.mockResolvedValueOnce({ compacted: true }); + fireEvent.click( + screen.getByRole("button", { name: "chat.deleteSessionAndCompact" }), + ); + await waitFor(() => + expect(mocks.remove).toHaveBeenLastCalledWith("A", "same-id", true), + ); + await waitFor(() => + expect( + screen.queryByText("visible conversation"), + ).not.toBeInTheDocument(), + ); + await waitFor(() => + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(), + ); + expect(mocks.success).toHaveBeenCalledWith("chat.deleteSessionCompacted"); + expect(mocks.closeLoading).toHaveBeenCalledOnce(); + }); +}); diff --git a/dashboard/src/pages/Agent/Memory/MemoryLists.race.test.tsx b/dashboard/src/pages/Agent/Memory/MemoryLists.race.test.tsx new file mode 100644 index 0000000000..02719c6f63 --- /dev/null +++ b/dashboard/src/pages/Agent/Memory/MemoryLists.race.test.tsx @@ -0,0 +1,784 @@ +import { + StrictMode, + useState, + type ComponentType, + type ReactNode, +} from "react"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + makeAtom, + makeCandidate, + makeEntity, + makeEpisode, + makeJournal, +} from "../../../test/memoryFixtures"; + +const mocks = vi.hoisted(() => ({ + atoms: vi.fn(), + raw: vi.fn(), + episodes: vi.fn(), + journal: vi.fn(), + candidates: vi.fn(), + entities: vi.fn(), + threads: vi.fn(), + history: vi.fn(), + removeThread: vi.fn(), + promote: vi.fn(), + reject: vi.fn(), + edit: vi.fn(), + deprecate: vi.fn(), + destroyAction: vi.fn(), + confirmDelete: vi.fn(), + error: vi.fn(), + success: vi.fn(), + createProps: null as null | { + onSuccess: () => void; + onClose: () => void; + entities: { canonical_name: string }[]; + open: boolean; + }, + t: (key: string, fallback?: unknown) => + typeof fallback === "string" ? fallback : key, +})); + +vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: mocks.t }) })); +vi.mock("../../../hooks/useIsMobile", () => ({ useIsMobile: () => false })); +vi.mock("../../../hooks/useServerTimezone", () => ({ + useServerTimezone: () => "UTC", +})); +vi.mock("../../../utils/antdMessage", () => ({ + message: { error: mocks.error, success: mocks.success }, +})); +vi.mock("../../../utils/antdModal", () => ({ + modal: { confirm: mocks.confirmDelete }, +})); +vi.mock("../../../api/modules/memoryDashboard", () => ({ + memoryDashboardApi: { + listAtoms: mocks.atoms, + listRawEvents: mocks.raw, + listEpisodes: mocks.episodes, + listJournal: mocks.journal, + listCandidates: mocks.candidates, + listEntities: mocks.entities, + promoteCandidate: mocks.promote, + rejectCandidate: mocks.reject, + }, + isAtomDeprecated: () => false, +})); +vi.mock("../../../api/modules/octopThreads", () => ({ + CHAT_HISTORY_PAGE_SIZE: 50, + octopThreadsApi: { + list: mocks.threads, + history: mocks.history, + delete: mocks.removeThread, + }, +})); +vi.mock("./shared/LineageStrip", () => ({ default: () => null })); +vi.mock("./shared/MemoryPipelineEmpty", () => ({ default: () => null })); +vi.mock("../../../components/Markdown/LazyMarkdown", () => ({ + default: () => null, +})); +vi.mock("./shared/editAtom", () => ({ confirmEditAtom: mocks.edit })); +vi.mock("./shared/deprecateAtom", () => ({ + confirmDeprecateAtom: mocks.deprecate, +})); +vi.mock("./shared/createAtom", () => ({ + default: (props: NonNullable) => { + mocks.createProps = props; + return ( + + {props.entities.map((entity) => entity.canonical_name).join(",")} + + ); + }, +})); + +// Keep the real list components and their event handlers. Lightweight display +// controls expose loading/count state without Antd animation or portal timing. +vi.mock("antd", async (importOriginal) => { + const actual = await importOriginal(); + const Pagination = ({ + total, + current = 1, + onChange, + }: { + total: number; + current?: number; + onChange?: (page: number) => void; + }) => ( +
+ {total} + {current} + {[2, 3].map((page) => ( + + ))} +
+ ); + return { + ...actual, + Skeleton: () =>
, + Pagination, + Select: ({ + value, + onChange, + options, + }: { + value: string; + onChange: (value: string) => void; + options: { value: string; label: string }[]; + }) => ( + + ), + Drawer: ({ open, children }: { open: boolean; children: ReactNode }) => + open ?
{children}
: null, + Modal: ({ + open, + children, + onOk, + confirmLoading, + }: { + open: boolean; + children: ReactNode; + onOk: () => void; + confirmLoading: boolean; + }) => + open ? ( +
+ {children} + +
+ ) : null, + Popconfirm: ({ + children, + onConfirm, + disabled, + }: { + children: ReactNode; + onConfirm: () => void; + disabled?: boolean; + }) => ( + + {children} + + + ), + Table: function Table({ + dataSource, + loading, + columns, + pagination, + }: { + dataSource: { thread_id: string; title: string }[]; + loading: boolean; + columns: { + key?: string; + render?: ( + value: undefined, + row: { thread_id: string; title: string }, + ) => ReactNode; + }[]; + pagination: { + current?: number; + onChange?: (page: number, size: number) => void; + pageSize?: number; + }; + }) { + const [page, setPage] = useState(1); + return ( +
+ {loading &&
} + { + setPage(page); + pagination.onChange?.(page, pagination.pageSize ?? 20); + }} + /> + {dataSource.map((row) => ( +
+ {row.title} + {columns + .find((column) => column.key === "actions") + ?.render?.(undefined, row)} +
+ ))} +
+ ); + }, + }; +}); + +import AtomsList from "./AtomsList"; +import RawEventsList from "./RawEventsList"; +import EpisodesList from "./EpisodesList"; +import JournalList from "./JournalList"; +import CandidatesReview from "./CandidatesReview"; +import ConversationRecords from "./ConversationRecords"; + +function deferred() { + let resolve!: (value: unknown) => void; + let reject!: (reason: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +const cases = [ + { + name: "atoms", + View: AtomsList, + api: mocks.atoms, + pageSize: 20, + item: (label: string) => makeAtom({ id: label, assertion: label }), + filters: ["Fact", "Task"], + }, + { + name: "raw", + View: RawEventsList, + api: mocks.raw, + pageSize: 20, + item: (label: string) => ({ + id: label, + content: label, + event_type: "user_message", + timestamp: "2026-09-01T00:00:00Z", + }), + filters: ["user_message", "assistant_message"], + }, + { + name: "episodes", + View: EpisodesList, + api: mocks.episodes, + pageSize: 20, + item: (label: string) => makeEpisode({ id: label, summary: label }), + }, + { + name: "journal", + View: JournalList, + api: mocks.journal, + pageSize: 30, + item: (label: string) => makeJournal({ id: label, target_summary: label }), + filters: ["promote", "reject"], + }, + { + name: "candidates", + View: CandidatesReview, + api: mocks.candidates, + pageSize: 20, + item: (label: string) => makeCandidate({ id: label, title: label }), + filters: ["pending", "promoted"], + }, + { + name: "threads", + View: ConversationRecords, + api: mocks.threads, + item: (label: string) => ({ + thread_id: label, + title: label, + channel_type: "web", + created_at: 1, + last_active: 2, + }), + }, +]; + +function response(testCase: (typeof cases)[number], label: string, total = 1) { + const items = [testCase.item(label)]; + return testCase.name === "threads" + ? Array.from({ length: total }, (_, index) => + testCase.item(index ? `${label}-${index}` : label), + ) + : { items, total, has_more: total > 1 }; +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.promote.mockReset(); + mocks.reject.mockReset(); + mocks.removeThread.mockReset(); + for (const testCase of cases) testCase.api.mockReset(); + mocks.entities + .mockReset() + .mockResolvedValue({ items: [], total: 0, has_more: false }); + mocks.history.mockResolvedValue({ messages: [], has_more: false }); + mocks.createProps = null; + mocks.edit.mockReturnValue({ destroy: mocks.destroyAction }); + mocks.deprecate.mockReturnValue({ destroy: mocks.destroyAction }); + mocks.confirmDelete.mockReturnValue({ destroy: mocks.destroyAction }); +}); + +describe.each(cases)("$name list request ownership", (testCase) => { + const View: ComponentType<{ agentId: string }> = testCase.View; + + it("keeps B's rows and count when A completes last", async () => { + const old = deferred(); + const current = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockReturnValueOnce(current.promise); + const { rerender } = render(); + rerender(); + await act(async () => + current.resolve(response(testCase, "current-row", 2)), + ); + await act(async () => old.resolve(response(testCase, "obsolete-row", 3))); + expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument(); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + expect(screen.getByTestId("total")).toHaveTextContent(/^2$/); + }); + + it.each(["resolve", "reject"] as const)( + "ignores obsolete %s while B is pending", + async (outcome) => { + const old = deferred(); + const current = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockReturnValueOnce(current.promise); + const { rerender } = render(); + rerender(); + await act(async () => { + if (outcome === "resolve") + old.resolve(response(testCase, "obsolete-row")); + else old.reject(new Error("obsolete failure")); + }); + expect(screen.getByTestId("loading")).toBeInTheDocument(); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + expect(mocks.error).not.toHaveBeenCalled(); + await act(async () => current.resolve(response(testCase, "current-row"))); + expect(screen.queryByTestId("loading")).not.toBeInTheDocument(); + }, + ); + + it("does not clear B's successful result when A fails later", async () => { + const old = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockResolvedValueOnce(response(testCase, "current-row")); + const { rerender } = render(); + await act(async () => rerender()); + await act(async () => old.reject(new Error("obsolete failure"))); + expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument(); + expect(mocks.error).not.toHaveBeenCalled(); + }); + + it("clears previously loaded rows and count before B responds", async () => { + testCase.api.mockResolvedValueOnce(response(testCase, "obsolete-row", 2)); + const { rerender } = render(); + await act(async () => {}); + expect(screen.getByText(/^「?obsolete-row」?$/)).toBeInTheDocument(); + testCase.api.mockReturnValue(new Promise(() => {})); + rerender(); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + expect(screen.getByTestId("total")).toHaveTextContent(/^0$/); + expect(screen.getByTestId("loading")).toBeInTheDocument(); + await act(async () => {}); + }); + + it("distinguishes two visits to A separated by B", async () => { + const old = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockResolvedValue(response(testCase, "current-row")); + const { rerender } = render(); + await act(async () => rerender()); + await act(async () => rerender()); + await act(async () => old.resolve(response(testCase, "obsolete-row"))); + expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument(); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + }); + + it("ignores a failure after unmount", async () => { + const pending = deferred(); + testCase.api.mockReturnValue(pending.promise); + const { unmount } = render(); + unmount(); + await act(async () => pending.reject(new Error("unmounted failure"))); + expect(mocks.error).not.toHaveBeenCalled(); + }); + + it("survives StrictMode effect cleanup and replay", async () => { + const old = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockResolvedValue(response(testCase, "current-row")); + render( + + + , + ); + await act(async () => {}); + await act(async () => old.resolve(response(testCase, "obsolete-row"))); + expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument(); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + }); +}); + +describe.each(cases.filter((testCase) => testCase.pageSize))( + "$name pagination", + (testCase) => { + it("keeps the latest page when responses arrive out of order, and resets the page for a new agent", async () => { + const View = testCase.View; + testCase.api.mockResolvedValueOnce( + response(testCase, "initial-row", 200), + ); + const { rerender } = render(); + await act(async () => {}); + const old = deferred(); + const current = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockReturnValueOnce(current.promise); + fireEvent.click(screen.getByText("page 2")); + fireEvent.click(screen.getByText("page 3")); + await act(async () => + current.resolve(response(testCase, "current-row", 200)), + ); + await act(async () => + old.resolve(response(testCase, "obsolete-row", 100)), + ); + expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument(); + expect(screen.getByTestId("page")).toHaveTextContent(/^3$/); + expect(screen.getByTestId("total")).toHaveTextContent(/^200$/); + testCase.api.mockResolvedValue(response(testCase, "new-agent-row")); + await act(async () => rerender()); + expect(screen.getByTestId("page")).toHaveTextContent(/^1$/); + expect(testCase.api).toHaveBeenLastCalledWith( + "B", + expect.objectContaining({ offset: 0 }), + ); + }); + }, +); + +describe.each(cases.filter((testCase) => testCase.filters))( + "$name filters", + (testCase) => { + it("keeps the latest filter result and preserves the filter on agent change", async () => { + const View = testCase.View; + testCase.api.mockResolvedValueOnce(response(testCase, "initial-row")); + const { rerender } = render(); + await act(async () => {}); + const old = deferred(); + const current = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockReturnValueOnce(current.promise); + const select = screen.getAllByRole("combobox")[0]; + fireEvent.change(select, { target: { value: testCase.filters![0] } }); + fireEvent.change(select, { target: { value: testCase.filters![1] } }); + await act(async () => current.resolve(response(testCase, "current-row"))); + await act(async () => old.resolve(response(testCase, "obsolete-row"))); + expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument(); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + testCase.api.mockResolvedValue(response(testCase, "new-agent-row")); + await act(async () => rerender()); + expect(screen.getAllByRole("combobox")[0]).toHaveValue( + testCase.filters![1], + ); + }); + }, +); + +describe.each( + cases.filter((testCase) => + ["raw", "episodes", "candidates"].includes(testCase.name), + ), +)("$name selection", (testCase) => { + it("closes the old detail on agent change", async () => { + const View = testCase.View; + testCase.api.mockResolvedValue(response(testCase, "visible-row")); + const { rerender } = render(); + await act(async () => {}); + fireEvent.click(screen.getByText("visible-row")); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + testCase.api.mockReturnValue(new Promise(() => {})); + rerender(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }); +}); + +describe.each( + cases.filter((testCase) => ["candidates", "threads"].includes(testCase.name)), +)("$name current errors", (testCase) => { + it("still reports the current failure and does not accept an older success", async () => { + const View = testCase.View; + const old = deferred(); + testCase.api + .mockReturnValueOnce(old.promise) + .mockRejectedValueOnce(new Error("current failure")); + const { rerender } = render(); + await act(async () => rerender()); + expect(mocks.error).toHaveBeenCalledTimes(1); + expect(screen.queryByTestId("loading")).not.toBeInTheDocument(); + await act(async () => old.resolve(response(testCase, "obsolete-row"))); + expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument(); + expect(screen.getByTestId("total")).toHaveTextContent(/^0$/); + }); +}); + +describe("Atoms related requests and callbacks", () => { + it.each(["resolve", "reject"] as const)( + "ignores obsolete entity %s without invalidating the atom request", + async (outcome) => { + const old = deferred(); + const currentAtoms = deferred(); + mocks.atoms + .mockReturnValueOnce(new Promise(() => {})) + .mockReturnValueOnce(currentAtoms.promise); + mocks.entities.mockReturnValueOnce(old.promise).mockResolvedValueOnce({ + items: [makeEntity({ canonical_name: "B entity" })], + }); + const { rerender } = render(); + await act(async () => rerender()); + await act(async () => { + if (outcome === "resolve") + old.resolve({ items: [makeEntity({ canonical_name: "A entity" })] }); + else old.reject(new Error("old entities")); + currentAtoms.resolve({ + items: [makeAtom({ assertion: "B atom" })], + total: 1, + }); + }); + expect(screen.getByTestId("entities")).toHaveTextContent(/^B entity$/); + expect(screen.getByText("B atom")).toBeInTheDocument(); + }, + ); + + it("gates repeated creation refreshes for both atoms and entities", async () => { + mocks.atoms.mockResolvedValue({ items: [], total: 0 }); + render(); + await act(async () => {}); + const oldAtoms = deferred(); + const oldEntities = deferred(); + mocks.atoms.mockReturnValueOnce(oldAtoms.promise).mockResolvedValueOnce({ + items: [makeAtom({ assertion: "new atom" })], + total: 1, + }); + mocks.entities + .mockReturnValueOnce(oldEntities.promise) + .mockResolvedValueOnce({ + items: [makeEntity({ canonical_name: "new entity" })], + }); + await act(async () => { + mocks.createProps!.onSuccess(); + mocks.createProps!.onSuccess(); + }); + await act(async () => { + oldAtoms.resolve({ + items: [makeAtom({ assertion: "old atom" })], + total: 1, + }); + oldEntities.resolve({ + items: [makeEntity({ canonical_name: "old entity" })], + }); + }); + expect(screen.getByText("new atom")).toBeInTheDocument(); + expect(screen.getByTestId("entities")).toHaveTextContent(/^new entity$/); + }); + + it("clears the selected atom and create modal, and ignores callbacks from a prior A visit", async () => { + mocks.atoms.mockResolvedValue({ + items: [makeAtom({ assertion: "visible atom" })], + total: 1, + }); + const { rerender } = render(); + await act(async () => {}); + fireEvent.click(screen.getByText("visible atom")); + fireEvent.click(screen.getByRole("button", { name: "编辑这条记忆" })); + const editSuccess = mocks.edit.mock.calls[0][0].onSuccess; + const oldCreateSuccess = mocks.createProps!.onSuccess; + const oldCreateClose = mocks.createProps!.onClose; + fireEvent.click(screen.getByRole("button", { name: "新建记忆" })); + expect(mocks.createProps!.open).toBe(true); + await act(async () => rerender()); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(mocks.createProps!.open).toBe(false); + expect(mocks.destroyAction).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByRole("button", { name: "新建记忆" })); + act(() => oldCreateClose()); + expect(mocks.createProps!.open).toBe(true); + await act(async () => rerender()); + const atomCalls = mocks.atoms.mock.calls.length; + const entityCalls = mocks.entities.mock.calls.length; + await act(async () => { + editSuccess(makeAtom({ assertion: "obsolete edit" })); + oldCreateSuccess(); + }); + expect(mocks.atoms).toHaveBeenCalledTimes(atomCalls); + expect(mocks.entities).toHaveBeenCalledTimes(entityCalls); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }); + + it("destroys the deprecation confirmation when the list unmounts", async () => { + mocks.atoms.mockResolvedValue({ + items: [makeAtom({ assertion: "visible atom" })], + total: 1, + }); + const { unmount } = render(); + await act(async () => {}); + fireEvent.click(screen.getByText("visible atom")); + fireEvent.click(screen.getByRole("button", { name: "弃用这条记忆" })); + expect(mocks.deprecate).toHaveBeenCalledOnce(); + unmount(); + expect(mocks.destroyAction).toHaveBeenCalledOnce(); + }); + + it("refreshes the current filter when an edit started under the previous filter completes", async () => { + mocks.atoms.mockResolvedValue({ + items: [makeAtom({ assertion: "visible atom" })], + total: 1, + }); + render(); + await act(async () => {}); + fireEvent.click(screen.getByText("visible atom")); + fireEvent.click(screen.getByRole("button", { name: "编辑这条记忆" })); + const editSuccess = mocks.edit.mock.calls[0][0].onSuccess; + await act(async () => + fireEvent.change(screen.getAllByRole("combobox")[0], { + target: { value: "Fact" }, + }), + ); + const calls = mocks.atoms.mock.calls.length; + await act(async () => editSuccess(makeAtom())); + expect(mocks.atoms).toHaveBeenCalledTimes(calls + 1); + expect(mocks.atoms).toHaveBeenLastCalledWith( + "A", + expect.objectContaining({ candidate_type: "Fact" }), + ); + }); +}); + +describe("Candidate action completion", () => { + it.each(["resolve", "reject"] as const)( + "ignores obsolete promote %s after A/B/A", + async (outcome) => { + const pending = deferred(); + mocks.promote.mockReturnValue(pending.promise); + mocks.candidates.mockResolvedValue({ + items: [makeCandidate()], + total: 1, + }); + const { rerender } = render(); + await act(async () => {}); + fireEvent.click(screen.getByText("confirm action")); + await act(async () => rerender()); + await act(async () => rerender()); + const calls = mocks.candidates.mock.calls.length; + await act(async () => { + if (outcome === "resolve") + pending.resolve({ merged: 0, promoted: 1, needs_review: 0 }); + else pending.reject(new Error("old promote")); + }); + expect(mocks.candidates).toHaveBeenCalledTimes(calls); + expect(mocks.success).not.toHaveBeenCalled(); + expect(mocks.error).not.toHaveBeenCalled(); + }, + ); + + it("does not let A's rejection close B's pending rejection modal", async () => { + const old = deferred(); + const current = deferred(); + mocks.reject + .mockReturnValueOnce(old.promise) + .mockReturnValueOnce(current.promise); + mocks.candidates.mockResolvedValue({ items: [makeCandidate()], total: 1 }); + const { rerender } = render(); + await act(async () => {}); + fireEvent.click(screen.getByRole("button", { name: /忽\s*略/ })); + fireEvent.click(screen.getByText("confirm reject")); + await act(async () => rerender()); + expect(screen.queryByTestId("reject-modal")).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: /忽\s*略/ })); + fireEvent.click(screen.getByText("confirm reject")); + const calls = mocks.candidates.mock.calls.length; + await act(async () => old.resolve({})); + expect(screen.getByTestId("reject-modal")).toHaveAttribute( + "data-loading", + "true", + ); + expect(mocks.candidates).toHaveBeenCalledTimes(calls); + expect(mocks.success).not.toHaveBeenCalled(); + await act(async () => current.resolve({})); + expect(screen.queryByTestId("reject-modal")).not.toBeInTheDocument(); + expect(mocks.candidates).toHaveBeenLastCalledWith("B", expect.anything()); + }); + + it("finishes an in-agent rejection and refreshes the latest filter", async () => { + const pending = deferred(); + mocks.reject.mockReturnValue(pending.promise); + mocks.candidates.mockResolvedValue({ items: [makeCandidate()], total: 1 }); + render(); + await act(async () => {}); + fireEvent.click(screen.getByRole("button", { name: /忽\s*略/ })); + fireEvent.click(screen.getByText("confirm reject")); + await act(async () => + fireEvent.change(screen.getAllByRole("combobox")[0], { + target: { value: "promoted" }, + }), + ); + const calls = mocks.candidates.mock.calls.length; + await act(async () => pending.resolve({})); + expect(screen.queryByTestId("reject-modal")).not.toBeInTheDocument(); + expect(mocks.candidates).toHaveBeenCalledTimes(calls + 1); + expect(mocks.candidates).toHaveBeenLastCalledWith( + "A", + expect.objectContaining({ status: "promoted" }), + ); + }); +}); + +describe("Conversation list actions", () => { + it("clears the selection and desktop page on agent change; ignores the old delete", async () => { + const pending = deferred(); + mocks.removeThread.mockReturnValue(pending.promise); + mocks.threads.mockResolvedValue([ + { + thread_id: "same-id", + title: "visible thread", + channel_type: "web", + created_at: 1, + last_active: 2, + }, + ]); + const { rerender } = render(); + await act(async () => {}); + await act(async () => + fireEvent.click(screen.getByRole("button", { name: "common.view" })), + ); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + fireEvent.click(screen.getByText("page 2")); + expect(screen.getByTestId("page")).toHaveTextContent(/^2$/); + fireEvent.click(screen.getByRole("button", { name: "common.delete" })); + render(<>{mocks.confirmDelete.mock.calls[0][0].footer}); + await act(async () => + fireEvent.click( + screen.getByRole("button", { name: "chat.deleteSessionOnly" }), + ), + ); + await act(async () => rerender()); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(screen.getByTestId("page")).toHaveTextContent(/^1$/); + await act(async () => pending.resolve({})); + expect(screen.getByText("visible thread")).toBeInTheDocument(); + expect(mocks.success).not.toHaveBeenCalled(); + }); +}); diff --git a/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx b/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx index d07ac38d48..b513f04e5a 100644 --- a/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx +++ b/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx @@ -35,6 +35,7 @@ import MemorySettings from "./MemorySettings"; import StrongMemory from "./StrongMemory"; import memoryDashboardApi from "../../../api/modules/memoryDashboard"; +import { useAgent } from "../../../context/AgentContext"; import styles from "./index.module.less"; type MemoryTab = @@ -136,11 +137,24 @@ export interface MemoryPanelProps { fill?: boolean; } +/** Memory tabs. Managed experts use the same pages; memory stays off until enabled. */ +export function memoryTabsForKind( + kind: string | null | undefined, +): readonly TabDef[] { + void kind; + return TABS; +} + export default function MemoryPanel({ agentId, fill = true, }: MemoryPanelProps) { const { t } = useTranslation(); + const { agents } = useAgent(); + const agentKind = agents.find((agent) => agent.agent_id === agentId)?.kind; + const tabs = useMemo(() => memoryTabsForKind(agentKind), [agentKind]); + const conversationsOnly = + tabs.length === 1 && tabs[0]?.key === "conversations"; const [activeTab, setActiveTab] = useState("overview"); const [libraryView, setLibraryView] = useState("tree"); @@ -151,7 +165,7 @@ export default function MemoryPanel({ const [expandKey, setExpandKey] = useState(0); useEffect(() => { - if (!agentId) { + if (!agentId || conversationsOnly) { setPendingCount(0); return; } @@ -167,7 +181,7 @@ export default function MemoryPanel({ return () => { cancelled = true; }; - }, [agentId, activeTab]); + }, [agentId, activeTab, conversationsOnly]); const tabItems = useMemo(() => { if (!agentId) return []; @@ -224,7 +238,7 @@ export default function MemoryPanel({
); - return TABS.map((tab) => { + return tabs.map((tab) => { const showBadge = tab.showPendingBadge && pendingCount > 0; const label = ( @@ -310,7 +324,7 @@ export default function MemoryPanel({ return { key: tab.key, label, children }; }); - }, [agentId, expandEntityId, expandKey, libraryView, pendingCount, t]); + }, [agentId, expandEntityId, expandKey, libraryView, pendingCount, t, tabs]); if (!agentId) { return ( @@ -325,7 +339,7 @@ export default function MemoryPanel({ setActiveTab(k as MemoryTab)} destroyOnHidden items={tabItems} diff --git a/dashboard/src/pages/Agent/Memory/RawEventsList.tsx b/dashboard/src/pages/Agent/Memory/RawEventsList.tsx index 18411a9d1a..bf06848133 100644 --- a/dashboard/src/pages/Agent/Memory/RawEventsList.tsx +++ b/dashboard/src/pages/Agent/Memory/RawEventsList.tsx @@ -8,7 +8,7 @@ * pipeline card hint on the Overview tab. */ -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useState } from "react"; import { Input, Select, Space, Tag, Typography } from "antd"; import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; @@ -20,6 +20,7 @@ import { } from "../../../api/modules/memoryDashboard"; import MemoryLayerView from "./shared/MemoryLayerView"; import MemoryPipelineEmpty from "./shared/MemoryPipelineEmpty"; +import { useMemoryRequestGate } from "./shared/useMemoryRequestGate"; import { useServerTimezone } from "../../../hooks/useServerTimezone"; import { formatServerIsoDateTime } from "../../../utils/formatMessageTime"; @@ -78,8 +79,21 @@ export default function RawEventsList({ agentId }: Props) { const [eventType, setEventType] = useState(""); const [query, setQuery] = useState(""); const [selected, setSelected] = useState(null); + const listGate = useMemoryRequestGate( + JSON.stringify([agentId, page, eventType, query]), + ); + + useLayoutEffect(() => { + setItems([]); + setTotal(0); + setPage(1); + setLoading(Boolean(agentId)); + setSelected(null); + }, [agentId]); const load = useCallback(async () => { + const isCurrent = listGate.begin(); + if (!isCurrent) return; setLoading(true); const body: ListRawEventsBody = { offset: (page - 1) * PAGE_SIZE, @@ -89,12 +103,15 @@ export default function RawEventsList({ agentId }: Props) { if (query.trim()) body.query = query.trim(); try { const r = await memoryDashboardApi.listRawEvents(agentId, body); + if (!isCurrent()) return; setItems(r.items); setTotal(r.total); + } catch (error) { + if (isCurrent()) throw error; } finally { - setLoading(false); + if (isCurrent()) setLoading(false); } - }, [agentId, page, eventType, query]); + }, [agentId, page, eventType, query, listGate]); useEffect(() => { if (!agentId) return; diff --git a/dashboard/src/pages/Agent/Memory/memoryTabsForKind.test.ts b/dashboard/src/pages/Agent/Memory/memoryTabsForKind.test.ts new file mode 100644 index 0000000000..c3c17c2c06 --- /dev/null +++ b/dashboard/src/pages/Agent/Memory/memoryTabsForKind.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { memoryTabsForKind } from "./MemoryPanel"; + +describe("memoryTabsForKind", () => { + it("keeps the full memory dashboard for a managed expert", () => { + const keys = memoryTabsForKind("managed").map((tab) => tab.key); + expect(keys).toContain("settings"); + expect(keys).toContain("conversations"); + expect(keys.length).toBeGreaterThan(1); + }); + + it("keeps the full memory dashboard for other experts", () => { + const keys = memoryTabsForKind("expert").map((tab) => tab.key); + expect(keys).toContain("overview"); + expect(keys).toContain("conversations"); + expect(keys.length).toBeGreaterThan(1); + }); +}); diff --git a/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx b/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx index 533f87546d..0aafbaf242 100644 --- a/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx +++ b/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx @@ -36,6 +36,7 @@ interface Props { /** When set, lock the form to this existing topic. */ presetEntityId?: string; onClose: () => void; + isActive?: () => boolean; onSuccess?: ( atom: AtomItem, entity: EntityItem, @@ -50,6 +51,7 @@ export default function CreateAtomModal({ presetEntityId, onClose, onSuccess, + isActive = () => true, }: Props) { const { t } = useTranslation(); const [form] = Form.useForm(); @@ -85,7 +87,9 @@ export default function CreateAtomModal({ cancelText={t("common.cancel", "取消")} destroyOnHidden onOk={async () => { + if (!isActive()) return; const values = await form.validateFields(); + if (!isActive()) return; const assertion = String(values.assertion || "").trim(); try { const body = @@ -102,10 +106,12 @@ export default function CreateAtomModal({ kind: values.kind as AtomKind, }; const r = await memoryDashboardApi.createAtom(agentId, body); + if (!isActive()) return; message.success(t("memory.create.success", "记忆已添加")); onSuccess?.(r.atom, r.entity, r.created_entity); onClose(); } catch (e) { + if (!isActive()) return; message.error( t("memory.create.failed", { message: (e as Error).message ?? e, diff --git a/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx b/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx index 6fecc9ab5a..51a279d35b 100644 --- a/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx +++ b/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx @@ -18,14 +18,16 @@ export function confirmDeprecateAtom({ agentId, atom, onSuccess, + isActive = () => true, }: { agentId: string; atom: AtomItem; /** Callback after successful deprecation, usually to close drawer and refresh list. */ onSuccess?: () => void; + isActive?: () => boolean; }) { let reason = ""; - modal.confirm({ + return modal.confirm({ title: i18n.t("memory.deprecate.title"), content: (
@@ -45,13 +47,16 @@ export function confirmDeprecateAtom({ okType: "danger", cancelText: i18n.t("common.cancel"), onOk: async () => { + if (!isActive()) return; try { await memoryDashboardApi.deprecateAtom(agentId, atom.id, { reason: reason || undefined, }); + if (!isActive()) return; message.success(i18n.t("memory.deprecate.success")); onSuccess?.(); } catch (e) { + if (!isActive()) return; message.error( i18n.t("memory.deprecate.failed", { message: (e as Error).message ?? e, diff --git a/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx b/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx index 730098c630..0c7a3acb9a 100644 --- a/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx +++ b/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx @@ -14,13 +14,15 @@ export function confirmEditAtom({ agentId, atom, onSuccess, + isActive = () => true, }: { agentId: string; atom: AtomItem; onSuccess?: (next: AtomItem) => void; + isActive?: () => boolean; }) { let assertion = atom.assertion; - Modal.confirm({ + return Modal.confirm({ title: i18n.t("memory.edit.title"), width: 520, content: ( @@ -40,6 +42,7 @@ export function confirmEditAtom({ okText: i18n.t("memory.edit.ok"), cancelText: i18n.t("common.cancel"), onOk: async () => { + if (!isActive()) return; const text = assertion.trim(); if (!text) { message.error(i18n.t("memory.edit.empty")); @@ -49,9 +52,11 @@ export function confirmEditAtom({ const r = await memoryDashboardApi.replaceAtom(agentId, atom.id, { assertion: text, }); + if (!isActive()) return; message.success(i18n.t("memory.edit.success")); onSuccess?.(r.atom); } catch (e) { + if (!isActive()) return; message.error( i18n.t("memory.edit.failed", { message: (e as Error).message ?? e, diff --git a/dashboard/src/pages/Agent/Memory/shared/useMemoryRequestGate.ts b/dashboard/src/pages/Agent/Memory/shared/useMemoryRequestGate.ts new file mode 100644 index 0000000000..e15633b9d8 --- /dev/null +++ b/dashboard/src/pages/Agent/Memory/shared/useMemoryRequestGate.ts @@ -0,0 +1,31 @@ +import { useLayoutEffect, useMemo } from "react"; +import { createDetailRequestGate } from "../../../../utils/detailRequestGate"; + +/** Own requests by a committed memory view, including repeated visits to it. */ +export function useMemoryRequestGate(scopeKey: string) { + const scope = useMemo( + () => ({ scopeKey, active: false, gate: createDetailRequestGate() }), + [scopeKey], + ); + + useLayoutEffect(() => { + scope.active = true; + return () => { + scope.active = false; + scope.gate.begin(); + }; + }, [scope]); + + return useMemo( + () => ({ + isActive: () => scope.active, + begin: () => { + // An old mutation callback must not start a new request for its view. + if (!scope.active) return null; + const requestId = scope.gate.begin(); + return () => scope.active && scope.gate.isCurrent(requestId); + }, + }), + [scope], + ); +} diff --git a/dashboard/src/pages/Agent/Personalization/index.tsx b/dashboard/src/pages/Agent/Personalization/index.tsx index acdbeb5584..425901149a 100644 --- a/dashboard/src/pages/Agent/Personalization/index.tsx +++ b/dashboard/src/pages/Agent/Personalization/index.tsx @@ -102,17 +102,31 @@ export default function PersonalizationPage() { `personalization.tabs.${activeTab}`, )}`; const showTeams = activeTab === "memory" || activeTab === "channels"; + const hideManaged = activeTab === "mbti"; const expertOnlyBlocked = isTeamAgent(activeAgent) && !showTeams; + const managedAgent = activeAgent?.kind === "managed"; const teamNeedsExpert = t("agentSelector.teamNeedsExpert", { name: activeAgent?.name ?? "", defaultValue: "当前是团队「{{name}}」,此页请选择专家", }); + const managedNeedsExpert = t("agentSelector.managedNeedsExpert", { + name: activeAgent?.name ?? "", + defaultValue: "当前是托管专家「{{name}}」,此页请选择其他专家", + }); const expertOnly = (node: ReactNode) => expertOnlyBlocked ? ( ) : ( node ); + const withoutManaged = (node: ReactNode) => + expertOnlyBlocked ? ( + + ) : managedAgent ? ( + + ) : ( + node + ); return ( @@ -165,7 +180,7 @@ export default function PersonalizationPage() { > {expertOnly(
- +
, )}
@@ -215,21 +230,21 @@ export default function PersonalizationPage() { style={{ display: activeTab === "mbti" ? "flex" : "none" }} aria-hidden={activeTab !== "mbti"} > - {!activeAgentId || expertOnlyBlocked ? ( + {!activeAgentId ? ( ) : ( -
- -
+ withoutManaged( +
+ +
, + ) )}
)} diff --git a/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx b/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx index e8965ecf45..c2bf654487 100644 --- a/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx +++ b/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx @@ -86,6 +86,8 @@ interface ToolsPanelProps { agentId: string | null; /** Which tool source to show. Defaults to built-in. */ source?: "builtin" | "plugin"; + /** Managed experts only list tools Octop can attach. */ + managed?: boolean; } /** @@ -94,6 +96,7 @@ interface ToolsPanelProps { export default function ToolsPanel({ agentId, source = "builtin", + managed = false, }: ToolsPanelProps) { const { t } = useTranslation(); const [loading, setLoading] = useState(false); @@ -472,7 +475,9 @@ export default function ToolsPanel({ return (
-

{t("toolSettings.hint")}

+

+ {t(managed ? "toolSettings.hintManaged" : "toolSettings.hint")} +

{builtinGroups.map((group) => (
diff --git a/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx b/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx index c323b5403a..44bd3c0b17 100644 --- a/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx +++ b/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx @@ -25,11 +25,16 @@ const TOOL_TABS: TabBarItem[] = [ interface ToolsTabsProps { agentId: string | null; + /** Managed experts only list tools Octop can attach, plus plugin tools. */ + managed?: boolean; } -export default function ToolsTabs({ agentId }: ToolsTabsProps) { +export default function ToolsTabs({ + agentId, + managed = false, +}: ToolsTabsProps) { const user = useCurrentUser(); - const canAcp = canAccessKeys(user, "admin"); + const canAcp = canAccessKeys(user, "admin") && !managed; const [activeTab, setActiveTab] = useState("builtin"); const tabs = useMemo( @@ -50,7 +55,7 @@ export default function ToolsTabs({ agentId }: ToolsTabsProps) { )} > {resolvedTab === "builtin" ? ( - + ) : resolvedTab === "plugin" ? ( ) : ( diff --git a/dashboard/src/pages/Chat/components/ChatInput.tsx b/dashboard/src/pages/Chat/components/ChatInput.tsx index c8fa024de1..bf167e6c8f 100644 --- a/dashboard/src/pages/Chat/components/ChatInput.tsx +++ b/dashboard/src/pages/Chat/components/ChatInput.tsx @@ -21,6 +21,7 @@ import { useSlashCommands } from "../../../hooks/useSlashCommands"; import SlashCommandMenu from "./SlashCommandMenu"; import { textAssistApi } from "../../../api/modules/textAssist"; import type { ChatAttachment } from "../hooks/useChat"; +import type { AcpSessionMode } from "../../../api/modules/acp"; import type { ResolvedModel } from "../../../api/types"; import type { KnowledgeBase } from "../../../api/modules/knowledgeBases"; import type { SkillSpec } from "../../Agent/Skills/useSkills"; @@ -112,6 +113,9 @@ interface ChatInputProps { ) => void; conversationMode?: "ask" | "plan" | "craft"; onConversationModeChange?: (mode: "ask" | "plan" | "craft") => void; + sessionModes?: AcpSessionMode[]; + sessionMode?: string; + onSessionModeChange?: (modeId: string) => void; hitlPolicy?: HitlSessionPolicy; onHitlPolicyChange?: (policy: HitlSessionPolicy) => void; /** Shared conversation: model, reasoning, mode, and approval stay with the owner. */ @@ -178,6 +182,9 @@ const ChatInput = forwardRef( onReasoningChange, conversationMode = "craft", onConversationModeChange, + sessionModes, + sessionMode, + onSessionModeChange, hitlPolicy, onHitlPolicyChange, lockThreadSettings = false, @@ -504,7 +511,7 @@ const ChatInput = forwardRef( locale: i18n.language, availableSkills, availableConnectors, - availableExperts: managed ? [] : availableExperts, + availableExperts, availableSubagents, agentId, selectedConnectors, @@ -515,6 +522,7 @@ const ChatInput = forwardRef( isStreaming, onSubmitRef: submitRef, enterToSend: !isMobile, + slashMenuEnabled: !managed, }); const skillTokenRefs = useMemo( @@ -1034,6 +1042,9 @@ const ChatInput = forwardRef( onReasoningChange={onReasoningChange} conversationMode={conversationMode} onConversationModeChange={onConversationModeChange} + sessionModes={sessionModes} + sessionMode={sessionMode} + onSessionModeChange={onSessionModeChange} hitlPolicy={hitlPolicy} onHitlPolicyChange={onHitlPolicyChange} lockThreadSettings={lockThreadSettings} @@ -1046,11 +1057,9 @@ const ChatInput = forwardRef( onKnowledgeBaseIdsChange={onKnowledgeBaseIdsChange} availableSkills={availableSkills} onInsertSkillCommand={insertSkillCommand} - availableExperts={ - managed - ? [] - : availableExperts.filter((a) => a.agent_id !== agentId) - } + availableExperts={availableExperts.filter( + (a) => a.agent_id !== agentId, + )} onInsertExpertMention={insertExpertMention} availableSubagents={availableSubagents} onInsertSubagentMention={insertSubagentMention} diff --git a/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx b/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx index eae61eca9e..6c40d918b6 100644 --- a/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx +++ b/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx @@ -89,6 +89,137 @@ describe("ChatInputActionsRow plus menu", () => { ); expect(screen.queryByTestId("context-window-ring")).not.toBeInTheDocument(); + expect(screen.getByTestId("managed-approval-picker")).toBeInTheDocument(); + expect(screen.queryByTestId("hitl-policy-picker")).not.toBeInTheDocument(); + }); + + it("keeps approval when the managed agent has no unattended mode", () => { + render( + + undefined} + sessionModes={[ + { + id: "build", + name_zh: "构建", + name_en: "Build", + hint_zh: "", + hint_en: "", + }, + { + id: "plan", + name_zh: "规划", + name_en: "Plan", + hint_zh: "", + hint_en: "", + }, + ]} + /> + , + ); + + expect(screen.getByTestId("managed-approval-picker")).toBeInTheDocument(); + expect( + screen.getByLabelText("chat.conversationMode.picker"), + ).toBeInTheDocument(); + }); + + it("hides approval when a session mode already skips it", () => { + render( + + undefined} + sessionModes={[ + { + id: "default", + name_zh: "默认", + name_en: "Default", + hint_zh: "", + hint_en: "", + }, + { + id: "bypassPermissions", + name_zh: "YOLO", + name_en: "YOLO", + hint_zh: "", + hint_en: "", + }, + ]} + /> + , + ); + + expect( + screen.queryByTestId("managed-approval-picker"), + ).not.toBeInTheDocument(); + }); + + it("keeps connector and knowledge pickers for a managed expert", () => { + render( + + undefined} + availableKnowledgeBases={[ + { + id: "kb1", + owner_user_id: 1, + name: "手册", + description: "", + default_open: false, + shared: false, + icon_name: "book", + embedding_model: "", + embedding_dim: 0, + doc_count: 0, + max_documents: 1, + created_at: 0, + updated_at: 0, + }, + ]} + selectedKnowledgeBaseIds={[]} + onKnowledgeBaseIdsChange={() => undefined} + /> + , + ); + + expect(screen.getByLabelText("connectors.chatPicker")).toBeInTheDocument(); + expect(screen.getByLabelText("chat.knowledgePicker")).toBeInTheDocument(); + expect(screen.queryByLabelText("Model")).not.toBeInTheDocument(); + }); + + it("keeps the expert picker for a managed expert", () => { + render( + + undefined} + /> + , + ); + + expect(screen.getByLabelText("chat.expertPicker")).toBeInTheDocument(); }); it("folds shortcut, upload, and polish into the plus menu when the composer is narrow", async () => { diff --git a/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx b/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx index d214b3fdef..9ab0202429 100644 --- a/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx +++ b/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx @@ -32,6 +32,11 @@ import { import { Tooltip, Popover } from "antd"; import cx from "classnames"; import { message } from "@/utils/antdMessage"; +import { + catalogOffersUnattendedMode, + type AcpSessionMode, +} from "../../../api/modules/acp"; +import { acpSessionModeText } from "../../../api/modules/acp"; import type { ResolvedModel } from "../../../api/types"; import type { KnowledgeBase } from "../../../api/modules/knowledgeBases"; import type { SkillSpec } from "../../Agent/Skills/useSkills"; @@ -53,6 +58,8 @@ import { conversationModeIcon, } from "./ConversationModePicker"; import HitlPolicyPicker from "./HitlPolicyPicker"; +import { SessionModeMenu, sessionModeIcon } from "./SessionModeMenu"; +import ManagedApprovalPicker from "./ManagedApprovalPicker"; import SlashCommandMenu from "./SlashCommandMenu"; import type { SlashMenuGroup } from "../../../utils/slashCategories"; import type { SlashMenuItem } from "../hooks/useSlashMentionInput"; @@ -160,6 +167,9 @@ interface ChatInputActionsRowProps { ) => void; conversationMode?: "ask" | "plan" | "craft"; onConversationModeChange?: (mode: "ask" | "plan" | "craft") => void; + sessionModes?: AcpSessionMode[]; + sessionMode?: string; + onSessionModeChange?: (modeId: string) => void; hitlPolicy?: HitlSessionPolicy; onHitlPolicyChange?: (policy: HitlSessionPolicy) => void; lockThreadSettings?: boolean; @@ -182,7 +192,7 @@ interface ChatInputActionsRowProps { slashPickerGroups: SlashMenuGroup[] | null; slashMenuItems: SlashMenuItem[]; onSlashShortcutSelect: (command: string) => void; - /** Hide mode, model, connectors, knowledge, experts, and shortcuts. */ + /** Hide mode, model, and shortcuts. Experts, subagents, connectors, and knowledge stay. */ managed?: boolean; onFileSelect: () => void; onFolderSelect: () => void; @@ -226,6 +236,9 @@ export default function ChatInputActionsRow({ onReasoningChange, conversationMode = "craft", onConversationModeChange, + sessionModes, + sessionMode = "", + onSessionModeChange, hitlPolicy, onHitlPolicyChange, lockThreadSettings = false, @@ -253,7 +266,7 @@ export default function ChatInputActionsRow({ onCancel, onSubmit, }: ChatInputActionsRowProps) { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); const settingsLockedHint = lockThreadSettings ? t("chat.threadSettingsOwnerOnly", "只有会话创建人可以改模型和审批设置") : undefined; @@ -359,22 +372,21 @@ export default function ChatInputActionsRow({ !managed && Boolean(availableModels && availableModels.length > 0 && onModelChange); const allowWriteTools = conversationMode === "craft"; - const showConnectorPicker = - !managed && - Boolean(allowWriteTools && availableConnectors && onConnectorsChange); - const showKnowledgePicker = - !managed && Boolean(availableKnowledgeBases && onKnowledgeBaseIdsChange); + const showConnectorPicker = Boolean( + allowWriteTools && availableConnectors && onConnectorsChange, + ); + const showKnowledgePicker = Boolean( + availableKnowledgeBases && onKnowledgeBaseIdsChange, + ); const showSkillPicker = Boolean( allowWriteTools && availableSkills && onInsertSkillCommand, ); - const showExpertPicker = - !managed && - Boolean( - allowWriteTools && - availableExperts && - onInsertExpertMention && - availableExperts.length > 0, - ); + const showExpertPicker = Boolean( + allowWriteTools && + availableExperts && + onInsertExpertMention && + availableExperts.length > 0, + ); const showSubagentPicker = Boolean( allowWriteTools && availableSubagents && @@ -396,7 +408,13 @@ export default function ChatInputActionsRow({ [availableSkills, skillDisplayName], ); const activeSkillSlugs = parseSkillSlugsInText(text, skillTokenRefs); - const showModePicker = !managed && Boolean(onConversationModeChange); + const showManagedModes = + managed && (sessionModes?.length ?? 0) > 0 && Boolean(onSessionModeChange); + const showModePicker = + showManagedModes || (!managed && Boolean(onConversationModeChange)); + const activeSessionMode = sessionModes?.find( + (mode) => mode.id === sessionMode, + ); const polishDisabled = !text.trim() || polishing || isStreaming || disabled || !agentId; const overflowKeys = ( @@ -460,7 +478,7 @@ export default function ChatInputActionsRow({ expert: t("chat.expertPicker"), subagent: t("chat.subagentPicker"), shortcut: t("shortcut.title", "快捷指令"), - upload: t("upload.tooltip", "Upload"), + upload: t("upload.action", "Upload"), }; const reasoningModel = availableModels?.find( @@ -765,7 +783,9 @@ export default function ChatInputActionsRow({
); - const ModeIcon = conversationModeIcon(conversationMode); + const ModeIcon = showManagedModes + ? sessionModeIcon(sessionMode) + : conversationModeIcon(conversationMode); const renderPlusMenu = () => (
@@ -788,7 +808,11 @@ export default function ChatInputActionsRow({ - {t(`chat.conversationMode.${conversationMode}`)} + {showManagedModes + ? activeSessionMode + ? acpSessionModeText(activeSessionMode, i18n.language, "name") + : sessionMode + : t(`chat.conversationMode.${conversationMode}`)} @@ -951,7 +975,7 @@ export default function ChatInputActionsRow({ > - {t("upload.tooltip", "Upload")} + {t("upload.action", "Upload")} @@ -1074,7 +1098,17 @@ export default function ChatInputActionsRow({ const renderPickerBody = (key: CompactPickerKey) => { switch (key) { case "mode": - return ( + return showManagedModes ? ( + { + onSessionModeChange?.(modeId); + closePlusMenu(); + }} + /> + ) : ( { @@ -1277,14 +1311,24 @@ export default function ChatInputActionsRow({ )} - {onHitlPolicyChange && ( + {onHitlPolicyChange && + managed && + !catalogOffersUnattendedMode(sessionModes ?? []) ? ( + + ) : null} + {onHitlPolicyChange && !managed ? ( - )} + ) : null} {!useCompactControls && !managed && ( ); - return {avatar}; + return ( + + {avatar} + + ); } diff --git a/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx b/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx index 43d8a846bc..6f40b62994 100644 --- a/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx +++ b/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx @@ -8,6 +8,7 @@ import SearchablePickerPanel, { } from "../../../components/ChatPicker/SearchablePickerPanel"; import { message } from "@/utils/antdMessage"; import ExpertAgentAvatar, { type ChatAgentOption } from "./ExpertAgentAvatar"; +import { incomingShareProps } from "../../../components/SharedResourceBadge"; import RemoteExpertHint from "./RemoteExpertHint"; import { SharedResourceBadge } from "../../../components/SharedResourceBadge"; import { groupExpertsByConnection } from "../../../utils/remoteExpert"; @@ -164,6 +165,7 @@ export default function ExpertPickerPopover({ size={32} iconSize={18} managedRunner={agent.managed_runner} + {...incomingShareProps(agent)} /> {agent.name} diff --git a/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx b/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx index 71fd7ebf6f..2444c4bfd7 100644 --- a/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx +++ b/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx @@ -4,6 +4,7 @@ import { useAgent } from "../../../context/AgentContext"; import { isTeamAgent, isTeamHostSpeaker } from "../../../utils/teamAgent"; import { rewritePeerSpeakerId } from "../../../utils/remoteExpert"; import { managedRunnerId } from "../../Experts/components/ManagedAvatarMark"; +import { incomingShareProps } from "../../../components/SharedResourceBadge"; import { ExpertMessageAvatar } from "./MessageSender"; import styles from "../index.module.less"; @@ -62,6 +63,7 @@ function GeneratingAvatar({ agentId }: { agentId?: string | null }) { tooltip={avatarTooltip} profileAgentId={avatarProfileId} managedRunner={managedRunnerId(expert)} + {...incomingShareProps(expert)} />
); diff --git a/dashboard/src/pages/Chat/components/ManagedApprovalPicker.tsx b/dashboard/src/pages/Chat/components/ManagedApprovalPicker.tsx new file mode 100644 index 0000000000..640062b5a5 --- /dev/null +++ b/dashboard/src/pages/Chat/components/ManagedApprovalPicker.tsx @@ -0,0 +1,97 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { ShieldAlert, ShieldOff } from "lucide-react"; +import { Popover, Tooltip } from "antd"; +import cx from "classnames"; +import type { HitlSessionPolicy } from "../utils/hitlSessionPolicy"; +import styles from "../index.module.less"; + +interface ManagedApprovalPickerProps { + policy: HitlSessionPolicy; + onChange: (policy: HitlSessionPolicy) => void; + disabled?: boolean; + disabledHint?: string; +} + +/** Approval switch for a chat whose replies come from an external agent. */ +export default function ManagedApprovalPicker({ + policy, + onChange, + disabled = false, + disabledHint, +}: ManagedApprovalPickerProps) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const yolo = policy.mode === "allow_all"; + const triggerLabel = yolo + ? t("chat.managedApproval.yolo") + : t("chat.managedApproval.ask"); + + const choose = (next: HitlSessionPolicy) => { + onChange(next); + setOpen(false); + }; + + return ( + + + +
+ } + > + + + + + ); +} diff --git a/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx b/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx index 15cc64eeed..ff88cb015d 100644 --- a/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx +++ b/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx @@ -11,6 +11,7 @@ import { type WorkspaceMentionHint, } from "../utils/fileMention"; import ExpertAgentAvatar from "./ExpertAgentAvatar"; +import { incomingShareProps } from "../../../components/SharedResourceBadge"; import styles from "../index.module.less"; export type MentionAgentOption = ChatAgentOption; @@ -205,6 +206,7 @@ export default function MentionPickerMenu({ size={20} iconSize={11} managedRunner={agent?.managed_runner} + {...incomingShareProps(agent)} /> ); } diff --git a/dashboard/src/pages/Chat/components/MessageBubble.tsx b/dashboard/src/pages/Chat/components/MessageBubble.tsx index 74ad0020c3..9baf677386 100644 --- a/dashboard/src/pages/Chat/components/MessageBubble.tsx +++ b/dashboard/src/pages/Chat/components/MessageBubble.tsx @@ -40,6 +40,7 @@ import { prepareSpeechText } from "../../../utils/plainTextForSpeech"; import { chatStreamErrorAction, formatChatStreamError, + isChatStreamError, } from "../../../utils/chatStreamError"; import { MessageFileCard } from "./MessageFileCard"; import AskQuestionCard from "./AskQuestionCard"; @@ -49,6 +50,7 @@ import { } from "./ConnectorAuthAction"; import HitlApprovalCard from "./HitlApprovalCard"; import { managedRunnerId } from "../../Experts/components/ManagedAvatarMark"; +import { incomingShareProps } from "../../../components/SharedResourceBadge"; import MessageSender, { ExpertMessageAvatar } from "./MessageSender"; import { useCurrentUser } from "../../../hooks/useCurrentUser"; import { useAgent } from "../../../context/AgentContext"; @@ -746,7 +748,9 @@ function MessageBubble({ isUser && !isEditing && hasUserComposerTags(message.composerContext); const isStreaming = message.status === "streaming"; const hasToolData = !!message.toolData; - const isError = message.status === "error"; + const isError = + message.status === "error" || + (!isUser && !hasToolData && isChatStreamError(textContent)); const errorSource = isError ? message.errorInfo?.message?.trim() || textContent : textContent; @@ -848,6 +852,7 @@ function MessageBubble({ tooltip={avatarTooltip} profileAgentId={avatarProfileId} managedRunner={managedRunnerId(expert)} + {...incomingShareProps(expert)} /> ) : null; diff --git a/dashboard/src/pages/Chat/components/MessageSender.tsx b/dashboard/src/pages/Chat/components/MessageSender.tsx index 2cbbee1d32..abf0439849 100644 --- a/dashboard/src/pages/Chat/components/MessageSender.tsx +++ b/dashboard/src/pages/Chat/components/MessageSender.tsx @@ -36,6 +36,9 @@ interface ExpertMessageAvatarProps { profileAgentId?: string | null; /** ACP runner shown at the avatar's bottom-right. */ managedRunner?: string | null; + shared?: boolean; + owned?: boolean; + ownerName?: string | null; } export function ExpertMessageAvatar({ @@ -46,6 +49,9 @@ export function ExpertMessageAvatar({ tooltip, profileAgentId, managedRunner, + shared, + owned, + ownerName, }: ExpertMessageAvatarProps) { const { t } = useTranslation(); const profile = useChatAgentProfile(); @@ -58,6 +64,9 @@ export function ExpertMessageAvatar({ color={color} size={MESSAGE_AVATAR_SIZE} managedRunner={managedRunner} + shared={shared} + owned={owned} + ownerName={ownerName} /> ); diff --git a/dashboard/src/pages/Chat/components/SessionModeMenu.tsx b/dashboard/src/pages/Chat/components/SessionModeMenu.tsx new file mode 100644 index 0000000000..d7b0962074 --- /dev/null +++ b/dashboard/src/pages/Chat/components/SessionModeMenu.tsx @@ -0,0 +1,70 @@ +import { + Hammer, + ListTodo, + MessageCircleQuestion, + ShieldOff, + type LucideIcon, +} from "lucide-react"; +import cx from "classnames"; +import { + acpSessionModeText, + isUnattendedSessionMode, + type AcpSessionMode, +} from "../../../api/modules/acp"; +import styles from "../index.module.less"; + +export function sessionModeIcon(modeId: string): LucideIcon { + const folded = modeId.toLowerCase(); + if (isUnattendedSessionMode(modeId)) { + return ShieldOff; + } + if (folded.includes("plan")) return ListTodo; + if ( + folded.includes("read-only") || + folded.includes("readonly") || + folded === "default" || + folded.includes("ask") + ) { + return MessageCircleQuestion; + } + return Hammer; +} + +export function SessionModeMenu({ + modes, + modeId, + language, + onChange, +}: { + modes: AcpSessionMode[]; + modeId: string; + language: string; + onChange: (modeId: string) => void; +}) { + return ( +
+ {modes.map((mode) => { + const Icon = sessionModeIcon(mode.id); + return ( + + ); + })} +
+ ); +} diff --git a/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx b/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx index dd5118e1f3..ff25dc07fd 100644 --- a/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx +++ b/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx @@ -7,6 +7,7 @@ import { useToolRendererVersion } from "../../../plugins/toolRenderers"; import AssistantProcessSummary from "./AssistantProcessSummary"; import { ToolDetailsInline } from "./MessageBubble"; import { managedRunnerId } from "../../Experts/components/ManagedAvatarMark"; +import { incomingShareProps } from "../../../components/SharedResourceBadge"; import { ExpertMessageAvatar } from "./MessageSender"; import { useAgent } from "../../../context/AgentContext"; import { isTeamAgent, isTeamHostSpeaker } from "../../../utils/teamAgent"; @@ -90,6 +91,7 @@ export function TurnProcessBlocks({ tooltip={avatarTooltip} profileAgentId={avatarProfileId} managedRunner={managedRunnerId(expert)} + {...incomingShareProps(expert)} />
) : null} diff --git a/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx b/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx index 63a1dfed40..053f68f501 100644 --- a/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx +++ b/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx @@ -7,6 +7,7 @@ import { useSkillDisplayName } from "../../Agent/Skills/skillDisplayNames"; import type { KnowledgeBase } from "../../../api/modules/knowledgeBases"; import type { ChatAgentOption } from "./ExpertAgentAvatar"; import ExpertAgentAvatar from "./ExpertAgentAvatar"; +import { incomingShareProps } from "../../../components/SharedResourceBadge"; import { ConnectorLogo } from "../../Agent/Connectors/connectorDefs"; import { knowledgeIconForName } from "../../KnowledgeBases/knowledgeIcons"; import ContextChip, { type ContextChipVariant } from "./ContextChip"; @@ -114,6 +115,7 @@ export default function UserMessageComposerTags({ iconSize={9} muted managedRunner={agent?.managed_runner} + {...incomingShareProps(agent)} /> ), label: agent?.name || id, diff --git a/dashboard/src/pages/Chat/hooks/chatStore.ts b/dashboard/src/pages/Chat/hooks/chatStore.ts index c95479d9ec..7829997c09 100644 --- a/dashboard/src/pages/Chat/hooks/chatStore.ts +++ b/dashboard/src/pages/Chat/hooks/chatStore.ts @@ -3186,6 +3186,7 @@ async function sendTurnWebSocket( conversationMode?: "ask" | "plan" | "craft" | null, hitlPolicy?: { mode: string; tools?: string[] } | null, clientMessageId?: string | null, + sessionMode?: string | null, ): Promise { const state = getOrCreate(sessionId); const resolvedThreadId = (threadId || sessionId).trim(); @@ -3269,6 +3270,7 @@ async function sendTurnWebSocket( if (reasoningMode) payload.reasoning_mode = reasoningMode; if (reasoningEffort) payload.reasoning_effort = reasoningEffort; if (conversationMode) payload.conversation_mode = conversationMode; + if (sessionMode) payload.session_mode = sessionMode; if (hitlPolicy) payload.hitl_policy = hitlPolicy; ws.send(JSON.stringify(payload)); }; @@ -3501,6 +3503,7 @@ export async function sendTurn( conversationMode?: "ask" | "plan" | "craft" | null, hitlPolicy?: { mode: string; tools?: string[] } | null, clientMessageId?: string | null, + sessionMode?: string | null, ): Promise { const state = getOrCreate(sessionId); rememberRoomAgent(state, agentId); @@ -3607,6 +3610,7 @@ export async function sendTurn( conversationMode, hitlPolicy, clientMessageId, + sessionMode, ); if (!wsOk) { state.messages = [ diff --git a/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts b/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts index 02d8a5a108..08f9a1c078 100644 --- a/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts +++ b/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts @@ -11,6 +11,16 @@ describe("preferToolName", () => { expect(preferToolName("Web Search", "unknown")).toBe("Web Search"); }); + it("keeps write_file when a later ACP title reuses the call", () => { + expect( + preferToolName( + "Write /home/wally/GWN3MS/random_7f3a9c.txt", + "write_file", + ), + ).toBe("write_file"); + expect(preferToolName("edit_file", "Write notes.md")).toBe("edit_file"); + }); + it("treats only a blank or unknown name as a placeholder", () => { expect(isPlaceholderToolName("unknown")).toBe(true); expect(isPlaceholderToolName("Web Search")).toBe(false); diff --git a/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts b/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts index e3fc3c9120..d4939d812f 100644 --- a/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts +++ b/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts @@ -4,6 +4,7 @@ */ import { useTranslation } from "react-i18next"; +import { isFileToolName } from "../constants"; /** Names the harness invents when an ACP update did not include a title. */ export function isPlaceholderToolName(name?: string): boolean { @@ -11,14 +12,20 @@ export function isPlaceholderToolName(name?: string): boolean { return !text || text === "unknown"; } -/** Keep a real tool name. A later ``unknown`` update must not replace it. */ +/** Keep a real tool name. A later ``unknown`` update must not replace it. + +ACP file edits are stored as ``write_file`` / ``edit_file`` and then again +under the agent title (``Write /path``). The file card only recognizes the +native name, so that title must not replace it. +*/ export function preferToolName( incoming?: string, current?: string, ): string | undefined { const next = incoming?.trim(); - if (!isPlaceholderToolName(next)) return next; const prev = current?.trim(); + if (isFileToolName(prev) && !isFileToolName(next)) return prev; + if (!isPlaceholderToolName(next)) return next; return prev || next; } diff --git a/dashboard/src/pages/Chat/hooks/useChat.ts b/dashboard/src/pages/Chat/hooks/useChat.ts index 875e649783..a4e97a176f 100644 --- a/dashboard/src/pages/Chat/hooks/useChat.ts +++ b/dashboard/src/pages/Chat/hooks/useChat.ts @@ -34,6 +34,7 @@ import { import { injectPendingHitlMessage } from "../../../utils/injectPendingHitlMessage"; import { mergeHistoryWithLocalTail, + preserveLocalComposerContext, preferLocalTranscript, restoreUnpersistedTurn, serverCaughtUp, @@ -542,12 +543,22 @@ function convertCallEntries(entries: CallEntry[]): ChatMessage[] { current.toolData?.name, existing.toolData?.name, ); - if (name && name !== existing.toolData?.name) { + const existingArgs = existing.toolData?.arguments?.trim() ?? ""; + const incomingArgs = current.toolData?.arguments?.trim() ?? ""; + const argumentsJson = + !existingArgs || existingArgs === "{}" + ? incomingArgs || existing.toolData?.arguments + : existing.toolData?.arguments; + if ( + (name && name !== existing.toolData?.name) || + argumentsJson !== existing.toolData?.arguments + ) { merged[existingIdx] = { ...existing, toolData: { ...existing.toolData, - name, + name: name || existing.toolData?.name, + arguments: argumentsJson, displayName: isPlaceholderToolName(current.toolData?.name) ? existing.toolData?.displayName : current.toolData?.displayName || @@ -828,6 +839,7 @@ async function loadThreadHistory( syncSessionArtifacts, syncSessionConversationMode, syncSessionHitlPolicy, + syncSessionMode, } = await import("./useSessions"); const limit = params.limit ?? CHAT_HISTORY_PAGE_SIZE; const offset = params.offset ?? 0; @@ -851,6 +863,7 @@ async function loadThreadHistory( history.pending_plan_path, ); syncSessionHitlPolicy(threadId, history.hitl_policy); + syncSessionMode(threadId, history.session_mode); chatStore.setPendingPlanPath(threadId, history.pending_plan_path); } const messages = injectPendingHitlMessage( @@ -1025,6 +1038,7 @@ export function useChat( reasoningEffort?: string | null, conversationMode?: "ask" | "plan" | "craft" | null, hitlPolicy?: HitlSessionPolicy | null, + sessionMode?: string | null, ) => { const key = storeKey || stableSessionId; @@ -1070,6 +1084,7 @@ export function useChat( conversationMode, hitlPolicy, userMsg.id, + sessionMode, ); }, [currentUser, stableSessionId], @@ -1170,10 +1185,13 @@ export function useChat( retainedHistoryPrefix(loaded.messages, current.messages).length > 0; chatStore.setHistoryPage( key, - mergeHistoryWithLocalTail( - loaded.messages, + preserveLocalComposerContext( + mergeHistoryWithLocalTail( + loaded.messages, + local, + current.isStreaming, + ), local, - current.isStreaming, ), { hasMore: keptOlder ? current.historyHasMore : loaded.hasMore, @@ -1339,7 +1357,10 @@ export function useChat( retainedHistoryPrefix(latest, current.messages).length > 0; chatStore.setHistoryPage( key, - mergeHistoryWithLocalTail(latest, local, current.isStreaming), + preserveLocalComposerContext( + mergeHistoryWithLocalTail(latest, local, current.isStreaming), + local, + ), { hasMore: keptOlder ? current.historyHasMore : hasMore, nextOffset: keptOlder ? current.historyNextOffset : nextOffset, diff --git a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts index e3f2c2ce16..754ab21296 100644 --- a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts +++ b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts @@ -12,6 +12,8 @@ import type { ResolvedModel } from "../../../api/types"; import { CONNECTORS_CHANGED_EVENT } from "../../Agent/Connectors/customMcpUtils"; import { useCurrentUser } from "../../../hooks/useCurrentUser"; import { useAgent } from "../../../context/AgentContext"; +import { useAcpSessionModes } from "../../../hooks/useAcpSessionModes"; +import { isUnattendedSessionMode } from "../../../api/modules/acp"; import { activeModelToRef } from "./useChatContextWindow"; import { hasSavedConnectors, @@ -31,6 +33,7 @@ import { isPendingThread, syncSessionConversationMode, syncSessionHitlPolicy, + syncSessionMode, } from "./useSessions"; import { isTeamAgent } from "../../../utils/teamAgent"; import * as chatStore from "./chatStore"; @@ -69,6 +72,7 @@ export function useChatComposerResources( stickyReasoningEffort?: string | null, stickyConversationMode?: ConversationMode | null, stickyHitlPolicy?: HitlSessionPolicy | null, + stickySessionMode?: string | null, persistThreadSettings = true, ) { const user = useCurrentUser(); @@ -78,6 +82,19 @@ export function useChatComposerResources( const expertDefaultMode = parseConversationMode( expert?.config?.conversation_mode, ); + const expertYolo = + expert?.kind === "managed" && + expert.config?.managed_permission_mode === "yolo"; + const managedRunner = + expert?.kind === "managed" && + typeof expert.config?.managed_runner === "string" + ? expert.config.managed_runner + : ""; + const sessionModes = useAcpSessionModes(managedRunner); + const pinnedSessionMode = + typeof expert?.config?.managed_session_mode === "string" + ? expert.config.managed_session_mode.trim() + : ""; const teamHost = isTeamAgent(expert); const bridgeConnectionId = expert?.bridge && expert.bridge_connection_id @@ -140,6 +157,7 @@ export function useChatComposerResources( const [hitlPolicy, setHitlPolicy] = useState( DEFAULT_HITL_SESSION_POLICY, ); + const [sessionMode, setSessionMode] = useState(""); const [conversationOverrides, setConversationOverrides] = useState< Record< string, @@ -230,10 +248,36 @@ export function useChatComposerResources( useEffect(() => { setHitlPolicy( isNewSession - ? DEFAULT_HITL_SESSION_POLICY + ? expertYolo + ? { mode: "allow_all" } + : DEFAULT_HITL_SESSION_POLICY : parseHitlSessionPolicy(stickyHitlPolicy), ); - }, [isNewSession, stickyHitlPolicy, activeThreadId]); + }, [isNewSession, stickyHitlPolicy, activeThreadId, expertYolo]); + + const expertSessionMode = + pinnedSessionMode || + (expertYolo + ? sessionModes.find((mode) => isUnattendedSessionMode(mode.id))?.id ?? "" + : "") || + sessionModes[0]?.id || + ""; + + useEffect(() => { + if (expert?.kind !== "managed") { + setSessionMode(""); + return; + } + const sticky = + !isNewSession && stickySessionMode ? stickySessionMode.trim() : ""; + setSessionMode(sticky || expertSessionMode); + }, [ + expert?.kind, + isNewSession, + stickySessionMode, + activeThreadId, + expertSessionMode, + ]); useEffect(() => { if (agentsLoading) return; @@ -670,6 +714,28 @@ export function useChatComposerResources( [activeThreadId, persistThreadSettings, resolvedAgentId], ); + const handleSessionModeChange = useCallback( + (modeId: string) => { + const next = modeId.trim(); + if (!next) return; + setSessionMode(next); + if (activeThreadId) { + syncSessionMode(activeThreadId, next); + } + if ( + persistThreadSettings && + resolvedAgentId && + activeThreadId && + !isPendingThread(activeThreadId) + ) { + void octopThreadsApi.patch(resolvedAgentId, activeThreadId, { + session_mode: next, + }); + } + }, + [activeThreadId, persistThreadSettings, resolvedAgentId], + ); + return { selectedModel, setSelectedModel: handleModelChange, @@ -680,6 +746,9 @@ export function useChatComposerResources( handleConversationModeChange, hitlPolicy, handleHitlPolicyChange, + sessionModes, + sessionMode, + handleSessionModeChange, selectedConnectors, selectedKnowledgeBaseIds, chatConnectors, diff --git a/dashboard/src/pages/Chat/hooks/useChatSend.ts b/dashboard/src/pages/Chat/hooks/useChatSend.ts index 5ebccbec27..ae485e0c23 100644 --- a/dashboard/src/pages/Chat/hooks/useChatSend.ts +++ b/dashboard/src/pages/Chat/hooks/useChatSend.ts @@ -29,6 +29,7 @@ interface UseChatSendParams { reasoningMode: "auto" | "enabled" | "disabled"; reasoningEffort: string | null; conversationMode?: "ask" | "plan" | "craft"; + sessionMode?: string; hitlPolicy?: HitlSessionPolicy; defaultModel?: string | null; sendMessage: ( @@ -46,6 +47,7 @@ interface UseChatSendParams { reasoningEffort?: string | null, conversationMode?: "ask" | "plan" | "craft" | null, hitlPolicy?: HitlSessionPolicy | null, + sessionMode?: string | null, ) => void; createSession: () => { session: Session; resolvedId: Promise }; /** Called when auto-recording starts successfully from a pending message. */ @@ -79,6 +81,7 @@ export function useChatSend({ reasoningMode, reasoningEffort, conversationMode = "craft", + sessionMode, hitlPolicy, defaultModel, sendMessage, @@ -155,6 +158,7 @@ export function useChatSend({ composerContext?.reasoningEffort ?? reasoningEffort, mode, policy, + sessionMode, ); }; @@ -210,6 +214,7 @@ export function useChatSend({ mode, policy, userMsg.id, + sessionMode, ); navigate(`/chat/${agent}/${tid}`, { replace: true }); }); @@ -228,6 +233,7 @@ export function useChatSend({ reasoningMode, reasoningEffort, conversationMode, + sessionMode, hitlPolicy, defaultModel, t, diff --git a/dashboard/src/pages/Chat/hooks/useSessions.ts b/dashboard/src/pages/Chat/hooks/useSessions.ts index 1804af4d4b..495a2a4d93 100644 --- a/dashboard/src/pages/Chat/hooks/useSessions.ts +++ b/dashboard/src/pages/Chat/hooks/useSessions.ts @@ -25,6 +25,7 @@ export interface Session { reasoningMode?: "auto" | "enabled" | "disabled" | null; reasoningEffort?: string | null; conversationMode?: "ask" | "plan" | "craft" | null; + sessionMode?: string | null; pendingPlanPath?: string | null; hitlPolicy?: HitlSessionPolicy | null; artifacts?: ThreadArtifact[]; @@ -52,6 +53,7 @@ export function toSession(row: { reasoning_mode?: "auto" | "enabled" | "disabled" | null; reasoning_effort?: string | null; conversation_mode?: "ask" | "plan" | "craft" | null; + session_mode?: string | null; pending_plan_path?: string | null; hitl_policy?: HitlSessionPolicy | null; artifacts?: Array | null; @@ -85,6 +87,7 @@ export function toSession(row: { reasoningMode: row.reasoning_mode ?? null, reasoningEffort: row.reasoning_effort ?? null, conversationMode: row.conversation_mode ?? null, + sessionMode: row.session_mode ?? null, pendingPlanPath: row.pending_plan_path ?? null, hitlPolicy: row.hitl_policy ? parseHitlSessionPolicy(row.hitl_policy) @@ -179,6 +182,23 @@ export function syncSessionHitlPolicy( }); } +/** Patch the managed agent's session mode for one thread. */ +export function syncSessionMode( + threadId: string, + mode: string | null | undefined, +) { + if (!threadId) return; + const nextMode = mode?.trim() || null; + setModuleSessions((prev) => { + const idx = prev.findIndex((s) => s.id === threadId); + if (idx < 0) return prev; + if ((prev[idx].sessionMode ?? null) === nextMode) return prev; + const next = [...prev]; + next[idx] = { ...prev[idx], sessionMode: nextMode }; + return next; + }); +} + /** Patch conversation-mode fields for one thread in the module session store. */ export function syncSessionConversationMode( threadId: string, diff --git a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts index df0699047a..80974f3d37 100644 --- a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts +++ b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts @@ -78,6 +78,35 @@ describe("useSlashMentionInput skills", () => { }); }); +describe("useSlashMentionInput managed composer", () => { + it("does not open the shortcut menu when slash shortcuts are disabled", () => { + const { result } = renderHook(() => + useSlashMentionInput({ + text: "", + setText: vi.fn(), + textareaRef: { current: null }, + slashCommands: [stopCommand], + labelFor: (spec) => spec.label_en, + locale: "en", + availableExperts: [], + selectedConnectors: [], + onSend: vi.fn(), + onNewChat: vi.fn(), + onCancel: vi.fn(), + isStreaming: false, + onSubmitRef: { current: vi.fn() }, + slashMenuEnabled: false, + }), + ); + + act(() => { + result.current.handleTextChange("/st"); + }); + + expect(result.current.slashMenuOpen).toBe(false); + }); +}); + describe("useSlashMentionInput workspace files", () => { it("keeps empty @ as a hint-only file section and inserts the workspace path", () => { const setText = vi.fn(); diff --git a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts index fdee4e8c7c..2c21394c9e 100644 --- a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts +++ b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts @@ -66,6 +66,8 @@ interface UseSlashMentionInputParams { onSubmitRef: React.MutableRefObject<() => void>; /** When false, Enter inserts a newline; send only via button (mobile). */ enterToSend?: boolean; + /** Managed experts keep typed slash text, but do not open the shortcut menu. */ + slashMenuEnabled?: boolean; } export function useSlashMentionInput({ @@ -88,6 +90,7 @@ export function useSlashMentionInput({ isStreaming: _isStreaming, onSubmitRef, enterToSend = true, + slashMenuEnabled = true, }: UseSlashMentionInputParams) { const skillDisplayName = useSkillDisplayName(); const skillTokenRefs = useMemo( @@ -364,8 +367,12 @@ export function useSlashMentionInput({ (val: string) => { setText(val); if (isSlashNamePrefix(val)) { - setSlashMenuOpen(true); - setSlashMenuIndex(0); + if (slashMenuEnabled) { + setSlashMenuOpen(true); + setSlashMenuIndex(0); + } else { + setSlashMenuOpen(false); + } setMentionMenuOpen(false); } else { setSlashMenuOpen(false); @@ -392,9 +399,14 @@ export function useSlashMentionInput({ mentionAgents.length, availableSubagents.length, agentId, + slashMenuEnabled, ], ); + useEffect(() => { + if (!slashMenuEnabled) setSlashMenuOpen(false); + }, [slashMenuEnabled]); + const handleKeyDown = useCallback( (e: KeyboardEvent) => { if (e.nativeEvent.isComposing || e.keyCode === 229) return; diff --git a/dashboard/src/pages/Chat/index.tsx b/dashboard/src/pages/Chat/index.tsx index 081d0f8190..36ba3c3102 100644 --- a/dashboard/src/pages/Chat/index.tsx +++ b/dashboard/src/pages/Chat/index.tsx @@ -597,6 +597,9 @@ function ChatPageInner() { handleConversationModeChange, hitlPolicy, handleHitlPolicyChange, + sessionModes, + sessionMode, + handleSessionModeChange, handleConnectorsChange, handleKnowledgeBaseIdsChange, } = useChatComposerResources( @@ -607,6 +610,7 @@ function ChatPageInner() { composerSession?.reasoningEffort, composerSession?.conversationMode, composerSession?.hitlPolicy, + composerSession?.sessionMode, composerSession?.owned !== false, ); @@ -742,6 +746,7 @@ function ChatPageInner() { reasoningMode, reasoningEffort, conversationMode, + sessionMode, hitlPolicy, defaultModel: activeAgent?.default_model ?? null, sendMessage, @@ -1671,11 +1676,7 @@ function ChatPageInner() { onOpenBrowser={ hasBrowserTool ? openBrowserTab : undefined } - onEditFile={ - !sharedExpertViewer && panelFilePaths.length > 0 - ? openFileList - : undefined - } + onEditFile={sharedExpertViewer ? undefined : openFileList} /> @@ -1974,9 +1975,14 @@ function ChatPageInner() { onReasoningChange={handleReasoningChange} conversationMode={conversationMode} onConversationModeChange={handleConversationModeChange} + sessionModes={sessionModes} + sessionMode={sessionMode} + onSessionModeChange={handleSessionModeChange} hitlPolicy={hitlPolicy} onHitlPolicyChange={ - hitlEnabled ? handleComposerHitlPolicyChange : undefined + hitlEnabled || isManagedChat + ? handleComposerHitlPolicyChange + : undefined } lockThreadSettings={composerSession?.owned === false} availableConnectors={isTeamChat ? undefined : chatConnectors} diff --git a/dashboard/src/pages/Chat/utils/deleteConversation.tsx b/dashboard/src/pages/Chat/utils/deleteConversation.tsx index 3e3a5f1eed..f2498913c5 100644 --- a/dashboard/src/pages/Chat/utils/deleteConversation.tsx +++ b/dashboard/src/pages/Chat/utils/deleteConversation.tsx @@ -34,17 +34,20 @@ export async function deleteConversation( threadId: string, compact: boolean, t: TFunction, + isActive: () => boolean = () => true, ): Promise { + if (!isActive()) return false; const closeLoading = compact ? antMessage.loading(t("chat.deleteSessionCompacting"), 0) : undefined; try { const result = await octopThreadsApi.delete(agentId, threadId, compact); if (typeof closeLoading === "function") closeLoading(); - antMessage.success(deleteResultText(t, compact, result)); + if (isActive()) antMessage.success(deleteResultText(t, compact, result)); return true; } catch (error) { if (typeof closeLoading === "function") closeLoading(); + if (!isActive()) return false; if (parseApiError(error)?.code === "THREAD_TURN_ACTIVE") { antMessage.error(t("apiErrors.THREAD_TURN_ACTIVE")); return null; @@ -68,7 +71,7 @@ export function confirmDeleteConversation( | DeleteConversationResult | void | Promise, -): void { +): ReturnType { const mobile = typeof window !== "undefined" && window.innerWidth < MOBILE_BREAKPOINT; let inflight = false; @@ -133,4 +136,5 @@ export function confirmDeleteConversation( ), }); handle.destroy = opened.destroy; + return opened; } diff --git a/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts b/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts index 027539de19..cdcf513874 100644 --- a/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts +++ b/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts @@ -182,6 +182,45 @@ export function retainedHistoryPrefix( : []; } +/** Keep chips the live bubble already showed when the stored row omitted them. */ +export function preserveLocalComposerContext( + loaded: ChatMessage[], + local: ChatMessage[], +): ChatMessage[] { + const byId = new Map(); + for (const message of local) { + if (message.role === "user" && message.composerContext) { + byId.set(message.id, message.composerContext); + } + } + if (byId.size === 0) return loaded; + return loaded.map((message) => { + if (message.role !== "user") return message; + const previous = byId.get(message.id); + if (!previous) return message; + const server = message.composerContext; + if (!server) return { ...message, composerContext: previous }; + return { + ...message, + composerContext: { + skills: server.skills?.length ? server.skills : previous.skills, + connectors: server.connectors?.length + ? server.connectors + : previous.connectors, + knowledgeBaseIds: server.knowledgeBaseIds?.length + ? server.knowledgeBaseIds + : previous.knowledgeBaseIds, + targetAgents: server.targetAgents?.length + ? server.targetAgents + : previous.targetAgents, + model: server.model || previous.model, + reasoningMode: server.reasoningMode || previous.reasoningMode, + reasoningEffort: server.reasoningEffort || previous.reasoningEffort, + }, + }; + }); +} + /** * Apply a server history page without dropping a turn the user just sent. * diff --git a/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less b/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less index a635c31d5f..403fbdd5e9 100644 --- a/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less +++ b/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less @@ -22,7 +22,7 @@ align-items: center; min-height: 34px; padding: 7px 12px; - font-size: 11px; + font-size: 12px; color: #55708f; background: linear-gradient(100deg, #f4f9ff, #f8fbff 52%, #f5f8fd); border: 1px solid #dfe9f7; @@ -75,7 +75,7 @@ align-items: center; justify-content: space-between; margin-bottom: 8px; - font-size: 11px; + font-size: 12px; color: #788190; } @@ -118,14 +118,14 @@ gap: 6px; align-items: center; margin-top: 9px; - font-size: 11px; + font-size: 12px; color: #9aa2af; white-space: nowrap; } .miniTag { padding: 1px 5px; - font-size: 11px; + font-size: 12px; color: #29a17d; background: #eef8f3; border-radius: 4px; @@ -203,7 +203,7 @@ .panelSub { margin: 3px 0 0; - font-size: 11px; + font-size: 12px; color: #9aa2af; } @@ -214,7 +214,7 @@ .count { padding: 1px 5px; font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; color: #a0a8b4; border: 1px solid #e9ecf0; border-radius: 4px; @@ -232,7 +232,7 @@ .segmented button { padding: 4px 10px; - font-size: 11px; + font-size: 12px; line-height: 1.3; color: #8a92a0; white-space: nowrap; @@ -278,7 +278,7 @@ align-items: center; justify-content: space-between; margin-bottom: 8px; - font-size: 11px; + font-size: 12px; color: #677182; } @@ -298,7 +298,7 @@ .regionTotal { font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; color: #a7aeba; white-space: nowrap; } @@ -319,7 +319,7 @@ min-width: 0; padding: 0; font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; cursor: pointer; border: 1px solid transparent; border-radius: 4px; @@ -374,7 +374,7 @@ gap: 11px; align-items: center; padding: 10px 16px; - font-size: 11px; + font-size: 12px; color: #8b94a2; border-top: 1px solid #f0f2f5; } @@ -435,7 +435,7 @@ .trendEmpty { padding: 28px 0; - font-size: 11px; + font-size: 12px; color: var(--fn-text-quaternary); text-align: center; } @@ -444,7 +444,7 @@ display: flex; gap: 13px; padding: 0 16px 6px; - font-size: 11px; + font-size: 12px; color: #8590a0; } @@ -493,7 +493,7 @@ grid-template-columns: 96px minmax(0, 1fr) 42px; gap: 8px; align-items: center; - font-size: 11px; + font-size: 12px; color: #8a94a3; } @@ -515,7 +515,7 @@ .resourceName i { font-style: normal; - font-size: 10px; + font-size: 12px; color: #b0b8c4; } @@ -536,7 +536,7 @@ .resourceNumber { font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; color: #9099a7; text-align: right; } @@ -552,7 +552,7 @@ .alertCount { padding: 2px 6px; - font-size: 11px; + font-size: 12px; font-weight: 600; color: #c64756; background: #fdefef; @@ -567,7 +567,7 @@ .table { width: 100%; min-width: 560px; - font-size: 12px; + font-size: 13px; text-align: left; border-collapse: collapse; } @@ -575,7 +575,7 @@ .table th { height: 28px; padding: 0 10px; - font-size: 11px; + font-size: 12px; font-weight: 400; color: #a0a8b5; background: #fafbfc; @@ -605,7 +605,7 @@ align-items: center; padding: 0; font-family: var(--sc-mono); - font-size: 12px; + font-size: 13px; color: #4e5a6e; cursor: pointer; background: none; @@ -628,7 +628,7 @@ } .cellMain { - font-size: 12px; + font-size: 13px; font-weight: 500; color: #657083; } @@ -636,13 +636,13 @@ .cellSub { margin-top: 1px; font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; color: #adb4bf; } .metricNumber { font-family: var(--sc-mono); - font-size: 12px; + font-size: 13px; color: #7a8495; } @@ -668,7 +668,7 @@ .softBadge { padding: 3px 6px; - font-size: 11px; + font-size: 12px; font-weight: 500; color: #7a8290; background: #f5f6f8; @@ -731,13 +731,13 @@ display: flex; gap: 5px; justify-content: space-between; - font-size: 12px; + font-size: 13px; color: #747f90; } .eventTime { font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; color: #a7afbb; white-space: nowrap; } @@ -745,7 +745,7 @@ .eventDesc { margin-top: 1px; font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; color: #a4acb8; } @@ -758,7 +758,7 @@ gap: 10px; align-items: center; padding: 0 2px 2px; - font-size: 11px; + font-size: 12px; color: #a1a9b6; } @@ -783,7 +783,7 @@ gap: 7px; min-height: 80px; padding: 20px; - font-size: 11px; + font-size: 12px; color: #a0a8b4; grid-column: 1 / -1; } @@ -862,7 +862,7 @@ .summaryBand { flex-wrap: wrap; - font-size: 11px; + font-size: 12px; } .bandTime { diff --git a/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.module.less b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.module.less new file mode 100644 index 0000000000..bd38c9f43b --- /dev/null +++ b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.module.less @@ -0,0 +1,246 @@ +/* 地域选择器:触发器沿用工具栏输入框的尺寸,弹层参考腾讯云控制台的 + 「最近访问 + 全部地区」双段式布局。 */ + +.trigger { + display: inline-flex; + flex: 0 0 auto; + gap: 6px; + align-items: center; + min-width: 240px; + max-width: 360px; + height: 32px; + padding: 0 10px; + font-size: 14px; + color: var(--fn-text-primary); + cursor: pointer; + background: var(--fn-bg-primary); + border: 1px solid var(--fn-border-secondary); + border-radius: 8px; + transition: + border-color 0.15s ease, + box-shadow 0.15s ease; +} + +.trigger:hover:not(:disabled) { + border-color: var(--fn-color-brand); +} + +.trigger:focus-visible { + outline: 2px solid var(--fn-color-brand); + outline-offset: 1px; +} + +.triggerDisabled { + cursor: not-allowed; + opacity: 0.55; +} + +.triggerMain { + display: inline-flex; + align-items: baseline; + gap: 2px; + min-width: 0; + font-weight: 500; +} + +.triggerLabel { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* 选中地域的节点总数:与地名同色,只有后面那个红点强调"有节点" */ +.triggerCount { + font-size: 12px; + font-variant-numeric: tabular-nums; + color: inherit; +} + +.triggerDot { + flex: 0 0 auto; + align-self: flex-start; + width: 4px; + height: 4px; + margin: 3px 0 0 2px; + background: var(--fn-color-danger); + border-radius: 50%; +} + +.triggerRest { + flex: 0 0 auto; + font-size: 13px; + color: var(--fn-text-tertiary); + white-space: nowrap; +} + +.triggerRest::before { + padding-right: 6px; + color: var(--fn-border-secondary); + content: "|"; +} + +.caret { + flex: 0 0 auto; + margin-left: auto; + color: var(--fn-text-tertiary); + transition: transform 0.15s ease; +} + +.caretOpen { + transform: rotate(180deg); +} + +.popover { + /* 弹层自己控内边距,antd 默认的 12px 会把两段式布局压扁 */ +} + +.popover :global(.ant-popover-inner) { + padding: 0; + border-radius: 12px; + box-shadow: 0 14px 38px + color-mix(in srgb, var(--fn-text-primary) 16%, transparent); +} + +.body { + box-sizing: border-box; + width: min(1060px, calc(100vw - 32px)); + max-height: min(76vh, 680px); + padding: 16px 24px 20px; + overflow: auto; +} + +.section { + padding-bottom: 16px; +} + +.sectionTitle { + margin-bottom: 16px; + font-size: 14px; + font-weight: 600; + color: var(--fn-text-primary); +} + +/* 最近访问与下面的大区共用同一套列宽,视觉上对齐到同一栅格 */ +.recentRow { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(128px, 1fr)); + column-gap: 24px; + row-gap: 8px; +} + +/* 报纸式多栏流:大区块按列往下排,短列表不会独占一整行留白。 + 列宽取 128px 保证最长地名(7 个汉字)不截断。 */ +.areas { + column-width: 128px; + column-gap: 24px; + column-fill: balance; +} + +.area { + margin-bottom: 18px; + break-inside: avoid; + page-break-inside: avoid; +} + +/* 层级对比是"清晰"的关键:地域名用主色,大区标题刻意压浅, + 跟控制台一样靠颜色深浅区分两级,而不是靠字号。 */ +.areaTitle { + margin-bottom: 14px; + font-size: 12px; + font-weight: 400; + color: var(--fn-text-tertiary); +} + +.areaItems { + display: flex; + flex-direction: column; + gap: 6px; +} + +.item { + display: inline-flex; + align-self: flex-start; + align-items: baseline; + max-width: 100%; + padding: 5px 10px; + font-size: 14px; + line-height: 22px; + color: var(--fn-text-primary); + text-align: left; + cursor: pointer; + background: transparent; + border: 0; + border-radius: 6px; + transition: + background 0.12s ease, + color 0.12s ease; +} + +.item:hover { + color: var(--fn-text-primary); + background: var(--fn-bg-hover); +} + +.item:focus-visible { + outline: 2px solid var(--fn-color-brand); + outline-offset: -2px; +} + +.itemActive { + font-weight: 500; + color: var(--fn-text-primary); + background: var(--fn-bg-selected, var(--fn-bg-hover)); +} + +.itemName { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* 地域下的节点数:与地名同色(继承父级),红点只用来标记"这个地域有节点" */ +.itemCount { + margin-left: 3px; + font-size: 11px; + font-variant-numeric: tabular-nums; + color: inherit; +} + +.itemDot { + flex: 0 0 auto; + align-self: flex-start; + width: 4px; + height: 4px; + margin: 6px 0 0 3px; + background: var(--fn-color-danger); + border-radius: 50%; +} + +.footer { + display: flex; + gap: 8px; + align-items: center; + justify-content: space-between; + padding: 8px 6px 2px; + margin-top: 6px; + border-top: 1px solid var(--fn-border-primary); +} + +.footerText { + font-size: 12px; + color: var(--fn-text-tertiary); +} + +.clearBtn { + padding: 2px 6px; + font-size: 12px; + color: var(--fn-text-brand); + cursor: pointer; + background: transparent; + border: 0; + border-radius: 4px; +} + +.clearBtn:hover { + background: var(--fn-bg-hover); +} diff --git a/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.tsx b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.tsx new file mode 100644 index 0000000000..f12764d03d --- /dev/null +++ b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.tsx @@ -0,0 +1,286 @@ +import { useCallback, useMemo, useState } from "react"; +import { Popover } from "antd"; +import cx from "classnames"; +import { ChevronDown } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import styles from "./RegionPicker.module.less"; + +export type CloudRegion = { id: string; name: string }; + +interface RegionPickerProps { + regions: CloudRegion[]; + /** 每个地域的节点数(`region` → 实例数量)。 */ + counts: Record; + /** 已选地域 id,空数组表示"全部地域"。 */ + value: string[]; + onChange: (next: string[]) => void; + disabled?: boolean; +} + +interface RegionItem { + id: string; + short: string; + area: string; + count: number; +} + +const RECENT_KEY = "octop:cloud:recent-regions"; +const RECENT_MAX = 6; + +/** 大区排序:与腾讯云控制台地域选择器一致,未命中的排在末尾。 */ +const AREA_ORDER = [ + "华南地区", + "华东地区", + "华北地区", + "华中地区", + "西南地区", + "西北地区", + "东北地区", + "港澳台地区", + "亚太东南", + "亚太东北", + "亚太南部", + "欧洲地区", + "北美地区", + "南美地区", + "中东地区", + "非洲地区", +]; + +/** "华南地区(广州 OPEN)" → { area: "华南地区", short: "广州 OPEN" } */ +function parseRegionName( + name: string, + id: string, +): { area: string; short: string } { + const match = /^\s*(.+?)\s*[((](.+?)[))]\s*$/.exec(name ?? ""); + if (match) { + return { area: match[1].trim(), short: match[2].trim() }; + } + return { area: "", short: (name || id).trim() }; +} + +function readRecent(): string[] { + try { + const raw = window.localStorage.getItem(RECENT_KEY); + if (!raw) return []; + const parsed = JSON.parse(raw); + return Array.isArray(parsed) + ? parsed.filter((item): item is string => typeof item === "string") + : []; + } catch { + return []; + } +} + +function writeRecent(ids: string[]) { + try { + window.localStorage.setItem(RECENT_KEY, JSON.stringify(ids)); + } catch { + // 隐私模式 / 配额满:只是便利功能,失败不影响筛选 + } +} + +export default function RegionPicker({ + regions, + counts, + value, + onChange, + disabled = false, +}: RegionPickerProps) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [recent, setRecent] = useState(readRecent); + + const items = useMemo( + () => + regions.map((region) => { + const { area, short } = parseRegionName(region.name, region.id); + return { id: region.id, short, area, count: counts[region.id] ?? 0 }; + }), + [regions, counts], + ); + + const groups = useMemo(() => { + const map = new Map(); + for (const item of items) { + const bucket = map.get(item.area); + if (bucket) bucket.push(item); + else map.set(item.area, [item]); + } + return [...map.entries()] + .map(([area, list]) => ({ + area, + label: area || t("cloud.regionOtherArea", "其他地区"), + items: list, + })) + .sort((a, b) => { + const ia = AREA_ORDER.indexOf(a.area); + const ib = AREA_ORDER.indexOf(b.area); + return ( + (ia < 0 ? AREA_ORDER.length : ia) - (ib < 0 ? AREA_ORDER.length : ib) + ); + }); + }, [items, t]); + + const recentItems = useMemo( + () => + recent + .map((id) => items.find((item) => item.id === id)) + .filter((item): item is RegionItem => Boolean(item)) + .slice(0, RECENT_MAX), + [recent, items], + ); + + const selected = useMemo( + () => items.filter((item) => value.includes(item.id)), + [items, value], + ); + const totalCount = useMemo( + () => items.reduce((sum, item) => sum + item.count, 0), + [items], + ); + const selectedCount = selected.reduce((sum, item) => sum + item.count, 0); + const restCount = Math.max(0, totalCount - selectedCount); + + const toggle = useCallback( + (id: string) => { + const next = value.includes(id) + ? value.filter((item) => item !== id) + : [...value, id]; + onChange(next); + setRecent((prev) => { + const merged = [id, ...prev.filter((item) => item !== id)].slice( + 0, + RECENT_MAX, + ); + writeRecent(merged); + return merged; + }); + }, + [onChange, value], + ); + + const triggerLabel = + selected.length === 0 + ? t("cloud.regionAll", "全部地域") + : selected.length === 1 + ? selected[0].short + : t("cloud.regionSelectedMulti", { + name: selected[0].short, + count: selected.length, + defaultValue: "{{name}} 等 {{count}} 个", + }); + + const renderItem = (item: RegionItem, extraClass?: string) => { + const active = value.includes(item.id); + return ( + + ); + }; + + const body = ( +
+ {recentItems.length > 0 ? ( +
+
+ {t("cloud.regionRecent", "最近访问")} +
+
+ {recentItems.map((item) => renderItem(item, styles.recentItem))} +
+
+ ) : null} + +
+
+ {t("cloud.regionAllAreas", "全部地区")} +
+
+ {groups.map((group) => ( +
+
{group.label}
+
+ {group.items.map((item) => renderItem(item))} +
+
+ ))} +
+
+ + {value.length > 0 ? ( +
+ + {t("cloud.regionSelectedTotal", { + count: value.length, + defaultValue: "已选 {{count}} 个地域", + })} + + +
+ ) : null} +
+ ); + + return ( + setOpen(disabled ? false : next)} + overlayClassName={styles.popover} + content={body} + arrow={false} + > + + + ); +} diff --git a/dashboard/src/pages/Control/CloudHosts/index.module.less b/dashboard/src/pages/Control/CloudHosts/index.module.less index 7370eedd3b..5cdd1957e1 100644 --- a/dashboard/src/pages/Control/CloudHosts/index.module.less +++ b/dashboard/src/pages/Control/CloudHosts/index.module.less @@ -84,7 +84,7 @@ align-items: center; padding: 3px 10px; font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; font-variant-numeric: tabular-nums; color: inherit; cursor: pointer; @@ -167,7 +167,7 @@ .overviewLabel { font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; opacity: 0.5; @@ -182,11 +182,13 @@ } .overviewHint { - font-size: 11px; + font-size: 12px; opacity: 0.45; } .sidebar { + /* RailEdgeControl 绝对定位的锚点:折叠手柄骑在右侧分隔线上 */ + position: relative; display: flex; flex: 0 0 196px; flex-direction: column; @@ -201,31 +203,8 @@ flex: 0 0 auto; gap: 4px; align-items: center; - font-size: 11px; - color: var(--fn-text-quaternary); -} - -.railBtn { - display: inline-flex; - flex: 0 0 auto; - align-items: center; - justify-content: center; - width: 24px; - height: 24px; - padding: 0; + font-size: 12px; color: var(--fn-text-quaternary); - cursor: pointer; - background: transparent; - border: 0; - border-radius: 6px; - transition: - background 0.12s ease, - color 0.12s ease; -} - -.railBtn:hover { - color: var(--fn-text-primary); - background: var(--fn-bg-secondary); } .sidebarHead { @@ -234,20 +213,18 @@ align-items: center; } +/* 标签统一走 12px 常规字体,不再用 mono + 全大写 + 低透明度的终端风, + 否则和页面其它文案放在一起显得忽大忽小、忽轻忽重。 */ .sidebarTitle { flex: 1; - font-family: var(--sc-mono); - font-size: 10px; - letter-spacing: 0.1em; - text-transform: uppercase; - opacity: 0.45; + font-size: 12px; + color: var(--fn-text-tertiary); } .sidebarCount { - font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; font-variant-numeric: tabular-nums; - opacity: 0.55; + color: var(--fn-text-tertiary); } .nodeList { @@ -348,7 +325,7 @@ .nodeName { overflow: hidden; - font-size: 12.5px; + font-size: 13px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; @@ -357,16 +334,16 @@ .nodeMeta { overflow: hidden; font-family: var(--sc-mono); - font-size: 10.5px; - opacity: 0.45; + font-size: 12px; + color: var(--fn-text-tertiary); text-overflow: ellipsis; white-space: nowrap; } .nodeEmpty { padding: 16px 4px; - font-size: 11px; - opacity: 0.45; + font-size: 12px; + color: var(--fn-text-tertiary); text-align: center; } @@ -405,7 +382,7 @@ .miniValue { font-family: var(--sc-mono); - font-size: 11px; + font-size: 12px; font-variant-numeric: tabular-nums; opacity: 0.7; } @@ -461,6 +438,8 @@ } .stage { + /* 折叠态下 RailEdgeControl 以此为锚点,手柄停在内容区左边缘 */ + position: relative; display: flex; flex: 1; flex-direction: row; @@ -469,6 +448,19 @@ min-height: 0; } +/* 折叠态:左侧没有独立面板可以挂边线,手柄整体内移几个像素, + 避免被 Workbench 面板的 overflow: hidden 裁掉一半。 */ +.railEdgeClosed { + left: 4px !important; + right: auto !important; + + /* 面板收起后这是唯一的展开入口,常驻可见,不等 hover */ + > button { + opacity: 1; + pointer-events: auto; + } +} + .main { display: flex; flex: 1; @@ -609,11 +601,8 @@ } .kpiLabel { - font-family: var(--sc-mono); - font-size: 10px; - letter-spacing: 0.14em; - text-transform: uppercase; - opacity: 0.5; + font-size: 12px; + color: var(--fn-text-tertiary); } .kpiValue { @@ -636,11 +625,9 @@ } .blockTitle { - font-family: var(--sc-mono); - font-size: 10px; - letter-spacing: 0.14em; - text-transform: uppercase; - opacity: 0.5; + font-size: 13px; + font-weight: 600; + color: var(--fn-text-primary); } .mono { @@ -652,17 +639,14 @@ /* ---- Terminal-flavoured table ---- */ .page :global(.octop-table) { - font-size: 12.5px; + font-size: 13px; } .page :global(.octop-table-thead > tr > th) { - font-family: var(--sc-mono); - font-size: 10px; + font-size: 12px; font-weight: 500; - letter-spacing: 0.1em; - text-transform: uppercase; + color: var(--fn-text-tertiary); background: transparent !important; - opacity: 0.6; } .page :global(.octop-table-tbody > tr > td) { @@ -671,8 +655,6 @@ .page :global(.octop-tag) { margin: 0; - font-family: var(--sc-mono); - font-size: 10px; - letter-spacing: 0.06em; + font-size: 12px; border-radius: 3px; } diff --git a/dashboard/src/pages/Control/CloudHosts/index.tsx b/dashboard/src/pages/Control/CloudHosts/index.tsx index 37233de220..a717ce852e 100644 --- a/dashboard/src/pages/Control/CloudHosts/index.tsx +++ b/dashboard/src/pages/Control/CloudHosts/index.tsx @@ -8,7 +8,6 @@ import { Modal, Popconfirm, Segmented, - Select, Space, Spin, Table, @@ -21,8 +20,6 @@ import { Info, KeyRound, LogIn, - PanelLeftClose, - PanelLeftOpen, PauseCircle, PlayCircle, RefreshCw, @@ -32,6 +29,7 @@ import { } from "lucide-react"; import { request } from "../../../api/request"; import { OctopEmptyMascot } from "../../../components/EmptyState"; +import RailEdgeControl from "../../../components/RailEdgeControl"; import StreamSetupGuide from "../../../components/StreamSetupGuide/StreamSetupGuide"; import { useCvmOpsExpert } from "../../../hooks/useCvmOpsExpert"; import { ALERT_MIN, WARN_MIN, levelTone } from "./theme"; @@ -47,6 +45,7 @@ import CloudOverviewBoard, { type BoardInstance, type TrendPoint, } from "./components/CloudOverviewBoard"; +import RegionPicker from "./components/RegionPicker"; import styles from "./index.module.less"; type CloudStatus = { @@ -187,8 +186,10 @@ function CredentialBadge({ onExpire(); }, [remaining, expiresAt, status?.authorized, onExpire]); + // 未授权时不再渲染「未授权」标签:空状态引导里已有完整说明, + // 工具栏再挂一个灰 Tag 只会干扰视线。 if (!status?.authorized) { - return {t("cloud.notAuthorized")}; + return null; } const critical = remaining <= 60; @@ -747,6 +748,15 @@ export default function CloudHostsPage({ ); }, [instances, keyword]); + // 每个地域的节点数:地域选择器要在名字后带上这个数字 + const regionCounts = useMemo(() => { + const out: Record = {}; + for (const row of instances) { + out[row.region] = (out[row.region] ?? 0) + 1; + } + return out; + }, [instances]); + // KPI 跟随搜索范围,避免"顶部写 486、左侧只剩 2 台"的口径不一致 const runningCount = filteredInstances.filter( (row) => row.state === "RUNNING", @@ -893,17 +903,11 @@ export default function CloudHostsPage({ onExpire={handleExpire} onRenew={() => void refreshCredential()} /> - @@ -466,11 +456,7 @@ export function JobDrawer({ { required: true, message: t("cronJobs.pleaseInputCron") }, ]} tooltip={t("cronJobs.form.cronTooltip")} - extra={ - - {t("cronJobs.form.cronExamples")} - - } + extra={t("cronJobs.form.cronExamples")} > - {t("cronJobs.form.connectorsHint")} - - } + extra={t("cronJobs.form.connectorsHint")} > {t("experts.memorySlimming")} )} - setMbtiCatalogOpen(true) : undefined} - /> + {agent.kind === "managed" ? null : ( + setMbtiCatalogOpen(true) : undefined + } + /> + )}
@@ -516,6 +520,7 @@ export const AgentCard = memo(function AgentCard({ setSkillCatalogOpen(true)} onSubagents={openSubagentCatalog} onTools={() => setToolSettingsOpen(true)} @@ -577,6 +582,7 @@ export const AgentCard = memo(function AgentCard({ /> setToolSettingsOpen(false)} /> diff --git a/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx b/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx index a3ef6de48e..a3c32d29fb 100644 --- a/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx +++ b/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx @@ -50,7 +50,11 @@ import { apiErrorMessage } from "../../../utils/apiError"; import styles from "../index.module.less"; import RemoteExpertHint from "../../Chat/components/RemoteExpertHint"; import { expertDeleteConfirm } from "../../../utils/remoteExpert"; -import { SharedResourceBadge } from "../../../components/SharedResourceBadge"; +import { + incomingShareProps, + SharedAvatarMark, + SharedResourceBadge, +} from "../../../components/SharedResourceBadge"; import { canManageExpert, canReadAgentRuntimeStatus, @@ -311,28 +315,30 @@ export default function AgentExpertsTable({ fixed: isMobile ? undefined : "left", render: (name: string, row) => (
- - + - - - + + + + + {name} ( - openMbtiCatalog(row.agent_id) - : undefined - } - /> - ), + render: (value: string | null, row) => + row.kind === "managed" ? ( + "—" + ) : ( + openMbtiCatalog(row.agent_id) + : undefined + } + /> + ), }, { title: t("experts.table.actions", "操作"), @@ -536,6 +545,7 @@ export default function AgentExpertsTable({ )} setSkillCatalogAgentId(row.agent_id)} onSubagents={() => openSubagentCatalog(row.agent_id)} onTools={() => setToolSettingsAgentId(row.agent_id)} @@ -606,6 +616,10 @@ export default function AgentExpertsTable({ /> row.agent_id === toolSettingsAgentId)?.kind === + "managed" + } open={toolSettingsAgentId !== null} onClose={() => setToolSettingsAgentId(null)} /> diff --git a/dashboard/src/pages/Experts/components/AgentMoreActions.tsx b/dashboard/src/pages/Experts/components/AgentMoreActions.tsx index a25accd707..48a29a3e87 100644 --- a/dashboard/src/pages/Experts/components/AgentMoreActions.tsx +++ b/dashboard/src/pages/Experts/components/AgentMoreActions.tsx @@ -21,6 +21,8 @@ interface AgentMoreActionsProps { onMbti: () => void; onMemory: () => void; onChannels: () => void; + /** Managed experts omit MBTI. Tools and plugins stay. */ + managed?: boolean; } /** Overflow menu for expert catalog actions (skills / subagents / …). */ @@ -33,6 +35,7 @@ export default function AgentMoreActions({ onMbti, onMemory, onChannels, + managed = false, }: AgentMoreActionsProps) { const { t } = useTranslation(); @@ -61,12 +64,16 @@ export default function AgentMoreActions({ label: t("experts.pluginsBtn"), onClick: onPlugins, }, - { - key: "mbti", - icon: , - label: t("experts.mbtiBtn"), - onClick: onMbti, - }, + ...(managed + ? [] + : [ + { + key: "mbti", + icon: , + label: t("experts.mbtiBtn"), + onClick: onMbti, + }, + ]), { key: "memory", icon: , diff --git a/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx b/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx index 8285d8064b..30ab6aa6c6 100644 --- a/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx +++ b/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx @@ -694,6 +694,8 @@ export default function CreateFromExpertDrawer({ width={600} onClose={onClose} destroyOnHidden + className={styles.expertDrawer} + rootClassName={styles.expertDrawerRoot} footer={