diff --git a/backend/internal/application/egress/probe_match.go b/backend/internal/application/egress/probe_match.go new file mode 100644 index 00000000..89ac2874 --- /dev/null +++ b/backend/internal/application/egress/probe_match.go @@ -0,0 +1,62 @@ +package egress + +import ( + "regexp" + "strings" + "unicode" +) + +const ( + MatchContains = "contains" + MatchLastLine = "last_line" + MatchRegex = "regex" +) + +func NormalizeMatchMode(mode string) string { + switch strings.ToLower(strings.TrimSpace(mode)) { + case MatchLastLine, "last-line", "lastline": + return MatchLastLine + case MatchRegex, "regexp": + return MatchRegex + default: + return MatchContains + } +} + +func lastNonEmptyLine(text string) string { + lines := strings.Split(text, "\n") + for i := len(lines) - 1; i >= 0; i-- { + line := strings.TrimSpace(lines[i]) + if line != "" { + return line + } + } + return "" +} + +// MatchExpected reports whether the probe body satisfies the expected marker. +// An empty expected string always matches so throughput-only profiles can skip +// content checks. +func MatchExpected(text, expected, mode string) bool { + expected = strings.TrimSpace(expected) + if expected == "" { + return true + } + text = strings.TrimRightFunc(text, unicode.IsSpace) + switch NormalizeMatchMode(mode) { + case MatchLastLine: + line := lastNonEmptyLine(text) + if line == "" { + return false + } + return strings.EqualFold(line, expected) || strings.Contains(line, expected) + case MatchRegex: + re, err := regexp.Compile(expected) + if err != nil { + return false + } + return re.MatchString(text) + default: + return strings.Contains(text, expected) + } +} diff --git a/backend/internal/application/egress/probe_match_test.go b/backend/internal/application/egress/probe_match_test.go new file mode 100644 index 00000000..d19e30c3 --- /dev/null +++ b/backend/internal/application/egress/probe_match_test.go @@ -0,0 +1,28 @@ +package egress + +import "testing" + +func TestMatchExpectedModes(t *testing.T) { + text := "天空是蓝的,因为瑞利散射。\nQUALITY_OK\n" + if !MatchExpected(text, "QUALITY_OK", MatchLastLine) { + t.Fatal("last line QUALITY_OK should match") + } + if MatchExpected("hello\nNOT_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("wrong last line must not match") + } + if !MatchExpected("prefix QUALITY_OK suffix", "QUALITY_OK", MatchContains) { + t.Fatal("contains should match") + } + if !MatchExpected("done\nstatus=QUALITY_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("last line containing the marker should match") + } + if !MatchExpected("alpha\nbeta QUALITY_OK", `QUALITY_OK$`, MatchRegex) { + t.Fatal("regex should match") + } + if MatchExpected("nope", "[", MatchRegex) { + t.Fatal("invalid regex must not match") + } + if !MatchExpected("anything", "", MatchContains) { + t.Fatal("empty expected is always a match") + } +} diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 7bdefb59..4a45045f 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -41,6 +41,7 @@ type QualityProbeInput struct { Model string Prompt string Expected string + MatchMode string MaxOutputTokens int } @@ -128,13 +129,15 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality input.Model = strings.TrimSpace(input.Model) input.Prompt = strings.TrimSpace(input.Prompt) input.Expected = strings.TrimSpace(input.Expected) + rawMatchMode := strings.TrimSpace(input.MatchMode) + input.MatchMode = NormalizeMatchMode(input.MatchMode) if input.Model == "" { return QualityProbeResult{}, fmt.Errorf("%w: model 必填", ErrInvalidInput) } if input.Prompt == "" { input.Prompt = DefaultQualityProbePrompt } - if input.Expected == "" { + if input.Expected == "" && rawMatchMode == "" { input.Expected = DefaultQualityProbeExpected } if len(input.Prompt) > MaxQualityProbePromptBytes || len(input.Expected) > MaxQualityProbeExpectedBytes { diff --git a/backend/internal/application/gateway/quality_probe.go b/backend/internal/application/gateway/quality_probe.go index 689685a7..7fb3ef93 100644 --- a/backend/internal/application/gateway/quality_probe.go +++ b/backend/internal/application/gateway/quality_probe.go @@ -184,7 +184,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e FirstTokenMS: firstTokenMS, DurationMS: durationMS, GenerationMS: generationMS, ChunkCount: chunkCount, OutputTokens: usage.OutputTokens, ReasoningTokens: usage.ReasoningTokens, VisibleTokens: visibleTokens, VisibleCharacters: visibleCharacters, OutputTokensPerSecond: outputTokensPerSecond, - ExpectedMatched: strings.Contains(text, input.Expected), ResponseSHA256: hex.EncodeToString(digest[:]), + ExpectedMatched: egressapp.MatchExpected(text, input.Expected, input.MatchMode), ResponseSHA256: hex.EncodeToString(digest[:]), }, nil } diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index 52f73f07..45c62fd6 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -59,6 +59,10 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/egress-nodes/:id/quality-test", h.testQuality) router.GET("/egress-quality-guard", h.qualityGuardStatus) router.PUT("/egress-quality-guard/config", h.updateQualityGuardConfig) + router.GET("/egress-quality-guard/profiles", h.listQualityGuardProfiles) + router.POST("/egress-quality-guard/profiles", h.createQualityGuardProfile) + router.PUT("/egress-quality-guard/profiles/:id", h.updateQualityGuardProfile) + router.DELETE("/egress-quality-guard/profiles/:id", h.deleteQualityGuardProfile) router.POST("/egress-quality-guard/nodes/:id/test", h.testQualityGuardNode) router.POST("/egress-nodes/:id/accounts", h.assignAccounts) router.DELETE("/egress-nodes/accounts", h.unassignAccounts) @@ -203,6 +207,10 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) { if state.Statistics.StartedAt > 0 { payload["statistics"] = state.Statistics } + if profiles, err := loadProbeProfileFile(h.profilesPath()); err == nil { + payload["activeProfileId"] = profiles.ActiveProfileID + payload["profiles"] = profiles.summaries() + } response.Success(c, http.StatusOK, payload) } @@ -361,11 +369,24 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { if !ok { return } - if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" || h.guardProbe.Prompt == "" || h.guardProbe.Expected == "" { + if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" { response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") return } - value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, h.guardProbe) + var request struct { + ProfileID string `json:"profileId"` + } + _ = c.ShouldBindJSON(&request) + input, err := h.resolveProbeInput(strings.TrimSpace(request.ProfileID)) + if err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + if strings.TrimSpace(input.Prompt) == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") + return + } + value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, input) if err != nil { h.writeQualityProbeError(c, err) return diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 2b664174..d3d62c5d 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -94,6 +94,37 @@ func TestWriteQualityProbeErrorIdentifiesMissingProbeAccount(t *testing.T) { } } +func TestQualityGuardProfilesCRUDAndStatusOmitsPrompt(t *testing.T) { + directory := t.TempDir() + statePath := directory + "/state.json" + configPath := directory + "/runtime-config.json" + if err := os.WriteFile(statePath, []byte(`{"version":1,"guard":{"mode":"hybrid","model":"grok-4.5","node_ids":["8"]},"nodes":{}}`), 0o600); err != nil { + t.Fatal(err) + } + handler := NewHandler(nil, statePath, configPath) + + createRecorder := httptest.NewRecorder() + createContext, _ := gin.CreateTestContext(createRecorder) + createContext.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(`{"name":"自定义标记","prompt":"只输出 FLAG_OK","expectedText":"FLAG_OK","matchMode":"last_line","active":true}`)) + createContext.Request.Header.Set("Content-Type", "application/json") + handler.createQualityGuardProfile(createContext) + if createRecorder.Code != 200 || !strings.Contains(createRecorder.Body.String(), `"FLAG_OK"`) { + t.Fatalf("create status=%d body=%s", createRecorder.Code, createRecorder.Body.String()) + } + + statusRecorder := httptest.NewRecorder() + statusContext, _ := gin.CreateTestContext(statusRecorder) + statusContext.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil) + handler.qualityGuardStatus(statusContext) + body := statusRecorder.Body.String() + if statusRecorder.Code != 200 || !strings.Contains(body, `"activeProfileId":"p-2"`) || !strings.Contains(body, `"has_expected":true`) { + t.Fatalf("status=%d body=%s", statusRecorder.Code, body) + } + if strings.Contains(body, "只输出 FLAG_OK") || strings.Contains(body, "FLAG_OK") { + t.Fatalf("status leaked probe prompt or marker: %s", body) + } +} + func TestUpdateQualityGuardConfigWritesPrivateAtomicFile(t *testing.T) { directory := t.TempDir() statePath := directory + "/state.json" diff --git a/backend/internal/transport/http/egress/profiles.go b/backend/internal/transport/http/egress/profiles.go new file mode 100644 index 00000000..0f59599c --- /dev/null +++ b/backend/internal/transport/http/egress/profiles.go @@ -0,0 +1,414 @@ +package egress + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + egressapp "github.com/chenyme/grok2api/backend/internal/application/egress" + "github.com/chenyme/grok2api/backend/internal/shared/response" + "github.com/gin-gonic/gin" +) + +const ( + profileThroughput = "throughput" + profileQualityMarker = "quality-marker" + maxCustomProfiles = 32 +) + +type probeProfile struct { + ID string `json:"id"` + Name string `json:"name"` + BuiltIn bool `json:"built_in"` + Prompt string `json:"prompt"` + ExpectedText string `json:"expected_text,omitempty"` + MatchMode string `json:"match_mode"` + MaxOutputTokens int `json:"max_output_tokens,omitempty"` + UpdatedAt float64 `json:"updated_at,omitempty"` +} + +type probeProfileFile struct { + Version int `json:"version"` + ActiveProfileID string `json:"active_profile_id"` + NextID int `json:"next_id"` + Profiles map[string]probeProfile `json:"profiles"` +} + +func builtinProbeProfiles() []probeProfile { + return []probeProfile{ + { + ID: profileQualityMarker, + Name: "预期标记", + BuiltIn: true, + Prompt: "先用三点总结为什么天空呈蓝色,最后一行只输出 QUALITY_OK。", + ExpectedText: "QUALITY_OK", + MatchMode: egressapp.MatchLastLine, + }, + { + ID: profileThroughput, + Name: "吞吐基线", + BuiltIn: true, + Prompt: "Write a detailed technical explanation of how TCP slow start works, at least 12 sentences, plain text only.", + MatchMode: egressapp.MatchContains, + }, + } +} + +func (h *Handler) profilesPath() string { + if h.guardConfigPath == "" { + return "" + } + return filepath.Join(filepath.Dir(h.guardConfigPath), "profiles.json") +} + +func seedProbeProfileFile(data *probeProfileFile) { + if data.Profiles == nil { + data.Profiles = map[string]probeProfile{} + } + if data.Version == 0 { + data.Version = 1 + } + now := float64(time.Now().Unix()) + for _, builtin := range builtinProbeProfiles() { + existing, ok := data.Profiles[builtin.ID] + if !ok { + builtin.UpdatedAt = now + data.Profiles[builtin.ID] = builtin + continue + } + if existing.BuiltIn { + existing.Name = builtin.Name + existing.Prompt = builtin.Prompt + existing.ExpectedText = builtin.ExpectedText + existing.MatchMode = builtin.MatchMode + data.Profiles[builtin.ID] = existing + } + } + if data.ActiveProfileID == "" { + data.ActiveProfileID = profileQualityMarker + } + if _, ok := data.Profiles[data.ActiveProfileID]; !ok { + data.ActiveProfileID = profileQualityMarker + } + if data.NextID < 1 { + data.NextID = 1 + } +} + +func loadProbeProfileFile(path string) (probeProfileFile, error) { + data := probeProfileFile{Version: 1, Profiles: map[string]probeProfile{}} + if path == "" { + seedProbeProfileFile(&data) + return data, nil + } + raw, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + seedProbeProfileFile(&data) + return data, nil + } + return probeProfileFile{}, err + } + if err := json.Unmarshal(raw, &data); err != nil { + return probeProfileFile{}, err + } + seedProbeProfileFile(&data) + return data, nil +} + +func saveProbeProfileFile(path string, data probeProfileFile) error { + if path == "" { + return errors.New("profiles path is empty") + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + raw, err := json.Marshal(data) + if err != nil { + return err + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".profiles-") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err := temporary.Chmod(0o600); err != nil { + _ = temporary.Close() + return err + } + if _, err := temporary.Write(raw); err != nil { + _ = temporary.Close() + return err + } + if err := temporary.Close(); err != nil { + return err + } + return os.Rename(temporaryPath, path) +} + +func (data probeProfileFile) resolve(id string) (probeProfile, bool) { + if id == "" { + id = data.ActiveProfileID + } + profile, ok := data.Profiles[id] + return profile, ok +} + +func (data probeProfileFile) summaries() []map[string]any { + out := make([]map[string]any, 0, len(data.Profiles)) + for _, profile := range data.Profiles { + out = append(out, map[string]any{ + "id": profile.ID, + "name": profile.Name, + "built_in": profile.BuiltIn, + "match_mode": profile.MatchMode, + "has_expected": strings.TrimSpace(profile.ExpectedText) != "", + }) + } + sort.Slice(out, func(i, j int) bool { + leftBuiltIn, _ := out[i]["built_in"].(bool) + rightBuiltIn, _ := out[j]["built_in"].(bool) + if leftBuiltIn != rightBuiltIn { + return leftBuiltIn + } + leftID, _ := out[i]["id"].(string) + rightID, _ := out[j]["id"].(string) + return leftID < rightID + }) + return out +} + +func validateProbeProfile(profile *probeProfile, creating bool) error { + profile.Name = strings.TrimSpace(profile.Name) + profile.Prompt = strings.TrimSpace(profile.Prompt) + profile.ExpectedText = strings.TrimSpace(profile.ExpectedText) + profile.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode) + if profile.Name == "" { + return errors.New("方案名称不能为空") + } + if len(profile.Name) > 80 { + return errors.New("方案名称不能超过 80 个字符") + } + if profile.Prompt == "" { + return errors.New("探测 Prompt 不能为空") + } + if len(profile.Prompt) > egressapp.MaxQualityProbePromptBytes { + return errors.New("探测 Prompt 过长") + } + if len(profile.ExpectedText) > egressapp.MaxQualityProbeExpectedBytes { + return errors.New("预期标记过长") + } + if profile.MatchMode == egressapp.MatchRegex && profile.ExpectedText != "" { + if _, err := regexp.Compile(profile.ExpectedText); err != nil { + return fmt.Errorf("正则预期标记无效") + } + } + if profile.MaxOutputTokens < 0 || profile.MaxOutputTokens > egressapp.MaxQualityProbeOutputTokens { + return fmt.Errorf("方案最大输出需在 0 到 %d Token 之间", egressapp.MaxQualityProbeOutputTokens) + } + if creating && profile.BuiltIn { + return errors.New("不能新建内置方案") + } + return nil +} + +func applyProfile(base egressapp.QualityProbeInput, profile probeProfile) egressapp.QualityProbeInput { + base.Prompt = profile.Prompt + base.Expected = profile.ExpectedText + base.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode) + if profile.MaxOutputTokens > 0 { + base.MaxOutputTokens = profile.MaxOutputTokens + } + return base +} + +func (h *Handler) listQualityGuardProfiles(c *gin.Context) { + data, err := loadProbeProfileFile(h.profilesPath()) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + items := make([]probeProfile, 0, len(data.Profiles)) + for _, profile := range data.Profiles { + items = append(items, profile) + } + sort.Slice(items, func(i, j int) bool { + if items[i].BuiltIn != items[j].BuiltIn { + return items[i].BuiltIn + } + return items[i].ID < items[j].ID + }) + response.Success(c, http.StatusOK, gin.H{ + "activeProfileId": data.ActiveProfileID, + "items": items, + }) +} + +type probeProfileWriteRequest struct { + Name string `json:"name"` + Prompt string `json:"prompt"` + ExpectedText string `json:"expectedText"` + MatchMode string `json:"matchMode"` + MaxOutputTokens int `json:"maxOutputTokens"` + Active bool `json:"active"` +} + +func (h *Handler) createQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + var request probeProfileWriteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + custom := 0 + for _, profile := range data.Profiles { + if !profile.BuiltIn { + custom++ + } + } + if custom >= maxCustomProfiles { + response.Error(c, http.StatusBadRequest, "invalidRequest", fmt.Sprintf("自定义方案最多 %d 个", maxCustomProfiles)) + return + } + profile := probeProfile{ + Name: request.Name, Prompt: request.Prompt, ExpectedText: request.ExpectedText, + MatchMode: request.MatchMode, MaxOutputTokens: request.MaxOutputTokens, + } + if err := validateProbeProfile(&profile, true); err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + data.NextID++ + profile.ID = fmt.Sprintf("p-%d", data.NextID) + profile.UpdatedAt = float64(time.Now().Unix()) + data.Profiles[profile.ID] = profile + if request.Active { + data.ActiveProfileID = profile.ID + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, profile) +} + +func (h *Handler) updateQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + id := strings.TrimSpace(c.Param("id")) + var request probeProfileWriteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + existing, ok := data.Profiles[id] + if !ok { + response.Error(c, http.StatusNotFound, "notFound", "方案不存在") + return + } + if existing.BuiltIn { + if request.Active { + data.ActiveProfileID = existing.ID + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, existing) + return + } + response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能修改,请复制后另存") + return + } + existing.Name = request.Name + existing.Prompt = request.Prompt + existing.ExpectedText = request.ExpectedText + existing.MatchMode = request.MatchMode + existing.MaxOutputTokens = request.MaxOutputTokens + if err := validateProbeProfile(&existing, false); err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + existing.UpdatedAt = float64(time.Now().Unix()) + data.Profiles[id] = existing + if request.Active { + data.ActiveProfileID = id + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, existing) +} + +func (h *Handler) deleteQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + id := strings.TrimSpace(c.Param("id")) + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + existing, ok := data.Profiles[id] + if !ok { + response.Error(c, http.StatusNotFound, "notFound", "方案不存在") + return + } + if existing.BuiltIn { + response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能删除") + return + } + delete(data.Profiles, id) + if data.ActiveProfileID == id { + data.ActiveProfileID = profileQualityMarker + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, gin.H{"deleted": true}) +} + +func (h *Handler) resolveProbeInput(profileID string) (egressapp.QualityProbeInput, error) { + input := h.guardProbe + data, err := loadProbeProfileFile(h.profilesPath()) + if err != nil { + return input, err + } + profile, ok := data.resolve(profileID) + if !ok { + if profileID != "" { + return input, fmt.Errorf("方案不存在") + } + return input, nil + } + return applyProfile(input, profile), nil +} diff --git a/frontend/src/features/quality-guard/probe-profiles-panel.tsx b/frontend/src/features/quality-guard/probe-profiles-panel.tsx new file mode 100644 index 00000000..d013b78e --- /dev/null +++ b/frontend/src/features/quality-guard/probe-profiles-panel.tsx @@ -0,0 +1,186 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Pencil, Plus, Star, Trash2 } from "lucide-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; + +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Spinner } from "@/components/ui/spinner"; +import { Textarea } from "@/components/ui/textarea"; +import { createProbeProfile, deleteProbeProfile, listProbeProfiles, updateProbeProfile, type ProbeProfile } from "@/features/quality-guard/quality-guard-api"; + +type Draft = { + name: string; + prompt: string; + expectedText: string; + matchMode: string; +}; + +const emptyDraft = (): Draft => ({ name: "", prompt: "", expectedText: "", matchMode: "last_line" }); + +export function ProbeProfilesPanel() { + const { t } = useTranslation(); + const queryClient = useQueryClient(); + const [editing, setEditing] = useState(undefined); + const [draft, setDraft] = useState(emptyDraft()); + const [deleting, setDeleting] = useState(null); + const query = useQuery({ queryKey: ["quality-guard-profiles"], queryFn: listProbeProfiles }); + const invalidate = () => { + void queryClient.invalidateQueries({ queryKey: ["quality-guard-profiles"] }); + void queryClient.invalidateQueries({ queryKey: ["quality-guard"] }); + }; + const saveMutation = useMutation({ + mutationFn: async () => { + const payload = { + name: draft.name.trim(), + prompt: draft.prompt.trim(), + expectedText: draft.expectedText.trim(), + matchMode: draft.matchMode, + }; + if (editing && !editing.built_in) { + return updateProbeProfile(editing.id, payload); + } + return createProbeProfile(payload); + }, + onSuccess: () => { + toast.success(t("qualityGuard.profileSaved")); + setEditing(undefined); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + const activateMutation = useMutation({ + mutationFn: (profile: ProbeProfile) => updateProbeProfile(profile.id, { + name: profile.name, + prompt: profile.prompt, + expectedText: profile.expected_text ?? "", + matchMode: profile.match_mode, + active: true, + }), + onSuccess: () => { + toast.success(t("qualityGuard.profileSaved")); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + const deleteMutation = useMutation({ + mutationFn: (profile: ProbeProfile) => deleteProbeProfile(profile.id), + onSuccess: () => { + toast.success(t("qualityGuard.profileDeleted")); + setDeleting(null); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + + const items = query.data?.items ?? []; + const activeId = query.data?.activeProfileId; + const readonly = Boolean(editing?.built_in); + const matchLabel = (mode: string) => { + if (mode === "last_line") return t("qualityGuard.profileMatchLastLine"); + if (mode === "regex") return t("qualityGuard.profileMatchRegex"); + return t("qualityGuard.profileMatchContains"); + }; + + return ( +
+
+
+

{t("qualityGuard.profilesTab")}

+

{t("qualityGuard.profilesHelp")}

+
+ +
+
+ {items.map((profile) => { + const active = profile.id === activeId; + const marker = profile.expected_text + ? `${t("qualityGuard.profileExpected")} ${profile.expected_text} · ${matchLabel(profile.match_mode)}` + : t("qualityGuard.profileNoExpected"); + return ( +
+
+
+ {profile.name} + {t(profile.built_in ? "qualityGuard.profileBuiltin" : "qualityGuard.profileCustom")} + {active ? {t("qualityGuard.profileActive")} : null} +
+

{marker}

+
+
+ {!active ? : null} + + {!profile.built_in ? : null} +
+
+ ); + })} +
+ + { if (!open && !saveMutation.isPending) setEditing(undefined); }}> + + + {editing ? t(readonly ? "qualityGuard.profileView" : "qualityGuard.profileEdit") : t("qualityGuard.profileCreate")} + {t("qualityGuard.profilesHelp")} + +
{ event.preventDefault(); if (!readonly) saveMutation.mutate(); }}> +
+ + setDraft({ ...draft, name: event.target.value })} /> +
+
+ + +
+
+ + setDraft({ ...draft, expectedText: event.target.value })} /> +

{t("qualityGuard.profileExpectedHelp")}

+
+
+ +