From 3d71a2b7f8d86edb52b2f0dded6d4a35ce657ea2 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Sat, 21 Nov 2026 13:31:52 +0800 Subject: [PATCH 1/2] test: keep the full suite green on Windows --- internal/api/auth_test.go | 9 +++++++++ internal/api/update_test.go | 2 +- internal/executor/pool_test.go | 8 +++++++- internal/providers/qoder/worker_test.go | 9 +++++---- internal/runtime/manager_test.go | 4 ++-- internal/store/backup_test.go | 5 ++++- internal/store/store_test.go | 4 ++++ 7 files changed, 32 insertions(+), 9 deletions(-) diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index cfa1b3c2..506c1fc5 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -63,6 +63,7 @@ func TestManagementRoutesRequireAPIKey(t *testing.T) { ProxyAPIKey: "secret", QoderHome: t.TempDir(), }) + defer srv.Close() h := srv.Handler() for _, path := range []string{ @@ -492,6 +493,7 @@ func TestLegacyDiagnosticRoutesAreRemoved(t *testing.T) { ProxyAPIKey: "secret", QoderHome: t.TempDir(), }) + defer srv.Close() for _, target := range []struct { method string @@ -521,6 +523,7 @@ func TestSPAFallbackServesIndexForClientRoutes(t *testing.T) { ProxyAPIKey: "secret", QoderHome: t.TempDir(), }) + defer srv.Close() req := httptest.NewRequest(http.MethodGet, "/auth", nil) rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) @@ -543,6 +546,7 @@ func TestOverviewWithAPIKeyDoesNotLeakWorkerProxyFailureAs200Auth(t *testing.T) ProxyAPIKey: "secret", QoderHome: t.TempDir(), }) + defer srv.Close() req := httptest.NewRequest(http.MethodGet, "/api/overview", nil) req.Header.Set("Authorization", "Bearer secret") rec := httptest.NewRecorder() @@ -573,6 +577,7 @@ func TestSPAFallbackServesAccounts(t *testing.T) { ProxyAPIKey: "secret", QoderHome: t.TempDir(), }) + defer srv.Close() req := httptest.NewRequest(http.MethodGet, "/accounts", nil) rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) @@ -588,6 +593,7 @@ func TestSPAFallbackServesLogin(t *testing.T) { ProxyAPIKey: "secret", QoderHome: t.TempDir(), }) + defer srv.Close() req := httptest.NewRequest(http.MethodGet, "/login", nil) rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) @@ -637,6 +643,7 @@ func TestAccountsAPICreatesAndListsDisabledAccount(t *testing.T) { QoderHome: t.TempDir(), DataDir: dataDir, }) + defer srv.Close() body := bytes.NewBufferString(`{"name":"Work","enabled":false,"max_inflight":5,"drop_system_prompt":false}`) req := httptest.NewRequest(http.MethodPost, "/api/accounts", body) req.Header.Set("Authorization", "Bearer secret") @@ -678,6 +685,7 @@ func TestAccountsAPIImportsNativeCredential(t *testing.T) { QoderHome: t.TempDir(), DataDir: t.TempDir(), }) + defer srv.Close() body := bytes.NewBufferString(`{"format":"qoder-native-v1","name":"Imported","enabled":false,"user_blob":"Y2lwaGVy","machine_id":"machine-1"}`) req := httptest.NewRequest(http.MethodPost, "/api/accounts/import", body) req.Header.Set("Authorization", "Bearer secret") @@ -700,6 +708,7 @@ func TestAccountsAPIUpdatesExportsAndDeletesAccount(t *testing.T) { QoderHome: t.TempDir(), DataDir: t.TempDir(), }) + defer srv.Close() importBody := bytes.NewBufferString(`{"format":"qoder-native-v1","name":"Imported","enabled":false,"user_blob":"Y2lwaGVy","machine_id":"machine-1"}`) req := httptest.NewRequest(http.MethodPost, "/api/accounts/import", importBody) req.Header.Set("Authorization", "Bearer secret") diff --git a/internal/api/update_test.go b/internal/api/update_test.go index a1f8b8ec..ca1585d5 100644 --- a/internal/api/update_test.go +++ b/internal/api/update_test.go @@ -126,7 +126,7 @@ func TestSystemUpdateBacksUpSQLiteBeforeSubmittingNextVersion(t *testing.T) { if request.CurrentVersion != "v0.2.1" || request.TargetVersion != "v0.2.2" { t.Fatalf("request = %+v", request) } - if filepath.Dir(request.BackupPath) != "/data/backups" { + if filepath.Dir(request.BackupPath) != filepath.Join("/data", "backups") { t.Fatalf("backup path = %q", request.BackupPath) } backupPath := filepath.Join(dataDir, "backups", filepath.Base(request.BackupPath)) diff --git a/internal/executor/pool_test.go b/internal/executor/pool_test.go index 4805878f..b6c93013 100644 --- a/internal/executor/pool_test.go +++ b/internal/executor/pool_test.go @@ -342,6 +342,9 @@ func TestRepeatedFailuresBackOff(t *testing.T) { p.MarkClassified("a", Classified{Kind: KindRateLimit, Cooldown: base, Failover: true}) first, _ := p.ByID("a") + // Windows timers can resolve coarser than the two consecutive calls; let + // the clock advance so the extended deadline is observable. + time.Sleep(10 * time.Millisecond) p.MarkClassified("a", Classified{Kind: KindRateLimit, Cooldown: base, Failover: true}) second, _ := p.ByID("a") if !second.DownUntil.After(first.DownUntil) { @@ -452,7 +455,10 @@ func TestBackoffResetsOnKindChange(t *testing.T) { p.MarkClassified("a", Classified{Kind: KindRateLimit, Cooldown: base, Failover: true}) first, _ := p.ByID("a") // Different kind with the same base cooldown: ladder restarts, so the - // cooldown must not exceed (and should equal) the base. + // cooldown must not exceed (and should equal) the base. Wait for the + // clock to advance so Windows' coarser timer cannot return the same + // instant for both calls. + time.Sleep(10 * time.Millisecond) p.MarkClassified("a", Classified{Kind: KindAuth, Cooldown: base, Failover: true}) second, _ := p.ByID("a") if !second.DownUntil.After(first.DownUntil) { diff --git a/internal/providers/qoder/worker_test.go b/internal/providers/qoder/worker_test.go index c5bbf8ce..734a9835 100644 --- a/internal/providers/qoder/worker_test.go +++ b/internal/providers/qoder/worker_test.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "path/filepath" "strings" "sync/atomic" "testing" @@ -210,14 +211,14 @@ func TestRuntimeSpecSelectsCNCLIAndConfigDir(t *testing.T) { if err != nil { t.Fatal(err) } - if global.CLIPath != "/opt/qodercli.js" || global.Site != "global" || global.ConfigDir != "/run/acc-g/.qoder" || global.ConfigEnv != "QODER_CONFIG_DIR" { + if global.CLIPath != "/opt/qodercli.js" || global.Site != "global" || global.ConfigDir != filepath.Join("/run/acc-g", ".qoder") || global.ConfigEnv != "QODER_CONFIG_DIR" { t.Fatalf("global spec = %+v", global) } cn, err := RuntimeSpec("/opt/qodercli.js", "/opt/qoderclicn.js", "cn", "/run/acc-c") if err != nil { t.Fatal(err) } - if cn.CLIPath != "/opt/qoderclicn.js" || cn.Site != "cn" || cn.ConfigDir != "/run/acc-c/.qoder-cn" || cn.ConfigEnv != "QODERCN_CONFIG_DIR" { + if cn.CLIPath != "/opt/qoderclicn.js" || cn.Site != "cn" || cn.ConfigDir != filepath.Join("/run/acc-c", ".qoder-cn") || cn.ConfigEnv != "QODERCN_CONFIG_DIR" { t.Fatalf("cn spec = %+v", cn) } if _, err := RuntimeSpec("/opt/qodercli.js", "", "cn", "/run/acc-c"); err == nil { @@ -242,7 +243,7 @@ func TestStarterEnvSetsRegionAndProxy(t *testing.T) { values[key] = value } } - if values["QODER_SITE"] != "global" || values["QODER_HOME"] != "/tmp/home/.qoder" || values["QODERCLI_JS"] != "/usr/lib/qodercli.js" { + if values["QODER_SITE"] != "global" || values["QODER_HOME"] != filepath.Join("/tmp/home", ".qoder") || values["QODERCLI_JS"] != "/usr/lib/qodercli.js" { t.Fatalf("env = %+v", values) } if values["PROXY_API_KEY"] != "k" || values["WORKER_PORT"] != "32100" { @@ -267,7 +268,7 @@ func TestStarterEnvSetsRegionAndProxy(t *testing.T) { cnValues[key] = value } } - if cnValues["QODER_SITE"] != "cn" || cnValues["QODERCN_CONFIG_DIR"] != "/tmp/cn/.qoder-cn" || cnValues["QODERCLI_JS"] != "/usr/lib/qoderclicn.js" { + if cnValues["QODER_SITE"] != "cn" || cnValues["QODERCN_CONFIG_DIR"] != filepath.Join("/tmp/cn", ".qoder-cn") || cnValues["QODERCLI_JS"] != "/usr/lib/qoderclicn.js" { t.Fatalf("cn env = %+v", cnValues) } } diff --git a/internal/runtime/manager_test.go b/internal/runtime/manager_test.go index ef36a4bc..e3ca3377 100644 --- a/internal/runtime/manager_test.go +++ b/internal/runtime/manager_test.go @@ -364,14 +364,14 @@ func TestQoderRuntimeSpecSelectsCNCLIAndConfigDir(t *testing.T) { if err != nil { t.Fatal(err) } - if globalPath != "/opt/qodercli.js" || globalSite != "global" || globalDir != "/run/acc-g/.qoder" || globalEnv != "QODER_CONFIG_DIR" { + if globalPath != "/opt/qodercli.js" || globalSite != "global" || globalDir != filepath.Join("/run/acc-g", ".qoder") || globalEnv != "QODER_CONFIG_DIR" { t.Fatalf("global spec path=%s site=%s dir=%s env=%s", globalPath, globalSite, globalDir, globalEnv) } cnPath, cnSite, cnDir, cnEnv, err := accountruntime.QoderRuntimeSpec(cfg, accounts.Account{ProviderRegion: "cn"}, "/run/acc-c") if err != nil { t.Fatal(err) } - if cnPath != "/opt/qoderclicn.js" || cnSite != "cn" || cnDir != "/run/acc-c/.qoder-cn" || cnEnv != "QODERCN_CONFIG_DIR" { + if cnPath != "/opt/qoderclicn.js" || cnSite != "cn" || cnDir != filepath.Join("/run/acc-c", ".qoder-cn") || cnEnv != "QODERCN_CONFIG_DIR" { t.Fatalf("cn spec path=%s site=%s dir=%s env=%s", cnPath, cnSite, cnDir, cnEnv) } if _, _, _, _, err := accountruntime.QoderRuntimeSpec(accountruntime.ManagerConfig{QoderCLIPath: "/opt/qodercli.js"}, accounts.Account{ProviderRegion: "cn"}, "/run/acc-c"); err == nil { diff --git a/internal/store/backup_test.go b/internal/store/backup_test.go index 3bb9e932..7442453b 100644 --- a/internal/store/backup_test.go +++ b/internal/store/backup_test.go @@ -8,6 +8,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "os" "path/filepath" + "runtime" "testing" "time" @@ -47,7 +48,9 @@ func TestStoreBackupCreatesConsistentSQLiteSnapshot(t *testing.T) { if err != nil { t.Fatal(err) } - if info.Mode().Perm() != 0o600 { + // Windows reports synthesized permission bits instead of Unix modes; the + // 0600 contract is enforced by os.Chmod on Unix hosts. + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { t.Fatalf("backup mode = %o, want 600", info.Mode().Perm()) } diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 46c2347f..3f6ff791 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -580,6 +580,7 @@ func TestCooldownsSurviveReopen(t *testing.T) { if err != nil { t.Fatal(err) } + defer store.Close() account, err := store.Create(ctx, accounts.CreateAccount{Name: "Work", Enabled: true, MaxInFlight: 4}) if err != nil { t.Fatal(err) @@ -599,6 +600,7 @@ func TestCooldownsSurviveReopen(t *testing.T) { if err != nil { t.Fatal(err) } + defer reopened.Close() loaded, err := reopened.LoadCooldowns(ctx) if err != nil { t.Fatal(err) @@ -631,6 +633,7 @@ func TestSaveCooldownsReplacesStaleRows(t *testing.T) { if err != nil { t.Fatal(err) } + defer store.Close() account, err := store.Create(ctx, accounts.CreateAccount{Name: "Work", Enabled: true}) if err != nil { t.Fatal(err) @@ -662,6 +665,7 @@ func TestLoadCooldownsPrunesExpired(t *testing.T) { if err != nil { t.Fatal(err) } + defer store.Close() account, err := store.Create(ctx, accounts.CreateAccount{Name: "Work", Enabled: true}) if err != nil { t.Fatal(err) From f95041652ec4b6e667a2fcc067f70fd7fe58d64b Mon Sep 17 00:00:00 2001 From: guyu233 Date: Sat, 21 Nov 2026 13:32:04 +0800 Subject: [PATCH 2/2] perf(console): cut first-screen payload and request stats scans Lazy-load every console page, replace the shell's HeroUI controls with dependency-free primitives, load the update dialog on demand, and poll resources/live data less often. The embedded console now preloads only the entry, jsx-runtime and GSAP instead of the HeroUI shared chunk. Also summarize request logs with one SELECT and aggregate in Go; the 20k-row local benchmark drops from ~227 ms to ~57 ms per call. --- changelog/unreleased/console-lazy-routes.md | 15 + frontend/src/App.tsx | 58 +-- .../src/components/access/ChatComposer.tsx | 3 +- .../src/components/account/AccountCard.tsx | 9 +- frontend/src/components/layout/AppHeader.tsx | 77 ++-- frontend/src/components/layout/AppLayout.tsx | 14 +- frontend/src/components/layout/AppSidebar.tsx | 103 +++-- .../components/layout/SidebarUpdateDialog.tsx | 60 +++ .../components/layout/SidebarUpdateItem.tsx | 64 ++- .../overview/InflightDepthChart.tsx | 120 ++++++ .../components/overview/InflightLiveCard.tsx | 141 +------ .../src/components/overview/LiveSparkline.tsx | 50 ++- .../src/components/overview/LiveStrip.tsx | 10 +- .../src/components/overview/TrafficChart.tsx | 6 +- frontend/src/components/ui/PageSkeletons.tsx | 6 +- frontend/src/components/ui/RouteFallback.tsx | 18 + frontend/src/components/ui/ShellControls.tsx | 76 ++++ frontend/src/components/ui/SkeletonBlock.tsx | 3 + frontend/src/hooks/useLive.ts | 6 +- frontend/src/hooks/useSharedClock.ts | 33 ++ frontend/src/index.css | 27 ++ frontend/src/pages/LogsPage.tsx | 2 +- frontend/src/pages/OverviewPage.tsx | 44 +- frontend/vite.config.ts | 7 + internal/store/request_logs.go | 345 +--------------- internal/store/request_stats_singlepass.go | 386 ++++++++++++++++++ .../static/assets/AccessPage-CwOZKxNi.js | 10 + .../static/assets/AccountsPage-CdI-P2Hp.js | 1 + .../webui/static/assets/AreaChart-DIVZvd7t.js | 1 + .../static/assets/CaiaiSoftLink-BIa82KWH.js | 1 + .../static/assets/CartesianChart-C6e6Xv4M.js | 32 ++ .../static/assets/CartesianGrid-C189o99f.js | 22 + .../static/assets/CartesianGrid-DKe6ds4c.js | 22 - .../webui/static/assets/Check.es-B3dlSekP.js | 1 + .../webui/static/assets/Checkbox-nLstOpHL.js | 1 + .../static/assets/CompactSwitch-BYUIxLVe.js | 1 + .../static/assets/ConfirmDialog-JfQPGzLq.js | 1 + .../webui/static/assets/CostChart-BjtPc4sZ.js | 1 + .../webui/static/assets/CostChart-DPlno3Ip.js | 1 - .../webui/static/assets/Dialog-Xv6OwTGL.js | 5 + .../static/assets/EmptyPanel-DhxBFmL7.js | 1 + .../static/assets/FilterSelect-CO_Qvq7c.js | 1 + .../static/assets/FilterToggle-BabPVnUu.js | 1 + .../webui/static/assets/FormRow-CEEf3Vvm.js | 1 + .../assets/InflightDepthChart-yjk-xcdS.js | 1 + .../assets/InflightLiveCard-BPD_Sodv.js | 104 +++++ .../webui/static/assets/KeysPage-YViMviZq.js | 1 + .../static/assets/LatencyStats-CniqHkVo.js | 1 + .../static/assets/LiveSparkline-DeHuN5vF.js | 1 - .../webui/static/assets/LoginPage-goLWSJL8.js | 1 + .../webui/static/assets/LogsPage-PPImeI90.js | 1 + .../static/assets/OverviewPage-C2ukBBEO.js | 2 + .../webui/static/assets/PageAlert-BPYnzn-V.js | 7 + .../static/assets/PageSkeletons-BA1c1rsM.js | 1 + .../webui/static/assets/Plus.es-CETcjypp.js | 1 + .../static/assets/ProviderMark-DiGxqtb_.js | 1 + .../static/assets/ProvidersPage-DURVbBKL.js | 1 + .../static/assets/ReferenceArea-C1bTOHZk.js | 1 + .../webui/static/assets/SearchBar-duj7XPNM.js | 1 + .../static/assets/ShieldCheck.es-CGv4Cm6O.js | 1 + .../assets/SidebarUpdateDialog-Do_JpDsS.js | 1 + .../static/assets/SystemPage-Bxez10TF.js | 1 + .../static/assets/TimeRangePicker-DojkkHhz.js | 1 + .../static/assets/TrafficChart-DnkS8mnP.js | 1 + .../static/assets/TrafficChart-ItayYtg3.js | 1 - .../static/assets/TrashSimple.es-C818dJNb.js | 1 + .../static/assets/UpdateControls-BDX7trI8.js | 4 + .../webui/static/assets/UsagePage-Bj72rLJj.js | 2 + .../webui/static/assets/accordion-W7scJmtG.js | 1 + .../webui/static/assets/account-BJHim5bc.js | 1 + .../webui/static/assets/assertion-BLQtDfw6.js | 1 + .../webui/static/assets/clipboard-6u9IXVCz.js | 1 + .../static/assets/close-button-BCBkrQI6.js | 1 + .../collection-prop-injection-B_qU8pO9.js | 1 + .../webui/static/assets/format-w9AnkY-Z.js | 1 + internal/webui/static/assets/gsap-C3sDxib7.js | 1 + ...{index-Ctz5Puzt.css => index-BShBplZp.css} | 2 +- .../webui/static/assets/index-DBgREfbP.js | 13 + .../webui/static/assets/index-mT6oJ2cL.js | 168 -------- .../static/assets/jsx-runtime-DbPMZkE_.js | 1 + internal/webui/static/assets/keys-CG4m5nFc.js | 1 + .../webui/static/assets/label-CPirMxP_.js | 1 + .../webui/static/assets/list-box-DRRVPuzD.js | 1 + .../webui/static/assets/logsLink-8KJ2EcQw.js | 1 + .../webui/static/assets/modal-CyO88n28.js | 1 + .../static/assets/number-field-EsSoaiqG.js | 1 + .../webui/static/assets/provider-gHnttGKq.js | 1 + .../static/assets/search-field-DpxzrBqp.js | 1 + .../webui/static/assets/select-BWETLI2p.js | 1 + internal/webui/static/assets/shim-B6HbdSKE.js | 1 + .../webui/static/assets/table-BVEdAjdq.js | 1 + internal/webui/static/assets/tabs-Wot3KmtE.js | 1 + .../webui/static/assets/textfield-BFr8if3H.js | 1 + .../webui/static/assets/textfield-BK1CXcJM.js | 1 + .../assets/toggle-button-group-BonAn8SP.js | 1 + .../webui/static/assets/tooltip-CKvhWcox.js | 1 + .../assets/use-css-variable-DV5AhwxN.js | 1 + .../assets/use-has-text-slot-DDCQ1hKo.js | 1 + .../assets/useApiKeyOptions-Bw0wUGwa.js | 1 + .../assets/useHasTabbableChild-BwM8fyYT.js | 1 + .../static/assets/useSpinButton-B0tsFWSk.js | 1 + .../static/assets/useTextField-BQDgyih9.js | 1 + .../webui/static/assets/useToggle-ChNHFGWe.js | 1 + .../static/assets/useUpdateEffect-CuR0JABJ.js | 1 + internal/webui/static/index.html | 6 +- 105 files changed, 1270 insertions(+), 877 deletions(-) create mode 100644 changelog/unreleased/console-lazy-routes.md create mode 100644 frontend/src/components/layout/SidebarUpdateDialog.tsx create mode 100644 frontend/src/components/overview/InflightDepthChart.tsx create mode 100644 frontend/src/components/ui/RouteFallback.tsx create mode 100644 frontend/src/components/ui/ShellControls.tsx create mode 100644 frontend/src/components/ui/SkeletonBlock.tsx create mode 100644 frontend/src/hooks/useSharedClock.ts create mode 100644 internal/store/request_stats_singlepass.go create mode 100644 internal/webui/static/assets/AccessPage-CwOZKxNi.js create mode 100644 internal/webui/static/assets/AccountsPage-CdI-P2Hp.js create mode 100644 internal/webui/static/assets/AreaChart-DIVZvd7t.js create mode 100644 internal/webui/static/assets/CaiaiSoftLink-BIa82KWH.js create mode 100644 internal/webui/static/assets/CartesianChart-C6e6Xv4M.js create mode 100644 internal/webui/static/assets/CartesianGrid-C189o99f.js delete mode 100644 internal/webui/static/assets/CartesianGrid-DKe6ds4c.js create mode 100644 internal/webui/static/assets/Check.es-B3dlSekP.js create mode 100644 internal/webui/static/assets/Checkbox-nLstOpHL.js create mode 100644 internal/webui/static/assets/CompactSwitch-BYUIxLVe.js create mode 100644 internal/webui/static/assets/ConfirmDialog-JfQPGzLq.js create mode 100644 internal/webui/static/assets/CostChart-BjtPc4sZ.js delete mode 100644 internal/webui/static/assets/CostChart-DPlno3Ip.js create mode 100644 internal/webui/static/assets/Dialog-Xv6OwTGL.js create mode 100644 internal/webui/static/assets/EmptyPanel-DhxBFmL7.js create mode 100644 internal/webui/static/assets/FilterSelect-CO_Qvq7c.js create mode 100644 internal/webui/static/assets/FilterToggle-BabPVnUu.js create mode 100644 internal/webui/static/assets/FormRow-CEEf3Vvm.js create mode 100644 internal/webui/static/assets/InflightDepthChart-yjk-xcdS.js create mode 100644 internal/webui/static/assets/InflightLiveCard-BPD_Sodv.js create mode 100644 internal/webui/static/assets/KeysPage-YViMviZq.js create mode 100644 internal/webui/static/assets/LatencyStats-CniqHkVo.js delete mode 100644 internal/webui/static/assets/LiveSparkline-DeHuN5vF.js create mode 100644 internal/webui/static/assets/LoginPage-goLWSJL8.js create mode 100644 internal/webui/static/assets/LogsPage-PPImeI90.js create mode 100644 internal/webui/static/assets/OverviewPage-C2ukBBEO.js create mode 100644 internal/webui/static/assets/PageAlert-BPYnzn-V.js create mode 100644 internal/webui/static/assets/PageSkeletons-BA1c1rsM.js create mode 100644 internal/webui/static/assets/Plus.es-CETcjypp.js create mode 100644 internal/webui/static/assets/ProviderMark-DiGxqtb_.js create mode 100644 internal/webui/static/assets/ProvidersPage-DURVbBKL.js create mode 100644 internal/webui/static/assets/ReferenceArea-C1bTOHZk.js create mode 100644 internal/webui/static/assets/SearchBar-duj7XPNM.js create mode 100644 internal/webui/static/assets/ShieldCheck.es-CGv4Cm6O.js create mode 100644 internal/webui/static/assets/SidebarUpdateDialog-Do_JpDsS.js create mode 100644 internal/webui/static/assets/SystemPage-Bxez10TF.js create mode 100644 internal/webui/static/assets/TimeRangePicker-DojkkHhz.js create mode 100644 internal/webui/static/assets/TrafficChart-DnkS8mnP.js delete mode 100644 internal/webui/static/assets/TrafficChart-ItayYtg3.js create mode 100644 internal/webui/static/assets/TrashSimple.es-C818dJNb.js create mode 100644 internal/webui/static/assets/UpdateControls-BDX7trI8.js create mode 100644 internal/webui/static/assets/UsagePage-Bj72rLJj.js create mode 100644 internal/webui/static/assets/accordion-W7scJmtG.js create mode 100644 internal/webui/static/assets/account-BJHim5bc.js create mode 100644 internal/webui/static/assets/assertion-BLQtDfw6.js create mode 100644 internal/webui/static/assets/clipboard-6u9IXVCz.js create mode 100644 internal/webui/static/assets/close-button-BCBkrQI6.js create mode 100644 internal/webui/static/assets/collection-prop-injection-B_qU8pO9.js create mode 100644 internal/webui/static/assets/format-w9AnkY-Z.js create mode 100644 internal/webui/static/assets/gsap-C3sDxib7.js rename internal/webui/static/assets/{index-Ctz5Puzt.css => index-BShBplZp.css} (84%) create mode 100644 internal/webui/static/assets/index-DBgREfbP.js delete mode 100644 internal/webui/static/assets/index-mT6oJ2cL.js create mode 100644 internal/webui/static/assets/jsx-runtime-DbPMZkE_.js create mode 100644 internal/webui/static/assets/keys-CG4m5nFc.js create mode 100644 internal/webui/static/assets/label-CPirMxP_.js create mode 100644 internal/webui/static/assets/list-box-DRRVPuzD.js create mode 100644 internal/webui/static/assets/logsLink-8KJ2EcQw.js create mode 100644 internal/webui/static/assets/modal-CyO88n28.js create mode 100644 internal/webui/static/assets/number-field-EsSoaiqG.js create mode 100644 internal/webui/static/assets/provider-gHnttGKq.js create mode 100644 internal/webui/static/assets/search-field-DpxzrBqp.js create mode 100644 internal/webui/static/assets/select-BWETLI2p.js create mode 100644 internal/webui/static/assets/shim-B6HbdSKE.js create mode 100644 internal/webui/static/assets/table-BVEdAjdq.js create mode 100644 internal/webui/static/assets/tabs-Wot3KmtE.js create mode 100644 internal/webui/static/assets/textfield-BFr8if3H.js create mode 100644 internal/webui/static/assets/textfield-BK1CXcJM.js create mode 100644 internal/webui/static/assets/toggle-button-group-BonAn8SP.js create mode 100644 internal/webui/static/assets/tooltip-CKvhWcox.js create mode 100644 internal/webui/static/assets/use-css-variable-DV5AhwxN.js create mode 100644 internal/webui/static/assets/use-has-text-slot-DDCQ1hKo.js create mode 100644 internal/webui/static/assets/useApiKeyOptions-Bw0wUGwa.js create mode 100644 internal/webui/static/assets/useHasTabbableChild-BwM8fyYT.js create mode 100644 internal/webui/static/assets/useSpinButton-B0tsFWSk.js create mode 100644 internal/webui/static/assets/useTextField-BQDgyih9.js create mode 100644 internal/webui/static/assets/useToggle-ChNHFGWe.js create mode 100644 internal/webui/static/assets/useUpdateEffect-CuR0JABJ.js diff --git a/changelog/unreleased/console-lazy-routes.md b/changelog/unreleased/console-lazy-routes.md new file mode 100644 index 00000000..6dc2d778 --- /dev/null +++ b/changelog/unreleased/console-lazy-routes.md @@ -0,0 +1,15 @@ +### English + +- Split console pages into per-route chunks so the first screen loads less JavaScript; rejected chat attachments now use the console toast instead of a browser alert. +- The overview resource panel now follows the backend's 30s sample cadence instead of polling every 5s, account countdowns share one timer, and runtime logs stop polling while the tab is hidden. +- Request statistics now stream the window once instead of running about ten SQL scans; the local 20k-row benchmark drops from ~227 ms to ~57 ms per call. +- The expanded live card now polls at 800ms instead of 400ms. The 60s concurrency sparkline is hand-drawn SVG, and the inflight depth chart loads only when expanded, keeping the 316 kB chart bundle out of the default console preload. +- The console shell no longer imports HeroUI: header and sidebar controls are dependency-free, the mobile drawer is native, and the update dialog loads on demand. Together with route-level lazy pages, the entry chunk is 422 kB (134.8 kB gzip) and preloads only `jsx-runtime` (12 kB) and GSAP (93 kB), down from the previous 461 + 239 + 94 + 13 kB preload group. + +### 中文 + +- 控制台页面按路由拆包,首屏加载的 JavaScript 更少;聊天不支持的文件改用控制台提示,不再弹浏览器 alert。 +- 概览资源面板改为对齐后端 30 秒采样节奏,不再每 5 秒重复请求;账号冷却倒计时共用一个定时器;运行日志在标签页隐藏时停止轮询。 +- 请求统计改为单次扫描窗口并在 Go 内聚合,本机 20,000 行基准从约 227 ms/次降到约 57 ms/次。 +- 展开态实时卡片轮询从 400ms 放慢到 800ms;60 秒并发曲线改为手绘 SVG,展开后才加载 inflight 深度图表,316 kB 图表包不再进入控制台默认预加载。 +- 控制台外壳不再导入 HeroUI:顶栏与侧栏控件改为无依赖原生组件,移动抽屉改为原生实现,版本更新弹窗点击时才加载。配合路由级拆包,入口为 422 kB(gzip 134.8 kB),首屏仅预加载 `jsx-runtime`(12 kB)与 GSAP(93 kB),此前首屏组合为 461 + 239 + 94 + 13 kB。 \ No newline at end of file diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 30418f5b..be670980 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,19 +1,23 @@ +import { Suspense, lazy } from 'react' import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom' import { AppLayout } from '@/components/layout/AppLayout' import { RequireAuth } from '@/components/RequireAuth' +import { RouteFallback } from '@/components/ui/RouteFallback' import { ApiKeyProvider } from '@/hooks/useApiKey' import { I18nProvider } from '@/hooks/useI18n' import { OverviewProvider } from '@/hooks/useOverview' import { ThemeProvider } from '@/hooks/useTheme' -import { OverviewPage } from '@/pages/OverviewPage' -import { ProvidersPage } from '@/pages/ProvidersPage' -import { AccessPage } from '@/pages/AccessPage' -import { AccountsPage } from '@/pages/AccountsPage' -import { LoginPage } from '@/pages/LoginPage' -import { SystemPage } from '@/pages/SystemPage' -import { LogsPage } from '@/pages/LogsPage' -import { UsagePage } from '@/pages/UsagePage' -import { KeysPage } from '@/pages/KeysPage' + +const LoginPage = lazy(() => import('@/pages/LoginPage').then((module) => ({ default: module.LoginPage }))) + +const OverviewPage = lazy(() => import('@/pages/OverviewPage').then((module) => ({ default: module.OverviewPage }))) +const ProvidersPage = lazy(() => import('@/pages/ProvidersPage').then((module) => ({ default: module.ProvidersPage }))) +const AccessPage = lazy(() => import('@/pages/AccessPage').then((module) => ({ default: module.AccessPage }))) +const AccountsPage = lazy(() => import('@/pages/AccountsPage').then((module) => ({ default: module.AccountsPage }))) +const SystemPage = lazy(() => import('@/pages/SystemPage').then((module) => ({ default: module.SystemPage }))) +const LogsPage = lazy(() => import('@/pages/LogsPage').then((module) => ({ default: module.LogsPage }))) +const UsagePage = lazy(() => import('@/pages/UsagePage').then((module) => ({ default: module.UsagePage }))) +const KeysPage = lazy(() => import('@/pages/KeysPage').then((module) => ({ default: module.KeysPage }))) export default function App() { return ( @@ -22,24 +26,26 @@ export default function App() { - - } /> - }> - }> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> + }> + + } /> + }> + }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + - - + + diff --git a/frontend/src/components/access/ChatComposer.tsx b/frontend/src/components/access/ChatComposer.tsx index 1edb6adf..107c885b 100644 --- a/frontend/src/components/access/ChatComposer.tsx +++ b/frontend/src/components/access/ChatComposer.tsx @@ -2,6 +2,7 @@ import { useRef, type KeyboardEvent, type ReactNode } from 'react' import { Button, Label, ListBox, Select, TextArea } from '@heroui/react' import { FileText, PaperPlaneTilt, Plus, Stop, X } from '@phosphor-icons/react' import { useI18n } from '@/hooks/useI18n' +import { toast } from '@/lib/toast' import type { ChatAttachment } from './types' import { IMAGE_ATTACHMENT_MIMES, TEXT_ATTACHMENT_EXTS, attachmentExt } from './types' @@ -161,7 +162,7 @@ export function ChatComposer({ } if (accepted.length) onAttachmentsChange([...attachments, ...accepted]) if (rejected.length) { - window.alert(t('chatAttachUnsupported', { names: rejected.join(', ') })) + toast({ type: 'error', title: t('chatAttachUnsupported', { names: rejected.join(', ') }) }) } if (fileRef.current) fileRef.current.value = '' } diff --git a/frontend/src/components/account/AccountCard.tsx b/frontend/src/components/account/AccountCard.tsx index 912121e6..6769088a 100644 --- a/frontend/src/components/account/AccountCard.tsx +++ b/frontend/src/components/account/AccountCard.tsx @@ -1,5 +1,6 @@ import { CopyIcon } from '@/components/motion/CopyIcon' import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useSharedClock } from '@/hooks/useSharedClock' import { Button, Card, Chip, Dropdown, Input, Label, TextArea, TextField, Tooltip } from '@heroui/react' import { ArrowClockwise, @@ -122,17 +123,11 @@ export function AccountCard({ const [idCopied, setIdCopied] = useState(false) const [cooldownsOpen, setCooldownsOpen] = useState(false) const lastStateRef = useRef(null) - const [, refreshCooldowns] = useState(0) const state = accountState(account) const cooldown = cooldownLabel(account.down_until || account.cooldown_until) const restartIn = cooldownLabel(account.next_restart_at) const modelCooldowns = modelCooldownEntries(account) - - useEffect(() => { - if (!cooldown && !restartIn && modelCooldowns.length === 0) return - const timer = window.setInterval(() => refreshCooldowns((value) => value + 1), 1000) - return () => window.clearInterval(timer) - }, [cooldown, restartIn, modelCooldowns.length]) + useSharedClock(Boolean(cooldown || restartIn || modelCooldowns.length)) // Transient check-in feedback: a green check / yellow circle / red cross row // that the page pushes after a manual check-in. It shows for three seconds diff --git a/frontend/src/components/layout/AppHeader.tsx b/frontend/src/components/layout/AppHeader.tsx index 93b8f3fb..8fff7ecd 100644 --- a/frontend/src/components/layout/AppHeader.tsx +++ b/frontend/src/components/layout/AppHeader.tsx @@ -1,5 +1,5 @@ import { ArrowClockwise, Globe, List, Moon, SignOut, Sun } from '@phosphor-icons/react' -import { Button, Toolbar, Tooltip } from '@heroui/react' +import { ShellIconButton, ShellTooltip } from '@/components/ui/ShellControls' import { useNavigate } from 'react-router-dom' import { useI18n } from '@/hooks/useI18n' import { useOverview } from '@/hooks/useOverview' @@ -25,9 +25,9 @@ export function AppHeader({ return (
- +
@@ -37,49 +37,34 @@ export function AppHeader({
- - - - - - {t('refresh')} - - - - - - {lang === 'zh' ? 'English' : '中文'} - - - - - - {theme === 'dark' ? 'Light mode' : 'Dark mode'} - - - - - - {t('signOut')} - - +
+ + void refresh().catch(() => undefined)}> + + + + + setLang(lang === 'zh' ? 'en' : 'zh')}> + + + + + + {theme === 'dark' ? : } + + + + { + signOut() + navigate('/login', { replace: true }) + }} + > + + + +
) diff --git a/frontend/src/components/layout/AppLayout.tsx b/frontend/src/components/layout/AppLayout.tsx index 4bb22a70..3c7d9976 100644 --- a/frontend/src/components/layout/AppLayout.tsx +++ b/frontend/src/components/layout/AppLayout.tsx @@ -1,7 +1,8 @@ -import { useState } from 'react' +import { Suspense, useCallback, useState } from 'react' import { Outlet, useLocation } from 'react-router-dom' import { AppHeader } from './AppHeader' import { AppSidebar } from './AppSidebar' +import { RouteFallback } from '@/components/ui/RouteFallback' import { useI18n } from '@/hooks/useI18n' import { Toaster } from '@/components/motion/Toaster' @@ -19,6 +20,7 @@ const routeKey: Record = { export function AppLayout() { const [mobileOpen, setMobileOpen] = useState(false) + const closeMobile = useCallback(() => setMobileOpen(false), []) const location = useLocation() const { page } = useI18n() const key = routeKey[location.pathname] || 'home' @@ -27,7 +29,7 @@ export function AppLayout() { return (
- setMobileOpen(false)} /> +
-
- -
+ }> +
+ +
+
diff --git a/frontend/src/components/layout/AppSidebar.tsx b/frontend/src/components/layout/AppSidebar.tsx index 65203811..f0170f98 100644 --- a/frontend/src/components/layout/AppSidebar.tsx +++ b/frontend/src/components/layout/AppSidebar.tsx @@ -1,10 +1,10 @@ -import { useState } from 'react' +import { useEffect, useState } from 'react' import { NavLink } from 'react-router-dom' -import { Drawer, Button, Chip, Separator, Tooltip } from '@heroui/react' import { ChartBar, Cube, Gauge, GearSix, Key, Lightning, Scroll, SidebarSimple, UsersThree, X } from '@phosphor-icons/react' import { SidebarUpdateItem } from '@/components/layout/SidebarUpdateItem' import { BrandMark } from '@/components/BrandMark' -import { SkeletonBlock } from '@/components/ui/PageSkeletons' +import { SkeletonBlock } from '@/components/ui/SkeletonBlock' +import { ShellChip, ShellIconButton, ShellSeparator, ShellTooltip } from '@/components/ui/ShellControls' import { pressScale } from '@/hooks/useGsapReveal' import { useI18n } from '@/hooks/useI18n' import { useOverview } from '@/hooks/useOverview' @@ -40,7 +40,7 @@ function NavList({ collapsed, onNavigate }: { collapsed: boolean; onNavigate?: ( {groups.map((group) => (
{collapsed ? ( - + ) : ( {group.label} )} @@ -124,19 +124,16 @@ function InFlightIndicator({ initial, collapsed }: { initial: number; collapsed: const label = t('sidebarInFlight', { count: value }) return ( - - - - 0 ? 'ok' : undefined} /> - {value} - - - {label} - + + + 0 ? 'ok' : undefined} /> + {value} + + ) } @@ -159,10 +156,34 @@ export function AppSidebar({ mobileOpen, onClose }: Props) { }) } + useEffect(() => { + if (!mobileOpen) return + const previousOverflow = document.body.style.overflow + document.body.style.overflow = 'hidden' + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') onClose() + } + document.addEventListener('keydown', onKeyDown) + return () => { + document.body.style.overflow = previousOverflow + document.removeEventListener('keydown', onKeyDown) + } + }, [mobileOpen, onClose]) + + useEffect(() => { + if (!mobileOpen) return + const media = window.matchMedia('(min-width: 1024px)') + const onChange = () => { + if (media.matches) onClose() + } + media.addEventListener('change', onChange) + return () => media.removeEventListener('change', onChange) + }, [mobileOpen, onClose]) + const toggle = ( - + ) const footer = ( @@ -177,7 +198,7 @@ export function AppSidebar({ mobileOpen, onClose }: Props) { {healthy ? t('running') : t('degraded')}
- {hotCount}/{accountCount} + {hotCount}/{accountCount}
Proxy @@ -191,14 +212,11 @@ export function AppSidebar({ mobileOpen, onClose }: Props) { )} {collapsed ? (
- - - - - {showStatusSkeleton ? t('refreshing') : healthy ? t('running') : t('degraded')} - + + + {showStatusSkeleton ? : } + +
) : null} @@ -219,14 +237,27 @@ export function AppSidebar({ mobileOpen, onClose }: Props) {
{footer} - { if (!open) onClose() }}> - - -
- -
-
-
+ {mobileOpen ? ( +
+ + ) : null} ) } diff --git a/frontend/src/components/layout/SidebarUpdateDialog.tsx b/frontend/src/components/layout/SidebarUpdateDialog.tsx new file mode 100644 index 00000000..f65b0140 --- /dev/null +++ b/frontend/src/components/layout/SidebarUpdateDialog.tsx @@ -0,0 +1,60 @@ +import { Button, Modal } from '@heroui/react' +import { X } from '@phosphor-icons/react' +import { PageAlert } from '@/components/ui/PageAlert' +import { ReleaseNotes } from '@/components/ReleaseNotes' +import { UpdateControls } from '@/components/system/UpdateControls' +import { extractReleaseNotes } from '@/lib/releaseNotes' +import type { SystemUpdateInfo } from '@/api/system' +import type { SystemUpdateController } from '@/hooks/useSystemUpdate' + +type Props = { + open: boolean + update: SystemUpdateController + release?: SystemUpdateInfo['release'] + version: string + lang: 'zh' | 'en' + labels: { + versionUpdate: string + close: string + releaseNotes: string + emptyNotes: string + goToUpdate: string + } + onClose: () => void + onGoToUpdate: () => void +} + +/** The update dialog is lazy: it is only downloaded when the sidebar entry is opened. */ +export function SidebarUpdateDialog({ open, update, release, version, lang, labels, onClose, onGoToUpdate }: Props) { + return ( + { if (!next) onClose() }}> + + + + +
+ {labels.versionUpdate} +

{release?.tag_name || version}

+
+ + + +
+ + {update.error ? : null} + +
{labels.releaseNotes}
+ +
+ + + + +
+
+
+
+ ) +} diff --git a/frontend/src/components/layout/SidebarUpdateItem.tsx b/frontend/src/components/layout/SidebarUpdateItem.tsx index b823db64..68de073c 100644 --- a/frontend/src/components/layout/SidebarUpdateItem.tsx +++ b/frontend/src/components/layout/SidebarUpdateItem.tsx @@ -1,21 +1,18 @@ -import { useLayoutEffect, useRef, useState, type RefObject } from 'react' +import { Suspense, lazy, useLayoutEffect, useRef, useState, type RefObject } from 'react' import { useNavigate } from 'react-router-dom' -import { Button, Modal } from '@heroui/react' -import { ArrowCircleUp, Notebook, X } from '@phosphor-icons/react' -import { UpdateControls } from '@/components/system/UpdateControls' -import { PageAlert } from '@/components/ui/PageAlert' +import { ArrowCircleUp, Notebook } from '@phosphor-icons/react' import { useSystemUpdate } from '@/hooks/useSystemUpdate' -import { ReleaseNotes } from '@/components/ReleaseNotes' -import { extractReleaseNotes } from '@/lib/releaseNotes' import { duration, ease, gsap } from '@/lib/motion' import { useI18n } from '@/hooks/useI18n' +const SidebarUpdateDialog = lazy(() => import('@/components/layout/SidebarUpdateDialog').then((module) => ({ default: module.SidebarUpdateDialog }))) + /** Compact version / new-release entry pinned to the bottom-left of the sidebar. */ export function SidebarUpdateItem({ collapsed, onNavigate }: { collapsed: boolean; onNavigate?: () => void }) { const { t, lang } = useI18n() const navigate = useNavigate() const update = useSystemUpdate() - const { info, error } = update + const { info } = update const [open, setOpen] = useState(false) const nudgeRef = useRef(null) @@ -48,33 +45,30 @@ export function SidebarUpdateItem({ collapsed, onNavigate }: { collapsed: boolea {hasUpdate ? : null} - - - - - -
- {t('versionUpdate')} -

{release?.tag_name || version}

-
- -
- - {error ? : null} - -
{t('sidebarReleaseNotes')}
- -
- - - - -
-
-
-
+ {open ? ( + + setOpen(false)} + onGoToUpdate={() => { + setOpen(false) + onNavigate?.() + navigate('/system?tab=updates') + }} + /> + + ) : null} ) } diff --git a/frontend/src/components/overview/InflightDepthChart.tsx b/frontend/src/components/overview/InflightDepthChart.tsx new file mode 100644 index 00000000..7a9b3fc0 --- /dev/null +++ b/frontend/src/components/overview/InflightDepthChart.tsx @@ -0,0 +1,120 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { + Area, + AreaChart, + ReferenceArea, + ReferenceLine, + ResponsiveContainer, + XAxis, + YAxis, +} from 'recharts' +import { motionDuration, prefersReducedMotion } from '@/lib/motion' + +export function InflightDepthChart({ + series, + bands, + backpressure, + label, +}: { + series: number[] + bands: Array<{ from: number; until: number }> + backpressure: number + label: string +}) { + // Continuous glide: keep a stable x domain (0..n-1) while values scroll; + // ease Y peak so scale changes don’t jump. Tick cadence ~260ms → linear ~560ms morph. + const rawPeak = Math.max(backpressure, ...series, 1) + const peakRef = useRef(rawPeak) + const [peak, setPeak] = useState(rawPeak) + useEffect(() => { + if (prefersReducedMotion()) { + peakRef.current = rawPeak + setPeak(rawPeak) + return + } + const from = peakRef.current + const to = rawPeak + if (Math.abs(to - from) < 0.01) return + let raf = 0 + const t0 = performance.now() + const dur = motionDuration(0.56) * 1000 + const tick = (now: number) => { + const t = Math.min(1, (now - t0) / dur) + const e = 1 - Math.pow(1 - t, 3) + const v = from + (to - from) * e + peakRef.current = v + setPeak(v) + if (t < 1) raf = requestAnimationFrame(tick) + } + raf = requestAnimationFrame(tick) + return () => cancelAnimationFrame(raf) + }, [rawPeak]) + + const data = useMemo( + () => series.map((v, i) => ({ i, v, bp: backpressure })), + [series, backpressure], + ) + const bandRows = useMemo( + () => + bands.map((band, idx) => { + const n = Math.max(1, series.length - 1) + return { + key: idx, + x1: band.from * n, + x2: Math.max(band.from * n + 0.35, band.until * n), + } + }), + [bands, series.length], + ) + const yMax = Math.max(peak, backpressure, 1) + + return ( +
+ + + + + {bandRows.map((b) => ( + + ))} + + + + + + + + + + +
+ ) +} diff --git a/frontend/src/components/overview/InflightLiveCard.tsx b/frontend/src/components/overview/InflightLiveCard.tsx index c20ce9d9..1f9083c9 100644 --- a/frontend/src/components/overview/InflightLiveCard.tsx +++ b/frontend/src/components/overview/InflightLiveCard.tsx @@ -1,19 +1,10 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { lazy, Suspense, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { Link } from 'react-router-dom' import { Card } from '@heroui/react' import { ArrowUpRight, CaretRight, ChatCircle, Check, Cube, Wrench, X } from '@phosphor-icons/react' import type { LiveSnapshot, LiveSticky } from '@/api/live' import CustomEase from 'gsap/CustomEase' import { MotionPathPlugin } from 'gsap/MotionPathPlugin' -import { - Area, - AreaChart, - ReferenceArea, - ReferenceLine, - ResponsiveContainer, - XAxis, - YAxis, -} from 'recharts' import { applyLiveProjection, clampSlotConcurrency, @@ -33,6 +24,8 @@ import { ProviderMark } from '@/components/ProviderMark' import { CompactSwitch } from '@/components/ui/CompactSwitch' import { ease, gsap, motionDuration, prefersReducedMotion } from '@/lib/motion' +const InflightDepthChart = lazy(() => import('@/components/overview/InflightDepthChart').then((mod) => ({ default: mod.InflightDepthChart }))) + const MOCK_DEMO_STORAGE_KEY = 'cli2api_inflight_mock_demo' function readMockDemoPref(): boolean { @@ -67,7 +60,7 @@ const WORKER_VISIBLE_MAX = 4 /** * Inflight choreography timings (display-only — Acquire/Bind never delayed): * selectingMinDwell 1600ms recorder: wait-rail visibility after Start - * LIVE_POLL_EXPANDED_MS 400ms catch several dwell frames while expanded + * LIVE_POLL_EXPANDED_MS 800ms catch several dwell frames while expanded * QUEUE_TO_SLOT_FLY_S 0.88s GSAP MotionPath slide into the cell * land hold+fade ~0.30s ghost settle after onLand * Pipeline: 选号 pill → (dwell) → fly into cell → onLand reveals model/elapsed @@ -155,116 +148,6 @@ function kindPill(kind: MockJobKind): string { } } -function DepthChart({ - series, - bands, - backpressure, - label, -}: { - series: number[] - bands: Array<{ from: number; until: number }> - backpressure: number - label: string -}) { - // Continuous glide: keep a stable x domain (0..n-1) while values scroll; - // ease Y peak so scale changes don’t jump. Tick cadence ~260ms → linear ~560ms morph. - const rawPeak = Math.max(backpressure, ...series, 1) - const peakRef = useRef(rawPeak) - const [peak, setPeak] = useState(rawPeak) - useEffect(() => { - if (prefersReducedMotion()) { - peakRef.current = rawPeak - setPeak(rawPeak) - return - } - const from = peakRef.current - const to = rawPeak - if (Math.abs(to - from) < 0.01) return - let raf = 0 - const t0 = performance.now() - const dur = motionDuration(0.56) * 1000 - const tick = (now: number) => { - const t = Math.min(1, (now - t0) / dur) - // queue ease approx: 1 - (1-t)^3 - const e = 1 - Math.pow(1 - t, 3) - const v = from + (to - from) * e - peakRef.current = v - setPeak(v) - if (t < 1) raf = requestAnimationFrame(tick) - } - raf = requestAnimationFrame(tick) - return () => cancelAnimationFrame(raf) - }, [rawPeak]) - - const data = useMemo( - () => series.map((v, i) => ({ i, v, bp: backpressure })), - [series, backpressure], - ) - const bandRows = useMemo( - () => - bands.map((band, idx) => { - const n = Math.max(1, series.length - 1) - return { - key: idx, - x1: band.from * n, - x2: Math.max(band.from * n + 0.35, band.until * n), - } - }), - [bands, series.length], - ) - const yMax = Math.max(peak, backpressure, 1) - - return ( -
- - - - - {bandRows.map((b) => ( - - ))} - - - - - - - - - - -
- ) -} - function SlotBar({ slot, jobById, @@ -346,7 +229,7 @@ function SlotBar({ data-cell-id={cell?.id ?? ''} data-cell-index={i} data-cell-pending={reserved && !showChrome ? '' : undefined} - className={`relative flex min-w-0 flex-1 flex-col justify-center overflow-hidden rounded-md px-1 ${ + className={`relative flex min-w-0 flex-1 flex-col justify-center overflow-hidden rounded-[2px] px-1 ${ showChrome ? 'border border-foreground/14 bg-[var(--il-busy-fill)] text-foreground/85' : 'bg-[var(--il-track)] opacity-55' @@ -1751,12 +1634,14 @@ export function InflightLiveCard({ {depthLabel}
- + }> + +
diff --git a/frontend/src/components/overview/LiveSparkline.tsx b/frontend/src/components/overview/LiveSparkline.tsx index 29111978..27d3d004 100644 --- a/frontend/src/components/overview/LiveSparkline.tsx +++ b/frontend/src/components/overview/LiveSparkline.tsx @@ -1,28 +1,36 @@ -import { Area, AreaChart, ResponsiveContainer, YAxis } from 'recharts' import type { LiveSample } from '@/hooks/useLive' -/** Bare ~60s concurrency trace; no axes, no animation. */ +/** Bare ~60s concurrency trace; no axes, no animation, no chart library. */ export function LiveSparkline({ samples, capacity, label }: { samples: LiveSample[]; capacity: number; label: string }) { + const width = 120 + const height = 24 const data = samples.length ? samples : [{ at: 0, value: 0 }] - const peak = Math.max(1, capacity, ...data.map((s) => s.value)) + const peak = Math.max(1, capacity, ...data.map((sample) => sample.value)) + const points = data.map((sample, index) => { + const x = data.length === 1 ? 0 : (index / (data.length - 1)) * width + const y = height - 1 - (sample.value / peak) * (height - 2) + return `${x.toFixed(2)},${y.toFixed(2)}` + }) + const line = `M${points.join(' L')}` + const area = `M0 ${height} L${points.join(' L')} L${width} ${height} Z` + return ( -
- - - - - - -
+ + + + ) } diff --git a/frontend/src/components/overview/LiveStrip.tsx b/frontend/src/components/overview/LiveStrip.tsx index bdf4d598..2818d715 100644 --- a/frontend/src/components/overview/LiveStrip.tsx +++ b/frontend/src/components/overview/LiveStrip.tsx @@ -1,8 +1,6 @@ -import { lazy, Suspense } from 'react' import type { LiveSnapshot } from '@/api/live' import type { LiveSample } from '@/hooks/useLive' - -const LiveSparkline = lazy(() => import('@/components/overview/LiveSparkline').then((mod) => ({ default: mod.LiveSparkline }))) +import { LiveSparkline } from '@/components/overview/LiveSparkline' type T = (key: string, vars?: Record) => string @@ -49,7 +47,7 @@ export function LiveStrip({ type="button" data-testid="live-strip-concurrency" onClick={onConcurrencyClick} - className="inline-flex flex-col gap-1 rounded-md text-left outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-focus sm:flex-row sm:items-center sm:gap-2" + className="inline-flex flex-col gap-1 rounded-lg text-left outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-focus sm:flex-row sm:items-center sm:gap-2" aria-label={t('inflightExpandFromConcurrency')} > {concurrencyInner} @@ -65,9 +63,7 @@ export function LiveStrip({ {t('liveTrace')} - }> - - +
) diff --git a/frontend/src/components/overview/TrafficChart.tsx b/frontend/src/components/overview/TrafficChart.tsx index d6a2e8b3..7f98a509 100644 --- a/frontend/src/components/overview/TrafficChart.tsx +++ b/frontend/src/components/overview/TrafficChart.tsx @@ -1,4 +1,4 @@ -import { useLayoutEffect, useMemo, useRef, useState } from 'react' +import { memo, useLayoutEffect, useMemo, useRef, useState } from 'react' import gsap from 'gsap' import { Area, @@ -106,7 +106,7 @@ function TrafficTooltip({ ) } -export function TrafficChart({ +export const TrafficChart = memo(function TrafficChart({ series, lang, emptyLabel, @@ -385,4 +385,4 @@ export function TrafficChart({ ) -} +}) diff --git a/frontend/src/components/ui/PageSkeletons.tsx b/frontend/src/components/ui/PageSkeletons.tsx index 30df3f73..8e6fcf3a 100644 --- a/frontend/src/components/ui/PageSkeletons.tsx +++ b/frontend/src/components/ui/PageSkeletons.tsx @@ -1,8 +1,6 @@ -import { Skeleton } from '@heroui/react' +import { SkeletonBlock } from './SkeletonBlock' -export function SkeletonBlock({ className }: { className: string }) { - return -} +export { SkeletonBlock } from './SkeletonBlock' export function RankListSkeleton({ rows = 5 }: { rows?: number }) { return ( diff --git a/frontend/src/components/ui/RouteFallback.tsx b/frontend/src/components/ui/RouteFallback.tsx new file mode 100644 index 00000000..d93f1235 --- /dev/null +++ b/frontend/src/components/ui/RouteFallback.tsx @@ -0,0 +1,18 @@ +import { SkeletonBlock } from '@/components/ui/SkeletonBlock' + +/** Route-level fallback shown while a page chunk is fetched. */ +export function RouteFallback() { + return ( +
+
+ + +
+
+ {Array.from({ length: 6 }, (_, index) => ( + + ))} +
+
+ ) +} diff --git a/frontend/src/components/ui/ShellControls.tsx b/frontend/src/components/ui/ShellControls.tsx new file mode 100644 index 00000000..9256c987 --- /dev/null +++ b/frontend/src/components/ui/ShellControls.tsx @@ -0,0 +1,76 @@ +import type { ButtonHTMLAttributes, ReactNode } from 'react' +import { Spinner } from '@phosphor-icons/react' + +/** + * Shell controls are deliberately dependency-free. The app frame renders on + * every page, so importing HeroUI here made its shared runtime part of the + * entry chunk even though the shell only needs a button, chip and tooltip. + */ + +type IconButtonProps = Omit, 'aria-label' | 'title'> & { + label: string + pending?: boolean +} + +export function ShellIconButton({ + label, + pending = false, + disabled = false, + className = '', + children, + ...rest +}: IconButtonProps) { + return ( + + ) +} + +type TooltipProps = { + label: string + children: ReactNode + side?: 'top' | 'bottom' +} + +export function ShellTooltip({ label, children, side = 'bottom' }: TooltipProps) { + return ( + + {children} + + {label} + + + ) +} + +type ChipProps = { + children: ReactNode + tone?: 'neutral' | 'success' | 'warning' +} + +export function ShellChip({ children, tone = 'neutral' }: ChipProps) { + const toneClass = tone === 'success' + ? 'text-success' + : tone === 'warning' + ? 'text-warning' + : 'text-muted' + return ( + + {children} + + ) +} + +export function ShellSeparator({ className = '' }: { className?: string }) { + return
+} diff --git a/frontend/src/components/ui/SkeletonBlock.tsx b/frontend/src/components/ui/SkeletonBlock.tsx new file mode 100644 index 00000000..0b9773ab --- /dev/null +++ b/frontend/src/components/ui/SkeletonBlock.tsx @@ -0,0 +1,3 @@ +export function SkeletonBlock({ className }: { className: string }) { + return