Merge remote-tracking branch 'origin/master' into ji
# Conflicts: # .gitignore # frontend-web/src/components/workspace/input-box.tsx # frontend-web/src/core/threads/types.ts # frontend-web/src/pages/ChatPage.tsx
No files matched your search
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;opacity:0;}.b{fill:none;stroke:#fff;stroke-linecap:round;stroke-linejoin:round;}</style></defs><rect class="a" width="16" height="16"/><path class="b" d="M24.036,10l-.012,9.333" transform="translate(-16.016 -6.667)"/><path class="b" d="M10,24h9.333" transform="translate(-6.667 -16)"/></svg>
|
||||
|
After Width: | Height: | Size: 401 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="36" height="36" viewBox="0 0 36 36"><defs><style>.a,.d{fill:#fff;}.a{opacity:0;}.b{fill:#da2331;}.c{fill:#0a54cf;}.e{fill:#1677ff;}.f{fill:#1e2433;}.g{fill:#10d6ff;}.h{fill:#ff8181;}.i{fill:none;stroke:#10d6ff;stroke-linecap:round;stroke-linejoin:round;}.j{filter:url(#d);}.k{filter:url(#a);}</style><filter id="a"><feOffset dx="4" input="SourceAlpha"/><feGaussianBlur stdDeviation="1" result="b"/><feFlood flood-opacity="0.161" result="c"/><feComposite operator="out" in="SourceGraphic" in2="b"/><feComposite operator="in" in="c"/><feComposite operator="in" in2="SourceGraphic"/></filter><filter id="d"><feOffset dx="-4" input="SourceAlpha"/><feGaussianBlur stdDeviation="1" result="e"/><feFlood flood-opacity="0.161" result="f"/><feComposite operator="out" in="SourceGraphic" in2="e"/><feComposite operator="in" in="f"/><feComposite operator="in" in2="SourceGraphic"/></filter></defs><g transform="translate(0 -1)"><rect class="a" width="36" height="36" transform="translate(0 1)"/><path class="b" d="M23.5,14.75a1.5,1.5,0,0,1-1.5-1.5V9.5a1.5,1.5,0,1,1,3,0v3.75A1.5,1.5,0,0,1,23.5,14.75Z" transform="translate(-5.5 -1)"/><g data-type="innerShadowGroup"><path class="c" d="M-2-2H1C3.206-2,5-.532,5,1.273V3.727C5,5.532,3.206,7,1,7H-2Z" transform="translate(28.66 19.541)"/><g class="k" transform="matrix(1, 0, 0, 1, 0, 1)"><path class="d" d="M-2-2H1C3.206-2,5-.532,5,1.273V3.727C5,5.532,3.206,7,1,7H-2Z" transform="translate(28.66 18.54)"/></g></g><g data-type="innerShadowGroup"><path class="c" d="M5-2H2C-.206-2-2-.532-2,1.273V3.727C-2,5.532-.206,7,2,7H5Z" transform="translate(4.34 19.541)"/><g class="j" transform="matrix(1, 0, 0, 1, 0, 1)"><path class="d" d="M5-2H2C-.206-2-2-.532-2,1.273V3.727C-2,5.532-.206,7,2,7H5Z" transform="translate(4.34 18.54)"/></g></g><path class="e" d="M5.5-2H16a7.508,7.508,0,0,1,7.5,7.5V13A7.508,7.508,0,0,1,16,20.5H5.5A7.508,7.508,0,0,1-2,13V5.5A7.508,7.508,0,0,1,5.5-2Z" transform="translate(7.25 13.5)"/><path class="f" d="M5.25,0h9A5.25,5.25,0,0,1,19.5,5.25V7.5a5.25,5.25,0,0,1-5.25,5.25h-9A5.25,5.25,0,0,1,0,7.5V5.25A5.25,5.25,0,0,1,5.25,0Z" transform="translate(8.25 15.25)"/><circle class="g" cx="1.5" cy="1.5" r="1.5" transform="translate(21 19)"/><circle class="g" cx="1.5" cy="1.5" r="1.5" transform="translate(12 19)"/><path class="d" d="M24,10v3.75" transform="translate(-6 -1.5)"/><circle class="h" cx="3" cy="3" r="3" transform="translate(15 4)"/><path class="i" d="M44,28.667a3.367,3.367,0,0,0,1.922.412,2.841,2.841,0,0,0,1.828-.412" transform="translate(-27.875 -5.017)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 2.6 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96"><defs><style>.a{fill:#fff;opacity:0;}.b,.c{fill:none;stroke:#006efe;stroke-width:6px;}.b{stroke-linecap:round;stroke-linejoin:round;}</style></defs><g transform="translate(0 1)"><rect class="a" width="96" height="96" transform="translate(0 -1)"/><path class="b" d="M47,67H38L18,77V67H4V7H84V29" transform="translate(4 8)"/><circle class="c" cx="12" cy="12" r="12" transform="translate(56 45)"/><path class="b" d="M39,32l10,8" transform="translate(39 33)"/><path class="b" d="M12,15H24" transform="translate(12 16)"/><path class="b" d="M12,21H36" transform="translate(12 22)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 670 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="13" height="11" viewBox="0 0 13 11"><defs><style>.a{stroke:rgba(0,0,0,0);stroke-miterlimit:10;fill:url(#a);}</style><linearGradient id="a" x1="0.277" y1="0.03" x2="0.725" y2="1.083" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#92eeff"/><stop offset="1" stop-color="#00c7ff"/></linearGradient></defs><path class="a" d="M1,10A1,1,0,1,1,1,8H6a1,1,0,0,1,0,2Zm9.8-.482L7.848,7.361A.445.445,0,0,1,7.661,7a.46.46,0,0,1,.187-.366L10.8,4.481a.45.45,0,0,1,.716.365V9.152a.44.44,0,0,1-.131.317.445.445,0,0,1-.322.136A.454.454,0,0,1,10.8,9.518ZM1,6A1,1,0,1,1,1,4H6A1,1,0,0,1,6,6ZM1,2A1,1,0,1,1,1,0H11a1,1,0,1,1,0,2Z" transform="translate(0.5 0.5)"/></svg>
|
||||
|
After Width: | Height: | Size: 753 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="13" height="11" viewBox="0 0 13 11"><defs><style>.a{fill:url(#a);}.b{fill:url(#b);}</style><linearGradient id="a" x1="0.023" x2="1" y2="1" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#92eeff" stop-opacity="0.302"/><stop offset="1" stop-color="#00c7ff" stop-opacity="0.302"/></linearGradient><linearGradient id="b" x1="0.023" x2="1" y2="1" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#92eeff"/><stop offset="1" stop-color="#00c7ff"/></linearGradient></defs><path class="a" d="M5.5,0,11,8H0Z" transform="translate(13) rotate(90)"/><path class="b" d="M5.5,0,11,8H0Z" transform="translate(8) rotate(90)"/></svg>
|
||||
|
After Width: | Height: | Size: 735 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;opacity:0;}.b,.c{fill:none;stroke:#fff;stroke-linejoin:round;}.b{stroke-linecap:round;}</style></defs><g transform="translate(-1)"><rect class="a" width="16" height="16" transform="translate(1)"/><path class="b" d="M7,42H19" transform="translate(-4 -28)"/><path class="b" d="M0,0H3" transform="translate(9.848 3.848) rotate(45)"/><path class="c" d="M11,12.907v2.427h2.439l6.894-6.9L17.9,6Z" transform="translate(-6.667 -4)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 545 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;opacity:0;}.b{fill:rgba(255,255,255,0.8);}</style></defs><rect class="a" width="16" height="16"/><path class="b" d="M10,1.5A1.5,1.5,0,1,1,11.5,3,1.5,1.5,0,0,1,10,1.5Zm-5,0A1.5,1.5,0,1,1,6.5,3,1.5,1.5,0,0,1,5,1.5Zm-5,0A1.5,1.5,0,1,1,1.5,3,1.5,1.5,0,0,1,0,1.5Z" transform="translate(1.498 6.5)"/></svg>
|
||||
|
After Width: | Height: | Size: 410 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;opacity:0;}.b{fill:rgba(85,166,254,0.6);}</style></defs><rect class="a" width="16" height="16"/><path class="b" d="M12.715,13.421,9.588,10.294a5.841,5.841,0,1,1,.707-.707l3.128,3.128a.5.5,0,0,1-.708.706ZM1,5.833A4.833,4.833,0,1,0,5.834,1,4.838,4.838,0,0,0,1,5.833Z" transform="translate(1.334 1.216)"/></svg>
|
||||
|
After Width: | Height: | Size: 418 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;}</style></defs><path class="a" d="M14.488.053.824,4.256a1.167,1.167,0,0,0-.285,2.1L4.576,8.936a1.167,1.167,0,0,0,1.382-.092L11,4.593A.292.292,0,0,1,11.408,5L7.156,10.043a1.167,1.167,0,0,0-.091,1.382l2.58,4.036a1.168,1.168,0,0,0,2.1-.286l4.2-13.663A1.167,1.167,0,0,0,14.488.053Z" transform="translate(0)"/></svg>
|
||||
|
After Width: | Height: | Size: 422 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16.131" height="16" viewBox="0 0 16.131 16"><defs><style>.a{fill:#fff;opacity:0;}.b{fill:none;stroke:#97edff;stroke-linecap:round;stroke-linejoin:round;}</style></defs><rect class="a" width="16" height="16"/><path class="b" d="M6,30V34.12H18.361V30" transform="translate(-2.73 -19.994)"/><path class="b" d="M21.181,9.09,18.09,6,15,9.09" transform="translate(-8.64 -4.235)"/><path class="b" d="M23.992,14.241V6" transform="translate(-14.544 -4.235)"/></svg>
|
||||
|
After Width: | Height: | Size: 504 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;opacity:0;}.b,.c{fill:none;stroke:#346fb1;stroke-linejoin:round;}.c{stroke-linecap:round;}</style></defs><rect class="a" width="16" height="16"/><path class="b" d="M10.667,17.333A6.667,6.667,0,1,0,4,10.667,6.667,6.667,0,0,0,10.667,17.333Z" transform="translate(-2.667 -2.667)"/><path class="c" d="M24.008,12v4l2.826,2.826" transform="translate(-16.005 -8)"/></svg>
|
||||
|
After Width: | Height: | Size: 473 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="95.001" height="26" viewBox="0 0 95.001 26"><defs><style>.a{fill:rgba(212,120,0,0.5);}</style></defs><path class="a" d="M250.146,407.92h91l-11.4,18.235c-2.679,4.26-5.243,7.5-11.211,7.765H246.146v-22A4,4,0,0,1,250.146,407.92Z" transform="translate(-246.146 -407.92)"/></svg>
|
||||
|
After Width: | Height: | Size: 320 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="95.001" height="26" viewBox="0 0 95.001 26"><defs><style>.a{fill:rgba(207,19,34,0.5);}</style></defs><path class="a" d="M250.146,407.92h91l-11.4,18.235c-2.679,4.26-5.243,7.5-11.211,7.765H246.146v-22A4,4,0,0,1,250.146,407.92Z" transform="translate(-246.146 -407.92)"/></svg>
|
||||
|
After Width: | Height: | Size: 320 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="95.001" height="26" viewBox="0 0 95.001 26"><defs><style>.a{fill:rgba(29,171,123,0.5);}</style></defs><path class="a" d="M250.146,407.92h91l-11.4,18.235c-2.679,4.26-5.243,7.5-11.211,7.765H246.146v-22A4,4,0,0,1,250.146,407.92Z" transform="translate(-246.146 -407.92)"/></svg>
|
||||
|
After Width: | Height: | Size: 321 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="95.001" height="26" viewBox="0 0 95.001 26"><defs><style>.a{fill:rgba(132,85,230,0.5);}</style></defs><path class="a" d="M250.146,407.92h91l-11.4,18.235c-2.679,4.26-5.243,7.5-11.211,7.765H246.146v-22A4,4,0,0,1,250.146,407.92Z" transform="translate(-246.146 -407.92)"/></svg>
|
||||
|
After Width: | Height: | Size: 321 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="95.001" height="26" viewBox="0 0 95.001 26"><defs><style>.a{fill:rgba(201,181,0,0.5);}</style></defs><path class="a" d="M250.146,407.92h91l-11.4,18.235c-2.679,4.26-5.243,7.5-11.211,7.765H246.146v-22A4,4,0,0,1,250.146,407.92Z" transform="translate(-246.146 -407.92)"/></svg>
|
||||
|
After Width: | Height: | Size: 320 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="95.001" height="26" viewBox="0 0 95.001 26"><defs><style>.a{fill:rgba(69,195,243,0.5);}</style></defs><path class="a" d="M250.146,407.92h91l-11.4,18.235c-2.679,4.26-5.243,7.5-11.211,7.765H246.146v-22A4,4,0,0,1,250.146,407.92Z" transform="translate(-246.146 -407.92)"/></svg>
|
||||
|
After Width: | Height: | Size: 321 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><defs><style>.a{fill:#fff;opacity:0;}.b{fill:none;stroke:#346fb1;stroke-linecap:round;stroke-linejoin:round;}</style></defs><g transform="translate(0 -2)"><rect class="a" width="16" height="16" transform="translate(0 2)"/><path class="b" d="M17.333,8H4V18H9l1.667,1.667L12.333,18h5Z" transform="translate(-2.667 -3.667)"/><circle class="b" cx="1.667" cy="1.667" r="1.667" transform="translate(6.333 6.333)"/><path class="b" d="M21,26.667A2.848,2.848,0,0,0,18,24a2.848,2.848,0,0,0-3,2.667" transform="translate(-10 -14.333)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 618 B |
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import {
|
||||
Bell,
|
||||
Cpu,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronsUpDown,
|
||||
@@ -252,6 +253,14 @@ function SecondaryNavSidebar({ headerHidden }: { headerHidden: boolean }) {
|
||||
白名单管理
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate("/page/workspace/admin/models")}
|
||||
>
|
||||
<Cpu className="size-4" />
|
||||
模型配置
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate("/page/strategy/settings/model-concurrency")}
|
||||
@@ -555,6 +564,12 @@ function LegacyAccordionSidebar({
|
||||
岗位角色配置
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem onClick={() => navigate("/page/workspace/admin/models")}>
|
||||
<Cpu className="size-4" />
|
||||
模型配置
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/login-whitelist")}>
|
||||
<ShieldCheck className="size-4" />
|
||||
|
||||
@@ -104,15 +104,17 @@ function Section({
|
||||
icon,
|
||||
title,
|
||||
extra,
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
icon?: ReactNode;
|
||||
title: string;
|
||||
extra?: ReactNode;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="bg-card/60 rounded-xl border p-4">
|
||||
<section className={cn("bg-card/60 rounded-xl border p-4", className)}>
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<h4 className="text-foreground flex items-center gap-1.5 text-sm font-semibold">
|
||||
{icon}
|
||||
@@ -143,6 +145,15 @@ export function AgentDetailPanel({
|
||||
defaultCollapsed,
|
||||
showRecentChats,
|
||||
compactAppearanceActions,
|
||||
avatarSrc,
|
||||
positionName,
|
||||
skillsIcon,
|
||||
skillsTitle,
|
||||
showCommonQuestions = false,
|
||||
panelTitle,
|
||||
embedded,
|
||||
hideStatusBadges = false,
|
||||
editIcon,
|
||||
}: {
|
||||
agent: Agent | null | undefined;
|
||||
agentName: string;
|
||||
@@ -154,6 +165,19 @@ export function AgentDetailPanel({
|
||||
showRecentChats?: boolean;
|
||||
/** 简洁模式下挂在右上角收起/展开按钮左侧的外观控件。 */
|
||||
compactAppearanceActions?: ReactNode;
|
||||
avatarSrc?: string;
|
||||
positionName?: string;
|
||||
skillsIcon?: ReactNode;
|
||||
skillsTitle?: string;
|
||||
showCommonQuestions?: boolean;
|
||||
/** Overrides the standard panel heading for an embedded consumer. */
|
||||
panelTitle?: string;
|
||||
/** Renders one fixed panel instead of the responsive collapsible rail. */
|
||||
embedded?: boolean;
|
||||
/** Keeps deployment/status badges out of an embedded product surface. */
|
||||
hideStatusBadges?: boolean;
|
||||
/** Optional icon used by the compact embedded edit action. */
|
||||
editIcon?: ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false);
|
||||
@@ -481,11 +505,25 @@ export function AgentDetailPanel({
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button size="sm" variant="outline" onClick={beginEdit}>
|
||||
<SquarePenIcon className="size-3.5" />
|
||||
编辑
|
||||
</Button>
|
||||
{canTogglePublish && (
|
||||
{embedded ? (
|
||||
<Tooltip content="编辑智能体">
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
onClick={beginEdit}
|
||||
aria-label="编辑智能体"
|
||||
>
|
||||
{editIcon ?? <SquarePenIcon className="size-3.5" />}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Button size="sm" variant="outline" onClick={beginEdit}>
|
||||
<SquarePenIcon className="size-3.5" />
|
||||
编辑
|
||||
</Button>
|
||||
)}
|
||||
{!embedded && canTogglePublish && (
|
||||
<Tooltip content={agent?.published ? "下架" : "发布"}>
|
||||
<Button
|
||||
size="icon-sm"
|
||||
@@ -502,17 +540,19 @@ export function AgentDetailPanel({
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip content="删除智能体">
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
aria-label="删除智能体"
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
{!embedded && (
|
||||
<Tooltip content="删除智能体">
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
aria-label="删除智能体"
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
) : null;
|
||||
@@ -530,7 +570,11 @@ export function AgentDetailPanel({
|
||||
<section className="bg-card/60 rounded-xl border p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="agent-avatar bg-primary/10 ring-primary/15 flex size-12 shrink-0 items-center justify-center rounded-2xl ring-1">
|
||||
<BotIcon className="text-primary size-6" />
|
||||
{avatarSrc ? (
|
||||
<img src={avatarSrc} alt="" aria-hidden="true" className="size-9" />
|
||||
) : (
|
||||
<BotIcon className="text-primary size-6" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-1.5">
|
||||
{editing && draft ? (
|
||||
@@ -550,9 +594,16 @@ export function AgentDetailPanel({
|
||||
{displayName}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{statusBadges}
|
||||
</div>
|
||||
{!editing && positionName && (
|
||||
<div className="position-agent-role text-sm">
|
||||
岗位:{desensitize(positionName)}
|
||||
</div>
|
||||
)}
|
||||
{!hideStatusBadges && (
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{statusBadges}
|
||||
</div>
|
||||
)}
|
||||
{!editing && agent.owner_username && !agent.builtin && (
|
||||
<div className="text-muted-foreground flex items-center gap-1 text-xs">
|
||||
<UserRoundIcon className="size-3 shrink-0" />
|
||||
@@ -670,7 +721,7 @@ export function AgentDetailPanel({
|
||||
|
||||
|
||||
{/* ── 常用问题 ───────────────────────────────────────────────────── */}
|
||||
{(editing || questions.length > 0 || canEdit) && (
|
||||
{(showCommonQuestions || editing || questions.length > 0 || canEdit) && (
|
||||
<Section
|
||||
icon={<MessageCircleQuestionIcon className="size-3.5" />}
|
||||
title="常用问题"
|
||||
@@ -811,8 +862,9 @@ export function AgentDetailPanel({
|
||||
|
||||
{/* ── 技能管理 ───────────────────────────────────────────────────── */}
|
||||
<Section
|
||||
icon={<SparklesIcon className="size-3.5" />}
|
||||
title={`已启用技能 ${skillNamesShown.length} 个`}
|
||||
icon={skillsIcon ?? <SparklesIcon className="size-3.5" />}
|
||||
title={skillsTitle ?? `已启用技能 ${skillNamesShown.length} 个`}
|
||||
className="position-roundtable-skills-section"
|
||||
extra={
|
||||
editing ? (
|
||||
<Button
|
||||
@@ -854,7 +906,9 @@ export function AgentDetailPanel({
|
||||
const panelChrome = (collapseButton: ReactNode) => (
|
||||
<>
|
||||
<div className="flex h-12 shrink-0 items-center justify-between border-b px-4">
|
||||
<span className="shrink-0 whitespace-nowrap text-sm font-semibold">智能体信息</span>
|
||||
<span className="shrink-0 whitespace-nowrap text-sm font-semibold">
|
||||
{panelTitle ?? "智能体信息"}
|
||||
</span>
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
{headerActions}
|
||||
{compactAppearanceActions}
|
||||
@@ -868,7 +922,11 @@ export function AgentDetailPanel({
|
||||
return (
|
||||
<>
|
||||
{/* ── Desktop (lg+): inline aside, collapsible to a rail ───────────── */}
|
||||
{collapsed ? (
|
||||
{embedded ? (
|
||||
<aside className="bg-card/40 flex h-full w-full min-w-0 shrink-0 flex-col border-l">
|
||||
{panelChrome(null)}
|
||||
</aside>
|
||||
) : collapsed ? (
|
||||
<div className="hidden shrink-0 items-start border-l px-2 pt-3 lg:flex">
|
||||
<div className="flex items-center gap-1">
|
||||
{compactAppearanceActions}
|
||||
@@ -901,30 +959,34 @@ export function AgentDetailPanel({
|
||||
</aside>
|
||||
)}
|
||||
|
||||
{/* ── Narrow screens (<lg): rail trigger + drawer with the same body ── */}
|
||||
<div className="flex shrink-0 flex-col items-center border-l pt-3 lg:hidden">
|
||||
<Tooltip content="智能体信息">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setMobileOpen(true)}
|
||||
aria-label="打开智能体信息"
|
||||
>
|
||||
<InfoIcon className="size-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
|
||||
<SheetContent side="right" className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
|
||||
<SheetHeader className="border-b px-4 pb-3 pt-4">
|
||||
<SheetTitle className="flex items-center justify-between text-sm">
|
||||
智能体信息
|
||||
<span className="mr-6">{headerActions}</span>
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{body}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
{!embedded && (
|
||||
<>
|
||||
{/* ── Narrow screens (<lg): rail trigger + drawer with the same body ── */}
|
||||
<div className="flex shrink-0 flex-col items-center border-l pt-3 lg:hidden">
|
||||
<Tooltip content="智能体信息">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setMobileOpen(true)}
|
||||
aria-label="打开智能体信息"
|
||||
>
|
||||
<InfoIcon className="size-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
|
||||
<SheetContent side="right" className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
|
||||
<SheetHeader className="border-b px-4 pb-3 pt-4">
|
||||
<SheetTitle className="flex items-center justify-between text-sm">
|
||||
智能体信息
|
||||
<span className="mr-6">{headerActions}</span>
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{body}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ── Secondary surfaces ───────────────────────────────────────────── */}
|
||||
<SkillPickerSheet
|
||||
|
||||
@@ -121,8 +121,9 @@ function findScrollableArtifactElement(root: HTMLElement | null) {
|
||||
|
||||
export function ArtifactFileDetail({
|
||||
className,
|
||||
filepath: filepathFromProps,
|
||||
threadId,
|
||||
filepath: filepathFromProps,
|
||||
threadId,
|
||||
mimeType = null,
|
||||
onClose,
|
||||
allowVirtualMarkdownEdit = false,
|
||||
disableDesensitize = false,
|
||||
@@ -131,6 +132,8 @@ export function ArtifactFileDetail({
|
||||
className?: string;
|
||||
filepath: string;
|
||||
threadId: string;
|
||||
/** Server/tool supplied type wins over path guessing when available. */
|
||||
mimeType?: string | null;
|
||||
/** 覆盖默认关闭行为(仅 setOpen(false));圆桌 Step3 文件预览用于退出沙箱模式。 */
|
||||
onClose?: () => void;
|
||||
/**
|
||||
@@ -150,16 +153,38 @@ export function ArtifactFileDetail({
|
||||
const { t } = useI18n();
|
||||
const { artifacts, setOpen, select } = useArtifacts();
|
||||
const { isMock, thread, publicShareCode } = useThread();
|
||||
const isWriteFileVirtual = useMemo(() => {
|
||||
return filepathFromProps.startsWith("write-file:");
|
||||
}, [filepathFromProps]);
|
||||
const filepath = useMemo(() => {
|
||||
if (isWriteFileVirtual) {
|
||||
const url = new URL(filepathFromProps);
|
||||
return decodeURIComponent(url.pathname);
|
||||
}
|
||||
return filepathFromProps;
|
||||
}, [filepathFromProps, isWriteFileVirtual]);
|
||||
const isWriteFileVirtual = useMemo(() => {
|
||||
return filepathFromProps.startsWith("write-file:");
|
||||
}, [filepathFromProps]);
|
||||
// A streamed tool call can be opened before the path has been normalized by
|
||||
// the artifacts API. Keep the format supplied by the writer so Markdown is
|
||||
// rendered as Markdown instead of falling back to a TEXT source preview.
|
||||
const writeFileLanguageHint = useMemo(() => {
|
||||
if (!isWriteFileVirtual) return null;
|
||||
try {
|
||||
const language = new URL(filepathFromProps).searchParams.get("language");
|
||||
return language === "markdown" ? language : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [filepathFromProps, isWriteFileVirtual]);
|
||||
const mimeLanguageHint = useMemo(() => {
|
||||
const normalized = mimeType?.toLowerCase().trim() ?? "";
|
||||
if (normalized.includes("markdown")) return "markdown";
|
||||
if (normalized.includes("html")) return "html";
|
||||
if (normalized.includes("mermaid")) return "mermaid";
|
||||
if (normalized.startsWith("text/")) return "text";
|
||||
return null;
|
||||
}, [mimeType]);
|
||||
const filepath = useMemo(() => {
|
||||
if (isWriteFileVirtual) {
|
||||
const url = new URL(filepathFromProps);
|
||||
return decodeURIComponent(url.pathname).trim();
|
||||
}
|
||||
// Tool arguments may contain harmless surrounding whitespace. Passing it
|
||||
// into extension detection turns `report.md ` into a generic TEXT file.
|
||||
return filepathFromProps.trim();
|
||||
}, [filepathFromProps, isWriteFileVirtual]);
|
||||
const isSkillFile = useMemo(() => {
|
||||
return filepath.endsWith(".skill");
|
||||
}, [filepath]);
|
||||
@@ -186,17 +211,22 @@ export function ArtifactFileDetail({
|
||||
const useWriteFileStreaming = useMemo(() => {
|
||||
return isWriteFileVirtual && !isImageFile(filepath) && !editVirtualMarkdown;
|
||||
}, [filepath, isWriteFileVirtual, editVirtualMarkdown]);
|
||||
const { isCodeFile, language } = useMemo(() => {
|
||||
if (useWriteFileStreaming) {
|
||||
let nextLanguage = checkCodeFile(filepath).language;
|
||||
nextLanguage ??= "text";
|
||||
return { isCodeFile: true, language: nextLanguage };
|
||||
const { isCodeFile, language } = useMemo(() => {
|
||||
if (useWriteFileStreaming) {
|
||||
let nextLanguage =
|
||||
mimeLanguageHint ?? writeFileLanguageHint ?? checkCodeFile(filepath).language;
|
||||
nextLanguage ??= "text";
|
||||
return { isCodeFile: true, language: nextLanguage };
|
||||
}
|
||||
if (isSkillFile) {
|
||||
return { isCodeFile: true, language: "markdown" };
|
||||
}
|
||||
return checkCodeFile(filepath);
|
||||
}, [filepath, useWriteFileStreaming, isSkillFile]);
|
||||
const detected = checkCodeFile(filepath);
|
||||
if (mimeLanguageHint) {
|
||||
return { isCodeFile: true as const, language: mimeLanguageHint };
|
||||
}
|
||||
return detected;
|
||||
}, [filepath, useWriteFileStreaming, isSkillFile, mimeLanguageHint, writeFileLanguageHint]);
|
||||
const isSupportPreview = useMemo(() => {
|
||||
return (
|
||||
language === "html" ||
|
||||
@@ -209,7 +239,8 @@ export function ArtifactFileDetail({
|
||||
// editVirtualMarkdown:用解码后的真实路径走 artifacts API(而非 write-file 虚拟
|
||||
// URL),这样保存后 useUpdateArtifactContent 写入的查询缓存才能命中,编辑内容
|
||||
// 不会被旧的内存 stub 值覆盖回退。
|
||||
filepath: editVirtualMarkdown ? filepath : filepathFromProps,
|
||||
filepath:
|
||||
editVirtualMarkdown || !isWriteFileVirtual ? filepath : filepathFromProps,
|
||||
enabled: isCodeFile && !useWriteFileStreaming,
|
||||
});
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
|
||||
import { isSingleRoundRagMessage } from "@/core/threads/use-single-round-rag";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import type { SkillDisplayConfig } from "@/core/skills/type";
|
||||
import {
|
||||
@@ -92,6 +93,13 @@ const ChatBox: React.FC<{
|
||||
const [settings] = useLocalSettings();
|
||||
const ragModeEnabled =
|
||||
settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
|
||||
// Frontend single-round RAG writes its own source tool message, so it should
|
||||
// use the same reference panel without changing the user's global RAG mode.
|
||||
const hasSingleRoundRag = useMemo(
|
||||
() => (thread.values.messages ?? []).some(isSingleRoundRagMessage),
|
||||
[thread.values.messages],
|
||||
);
|
||||
const referencesEnabled = ragModeEnabled || hasSingleRoundRag;
|
||||
const { skills } = useSkills();
|
||||
|
||||
const {
|
||||
@@ -106,11 +114,11 @@ const ChatBox: React.FC<{
|
||||
|
||||
const [autoSelectFirstArtifact, setAutoSelectFirstArtifact] = useState(true);
|
||||
const skillDisplayMap = useMemo(
|
||||
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[ragModeEnabled, skills],
|
||||
() => (referencesEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[referencesEnabled, skills],
|
||||
);
|
||||
const fallbackReferenceBatches = useMemo(() => {
|
||||
if (!ragModeEnabled) {
|
||||
if (!referencesEnabled) {
|
||||
return [];
|
||||
}
|
||||
return buildTurnReferenceBatches(
|
||||
@@ -118,9 +126,9 @@ const ChatBox: React.FC<{
|
||||
skillDisplayMap,
|
||||
thread.isLoading,
|
||||
);
|
||||
}, [ragModeEnabled, skillDisplayMap, thread.isLoading, thread.values.messages]);
|
||||
}, [referencesEnabled, skillDisplayMap, thread.isLoading, thread.values.messages]);
|
||||
useEffect(() => {
|
||||
if (!ragModeEnabled) {
|
||||
if (!referencesEnabled) {
|
||||
setBackendReferenceBatches([]);
|
||||
return;
|
||||
}
|
||||
@@ -156,7 +164,7 @@ const ChatBox: React.FC<{
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [ragModeEnabled, thread.isLoading, threadId, thread.values.messages]);
|
||||
}, [referencesEnabled, thread.isLoading, threadId, thread.values.messages]);
|
||||
const adaptedBackendReferenceBatches = useMemo(
|
||||
() =>
|
||||
adaptBackendReferenceBatches(
|
||||
@@ -175,7 +183,7 @@ const ChatBox: React.FC<{
|
||||
[adaptedBackendReferenceBatches, fallbackReferenceBatches],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!ragModeEnabled) {
|
||||
if (!referencesEnabled) {
|
||||
return;
|
||||
}
|
||||
const signature = JSON.stringify({
|
||||
@@ -202,7 +210,7 @@ const ChatBox: React.FC<{
|
||||
fallbackBatches: debugReferenceBatches(fallbackReferenceBatches),
|
||||
finalBatches: debugReferenceBatches(referenceBatches),
|
||||
});
|
||||
}, [adaptedBackendReferenceBatches, backendReferenceBatches, fallbackReferenceBatches, ragModeEnabled, referenceBatches, threadId]);
|
||||
}, [adaptedBackendReferenceBatches, backendReferenceBatches, fallbackReferenceBatches, referencesEnabled, referenceBatches, threadId]);
|
||||
const latestReferenceBatch =
|
||||
referenceBatches.length > 0
|
||||
? referenceBatches[referenceBatches.length - 1]!
|
||||
@@ -213,7 +221,7 @@ const ChatBox: React.FC<{
|
||||
const referenceSources = activeReferenceBatch?.sources ?? [];
|
||||
const hasCitationReferences = referenceSources.length > 0;
|
||||
useEffect(() => {
|
||||
if (!ragModeEnabled || !activeReferenceBatch) {
|
||||
if (!referencesEnabled || !activeReferenceBatch) {
|
||||
return;
|
||||
}
|
||||
logReferenceDebug("frontend-active-reference-batch-payload", threadId, {
|
||||
@@ -222,7 +230,7 @@ const ChatBox: React.FC<{
|
||||
sourceCount: activeReferenceBatch.sources.length,
|
||||
sources: activeReferenceBatch.sources.map(debugReferenceSource),
|
||||
});
|
||||
}, [activeReferenceBatch, ragModeEnabled, threadId]);
|
||||
}, [activeReferenceBatch, referencesEnabled, threadId]);
|
||||
useEffect(() => {
|
||||
if (hasCitationReferences) {
|
||||
setReferencesOpen(true);
|
||||
|
||||
@@ -65,6 +65,7 @@ import { getBackendBaseURL } from "@/core/config";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { isHiddenFromUIMessage } from "@/core/messages/utils";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import type { Model } from "@/core/models/types";
|
||||
import type { AgentThreadContext } from "@/core/threads";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
@@ -136,6 +137,7 @@ export function InputBox({
|
||||
promptPrefix,
|
||||
agentSelector,
|
||||
knowledgeSelector,
|
||||
extraModels = [],
|
||||
assistantId,
|
||||
hideAdminRecommendedQuestions,
|
||||
compact,
|
||||
@@ -198,12 +200,19 @@ export function InputBox({
|
||||
};
|
||||
/** WeKnora-style knowledge-space picker rendered inside the composer toolbar. */
|
||||
knowledgeSelector?: ReactNode;
|
||||
/** Page-scoped model choices implemented outside the DeerFlow model API. */
|
||||
extraModels?: Model[];
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [localSettings, setLocalSettings] = useLocalSettings();
|
||||
const searchParams = useSearchParams();
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const { models } = useModels();
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const { models } = useModels();
|
||||
const singleRoundRagActive =
|
||||
context.execution_profile === "single_round_rag";
|
||||
const modelOptions = useMemo(() => {
|
||||
return singleRoundRagActive ? extraModels : models;
|
||||
}, [extraModels, models, singleRoundRagActive]);
|
||||
const { thread, isMock } = useThread();
|
||||
const { textInput } = usePromptInputController();
|
||||
const promptRootRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -227,34 +236,40 @@ export function InputBox({
|
||||
recommendedQuestions.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (models.length === 0) {
|
||||
return;
|
||||
}
|
||||
const currentModel = models.find((m) => m.name === context.model_name);
|
||||
const fallbackModel = currentModel ?? models[0]!;
|
||||
if (modelOptions.length === 0) {
|
||||
return;
|
||||
}
|
||||
const currentModel = modelOptions.find((m) => m.name === context.model_name);
|
||||
const fallbackModel = currentModel ?? modelOptions[0]!;
|
||||
const supportsThinking = fallbackModel.supports_thinking ?? false;
|
||||
const nextModelName = fallbackModel.name;
|
||||
const nextMode = getResolvedMode(context.mode, supportsThinking);
|
||||
|
||||
if (context.model_name === nextModelName && context.mode === nextMode) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
context.model_name === nextModelName &&
|
||||
context.mode === nextMode &&
|
||||
context.execution_profile === fallbackModel.execution_profile
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: nextModelName,
|
||||
mode: nextMode,
|
||||
});
|
||||
}, [context, models, onContextChange]);
|
||||
...context,
|
||||
model_name: nextModelName,
|
||||
mode: nextMode,
|
||||
execution_profile: fallbackModel.execution_profile,
|
||||
});
|
||||
}, [context, modelOptions, onContextChange]);
|
||||
|
||||
const selectedModel = useMemo(() => {
|
||||
if (modelOptions.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return modelOptions.find((m) => m.name === context.model_name) ?? modelOptions[0];
|
||||
}, [context.model_name, modelOptions]);
|
||||
|
||||
const selectedModel = useMemo(() => {
|
||||
if (models.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return models.find((m) => m.name === context.model_name) ?? models[0];
|
||||
}, [context.model_name, models]);
|
||||
|
||||
const resolvedModelName = selectedModel?.name;
|
||||
const resolvedModelName = selectedModel?.name;
|
||||
const selectedSingleRoundRag = singleRoundRagActive;
|
||||
|
||||
const supportThinking = useMemo(
|
||||
() => selectedModel?.supports_thinking ?? false,
|
||||
@@ -268,38 +283,65 @@ export function InputBox({
|
||||
|
||||
const handleModelSelect = useCallback(
|
||||
(model_name: string) => {
|
||||
const model = models.find((m) => m.name === model_name);
|
||||
const model = modelOptions.find((m) => m.name === model_name);
|
||||
if (!model) {
|
||||
return;
|
||||
}
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name,
|
||||
mode: getResolvedMode(context.mode, model.supports_thinking ?? false),
|
||||
reasoning_effort: context.reasoning_effort,
|
||||
});
|
||||
setModelDialogOpen(false);
|
||||
},
|
||||
[onContextChange, context, models],
|
||||
mode: getResolvedMode(context.mode, model.supports_thinking ?? false),
|
||||
reasoning_effort: context.reasoning_effort,
|
||||
execution_profile: model.execution_profile,
|
||||
});
|
||||
setModelDialogOpen(false);
|
||||
},
|
||||
[onContextChange, context, modelOptions],
|
||||
);
|
||||
|
||||
const handleModeSelect = useCallback(
|
||||
(mode: InputMode) => {
|
||||
onContextChange?.({
|
||||
...context,
|
||||
mode: getResolvedMode(mode, supportThinking),
|
||||
reasoning_effort:
|
||||
mode === "ultra"
|
||||
? "high"
|
||||
const handleModeSelect = useCallback(
|
||||
(mode: InputMode) => {
|
||||
const ordinaryModel =
|
||||
models.find((model) => model.name === context.model_name) ?? models[0];
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: ordinaryModel?.name ?? context.model_name,
|
||||
mode: getResolvedMode(
|
||||
mode,
|
||||
ordinaryModel?.supports_thinking ?? supportThinking,
|
||||
),
|
||||
reasoning_effort:
|
||||
mode === "ultra"
|
||||
? "high"
|
||||
: mode === "pro"
|
||||
? "medium"
|
||||
: mode === "thinking"
|
||||
? "low"
|
||||
: "minimal",
|
||||
});
|
||||
},
|
||||
[onContextChange, context, supportThinking],
|
||||
);
|
||||
? "low"
|
||||
: "minimal",
|
||||
execution_profile: undefined,
|
||||
});
|
||||
},
|
||||
[onContextChange, context, models, supportThinking],
|
||||
);
|
||||
|
||||
const handleSingleRoundRagSelect = useCallback(() => {
|
||||
const ragModel =
|
||||
extraModels.find((model) => model.name === context.model_name) ??
|
||||
extraModels[0];
|
||||
if (!ragModel) {
|
||||
return;
|
||||
}
|
||||
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: ragModel.name,
|
||||
mode: getResolvedMode(
|
||||
context.mode,
|
||||
ragModel.supports_thinking ?? false,
|
||||
),
|
||||
execution_profile: "single_round_rag",
|
||||
});
|
||||
}, [context, extraModels, onContextChange]);
|
||||
|
||||
const handleReasoningEffortSelect = useCallback(
|
||||
(effort: "minimal" | "low" | "medium" | "high") => {
|
||||
@@ -365,10 +407,11 @@ export function InputBox({
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: resolvedModelName,
|
||||
mode: getResolvedMode(
|
||||
context.mode,
|
||||
selectedModel?.supports_thinking ?? false,
|
||||
),
|
||||
mode: getResolvedMode(
|
||||
context.mode,
|
||||
selectedModel?.supports_thinking ?? false,
|
||||
),
|
||||
execution_profile: selectedModel?.execution_profile,
|
||||
});
|
||||
setTimeout(() => onSubmit?.(message), 0);
|
||||
return;
|
||||
@@ -383,7 +426,8 @@ export function InputBox({
|
||||
onStop,
|
||||
resolvedModelName,
|
||||
ragModeEnabled,
|
||||
selectedModel?.supports_thinking,
|
||||
selectedModel?.supports_thinking,
|
||||
selectedModel?.execution_profile,
|
||||
status,
|
||||
threadId,
|
||||
],
|
||||
@@ -441,8 +485,9 @@ export function InputBox({
|
||||
}, [pendingSuggestion, requestFormSubmit, textInput]);
|
||||
|
||||
const showFollowups =
|
||||
!disabled &&
|
||||
!isNewThread &&
|
||||
!disabled &&
|
||||
!isNewThread &&
|
||||
!selectedSingleRoundRag &&
|
||||
!followupsHidden &&
|
||||
(followupsLoading || followups.length > 0);
|
||||
|
||||
@@ -468,7 +513,7 @@ export function InputBox({
|
||||
return;
|
||||
}
|
||||
|
||||
if (disabled || isMock) {
|
||||
if (disabled || isMock || selectedSingleRoundRag) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -530,7 +575,7 @@ export function InputBox({
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [context.model_name, disabled, isMock, status, thread.messages, threadId]);
|
||||
}, [context.model_name, disabled, isMock, selectedSingleRoundRag, status, thread.messages, threadId]);
|
||||
|
||||
return (
|
||||
<div ref={promptRootRef} className="relative flex flex-col gap-6">
|
||||
@@ -786,54 +831,64 @@ export function InputBox({
|
||||
</PromptInputButton>
|
||||
</Tooltip>
|
||||
<PromptInputActionMenu>
|
||||
<ModeHoverGuide
|
||||
mode={
|
||||
<ModeHoverGuide
|
||||
mode={
|
||||
context.mode === "flash" ||
|
||||
context.mode === "thinking" ||
|
||||
context.mode === "pro" ||
|
||||
context.mode === "ultra"
|
||||
? context.mode
|
||||
: "flash"
|
||||
}
|
||||
>
|
||||
? context.mode
|
||||
: "flash"
|
||||
}
|
||||
tooltipContent={
|
||||
selectedSingleRoundRag
|
||||
? "单轮 RAG 问答:基于知识库检索生成答案,并展示参考资料"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<PromptInputActionMenuTrigger
|
||||
className={cn(
|
||||
"gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||
compact && "rounded-lg border px-2.5! py-1! text-[11px] font-medium",
|
||||
compact &&
|
||||
(context.mode === "thinking"
|
||||
? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200"
|
||||
compact &&
|
||||
(selectedSingleRoundRag
|
||||
? "border-emerald-200 bg-emerald-50/60 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
|
||||
: context.mode === "thinking"
|
||||
? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200"
|
||||
: context.mode === "pro"
|
||||
? "border-violet-200 bg-violet-50/60 text-violet-700 hover:bg-violet-100 dark:border-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
|
||||
: context.mode === "ultra"
|
||||
? "border-amber-200 bg-amber-50/60 text-amber-700 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
: "border-transparent bg-muted/40 hover:bg-muted hover:text-foreground"),
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
{context.mode === "flash" && <ZapIcon className="size-3" />}
|
||||
{context.mode === "thinking" && (
|
||||
<LightbulbIcon className="size-3" />
|
||||
)}
|
||||
{context.mode === "pro" && (
|
||||
<GraduationCapIcon className="size-3" />
|
||||
)}
|
||||
{context.mode === "ultra" && (
|
||||
<RocketIcon className="size-3 text-[#dabb5e]" />
|
||||
)}
|
||||
</div>
|
||||
>
|
||||
<div>
|
||||
{selectedSingleRoundRag ? (
|
||||
<BookMarkedIcon className="size-3" />
|
||||
) : context.mode === "flash" ? (
|
||||
<ZapIcon className="size-3" />
|
||||
) : context.mode === "thinking" ? (
|
||||
<LightbulbIcon className="size-3" />
|
||||
) : context.mode === "pro" ? (
|
||||
<GraduationCapIcon className="size-3" />
|
||||
) : context.mode === "ultra" ? (
|
||||
<RocketIcon className="size-3 text-[#dabb5e]" />
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"text-xs font-normal",
|
||||
context.mode === "ultra" ? "golden-text" : "",
|
||||
)}
|
||||
>
|
||||
{(context.mode === "flash" && t.inputBox.flashMode) ||
|
||||
(context.mode === "thinking" &&
|
||||
t.inputBox.reasoningMode) ||
|
||||
(context.mode === "pro" && t.inputBox.proMode) ||
|
||||
(context.mode === "ultra" && t.inputBox.ultraMode)}
|
||||
</div>
|
||||
{selectedSingleRoundRag
|
||||
? "单轮 RAG"
|
||||
: (context.mode === "flash" && t.inputBox.flashMode) ||
|
||||
(context.mode === "thinking" &&
|
||||
t.inputBox.reasoningMode) ||
|
||||
(context.mode === "pro" && t.inputBox.proMode) ||
|
||||
(context.mode === "ultra" && t.inputBox.ultraMode)}
|
||||
</div>
|
||||
</PromptInputActionMenuTrigger>
|
||||
</ModeHoverGuide>
|
||||
<PromptInputActionMenuContent className="w-80">
|
||||
@@ -842,11 +897,11 @@ export function InputBox({
|
||||
{t.inputBox.mode}
|
||||
</DropdownMenuLabel>
|
||||
<PromptInputActionMenu>
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "flash"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "flash"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
onSelect={() => handleModeSelect("flash")}
|
||||
>
|
||||
@@ -854,9 +909,9 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<ZapIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "flash" &&
|
||||
"text-accent-foreground",
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag && context.mode === "flash" &&
|
||||
"text-accent-foreground",
|
||||
)}
|
||||
/>
|
||||
{t.inputBox.flashMode}
|
||||
@@ -865,7 +920,7 @@ export function InputBox({
|
||||
{t.inputBox.flashModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "flash" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "flash" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
@@ -873,9 +928,9 @@ export function InputBox({
|
||||
</PromptInputActionMenuItem>
|
||||
{supportThinking && (
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "thinking"
|
||||
? "text-accent-foreground"
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "thinking"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
onSelect={() => handleModeSelect("thinking")}
|
||||
@@ -884,9 +939,9 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<LightbulbIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "thinking" &&
|
||||
"text-accent-foreground",
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag && context.mode === "thinking" &&
|
||||
"text-accent-foreground",
|
||||
)}
|
||||
/>
|
||||
{t.inputBox.reasoningMode}
|
||||
@@ -895,7 +950,7 @@ export function InputBox({
|
||||
{t.inputBox.reasoningModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "thinking" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "thinking" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
@@ -903,8 +958,8 @@ export function InputBox({
|
||||
</PromptInputActionMenuItem>
|
||||
)}
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "pro"
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "pro"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
@@ -914,8 +969,8 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<GraduationCapIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "pro" &&
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag && context.mode === "pro" &&
|
||||
"text-accent-foreground",
|
||||
)}
|
||||
/>
|
||||
@@ -925,15 +980,15 @@ export function InputBox({
|
||||
{t.inputBox.proModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "pro" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "pro" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "ultra"
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "ultra"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
@@ -943,13 +998,17 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<RocketIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "ultra" && "text-[#dabb5e]",
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag &&
|
||||
context.mode === "ultra" &&
|
||||
"text-[#dabb5e]",
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
context.mode === "ultra" && "golden-text",
|
||||
!selectedSingleRoundRag &&
|
||||
context.mode === "ultra" &&
|
||||
"golden-text",
|
||||
)}
|
||||
>
|
||||
{t.inputBox.ultraMode}
|
||||
@@ -959,13 +1018,46 @@ export function InputBox({
|
||||
{t.inputBox.ultraModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "ultra" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "ultra" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
</PromptInputActionMenu>
|
||||
</PromptInputActionMenuItem>
|
||||
{extraModels.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator className="my-2" />
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
selectedSingleRoundRag
|
||||
? "bg-emerald-50 text-emerald-800 hover:bg-emerald-100 focus:bg-emerald-100 dark:bg-emerald-950/40 dark:text-emerald-200 dark:hover:bg-emerald-950/60 dark:focus:bg-emerald-950/60"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
onSelect={handleSingleRoundRagSelect}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<BookMarkedIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
selectedSingleRoundRag && "text-emerald-700 dark:text-emerald-200",
|
||||
)}
|
||||
/>
|
||||
单轮 RAG 问答
|
||||
</div>
|
||||
<div className="pl-7 text-xs">
|
||||
基于知识库检索生成答案,并展示思考内容与参考资料
|
||||
</div>
|
||||
</div>
|
||||
{selectedSingleRoundRag ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
</>
|
||||
)}
|
||||
</PromptInputActionMenu>
|
||||
</DropdownMenuGroup>
|
||||
</PromptInputActionMenuContent>
|
||||
</PromptInputActionMenu>
|
||||
@@ -1151,7 +1243,7 @@ export function InputBox({
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder={t.inputBox.searchModels} />
|
||||
<ModelSelectorList>
|
||||
{models.map((m) => (
|
||||
{modelOptions.map((m) => (
|
||||
<ModelSelectorItem
|
||||
key={m.name}
|
||||
value={m.name}
|
||||
@@ -1159,9 +1251,11 @@ export function InputBox({
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<ModelSelectorName>{m.display_name}</ModelSelectorName>
|
||||
<span className="text-muted-foreground truncate text-[10px]">
|
||||
{m.model}
|
||||
</span>
|
||||
<span className="text-muted-foreground truncate text-[10px]">
|
||||
{selectedSingleRoundRag
|
||||
? `单轮知识库问答 · ${m.name}`
|
||||
: m.model}
|
||||
</span>
|
||||
</div>
|
||||
{m.name === context.model_name ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
@@ -1169,8 +1263,8 @@ export function InputBox({
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
<PromptInputSubmit
|
||||
|
||||
@@ -33,7 +33,8 @@ import {
|
||||
} from "@/core/skill-display/runtime";
|
||||
import type { Subtask } from "@/core/tasks";
|
||||
import { useUpdateSubtask } from "@/core/tasks/context";
|
||||
import type { AgentThreadState } from "@/core/threads";
|
||||
import type { AgentThreadState } from "@/core/threads";
|
||||
import { isSingleRoundRagMessage } from "@/core/threads/use-single-round-rag";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||
|
||||
@@ -235,12 +236,17 @@ export function MessageList({
|
||||
}, [messages, askTimes]);
|
||||
|
||||
const [settings] = useLocalSettings();
|
||||
const ragModeEnabled =
|
||||
settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
|
||||
const { skills } = useSkills();
|
||||
const skillDisplayMap = useMemo(
|
||||
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[ragModeEnabled, skills],
|
||||
const ragModeEnabled =
|
||||
settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
|
||||
const hasSingleRoundRag = useMemo(
|
||||
() => messages.some(isSingleRoundRagMessage),
|
||||
[messages],
|
||||
);
|
||||
const referencesEnabled = ragModeEnabled || hasSingleRoundRag;
|
||||
const { skills } = useSkills();
|
||||
const skillDisplayMap = useMemo(
|
||||
() => (referencesEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[referencesEnabled, skills],
|
||||
);
|
||||
// Same per-turn reference batches the right-side panel renders (backend
|
||||
// batches preferred). Inline [n] tokens must resolve against these so badge
|
||||
@@ -373,7 +379,7 @@ export function MessageList({
|
||||
if (group.type === "human" || group.type === "assistant") {
|
||||
return group.messages.map((msg) => {
|
||||
const isAssistantMessage =
|
||||
ragModeEnabled &&
|
||||
referencesEnabled &&
|
||||
group.type === "assistant" &&
|
||||
msg.type === "ai";
|
||||
const batchSources = isAssistantMessage
|
||||
|
||||
@@ -46,20 +46,23 @@ function getModeDescriptionKey(
|
||||
}
|
||||
}
|
||||
|
||||
export function ModeHoverGuide({
|
||||
mode,
|
||||
children,
|
||||
showTitle = true,
|
||||
}: {
|
||||
mode: AgentMode;
|
||||
children: React.ReactNode;
|
||||
/** When true, tooltip shows "ModeName: Description". When false, only description. */
|
||||
showTitle?: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const label = t.inputBox[getModeLabelKey(mode)];
|
||||
const description = t.inputBox[getModeDescriptionKey(mode)];
|
||||
const content = showTitle ? `${label}: ${description}` : description;
|
||||
export function ModeHoverGuide({
|
||||
mode,
|
||||
children,
|
||||
showTitle = true,
|
||||
tooltipContent,
|
||||
}: {
|
||||
mode: AgentMode;
|
||||
children: React.ReactNode;
|
||||
/** When true, tooltip shows "ModeName: Description". When false, only description. */
|
||||
showTitle?: boolean;
|
||||
/** Overrides the standard mode tooltip for page-specific execution modes. */
|
||||
tooltipContent?: string;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const label = t.inputBox[getModeLabelKey(mode)];
|
||||
const description = t.inputBox[getModeDescriptionKey(mode)];
|
||||
const content = tooltipContent ?? (showTitle ? `${label}: ${description}` : description);
|
||||
|
||||
return <Tooltip content={content}>{children}</Tooltip>;
|
||||
}
|
||||
@@ -71,8 +71,9 @@ import { useTheme } from "@/contexts/ThemeContext";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import type { ValidateSkillUploadResponse } from "@/core/skills/api";
|
||||
import {
|
||||
useDeleteCustomSkill,
|
||||
import {
|
||||
useDeleteBuiltinSkill,
|
||||
useDeleteCustomSkill,
|
||||
useDuplicateSkill,
|
||||
useGenerateMissingSkillNameZh,
|
||||
useGenerateSkillNameZh,
|
||||
@@ -616,9 +617,10 @@ export function SkillRow({
|
||||
const { data: cardPublishSquares } = usePublishSquares();
|
||||
const setPinned = useSetSkillPinned();
|
||||
const setFeatured = useSetSkillFeatured();
|
||||
const setAlwaysOn = useSetSkillAlwaysOn();
|
||||
const { data: compression } = useSkillCompressionSettings();
|
||||
const deleteSkill = useDeleteCustomSkill();
|
||||
const setAlwaysOn = useSetSkillAlwaysOn();
|
||||
const { data: compression } = useSkillCompressionSettings();
|
||||
const deleteCustom = useDeleteCustomSkill();
|
||||
const deleteBuiltin = useDeleteBuiltinSkill();
|
||||
const duplicateSkillMutation = useDuplicateSkill();
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [tagPickerOpen, setTagPickerOpen] = useState(false);
|
||||
@@ -634,8 +636,9 @@ export function SkillRow({
|
||||
const isOwned =
|
||||
isCustom && !isBuiltin && !!skill.owner_user_id && skill.owner_user_id === currentUserId;
|
||||
const isFromOthers = isCustom && !isBuiltin && !isOwned;
|
||||
// Admin can edit/delete/unpublish anyone's skill; non-admin only their own.
|
||||
const canManage = isCustom && (isOwned || isAdmin);
|
||||
// Admin can manage custom skills from any owner; non-admin only their own.
|
||||
const canManage = isCustom && (isOwned || isAdmin);
|
||||
const canDelete = isAdmin || isOwned;
|
||||
const canTogglePublish = canManage && !isBuiltin;
|
||||
// 常驻(免压缩):内置技能仅管理员可设;自定义技能其所有者或管理员可设(与后端一致)。
|
||||
const canSetAlwaysOn = isAdmin || isOwned;
|
||||
@@ -686,11 +689,15 @@ export function SkillRow({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
try {
|
||||
await deleteSkill.mutateAsync(skill.name);
|
||||
toast.success(t.settings.skills.deleteSuccess);
|
||||
setConfirmDeleteOpen(false);
|
||||
async function handleDelete() {
|
||||
try {
|
||||
if (isBuiltin) {
|
||||
await deleteBuiltin.mutateAsync(skill.name);
|
||||
} else {
|
||||
await deleteCustom.mutateAsync(skill.name);
|
||||
}
|
||||
toast.success(t.settings.skills.deleteSuccess);
|
||||
setConfirmDeleteOpen(false);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
@@ -918,7 +925,7 @@ export function SkillRow({
|
||||
>
|
||||
<TagsIcon className="size-3.5" />
|
||||
</Button>
|
||||
{canManage && (
|
||||
{canManage && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
@@ -939,12 +946,12 @@ export function SkillRow({
|
||||
/>
|
||||
</Button>
|
||||
)}
|
||||
{canManage && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 w-8 shrink-0",
|
||||
{canManage && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 w-8 shrink-0",
|
||||
skill.pinned && "text-emerald-600 hover:text-emerald-700",
|
||||
)}
|
||||
disabled={setPinned.isPending}
|
||||
@@ -1011,11 +1018,11 @@ export function SkillRow({
|
||||
>
|
||||
<CopyIcon className="size-3.5" />
|
||||
</Button>
|
||||
{canManage && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
||||
{canDelete && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
|
||||
onClick={() => setConfirmDeleteOpen(true)}
|
||||
title={t.settings.skills.deleteAction}
|
||||
>
|
||||
@@ -1109,16 +1116,18 @@ export function SkillRow({
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setConfirmDeleteOpen(false)}
|
||||
disabled={deleteSkill.isPending}
|
||||
disabled={deleteCustom.isPending || deleteBuiltin.isPending}
|
||||
>
|
||||
{t.common.cancel}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => void handleDelete()}
|
||||
disabled={deleteSkill.isPending}
|
||||
>
|
||||
{deleteSkill.isPending ? t.common.loading : t.common.delete}
|
||||
disabled={deleteCustom.isPending || deleteBuiltin.isPending}
|
||||
>
|
||||
{deleteCustom.isPending || deleteBuiltin.isPending
|
||||
? t.common.loading
|
||||
: t.common.delete}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DownloadIcon,
|
||||
Loader2,
|
||||
PencilIcon,
|
||||
Trash2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
@@ -22,6 +23,7 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { getSkillFileDownloadURL } from "@/core/skills/api";
|
||||
import {
|
||||
useDeleteSkillFile,
|
||||
useSaveSkillFile,
|
||||
useSkillFileContent,
|
||||
} from "@/core/skills/hooks";
|
||||
@@ -66,6 +68,7 @@ export function SkillFilePreviewDialog({
|
||||
open ? path : null,
|
||||
);
|
||||
const save = useSaveSkillFile();
|
||||
const remove = useDeleteSkillFile();
|
||||
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState("");
|
||||
@@ -77,6 +80,8 @@ export function SkillFilePreviewDialog({
|
||||
}, [path, open]);
|
||||
|
||||
const fileEditable = !!data?.editable && treeEditable;
|
||||
const isRootSkillFile = path?.replace(/\\/g, "/").toLowerCase() === "skill.md";
|
||||
const fileDeletable = !!data && treeEditable && !isRootSkillFile;
|
||||
const isMarkdown = useMemo(() => {
|
||||
if (!path) return false;
|
||||
const lower = path.toLowerCase();
|
||||
@@ -115,6 +120,18 @@ export function SkillFilePreviewDialog({
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!skillName || !path) return;
|
||||
if (!window.confirm(tx.filesDeleteConfirm.replace("{path}", path))) return;
|
||||
try {
|
||||
await remove.mutateAsync({ skillName, path });
|
||||
toast.success(tx.filesDeleteSuccess);
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopyPath() {
|
||||
if (!path) return;
|
||||
await navigator.clipboard.writeText(path);
|
||||
@@ -158,6 +175,18 @@ export function SkillFilePreviewDialog({
|
||||
{tx.filesEditAction}
|
||||
</Button>
|
||||
)}
|
||||
{fileDeletable && !editing && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-xs text-destructive hover:text-destructive"
|
||||
onClick={() => void handleDelete()}
|
||||
disabled={remove.isPending}
|
||||
>
|
||||
{remove.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Trash2Icon className="size-3.5" />}
|
||||
{tx.filesDeleteAction}
|
||||
</Button>
|
||||
)}
|
||||
{editing && (
|
||||
<>
|
||||
<Button
|
||||
|
||||
@@ -184,7 +184,7 @@ export function WorkspaceNavChatList({
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
{/* <SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname.startsWith("/page/workspace/roundtable/position")}
|
||||
asChild
|
||||
@@ -195,7 +195,7 @@ export function WorkspaceNavChatList({
|
||||
<span>岗位会商</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenuItem> */}
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname === "/page/workspace/scheduled/tasks"}
|
||||
|
||||
@@ -545,10 +545,13 @@ export const enUS: Translations = {
|
||||
filesSaveAction: "Save",
|
||||
filesCancelEditAction: "Cancel",
|
||||
filesDownloadAction: "Download",
|
||||
filesCopyPathAction: "Copy path",
|
||||
filesDiscardConfirm: "Discard unsaved changes?",
|
||||
filesSaveSuccess: "File saved",
|
||||
filesReadOnlyHint: "Built-in skills are read-only.",
|
||||
filesCopyPathAction: "Copy path",
|
||||
filesDiscardConfirm: "Discard unsaved changes?",
|
||||
filesSaveSuccess: "File saved",
|
||||
filesDeleteAction: "Delete",
|
||||
filesDeleteConfirm: "Delete \"{path}\"? This cannot be undone.",
|
||||
filesDeleteSuccess: "File deleted",
|
||||
filesReadOnlyHint: "Only administrators can edit or delete built-in skill files.",
|
||||
viewDetailAction: "View skill details",
|
||||
stateSheet: {
|
||||
archivedTitle: "Archived skills",
|
||||
|
||||
@@ -475,10 +475,13 @@ export interface Translations {
|
||||
filesSaveAction: string;
|
||||
filesCancelEditAction: string;
|
||||
filesDownloadAction: string;
|
||||
filesCopyPathAction: string;
|
||||
filesDiscardConfirm: string;
|
||||
filesSaveSuccess: string;
|
||||
filesReadOnlyHint: string;
|
||||
filesCopyPathAction: string;
|
||||
filesDiscardConfirm: string;
|
||||
filesSaveSuccess: string;
|
||||
filesDeleteAction: string;
|
||||
filesDeleteConfirm: string;
|
||||
filesDeleteSuccess: string;
|
||||
filesReadOnlyHint: string;
|
||||
viewDetailAction: string;
|
||||
stateSheet: {
|
||||
archivedTitle: string;
|
||||
|
||||
@@ -524,8 +524,11 @@ export const zhCN: Translations = {
|
||||
filesDownloadAction: "下载",
|
||||
filesCopyPathAction: "复制路径",
|
||||
filesDiscardConfirm: "有未保存的修改,确定放弃吗?",
|
||||
filesSaveSuccess: "文件已保存",
|
||||
filesReadOnlyHint: "内置技能为只读,仅可查看。",
|
||||
filesSaveSuccess: "文件已保存",
|
||||
filesDeleteAction: "删除",
|
||||
filesDeleteConfirm: "确定删除“{path}”?该操作不可撤销。",
|
||||
filesDeleteSuccess: "文件已删除",
|
||||
filesReadOnlyHint: "仅管理员可以编辑或删除内置技能文件。",
|
||||
viewDetailAction: "查看技能详情",
|
||||
stateSheet: {
|
||||
archivedTitle: "归档的技能",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
export interface ManagedModel {
|
||||
name: string;
|
||||
display_name: string | null;
|
||||
description: string | null;
|
||||
use: string;
|
||||
model: string;
|
||||
base_url: string | null;
|
||||
request_timeout: number | null;
|
||||
max_retries: number | null;
|
||||
max_tokens: number | null;
|
||||
temperature: number | null;
|
||||
stream_usage: boolean | null;
|
||||
supports_thinking: boolean;
|
||||
supports_reasoning_effort: boolean;
|
||||
supports_vision: boolean;
|
||||
when_thinking_enabled: Record<string, unknown> | null;
|
||||
when_thinking_disabled: Record<string, unknown> | null;
|
||||
thinking: Record<string, unknown> | null;
|
||||
use_responses_api: boolean | null;
|
||||
output_version: string | null;
|
||||
extra_settings: Record<string, unknown>;
|
||||
api_key_configured: boolean;
|
||||
api_key_source: string | null;
|
||||
source: "config.yaml";
|
||||
}
|
||||
|
||||
export interface ManagedModelsResponse {
|
||||
models: ManagedModel[];
|
||||
config_path: string;
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
export interface ModelSavePayload {
|
||||
name: string;
|
||||
display_name?: string | null;
|
||||
description?: string | null;
|
||||
use: string;
|
||||
model: string;
|
||||
api_key?: string;
|
||||
clear_api_key?: boolean;
|
||||
base_url?: string | null;
|
||||
request_timeout?: number | null;
|
||||
max_retries?: number | null;
|
||||
max_tokens?: number | null;
|
||||
temperature?: number | null;
|
||||
stream_usage?: boolean | null;
|
||||
supports_thinking: boolean;
|
||||
supports_reasoning_effort: boolean;
|
||||
supports_vision: boolean;
|
||||
when_thinking_enabled?: Record<string, unknown> | null;
|
||||
when_thinking_disabled?: Record<string, unknown> | null;
|
||||
thinking?: Record<string, unknown> | null;
|
||||
use_responses_api?: boolean | null;
|
||||
output_version?: string | null;
|
||||
extra_settings: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ModelConnectionTestResult {
|
||||
success: boolean;
|
||||
latency_ms: number;
|
||||
message: string;
|
||||
preview?: string | null;
|
||||
}
|
||||
|
||||
async function readError(response: Response, fallback: string): Promise<never> {
|
||||
const payload = await response.json().catch(() => null) as { detail?: string } | null;
|
||||
throw new Error(payload?.detail || fallback);
|
||||
}
|
||||
|
||||
export async function loadManagedModels(): Promise<ManagedModelsResponse> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/models`);
|
||||
if (!response.ok) return readError(response, "加载模型配置失败");
|
||||
return response.json() as Promise<ManagedModelsResponse>;
|
||||
}
|
||||
|
||||
export async function createManagedModel(payload: ModelSavePayload): Promise<ManagedModel> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/models`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) return readError(response, "创建模型失败");
|
||||
return response.json() as Promise<ManagedModel>;
|
||||
}
|
||||
|
||||
export async function updateManagedModel(name: string, payload: ModelSavePayload): Promise<ManagedModel> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/models/${encodeURIComponent(name)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) return readError(response, "保存模型配置失败");
|
||||
return response.json() as Promise<ManagedModel>;
|
||||
}
|
||||
|
||||
export async function deleteManagedModel(name: string): Promise<void> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/models/${encodeURIComponent(name)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!response.ok) return readError(response, "删除模型失败");
|
||||
}
|
||||
|
||||
export async function testManagedModel(model: ModelSavePayload): Promise<ModelConnectionTestResult> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/admin/models/test`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model }),
|
||||
});
|
||||
if (!response.ok) return readError(response, "模型连接测试失败");
|
||||
return response.json() as Promise<ModelConnectionTestResult>;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
createManagedModel,
|
||||
deleteManagedModel,
|
||||
loadManagedModels,
|
||||
testManagedModel,
|
||||
updateManagedModel,
|
||||
type ModelSavePayload,
|
||||
} from "./api";
|
||||
|
||||
export const MANAGED_MODELS_QUERY_KEY = ["admin", "model-config"] as const;
|
||||
|
||||
export function useManagedModels() {
|
||||
return useQuery({
|
||||
queryKey: MANAGED_MODELS_QUERY_KEY,
|
||||
queryFn: loadManagedModels,
|
||||
staleTime: 10_000,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveManagedModel() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ name, payload, isNew }: { name: string; payload: ModelSavePayload; isNew: boolean }) =>
|
||||
isNew ? createManagedModel(payload) : updateManagedModel(name, payload),
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: MANAGED_MODELS_QUERY_KEY }),
|
||||
queryClient.invalidateQueries({ queryKey: ["models"] }),
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useTestManagedModel() {
|
||||
return useMutation({ mutationFn: testManagedModel });
|
||||
}
|
||||
|
||||
export function useDeleteManagedModel() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: deleteManagedModel,
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: MANAGED_MODELS_QUERY_KEY }),
|
||||
queryClient.invalidateQueries({ queryKey: ["models"] }),
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./api";
|
||||
export * from "./hooks";
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Model } from "./types";
|
||||
|
||||
export const SINGLE_ROUND_RAG_MODELS: Model[] = [
|
||||
{ id: "single-round-rag-openai3", name: "OpenAI3", model: "OpenAI3", display_name: "Qwen3-32B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai4", name: "OpenAI4", model: "OpenAI4", display_name: "Qwen3-235B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai5", name: "OpenAI5", model: "OpenAI5", display_name: "GLM-5", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai6", name: "OpenAI6", model: "OpenAI6", display_name: "Qwen3.5-27B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai7", name: "OpenAI7", model: "OpenAI7", display_name: "Qwen3-8B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai9", name: "OpenAI9", model: "OpenAI9", display_name: "四季7B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
];
|
||||
|
||||
export function isSingleRoundRagProfile(
|
||||
context: unknown,
|
||||
): boolean {
|
||||
return (
|
||||
typeof context === "object" &&
|
||||
context !== null &&
|
||||
(context as { execution_profile?: unknown }).execution_profile ===
|
||||
"single_round_rag"
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,11 @@ export interface Model {
|
||||
model: string;
|
||||
display_name: string;
|
||||
description?: string | null;
|
||||
supports_thinking?: boolean;
|
||||
supports_reasoning_effort?: boolean;
|
||||
}
|
||||
supports_thinking?: boolean;
|
||||
supports_reasoning_effort?: boolean;
|
||||
/** Execution profiles handled by the frontend instead of DeerFlow. */
|
||||
execution_profile?: "single_round_rag";
|
||||
}
|
||||
|
||||
export interface TokenUsageSettings {
|
||||
enabled: boolean;
|
||||
|
||||
@@ -402,15 +402,26 @@ export async function getSkillContent(
|
||||
return response.json() as Promise<SkillContentResponse>;
|
||||
}
|
||||
|
||||
export async function deleteCustomSkill(skillName: string): Promise<void> {
|
||||
export async function deleteCustomSkill(skillName: string): Promise<void> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(skillName)}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await parseDetailedError(response, "Failed to delete skill");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete a built-in skill. The backend permits this only for administrators. */
|
||||
export async function deleteBuiltinSkill(skillName: string): Promise<void> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/skills/${encodeURIComponent(skillName)}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await parseDetailedError(response, "Failed to delete built-in skill");
|
||||
}
|
||||
}
|
||||
|
||||
export interface SkillFileNode {
|
||||
name: string;
|
||||
@@ -479,7 +490,7 @@ export function getSkillFileDownloadURL(skillName: string, path: string): string
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveSkillFile(
|
||||
export async function saveSkillFile(
|
||||
skillName: string,
|
||||
path: string,
|
||||
content: string,
|
||||
@@ -494,9 +505,22 @@ export async function saveSkillFile(
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await parseDetailedError(response, "Failed to save skill file");
|
||||
}
|
||||
return response.json() as Promise<SkillFileSaveResponse>;
|
||||
}
|
||||
}
|
||||
return response.json() as Promise<SkillFileSaveResponse>;
|
||||
}
|
||||
|
||||
export async function deleteSkillFile(
|
||||
skillName: string,
|
||||
path: string,
|
||||
): Promise<void> {
|
||||
const url =
|
||||
`${getBackendBaseURL()}/api/skills/${encodeURIComponent(skillName)}/files/content` +
|
||||
`?path=${encodeURIComponent(path)}`;
|
||||
const response = await apiFetch(url, { method: "DELETE" });
|
||||
if (!response.ok) {
|
||||
throw await parseDetailedError(response, "Failed to delete skill file");
|
||||
}
|
||||
}
|
||||
|
||||
export interface SkillNameZhResponse {
|
||||
name: string;
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
deleteCustomSkill,
|
||||
import {
|
||||
deleteBuiltinSkill,
|
||||
deleteCustomSkill,
|
||||
deleteSkillFile,
|
||||
duplicateSkill,
|
||||
enableSkill,
|
||||
generateMissingSkillNameZh,
|
||||
@@ -318,7 +320,7 @@ export function useSkillFileContent(skillName: string | null, path: string | nul
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveSkillFile() {
|
||||
export function useSaveSkillFile() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
@@ -339,5 +341,33 @@ export function useSaveSkillFile() {
|
||||
void queryClient.invalidateQueries({ queryKey: ["skill", skillName] });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteSkillFile() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
skillName,
|
||||
path,
|
||||
}: {
|
||||
skillName: string;
|
||||
path: string;
|
||||
}) => deleteSkillFile(skillName, path),
|
||||
onSuccess: (_data, { skillName, path }) => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["skill-files", skillName] });
|
||||
void queryClient.removeQueries({ queryKey: ["skill-file", skillName, path] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteBuiltinSkill() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: deleteBuiltinSkill,
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["skills"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-skills"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -25,10 +25,13 @@ import { promptInputFilePartToFile, uploadFiles } from "../uploads";
|
||||
|
||||
import type { AgentThread, AgentThreadState } from "./types";
|
||||
|
||||
export type ToolEndEvent = {
|
||||
name: string;
|
||||
data: unknown;
|
||||
};
|
||||
export type ToolEndEvent = {
|
||||
name: string;
|
||||
data: unknown;
|
||||
toolCallId?: string;
|
||||
};
|
||||
|
||||
export type ToolStartEvent = ToolEndEvent;
|
||||
|
||||
export type ThreadStreamOptions = {
|
||||
threadId?: string | null | undefined;
|
||||
@@ -47,10 +50,11 @@ export type ThreadStreamOptions = {
|
||||
/** 额外写到新建 thread 的 metadata(与 agent_id 合并)。
|
||||
* 任务深链用 `{ taskId }` 把对话挂到任务下(1:N),列表按 metadata.taskId 过滤。 */
|
||||
threadMetadata?: Record<string, unknown>;
|
||||
onStart?: (threadId: string) => void;
|
||||
onFinish?: (state: AgentThreadState) => void;
|
||||
onToolEnd?: (event: ToolEndEvent) => void;
|
||||
};
|
||||
onStart?: (threadId: string) => void;
|
||||
onFinish?: (state: AgentThreadState) => void;
|
||||
onToolStart?: (event: ToolStartEvent) => void;
|
||||
onToolEnd?: (event: ToolEndEvent) => void;
|
||||
};
|
||||
|
||||
type SendMessageOptions = {
|
||||
additionalKwargs?: Record<string, unknown>;
|
||||
@@ -447,10 +451,11 @@ export function useThreadStream({
|
||||
assistantId,
|
||||
runOptions,
|
||||
threadMetadata,
|
||||
onStart,
|
||||
onFinish,
|
||||
onToolEnd,
|
||||
}: ThreadStreamOptions) {
|
||||
onStart,
|
||||
onFinish,
|
||||
onToolStart,
|
||||
onToolEnd,
|
||||
}: ThreadStreamOptions) {
|
||||
const { t } = useI18n();
|
||||
const [localSettings] = useLocalSettings();
|
||||
// Track the thread ID that is currently streaming to handle thread changes during streaming
|
||||
@@ -466,16 +471,17 @@ export function useThreadStream({
|
||||
lastStreamActivityAtRef.current = Date.now();
|
||||
}, []);
|
||||
|
||||
const listeners = useRef({
|
||||
onStart,
|
||||
onFinish,
|
||||
onToolEnd,
|
||||
});
|
||||
const listeners = useRef({
|
||||
onStart,
|
||||
onFinish,
|
||||
onToolStart,
|
||||
onToolEnd,
|
||||
});
|
||||
|
||||
// Keep listeners ref updated with latest callbacks
|
||||
useEffect(() => {
|
||||
listeners.current = { onStart, onFinish, onToolEnd };
|
||||
}, [onStart, onFinish, onToolEnd]);
|
||||
useEffect(() => {
|
||||
listeners.current = { onStart, onFinish, onToolStart, onToolEnd };
|
||||
}, [onStart, onFinish, onToolStart, onToolEnd]);
|
||||
|
||||
useEffect(() => {
|
||||
const normalizedThreadId = threadId ?? null;
|
||||
@@ -545,12 +551,6 @@ export function useThreadStream({
|
||||
},
|
||||
onLangChainEvent(event) {
|
||||
markStreamActivity();
|
||||
if (event.event === "on_tool_end") {
|
||||
listeners.current.onToolEnd?.({
|
||||
name: event.name,
|
||||
data: event.data,
|
||||
});
|
||||
}
|
||||
// 操作日志(Y-Log):每一次大模型调用结束都各上报一条(一次 LLM 调用 = 一条),
|
||||
// 让问答日志尽量「多、全」——一个问答轮次里 lead agent / 子代理的每次模型调用
|
||||
// 都会落一条。门控与失败静默都在 writeYLog 内部处理,绝不影响问答。
|
||||
@@ -572,8 +572,32 @@ export function useThreadStream({
|
||||
} catch {
|
||||
/* 上报绝不影响问答 */
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// The SDK emits UI tool lifecycle events on the dedicated `tools` stream
|
||||
// mode. `events` is a separate LangChain trace channel; using it for UI
|
||||
// reactions can miss a tool that the conversation has already rendered.
|
||||
onToolEvent:
|
||||
onToolStart || onToolEnd
|
||||
? (event) => {
|
||||
markStreamActivity();
|
||||
if (event.event === "on_tool_start") {
|
||||
listeners.current.onToolStart?.({
|
||||
name: event.name,
|
||||
data: event.input,
|
||||
toolCallId: event.toolCallId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.event === "on_tool_end") {
|
||||
listeners.current.onToolEnd?.({
|
||||
name: event.name,
|
||||
data: event.output,
|
||||
toolCallId: event.toolCallId,
|
||||
});
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
onUpdateEvent(data) {
|
||||
markStreamActivity();
|
||||
const updates: Array<Partial<AgentThreadState> | null> = Object.values(
|
||||
|
||||
@@ -23,11 +23,13 @@ export interface AgentThreadContext extends Record<string, unknown> {
|
||||
rag_mode_enabled?: boolean;
|
||||
/** Per-request switch for context compression (上下文压缩). Default off. */
|
||||
summarization_enabled?: boolean;
|
||||
/** Per-conversation switch for knowledge-base RAG injection (phase 2). */
|
||||
/** Per-conversation switch for knowledge-base RAG injection (phase 2). */
|
||||
knowledge_rag_enabled?: boolean;
|
||||
/** DeerFlow LLMWiki mapping ids selected for this conversation. */
|
||||
llmwiki_knowledge_base_ids?: string[];
|
||||
agent_id?: string;
|
||||
/** Direct knowledge-base RAG mode; this request never enters Lead Agent. */
|
||||
execution_profile?: "single_round_rag";
|
||||
agent_id?: string;
|
||||
/** @deprecated kept for reading legacy thread metadata; prefer agent_id */
|
||||
agent_name?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import type { Message } from "@langchain/langgraph-sdk";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
|
||||
const STORAGE_PREFIX = "workspace.single-round-rag.";
|
||||
|
||||
type KnowledgeBaseChunk = {
|
||||
answer?: unknown;
|
||||
docs?: unknown;
|
||||
};
|
||||
|
||||
type RagSource = {
|
||||
id?: string;
|
||||
title: string;
|
||||
type: string;
|
||||
snippet: string;
|
||||
content: string;
|
||||
source?: string;
|
||||
time?: string;
|
||||
url?: string;
|
||||
raw: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/** Same JSON-object framing used by the established GeneralQA single-RAG flow. */
|
||||
function extractJsonObjects(raw: string): { objects: string[]; rest: string } {
|
||||
const objects: string[] = [];
|
||||
let depth = 0;
|
||||
let stringQuote: '"' | "'" | null = null;
|
||||
let escaped = false;
|
||||
let start = -1;
|
||||
for (let index = 0; index < raw.length; index += 1) {
|
||||
const char = raw[index]!;
|
||||
if (stringQuote) {
|
||||
if (escaped) escaped = false;
|
||||
else if (char === "\\") escaped = true;
|
||||
else if (char === stringQuote) stringQuote = null;
|
||||
continue;
|
||||
}
|
||||
if (char === '"' || char === "'") {
|
||||
stringQuote = char;
|
||||
continue;
|
||||
}
|
||||
if (char === "{") {
|
||||
if (depth === 0) start = index;
|
||||
depth += 1;
|
||||
} else if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0 && start !== -1) {
|
||||
objects.push(raw.slice(start, index + 1));
|
||||
start = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return depth > 0 && start !== -1
|
||||
? { objects, rest: raw.slice(start) }
|
||||
: { objects, rest: "" };
|
||||
}
|
||||
|
||||
/** Same `<think>` split semantics as GeneralQA, kept local to avoid loading its demo data. */
|
||||
function parseSingleRagStream(chunks: { answer: string }[]) {
|
||||
let thinkingMarkdown = "";
|
||||
let answerMarkdown = "";
|
||||
let inThink = false;
|
||||
let thinkingComplete = false;
|
||||
for (const { answer } of chunks) {
|
||||
let remaining = answer;
|
||||
while (remaining) {
|
||||
if (inThink) {
|
||||
const endIndex = remaining.indexOf("</think>");
|
||||
if (endIndex === -1) {
|
||||
thinkingMarkdown += remaining;
|
||||
remaining = "";
|
||||
} else {
|
||||
thinkingMarkdown += remaining.slice(0, endIndex);
|
||||
remaining = remaining.slice(endIndex + "</think>".length);
|
||||
inThink = false;
|
||||
thinkingComplete = true;
|
||||
}
|
||||
} else {
|
||||
const startIndex = remaining.indexOf("<think>");
|
||||
if (startIndex === -1) {
|
||||
answerMarkdown += remaining;
|
||||
remaining = "";
|
||||
} else {
|
||||
answerMarkdown += remaining.slice(0, startIndex);
|
||||
remaining = remaining.slice(startIndex + "<think>".length);
|
||||
inThink = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { thinkingMarkdown, answerMarkdown, thinkingComplete };
|
||||
}
|
||||
|
||||
function storageKey(threadId: string) {
|
||||
return `${STORAGE_PREFIX}${threadId}`;
|
||||
}
|
||||
|
||||
function readStoredMessages(threadId: string): Message[] {
|
||||
if (typeof window === "undefined" || !threadId) return [];
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(storageKey(threadId));
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed) ? (parsed as Message[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredMessages(threadId: string, messages: Message[]) {
|
||||
if (typeof window === "undefined" || !threadId) return;
|
||||
try {
|
||||
window.sessionStorage.setItem(storageKey(threadId), JSON.stringify(messages));
|
||||
} catch {
|
||||
// Quota errors must never interrupt an already-running answer.
|
||||
}
|
||||
}
|
||||
|
||||
function parseLooseStringValue(rawValue: string): string {
|
||||
try {
|
||||
return JSON.parse(rawValue) as string;
|
||||
} catch {
|
||||
const value = rawValue.trim();
|
||||
if (value.startsWith("'") && value.endsWith("'")) {
|
||||
return value
|
||||
.slice(1, -1)
|
||||
.replace(/\\n/g, "\n")
|
||||
.replace(/\\r/g, "\r")
|
||||
.replace(/\\t/g, "\t")
|
||||
.replace(/\\'/g, "'")
|
||||
.replace(/\\\\/g, "\\");
|
||||
}
|
||||
throw new Error(`无法解析知识库流片段:${rawValue}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseKnowledgeBaseChunk(jsonText: string): KnowledgeBaseChunk {
|
||||
try {
|
||||
return JSON.parse(jsonText) as KnowledgeBaseChunk;
|
||||
} catch {
|
||||
const objectText = jsonText.trim();
|
||||
const answerMatch = objectText.match(/^\{\s*answer\s*:\s*([\s\S]*)\s*\}$/);
|
||||
if (answerMatch) {
|
||||
return { answer: parseLooseStringValue(answerMatch[1]!.trim()) };
|
||||
}
|
||||
const docsMatch = objectText.match(/^\{\s*docs\s*:\s*([\s\S]*)\s*\}$/);
|
||||
if (docsMatch) {
|
||||
const rawValue = docsMatch[1]!.trim();
|
||||
try {
|
||||
return { docs: JSON.parse(rawValue) };
|
||||
} catch {
|
||||
return { docs: parseLooseStringValue(rawValue) };
|
||||
}
|
||||
}
|
||||
const normalizedText = objectText.replace(
|
||||
/([{,]\s*)(answer|docs)(\s*:)/g,
|
||||
'$1"$2"$3',
|
||||
);
|
||||
return JSON.parse(normalizedText) as KnowledgeBaseChunk;
|
||||
}
|
||||
}
|
||||
|
||||
function flattenDocs(value: unknown): Record<string, unknown>[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value.flatMap((item) => flattenDocs(item));
|
||||
}
|
||||
if (!value || typeof value !== "object") return [];
|
||||
const record = value as Record<string, unknown>;
|
||||
if ("docs" in record) return flattenDocs(record.docs);
|
||||
return [record];
|
||||
}
|
||||
|
||||
function normalizeSources(value: unknown): RagSource[] {
|
||||
return flattenDocs(value).map((item, index) => {
|
||||
const title = String(item.m_title ?? item.title ?? item.source ?? `参考资料 ${index + 1}`);
|
||||
const content = String(item.m_content ?? item.content ?? item.snippet ?? "");
|
||||
const source = item.source1 ?? item.source;
|
||||
const rawUrl = item.url ?? item.link ?? item.href;
|
||||
return {
|
||||
id: String(item.recUuid ?? item.rec_uuid ?? item.uuid ?? item.id ?? "") || undefined,
|
||||
title,
|
||||
type: String(item.source1 ?? item.type ?? "知识库"),
|
||||
snippet: content,
|
||||
content,
|
||||
source: typeof source === "string" ? source : undefined,
|
||||
time: typeof item.m_publish === "string" ? item.m_publish : undefined,
|
||||
url: typeof rawUrl === "string" && /^https?:\/\//i.test(rawUrl) ? rawUrl : undefined,
|
||||
raw: item,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function createId(prefix: string) {
|
||||
return `${prefix}-${crypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown) {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function isSingleRoundRagMessage(message: Message): boolean {
|
||||
return message.additional_kwargs?.single_round_rag === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Frontend-only adapter for the existing general-QA single-round endpoint.
|
||||
* It deliberately never submits a run to DeerFlow or mutates the Lead Agent.
|
||||
*/
|
||||
export function useSingleRoundRagMessages(threadId: string) {
|
||||
const [messages, setMessages] = useState<Message[]>(() => readStoredMessages(threadId));
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const controllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setMessages(readStoredMessages(threadId));
|
||||
setError(null);
|
||||
}, [threadId]);
|
||||
|
||||
useEffect(() => () => controllerRef.current?.abort(), []);
|
||||
|
||||
const updateMessages = useCallback(
|
||||
(targetThreadId: string, updater: (current: Message[]) => Message[]) => {
|
||||
setMessages((current) => {
|
||||
const next = updater(current);
|
||||
writeStoredMessages(targetThreadId, next);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const stop = useCallback(() => controllerRef.current?.abort(), []);
|
||||
|
||||
const submit = useCallback(
|
||||
async ({
|
||||
targetThreadId,
|
||||
query,
|
||||
modelName,
|
||||
}: {
|
||||
targetThreadId: string;
|
||||
query: string;
|
||||
modelName: string;
|
||||
}) => {
|
||||
if (isLoading) return;
|
||||
const question = query.trim();
|
||||
if (!question) return;
|
||||
|
||||
const humanId = createId("single-rag-human");
|
||||
const assistantId = createId("single-rag-ai");
|
||||
const sourceId = createId("single-rag-sources");
|
||||
const clientTs = new Date().toISOString();
|
||||
const userMessage: Message = {
|
||||
id: humanId,
|
||||
type: "human",
|
||||
content: [{ type: "text", text: question }],
|
||||
additional_kwargs: { client_ts: clientTs, single_round_rag: true },
|
||||
};
|
||||
const initialAssistant: Message = {
|
||||
id: assistantId,
|
||||
type: "ai",
|
||||
content: "",
|
||||
additional_kwargs: { single_round_rag: true },
|
||||
};
|
||||
updateMessages(targetThreadId, (current) => [...current, userMessage, initialAssistant]);
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
const controller = new AbortController();
|
||||
controllerRef.current = controller;
|
||||
const answerChunks: { answer: string }[] = [];
|
||||
let sources: RagSource[] = [];
|
||||
|
||||
const refreshAssistant = () => {
|
||||
const trace = parseSingleRagStream(answerChunks);
|
||||
updateMessages(targetThreadId, (current) => {
|
||||
const next = current.filter((message) => message.id !== sourceId);
|
||||
const assistantIndex = next.findIndex((message) => message.id === assistantId);
|
||||
if (assistantIndex < 0) return current;
|
||||
next[assistantIndex] = {
|
||||
...next[assistantIndex],
|
||||
content: trace.answerMarkdown,
|
||||
additional_kwargs: {
|
||||
...next[assistantIndex]!.additional_kwargs,
|
||||
single_round_rag: true,
|
||||
reasoning_content: trace.thinkingMarkdown || null,
|
||||
},
|
||||
} as Message;
|
||||
if (sources.length > 0) {
|
||||
next.splice(assistantIndex, 0, {
|
||||
id: sourceId,
|
||||
type: "tool",
|
||||
name: "knowledge_base_search",
|
||||
content: { results: sources },
|
||||
additional_kwargs: {
|
||||
hide_from_ui: true,
|
||||
single_round_rag: true,
|
||||
},
|
||||
} as unknown as Message);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
const chatUrl = readRuntimeEnv("VITE_AIPI_CHAT_URL") || "";
|
||||
if (!chatUrl) {
|
||||
throw new Error("未配置 VITE_AIPI_CHAT_URL,无法发起单轮 RAG 问答。");
|
||||
}
|
||||
const response = await fetch(
|
||||
`${chatUrl.replace(/\/$/, "")}/chat/knowledge_base_chat_tiaoshi`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
query: question,
|
||||
knowledge_base_name: [],
|
||||
top_k: 5,
|
||||
score_threshold: 0.5,
|
||||
history: [],
|
||||
stream: true,
|
||||
model_name: modelName,
|
||||
temperature: 0.3,
|
||||
prompt_name: "default",
|
||||
local_doc_url: false,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new Error(`知识库服务请求失败(${response.status})`);
|
||||
if (!response.body) throw new Error("知识库服务未返回流式响应。");
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const extracted = extractJsonObjects(buffer);
|
||||
buffer = extracted.rest;
|
||||
for (const jsonText of extracted.objects) {
|
||||
const chunk = parseKnowledgeBaseChunk(jsonText);
|
||||
if (typeof chunk.answer === "string") answerChunks.push({ answer: chunk.answer });
|
||||
if (chunk.docs !== undefined) sources = normalizeSources(chunk.docs);
|
||||
refreshAssistant();
|
||||
}
|
||||
}
|
||||
} catch (caught) {
|
||||
if (!isAbortError(caught)) {
|
||||
const message = caught instanceof Error ? caught.message : "单轮 RAG 问答失败。";
|
||||
setError(message);
|
||||
updateMessages(targetThreadId, (current) =>
|
||||
current.map((item) =>
|
||||
item.id === assistantId
|
||||
? ({
|
||||
...item,
|
||||
content: answerChunks.length > 0 ? item.content : message,
|
||||
additional_kwargs: {
|
||||
...item.additional_kwargs,
|
||||
single_round_rag: true,
|
||||
},
|
||||
} as Message)
|
||||
: item,
|
||||
),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (controllerRef.current === controller) controllerRef.current = null;
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[isLoading, updateMessages],
|
||||
);
|
||||
|
||||
return { messages, isLoading, error, submit, stop };
|
||||
}
|
||||
@@ -45,6 +45,10 @@ import { PanelLeftOpen } from "lucide-react";
|
||||
import { useAgentSelector, useAgentsPaginated } from "@/core/agents";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import {
|
||||
isSingleRoundRagProfile,
|
||||
SINGLE_ROUND_RAG_MODELS,
|
||||
} from "@/core/models/single-round-rag";
|
||||
import { useNotification } from "@/core/notification/hooks";
|
||||
import {
|
||||
getLastAgentId,
|
||||
@@ -54,6 +58,7 @@ import {
|
||||
} from "@/core/settings";
|
||||
import { useThreadStream } from "@/core/threads/hooks";
|
||||
import { queueLlmWikiConversationDeposit } from "@/core/llmwiki/conversation-deposit";
|
||||
import { useSingleRoundRagMessages } from "@/core/threads/use-single-round-rag";
|
||||
import { useLayoutMode } from "@/core/system-settings/hooks";
|
||||
import { useRouteBase } from "@/core/route-base";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
@@ -304,6 +309,20 @@ export default function ChatPage() {
|
||||
}
|
||||
},
|
||||
});
|
||||
const singleRoundRag = useSingleRoundRagMessages(threadId);
|
||||
const singleRoundRagSelected = isSingleRoundRagProfile(settings.context);
|
||||
const displayThread = useMemo(() => {
|
||||
if (singleRoundRag.messages.length === 0 && !singleRoundRag.isLoading) {
|
||||
return thread;
|
||||
}
|
||||
const messages = [...thread.messages, ...singleRoundRag.messages];
|
||||
return {
|
||||
...thread,
|
||||
values: { ...thread.values, messages },
|
||||
messages,
|
||||
isLoading: thread.isLoading || singleRoundRag.isLoading,
|
||||
} as typeof thread;
|
||||
}, [singleRoundRag.isLoading, singleRoundRag.messages, thread]);
|
||||
|
||||
const writingArtifactPath = useMemo(() => {
|
||||
const isMarkdown = (path: string | null | undefined) =>
|
||||
@@ -318,6 +337,46 @@ export default function ChatPage() {
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(message: PromptInputMessage) => {
|
||||
if (singleRoundRagSelected) {
|
||||
if (message.files && message.files.length > 0) {
|
||||
toast.error("单轮 RAG 问答暂不支持附件,请移除附件后重试。");
|
||||
return;
|
||||
}
|
||||
setHasStartedConversation(true);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("workspace:sandbox-resume-autoscroll"),
|
||||
);
|
||||
void (async () => {
|
||||
try {
|
||||
let targetThreadId = threadId;
|
||||
if (isNewThread) {
|
||||
const created = await getAPIClient(isMock).threads.create({});
|
||||
targetThreadId = created.thread_id;
|
||||
setThreadId(targetThreadId);
|
||||
setIsNewThread(false);
|
||||
history.replaceState(
|
||||
null,
|
||||
"",
|
||||
`${window.location.pathname}${window.location.search}#${routeBase}/chats/${targetThreadId}`,
|
||||
);
|
||||
const title = message.text.trim().replace(/\s+/g, " ").slice(0, 60);
|
||||
if (title) {
|
||||
void getAPIClient(isMock).threads
|
||||
.updateState(targetThreadId, { values: { title } })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
await singleRoundRag.submit({
|
||||
targetThreadId,
|
||||
query: message.text,
|
||||
modelName: settings.context.model_name ?? "OpenAI3",
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "单轮 RAG 问答失败。");
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
// If the user picked an agent before sending the opening turn, hand off
|
||||
// to AgentChatPage so the conversation runs against that agent. We stash
|
||||
// the pending text in sessionStorage because the next/navigation shim
|
||||
@@ -420,7 +479,13 @@ export default function ChatPage() {
|
||||
isMock,
|
||||
router,
|
||||
settings.context.writing_mode,
|
||||
settings.context.model_name,
|
||||
writingArtifactPath,
|
||||
singleRoundRag,
|
||||
singleRoundRagSelected,
|
||||
routeBase,
|
||||
setIsNewThread,
|
||||
setThreadId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -511,8 +576,12 @@ export default function ChatPage() {
|
||||
saveLastAgentId(agentId);
|
||||
}, []);
|
||||
const handleStop = useCallback(async () => {
|
||||
if (singleRoundRag.isLoading) {
|
||||
singleRoundRag.stop();
|
||||
return;
|
||||
}
|
||||
await thread.stop();
|
||||
}, [thread]);
|
||||
}, [singleRoundRag, thread]);
|
||||
|
||||
const promptPrefixProp = useMemo(() => {
|
||||
if (!promptPrefixSettings?.enabled) return undefined;
|
||||
@@ -558,7 +627,7 @@ export default function ChatPage() {
|
||||
const compactActionsHidden = isHideChromeActive();
|
||||
|
||||
return (
|
||||
<ThreadContext.Provider value={{ thread, isMock }}>
|
||||
<ThreadContext.Provider value={{ thread: displayThread, isMock }}>
|
||||
<ChatBox threadId={threadId}>
|
||||
<div
|
||||
className={cn(
|
||||
@@ -576,7 +645,7 @@ export default function ChatPage() {
|
||||
)}
|
||||
>
|
||||
<div className="flex w-full items-center text-sm font-medium">
|
||||
<ThreadTitle threadId={threadId} thread={thread} />
|
||||
<ThreadTitle threadId={threadId} thread={displayThread} />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 仅在收起态显示「展开历史」钮;展开后由侧栏内(新对话右侧)的收起钮负责收起。 */}
|
||||
@@ -595,7 +664,7 @@ export default function ChatPage() {
|
||||
)}
|
||||
<TokenUsageIndicator
|
||||
enabled={tokenUsageEnabled}
|
||||
messages={thread.messages}
|
||||
messages={displayThread.messages}
|
||||
/>
|
||||
<ExportTrigger threadId={threadId} />
|
||||
<KnowledgeSaveTrigger threadId={threadId} />
|
||||
@@ -633,7 +702,7 @@ export default function ChatPage() {
|
||||
<MessageList
|
||||
className={cn("size-full", "pt-10")}
|
||||
threadId={threadId}
|
||||
thread={thread}
|
||||
thread={displayThread}
|
||||
paddingBottom={messageListPaddingBottom}
|
||||
tokenUsageEnabled={tokenUsageEnabled}
|
||||
// 输入框为底部绝对浮层(约 160px 高),按钮上移到其上方居中。
|
||||
@@ -675,9 +744,9 @@ export default function ChatPage() {
|
||||
<div className="absolute right-0 bottom-0 left-0">
|
||||
<TodoList
|
||||
className="bg-background/5"
|
||||
todos={thread.values.todos ?? []}
|
||||
todos={displayThread.values.todos ?? []}
|
||||
hidden={
|
||||
!thread.values.todos || thread.values.todos.length === 0
|
||||
!displayThread.values.todos || displayThread.values.todos.length === 0
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
@@ -702,16 +771,18 @@ export default function ChatPage() {
|
||||
status={
|
||||
thread.error
|
||||
? "error"
|
||||
: thread.isLoading
|
||||
: displayThread.isLoading
|
||||
? "streaming"
|
||||
: "ready"
|
||||
}
|
||||
context={settings.context}
|
||||
extraModels={SINGLE_ROUND_RAG_MODELS}
|
||||
disabled={
|
||||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" ||
|
||||
isUploading ||
|
||||
agentHandoffPending ||
|
||||
knowledgeSelectionLoading
|
||||
knowledgeSelectionLoading ||
|
||||
singleRoundRag.isLoading
|
||||
}
|
||||
onContextChange={(context) =>
|
||||
setSettings("context", context)
|
||||
@@ -771,7 +842,7 @@ export default function ChatPage() {
|
||||
*/}
|
||||
{!isLandingState && (
|
||||
<QuestionNavigator
|
||||
messages={thread.messages}
|
||||
messages={displayThread.messages}
|
||||
className="top-16 right-0 bottom-48 left-0"
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,491 @@
|
||||
import {
|
||||
BotIcon,
|
||||
ChevronDownIcon,
|
||||
CircleAlertIcon,
|
||||
CpuIcon,
|
||||
EyeIcon,
|
||||
KeyRoundIcon,
|
||||
LoaderCircleIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
Settings2Icon,
|
||||
SparklesIcon,
|
||||
Trash2Icon,
|
||||
WrenchIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Button as TButton,
|
||||
Dialog,
|
||||
Input,
|
||||
InputNumber,
|
||||
MessagePlugin,
|
||||
Select,
|
||||
Switch,
|
||||
Tag,
|
||||
Textarea,
|
||||
} from "tdesign-react";
|
||||
|
||||
import {
|
||||
type ManagedModel,
|
||||
type ModelSavePayload,
|
||||
useDeleteManagedModel,
|
||||
useManagedModels,
|
||||
useSaveManagedModel,
|
||||
useTestManagedModel,
|
||||
} from "@/core/model-management";
|
||||
import {
|
||||
WorkspaceBody,
|
||||
WorkspaceContainer,
|
||||
WorkspaceHeader,
|
||||
} from "@/components/workspace/workspace-container";
|
||||
|
||||
type ModelDraft = ModelSavePayload & {
|
||||
api_key: string;
|
||||
keep_existing_key: boolean;
|
||||
extra_settings_text: string;
|
||||
};
|
||||
|
||||
const PROVIDER_OPTIONS = [
|
||||
{ label: "OpenAI 兼容接口", value: "langchain_openai:ChatOpenAI" },
|
||||
{ label: "Anthropic", value: "langchain_anthropic:ChatAnthropic" },
|
||||
{ label: "Google Gemini", value: "langchain_google_genai:ChatGoogleGenerativeAI" },
|
||||
{ label: "Groq", value: "langchain_groq:ChatGroq" },
|
||||
{ label: "Ollama", value: "langchain_ollama:ChatOllama" },
|
||||
];
|
||||
|
||||
const emptyDraft = (): ModelDraft => ({
|
||||
name: "",
|
||||
display_name: "",
|
||||
description: "",
|
||||
use: "langchain_openai:ChatOpenAI",
|
||||
model: "",
|
||||
api_key: "",
|
||||
keep_existing_key: false,
|
||||
clear_api_key: false,
|
||||
base_url: "",
|
||||
request_timeout: 30,
|
||||
max_retries: 2,
|
||||
max_tokens: undefined,
|
||||
temperature: undefined,
|
||||
stream_usage: true,
|
||||
supports_thinking: false,
|
||||
supports_reasoning_effort: false,
|
||||
supports_vision: false,
|
||||
when_thinking_enabled: null,
|
||||
when_thinking_disabled: null,
|
||||
thinking: null,
|
||||
use_responses_api: null,
|
||||
output_version: null,
|
||||
extra_settings: {},
|
||||
extra_settings_text: "{}",
|
||||
});
|
||||
|
||||
function draftFromModel(model: ManagedModel): ModelDraft {
|
||||
return {
|
||||
...model,
|
||||
api_key: "",
|
||||
keep_existing_key: model.api_key_configured,
|
||||
clear_api_key: false,
|
||||
extra_settings_text: JSON.stringify(model.extra_settings ?? {}, null, 2),
|
||||
};
|
||||
}
|
||||
|
||||
function optionalString(value: string | null | undefined): string | null {
|
||||
const normalized = (value ?? "").trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
function toNumber(value: number | string | null | undefined): number | undefined {
|
||||
if (value === "" || value === null || value === undefined) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function buildPayload(draft: ModelDraft): ModelSavePayload {
|
||||
let extraSettings: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed = JSON.parse(draft.extra_settings_text || "{}") as unknown;
|
||||
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
|
||||
throw new Error("额外参数必须是 JSON 对象");
|
||||
}
|
||||
extraSettings = parsed as Record<string, unknown>;
|
||||
} catch (error) {
|
||||
throw error instanceof Error ? error : new Error("额外参数不是有效 JSON");
|
||||
}
|
||||
const payload: ModelSavePayload = {
|
||||
name: draft.name.trim(),
|
||||
display_name: optionalString(draft.display_name),
|
||||
description: optionalString(draft.description),
|
||||
use: draft.use.trim(),
|
||||
model: draft.model.trim(),
|
||||
clear_api_key: Boolean(draft.clear_api_key),
|
||||
base_url: optionalString(draft.base_url),
|
||||
request_timeout: toNumber(draft.request_timeout),
|
||||
max_retries: toNumber(draft.max_retries),
|
||||
max_tokens: toNumber(draft.max_tokens),
|
||||
temperature: toNumber(draft.temperature),
|
||||
stream_usage: draft.stream_usage,
|
||||
supports_thinking: draft.supports_thinking,
|
||||
supports_reasoning_effort: draft.supports_reasoning_effort,
|
||||
supports_vision: draft.supports_vision,
|
||||
when_thinking_enabled: draft.when_thinking_enabled,
|
||||
when_thinking_disabled: draft.when_thinking_disabled,
|
||||
thinking: draft.thinking,
|
||||
use_responses_api: draft.use_responses_api,
|
||||
output_version: optionalString(draft.output_version),
|
||||
extra_settings: extraSettings,
|
||||
};
|
||||
if (draft.api_key.trim()) payload.api_key = draft.api_key.trim();
|
||||
return payload;
|
||||
}
|
||||
|
||||
function StatCard({ icon: Icon, label, value }: { icon: typeof CpuIcon; label: string; value: number }) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 shadow-sm">
|
||||
<span className="flex size-10 items-center justify-center rounded-lg bg-primary/10 text-primary"><Icon className="size-5" /></span>
|
||||
<div><div className="text-xl font-semibold tabular-nums">{value}</div><div className="text-xs text-muted-foreground">{label}</div></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, required = false, children }: { label: string; required?: boolean; children: ReactNode }) {
|
||||
return <label className="space-y-1.5 text-sm font-medium">{label}{required && <span className="ml-1 text-destructive">*</span>}{children}</label>;
|
||||
}
|
||||
|
||||
function ModelCapabilityBadge({
|
||||
icon: Icon,
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
icon?: typeof KeyRoundIcon;
|
||||
label: string;
|
||||
className: string;
|
||||
}) {
|
||||
return (
|
||||
<span className={`inline-flex h-7 items-center gap-1 whitespace-nowrap rounded px-2 text-xs font-medium leading-none ${className}`}>
|
||||
{Icon && <Icon aria-hidden className="block size-3.5 shrink-0" />}
|
||||
<span className="block leading-none">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function showGlobalMessage(
|
||||
theme: "success" | "error" | "warning",
|
||||
content: string,
|
||||
) {
|
||||
// Schedule after the modal state update so the message is rendered above
|
||||
// the page, rather than inside or behind a closing dialog.
|
||||
window.setTimeout(() => {
|
||||
MessagePlugin.closeAll();
|
||||
void MessagePlugin[theme]({
|
||||
content,
|
||||
duration: 5_000,
|
||||
placement: "top",
|
||||
zIndex: 10_000,
|
||||
attach: () => document.body,
|
||||
});
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function ModelEditor({ model, onClose }: { model: ManagedModel | null; onClose: () => void }) {
|
||||
const isNew = model === null;
|
||||
const [draft, setDraft] = useState<ModelDraft>(() => model ? draftFromModel(model) : emptyDraft());
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
const [testResult, setTestResult] = useState<{ success: boolean; latency: number; message: string; preview?: string | null } | null>(null);
|
||||
const save = useSaveManagedModel();
|
||||
const test = useTestManagedModel();
|
||||
const patch = (next: Partial<ModelDraft>) => setDraft((current) => ({ ...current, ...next }));
|
||||
|
||||
const handleTest = async () => {
|
||||
try {
|
||||
const payload = buildPayload(draft);
|
||||
const result = await test.mutateAsync(payload);
|
||||
setTestResult({ success: result.success, latency: result.latency_ms, message: result.message, preview: result.preview });
|
||||
if (!result.success) return void showGlobalMessage("error", `连接失败:${result.message}`);
|
||||
showGlobalMessage("success", `连接成功${result.latency_ms ? `,${result.latency_ms} ms` : ""}`);
|
||||
} catch (error) {
|
||||
showGlobalMessage("error", error instanceof Error ? error.message : "连接测试失败");
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
const payload = buildPayload(draft);
|
||||
if (!payload.name || !payload.use || !payload.model) {
|
||||
return void showGlobalMessage("warning", "请填写模型标识、驱动与实际模型名");
|
||||
}
|
||||
await save.mutateAsync({ name: model?.name ?? payload.name, payload, isNew });
|
||||
onClose();
|
||||
showGlobalMessage(
|
||||
"success",
|
||||
isNew
|
||||
? `模型“${payload.name}”已添加,所有页面的模型选择器已刷新。`
|
||||
: `模型“${payload.name}”的配置已保存并立即生效。`,
|
||||
);
|
||||
} catch (error) {
|
||||
showGlobalMessage("error", error instanceof Error ? error.message : "保存模型配置失败");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
visible
|
||||
header={isNew ? "添加模型" : `编辑模型:${model?.display_name || model?.name}`}
|
||||
placement="center"
|
||||
width={860}
|
||||
zIndex={3200}
|
||||
confirmBtn={{ content: isNew ? "添加并启用" : "保存配置", theme: "primary" }}
|
||||
cancelBtn="取消"
|
||||
confirmLoading={save.isPending}
|
||||
onClose={onClose}
|
||||
onConfirm={() => void handleSave()}
|
||||
onCancel={onClose}
|
||||
>
|
||||
<div className="max-h-[70vh] space-y-5 overflow-y-auto px-1 py-1 pr-3">
|
||||
<div className="rounded-lg border border-primary/20 bg-primary/5 px-3 py-2 text-sm text-muted-foreground">
|
||||
保存会直接更新当前部署的 <code className="rounded bg-background px-1 py-0.5">config.yaml</code> 模型段,自动备份并热刷新;不会中断已开始的会话。
|
||||
</div>
|
||||
<section className="grid gap-4 md:grid-cols-2">
|
||||
<Field label="稳定标识" required><Input value={draft.name} disabled={!isNew} placeholder="例如 deepseek-chat" tips={isNew ? "保存后不可修改,用于智能体和运行配置引用。" : "稳定标识不可修改,避免已有配置失效。"} onChange={(value) => patch({ name: String(value) })} /></Field>
|
||||
<Field label="显示名称"><Input value={draft.display_name ?? ""} placeholder="例如 DeepSeek Chat" onChange={(value) => patch({ display_name: String(value) })} /></Field>
|
||||
<Field label="模型驱动" required><Select value={draft.use} options={PROVIDER_OPTIONS} filterable creatable inputProps={{ placeholder: "选择或输入 use 类路径" }} onChange={(value) => patch({ use: String(value) })} /></Field>
|
||||
<Field label="实际模型名" required><Input value={draft.model} placeholder="例如 deepseek-chat" onChange={(value) => patch({ model: String(value) })} /></Field>
|
||||
<Field label="Base URL"><Input value={draft.base_url ?? ""} type="url" placeholder="https://api.example.com/v1" onChange={(value) => patch({ base_url: String(value) })} /></Field>
|
||||
<Field label="API Key"><Input value={draft.api_key} type="password" placeholder={draft.keep_existing_key && !draft.clear_api_key ? "已配置,留空则保持不变" : "可填写密钥或 $ENVIRONMENT_VARIABLE"} onChange={(value) => patch({ api_key: String(value), clear_api_key: false })} /></Field>
|
||||
{draft.keep_existing_key && !draft.api_key && <div className="md:col-span-2 flex items-center gap-2 text-xs text-muted-foreground"><KeyRoundIcon className="size-3.5" />已配置密钥{model?.api_key_source ? `(环境变量 ${model.api_key_source})` : ""},不会回显。<TButton theme="default" variant="text" size="small" onClick={() => patch({ clear_api_key: !draft.clear_api_key })}>{draft.clear_api_key ? "撤销清除" : "清除密钥"}</TButton></div>}
|
||||
<div className="md:col-span-2"><Field label="描述"><Textarea value={draft.description ?? ""} autosize={{ minRows: 2, maxRows: 4 }} placeholder="说明模型适用的任务与限制" onChange={(value) => patch({ description: String(value) })} /></Field></div>
|
||||
</section>
|
||||
<section className="rounded-lg border border-border p-4">
|
||||
<div className="mb-2"><h3 className="font-medium">能力声明</h3><p className="mt-1 text-xs text-muted-foreground">这些标识决定哪些页面会向模型提供思考、视觉或工具调用入口。</p></div>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-3 text-sm"><span className="flex items-center gap-2"><Switch value={draft.supports_thinking} onChange={(value) => patch({ supports_thinking: Boolean(value) })} />支持思考</span><span className="flex items-center gap-2"><Switch value={draft.supports_vision} onChange={(value) => patch({ supports_vision: Boolean(value) })} />支持视觉</span><span className="flex items-center gap-2"><Switch value={draft.supports_reasoning_effort} onChange={(value) => patch({ supports_reasoning_effort: Boolean(value) })} />推理档位</span></div>
|
||||
</section>
|
||||
<div className="flex items-center justify-between border-t pt-4"><TButton theme="default" variant="outline" loading={test.isPending} onClick={() => void handleTest()}><WrenchIcon className="mr-1.5 size-4" />测试连接</TButton><TButton theme="default" variant="text" onClick={() => setAdvanced((value) => !value)}><Settings2Icon className="mr-1.5 size-4" />高级配置 <ChevronDownIcon className={`ml-1 size-4 transition-transform ${advanced ? "rotate-180" : ""}`} /></TButton></div>
|
||||
{testResult && <div className={`rounded-lg border px-3 py-2 text-sm ${testResult.success ? "border-primary/20 bg-primary/5 text-foreground" : "border-destructive/25 bg-destructive/5 text-destructive"}`}><div className="font-medium">{testResult.success ? "连接成功" : "连接失败"}{testResult.success && testResult.latency ? ` · ${testResult.latency} ms` : ""}</div><p className="mt-1 break-words text-xs opacity-80">{testResult.preview || testResult.message}</p></div>}
|
||||
{advanced && <section className="space-y-4 rounded-lg border border-dashed border-border bg-muted/10 p-4"><div className="grid gap-4 md:grid-cols-3"><Field label="请求超时(秒)"><InputNumber value={draft.request_timeout ?? ""} min={1} max={600} onChange={(value) => patch({ request_timeout: toNumber(value) })} /></Field><Field label="最大重试次数"><InputNumber value={draft.max_retries ?? ""} min={0} max={20} onChange={(value) => patch({ max_retries: toNumber(value) })} /></Field><Field label="最大输出 Token"><InputNumber value={draft.max_tokens ?? ""} min={1} max={1_000_000} onChange={(value) => patch({ max_tokens: toNumber(value) })} /></Field><Field label="温度"><InputNumber value={draft.temperature ?? ""} min={0} max={2} step={0.1} decimalPlaces={1} onChange={(value) => patch({ temperature: toNumber(value) })} /></Field><span className="flex items-end gap-2 pb-1 text-sm font-medium"><Switch value={draft.stream_usage ?? true} onChange={(value) => patch({ stream_usage: Boolean(value) })} />流式 Token 统计</span></div><Field label="额外参数 JSON"><Textarea value={draft.extra_settings_text} autosize={{ minRows: 4, maxRows: 10 }} placeholder={'{\n "extra_body": {}\n}'} onChange={(value) => patch({ extra_settings_text: String(value) })} /><p className="text-xs font-normal text-muted-foreground">保留并编辑配置文件中未在基础表单展示的兼容参数。必须为 JSON 对象。</p></Field></section>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ModelManagementPage() {
|
||||
const { data, isLoading, error, refetch, isFetching } = useManagedModels();
|
||||
const [search, setSearch] = useState("");
|
||||
const [filter, setFilter] = useState<"all" | "thinking" | "vision">("all");
|
||||
const [editor, setEditor] = useState<ManagedModel | null | "new">(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<ManagedModel | null>(null);
|
||||
const remove = useDeleteManagedModel();
|
||||
const models = useMemo(() => {
|
||||
const keyword = search.trim().toLowerCase();
|
||||
return (data?.models ?? []).filter((model) => {
|
||||
const matchesFilter = filter === "all" || (filter === "thinking" ? model.supports_thinking : model.supports_vision);
|
||||
const matchesSearch = !keyword || [model.name, model.display_name, model.model, model.use].filter(Boolean).join(" ").toLowerCase().includes(keyword);
|
||||
return matchesFilter && matchesSearch;
|
||||
});
|
||||
}, [data?.models, filter, search]);
|
||||
const stats = useMemo(() => ({ total: data?.models.length ?? 0, thinking: data?.models.filter((item) => item.supports_thinking).length ?? 0, vision: data?.models.filter((item) => item.supports_vision).length ?? 0 }), [data?.models]);
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTarget)
|
||||
return;
|
||||
try {
|
||||
await remove.mutateAsync(deleteTarget.name);
|
||||
const deletedName = deleteTarget.name;
|
||||
setDeleteTarget(null);
|
||||
showGlobalMessage("success", `模型“${deletedName}”已删除,配置已立即生效。`);
|
||||
}
|
||||
catch (error) {
|
||||
showGlobalMessage("error", error instanceof Error ? error.message : "删除模型失败,请稍后重试。");
|
||||
}
|
||||
};
|
||||
return (
|
||||
<WorkspaceContainer>
|
||||
<WorkspaceHeader />
|
||||
<WorkspaceBody>
|
||||
<main className="flex size-full min-h-0 flex-col overflow-y-auto bg-background px-6 py-5 md:px-8">
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
||||
<header className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
|
||||
<CpuIcon className="size-5" />
|
||||
</span>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">模型配置</h1>
|
||||
</div>
|
||||
<p className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">
|
||||
管理当前部署 <code className="rounded bg-muted px-1 py-0.5">config.yaml</code> 中的对话模型。保存后所有页面立即可选;密钥仅可写入,永不回显。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<TButton theme="default" variant="outline" loading={isFetching} onClick={() => void refetch()}>
|
||||
<RefreshCwIcon className="mr-1.5 size-4" />刷新
|
||||
</TButton>
|
||||
<TButton theme="primary" onClick={() => setEditor("new")}>
|
||||
<PlusIcon className="mr-1.5 size-4" />添加模型
|
||||
</TButton>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<StatCard icon={BotIcon} label="已配置模型" value={stats.total} />
|
||||
<StatCard icon={SparklesIcon} label="支持思考" value={stats.thinking} />
|
||||
<StatCard icon={EyeIcon} label="支持视觉" value={stats.vision} />
|
||||
</div>
|
||||
|
||||
<section className="rounded-xl border border-border bg-card shadow-sm">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 py-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{([
|
||||
["all", "全部"],
|
||||
["thinking", "支持思考"],
|
||||
["vision", "支持视觉"],
|
||||
] as const).map(([value, label]) => (
|
||||
<TButton
|
||||
key={value}
|
||||
theme={filter === value ? "primary" : "default"}
|
||||
variant={filter === value ? "base" : "text"}
|
||||
size="small"
|
||||
onClick={() => setFilter(value)}
|
||||
>
|
||||
{label}
|
||||
</TButton>
|
||||
))}
|
||||
</div>
|
||||
<Input
|
||||
value={search}
|
||||
placeholder="搜索名称、模型或驱动"
|
||||
clearable
|
||||
className="w-full sm:w-72"
|
||||
onChange={(value) => setSearch(String(value))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isLoading && (
|
||||
<div className="flex h-52 items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<LoaderCircleIcon className="size-4 animate-spin" />加载模型配置…
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="m-4 flex items-start gap-2 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
<CircleAlertIcon className="mt-0.5 size-4" />{error.message}
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && !error && models.length === 0 && (
|
||||
<div className="flex h-52 flex-col items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<CpuIcon className="size-7" />没有匹配的模型配置
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && !error && models.length > 0 && (
|
||||
<div className="grid gap-3 p-4 lg:grid-cols-2">
|
||||
{models.map((model) => (
|
||||
<article key={model.name} className="rounded-lg border border-border bg-background p-4 transition-colors hover:border-primary/35">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 className="truncate font-semibold">{model.display_name || model.name}</h2>
|
||||
<Tag theme="success" variant="light" size="small">config.yaml</Tag>
|
||||
</div>
|
||||
<p className="mt-1 truncate font-mono text-xs text-muted-foreground">{model.name}</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<TButton theme="default" variant="outline" size="small" onClick={() => setEditor(model)}>
|
||||
配置
|
||||
</TButton>
|
||||
<TButton
|
||||
theme="danger"
|
||||
variant="text"
|
||||
size="small"
|
||||
aria-label={"删除模型 " + (model.display_name || model.name)}
|
||||
onClick={() => setDeleteTarget(model)}
|
||||
>
|
||||
<Trash2Icon className="mr-1 size-3.5" />删除
|
||||
</TButton>
|
||||
</div>
|
||||
</div>
|
||||
{model.description ? (
|
||||
<p className="mt-3 line-clamp-2 min-h-10 text-sm leading-5 text-muted-foreground">{model.description}</p>
|
||||
) : (
|
||||
<p className="mt-3 min-h-10 text-sm leading-5 text-muted-foreground">未填写描述</p>
|
||||
)}
|
||||
<div className="mt-3 grid gap-2 border-t pt-3 text-xs text-muted-foreground sm:grid-cols-2">
|
||||
<span className="truncate" title={model.use}>驱动:{model.use}</span>
|
||||
<span className="truncate" title={model.model}>模型:{model.model}</span>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-1.5">
|
||||
{model.api_key_configured && (
|
||||
<ModelCapabilityBadge
|
||||
icon={KeyRoundIcon}
|
||||
label="已配置密钥"
|
||||
className="bg-muted text-foreground"
|
||||
/>
|
||||
)}
|
||||
{model.supports_thinking && (
|
||||
<ModelCapabilityBadge
|
||||
icon={SparklesIcon}
|
||||
label="思考"
|
||||
className="bg-primary/10 text-primary"
|
||||
/>
|
||||
)}
|
||||
{model.supports_vision && (
|
||||
<ModelCapabilityBadge
|
||||
icon={EyeIcon}
|
||||
label="视觉"
|
||||
className="bg-amber-500/10 text-amber-700 dark:text-amber-300"
|
||||
/>
|
||||
)}
|
||||
{model.supports_reasoning_effort && (
|
||||
<ModelCapabilityBadge
|
||||
label="推理档位"
|
||||
className="bg-muted text-muted-foreground"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{data?.config_path && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
当前配置文件:<code>{data.config_path}</code>
|
||||
{data.updated_at ? " · 最近更新 " + new Date(data.updated_at).toLocaleString() : ""}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</WorkspaceBody>
|
||||
|
||||
{editor !== null && (
|
||||
<ModelEditor
|
||||
key={editor === "new" ? "new" : editor.name}
|
||||
model={editor === "new" ? null : editor}
|
||||
onClose={() => setEditor(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deleteTarget && (
|
||||
<Dialog
|
||||
visible
|
||||
header="删除模型"
|
||||
placement="center"
|
||||
width={440}
|
||||
zIndex={3200}
|
||||
confirmBtn={{ content: "删除", theme: "danger" }}
|
||||
cancelBtn="取消"
|
||||
confirmLoading={remove.isPending}
|
||||
onClose={() => {
|
||||
if (!remove.isPending) setDeleteTarget(null);
|
||||
}}
|
||||
onCancel={() => {
|
||||
if (!remove.isPending) setDeleteTarget(null);
|
||||
}}
|
||||
onConfirm={() => void handleDelete()}
|
||||
>
|
||||
<p className="text-sm leading-6 text-muted-foreground">
|
||||
确定要删除模型 <code className="rounded bg-muted px-1 py-0.5">{deleteTarget.name}</code> 吗?删除后会立即更新运行中的模型配置,依赖它的智能体或任务可能无法继续使用。
|
||||
</p>
|
||||
</Dialog>
|
||||
)}
|
||||
</WorkspaceContainer>
|
||||
);
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import MemoryPage from './MemoryPage';
|
||||
import PromptPrefixSettingsPage from './PromptPrefixSettingsPage';
|
||||
import PrivateSquareSettingsPage from './PrivateSquareSettingsPage';
|
||||
import ModelConcurrencySettingsPage from './ModelConcurrencySettingsPage';
|
||||
import ModelManagementPage from './ModelManagementPage';
|
||||
import PublishSquaresSettingsPage from './PublishSquaresSettingsPage';
|
||||
import SkillCompressionSettingsPage from './SkillCompressionSettingsPage';
|
||||
import SkillEvolutionPage from './SkillEvolutionPage';
|
||||
@@ -785,6 +786,18 @@ export default function WorkspaceRoutes({
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="admin/models"
|
||||
element={
|
||||
getStoredAuth()?.system_role === 'admin' ? (
|
||||
<WorkspaceLayout {...layoutProps}>
|
||||
<ModelManagementPage />
|
||||
</WorkspaceLayout>
|
||||
) : (
|
||||
<Navigate to="/page/workspace/chats/new" replace />
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="settings/model-concurrency"
|
||||
element={
|
||||
|
||||
@@ -24,11 +24,23 @@
|
||||
|
||||
| 参数 | 是否必填 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| `taskId` | 否 | 外部任务 ID。缺失时使用本地 mock 任务,便于演示和开发。 |
|
||||
| `taskId` | 否 | 外部任务 ID。传入后它是岗位会商的共享存储作用域;缺失时保持原有的个人会话逻辑。mock 仅提供任务卡片的显示兜底,绝不替换路由传入的 ID。 |
|
||||
| `sessionId` | 否 | 直接恢复指定岗位会商会话;缺失时页面会按 `taskId` 查找最近一条未归档会话。 |
|
||||
| `positionId` | 否 | 初始打开的岗位,同时同步顶部岗位选择器。无效值回退到 `intelligence`。 |
|
||||
| `new=1` | 否 | 强制不恢复历史会话,以新会话开始。 |
|
||||
|
||||
传入 `taskId` 时,同一个任务下可以有多条会商会话,所有用户共享同一份历史、节点快照与 LangGraph 线程;当前 `user_id` 仅保留创建审计,不参与这些任务会话的读写过滤。页面恢复 `sessionId` 时会核验其 `externalTaskId` 与路由 `taskId` 一致,不一致会丢弃该会话并按当前任务重新发现历史。未传 `taskId` 时,会继续只读取当前用户的原有个人会话。
|
||||
|
||||
### 外部系统按 taskId 对接
|
||||
|
||||
1. 进入页面时将业务侧任务的稳定主键原样放入 URL。工作区入口使用 `/#/page/workspace/roundtable/position?taskId=<taskId>`;策略页入口也兼容 `/#/page/strategy/qa/position-roundtable?taskId=<taskId>`。不要使用任务标题、序号或每次请求都变化的临时 ID。
|
||||
2. 前端先调用 `GET /api/position-roundtable/sessions?external_task_id=<taskId>`;返回的是该任务下所有用户共享的会商记录,按最近更新时间排序。选中一条后再调用 `GET /sessions/{sessionId}` 恢复完整节点和聊天快照。
|
||||
3. 没有可恢复记录时,调用 `POST /sessions`,至少传入 `{ external_task_id: taskId, task_snapshot: { ...任务展示字段 } }`。服务端将 `task_scoped` 设为 `true`,并固定快照中的 `id` / `externalTaskId` 为传入的 taskId。
|
||||
4. 后续所有意图、链条、节点、收口智能体和历史删除 API 只使用返回的 `sessionId`;不要在每次消息请求中重新创建会话。一个 taskId 可以有多条 sessionId。
|
||||
5. 不传 `taskId`(同时省略 `external_task_id`)就是兼容模式:后端只返回和操作当前用户自己的个人会话,绝不会把历史记录升级为共享。响应中的 `task_scoped` 可用来区分两种记录。
|
||||
|
||||
服务端从请求中的非空 `external_task_id` 判断是否开启共享,调用方无需也不应自行传 `task_scoped`。
|
||||
|
||||
当前岗位 ID 定义在 `lib/positions.ts`:
|
||||
|
||||
| ID | 页面岗位 | 职责 |
|
||||
@@ -109,6 +121,31 @@ PositionRoundtablePage
|
||||
|
||||
后端会冻结链条快照并根据链条阶段创建节点。已启动后意图不可再修改;需要重新识别时必须新建会话。
|
||||
|
||||
The position workspace selects the dedicated built-in `position-roundtable-intent`
|
||||
agent by sending `intent_agent_id` through the shared Step-1 init and stream
|
||||
requests. The thread lifecycle, file upload, and SSE transport stay identical
|
||||
to the generic multi-agent flow. The dedicated agent permits at most five
|
||||
user-assistance rounds; one round may contain multiple independent
|
||||
`ask_clarification` cards. `Step1Panel` renders every card separately and
|
||||
submits the selected answers together, so cards must never be merged into one
|
||||
numbered multi-question card. Only its final `[INTENT_READY]` schema changes to
|
||||
the following four string arrays:
|
||||
|
||||
```json
|
||||
{
|
||||
"coreGoals": ["..."],
|
||||
"riskWarnings": ["..."],
|
||||
"keyPoints": ["..."],
|
||||
"strategicSignificance": ["..."]
|
||||
}
|
||||
```
|
||||
|
||||
The position sidebar and edit dialog render these four fields. Business-chain
|
||||
activation requires all four arrays and at least one core goal or strategic
|
||||
significance. Historic `objective` / `constraints` / `assumptions` snapshots
|
||||
are read through a compatibility mapping only; ordinary multi-agent Step 1 is
|
||||
not changed.
|
||||
|
||||
### 4.2 普通节点问答
|
||||
|
||||
`PositionNodeChat` 在发送前调用 `getPositionNodeContext` 获取受长度控制的任务、意图和已交付上游内容,再以 `task_external_context` 作为隐藏上下文发送给当前智能体。
|
||||
@@ -132,10 +169,16 @@ PositionRoundtablePage
|
||||
|
||||
页面只维护一个 `sandboxArtifact`。`PositionNodeChat` 和 `PositionBuiltinAgentChat` 通过 `onPreviewArtifact` 上报预览目标;父页面统一渲染 `ArtifactFileDetail`。
|
||||
|
||||
**对接 / 重做页面 / 排障指南(打开关闭时机、步骤条、接口约定):**
|
||||
[`../../docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md`](../../docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md)
|
||||
(目录说明见 [`../../docs/position-roundtable-sandbox/README.md`](../../docs/position-roundtable-sandbox/README.md))
|
||||
|
||||
设计要点:
|
||||
|
||||
- 文件正在由 `write_file` 流式生成时,优先显示源码;完成后交由预览组件切换 Markdown 预览;
|
||||
- `sandboxThreadSnapshot` 有 160ms 合并节流,只保留当前打开文件所在线程的最新快照,避免流式时频繁 setState;
|
||||
- `write_file` 的参数是一整个 JSON 流,键顺序由模型决定。若 `content` 先于 `path` 到达,会先用临时文件名(`未命名文件.md`/`.html`,按正文首部嗅探)开沙箱——流式内容只按 `message_id` + `tool_call_id` 定位,与路径无关;真实 `path` 到达后沿用同一个 `previewKey` 改名,属于「更新」而非第二次交付;
|
||||
- 流式快照**不能进页面 state**。本页很大(任务面板、意图结果、流程图、节点对话),按流式频率重渲染整页会把主线程占满,连消息列表都会停止绘制直到本轮结束。快照走 `createSandboxThreadStore()` + `SandboxThreadProvider`(`useSyncExternalStore`),只有沙箱子树重渲染;
|
||||
- 快照的合并节流是**前沿**节流:距上次推送超过 160ms 就在流回调里同步推送,未满则挂一个补尾定时器。不能只靠尾随定时器——主线程繁忙时回调会被饿死,面板会一直冻在打开时的内容;
|
||||
- 用户手动关闭后,`closedSandboxKeyRef` 与 `suppressedAutoPreviewThreadIdsRef` 阻止同一线程立即把沙箱重新打开;
|
||||
- 切岗位、切节点、切收口阶段、新建会话和切换历史会话都会先调用 `closeSandbox()`。
|
||||
|
||||
@@ -158,8 +201,8 @@ PositionRoundtablePage
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/sessions?external_task_id=` | 按任务查询会话,用于恢复最近会话和历史记录。 |
|
||||
| `POST` | `/sessions` | 创建初始会话并保存任务快照。 |
|
||||
| `GET` | `/sessions?external_task_id=<taskId>` | 传入时按任务作用域查询共享会话;不传参数时查询当前用户的个人历史。 |
|
||||
| `POST` | `/sessions` | 创建会话并保存任务快照;传入非空 `external_task_id` 时服务端会将快照 ID 固定为该值并启用共享;缺失或空值时创建原有个人会话。 |
|
||||
| `GET` | `/sessions/{id}` | 恢复会话、节点和冻结快照。 |
|
||||
| `DELETE` | `/sessions/{id}` | 删除一条岗位会商历史及其节点;删除当前记录时前端会先屏蔽并发恢复请求。 |
|
||||
| `PUT` | `/sessions/{id}/task` | 更新未冻结的任务快照。 |
|
||||
@@ -173,7 +216,7 @@ PositionRoundtablePage
|
||||
| `POST` | `/sessions/{id}/summary/*` | 准备、发送和完成方案总结。 |
|
||||
| `POST` | `/sessions/{id}/action-plan/*` | 准备、发送和完成行动规划。 |
|
||||
| `PUT` | `/sessions/{id}/{summary|action-plan}/conversation` | 保存两个收口智能体的消息与未发送草稿。 |
|
||||
| `POST` | `/demo/seed` | 按用户和 `demoKey` 幂等初始化完整演示会话。 |
|
||||
| `POST` | `/demo/seed` | 按 `demoKey` 幂等初始化完整演示会话。 |
|
||||
|
||||
后端实现在 `offline-backend-20260512/backend/app/gateway/routers/position_roundtable.py`。
|
||||
|
||||
|
||||
@@ -68,7 +68,10 @@ export interface PositionRoundtableNode {
|
||||
*/
|
||||
export interface PositionRoundtableSession {
|
||||
id: string;
|
||||
/** Present only when the workspace was opened with a route `taskId`. */
|
||||
externalTaskId: string | null;
|
||||
/** True only for sessions intentionally shared by an explicit route taskId. */
|
||||
taskScoped: boolean;
|
||||
taskSnapshot: Record<string, unknown>;
|
||||
chainId: string | null;
|
||||
chainSnapshot: Record<string, unknown> | null;
|
||||
@@ -112,6 +115,7 @@ interface ServerNode {
|
||||
interface ServerSession {
|
||||
id: string;
|
||||
external_task_id: string | null;
|
||||
task_scoped?: boolean;
|
||||
task_snapshot?: Record<string, unknown>;
|
||||
chain_id: string | null;
|
||||
chain_snapshot?: Record<string, unknown> | null;
|
||||
@@ -270,6 +274,7 @@ function toSession(session: ServerSession): PositionRoundtableSession {
|
||||
const result: PositionRoundtableSession = {
|
||||
id: session.id,
|
||||
externalTaskId: session.external_task_id,
|
||||
taskScoped: session.task_scoped ?? false,
|
||||
taskSnapshot: session.task_snapshot ?? {},
|
||||
chainId: session.chain_id,
|
||||
chainSnapshot: session.chain_snapshot ?? null,
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
import { useEffect, useRef, type ComponentProps } from "react";
|
||||
import { useEffect, useMemo, useRef, type ComponentProps } from "react";
|
||||
|
||||
import { InputBox } from "@/components/workspace/input-box";
|
||||
import { usePromptInputController } from "@/components/ai-elements/prompt-input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
usePromptInputController,
|
||||
type PromptInputMessage,
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import type { InputBox } from "@/components/workspace/input-box";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import type { AgentQuestion } from "@/core/agents";
|
||||
import { PositionIntentInput } from "@/position-roundtable/components/PositionIntentInput";
|
||||
|
||||
type PositionAgentInputProps = ComponentProps<typeof InputBox> & {
|
||||
type InputBoxProps = ComponentProps<typeof InputBox>;
|
||||
type PositionAgentInputProps = Pick<
|
||||
InputBoxProps,
|
||||
| "className"
|
||||
| "assistantId"
|
||||
| "status"
|
||||
| "disabled"
|
||||
| "context"
|
||||
| "onContextChange"
|
||||
| "onSubmit"
|
||||
| "onStop"
|
||||
| "isNewThread"
|
||||
| "threadId"
|
||||
| "hideAdminRecommendedQuestions"
|
||||
> & {
|
||||
commonQuestions?: (string | AgentQuestion)[] | null;
|
||||
/** Stable node/builtin key used to restore the matching SQL-backed draft. */
|
||||
draftKey?: string;
|
||||
draftValue?: string;
|
||||
@@ -18,18 +38,36 @@ type PositionAgentInputProps = ComponentProps<typeof InputBox> & {
|
||||
* 只改这个组件即可,不会影响普通对话、工作区或其他业务页面。
|
||||
*/
|
||||
export function PositionAgentInput({
|
||||
className,
|
||||
context,
|
||||
disabled = false,
|
||||
status = "ready",
|
||||
onContextChange,
|
||||
onSubmit,
|
||||
onStop,
|
||||
commonQuestions,
|
||||
draftKey = "",
|
||||
draftValue = "",
|
||||
onDraftChange,
|
||||
...props
|
||||
}: PositionAgentInputProps) {
|
||||
const { textInput } = usePromptInputController();
|
||||
const { textInput, attachments } = usePromptInputController();
|
||||
const { models } = useModels();
|
||||
const activeDraftKeyRef = useRef("");
|
||||
const restoringValueRef = useRef<string | null>(null);
|
||||
const textInputRef = useRef(textInput);
|
||||
textInputRef.current = textInput;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() => models.map((model) => ({ label: model.display_name ?? model.name, value: model.name })),
|
||||
[models],
|
||||
);
|
||||
const attachedFiles = useMemo(
|
||||
() =>
|
||||
attachments.files
|
||||
.map((attachment) => attachment.file)
|
||||
.filter((file): file is File => file instanceof File),
|
||||
[attachments.files],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
activeDraftKeyRef.current = draftKey;
|
||||
if (textInputRef.current.value !== draftValue) {
|
||||
@@ -51,13 +89,60 @@ export function PositionAgentInput({
|
||||
onDraftChange?.(textInput.value);
|
||||
}, [draftKey, onDraftChange, textInput.value]);
|
||||
|
||||
// Keep the page-specific class on the wrapper rather than adding a variant
|
||||
// to InputBox. Node chat and built-in chat can evolve together while every
|
||||
// other workspace keeps the global composer untouched.
|
||||
const handleSend = () => {
|
||||
if (status === "streaming") {
|
||||
onStop?.();
|
||||
return;
|
||||
}
|
||||
const text = textInput.value.trim();
|
||||
if (!text && attachedFiles.length === 0) return;
|
||||
const message: PromptInputMessage = {
|
||||
text: textInput.value,
|
||||
files: attachments.files,
|
||||
};
|
||||
void onSubmit?.(message);
|
||||
textInput.clear();
|
||||
attachments.clear();
|
||||
};
|
||||
|
||||
const handleModelChange = (modelName: string) => {
|
||||
const model = models.find((candidate) => candidate.name === modelName);
|
||||
if (!model) return;
|
||||
onContextChange?.({ ...context, model_name: model.name });
|
||||
};
|
||||
const selectedModel =
|
||||
typeof context.model_name === "string"
|
||||
? context.model_name
|
||||
: modelOptions[0]?.value;
|
||||
|
||||
return (
|
||||
<InputBox
|
||||
{...props}
|
||||
className={cn("position-roundtable-agent-input w-full", className)}
|
||||
<PositionIntentInput
|
||||
value={textInput.value}
|
||||
onValueChange={textInput.setInput}
|
||||
attachedFiles={attachedFiles}
|
||||
onAddFiles={attachments.add}
|
||||
onRemoveFile={(index) => {
|
||||
const attachment = attachments.files[index];
|
||||
if (attachment) attachments.remove(attachment.id);
|
||||
}}
|
||||
charactersLeft={textInput.value.length}
|
||||
isSending={status === "streaming"}
|
||||
canSend={!disabled && (Boolean(textInput.value.trim()) || attachedFiles.length > 0)}
|
||||
pendingClarification={false}
|
||||
onSend={handleSend}
|
||||
onStop={() => onStop?.()}
|
||||
onFollowUp={() => undefined}
|
||||
onSkip={() => undefined}
|
||||
onEnterRoundtable={() => undefined}
|
||||
enterButtonLabel=""
|
||||
intentReady={null}
|
||||
hideEnterRoundtable
|
||||
onManualSave={() => undefined}
|
||||
onTriggerToast={() => undefined}
|
||||
modelOptions={modelOptions}
|
||||
selectedModel={selectedModel}
|
||||
onSelectedModelChange={handleModelChange}
|
||||
commonQuestions={commonQuestions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -716,7 +716,7 @@ export function PositionBuiltinAgentChat({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="position-roundtable-agent-composer-bar shrink-0 border-t border-slate-100 px-4 py-3 dark:border-[#2b8ffe]/20">
|
||||
<div className="position-roundtable-agent-composer-bar position-roundtable-node-composer shrink-0">
|
||||
<PositionAgentInput
|
||||
className="w-full"
|
||||
isNewThread={!boundThreadId}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { useRef } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import {
|
||||
FileText,
|
||||
Loader2,
|
||||
Paperclip,
|
||||
Pause,
|
||||
Repeat,
|
||||
Save,
|
||||
Send,
|
||||
Smile,
|
||||
Sparkles,
|
||||
X,
|
||||
@@ -14,7 +11,11 @@ import {
|
||||
import { Select as TSelect } from "tdesign-react";
|
||||
|
||||
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
|
||||
import { normalizeAgentQuestions, type AgentQuestion } from "@/core/agents";
|
||||
import type { Step1InputAreaProps } from "@/roundtable-planning/components/Step1Panel";
|
||||
import moreTaskIcon from "@/assets/position-roundtable/more-task.svg";
|
||||
import uploadFileIcon from "@/assets/position-roundtable/upload-file.svg";
|
||||
import sendMessageIcon from "@/assets/position-roundtable/send-message.svg";
|
||||
|
||||
interface PositionIntentModelOption {
|
||||
label: string;
|
||||
@@ -25,6 +26,7 @@ interface PositionIntentInputProps extends Step1InputAreaProps {
|
||||
modelOptions?: PositionIntentModelOption[];
|
||||
selectedModel?: string;
|
||||
onSelectedModelChange?: (model: string) => void;
|
||||
commonQuestions?: (string | AgentQuestion)[] | null;
|
||||
}
|
||||
|
||||
/** Keep attachment metadata presentation local to this position-only composer. */
|
||||
@@ -64,40 +66,25 @@ export function PositionIntentInput({
|
||||
modelOptions = [],
|
||||
selectedModel,
|
||||
onSelectedModelChange,
|
||||
commonQuestions,
|
||||
}: PositionIntentInputProps) {
|
||||
// Files are owned by Step1Panel. This ref only opens the native picker and
|
||||
// forwards its selection through onAddFiles, so replacement layouts do not
|
||||
// accidentally create a second attachment state.
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [showMoreQuestions, setShowMoreQuestions] = useState(false);
|
||||
const normalizedCommonQuestions = normalizeAgentQuestions(commonQuestions);
|
||||
const visibleCommonQuestions = normalizedCommonQuestions.slice(0, 2);
|
||||
const extraCommonQuestions = normalizedCommonQuestions.slice(2);
|
||||
|
||||
const pickCommonQuestion = (question: AgentQuestion) => {
|
||||
onValueChange(question.prompt);
|
||||
setShowMoreQuestions(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="position-roundtable-intent-input position-roundtable-intent-composer shrink-0 border-t border-slate-200 bg-[#f7faff] px-4 py-3 dark:border-[#2b8ffe]/35 dark:bg-[#071a38]">
|
||||
<div className="position-roundtable-intent-composer-frame relative overflow-hidden rounded-[4px] border border-slate-300 bg-white shadow-[0_2px_10px_rgba(15,23,42,0.08)] transition-all focus-within:border-primary focus-within:ring-2 focus-within:ring-[var(--brand-200)]/45 dark:border-[#2b8ffe]/55 dark:bg-[#0d2855] dark:shadow-none dark:focus-within:border-[#56baff] dark:focus-within:ring-[#2b8ffe]/25">
|
||||
{attachedFiles.length > 0 && (
|
||||
<div className="position-roundtable-intent-attachments mx-3 mb-2 flex flex-wrap gap-1.5 border-b border-slate-100 pb-2 pt-2.5 dark:border-[#2b8ffe]/25">
|
||||
{attachedFiles.map((file, index) => (
|
||||
<span
|
||||
key={`${file.name}-${file.size}-${index}`}
|
||||
className="inline-flex max-w-[200px] items-center gap-1.5 rounded-[4px] border border-slate-200 bg-slate-50 py-1 pl-2 pr-1 text-[11px] text-slate-600 dark:border-[#2b8ffe]/30 dark:bg-[#102f63] dark:text-[#c4dcff]"
|
||||
>
|
||||
<FileText className="size-3 shrink-0 text-primary" />
|
||||
<span className="truncate font-medium" title={file.name}>
|
||||
{file.name}
|
||||
</span>
|
||||
<span className="shrink-0 text-slate-400">{formatFileSize(file.size)}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveFile(index)}
|
||||
className="shrink-0 rounded-[3px] p-0.5 text-slate-400 transition hover:bg-slate-200 hover:text-slate-600 dark:text-[#8aaee0] dark:hover:bg-[#21447c] dark:hover:text-white"
|
||||
title="移除"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AutoGrowTextarea
|
||||
id="input-text-area"
|
||||
value={value}
|
||||
@@ -144,7 +131,8 @@ export function PositionIntentInput({
|
||||
title="上传参考文件(智能体将读取文件内容辅助理解任务)"
|
||||
className="rounded-[3px] p-1.5 transition hover:bg-white hover:text-primary dark:hover:bg-[#16386e] dark:hover:text-[#73c8ff]"
|
||||
>
|
||||
<Paperclip className="size-4" />
|
||||
<img src={uploadFileIcon} alt="" aria-hidden="true" />
|
||||
<span>上传附件</span>
|
||||
</button>
|
||||
</div>
|
||||
<span className="font-mono text-[10px] text-slate-400">{charactersLeft}/500</span>
|
||||
@@ -154,8 +142,79 @@ export function PositionIntentInput({
|
||||
Parent pages can still hide optional actions by their stable ids
|
||||
without changing this component's layout or global input styles.
|
||||
*/}
|
||||
<div className="position-roundtable-intent-toolbar flex flex-wrap items-center gap-3 border-t border-slate-100 bg-white px-3 py-2.5 dark:border-[#2b8ffe]/25 dark:bg-[#0b234c]">
|
||||
<div className="flex shrink-0 items-center">
|
||||
<div className="position-roundtable-intent-toolbar flex flex-wrap items-center gap-3 border-t border-slate-100 px-3 py-2.5 dark:border-[#2b8ffe]/25">
|
||||
<div className="position-roundtable-intent-common-slot">
|
||||
{visibleCommonQuestions.length > 0 && (
|
||||
<div className="position-roundtable-intent-common-questions">
|
||||
{visibleCommonQuestions.map((question, index) => (
|
||||
<button
|
||||
key={`${question.prompt}-${index}`}
|
||||
type="button"
|
||||
className="position-roundtable-intent-common-question"
|
||||
title={question.prompt}
|
||||
onClick={() => pickCommonQuestion(question)}
|
||||
>
|
||||
<span aria-hidden="true" />
|
||||
<span>{question.title}</span>
|
||||
</button>
|
||||
))}
|
||||
{extraCommonQuestions.length > 0 && (
|
||||
<div className="position-roundtable-intent-common-more">
|
||||
<button
|
||||
type="button"
|
||||
className="position-roundtable-intent-common-more-button"
|
||||
aria-label="更多常用问题"
|
||||
aria-expanded={showMoreQuestions}
|
||||
title="更多常用问题"
|
||||
onClick={() => setShowMoreQuestions((visible) => !visible)}
|
||||
>
|
||||
<img src={moreTaskIcon} alt="" aria-hidden="true" />
|
||||
</button>
|
||||
{showMoreQuestions && (
|
||||
<div className="position-roundtable-intent-common-more-menu">
|
||||
{extraCommonQuestions.map((question, index) => (
|
||||
<button
|
||||
key={`${question.prompt}-${index}`}
|
||||
type="button"
|
||||
title={question.prompt}
|
||||
onClick={() => pickCommonQuestion(question)}
|
||||
>
|
||||
{question.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{attachedFiles.length > 0 && (
|
||||
<div className="position-roundtable-intent-file-cards flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto">
|
||||
{attachedFiles.map((file, index) => (
|
||||
<span
|
||||
key={`${file.name}-${file.size}-${index}`}
|
||||
className="inline-flex max-w-[220px] shrink-0 items-center gap-1.5 rounded-[4px] border border-[#2b8ffe]/45 bg-[#0b3168] py-1 pl-2 pr-1 text-[11px] text-[#c4dcff]"
|
||||
>
|
||||
<FileText className="size-3 shrink-0 text-[#73c8ff]" />
|
||||
<span className="truncate font-medium" title={file.name}>
|
||||
{file.name}
|
||||
</span>
|
||||
<span className="shrink-0 text-[#8aaee0]">{formatFileSize(file.size)}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveFile(index)}
|
||||
className="shrink-0 cursor-pointer rounded-[3px] p-0.5 text-[#8aaee0] transition hover:bg-[#21447c] hover:text-white"
|
||||
title="移除"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="position-roundtable-intent-actions ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1.5">
|
||||
<div className="position-roundtable-intent-upload-wrap flex shrink-0 items-center">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
@@ -169,28 +228,28 @@ export function PositionIntentInput({
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
title="上传参考文件"
|
||||
aria-label="上传参考文件"
|
||||
className="position-roundtable-intent-upload-btn flex size-10 items-center justify-center rounded-[4px] border border-slate-200 bg-white text-slate-500 transition hover:border-primary/45 hover:text-primary dark:border-[#2b8ffe]/35 dark:bg-[#102f63] dark:text-[#b9d3f7] dark:hover:bg-[#1a417b] dark:hover:text-[#73c8ff]"
|
||||
title="上传附件"
|
||||
aria-label="上传附件"
|
||||
className="position-roundtable-intent-upload-btn flex items-center justify-center rounded-[24px] border-0"
|
||||
>
|
||||
<Paperclip className="size-4" />
|
||||
<img src={uploadFileIcon} alt="" aria-hidden="true" />
|
||||
<span>上传附件</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="position-roundtable-intent-actions ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1.5">
|
||||
{modelOptions.length > 0 && (
|
||||
<div
|
||||
className="position-roundtable-intent-model-switch flex h-10 shrink-0 items-center gap-1.5 rounded-[4px] border border-slate-200 bg-white pl-2 text-xs font-bold text-slate-700 shadow-sm dark:border-[#2b8ffe]/35 dark:bg-[#102f63] dark:text-[#b9d3f7]"
|
||||
title="切换意图理解模型"
|
||||
className="position-roundtable-intent-model-switch flex h-8 shrink-0 items-center gap-1.5 rounded-[20px] border border-[#2b8ffe]/55 bg-[#0b3168] px-2.5 text-xs font-bold text-[#dceaff]"
|
||||
title="鍒囨崲鎰忓浘鐞嗚В妯″瀷"
|
||||
>
|
||||
<Sparkles className="size-3.5 shrink-0 text-primary dark:text-[#73c8ff]" />
|
||||
<Sparkles className="size-3.5 shrink-0 text-[#73c8ff]" />
|
||||
<TSelect
|
||||
size="small"
|
||||
aria-label="切换意图理解模型"
|
||||
aria-label="鍒囨崲鎰忓浘鐞嗚В妯″瀷"
|
||||
value={selectedModel}
|
||||
options={modelOptions}
|
||||
disabled={isSending}
|
||||
onChange={(value) => onSelectedModelChange?.(String(value))}
|
||||
className="w-[150px] shrink-0 [&_.t-input]:!h-8 [&_.t-input]:!border-0 [&_.t-input]:!bg-transparent [&_.t-input]:!px-1 [&_.t-input]:!text-xs [&_.t-input]:!font-bold [&_.t-input]:!shadow-none dark:[&_.t-input]:!text-[#dceaff]"
|
||||
className="w-[150px] shrink-0 [&_.t-input]:!h-7 [&_.t-input]:!rounded-[4px] [&_.t-input]:!border-0 [&_.t-input]:!bg-transparent [&_.t-input]:!px-1 [&_.t-input]:!text-xs [&_.t-input]:!font-bold [&_.t-input]:!text-[#dceaff] [&_.t-input]:!shadow-none"
|
||||
popupProps={{ overlayClassName: "z-[80]" }}
|
||||
/>
|
||||
</div>
|
||||
@@ -198,26 +257,20 @@ export function PositionIntentInput({
|
||||
<button
|
||||
id="send-message-btn"
|
||||
type="button"
|
||||
onClick={onSend}
|
||||
disabled={!canSend}
|
||||
className="position-roundtable-intent-send-btn flex h-10 shrink-0 items-center gap-1.5 rounded-[4px] bg-primary px-3 text-xs font-bold text-white shadow-[0_2px_8px_rgba(245,34,45,0.15)] transition-all active:scale-[0.98] hover:bg-[var(--brand-900)] disabled:cursor-not-allowed disabled:bg-slate-300 dark:bg-[#1478e8] dark:hover:bg-[#2995ff] dark:disabled:bg-[#28476f]"
|
||||
onClick={isSending ? onStop : onSend}
|
||||
disabled={isSending ? false : !canSend}
|
||||
aria-label={isSending ? "暂停生成" : "发送"}
|
||||
title={isSending ? "暂停生成" : "发送"}
|
||||
className={`position-roundtable-intent-send-btn flex h-10 shrink-0 items-center gap-1.5 rounded-[4px] bg-primary px-3 text-xs font-bold text-white shadow-[0_2px_8px_rgba(245,34,45,0.15)] transition-all active:scale-[0.98] hover:bg-[var(--brand-900)] disabled:cursor-not-allowed disabled:bg-slate-300 dark:bg-[#1478e8] dark:hover:bg-[#2995ff] dark:disabled:bg-[#28476f]${isSending ? " position-roundtable-intent-send-btn--stopping" : ""}`}
|
||||
>
|
||||
{isSending ? <Loader2 className="size-3 animate-spin" /> : <Send className="size-3" />}
|
||||
{isSending ? "发送中" : "发送"}
|
||||
{isSending ? (
|
||||
<Pause className="size-4" aria-hidden="true" />
|
||||
) : (
|
||||
<img src={sendMessageIcon} alt="" aria-hidden="true" />
|
||||
)}
|
||||
<span className="sr-only">{isSending ? "暂停生成" : "发送"}</span>
|
||||
</button>
|
||||
|
||||
{isSending && (
|
||||
<button
|
||||
id="pause-intent-btn"
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
className="flex h-10 shrink-0 items-center gap-1.5 rounded-[4px] border border-amber-200/40 bg-amber-100 px-3 text-xs font-bold text-amber-800 shadow-sm transition active:scale-[0.98] hover:bg-amber-200 dark:border-amber-300/30 dark:bg-amber-400/15 dark:text-amber-200 dark:hover:bg-amber-400/25"
|
||||
>
|
||||
<Pause className="size-3" />
|
||||
暂停
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
id="suggest-followup-btn"
|
||||
type="button"
|
||||
|
||||
@@ -15,7 +15,11 @@ import { ThreadContext } from "@/components/workspace/messages/context";
|
||||
import { MessageList } from "@/components/workspace/messages";
|
||||
import { useAgent } from "@/core/agents";
|
||||
import { useLocalSettings } from "@/core/settings";
|
||||
import { useEditMessage, useThreadStream } from "@/core/threads/hooks";
|
||||
import {
|
||||
useEditMessage,
|
||||
useThreadStream,
|
||||
type ToolStartEvent,
|
||||
} from "@/core/threads/hooks";
|
||||
import type { AgentThreadState } from "@/core/threads/types";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
import { uuid } from "@/core/utils/uuid";
|
||||
@@ -40,7 +44,6 @@ import {
|
||||
readConversationDraft,
|
||||
readConversationMessages,
|
||||
} from "@/position-roundtable/lib/conversation-snapshot";
|
||||
|
||||
interface PositionNodeSwitchOption {
|
||||
node: PositionRoundtableNode;
|
||||
agentName?: string | null;
|
||||
@@ -164,17 +167,100 @@ function artifactDisplayName(pathOrUrl: string): string {
|
||||
return path.split("/").filter(Boolean).at(-1) || "Markdown 报告";
|
||||
}
|
||||
|
||||
function normalizeWriteFilePath(path: string): string {
|
||||
let normalized = path.trim();
|
||||
const first = normalized[0];
|
||||
const last = normalized.at(-1);
|
||||
if (
|
||||
normalized.length >= 2 &&
|
||||
((first === '"' && last === '"') ||
|
||||
(first === "'" && last === "'") ||
|
||||
(first === "`" && last === "`"))
|
||||
) {
|
||||
normalized = normalized.slice(1, -1).trim();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function isMarkdownPath(path: string): boolean {
|
||||
const pathname = normalizeWriteFilePath(path).split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
|
||||
return pathname.endsWith(".md") || pathname.endsWith(".markdown");
|
||||
}
|
||||
|
||||
function hasCompleteArtifactExtension(path: string): boolean {
|
||||
const pathname = normalizeWriteFilePath(path).split(/[?#]/, 1)[0] ?? "";
|
||||
const filename = pathname.split("/").filter(Boolean).at(-1) ?? "";
|
||||
// During JSON argument streaming a Markdown path arrives as `.m` and then
|
||||
// `.md`. Opening on the partial suffix permanently labels the preview TEXT.
|
||||
// Extensionless files still open from on_tool_start once the full path is known.
|
||||
return /\.[a-z0-9]{2,12}$/i.test(filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* `write_file` arguments stream as one JSON object and the key order is up to
|
||||
* the model. Agents that emit `content` before `path` leave the file nameless
|
||||
* for as long as the body takes to write — a minute for a full report. The
|
||||
* sandbox follows a streaming file by message/tool-call id, not by path, so it
|
||||
* can open under a provisional name and adopt the real one later. Sniff the
|
||||
* body so the provisional name at least carries the right extension.
|
||||
*/
|
||||
function provisionalWriteFilePath(content: string): string {
|
||||
const head = content.slice(0, 256).trimStart().toLowerCase();
|
||||
if (head.startsWith("<!doctype html") || head.startsWith("<html")) {
|
||||
return "未命名文件.html";
|
||||
}
|
||||
return "未命名文件.md";
|
||||
}
|
||||
|
||||
function writeFilePathFromToolEvent(data: unknown, depth = 0): string | null {
|
||||
if (depth > 3 || data == null) return null;
|
||||
if (typeof data === "string") {
|
||||
const value = data.trim();
|
||||
if (!value) return null;
|
||||
if (value.startsWith("{") || value.startsWith("[")) {
|
||||
try {
|
||||
return writeFilePathFromToolEvent(JSON.parse(value), depth + 1);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (typeof data !== "object" || Array.isArray(data)) return null;
|
||||
const record = data as Record<string, unknown>;
|
||||
if (typeof record.path === "string") {
|
||||
const path = normalizeWriteFilePath(record.path);
|
||||
return path || null;
|
||||
}
|
||||
for (const key of ["input", "inputs", "args", "kwargs"]) {
|
||||
const path = writeFilePathFromToolEvent(record[key], depth + 1);
|
||||
if (path) return path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildWriteFileVirtualUrl(path: string, messageId: string, toolCallId: string): string {
|
||||
const language = isMarkdownPath(path) ? "&language=markdown" : "";
|
||||
return new URL(
|
||||
`write-file:${path}?message_id=${encodeURIComponent(
|
||||
messageId,
|
||||
)}&tool_call_id=${encodeURIComponent(toolCallId)}`,
|
||||
)}&tool_call_id=${encodeURIComponent(toolCallId)}${language}`,
|
||||
).toString();
|
||||
}
|
||||
|
||||
function isArtifactWriteTool(name: string | undefined): name is "write_file" | "str_replace" {
|
||||
return name === "write_file" || name === "str_replace";
|
||||
}
|
||||
|
||||
function latestStreamingWriteFile(
|
||||
messages: AgentThreadState["messages"],
|
||||
): { key: string; path: string; name: string; mimeType: string | null } | null {
|
||||
): {
|
||||
key: string;
|
||||
path: string;
|
||||
sourcePath: string;
|
||||
name: string;
|
||||
mimeType: string | null;
|
||||
} | null {
|
||||
for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
|
||||
const message = messages[messageIndex] as (typeof messages)[number] & {
|
||||
id?: string;
|
||||
@@ -183,17 +269,33 @@ function latestStreamingWriteFile(
|
||||
if (message.type !== "ai" || !message.id || !Array.isArray(message.tool_calls)) continue;
|
||||
for (let toolIndex = message.tool_calls.length - 1; toolIndex >= 0; toolIndex -= 1) {
|
||||
const toolCall = message.tool_calls[toolIndex];
|
||||
if (toolCall?.name !== "write_file" || !toolCall.id) continue;
|
||||
const rawPath = toolCall.args?.path;
|
||||
if (typeof rawPath !== "string" || !rawPath.trim()) continue;
|
||||
const content = toolCall.args?.content;
|
||||
if (typeof content !== "string" || content.length === 0) continue;
|
||||
const virtualPath = buildWriteFileVirtualUrl(rawPath, message.id, toolCall.id);
|
||||
if (!isArtifactWriteTool(toolCall?.name) || !toolCall.id) continue;
|
||||
const rawPath = typeof toolCall.args?.path === "string" ? toolCall.args.path : "";
|
||||
const rawContent = typeof toolCall.args?.content === "string" ? toolCall.args.content : "";
|
||||
const normalizedPath = normalizeWriteFilePath(rawPath);
|
||||
const hasUsablePath =
|
||||
Boolean(normalizedPath) && hasCompleteArtifactExtension(normalizedPath);
|
||||
if (!hasUsablePath) {
|
||||
// `str_replace` edits an existing file, so it can only be previewed once
|
||||
// its real path is known. A new file is identified by its tool call, so
|
||||
// its body can be previewed as soon as the first characters arrive.
|
||||
if (toolCall.name !== "write_file" || !rawContent.trim()) continue;
|
||||
}
|
||||
const sourcePath = hasUsablePath ? normalizedPath : provisionalWriteFilePath(rawContent);
|
||||
// Do not wait for the complete `content` argument. LangGraph streams
|
||||
// write_file arguments incrementally, and the virtual artifact loader
|
||||
// will redraw as `content` arrives. Waiting for it turns this into a
|
||||
// post-generation preview instead of a live sandbox.
|
||||
const previewPath =
|
||||
toolCall.name === "write_file"
|
||||
? buildWriteFileVirtualUrl(sourcePath, message.id, toolCall.id)
|
||||
: sourcePath;
|
||||
return {
|
||||
key: `${message.id}:${toolCall.id}`,
|
||||
path: virtualPath,
|
||||
name: artifactDisplayName(rawPath),
|
||||
mimeType: rawPath.toLowerCase().endsWith(".md") ? "text/markdown" : null,
|
||||
path: previewPath,
|
||||
sourcePath,
|
||||
name: artifactDisplayName(sourcePath),
|
||||
mimeType: isMarkdownPath(sourcePath) ? "text/markdown" : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -214,7 +316,7 @@ function writeFileCallKeys(messages: AgentThreadState["messages"]): Set<string>
|
||||
};
|
||||
if (message.type !== "ai" || !message.id || !Array.isArray(message.tool_calls)) continue;
|
||||
for (const toolCall of message.tool_calls) {
|
||||
if (toolCall?.name === "write_file" && toolCall.id) {
|
||||
if (isArtifactWriteTool(toolCall?.name) && toolCall.id) {
|
||||
keys.add(`${message.id}:${toolCall.id}`);
|
||||
}
|
||||
}
|
||||
@@ -265,11 +367,21 @@ export function PositionNodeChat({
|
||||
);
|
||||
const [boundThreadId, setBoundThreadId] = useState<string | null>(node.threadId);
|
||||
const boundThreadIdRef = useRef<string | null>(node.threadId);
|
||||
const previousNodeBindingRef = useRef({
|
||||
nodeKey: node.nodeKey,
|
||||
threadId: node.threadId,
|
||||
});
|
||||
const draftThreadIdRef = useRef(node.threadId ?? uuid());
|
||||
const upstreamRevisionRef = useRef<Record<string, unknown> | null>(null);
|
||||
const autoPreviewedArtifactKeyRef = useRef<string | null>(null);
|
||||
const autoPreviewBaselineCallKeysRef = useRef<Set<string>>(new Set());
|
||||
const autoPreviewRunArmedRef = useRef(false);
|
||||
const writeFilePreviewSequenceRef = useRef(0);
|
||||
const activeWriteFilePreviewRef = useRef<{
|
||||
path: string;
|
||||
previewKey: string;
|
||||
toolCallId?: string;
|
||||
} | null>(null);
|
||||
const editMessage = useEditMessage();
|
||||
const [messageContentOverrides, setMessageContentOverrides] = useState<Record<string, string>>({});
|
||||
const persistedMessages = useMemo(
|
||||
@@ -288,12 +400,28 @@ export function PositionNodeChat({
|
||||
!node.invalidatedBy;
|
||||
|
||||
useEffect(() => {
|
||||
const previousBinding = previousNodeBindingRef.current;
|
||||
previousNodeBindingRef.current = { nodeKey: node.nodeKey, threadId: node.threadId };
|
||||
// `onStart` binds a newly created LangGraph thread before the session API
|
||||
// persists that id back into `node.threadId`. That prop update happens
|
||||
// while the first turn is already streaming; it is not a node switch and
|
||||
// must not clear the preview run that has just been armed.
|
||||
const isOwnThreadBinding =
|
||||
previousBinding.nodeKey === node.nodeKey &&
|
||||
previousBinding.threadId == null &&
|
||||
node.threadId != null &&
|
||||
node.threadId === boundThreadIdRef.current;
|
||||
if (isOwnThreadBinding) return;
|
||||
|
||||
setBoundThreadId(node.threadId);
|
||||
boundThreadIdRef.current = node.threadId;
|
||||
setInputDraft(readConversationDraft(node.conversationSnapshot));
|
||||
setMessageContentOverrides({});
|
||||
autoPreviewedArtifactKeyRef.current = null;
|
||||
autoPreviewBaselineCallKeysRef.current = new Set();
|
||||
autoPreviewRunArmedRef.current = false;
|
||||
writeFilePreviewSequenceRef.current = 0;
|
||||
activeWriteFilePreviewRef.current = null;
|
||||
// The component is keyed by nodeKey in the page. This reset is therefore
|
||||
// only a defensive guard for callers that reuse the component instance.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -314,6 +442,43 @@ export function PositionNodeChat({
|
||||
[node.nodeKey, onNodeUpdate, sessionId],
|
||||
);
|
||||
|
||||
const handleToolStart = useCallback(
|
||||
(event: ToolStartEvent) => {
|
||||
if (!isArtifactWriteTool(event.name) || !autoPreviewRunArmedRef.current) return;
|
||||
const path = writeFilePathFromToolEvent(event.data);
|
||||
const threadId = boundThreadIdRef.current;
|
||||
if (!path || !threadId) return;
|
||||
|
||||
// Message chunks and on_tool_start can describe the same invocation in
|
||||
// either order. Reuse the first preview key so a manual close suppresses
|
||||
// only this write, while a later rewrite receives a fresh key and opens.
|
||||
const activePreview = activeWriteFilePreviewRef.current;
|
||||
if (
|
||||
activePreview?.path === path &&
|
||||
(activePreview.toolCallId === event.toolCallId ||
|
||||
(event.toolCallId != null && activePreview.previewKey.endsWith(`:${event.toolCallId}`)))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const previewKey = event.toolCallId
|
||||
? `tool-start:${event.toolCallId}`
|
||||
: `tool-start:${node.nodeKey}:${++writeFilePreviewSequenceRef.current}`;
|
||||
activeWriteFilePreviewRef.current = { path, previewKey, toolCallId: event.toolCallId };
|
||||
const artifactKey = `${threadId}:${previewKey}`;
|
||||
if (autoPreviewedArtifactKeyRef.current === artifactKey) return;
|
||||
autoPreviewedArtifactKeyRef.current = artifactKey;
|
||||
onPreviewArtifact?.({
|
||||
threadId,
|
||||
path,
|
||||
name: artifactDisplayName(path),
|
||||
mimeType: isMarkdownPath(path) ? "text/markdown" : null,
|
||||
previewKey,
|
||||
auto: true,
|
||||
});
|
||||
},
|
||||
[node.nodeKey, onPreviewArtifact],
|
||||
);
|
||||
|
||||
const [thread, sendMessage, , actualThreadId] = useThreadStream({
|
||||
threadId: boundThreadId,
|
||||
assistantId: node.agentId,
|
||||
@@ -334,15 +499,21 @@ export function PositionNodeChat({
|
||||
agent_id: node.agentId,
|
||||
},
|
||||
onStart: bindCreatedThread,
|
||||
onToolStart: handleToolStart,
|
||||
onFinish: (state) => {
|
||||
// A turn is not considered delivered by the UI alone. The persisted
|
||||
// completion call records the answer, file manifest and upstream version
|
||||
// so the service can decide whether this seat unlocks its downstream.
|
||||
const threadId = boundThreadIdRef.current;
|
||||
const latestAi = [...(state.messages ?? [])]
|
||||
// `present_files` is often the last AI tool call and has no prose of
|
||||
// its own. Keep walking backwards to the last actual answer; otherwise
|
||||
// a successful file delivery would return early here and never refresh
|
||||
// the node's artifact cards.
|
||||
const latestAnswer = [...(state.messages ?? [])]
|
||||
.reverse()
|
||||
.find((message) => message.type === "ai");
|
||||
const latestAnswer = latestAi ? textOfMessage(latestAi) ?? "" : "";
|
||||
.filter((message) => message.type === "ai")
|
||||
.map((message) => textOfMessage(message) ?? "")
|
||||
.find((content) => content.trim()) ?? "";
|
||||
if (!threadId || !latestAnswer.trim()) return;
|
||||
void (async () => {
|
||||
let artifactManifest: Array<Record<string, unknown>> = [];
|
||||
@@ -378,6 +549,10 @@ export function PositionNodeChat({
|
||||
|
||||
const activeThreadId =
|
||||
boundThreadIdRef.current ?? actualThreadId ?? boundThreadId ?? draftThreadIdRef.current;
|
||||
// A sandbox must always receive the server thread id. In particular, do not
|
||||
// attach a streaming preview to the provisional UUID used for a new node
|
||||
// before `useThreadStream` has created and bound its thread.
|
||||
const previewThreadId = boundThreadIdRef.current ?? actualThreadId ?? boundThreadId ?? null;
|
||||
const persistedThreadId =
|
||||
boundThreadIdRef.current ?? actualThreadId ?? boundThreadId ?? null;
|
||||
const recoveredMessages = useMemo(
|
||||
@@ -566,32 +741,60 @@ export function PositionNodeChat({
|
||||
() => (thread.isLoading ? latestStreamingWriteFile(thread.messages) : null),
|
||||
[thread.isLoading, thread.messages],
|
||||
);
|
||||
const newStreamingArtifact =
|
||||
streamingArtifact && !autoPreviewBaselineCallKeysRef.current.has(streamingArtifact.key)
|
||||
? streamingArtifact
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!thread.isLoading ||
|
||||
!streamingArtifact ||
|
||||
!autoPreviewRunArmedRef.current ||
|
||||
autoPreviewBaselineCallKeysRef.current.has(streamingArtifact.key)
|
||||
!newStreamingArtifact ||
|
||||
!previewThreadId ||
|
||||
!autoPreviewRunArmedRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// One write_file call should open at most one preview. The parent further
|
||||
// guards manual close state, because it owns the page-wide singleton sandbox.
|
||||
// A report is often rewritten to the same output path. The tool-call key
|
||||
// (not just the path) makes that a new previewable delivery.
|
||||
const artifactKey = `${activeThreadId}:${streamingArtifact.key}`;
|
||||
// A report is often rewritten to the same output path — identity must be the
|
||||
// tool-call key, not the path, otherwise a second write keeps the old panel
|
||||
// and the sandbox never clears / remounts for the rewrite.
|
||||
const toolCallKey = newStreamingArtifact.key;
|
||||
const toolCallId = toolCallKey.includes(":")
|
||||
? toolCallKey.slice(toolCallKey.lastIndexOf(":") + 1)
|
||||
: undefined;
|
||||
const startedPreview = activeWriteFilePreviewRef.current;
|
||||
const isSameToolCall =
|
||||
startedPreview != null &&
|
||||
(startedPreview.previewKey === toolCallKey ||
|
||||
(toolCallId != null &&
|
||||
(startedPreview.toolCallId === toolCallId ||
|
||||
startedPreview.previewKey.endsWith(`:${toolCallId}`))));
|
||||
// Same tool call may upgrade a provisional filename → real path; keep the
|
||||
// open panel. A different tool call is a new delivery even on the same path.
|
||||
const previewKey = isSameToolCall ? startedPreview.previewKey : toolCallKey;
|
||||
activeWriteFilePreviewRef.current = {
|
||||
path: newStreamingArtifact.sourcePath,
|
||||
previewKey,
|
||||
toolCallId: toolCallId ?? startedPreview?.toolCallId,
|
||||
};
|
||||
// The path takes part in the identity so that a preview opened under a
|
||||
// provisional name is re-published once the real path streams in. The
|
||||
// preview key stays the same, so the parent treats it as an update of the
|
||||
// open panel rather than a second delivery.
|
||||
const artifactKey = `${previewThreadId}:${previewKey}:${newStreamingArtifact.sourcePath}`;
|
||||
if (autoPreviewedArtifactKeyRef.current === artifactKey) return;
|
||||
autoPreviewedArtifactKeyRef.current = artifactKey;
|
||||
onPreviewArtifact?.({
|
||||
threadId: activeThreadId,
|
||||
path: streamingArtifact.path,
|
||||
name: streamingArtifact.name,
|
||||
mimeType: streamingArtifact.mimeType,
|
||||
previewKey: streamingArtifact.key,
|
||||
threadId: previewThreadId,
|
||||
path: newStreamingArtifact.path,
|
||||
name: newStreamingArtifact.name,
|
||||
mimeType: newStreamingArtifact.mimeType,
|
||||
previewKey,
|
||||
auto: true,
|
||||
});
|
||||
}, [activeThreadId, onPreviewArtifact, streamingArtifact, thread.isLoading]);
|
||||
}, [newStreamingArtifact, onPreviewArtifact, previewThreadId, thread.isLoading]);
|
||||
|
||||
// SDK thread creation is asynchronous. ``onStart`` normally binds it, but
|
||||
// watching the actual stream id as well closes the last race where a page
|
||||
@@ -628,6 +831,7 @@ export function PositionNodeChat({
|
||||
: null;
|
||||
// A thread retains historical write_file tool calls. Only files whose
|
||||
// call id appears after this exact submission may open the sandbox.
|
||||
activeWriteFilePreviewRef.current = null;
|
||||
autoPreviewBaselineCallKeysRef.current = writeFileCallKeys(thread.messages);
|
||||
autoPreviewRunArmedRef.current = true;
|
||||
await sendMessage(boundThreadIdRef.current ?? draftThreadIdRef.current, message, {
|
||||
@@ -811,7 +1015,7 @@ export function PositionNodeChat({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="position-roundtable-agent-composer-bar shrink-0 border-t border-slate-100 px-4 py-3 dark:border-[#2b8ffe]/20">
|
||||
<div className="position-roundtable-agent-composer-bar position-roundtable-node-composer shrink-0">
|
||||
<PositionAgentInput
|
||||
className="w-full"
|
||||
isNewThread={!boundThreadId}
|
||||
@@ -825,6 +1029,7 @@ export function PositionNodeChat({
|
||||
onDraftChange={setInputDraft}
|
||||
hideAdminRecommendedQuestions
|
||||
onContextChange={(context) => setSettings("context", context)}
|
||||
commonQuestions={agent?.common_questions}
|
||||
onSubmit={(message) => void handleSubmit(message)}
|
||||
onStop={() => void thread.stop()}
|
||||
/>
|
||||
|
||||
@@ -97,6 +97,7 @@ export function getPositionDemoTask(): PositionTask {
|
||||
direction: String(task.direction ?? ""),
|
||||
source: String(task.source ?? "演示数据"),
|
||||
issuedAt: String(task.issuedAt ?? ""),
|
||||
priority: String(task.priority ?? "紧急"),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
# 岗位会商沙箱对接指南(重做页面 / 排障)
|
||||
|
||||
## 文档用途
|
||||
|
||||
给**下次重做或对接岗位会商页面**的同事用,也给线上「沙箱不实时 / 卡死 / 第二次不刷新」时排障用。
|
||||
|
||||
读完应能回答:
|
||||
|
||||
1. 新页面要接哪几个回调、传什么字段?
|
||||
2. 打开 / 关闭沙箱各在什么时机?和步骤条是什么关系?
|
||||
3. 哪些写法绝对不能用(会复现历史 bug)?
|
||||
4. 出问题时按什么顺序查?
|
||||
|
||||
对照实现(当前生产路径):
|
||||
|
||||
| 角色 | 文件 |
|
||||
| --- | --- |
|
||||
| 页面壳(沙箱唯一宿主) | `pages/PositionRoundtablePage.tsx` |
|
||||
| 节点对话(探测 write_file、上报预览) | `components/PositionNodeChat.tsx` |
|
||||
| 收口对话 | `components/PositionBuiltinAgentChat.tsx` |
|
||||
| 预览 UI(共享组件,勿分叉逻辑) | `components/workspace/artifacts/artifact-file-detail.tsx` |
|
||||
| 流式正文读取 | `core/artifacts/loader.ts` → `loadArtifactContentFromToolCall` |
|
||||
| 普通对话页对照(步骤条自动开) | `components/workspace/messages/message-group.tsx` |
|
||||
|
||||
模块总览见同目录上级 [`../README.md`](../README.md);本文只覆盖**文件预览沙箱**这一条链路。
|
||||
|
||||
---
|
||||
|
||||
## 1. 验收标准(对接完成即通过)
|
||||
|
||||
重做页面后,下列行为必须全部成立(与普通对话页用户感知一致):
|
||||
|
||||
| # | 行为 |
|
||||
| --- | --- |
|
||||
| A | 步骤条刚出现「写入文件」时,右侧沙箱应已打开(不必等文件名出现) |
|
||||
| B | 沙箱内源码随模型输出边写边滚;消息列表文字也实时出现,不能整页卡死 |
|
||||
| C | 模型若先吐正文、后吐 `path`:先用临时名打开,path 到了再改名,不闪屏重挂 |
|
||||
| D | 同一次问答里第二次 `write_file` 写同一路径(「重新生成」):沙箱清空并重新流式 |
|
||||
| E | 整轮 `isLoading=false` 后,自动从源码切到 Markdown 预览 |
|
||||
| F | 用户手动关闭后,**同一次**写入不再自动弹;**下一轮**新写入仍可自动开 |
|
||||
| G | 切岗位 / 切节点 / 新建或切换会话时,沙箱关掉且不串内容 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 职责划分(谁干什么)
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 页面壳(PositionRoundtablePage 或你的新页面) │
|
||||
│ · 唯一 sandboxArtifact 状态 │
|
||||
│ · handlePreviewArtifact / closeSandbox │
|
||||
│ · 流式线程外部 store(禁止整页 useState) │
|
||||
│ · 渲染唯一 ArtifactFileDetail │
|
||||
└──────────────────────────▲──────────────────────────────────┘
|
||||
│ onPreviewArtifact / onThreadSnapshot
|
||||
┌──────────────────────────┴──────────────────────────────────┐
|
||||
│ 对话子组件(PositionNodeChat 等) │
|
||||
│ · useThreadStream 拉消息 │
|
||||
│ · 渲染 MessageList / 步骤条(只展示,不直接开沙箱) │
|
||||
│ · 探测 write_file → 组装 PositionArtifactPreview 上报 │
|
||||
│ · 每次 thread 变化上报 onThreadSnapshot │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
硬性规则:
|
||||
|
||||
1. **沙箱只有一个实例**,挂在页面壳上,不要在对话子组件里再挂 `ArtifactFileDetail`。
|
||||
2. 对话子组件**不要**直接 `artifacts.setOpen(true)` 当作岗位会商的主路径(页面壳统一开合,才能做关闭抑制、切节点清理)。
|
||||
3. 步骤条和沙箱是**两条线**:步骤条只反映 tool call 展示;开沙箱走 `onPreviewArtifact`。
|
||||
|
||||
---
|
||||
|
||||
## 3. 对接接口(重新接页面时照此接线)
|
||||
|
||||
### 3.1 对话子组件 → 页面壳
|
||||
|
||||
#### `onPreviewArtifact(artifact)`
|
||||
|
||||
请求打开或更新沙箱。载荷:
|
||||
|
||||
```ts
|
||||
type PositionArtifactPreview = {
|
||||
threadId: string; // 必填:LangGraph thread id
|
||||
path: string; // 必填:真实路径,或 write-file: 虚拟 URL,或临时文件名
|
||||
name: string; // 展示名
|
||||
mimeType: string | null; // 如 text/markdown;帮助预览语言判断
|
||||
previewKey?: string; // 强烈建议:一次交付的身份,推荐 `${messageId}:${toolCallId}`
|
||||
auto?: boolean; // true = 流式自动打开;false/缺省 = 用户点击打开
|
||||
};
|
||||
```
|
||||
|
||||
页面壳收到后应:
|
||||
|
||||
1. `auto===true` 且 `closedSandboxKey === sandboxCloseKey(artifact)` → **直接 return**(用户刚关过这一次)。
|
||||
2. 更新页面级 `sandboxArtifact`(并同步 ref,见下)。
|
||||
3. 同步 `ArtifactsContext.select(path) + setOpen(true)`(与共享预览组件生命周期对齐)。
|
||||
4. 若已有该 thread 的最新快照,立刻推进沙箱 store。
|
||||
5. React `key` 用 `sandboxCloseKey(artifact)`(有 `previewKey` 时优先它),保证新交付会重挂。
|
||||
|
||||
`sandboxCloseKey` 约定:
|
||||
|
||||
```ts
|
||||
// 有 previewKey:threadId:write:${previewKey}
|
||||
// 无 previewKey:threadId:${normalizePath(path)}
|
||||
```
|
||||
|
||||
#### `onThreadSnapshot({ threadId, thread })`
|
||||
|
||||
把当前 `useThreadStream` 的 thread 对象持续交给页面壳,供沙箱读流式 `content`。
|
||||
|
||||
页面壳应:
|
||||
|
||||
1. 始终写入 `latestNodeThreadSnapshotRef`(打开瞬间可能用到)。
|
||||
2. **仅当**当前沙箱 `threadId` 与 snapshot 一致时,才 `queue` → store `publish`。
|
||||
3. 节流:前沿 160ms(见第 5 节),不要纯尾随 `setTimeout`。
|
||||
|
||||
### 3.2 页面壳 → 预览组件
|
||||
|
||||
```tsx
|
||||
{sandboxOpen && sandboxArtifact && (
|
||||
<SandboxThreadProvider store={store} threadId={sandboxArtifact.threadId} fallbackThread={stub}>
|
||||
<ArtifactFileDetail
|
||||
key={sandboxCloseKey(sandboxArtifact)}
|
||||
filepath={sandboxArtifact.path}
|
||||
threadId={sandboxArtifact.threadId}
|
||||
mimeType={sandboxArtifact.mimeType}
|
||||
onClose={closeSandbox}
|
||||
allowVirtualMarkdownEdit
|
||||
// ...
|
||||
/>
|
||||
</SandboxThreadProvider>
|
||||
)}
|
||||
```
|
||||
|
||||
流式正文依赖虚拟 URL:
|
||||
|
||||
```text
|
||||
write-file:${path}?message_id=...&tool_call_id=...&language=markdown
|
||||
```
|
||||
|
||||
`loadArtifactContentFromToolCall` **只认** URL 里的 `message_id` + `tool_call_id`,从 `thread.messages` 对应 tool call 的 `args.content` 取值。
|
||||
因此:**可以没有真实磁盘 path 就开沙箱**;path 主要用于文件名展示和语言猜测。
|
||||
|
||||
### 3.3 对话子组件内部必做状态(可复用现有逻辑)
|
||||
|
||||
重新实现探测时,至少保留这些语义(不必同名,语义要对):
|
||||
|
||||
| 状态 | 作用 |
|
||||
| --- | --- |
|
||||
| `armed` | 仅本轮用户 `send` 成功武装后才允许自动 `onPreviewArtifact` |
|
||||
| `baselineCallKeys` | send 前已有的 `messageId:toolCallId` 集合;忽略历史 write,防止一提问就开旧文件 |
|
||||
| `activePreview` | 当前已打开的 previewKey / path / toolCallId,用于 path 升级与同 call 去重 |
|
||||
| 线程绑定保护 | `node.threadId` 从 null→本节点刚创建的 id 时,**不要** disarm |
|
||||
|
||||
发送时:
|
||||
|
||||
```text
|
||||
baseline = 当前历史 write keys
|
||||
armed = true
|
||||
activePreview = null
|
||||
→ sendMessage(...)
|
||||
```
|
||||
|
||||
探测时(`isLoading`):
|
||||
|
||||
```text
|
||||
找到最新 write_file / str_replace
|
||||
若不在 baseline:
|
||||
- 有完整扩展名 path → 用真实 path
|
||||
- write_file 且仅有 content → 临时名(未命名文件.md / .html)
|
||||
- str_replace 无 path → 先不报
|
||||
previewKey = 同 tool call 复用,否则新 key
|
||||
→ onPreviewArtifact({ ..., auto: true })
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 打开 / 关闭时序(对接时按此实现)
|
||||
|
||||
### 4.1 打开(自动)
|
||||
|
||||
```text
|
||||
用户发送
|
||||
→ armed=true + 拍 baseline
|
||||
→ 模型开始 write_file
|
||||
→ 步骤条出现「写入文件」(可能还没有 path)
|
||||
→ content 或完整 path 任一满足探测条件
|
||||
→ onPreviewArtifact(auto)
|
||||
→ 页面壳打开 ArtifactFileDetail + 推送 thread 快照
|
||||
→ 源码视图滚动更新
|
||||
→(可选)真实 path 到达:同 previewKey 改名(path upgrade,不重挂)
|
||||
→ isLoading=false:共享组件自动切预览
|
||||
```
|
||||
|
||||
### 4.2 同轮第二次写入(重新生成)
|
||||
|
||||
```text
|
||||
write_file #1 → previewKey = msg:tc1 → 打开
|
||||
write_file #2 同 path → previewKey = msg:tc2(必须变)
|
||||
→ React key 变 → 组件重挂 → 视觉上清空再生成
|
||||
```
|
||||
|
||||
**禁止**用「path 相同 ⇒ 复用 previewKey」。那会导致步骤条有「重新生成」、沙箱却不动。
|
||||
|
||||
### 4.3 关闭
|
||||
|
||||
| 触发 | 行为 |
|
||||
| --- | --- |
|
||||
| 用户点关闭 | `closedSandboxKeyRef = sandboxCloseKey(current)`;清 artifact / store / 定时器 |
|
||||
| 切岗位、切节点、新会话、切历史 | 先 `closeSandbox()`(可按产品决定是否写入抑制键;至少清面板) |
|
||||
| 自动打开被抑制 | 仅当 `auto && closedKey === 当前 key`;手动打开应清抑制 |
|
||||
|
||||
抑制粒度必须是**单次交付(previewKey)**,不能是「整个 thread 永远不再自动开」。
|
||||
|
||||
---
|
||||
|
||||
## 5. 重做页面时的必守规则(违反必出 bug)
|
||||
|
||||
1. **流式 thread 快照禁止进页面级 `useState`**
|
||||
大页面每秒重渲染数次会占满主线程:消息列表停更、沙箱冻住、定时器饿死。
|
||||
正确:外部 store + `useSyncExternalStore`,只让沙箱子树订阅。
|
||||
|
||||
2. **节流用前沿(leading-edge),不要纯尾随 `setTimeout`**
|
||||
距上次 publish ≥ 160ms → 同步 publish;否则补尾定时器。
|
||||
纯「有 timer 就 return」在忙主线程下会十几秒不 flush。
|
||||
|
||||
3. **不要等完整 `path` 才开沙箱**
|
||||
报告类 agent 常先流 `content`、最后才流 `path`,硬等会晚几十秒。
|
||||
`write_file` + 已有 content → 临时名打开;`str_replace` 仍等真实 path。
|
||||
|
||||
4. **扩展名要完整再当「真实 path」**
|
||||
流式中 `.m` → `.md`,过早打开会把语言锁成 TEXT。
|
||||
|
||||
5. **previewKey 按 tool call,不按 path**
|
||||
同 path 多次写入 = 多次交付。
|
||||
|
||||
6. **打开瞬间同步推进 `sandboxArtifactRef`**
|
||||
若 flush 快照时只看 ref、而 setState 尚未提交,首帧会被「threadId 不匹配」丢掉。
|
||||
|
||||
7. **不要依赖 `onToolStart` 作为唯一打开手段**
|
||||
当前后端对部分 stream mode 可能过滤;主路径必须是 `thread.messages` 里渐进出现的 `tool_calls`。
|
||||
|
||||
8. **path upgrade 不要当第二次打开**
|
||||
同 previewKey 改 path:更新 artifact,不要乱关抽屉 / 不要重挂。
|
||||
|
||||
9. **「结束后才切预览」不是打开 bug**
|
||||
`ArtifactFileDetail` 对 markdown/html 在 `isLoading` 期间强制源码视图,与普通对话页相同。
|
||||
|
||||
---
|
||||
|
||||
## 6. 步骤条怎么对接理解
|
||||
|
||||
步骤条来自消息里的 tool call 渲染(`message-group`),标题优先 `args.description`,否则文案「写入文件」;子行显示 `args.path`。
|
||||
|
||||
| 你看到的步骤条 | 含义 | 沙箱应处于 |
|
||||
| --- | --- | --- |
|
||||
| 仅「写入文件」,无路径 | tool call 已开始,path 可能还没流到 | **应已打开**(临时名) |
|
||||
| 「写入文件」+ 路径 | path 已可用 | 已打开;若刚从临时名升级则只改名 |
|
||||
| 第二条「重新生成…」+ 同路径 | 新的 write_file(新 toolCallId) | **应重挂**并重新流式 |
|
||||
| 生成中顶部「正在生成,完成后自动预览」 | 仍在 code 视图 | 正常,等 isLoading 结束切预览 |
|
||||
|
||||
对接时不要把「步骤条出现文件名」当成「开沙箱的唯一信号」——那会在 content-first 模型上系统性偏晚。
|
||||
|
||||
---
|
||||
|
||||
## 7. 排障手册(按症状查)
|
||||
|
||||
### 7.1 沙箱开得很晚 / 要等文件名才开
|
||||
|
||||
检查顺序:
|
||||
|
||||
1. 探测是否仍要求「必须有完整 path」?→ 改为 content 可开临时名。
|
||||
2. `armed` 是否在 `threadId` 回写时被误清?→ 保护「本节点绑定自己的新 thread」。
|
||||
3. 是否被 `closedSandboxKey` 抑制?→ 看是否刚关过同 previewKey。
|
||||
4. 新 call 是否落在 baseline 里?→ baseline 只能在 send 时拍一次。
|
||||
|
||||
### 7.2 沙箱打开了但内容空白 / 冻住,生成完才一口气出来
|
||||
|
||||
1. 快照是否写进了页面 `useState`?→ 改 store。
|
||||
2. 节流是否纯尾随定时器?→ 改前沿。
|
||||
3. `SandboxThreadProvider` 是否把带 `messages` 的 thread 传给了 `ArtifactFileDetail`?
|
||||
4. 虚拟 URL 的 `tool_call_id` 是否与消息里一致?
|
||||
5. 打开时 `sandboxArtifactRef` 是否已同步(避免首帧 flush 被丢)?
|
||||
|
||||
### 7.3 消息列表也不实时,整页很卡
|
||||
|
||||
优先怀疑页面壳在流式频率下整页重渲染。
|
||||
确认没有把 `onThreadSnapshot` 落到大页面 state;临时 `console.debug` 每 chunk 打大对象也会加重(排障完删掉)。
|
||||
|
||||
### 7.4 第二次「重新生成」步骤有了,沙箱不变
|
||||
|
||||
previewKey 是否按 path 复用了?→ 必须按 `messageId:toolCallId`。
|
||||
`ArtifactFileDetail` 的 `key` 是否跟 previewKey 走?否则不会重挂。
|
||||
|
||||
### 7.5 第一次实时开,关掉后再问就不实时 / 很晚才开
|
||||
|
||||
抑制是否绑在整个 `threadId` 上?→ 改为单次 `sandboxCloseKey(previewKey)`。
|
||||
|
||||
### 7.6 预览变成纯文本 / 不像 Markdown
|
||||
|
||||
1. 是否在 `.m` 阶段就当完整 path 打开了?
|
||||
2. 临时名是否带 `.md` / URL 是否带 `language=markdown` / 是否传了 `mimeType`?
|
||||
3. path 是否有首尾空格?
|
||||
|
||||
### 7.7 只靠 onToolStart,线上偶发永远不开
|
||||
|
||||
后端可能不推 tools/events。主路径改为扫描 `thread.messages` 的 streaming `tool_calls`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 对接自测清单(重做页面后必跑)
|
||||
|
||||
- [ ] 首轮:步骤条「写入文件」出现时,沙箱是否已开并开始出字?
|
||||
- [ ] content-first agent:无文件名阶段是否也能开?
|
||||
- [ ] path 到达后:是否只改名、不整页闪?
|
||||
- [ ] 同轮第二次同路径 write:是否清空并重新流式?
|
||||
- [ ] 流式中消息列表是否仍实时?页面是否明显卡顿?
|
||||
- [ ] 手动关闭后本次是否不再弹?下一轮是否仍可自动开?
|
||||
- [ ] 结束后是否自动切 Markdown 预览?
|
||||
- [ ] 切节点 / 切岗位 / 新会话:沙箱是否关闭且内容不串?
|
||||
|
||||
---
|
||||
|
||||
## 9. 最小接线伪代码(新页面可抄)
|
||||
|
||||
```tsx
|
||||
// 页面壳
|
||||
const [sandboxArtifact, setSandboxArtifact] = useState<PositionArtifactPreview | null>(null);
|
||||
const sandboxArtifactRef = useRef(sandboxArtifact);
|
||||
const closedSandboxKeyRef = useRef<string | null>(null);
|
||||
const store = useMemo(createSandboxThreadStore, []);
|
||||
|
||||
function handlePreviewArtifact(artifact: PositionArtifactPreview) {
|
||||
const key = sandboxCloseKey(artifact);
|
||||
if (artifact.auto && closedSandboxKeyRef.current === key) return;
|
||||
|
||||
const prev = sandboxArtifactRef.current;
|
||||
const sameKey = prev?.previewKey && prev.previewKey === artifact.previewKey
|
||||
&& prev.threadId === artifact.threadId;
|
||||
const pathOnlyUpgrade = sameKey && prev.path !== artifact.path;
|
||||
|
||||
sandboxArtifactRef.current = artifact;
|
||||
setSandboxArtifact(artifact);
|
||||
// publish latest thread snapshot into store (leading-edge throttle)
|
||||
// ArtifactsContext.select + setOpen(true)
|
||||
if (!pathOnlyUpgrade) closeRightDrawer();
|
||||
}
|
||||
|
||||
function closeSandbox() {
|
||||
if (sandboxArtifactRef.current) {
|
||||
closedSandboxKeyRef.current = sandboxCloseKey(sandboxArtifactRef.current);
|
||||
}
|
||||
sandboxArtifactRef.current = null;
|
||||
setSandboxArtifact(null);
|
||||
store.publish(null);
|
||||
}
|
||||
|
||||
// 对话子组件
|
||||
<PositionNodeChat
|
||||
onPreviewArtifact={handlePreviewArtifact}
|
||||
onThreadSnapshot={handleNodeThreadSnapshot}
|
||||
/>
|
||||
```
|
||||
|
||||
对话侧探测逻辑优先**复用** `PositionNodeChat` 内的 `latestStreamingWriteFile` / armed / baseline,而不是从零再写一套——这是最容易写错的部分。
|
||||
|
||||
---
|
||||
|
||||
## 10. 术语
|
||||
|
||||
| 词 | 含义 |
|
||||
| --- | --- |
|
||||
| armed | 本轮用户发送后,允许自动打开沙箱 |
|
||||
| baseline | send 前已有 write tool call 集合,用于忽略历史产物 |
|
||||
| previewKey | 一次交付身份,推荐 `messageId:toolCallId` |
|
||||
| sandboxCloseKey | 关闭抑制键 + React key |
|
||||
| provisional path | 无真实 path 时的临时文件名 |
|
||||
| path upgrade | 同 previewKey 下临时名 → 真实 path |
|
||||
| sandboxThreadStore | 流式线程外部 store,避免整页重渲染 |
|
||||
| write-file: URL | 用 message/tool call id 定位流式 content 的虚拟路径 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 相关提交(背景)
|
||||
|
||||
若需对照修复动机,可查:
|
||||
|
||||
- `fix(frontend): 岗位会商沙箱在 write_file 流式阶段实时打开并刷新` — 临时名打开、store、前沿节流
|
||||
- `fix(frontend): 同路径二次 write_file 时重挂岗位会商沙箱` — previewKey 按 tool call
|
||||
|
||||
排障时优先对照本文第 5、7 节,再对照上述提交的 diff。
|
||||
@@ -13,6 +13,7 @@ export interface PositionTask {
|
||||
direction: string;
|
||||
source: string;
|
||||
issuedAt: string;
|
||||
priority?: string;
|
||||
}
|
||||
|
||||
export const MOCK_POSITION_TASKS: readonly PositionTask[] = [
|
||||
@@ -30,16 +31,21 @@ export const MOCK_POSITION_TASKS: readonly PositionTask[] = [
|
||||
export const DEFAULT_MOCK_POSITION_TASK_ID = MOCK_POSITION_TASKS[0].id;
|
||||
|
||||
export function getMockPositionTask(taskId?: string | null): PositionTask {
|
||||
return (
|
||||
const fixture =
|
||||
MOCK_POSITION_TASKS.find((task) => task.id === taskId) ??
|
||||
MOCK_POSITION_TASKS[0]
|
||||
);
|
||||
MOCK_POSITION_TASKS[0];
|
||||
const scopedTaskId = taskId?.trim();
|
||||
// The fixture supplies only display defaults. Preserve the caller's task
|
||||
// identity so persistence, history and LangGraph thread metadata all remain
|
||||
// bound to the route taskId.
|
||||
return scopedTaskId ? { ...fixture, id: scopedTaskId } : fixture;
|
||||
}
|
||||
|
||||
/** Normalizes a persisted Session task snapshot without exposing source internals. */
|
||||
export function taskFromPositionSnapshot(
|
||||
snapshot: Record<string, unknown> | null | undefined,
|
||||
fallback: PositionTask,
|
||||
taskScopeId?: string,
|
||||
): PositionTask {
|
||||
if (!snapshot || Object.keys(snapshot).length === 0) return fallback;
|
||||
const value = (keys: string[], defaultValue: string) => {
|
||||
@@ -49,10 +55,15 @@ export function taskFromPositionSnapshot(
|
||||
return typeof found === "string" ? found : defaultValue;
|
||||
};
|
||||
return {
|
||||
id: value(["id", "taskId", "externalTaskId"], fallback.id),
|
||||
// Session snapshots are editable display data, while the route taskId is
|
||||
// the stable shared-storage scope. Keeping them separate prevents a
|
||||
// legacy/mock snapshot from moving a live external task into another
|
||||
// task's history bucket.
|
||||
id: taskScopeId?.trim() || value(["id", "taskId", "externalTaskId"], fallback.id),
|
||||
title: value(["title", "taskName", "name"], fallback.title),
|
||||
description: value(["description", "taskContent", "overview", "content"], fallback.description),
|
||||
direction: value(["direction", "taskDirection", "category"], fallback.direction),
|
||||
priority: value(["priority", "level", "urgency"], fallback.priority ?? "紧急"),
|
||||
source: (() => {
|
||||
const source = value(["source", "taskSource", "sourceName"], fallback.source);
|
||||
return source === "mock" ? "本系统创建" : source;
|
||||
|
||||
@@ -4,9 +4,15 @@ import { getBackendBaseURL } from "@/core/config";
|
||||
import type { ClarificationPayload } from "./multi-agent";
|
||||
import { reportRoundtableError } from "./diagnostics-report";
|
||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||
import { normalizeIntentReadySummary } from "@/roundtable-planning/lib/roundtable-constants";
|
||||
|
||||
export type { ClarificationPayload };
|
||||
|
||||
/** Stable built-in agent used by the multi-agent roundtable Step 1 flow. */
|
||||
export const INTENT_AGENT_ID = "roundtable-intent";
|
||||
/** Dedicated Step 1 agent for the position-roundtable workspace. */
|
||||
export const POSITION_INTENT_AGENT_ID = "position-roundtable-intent";
|
||||
|
||||
/**
|
||||
* Task-intent agent (Step 1) API. Mirror of multi-agent.ts but with a single
|
||||
* built-in agent and no per-call coordinator: one /init creates a thread
|
||||
@@ -100,13 +106,18 @@ function parseIntentErrorDetail(value: unknown): IntentErrorDetail | null {
|
||||
export async function initIntent(
|
||||
model?: string,
|
||||
taskContext?: Record<string, unknown> | null,
|
||||
intentAgentId?: string,
|
||||
): Promise<IntentInitResponse> {
|
||||
const res = await apiFetch(`${getBackendBaseURL()}/api/intent/init`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
// 岗位会商在创建意图线程时就写入父任务标识。这样即使用户尚未确认
|
||||
// 业务链,第一阶段的对话也已经可以按 taskId 恢复。
|
||||
body: JSON.stringify({ model, task_context: taskContext ?? undefined }),
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
task_context: taskContext ?? undefined,
|
||||
intent_agent_id: intentAgentId || undefined,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const raw = await res.text().catch(() => "");
|
||||
@@ -137,6 +148,19 @@ export interface IntentSummary {
|
||||
constraints: string[];
|
||||
/** Optional assumptions the agent is making on the user's behalf. */
|
||||
assumptions?: string[];
|
||||
/** Present only for the dedicated position-roundtable intent agent. */
|
||||
coreGoals?: string[];
|
||||
riskWarnings?: string[];
|
||||
keyPoints?: string[];
|
||||
strategicSignificance?: string[];
|
||||
}
|
||||
|
||||
/** Final hand-off shape emitted only by the position-roundtable intent agent. */
|
||||
export interface PositionIntentSummary {
|
||||
coreGoals: string[];
|
||||
riskWarnings: string[];
|
||||
keyPoints: string[];
|
||||
strategicSignificance: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -164,6 +188,8 @@ export interface StreamIntentRequest {
|
||||
threadId: string;
|
||||
message: string;
|
||||
model?: string;
|
||||
/** Explicit built-in Step-1 agent. Omit to retain the multi-agent default. */
|
||||
intentAgentId?: string;
|
||||
/** Optional hidden business/task context injected into the model run. */
|
||||
taskContext?: Record<string, unknown> | null;
|
||||
/** Step 1 用户上传的参考文件(可选)。 */
|
||||
@@ -186,8 +212,7 @@ export interface StreamIntentRequest {
|
||||
* Fires for every `ask_clarification` tool message parsed out of the live
|
||||
* stream (the intent agent may emit several in a single turn). Lets the UI
|
||||
* surface each assistance question in real-time instead of waiting for the
|
||||
* terminal frame — which only carries the *first* question. `index` is the
|
||||
* 0-based arrival order within this turn.
|
||||
* terminal frame. `index` is the 0-based arrival order within this turn.
|
||||
*/
|
||||
onClarification?: (clarification: ClarificationPayload, index: number) => void;
|
||||
}
|
||||
@@ -208,8 +233,8 @@ export interface StreamIntentResult {
|
||||
clarification: ClarificationPayload | null;
|
||||
/**
|
||||
* All `ask_clarification` questions the agent asked this turn, in arrival
|
||||
* order. Collected from the live `type:"tool"` frames (the terminal frame
|
||||
* only carries the first). Empty unless status === "clarification".
|
||||
* order. Collected live and reconciled against the terminal frame so a
|
||||
* reconnect cannot lose cards. Empty unless status === "clarification".
|
||||
*/
|
||||
clarifications: ClarificationPayload[];
|
||||
/**
|
||||
@@ -235,6 +260,7 @@ function isFinalIntentFrame(value: unknown): value is {
|
||||
options?: unknown[];
|
||||
allow_custom?: boolean;
|
||||
allow_multiple?: boolean;
|
||||
clarifications?: unknown[];
|
||||
error_detail?: unknown;
|
||||
} {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
@@ -327,6 +353,41 @@ function extractClarificationToolMessage(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one clarification included in the terminal status frame. This is
|
||||
* the reconnect / proxy fallback for cases where one or more live `tool`
|
||||
* frames were not delivered to the browser.
|
||||
*/
|
||||
function parseTerminalClarification(
|
||||
value: unknown,
|
||||
): { payload: ClarificationPayload; toolCallId: string } | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const raw = value as Record<string, unknown>;
|
||||
const clarificationType =
|
||||
typeof raw.clarification_type === "string" ? raw.clarification_type : "";
|
||||
const toolCallId = typeof raw.id === "string" ? raw.id : "";
|
||||
return {
|
||||
toolCallId,
|
||||
payload: {
|
||||
id: toolCallId || undefined,
|
||||
question: typeof raw.question === "string" ? raw.question : "",
|
||||
clarificationType,
|
||||
context:
|
||||
typeof raw.clarification_context === "string"
|
||||
? raw.clarification_context
|
||||
: typeof raw.context === "string"
|
||||
? raw.context
|
||||
: "",
|
||||
options: Array.isArray(raw.options) ? raw.options : [],
|
||||
allowCustom: raw.allow_custom !== false,
|
||||
allowMultiple: resolveAllowMultiple(
|
||||
typeof raw.allow_multiple === "boolean" ? raw.allow_multiple : undefined,
|
||||
clarificationType,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Open an SSE connection to /api/intent/stream and resolve when the upstream
|
||||
* stream completes. Each call is one user turn; reuse the same threadId
|
||||
@@ -340,6 +401,7 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
thread_id: req.threadId,
|
||||
message: req.message,
|
||||
model: req.model,
|
||||
intent_agent_id: req.intentAgentId || undefined,
|
||||
task_context: req.taskContext ?? undefined,
|
||||
// 仅在有文件时带上,空数组后端也安全忽略。
|
||||
files: req.files && req.files.length > 0 ? req.files : undefined,
|
||||
@@ -387,8 +449,7 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
};
|
||||
|
||||
// Clarifications collected live from `type:"tool"` frames, deduped by
|
||||
// tool_call_id. The terminal frame only carries the first question, so this
|
||||
// is the source of truth for multi-question turns.
|
||||
// tool_call_id, then reconciled against the complete terminal list.
|
||||
const seenClarificationIds = new Set<string>();
|
||||
const collectClarification = (payload: ClarificationPayload, toolCallId: string) => {
|
||||
const dedupeKey = toolCallId || `idx-${result.clarifications.length}`;
|
||||
@@ -435,7 +496,7 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
result.status = parsed.status;
|
||||
if (typeof parsed.content === "string") result.content = parsed.content;
|
||||
if (parsed.summary && typeof parsed.summary === "object") {
|
||||
result.summary = parsed.summary as IntentSummary;
|
||||
result.summary = normalizeIntentReadySummary(parsed.summary);
|
||||
}
|
||||
if (parsed.status === "error") {
|
||||
result.errorDetail = parseIntentErrorDetail(parsed.error_detail);
|
||||
@@ -445,28 +506,26 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
detail: result.errorDetail,
|
||||
});
|
||||
}
|
||||
if (parsed.status === "clarification" && result.clarifications.length === 0) {
|
||||
// Fallback path: no live `type:"tool"` clarification frames were seen
|
||||
// (older backend, or single-question turn) — synthesize one from the
|
||||
// terminal frame so the UI still gets a card. When tool frames *were*
|
||||
// seen, `clarifications` already holds the full (possibly multi-question)
|
||||
// set and we keep it.
|
||||
const clarificationType =
|
||||
typeof parsed.clarification_type === "string" ? parsed.clarification_type : "";
|
||||
const fallback: ClarificationPayload = {
|
||||
question: typeof parsed.question === "string" ? parsed.question : "",
|
||||
clarificationType,
|
||||
context:
|
||||
typeof parsed.clarification_context === "string" ? parsed.clarification_context : "",
|
||||
options: Array.isArray(parsed.options) ? parsed.options : [],
|
||||
allowCustom: parsed.allow_custom !== false,
|
||||
allowMultiple: resolveAllowMultiple(
|
||||
typeof parsed.allow_multiple === "boolean" ? parsed.allow_multiple : undefined,
|
||||
clarificationType,
|
||||
),
|
||||
};
|
||||
result.clarification = fallback;
|
||||
result.clarifications = [fallback];
|
||||
if (parsed.status === "clarification") {
|
||||
// Newer backend frames contain every card. Merge them even when a
|
||||
// subset already arrived live: an SSE reconnect can otherwise leave
|
||||
// the user with only the first card in a multi-question assistance
|
||||
// round. Older backends still fall back to the legacy top-level card.
|
||||
const terminalCards = Array.isArray(parsed.clarifications)
|
||||
? parsed.clarifications
|
||||
.map(parseTerminalClarification)
|
||||
.filter((item): item is { payload: ClarificationPayload; toolCallId: string } => item !== null)
|
||||
: [];
|
||||
if (terminalCards.length > 0) {
|
||||
terminalCards.forEach((card, index) => {
|
||||
collectClarification(card.payload, card.toolCallId || `terminal-${index}`);
|
||||
});
|
||||
} else if (result.clarifications.length === 0) {
|
||||
const fallback = parseTerminalClarification(parsed);
|
||||
if (fallback) {
|
||||
collectClarification(fallback.payload, fallback.toolCallId || "terminal-0");
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -153,6 +153,10 @@ export function BusinessChainPicker({
|
||||
// 席位「会商技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
|
||||
const skillById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
|
||||
const skillOf = (id: string) => skillById.get(id) ?? false;
|
||||
const humanValidationById = new Map(
|
||||
selectedChain.seats.map((s) => [s.agent_id, s.human_validation ?? false]),
|
||||
);
|
||||
const humanValidationOf = (id: string) => humanValidationById.get(id) ?? false;
|
||||
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
|
||||
const seatModeById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
|
||||
const seatModeOf = (id: string) => seatModeById.get(id) ?? null;
|
||||
@@ -162,12 +166,12 @@ export function BusinessChainPicker({
|
||||
// dag:席位顺序按 stage 展平(与 plan 一致)。
|
||||
const agents = dagPlan.stages
|
||||
.flatMap((st) => st.agentIds)
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), human_validation: humanValidationOf(id), seatMode: seatModeOf(id) }));
|
||||
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode, gatherFirst: selectedChain.gatherFirst ?? false });
|
||||
return;
|
||||
}
|
||||
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), human_validation: humanValidationOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
onConfirm({ agents, mode: "chain", chain: chainMeta, gatherFirst: selectedChain.gatherFirst ?? false });
|
||||
};
|
||||
|
||||
|
||||
@@ -103,6 +103,12 @@ export interface Step1PanelProps {
|
||||
*/
|
||||
headerLeftSlot?: React.ReactNode;
|
||||
headerRightSlot?: React.ReactNode;
|
||||
/** Optional side content rendered below the shared header, beside the dialogue area. */
|
||||
rightSidebar?: React.ReactNode;
|
||||
/** Hide the shared question-count badge when a workspace supplies its own header actions. */
|
||||
hideQuestionCount?: boolean;
|
||||
/** Optional empty state rendered in the centre of an otherwise blank dialogue list. */
|
||||
emptyState?: React.ReactNode;
|
||||
interactiveMessages: InteractiveMessage[];
|
||||
intentThreadId: string | null;
|
||||
intentReady: object | null;
|
||||
@@ -146,6 +152,9 @@ export function Step1Panel(props: Step1PanelProps) {
|
||||
const {
|
||||
headerLeftSlot,
|
||||
headerRightSlot,
|
||||
rightSidebar,
|
||||
hideQuestionCount = false,
|
||||
emptyState,
|
||||
rootClassName,
|
||||
interactiveMessages,
|
||||
intentThreadId,
|
||||
@@ -230,6 +239,7 @@ export function Step1Panel(props: Step1PanelProps) {
|
||||
|
||||
// 顶部标题栏整片脱敏(消息列表正文在下方,不在此容器内,保持原文)。
|
||||
const headerDzRef = useDesensitizeSubtree<HTMLDivElement>();
|
||||
const showEmptyState = interactiveMessages.length === 0 && Boolean(emptyState);
|
||||
|
||||
return (
|
||||
<div className={`flex-1 flex flex-col min-h-0 ${rootClassName ?? ""}`}>
|
||||
@@ -244,34 +254,45 @@ export function Step1Panel(props: Step1PanelProps) {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<span className="shrink-0 text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
|
||||
问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮
|
||||
</span>
|
||||
{!hideQuestionCount && (
|
||||
<span className="shrink-0 text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
|
||||
问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮
|
||||
</span>
|
||||
)}
|
||||
{headerRightSlot}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={rightSidebar ? "flex min-h-0 flex-1" : "contents"}>
|
||||
<div className={rightSidebar ? "flex min-w-0 flex-1 flex-col" : "contents"}>
|
||||
{/* Chat list */}
|
||||
<div className="relative flex-1 min-h-0 flex flex-col font-normal">
|
||||
<div
|
||||
ref={step1ScrollRef}
|
||||
// overflow-x-hidden:消息列表只竖向滚(见 Step2Panel 同处注释),避免误触横向拖动抢滑块。
|
||||
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden bg-white"
|
||||
className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden bg-white"
|
||||
>
|
||||
<div ref={step1ContentRef} className="space-y-4 p-6">
|
||||
{interactiveMessages.map((msg) => (
|
||||
<Step1Message
|
||||
key={msg.id}
|
||||
msg={msg}
|
||||
metric={speedMeterEnabled ? messageMetrics.get(msg.id) : undefined}
|
||||
intentReady={intentReady}
|
||||
pendingIntentClarificationMsgId={pendingIntentClarificationMsgId}
|
||||
intentClarificationSelections={intentClarificationSelections}
|
||||
setIntentClarificationSelections={setIntentClarificationSelections}
|
||||
isIntentSending={isIntentSending}
|
||||
submitIntentClarifications={submitIntentClarifications}
|
||||
/>
|
||||
))}
|
||||
<div
|
||||
ref={step1ContentRef}
|
||||
className={showEmptyState ? "flex min-h-full flex-1 p-6" : "space-y-4 p-6"}
|
||||
>
|
||||
{showEmptyState ? (
|
||||
<div className="flex min-h-full w-full flex-1 items-center justify-center">{emptyState}</div>
|
||||
) : (
|
||||
interactiveMessages.map((msg) => (
|
||||
<Step1Message
|
||||
key={msg.id}
|
||||
msg={msg}
|
||||
metric={speedMeterEnabled ? messageMetrics.get(msg.id) : undefined}
|
||||
intentReady={intentReady}
|
||||
pendingIntentClarificationMsgId={pendingIntentClarificationMsgId}
|
||||
intentClarificationSelections={intentClarificationSelections}
|
||||
setIntentClarificationSelections={setIntentClarificationSelections}
|
||||
isIntentSending={isIntentSending}
|
||||
submitIntentClarifications={submitIntentClarifications}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!step1AtBottom && <ScrollToBottomButton onClick={scrollStep1ToBottom} />}
|
||||
@@ -453,6 +474,9 @@ export function Step1Panel(props: Step1PanelProps) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{rightSidebar}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -664,6 +688,15 @@ function Step1Message({
|
||||
|
||||
/** [INTENT_READY] 标记块解析出 IntentSummary 后的绿色摘要卡。 */
|
||||
function IntentReadySummaryCard({ summary }: { summary: IntentSummary }) {
|
||||
const positionSections =
|
||||
summary.coreGoals && summary.riskWarnings && summary.keyPoints && summary.strategicSignificance
|
||||
? ([
|
||||
["核心目标", summary.coreGoals],
|
||||
["风险提示", summary.riskWarnings],
|
||||
["关键要点", summary.keyPoints],
|
||||
["战略意义", summary.strategicSignificance],
|
||||
] as const)
|
||||
: null;
|
||||
return (
|
||||
<div className="mt-1 border border-emerald-200 bg-emerald-50/50 rounded-xl p-3 space-y-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
@@ -672,30 +705,35 @@ function IntentReadySummaryCard({ summary }: { summary: IntentSummary }) {
|
||||
任务意图已明确
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">核心目标</span>
|
||||
<p className="text-[11.5px] text-slate-800 leading-relaxed">{summary.objective}</p>
|
||||
</div>
|
||||
{summary.constraints?.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">约束条件</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.constraints.map((c, i) => (
|
||||
<li key={i} className="leading-snug">{c}</li>
|
||||
))}
|
||||
</ul>
|
||||
{positionSections ? positionSections.map(([label, values]) => (
|
||||
<div key={label} className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">{label}</span>
|
||||
{values.length > 0 ? <ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{values.map((value, index) => <li key={index} className="leading-snug">{value}</li>)}
|
||||
</ul> : <p className="text-[11px] text-slate-500">暂无{label}</p>}
|
||||
</div>
|
||||
)}
|
||||
{summary.assumptions && summary.assumptions.length > 0 && (
|
||||
)) : <>
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">关键假设</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.assumptions.map((a, i) => (
|
||||
<li key={i} className="leading-snug">{a}</li>
|
||||
))}
|
||||
</ul>
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">核心目标</span>
|
||||
<p className="text-[11.5px] text-slate-800 leading-relaxed">{summary.objective}</p>
|
||||
</div>
|
||||
)}
|
||||
{summary.constraints?.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">约束条件</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.constraints.map((c, i) => <li key={i} className="leading-snug">{c}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{summary.assumptions && summary.assumptions.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">关键假设</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.assumptions.map((a, i) => <li key={i} className="leading-snug">{a}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -90,10 +90,14 @@ export interface UseStep1IntentOptions {
|
||||
currentStep: number;
|
||||
/** 全局选中模型;调用 `/api/intent/init` / `/api/intent/stream` 时透传。 */
|
||||
selectedModel: string;
|
||||
/** Optional built-in agent override for a workspace with a distinct schema. */
|
||||
intentAgentId?: string;
|
||||
/** Optional hidden task/business context for each intent-agent turn. */
|
||||
taskContext?: Record<string, unknown> | null;
|
||||
/** Optional task-aware welcome bubble text before the first user turn. */
|
||||
initialWelcomeText?: string;
|
||||
/** Keep the dialogue visually empty while its intent thread is initialising. */
|
||||
showInitialWelcome?: boolean;
|
||||
/** 主页面统一的 toast 入口。 */
|
||||
triggerToast: (msg: string) => void;
|
||||
}
|
||||
@@ -104,6 +108,7 @@ export interface UseStep1IntentReturn {
|
||||
intentReady: IntentSummary | null;
|
||||
intentInitError: string | null;
|
||||
intentInitErrorDetail: IntentErrorDetail | null;
|
||||
isIntentInitializing: boolean;
|
||||
isIntentSending: boolean;
|
||||
pendingIntentClarificationMsgId: number | null;
|
||||
/** Per-question selections, keyed by `clarificationKey(msgId, clarId, index)`. */
|
||||
@@ -172,13 +177,22 @@ function intentPhaseLabel(phase: IntentStreamPhase, toolName?: string): string {
|
||||
}
|
||||
|
||||
export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentReturn {
|
||||
const { currentStep, selectedModel, taskContext, initialWelcomeText, triggerToast } = options;
|
||||
const {
|
||||
currentStep,
|
||||
selectedModel,
|
||||
intentAgentId,
|
||||
taskContext,
|
||||
initialWelcomeText,
|
||||
showInitialWelcome = true,
|
||||
triggerToast,
|
||||
} = options;
|
||||
|
||||
const [intentThreadId, setIntentThreadId] = useState<string | null>(null);
|
||||
const [intentReady, setIntentReady] = useState<IntentSummary | null>(null);
|
||||
const [intentInitError, setIntentInitError] = useState<string | null>(null);
|
||||
const [intentInitErrorDetail, setIntentInitErrorDetail] =
|
||||
useState<IntentErrorDetail | null>(null);
|
||||
const [isIntentInitializing, setIsIntentInitializing] = useState<boolean>(false);
|
||||
const [isIntentSending, setIsIntentSending] = useState<boolean>(false);
|
||||
const [pendingIntentClarificationMsgId, setPendingIntentClarificationMsgId] =
|
||||
useState<number | null>(null);
|
||||
@@ -203,6 +217,10 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
useEffect(() => {
|
||||
selectedModelRef.current = selectedModel;
|
||||
}, [selectedModel]);
|
||||
const intentAgentIdRef = useRef<string | undefined>(intentAgentId);
|
||||
useEffect(() => {
|
||||
intentAgentIdRef.current = intentAgentId;
|
||||
}, [intentAgentId]);
|
||||
const taskContextRef = useRef<Record<string, unknown> | null>(taskContext ?? null);
|
||||
useEffect(() => {
|
||||
taskContextRef.current = taskContext ?? null;
|
||||
@@ -230,18 +248,23 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
setIntentInitError(null);
|
||||
setIntentInitErrorDetail(null);
|
||||
setIntentThreadId(null);
|
||||
setIsIntentInitializing(true);
|
||||
setPendingIntentClarificationMsgId(null);
|
||||
setIntentClarificationSelections(new Map());
|
||||
setTimelineEntries([]);
|
||||
setInteractiveMessages([
|
||||
{
|
||||
id: 1,
|
||||
sender: "agent",
|
||||
senderName: "任务理解智能体",
|
||||
content: initialWelcomeTextRef.current || INTENT_WELCOME_TEXT,
|
||||
time: nowTime(),
|
||||
},
|
||||
]);
|
||||
setInteractiveMessages(
|
||||
showInitialWelcome
|
||||
? [
|
||||
{
|
||||
id: 1,
|
||||
sender: "agent",
|
||||
senderName: "任务理解智能体",
|
||||
content: initialWelcomeTextRef.current || INTENT_WELCOME_TEXT,
|
||||
time: nowTime(),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
(async () => {
|
||||
try {
|
||||
// initIntent 当前不在 thread 上落盘 model,只为占位与兼容;空时由后端
|
||||
@@ -249,9 +272,11 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
const res = await initIntent(
|
||||
selectedModelRef.current || undefined,
|
||||
taskContextRef.current,
|
||||
intentAgentIdRef.current,
|
||||
);
|
||||
if (step1InitGenRef.current !== myGen) return;
|
||||
setIntentThreadId(res.thread_id);
|
||||
setIsIntentInitializing(false);
|
||||
setTimelineEntries([
|
||||
{
|
||||
id: 1,
|
||||
@@ -262,6 +287,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
]);
|
||||
} catch (err) {
|
||||
if (step1InitGenRef.current !== myGen) return;
|
||||
setIsIntentInitializing(false);
|
||||
console.error("init intent failed:", err);
|
||||
if (err instanceof IntentInitError) {
|
||||
setIntentInitError(err.detail?.message || err.message);
|
||||
@@ -272,13 +298,14 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
}, [showInitialWelcome]);
|
||||
|
||||
const resetIntent = useCallback(() => {
|
||||
stopIntentStream();
|
||||
step1InitRef.current = false;
|
||||
step1InitGenRef.current += 1;
|
||||
setIntentThreadId(null);
|
||||
setIsIntentInitializing(false);
|
||||
setIntentReady(null);
|
||||
setIntentInitError(null);
|
||||
setIntentInitErrorDetail(null);
|
||||
@@ -424,6 +451,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
threadId: intentThreadId,
|
||||
message: trimmed,
|
||||
model: selectedModelRef.current || undefined,
|
||||
intentAgentId: intentAgentIdRef.current,
|
||||
taskContext: taskContextRef.current,
|
||||
files: fileRefs,
|
||||
signal: aborter.signal,
|
||||
@@ -654,6 +682,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
// 或继续显示旧会话的澄清选择。
|
||||
stopIntentStream();
|
||||
setIsIntentSending(false);
|
||||
setIsIntentInitializing(false);
|
||||
setPendingIntentClarificationMsgId(null);
|
||||
setIntentClarificationSelections(new Map());
|
||||
setIntentThreadId(snapshot.intentThreadId);
|
||||
@@ -690,6 +719,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
intentReady,
|
||||
intentInitError,
|
||||
intentInitErrorDetail,
|
||||
isIntentInitializing,
|
||||
isIntentSending,
|
||||
pendingIntentClarificationMsgId,
|
||||
intentClarificationSelections,
|
||||
|
||||
@@ -33,6 +33,13 @@ import { useUpdateSubtask } from "@/core/tasks/context";
|
||||
/** 干预消息携带的上传文件引用(与 streamMultiAgent 的 files 字段同形)。 */
|
||||
type RunFileRef = NonNullable<StreamMultiAgentRequest["files"]>[number];
|
||||
|
||||
type SeatDelivery = { name: string; content: string };
|
||||
|
||||
/** In-memory cursor for a business-chain human-validation pause. */
|
||||
type HumanValidationContinuation =
|
||||
| { mode: "chain"; nextSeatIndex: number }
|
||||
| { mode: "dag"; nextStageIndex: number; priorDeliveries: SeatDelivery[] };
|
||||
|
||||
/** 读取并清空 ref(consume-once):首个 leader run 拿到文件后清空,后续轮次不再带。 */
|
||||
function takeOnce<T>(ref: { current: T | null }): T | undefined {
|
||||
const v = ref.current ?? undefined;
|
||||
@@ -286,6 +293,8 @@ export interface UseStep2OrchestrationOptions {
|
||||
* OR。recommend / 未选链条 → 空 {}(各席位仅靠其自身开关)。
|
||||
*/
|
||||
seatSkillDirectives?: Record<string, boolean>;
|
||||
/** Per-seat human-validation checkpoints inherited from the selected chain. */
|
||||
humanValidations?: Record<string, boolean>;
|
||||
/**
|
||||
* 每席位「推理深度覆盖」映射 {agentId: SeatMode | null}(沿用所选业务链条里每个席位的配置)。
|
||||
* 派活该 special 席位时按 agentId 查表,**席位覆盖优先、否则跟随链条级 `selectedMode`**:
|
||||
@@ -456,6 +465,7 @@ export function useStep2Orchestration(
|
||||
selectedModel,
|
||||
selectedMode,
|
||||
seatSkillDirectives = {},
|
||||
humanValidations = {},
|
||||
seatModes = {},
|
||||
gatherFirst = false,
|
||||
orchestrationMode,
|
||||
@@ -593,6 +603,7 @@ export function useStep2Orchestration(
|
||||
const selectedModeRef = useRef<SeatMode>(selectedMode);
|
||||
// 每席位技能识别强化映射(所选业务链条各席位开关)同样打到 ref,席位调用按 agentId 读最新值。
|
||||
const seatSkillDirectivesRef = useRef<Record<string, boolean>>(seatSkillDirectives);
|
||||
const humanValidationsRef = useRef<Record<string, boolean>>(humanValidations);
|
||||
// 每席位推理深度覆盖映射(所选业务链条各席位 seatMode)打到 ref,席位调用按 agentId 读最新值;
|
||||
// 覆盖优先、否则跟随 selectedModeRef。
|
||||
const seatModesRef = useRef<Record<string, SeatMode | null>>(seatModes);
|
||||
@@ -624,6 +635,7 @@ export function useStep2Orchestration(
|
||||
// 澄清回复都改走 **leader 自由派活循环**(runOrchestration),由总控接着派活,而**不是**
|
||||
// 重新把整张 DAG 从头跑一遍(致命 bug 修复)。新任务 / 重新进入时由 resetInitGate 复位。
|
||||
const dagPlanExecutedRef = useRef<boolean>(false);
|
||||
const humanValidationContinuationRef = useRef<HumanValidationContinuation | null>(null);
|
||||
const selectedAgentsRef = useRef<SelectedAgent[]>(selectedAgents);
|
||||
useEffect(() => {
|
||||
orchestrationModeRef.current = orchestrationMode;
|
||||
@@ -643,6 +655,9 @@ export function useStep2Orchestration(
|
||||
useEffect(() => {
|
||||
seatSkillDirectivesRef.current = seatSkillDirectives;
|
||||
}, [seatSkillDirectives]);
|
||||
useEffect(() => {
|
||||
humanValidationsRef.current = humanValidations;
|
||||
}, [humanValidations]);
|
||||
useEffect(() => {
|
||||
seatModesRef.current = seatModes;
|
||||
}, [seatModes]);
|
||||
@@ -1213,6 +1228,21 @@ export function useStep2Orchestration(
|
||||
[],
|
||||
);
|
||||
|
||||
const pauseForHumanValidation = useCallback(
|
||||
(continuation: HumanValidationContinuation, seatNames: string[]) => {
|
||||
humanValidationContinuationRef.current = continuation;
|
||||
appendDialogue({
|
||||
sender: "系统",
|
||||
avatarType: "blue",
|
||||
content: `已完成 ${seatNames.join("、")} 的输出,按业务链条配置暂停,等待人工校验。可直接点击“恢复会商”继续,或在下方输入修改意见后提交。`,
|
||||
confidence: "等待人工校验",
|
||||
});
|
||||
setIsRoundTableRunning(false);
|
||||
triggerToast("已暂停等待人工校验:可恢复会商,或输入修改意见后继续");
|
||||
},
|
||||
[appendDialogue, triggerToast],
|
||||
);
|
||||
|
||||
const phaseLabel = useCallback(
|
||||
(
|
||||
phase: StreamPhase,
|
||||
@@ -2012,11 +2042,17 @@ export function useStep2Orchestration(
|
||||
|
||||
const chainSeats = selectedAgentsRef.current;
|
||||
const total = chainSeats.length;
|
||||
const continuation = humanValidationContinuationRef.current;
|
||||
const startSeatIndex =
|
||||
continuation?.mode === "chain" ? continuation.nextSeatIndex : 0;
|
||||
if (continuation?.mode === "chain") {
|
||||
humanValidationContinuationRef.current = null;
|
||||
}
|
||||
const leaderThreadId = resolveSeatThreadId(ids, coord);
|
||||
let finishedAllSeats = true;
|
||||
|
||||
try {
|
||||
for (let i = 0; i < total; i += 1) {
|
||||
for (let i = startSeatIndex; i < total; i += 1) {
|
||||
if (isStale()) {
|
||||
finishedAllSeats = false;
|
||||
break;
|
||||
@@ -2179,6 +2215,14 @@ export function useStep2Orchestration(
|
||||
}
|
||||
|
||||
setConsensusPercentage(Math.min(95, Math.round(((i + 1) / total) * 90)));
|
||||
if (humanValidationsRef.current[seat.agent_id]) {
|
||||
pauseForHumanValidation(
|
||||
{ mode: "chain", nextSeatIndex: i + 1 },
|
||||
[seatName],
|
||||
);
|
||||
finishedAllSeats = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── (c) 总控收口:综合全链交付,产出最终结论 ──
|
||||
@@ -2257,6 +2301,7 @@ export function useStep2Orchestration(
|
||||
handleUpstreamFrame,
|
||||
ingestSubagentTaskFrame,
|
||||
resolveSeatThreadId,
|
||||
pauseForHumanValidation,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2300,23 +2345,37 @@ export function useStep2Orchestration(
|
||||
dagPlanExecutedRef.current = true;
|
||||
|
||||
const leaderThreadId = resolveSeatThreadId(ids, coord);
|
||||
const continuation = humanValidationContinuationRef.current;
|
||||
const startStageIndex =
|
||||
continuation?.mode === "dag" ? continuation.nextStageIndex : 0;
|
||||
if (continuation?.mode === "dag") {
|
||||
humanValidationContinuationRef.current = null;
|
||||
}
|
||||
let finishedAllStages = true;
|
||||
// 跨 stage 累积的**完整交付** {name, content}[] —— 注入下一 stage 席位的 run context
|
||||
// (peerDeliveries),供 read_peer_delivery 工具按需取全文(§12.9 传摘要按需传全文)。
|
||||
// 研讨前并行取数(gatherFirst)的产物作为初始注入:首个 stage 席位开局即带共享资料。
|
||||
const priorDeliveries: Array<{ name: string; content: string }> = [...gatheredDeliveriesRef.current];
|
||||
const priorDeliveries: SeatDelivery[] =
|
||||
continuation?.mode === "dag"
|
||||
? [...continuation.priorDeliveries]
|
||||
: [...gatheredDeliveriesRef.current];
|
||||
|
||||
// Phase 7:初始化 DAG 流程图节点状态 —— 计划内所有席位置 pending,执行过程中逐个点亮。
|
||||
const markDagNode = (agentId: string, state: ChainNodeState) =>
|
||||
setDagNodeStates((prev) => ({ ...prev, [agentId.toLowerCase()]: state }));
|
||||
setDagNodeStates(
|
||||
Object.fromEntries(
|
||||
plan.stages.flatMap((st) => st.agentIds.map((id) => [id.toLowerCase(), "pending" as ChainNodeState])),
|
||||
plan.stages.flatMap((st, stageIndex) =>
|
||||
st.agentIds.map((id) => [
|
||||
id.toLowerCase(),
|
||||
(stageIndex < startStageIndex ? "done" : "pending") as ChainNodeState,
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
for (let s = 0; s < plan.stages.length; s += 1) {
|
||||
for (let s = startStageIndex; s < plan.stages.length; s += 1) {
|
||||
if (isStale()) {
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
@@ -2558,6 +2617,21 @@ export function useStep2Orchestration(
|
||||
setConsensusPercentage(
|
||||
Math.min(95, Math.round(((s + 1) / plan.stages.length) * 90)),
|
||||
);
|
||||
const validationSeatNames = stageSeats
|
||||
.filter(({ agentId }) => humanValidationsRef.current[agentId])
|
||||
.map(({ name }) => name);
|
||||
if (validationSeatNames.length > 0) {
|
||||
pauseForHumanValidation(
|
||||
{
|
||||
mode: "dag",
|
||||
nextStageIndex: s + 1,
|
||||
priorDeliveries: [...priorDeliveries],
|
||||
},
|
||||
validationSeatNames,
|
||||
);
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 计划阶段全部完成 → **交给总控(leader 自由派活循环)继续** ──
|
||||
@@ -2613,6 +2687,7 @@ export function useStep2Orchestration(
|
||||
ingestParallelDelta,
|
||||
resetParallelStreams,
|
||||
runOrchestration,
|
||||
pauseForHumanValidation,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2746,8 +2821,9 @@ export function useStep2Orchestration(
|
||||
// 改走 leader 自由派活循环,由总控接着派活,而不是把 DAG 从头重跑一遍。
|
||||
if (
|
||||
mode === "dag" &&
|
||||
!dagPlanExecutedRef.current &&
|
||||
(orchestrationPlanRef.current?.stages.length ?? 0) > 0
|
||||
(humanValidationContinuationRef.current?.mode === "dag" ||
|
||||
(!dagPlanExecutedRef.current &&
|
||||
(orchestrationPlanRef.current?.stages.length ?? 0) > 0))
|
||||
) {
|
||||
return runDagOrchestration(seedMessage, ids, coord);
|
||||
}
|
||||
@@ -3070,6 +3146,7 @@ export function useStep2Orchestration(
|
||||
|
||||
const resetInitGate = useCallback(() => {
|
||||
step2InitRef.current = false;
|
||||
humanValidationContinuationRef.current = null;
|
||||
// 新一轮研讨:允许 DAG 计划重新执行一遍。
|
||||
dagPlanExecutedRef.current = false;
|
||||
// 新一轮研讨:允许「研讨前并行取数」再取一次(清掉上一轮取数产物 + 闸门)。
|
||||
@@ -3086,6 +3163,7 @@ export function useStep2Orchestration(
|
||||
// 这里只重复设 cancel ref 与 UI 标记,确保从 Step 2 在编排中切到草稿时
|
||||
// UI 立刻翻成静止态。
|
||||
orchestrationCancelRef.current = true;
|
||||
humanValidationContinuationRef.current = null;
|
||||
setIsOrchestrating(false);
|
||||
setIsInitializing(false);
|
||||
setPendingClarification(null);
|
||||
@@ -3166,6 +3244,7 @@ export function useStep2Orchestration(
|
||||
return false;
|
||||
}
|
||||
dagPlanExecutedRef.current = true;
|
||||
humanValidationContinuationRef.current = null;
|
||||
orchestrationCancelRef.current = true;
|
||||
abortAllInFlight();
|
||||
isOrchestratingRef.current = false;
|
||||
@@ -3208,6 +3287,7 @@ export function useStep2Orchestration(
|
||||
hasAutoOpenedRef.current = new Set();
|
||||
pendingInjectPromptRef.current = null;
|
||||
dagPlanExecutedRef.current = false;
|
||||
humanValidationContinuationRef.current = null;
|
||||
gatherPhaseDoneRef.current = false;
|
||||
gatheredDeliveriesRef.current = [];
|
||||
deselectArtifact();
|
||||
|
||||
@@ -36,6 +36,11 @@ export interface ChainSeat {
|
||||
* (无需 DB 列),在链条编辑器里逐席位开关。
|
||||
*/
|
||||
seat_skill_directive?: boolean;
|
||||
/**
|
||||
* Human-validation checkpoint. When enabled, Step 2 pauses after this seat
|
||||
* (or its DAG stage) completes and reuses the existing resume/intervention UI.
|
||||
*/
|
||||
human_validation?: boolean;
|
||||
/**
|
||||
* 可选「席位推理深度覆盖」:覆盖链条级 `seatMode`,只对该席位生效。值是同一套
|
||||
* `SeatMode`(flash/thinking/pro/ultra);null / 缺省 = 跟随链条级默认。用于「卡顿提速」:
|
||||
@@ -109,7 +114,7 @@ export interface SeatSelectionResult {
|
||||
* `model` 为该席位在来源链条里配置的模型覆盖(空 / 缺省 = 跟随全局模型)。
|
||||
* `seat_skill_directive` 为该席位在来源链条里配置的「技能识别强化」开关(缺省 = 关)。
|
||||
*/
|
||||
agents: Array<{ agent_id: string; name: string; model?: string | null; seat_skill_directive?: boolean; seatMode?: SeatMode | null }>;
|
||||
agents: Array<{ agent_id: string; name: string; model?: string | null; seat_skill_directive?: boolean; human_validation?: boolean; seatMode?: SeatMode | null }>;
|
||||
/**
|
||||
* 决定 Step 2 走哪种编排:
|
||||
* - `recommend` 总控自由派活;
|
||||
@@ -171,6 +176,10 @@ export function buildChainSeatSelection(
|
||||
// 席位「技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
|
||||
const skillById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
|
||||
const skillOf = (id: string) => skillById.get(id) ?? false;
|
||||
const humanValidationById = new Map(
|
||||
chain.seats.map((s) => [s.agent_id, s.human_validation ?? false]),
|
||||
);
|
||||
const humanValidationOf = (id: string) => humanValidationById.get(id) ?? false;
|
||||
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
|
||||
// 输出到 SeatSelectionResult.agents[].seatMode(camel,喂给编排/作业的 seatModes map)。
|
||||
const seatModeById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
|
||||
@@ -196,12 +205,12 @@ export function buildChainSeatSelection(
|
||||
if (hasParallel || hasGoal || hasCoord) {
|
||||
const agents = plan.stages
|
||||
.flatMap((st) => st.agentIds)
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), human_validation: humanValidationOf(id), seatMode: seatModeOf(id) }));
|
||||
return { agents, mode: "dag", chain: chainMeta, plan, dagExecMode: "sandbox", seatMode: chain.seatMode, gatherFirst: chain.gatherFirst ?? false };
|
||||
}
|
||||
}
|
||||
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), human_validation: humanValidationOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
return { agents, mode: "chain", chain: chainMeta, seatMode: chain.seatMode, gatherFirst: chain.gatherFirst ?? false };
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
moveSeatToStage,
|
||||
moveStage,
|
||||
removeSeat,
|
||||
setSeatHumanValidation,
|
||||
setStageGoal,
|
||||
splitSeatToNewStage,
|
||||
stageGroupsToSeats,
|
||||
@@ -122,6 +123,15 @@ test("setStageGoal is immutable + out-of-range no-op", () => {
|
||||
assert.equal(setStageGoal(groups, 9, "x"), groups); // 越界返回原引用
|
||||
});
|
||||
|
||||
test("setSeatHumanValidation updates only the selected seat and is immutable", () => {
|
||||
const groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
const next = setSeatHumanValidation(groups, "b", true);
|
||||
assert.equal(next[0].seats[1].human_validation, true);
|
||||
assert.equal(next[0].seats[0].human_validation, undefined);
|
||||
assert.equal(next[1].seats[0].human_validation, undefined);
|
||||
assert.equal(groups[0].seats[1].human_validation, undefined);
|
||||
});
|
||||
|
||||
// ── lookups ───────────────────────────────────────────────────────────────────
|
||||
|
||||
test("findStageIndexOfSeat / countSeats", () => {
|
||||
|
||||
@@ -141,6 +141,23 @@ export function setSeatSkillDirective(groups: StageGroups, agentId: string, enab
|
||||
});
|
||||
}
|
||||
|
||||
/** Update a seat's human-validation checkpoint without changing other stages. */
|
||||
export function setSeatHumanValidation(
|
||||
groups: StageGroups,
|
||||
agentId: string,
|
||||
enabled: boolean,
|
||||
): StageGroups {
|
||||
return groups.map((g) => {
|
||||
if (!g.seats.some((s) => s.agent_id === agentId)) return g;
|
||||
return {
|
||||
...g,
|
||||
seats: g.seats.map((s) =>
|
||||
s.agent_id === agentId ? { ...s, human_validation: enabled } : s,
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置某个席位的「推理深度覆盖」(不可变,供编辑器席位下拉 onChange)。
|
||||
* `mode` 为 null = 清除覆盖(跟随链条级 seatMode)。按 agent_id 定位,跨 stage 适用。
|
||||
|
||||
@@ -292,9 +292,29 @@ function toStringArray(value: unknown): string[] {
|
||||
* 把解析出的对象归一成 IntentSummary。只要 `objective` 是非空字符串就认。
|
||||
* constraints / assumptions 容忍模型写成字符串 / null / 缺失,统一归到 string[]。
|
||||
*/
|
||||
function normalizeIntentSummary(parsed: unknown): IntentSummary | null {
|
||||
export function normalizeIntentReadySummary(parsed: unknown): IntentSummary | null {
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
const positionKeys = ["coreGoals", "riskWarnings", "keyPoints", "strategicSignificance"];
|
||||
if (positionKeys.some((key) => key in obj)) {
|
||||
if (!positionKeys.every((key) => Array.isArray(obj[key]))) return null;
|
||||
const coreGoals = toStringArray(obj.coreGoals);
|
||||
const riskWarnings = toStringArray(obj.riskWarnings);
|
||||
const keyPoints = toStringArray(obj.keyPoints);
|
||||
const strategicSignificance = toStringArray(obj.strategicSignificance);
|
||||
// Keep the long-standing Step-1 state machine compatible while retaining
|
||||
// every position-specific field verbatim for its dedicated UI and storage.
|
||||
return {
|
||||
objective:
|
||||
strategicSignificance[0] || coreGoals[0] || keyPoints[0] || "岗位任务意图已识别",
|
||||
constraints: riskWarnings,
|
||||
assumptions: keyPoints,
|
||||
coreGoals,
|
||||
riskWarnings,
|
||||
keyPoints,
|
||||
strategicSignificance,
|
||||
};
|
||||
}
|
||||
const objective =
|
||||
typeof obj.objective === "string" ? obj.objective.trim() : "";
|
||||
if (!objective) return null;
|
||||
@@ -310,14 +330,14 @@ function normalizeIntentSummary(parsed: unknown): IntentSummary | null {
|
||||
* 1) 原文直接 parse
|
||||
* 2) 转义字符串内的裸控制字符(换行 / 制表符)后再 parse
|
||||
* 3) 再去掉尾随逗号后 parse
|
||||
* 三次都失败才放弃。任一成功都过 `normalizeIntentSummary` 兜字段类型。
|
||||
* 三次都失败才放弃。任一成功都过 `normalizeIntentReadySummary` 兜字段类型。
|
||||
*/
|
||||
function parseIntentSummary(raw: string): IntentSummary | null {
|
||||
const sanitized = sanitizeJsonControlChars(raw);
|
||||
const candidates = [raw, sanitized, stripTrailingCommas(sanitized)];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const summary = normalizeIntentSummary(JSON.parse(candidate));
|
||||
const summary = normalizeIntentReadySummary(JSON.parse(candidate));
|
||||
if (summary) return summary;
|
||||
} catch {
|
||||
// 下一个候选
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
Sparkles,
|
||||
SplitSquareVertical,
|
||||
Trash2,
|
||||
UserCheck,
|
||||
UserPlus,
|
||||
Wand2,
|
||||
X,
|
||||
@@ -127,6 +128,7 @@ import {
|
||||
seatExistsInGroups,
|
||||
setSeatMode as setSeatModeOnGroups,
|
||||
setSeatModel,
|
||||
setSeatHumanValidation,
|
||||
setSeatSkillDirective,
|
||||
setStageGoal,
|
||||
splitSeatToNewStage,
|
||||
@@ -453,6 +455,10 @@ export default function BusinessChainEditorPage() {
|
||||
setStageGroups((prev) => setSeatSkillDirective(prev, agentId, enabled));
|
||||
}, []);
|
||||
|
||||
const setSeatHumanValidationCb = useCallback((agentId: string, enabled: boolean) => {
|
||||
setStageGroups((prev) => setSeatHumanValidation(prev, agentId, enabled));
|
||||
}, []);
|
||||
|
||||
// 席位「推理深度覆盖」:编辑器席位小图标下拉 onChange(null = 清除,跟随链条级 seatMode)。
|
||||
const setSeatModeCb = useCallback((agentId: string, mode: SeatMode | null) => {
|
||||
setStageGroups((prev) => setSeatModeOnGroups(prev, agentId, mode));
|
||||
@@ -670,6 +676,7 @@ export default function BusinessChainEditorPage() {
|
||||
model: s.model ?? null,
|
||||
// 席位「会商技能识别强化」开关:随席位一起落库(缺省 = false 关)。
|
||||
seat_skill_directive: s.seat_skill_directive ?? false,
|
||||
human_validation: s.human_validation ?? false,
|
||||
// 席位「推理深度覆盖」:随席位一起落库(null = 跟随链条级 seatMode)。
|
||||
seat_mode: s.seat_mode ?? null,
|
||||
// 岗位协同专用岗位归属:普通圆桌忽略,但保存时必须原样保留。
|
||||
@@ -1272,6 +1279,7 @@ export default function BusinessChainEditorPage() {
|
||||
onSplitSeat={splitSeat}
|
||||
onSeatModelChange={setSeatModelCb}
|
||||
onSeatSkillDirectiveChange={setSeatSkillDirectiveCb}
|
||||
onSeatHumanValidationChange={setSeatHumanValidationCb}
|
||||
onSeatModeChange={setSeatModeCb}
|
||||
positionConfigMode={positionConfigMode}
|
||||
positionOptions={positionOptions}
|
||||
@@ -1455,6 +1463,7 @@ function StagesColumn({
|
||||
onSplitSeat,
|
||||
onSeatModelChange,
|
||||
onSeatSkillDirectiveChange,
|
||||
onSeatHumanValidationChange,
|
||||
onSeatModeChange,
|
||||
positionConfigMode,
|
||||
positionOptions,
|
||||
@@ -1476,6 +1485,7 @@ function StagesColumn({
|
||||
onSplitSeat: (agentId: string) => void;
|
||||
onSeatModelChange: (agentId: string, model: string | null) => void;
|
||||
onSeatSkillDirectiveChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatHumanValidationChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatModeChange: (agentId: string, mode: SeatMode | null) => void;
|
||||
/** 仅岗位协同入口启用;普通圆桌编辑器不显示岗位控件。 */
|
||||
positionConfigMode: boolean;
|
||||
@@ -1586,6 +1596,7 @@ function StagesColumn({
|
||||
onSplitSeat={onSplitSeat}
|
||||
onSeatModelChange={onSeatModelChange}
|
||||
onSeatSkillDirectiveChange={onSeatSkillDirectiveChange}
|
||||
onSeatHumanValidationChange={onSeatHumanValidationChange}
|
||||
onSeatModeChange={onSeatModeChange}
|
||||
positionConfigMode={positionConfigMode}
|
||||
positionOptions={positionOptions}
|
||||
@@ -1620,6 +1631,7 @@ function StageSection({
|
||||
onSplitSeat,
|
||||
onSeatModelChange,
|
||||
onSeatSkillDirectiveChange,
|
||||
onSeatHumanValidationChange,
|
||||
onSeatModeChange,
|
||||
positionConfigMode,
|
||||
positionOptions,
|
||||
@@ -1643,6 +1655,7 @@ function StageSection({
|
||||
onSplitSeat: (agentId: string) => void;
|
||||
onSeatModelChange: (agentId: string, model: string | null) => void;
|
||||
onSeatSkillDirectiveChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatHumanValidationChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatModeChange: (agentId: string, mode: SeatMode | null) => void;
|
||||
positionConfigMode: boolean;
|
||||
positionOptions: readonly PositionOption[];
|
||||
@@ -1809,6 +1822,7 @@ function StageSection({
|
||||
onSplit={() => onSplitSeat(seat.agent_id)}
|
||||
onModelChange={(model) => onSeatModelChange(seat.agent_id, model)}
|
||||
onSkillDirectiveChange={(enabled) => onSeatSkillDirectiveChange(seat.agent_id, enabled)}
|
||||
onHumanValidationChange={(enabled) => onSeatHumanValidationChange(seat.agent_id, enabled)}
|
||||
onSeatModeChange={(mode) => onSeatModeChange(seat.agent_id, mode)}
|
||||
showPositionConfig={positionConfigMode}
|
||||
positionOptions={positionOptions}
|
||||
@@ -1837,6 +1851,7 @@ function SeatStrip({
|
||||
onSplit,
|
||||
onModelChange,
|
||||
onSkillDirectiveChange,
|
||||
onHumanValidationChange,
|
||||
onSeatModeChange,
|
||||
showPositionConfig,
|
||||
positionOptions,
|
||||
@@ -1857,6 +1872,7 @@ function SeatStrip({
|
||||
onModelChange: (model: string | null) => void;
|
||||
/** 席位「会商技能识别强化」开关变更。 */
|
||||
onSkillDirectiveChange: (enabled: boolean) => void;
|
||||
onHumanValidationChange: (enabled: boolean) => void;
|
||||
/** 席位「推理深度覆盖」变更(null = 跟随链条级 seatMode)。 */
|
||||
onSeatModeChange: (mode: SeatMode | null) => void;
|
||||
/** 仅岗位协同入口展示的岗位配置。 */
|
||||
@@ -2058,6 +2074,38 @@ function SeatStrip({
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
title="人工校验:该席位完成后暂停会商,等待用户恢复或输入修改意见"
|
||||
className={cn(
|
||||
"p-1 transition",
|
||||
R_CTRL,
|
||||
seat.human_validation
|
||||
? "bg-primary/10 text-primary"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<UserCheck className="size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64 p-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-xs font-semibold text-foreground">人工校验</p>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
开启后,该席位所在的执行单元完成时会自动暂停。用户可直接点击“恢复会商”继续,或在下方输入修改意见后提交;不会新增校验卡片。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={seat.human_validation ?? false}
|
||||
onCheckedChange={onHumanValidationChange}
|
||||
aria-label={`切换 ${seat.name || seat.agent_id} 的人工校验`}
|
||||
/>
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDetail}
|
||||
|
||||
@@ -409,6 +409,10 @@ export default function RoundtablePlanningPage({
|
||||
// Step 2 每席位「技能识别强化」开关映射 {agentId: bool}:由所选业务链条里**每个席位**的同名
|
||||
// 配置决定(recommend 无链条 → 空 {})。透传给每个席位 run,与各席位智能体自身的开关取 OR。
|
||||
const [seatSkillDirectives, setSeatSkillDirectives] = useState<Record<string, boolean>>({});
|
||||
// Per-seat human-validation checkpoints from the selected business chain.
|
||||
// A checkpoint pauses Step 2 after the configured seat/stage completes and
|
||||
// reuses the existing resume button plus bottom intervention composer.
|
||||
const [humanValidations, setHumanValidations] = useState<Record<string, boolean>>({});
|
||||
// Step 2 每席位「推理深度覆盖」映射 {agentId: SeatMode|null}:由所选业务链条里**每个席位**单独配
|
||||
// 的推理深度决定(null/未配 → 跟随链条级 seatMode)。透传给席位 run(覆盖优先、否则跟随 seatMode)。
|
||||
// 「卡顿提速」用:把次要席位降到 flash 即可大幅缩短第二步耗时。
|
||||
@@ -573,6 +577,7 @@ export default function RoundtablePlanningPage({
|
||||
selectedModel,
|
||||
selectedMode: seatMode,
|
||||
seatSkillDirectives,
|
||||
humanValidations,
|
||||
seatModes,
|
||||
gatherFirst,
|
||||
orchestrationMode,
|
||||
@@ -1058,6 +1063,9 @@ export default function RoundtablePlanningPage({
|
||||
setSeatSkillDirectives(
|
||||
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.seat_skill_directive ?? false])),
|
||||
);
|
||||
setHumanValidations(
|
||||
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.human_validation ?? false])),
|
||||
);
|
||||
// 每席位推理深度覆盖:取所选业务链条里**每席位**单独配的 seatMode → {agentId: SeatMode|null}
|
||||
// 映射(recommend / 未配 → null,跟随链条级 seatMode)。
|
||||
setSeatModes(
|
||||
|
||||
@@ -746,7 +746,7 @@
|
||||
|
||||
/* 岗位会商左侧总面板:仅收窄滚动条宽度,沿用全局既有的滑块颜色、圆角和轨道样式。 */
|
||||
.position-roundtable-sidebar-scrollbar::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
width: 5px;
|
||||
}
|
||||
|
||||
.workspace-shell {
|
||||
|
||||