Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9afd7d0067 | ||
|
|
8abb9d8a55 | ||
|
|
d7c007adc4 |
No files matched your search
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"github.com/go-sql-driver/mysql"
|
"github.com/go-sql-driver/mysql"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -17,6 +18,7 @@ import (
|
|||||||
"sea-vhost/internal/store"
|
"sea-vhost/internal/store"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -118,6 +120,49 @@ func TestResourceCRUDMySQL(t *testing.T) {
|
|||||||
must(e)
|
must(e)
|
||||||
must(db.UpdateRuntimeJob(ctx, last.ID, "completed", "verified", "test"))
|
must(db.UpdateRuntimeJob(ctx, last.ID, "completed", "verified", "test"))
|
||||||
})
|
})
|
||||||
|
t.Run("Python submission returns its job and uses only the source isolator", func(t *testing.T) {
|
||||||
|
p := &pythonInstallPanel{Mock: panel.NewMock()}
|
||||||
|
isolator := pythonInstallIsolation{Mock: isolation.Mock{Root: root}, panel: p}
|
||||||
|
svc := service.NewProjects(db, p, isolator, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||||
|
api := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, svc)
|
||||||
|
r := httptest.NewRequest("POST", "https://control.example.invalid/api/v1/admin/runtime-environments/Python/install", strings.NewReader(`{"version":"3.13.1"}`))
|
||||||
|
r.Header.Set("Origin", "https://control.example.invalid")
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
r.AddCookie(&http.Cookie{Name: "sea_session", Value: token})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
api.Handler().ServeHTTP(w, r)
|
||||||
|
var submitted struct {
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
JobID uint64 `json:"jobId"`
|
||||||
|
}
|
||||||
|
if w.Code != 202 || json.Unmarshal(w.Body.Bytes(), &submitted) != nil || !submitted.OK || submitted.JobID == 0 {
|
||||||
|
t.Fatalf("missing correlated installation task: %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
workerCtx, stop := context.WithCancel(ctx)
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { defer close(done); svc.RunRuntimeMaintenance(workerCtx) }()
|
||||||
|
defer func() { stop(); <-done }()
|
||||||
|
deadline := time.Now().Add(7 * time.Second)
|
||||||
|
for {
|
||||||
|
job, e := db.RuntimeJob(ctx, submitted.JobID)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if job.Status == "completed" {
|
||||||
|
p.mu.Lock()
|
||||||
|
calls, installed := p.sourceCalls, p.installed
|
||||||
|
p.mu.Unlock()
|
||||||
|
if calls != 1 || !installed || job.TargetVersion != "3.13.1" || !strings.Contains(job.Message, "已安装并核验") {
|
||||||
|
t.Fatalf("unexpected Python installation result: %#v", job)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) || job.Status == "failed" || job.Status == "interrupted" {
|
||||||
|
t.Fatalf("Python installation did not complete through isolator: %#v", job)
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
}
|
||||||
|
})
|
||||||
account, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-customer", Name: "CRUD 用户", Email: "crud-customer@example.invalid", DisplayName: "测试联系人", Password: "crud-customer-password-123", PlanID: 1})
|
account, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-customer", Name: "CRUD 用户", Email: "crud-customer@example.invalid", DisplayName: "测试联系人", Password: "crud-customer-password-123", PlanID: 1})
|
||||||
must(err)
|
must(err)
|
||||||
user, err := db.UserByLogin(ctx, "crud-customer@example.invalid")
|
user, err := db.UserByLogin(ctx, "crud-customer@example.invalid")
|
||||||
@@ -485,6 +530,47 @@ type pendingStatePanel struct {
|
|||||||
states map[int64]bool
|
states map[int64]bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type pythonInstallPanel struct {
|
||||||
|
*panel.Mock
|
||||||
|
mu sync.Mutex
|
||||||
|
installed bool
|
||||||
|
sourceCalls int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *pythonInstallPanel) RuntimeEnvironments(ctx context.Context) ([]panel.RuntimeEnvironment, error) {
|
||||||
|
items, err := p.Mock.RuntimeEnvironments(ctx)
|
||||||
|
p.mu.Lock()
|
||||||
|
installed := p.installed
|
||||||
|
p.mu.Unlock()
|
||||||
|
if installed {
|
||||||
|
for i := range items {
|
||||||
|
if items[i].Name == "Python" {
|
||||||
|
items[i].Installed = append(items[i].Installed, "3.13.1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items, err
|
||||||
|
}
|
||||||
|
func (p *pythonInstallPanel) InstallRuntimeEnvironment(context.Context, string, string) error {
|
||||||
|
return fmt.Errorf("unexpected panel installer; Python must use the source isolator")
|
||||||
|
}
|
||||||
|
|
||||||
|
type pythonInstallIsolation struct {
|
||||||
|
isolation.Mock
|
||||||
|
panel *pythonInstallPanel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i pythonInstallIsolation) InstallPythonRuntime(_ context.Context, version string) error {
|
||||||
|
if version != "3.13.1" {
|
||||||
|
return fmt.Errorf("unexpected Python version")
|
||||||
|
}
|
||||||
|
i.panel.mu.Lock()
|
||||||
|
defer i.panel.mu.Unlock()
|
||||||
|
i.panel.installed = true
|
||||||
|
i.panel.sourceCalls++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type busyPatchPanel struct {
|
type busyPatchPanel struct {
|
||||||
*panel.Mock
|
*panel.Mock
|
||||||
entered chan struct{}
|
entered chan struct{}
|
||||||
|
|||||||
@@ -49,11 +49,12 @@ func (s *Server) adminInstallRuntimeEnvironment(w http.ResponseWriter, r *http.R
|
|||||||
}
|
}
|
||||||
input.Version = strings.TrimSpace(input.Version)
|
input.Version = strings.TrimSpace(input.Version)
|
||||||
user := currentUser(r)
|
user := currentUser(r)
|
||||||
if err := s.projects.InstallRuntimeEnvironment(r.Context(), runtimeName, input.Version); err != nil {
|
jobID, err := s.projects.SubmitRuntimeInstallation(r.Context(), runtimeName, input.Version)
|
||||||
|
if err != nil {
|
||||||
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), false, err.Error())
|
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), false, err.Error())
|
||||||
writeError(w, http.StatusBadGateway, "运行环境安装任务提交失败")
|
writeError(w, http.StatusBadGateway, "运行环境安装任务提交失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), true, "提交 "+runtimeName+" "+input.Version+" 安装任务")
|
s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), true, "提交 "+runtimeName+" "+input.Version+" 安装任务")
|
||||||
writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true})
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "jobId": jobID})
|
||||||
}
|
}
|
||||||
@@ -430,11 +430,9 @@ func (c *Client) pythonInstallations(ctx context.Context) ([]pythonInstallation,
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, error) {
|
func (c *Client) pythonCommonAvailableVersions(ctx context.Context) ([]string, error) {
|
||||||
// The legacy Python manager list contains the first patch releases of many
|
// Match Websites -> Python Project -> Common Versions exactly. The full
|
||||||
// branches (for example 3.12.0) and is not updated consistently. aaPanel's
|
// archive is not a fallback: it may advertise a different patch or branch.
|
||||||
// project SDK catalog tracks the current stable patch of each branch even
|
|
||||||
// when its bundled installer cannot fetch that release.
|
|
||||||
body, err := c.request(ctx, http.MethodPost, "/project/python/list_py_version/stype", nil)
|
body, err := c.request(ctx, http.MethodPost, "/project/python/list_py_version/stype", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("read latest Python versions: %w", err)
|
return nil, fmt.Errorf("read latest Python versions: %w", err)
|
||||||
@@ -444,7 +442,6 @@ func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, e
|
|||||||
Msg string `json:"msg"`
|
Msg string `json:"msg"`
|
||||||
SDK struct {
|
SDK struct {
|
||||||
Streamline []runtimeSDK `json:"streamline"`
|
Streamline []runtimeSDK `json:"streamline"`
|
||||||
All []runtimeSDK `json:"all"`
|
|
||||||
} `json:"sdk"`
|
} `json:"sdk"`
|
||||||
}
|
}
|
||||||
if err = json.Unmarshal(body, &response); err != nil {
|
if err = json.Unmarshal(body, &response); err != nil {
|
||||||
@@ -453,13 +450,13 @@ func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, e
|
|||||||
if failed(response.Status) {
|
if failed(response.Status) {
|
||||||
return nil, fmt.Errorf("read latest Python versions: %s", safeMessage(response.Msg))
|
return nil, fmt.Errorf("read latest Python versions: %s", safeMessage(response.Msg))
|
||||||
}
|
}
|
||||||
versions := make([]string, 0, len(response.SDK.Streamline)+len(response.SDK.All))
|
versions := make([]string, 0, len(response.SDK.Streamline))
|
||||||
for _, item := range append(response.SDK.Streamline, response.SDK.All...) {
|
for _, item := range response.SDK.Streamline {
|
||||||
versions = append(versions, item.Version)
|
versions = append(versions, item.Version)
|
||||||
}
|
}
|
||||||
versions = latestPythonBranchVersions(versions)
|
versions = latestPythonBranchVersions(versions)
|
||||||
if len(versions) == 0 {
|
if len(versions) == 0 {
|
||||||
return nil, errors.New("latest Python branch catalog is empty")
|
return nil, errors.New("宝塔 Python 项目的常用版本列表为空,请在面板刷新版本后重试")
|
||||||
}
|
}
|
||||||
return versions, nil
|
return versions, nil
|
||||||
}
|
}
|
||||||
@@ -813,7 +810,7 @@ func (c *Client) RuntimeEnvironments(ctx context.Context) ([]RuntimeEnvironment,
|
|||||||
items[2].ComponentInstallable = items[2].ComponentUpdateAvailable
|
items[2].ComponentInstallable = items[2].ComponentUpdateAvailable
|
||||||
}
|
}
|
||||||
installations, installedErr := c.pythonInstallations(ctx)
|
installations, installedErr := c.pythonInstallations(ctx)
|
||||||
available, availableErr := c.pythonLatestAvailableVersions(ctx)
|
available, availableErr := c.pythonCommonAvailableVersions(ctx)
|
||||||
if installedErr != nil || availableErr != nil {
|
if installedErr != nil || availableErr != nil {
|
||||||
items[2].ComponentStatus, items[2].Detail = RuntimeComponentFailed, "Python 版本清单暂不可用"
|
items[2].ComponentStatus, items[2].Detail = RuntimeComponentFailed, "Python 版本清单暂不可用"
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -125,6 +125,38 @@ func TestRuntimeCatalogUsesAaPanelProjectRoutes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPythonAvailableVersionsUseCommonCatalogWithoutArchiveFallback(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name, body string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"common differs from archive", `{"status":true,"sdk":{"streamline":[{"version":"3.12.15"},{"version":"3.13.17"}],"all":[{"version":"3.12.16"},{"version":"3.16.1"}]}}`, []string{"3.13.17", "3.12.15"}},
|
||||||
|
{"no common catalog", `{"status":true,"sdk":{"all":[{"version":"3.12.16"}]}}`, nil},
|
||||||
|
{"empty common catalog", `{"status":true,"sdk":{"streamline":[],"all":[{"version":"3.12.16"}]}}`, nil},
|
||||||
|
{"unsafe or prerelease entries", `{"status":true,"sdk":{"streamline":[{"version":"3.13.17"},{"version":"3.14.0rc1"},{"version":"../../../tmp"},{"version":"3.12.15;id"}]}}`, []string{"3.13.17"}},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/project/python/list_py_version/stype" || r.Method != http.MethodPost {
|
||||||
|
t.Errorf("unexpected Python catalog request: %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(test.body))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
client := NewClient(server.URL, "test-key", false, time.Second)
|
||||||
|
got, err := client.pythonCommonAvailableVersions(context.Background())
|
||||||
|
if test.want == nil {
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "常用版本") {
|
||||||
|
t.Fatalf("missing common catalog was silently accepted: %v", err)
|
||||||
|
}
|
||||||
|
} else if err != nil || !reflect.DeepEqual(got, test.want) {
|
||||||
|
t.Fatalf("got %v, %v; want %v", got, err, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRuntimeCapabilitiesDoNotFailAsAGroup(t *testing.T) {
|
func TestRuntimeCapabilitiesDoNotFailAsAGroup(t *testing.T) {
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|||||||
@@ -57,9 +57,14 @@ func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version
|
|||||||
if s.store == nil {
|
if s.store == nil {
|
||||||
return s.installRuntimeEnvironmentLegacy(ctx, name, version)
|
return s.installRuntimeEnvironmentLegacy(ctx, name, version)
|
||||||
}
|
}
|
||||||
|
_, err := s.SubmitRuntimeInstallation(ctx, name, version)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Projects) SubmitRuntimeInstallation(ctx context.Context, name, version string) (uint64, error) {
|
||||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return 0, err
|
||||||
}
|
}
|
||||||
allowed := false
|
allowed := false
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
@@ -68,10 +73,9 @@ func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !allowed {
|
if !allowed {
|
||||||
return errors.New("请选择清单中尚未安装的运行环境版本")
|
return 0, errors.New("请选择清单中尚未安装的运行环境版本")
|
||||||
}
|
}
|
||||||
_, err = s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version})
|
return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version})
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
func (s *Projects) SubmitPHPPatch(ctx context.Context, branch, target string) (uint64, error) {
|
func (s *Projects) SubmitPHPPatch(ctx context.Context, branch, target string) (uint64, error) {
|
||||||
items, err := s.panel.RuntimeEnvironments(ctx)
|
items, err := s.panel.RuntimeEnvironments(ctx)
|
||||||
@@ -232,6 +236,7 @@ func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJo
|
|||||||
}
|
}
|
||||||
if err == nil && !installed && !installing {
|
if err == nil && !installed && !installing {
|
||||||
if job.Runtime == "Python" {
|
if job.Runtime == "Python" {
|
||||||
|
slog.Info("installing Python from verified source", "job_id", job.ID, "node_id", job.NodeID, "version", job.TargetVersion)
|
||||||
err = s.isolation.InstallPythonRuntime(ctx, job.TargetVersion)
|
err = s.isolation.InstallPythonRuntime(ctx, job.TargetVersion)
|
||||||
} else {
|
} else {
|
||||||
err = s.panel.InstallRuntimeEnvironment(ctx, job.Runtime, job.TargetVersion)
|
err = s.panel.InstallRuntimeEnvironment(ctx, job.Runtime, job.TargetVersion)
|
||||||
@@ -268,7 +273,11 @@ func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJo
|
|||||||
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护失败", fmt.Sprintf("任务 #%d %s %s:%v", job.ID, job.Runtime, job.TargetVersion, err))
|
_ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护失败", fmt.Sprintf("任务 #%d %s %s:%v", job.ID, job.Runtime, job.TargetVersion, err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", "目标版本已核验;原本停止的站点保持停止,待启动后核验进程")
|
message := "目标版本已核验;原本停止的站点保持停止,待启动后核验进程"
|
||||||
|
if job.Action == "install" {
|
||||||
|
message = job.Runtime + " " + job.TargetVersion + " 已安装并核验"
|
||||||
|
}
|
||||||
|
_ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", message)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Coordinate with host identity changes and unfinished site switches, not
|
// Coordinate with host identity changes and unfinished site switches, not
|
||||||
|
|||||||
+1
-1
@@ -143,8 +143,8 @@ fi
|
|||||||
[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}"
|
[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}"
|
||||||
install -d -o root -g root -m 0755 /usr/local/libexec
|
install -d -o root -g root -m 0755 /usr/local/libexec
|
||||||
install -o root -g root -m 0755 "${build_dir}/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run
|
install -o root -g root -m 0755 "${build_dir}/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run
|
||||||
install -o root -g root -m 0750 "${build_dir}/bin/sea-vhost-scheduler" /opt/sea-vhost/bin/sea-vhost-scheduler
|
|
||||||
install -d -o root -g sea-vhost-control -m 0750 /opt/sea-vhost/bin
|
install -d -o root -g sea-vhost-control -m 0750 /opt/sea-vhost/bin
|
||||||
|
install -o root -g root -m 0750 "${build_dir}/bin/sea-vhost-scheduler" /opt/sea-vhost/bin/sea-vhost-scheduler
|
||||||
install -d -o root -g root -m 0755 /opt/sea-vhost/web
|
install -d -o root -g root -m 0755 /opt/sea-vhost/web
|
||||||
install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost
|
install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost
|
||||||
install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel
|
install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
# 宝塔 API 兼容性记录
|
# 宝塔 API 兼容性记录
|
||||||
|
|
||||||
|
## Python 常用版本与安装边界(2026-10-30)
|
||||||
|
|
||||||
|
Python 待安装版本来自 `POST /project/python/list_py_version/stype` 的 `sdk.streamline`,对应面板“Python 项目 → 常用版本”;不合并 `sdk.all`,为空即报错。稳定版本格式和本系统支持分支继续校验,归档中的更新补丁不能越过面板常用列表进入选择器。
|
||||||
|
|
||||||
|
36 上确认原生 `btpyvm.py` 使用 XML 解析 HTML 镜像目录会产生 `mismatched tag`,华为目录实测位置为第 7 行第 2 列。Sea vHost 的 Python 安装通过隔离服务执行官方摘要校验的源码构建,不调用此原生命令;本次没有改写宝塔代码。安装接口返回 `jobId`,前端显示同一编号,使用 Sea vHost 的维护记录跟踪结果。宝塔全局日志不能作为该任务执行路径的证据。
|
||||||
|
|
||||||
|
下方保留其他基础接口与历史兼容记录。
|
||||||
|
|
||||||
公开接口基线:宝塔 Linux 面板官方 API `11.7.0-docs`。只读兼容性探测基线:宝塔 Linux 面板 12.0.0 + Debian 13;该探测未修改测试机资源。
|
公开接口基线:宝塔 Linux 面板官方 API `11.7.0-docs`。只读兼容性探测基线:宝塔 Linux 面板 12.0.0 + Debian 13;该探测未修改测试机资源。
|
||||||
|
|
||||||
| 能力 | 路由 / action | 策略 | Sea vHost 用途 |
|
| 能力 | 路由 / action | 策略 | Sea vHost 用途 |
|
||||||
|
|||||||
@@ -1,7 +1,25 @@
|
|||||||
# 36 单机实机测试交付
|
# 36 单机实机测试交付
|
||||||
|
|
||||||
|
## 当前状态:已清理重装,等待用户初始化
|
||||||
|
|
||||||
|
2026-10-30 经用户确认,36 已清除 Sea vHost 的旧账号、三台主机及其站点、FTP、主机数据库和旧控制库,重新安装后停留在空白 Web 安装向导。控制台地址仍为 `https://host.ser888.cn/`,新应用数据库为 `sea_vhost`,尚无数据表或管理员;安装令牌及数据库密码由单独的私密交付信息提供,不进入源码包。重装前已验证完整备份,宝塔其他资源、控制台证书和已安装运行环境保留。
|
||||||
|
|
||||||
|
rc.4 修复全新安装时调度器程序先于目标目录安装的问题。已通过 19 项安装向导测试及 36 的实际清理安装、空库连接和待安装状态检查。下方账号与主机说明为重装前的历史验收记录,相关体验资源已清理,不代表当前可登录资源。
|
||||||
|
|
||||||
交付日期:2026-10-30。当前目标为 36 机器上的单机生产测试环境,不使用早期 202 机器的端口映射或临时域名。本次整理不重装、不清空业务数据库、不修改现有账号密码。
|
交付日期:2026-10-30。当前目标为 36 机器上的单机生产测试环境,不使用早期 202 机器的端口映射或临时域名。本次整理不重装、不清空业务数据库、不修改现有账号密码。
|
||||||
|
|
||||||
|
## Python 安装补充验收(rc.2)
|
||||||
|
|
||||||
|
36 本机节点在 Sea vHost“环境配置”页提交 Python 3.14.9,任务 #38 于北京时间 2026-10-30 09:37 完成,页面显示“Python 3.14.9 已安装并核验”。已核验 `ssl`、`sqlite3`、`venv`、`ensurepip`,并以体验主机独立 Linux 身份创建和运行临时虚拟环境。测试临时目录已自动清理,未改变体验站点运行环境或现有账号密码。
|
||||||
|
|
||||||
|
待安装列表仅采用宝塔 Python 项目的 `sdk.streamline` 常用版本。Sea vHost 使用带官方 SHA-256 校验的源码构建,未修改宝塔 `btpyvm.py`;宝塔原生 XML 目录解析异常仍属于面板自身问题。本次实装仅覆盖 3.14.9,不代表全部 Python 分支已逐一安装。
|
||||||
|
|
||||||
|
## 用户导航与小屏补充验收(rc.3)
|
||||||
|
|
||||||
|
用户侧边栏保留“总览、域名、DNS API、操作日志”,用户计划任务入口移至总览工具区。总览每行仅保留“进入主机”,也可双击行进入;主机管理显示当前主机并可返回用户总览。主机内文件、数据库、FTP、图表和日志限定到当前主机,独立主机账号仍只管理自身。
|
||||||
|
|
||||||
|
前端 95 项回归通过。内置浏览器在 1280×900 与 390×844 检查列表及主机操作区;小屏操作列保留可达入口,表格操作按钮保持横向排列,主机详情按钮采用双列。36 线上双主机账号已验证进入指定主机、数据库与文件范围;本轮前端更新未修改账号、主机归属或后端程序。
|
||||||
|
|
||||||
## 直接开始使用
|
## 直接开始使用
|
||||||
|
|
||||||
- 控制台:<https://host.ser888.cn/>。
|
- 控制台:<https://host.ser888.cn/>。
|
||||||
|
|||||||
@@ -39,11 +39,13 @@
|
|||||||
|
|
||||||
## 网站、文件、环境与日志
|
## 网站、文件、环境与日志
|
||||||
|
|
||||||
用户在“虚拟主机”选择名下主机,再点击“网站管理”;独立主机账号登录后直接进入主机详情。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。
|
用户侧边栏仅保留“总览、域名、DNS API、操作日志”。在总览主机列表点击“进入主机”,或双击主机行,进入该主机管理;页头显示目前主机,可“返回用户总览”后选择另一台。主机管理中提供资源配置、网站、文件、数据库、FTP、资源图表及该主机日志,均限定当前主机。账号权限不因进入主机而改变;独立主机账号直接进入自身管理,不提供返回用户总览。用户级计划任务入口保留在用户总览工具区,独立主机账号不可用。用户视图的域名与日志可查看名下主机汇总。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。
|
||||||
|
|
||||||
在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。
|
在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。
|
||||||
|
|
||||||
组件安装及 PHP 补丁更新交由宝塔执行,Sea vHost 跟踪进度,不因此锁住整个节点的主机操作。即使组件任务中断待核验,其他主机仍可保存文件和管理配置。站点版本迁移或跨语言切换仅保护所属主机;PHP 更新完成后只在刷新对应主机独立 FPM 的短暂阶段保护该主机,其他主机继续可用。
|
组件安装(Python 解释器除外)及 PHP 补丁更新交由宝塔执行,Sea vHost 跟踪进度,不因此锁住整个节点的主机操作。即使组件任务中断待核验,其他主机仍可保存文件和管理配置。站点版本迁移或跨语言切换仅保护所属主机;PHP 更新完成后只在刷新对应主机独立 FPM 的短暂阶段保护该主机,其他主机继续可用。
|
||||||
|
|
||||||
|
Python 待安装版本只读取宝塔“网站 → Python 项目 → 常用版本”,不再合并“全部版本”;当前仅提供本系统支持的稳定 CPython 分支。常用列表为空时停止提交,不用全部列表代替。Python 由隔离服务下载源码并按官方 HTTPS 元数据中的 SHA-256 校验后编译,解释器保存在 `/www/server/python_manager/versions/<版本>`,保留既有版本;创建网站时再注册给宝塔 Python 项目。环境页提交成功会显示 Sea vHost 任务编号,安装结果以同编号的维护记录为准,不能用宝塔全局安装日志代替该任务结果。
|
||||||
|
|
||||||
PHP 网站创建后即可上传程序。Node.js、Python、Go、Java 网站先创建,上传入口文件后点击“部署检查”→“检查文件”→“开始部署”。应用监听 `127.0.0.1`,使用系统注入的 `PORT`;Java 同时获得 `--server.port` 参数。Go 上传 Linux amd64 可执行程序,Java 上传可运行 JAR;Node 使用 `package.json` 的 `start` 脚本。
|
PHP 网站创建后即可上传程序。Node.js、Python、Go、Java 网站先创建,上传入口文件后点击“部署检查”→“检查文件”→“开始部署”。应用监听 `127.0.0.1`,使用系统注入的 `PORT`;Java 同时获得 `--server.port` 参数。Go 上传 Linux amd64 可执行程序,Java 上传可运行 JAR;Node 使用 `package.json` 的 `start` 脚本。
|
||||||
|
|
||||||
|
|||||||
+26
-12
@@ -1,5 +1,5 @@
|
|||||||
import '@testing-library/jest-dom/vitest';
|
import '@testing-library/jest-dom/vitest';
|
||||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||||
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
import {DNSCredentials} from './components/DNSCredentials';
|
import {DNSCredentials} from './components/DNSCredentials';
|
||||||
import { App } from './App';
|
import { App } from './App';
|
||||||
@@ -20,6 +20,8 @@ afterEach(() => {
|
|||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function enterFirstHost(){fireEvent.click(screen.getByRole('button',{name:'进入主机 '+initialProjects[0].hostName}))}
|
||||||
|
|
||||||
describe('Sea vHost', () => {
|
describe('Sea vHost', () => {
|
||||||
it('opens the create project workflow', () => {
|
it('opens the create project workflow', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
@@ -34,7 +36,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('lets a tenant configure a host-relative run directory', () => {
|
it('lets a tenant configure a host-relative run directory', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '主站目录' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '设置运行目录' }));
|
||||||
expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument();
|
expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument();
|
||||||
const input = screen.getByDisplayValue('/public');
|
const input = screen.getByDisplayValue('/public');
|
||||||
fireEvent.change(input, { target: { value: '/../etc' } });
|
fireEvent.change(input, { target: { value: '/../etc' } });
|
||||||
@@ -43,14 +46,16 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('opens file management for a selected project', async () => {
|
it('opens file management for a selected project', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '文件' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'文件管理'}));
|
||||||
expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument();
|
expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument();
|
||||||
expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1');
|
expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds another website with an independent runtime and directory', () => {
|
it('adds another website with an independent runtime and directory', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument();
|
expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
||||||
fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } });
|
fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } });
|
||||||
@@ -64,7 +69,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('checks and deploys an uploaded language project before reporting it running', async () => {
|
it('checks and deploys an uploaded language project before reporting it running', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
||||||
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
|
fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } });
|
||||||
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
||||||
@@ -80,7 +86,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('installs a manual certificate without retaining the private key form', async () => {
|
it('installs a manual certificate without retaining the private key form', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' }));
|
fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' }));
|
||||||
expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument();
|
expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument();
|
||||||
fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } });
|
fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } });
|
||||||
@@ -91,7 +98,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('lets a tenant retry automatic certificate issuance for a managed site', async () => {
|
it('lets a tenant retry automatic certificate issuance for a managed site', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument();
|
expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' }));
|
fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' }));
|
||||||
await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument());
|
await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument());
|
||||||
@@ -99,7 +107,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('lets a tenant explicitly disable SSL and automatic renewal', async () => {
|
it('lets a tenant explicitly disable SSL and automatic renewal', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' }));
|
fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
||||||
await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument());
|
await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument());
|
||||||
@@ -108,7 +117,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('shows reusable FTP and database credentials', () => {
|
it('shows reusable FTP and database credentials', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '访问凭据' }));
|
||||||
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存');
|
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存');
|
||||||
expect(screen.getByText('demo-ftp-password')).toBeInTheDocument();
|
expect(screen.getByText('demo-ftp-password')).toBeInTheDocument();
|
||||||
expect(screen.getByText('demo-database-password')).toBeInTheDocument();
|
expect(screen.getByText('demo-database-password')).toBeInTheDocument();
|
||||||
@@ -116,7 +126,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('resets the independent host login password', async () => {
|
it('resets the independent host login password', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '访问凭据' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '重置主机密码' }));
|
fireEvent.click(screen.getByRole('button', { name: '重置主机密码' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
fireEvent.click(screen.getByRole('button', { name: '确认继续' }));
|
||||||
expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument();
|
expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument();
|
||||||
@@ -124,7 +135,8 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('stops and deletes an additional website without deleting host files', async () => {
|
it('stops and deletes an additional website without deleting host files', async () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]);
|
enterFirstHost();
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '网站管理' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '新增网站' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
fireEvent.click(screen.getByRole('button', { name: '创建网站' }));
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' }));
|
fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' }));
|
||||||
@@ -147,6 +159,7 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('opens encrypted credentials from the FTP resource page', () => {
|
it('opens encrypted credentials from the FTP resource page', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
|
enterFirstHost();
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'FTP' }));
|
fireEvent.click(screen.getByRole('button', { name: 'FTP' }));
|
||||||
fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ }));
|
fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ }));
|
||||||
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password');
|
expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password');
|
||||||
@@ -154,6 +167,7 @@ describe('Sea vHost', () => {
|
|||||||
|
|
||||||
it('opens the mobile navigation and navigates to a resource page', () => {
|
it('opens the mobile navigation and navigates to a resource page', () => {
|
||||||
render(<App />);
|
render(<App />);
|
||||||
|
enterFirstHost();
|
||||||
const menu = screen.getByRole('button', { name: '打开导航' });
|
const menu = screen.getByRole('button', { name: '打开导航' });
|
||||||
fireEvent.click(menu);
|
fireEvent.click(menu);
|
||||||
expect(menu).toHaveAttribute('aria-expanded', 'true');
|
expect(menu).toHaveAttribute('aria-expanded', 'true');
|
||||||
@@ -302,7 +316,7 @@ describe('宝塔站点迁移', () => {
|
|||||||
describe('主机账号边界', () => {
|
describe('主机账号边界', () => {
|
||||||
it('不显示用户级聚合用量和创建主机入口', () => {
|
it('不显示用户级聚合用量和创建主机入口', () => {
|
||||||
const noop = () => undefined;
|
const noop = () => undefined;
|
||||||
render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onToggle={noop} onFiles={noop} onRunPath={noop} onSites={noop} onCredentials={noop} />);
|
render(<Overview projects={[initialProjects[0]]} plan={demoPlan} usage={demoUsage} activities={[]} hostScoped canCreate={false} onCreate={noop} onEnterHost={noop} />);
|
||||||
expect(screen.queryByText('存储空间')).not.toBeInTheDocument();
|
expect(screen.queryByText('存储空间')).not.toBeInTheDocument();
|
||||||
expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument();
|
expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument();
|
||||||
expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument();
|
expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument();
|
||||||
|
|||||||
+19
-6
@@ -29,6 +29,8 @@ export function App() {
|
|||||||
const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1';
|
const adminPreview = import.meta.env.DEV && new URLSearchParams(window.location.search).get('admin') === '1';
|
||||||
const [page, setPage] = useState('overview');
|
const [page, setPage] = useState('overview');
|
||||||
const [projects, setProjects] = useState<Project[]>(initialProjects);
|
const [projects, setProjects] = useState<Project[]>(initialProjects);
|
||||||
|
const [managedProjectID, setManagedProjectID] = useState<number>();
|
||||||
|
useEffect(()=>{document.documentElement.scrollTop=0;document.body.scrollTop=0},[page,managedProjectID]);
|
||||||
const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]);
|
const changingProjects=useRef(new Set<number>()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState<number[]>([]);
|
||||||
const [fileProjectID, setFileProjectID] = useState<number>();
|
const [fileProjectID, setFileProjectID] = useState<number>();
|
||||||
const [runPathProject, setRunPathProject] = useState<Project>();
|
const [runPathProject, setRunPathProject] = useState<Project>();
|
||||||
@@ -53,6 +55,11 @@ export function App() {
|
|||||||
const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>();
|
const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState<number>();
|
||||||
const [bootAttempt, setBootAttempt] = useState(0);
|
const [bootAttempt, setBootAttempt] = useState(0);
|
||||||
const [showSecurity, setShowSecurity] = useState(false);
|
const [showSecurity, setShowSecurity] = useState(false);
|
||||||
|
useEffect(()=>{
|
||||||
|
if(managedProjectID && !projects.some(project=>project.id===managedProjectID)){
|
||||||
|
setManagedProjectID(undefined);setPage('overview');setSitesProject(undefined);setRunPathProject(undefined);setCredentials(null);
|
||||||
|
}
|
||||||
|
},[managedProjectID,projects]);
|
||||||
|
|
||||||
const applyDashboard=useCallback((dashboard:Dashboard)=>{
|
const applyDashboard=useCallback((dashboard:Dashboard)=>{
|
||||||
setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot);
|
setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot);
|
||||||
@@ -203,6 +210,12 @@ export function App() {
|
|||||||
if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败'));
|
if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const managedProject = hostScoped ? projects[0] : projects.find(project=>project.id===managedProjectID);
|
||||||
|
const hostView = hostScoped || !!managedProject;
|
||||||
|
const visibleProjects = hostView ? (managedProject ? [managedProject] : []) : projects;
|
||||||
|
function enterHost(project:Project){setManagedProjectID(project.id);setFileProjectID(project.id);setPage('projects')}
|
||||||
|
function leaveHost(){setManagedProjectID(undefined);setPage('overview');setSitesProject(undefined);setRunPathProject(undefined);setCredentials(null)}
|
||||||
|
|
||||||
if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />;
|
if (adminPreview) return <AdminConsole user={{ id: 1, email: 'admin@ser888.cn', loginName: 'admin@ser888.cn', displayName: '平台管理员', role: 'admin', mfaEnabled: true }} tenants={[{ id: 1, slug: 'sea-demo', name: '示例用户', status: 'active', lifecycleState: 'active', planName: '标准套餐', userCount: 1, projectCount: 3, expiresAt: '2026-12-31T16:00:00Z', createdAt: '2026-10-01T08:00:00Z' }]} plans={[demoPlan]} pendingDomains={[{ id: 9, projectId: 1, siteId: 1, tenantName: '示例用户', hostName: 'sv8c0a6d2f91', projectName: '企业官网', siteName: '主站', domain: 'www.customer.example', kind: 'custom', status: 'pending', resolutionMode: 'cname', cnameTarget: 'sv8c0a6d2f91.vhost.ser888.cn', filingStatus: 'pending', sslStatus: 'pending', createdAt: '2026-10-22T08:00:00Z' }]} approval onApproval={async () => undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />;
|
||||||
if (setupPreview) return <InstallWizard preview />;
|
if (setupPreview) return <InstallWizard preview />;
|
||||||
if (apiMode && setupRequired === true) return <InstallWizard />;
|
if (apiMode && setupRequired === true) return <InstallWizard />;
|
||||||
@@ -212,17 +225,17 @@ export function App() {
|
|||||||
if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>;
|
if (apiMode && user?.role === 'admin') return <><AdminConsole onPlansChanged={async()=>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? <SecurityModal onClose={() => setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}</>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AppShell page={page === 'create' ? 'projects' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}>
|
<AppShell page={page === 'create'||page==='schedules' ? 'overview' : page} tenantName={user?.tenantName ?? '示例科技有限公司'} displayName={user?.displayName ?? '张三'} hostScoped={hostScoped} hostView={hostView} hostName={managedProject?.hostName} onBack={hostView&&!hostScoped?leaveHost:undefined} onNavigate={setPage} onLogout={()=>{void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}>
|
||||||
{user?.impersonating?<ImpersonationBanner user={user}/>:null}
|
{user?.impersonating?<ImpersonationBanner user={user}/>:null}
|
||||||
{dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null}
|
{dashboardSync.error?<p className="resource-error" role="alert">状态刷新失败:{dashboardSync.error}。<button className="secondary" onClick={dashboardSync.refresh}>重新读取状态</button></p>:null}
|
||||||
{page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} pendingProjectIDs={pendingProjectIDs} onLogs={() => setPage('logs')} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onToggle={toggleProject} onFiles={(id) => { setFileProjectID(id); setPage('files'); }} onRunPath={(project) => setRunPathProject(project)} onSites={(project)=>{setRuntimeVersions(normalizeCatalog({}));setSitesProject(project);if(apiMode) void api.runtimeCatalog(project.id).then(result=>setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason=>notify(reason instanceof Error?reason.message:"节点环境读取失败"));else setRuntimeVersions(demoRuntimeVersions);}} onCredentials={(project) => void showCredentials(project)} /> : null}
|
{page === 'overview' ? <Overview onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onLogs={() => setPage('logs')} onSchedules={!hostScoped?()=>setPage('schedules'):undefined} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onEnterHost={enterHost} /> : null}
|
||||||
{page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null}
|
{page === 'create' ? <CreateProject runtimeVersions={runtimeVersions} rootDomain={rootDomain} projectRoot={projectRoot} plan={plan} domainApproval={domainApproval} onCancel={() => setPage('overview')} onSubmit={createProject} /> : null}
|
||||||
{page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null}
|
{page==='schedules'&&!hostScoped?<UserSchedules projects={projects} live={apiMode}/>:null}
|
||||||
{page==='metrics'?<ResourceCharts projects={projects} live={apiMode}/>:null}
|
{page==='metrics'?<ResourceCharts key={managedProject?.id} projects={visibleProjects} live={apiMode}/>:null}
|
||||||
{page === 'files' ? <FileManager projects={projects} initialProjectID={fileProjectID} live={apiMode} /> : null}
|
{page === 'files' ? <FileManager key={managedProject?.id} projects={visibleProjects} initialProjectID={fileProjectID} live={apiMode} /> : null}
|
||||||
{page === 'projects' ? <HostDetails onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={projects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null}
|
{page === 'projects' ? <HostDetails key={managedProject?.id} onRefresh={apiMode?dashboardSync.refresh:undefined} refreshing={dashboardSync.refreshing} onToggle={toggleProject} pendingProjectIDs={pendingProjectIDs} hostScoped={hostScoped} projects={visibleProjects} plan={plan} usage={usage} live={apiMode} onRunPath={setRunPathProject} onSites={showSites} onCredentials={project => void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null}
|
||||||
{page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null}
|
{page === 'dns' && !hostScoped ? <DNSCredentials live={apiMode} /> : null}
|
||||||
{['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter page={page} projects={projects} activities={activities} hostScoped={hostScoped} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null}
|
{['domains', 'databases', 'ftp', 'logs'].includes(page) ? <ResourceCenter key={`${managedProject?.id}:${page}`} page={page} projects={visibleProjects} projectID={managedProject?.id} activities={activities} hostScoped={hostView} domainApproval={domainApproval} live={apiMode} onCredentials={showCredentialsByID} onNotify={notify} /> : null}
|
||||||
{toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null}
|
{toast ? <div className="toast" role="status"><CheckIcon />{toast}</div> : null}
|
||||||
{credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null}
|
{credentials ? <CredentialsModal credentials={credentials} onReset={user?.role !== 'host' ? resetHostPassword : undefined} onClose={() => { setCredentials(null); setCredentialProjectID(undefined); }} /> : null}
|
||||||
{runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null}
|
{runPathProject ? <RunPathModal project={runPathProject} onClose={() => setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null}
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import '@testing-library/jest-dom/vitest';
|
||||||
|
import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react';
|
||||||
|
import {afterEach,expect,it,vi} from 'vitest';
|
||||||
|
import {api,type RuntimeEnvironment} from './api';
|
||||||
|
import {EnvironmentConfiguration} from './components/EnvironmentConfiguration';
|
||||||
|
|
||||||
|
vi.mock('./components/RuntimeMaintenancePanel',()=>({RuntimeMaintenancePanel:()=>null}));
|
||||||
|
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
||||||
|
|
||||||
|
it('correlates the selected Python version with its actual Sea vHost task',async()=>{
|
||||||
|
const python:RuntimeEnvironment={name:'Python',componentTitle:'Python 项目管理器',componentStatus:'installed',componentInstallable:false,installed:[],available:['3.14.9','3.13.17'],installing:[],recommended:'3.14.9'};
|
||||||
|
vi.spyOn(api,'runtimeEnvironments').mockResolvedValue({environments:[python]});
|
||||||
|
const install=vi.spyOn(api,'installRuntimeEnvironment').mockResolvedValue({ok:true,jobId:38});
|
||||||
|
render(<EnvironmentConfiguration nodeId={1}/>);
|
||||||
|
expect(await screen.findByRole('combobox',{name:'Python 待安装版本'})).toHaveValue('3.14.9');
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'安装版本'}));
|
||||||
|
expect(screen.getByRole('alertdialog')).toHaveTextContent('Python 3.14.9');
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'确认继续'}));
|
||||||
|
await waitFor(()=>expect(install).toHaveBeenCalledWith('Python','3.14.9',1));
|
||||||
|
expect(await screen.findByText(/Python 3.14.9 已提交 Sea vHost 任务 #38/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
@@ -14,6 +14,31 @@ it('opens real host configuration controls with administrator-assigned limits',(
|
|||||||
fireEvent.click(screen.getByRole('button',{name:'设置运行目录'}));expect(onRunPath).toHaveBeenCalledWith(initialProjects[0]);
|
fireEvent.click(screen.getByRole('button',{name:'设置运行目录'}));expect(onRunPath).toHaveBeenCalledWith(initialProjects[0]);
|
||||||
fireEvent.click(screen.getByRole('button',{name:'网站管理'}));expect(onSites).toHaveBeenCalledWith(initialProjects[0]);
|
fireEvent.click(screen.getByRole('button',{name:'网站管理'}));expect(onSites).toHaveBeenCalledWith(initialProjects[0]);
|
||||||
});
|
});
|
||||||
|
it('switches all host management actions to the selected host',()=>{
|
||||||
|
const onSites=vi.fn(),onFiles=vi.fn(),onCredentials=vi.fn(),onRunPath=vi.fn(),onToggle=vi.fn();
|
||||||
|
render(<HostDetails projects={initialProjects} plan={demoPlan} usage={demoUsage} live={false} onSites={onSites} onFiles={onFiles} onCredentials={onCredentials} onRunPath={onRunPath} onToggle={onToggle}/>);
|
||||||
|
const target=initialProjects[1];
|
||||||
|
fireEvent.change(screen.getByRole('combobox',{name:'选择虚拟主机'}),{target:{value:String(target.id)}});
|
||||||
|
expect(screen.getByRole('heading',{name:target.hostName})).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('link',{name:target.domain})).toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'网站管理'}));expect(onSites).toHaveBeenCalledWith(target);
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'设置运行目录'}));expect(onRunPath).toHaveBeenCalledWith(target);
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'文件管理'}));expect(onFiles).toHaveBeenCalledWith(target.id);
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'访问凭据'}));expect(onCredentials).toHaveBeenCalledWith(target);
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'停止主站'}));expect(onToggle).toHaveBeenCalledWith(target.id);
|
||||||
|
});
|
||||||
|
it('does not show a host switcher for a single-host login',()=>{
|
||||||
|
render(<HostDetails projects={initialProjects.slice(0,1)} plan={demoPlan} usage={demoUsage} live={false} hostScoped onSites={vi.fn()} onFiles={vi.fn()} onCredentials={vi.fn()} onRunPath={vi.fn()}/>);
|
||||||
|
expect(screen.queryByRole('combobox',{name:'选择虚拟主机'})).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('heading',{name:initialProjects[0].hostName})).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it('shows only the entered host databases even when the account resource response includes other hosts',async()=>{
|
||||||
|
const first=initialProjects[0],target=initialProjects[1];
|
||||||
|
vi.spyOn(api,'resources').mockResolvedValue({sites:[],domains:[],ftpAccounts:[],databases:[first,target].map(p=>({id:p.id,projectId:p.id,hostName:p.hostName,projectName:p.name,name:'db-'+p.hostName,username:p.hostName,sizeBytes:0,status:'active',createdAt:'2026-10-30T00:00:00Z'}))});
|
||||||
|
render(<ResourceCenter page="databases" projectID={target.id} projects={[target]} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
|
||||||
|
expect(await screen.findByText('db-'+target.hostName)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('db-'+first.hostName)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
it('loads and refreshes logs scoped to the signed-in host',async()=>{
|
it('loads and refreshes logs scoped to the signed-in host',async()=>{
|
||||||
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]});
|
const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]});
|
||||||
render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
|
render(<ResourceCenter page="logs" projects={initialProjects.slice(0,1)} activities={[]} hostScoped live domainApproval onCredentials={vi.fn()} onNotify={vi.fn()}/>);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ it('submits one state change during rapid clicks and shows the requested final s
|
|||||||
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User});
|
vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:4,role:'tenant',displayName:'测试用户',tenantName:'测试账号'} as User});
|
||||||
vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard);
|
vi.spyOn(api,'dashboard').mockResolvedValue({plan:demoPlan,usage:demoUsage,activities:[],hostScoped:false,domainApproval:true,rootDomain:'vhost.ser888.cn',projectRoot:'/www/wwwroot/seavHost/vHost',projects:[{id:9,hostName:'sv9999999999',name:'主机',domain:'qa.vhost.ser888.cn',path:'/www/wwwroot/seavHost/vHost/sv9999999999',runPath:'/public',runtime:'PHP',version:'8.4',status:'stopped',sslStatus:'off',autoSSL:false,processLimit:10,createdAt:'2026-10-29T00:00:00Z'}]} as Dashboard);
|
||||||
let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending);
|
let finish!:()=>void;const pending=new Promise<void>(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending);
|
||||||
render(<App/>);const start=await screen.findByRole('button',{name:'启动'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true);
|
render(<App/>);fireEvent.click(await screen.findByRole('button',{name:'进入主机 sv9999999999'}));const start=await screen.findByRole('button',{name:'启动主站'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止主站'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true);
|
||||||
});
|
});
|
||||||
it('keeps a rejected run directory visible with an inline reason',async()=>{
|
it('keeps a rejected run directory visible with an inline reason',async()=>{
|
||||||
render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled();
|
render(<RunPathModal project={initialProjects[0]} onClose={vi.fn()} onSubmit={vi.fn().mockRejectedValue(new Error('目标目录不存在'))}/>);fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled();
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import '@testing-library/jest-dom/vitest';
|
||||||
|
import {cleanup,fireEvent,render,screen,within} from '@testing-library/react';
|
||||||
|
import {afterEach,expect,it,vi} from 'vitest';
|
||||||
|
import {App} from './App';
|
||||||
|
import {initialProjects} from './data';
|
||||||
|
afterEach(()=>{cleanup();vi.restoreAllMocks()});
|
||||||
|
it('keeps only account navigation and preserves user schedules in the overview',()=>{
|
||||||
|
render(<App/>);
|
||||||
|
expect(within(screen.getByLabelText('主导航')).getAllByRole('button').map(item=>item.textContent)).toEqual(['总览','域名','DNS API','操作日志']);
|
||||||
|
expect(screen.getByRole('button',{name:'计划任务'})).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button',{name:'文件管理'})).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it('enters the selected host, scopes its tools, and returns to the user overview',()=>{
|
||||||
|
render(<App/>);const host=initialProjects[1];
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'进入主机 '+host.hostName}));
|
||||||
|
expect(screen.getByRole('heading',{name:host.hostName})).toBeInTheDocument();
|
||||||
|
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'数据库'}));
|
||||||
|
expect(screen.getAllByText(host.hostName).length).toBeGreaterThan(0);
|
||||||
|
expect(screen.queryByText(initialProjects[0].hostName)).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(within(screen.getByLabelText('主导航')).getByRole('button',{name:'文件管理'}));
|
||||||
|
expect(screen.getByRole('combobox',{name:'选择虚拟主机'}).querySelectorAll('option')).toHaveLength(1);
|
||||||
|
expect(screen.getByRole('combobox',{name:'选择虚拟主机'})).toHaveValue(String(host.id));
|
||||||
|
fireEvent.click(screen.getByRole('button',{name:'返回用户总览'}));
|
||||||
|
expect(screen.getAllByRole('button',{name:/^进入主机 /})).toHaveLength(initialProjects.length);
|
||||||
|
expect(screen.getByRole('heading',{name:'总览'})).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it('supports double-clicking a host row without changing account identity',()=>{
|
||||||
|
render(<App/>);const host=initialProjects[2];
|
||||||
|
fireEvent.doubleClick(screen.getByRole('button',{name:'进入主机 '+host.hostName}).closest('tr')!);
|
||||||
|
expect(screen.getByRole('heading',{name:host.hostName})).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button',{name:'返回用户总览'})).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('button',{name:'返回管理视图'})).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
+1
-1
@@ -235,7 +235,7 @@ export const api = {
|
|||||||
migrateSiteRuntime: (siteID: number, version: string, allowBranchChange = false, entryFile = '') => request<{ jobId: number }>(`/api/v1/admin/runtime-maintenance/sites/${siteID}`, { method: 'POST', body: JSON.stringify({ version, allowBranchChange, entryFile }) }),
|
migrateSiteRuntime: (siteID: number, version: string, allowBranchChange = false, entryFile = '') => request<{ jobId: number }>(`/api/v1/admin/runtime-maintenance/sites/${siteID}`, { method: 'POST', body: JSON.stringify({ version, allowBranchChange, entryFile }) }),
|
||||||
resumeRuntimeMaintenance: (id: number,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-maintenance/jobs/${id}/resume`+nodeQuery(nodeId), { method: 'POST' }),
|
resumeRuntimeMaintenance: (id: number,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-maintenance/jobs/${id}/resume`+nodeQuery(nodeId), { method: 'POST' }),
|
||||||
installRuntimeComponent: (runtime: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-components/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST' }),
|
installRuntimeComponent: (runtime: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-components/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST' }),
|
||||||
installRuntimeEnvironment: (runtime: string, version: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-environments/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify({ version }) }),
|
installRuntimeEnvironment: (runtime: string, version: string,nodeId?:number) => request<{ ok: boolean; jobId?:number }>(`/api/v1/admin/runtime-environments/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify({ version }) }),
|
||||||
adoptPanelSite: (id: number, input: { tenantId: number; name: string; runtime: string; version: string; runPath: string; autoSSL: boolean;planId:number },nodeId?:number) => request<{ project: APIProject; credentials: Credentials }>(`/api/v1/admin/panel-sites/${id}/adopt`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify(input) }),
|
adoptPanelSite: (id: number, input: { tenantId: number; name: string; runtime: string; version: string; runPath: string; autoSSL: boolean;planId:number },nodeId?:number) => request<{ project: APIProject; credentials: Credentials }>(`/api/v1/admin/panel-sites/${id}/adopt`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify(input) }),
|
||||||
updateDomainMetadata: (id: number, input: Record<string, unknown>) => request<void>(`/api/v1/admin/domains/${id}/metadata`, { method: 'PUT', body: JSON.stringify(input) }),
|
updateDomainMetadata: (id: number, input: Record<string, unknown>) => request<void>(`/api/v1/admin/domains/${id}/metadata`, { method: 'PUT', body: JSON.stringify(input) }),
|
||||||
provisionDomainDNS: (id: number, admin = false) => request<{ domain: DomainResource }>(`${admin ? '/api/v1/admin' : '/api/v1'}/domains/${id}/dns`, { method: 'POST' }),
|
provisionDomainDNS: (id: number, admin = false) => request<{ domain: DomainResource }>(`${admin ? '/api/v1/admin' : '/api/v1'}/domains/${id}/dns`, { method: 'POST' }),
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react';
|
import { ArrowLeft, Building2, ChevronDown, Menu, UserRound,LogOut } from 'lucide-react';
|
||||||
import { useState, type ReactNode } from 'react';
|
import { useState, type ReactNode } from 'react';
|
||||||
import { Brand } from './Brand';
|
import { Brand } from './Brand';
|
||||||
import { Sidebar } from './Sidebar';
|
import { Sidebar } from './Sidebar';
|
||||||
import {useNavigationOverlay} from './overlay';
|
import {useNavigationOverlay} from './overlay';
|
||||||
|
|
||||||
export function AppShell({ page, tenantName, displayName, hostScoped = false, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) {
|
export function AppShell({ page, tenantName, displayName, hostScoped = false, hostView = false, hostName, onBack, onNavigate, onSecurity,onLogout, children }: { page: string; tenantName: string; displayName: string; hostScoped?: boolean; hostView?: boolean; hostName?:string; onBack?:()=>void; onNavigate: (page: string) => void; onSecurity: () => void;onLogout?:()=>void; children: ReactNode }) {
|
||||||
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
const [mobileNavOpen, setMobileNavOpen] = useState(false);
|
||||||
useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
|
useNavigationOverlay(mobileNavOpen,setMobileNavOpen);
|
||||||
function navigate(pageName: string) {
|
function navigate(pageName: string) {
|
||||||
@@ -16,15 +16,15 @@ export function AppShell({ page, tenantName, displayName, hostScoped = false, on
|
|||||||
<header className="topbar">
|
<header className="topbar">
|
||||||
<button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button>
|
<button className="mobile-menu" aria-label={mobileNavOpen ? '关闭导航' : '打开导航'} aria-expanded={mobileNavOpen} onClick={() => setMobileNavOpen((value) => !value)}><Menu size={21} /></button>
|
||||||
<Brand />
|
<Brand />
|
||||||
<div className="tenant-switch"><Building2 size={17} /><span>{tenantName}</span></div>
|
<div className="tenant-switch"><Building2 size={17} /><span>{hostView || hostScoped ? hostName : tenantName}</span></div>
|
||||||
<div className="top-actions">
|
<div className="top-actions">
|
||||||
{onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null}
|
{onLogout?<button className="icon-button" aria-label="退出登录" onClick={onLogout}><LogOut size={18}/></button>:null}
|
||||||
<button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button>
|
<button className="user-menu" onClick={onSecurity} aria-label="账号安全"><span className="avatar"><UserRound size={17} /></span><span>{displayName}</span><ChevronDown size={15} /></button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
{mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null}
|
{mobileNavOpen ? <button className="mobile-nav-backdrop" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} /> : null}
|
||||||
<div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} onNavigate={navigate} /></div>
|
<div className={mobileNavOpen ? 'mobile-sidebar open' : 'mobile-sidebar'}><Sidebar page={page} hostScoped={hostScoped} hostView={hostView} onNavigate={navigate} /></div>
|
||||||
<main className="main-content">{children}</main>
|
<main className="main-content">{onBack ? <div className="host-context-bar"><span>目前主机 <b>{hostName}</b></span><button className="secondary" onClick={()=>{setMobileNavOpen(false);onBack()}}><ArrowLeft size={15}/>返回用户总览</button></div> : null}{children}</main>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -66,8 +66,8 @@ export function EnvironmentConfiguration({nodeId,nodeSelector,hideHeading=false,
|
|||||||
if (!version || !await confirm(`安装 ${item.name} ${version}?现有项目和已安装版本不会被删除。${sourceNotice}`)) return;
|
if (!version || !await confirm(`安装 ${item.name} ${version}?现有项目和已安装版本不会被删除。${sourceNotice}`)) return;
|
||||||
setBusy(`${item.name}:${version}`); setError(''); setNotice('');
|
setBusy(`${item.name}:${version}`); setError(''); setNotice('');
|
||||||
try {
|
try {
|
||||||
await api.installRuntimeEnvironment(item.name, version,nodeId);
|
const result=await api.installRuntimeEnvironment(item.name, version,nodeId);
|
||||||
setNotice(`${item.name} ${version} 安装任务已提交。`);
|
setNotice(`${item.name} ${version} 已提交 Sea vHost 任务${result.jobId?` #${result.jobId}`:''},请在下方维护任务记录查看结果。`);
|
||||||
await load();
|
await load();
|
||||||
} catch (installError) { setError(safeError(installError)); }
|
} catch (installError) { setError(safeError(installError)); }
|
||||||
finally { setBusy(''); }
|
finally { setBusy(''); }
|
||||||
|
|||||||
@@ -9,23 +9,19 @@ const resourceLabels: Record<string, string> = { file: '文件管理', database:
|
|||||||
|
|
||||||
interface OverviewProps {
|
interface OverviewProps {
|
||||||
onRefresh?:()=>void;refreshing?:boolean;
|
onRefresh?:()=>void;refreshing?:boolean;
|
||||||
pendingProjectIDs?:number[];
|
onEnterHost:(project:Project)=>void;
|
||||||
|
onSchedules?:()=>void;
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
plan: Plan;
|
plan: Plan;
|
||||||
usage: Usage;
|
usage: Usage;
|
||||||
activities: ActivityEntry[];
|
activities: ActivityEntry[];
|
||||||
hostScoped: boolean;
|
hostScoped: boolean;
|
||||||
onCreate: () => void;
|
onCreate: () => void;
|
||||||
onToggle: (id: number) => void;
|
|
||||||
onFiles: (id: number) => void;
|
|
||||||
onRunPath: (project: Project) => void;
|
|
||||||
onSites: (project: Project) => void;
|
|
||||||
onCredentials: (project: Project) => void;
|
|
||||||
canCreate: boolean;
|
canCreate: boolean;
|
||||||
onLogs?: () => void;
|
onLogs?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan, usage, activities, hostScoped, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials, canCreate, onLogs }: OverviewProps) {
|
export function Overview({ onRefresh,refreshing,projects, plan, usage, activities, hostScoped, onCreate, onEnterHost, onSchedules, canCreate, onLogs }: OverviewProps) {
|
||||||
const resources = [
|
const resources = [
|
||||||
{ label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes },
|
{ label: '存储空间', value: usage.storageBytes, limit: plan.storageBytes },
|
||||||
{ label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes },
|
{ label: '本月流量', value: usage.bandwidthBytes, limit: plan.bandwidthBytes },
|
||||||
@@ -34,14 +30,14 @@ export function Overview({ onRefresh,refreshing,pendingProjectIDs,projects, plan
|
|||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<div className="page">
|
<div className="page">
|
||||||
<PageHeader title="总览" description={hostScoped ? '管理当前虚拟主机的网站、文件与访问凭据。' : '查看当前账号下的资源使用情况和业务概览。'} actions={onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}/>
|
<PageHeader title="总览" actions={<div className="overview-actions">{onSchedules?<button className="secondary" onClick={onSchedules}>计划任务</button>:null}{onRefresh?<button className="secondary" disabled={refreshing} onClick={onRefresh}><RefreshCw size={15}/>{refreshing?'正在刷新…':'刷新状态'}</button>:null}</div>}/>
|
||||||
{!hostScoped ? <div className="metrics-grid">
|
{!hostScoped ? <div className="metrics-grid">
|
||||||
<MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} />
|
<MetricCard icon={HardDrive} label="存储空间" value={formatBytes(usage.storageBytes)} limit={formatBytes(plan.storageBytes)} percent={usagePercent(usage.storageBytes, plan.storageBytes)} />
|
||||||
<MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} />
|
<MetricCard icon={Network} label="本月流量" value={formatBytes(usage.bandwidthBytes)} limit={formatBytes(plan.bandwidthBytes)} percent={usagePercent(usage.bandwidthBytes, plan.bandwidthBytes)} />
|
||||||
<MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} />
|
<MetricCard icon={Cpu} label="进程数量" value={String(usage.processCount)} limit={String(plan.processLimit)} percent={usagePercent(usage.processCount, plan.processLimit)} />
|
||||||
<MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} />
|
<MetricCard icon={Database} label="数据库大小" value={formatBytes(usage.databaseBytes)} limit={formatBytes(plan.databaseBytes)} percent={usagePercent(usage.databaseBytes, plan.databaseBytes)} />
|
||||||
</div> : null}
|
</div> : null}
|
||||||
<ProjectTable pendingProjectIDs={pendingProjectIDs} projects={projects} canCreate={canCreate} onCreate={onCreate} onToggle={onToggle} onFiles={onFiles} onRunPath={onRunPath} onSites={onSites} onCredentials={onCredentials} />
|
<ProjectTable projects={projects} canCreate={canCreate} onCreate={onCreate} onEnterHost={onEnterHost} />
|
||||||
{!hostScoped ? <div className="lower-grid">
|
{!hostScoped ? <div className="lower-grid">
|
||||||
<section className="activity-panel">
|
<section className="activity-panel">
|
||||||
<div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div>
|
<div className="section-title"><h2>最近操作日志</h2>{onLogs?<button onClick={onLogs}>查看全部 <ArrowRight size={15} /></button>:null}</div>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {formatBytes} from '../format';
|
|||||||
import {RuntimeMark} from './UI';
|
import {RuntimeMark} from './UI';
|
||||||
const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' };
|
const statusLabels: Record<Project['status'], string> = { running: '运行中', stopped: '已停止', provisioning: '创建中', awaiting_upload: '待上传', failed: '创建失败', quota_suspended: '配额暂停' };
|
||||||
|
|
||||||
export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreate, onToggle, onFiles, onRunPath, onSites, onCredentials }: {pendingProjectIDs?:number[]; projects: Project[]; canCreate: boolean; onCreate: () => void; onToggle: (id: number) => void; onFiles: (id: number) => void; onRunPath: (project: Project) => void; onSites: (project: Project) => void; onCredentials: (project: Project) => void }) {
|
export function ProjectTable({ projects, canCreate, onCreate, onEnterHost }: { projects: Project[]; canCreate: boolean; onCreate: () => void; onEnterHost: (project:Project)=>void }) {
|
||||||
const [query, setQuery] = useState('');
|
const [query, setQuery] = useState('');
|
||||||
const deferredQuery = useDeferredValue(query);
|
const deferredQuery = useDeferredValue(query);
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
@@ -23,19 +23,19 @@ export function ProjectTable({pendingProjectIDs=[], projects, canCreate, onCreat
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-scroll">
|
<div className="table-scroll">
|
||||||
<table>
|
<table className="user-host-table">
|
||||||
<thead><tr><th>#</th><th>域名(主机名 / 目录)</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead>
|
<thead><tr><th>#</th><th>域名 / 主机</th><th>运行环境</th><th>状态</th><th>SSL 证书</th><th>本月流量</th><th>创建时间</th><th>操作</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{filtered.map((project, index) => (
|
{filtered.map((project, index) => (
|
||||||
<tr key={project.id}>
|
<tr key={project.id} title="双击进入主机管理" onDoubleClick={event=>{if(!(event.target as HTMLElement).closest('button,a,input,select'))onEnterHost(project)}}>
|
||||||
<td className="muted">{index + 1}</td>
|
<td className="muted">{index + 1}</td>
|
||||||
<td><b>{project.domain}</b><small>{project.name} · {project.hostName} · {project.path} · 发布 {project.runPath}</small></td>
|
<td><b>{project.domain}</b><small>{project.hostName} · {project.name}</small></td>
|
||||||
<td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td>
|
<td><RuntimeMark runtime={project.runtime}/>{project.runtime} {project.version}</td>
|
||||||
<td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td>
|
<td><span className={`status ${project.status}`}>{statusLabels[project.status]}</span></td>
|
||||||
<td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td>
|
<td className={project.ssl ? 'success' : 'muted'}><LockKeyhole size={14} /> {project.ssl ? '已部署' : '未部署'}</td>
|
||||||
<td>{formatBytes(project.trafficGB*1024**3)}</td>
|
<td>{formatBytes(project.trafficGB*1024**3)}</td>
|
||||||
<td className="muted">{project.createdAt}</td>
|
<td className="muted">{project.createdAt}</td>
|
||||||
<td className="row-actions"><button title={pendingProjectIDs.includes(project.id)?'正在应用主站状态':!['running','stopped'].includes(project.status)?'主站尚未完成部署或已受配额限制':undefined} disabled={pendingProjectIDs.includes(project.id)||!['running', 'stopped'].includes(project.status)} onClick={() => onToggle(project.id)}>{pendingProjectIDs.includes(project.id)?'处理中…':project.status === 'running' ? '停止' : '启动'}</button><button onClick={() => onSites(project)}>网站</button><button onClick={() => onFiles(project.id)}>文件</button><button onClick={() => onCredentials(project)}>凭据</button><button disabled={['failed', 'provisioning'].includes(project.status)} onClick={() => onRunPath(project)}>主站目录</button></td>
|
<td><button className="host-enter-button" aria-label={'进入主机 '+project.hostName} onClick={() => onEnterHost(project)}>进入主机</button></td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null}
|
{filtered.length === 0 ? <tr><td colSpan={8} className="empty-row">没有匹配的虚拟主机</td></tr> : null}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import type { ActivityEntry, Project, Site } from '../types';
|
|||||||
|
|
||||||
interface ResourceCenterProps {
|
interface ResourceCenterProps {
|
||||||
page: string;
|
page: string;
|
||||||
|
projectID?:number;
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
activities: ActivityEntry[];
|
activities: ActivityEntry[];
|
||||||
hostScoped: boolean;
|
hostScoped: boolean;
|
||||||
@@ -17,7 +18,7 @@ interface ResourceCenterProps {
|
|||||||
onNotify: (message: string) => void;
|
onNotify: (message: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ResourceCenter({ page, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) {
|
export function ResourceCenter({ page, projectID, projects, activities, hostScoped, domainApproval, live, onCredentials, onNotify }: ResourceCenterProps) {
|
||||||
const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]);
|
const demoInventory = useMemo(() => inventoryFromProjects(projects), [projects]);
|
||||||
const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory);
|
const [inventory, setInventory] = useState<ResourceInventory>(()=>live?{sites:[],domains:[],ftpAccounts:[],databases:[]}:demoInventory);
|
||||||
const [busy, setBusy] = useState(live);
|
const [busy, setBusy] = useState(live);
|
||||||
@@ -40,9 +41,15 @@ export function ResourceCenter({ page, projects, activities, hostScoped, domainA
|
|||||||
return () => { active = false; };
|
return () => { active = false; };
|
||||||
}, [demoInventory, live, page,epoch]);
|
}, [demoInventory, live, page,epoch]);
|
||||||
|
|
||||||
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={inventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />;
|
const visibleInventory = projectID ? {
|
||||||
if (page === 'databases') return <DatabasePage onRefresh={reload} items={inventory.databases} busy={busy} error={error} onCredentials={onCredentials} />;
|
sites:inventory.sites.filter(item=>item.projectId===projectID),
|
||||||
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={inventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>;
|
domains:inventory.domains.filter(item=>item.projectId===projectID),
|
||||||
|
databases:inventory.databases.filter(item=>item.projectId===projectID),
|
||||||
|
ftpAccounts:inventory.ftpAccounts.filter(item=>item.projectId===projectID),
|
||||||
|
} : inventory;
|
||||||
|
if (page === 'domains') return <DomainPage onRefresh={reload} inventory={visibleInventory} setInventory={setInventory} approval={domainApproval} live={live} busy={busy} error={error} onNotify={onNotify} />;
|
||||||
|
if (page === 'databases') return <DatabasePage onRefresh={reload} items={visibleInventory.databases} busy={busy} error={error} onCredentials={onCredentials} />;
|
||||||
|
if (page === 'ftp') return <FTPPage pausedProjectIDs={projects.filter(p=>p.status==='quota_suspended').map(p=>p.id)} onRefresh={reload} items={visibleInventory.ftpAccounts} busy={busy} error={error} onCredentials={onCredentials} live={live} onNotify={onNotify} onChanged={async()=>setInventory(await api.resources())}/>;
|
||||||
return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />;
|
return <ActivityPage activities={activities} hostScoped={hostScoped} projects={projects} live={live} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,11 +13,12 @@ const items = [
|
|||||||
['logs', '操作日志', ScrollText],
|
['logs', '操作日志', ScrollText],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export function Sidebar({ page, onNavigate, hostScoped = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean }) {
|
export function Sidebar({ page, onNavigate, hostScoped = false, hostView = false }: { page: string; onNavigate: (page: string) => void; hostScoped?: boolean; hostView?: boolean }) {
|
||||||
|
const hostNavigation = hostScoped || hostView;
|
||||||
return (
|
return (
|
||||||
<aside className="sidebar" aria-label="主导航">
|
<aside className="sidebar" aria-label="主导航">
|
||||||
<nav>
|
<nav>
|
||||||
{items.filter(([key]) => !(hostScoped && (key === 'overview'||key === 'dns'||key==='schedules'))).map(([key, label, Icon]) => (
|
{items.filter(([key]) => hostNavigation ? !['overview','dns','schedules'].includes(key) : ['overview','domains','dns','logs'].includes(key)).map(([key, label, Icon]) => (
|
||||||
<button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}>
|
<button key={key} aria-current={page === key ? "page" : undefined} className={page === key ? 'nav-item active' : 'nav-item'} onClick={() => onNavigate(key)}>
|
||||||
<Icon size={19} aria-hidden="true" />
|
<Icon size={19} aria-hidden="true" />
|
||||||
<span>{label}</span>
|
<span>{label}</span>
|
||||||
|
|||||||
@@ -34,6 +34,36 @@
|
|||||||
.sso-identity small { color: var(--muted); overflow-wrap: anywhere; }
|
.sso-identity small { color: var(--muted); overflow-wrap: anywhere; }
|
||||||
.sso-create-actions { display: grid; gap: 14px; margin-top: 14px; }
|
.sso-create-actions { display: grid; gap: 14px; margin-top: 14px; }
|
||||||
.sso-create-actions .text-button { background: none; border: none; color: var(--muted); }
|
.sso-create-actions .text-button { background: none; border: none; color: var(--muted); }
|
||||||
|
.host-context-bar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:14px 32px; border-bottom:1px solid var(--line); background:var(--surface,#fff); color:var(--muted); font-size:13px; }
|
||||||
|
.host-context-bar > span { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.host-context-bar b { color:var(--ink); font-weight:600; }
|
||||||
|
.host-context-bar button { flex:0 0 auto; min-height:34px; white-space:nowrap; display:inline-flex; align-items:center; gap:6px; }
|
||||||
|
.overview-actions { display:flex; flex-wrap:nowrap; gap:10px; }
|
||||||
|
.overview-actions > button { white-space:nowrap; flex:0 0 auto; }
|
||||||
|
.table-panel .user-host-table { min-width:960px; }
|
||||||
|
.user-host-table td:nth-child(2) { max-width:300px; }
|
||||||
|
.user-host-table td:nth-child(2) :is(b,small) { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.user-host-table td:last-child,.user-host-table th:last-child { position:sticky; right:0; width:116px; background:var(--surface,#fff); box-shadow:-8px 0 12px -12px #526580; z-index:1; white-space:nowrap; }
|
||||||
|
.user-host-table tbody tr:hover td:last-child { background:var(--surface-subtle,#fafcff); }
|
||||||
|
.host-enter-button { display:inline-flex; align-items:center; min-height:32px; padding:5px 10px; color:var(--blue-strong); border:1px solid var(--line); border-radius:6px; background:var(--surface,#fff); white-space:nowrap; }
|
||||||
|
.host-enter-button:hover { background:var(--blue-soft); border-color:var(--blue); }
|
||||||
|
.table-scroll td > .row-actions,.admin-table-v2 td > .row-actions { flex-wrap:nowrap; width:max-content; max-width:none; }
|
||||||
|
td.row-actions { display:table-cell; white-space:nowrap; }
|
||||||
|
.row-actions > button { flex-shrink:0; white-space:nowrap; }
|
||||||
|
.host-row-actions { display:flex; flex-wrap:nowrap; gap:12px; min-width:max-content; }
|
||||||
|
.host-row-actions .danger-text { border-left:1px solid var(--line); padding-left:12px; }
|
||||||
|
.sites-row .site-actions { flex-wrap:nowrap; min-width:0; max-width:100%; overflow-x:auto; overscroll-behavior-x:contain; scrollbar-width:thin; padding-bottom:5px; }
|
||||||
|
@media (max-width:700px) {
|
||||||
|
.host-context-bar { padding:12px 16px; gap:8px; }
|
||||||
|
.host-context-bar button { padding:6px 9px; font-size:12px; }
|
||||||
|
.host-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:9px; }
|
||||||
|
.host-actions button { width:auto; justify-content:center; min-width:0; padding:9px 6px; white-space:nowrap; }
|
||||||
|
.host-info-card > header { flex-wrap:nowrap; gap:8px; }
|
||||||
|
.host-info-card > header > div { gap:7px; min-width:0; }
|
||||||
|
.host-info-card > header > div h2 { font-size:14px; overflow-wrap:anywhere; }
|
||||||
|
.host-info-card > header > button { flex-shrink:0; padding:7px 9px; white-space:nowrap; }
|
||||||
|
.table-panel .panel-toolbar { align-items:flex-start; }
|
||||||
|
}
|
||||||
@media (min-width: 980px) {
|
@media (min-width: 980px) {
|
||||||
.dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; }
|
.dns-credential-row { grid-template-columns: minmax(160px,1.2fr) 110px minmax(150px,1fr) 140px minmax(258px,auto); gap: 16px; }
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user