diff --git a/docs/deployment.md b/docs/deployment.md index 693cb9d6..95be92af 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -191,6 +191,8 @@ For an external MySQL deployment, review that migration and check column existen | Required upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) | | Optional backfills and rewrites of existing rows | `016_public_optional_repositories.sql`, `021_assistant_session_sources.sql` | Run them if the installation needs the converted rows | +Platform administrators can open **Platform administration → Deployment diagnostics** (or call `GET /api/platform/diagnostics`) for a read-only deployment check: database connectivity, the generated columns and artifact column capacity described above, the single-artifact size limit, the Agent browser sidecar image, and Docker availability. Each warning lists the command that fixes it; the page never runs migrations itself, matching the manual-script policy above. + ## Updating existing public SOPs Repository binding is optional for all built-in generic SOPs. To update the original catalog instructions on an existing installation, explicitly apply: diff --git a/internal/engine/artifacts.go b/internal/engine/artifacts.go index fc364e69..f4f28781 100644 --- a/internal/engine/artifacts.go +++ b/internal/engine/artifacts.go @@ -18,6 +18,11 @@ import ( const maxArtifactBytes = 1 << 20 +// ArtifactSizeLimit reports the largest artifact body the engine accepts. The +// runner upload limit matches it (maxArtifactUploadBytes), and the platform +// diagnostics page compares it with the run_artifacts.content column capacity. +func ArtifactSizeLimit() int { return maxArtifactBytes } + // artifactSeq keeps IDs unique when parallel branches publish in the same // clock tick. var artifactSeq atomic.Uint64 diff --git a/internal/engine/artifacts_limit_test.go b/internal/engine/artifacts_limit_test.go new file mode 100644 index 00000000..45f262f0 --- /dev/null +++ b/internal/engine/artifacts_limit_test.go @@ -0,0 +1,11 @@ +package engine + +import "testing" + +// The platform diagnostics page compares this limit with the database column +// capacity, so it must stay aligned with the runner upload cap (1 MiB). +func TestArtifactSizeLimit(t *testing.T) { + if got := ArtifactSizeLimit(); got != 1<<20 { + t.Fatalf("ArtifactSizeLimit() = %d, want %d", got, 1<<20) + } +} diff --git a/internal/httpapi/platform_diagnostics.go b/internal/httpapi/platform_diagnostics.go new file mode 100644 index 00000000..fa1da5bb --- /dev/null +++ b/internal/httpapi/platform_diagnostics.go @@ -0,0 +1,295 @@ +package httpapi + +import ( + "context" + "database/sql" + "errors" + "fmt" + "net/http" + "os" + "strings" + "time" + + "agentflow/internal/engine" + "agentflow/internal/runtime" + + "github.com/gin-gonic/gin" +) + +// diagnosticsHandlers serves the read-only platform diagnostics page: +// deployment checks that previously required docker exec + SQL access. +type diagnosticsHandlers struct { + *deps +} + +type platformDiagnosticCheck struct { + ID string `json:"id"` + Category string `json:"category"` + Status string `json:"status"` // ok | warn | error | info + Title string `json:"title"` + Detail string `json:"detail,omitempty"` + Hint string `json:"hint,omitempty"` + Command string `json:"command,omitempty"` +} + +type platformDiagnosticsView struct { + GeneratedAt string `json:"generatedAt"` + Checks []platformDiagnosticCheck `json:"checks"` +} + +const ( + diagnosticStatusOK = "ok" + diagnosticStatusWarn = "warn" + diagnosticStatusError = "error" + diagnosticStatusInfo = "info" +) + +// diagnostics returns the deployment checks. Read-only: nothing is written and +// no migration is executed, matching the repository rule that operators run +// migrations/ by hand. +func (h *diagnosticsHandlers) diagnostics(c *gin.Context) { + if !h.isPlatformAdmin(c.Request) { + c.JSON(http.StatusForbidden, gin.H{"error": "只有平台管理员可以查看运维诊断"}) + return + } + c.Header("Cache-Control", "no-store") + c.JSON(http.StatusOK, platformDiagnosticsView{ + GeneratedAt: time.Now().UTC().Format(time.RFC3339), + Checks: h.collectDiagnostics(c.Request.Context()), + }) +} + +func (h *diagnosticsHandlers) collectDiagnostics(ctx context.Context) []platformDiagnosticCheck { + _, checks := h.databaseChecks(ctx) + checks = append(checks, h.artifactChecks()...) + checks = append(checks, h.browserChecks(ctx)...) + checks = append(checks, h.runtimeChecks(ctx)...) + return checks +} + +func (h *diagnosticsHandlers) databaseChecks(ctx context.Context) (string, []platformDiagnosticCheck) { + if h.repo == nil { + return "", []platformDiagnosticCheck{{ + ID: "database.connection", Category: "database", Status: diagnosticStatusError, + Title: "数据库未配置", Hint: "检查 AGENTFLOW_MYSQL_DSN 配置。", + }} + } + driver := fmt.Sprint(h.repo.StorageInfo()["driver"]) + pingErr := errors.New("database handle unavailable") + if sqlDB, err := h.repo.DB.DB(); err == nil { + pingErr = sqlDB.PingContext(ctx) + } + if pingErr != nil { + return driver, []platformDiagnosticCheck{{ + ID: "database.connection", Category: "database", Status: diagnosticStatusError, + Title: "数据库连接失败", Detail: pingErr.Error(), + Hint: "确认 MySQL 容器状态与 AGENTFLOW_MYSQL_DSN 配置。", + }} + } + detail := driver + if driver == "mysql" { + var version, database string + if row := h.repo.DB.WithContext(ctx).Raw("SELECT VERSION(), DATABASE()").Row(); row != nil { + if scanErr := row.Scan(&version, &database); scanErr == nil { + detail = fmt.Sprintf("%s · MySQL %s · %s", driver, version, database) + } + } + } + checks := []platformDiagnosticCheck{{ + ID: "database.connection", Category: "database", Status: diagnosticStatusOK, + Title: "数据库连接正常", Detail: detail, + }} + if driver != "mysql" { + return driver, append(checks, platformDiagnosticCheck{ + ID: "database.schema", Category: "database", Status: diagnosticStatusInfo, + Title: "跳过 schema 检查", Detail: "当前存储驱动不是 MySQL;对象检查仅适用于 MySQL 部署。", + }) + } + return driver, append(checks, h.schemaChecks(ctx)...) +} + +func (h *diagnosticsHandlers) schemaChecks(ctx context.Context) []platformDiagnosticCheck { + checks := make([]platformDiagnosticCheck, 0, 2) + checks = append(checks, h.observabilitySchemaCheck(ctx)) + checks = append(checks, h.artifactColumnCheck(ctx)) + return checks +} + +// observabilitySchemaCheck verifies the generated columns the installer adds +// through migrations/001_run_obs_generated_columns.sql: without them the run +// telemetry endpoints fail with a raw "Unknown column" error. +func (h *diagnosticsHandlers) observabilitySchemaCheck(ctx context.Context) platformDiagnosticCheck { + const id = "database.observability_columns" + rows, err := h.repo.DB.WithContext(ctx).Raw( + `SELECT table_name, column_name, extra FROM information_schema.columns + WHERE table_schema = DATABASE() + AND ((table_name = 'run_telemetry' AND column_name = 'adapter') + OR (table_name = 'run_logs' AND column_name = 'level'))`).Rows() + if err != nil { + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusWarn, + Title: "无法读取 schema 信息", Detail: err.Error(), + } + } + defer rows.Close() + found := map[string]string{} + for rows.Next() { + var table, column, extra string + if scanErr := rows.Scan(&table, &column, &extra); scanErr == nil { + found[table+"."+column] = strings.ToUpper(extra) + } + } + var missing []string + for _, key := range []string{"run_telemetry.adapter", "run_logs.level"} { + extra, ok := found[key] + switch { + case !ok: + missing = append(missing, key+" 缺失") + case !strings.Contains(extra, "GENERATED"): + missing = append(missing, key+" 存在但不是生成列") + } + } + if len(missing) == 0 { + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusOK, + Title: "观测 schema 已就绪", Detail: "run_telemetry.adapter / run_logs.level 生成列存在。", + } + } + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusWarn, + Title: "观测 schema 未补齐", Detail: strings.Join(missing, ";"), + Hint: "安装器和 ./start.sh pull 会补齐 Compose 数据库;外部 MySQL 按 docs/deployment.md 手动执行迁移。", + Command: "bash scripts/install-schema-extensions.sh", + } +} + +// artifactColumnCheck compares the artifact body column with the engine limit; +// a TEXT column is 64 KiB and rejects larger artifacts with MySQL error 1406. +func (h *diagnosticsHandlers) artifactColumnCheck(ctx context.Context) platformDiagnosticCheck { + const id = "database.artifact_content" + limit := diagnosticBytes(engine.ArtifactSizeLimit()) + dataType, ok, err := h.mysqlColumnType(ctx, "run_artifacts", "content") + if err != nil { + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusWarn, + Title: "无法读取产物列类型", Detail: err.Error(), + } + } + if !ok { + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusWarn, + Title: "缺少产物正文列", Detail: "information_schema 中找不到 run_artifacts.content。", + } + } + switch dataType { + case "tinytext", "text": + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusWarn, + Title: "产物正文列容量不足", Detail: fmt.Sprintf("run_artifacts.content 为 %s(上限 64 KiB),小于引擎单产物上限 %s;更大的产物会让运行终态写库失败,节点停在 running。", strings.ToUpper(dataType), limit), + Hint: "把该列手动扩宽为 MEDIUMTEXT(16 MiB)后重启平台;参见 issue #1092。", + } + case "mediumtext", "longtext": + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusOK, + Title: "产物正文列容量充足", Detail: fmt.Sprintf("run_artifacts.content 为 %s,覆盖引擎单产物上限 %s。", strings.ToUpper(dataType), limit), + } + default: + return platformDiagnosticCheck{ + ID: id, Category: "database", Status: diagnosticStatusInfo, + Title: "产物正文列类型未识别", Detail: fmt.Sprintf("run_artifacts.content 为 %s;引擎单产物上限 %s。", strings.ToUpper(dataType), limit), + } + } +} + +func (h *diagnosticsHandlers) artifactChecks() []platformDiagnosticCheck { + return []platformDiagnosticCheck{{ + ID: "artifacts.size_limit", Category: "artifacts", Status: diagnosticStatusInfo, + Title: "单产物大小上限", Detail: fmt.Sprintf("引擎接受单产物最大 %s;超过数据库列容量时终态写入失败,而不是产生一条产物。", diagnosticBytes(engine.ArtifactSizeLimit())), + Hint: "产物体积较大时优先拆分文件;同时确认 run_artifacts.content 的列容量足够。", + }} +} + +func (h *diagnosticsHandlers) browserChecks(ctx context.Context) []platformDiagnosticCheck { + if !runtime.BrowserEnabled() { + return []platformDiagnosticCheck{{ + ID: "browser.agent_browser", Category: "browser", Status: diagnosticStatusInfo, + Title: "Agent 浏览器已关闭", Detail: "AGENTFLOW_BROWSER=off。", + }} + } + image, exists, err := runtime.BrowserSidecarImage(ctx) + if err != nil { + return []platformDiagnosticCheck{{ + ID: "browser.agent_browser", Category: "browser", Status: diagnosticStatusWarn, + Title: "无法检查 Agent 浏览器镜像", Detail: err.Error(), + }} + } + if exists { + return []platformDiagnosticCheck{{ + ID: "browser.agent_browser", Category: "browser", Status: diagnosticStatusOK, + Title: "Agent 浏览器 sidecar 镜像已就绪", Detail: image, + }} + } + return []platformDiagnosticCheck{{ + ID: "browser.agent_browser", Category: "browser", Status: diagnosticStatusWarn, + Title: "Agent 浏览器 sidecar 镜像尚未构建", Detail: "首次打开浏览器时会在平台容器内构建该镜像(Chromium + Playwright MCP,约 1 GB),需要访问 deb.debian.org 与 npm;构建超过请求超时会导致首次打开失败。", + Hint: "网络较慢时先预构建,网络良好时只需一次。", + Command: "docker compose exec platform /app/bin/agentflow -browser-image", + }} +} + +func (h *diagnosticsHandlers) runtimeChecks(ctx context.Context) []platformDiagnosticCheck { + checks := make([]platformDiagnosticCheck, 0, 2) + if runtime.DockerReady() { + checks = append(checks, platformDiagnosticCheck{ + ID: "runtime.docker", Category: "runtime", Status: diagnosticStatusOK, + Title: "Docker 执行环境可用", Detail: "平台可以创建沙箱与 sidecar 容器。", + }) + } else { + checks = append(checks, platformDiagnosticCheck{ + ID: "runtime.docker", Category: "runtime", Status: diagnosticStatusWarn, + Title: "Docker 不可用", Detail: "平台无法创建沙箱容器;Compose 部署需要挂载 /var/run/docker.sock。", + Hint: "检查 Docker 守护进程与 compose.yaml 的 docker.sock 挂载。", + }) + } + if image := strings.TrimSpace(os.Getenv("AGENTFLOW_ISOLATED_IMAGE")); image != "" { + if runtime.DockerImageExists(ctx, image) { + checks = append(checks, platformDiagnosticCheck{ + ID: "runtime.isolated_image", Category: "runtime", Status: diagnosticStatusOK, + Title: "隔离运行时镜像已就绪", Detail: image, + }) + } else { + checks = append(checks, platformDiagnosticCheck{ + ID: "runtime.isolated_image", Category: "runtime", Status: diagnosticStatusWarn, + Title: "隔离运行时镜像不在本地", Detail: image, + Hint: "首次运行沙箱时可能需要拉取或构建该镜像。", + }) + } + } + return checks +} + +func (h *diagnosticsHandlers) mysqlColumnType(ctx context.Context, table, column string) (string, bool, error) { + var dataType string + row := h.repo.DB.WithContext(ctx).Raw( + `SELECT data_type FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`, + table, column).Row() + if err := row.Scan(&dataType); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + return "", false, err + } + return strings.ToLower(strings.TrimSpace(dataType)), true, nil +} + +func diagnosticBytes(n int) string { + switch { + case n >= 1<<20: + return fmt.Sprintf("%d MiB", n>>20) + case n >= 1<<10: + return fmt.Sprintf("%d KiB", n>>10) + default: + return fmt.Sprintf("%d B", n) + } +} diff --git a/internal/httpapi/platform_diagnostics_test.go b/internal/httpapi/platform_diagnostics_test.go new file mode 100644 index 00000000..9f2af497 --- /dev/null +++ b/internal/httpapi/platform_diagnostics_test.go @@ -0,0 +1,57 @@ +package httpapi + +import ( + "encoding/json" + "net/http" + "testing" + + "agentflow/internal/domain" +) + +// TestPlatformDiagnosticsAPI covers the read-only deployment diagnostics used +// by 平台管理 → 运维诊断: admins get checks, other members are rejected. +func TestPlatformDiagnosticsAPI(t *testing.T) { + t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true") + admin := cvBNewHTTPFixture(t) + if _, err := admin.s.GrantPlatformAdmin(admin.user.LoginName); err != nil { + t.Fatal(err) + } + member := admin + user := domain.User{LoginName: "diagnostics-member"} + if err := admin.s.PutUser(user); err != nil { + t.Fatal(err) + } + member.user, _ = admin.s.UserByLoginName(user.LoginName) + + if resp := cvBRequest(t, member, http.MethodGet, "/api/platform/diagnostics", nil, true); resp.Code != http.StatusForbidden { + t.Fatalf("member: HTTP %d, want 403 (%s)", resp.Code, resp.Body.String()) + } + resp := cvBRequest(t, admin, http.MethodGet, "/api/platform/diagnostics", nil, true) + if resp.Code != http.StatusOK { + t.Fatalf("admin: HTTP %d (%s)", resp.Code, resp.Body.String()) + } + var view platformDiagnosticsView + if err := json.Unmarshal(resp.Body.Bytes(), &view); err != nil { + t.Fatalf("decode: %v", err) + } + if view.GeneratedAt == "" || len(view.Checks) == 0 { + t.Fatalf("empty diagnostics view: %+v", view) + } + seen := map[string]bool{} + for _, check := range view.Checks { + seen[check.ID] = true + if check.Title == "" { + t.Fatalf("check %s has no title", check.ID) + } + switch check.Status { + case diagnosticStatusOK, diagnosticStatusWarn, diagnosticStatusError, diagnosticStatusInfo: + default: + t.Fatalf("check %s has unexpected status %q", check.ID, check.Status) + } + } + for _, want := range []string{"database.connection", "database.schema", "artifacts.size_limit", "browser.agent_browser", "runtime.docker"} { + if !seen[want] { + t.Fatalf("missing check %q in %v", want, seen) + } + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 0760f29b..d90fc8ba 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -94,6 +94,7 @@ type Server struct { botInteractions *botInteractionHandlers botIdentities *botIdentityHandlers know *knowledgeHandlers // knowledge.go / knowledge_proxy.go + diagnostics *diagnosticsHandlers } func New(s *repo.Store, e *engine.Engine, syncSvc *tracker.Service, basicUser, basicPass string) *gin.Engine { @@ -157,6 +158,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv github: newGitHubHandlers(d), users: &usersHandlers{deps: d}, sshHostTrust: &sshHostTrustHandlers{deps: d, hosts: s.SSHHostTrustRepo, runnerControls: runnerControls}, + diagnostics: &diagnosticsHandlers{deps: d}, catalog: &catalogHandlers{deps: d}, businessDomains: &businessDomainsHandlers{deps: d}, insights: &insightsHandlers{deps: d}, @@ -275,6 +277,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.POST("/api/platform/git-ssh-hosts/preview", api.sshHostTrust.preview) g.PUT("/api/platform/git-ssh-hosts/:host", api.sshHostTrust.save) g.DELETE("/api/platform/git-ssh-hosts/:host", api.sshHostTrust.remove) + g.GET("/api/platform/diagnostics", api.diagnostics.diagnostics) // master(net/http) 的 /api/users/ 子树只接受 PUT /api/users//credentials // 一种形态,其余任何方法/子路径都走 method(w) → 405 JSON。 g.Any("/api/users/:id/credentials", func(c *gin.Context) { diff --git a/internal/runtime/browser.go b/internal/runtime/browser.go index 7ef587bc..5e959d84 100644 --- a/internal/runtime/browser.go +++ b/internal/runtime/browser.go @@ -176,6 +176,18 @@ func browserImageName() (string, error) { return "agentflow-browser-" + hex.EncodeToString(h.Sum(nil))[:16], nil } +// BrowserSidecarImage reports the Agent browser sidecar image reference and +// whether it already exists in the local Docker image store. The platform +// diagnostics page uses it to tell operators whether the first browser use +// would start with a build. +func BrowserSidecarImage(ctx context.Context) (string, bool, error) { + image, err := browserImageName() + if err != nil { + return "", false, err + } + return image, dockerImageExists(ctx, image), nil +} + // EnsureBrowserImage builds the sidecar image once per content hash. It is // exported for ensure-chromium style pre-warming. func EnsureBrowserImage(ctx context.Context) (string, error) { diff --git a/internal/runtime/browser_sidecar_status_test.go b/internal/runtime/browser_sidecar_status_test.go new file mode 100644 index 00000000..380afd63 --- /dev/null +++ b/internal/runtime/browser_sidecar_status_test.go @@ -0,0 +1,32 @@ +package runtime + +import ( + "context" + "strings" + "testing" +) + +func TestBrowserSidecarImageReportsReference(t *testing.T) { + t.Setenv("AGENTFLOW_BROWSER_IMAGE", "") + image, exists, err := BrowserSidecarImage(context.Background()) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(image, "agentflow-browser-") || len(image) != len("agentflow-browser-")+16 { + t.Fatalf("image = %q, want agentflow-browser-<16 hex>", image) + } + if exists && !DockerImageExists(context.Background(), image) { + t.Fatalf("exists=true but DockerImageExists(%q) = false", image) + } + t.Setenv("AGENTFLOW_BROWSER_IMAGE", "ghcr.io/example/agentflow-browser:prebuilt") + image, _, err = BrowserSidecarImage(context.Background()) + if err != nil || image != "ghcr.io/example/agentflow-browser:prebuilt" { + t.Fatalf("pinned image = %q, err = %v", image, err) + } +} + +func TestDockerImageExistsRejectsEmptyReference(t *testing.T) { + if DockerImageExists(context.Background(), " ") { + t.Fatal("an empty image reference must not exist") + } +} diff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.go index 9abaf864..38801a9e 100644 --- a/internal/runtime/sandbox_docker.go +++ b/internal/runtime/sandbox_docker.go @@ -618,6 +618,12 @@ func dockerImageExists(ctx context.Context, image string) bool { return exec.CommandContext(ctx, "docker", "image", "inspect", image).Run() == nil } +// DockerImageExists reports whether a Docker image reference already exists in +// the local image store. Platform diagnostics use it for runtime images. +func DockerImageExists(ctx context.Context, image string) bool { + return dockerImageExists(ctx, image) +} + // DockerImageCached reports whether this Dockerfile already has a local cache // tag. Used by the engine to tell first-run users that a long image build is // about to start, instead of looking like the node never began. diff --git a/web/app/platform-diagnostics.js b/web/app/platform-diagnostics.js new file mode 100644 index 00000000..087ffbb4 --- /dev/null +++ b/web/app/platform-diagnostics.js @@ -0,0 +1,129 @@ +const platformDiagnosticsEndpoint='/api/platform/diagnostics'; +const platformDiagnosticCategoryOrder=['database','artifacts','browser','runtime']; +const platformDiagnosticCategoryLabels={ + database:['数据库','Database'], + artifacts:['产物','Artifacts'], + browser:['Agent 浏览器','Agent browser'], + runtime:['执行环境','Runtime'], +}; +const platformDiagnosticStatusLabels={ + ok:['正常','OK'], + warn:['需要处理','Action needed'], + error:['错误','Error'], + info:['说明','Info'], +}; + +function platformDiagnosticStatusClass(status){ + if(status==='ok')return 'is-ok'; + if(status==='warn')return 'is-warn'; + if(status==='error')return 'is-error'; + return 'is-info'; +} + +function platformDiagnosticCounts(checks){ + const counts={ok:0,warn:0,error:0,info:0}; + for(const check of checks||[]){ + if(Object.prototype.hasOwnProperty.call(counts,check.status))counts[check.status]++; + else counts.info++; + } + return counts; +} + +function platformDiagnosticCheckHTML(check){ + const status=platformDiagnosticStatusClass(check.status); + const label=platformDiagnosticStatusLabels[check.status]||platformDiagnosticStatusLabels.info; + const detail=check.detail?`

${escapeHTML(check.detail)}

`:''; + const hint=check.hint?`

${escapeHTML(check.hint)}

`:''; + const command=check.command?`
${escapeHTML(check.command)}
`:''; + return `
+
+ ${lfT(label[0],label[1])} +

${escapeHTML(check.title||check.id||'')}

+
+ ${detail}${hint}${command} +
`; +} + +function platformDiagnosticGroupHTML(category,checks){ + const label=platformDiagnosticCategoryLabels[category]||[category,category]; + return `
+

${lfT(label[0],label[1])}

+ ${checks.map(platformDiagnosticCheckHTML).join('')} +
`; +} + +function platformDiagnosticsHTML(){ + return `
+
+
+

${lfT('运维诊断','Deployment diagnostics')}

+

${lfT('检查数据库对象、产物上限与 Agent 浏览器镜像。只做检查并给出处理建议,不会自动执行迁移。','Checks the database objects, artifact limits and the Agent browser image. Checks are read-only and never apply migrations.')}

+
+ +
+
+
+
`; +} + +function platformDiagnosticsRender(view){ + const checks=Array.isArray(view?.checks)?view.checks:[]; + const counts=platformDiagnosticCounts(checks); + const summary=counts.error?lfT(`发现 ${counts.error} 项错误,${counts.warn} 项需要处理`,`${counts.error} error(s), ${counts.warn} item(s) need attention`) + :counts.warn?lfT(`${counts.warn} 项需要处理,其它正常`,`${counts.warn} item(s) need attention, the rest are OK`) + :lfT('全部检查通过','All checks passed'); + const summaryHTML=`${escapeHTML(summary)}${escapeHTML(view?.generatedAt||'')}`; + const groups=[]; + for(const category of platformDiagnosticCategoryOrder){ + const items=checks.filter(check=>check.category===category); + if(items.length)groups.push(platformDiagnosticGroupHTML(category,items)); + } + const rest=checks.filter(check=>!platformDiagnosticCategoryOrder.includes(check.category)); + if(rest.length)groups.push(platformDiagnosticGroupHTML('runtime',rest)); + return {summaryHTML, bodyHTML:groups.join('')}; +} + +async function loadPlatformDiagnostics(host){ + const card=host.querySelector('#platformDiagnosticsCard'); + if(!card)return; + const list=card.querySelector('[data-diagnostics-list]'); + const summary=card.querySelector('[data-diagnostics-summary]'); + const refresh=card.querySelector('[data-diagnostics-refresh]'); + let busy=false; + const bindCopy=()=>{ + list.querySelectorAll('[data-diagnostic-copy]').forEach(button=>{ + button.onclick=async()=>{ + const item=button.closest('[data-diagnostic-item]'); + const command=item?.dataset.diagnosticCommand||''; + try{ + await navigator.clipboard.writeText(command); + button.textContent=lfT('已复制','Copied'); + }catch{ + button.textContent=lfT('复制失败','Copy failed'); + } + setTimeout(()=>{button.textContent=lfT('复制命令','Copy')},1500); + }; + }); + }; + const load=async()=>{ + if(busy)return; + busy=true; + refresh.disabled=true; + summary.innerHTML=''; + list.innerHTML=`
${lfT('检查中…','Running checks…')}
`; + try{ + const view=await api(platformDiagnosticsEndpoint,{silent:true}); + const rendered=platformDiagnosticsRender(view); + summary.innerHTML=rendered.summaryHTML; + list.innerHTML=rendered.bodyHTML||`
${lfT('没有检查项','No checks')}
`; + bindCopy(); + }catch(err){ + list.innerHTML=`
${escapeHTML(err?.message||lfT('检查失败','Checks failed'))}
`; + }finally{ + busy=false; + refresh.disabled=false; + } + }; + refresh.onclick=load; + await load(); +} diff --git a/web/app/workbench.js b/web/app/workbench.js index 93e456df..050bd943 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -1622,6 +1622,7 @@ const PLATFORM_TABS=[ {id:'admins',zh:'平台管理员',en:'Admins'}, {id:'sharedKey',zh:'共享 CodeBuddy Key',en:'Shared CodeBuddy Key'}, {id:'sshTrust',zh:'Git SSH 主机信任',en:'Git SSH Host Trust'}, + {id:'diagnostics',zh:'运维诊断',en:'Deployment diagnostics'}, ]; function platformTabsHTML(active){ return `
${PLATFORM_TABS.map(t=>{ @@ -1791,12 +1792,14 @@ function renderPlatformAdminPanel(){ `)} ${platformTabPanel('sharedKey',tab,platformSharedKeyHTML())} ${platformTabPanel('sshTrust',tab,platformSSHHostTrustHTML())} + ${platformTabPanel('diagnostics',tab,platformDiagnosticsHTML())} `; bindPlatformTabs(host); loadPlatformAccounts(host); loadPlatformSharedKey(host); loadPlatformSSHHosts(host); loadPlatformAdmins(host); + loadPlatformDiagnostics(host); } // 平台管理 → 成员账号 / 平台共享 CodeBuddy Key. diff --git a/web/index.html b/web/index.html index c5eca185..b977dce4 100644 --- a/web/index.html +++ b/web/index.html @@ -1304,7 +1304,8 @@

确认操作

- + + diff --git a/web/platform.css b/web/platform.css index 03838854..aa1236f9 100644 --- a/web/platform.css +++ b/web/platform.css @@ -2823,3 +2823,30 @@ textarea.pw-input{height:auto;min-height:64px;padding:9px 12px;line-height:1.55; .pw-footer{padding:12px 16px} .pw-row2,.pw-actions,.pw-status-list{grid-template-columns:1fr} } + +/* 平台管理 → 运维诊断 */ +.platform-diagnostic-summary{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:13px;color:var(--muted)} +.platform-diagnostic-summary-text{font-weight:600;color:var(--text)} +.platform-diagnostic-summary-meta{font-family:var(--mono,ui-monospace,Menlo,monospace);font-size:11.5px;color:var(--muted)} +.platform-diagnostic-list{display:flex;flex-direction:column;gap:22px} +.platform-diagnostic-group{display:flex;flex-direction:column;gap:10px} +.platform-diagnostic-group-title{margin:0;font-size:12px;font-weight:700;letter-spacing:.04em;color:var(--muted);text-transform:uppercase} +.platform-diagnostic-item{display:flex;flex-direction:column;gap:6px;padding:14px 16px;border:1px solid var(--line);border-left:3px solid var(--line-strong);border-radius:12px;background:var(--panel)} +.platform-diagnostic-item.is-ok{border-left-color:var(--green)} +.platform-diagnostic-item.is-warn{border-left-color:var(--amber)} +.platform-diagnostic-item.is-error{border-left-color:var(--red)} +.platform-diagnostic-item.is-info{border-left-color:var(--blue)} +.platform-diagnostic-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap} +.platform-diagnostic-head h3{margin:0;font-size:14px;font-weight:650;color:var(--text)} +.platform-diagnostic-status{padding:2px 9px;border-radius:999px;font-size:11.5px;font-weight:700;white-space:nowrap;border:1px solid transparent} +.platform-diagnostic-status.is-ok{background:color-mix(in srgb,var(--green) 12%,transparent);border-color:color-mix(in srgb,var(--green) 26%,transparent);color:var(--green)} +.platform-diagnostic-status.is-warn{background:color-mix(in srgb,var(--amber) 14%,transparent);border-color:color-mix(in srgb,var(--amber) 28%,transparent);color:var(--amber)} +.platform-diagnostic-status.is-error{background:color-mix(in srgb,var(--red) 12%,transparent);border-color:color-mix(in srgb,var(--red) 26%,transparent);color:var(--red)} +.platform-diagnostic-status.is-info{background:color-mix(in srgb,var(--blue) 12%,transparent);border-color:color-mix(in srgb,var(--blue) 26%,transparent);color:var(--blue)} +.platform-diagnostic-detail{margin:0;font-size:12.5px;line-height:1.6;color:var(--text)} +.platform-diagnostic-hint{margin:0;font-size:12.5px;line-height:1.6;color:var(--muted)} +.platform-diagnostic-command{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:2px} +.platform-diagnostic-command code{flex:1 1 260px;min-width:0;padding:7px 10px;border:1px solid var(--line);border-radius:8px;background:color-mix(in srgb,var(--text) 4%,transparent);font-family:var(--mono,ui-monospace,Menlo,monospace);font-size:12px;overflow-wrap:anywhere} +.platform-diagnostic-placeholder{padding:24px;text-align:center;font-size:13px;color:var(--muted)} +.platform-diagnostic-placeholder.is-error{color:var(--red)} +@media (max-width:760px){.platform-diagnostic-summary{flex-direction:column;align-items:flex-start}} diff --git a/web/platform_diagnostics_test.go b/web/platform_diagnostics_test.go new file mode 100644 index 00000000..437ea140 --- /dev/null +++ b/web/platform_diagnostics_test.go @@ -0,0 +1,18 @@ +package web + +import ( + "os/exec" + "testing" +) + +// The diagnostics panel is assembled from a few pure helpers; node asserts the +// markup and the status/count mapping against the concatenated app bundle. +func TestPlatformDiagnosticsPanel(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not installed") + } + if out, err := exec.Command(node, "platform_diagnostics_test.js", appBundlePath(t)).CombinedOutput(); err != nil { + t.Fatalf("platform diagnostics panel: %v\n%s", err, out) + } +} diff --git a/web/platform_diagnostics_test.js b/web/platform_diagnostics_test.js new file mode 100644 index 00000000..90fb2e92 --- /dev/null +++ b/web/platform_diagnostics_test.js @@ -0,0 +1,74 @@ +const fs = require('node:fs'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +const bundle = fs.readFileSync(process.argv[2], 'utf8'); + +function source(name) { + const match = new RegExp('^(?:async )?function ' + name + '\\(', 'm').exec(bundle); + assert(match, name + ' not found in the app bundle'); + const tail = bundle.slice(match.index); + const next = /\n(?:async )?function |\n(?:let|const) [A-Za-z]|\n\/\/ /.exec(tail); + return next ? tail.slice(0, next.index) : tail; +} + +const context = { + lfT: (zh) => zh, + escapeHTML: (value) => String(value ?? ''), + platformDiagnosticsEndpoint: '/api/platform/diagnostics', + platformDiagnosticCategoryOrder: ['database', 'artifacts', 'browser', 'runtime'], + platformDiagnosticCategoryLabels: { + database: ['数据库', 'Database'], + artifacts: ['产物', 'Artifacts'], + browser: ['Agent 浏览器', 'Agent browser'], + runtime: ['执行环境', 'Runtime'], + }, + platformDiagnosticStatusLabels: { + ok: ['正常', 'OK'], + warn: ['需要处理', 'Action needed'], + error: ['错误', 'Error'], + info: ['说明', 'Info'], + }, +}; +vm.createContext(context); +for (const name of ['platformDiagnosticStatusClass', 'platformDiagnosticCounts', 'platformDiagnosticCheckHTML', 'platformDiagnosticGroupHTML', 'platformDiagnosticsHTML', 'platformDiagnosticsRender']) { + vm.runInContext(source(name), context); +} + +assert.equal(context.platformDiagnosticStatusClass('ok'), 'is-ok'); +assert.equal(context.platformDiagnosticStatusClass('warn'), 'is-warn'); +assert.equal(context.platformDiagnosticStatusClass('error'), 'is-error'); +assert.equal(context.platformDiagnosticStatusClass('weird'), 'is-info'); + +const counts = context.platformDiagnosticCounts([ + { status: 'ok' }, { status: 'warn' }, { status: 'warn' }, { status: 'error' }, { status: 'other' }, +]); +assert.deepEqual(JSON.parse(JSON.stringify(counts)), { ok: 1, warn: 2, error: 1, info: 1 }); + +const panel = context.platformDiagnosticsHTML(); +assert(panel.includes('platformDiagnosticsCard'), 'panel card id'); +assert(panel.includes('运维诊断'), 'panel title'); +assert(panel.includes('data-diagnostics-refresh'), 'refresh button'); + +const check = { + id: 'database.artifact_content', + category: 'database', + status: 'warn', + title: '产物正文列容量不足', + detail: 'run_artifacts.content 为 TEXT', + hint: '把该列手动扩宽为 MEDIUMTEXT', + command: 'docker compose exec platform /app/bin/agentflow -browser-image', +}; +const item = context.platformDiagnosticCheckHTML(check); +assert(item.includes('is-warn'), 'warn status class'); +assert(item.includes('产物正文列容量不足'), 'title rendered'); +assert(item.includes('data-diagnostic-command'), 'command data attribute'); +assert(item.includes('docker compose exec platform'), 'command rendered'); + +const rendered = context.platformDiagnosticsRender({ + generatedAt: '2026-01-01T00:00:00Z', + checks: [check, { id: 'database.connection', category: 'database', status: 'ok', title: '数据库连接正常' }], +}); +assert(rendered.summaryHTML.includes('1'), 'summary mentions the warning count'); +assert(rendered.bodyHTML.includes('数据库'), 'checks grouped under the database heading'); +assert(!rendered.bodyHTML.includes('产物上限'), 'unknown categories stay out of the fixed groups'); +assert(rendered.bodyHTML.includes('database.artifact_content'), 'check rendered');