feat(ECR-021): AICoreConfig SystemPrompt 只读并 Closed

新增 system_prompts 目录、admin.ai_config.read 与 admin-h5「AI」页;本切片不改运行时 Prompt、禁写发布/UGC/真支付。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-08 00:27:17 +08:00
co-authored by Cursor
parent 22f9e358ae
commit 140b08ca01
33 changed files with 649 additions and 5 deletions
+26
View File
@@ -295,6 +295,32 @@ export const adminApi = {
rating: number
source: string
}>('POST', `/ask/threads/${threadId}/feedback`, body),
systemPrompts: () =>
request<{
items: Array<{
id: string
code: string
title: string
scene?: string
body: string
version: number
active: boolean
system: boolean
updated_at: string
}>
}>('GET', '/ai/system-prompts'),
systemPrompt: (id: string) =>
request<{
id: string
code: string
title: string
scene?: string
body: string
version: number
active: boolean
system: boolean
updated_at: string
}>('GET', `/ai/system-prompts/${id}`),
orders: () =>
request<{
items: Array<{
+1
View File
@@ -32,6 +32,7 @@ async function onLogout() {
<RouterLink to="/codes">兑换码</RouterLink>
<RouterLink to="/ask">问答</RouterLink>
<RouterLink to="/safety">安全</RouterLink>
<RouterLink to="/ai">AI</RouterLink>
<RouterLink to="/orders">订单</RouterLink>
<RouterLink to="/audit">审计</RouterLink>
</nav>
+104
View File
@@ -0,0 +1,104 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { adminApi } from '@/api/client'
type Prompt = Awaited<ReturnType<typeof adminApi.systemPrompts>>['items'][number]
const loading = ref(false)
const error = ref('')
const items = ref<Prompt[]>([])
const selected = ref<Prompt | null>(null)
const detailErr = ref('')
async function load() {
loading.value = true
error.value = ''
try {
const res = await adminApi.systemPrompts()
items.value = res.items || []
} catch (e) {
error.value = e instanceof Error ? e.message : '加载失败'
} finally {
loading.value = false
}
}
async function openPrompt(id: string) {
detailErr.value = ''
try {
selected.value = await adminApi.systemPrompt(id)
} catch (e) {
detailErr.value = e instanceof Error ? e.message : '详情失败'
selected.value = null
}
}
function fmtTime(iso?: string) {
if (!iso) return '—'
try {
return new Date(iso).toLocaleString('zh-CN')
} catch {
return iso
}
}
onMounted(load)
</script>
<template>
<section>
<h1>AI 配置</h1>
<p class="muted">SystemPrompt 只读目录 · 本切片不可编辑发布</p>
<p v-if="loading" class="muted">加载中</p>
<p v-else-if="error" class="err">{{ error }}</p>
<div v-else class="layout">
<div class="card">
<h2>系统提示词</h2>
<p v-if="!items.length" class="muted">暂无</p>
<table v-else>
<thead>
<tr><th>代码</th><th>标题</th><th>版本</th><th>状态</th><th></th></tr>
</thead>
<tbody>
<tr v-for="p in items" :key="p.id">
<td><code>{{ p.code }}</code></td>
<td>{{ p.title }}</td>
<td>v{{ p.version }}</td>
<td>{{ p.active ? '启用' : '停用' }}{{ p.system ? ' · 系统' : '' }}</td>
<td><button class="btn" type="button" @click="openPrompt(p.id)">查看</button></td>
</tr>
</tbody>
</table>
</div>
<div class="card">
<h2>正文</h2>
<p v-if="detailErr" class="err">{{ detailErr }}</p>
<template v-else-if="selected">
<p class="meta">{{ selected.title }} · 更新 {{ fmtTime(selected.updated_at) }}</p>
<pre>{{ selected.body }}</pre>
</template>
<p v-else class="muted">选择左侧提示词查看正文</p>
</div>
</div>
</section>
</template>
<style scoped>
h1 { margin: 0 0 0.35rem; font-size: 1.35rem; }
h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
.layout { display: grid; grid-template-columns: 1fr 1.1fr; gap: 1rem; margin-top: 1rem; }
.meta { color: var(--muted); font-size: 0.85rem; margin-bottom: 0.5rem; }
pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-size: 0.85rem;
line-height: 1.45;
border: 1px solid var(--line);
border-radius: 10px;
padding: 0.75rem;
background: rgba(255, 253, 251, 0.8);
}
code { font-size: 0.8rem; }
@media (max-width: 900px) { .layout { grid-template-columns: 1fr; } }
</style>
+1
View File
@@ -19,6 +19,7 @@ const router = createRouter({
{ path: 'codes', name: 'codes', component: () => import('@/pages/RedemptionPage.vue') },
{ path: 'ask', name: 'ask', component: () => import('@/pages/AskPage.vue') },
{ path: 'safety', name: 'safety', component: () => import('@/pages/SafetyPage.vue') },
{ path: 'ai', name: 'ai', component: () => import('@/pages/AIConfigPage.vue') },
{ path: 'audit', name: 'audit', component: () => import('@/pages/AuditPage.vue') },
],
},
+1
View File
@@ -51,6 +51,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
h.registerQualityFeedback(authed)
h.registerEntitlement(authed)
h.registerContentSafety(authed)
h.registerAIConfig(authed)
}
func (h *AdminHandler) Login(c *gin.Context) {
@@ -0,0 +1,46 @@
package handler
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/yuxingu/digital-psychology/apps/api/internal/middleware"
"github.com/yuxingu/digital-psychology/apps/api/internal/service/admin"
"github.com/yuxingu/digital-psychology/apps/api/pkg/response"
)
func (h *AdminHandler) registerAIConfig(authed *gin.RouterGroup) {
g := authed.Group("/ai")
g.GET("/system-prompts", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.ListSystemPrompts)
g.GET("/system-prompts/:id", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.GetSystemPrompt)
}
func (h *AdminHandler) ListSystemPrompts(c *gin.Context) {
items, err := h.Svc.ListSystemPrompts(c.Request.Context())
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50027, "list system prompts failed")
return
}
response.OK(c, gin.H{"items": items})
}
func (h *AdminHandler) GetSystemPrompt(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
return
}
row, err := h.Svc.GetSystemPrompt(c.Request.Context(), id)
if errors.Is(err, admin.ErrSystemPromptNotFound) {
response.Fail(c, http.StatusNotFound, 40404, "system prompt not found")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50028, "get system prompt failed")
return
}
response.OK(c, row)
}
@@ -0,0 +1,105 @@
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func TestAICoreSystemPrompts(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/system-prompts", nil, "")
if code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", code)
}
limitedRoleID := uuid.New()
_, err := pool.Exec(ctx, `
INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`,
limitedRoleID, "ai_lim_"+limitedRoleID.String()[:8])
if err != nil {
t.Fatal(err)
}
_, err = pool.Exec(ctx, `
INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.users.read')`, limitedRoleID)
if err != nil {
t.Fatal(err)
}
hash, err := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost)
if err != nil {
t.Fatal(err)
}
limUser := fmt.Sprintf("ailim_%d", time.Now().UnixNano())
_, err = pool.Exec(ctx, `
INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
limUser, string(hash), limitedRoleID)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limUser)
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
})
limTok := adminLogin(t, r, limUser, "limited-pass")
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/system-prompts", nil, limTok)
if code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", code)
}
start := time.Now()
env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/system-prompts", nil, tok)
if code != 200 || env.Code != 0 {
t.Fatalf("list http=%d msg=%s", code, env.Message)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("list too slow %v", time.Since(start))
}
var list struct {
Items []struct {
ID string `json:"id"`
Code string `json:"code"`
Body string `json:"body"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
var askID string
for _, it := range list.Items {
if it.Code == "ask_default" {
askID = it.ID
if it.Body == "" {
t.Fatal("ask_default body empty in list")
}
break
}
}
if askID == "" {
t.Fatalf("missing ask_default: %#v", list.Items)
}
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/system-prompts/"+askID, nil, tok)
if code != 200 {
t.Fatalf("get %d", code)
}
var detail struct {
Body string `json:"body"`
Code string `json:"code"`
}
_ = json.Unmarshal(env.Data, &detail)
if detail.Code != "ask_default" || detail.Body == "" {
t.Fatalf("bad detail %#v", detail)
}
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/system-prompts/"+fakeUUID(), nil, tok)
if code != http.StatusNotFound {
t.Fatalf("expected 404, got %d", code)
}
}
@@ -0,0 +1,62 @@
package repository
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// SystemPromptRow is AICoreConfig SystemPrompt catalog row.
type SystemPromptRow struct {
ID uuid.UUID `json:"id"`
Code string `json:"code"`
Title string `json:"title"`
Scene *string `json:"scene,omitempty"`
Body string `json:"body"`
Version int `json:"version"`
Active bool `json:"active"`
System bool `json:"system"`
UpdatedAt time.Time `json:"updated_at"`
}
// ListSystemPrompts returns prompt catalog (body included for ops read).
func (r *AdminRepo) ListSystemPrompts(ctx context.Context) ([]SystemPromptRow, error) {
rows, err := r.Pool.Query(ctx, `
SELECT id, code, title, scene, body, version, active, system, updated_at
FROM system_prompts
ORDER BY active DESC, code ASC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []SystemPromptRow
for rows.Next() {
var p SystemPromptRow
if err := rows.Scan(
&p.ID, &p.Code, &p.Title, &p.Scene, &p.Body, &p.Version, &p.Active, &p.System, &p.UpdatedAt,
); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// GetSystemPrompt loads one prompt by id.
func (r *AdminRepo) GetSystemPrompt(ctx context.Context, id uuid.UUID) (*SystemPromptRow, error) {
var p SystemPromptRow
err := r.Pool.QueryRow(ctx, `
SELECT id, code, title, scene, body, version, active, system, updated_at
FROM system_prompts WHERE id=$1`, id,
).Scan(&p.ID, &p.Code, &p.Title, &p.Scene, &p.Body, &p.Version, &p.Active, &p.System, &p.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, err
}
if err != nil {
return nil, err
}
return &p, nil
}
@@ -0,0 +1,34 @@
package admin
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
)
var ErrSystemPromptNotFound = errString("system prompt not found")
// ListSystemPrompts returns SystemPrompt catalog.
func (s *Service) ListSystemPrompts(ctx context.Context) ([]repository.SystemPromptRow, error) {
items, err := s.Repo.ListSystemPrompts(ctx)
if err != nil {
return nil, err
}
if items == nil {
items = []repository.SystemPromptRow{}
}
return items, nil
}
// GetSystemPrompt loads one prompt.
func (s *Service) GetSystemPrompt(ctx context.Context, id uuid.UUID) (*repository.SystemPromptRow, error) {
row, err := s.Repo.GetSystemPrompt(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrSystemPromptNotFound
}
return row, err
}
+2
View File
@@ -27,6 +27,7 @@ const (
PermAskRead = "admin.ask.read"
PermAskFeedbackWrite = "admin.ask.feedback.write"
PermContentSafetyRead = "admin.content_safety.read"
PermAIConfigRead = "admin.ai_config.read"
)
var knownPermissions = map[string]struct{}{
@@ -36,6 +37,7 @@ var knownPermissions = map[string]struct{}{
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
PermAskRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {},
PermAIConfigRead: {},
}
var (
@@ -0,0 +1,4 @@
-- ECR-021 down
DELETE FROM admin_role_permissions WHERE code = 'admin.ai_config.read';
DROP TABLE IF EXISTS system_prompts;
@@ -0,0 +1,42 @@
-- ECR-021 AICoreConfig SystemPrompt (read catalog)
CREATE TABLE IF NOT EXISTS system_prompts (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code varchar(64) NOT NULL UNIQUE,
title varchar(128) NOT NULL,
scene varchar(32) NULL,
body text NOT NULL,
version int NOT NULL DEFAULT 1 CHECK (version > 0),
active boolean NOT NULL DEFAULT true,
system boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_system_prompts_active ON system_prompts(active);
INSERT INTO system_prompts(code, title, scene, body, version, active, system)
VALUES (
'ask_default',
'问答默认系统提示',
NULL,
$prompt$你是 AI
宿
{{display_name}} · {{relation}} · {{birth_date}} · {{scene}} · {{report_ctx}}
$prompt$,
1,
true,
true
)
ON CONFLICT (code) DO NOTHING;
INSERT INTO admin_role_permissions(role_id, code)
SELECT r.id, 'admin.ai_config.read'
FROM admin_roles r
WHERE r.name = 'super_admin'
ON CONFLICT DO NOTHING;