You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@hertzbeat.apache.org by zh...@apache.org on 2026/08/12 11:46:20 UTC
(hertzbeat) branch 2.0.0 updated: feat: refine monitor workbench and login experience
This is an automated email from the ASF dual-hosted git repository.
zqr10159 pushed a commit to branch 2.0.0
in repository https://gitbox.apache.org/repos/asf/hertzbeat.git
The following commit(s) were added to refs/heads/2.0.0 by this push:
new ec51227a8c feat: refine monitor workbench and login experience
ec51227a8c is described below
commit ec51227a8cac85f7b78b1d2554a8926c4b5c29be
Author: Logic <zq...@dromara.org>
AuthorDate: Wed Aug 12 19:45:52 2026 +0800
feat: refine monitor workbench and login experience
---
.../entity/manager/MonitorMetricLayoutEntity.java | 71 +++
.../controller/MonitorMetricLayoutController.java | 121 +++++
.../manager/dao/MonitorMetricLayoutDao.java | 54 +++
.../manager/pojo/dto/MonitorMetricHistoryDock.java | 24 +
.../manager/pojo/dto/MonitorMetricLayout.java | 33 ++
.../manager/pojo/dto/MonitorMetricLayoutItem.java | 31 ++
.../pojo/dto/MonitorMetricLayoutSaveRequest.java | 32 ++
.../MonitorMetricLayoutConflictException.java | 28 ++
.../service/MonitorMetricLayoutService.java | 34 ++
.../impl/MonitorMetricLayoutServiceImpl.java | 265 +++++++++++
.../MonitorMetricLayoutControllerTest.java | 168 +++++++
.../impl/MonitorMetricLayoutServiceImplTest.java | 171 +++++++
.../h2/V205__add_monitor_metric_layout.sql | 30 ++
.../mysql/V205__add_monitor_metric_layout.sql | 28 ++
.../postgresql/V205__add_monitor_metric_layout.sql | 30 ++
hertzbeat-startup/src/main/resources/sureness.yml | 3 +
.../tsdb/greptime/GreptimeDbDataStorage.java | 28 +-
.../GreptimeDbIntervalAggregationTest.java | 124 +++++
script/dev/start-workspace-backend.sh | 20 +
web-app/package.json | 1 +
web-app/pnpm-lock.yaml | 51 ++
web-app/scripts/bundle-limits-contract.test.mjs | 2 +-
web-app/scripts/bundle-limits.json | 2 +-
.../app/decorative-boundary-style-contract.test.ts | 6 +-
web-app/src/app/main.tsx | 1 +
web-app/src/app/providers.test.tsx | 18 +
web-app/src/app/providers.tsx | 2 +-
web-app/src/app/styles.css | 3 +-
web-app/src/app/theme/hertzbeat-theme.test.ts | 2 +-
web-app/src/assets/i18n/en-us.json | 90 +++-
web-app/src/assets/i18n/ja-jp.json | 90 +++-
web-app/src/assets/i18n/pt-br.json | 90 +++-
web-app/src/assets/i18n/zh-cn.json | 90 +++-
web-app/src/assets/i18n/zh-tw.json | 90 +++-
.../auth/pages/login-page-style-contract.test.ts | 29 +-
.../src/features/auth/pages/login-page.module.css | 168 +++++--
.../src/features/auth/pages/login-page.test.tsx | 17 +-
web-app/src/features/auth/pages/login-page.tsx | 1 -
.../auth/pages/passport-introduction-motion.ts | 98 ++++
.../auth/pages/passport-introduction.test.tsx | 144 ++++++
.../features/auth/pages/passport-introduction.tsx | 97 ++++
.../features/auth/pages/passport-page-frame.tsx | 60 +--
.../src/features/monitor/api/monitor-api.test.ts | 23 +-
.../src/features/monitor/api/monitor-metric-api.ts | 15 +-
.../monitor/api/monitor-metric-layout-api.ts | 31 ++
.../api/monitor-metric-layout-schema.test.ts | 38 ++
.../monitor/api/monitor-metric-layout-schema.ts | 85 ++++
.../monitor/components/monitor-detail-metadata.tsx | 38 --
.../components/monitor-detail-view.module.css | 39 --
.../components/monitor-detail-view.test.tsx | 12 +-
.../monitor/components/monitor-detail-view.tsx | 3 +-
.../monitor-history-chart-runtime.test.ts | 73 ++-
.../components/monitor-history-chart-runtime.ts | 23 +-
.../monitor/components/monitor-history-chart.tsx | 95 ++++
.../components/monitor-history-results.module.css | 231 +++++++++
.../monitor/components/monitor-history-results.tsx | 188 --------
.../monitor/components/monitor-history-values.ts | 37 ++
.../components/monitor-metric-group-navigation.ts | 41 ++
.../monitor-metric-layout-toolbar.test.tsx | 72 +++
.../components/monitor-metric-layout-toolbar.tsx | 101 ++++
.../components/monitor-metric-layout.module.css | 84 ++++
.../monitor/components/monitor-metric-results.tsx | 149 +++---
.../monitor/components/monitor-metric-toolbar.tsx | 166 +++++++
.../monitor/components/monitor-metric-value.tsx | 184 ++++++++
.../monitor-metric-visual-contract.test.ts | 70 ++-
.../components/monitor-metric-workbench.module.css | 220 ++++-----
.../components/monitor-metric-workbench.test.tsx | 516 +++++++++++----------
.../components/monitor-metric-workbench.tsx | 46 +-
.../components/monitor-realtime-card.module.css | 99 ++++
.../components/monitor-realtime-evidence.tsx | 47 ++
.../components/monitor-realtime-group-card.tsx | 79 ++++
.../components/monitor-realtime-group-support.tsx | 35 ++
.../components/monitor-realtime-group-time.ts | 17 +
.../monitor-realtime-layout-grid.test.tsx | 139 ++++++
.../components/monitor-realtime-layout-grid.tsx | 153 ++++++
.../components/monitor-realtime-matrix-table.tsx | 67 +++
.../components/monitor-realtime-results.tsx | 134 ++----
.../components/monitor-realtime-table.module.css | 150 ++++++
.../components/monitor-realtime-table.test.tsx | 100 ++++
.../monitor/components/monitor-realtime-table.tsx | 173 +++++++
.../components/monitor-segmented-switch.module.css | 27 ++
.../components/monitor-segmented-switch.tsx | 40 ++
.../monitor-selected-history-controls.tsx | 57 +++
.../components/monitor-selected-history-tray.tsx | 148 ++++++
.../monitor-history-workbench-evidence.ts | 14 +-
.../monitor-metric-query-evidence.test.ts | 19 +-
.../controller/monitor-metric-query-evidence.ts | 23 +-
.../controller/monitor-metric-workbench-actions.ts | 78 ++++
.../controller/monitor-metric-workbench-result.ts | 83 ++--
.../monitor/controller/monitor-query-keys.test.ts | 9 +-
.../monitor/controller/monitor-query-keys.ts | 6 +-
.../controller/use-monitor-history-selection.ts | 65 ++-
.../controller/use-monitor-metric-data.test.ts | 15 +-
.../monitor/controller/use-monitor-metric-data.ts | 16 +-
.../use-monitor-metric-layout-controller.test.tsx | 121 +++++
.../use-monitor-metric-layout-controller.ts | 158 +++++++
.../controller/use-monitor-metric-sources.ts | 12 +
...se-monitor-metric-workbench-controller.test.tsx | 51 +-
.../use-monitor-metric-workbench-controller.ts | 132 +++---
.../monitor/model/monitor-detail-model.test.ts | 14 +-
.../features/monitor/model/monitor-detail-model.ts | 10 +-
.../model/monitor-metric-layout-model.test.ts | 78 ++++
.../monitor/model/monitor-metric-layout-model.ts | 195 ++++++++
.../shell/shell-status-style-contract.test.ts | 2 +-
.../src/{app => shared}/theme/hertzbeat-theme.ts | 0
.../time-series-chart/time-series-chart-runtime.ts | 153 ++++--
106 files changed, 6498 insertions(+), 1248 deletions(-)
diff --git a/hertzbeat-common-spring/src/main/java/org/apache/hertzbeat/common/entity/manager/MonitorMetricLayoutEntity.java b/hertzbeat-common-spring/src/main/java/org/apache/hertzbeat/common/entity/manager/MonitorMetricLayoutEntity.java
new file mode 100644
index 0000000000..6f8544f91c
--- /dev/null
+++ b/hertzbeat-common-spring/src/main/java/org/apache/hertzbeat/common/entity/manager/MonitorMetricLayoutEntity.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.common.entity.manager;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Lob;
+import jakarta.persistence.Table;
+import jakarta.persistence.UniqueConstraint;
+import java.time.LocalDateTime;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Per-user presentation layout for one monitor application.
+ */
+@Entity
+@Table(name = "hzb_monitor_metric_layout",
+ uniqueConstraints = @UniqueConstraint(columnNames = {"creator", "application"}))
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class MonitorMetricLayoutEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(name = "creator", nullable = false, length = 255)
+ private String creator;
+
+ @Column(name = "application", nullable = false, length = 128)
+ private String application;
+
+ @Column(name = "schema_version", nullable = false)
+ private Integer schemaVersion;
+
+ @Lob
+ @Column(name = "layout_document", nullable = false, columnDefinition = "TEXT")
+ private String layoutDocument;
+
+ @Column(name = "revision", nullable = false, length = 64)
+ private String revision;
+
+ @Column(name = "create_time", nullable = false)
+ private LocalDateTime createTime;
+
+ @Column(name = "update_time", nullable = false)
+ private LocalDateTime updateTime;
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/controller/MonitorMetricLayoutController.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/controller/MonitorMetricLayoutController.java
new file mode 100644
index 0000000000..22e27e66ec
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/controller/MonitorMetricLayoutController.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.controller;
+
+import static org.apache.hertzbeat.common.constants.CommonConstants.LOGIN_FAILED_CODE;
+import static org.apache.hertzbeat.common.constants.CommonConstants.MONITOR_CONFLICT_CODE;
+
+import com.usthe.sureness.subject.SubjectSum;
+import com.usthe.sureness.util.SurenessContextHolder;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hertzbeat.common.entity.dto.Message;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayout;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutSaveRequest;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutConflictException;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutService;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Personal monitor metric workspace layout controller.
+ */
+@Tag(name = "Monitor Metric Layout API")
+@RestController
+@RequestMapping(path = "/api/metrics/layout")
+@RequiredArgsConstructor
+@Slf4j
+public class MonitorMetricLayoutController {
+
+ private final MonitorMetricLayoutService monitorMetricLayoutService;
+
+ @GetMapping("/{application}")
+ @Operation(summary = "Get personal monitor metric layout")
+ public ResponseEntity<Message<MonitorMetricLayout>> get(@PathVariable String application) {
+ String user = getCurrentUser();
+ if (user == null) {
+ return ResponseEntity.ok(Message.fail(LOGIN_FAILED_CODE, "User not authenticated"));
+ }
+ MonitorMetricLayout layout = monitorMetricLayoutService.get(user, application).orElse(null);
+ return ResponseEntity.ok(Message.success(layout));
+ }
+
+ @PutMapping("/{application}")
+ @Operation(summary = "Save personal monitor metric layout")
+ public ResponseEntity<Message<MonitorMetricLayout>> save(
+ @PathVariable String application,
+ @RequestBody MonitorMetricLayoutSaveRequest request) {
+ String user = getCurrentUser();
+ if (user == null) {
+ return ResponseEntity.ok(Message.fail(LOGIN_FAILED_CODE, "User not authenticated"));
+ }
+ try {
+ return ResponseEntity.ok(Message.success(
+ monitorMetricLayoutService.save(user, application, request)));
+ } catch (MonitorMetricLayoutConflictException conflict) {
+ return conflict();
+ }
+ }
+
+ @DeleteMapping("/{application}")
+ @Operation(summary = "Reset personal monitor metric layout")
+ public ResponseEntity<Message<Void>> delete(
+ @PathVariable String application,
+ @RequestParam String expectedRevision) {
+ String user = getCurrentUser();
+ if (user == null) {
+ return ResponseEntity.ok(Message.fail(LOGIN_FAILED_CODE, "User not authenticated"));
+ }
+ try {
+ monitorMetricLayoutService.delete(user, application, expectedRevision);
+ return ResponseEntity.ok(Message.success("Monitor metric layout reset successfully"));
+ } catch (MonitorMetricLayoutConflictException conflict) {
+ return ResponseEntity.status(HttpStatus.CONFLICT)
+ .body(Message.fail(MONITOR_CONFLICT_CODE, conflict.getMessage()));
+ }
+ }
+
+ private ResponseEntity<Message<MonitorMetricLayout>> conflict() {
+ return ResponseEntity.status(HttpStatus.CONFLICT)
+ .body(Message.fail(
+ MONITOR_CONFLICT_CODE,
+ "monitor_metric_layout_revision_conflict"));
+ }
+
+ private String getCurrentUser() {
+ try {
+ SubjectSum subject = SurenessContextHolder.getBindSubject();
+ Object principal = subject == null ? null : subject.getPrincipal();
+ return principal == null ? null : StringUtils.trimToNull(String.valueOf(principal));
+ } catch (Exception exception) {
+ log.warn("Monitor metric layout is unavailable without an authenticated user");
+ return null;
+ }
+ }
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/dao/MonitorMetricLayoutDao.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/dao/MonitorMetricLayoutDao.java
new file mode 100644
index 0000000000..06987c9b70
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/dao/MonitorMetricLayoutDao.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.dao;
+
+import java.util.Optional;
+import org.apache.hertzbeat.common.entity.manager.MonitorMetricLayoutEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+/**
+ * Monitor metric layout repository.
+ */
+public interface MonitorMetricLayoutDao extends JpaRepository<MonitorMetricLayoutEntity, Long> {
+
+ Optional<MonitorMetricLayoutEntity> findByCreatorAndApplication(String creator, String application);
+
+ @Modifying(clearAutomatically = true, flushAutomatically = true)
+ @Query("update MonitorMetricLayoutEntity layout set layout.layoutDocument = :document, "
+ + "layout.schemaVersion = :schemaVersion, layout.revision = :revision, "
+ + "layout.updateTime = CURRENT_TIMESTAMP where layout.creator = :creator "
+ + "and layout.application = :application and layout.revision = :expectedRevision")
+ int updateLayoutIfRevision(
+ @Param("creator") String creator,
+ @Param("application") String application,
+ @Param("document") String document,
+ @Param("schemaVersion") Integer schemaVersion,
+ @Param("revision") String revision,
+ @Param("expectedRevision") String expectedRevision);
+
+ @Modifying(clearAutomatically = true, flushAutomatically = true)
+ @Query("delete from MonitorMetricLayoutEntity layout where layout.creator = :creator "
+ + "and layout.application = :application and layout.revision = :revision")
+ int deleteByCreatorAndApplicationAndRevision(
+ @Param("creator") String creator,
+ @Param("application") String application,
+ @Param("revision") String revision);
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricHistoryDock.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricHistoryDock.java
new file mode 100644
index 0000000000..d64dd27854
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricHistoryDock.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.pojo.dto;
+
+/**
+ * Presentation intent for the selected history dock.
+ */
+public record MonitorMetricHistoryDock(boolean collapsed, int height) {
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayout.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayout.java
new file mode 100644
index 0000000000..cd0461bb31
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayout.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.pojo.dto;
+
+import java.util.List;
+
+/**
+ * Saved monitor metric workspace layout.
+ */
+public record MonitorMetricLayout(
+ String application,
+ String revision,
+ int schemaVersion,
+ String mode,
+ int columns,
+ List<MonitorMetricLayoutItem> items,
+ MonitorMetricHistoryDock historyDock) {
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayoutItem.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayoutItem.java
new file mode 100644
index 0000000000..0ea3a3afff
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayoutItem.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.pojo.dto;
+
+/**
+ * Logical card geometry in the canonical desktop grid.
+ */
+public record MonitorMetricLayoutItem(
+ String group,
+ int x,
+ int y,
+ int w,
+ int h,
+ boolean collapsed,
+ int order) {
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayoutSaveRequest.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayoutSaveRequest.java
new file mode 100644
index 0000000000..0b54b67891
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/pojo/dto/MonitorMetricLayoutSaveRequest.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.pojo.dto;
+
+import java.util.List;
+
+/**
+ * Optimistic save request for a monitor metric workspace layout.
+ */
+public record MonitorMetricLayoutSaveRequest(
+ String expectedRevision,
+ int schemaVersion,
+ String mode,
+ int columns,
+ List<MonitorMetricLayoutItem> items,
+ MonitorMetricHistoryDock historyDock) {
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/MonitorMetricLayoutConflictException.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/MonitorMetricLayoutConflictException.java
new file mode 100644
index 0000000000..53a85c292a
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/MonitorMetricLayoutConflictException.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.service;
+
+/**
+ * Stable optimistic concurrency conflict for a personal metric layout.
+ */
+public class MonitorMetricLayoutConflictException extends RuntimeException {
+
+ public MonitorMetricLayoutConflictException() {
+ super("monitor_metric_layout_revision_conflict");
+ }
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/MonitorMetricLayoutService.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/MonitorMetricLayoutService.java
new file mode 100644
index 0000000000..8969dcf638
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/MonitorMetricLayoutService.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.service;
+
+import java.util.Optional;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayout;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutSaveRequest;
+
+/**
+ * Personal monitor metric layout service.
+ */
+public interface MonitorMetricLayoutService {
+
+ Optional<MonitorMetricLayout> get(String creator, String application);
+
+ MonitorMetricLayout save(String creator, String application, MonitorMetricLayoutSaveRequest request);
+
+ void delete(String creator, String application, String expectedRevision);
+}
diff --git a/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MonitorMetricLayoutServiceImpl.java b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MonitorMetricLayoutServiceImpl.java
new file mode 100644
index 0000000000..986aaecd7a
--- /dev/null
+++ b/hertzbeat-manager/src/main/java/org/apache/hertzbeat/manager/service/impl/MonitorMetricLayoutServiceImpl.java
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.service.impl;
+
+import java.time.LocalDateTime;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import lombok.RequiredArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.hertzbeat.common.entity.manager.MonitorMetricLayoutEntity;
+import org.apache.hertzbeat.common.util.JsonUtil;
+import org.apache.hertzbeat.manager.dao.MonitorMetricLayoutDao;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricHistoryDock;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayout;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutItem;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutSaveRequest;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutConflictException;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutService;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Personal monitor metric layout service implementation.
+ */
+@Service
+@RequiredArgsConstructor
+@Transactional(rollbackFor = Exception.class)
+public class MonitorMetricLayoutServiceImpl implements MonitorMetricLayoutService {
+
+ private static final int SCHEMA_VERSION = 1;
+ private static final int COLUMNS = 12;
+ private static final String MISSING_REVISION = "missing";
+ private static final Set<Integer> WIDTHS = Set.of(4, 6, 8, 12);
+
+ private final MonitorMetricLayoutDao monitorMetricLayoutDao;
+
+ @Override
+ @Transactional(readOnly = true)
+ public Optional<MonitorMetricLayout> get(String creator, String application) {
+ String normalizedCreator = requireText(creator, "creator");
+ String normalizedApplication = normalizeApplication(application);
+ return monitorMetricLayoutDao.findByCreatorAndApplication(normalizedCreator, normalizedApplication)
+ .map(this::toLayout);
+ }
+
+ @Override
+ public MonitorMetricLayout save(
+ String creator, String application, MonitorMetricLayoutSaveRequest request) {
+ String normalizedCreator = requireText(creator, "creator");
+ String normalizedApplication = normalizeApplication(application);
+ LayoutDocument document = validate(request);
+ String serialized = JsonUtil.toJson(document);
+ if (serialized == null) {
+ throw new IllegalStateException("Monitor metric layout could not be serialized");
+ }
+ String expectedRevision = requireText(request.expectedRevision(), "expectedRevision");
+ Optional<MonitorMetricLayoutEntity> existing = monitorMetricLayoutDao
+ .findByCreatorAndApplication(normalizedCreator, normalizedApplication);
+ return existing.isEmpty()
+ ? create(normalizedCreator, normalizedApplication, expectedRevision, document, serialized)
+ : update(existing.get(), expectedRevision, document, serialized);
+ }
+
+ @Override
+ public void delete(String creator, String application, String expectedRevision) {
+ int deleted = monitorMetricLayoutDao.deleteByCreatorAndApplicationAndRevision(
+ requireText(creator, "creator"),
+ normalizeApplication(application),
+ requireText(expectedRevision, "expectedRevision"));
+ if (deleted != 1) {
+ throw new MonitorMetricLayoutConflictException();
+ }
+ }
+
+ private MonitorMetricLayout create(
+ String creator,
+ String application,
+ String expectedRevision,
+ LayoutDocument document,
+ String serialized) {
+ if (!MISSING_REVISION.equals(expectedRevision)) {
+ throw new MonitorMetricLayoutConflictException();
+ }
+ LocalDateTime now = LocalDateTime.now();
+ String revision = nextRevision();
+ MonitorMetricLayoutEntity entity = MonitorMetricLayoutEntity.builder()
+ .creator(creator)
+ .application(application)
+ .schemaVersion(SCHEMA_VERSION)
+ .layoutDocument(serialized)
+ .revision(revision)
+ .createTime(now)
+ .updateTime(now)
+ .build();
+ try {
+ monitorMetricLayoutDao.saveAndFlush(entity);
+ } catch (DataIntegrityViolationException conflict) {
+ throw new MonitorMetricLayoutConflictException();
+ }
+ return toLayout(application, revision, document);
+ }
+
+ private MonitorMetricLayout update(
+ MonitorMetricLayoutEntity existing,
+ String expectedRevision,
+ LayoutDocument document,
+ String serialized) {
+ if (!expectedRevision.equals(existing.getRevision())) {
+ throw new MonitorMetricLayoutConflictException();
+ }
+ String revision = nextRevision();
+ int updated = monitorMetricLayoutDao.updateLayoutIfRevision(
+ existing.getCreator(),
+ existing.getApplication(),
+ serialized,
+ SCHEMA_VERSION,
+ revision,
+ expectedRevision);
+ if (updated != 1) {
+ throw new MonitorMetricLayoutConflictException();
+ }
+ return toLayout(existing.getApplication(), revision, document);
+ }
+
+ private MonitorMetricLayout toLayout(MonitorMetricLayoutEntity entity) {
+ LayoutDocument document = JsonUtil.fromJsonQuietly(entity.getLayoutDocument(), LayoutDocument.class);
+ if (document == null) {
+ throw new IllegalStateException("Saved monitor metric layout is invalid");
+ }
+ validate(document);
+ return toLayout(entity.getApplication(), entity.getRevision(), document);
+ }
+
+ private MonitorMetricLayout toLayout(String application, String revision, LayoutDocument document) {
+ return new MonitorMetricLayout(
+ application,
+ revision,
+ document.schemaVersion(),
+ document.mode(),
+ document.columns(),
+ List.copyOf(document.items()),
+ document.historyDock());
+ }
+
+ private LayoutDocument validate(MonitorMetricLayoutSaveRequest request) {
+ if (request == null) {
+ throw new IllegalArgumentException("layout is required");
+ }
+ LayoutDocument document = new LayoutDocument(
+ request.schemaVersion(),
+ request.mode(),
+ request.columns(),
+ request.items(),
+ request.historyDock());
+ validate(document);
+ return document;
+ }
+
+ private void validate(LayoutDocument document) {
+ if (document.schemaVersion() != SCHEMA_VERSION || document.columns() != COLUMNS) {
+ throw new IllegalArgumentException("Unsupported monitor metric layout version");
+ }
+ if (!"auto".equals(document.mode()) && !"custom".equals(document.mode())) {
+ throw new IllegalArgumentException("Invalid monitor metric layout mode");
+ }
+ List<MonitorMetricLayoutItem> items = document.items();
+ if (items == null || items.size() > 128 || document.historyDock() == null) {
+ throw new IllegalArgumentException("Invalid monitor metric layout document");
+ }
+ validateHistoryDock(document.historyDock());
+ validateItems(items);
+ }
+
+ private void validateHistoryDock(MonitorMetricHistoryDock dock) {
+ if (dock.height() < 8 || dock.height() > 20) {
+ throw new IllegalArgumentException("Invalid monitor metric history dock height");
+ }
+ }
+
+ private void validateItems(List<MonitorMetricLayoutItem> items) {
+ Set<String> groups = new HashSet<>();
+ Set<Integer> orders = new HashSet<>();
+ for (MonitorMetricLayoutItem item : items) {
+ validateItem(item);
+ if (!groups.add(item.group()) || !orders.add(item.order())) {
+ throw new IllegalArgumentException("Duplicate monitor metric layout item");
+ }
+ }
+ for (int index = 0; index < items.size(); index++) {
+ for (int candidate = index + 1; candidate < items.size(); candidate++) {
+ if (overlaps(items.get(index), items.get(candidate))) {
+ throw new IllegalArgumentException("Overlapping monitor metric layout items");
+ }
+ }
+ }
+ }
+
+ private void validateItem(MonitorMetricLayoutItem item) {
+ if (item == null || item.group() == null
+ || !item.group().matches("[A-Za-z0-9_.:-]{1,128}")) {
+ throw new IllegalArgumentException("Invalid monitor metric group key");
+ }
+ if (item.x() < 0 || item.y() < 0 || item.y() > 999
+ || !WIDTHS.contains(item.w()) || item.x() + item.w() > COLUMNS
+ || item.h() < (item.collapsed() ? 4 : 8) || item.h() > 24
+ || item.order() < 0 || item.order() > 127) {
+ throw new IllegalArgumentException("Invalid monitor metric layout geometry");
+ }
+ }
+
+ private boolean overlaps(MonitorMetricLayoutItem first, MonitorMetricLayoutItem second) {
+ return first.x() < second.x() + second.w()
+ && first.x() + first.w() > second.x()
+ && first.y() < second.y() + second.h()
+ && first.y() + first.h() > second.y();
+ }
+
+ private String normalizeApplication(String application) {
+ String normalized = requireText(application, "application").toLowerCase(Locale.ROOT);
+ if (!normalized.matches("[a-z0-9_.:-]{1,128}")) {
+ throw new IllegalArgumentException("Invalid monitor application");
+ }
+ return normalized;
+ }
+
+ private String requireText(String value, String field) {
+ String normalized = StringUtils.trimToNull(value);
+ if (normalized == null) {
+ throw new IllegalArgumentException(field + " is required");
+ }
+ return normalized;
+ }
+
+ private String nextRevision() {
+ return UUID.randomUUID().toString();
+ }
+
+ private record LayoutDocument(
+ int schemaVersion,
+ String mode,
+ int columns,
+ List<MonitorMetricLayoutItem> items,
+ MonitorMetricHistoryDock historyDock) {
+ }
+}
diff --git a/hertzbeat-manager/src/test/java/org/apache/hertzbeat/manager/controller/MonitorMetricLayoutControllerTest.java b/hertzbeat-manager/src/test/java/org/apache/hertzbeat/manager/controller/MonitorMetricLayoutControllerTest.java
new file mode 100644
index 0000000000..64204f99ec
--- /dev/null
+++ b/hertzbeat-manager/src/test/java/org/apache/hertzbeat/manager/controller/MonitorMetricLayoutControllerTest.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.controller;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.usthe.sureness.subject.SubjectSum;
+import com.usthe.sureness.util.SurenessContextHolder;
+import java.util.List;
+import java.util.Optional;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricHistoryDock;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayout;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutItem;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutConflictException;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutService;
+import org.apache.hertzbeat.manager.support.GlobalExceptionHandler;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+/**
+ * Test case for {@link MonitorMetricLayoutController}.
+ */
+@ExtendWith(MockitoExtension.class)
+class MonitorMetricLayoutControllerTest {
+
+ @Mock
+ private MonitorMetricLayoutService service;
+
+ @InjectMocks
+ private MonitorMetricLayoutController controller;
+
+ private MockMvc mockMvc;
+
+ @BeforeEach
+ void setUp() {
+ mockMvc = MockMvcBuilders.standaloneSetup(controller)
+ .setControllerAdvice(new GlobalExceptionHandler())
+ .setMessageConverters(new JacksonJsonHttpMessageConverter())
+ .build();
+ }
+
+ @Test
+ void getReturnsTheAuthenticatedUsersApplicationLayout() throws Exception {
+ when(service.get("operator", "mysql")).thenReturn(Optional.of(layout()));
+
+ withUser(() -> mockMvc.perform(get("/api/metrics/layout/mysql"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.code").value(0))
+ .andExpect(jsonPath("$.data.application").value("mysql"))
+ .andExpect(jsonPath("$.data.revision").value("revision-1"))
+ .andExpect(jsonPath("$.data.items[0].group").value("basic")));
+ }
+
+ @Test
+ void putPassesExpectedRevisionAndReturnsSavedGeometry() throws Exception {
+ when(service.save(org.mockito.ArgumentMatchers.eq("operator"),
+ org.mockito.ArgumentMatchers.eq("mysql"), org.mockito.ArgumentMatchers.any()))
+ .thenReturn(layout());
+
+ String request = """
+ {
+ "expectedRevision":"missing",
+ "schemaVersion":1,
+ "mode":"custom",
+ "columns":12,
+ "items":[{"group":"basic","x":0,"y":0,"w":6,"h":10,"collapsed":false,"order":0}],
+ "historyDock":{"collapsed":false,"height":12}
+ }
+ """;
+ withUser(() -> mockMvc.perform(put("/api/metrics/layout/mysql")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(request))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.data.mode").value("custom")));
+
+ verify(service).save(org.mockito.ArgumentMatchers.eq("operator"),
+ org.mockito.ArgumentMatchers.eq("mysql"), org.mockito.ArgumentMatchers.any());
+ }
+
+ @Test
+ void stalePutReturnsConflictWithoutLeakingPersistenceDetails() throws Exception {
+ when(service.save(org.mockito.ArgumentMatchers.eq("operator"),
+ org.mockito.ArgumentMatchers.eq("mysql"), org.mockito.ArgumentMatchers.any()))
+ .thenThrow(new MonitorMetricLayoutConflictException());
+
+ String request = """
+ {
+ "expectedRevision":"stale",
+ "schemaVersion":1,
+ "mode":"auto",
+ "columns":12,
+ "items":[],
+ "historyDock":{"collapsed":false,"height":12}
+ }
+ """;
+ withUser(() -> mockMvc.perform(put("/api/metrics/layout/mysql")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(request))
+ .andExpect(status().isConflict())
+ .andExpect(jsonPath("$.msg").value("monitor_metric_layout_revision_conflict")));
+ }
+
+ @Test
+ void deleteUsesTheOpaqueRevision() throws Exception {
+ withUser(() -> mockMvc.perform(delete("/api/metrics/layout/mysql")
+ .queryParam("expectedRevision", "revision-1"))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.code").value(0)));
+
+ verify(service).delete("operator", "mysql", "revision-1");
+ }
+
+ private static MonitorMetricLayout layout() {
+ return new MonitorMetricLayout(
+ "mysql",
+ "revision-1",
+ 1,
+ "custom",
+ 12,
+ List.of(new MonitorMetricLayoutItem("basic", 0, 0, 6, 10, false, 0)),
+ new MonitorMetricHistoryDock(false, 12));
+ }
+
+ private static void withUser(ThrowingAction action) throws Exception {
+ SubjectSum subject = mock(SubjectSum.class);
+ when(subject.getPrincipal()).thenReturn("operator");
+ try (var staticContext = mockStatic(SurenessContextHolder.class)) {
+ staticContext.when(SurenessContextHolder::getBindSubject).thenReturn(subject);
+ action.run();
+ }
+ }
+
+ @FunctionalInterface
+ private interface ThrowingAction {
+ void run() throws Exception;
+ }
+}
diff --git a/hertzbeat-manager/src/test/java/org/apache/hertzbeat/manager/service/impl/MonitorMetricLayoutServiceImplTest.java b/hertzbeat-manager/src/test/java/org/apache/hertzbeat/manager/service/impl/MonitorMetricLayoutServiceImplTest.java
new file mode 100644
index 0000000000..be640ec3d3
--- /dev/null
+++ b/hertzbeat-manager/src/test/java/org/apache/hertzbeat/manager/service/impl/MonitorMetricLayoutServiceImplTest.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.manager.service.impl;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+import org.apache.hertzbeat.common.entity.manager.MonitorMetricLayoutEntity;
+import org.apache.hertzbeat.manager.dao.MonitorMetricLayoutDao;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricHistoryDock;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayout;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutItem;
+import org.apache.hertzbeat.manager.pojo.dto.MonitorMetricLayoutSaveRequest;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutConflictException;
+import org.apache.hertzbeat.manager.service.MonitorMetricLayoutService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+/**
+ * Test case for {@link MonitorMetricLayoutServiceImpl}.
+ */
+@ExtendWith(MockitoExtension.class)
+class MonitorMetricLayoutServiceImplTest {
+
+ @Mock
+ private MonitorMetricLayoutDao monitorMetricLayoutDao;
+
+ private MonitorMetricLayoutService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new MonitorMetricLayoutServiceImpl(monitorMetricLayoutDao);
+ }
+
+ @Test
+ void missingLayoutIsDistinctFromSavedAutomaticLayout() {
+ when(monitorMetricLayoutDao.findByCreatorAndApplication("operator", "mysql"))
+ .thenReturn(Optional.empty());
+
+ assertEquals(Optional.empty(), service.get("operator", "mysql"));
+ }
+
+ @Test
+ void firstSaveRequiresMissingRevisionAndStoresOnlyVersionedPresentationIntent() {
+ when(monitorMetricLayoutDao.findByCreatorAndApplication("operator", "mysql"))
+ .thenReturn(Optional.empty());
+ when(monitorMetricLayoutDao.saveAndFlush(any(MonitorMetricLayoutEntity.class)))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+
+ MonitorMetricLayout saved = service.save("operator", "mysql", customRequest("missing"));
+
+ assertEquals("mysql", saved.application());
+ assertEquals(1, saved.schemaVersion());
+ assertEquals("custom", saved.mode());
+ assertNotEquals("missing", saved.revision());
+ ArgumentCaptor<MonitorMetricLayoutEntity> captor = ArgumentCaptor.forClass(MonitorMetricLayoutEntity.class);
+ verify(monitorMetricLayoutDao).saveAndFlush(captor.capture());
+ String document = captor.getValue().getLayoutDocument();
+ org.assertj.core.api.Assertions.assertThat(document)
+ .contains("basic", "historyDock", "schemaVersion")
+ .doesNotContain("password", "jdbc", "favorite", "sample");
+ }
+
+ @Test
+ void staleUpdateFailsWithoutOverwritingTheOtherTab() {
+ MonitorMetricLayoutEntity existing = existing("current-revision");
+ when(monitorMetricLayoutDao.findByCreatorAndApplication("operator", "mysql"))
+ .thenReturn(Optional.of(existing));
+
+ MonitorMetricLayoutConflictException conflict = assertThrows(
+ MonitorMetricLayoutConflictException.class,
+ () -> service.save("operator", "mysql", customRequest("stale-revision")));
+
+ assertEquals("monitor_metric_layout_revision_conflict", conflict.getMessage());
+ verify(monitorMetricLayoutDao, never()).updateLayoutIfRevision(
+ any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void exactRevisionUsesCompareAndSetAndReturnsTheNewRevision() {
+ MonitorMetricLayoutEntity existing = existing("current-revision");
+ when(monitorMetricLayoutDao.findByCreatorAndApplication("operator", "mysql"))
+ .thenReturn(Optional.of(existing));
+ when(monitorMetricLayoutDao.updateLayoutIfRevision(
+ eq("operator"), eq("mysql"), any(), eq(1), any(), eq("current-revision")))
+ .thenReturn(1);
+
+ MonitorMetricLayout saved = service.save(
+ "operator", "mysql", customRequest("current-revision"));
+
+ assertNotEquals("current-revision", saved.revision());
+ assertEquals("custom", saved.mode());
+ }
+
+ @Test
+ void deleteRequiresTheExactRevision() {
+ when(monitorMetricLayoutDao.deleteByCreatorAndApplicationAndRevision(
+ "operator", "mysql", "current-revision"))
+ .thenReturn(0);
+
+ assertThrows(
+ MonitorMetricLayoutConflictException.class,
+ () -> service.delete("operator", "mysql", "current-revision"));
+ }
+
+ @Test
+ void invalidOverlappingOrDuplicateGeometryIsRejectedBeforePersistence() {
+ MonitorMetricLayoutItem first = new MonitorMetricLayoutItem("basic", 0, 0, 6, 10, false, 0);
+ MonitorMetricLayoutItem overlap = new MonitorMetricLayoutItem("status", 4, 0, 6, 10, false, 1);
+ MonitorMetricLayoutSaveRequest request = new MonitorMetricLayoutSaveRequest(
+ "missing", 1, "custom", 12, List.of(first, overlap),
+ new MonitorMetricHistoryDock(false, 12));
+
+ assertThrows(IllegalArgumentException.class, () -> service.save("operator", "mysql", request));
+ verify(monitorMetricLayoutDao, never()).findByCreatorAndApplication(any(), any());
+ }
+
+ private static MonitorMetricLayoutSaveRequest customRequest(String revision) {
+ return new MonitorMetricLayoutSaveRequest(
+ revision,
+ 1,
+ "custom",
+ 12,
+ List.of(
+ new MonitorMetricLayoutItem("basic", 0, 0, 6, 10, false, 0),
+ new MonitorMetricLayoutItem("status", 6, 0, 6, 12, false, 1)),
+ new MonitorMetricHistoryDock(false, 12));
+ }
+
+ private static MonitorMetricLayoutEntity existing(String revision) {
+ return MonitorMetricLayoutEntity.builder()
+ .id(1L)
+ .creator("operator")
+ .application("mysql")
+ .schemaVersion(1)
+ .layoutDocument("{\"schemaVersion\":1,\"mode\":\"auto\",\"columns\":12,"
+ + "\"items\":[],\"historyDock\":{\"collapsed\":false,\"height\":12}}")
+ .revision(revision)
+ .createTime(LocalDateTime.now().minusMinutes(1))
+ .updateTime(LocalDateTime.now())
+ .build();
+ }
+}
diff --git a/hertzbeat-startup/src/main/resources/db/migration/h2/V205__add_monitor_metric_layout.sql b/hertzbeat-startup/src/main/resources/db/migration/h2/V205__add_monitor_metric_layout.sql
new file mode 100644
index 0000000000..3cc14d88ff
--- /dev/null
+++ b/hertzbeat-startup/src/main/resources/db/migration/h2/V205__add_monitor_metric_layout.sql
@@ -0,0 +1,30 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements. See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership. The ASF licenses this file
+-- to you under the Apache License, Version 2.0 (the
+-- "License"); you may not use this file except in compliance
+-- with the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied. See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+CREATE TABLE IF NOT EXISTS hzb_monitor_metric_layout (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ creator VARCHAR(255) NOT NULL,
+ application VARCHAR(128) NOT NULL,
+ schema_version INT NOT NULL,
+ layout_document CLOB NOT NULL,
+ revision VARCHAR(64) NOT NULL,
+ create_time TIMESTAMP NOT NULL,
+ update_time TIMESTAMP NOT NULL
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS uk_hzb_monitor_metric_layout_creator_app
+ ON hzb_monitor_metric_layout(creator, application);
diff --git a/hertzbeat-startup/src/main/resources/db/migration/mysql/V205__add_monitor_metric_layout.sql b/hertzbeat-startup/src/main/resources/db/migration/mysql/V205__add_monitor_metric_layout.sql
new file mode 100644
index 0000000000..0346ed9118
--- /dev/null
+++ b/hertzbeat-startup/src/main/resources/db/migration/mysql/V205__add_monitor_metric_layout.sql
@@ -0,0 +1,28 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements. See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership. The ASF licenses this file
+-- to you under the Apache License, Version 2.0 (the
+-- "License"); you may not use this file except in compliance
+-- with the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied. See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+CREATE TABLE IF NOT EXISTS hzb_monitor_metric_layout (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ creator VARCHAR(255) NOT NULL,
+ application VARCHAR(128) NOT NULL,
+ schema_version INT NOT NULL,
+ layout_document LONGTEXT NOT NULL,
+ revision VARCHAR(64) NOT NULL,
+ create_time DATETIME NOT NULL,
+ update_time DATETIME NOT NULL,
+ UNIQUE KEY uk_hzb_monitor_metric_layout_creator_app (creator, application)
+);
diff --git a/hertzbeat-startup/src/main/resources/db/migration/postgresql/V205__add_monitor_metric_layout.sql b/hertzbeat-startup/src/main/resources/db/migration/postgresql/V205__add_monitor_metric_layout.sql
new file mode 100644
index 0000000000..319f95b487
--- /dev/null
+++ b/hertzbeat-startup/src/main/resources/db/migration/postgresql/V205__add_monitor_metric_layout.sql
@@ -0,0 +1,30 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements. See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership. The ASF licenses this file
+-- to you under the Apache License, Version 2.0 (the
+-- "License"); you may not use this file except in compliance
+-- with the License. You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied. See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+CREATE TABLE IF NOT EXISTS hzb_monitor_metric_layout (
+ id BIGSERIAL PRIMARY KEY,
+ creator VARCHAR(255) NOT NULL,
+ application VARCHAR(128) NOT NULL,
+ schema_version INTEGER NOT NULL,
+ layout_document TEXT NOT NULL,
+ revision VARCHAR(64) NOT NULL,
+ create_time TIMESTAMP NOT NULL,
+ update_time TIMESTAMP NOT NULL
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS uk_hzb_monitor_metric_layout_creator_app
+ ON hzb_monitor_metric_layout(creator, application);
diff --git a/hertzbeat-startup/src/main/resources/sureness.yml b/hertzbeat-startup/src/main/resources/sureness.yml
index 06f0803bd4..17fef7dbdf 100644
--- a/hertzbeat-startup/src/main/resources/sureness.yml
+++ b/hertzbeat-startup/src/main/resources/sureness.yml
@@ -49,6 +49,9 @@ resourceRole:
- /api/monitor/**===put===[admin,user]
- /api/monitor===delete===[admin]
- /api/monitor/**===delete===[admin]
+ - /api/metrics/layout/**===get===[admin,user,guest]
+ - /api/metrics/layout/**===put===[admin,user]
+ - /api/metrics/layout/**===delete===[admin,user]
- /api/monitors===get===[admin,user,guest]
- /api/monitors/export===get===[admin]
- /api/monitors/export/all===get===[admin]
diff --git a/hertzbeat-warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbDataStorage.java b/hertzbeat-warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbDataStorage.java
index f4b9406340..e85e77baea 100644
--- a/hertzbeat-warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbDataStorage.java
+++ b/hertzbeat-warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbDataStorage.java
@@ -350,25 +350,26 @@ public class GreptimeDbDataStorage extends AbstractHistoryDataStorage {
}
timeSeriesSelector = timeSeriesSelector + "}";
+ Map<String, List<Value>> intervalValuesMap = new HashMap<>(instanceValuesMap.size());
try {
// max
String finalTimeSeriesSelector = timeSeriesSelector;
URI uri = getUri(effectiveStart, effectiveEnd, queryStep,
uriComponents -> "max_over_time(" + finalTimeSeriesSelector + "[" + queryStep + "])");
- requestIntervalMetricAndPutValue(uri, instanceValuesMap, Value::setMax);
+ requestIntervalMetricAndPutValue(uri, intervalValuesMap, Value::setMax);
// min
uri = getUri(effectiveStart, effectiveEnd, queryStep,
uriComponents -> "min_over_time(" + finalTimeSeriesSelector + "[" + queryStep + "])");
- requestIntervalMetricAndPutValue(uri, instanceValuesMap, Value::setMin);
+ requestIntervalMetricAndPutValue(uri, intervalValuesMap, Value::setMin);
// avg
uri = getUri(effectiveStart, effectiveEnd, queryStep,
uriComponents -> "avg_over_time(" + finalTimeSeriesSelector + "[" + queryStep + "])");
- requestIntervalMetricAndPutValue(uri, instanceValuesMap, Value::setMean);
+ requestIntervalMetricAndPutValue(uri, intervalValuesMap, Value::setMean);
} catch (Exception e) {
log.error("query interval metrics data from greptime error. {}", e.getMessage(), e);
}
- return instanceValuesMap;
+ return intervalValuesMap;
}
/**
@@ -594,14 +595,19 @@ public class GreptimeDbDataStorage extends AbstractHistoryDataStorage {
continue;
}
List<Value> valueList = instanceValuesMap.computeIfAbsent(labelStr, k -> new LinkedList<>());
- if (valueList.size() == content.getValues().size()) {
- for (int timestampIndex = 0; timestampIndex < valueList.size(); timestampIndex++) {
- Value value = valueList.get(timestampIndex);
- Object[] valueArr = content.getValues().get(timestampIndex);
- String avgValue = new BigDecimal(String.valueOf(valueArr[1])).setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
- valueConsumer.accept(value, avgValue);
- }
+ Map<Long, Value> valuesByTime = valueList.stream()
+ .collect(Collectors.toMap(Value::getTime, Function.identity(), (first, ignored) -> first));
+ for (Object[] valueArr : content.getValues()) {
+ long timestamp = ((Double) valueArr[0]).longValue() * 1000;
+ Value value = valuesByTime.computeIfAbsent(timestamp, key -> new Value(null, key));
+ String intervalValue = new BigDecimal(String.valueOf(valueArr[1]))
+ .setScale(4, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
+ valueConsumer.accept(value, intervalValue);
}
+ valueList.clear();
+ valueList.addAll(valuesByTime.values().stream()
+ .sorted((left, right) -> Long.compare(left.getTime(), right.getTime()))
+ .toList());
}
}
diff --git a/hertzbeat-warehouse/src/test/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbIntervalAggregationTest.java b/hertzbeat-warehouse/src/test/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbIntervalAggregationTest.java
new file mode 100644
index 0000000000..8f051db691
--- /dev/null
+++ b/hertzbeat-warehouse/src/test/java/org/apache/hertzbeat/warehouse/store/history/tsdb/greptime/GreptimeDbIntervalAggregationTest.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hertzbeat.warehouse.store.history.tsdb.greptime;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import io.greptime.GreptimeDB;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.hertzbeat.common.entity.dto.Value;
+import org.apache.hertzbeat.warehouse.db.GreptimeSqlQueryExecutor;
+import org.apache.hertzbeat.warehouse.store.history.tsdb.vm.PromQlQueryContent;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.RestTemplate;
+
+@ExtendWith(MockitoExtension.class)
+class GreptimeDbIntervalAggregationTest {
+
+ private static final long START_SECONDS = 1_712_730_000L;
+
+ @Mock
+ private GreptimeProperties properties;
+
+ @Mock
+ private RestTemplate restTemplate;
+
+ @Mock
+ private GreptimeSqlQueryExecutor sqlQueryExecutor;
+
+ @Mock
+ private GreptimeDB greptimeDb;
+
+ @BeforeEach
+ void setUp() {
+ when(properties.grpcEndpoints()).thenReturn("127.0.0.1:4001");
+ when(properties.database()).thenReturn("hertzbeat");
+ when(properties.username()).thenReturn("username");
+ when(properties.password()).thenReturn("password");
+ when(properties.httpEndpoint()).thenReturn("http://127.0.0.1:4000");
+ when(properties.expireTime()).thenReturn(null);
+ }
+
+ @Test
+ void alignsAggregateSeriesByTimestampWhenRawAndIntervalPointCountsDiffer() {
+ ResponseEntity<PromQlQueryContent> raw = response(
+ List.of(START_SECONDS, START_SECONDS + 12 * 60 * 60), List.of("151", "151"));
+ List<Long> aggregateTimes = List.of(
+ START_SECONDS,
+ START_SECONDS + 4 * 60 * 60,
+ START_SECONDS + 8 * 60 * 60,
+ START_SECONDS + 12 * 60 * 60);
+ ResponseEntity<PromQlQueryContent> max = response(aggregateTimes, List.of("154", "155", "156", "157"));
+ ResponseEntity<PromQlQueryContent> min = response(aggregateTimes, List.of("148", "149", "150", "151"));
+ ResponseEntity<PromQlQueryContent> mean = response(aggregateTimes, List.of("151", "152", "153", "154"));
+ when(restTemplate.exchange(any(), eq(HttpMethod.GET), any(HttpEntity.class), eq(PromQlQueryContent.class)))
+ .thenReturn(raw, max, min, mean);
+
+ try (MockedStatic<GreptimeDB> mocked = mockStatic(GreptimeDB.class)) {
+ mocked.when(() -> GreptimeDB.create(any())).thenReturn(greptimeDb);
+ GreptimeDbDataStorage storage = new GreptimeDbDataStorage(properties, restTemplate, sqlQueryExecutor);
+
+ Map<String, List<Value>> result = storage.getHistoryIntervalMetricData(
+ "127.0.0.1:3306", "mysql", "basic", "max_connections", "1W",
+ START_SECONDS * 1000, (START_SECONDS + 16 * 60 * 60) * 1000, "4h");
+
+ List<Value> values = result.get("{}");
+ assertEquals(4, values.size());
+ assertEquals(
+ aggregateTimes.stream().map(time -> time * 1000).toList(),
+ values.stream().map(Value::getTime).toList());
+ assertEquals(List.of("154", "155", "156", "157"), values.stream().map(Value::getMax).toList());
+ assertEquals(List.of("148", "149", "150", "151"), values.stream().map(Value::getMin).toList());
+ assertEquals(List.of("151", "152", "153", "154"), values.stream().map(Value::getMean).toList());
+ }
+ }
+
+ private ResponseEntity<PromQlQueryContent> response(List<Long> times, List<String> values) {
+ PromQlQueryContent content = new PromQlQueryContent();
+ PromQlQueryContent.ContentData data = new PromQlQueryContent.ContentData();
+ PromQlQueryContent.ContentData.Content result = new PromQlQueryContent.ContentData.Content();
+ Map<String, String> metric = new HashMap<>();
+ metric.put("__name__", "mysql_basic");
+ metric.put("instance", "127.0.0.1:3306");
+ result.setMetric(metric);
+ List<Object[]> points = new ArrayList<>();
+ for (int index = 0; index < times.size(); index++) {
+ points.add(new Object[]{times.get(index).doubleValue(), values.get(index)});
+ }
+ result.setValues(points);
+ data.setResult(List.of(result));
+ content.setData(data);
+ return new ResponseEntity<>(content, HttpStatus.OK);
+ }
+}
diff --git a/script/dev/start-workspace-backend.sh b/script/dev/start-workspace-backend.sh
index 25e589fb4e..ee5ea3ef0e 100755
--- a/script/dev/start-workspace-backend.sh
+++ b/script/dev/start-workspace-backend.sh
@@ -26,14 +26,34 @@ resolve_mapped_port() {
GREPTIME_HTTP_PORT="${GREPTIME_HTTP_PORT:-$(resolve_mapped_port 4000 4000)}"
GREPTIME_GRPC_PORT="${GREPTIME_GRPC_PORT:-$(resolve_mapped_port 4001 4001)}"
+export WAREHOUSE_STORE_DUCKDB_ENABLED="${WAREHOUSE_STORE_DUCKDB_ENABLED:-false}"
+export WAREHOUSE_STORE_GREPTIME_ENABLED="${WAREHOUSE_STORE_GREPTIME_ENABLED:-true}"
export WAREHOUSE_STORE_GREPTIME_HTTP_ENDPOINT="${WAREHOUSE_STORE_GREPTIME_HTTP_ENDPOINT:-http://127.0.0.1:${GREPTIME_HTTP_PORT}}"
export WAREHOUSE_STORE_GREPTIME_GRPC_ENDPOINTS="${WAREHOUSE_STORE_GREPTIME_GRPC_ENDPOINTS:-127.0.0.1:${GREPTIME_GRPC_PORT}}"
export WAREHOUSE_STORE_GREPTIME_EXPIRE_TIME="${WAREHOUSE_STORE_GREPTIME_EXPIRE_TIME:-1d}"
+require_greptime() {
+ local health_endpoint="${WAREHOUSE_STORE_GREPTIME_HTTP_ENDPOINT%/}/health"
+ local max_attempts="${GREPTIME_HEALTH_ATTEMPTS:-20}"
+ local attempt
+
+ for ((attempt = 1; attempt <= max_attempts; attempt++)); do
+ if curl --fail --silent --show-error --max-time 2 "${health_endpoint}" >/dev/null; then
+ return
+ fi
+ sleep 0.5
+ done
+
+ printf 'workspace backend requires a healthy GreptimeDB at %s\n' "${health_endpoint}" >&2
+ return 1
+}
+
printf 'workspace backend Greptime HTTP endpoint: %s\n' "${WAREHOUSE_STORE_GREPTIME_HTTP_ENDPOINT}"
printf 'workspace backend Greptime gRPC endpoints: %s\n' "${WAREHOUSE_STORE_GREPTIME_GRPC_ENDPOINTS}"
printf 'workspace backend Greptime expire time: %s\n' "${WAREHOUSE_STORE_GREPTIME_EXPIRE_TIME}"
+require_greptime
+
cd "${ROOT_DIR}"
./mvnw \
diff --git a/web-app/package.json b/web-app/package.json
index 0e21a80e66..bcec6eeaed 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -51,6 +51,7 @@
"i18next": "26.3.6",
"react": "19.2.7",
"react-dom": "19.2.7",
+ "react-grid-layout": "2.2.3",
"react-i18next": "17.0.9",
"react-router": "7.18.1",
"react-router-dom": "7.18.1",
diff --git a/web-app/pnpm-lock.yaml b/web-app/pnpm-lock.yaml
index a7c2633c4e..680927286b 100644
--- a/web-app/pnpm-lock.yaml
+++ b/web-app/pnpm-lock.yaml
@@ -74,6 +74,9 @@ importers:
react-dom:
specifier: 19.2.7
version: 19.2.7(react@19.2.7)
+ react-grid-layout:
+ specifier: 2.2.3
+ version: 2.2.3(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
react-i18next:
specifier: 17.0.9
version: 17.0.9(i18next@26.3.6(typescript@5.9.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(typescript@5.9.3)
@@ -1781,6 +1784,9 @@ packages:
fast-deep-equal@3.1.3:
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
+ fast-equals@4.0.3:
+ resolution: {integrity: sha512-G3BSX9cfKttjr+2o1O22tYMLq0DPluZnYtq1rXumE1SpL/F/SLIfHx08WYQoWSIpeMYf8sRbJ8++71+v6Pnxfg==}
+
fast-json-stable-stringify@2.1.0:
resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}
@@ -2671,6 +2677,18 @@ packages:
peerDependencies:
react: ^19.2.7
+ react-draggable@4.7.1:
+ resolution: {integrity: sha512-wa3tzfFnYt3yaZLuyU58fl1TNunfWfBekDgWhZA1+gb2jnp42wZ0ymuopR6M5kqDYmm4hKmzGlcKWjZf3Zb6RQ==}
+ peerDependencies:
+ react: '>= 16.3.0'
+ react-dom: '>= 16.3.0'
+
+ react-grid-layout@2.2.3:
+ resolution: {integrity: sha512-OAEJHBxmfuxQfVtZwRzmsokijGlBgzYIJ7MUlLk/VSa43SaGzu15w5D0P2RDrfX5EvP9POMbL6bFrai/huDzbQ==}
+ peerDependencies:
+ react: '>= 16.3.0'
+ react-dom: '>= 16.3.0'
+
react-i18next@17.0.9:
resolution: {integrity: sha512-buLzOSqHtXxjf+qgSrLWNTXVZ1jSwO6kUv3uJqSP1roGBPgNnbhFm7OmdVwWcgf2gIbUyP0J333uPyx+Btsi3w==}
peerDependencies:
@@ -2702,6 +2720,12 @@ packages:
'@types/react': '>=16'
react: '>=16'
+ react-resizable@3.2.0:
+ resolution: {integrity: sha512-3NKQ0SLZV7rs3LQHeXlOzDSRQfFrkX6TVet77/Qk03zqiZyee37b7N8/gwDJAA8UUjRz7PdWCCy49hcso45SMQ==}
+ peerDependencies:
+ react: '>= 16.3'
+ react-dom: '>= 16.3'
+
react-router-dom@7.18.1:
resolution: {integrity: sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==}
engines: {node: '>=20.0.0'}
@@ -5086,6 +5110,8 @@ snapshots:
fast-deep-equal@3.1.3: {}
+ fast-equals@4.0.3: {}
+
fast-json-stable-stringify@2.1.0: {}
fast-levenshtein@2.0.6: {}
@@ -6124,6 +6150,24 @@ snapshots:
react: 19.2.7
scheduler: 0.27.0
+ react-draggable@4.7.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
+ dependencies:
+ clsx: 2.1.1
+ prop-types: 15.8.1
+ react: 19.2.7
+ react-dom: 19.2.7(react@19.2.7)
+
+ react-grid-layout@2.2.3(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
+ dependencies:
+ clsx: 2.1.1
+ fast-equals: 4.0.3
+ prop-types: 15.8.1
+ react: 19.2.7
+ react-dom: 19.2.7(react@19.2.7)
+ react-draggable: 4.7.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
+ react-resizable: 3.2.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
+ resize-observer-polyfill: 1.5.1
+
react-i18next@17.0.9(i18next@26.3.6(typescript@5.9.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(typescript@5.9.3):
dependencies:
'@babel/runtime': 7.29.7
@@ -6161,6 +6205,13 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ react-resizable@3.2.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
+ dependencies:
+ prop-types: 15.8.1
+ react: 19.2.7
+ react-dom: 19.2.7(react@19.2.7)
+ react-draggable: 4.7.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
+
react-router-dom@7.18.1(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
dependencies:
react: 19.2.7
diff --git a/web-app/scripts/bundle-limits-contract.test.mjs b/web-app/scripts/bundle-limits-contract.test.mjs
index a97b86cfe0..5bbc9759bf 100644
--- a/web-app/scripts/bundle-limits-contract.test.mjs
+++ b/web-app/scripts/bundle-limits-contract.test.mjs
@@ -25,7 +25,7 @@ import bundleLimits from './bundle-limits.json' with { type: 'json' };
test('vendor chunks stay within the application chunk warning boundary', () => {
const chunkWarningBytes = bundleLimits.chunkWarningKilobytes * 1024;
- const approvedTotalJavaScriptCeiling = 6.25 * 1024 * 1024;
+ const approvedTotalJavaScriptCeiling = 6.3 * 1024 * 1024;
assert.ok(bundleLimits.vendorChunkMinBytes > 0);
assert.ok(bundleLimits.vendorChunkMinBytes <= bundleLimits.vendorChunkMaxBytes);
diff --git a/web-app/scripts/bundle-limits.json b/web-app/scripts/bundle-limits.json
index 77381b6eef..eba1da0a5f 100644
--- a/web-app/scripts/bundle-limits.json
+++ b/web-app/scripts/bundle-limits.json
@@ -3,5 +3,5 @@
"vendorChunkMinBytes": 512000,
"vendorChunkMaxBytes": 614400,
"shellGzipBytes": 460800,
- "totalJavaScriptBytes": 6553600
+ "totalJavaScriptBytes": 6600000
}
diff --git a/web-app/src/app/decorative-boundary-style-contract.test.ts b/web-app/src/app/decorative-boundary-style-contract.test.ts
index f0101c97ec..cbf59ea9a5 100644
--- a/web-app/src/app/decorative-boundary-style-contract.test.ts
+++ b/web-app/src/app/decorative-boundary-style-contract.test.ts
@@ -9,8 +9,8 @@ import { describe, expect, it } from 'vitest';
import noticeRuleEditorStyles from '@/features/alert/notice-rule/components/notice-rule-editor.module.css?raw';
import alertRuleEditorStyles from '@/features/alert/shared/alert-rule-editor.module.css?raw';
-import monitorDetailStyles from '@/features/monitor/components/monitor-detail-view.module.css?raw';
import monitorListStyles from '@/features/monitor/components/monitor-list.module.css?raw';
+import monitorWorkbenchStyles from '@/features/monitor/components/monitor-metric-workbench.module.css?raw';
import messageServerStyles from '@/features/settings/message-server/pages/message-server-page.module.css?raw';
import objectStoreStyles from '@/features/settings/object-store/components/object-store.module.css?raw';
import statusManagementStyles from '@/features/status/management/components/status-management.module.css?raw';
@@ -44,7 +44,9 @@ describe('decorative boundary style contract', () => {
it('keeps toolbars, summaries, and workflow navigation visually open', () => {
expect(ruleBody(monitorListStyles, /\.bulk\s*\{(?<body>[^}]*)\}/)).not.toMatch(horizontalBorder);
- expect(ruleBody(monitorDetailStyles, /\.summaryStrip\s*\{(?<body>[^}]*)\}/)).not.toMatch(horizontalBorder);
+ expect(ruleBody(monitorWorkbenchStyles, /\.metricToolbarPrimary[^{]*\{(?<body>[^}]*)\}/)).not.toMatch(
+ horizontalBorder
+ );
expect(ruleBody(notificationWorkspaceStyles, /\.workspace\s*\{(?<body>[^}]*)\}/)).not.toMatch(horizontalBorder);
expect(ruleBody(statusManagementStyles, /\.section\s*\{(?<body>[^}]*)\}/)).not.toMatch(horizontalBorder);
});
diff --git a/web-app/src/app/main.tsx b/web-app/src/app/main.tsx
index 056f189c39..e2aefd200a 100644
--- a/web-app/src/app/main.tsx
+++ b/web-app/src/app/main.tsx
@@ -17,6 +17,7 @@
import '@ant-design/v5-patch-for-react-19';
import 'antd/dist/reset.css';
+import 'react-grid-layout/css/styles.css';
import './styles.css';
import { StrictMode } from 'react';
diff --git a/web-app/src/app/providers.test.tsx b/web-app/src/app/providers.test.tsx
index 602bf4d123..fecaf982f7 100644
--- a/web-app/src/app/providers.test.tsx
+++ b/web-app/src/app/providers.test.tsx
@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { useRuntimeTheme } from '@/core/runtime-theme-context';
import { initializeI18n } from '@/core/i18n/i18n';
+import { PassportPageFrame } from '@/features/auth/pages/passport-page-frame';
import { AppProviders } from './providers';
@@ -85,4 +86,21 @@ describe('AppProviders theme contract', () => {
expect(screen.getByTestId('theme')).toHaveTextContent('default');
expect(screen.getByTestId('background')).toHaveTextContent('#f5f6f8');
});
+
+ it('keeps passport content light without changing the signed-in runtime preference', async () => {
+ localStorage.setItem('hertzbeat.theme', 'dark');
+
+ render(
+ <AppProviders>
+ <PassportPageFrame>
+ <ThemeProbe />
+ </PassportPageFrame>
+ </AppProviders>
+ );
+
+ await screen.findByTestId('probe');
+ expect(screen.getByTestId('theme')).toHaveTextContent('dark');
+ expect(screen.getByTestId('background')).toHaveTextContent('#f5f6f8');
+ expect(localStorage.getItem('hertzbeat.theme')).toBe('dark');
+ });
});
diff --git a/web-app/src/app/providers.tsx b/web-app/src/app/providers.tsx
index 3950471e7c..4a90f2d86a 100644
--- a/web-app/src/app/providers.tsx
+++ b/web-app/src/app/providers.tsx
@@ -29,7 +29,7 @@ import {
} from '@/core/runtime-preferences';
import { RuntimeThemeContext } from '@/core/runtime-theme-context';
-import { createHertzBeatTheme } from './theme/hertzbeat-theme';
+import { createHertzBeatTheme } from '@/shared/theme/hertzbeat-theme';
function RuntimeProviders({ children }: PropsWithChildren) {
const { i18n: runtimeI18n } = useTranslation();
diff --git a/web-app/src/app/styles.css b/web-app/src/app/styles.css
index 3cc191548b..3f64829902 100644
--- a/web-app/src/app/styles.css
+++ b/web-app/src/app/styles.css
@@ -84,7 +84,8 @@
text-rendering: optimizeLegibility;
}
-:root[data-theme='default'] {
+:root[data-theme='default'],
+[data-theme-scope='default'] {
--hb-bg-canvas: #f5f6f8;
--hb-bg-chrome: #ffffff;
--hb-bg-navigation: #ffffff;
diff --git a/web-app/src/app/theme/hertzbeat-theme.test.ts b/web-app/src/app/theme/hertzbeat-theme.test.ts
index 3fd88d2ade..9d86d46b69 100644
--- a/web-app/src/app/theme/hertzbeat-theme.test.ts
+++ b/web-app/src/app/theme/hertzbeat-theme.test.ts
@@ -8,7 +8,7 @@
import { theme } from 'antd';
import { describe, expect, it } from 'vitest';
-import { createHertzBeatTheme } from './hertzbeat-theme';
+import { createHertzBeatTheme } from '@/shared/theme/hertzbeat-theme';
describe('HertzBeat semantic theme', () => {
it('maps the dense purple operator tokens into Ant Design', () => {
diff --git a/web-app/src/assets/i18n/en-us.json b/web-app/src/assets/i18n/en-us.json
index 78a720acb1..17986ec1cb 100644
--- a/web-app/src/assets/i18n/en-us.json
+++ b/web-app/src/assets/i18n/en-us.json
@@ -1039,19 +1039,22 @@
}
},
"auth": {
- "title": "Sign in to HertzBeat",
+ "title": "Sign in to Apache HertzBeat",
"description": "Use your HertzBeat account to continue.",
"passport": {
- "description": "Open-source monitoring and observability for infrastructure and applications.",
+ "description": "Open-source monitoring and observability for infrastructure and applications",
+ "accessibleSummary": "Apache HertzBeat™ brings together agentless monitoring, metrics, logs, traces, extensible collection, distributed reach, alerting, self-hosting, and AI.",
+ "introductionPrefix": "Apache HertzBeat™",
+ "introductionAiAutomation": "AI for queries, diagnosis, and action",
"headingLineOne": "Monitor infrastructure.",
"headingLineTwo": "Observe applications.",
"capabilityListLabel": "HertzBeat capabilities",
- "capability1": "Agentless monitoring for databases, operating systems, middleware, networks, and APIs.",
- "capability2": "Metrics, logs, and traces through OpenTelemetry.",
- "capability3": "Custom collection protocols and reusable monitor definitions.",
- "capability4": "Distributed collectors for isolated networks and larger environments.",
- "capability5": "Alert rules, silences, notifications, and public status pages.",
- "capability6": "Self-hosted operation within your own deployment and storage boundaries."
+ "capability1": "Agentless monitoring across infrastructure",
+ "capability2": "Metrics, logs, and traces in one view",
+ "capability3": "Extensible collection, reusable definitions",
+ "capability4": "Distributed collection across isolated networks",
+ "capability5": "Alerts, notifications, and status publishing in one place",
+ "capability6": "Self-hosted, with your data under control"
},
"checkingSession": "Checking the current session",
"username": "Username",
@@ -1312,6 +1315,7 @@
},
"favorite": "Favorite",
"unfavorite": "Remove favorite",
+ "expand": "Expand metric group",
"favoriteSaved": "Favorite metrics updated.",
"favoriteFailed": "Favorite metrics could not be updated.",
"noCatalog": "This monitor exposes no numeric metric catalog.",
@@ -1321,7 +1325,75 @@
"unit": "Unit",
"series": "Series",
"time": "Time",
- "value": "Value"
+ "value": "Value",
+ "search": "Search metrics",
+ "searchPlaceholder": "Search groups or fields",
+ "groupFilter": "Metric group",
+ "allGroups": "All groups",
+ "metricView": "Metric view",
+ "allMetrics": "All metrics",
+ "allMetricCount": "All {{count}}",
+ "favoriteMetricCount": "Favorites {{count}}",
+ "latestSample": "Latest sample",
+ "live": "Live",
+ "paused": "Paused",
+ "returnLive": "Return live",
+ "pause": "Pause live refresh",
+ "groupNavigator": "Metric groups",
+ "groupCount": "{{count}} groups",
+ "favoriteCount": "{{count}} favorites",
+ "itemCount": "{{count}} items",
+ "currentValues": "Current metric values",
+ "value": {
+ "open": "View the full value for {{field}}",
+ "title": "Metric value · {{field}}",
+ "copy": "Copy value",
+ "copied": "Copied",
+ "error": "Copy failed"
+ },
+ "noMatches": "No metric values match the current filters.",
+ "historyTrend": "History trend",
+ "currentValue": "Current",
+ "historyMode": "History value mode",
+ "rawValues": "Raw values",
+ "aggregatedValues": "Aggregated values",
+ "minimum": "Min",
+ "maximum": "Max",
+ "average": "Avg",
+ "samples": "Samples",
+ "refreshHistory": "Refresh history",
+ "collapseHistory": "Collapse history",
+ "expandHistory": "Expand history",
+ "layout": {
+ "title": "Panel layout",
+ "auto": "Automatic",
+ "custom": "Custom",
+ "edit": "Edit layout",
+ "editing": "Editing layout",
+ "editHint": "Drag a panel title to move it; drag the lower-right corner to resize. Smaller screens adapt automatically.",
+ "localFallback": "Using an automatic layout",
+ "saved": "Layout saved.",
+ "conflict": "The layout changed elsewhere. The latest version has been loaded.",
+ "saveFailed": "The layout could not be saved.",
+ "resetDone": "Automatic layout restored.",
+ "historyShorter": "Shorter history",
+ "historyTaller": "Taller history",
+ "historyCollapse": "Collapse history",
+ "historyExpand": "Expand history",
+ "reset": "Reset",
+ "resetConfirm": "Restore the automatic panel layout?",
+ "card": "Panel layout controls",
+ "drag": "Drag panel",
+ "earlier": "Move panel earlier",
+ "later": "Move panel later",
+ "narrower": "Make panel narrower",
+ "wider": "Make panel wider",
+ "shorter": "Make panel shorter",
+ "taller": "Make panel taller",
+ "collapseCard": "Collapse panel",
+ "expandCard": "Expand panel",
+ "resizeHistory": "Resize history panel"
+ }
},
"alertNavigation": {
"events": "Alert events",
diff --git a/web-app/src/assets/i18n/ja-jp.json b/web-app/src/assets/i18n/ja-jp.json
index 2192562b57..462e1e2c3a 100644
--- a/web-app/src/assets/i18n/ja-jp.json
+++ b/web-app/src/assets/i18n/ja-jp.json
@@ -1036,19 +1036,22 @@
}
},
"auth": {
- "title": "HertzBeat にログイン",
+ "title": "Apache HertzBeat にログイン",
"description": "HertzBeat アカウントで続行します。",
"passport": {
- "description": "インフラストラクチャとアプリケーションのためのオープンソース監視・可観測性プラットフォーム。",
+ "description": "インフラストラクチャとアプリケーションのためのオープンソース監視・可観測性プラットフォーム",
+ "accessibleSummary": "Apache HertzBeat™ はエージェントレス監視を起点に、メトリクス、ログ、トレースを統合し、拡張可能な収集、分散 Collector、アラート、セルフホスト、AI を提供します。",
+ "introductionPrefix": "Apache HertzBeat™",
+ "introductionAiAutomation": "AI で検索、診断、タスクを実行",
"headingLineOne": "インフラを監視し、",
"headingLineTwo": "アプリを可視化。",
"capabilityListLabel": "HertzBeat の機能",
- "capability1": "データベース、OS、ミドルウェア、ネットワーク、API をエージェントなしで監視。",
- "capability2": "OpenTelemetry を通じてメトリクス、ログ、トレースを取り込み。",
- "capability3": "収集プロトコルをカスタマイズし、監視定義を再利用。",
- "capability4": "分散 Collector で分離ネットワークや大規模環境に対応。",
- "capability5": "アラートルール、サイレンス、通知、公開ステータスページを管理。",
- "capability6": "独自のデプロイとストレージ境界内でセルフホスト運用。"
+ "capability1": "エージェントレスで幅広い対象を監視",
+ "capability2": "メトリクス、ログ、トレースを統合",
+ "capability3": "収集を拡張し、監視定義を再利用",
+ "capability4": "分散収集で隔離ネットワークを監視",
+ "capability5": "アラート、通知、状態公開を一元管理",
+ "capability6": "セルフホストでデータを管理"
},
"checkingSession": "現在のセッションを確認しています",
"username": "ユーザー名",
@@ -1309,6 +1312,7 @@
},
"favorite": "お気に入り",
"unfavorite": "お気に入り解除",
+ "expand": "メトリクスグループを拡大",
"favoriteSaved": "お気に入りを更新しました。",
"favoriteFailed": "お気に入りを更新できませんでした。",
"noCatalog": "数値メトリクスがありません。",
@@ -1318,7 +1322,75 @@
"unit": "単位",
"series": "系列",
"time": "時刻",
- "value": "値"
+ "value": "値",
+ "search": "メトリクスを検索",
+ "searchPlaceholder": "グループまたはフィールドを検索",
+ "groupFilter": "メトリクスグループ",
+ "allGroups": "すべてのグループ",
+ "metricView": "メトリクス表示",
+ "allMetrics": "すべてのメトリクス",
+ "allMetricCount": "すべて {{count}}",
+ "favoriteMetricCount": "お気に入り {{count}}",
+ "latestSample": "最新サンプル",
+ "live": "ライブ",
+ "paused": "一時停止",
+ "returnLive": "ライブに戻る",
+ "pause": "ライブ更新を一時停止",
+ "groupNavigator": "メトリクスグループ",
+ "groupCount": "{{count}} グループ",
+ "favoriteCount": "お気に入り {{count}}",
+ "itemCount": "{{count}} 項目",
+ "currentValues": "現在のメトリクス値",
+ "value": {
+ "open": "{{field}} の完全な値を表示",
+ "title": "メトリクス値 · {{field}}",
+ "copy": "値をコピー",
+ "copied": "コピー済み",
+ "error": "コピーに失敗しました"
+ },
+ "noMatches": "現在のフィルターに一致するメトリクスはありません。",
+ "historyTrend": "履歴トレンド",
+ "currentValue": "現在値",
+ "historyMode": "履歴値モード",
+ "rawValues": "生データ",
+ "aggregatedValues": "集計値",
+ "minimum": "最小",
+ "maximum": "最大",
+ "average": "平均",
+ "samples": "サンプル",
+ "refreshHistory": "履歴を更新",
+ "collapseHistory": "履歴を折りたたむ",
+ "expandHistory": "履歴を展開",
+ "layout": {
+ "title": "パネルレイアウト",
+ "auto": "自動",
+ "custom": "カスタム",
+ "edit": "レイアウトを編集",
+ "editing": "レイアウトを編集中",
+ "editHint": "パネルのタイトルをドラッグして移動し、右下隅をドラッグしてサイズを変更します。小画面では自動調整します。",
+ "localFallback": "自動レイアウトを使用中",
+ "saved": "レイアウトを保存しました。",
+ "conflict": "別の場所でレイアウトが更新されたため、最新版を読み込みました。",
+ "saveFailed": "レイアウトを保存できませんでした。",
+ "resetDone": "自動レイアウトに戻しました。",
+ "historyShorter": "履歴を低く",
+ "historyTaller": "履歴を高く",
+ "historyCollapse": "履歴を折りたたむ",
+ "historyExpand": "履歴を展開",
+ "reset": "リセット",
+ "resetConfirm": "自動パネルレイアウトに戻しますか?",
+ "card": "パネルレイアウト操作",
+ "drag": "パネルをドラッグ",
+ "earlier": "パネルを前へ",
+ "later": "パネルを後へ",
+ "narrower": "パネルを狭く",
+ "wider": "パネルを広く",
+ "shorter": "パネルを低く",
+ "taller": "パネルを高く",
+ "collapseCard": "パネルを折りたたむ",
+ "expandCard": "パネルを展開",
+ "resizeHistory": "履歴パネルの高さを変更"
+ }
},
"alertNavigation": {
"events": "アラートイベント",
diff --git a/web-app/src/assets/i18n/pt-br.json b/web-app/src/assets/i18n/pt-br.json
index 4a3cf7db2c..aeb2040972 100644
--- a/web-app/src/assets/i18n/pt-br.json
+++ b/web-app/src/assets/i18n/pt-br.json
@@ -1044,19 +1044,22 @@
}
},
"auth": {
- "title": "Entrar no HertzBeat",
+ "title": "Entrar no Apache HertzBeat",
"description": "Use sua conta HertzBeat para continuar.",
"passport": {
- "description": "Monitoramento e observabilidade de código aberto para infraestrutura e aplicações.",
+ "description": "Monitoramento e observabilidade de código aberto para infraestrutura e aplicações",
+ "accessibleSummary": "O Apache HertzBeat™ reúne monitoramento sem agentes, métricas, logs, traces, coleta extensível e distribuída, alertas, auto-hospedagem e IA.",
+ "introductionPrefix": "Apache HertzBeat™",
+ "introductionAiAutomation": "IA para consultas, diagnóstico e execução",
"headingLineOne": "Monitore a infraestrutura.",
"headingLineTwo": "Observe as aplicações.",
"capabilityListLabel": "Recursos do HertzBeat",
- "capability1": "Monitoramento sem agente para bancos de dados, sistemas, middleware, redes e APIs.",
- "capability2": "Métricas, logs e traces por meio do OpenTelemetry.",
- "capability3": "Protocolos de coleta personalizados e definições de monitor reutilizáveis.",
- "capability4": "Coletores distribuídos para redes isoladas e ambientes maiores.",
- "capability5": "Regras de alerta, silêncios, notificações e páginas públicas de status.",
- "capability6": "Operação auto-hospedada dentro dos limites da sua implantação e armazenamento."
+ "capability1": "Monitoramento sem agentes para a infraestrutura",
+ "capability2": "Métricas, logs e traces em uma só visão",
+ "capability3": "Coleta extensível e definições reutilizáveis",
+ "capability4": "Coleta distribuída em redes isoladas",
+ "capability5": "Alertas, notificações e status em um só lugar",
+ "capability6": "Auto-hospedado, com seus dados sob controle"
},
"checkingSession": "Verificando a sessão atual",
"username": "Usuário",
@@ -1322,6 +1325,7 @@
},
"favorite": "Favoritar",
"unfavorite": "Remover favorito",
+ "expand": "Expandir grupo de métricas",
"favoriteSaved": "Favoritos atualizados.",
"favoriteFailed": "Não foi possível atualizar os favoritos.",
"noCatalog": "Este monitor não possui métricas numéricas.",
@@ -1331,7 +1335,75 @@
"unit": "Unidade",
"series": "Série",
"time": "Hora",
- "value": "Valor"
+ "value": "Valor",
+ "search": "Pesquisar métricas",
+ "searchPlaceholder": "Pesquisar grupos ou campos",
+ "groupFilter": "Grupo de métricas",
+ "allGroups": "Todos os grupos",
+ "metricView": "Visualização de métricas",
+ "allMetrics": "Todas as métricas",
+ "allMetricCount": "Todas {{count}}",
+ "favoriteMetricCount": "Favoritos {{count}}",
+ "latestSample": "Amostra mais recente",
+ "live": "Ao vivo",
+ "paused": "Pausado",
+ "returnLive": "Voltar ao vivo",
+ "pause": "Pausar atualização ao vivo",
+ "groupNavigator": "Grupos de métricas",
+ "groupCount": "{{count}} grupos",
+ "favoriteCount": "{{count}} favoritos",
+ "itemCount": "{{count}} itens",
+ "currentValues": "Valores atuais das métricas",
+ "value": {
+ "open": "Ver o valor completo de {{field}}",
+ "title": "Valor da métrica · {{field}}",
+ "copy": "Copiar valor",
+ "copied": "Copiado",
+ "error": "Falha ao copiar"
+ },
+ "noMatches": "Nenhuma métrica corresponde aos filtros atuais.",
+ "historyTrend": "Tendência histórica",
+ "currentValue": "Atual",
+ "historyMode": "Modo de valores históricos",
+ "rawValues": "Valores brutos",
+ "aggregatedValues": "Valores agregados",
+ "minimum": "Mín.",
+ "maximum": "Máx.",
+ "average": "Média",
+ "samples": "Amostras",
+ "refreshHistory": "Atualizar histórico",
+ "collapseHistory": "Recolher histórico",
+ "expandHistory": "Expandir histórico",
+ "layout": {
+ "title": "Layout dos painéis",
+ "auto": "Automático",
+ "custom": "Personalizado",
+ "edit": "Editar layout",
+ "editing": "Editando o layout",
+ "editHint": "Arraste o título para mover o painel e o canto inferior direito para redimensionar. Telas menores se adaptam.",
+ "localFallback": "Usando o layout automático",
+ "saved": "Layout salvo.",
+ "conflict": "O layout foi alterado em outro local. A versão mais recente foi carregada.",
+ "saveFailed": "Não foi possível salvar o layout.",
+ "resetDone": "Layout automático restaurado.",
+ "historyShorter": "Histórico menor",
+ "historyTaller": "Histórico maior",
+ "historyCollapse": "Recolher histórico",
+ "historyExpand": "Expandir histórico",
+ "reset": "Redefinir",
+ "resetConfirm": "Restaurar o layout automático dos painéis?",
+ "card": "Controles de layout do painel",
+ "drag": "Arrastar painel",
+ "earlier": "Mover painel para antes",
+ "later": "Mover painel para depois",
+ "narrower": "Deixar painel mais estreito",
+ "wider": "Deixar painel mais largo",
+ "shorter": "Deixar painel mais baixo",
+ "taller": "Deixar painel mais alto",
+ "collapseCard": "Recolher painel",
+ "expandCard": "Expandir painel",
+ "resizeHistory": "Redimensionar painel de histórico"
+ }
},
"alertNavigation": {
"events": "Eventos",
diff --git a/web-app/src/assets/i18n/zh-cn.json b/web-app/src/assets/i18n/zh-cn.json
index 0655ac0c22..96336ac501 100644
--- a/web-app/src/assets/i18n/zh-cn.json
+++ b/web-app/src/assets/i18n/zh-cn.json
@@ -1033,19 +1033,22 @@
}
},
"auth": {
- "title": "登录 HertzBeat",
+ "title": "登录 Apache HertzBeat",
"description": "使用 HertzBeat 账号继续。",
"passport": {
- "description": "面向基础设施和应用的开源监控与可观测平台。",
+ "description": "面向基础设施和应用的开源监控与可观测平台",
+ "accessibleSummary": "Apache HertzBeat™ 以无需 Agent 的传统监控为基础,统一观测指标、日志与链路,并扩展至分布式采集、告警闭环、自托管和 AI 能力。",
+ "introductionPrefix": "Apache HertzBeat™",
+ "introductionAiAutomation": "AI 查询、诊断并执行任务",
"headingLineOne": "监控基础设施,",
"headingLineTwo": "观察应用运行。",
"capabilityListLabel": "HertzBeat 能力",
- "capability1": "无 Agent 监控数据库、操作系统、中间件、网络设备和接口。",
- "capability2": "通过 OpenTelemetry 接入指标、日志和链路。",
- "capability3": "自定义采集协议,并复用监控定义。",
- "capability4": "使用分布式采集器覆盖隔离网络和大型环境。",
- "capability5": "配置告警规则、静默、通知和公开状态页。",
- "capability6": "在自己的部署和存储边界内自托管运行。"
+ "capability1": "无需 Agent,覆盖多类基础设施",
+ "capability2": "指标、日志与链路统一观测",
+ "capability3": "采集可扩展,监控定义可复用",
+ "capability4": "分布式采集覆盖隔离网络",
+ "capability5": "统一管理告警、通知与状态发布",
+ "capability6": "自托管,数据始终由你掌控"
},
"checkingSession": "正在检查当前会话",
"username": "用户名",
@@ -1306,6 +1309,7 @@
},
"favorite": "收藏",
"unfavorite": "取消收藏",
+ "expand": "展开指标组",
"favoriteSaved": "收藏指标已更新。",
"favoriteFailed": "收藏指标更新失败。",
"noCatalog": "该监控没有可用的数值指标目录。",
@@ -1315,7 +1319,75 @@
"unit": "单位",
"series": "序列",
"time": "时间",
- "value": "值"
+ "value": "值",
+ "search": "搜索指标",
+ "searchPlaceholder": "搜索分组或字段",
+ "groupFilter": "指标分组",
+ "allGroups": "全部分组",
+ "metricView": "指标视图",
+ "allMetrics": "全部指标",
+ "allMetricCount": "全部 {{count}}",
+ "favoriteMetricCount": "收藏 {{count}}",
+ "latestSample": "最近采集",
+ "live": "实时",
+ "paused": "已暂停",
+ "returnLive": "返回实时",
+ "pause": "暂停实时刷新",
+ "groupNavigator": "指标分组",
+ "groupCount": "共 {{count}} 个分组",
+ "favoriteCount": "{{count}} 个收藏",
+ "itemCount": "{{count}} 项",
+ "currentValues": "当前指标值",
+ "value": {
+ "open": "查看 {{field}} 的完整值",
+ "title": "指标值 · {{field}}",
+ "copy": "复制完整值",
+ "copied": "已复制",
+ "error": "复制失败"
+ },
+ "noMatches": "当前筛选条件下没有匹配的指标值。",
+ "historyTrend": "历史趋势",
+ "currentValue": "当前",
+ "historyMode": "历史值模式",
+ "rawValues": "原始值",
+ "aggregatedValues": "聚合值",
+ "minimum": "最小值",
+ "maximum": "最大值",
+ "average": "平均值",
+ "samples": "样本数",
+ "refreshHistory": "刷新历史趋势",
+ "collapseHistory": "收起历史趋势",
+ "expandHistory": "展开历史趋势",
+ "layout": {
+ "title": "面板布局",
+ "auto": "自动",
+ "custom": "自定义",
+ "edit": "编辑布局",
+ "editing": "正在编辑布局",
+ "editHint": "拖动面板标题移动,拖拽右下角缩放;小屏自动适配。",
+ "localFallback": "当前使用自动布局",
+ "saved": "布局已保存。",
+ "conflict": "布局已在其他位置更新,现已加载最新版本。",
+ "saveFailed": "布局保存失败。",
+ "resetDone": "已恢复自动布局。",
+ "historyShorter": "缩短历史区",
+ "historyTaller": "加高历史区",
+ "historyCollapse": "收起历史区",
+ "historyExpand": "展开历史区",
+ "reset": "重置",
+ "resetConfirm": "恢复自动面板布局?",
+ "card": "面板布局控制",
+ "drag": "拖动面板",
+ "earlier": "前移面板",
+ "later": "后移面板",
+ "narrower": "缩窄面板",
+ "wider": "加宽面板",
+ "shorter": "缩短面板",
+ "taller": "加高面板",
+ "collapseCard": "收起面板",
+ "expandCard": "展开面板",
+ "resizeHistory": "调整历史区高度"
+ }
},
"alertNavigation": {
"events": "告警事件",
diff --git a/web-app/src/assets/i18n/zh-tw.json b/web-app/src/assets/i18n/zh-tw.json
index e3634367dc..a7c316c92c 100644
--- a/web-app/src/assets/i18n/zh-tw.json
+++ b/web-app/src/assets/i18n/zh-tw.json
@@ -1033,19 +1033,22 @@
}
},
"auth": {
- "title": "登入 HertzBeat",
+ "title": "登入 Apache HertzBeat",
"description": "使用 HertzBeat 帳號繼續。",
"passport": {
- "description": "面向基礎設施與應用程式的開源監控與可觀測平台。",
+ "description": "面向基礎設施與應用程式的開源監控與可觀測平台",
+ "accessibleSummary": "Apache HertzBeat™ 以無需 Agent 的傳統監控為基礎,統一觀測指標、日誌與鏈路,並擴展至分散式採集、告警閉環、自託管和 AI 能力。",
+ "introductionPrefix": "Apache HertzBeat™",
+ "introductionAiAutomation": "AI 查詢、診斷並執行任務",
"headingLineOne": "監控基礎設施,",
"headingLineTwo": "觀察應用程式運作。",
"capabilityListLabel": "HertzBeat 功能",
- "capability1": "無 Agent 監控資料庫、作業系統、中介軟體、網路設備與介面。",
- "capability2": "透過 OpenTelemetry 接入指標、日誌與鏈路。",
- "capability3": "自訂採集協定,並重複使用監控定義。",
- "capability4": "使用分散式採集器涵蓋隔離網路與大型環境。",
- "capability5": "設定告警規則、靜默、通知與公開狀態頁。",
- "capability6": "在自己的部署與儲存邊界內自託管運作。"
+ "capability1": "無需 Agent,涵蓋多類基礎設施",
+ "capability2": "指標、日誌與鏈路統一觀測",
+ "capability3": "採集可擴充,監控定義可重複使用",
+ "capability4": "分散式採集涵蓋隔離網路",
+ "capability5": "統一管理告警、通知與狀態發布",
+ "capability6": "自託管,資料始終由你掌控"
},
"checkingSession": "正在檢查目前工作階段",
"username": "使用者名稱",
@@ -1306,6 +1309,7 @@
},
"favorite": "收藏",
"unfavorite": "取消收藏",
+ "expand": "展開指標群組",
"favoriteSaved": "收藏指標已更新。",
"favoriteFailed": "收藏指標更新失敗。",
"noCatalog": "此監控沒有可用的數值指標。",
@@ -1315,7 +1319,75 @@
"unit": "單位",
"series": "序列",
"time": "時間",
- "value": "值"
+ "value": "值",
+ "search": "搜尋指標",
+ "searchPlaceholder": "搜尋分組或欄位",
+ "groupFilter": "指標分組",
+ "allGroups": "全部分組",
+ "metricView": "指標檢視",
+ "allMetrics": "全部指標",
+ "allMetricCount": "全部 {{count}}",
+ "favoriteMetricCount": "收藏 {{count}}",
+ "latestSample": "最近採集",
+ "live": "即時",
+ "paused": "已暫停",
+ "returnLive": "返回即時",
+ "pause": "暫停即時更新",
+ "groupNavigator": "指標分組",
+ "groupCount": "共 {{count}} 個分組",
+ "favoriteCount": "{{count}} 個收藏",
+ "itemCount": "{{count}} 項",
+ "currentValues": "目前指標值",
+ "value": {
+ "open": "查看 {{field}} 的完整值",
+ "title": "指標值 · {{field}}",
+ "copy": "複製完整值",
+ "copied": "已複製",
+ "error": "複製失敗"
+ },
+ "noMatches": "目前篩選條件下沒有符合的指標值。",
+ "historyTrend": "歷史趨勢",
+ "currentValue": "目前",
+ "historyMode": "歷史值模式",
+ "rawValues": "原始值",
+ "aggregatedValues": "聚合值",
+ "minimum": "最小值",
+ "maximum": "最大值",
+ "average": "平均值",
+ "samples": "樣本數",
+ "refreshHistory": "重新整理歷史趨勢",
+ "collapseHistory": "收合歷史趨勢",
+ "expandHistory": "展開歷史趨勢",
+ "layout": {
+ "title": "面板佈局",
+ "auto": "自動",
+ "custom": "自訂",
+ "edit": "編輯佈局",
+ "editing": "正在編輯佈局",
+ "editHint": "拖動面板標題移動,拖曳右下角縮放;小螢幕自動調整。",
+ "localFallback": "目前使用自動佈局",
+ "saved": "佈局已儲存。",
+ "conflict": "佈局已在其他位置更新,現已載入最新版本。",
+ "saveFailed": "無法儲存佈局。",
+ "resetDone": "已恢復自動佈局。",
+ "historyShorter": "縮短歷史區",
+ "historyTaller": "加高歷史區",
+ "historyCollapse": "收合歷史區",
+ "historyExpand": "展開歷史區",
+ "reset": "重設",
+ "resetConfirm": "恢復自動面板佈局?",
+ "card": "面板佈局控制",
+ "drag": "拖曳面板",
+ "earlier": "前移面板",
+ "later": "後移面板",
+ "narrower": "縮窄面板",
+ "wider": "加寬面板",
+ "shorter": "縮短面板",
+ "taller": "加高面板",
+ "collapseCard": "收合面板",
+ "expandCard": "展開面板",
+ "resizeHistory": "調整歷史區高度"
+ }
},
"alertNavigation": {
"events": "警報事件",
diff --git a/web-app/src/features/auth/pages/login-page-style-contract.test.ts b/web-app/src/features/auth/pages/login-page-style-contract.test.ts
index f1d1856ded..30b0952039 100644
--- a/web-app/src/features/auth/pages/login-page-style-contract.test.ts
+++ b/web-app/src/features/auth/pages/login-page-style-contract.test.ts
@@ -12,14 +12,39 @@ import stylesheet from './login-page.module.css?raw';
describe('login page visual contract', () => {
it('uses the original artwork on desktop and preserves its light-theme treatment', () => {
expect(stylesheet).toContain("url('/assets/bg.png')");
- expect(stylesheet).toMatch(/@media \(min-width: 960px\)[\s\S]*\.page\s*{[^}]*linear-gradient/s);
- expect(stylesheet).toMatch(/:global\(:root\[data-theme='default'\]\)\s+\.page/);
+ expect(stylesheet).toMatch(/@media \(min-width: 960px\)[\s\S]*\.page\s*{[^}]*background-image:\s*url/s);
+ expect(stylesheet).not.toContain(":root[data-theme='default']");
expect(stylesheet).toMatch(/@media \(min-width: 960px\)/);
});
it('keeps the form narrow, the explanation desktop-only, and the passport route responsive', () => {
expect(stylesheet).toMatch(/\.formRegion\s*{[^}]*width:\s*min\(368px, 100%\)/s);
+ expect(stylesheet).toMatch(/\.introductionBrand\s*{[^}]*width:\s*280px/s);
+ expect(stylesheet).toMatch(/@media \(min-width: 960px\)[\s\S]*\.brandHeader\s*{[^}]*display:\s*none/s);
expect(stylesheet).toMatch(/@media \(max-width: 959px\)[\s\S]*\.introduction\s*{[^}]*display:\s*none/s);
expect(stylesheet).toMatch(/body:has\(\[data-passport-page='true'\]\)[^}]*min-width:\s*0/s);
});
+
+ it('keeps each capability on one fitted line and rolls the completed line before typing the next', () => {
+ expect(stylesheet).toMatch(/\.introductionPositioning\s*{[^}]*margin-bottom:\s*clamp\(26px,\s*2\.5vw,\s*32px\)/s);
+ expect(stylesheet).toMatch(/\.introductionPhraseStage\s*{[^}]*block-size:\s*1\.45em/s);
+ expect(stylesheet).toMatch(/\.introductionTypingLine\s*{[^}]*white-space:\s*nowrap/s);
+ expect(stylesheet).toContain('@keyframes passportIntroductionRollOut');
+ expect(stylesheet).toContain('@keyframes passportIntroductionRollIn');
+ expect(stylesheet).toMatch(/@keyframes passportIntroductionRollOut[\s\S]*translateY\(-115%\)/s);
+ expect(stylesheet).toMatch(/@keyframes passportIntroductionRollIn[\s\S]*translateY\(115%\)/s);
+ expect(stylesheet).toContain('@keyframes passportIntroductionCursor');
+ expect(stylesheet).toMatch(/\.introductionMeasure\s*{[^}]*white-space:\s*nowrap/s);
+ expect(stylesheet).toMatch(
+ /@media \(prefers-reduced-motion:\s*reduce\)[\s\S]*\.introductionCursor[^}]*animation:\s*none/s
+ );
+ });
+
+ it('uses a translucent glass login panel without a secondary introduction paragraph', () => {
+ expect(stylesheet).not.toContain('.introductionDescription');
+ expect(stylesheet).toMatch(
+ /@media \(min-width: 960px\)[\s\S]*\.panel\s*{[^}]*background:\s*color-mix\(in srgb, var\(--hb-bg-raised\) 58%, transparent\)/s
+ );
+ expect(stylesheet).toMatch(/\.panel\s*{[^}]*backdrop-filter:\s*blur\(18px\) saturate\(1\.15\)/s);
+ });
});
diff --git a/web-app/src/features/auth/pages/login-page.module.css b/web-app/src/features/auth/pages/login-page.module.css
index 7f614bd80e..6f006ae49e 100644
--- a/web-app/src/features/auth/pages/login-page.module.css
+++ b/web-app/src/features/auth/pages/login-page.module.css
@@ -27,17 +27,9 @@
flex-direction: column;
align-items: center;
align-self: center;
- gap: 8px;
text-align: center;
}
-.brandDescription {
- margin: 0;
- color: var(--hb-text-secondary);
- font-size: 14px;
- line-height: 1.6;
-}
-
.brandFull {
position: relative;
width: 220px;
@@ -50,10 +42,6 @@
display: block;
width: 220px;
height: 55px;
- filter: brightness(0) invert(1);
-}
-
-:global(:root[data-theme='default']) .brandLogoFull {
filter: none;
}
@@ -72,29 +60,126 @@
color: var(--hb-text-primary);
}
-.introduction h1 {
- margin: 0 0 34px;
+.screenReaderOnly {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+.introductionHeading {
font-size: clamp(32px, 3.4vw, 48px);
font-weight: 650;
letter-spacing: -0.035em;
line-height: 1.14;
+ text-wrap: balance;
}
-.introduction h1 span {
+.introductionBrand {
display: block;
+ width: 280px;
+ height: 70px;
+ margin-bottom: 4px;
}
-.introduction ul {
- display: grid;
- margin: 0;
- padding-left: 1.15em;
- gap: 15px;
- font-size: 15px;
- line-height: 1.55;
+.introductionPositioning {
+ display: block;
+ max-width: 540px;
+ margin-bottom: clamp(26px, 2.5vw, 32px);
+ font-size: clamp(16px, 1.45vw, 20px);
+ font-weight: 520;
+ letter-spacing: -0.01em;
+ line-height: 1.45;
+}
+
+.introductionPhraseStage {
+ position: relative;
+ display: block;
+ width: 100%;
+ block-size: 1.45em;
+ overflow: hidden;
+ font-size: 34px;
+ line-height: 1.18;
+}
+
+.introductionTypingLine {
+ position: absolute;
+ inset: 0 auto auto 0;
+ display: block;
+ max-width: 100%;
+ white-space: nowrap;
+ will-change: opacity, transform;
+}
+
+.introductionPhrase {
+ display: inline;
}
-.introduction li::marker {
- color: var(--hb-color-primary);
+.introductionCursor {
+ display: inline-block;
+ width: 0.075em;
+ height: 0.95em;
+ margin-left: 0.08em;
+ vertical-align: -0.08em;
+ background: currentColor;
+ animation: passportIntroductionCursor 860ms steps(1, end) infinite;
+}
+
+.introductionMeasure {
+ position: absolute;
+ visibility: hidden;
+ font-size: 34px;
+ white-space: nowrap;
+ pointer-events: none;
+}
+
+.introductionRollOut {
+ animation: passportIntroductionRollOut 460ms cubic-bezier(0.4, 0, 1, 1) both;
+}
+
+.introductionRollIn {
+ animation: passportIntroductionRollIn 460ms cubic-bezier(0.22, 1, 0.36, 1) both;
+}
+
+@keyframes passportIntroductionRollOut {
+ from {
+ opacity: 1;
+ transform: translateY(0);
+ }
+
+ to {
+ opacity: 0;
+ transform: translateY(-115%);
+ }
+}
+
+@keyframes passportIntroductionRollIn {
+ from {
+ opacity: 0.28;
+ transform: translateY(115%);
+ }
+
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes passportIntroductionCursor {
+ 0%,
+ 46% {
+ opacity: 1;
+ }
+
+ 47%,
+ 100% {
+ opacity: 0;
+ }
}
.formRegion {
@@ -148,27 +233,36 @@
}
@media (min-width: 960px) {
+ .brandHeader {
+ display: none;
+ }
+
.page {
- background-image: linear-gradient(var(--hb-bg-image-scrim), var(--hb-bg-image-scrim)), url('/assets/bg.png');
+ background-image: url('/assets/bg.png');
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
background-size: cover;
}
- :global(:root[data-theme='default']) .page {
- background-image: url('/assets/bg.png');
- }
-
- :global(:root[data-theme='default']) .brandDescription,
- :global(:root[data-theme='default']) .introduction {
+ .introduction {
color: var(--hb-text-on-image);
text-shadow: var(--hb-shadow-on-image);
}
- :global(:root[data-theme='default']) .panel {
- background: color-mix(in srgb, var(--hb-bg-raised) 94%, transparent);
- backdrop-filter: blur(10px);
+ .panel {
+ border-color: color-mix(in srgb, var(--hb-bg-raised) 72%, transparent);
+ background: color-mix(in srgb, var(--hb-bg-raised) 58%, transparent);
+ -webkit-backdrop-filter: blur(18px) saturate(1.15);
+ backdrop-filter: blur(18px) saturate(1.15);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .introductionCursor,
+ .introductionRollOut,
+ .introductionRollIn {
+ animation: none;
}
}
@@ -203,11 +297,7 @@
}
.brandHeader {
- gap: 4px;
- }
-
- .brandDescription {
- font-size: 13px;
+ gap: 0;
}
.content {
diff --git a/web-app/src/features/auth/pages/login-page.test.tsx b/web-app/src/features/auth/pages/login-page.test.tsx
index 72512d23ce..dee201025b 100644
--- a/web-app/src/features/auth/pages/login-page.test.tsx
+++ b/web-app/src/features/auth/pages/login-page.test.tsx
@@ -149,12 +149,25 @@ describe('LoginPage', () => {
const page = screen.getByRole('main');
const introduction = screen.getByTestId('passport-introduction');
- const capabilityList = within(introduction).getByRole('list');
expect(page).toHaveAttribute('data-passport-page', 'true');
expect(page).toHaveAttribute('data-passport-background', 'legacy-artwork');
+ expect(page).toHaveAttribute('data-theme-scope', 'default');
expect(introduction).toBeInTheDocument();
- expect(within(capabilityList).getAllByRole('listitem')).toHaveLength(6);
+ expect(within(introduction).queryByRole('list')).not.toBeInTheDocument();
+ expect(within(introduction).getByTestId('passport-introduction-brand')).toHaveAttribute(
+ 'src',
+ '/assets/hertzbeat-brand-white.svg'
+ );
+ expect(within(introduction).queryByText(i18n.t('auth.passport.introductionPrefix'))).not.toBeInTheDocument();
+ expect(within(introduction).getByText(i18n.t('auth.passport.description'))).toBeInTheDocument();
+ expect(within(introduction).getByTestId('passport-introduction-phrase')).toHaveTextContent('');
+ expect(introduction.querySelector('p')).toBeNull();
+ expect(
+ screen.getAllByText('Open-source monitoring and observability for infrastructure and applications')
+ ).toHaveLength(1);
+ expect(screen.getByRole('heading', { name: 'Sign in to Apache HertzBeat' })).toBeInTheDocument();
+ expect(screen.queryByText(i18n.t('auth.description'))).not.toBeInTheDocument();
expect(screen.getByTestId('passport-form-region')).toContainElement(
screen.getByRole('button', { name: 'Sign in' })
);
diff --git a/web-app/src/features/auth/pages/login-page.tsx b/web-app/src/features/auth/pages/login-page.tsx
index 6e7a349fc1..29636e650e 100644
--- a/web-app/src/features/auth/pages/login-page.tsx
+++ b/web-app/src/features/auth/pages/login-page.tsx
@@ -71,7 +71,6 @@ function LoginFormContent({ controller }: { controller: LoginController }) {
<Typography.Title id="login-title" level={2}>
{t('auth.title')}
</Typography.Title>
- <Typography.Paragraph type="secondary">{t('auth.description')}</Typography.Paragraph>
{controller.errorKey && (
<OperationalStatePanel
kind={controller.failureKind === 'unavailable' ? 'unavailable' : 'error'}
diff --git a/web-app/src/features/auth/pages/passport-introduction-motion.ts b/web-app/src/features/auth/pages/passport-introduction-motion.ts
new file mode 100644
index 0000000000..c3dd636845
--- /dev/null
+++ b/web-app/src/features/auth/pages/passport-introduction-motion.ts
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import type { RefObject } from 'react';
+
+const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
+const MAX_FONT_PX = 34;
+const MIN_FONT_PX = 18;
+const CURSOR_SPACE_PX = 14;
+
+export const PASSPORT_INTRODUCTION_TYPE_MS = 45;
+export const PASSPORT_INTRODUCTION_HOLD_MS = 1_750;
+export const PASSPORT_INTRODUCTION_ROLL_MS = 460;
+
+type TypewriterState = { phrase: number; visibleLength: number; phase: 'typing' | 'rolling' };
+
+export function usePassportIntroductionMotion(phrases: readonly string[]) {
+ const reducedMotion = useReducedMotion();
+ const [typewriter, setTypewriter] = useState<TypewriterState>({ phrase: 0, visibleLength: 0, phase: 'typing' });
+ const currentPhrase = phrases[typewriter.phrase] ?? phrases[0] ?? '';
+ const glyphs = Array.from(currentPhrase);
+ const visiblePhrase = reducedMotion ? currentPhrase : glyphs.slice(0, typewriter.visibleLength).join('');
+ const stageRef = useRef<HTMLSpanElement>(null);
+ const measureRef = useRef<HTMLSpanElement>(null);
+ const fittedFontSize = useFittedFontSize(stageRef, measureRef, currentPhrase);
+
+ useEffect(() => {
+ if (reducedMotion) return;
+ const [delay, next] = nextTypewriterState(typewriter, glyphs.length, phrases.length);
+ const timer = window.setTimeout(() => setTypewriter(next), delay);
+ return () => window.clearTimeout(timer);
+ }, [glyphs.length, phrases.length, reducedMotion, typewriter]);
+
+ return { currentPhrase, fittedFontSize, measureRef, phase: typewriter.phase, reducedMotion, stageRef, visiblePhrase };
+}
+
+function nextTypewriterState(
+ state: TypewriterState,
+ glyphCount: number,
+ phraseCount: number
+): [number, TypewriterState] {
+ if (state.phase === 'typing' && state.visibleLength < glyphCount) {
+ return [PASSPORT_INTRODUCTION_TYPE_MS, { ...state, visibleLength: state.visibleLength + 1 }];
+ }
+ if (state.phase === 'typing') return [PASSPORT_INTRODUCTION_HOLD_MS, { ...state, phase: 'rolling' }];
+ return [
+ PASSPORT_INTRODUCTION_ROLL_MS,
+ { phrase: (state.phrase + 1) % phraseCount, visibleLength: 0, phase: 'typing' }
+ ];
+}
+
+function useFittedFontSize(
+ stageRef: RefObject<HTMLElement | null>,
+ measureRef: RefObject<HTMLElement | null>,
+ phrase: string
+) {
+ const [fontSize, setFontSize] = useState(MAX_FONT_PX);
+ useLayoutEffect(() => {
+ const stage = stageRef.current;
+ const measure = measureRef.current;
+ if (!stage || !measure) return;
+ const fit = () => setFontSize(current => fittedFontSize(stage, measure, current));
+ fit();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(fit);
+ observer.observe(stage);
+ return () => observer.disconnect();
+ }, [measureRef, phrase, stageRef]);
+ return fontSize;
+}
+
+function fittedFontSize(stage: HTMLElement, measure: HTMLElement, current: number) {
+ const available = stage.clientWidth - CURSOR_SPACE_PX;
+ const required = measure.scrollWidth;
+ if (available <= 0 || required <= 0) return current;
+ return Math.max(MIN_FONT_PX, Math.min(MAX_FONT_PX, Math.floor(MAX_FONT_PX * (available / required))));
+}
+
+function useReducedMotion() {
+ const [reducedMotion, setReducedMotion] = useState(() => readReducedMotion());
+ useEffect(() => {
+ if (typeof window.matchMedia !== 'function') return;
+ const media = window.matchMedia(REDUCED_MOTION_QUERY);
+ const update = (event: MediaQueryListEvent) => setReducedMotion(event.matches);
+ media.addEventListener('change', update);
+ return () => media.removeEventListener('change', update);
+ }, []);
+ return reducedMotion;
+}
+
+function readReducedMotion() {
+ return typeof window.matchMedia === 'function' && window.matchMedia(REDUCED_MOTION_QUERY).matches;
+}
diff --git a/web-app/src/features/auth/pages/passport-introduction.test.tsx b/web-app/src/features/auth/pages/passport-introduction.test.tsx
new file mode 100644
index 0000000000..2d86f140e5
--- /dev/null
+++ b/web-app/src/features/auth/pages/passport-introduction.test.tsx
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { i18n, initializeI18n, loadLocale } from '@/core/i18n/i18n';
+
+import {
+ PassportIntroduction,
+ PASSPORT_INTRODUCTION_HOLD_MS,
+ PASSPORT_INTRODUCTION_ROLL_MS,
+ PASSPORT_INTRODUCTION_TYPE_MS
+} from './passport-introduction';
+
+describe('PassportIntroduction', () => {
+ beforeAll(async () => {
+ await initializeI18n();
+ await loadLocale('en-US');
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it('keeps the brand and positioning stable while every capability is typed in place', async () => {
+ vi.useFakeTimers();
+ useReducedMotion(false);
+ renderIntroduction();
+
+ expect(
+ screen.getByRole('heading', {
+ name: 'Apache HertzBeat™ brings together agentless monitoring, metrics, logs, traces, extensible collection, distributed reach, alerting, self-hosting, and AI.'
+ })
+ ).toBeInTheDocument();
+ expect(screen.getByTestId('passport-introduction-brand')).toHaveAttribute(
+ 'src',
+ '/assets/hertzbeat-brand-white.svg'
+ );
+ expect(screen.getByTestId('passport-introduction-brand')).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByTestId('passport-introduction-positioning')).toHaveTextContent(
+ 'Open-source monitoring and observability for infrastructure and applications'
+ );
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent('');
+ expect(screen.getByTestId('passport-introduction-measure')).toHaveTextContent(
+ 'Agentless monitoring across infrastructure'
+ );
+ expect(screen.getByTestId('passport-introduction-cursor')).toBeInTheDocument();
+ expect(screen.queryByRole('paragraph')).not.toBeInTheDocument();
+
+ const phrases = [
+ 'Agentless monitoring across infrastructure',
+ 'Metrics, logs, and traces in one view',
+ 'Extensible collection, reusable definitions',
+ 'Distributed collection across isolated networks',
+ 'Alerts, notifications, and status publishing in one place',
+ 'Self-hosted, with your data under control',
+ 'AI for queries, diagnosis, and action'
+ ] as const;
+
+ await typePhrase(phrases[0]);
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent(phrases[0]);
+
+ for (let index = 1; index < phrases.length; index += 1) {
+ const current = phrases[index - 1] ?? '';
+ const next = phrases[index] ?? '';
+ await rollToNext(current, next);
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent(next);
+ }
+
+ await rollToNext(phrases.at(-1) ?? '', phrases[0]);
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent(phrases[0]);
+ expect(screen.getAllByTestId('passport-introduction-phrase')).toHaveLength(1);
+ });
+
+ it('keeps the first product line static when reduced motion is requested', async () => {
+ vi.useFakeTimers();
+ useReducedMotion(true);
+ renderIntroduction();
+
+ await act(() => vi.advanceTimersByTimeAsync(30_000));
+
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent(i18n.t('auth.passport.capability1'));
+ expect(screen.queryByText(i18n.t('auth.passport.capability2'))).not.toBeInTheDocument();
+ expect(screen.getAllByTestId('passport-introduction-phrase')).toHaveLength(1);
+ expect(screen.queryByTestId('passport-introduction-cursor')).not.toBeInTheDocument();
+ });
+});
+
+async function typePhrase(phrase: string) {
+ for (let index = 0; index < Array.from(phrase).length; index += 1) {
+ await act(() => vi.advanceTimersByTimeAsync(PASSPORT_INTRODUCTION_TYPE_MS));
+ }
+}
+
+async function rollToNext(current: string, next: string) {
+ await act(() => vi.advanceTimersByTimeAsync(PASSPORT_INTRODUCTION_HOLD_MS));
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent(current);
+ expect(screen.getByTestId('passport-introduction-stage')).toHaveAttribute('data-typewriter-phase', 'rolling');
+ await act(() => vi.advanceTimersByTimeAsync(PASSPORT_INTRODUCTION_ROLL_MS));
+ expect(screen.getByTestId('passport-introduction-phrase')).toHaveTextContent('');
+ await typePhrase(next);
+}
+
+function renderIntroduction() {
+ return render(
+ <I18nextProvider i18n={i18n}>
+ <PassportIntroduction />
+ </I18nextProvider>
+ );
+}
+
+function useReducedMotion(reduced: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches: query === '(prefers-reduced-motion: reduce)' && reduced,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn()
+ }))
+ );
+}
diff --git a/web-app/src/features/auth/pages/passport-introduction.tsx b/web-app/src/features/auth/pages/passport-introduction.tsx
new file mode 100644
index 0000000000..917fda6b4e
--- /dev/null
+++ b/web-app/src/features/auth/pages/passport-introduction.tsx
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { useTranslation } from 'react-i18next';
+
+import styles from './login-page.module.css';
+import { usePassportIntroductionMotion } from './passport-introduction-motion';
+
+export {
+ PASSPORT_INTRODUCTION_HOLD_MS,
+ PASSPORT_INTRODUCTION_ROLL_MS,
+ PASSPORT_INTRODUCTION_TYPE_MS
+} from './passport-introduction-motion';
+
+const INTRODUCTION_KEYS = [
+ 'auth.passport.capability1',
+ 'auth.passport.capability2',
+ 'auth.passport.capability3',
+ 'auth.passport.capability4',
+ 'auth.passport.capability5',
+ 'auth.passport.capability6',
+ 'auth.passport.introductionAiAutomation'
+] as const;
+
+/** Keeps the login introduction calm, replaceable, and independent from authentication state. */
+export function PassportIntroduction() {
+ const { t } = useTranslation();
+ const motion = usePassportIntroductionMotion(INTRODUCTION_KEYS.map(key => t(key)));
+ return (
+ <section
+ className={styles.introduction}
+ data-testid="passport-introduction"
+ aria-labelledby="passport-introduction-title"
+ >
+ <h1 id="passport-introduction-title" className={styles.screenReaderOnly}>
+ {t('auth.passport.accessibleSummary')}
+ </h1>
+ <div className={styles.introductionHeading} aria-hidden="true">
+ <img
+ className={styles.introductionBrand}
+ src="/assets/hertzbeat-brand-white.svg"
+ alt=""
+ aria-hidden="true"
+ width={280}
+ height={70}
+ data-testid="passport-introduction-brand"
+ />
+ <span className={styles.introductionPositioning} data-testid="passport-introduction-positioning">
+ {t('auth.passport.description')}
+ </span>
+ <PassportIntroductionPhrase {...motion} />
+ </div>
+ </section>
+ );
+}
+
+function PassportIntroductionPhrase(props: ReturnType<typeof usePassportIntroductionMotion>) {
+ const { currentPhrase, fittedFontSize, measureRef, phase, reducedMotion, stageRef, visiblePhrase } = props;
+ const typingClass = `${styles.introductionTypingLine} ${phase === 'rolling' ? styles.introductionRollOut : ''}`;
+ return (
+ <span
+ ref={stageRef}
+ className={styles.introductionPhraseStage}
+ data-testid="passport-introduction-stage"
+ data-typewriter-phase={phase}
+ >
+ <span className={typingClass} style={{ fontSize: fittedFontSize }}>
+ <span className={styles.introductionPhrase} data-testid="passport-introduction-phrase">
+ {visiblePhrase}
+ </span>
+ {!reducedMotion && (
+ <span aria-hidden="true" className={styles.introductionCursor} data-testid="passport-introduction-cursor" />
+ )}
+ </span>
+ {phase === 'rolling' && (
+ <span
+ className={`${styles.introductionTypingLine} ${styles.introductionRollIn}`}
+ style={{ fontSize: fittedFontSize }}
+ >
+ <span aria-hidden="true" className={styles.introductionCursor} />
+ </span>
+ )}
+ <span
+ ref={measureRef}
+ aria-hidden="true"
+ className={styles.introductionMeasure}
+ data-testid="passport-introduction-measure"
+ >
+ {currentPhrase}
+ </span>
+ </span>
+ );
+}
diff --git a/web-app/src/features/auth/pages/passport-page-frame.tsx b/web-app/src/features/auth/pages/passport-page-frame.tsx
index 59424c7c1c..e34108c718 100644
--- a/web-app/src/features/auth/pages/passport-page-frame.tsx
+++ b/web-app/src/features/auth/pages/passport-page-frame.tsx
@@ -5,55 +5,41 @@
* The ASF licenses this file to You under the Apache License, Version 2.0.
*/
+import { ConfigProvider } from 'antd';
import type { ReactNode } from 'react';
-import { useTranslation } from 'react-i18next';
+
+import { createHertzBeatTheme } from '@/shared/theme/hertzbeat-theme';
import styles from './login-page.module.css';
import { PassportBrand } from './passport-brand';
+import { PassportIntroduction } from './passport-introduction';
-const CAPABILITY_KEYS = [
- 'auth.passport.capability1',
- 'auth.passport.capability2',
- 'auth.passport.capability3',
- 'auth.passport.capability4',
- 'auth.passport.capability5',
- 'auth.passport.capability6'
-] as const;
+const passportTheme = createHertzBeatTheme('default');
/** Shared product context for standalone passport routes without coupling it to authentication state. */
export function PassportPageFrame({ children }: { children: ReactNode }) {
- const { t } = useTranslation();
-
return (
- <main className={styles.page} data-passport-page="true" data-passport-background="legacy-artwork">
- <div className={styles.shell}>
- <header className={styles.brandHeader}>
- <PassportBrand variant="full" />
- <p className={styles.brandDescription}>{t('auth.passport.description')}</p>
- </header>
+ <ConfigProvider theme={passportTheme}>
+ <main
+ className={styles.page}
+ data-passport-page="true"
+ data-passport-background="legacy-artwork"
+ data-theme-scope="default"
+ >
+ <div className={styles.shell}>
+ <header className={styles.brandHeader}>
+ <PassportBrand variant="full" />
+ </header>
- <div className={styles.content}>
- <section
- className={styles.introduction}
- data-testid="passport-introduction"
- aria-labelledby="passport-introduction-title"
- >
- <h1 id="passport-introduction-title">
- <span>{t('auth.passport.headingLineOne')}</span>
- <span>{t('auth.passport.headingLineTwo')}</span>
- </h1>
- <ul aria-label={t('auth.passport.capabilityListLabel')}>
- {CAPABILITY_KEYS.map(key => (
- <li key={key}>{t(key)}</li>
- ))}
- </ul>
- </section>
+ <div className={styles.content}>
+ <PassportIntroduction />
- <div className={styles.formRegion} data-testid="passport-form-region">
- {children}
+ <div className={styles.formRegion} data-testid="passport-form-region">
+ {children}
+ </div>
</div>
</div>
- </div>
- </main>
+ </main>
+ </ConfigProvider>
);
}
diff --git a/web-app/src/features/monitor/api/monitor-api.test.ts b/web-app/src/features/monitor/api/monitor-api.test.ts
index a1b3c10147..660e4cf7a1 100644
--- a/web-app/src/features/monitor/api/monitor-api.test.ts
+++ b/web-app/src/features/monitor/api/monitor-api.test.ts
@@ -21,6 +21,7 @@ const http = vi.hoisted(() => ({
apiMessageDelete: vi.fn(),
apiMessageGet: vi.fn(),
apiMessagePost: vi.fn(),
+ apiMessagePostWithErrorEnvelope: vi.fn(),
apiMessagePut: vi.fn()
}));
vi.mock('@/core/http/api-message', async importOriginal => ({
@@ -352,17 +353,14 @@ describe('monitor metric API paths', () => {
it.each([
['30m', false],
- ['1h', false],
- ['6h', false],
- ['24h', false],
- ['1W', true],
- ['4W', true],
- ['12W', true]
- ] as const)('sends history=%s with interval=%s', (history, interval) => {
+ ['30m', true],
+ ['1W', false],
+ ['1W', true]
+ ] as const)('sends history=%s independently from interval=%s', (history, interval) => {
const monitor = { id: 7, app: 'website', name: 'home', instance: 'example.com:443', status: 1 };
const metric = { key: 'summary.responseTime', group: 'summary', field: 'responseTime', unit: 'ms' };
- expect(buildHistoryMetricPath(monitor, metric, history)).toBe(
+ expect(buildHistoryMetricPath(monitor, metric, history, interval)).toBe(
`/api/monitor/example.com%3A443/metric/website.summary.responseTime?history=${history}&interval=${interval}`
);
});
@@ -549,12 +547,13 @@ describe('monitor detail API contracts', () => {
const { signal } = controller;
const payload = { monitor: { name: 'home' } };
http.apiMessagePost.mockResolvedValue(undefined);
+ http.apiMessagePostWithErrorEnvelope.mockResolvedValue(undefined);
http.apiMessagePut.mockResolvedValue(undefined);
await detectMonitor(payload, signal);
await saveMonitor('new', payload, signal);
await saveMonitor('edit', payload, signal);
- expect(http.apiMessagePost).toHaveBeenCalledWith('/api/monitor/detect', payload, { signal });
- const detectSignal = http.apiMessagePost.mock.calls[0]?.[2]?.signal as AbortSignal;
+ expect(http.apiMessagePostWithErrorEnvelope).toHaveBeenCalledWith('/api/monitor/detect', payload, { signal });
+ const detectSignal = http.apiMessagePostWithErrorEnvelope.mock.calls[0]?.[2]?.signal as AbortSignal;
expect(detectSignal).toBe(signal);
expect(detectSignal.aborted).toBe(false);
controller.abort();
@@ -889,7 +888,7 @@ describe('monitor metric API contracts', () => {
}
]
});
- await expect(loadHistoryMetric(monitor, metric, '30m', signal)).resolves.toEqual({
+ await expect(loadHistoryMetric(monitor, metric, '30m', false, signal)).resolves.toEqual({
values: {
'host=a': [{ origin: null, mean: '11', median: null, min: null, max: null, time: 0 }]
}
@@ -980,7 +979,7 @@ describe('monitor metric API contracts', () => {
? loadFavoriteMetrics(7)
: kind === 'realtime'
? loadRealtimeMetric(7, metric)
- : loadHistoryMetric(monitor, metric, '30m');
+ : loadHistoryMetric(monitor, metric, '30m', false);
await expect(promise).rejects.toBeInstanceOf(MonitorContractError);
});
diff --git a/web-app/src/features/monitor/api/monitor-metric-api.ts b/web-app/src/features/monitor/api/monitor-metric-api.ts
index 9a2d265b53..35684900c6 100644
--- a/web-app/src/features/monitor/api/monitor-metric-api.ts
+++ b/web-app/src/features/monitor/api/monitor-metric-api.ts
@@ -44,11 +44,16 @@ export function buildFavoriteMetricPath(monitorId: number, metricKey?: string) {
: `/api/metrics/favorite/${monitorId}/${encodeURIComponent(metricKey)}`;
}
-export function buildHistoryMetricPath(monitor: Monitor, metric: MonitorMetricOption, history: MonitorMetricHistory) {
+export function buildHistoryMetricPath(
+ monitor: Monitor,
+ metric: MonitorMetricOption,
+ history: MonitorMetricHistory,
+ interval = monitorMetricHistoryUsesInterval(history)
+) {
const sourceApp = monitor.scrape && monitor.scrape !== 'static' ? monitor.scrape : monitor.app;
const app = sourceApp === 'prometheus' ? `_prometheus_${monitor.name}` : sourceApp;
const fullMetric = `${app}.${metric.group}.${metric.field}`;
- const params = new URLSearchParams({ history, interval: String(monitorMetricHistoryUsesInterval(history)) });
+ const params = new URLSearchParams({ history, interval: String(interval) });
return `/api/monitor/${encodeURIComponent(monitor.instance)}/metric/${fullMetric}?${params.toString()}`;
}
@@ -76,8 +81,12 @@ export async function loadHistoryMetric(
monitor: Monitor,
metric: MonitorMetricOption,
history: MonitorMetricHistory,
+ interval: boolean,
signal?: AbortSignal
) {
- const value = await apiMessageGet(buildHistoryMetricPath(monitor, metric, history), signal ? { signal } : undefined);
+ const value = await apiMessageGet(
+ buildHistoryMetricPath(monitor, metric, history, interval),
+ signal ? { signal } : undefined
+ );
return parseHistoryMetric(value, monitor.instance, metric.group, metric.field);
}
diff --git a/web-app/src/features/monitor/api/monitor-metric-layout-api.ts b/web-app/src/features/monitor/api/monitor-metric-layout-api.ts
new file mode 100644
index 0000000000..ea72daa232
--- /dev/null
+++ b/web-app/src/features/monitor/api/monitor-metric-layout-api.ts
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { apiMessageDelete, apiMessageGet, apiMessagePut } from '@/core/http/api-message';
+
+import type { MonitorMetricLayoutDocument } from '../model/monitor-metric-layout-model';
+import { parseMonitorMetricLayout } from './monitor-metric-layout-schema';
+
+export type MonitorMetricLayoutSavePayload = MonitorMetricLayoutDocument & { expectedRevision: string };
+
+function buildMonitorMetricLayoutPath(application: string) {
+ return `/api/metrics/layout/${encodeURIComponent(application)}`;
+}
+
+export async function loadMonitorMetricLayout(application: string, signal?: AbortSignal) {
+ const value = await apiMessageGet(buildMonitorMetricLayoutPath(application), signal ? { signal } : undefined);
+ return parseMonitorMetricLayout(value);
+}
+
+export async function saveMonitorMetricLayout(application: string, payload: MonitorMetricLayoutSavePayload) {
+ return parseMonitorMetricLayout(await apiMessagePut(buildMonitorMetricLayoutPath(application), payload));
+}
+
+export async function resetMonitorMetricLayout(application: string, expectedRevision: string) {
+ const params = new URLSearchParams({ expectedRevision });
+ await apiMessageDelete(`${buildMonitorMetricLayoutPath(application)}?${params.toString()}`);
+}
diff --git a/web-app/src/features/monitor/api/monitor-metric-layout-schema.test.ts b/web-app/src/features/monitor/api/monitor-metric-layout-schema.test.ts
new file mode 100644
index 0000000000..150de41273
--- /dev/null
+++ b/web-app/src/features/monitor/api/monitor-metric-layout-schema.test.ts
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { MonitorMetricLayoutContractError, parseMonitorMetricLayout } from './monitor-metric-layout-schema';
+
+describe('monitor metric layout schema', () => {
+ it('keeps missing and configured layouts distinct', () => {
+ expect(parseMonitorMetricLayout(null)).toBeNull();
+ expect(parseMonitorMetricLayout(layout())).toEqual(layout());
+ });
+
+ it.each([
+ { ...layout(), columns: 6 },
+ { ...layout(), password: 'must-not-pass' },
+ { ...layout(), items: [{ ...layout().items[0], w: 5 }] },
+ { ...layout(), items: [layout().items[0], { ...layout().items[0], order: 1 }] }
+ ])('rejects malformed, expanded, or ambiguous documents', value => {
+ expect(() => parseMonitorMetricLayout(value)).toThrow(MonitorMetricLayoutContractError);
+ });
+});
+
+function layout() {
+ return {
+ application: 'mysql',
+ revision: 'layout-r1',
+ schemaVersion: 1,
+ mode: 'custom',
+ columns: 12,
+ items: [{ group: 'basic', x: 0, y: 0, w: 6, h: 10, collapsed: false, order: 0 }],
+ historyDock: { collapsed: false, height: 12 }
+ } as const;
+}
diff --git a/web-app/src/features/monitor/api/monitor-metric-layout-schema.ts b/web-app/src/features/monitor/api/monitor-metric-layout-schema.ts
new file mode 100644
index 0000000000..877676bb41
--- /dev/null
+++ b/web-app/src/features/monitor/api/monitor-metric-layout-schema.ts
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { z } from 'zod';
+
+import type { MonitorMetricLayoutResource } from '../model/monitor-metric-layout-model';
+
+const groupSchema = z.string().regex(/^[A-Za-z0-9_.:-]{1,128}$/);
+const itemSchema = z
+ .object({
+ group: groupSchema,
+ x: z.number().int().min(0).max(11),
+ y: z.number().int().min(0).max(999),
+ w: z.union([z.literal(4), z.literal(6), z.literal(8), z.literal(12)]),
+ h: z.number().int().min(4).max(24),
+ collapsed: z.boolean(),
+ order: z.number().int().min(0).max(127)
+ })
+ .strict()
+ .refine(item => item.x + item.w <= 12, 'Item exceeds canonical columns')
+ .refine(item => item.collapsed || item.h >= 8, 'Expanded item is too short');
+
+const layoutSchema = z
+ .object({
+ application: z.string().regex(/^[a-z0-9_.:-]{1,128}$/),
+ revision: z.string().min(1).max(64),
+ schemaVersion: z.literal(1),
+ mode: z.enum(['auto', 'custom']),
+ columns: z.literal(12),
+ items: z.array(itemSchema).max(128),
+ historyDock: z.object({ collapsed: z.boolean(), height: z.number().int().min(8).max(20) }).strict()
+ })
+ .strict()
+ .superRefine((layout, context) => {
+ requireUnique(
+ layout.items.map(item => item.group),
+ 'group',
+ context
+ );
+ requireUnique(
+ layout.items.map(item => item.order),
+ 'order',
+ context
+ );
+ for (let index = 0; index < layout.items.length; index += 1) {
+ for (let candidate = index + 1; candidate < layout.items.length; candidate += 1) {
+ if (overlaps(layout.items[index]!, layout.items[candidate]!)) {
+ context.addIssue({ code: 'custom', message: 'Layout items overlap', path: ['items', candidate] });
+ }
+ }
+ }
+ });
+
+export class MonitorMetricLayoutContractError extends Error {
+ constructor(options?: ErrorOptions) {
+ super('Monitor metric layout response is invalid', options);
+ this.name = 'MonitorMetricLayoutContractError';
+ }
+}
+
+export function parseMonitorMetricLayout(value: unknown): MonitorMetricLayoutResource | null {
+ if (value === null) return null;
+ const result = layoutSchema.safeParse(value);
+ if (!result.success) throw new MonitorMetricLayoutContractError({ cause: result.error });
+ return result.data;
+}
+
+function requireUnique(values: Array<string | number>, field: string, context: z.RefinementCtx) {
+ if (new Set(values).size !== values.length) {
+ context.addIssue({ code: 'custom', message: `Duplicate layout ${field}`, path: ['items'] });
+ }
+}
+
+function overlaps(first: z.infer<typeof itemSchema>, second: z.infer<typeof itemSchema>) {
+ return (
+ first.x < second.x + second.w &&
+ first.x + first.w > second.x &&
+ first.y < second.y + second.h &&
+ first.y + first.h > second.y
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-detail-metadata.tsx b/web-app/src/features/monitor/components/monitor-detail-metadata.tsx
index 39e9fbb5cf..9fd44bd448 100644
--- a/web-app/src/features/monitor/components/monitor-detail-metadata.tsx
+++ b/web-app/src/features/monitor/components/monitor-detail-metadata.tsx
@@ -15,44 +15,6 @@ import { monitorStatusColor, monitorStatusKey, parseMonitorTimestamp } from '../
import styles from './monitor-detail-view.module.css';
-/**
- * Keeps the complete operational identity visible on the read-only surface.
- * These fields were present in the Angular detail and already belong to the
- * canonical monitor response, so hiding them would force operators into edit.
- */
-export function MonitorDetailSummary({
- monitor,
- collector
-}: {
- monitor: Monitor;
- collector: string | null | undefined;
-}) {
- const { t } = useTranslation();
- const facts = [
- {
- key: 'status',
- label: t('monitor.status.label'),
- value: <Tag color={monitorStatusColor(monitor.status)}>{t(monitorStatusKey(monitor.status))}</Tag>
- },
- { key: 'schedule', label: t('monitor.metadata.schedule'), value: monitorSchedule(t, monitor) },
- { key: 'collector', label: t('monitor.metadata.collector'), value: collector || '—' },
- { key: 'updated', label: t('monitor.metadata.updated'), value: monitorTime(monitor.gmtUpdate) }
- ];
-
- return (
- <section className={styles.summaryStrip} aria-label={t('monitor.metadata.summary')}>
- <dl className={styles.summaryFacts}>
- {facts.map(fact => (
- <div className={styles.summaryFact} key={fact.key}>
- <dt>{fact.label}</dt>
- <dd>{fact.value}</dd>
- </div>
- ))}
- </dl>
- </section>
- );
-}
-
/**
* Full configuration stays available without competing with the metric workbench.
* A drawer preserves Angular's data-first detail flow while keeping audit fields
diff --git a/web-app/src/features/monitor/components/monitor-detail-view.module.css b/web-app/src/features/monitor/components/monitor-detail-view.module.css
index ba5781a092..74b2fbe2c8 100644
--- a/web-app/src/features/monitor/components/monitor-detail-view.module.css
+++ b/web-app/src/features/monitor/components/monitor-detail-view.module.css
@@ -21,36 +21,6 @@
align-items: center;
gap: var(--hb-space-2);
}
-.summaryStrip {
- padding-block: var(--hb-space-3);
-}
-.summaryFacts {
- display: grid;
- grid-template-columns: repeat(4, minmax(0, 1fr));
- margin: 0;
-}
-.summaryFact {
- min-width: 0;
- padding-inline: var(--hb-space-4);
- border-inline-start: 1px solid var(--hb-border-subtle);
-}
-.summaryFact:first-child {
- padding-inline-start: 0;
- border-inline-start: 0;
-}
-.summaryFact dt {
- margin-bottom: 3px;
- color: var(--hb-text-secondary);
- font-size: 12px;
-}
-.summaryFact dd {
- min-width: 0;
- margin: 0;
- overflow: hidden;
- font-size: 13px;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
.configurationBody {
display: grid;
gap: var(--hb-space-5);
@@ -106,18 +76,9 @@
border: 0;
}
@media (max-width: 760px) {
- .summaryFacts,
.parameterGrid {
grid-template-columns: minmax(0, 1fr);
}
- .summaryFact,
- .summaryFact:first-child {
- padding: var(--hb-space-2) 0;
- border-inline-start: 0;
- }
- .summaryFact + .summaryFact {
- border-top: 1px solid var(--hb-border-subtle);
- }
.parameterEntry:nth-child(odd) {
border-inline-end: 0;
}
diff --git a/web-app/src/features/monitor/components/monitor-detail-view.test.tsx b/web-app/src/features/monitor/components/monitor-detail-view.test.tsx
index 551b98cc36..76ffb0e56b 100644
--- a/web-app/src/features/monitor/components/monitor-detail-view.test.tsx
+++ b/web-app/src/features/monitor/components/monitor-detail-view.test.tsx
@@ -79,7 +79,7 @@ describe('MonitorDetailView', () => {
expect(document.querySelector('[data-hb-operational-page][data-mode="workspace"]')).toBeInTheDocument();
expect(screen.getByRole('heading', { level: 2, name: 'checkout' })).toBeInTheDocument();
expect(screen.getByText('checkout')).toBeInTheDocument();
- expect(screen.getByText(i18n.t('monitor.metadata.interval', { seconds: 0 }))).toBeInTheDocument();
+ expect(screen.queryByText(i18n.t('monitor.metadata.interval', { seconds: 0 }))).not.toBeInTheDocument();
expect(screen.getByTestId('metrics')).toHaveTextContent('1');
});
@@ -152,7 +152,7 @@ describe('MonitorDetailView', () => {
expect(document.body).not.toHaveTextContent('private-encrypted-wire-value');
});
- it('uses the monitor identity as the only page heading and keeps a compact operational summary', () => {
+ it('keeps the monitor identity as the only page heading and leaves metadata in the configuration drawer', () => {
renderView({
...ready,
detail: {
@@ -164,7 +164,13 @@ describe('MonitorDetailView', () => {
expect(screen.getByRole('heading', { level: 2, name: 'checkout' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: i18n.t('monitor.detail') })).not.toBeInTheDocument();
- expect(screen.getByRole('region', { name: i18n.t('monitor.metadata.summary') })).toHaveTextContent('collector-a');
+ expect(screen.queryByRole('region', { name: i18n.t('monitor.metadata.summary') })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('monitor.metadata.viewConfiguration') }));
+
+ expect(screen.getByRole('dialog', { name: i18n.t('monitor.metadata.configuration') })).toHaveTextContent(
+ 'collector-a'
+ );
});
it('closes configuration when the route resolves to a different monitor', () => {
diff --git a/web-app/src/features/monitor/components/monitor-detail-view.tsx b/web-app/src/features/monitor/components/monitor-detail-view.tsx
index 5159688e6d..82027be4e7 100644
--- a/web-app/src/features/monitor/components/monitor-detail-view.tsx
+++ b/web-app/src/features/monitor/components/monitor-detail-view.tsx
@@ -33,7 +33,7 @@ import type {
MonitorDetailViewState
} from '../model/monitor-detail-model';
import { safeMonitorGrafanaUrl } from '../model/monitor-detail-model';
-import { MonitorDetailConfigurationDrawer, MonitorDetailSummary } from './monitor-detail-metadata';
+import { MonitorDetailConfigurationDrawer } from './monitor-detail-metadata';
import { MonitorHelpLink } from './monitor-help-link';
import styles from './monitor-detail-view.module.css';
@@ -98,7 +98,6 @@ function MonitorReadyDetailView({
</>
}
/>
- <MonitorDetailSummary monitor={monitor} collector={detail.collector} />
{metricWorkbench}
<MonitorDetailConfigurationDrawer
open={configurationOpen}
diff --git a/web-app/src/features/monitor/components/monitor-history-chart-runtime.test.ts b/web-app/src/features/monitor/components/monitor-history-chart-runtime.test.ts
index b4ae553418..d955ce610a 100644
--- a/web-app/src/features/monitor/components/monitor-history-chart-runtime.test.ts
+++ b/web-app/src/features/monitor/components/monitor-history-chart-runtime.test.ts
@@ -17,8 +17,18 @@ type ChartOptionContract = {
color: string[];
tooltip: { trigger: string; confine: boolean; axisPointer: { type: string } };
legend: { show: boolean; top: number; right: number };
+ toolbox?: unknown;
+ grid: { left: number; right: number; top: number; bottom: number; containLabel: boolean };
+ dataZoom: Array<{
+ type: string;
+ zoomOnMouseWheel?: boolean;
+ moveOnMouseMove?: boolean;
+ moveOnMouseWheel?: boolean;
+ }>;
series: Array<{
smooth: boolean;
+ showSymbol: boolean;
+ symbolSize: number;
lineStyle: { color: string; width: number };
areaStyle?: unknown;
}>;
@@ -29,6 +39,15 @@ type ChartOptionContract = {
axisTick: { show: boolean };
axisLabel: { hideOverlap: boolean; showMinLabel: boolean; showMaxLabel: boolean };
};
+ yAxis: {
+ minInterval?: number;
+ splitNumber: number;
+ min: number;
+ max: number;
+ interval: number;
+ splitLine: { lineStyle: { type: string } };
+ splitArea: { show: boolean };
+ };
};
const colors = {
@@ -36,7 +55,10 @@ const colors = {
muted: '#8d96a8',
border: '#28303d',
grid: '#202733',
- background: '#11151c'
+ background: '#11151c',
+ accent: '#9b5bb3',
+ available: '#49aa19',
+ degraded: '#d89614'
};
function chartOption(input: MonitorHistoryChartRenderInput) {
@@ -51,7 +73,7 @@ describe('monitor history chart runtime', () => {
expect(formatMonitorHistoryAxisTickLabel(timestamp, 48 * 60 * 60 * 1000)).toBe('08/03 23:04');
});
- it('uses the established blue primary curve and a subtle area fill', () => {
+ it('uses a compact Grafana-like plot without detached toolbox or slider chrome', () => {
const option = chartOption({
title: 'basic.max_connections',
series: [
@@ -59,42 +81,61 @@ describe('monitor history chart runtime', () => {
name: 'origin',
points: [
[1, 151],
- [2, 152]
+ [2, 151]
]
}
- ],
- saveImageTitle: 'Save image'
+ ]
});
- expect(option.color[0]).toBe('#60a5fa');
- expect(option.tooltip).toMatchObject({ trigger: 'axis', confine: true, axisPointer: { type: 'cross' } });
+ expect(option.color[0]).toBe('#9b5bb3');
+ expect(option.tooltip).toMatchObject({ trigger: 'axis', confine: true, axisPointer: { type: 'line' } });
expect(option.legend.show).toBe(false);
+ expect(option.toolbox).toBeUndefined();
+ expect(option.grid).toMatchObject({ left: 8, right: 16, bottom: 20, containLabel: true });
+ expect(option.dataZoom).toEqual([
+ { type: 'inside', zoomOnMouseWheel: true, moveOnMouseMove: true, moveOnMouseWheel: false }
+ ]);
expect(option.series[0]).toMatchObject({
- smooth: true,
- lineStyle: { color: '#60a5fa', width: 2.4 },
- areaStyle: expect.any(Object)
+ smooth: false,
+ showSymbol: true,
+ symbolSize: 5,
+ lineStyle: { color: '#9b5bb3', width: 2 }
});
+ expect(option.series[0]!.areaStyle).toBeDefined();
+ expect(option.yAxis.splitArea.show).toBe(false);
+ expect(option.yAxis.minInterval).toBeUndefined();
+ expect(option.yAxis.splitNumber).toBe(3);
+ expect(option.yAxis.splitLine.lineStyle.type).toBe('solid');
+ expect(option.yAxis).toMatchObject({ min: 149, max: 153, interval: 2 });
expect(option.xAxis).toMatchObject({
- splitNumber: 5,
+ splitNumber: 4,
min: 1,
max: 2,
axisTick: { show: false },
- axisLabel: { hideOverlap: true, showMinLabel: true, showMaxLabel: true }
+ axisLabel: { hideOverlap: true, showMinLabel: true, showMaxLabel: false }
});
});
- it('shows a top legend and stable semantic colors for interval aggregates', () => {
+ it('shows a top legend and token-backed semantic colors for interval aggregates', () => {
const option = chartOption({
title: 'status.qps',
series: [
{ name: 'Max', points: [[1, 10]] },
{ name: 'Min', points: [[1, 2]] },
{ name: 'Mean', points: [[1, 6]] }
- ],
- saveImageTitle: 'Save image'
+ ]
});
expect(option.legend).toMatchObject({ show: true, top: 8, right: 12 });
- expect(option.series.map(series => series.lineStyle.color)).toEqual(['#fbbf24', '#34d399', '#60a5fa']);
+ expect(option.series.map(series => series.lineStyle.color)).toEqual(['#d89614', '#49aa19', '#9b5bb3']);
+ });
+
+ it('hides symbols once a series is dense enough to read as a continuous signal', () => {
+ const option = chartOption({
+ title: 'status.qps',
+ series: [{ name: 'origin', points: Array.from({ length: 17 }, (_, index) => [index, index]) }]
+ });
+
+ expect(option.series[0]).toMatchObject({ showSymbol: false, symbolSize: 5 });
});
});
diff --git a/web-app/src/features/monitor/components/monitor-history-chart-runtime.ts b/web-app/src/features/monitor/components/monitor-history-chart-runtime.ts
index 047519a9e4..003e553f8f 100644
--- a/web-app/src/features/monitor/components/monitor-history-chart-runtime.ts
+++ b/web-app/src/features/monitor/components/monitor-history-chart-runtime.ts
@@ -13,8 +13,23 @@ import {
type TimeSeriesChartRuntime
} from '@/shared/time-series-chart/time-series-chart-runtime';
-export type MonitorHistoryChartRuntime = TimeSeriesChartRuntime;
-export type MonitorHistoryChartRenderInput = TimeSeriesChartRenderInput & { saveImageTitle: string };
-export const createMonitorHistoryChart = createTimeSeriesChart;
-export const buildMonitorHistoryChartOption = buildTimeSeriesChartOption;
+export type MonitorHistoryChartRuntime = Omit<TimeSeriesChartRuntime, 'update'> & {
+ update: (input: MonitorHistoryChartRenderInput) => void;
+};
+export type MonitorHistoryChartRenderInput = Omit<TimeSeriesChartRenderInput, 'presentation' | 'saveImageTitle'>;
+export const createMonitorHistoryChart = (element: HTMLDivElement, input: MonitorHistoryChartRenderInput) => {
+ const runtime = createTimeSeriesChart(element, monitorHistoryInput(input));
+ return {
+ update: (next: MonitorHistoryChartRenderInput) => runtime.update(monitorHistoryInput(next)),
+ dispose: runtime.dispose
+ };
+};
+export const buildMonitorHistoryChartOption = (
+ input: MonitorHistoryChartRenderInput,
+ colors: Parameters<typeof buildTimeSeriesChartOption>[1]
+) => buildTimeSeriesChartOption(monitorHistoryInput(input), colors);
export const formatMonitorHistoryAxisTickLabel = formatTimeSeriesAxisTickLabel;
+
+function monitorHistoryInput(input: MonitorHistoryChartRenderInput): TimeSeriesChartRenderInput {
+ return { ...input, presentation: 'monitor-history' };
+}
diff --git a/web-app/src/features/monitor/components/monitor-history-chart.tsx b/web-app/src/features/monitor/components/monitor-history-chart.tsx
new file mode 100644
index 0000000000..02b52c508b
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-history-chart.tsx
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { Alert } from 'antd';
+import type { ReactNode } from 'react';
+import { useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { OperationalStatePanel } from '@/shared/operational-page';
+
+import type { MonitorHistoryChart, MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import type { MonitorHistoryChartRenderInput, MonitorHistoryChartRuntime } from './monitor-history-chart-runtime';
+import styles from './monitor-history-results.module.css';
+
+export function HistoryAvailabilityBoundary({
+ availability,
+ children
+}: {
+ availability: MonitorMetricWorkbenchController['state']['historyAvailability'];
+ children: ReactNode;
+}) {
+ const { t } = useTranslation();
+ if (availability.kind === 'loading')
+ return <OperationalStatePanel kind="loading" title={t('monitorMetrics.loading')} />;
+ if (availability.kind === 'unavailable')
+ return <OperationalStatePanel kind="unavailable" title={t('common.unavailable')} />;
+ if (availability.kind === 'unknown')
+ return <OperationalStatePanel kind="unavailable" title={t('monitorMetrics.storageUnknown')} />;
+ if (availability.kind === 'error')
+ return <OperationalStatePanel kind="error" title={t('common.routeError.description')} />;
+ return (
+ <div className={styles.historyResult}>
+ {availability.kind === 'degraded' ? (
+ <Alert type="warning" showIcon message={t('monitorMetrics.storageDegraded')} />
+ ) : null}
+ {children}
+ </div>
+ );
+}
+
+export function HistoryChartEvidence({ chart }: { chart: MonitorHistoryChart }) {
+ const { t } = useTranslation();
+ if (chart.result.kind === 'unavailable') return <ChartState kind="unavailable" title={t('common.unavailable')} />;
+ if (chart.result.kind === 'error') return <ChartState kind="error" title={t('common.routeError.description')} />;
+ if (chart.result.kind === 'empty') return <ChartState kind="empty" title={t('monitorMetrics.empty')} />;
+ if (chart.result.kind === 'unsupported')
+ return <ChartState kind="empty" title={t('monitorMetrics.historyUnsupported')} />;
+ if (chart.result.kind === 'loading') return <ChartState kind="loading" title={t('monitorMetrics.loading')} />;
+ return <HistoryChartCanvas chart={chart} />;
+}
+
+function HistoryChartCanvas({ chart }: { chart: MonitorHistoryChart }) {
+ const element = useRef<HTMLDivElement>(null);
+ const runtime = useRef<MonitorHistoryChartRuntime | undefined>(undefined);
+ const input = useMemo<MonitorHistoryChartRenderInput>(
+ () => ({
+ title: chart.metric.key,
+ unit: chart.metric.unit,
+ series: chart.result.rows
+ }),
+ [chart.metric.key, chart.metric.unit, chart.result.rows]
+ );
+ const latest = useRef(input);
+ useEffect(() => {
+ latest.current = input;
+ runtime.current?.update(input);
+ }, [input]);
+ useEffect(() => {
+ let cancelled = false;
+ async function mountChart() {
+ const module = await import('./monitor-history-chart-runtime');
+ if (cancelled || !element.current) return;
+ runtime.current = module.createMonitorHistoryChart(element.current, latest.current);
+ }
+ void mountChart();
+ return () => {
+ cancelled = true;
+ runtime.current?.dispose();
+ runtime.current = undefined;
+ };
+ }, [chart.metric.key]);
+ return <div ref={element} className={styles.historyChartCanvas} role="img" aria-label={chart.metric.key} />;
+}
+
+function ChartState({ kind, title }: { kind: 'loading' | 'empty' | 'unavailable' | 'error'; title: string }) {
+ return (
+ <div className={styles.historyChartState}>
+ <OperationalStatePanel kind={kind} title={title} />
+ </div>
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-history-results.module.css b/web-app/src/features/monitor/components/monitor-history-results.module.css
new file mode 100644
index 0000000000..1135683183
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-history-results.module.css
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+.selectedHistoryTray {
+ position: relative;
+ min-width: 0;
+ height: var(--monitor-history-height, 264px);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ border: 1px solid var(--hb-border-subtle);
+ border-radius: var(--hb-radius-control);
+ background: var(--hb-bg-raised);
+}
+
+.historyDockResizeHandle {
+ position: absolute;
+ z-index: 3;
+ inset-inline-end: 0;
+ bottom: 0;
+ width: 18px;
+ height: 18px;
+ cursor: nwse-resize;
+}
+
+.historyDockResizeHandle::after {
+ position: absolute;
+ inset-inline-end: 4px;
+ bottom: 4px;
+ width: 8px;
+ height: 8px;
+ border-inline-end: 2px solid var(--hb-brand-accent);
+ border-bottom: 2px solid var(--hb-brand-accent);
+ content: '';
+}
+
+.historyDockResizeHandle:focus-visible {
+ outline: 2px solid var(--hb-brand-accent);
+ outline-offset: -2px;
+}
+
+.selectedHistoryTray > .historyResult {
+ min-height: 0;
+ flex: 1;
+}
+
+.selectedHistoryTray > .historyResult .historyChartCanvas,
+.selectedHistoryTray > .historyResult .historyChartState {
+ height: 100%;
+ min-height: 118px;
+}
+
+.selectedHistoryHeader {
+ display: flex;
+ min-height: 42px;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--hb-space-3);
+ padding: 5px 9px 5px 12px;
+ border-bottom: 1px solid var(--hb-border-subtle);
+}
+
+.selectedHistoryIdentity,
+.selectedHistoryControls,
+.historyStatistics {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ gap: var(--hb-space-2);
+}
+
+.selectedHistoryIdentity > span:not(.currentMetricValue),
+.selectedHistoryIdentity time {
+ overflow: hidden;
+ color: var(--hb-text-secondary);
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.selectedHistoryIdentity :global(.ant-btn) {
+ width: 24px;
+ min-width: 24px;
+ height: 24px;
+ padding: 0;
+}
+
+.currentMetricValue {
+ flex: none;
+ color: var(--hb-brand-accent);
+ font-size: 12px;
+ font-weight: 600;
+ white-space: nowrap;
+}
+
+.selectedHistoryControls {
+ flex: none;
+}
+
+.selectedHistoryControls > :global(.ant-select) {
+ width: 84px;
+}
+
+.historyStatistics {
+ min-height: 32px;
+ justify-content: flex-start;
+ gap: var(--hb-space-4);
+ margin: 0;
+ padding: 6px 14px 2px;
+ color: var(--hb-text-muted);
+ font-size: 10px;
+}
+
+.historyStatistic {
+ display: inline-flex;
+ align-items: baseline;
+ gap: var(--hb-space-1);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.historyStatistic dt,
+.historyStatistic dd {
+ margin: 0;
+}
+
+.historyStatistic dt {
+ color: var(--hb-text-muted);
+}
+
+.historyStatistic dd {
+ color: var(--hb-text-secondary);
+ font-size: 11px;
+ font-weight: 600;
+}
+
+.historyResult {
+ display: grid;
+ gap: var(--hb-space-3);
+}
+
+.historyGrid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: var(--hb-space-3);
+}
+
+.historyChart {
+ min-width: 0;
+ overflow: hidden;
+ border: 1px solid var(--hb-border-subtle);
+ border-radius: var(--hb-radius-surface);
+ background: var(--hb-bg-raised);
+}
+
+.historyChartHeader {
+ display: flex;
+ min-height: 48px;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--hb-space-3);
+ padding: var(--hb-space-2) var(--hb-space-3);
+ border-bottom: 1px solid var(--hb-border-subtle);
+}
+
+.historyChartTitle {
+ min-width: 0;
+}
+
+.historyChartTitle h5 {
+ margin: 0;
+ overflow: hidden;
+ font-size: 13px;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.historyChartTitle span {
+ color: var(--hb-text-secondary);
+ font-size: 12px;
+}
+
+.historyChartActions {
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: var(--hb-space-2);
+}
+
+.historyChartCanvas,
+.historyChartState {
+ width: 100%;
+ height: 190px;
+}
+
+.historyChartState {
+ display: grid;
+ place-items: center;
+}
+
+.loadMore {
+ grid-column: 1 / -1;
+ justify-self: center;
+}
+
+@container monitor-workbench (max-width: 860px) {
+ .selectedHistoryHeader {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+
+ .selectedHistoryControls {
+ width: 100%;
+ }
+}
+
+@container monitor-workbench (max-width: 720px) {
+ .historyGrid {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .historyStatistics {
+ justify-content: flex-start;
+ overflow-x: auto;
+ }
+}
diff --git a/web-app/src/features/monitor/components/monitor-history-results.tsx b/web-app/src/features/monitor/components/monitor-history-results.tsx
deleted file mode 100644
index ab8a027478..0000000000
--- a/web-app/src/features/monitor/components/monitor-history-results.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0.
- */
-
-import { Alert, Button, Select } from 'antd';
-import type { ReactNode } from 'react';
-import { useEffect, useMemo, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { OperationalStatePanel } from '@/shared/operational-page';
-
-import {
- monitorMetricHistoryRanges,
- type MonitorHistoryChart,
- type MonitorMetricWorkbenchController
-} from '../model/monitor-detail-model';
-import type { MonitorHistoryChartRenderInput, MonitorHistoryChartRuntime } from './monitor-history-chart-runtime';
-import styles from './monitor-metric-workbench.module.css';
-import { useActivateWhenVisible } from './use-activate-when-visible';
-
-export function MonitorHistoryResult({ state, actions }: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'>) {
- const { t } = useTranslation();
- return (
- <HistoryAvailabilityBoundary availability={state.historyAvailability}>
- {state.historyCharts.length === 0 && !state.hasMoreHistoryCharts ? (
- <OperationalStatePanel
- kind="empty"
- title={t(state.historySupported ? 'monitorMetrics.empty' : 'monitorMetrics.historyUnsupported')}
- />
- ) : (
- <div className={styles.historyGrid}>
- {state.historyCharts.map(chart => (
- <MonitorHistoryChartCard key={chart.metric.key} chart={chart} actions={actions} />
- ))}
- {state.hasMoreHistoryCharts ? <HistoryLoadMore actions={actions} /> : null}
- </div>
- )}
- </HistoryAvailabilityBoundary>
- );
-}
-
-function HistoryAvailabilityBoundary({
- availability,
- children
-}: {
- availability: MonitorMetricWorkbenchController['state']['historyAvailability'];
- children: ReactNode;
-}) {
- const { t } = useTranslation();
- if (availability.kind === 'loading')
- return <OperationalStatePanel kind="loading" title={t('monitorMetrics.loading')} />;
- if (availability.kind === 'unavailable')
- return <OperationalStatePanel kind="unavailable" title={t('common.unavailable')} />;
- if (availability.kind === 'unknown')
- return <OperationalStatePanel kind="unavailable" title={t('monitorMetrics.storageUnknown')} />;
- if (availability.kind === 'error')
- return <OperationalStatePanel kind="error" title={t('common.routeError.description')} />;
- return (
- <div className={styles.historyResult}>
- {availability.kind === 'degraded' ? (
- <Alert type="warning" showIcon message={t('monitorMetrics.storageDegraded')} />
- ) : null}
- {children}
- </div>
- );
-}
-
-export function MonitorSelectedHistoryResult({
- state,
- actions
-}: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'>) {
- const { t } = useTranslation();
- const chart = state.selectedHistoryChart;
- return (
- <HistoryAvailabilityBoundary availability={state.historyAvailability}>
- {chart ? (
- <MonitorHistoryChartCard chart={chart} actions={actions} />
- ) : (
- <OperationalStatePanel kind="empty" title={t('monitorMetrics.historyUnsupported')} />
- )}
- </HistoryAvailabilityBoundary>
- );
-}
-
-function MonitorHistoryChartCard({
- chart,
- actions
-}: {
- chart: MonitorHistoryChart;
- actions: MonitorMetricWorkbenchController['actions'];
-}) {
- const { t } = useTranslation();
- const target = useActivateWhenVisible<HTMLElement>(
- true,
- () => actions.activateHistoryChart(chart.metric.key),
- '240px 0px'
- );
- return (
- <article ref={target} className={styles.historyChart} data-history-metric={chart.metric.key}>
- <header className={styles.historyChartHeader}>
- <div className={styles.historyChartTitle}>
- <h5>{chart.metric.key}</h5>
- {chart.metric.unit ? <span>{chart.metric.unit}</span> : null}
- </div>
- <div className={styles.historyChartActions}>
- <Select
- size="small"
- value={chart.history}
- aria-label={t('monitorMetrics.historyRange')}
- onChange={value => actions.setHistoryChartRange(chart.metric.key, value)}
- options={monitorMetricHistoryRanges.map(value => ({ value, label: value }))}
- />
- <Button size="small" onClick={() => actions.refreshHistoryChart(chart.metric.key)}>
- {t('common.refresh')}
- </Button>
- </div>
- </header>
- <HistoryChartEvidence chart={chart} />
- </article>
- );
-}
-
-function HistoryChartEvidence({ chart }: { chart: MonitorHistoryChart }) {
- const { t } = useTranslation();
- if (chart.result.kind === 'unavailable') return <ChartState kind="unavailable" title={t('common.unavailable')} />;
- if (chart.result.kind === 'error') return <ChartState kind="error" title={t('common.routeError.description')} />;
- if (chart.result.kind === 'empty') return <ChartState kind="empty" title={t('monitorMetrics.empty')} />;
- if (chart.result.kind === 'unsupported')
- return <ChartState kind="empty" title={t('monitorMetrics.historyUnsupported')} />;
- if (chart.result.kind === 'loading') return <ChartState kind="loading" title={t('monitorMetrics.loading')} />;
- return <HistoryChartCanvas chart={chart} />;
-}
-
-function HistoryChartCanvas({ chart }: { chart: MonitorHistoryChart }) {
- const { t } = useTranslation();
- const element = useRef<HTMLDivElement>(null);
- const runtime = useRef<MonitorHistoryChartRuntime | undefined>(undefined);
- const input = useMemo<MonitorHistoryChartRenderInput>(
- () => ({
- title: chart.metric.key,
- unit: chart.metric.unit,
- series: chart.result.rows,
- saveImageTitle: t('monitorMetrics.saveImage')
- }),
- [chart.metric.key, chart.metric.unit, chart.result.rows, t]
- );
- const latest = useRef(input);
- useEffect(() => {
- latest.current = input;
- runtime.current?.update(input);
- }, [input]);
- useEffect(() => {
- let cancelled = false;
- async function mountChart() {
- const module = await import('./monitor-history-chart-runtime');
- if (cancelled || !element.current) return;
- runtime.current = module.createMonitorHistoryChart(element.current, latest.current);
- }
- void mountChart();
- return () => {
- cancelled = true;
- runtime.current?.dispose();
- runtime.current = undefined;
- };
- }, [chart.metric.key]);
- return <div ref={element} className={styles.historyChartCanvas} role="img" aria-label={chart.metric.key} />;
-}
-
-function ChartState({ kind, title }: { kind: 'loading' | 'empty' | 'unavailable' | 'error'; title: string }) {
- return (
- <div className={styles.historyChartState}>
- <OperationalStatePanel kind={kind} title={title} />
- </div>
- );
-}
-
-function HistoryLoadMore({ actions }: Pick<MonitorMetricWorkbenchController, 'actions'>) {
- const { t } = useTranslation();
- const target = useActivateWhenVisible<HTMLButtonElement>(true, actions.loadMoreHistoryCharts);
- return (
- <Button ref={target} className={styles.loadMore!} onClick={actions.loadMoreHistoryCharts}>
- {t('monitorMetrics.loadMoreHistory')}
- </Button>
- );
-}
diff --git a/web-app/src/features/monitor/components/monitor-history-values.ts b/web-app/src/features/monitor/components/monitor-history-values.ts
new file mode 100644
index 0000000000..2f7ebb117c
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-history-values.ts
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import type { MonitorHistoryChart, MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+
+export function selectedCurrentValue(state: MonitorMetricWorkbenchController['state'], field: string) {
+ const selectedRows = state.realtime.kind === 'ready' || state.realtime.kind === 'loading' ? state.realtime.rows : [];
+ const groupRows = state.realtimeGroups.flatMap(group =>
+ group.result.kind === 'ready' || group.result.kind === 'loading' ? group.result.rows : []
+ );
+ const row =
+ selectedRows.find(candidate => candidate.field === field) ?? groupRows.find(candidate => candidate.field === field);
+ return { value: row?.value ?? '—', time: row?.collectedAt ?? row?.time ?? null };
+}
+
+export function historyStatistics(chart: MonitorHistoryChart) {
+ if (chart.result.kind !== 'ready') return undefined;
+ const values = chart.result.rows.flatMap(series => series.points.map(([, value]) => value)).filter(Number.isFinite);
+ if (values.length === 0) return undefined;
+ const format = (value: number) => new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value);
+ return {
+ minimum: format(Math.min(...values)),
+ maximum: format(Math.max(...values)),
+ average: format(values.reduce((total, value) => total + value, 0) / values.length),
+ samples: values.length
+ };
+}
+
+export function formatMetricTime(value: number | null) {
+ return value == null
+ ? '—'
+ : new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'medium' }).format(value);
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-group-navigation.ts b/web-app/src/features/monitor/components/monitor-metric-group-navigation.ts
new file mode 100644
index 0000000000..58ae196c3d
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-metric-group-navigation.ts
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import type { MetricView } from './monitor-metric-toolbar';
+
+export function filterRealtimeGroups(
+ groups: MonitorMetricWorkbenchController['state']['realtimeGroups'],
+ favoriteGroups: Set<string>,
+ view: MetricView,
+ search: string,
+ groupFilter: string
+) {
+ const normalized = search.trim().toLocaleLowerCase();
+ return groups.flatMap(group => {
+ if (groupFilter && group.group !== groupFilter) return [];
+ if (view === 'favorites' && !favoriteGroups.has(group.group)) return [];
+ const groupMatches = group.group.toLocaleLowerCase().includes(normalized);
+ if (group.result.kind !== 'ready' && group.result.kind !== 'loading') {
+ return normalized && !groupMatches ? [] : [group];
+ }
+ const rows = group.result.rows.filter(row => {
+ const searchMatches =
+ !normalized ||
+ groupMatches ||
+ row.field.toLocaleLowerCase().includes(normalized) ||
+ row.value.toLocaleLowerCase().includes(normalized) ||
+ Object.entries(row.labels).some(([key, value]) => `${key}=${value}`.toLocaleLowerCase().includes(normalized));
+ return searchMatches;
+ });
+ return rows.length === 0 ? [] : [{ ...group, result: { ...group.result, rows } }];
+ });
+}
+
+export function availableFavoriteGroups(evidence: MonitorMetricWorkbenchController['state']['favoriteCollection']) {
+ return new Set(evidence.kind === 'ready' ? evidence.items.filter(item => item.available).map(item => item.key) : []);
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-layout-toolbar.test.tsx b/web-app/src/features/monitor/components/monitor-metric-layout-toolbar.test.tsx
new file mode 100644
index 0000000000..7172b1a5fa
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-metric-layout-toolbar.test.tsx
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { MonitorMetricLayoutActions, MonitorMetricLayoutState } from '../model/monitor-metric-layout-model';
+import { MonitorMetricLayoutToolbar } from './monitor-metric-layout-toolbar';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+describe('MonitorMetricLayoutToolbar', () => {
+ it('keeps the ordinary view quiet until the operator explicitly edits', () => {
+ const actions = layoutActions();
+ render(<MonitorMetricLayoutToolbar state={layoutState()} actions={actions} />);
+
+ expect(screen.getByRole('button', { name: 'monitorMetrics.layout.edit' })).toBeVisible();
+ expect(screen.queryByRole('button', { name: 'common.save' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'monitorMetrics.layout.edit' }));
+ expect(actions.beginEdit).toHaveBeenCalledOnce();
+ });
+
+ it('keeps edit mode focused on direct manipulation plus save, cancel, and reset', () => {
+ const actions = layoutActions();
+ render(<MonitorMetricLayoutToolbar state={layoutState({ editing: true })} actions={actions} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }));
+ fireEvent.click(screen.getByRole('button', { name: 'common.save' }));
+
+ expect(screen.queryByRole('button', { name: 'monitorMetrics.layout.historyTaller' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'monitorMetrics.layout.historyShorter' })).not.toBeInTheDocument();
+ expect(actions.cancelEdit).toHaveBeenCalledOnce();
+ expect(actions.save).toHaveBeenCalledOnce();
+ expect(screen.getByText('monitorMetrics.layout.editHint')).toBeVisible();
+ });
+});
+
+function layoutState(overrides: Partial<MonitorMetricLayoutState> = {}): MonitorMetricLayoutState {
+ return {
+ readState: 'ready',
+ editing: false,
+ saving: false,
+ revision: 'layout-r1',
+ hasSavedLayout: true,
+ layout: {
+ schemaVersion: 1,
+ mode: 'custom',
+ columns: 12,
+ items: [
+ { group: 'basic', x: 0, y: 0, w: 4, h: 10, collapsed: false, order: 0 },
+ { group: 'status', x: 4, y: 0, w: 4, h: 10, collapsed: false, order: 1 }
+ ],
+ historyDock: { collapsed: false, height: 12 }
+ },
+ ...overrides
+ };
+}
+
+function layoutActions(): MonitorMetricLayoutActions {
+ return {
+ beginEdit: vi.fn(),
+ cancelEdit: vi.fn(),
+ changeItems: vi.fn(),
+ changeHistoryDock: vi.fn(),
+ save: vi.fn().mockResolvedValue(undefined),
+ reset: vi.fn().mockResolvedValue(undefined)
+ };
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-layout-toolbar.tsx b/web-app/src/features/monitor/components/monitor-metric-layout-toolbar.tsx
new file mode 100644
index 0000000000..8a8b5047ed
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-metric-layout-toolbar.tsx
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { EditOutlined } from '@ant-design/icons';
+import { Button, Popconfirm } from 'antd';
+import { useTranslation } from 'react-i18next';
+
+import type { MonitorMetricLayoutActions, MonitorMetricLayoutState } from '../model/monitor-metric-layout-model';
+import styles from './monitor-metric-layout.module.css';
+
+export function MonitorMetricLayoutToolbar({
+ state,
+ actions,
+ onBeginEdit
+}: {
+ state: MonitorMetricLayoutState;
+ actions: MonitorMetricLayoutActions;
+ onBeginEdit?: (() => void) | undefined;
+}) {
+ return state.editing ? (
+ <LayoutEditToolbar state={state} actions={actions} />
+ ) : (
+ <LayoutViewToolbar state={state} actions={actions} onBeginEdit={onBeginEdit} />
+ );
+}
+
+function LayoutViewToolbar({
+ state,
+ actions,
+ onBeginEdit
+}: {
+ state: MonitorMetricLayoutState;
+ actions: MonitorMetricLayoutActions;
+ onBeginEdit?: (() => void) | undefined;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className={styles.layoutInlineControl}>
+ {state.readState !== 'ready' && state.readState !== 'loading' ? (
+ <span className={styles.layoutReadWarning}>{t('monitorMetrics.layout.localFallback')}</span>
+ ) : null}
+ <Button
+ size="small"
+ icon={<EditOutlined />}
+ aria-label={t('monitorMetrics.layout.edit')}
+ onClick={() => {
+ onBeginEdit?.();
+ actions.beginEdit();
+ }}
+ >
+ {t('monitorMetrics.layout.edit')}
+ </Button>
+ </div>
+ );
+}
+
+function LayoutEditToolbar({
+ state,
+ actions
+}: {
+ state: MonitorMetricLayoutState;
+ actions: MonitorMetricLayoutActions;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className={styles.layoutEditInline} role="toolbar" aria-label={t('monitorMetrics.layout.title')}>
+ <span className={styles.layoutEditHint}>{t('monitorMetrics.layout.editHint')}</span>
+ <div className={styles.layoutEditActions}>
+ <Popconfirm
+ title={t('monitorMetrics.layout.resetConfirm')}
+ okText={t('monitorMetrics.layout.reset')}
+ cancelText={t('common.cancel')}
+ onConfirm={() => {
+ void actions.reset();
+ }}
+ >
+ <Button size="small" disabled={state.saving}>
+ {t('monitorMetrics.layout.reset')}
+ </Button>
+ </Popconfirm>
+ <Button size="small" disabled={state.saving} onClick={actions.cancelEdit}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="primary"
+ size="small"
+ loading={state.saving}
+ onClick={() => {
+ void actions.save();
+ }}
+ >
+ {t('common.save')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-layout.module.css b/web-app/src/features/monitor/components/monitor-metric-layout.module.css
new file mode 100644
index 0000000000..e2bee13eb5
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-metric-layout.module.css
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+.layoutInlineControl,
+.layoutEditInline,
+.layoutEditActions {
+ display: flex;
+ min-width: 0;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--hb-space-2);
+}
+
+.layoutInlineControl {
+ padding-inline-start: var(--hb-space-2);
+ border-inline-start: 1px solid var(--hb-border-subtle);
+}
+
+.layoutReadWarning,
+.layoutEditHint {
+ color: var(--hb-text-muted);
+ font-size: 11px;
+}
+
+.layoutEditInline {
+ justify-content: flex-end;
+ padding-inline-start: var(--hb-space-2);
+ border-inline-start: 1px solid var(--hb-border-subtle);
+}
+
+.realtimeLayoutHost {
+ width: 100%;
+ min-width: 0;
+}
+
+.realtimeLayoutItem,
+.realtimeLayoutItemEditing {
+ min-width: 0;
+}
+
+.realtimeLayoutItem > :global([data-monitor-group]),
+.realtimeLayoutItemEditing > :global([data-monitor-group]) {
+ height: 100%;
+ overflow: hidden;
+}
+
+.realtimeLayoutItemEditing {
+ border-radius: var(--hb-radius-control);
+ outline: 1px dashed color-mix(in srgb, var(--hb-brand-accent) 65%, transparent);
+ outline-offset: 2px;
+}
+
+.realtimeLayoutItemEditing :global([data-layout-panel-header]) {
+ cursor: grab;
+ user-select: none;
+}
+
+.realtimeLayoutItemEditing :global([data-layout-panel-header]) :global(.ant-btn) {
+ cursor: default;
+}
+
+.realtimeLayoutHost :global(.react-grid-item > .react-resizable-handle::after) {
+ width: 8px;
+ height: 8px;
+ border-color: var(--hb-brand-accent);
+}
+
+@container monitor-workbench (max-width: 860px) {
+ .layoutInlineControl,
+ .layoutEditInline {
+ padding-inline-start: 0;
+ border-inline-start: 0;
+ }
+
+ .realtimeLayoutItemEditing :global([data-layout-panel-header]) {
+ min-height: 70px;
+ align-items: flex-end;
+ padding-inline-end: 8px;
+ }
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-results.tsx b/web-app/src/features/monitor/components/monitor-metric-results.tsx
index afa33d605f..d01eb7da29 100644
--- a/web-app/src/features/monitor/components/monitor-metric-results.tsx
+++ b/web-app/src/features/monitor/components/monitor-metric-results.tsx
@@ -5,86 +5,111 @@
* The ASF licenses this file to You under the Apache License, Version 2.0.
*/
-import { Button, Tabs, Tag } from 'antd';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { OperationalStatePanel } from '@/shared/operational-page';
import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
-import { MonitorHistoryResult, MonitorSelectedHistoryResult } from './monitor-history-results';
-import { MonitorRealtimeResult, SelectedRealtimeResult } from './monitor-realtime-results';
+import { availableFavoriteGroups, filterRealtimeGroups } from './monitor-metric-group-navigation';
+import { MonitorMetricToolbar, type MetricView } from './monitor-metric-toolbar';
+import { MonitorRealtimeResult } from './monitor-realtime-results';
+import { MonitorSelectedHistoryTray } from './monitor-selected-history-tray';
import styles from './monitor-metric-workbench.module.css';
export function MonitorMetricResults({ state, actions }: MonitorMetricWorkbenchController) {
- const { t } = useTranslation();
+ const [view, setView] = useState<MetricView>('all');
+ const [search, setSearch] = useState('');
+ const [groupFilter, setGroupFilter] = useState('');
+ const favoriteGroups = useMemo(() => availableFavoriteGroups(state.favoriteCollection), [state.favoriteCollection]);
+ const groups = useMemo(
+ () => filterRealtimeGroups(state.realtimeGroups, favoriteGroups, view, search, groupFilter),
+ [favoriteGroups, groupFilter, search, state.realtimeGroups, view]
+ );
+ useActivateSelectedHistory(state, actions);
return (
- <Tabs
- items={[
- {
- key: 'realtime',
- label: t('monitorMetrics.realtime'),
- children: <MonitorRealtimeResult state={state} actions={actions} />
- },
- {
- key: 'history',
- label: t('monitorMetrics.history'),
- children: <MonitorHistoryResult state={state} actions={actions} />
- },
- {
- key: 'favorites',
- label: t('monitorMetrics.favorites'),
- children: <FavoriteCollection state={state} actions={actions} />
- }
- ]}
- />
+ <>
+ <MonitorMetricToolbar
+ state={state}
+ actions={actions}
+ view={view}
+ search={search}
+ groupFilter={groupFilter}
+ favoriteCount={favoriteGroups.size}
+ onViewChange={setView}
+ onSearchChange={setSearch}
+ onGroupFilterChange={setGroupFilter}
+ onBeginLayoutEdit={() => {
+ setView('all');
+ setSearch('');
+ setGroupFilter('');
+ }}
+ />
+ <MonitorSelectedHistoryTray state={state} actions={actions} />
+ <MetricResultsBody
+ state={state}
+ actions={actions}
+ groups={groups}
+ favoriteGroupCount={favoriteGroups.size}
+ view={view}
+ />
+ </>
);
}
-function FavoriteCollection({ state, actions }: MonitorMetricWorkbenchController) {
+function MetricResultsBody({
+ state,
+ actions,
+ groups,
+ favoriteGroupCount,
+ view
+}: {
+ state: MonitorMetricWorkbenchController['state'];
+ actions: MonitorMetricWorkbenchController['actions'];
+ groups: MonitorMetricWorkbenchController['state']['realtimeGroups'];
+ favoriteGroupCount: number;
+ view: MetricView;
+}) {
const { t } = useTranslation();
- const evidence = state.favoriteCollection;
- if (evidence.kind !== 'ready') return <FavoriteCollectionState kind={evidence.kind} />;
- const selected = evidence.items.some(item => item.available && item.key === state.metricKey);
+ if (view === 'favorites' && state.favoriteCollection.kind !== 'ready') {
+ return <FavoriteCollectionState kind={state.favoriteCollection.kind} />;
+ }
+ if (view === 'favorites' && favoriteGroupCount === 0) {
+ return <FavoriteCollectionState kind="empty" />;
+ }
+ if (groups.length === 0) return <OperationalStatePanel kind="no-match" title={t('monitorMetrics.noMatches')} />;
return (
- <div className={styles.favoriteCollection}>
- <div className={styles.favoriteList}>
- {evidence.items.map(item => (
- <span key={item.key} className={styles.favoriteItem}>
- <Button
- disabled={!item.available}
- type="default"
- aria-pressed={item.key === state.metricKey}
- className={(item.key === state.metricKey ? styles.favoriteChoiceSelected : styles.favoriteChoice) ?? ''}
- onClick={() => actions.setMetric(item.key)}
- >
- {item.key}
- </Button>
- {!item.available && <Tag>{t('monitorMetrics.favoriteUnavailable')}</Tag>}
- </span>
- ))}
- </div>
- {selected ? (
- <Tabs
- items={[
- {
- key: 'realtime',
- label: t('monitorMetrics.realtime'),
- children: <SelectedRealtimeResult state={state} />
- },
- {
- key: 'history',
- label: t('monitorMetrics.history'),
- children: <MonitorSelectedHistoryResult state={state} actions={actions} />
- }
- ]}
- />
- ) : (
- <OperationalStatePanel kind="empty" title={t('monitorMetrics.favoriteSelect')} />
- )}
+ <div className={styles.currentValueWorkspace}>
+ <MonitorRealtimeResult
+ state={state}
+ actions={actions}
+ groups={groups}
+ onSelectMetric={metricKey => {
+ actions.setMetric(metricKey);
+ actions.activateHistoryChart(metricKey);
+ }}
+ />
</div>
);
}
+function useActivateSelectedHistory(
+ state: MonitorMetricWorkbenchController['state'],
+ actions: MonitorMetricWorkbenchController['actions']
+) {
+ const activatedHistoryKey = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ const metricKey = state.selectedHistoryChart?.metric.key;
+ if (!metricKey || !state.historySupported) {
+ activatedHistoryKey.current = undefined;
+ return;
+ }
+ if (activatedHistoryKey.current === metricKey) return;
+ activatedHistoryKey.current = metricKey;
+ actions.activateHistoryChart(metricKey);
+ }, [actions, state.historySupported, state.selectedHistoryChart?.metric.key]);
+}
+
function FavoriteCollectionState({ kind }: { kind: 'loading' | 'empty' | 'unavailable' | 'error' }) {
const { t } = useTranslation();
switch (kind) {
diff --git a/web-app/src/features/monitor/components/monitor-metric-toolbar.tsx b/web-app/src/features/monitor/components/monitor-metric-toolbar.tsx
new file mode 100644
index 0000000000..63f1ecac61
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-metric-toolbar.tsx
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { PauseOutlined, ReloadOutlined } from '@ant-design/icons';
+import { Button, Input, Select } from 'antd';
+import { useTranslation } from 'react-i18next';
+
+import { OperationalCommandBar } from '@/shared/operational-page';
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import { MonitorMetricLayoutToolbar } from './monitor-metric-layout-toolbar';
+import styles from './monitor-metric-workbench.module.css';
+import { MonitorRefreshSelect } from './monitor-refresh-select';
+import { MonitorSegmentedSwitch } from './monitor-segmented-switch';
+
+export type MetricView = 'all' | 'favorites';
+
+type MonitorMetricToolbarProps = Pick<MonitorMetricWorkbenchController, 'state' | 'actions'> & {
+ view: MetricView;
+ search: string;
+ groupFilter: string;
+ favoriteCount: number;
+ onViewChange: (value: MetricView) => void;
+ onSearchChange: (value: string) => void;
+ onGroupFilterChange: (value: string) => void;
+ onBeginLayoutEdit: () => void;
+};
+
+export function MonitorMetricToolbar(props: MonitorMetricToolbarProps) {
+ const { t } = useTranslation();
+ return (
+ <OperationalCommandBar
+ ariaLabel={t('monitorMetrics.title')}
+ primary={<MetricToolbarPrimary {...props} />}
+ secondary={
+ <div className={styles.metricToolbarSecondary}>
+ <MetricRefreshControls state={props.state} actions={props.actions} />
+ <MonitorMetricLayoutToolbar
+ state={props.state.layout}
+ actions={props.actions.layout}
+ onBeginEdit={props.onBeginLayoutEdit}
+ />
+ </div>
+ }
+ />
+ );
+}
+
+function MetricToolbarPrimary({
+ state,
+ view,
+ search,
+ groupFilter,
+ favoriteCount,
+ onViewChange,
+ onSearchChange,
+ onGroupFilterChange
+}: MonitorMetricToolbarProps) {
+ const { t } = useTranslation();
+ return (
+ <div className={styles.metricToolbarPrimary}>
+ <Input
+ allowClear
+ type="search"
+ value={search}
+ aria-label={t('monitorMetrics.search')}
+ placeholder={t('monitorMetrics.searchPlaceholder')}
+ disabled={state.layout.editing}
+ onChange={event => onSearchChange(event.target.value)}
+ />
+ <Select
+ value={groupFilter}
+ disabled={state.layout.editing}
+ aria-label={t('monitorMetrics.groupFilter')}
+ onChange={onGroupFilterChange}
+ options={[
+ { value: '', label: t('monitorMetrics.allGroups') },
+ ...state.realtimeGroupNames.map(group => ({ value: group, label: group }))
+ ]}
+ />
+ <MetricViewSwitch
+ view={view}
+ allCount={state.catalog.options.length}
+ favoriteCount={favoriteCount}
+ onChange={onViewChange}
+ disabled={state.layout.editing}
+ />
+ </div>
+ );
+}
+
+function MetricViewSwitch({
+ view,
+ allCount,
+ favoriteCount,
+ onChange,
+ disabled
+}: {
+ view: MetricView;
+ allCount: number;
+ favoriteCount: number;
+ onChange: (value: MetricView) => void;
+ disabled: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <MonitorSegmentedSwitch<MetricView>
+ label={t('monitorMetrics.metricView')}
+ value={view}
+ options={[
+ { value: 'all', label: t('monitorMetrics.allMetricCount', { count: allCount }) },
+ { value: 'favorites', label: t('monitorMetrics.favoriteMetricCount', { count: favoriteCount }) }
+ ]}
+ disabled={disabled}
+ onChange={onChange}
+ />
+ );
+}
+
+function MetricRefreshControls({ state, actions }: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'>) {
+ const { t } = useTranslation();
+ return (
+ <div className={styles.metricRefreshControls}>
+ <Button icon={<ReloadOutlined />} aria-label={t('common.refresh')} onClick={actions.refresh} />
+ <MonitorRefreshSelect value={state.refreshSeconds} onChange={actions.setRefreshSeconds} />
+ <span className={styles.recentSample}>
+ {t('monitorMetrics.latestSample')}: {formatShortTime(latestSampleTime(state.realtimeGroups))}
+ </span>
+ <span className={state.refreshSeconds === 0 ? styles.pausedState : styles.liveState}>
+ {t(state.refreshSeconds === 0 ? 'monitorMetrics.paused' : 'monitorMetrics.live')}
+ </span>
+ {state.refreshSeconds === 0 ? (
+ <Button size="small" onClick={() => actions.setRefreshSeconds(60)}>
+ {t('monitorMetrics.returnLive')}
+ </Button>
+ ) : (
+ <Button
+ size="small"
+ icon={<PauseOutlined />}
+ aria-label={t('monitorMetrics.pause')}
+ onClick={() => actions.setRefreshSeconds(0)}
+ />
+ )}
+ </div>
+ );
+}
+
+function latestSampleTime(groups: MonitorMetricWorkbenchController['state']['realtimeGroups']) {
+ let latest: number | null = null;
+ for (const group of groups) {
+ if (group.result.kind !== 'ready' && group.result.kind !== 'loading') continue;
+ for (const row of group.result.rows) {
+ const value = row.collectedAt ?? row.time;
+ if (value != null) latest = latest == null ? value : Math.max(latest, value);
+ }
+ }
+ return latest;
+}
+
+function formatShortTime(value: number | null) {
+ return value == null ? '—' : new Intl.DateTimeFormat(undefined, { timeStyle: 'medium' }).format(value);
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-value.tsx b/web-app/src/features/monitor/components/monitor-metric-value.tsx
new file mode 100644
index 0000000000..d0a9536a9e
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-metric-value.tsx
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { CopyOutlined } from '@ant-design/icons';
+import { Button, Popover, Tooltip } from 'antd';
+import { useCallback, useLayoutEffect, useRef, useState } from 'react';
+import type { KeyboardEvent, ReactNode, RefObject } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import styles from './monitor-realtime-table.module.css';
+
+export function MonitorMetricValue({ field, value }: { field: string; value: string }) {
+ const { t } = useTranslation();
+ const label = t('monitorMetrics.value.open', { field });
+ const [stored, setStored] = useState<ValueInteraction>(() => initialInteraction(value));
+ const interaction = activeInteraction(stored, value);
+ const update = (change: Partial<ValueInteraction>) =>
+ setStored(current => ({ ...activeInteraction(current, value), ...change, value }));
+ return (
+ <MetricValueTrigger
+ label={label}
+ value={value}
+ popoverOpen={interaction.popoverOpen}
+ onPopoverOpen={popoverOpen => update({ popoverOpen })}
+ popoverTitle={t('monitorMetrics.value.title', { field })}
+ popoverContent={
+ <MetricValuePopoverContent
+ field={field}
+ value={value}
+ copyState={interaction.copyState}
+ onCopyState={copyState => update({ copyState })}
+ />
+ }
+ />
+ );
+}
+
+type MetricValueTriggerProps = {
+ label: string;
+ value: string;
+ popoverOpen: boolean;
+ popoverTitle: string;
+ popoverContent: ReactNode;
+ onPopoverOpen: (open: boolean) => void;
+};
+
+function MetricValueTrigger(props: MetricValueTriggerProps) {
+ const { label, value, popoverOpen, popoverTitle, popoverContent, onPopoverOpen } = props;
+ const valueRef = useRef<HTMLSpanElement>(null);
+ const [measurement, setMeasurement] = useState({ value, overflowed: false });
+ const [hovered, setHovered] = useState(false);
+ const [focused, setFocused] = useState(false);
+ const overflowed = measurement.value === value && measurement.overflowed;
+ const measure = useCallback(() => {
+ const node = valueRef.current;
+ if (node) setMeasurement({ value, overflowed: node.scrollWidth > node.clientWidth });
+ }, [value]);
+ useLayoutEffect(() => observeOverflow(valueRef, measure), [measure, value]);
+ const open = overflowed && popoverOpen;
+ return (
+ <Tooltip
+ title={value}
+ open={overflowed && !open && (hovered || focused)}
+ placement="top"
+ mouseEnterDelay={0.25}
+ destroyOnHidden
+ >
+ <Popover
+ trigger="click"
+ placement="topRight"
+ destroyOnHidden
+ open={open}
+ onOpenChange={next => overflowed && onPopoverOpen(next)}
+ title={popoverTitle}
+ content={popoverContent}
+ >
+ <span
+ ref={valueRef}
+ className={styles.metricValueText}
+ {...(overflowed
+ ? {
+ 'aria-expanded': open,
+ 'aria-haspopup': 'dialog' as const,
+ 'aria-label': label,
+ role: 'button',
+ tabIndex: 0
+ }
+ : {})}
+ onMouseEnter={() => {
+ measure();
+ setHovered(true);
+ }}
+ onMouseLeave={() => setHovered(false)}
+ onFocus={() => {
+ measure();
+ setFocused(true);
+ }}
+ onBlur={() => setFocused(false)}
+ onKeyDown={event => handleTriggerKey(event, overflowed, open, onPopoverOpen, setFocused)}
+ >
+ {value}
+ </span>
+ </Popover>
+ </Tooltip>
+ );
+}
+
+function observeOverflow(ref: RefObject<HTMLSpanElement | null>, measure: () => void) {
+ measure();
+ if (typeof ResizeObserver === 'undefined' || !ref.current) return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(ref.current);
+ return () => observer.disconnect();
+}
+
+function handleTriggerKey(
+ event: KeyboardEvent<HTMLSpanElement>,
+ overflowed: boolean,
+ open: boolean,
+ setOpen: (open: boolean) => void,
+ setFocused: (focused: boolean) => void
+) {
+ if (!overflowed) return;
+ if (event.key === 'Escape' && open) {
+ event.preventDefault();
+ setOpen(false);
+ setFocused(false);
+ } else if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ setOpen(!open);
+ }
+}
+
+function MetricValuePopoverContent({
+ field,
+ value,
+ copyState,
+ onCopyState
+}: {
+ field: string;
+ value: string;
+ copyState: ValueInteraction['copyState'];
+ onCopyState: (copyState: 'copied' | 'error') => void;
+}) {
+ const { t } = useTranslation();
+ const copyKey = copyState === 'idle' ? 'copy' : copyState;
+ return (
+ <div className={styles.metricValuePopover} role="dialog" aria-label={t('monitorMetrics.value.title', { field })}>
+ <div className={styles.metricValuePopoverText}>{value}</div>
+ <Button
+ size="small"
+ type="text"
+ icon={<CopyOutlined />}
+ aria-label={t(`monitorMetrics.value.${copyKey}`)}
+ onClick={() => void copyValue(value, onCopyState)}
+ >
+ {t(`monitorMetrics.value.${copyKey}`)}
+ </Button>
+ </div>
+ );
+}
+
+async function copyValue(value: string, setCopyState: (state: 'copied' | 'error') => void) {
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopyState('copied');
+ } catch {
+ setCopyState('error');
+ }
+}
+
+type ValueInteraction = { value: string; popoverOpen: boolean; copyState: 'idle' | 'copied' | 'error' };
+
+function initialInteraction(value: string): ValueInteraction {
+ return { value, popoverOpen: false, copyState: 'idle' };
+}
+
+function activeInteraction(interaction: ValueInteraction, value: string) {
+ return interaction.value === value ? interaction : initialInteraction(value);
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-visual-contract.test.ts b/web-app/src/features/monitor/components/monitor-metric-visual-contract.test.ts
index b412b4eaf5..4b9fbdd2ce 100644
--- a/web-app/src/features/monitor/components/monitor-metric-visual-contract.test.ts
+++ b/web-app/src/features/monitor/components/monitor-metric-visual-contract.test.ts
@@ -7,22 +7,72 @@
import { describe, expect, it } from 'vitest';
+import historyStyles from './monitor-history-results.module.css?raw';
+import cardStyles from './monitor-realtime-card.module.css?raw';
+import segmentedStyles from './monitor-segmented-switch.module.css?raw';
+import tableStyles from './monitor-realtime-table.module.css?raw';
import workbenchStyles from './monitor-metric-workbench.module.css?raw';
describe('monitor metric visual contract', () => {
- it('keeps history charts in the established two-column desktop layout', () => {
- const historyRule = workbenchStyles.match(/\.historyGrid\s*\{(?<body>[^}]*)\}/)?.groups?.body;
- const responsiveRules = workbenchStyles.match(/@media[\s\S]*$/)?.[0];
+ it('uses the workbench container rather than the browser viewport to protect readable card widths', () => {
+ const gridRule = workbenchStyles.match(/\.realtimeGrid\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+ const workspaceRule = workbenchStyles.match(/\.currentValueWorkspace\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+ const workbenchRule = workbenchStyles.match(/\.workbench\s*\{(?<body>[^}]*)\}/)?.groups?.body;
- expect(historyRule).toBeDefined();
- expect(historyRule).toMatch(/grid-template-columns:\s*repeat\(2,\s*minmax\(0,\s*1fr\)\)/);
- expect(responsiveRules).toMatch(/\.historyGrid[\s\S]*grid-template-columns:\s*minmax\(0,\s*1fr\)/);
+ expect(gridRule).toMatch(/grid-template-columns:\s*repeat\(3,\s*minmax\(0,\s*1fr\)\)/);
+ expect(workspaceRule).toMatch(/grid-template-columns:\s*minmax\(0,\s*1fr\)/);
+ expect(workbenchRule).toMatch(/container-name:\s*monitor-workbench/);
+ expect(workbenchRule).toMatch(/container-type:\s*inline-size/);
+ expect(workbenchStyles).toMatch(
+ /@container monitor-workbench \(max-width:\s*1080px\)[\s\S]*?\.realtimeGrid\s*\{[\s\S]*?grid-template-columns:\s*repeat\(2,\s*minmax\(0,\s*1fr\)\)/
+ );
+ expect(workbenchStyles).toMatch(
+ /@container monitor-workbench \(max-width:\s*720px\)[\s\S]*?\.realtimeGrid\s*\{[\s\S]*?grid-template-columns:\s*minmax\(0,\s*1fr\)/
+ );
});
it('continues realtime column boundaries through table body cells', () => {
- expect(workbenchStyles).toMatch(
- /\.realtimeGroup\s+:global\(\.ant-table-tbody\s*>\s*tr\s*>\s*td:not\(:last-child\)\)/
- );
- expect(workbenchStyles).toMatch(/border-inline-end:\s*1px solid var\(--hb-border-subtle\)/);
+ expect(cardStyles).toMatch(/\.realtimeGroup\s+:global\(\.ant-table-tbody\s*>\s*tr\s*>\s*td:not\(:last-child\)\)/);
+ expect(cardStyles).toMatch(/border-inline-end:\s*1px solid var\(--hb-border-subtle\)/);
+ });
+
+ it('uses native panel overflow and an in-flow history panel instead of expansion surfaces or a fixed tray', () => {
+ const bodyRule = cardStyles.match(/\.realtimeGroupBody\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+ const valueRule = tableStyles.match(/\.metricValueText\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+ const canvasRule = historyStyles.match(/\.historyChartCanvas,\s*\n\.historyChartState\s*\{(?<body>[^}]*)\}/)?.groups
+ ?.body;
+ const trayRule = historyStyles.match(/\.selectedHistoryTray\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+
+ expect(bodyRule).toMatch(/overflow:\s*auto/);
+ expect(cardStyles).not.toMatch(/\.groupExpansion\s*\{/);
+ expect(valueRule).toMatch(/text-overflow:\s*ellipsis/);
+ expect(canvasRule).toMatch(/height:\s*190px/);
+ expect(trayRule).not.toMatch(/grid-template-columns/);
+ expect(trayRule).toMatch(/position:\s*relative/);
+ expect(trayRule).not.toMatch(/inset-inline-start|inset-inline-end|bottom/);
+ expect(historyStyles).not.toMatch(/\.historySummary\s*\{/);
+ });
+
+ it('presents chart statistics as a quiet inline legend instead of detached pills', () => {
+ const statisticsRules = [...historyStyles.matchAll(/\.historyStatistics\s*\{(?<body>[^}]*)\}/g)];
+ const statisticsRule = statisticsRules.find(rule => rule.groups?.body?.includes('min-height'))?.groups?.body;
+ const itemRule = historyStyles.match(/\.historyStatistic\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+
+ expect(statisticsRule).toMatch(/justify-content:\s*flex-start/);
+ expect(statisticsRule).toMatch(/gap:\s*var\(--hb-space-4\)/);
+ expect(itemRule).toMatch(/display:\s*inline-flex/);
+ expect(itemRule).not.toMatch(/border-radius|background/);
+ });
+
+ it('uses one token-backed segmented language for metric and history choices', () => {
+ const rootRule = segmentedStyles.match(/\.switch:global\(\.ant-segmented\)\s*\{(?<body>[^}]*)\}/)?.groups?.body;
+ const selectedRule = segmentedStyles.match(
+ /\.switch\s+:global\(\.ant-segmented-item-selected\)\s*\{(?<body>[^}]*)\}/
+ )?.groups?.body;
+
+ expect(rootRule).toMatch(/border:\s*1px solid var\(--hb-border-subtle\)/);
+ expect(rootRule).toMatch(/background:\s*var\(--hb-bg-hover\)/);
+ expect(selectedRule).toMatch(/background:\s*var\(--hb-brand-accent\)/);
+ expect(selectedRule).toMatch(/color:\s*var\(--hb-text-on-accent\)/);
});
});
diff --git a/web-app/src/features/monitor/components/monitor-metric-workbench.module.css b/web-app/src/features/monitor/components/monitor-metric-workbench.module.css
index 96d289e96c..58ce2e7e65 100644
--- a/web-app/src/features/monitor/components/monitor-metric-workbench.module.css
+++ b/web-app/src/features/monitor/components/monitor-metric-workbench.module.css
@@ -2,162 +2,138 @@
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
*/
.workbench {
display: grid;
- gap: var(--hb-space-3);
-}
-.toolbarControls {
- display: flex;
min-width: 0;
- flex-wrap: wrap;
gap: var(--hb-space-2);
+ container-name: monitor-workbench;
+ container-type: inline-size;
}
-.labels {
- display: flex;
- flex-wrap: wrap;
- gap: 4px;
-}
-.favoriteCollection {
- display: grid;
- gap: 12px;
-}
-.favoriteList {
+
+.metricToolbarPrimary,
+.metricToolbarSecondary,
+.metricRefreshControls {
display: flex;
+ min-width: 0;
flex-wrap: wrap;
- gap: 8px;
-}
-.favoriteItem {
- display: inline-flex;
align-items: center;
- gap: 4px;
-}
-.favoriteChoice,
-.favoriteChoiceSelected {
- color: var(--hb-text-secondary);
- background: transparent;
+ gap: var(--hb-space-2);
}
-.favoriteChoiceSelected,
-.favoriteChoiceSelected:hover {
- border-color: var(--hb-border-strong);
- color: var(--hb-text-primary);
- background: var(--hb-nav-selected);
- box-shadow: inset 2px 0 0 var(--hb-brand-accent);
+
+.metricToolbarPrimary :global(.ant-input-affix-wrapper),
+.metricToolbarPrimary > :global(.ant-input) {
+ width: 184px;
}
-.realtimeGrid {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: var(--hb-space-3);
+
+.metricToolbarPrimary > :global(.ant-select) {
+ width: 136px;
}
-.realtimeGroup {
- min-width: 0;
- overflow: hidden;
- border: 1px solid var(--hb-border-subtle);
- border-radius: var(--hb-radius-surface);
- background: var(--hb-bg-raised);
+
+.metricToolbarSecondary {
+ justify-content: flex-end;
}
-.realtimeGroupHeader {
- display: flex;
- min-height: 42px;
- align-items: center;
- justify-content: space-between;
- gap: var(--hb-space-2);
- padding: 0 var(--hb-space-3);
- border-bottom: 1px solid var(--hb-border-subtle);
+
+.metricRefreshControls {
+ flex-wrap: nowrap;
}
-.realtimeGroupHeader h5 {
- margin: 0;
- overflow: hidden;
- font-size: 13px;
- font-weight: 600;
- text-overflow: ellipsis;
+
+.recentSample {
+ color: var(--hb-text-muted);
+ font-size: 12px;
white-space: nowrap;
}
-.realtimeGroup :global(.ant-table-thead > tr > th:not(:last-child)),
-.realtimeGroup :global(.ant-table-tbody > tr > td:not(:last-child)) {
- border-inline-end: 1px solid var(--hb-border-subtle);
+
+.liveState,
+.pausedState {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--hb-text-secondary);
+ font-size: 12px;
+ white-space: nowrap;
}
-.realtimeGroup :global(.ant-table-thead > tr > th::before) {
- display: none;
+
+.liveState::before,
+.pausedState::before {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--hb-status-available);
+ content: '';
}
-.loadMore {
- grid-column: 1 / -1;
- justify-self: center;
+
+.pausedState::before {
+ background: var(--hb-status-unknown);
}
-.historyResult {
+
+.currentValueWorkspace {
display: grid;
- gap: var(--hb-space-3);
+ min-width: 0;
+ grid-template-columns: minmax(0, 1fr);
+ align-items: start;
+ gap: 0;
}
-.historyGrid {
+
+.realtimeGrid {
display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: var(--hb-space-3);
-}
-.historyChart {
min-width: 0;
- overflow: hidden;
- border: 1px solid var(--hb-border-subtle);
- border-radius: var(--hb-radius-surface);
- background: var(--hb-bg-raised);
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ align-items: start;
+ gap: 10px;
}
-.historyChartHeader {
+
+.groupNavigator {
+ position: sticky;
+ top: var(--hb-space-3);
display: flex;
- min-height: 48px;
- align-items: center;
- justify-content: space-between;
- gap: var(--hb-space-3);
- padding: var(--hb-space-2) var(--hb-space-3);
- border-bottom: 1px solid var(--hb-border-subtle);
-}
-.historyChartTitle {
+ max-height: 610px;
min-width: 0;
+ flex-direction: column;
+ gap: 1px;
+ padding-inline-start: var(--hb-space-3);
+ overflow-y: auto;
+ border-inline-start: 1px solid var(--hb-border-subtle);
}
-.historyChartTitle h5 {
- margin: 0;
- overflow: hidden;
- font-size: 13px;
+
+.groupNavigator strong {
+ padding: 5px 7px;
+ color: var(--hb-text-secondary);
+ font-size: 11px;
font-weight: 600;
- text-overflow: ellipsis;
- white-space: nowrap;
}
-.historyChartTitle span {
+
+.groupNavigator :global(.ant-btn) {
+ display: block;
+ width: 100%;
+ overflow: hidden;
+ justify-content: flex-start;
+ padding-inline: 7px;
color: var(--hb-text-secondary);
- font-size: 12px;
-}
-.historyChartActions {
- display: flex;
- flex: none;
- align-items: center;
- gap: var(--hb-space-2);
+ font-size: 11px;
+ text-align: start;
+ text-overflow: ellipsis;
}
-.historyChartCanvas,
-.historyChartState {
- width: 100%;
- height: 360px;
+
+@container monitor-workbench (max-width: 1080px) {
+ .realtimeGrid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
}
-.historyChartState {
- display: grid;
- place-items: center;
+
+@container monitor-workbench (max-width: 860px) {
+ .metricToolbarSecondary,
+ .metricRefreshControls {
+ width: 100%;
+ justify-content: flex-start;
+ flex-wrap: wrap;
+ }
}
-@media (max-width: 760px) {
- .realtimeGrid,
- .historyGrid {
+
+@container monitor-workbench (max-width: 720px) {
+ .realtimeGrid {
grid-template-columns: minmax(0, 1fr);
}
- .historyChartHeader {
- align-items: flex-start;
- flex-direction: column;
- }
}
diff --git a/web-app/src/features/monitor/components/monitor-metric-workbench.test.tsx b/web-app/src/features/monitor/components/monitor-metric-workbench.test.tsx
index ec9ba0f5db..e34d90ac24 100644
--- a/web-app/src/features/monitor/components/monitor-metric-workbench.test.tsx
+++ b/web-app/src/features/monitor/components/monitor-metric-workbench.test.tsx
@@ -10,11 +10,7 @@ import { I18nextProvider } from 'react-i18next';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { i18n, initializeI18n, loadLocale } from '@/core/i18n/i18n';
-import type {
- MonitorMetricCatalogEvidence,
- MonitorMetricFavoriteCollectionEvidence,
- MonitorMetricWorkbenchController
-} from '../model/monitor-detail-model';
+import type { MonitorMetricCatalogEvidence, MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
import { MonitorMetricWorkbench } from './monitor-metric-workbench';
const catalogCases: Array<[MonitorMetricCatalogEvidence, string]> = [
@@ -23,11 +19,6 @@ const catalogCases: Array<[MonitorMetricCatalogEvidence, string]> = [
[{ kind: 'error', options: [] }, 'common.routeError.description'],
[{ kind: 'empty', options: [] }, 'monitorMetrics.noCatalog']
];
-const favoriteCollectionCases: Array<[MonitorMetricFavoriteCollectionEvidence, string]> = [
- [{ kind: 'unavailable' }, 'common.unavailable'],
- [{ kind: 'error' }, 'common.routeError.description'],
- [{ kind: 'empty', items: [] }, 'monitorMetrics.favoriteEmpty']
-];
describe('MonitorMetricWorkbench', () => {
beforeAll(async () => {
@@ -39,92 +30,188 @@ describe('MonitorMetricWorkbench', () => {
vi.unstubAllGlobals();
});
- it('renders all realtime group fields with units, honest nulls, and epoch zero', () => {
+ it('renders the selected current-value workspace without detached realtime, history, or favorite tabs', () => {
+ const value = controller({
+ catalog: {
+ kind: 'ready',
+ options: [
+ { key: 'summary.responseTime', group: 'summary', field: 'responseTime', unit: 'ms' },
+ { key: 'availability.status', group: 'availability', field: 'status' }
+ ]
+ },
+ metricKey: 'summary.responseTime',
+ favorite: { kind: 'ready', value: true, token: 'summary.responseTime' },
+ favoriteCollection: { kind: 'ready', items: [{ key: 'summary', available: true }] },
+ realtimeGroupNames: ['summary', 'availability'],
+ realtimeGroups: [
+ {
+ ...realtimeGroup('summary'),
+ favorite: { kind: 'ready', value: true, token: 'summary' },
+ result: { kind: 'ready', rows: [{ ...metricRow('responseTime', '12'), unit: 'ms' }] }
+ },
+ {
+ ...realtimeGroup('availability'),
+ result: { kind: 'ready', rows: [metricRow('status', 'UP')] }
+ }
+ ],
+ realtime: { kind: 'ready', rows: [{ ...metricRow('responseTime', '12'), unit: 'ms', collectedAt: 0 }] },
+ selectedHistoryChart: historyChart('summary.responseTime', { kind: 'loading', rows: [] })
+ });
+ renderWorkbench(value);
+
+ expect(screen.queryByRole('tablist')).not.toBeInTheDocument();
+ expect(screen.getByRole('radio', { name: i18n.t('monitorMetrics.allMetricCount', { count: 2 }) })).toBeChecked();
+ expect(document.querySelector('[data-monitor-history-tray]')).toHaveAttribute(
+ 'data-history-metric',
+ 'summary.responseTime'
+ );
+ expect(document.querySelector('[data-monitor-history-tray]')).toHaveTextContent('Current: 12');
+
+ fireEvent.click(screen.getByRole('button', { name: 'summary.responseTime' }));
+ expect(value.actions.setMetric).toHaveBeenCalledWith('summary.responseTime');
+ expect(value.actions.activateHistoryChart).toHaveBeenCalledWith('summary.responseTime');
+
+ const row = document.querySelector('[data-monitor-metric="summary.responseTime"]')!;
+ expect(within(row as HTMLElement).queryByRole('button', { name: i18n.t('monitorMetrics.unfavorite') })).toBeNull();
+ expect(within(row as HTMLElement).queryByRole('button', { name: i18n.t('monitorMetrics.favorite') })).toBeNull();
+ expect(
+ within(document.querySelector('[data-monitor-history-tray]') as HTMLElement).queryByRole('button', {
+ name: i18n.t('monitorMetrics.unfavorite')
+ })
+ ).toBeNull();
+ expect(screen.getAllByRole('button', { name: i18n.t('monitorMetrics.unfavorite') })).toHaveLength(1);
+ });
+
+ it('renders one realtime sample as a dense field/value table without field-level favorites', () => {
+ const value = controller({
+ catalog: {
+ kind: 'ready',
+ options: [
+ { key: 'summary.responseTime', group: 'summary', field: 'responseTime', unit: 'ms' },
+ { key: 'summary.status', group: 'summary', field: 'status' }
+ ]
+ },
+ realtimeGroups: [
+ {
+ ...realtimeGroup('summary'),
+ result: {
+ kind: 'ready',
+ rows: [
+ { ...metricRow('responseTime', '12'), unit: 'ms', collectedAt: 0 },
+ { ...metricRow('status', 'UP'), collectedAt: 0 },
+ metricRow('message', '—')
+ ]
+ }
+ }
+ ]
+ });
+ renderWorkbench(value);
+
+ expect(screen.queryByRole('columnheader')).not.toBeInTheDocument();
+ const responseTimeRow = document.querySelector('[data-monitor-metric="summary.responseTime"]')!;
+ expect(within(responseTimeRow as HTMLElement).getByText('ms')).toBeInTheDocument();
+ expect(within(responseTimeRow as HTMLElement).getByText('12')).toBeInTheDocument();
+ expect(screen.getByText(new Intl.DateTimeFormat(undefined, { timeStyle: 'medium' }).format(0))).toBeInTheDocument();
+ expect(
+ within(responseTimeRow as HTMLElement).queryByRole('button', { name: i18n.t('monitorMetrics.favorite') })
+ ).toBeNull();
+ });
+
+ it('reserves the compact table width for metric identities and values only', () => {
+ renderWorkbench(controller());
+
+ const columns = screen.getByRole('table', { name: i18n.t('monitorMetrics.currentValues') }).querySelectorAll('col');
+ expect(columns).toHaveLength(2);
+ expect(columns[0]).toHaveAttribute('data-metric-column', 'identity');
+ expect(document.querySelector('[data-metric-column="favorite"]')).toBeNull();
+ });
+
+ it('preserves the multi-sample label and field matrix', () => {
renderWorkbench(
controller({
- realtime: {
- kind: 'ready',
- rows: [
- {
- key: '0:responseTime',
- labels: { host: 'a' },
- field: 'responseTime',
- unit: 'ms',
- value: '12',
- time: 0
- },
- {
- key: '0:status',
- labels: { host: 'a' },
- field: 'status',
- unit: null,
- value: 'UP',
- time: 1000
- },
- {
- key: '0:message',
- labels: { host: 'a' },
- field: 'message',
- unit: null,
- value: '—',
- time: null
+ realtimeGroups: [
+ {
+ ...realtimeGroup('summary'),
+ result: {
+ kind: 'ready',
+ rows: [
+ { ...metricRow('qps', '10'), labels: { host: 'a' }, time: 1000 },
+ { ...metricRow('threads', '2'), labels: { host: 'a' }, time: 1000 },
+ { ...metricRow('qps', '11'), key: '1:qps', labels: { host: 'b' }, time: 2000 },
+ { ...metricRow('threads', '3'), key: '1:threads', labels: { host: 'b' }, time: 2000 }
+ ]
}
- ]
- }
+ }
+ ]
})
);
- const responseTimeRow = screen.getByText('responseTime').closest('tr');
- expect(responseTimeRow).not.toBeNull();
- expect(within(responseTimeRow!).getByText('ms')).toBeInTheDocument();
- expect(within(responseTimeRow!).getByText('12')).toBeInTheDocument();
- expect(
- screen.getByText(new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'medium' }).format(0))
- ).toBeInTheDocument();
- expect(within(screen.getByText('status').closest('tr')!).getByText('UP')).toBeInTheDocument();
- expect(within(screen.getByText('message').closest('tr')!).getAllByText('—')).toHaveLength(3);
+
+ expect(screen.getByRole('columnheader', { name: 'host' })).toBeInTheDocument();
+ expect(screen.getByRole('columnheader', { name: 'qps' })).toBeInTheDocument();
+ expect(screen.getByRole('columnheader', { name: 'threads' })).toBeInTheDocument();
+ expect(within(screen.getByText('b').closest('tr')!).getByText('3')).toBeInTheDocument();
});
- it('renders independent realtime groups instead of one selected metric result', () => {
+ it('filters favorites, search, and groups through the single dashboard toolbar', () => {
const value = controller({
+ catalog: {
+ kind: 'ready',
+ options: [
+ { key: 'summary.responseTime', group: 'summary', field: 'responseTime' },
+ { key: 'availability.status', group: 'availability', field: 'status' }
+ ]
+ },
+ favoriteCollection: { kind: 'ready', items: [{ key: 'summary', available: true }] },
+ realtimeGroupNames: ['summary', 'availability'],
realtimeGroups: [
{
- group: 'summary',
+ ...realtimeGroup('summary'),
favorite: { kind: 'ready', value: true, token: 'summary' },
- favoriteBusy: false,
result: { kind: 'ready', rows: [metricRow('responseTime', '12')] }
},
- {
- group: 'availability',
- favorite: { kind: 'ready', value: false },
- favoriteBusy: false,
- result: { kind: 'ready', rows: [metricRow('status', 'UP')] }
- }
- ],
- hasMoreRealtimeGroups: true
+ { ...realtimeGroup('availability'), result: { kind: 'ready', rows: [metricRow('status', 'UP')] } }
+ ]
});
renderWorkbench(value);
+ fireEvent.click(screen.getByRole('radio', { name: /Favorites 1/ }));
expect(screen.getByRole('heading', { name: 'summary' })).toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'availability' })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('radio', { name: i18n.t('monitorMetrics.allMetricCount', { count: 2 }) }));
+ fireEvent.change(screen.getByRole('searchbox', { name: i18n.t('monitorMetrics.search') }), {
+ target: { value: 'status' }
+ });
+ expect(screen.queryByRole('heading', { name: 'summary' })).not.toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'availability' })).toBeInTheDocument();
- expect(screen.getByText('responseTime')).toBeInTheDocument();
- expect(screen.getByText('status')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: i18n.t('monitorMetrics.unfavorite') }));
- expect(value.actions.toggleRealtimeFavorite).toHaveBeenCalledWith('summary');
- fireEvent.click(screen.getByRole('button', { name: i18n.t('monitorMetrics.loadMore') }));
- expect(value.actions.loadMoreRealtimeGroups).toHaveBeenCalledOnce();
+
+ fireEvent.change(screen.getByRole('searchbox', { name: i18n.t('monitorMetrics.search') }), {
+ target: { value: '' }
+ });
+ fireEvent.mouseDown(screen.getByRole('combobox', { name: i18n.t('monitorMetrics.groupFilter') }));
+ fireEvent.click(
+ screen.getAllByText('summary').find(element => element.classList.contains('ant-select-item-option-content'))!
+ );
+ expect(screen.getByRole('heading', { name: 'summary' })).toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'availability' })).not.toBeInTheDocument();
+ });
+
+ it('uses the same two-way segmented control for metric view and history value mode', () => {
+ renderWorkbench(controller({ selectedHistoryChart: historyChart('summary.value', { kind: 'loading', rows: [] }) }));
+
+ expect(screen.getByRole('radiogroup', { name: i18n.t('monitorMetrics.metricView') })).toHaveClass('ant-segmented');
+ expect(screen.getByRole('radiogroup', { name: i18n.t('monitorMetrics.historyMode') })).toHaveClass('ant-segmented');
});
it('loads the next realtime group batch when the fallback control enters the viewport', () => {
let notifyIntersection: IntersectionObserverCallback | undefined;
const observeMock = vi.fn();
- const disconnectMock = vi.fn();
class MockIntersectionObserver {
constructor(callback: IntersectionObserverCallback) {
notifyIntersection = callback;
}
-
observe = observeMock;
- disconnect = disconnectMock;
+ disconnect = vi.fn();
unobserve = vi.fn();
takeRecords = vi.fn();
root = null;
@@ -132,222 +219,134 @@ describe('MonitorMetricWorkbench', () => {
thresholds: number[] = [];
}
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);
- const value = controller({
- realtimeGroups: [realtimeGroup('summary')],
- hasMoreRealtimeGroups: true
- });
+ const value = controller({ hasMoreRealtimeGroups: true });
renderWorkbench(value);
- expect(observeMock).toHaveBeenCalledWith(screen.getByRole('button', { name: i18n.t('monitorMetrics.loadMore') }));
+ const loadMore = screen.getByRole('button', { name: i18n.t('monitorMetrics.loadMore') });
+ expect(observeMock).toHaveBeenCalledWith(loadMore);
act(() =>
notifyIntersection?.([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver)
);
-
- expect(disconnectMock).toHaveBeenCalled();
expect(value.actions.loadMoreRealtimeGroups).toHaveBeenCalledOnce();
});
- it.each([
- ['unavailable', 'common.unavailable'],
- ['error', 'common.routeError.description'],
- ['empty', 'monitorMetrics.empty']
- ] as const)('renders distinct realtime %s evidence', (kind, key) => {
- renderWorkbench(controller({ realtime: { kind, rows: [] } }));
- expect(screen.getByText(i18n.t(key))).toBeInTheDocument();
- });
-
- it.each(catalogCases)('renders distinct catalog evidence %#', (catalog, key) => {
- renderWorkbench(controller({ catalog }));
- expect(screen.getByText(i18n.t(key)).closest('[data-state]')).toBeInTheDocument();
- });
-
- it('uses the shared command hierarchy for metric selection and actions', () => {
- renderWorkbench(controller());
-
- expect(document.querySelector('[data-hb-operational-command-bar]')).toBeInTheDocument();
- expect(screen.getByRole('heading', { name: i18n.t('monitorMetrics.title') })).toBeInTheDocument();
- });
+ it('does not promote a legacy field token to a whole-group favorite', () => {
+ const value = controller({
+ favoriteCollection: { kind: 'ready', items: [{ key: 'summary.value', available: false }] },
+ realtimeGroups: [realtimeGroup('summary')]
+ });
+ renderWorkbench(value);
- it.each([
- ['unavailable', 'common.unavailable'],
- ['error', 'common.routeError.description']
- ] as const)('renders favorite %s as unknown evidence', (kind, key) => {
- renderWorkbench(
- controller({
- favorite: { kind },
- realtimeGroups: [{ ...realtimeGroup('summary'), favorite: { kind } }]
- })
- );
- expect(screen.getAllByText(i18n.t(key)).length).toBeGreaterThan(0);
- expect(screen.getByRole('button', { name: i18n.t('monitorMetrics.favorite') })).toBeDisabled();
+ expect(screen.getByRole('radio', { name: /Favorites 0/ })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('radio', { name: /Favorites 0/ }));
+ expect(screen.queryByRole('heading', { name: 'summary' })).not.toBeInTheDocument();
+ expect(screen.getByText(i18n.t('monitorMetrics.favoriteEmpty'))).toBeInTheDocument();
});
- it('keeps favorite unavailable to interaction while canonical verification is pending', () => {
- renderWorkbench(
- controller({
- favoriteBusy: true,
- realtimeGroups: [{ ...realtimeGroup('summary'), favoriteBusy: true }]
- })
- );
+ it('lets panel height own dense scrolling without a second expand surface', () => {
+ const rows = Array.from({ length: 8 }, (_, index) => metricRow(`metric_${index + 1}`, String(index + 1)));
+ const value = controller({
+ catalog: {
+ kind: 'ready',
+ options: rows.map(row => ({ key: `summary.${row.field}`, group: 'summary', field: row.field }))
+ },
+ metricKey: 'summary.metric_8',
+ favoriteCollection: { kind: 'ready', items: [{ key: 'summary.metric_8', available: false }] },
+ realtimeGroups: [
+ {
+ ...realtimeGroup('summary'),
+ result: { kind: 'ready', rows }
+ }
+ ]
+ });
+ renderWorkbench(value);
- expect(screen.getByRole('button', { name: i18n.t('monitorMetrics.favorite') })).toBeDisabled();
+ const card = screen.getByRole('article');
+ expect(within(card).getAllByRole('row')).toHaveLength(8);
+ expect(within(card).getByRole('button', { name: 'summary.metric_7' })).toBeInTheDocument();
+ expect(within(card).getByRole('button', { name: 'summary.metric_8' })).toBeInTheDocument();
+ expect(within(card).queryByRole('button', { name: /Expand metric group/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it.each([
['unavailable', 'common.unavailable'],
['error', 'common.routeError.description'],
['empty', 'monitorMetrics.empty']
- ] as const)('renders distinct history %s evidence', (kind, key) => {
- renderWorkbench(
- controller({
- historyCharts: [historyChart('summary.value', { kind, rows: [] })]
- })
- );
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.history') }));
- expect(screen.getAllByText(i18n.t(key)).length).toBeGreaterThan(0);
+ ] as const)('renders distinct realtime group %s evidence', (kind, key) => {
+ renderWorkbench(controller({ realtimeGroups: [{ ...realtimeGroup('summary'), result: { kind, rows: [] } }] }));
+ expect(screen.getByText(i18n.t(key))).toBeInTheDocument();
});
- it('distinguishes storage availability before showing history charts', () => {
- renderWorkbench(controller({ historyAvailability: { kind: 'unavailable' } }));
-
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.history') }));
-
- expect(screen.getByText(i18n.t('common.unavailable')).closest('[data-state]')).toBeInTheDocument();
- expect(document.querySelector('[data-history-metric]')).not.toBeInTheDocument();
+ it.each(catalogCases)('renders distinct catalog evidence %#', (catalog, key) => {
+ renderWorkbench(controller({ catalog, realtimeGroups: [] }));
+ expect(screen.getByText(i18n.t(key)).closest('[data-state]')).toBeInTheDocument();
});
- it('applies the same storage gate to a selected favorite history chart', () => {
+ it('fails the selected history tray closed when storage is unavailable', () => {
renderWorkbench(
controller({
- favoriteCollection: { kind: 'ready', items: [{ key: 'summary.value', available: true }] },
selectedHistoryChart: historyChart('summary.value', { kind: 'loading', rows: [] }),
historyAvailability: { kind: 'unavailable' }
})
);
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.favorites') }));
- fireEvent.click(screen.getAllByRole('tab', { name: i18n.t('monitorMetrics.history') }).at(-1)!);
-
expect(screen.getByText(i18n.t('common.unavailable')).closest('[data-state]')).toBeInTheDocument();
- expect(document.querySelector('[data-history-metric]')).not.toBeInTheDocument();
+ expect(screen.queryByRole('img', { name: 'summary.value' })).not.toBeInTheDocument();
});
- it('activates, ranges, refreshes, and extends history charts without route-local requests', () => {
- const observations: Array<{ callback: IntersectionObserverCallback; element?: Element }> = [];
- class MockIntersectionObserver {
- record: { callback: IntersectionObserverCallback; element?: Element };
- constructor(callback: IntersectionObserverCallback) {
- this.record = { callback };
- observations.push(this.record);
- }
- observe = (element: Element) => {
- this.record.element = element;
- };
- disconnect = vi.fn();
- unobserve = vi.fn();
- takeRecords = vi.fn();
- root = null;
- rootMargin = '';
- thresholds: number[] = [];
- }
- vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);
- const value = controller({
- historyCharts: [historyChart('summary.value', { kind: 'loading', rows: [] })],
- hasMoreHistoryCharts: true
- });
+ it('controls exact history ranges, raw/aggregate mode, and refresh from an in-flow panel', () => {
+ const value = controller({ selectedHistoryChart: historyChart('summary.value', { kind: 'loading', rows: [] }) });
renderWorkbench(value);
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.history') }));
-
- const cardObservation = observations.find(
- item => item.element?.getAttribute('data-history-metric') === 'summary.value'
- );
- act(() =>
- cardObservation?.callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver)
- );
- expect(value.actions.activateHistoryChart).toHaveBeenCalledWith('summary.value');
const range = screen.getByRole('combobox', { name: i18n.t('monitorMetrics.historyRange') });
fireEvent.mouseDown(range);
- fireEvent.click(screen.getAllByText('12W').at(-1)!);
- expect(value.actions.setHistoryChartRange).toHaveBeenCalledWith('summary.value', '12W');
+ fireEvent.click(screen.getByText('4W'));
+ expect(value.actions.setHistoryChartRange).toHaveBeenCalledWith('summary.value', '4W');
- const card = document.querySelector('[data-history-metric="summary.value"]')!;
- fireEvent.click(within(card as HTMLElement).getByRole('button', { name: i18n.t('common.refresh') }));
+ fireEvent.click(screen.getByRole('radio', { name: i18n.t('monitorMetrics.aggregatedValues') }));
+ expect(value.actions.setHistoryChartMode).toHaveBeenCalledWith('summary.value', true);
+ expect(value.actions.setHistoryChartRange).not.toHaveBeenCalledWith('summary.value', '1W');
+ fireEvent.click(
+ within(document.querySelector('[data-monitor-history-tray]') as HTMLElement).getByRole('button', {
+ name: i18n.t('monitorMetrics.refreshHistory')
+ })
+ );
expect(value.actions.refreshHistoryChart).toHaveBeenCalledWith('summary.value');
- fireEvent.click(screen.getByRole('button', { name: i18n.t('monitorMetrics.loadMoreHistory') }));
- expect(value.actions.loadMoreHistoryCharts).toHaveBeenCalledOnce();
+ expect(screen.queryByRole('button', { name: i18n.t('monitorMetrics.collapseHistory') })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: i18n.t('monitorMetrics.expandHistory') })).not.toBeInTheDocument();
});
- it('marks realtime-only history unsupported while retaining favorite interaction', () => {
- const value = controller({
- historySupported: false,
- historical: { kind: 'unsupported', rows: [] },
- realtimeGroups: [realtimeGroup('summary')]
- });
- renderWorkbench(value);
+ it('integrates layout editing into the dashboard command bar and places history before realtime panels', () => {
+ renderWorkbench(controller({ selectedHistoryChart: historyChart('summary.value', { kind: 'loading', rows: [] }) }));
- fireEvent.click(screen.getByRole('button', { name: i18n.t('monitorMetrics.favorite') }));
- expect(value.actions.toggleRealtimeFavorite).toHaveBeenCalledWith('summary');
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.history') }));
- expect(screen.getByText(i18n.t('monitorMetrics.historyUnsupported'))).toBeInTheDocument();
+ const commandBar = document.querySelector('[data-hb-operational-command-bar]') as HTMLElement;
+ const history = document.querySelector('[data-monitor-history-tray]') as HTMLElement;
+ const realtime = screen.getByRole('article');
+
+ expect(within(commandBar).getByRole('button', { name: i18n.t('monitorMetrics.layout.edit') })).toBeVisible();
+ expect(history.compareDocumentPosition(realtime) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'summary' })).not.toBeInTheDocument();
});
- it('shows the auto-refresh choices and forwards an Off selection', () => {
+ it('pauses and resumes shared live refresh without hiding current values', () => {
const value = controller();
- renderWorkbench(value);
-
- const refreshSelect = screen.getByRole('combobox', { name: i18n.t('monitorMetrics.autoRefresh.label') });
- expect(refreshSelect.closest('.ant-select')).toHaveTextContent(
- i18n.t('monitorMetrics.autoRefresh.seconds', { count: 90 })
- );
- fireEvent.mouseDown(refreshSelect);
- fireEvent.click(screen.getByText(i18n.t('monitorMetrics.autoRefresh.off')));
+ const rendered = renderWorkbench(value);
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('monitorMetrics.pause') }));
expect(value.actions.setRefreshSeconds).toHaveBeenCalledWith(0);
+ rendered.rerender(workbenchNode(controller({ refreshSeconds: 0 })));
+ fireEvent.click(screen.getByRole('button', { name: i18n.t('monitorMetrics.returnLive') }));
+ expect(screen.getByRole('heading', { name: 'summary' })).toBeInTheDocument();
});
- it('offers the exact uppercase long history range tokens', () => {
- const value = controller({ historyCharts: [historyChart('summary.value', { kind: 'loading', rows: [] })] });
- renderWorkbench(value);
-
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.history') }));
- const historySelect = screen.getByRole('combobox', { name: i18n.t('monitorMetrics.historyRange') });
- fireEvent.mouseDown(historySelect);
- fireEvent.click(screen.getByText('4W'));
-
- expect(value.actions.setHistoryChartRange).toHaveBeenCalledWith('summary.value', '4W');
- expect(screen.getByText('1W')).toBeInTheDocument();
- expect(screen.getByText('12W')).toBeInTheDocument();
- });
-
- it('makes the favorite collection discoverable and selects only available favorite metrics', () => {
- const value = controller({
- favoriteCollection: {
- kind: 'ready',
- items: [
- { key: 'retired.value', available: false },
- { key: 'summary.value', available: true }
- ]
- }
- });
- renderWorkbench(value);
-
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.favorites') }));
- expect(screen.getByRole('button', { name: 'retired.value' })).toBeDisabled();
- expect(screen.getByText(i18n.t('monitorMetrics.favoriteUnavailable'))).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'summary.value' })).toHaveAttribute('aria-pressed', 'true');
- expect(screen.getByRole('button', { name: 'summary.value' })).not.toHaveClass('ant-btn-primary');
- fireEvent.click(screen.getByRole('button', { name: 'summary.value' }));
-
- expect(value.actions.setMetric).toHaveBeenCalledWith('summary.value');
- expect(screen.getAllByRole('tab', { name: i18n.t('monitorMetrics.realtime') })).toHaveLength(2);
- expect(screen.getAllByRole('tab', { name: i18n.t('monitorMetrics.history') })).toHaveLength(2);
- });
-
- it.each(favoriteCollectionCases)('renders distinct favorite collection %# evidence', (favoriteCollection, key) => {
+ it.each([
+ [{ kind: 'unavailable' as const }, 'common.unavailable'],
+ [{ kind: 'error' as const }, 'common.routeError.description'],
+ [{ kind: 'empty' as const, items: [] }, 'monitorMetrics.favoriteEmpty']
+ ])('renders distinct favorites evidence %#', (favoriteCollection, key) => {
renderWorkbench(controller({ favoriteCollection }));
-
- fireEvent.click(screen.getByRole('tab', { name: i18n.t('monitorMetrics.favorites') }));
+ fireEvent.click(screen.getByRole('radio', { name: /Favorites/ }));
expect(screen.getAllByText(i18n.t(key)).length).toBeGreaterThan(0);
});
});
@@ -365,13 +364,28 @@ function controller(
favorite: { kind: 'ready', value: false },
favoriteCollection: { kind: 'empty', items: [] },
favoriteBusy: false,
- realtimeGroups: [],
+ realtimeGroupNames: ['summary'],
+ realtimeGroups: [realtimeGroup('summary')],
hasMoreRealtimeGroups: false,
historyAvailability: { kind: 'available' },
historyCharts: [],
hasMoreHistoryCharts: false,
- realtime: { kind: 'empty', rows: [] },
+ realtime: { kind: 'ready', rows: [metricRow('value', '12')] },
historical: { kind: 'empty', rows: [] },
+ layout: {
+ readState: 'ready',
+ editing: false,
+ saving: false,
+ revision: '',
+ hasSavedLayout: false,
+ layout: {
+ schemaVersion: 1,
+ mode: 'auto',
+ columns: 12,
+ items: [{ group: 'summary', x: 0, y: 0, w: 4, h: 10, collapsed: false, order: 0 }],
+ historyDock: { collapsed: false, height: 12 }
+ }
+ },
...statePatch
},
actions: {
@@ -380,18 +394,28 @@ function controller(
setRefreshSeconds: vi.fn(),
toggleFavorite: vi.fn(),
toggleRealtimeFavorite: vi.fn(),
+ revealRealtimeGroup: vi.fn(),
loadMoreRealtimeGroups: vi.fn(),
activateHistoryChart: vi.fn(),
setHistoryChartRange: vi.fn(),
+ setHistoryChartMode: vi.fn(),
refreshHistoryChart: vi.fn(),
loadMoreHistoryCharts: vi.fn(),
- refresh: vi.fn()
+ refresh: vi.fn(),
+ layout: {
+ beginEdit: vi.fn(),
+ cancelEdit: vi.fn(),
+ changeItems: vi.fn(),
+ changeHistoryDock: vi.fn(),
+ save: vi.fn(),
+ reset: vi.fn()
+ }
}
};
}
function metricRow(field: string, value: string) {
- return { key: `0:${field}`, labels: {}, field, unit: null, value, time: null };
+ return { key: `0:${field}`, labels: {}, field, unit: null, value, time: null, collectedAt: null };
}
function realtimeGroup(group: string): MonitorMetricWorkbenchController['state']['realtimeGroups'][number] {
@@ -408,17 +432,17 @@ function historyChart(
result: MonitorMetricWorkbenchController['state']['historyCharts'][number]['result']
): MonitorMetricWorkbenchController['state']['historyCharts'][number] {
const [group, field] = key.split('.');
- return {
- metric: { key, group: group!, field: field! },
- history: '30m',
- result
- };
+ return { metric: { key, group: group!, field: field! }, history: '30m', interval: false, result };
}
-function renderWorkbench(value: MonitorMetricWorkbenchController) {
- return render(
+function workbenchNode(value: MonitorMetricWorkbenchController) {
+ return (
<I18nextProvider i18n={i18n}>
<MonitorMetricWorkbench {...value} />
</I18nextProvider>
);
}
+
+function renderWorkbench(value: MonitorMetricWorkbenchController) {
+ return render(workbenchNode(value));
+}
diff --git a/web-app/src/features/monitor/components/monitor-metric-workbench.tsx b/web-app/src/features/monitor/components/monitor-metric-workbench.tsx
index 9564aeabcf..e6d058ebb5 100644
--- a/web-app/src/features/monitor/components/monitor-metric-workbench.tsx
+++ b/web-app/src/features/monitor/components/monitor-metric-workbench.tsx
@@ -15,19 +15,14 @@
* limitations under the License.
*/
-import { Alert, Button } from 'antd';
+import { Alert } from 'antd';
+import type { CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
-import {
- OperationalCommandBar,
- OperationalSection,
- OperationalStatePanel,
- type OperationalStateKind
-} from '@/shared/operational-page';
+import { OperationalSection, OperationalStatePanel, type OperationalStateKind } from '@/shared/operational-page';
import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
import { MonitorMetricResults } from './monitor-metric-results';
-import { MonitorRefreshSelect } from './monitor-refresh-select';
import styles from './monitor-metric-workbench.module.css';
export function MonitorMetricWorkbench({ state, actions }: MonitorMetricWorkbenchController) {
@@ -78,31 +73,16 @@ function monitorMetricCatalogPresentation(
function MonitorMetricReadyWorkbench({ state, actions }: MonitorMetricWorkbenchController) {
const { t } = useTranslation();
+ const historyHeight = state.layout.layout.historyDock.height * 22;
return (
- <OperationalSection title={t('monitorMetrics.title')} description={t('monitorMetrics.description')}>
- <div className={styles.workbench}>
- <MonitorMetricToolbar state={state} actions={actions} />
- {state.favorite.kind === 'unavailable' && <Alert type="warning" showIcon message={t('common.unavailable')} />}
- {state.favorite.kind === 'error' && (
- <Alert type="error" showIcon message={t('common.routeError.description')} />
- )}
- <MonitorMetricResults state={state} actions={actions} />
- </div>
- </OperationalSection>
- );
-}
-
-function MonitorMetricToolbar({ state, actions }: MonitorMetricWorkbenchController) {
- const { t } = useTranslation();
- return (
- <OperationalCommandBar
- ariaLabel={t('monitorMetrics.title')}
- primary={
- <div className={styles.toolbarControls}>
- <MonitorRefreshSelect value={state.refreshSeconds} onChange={actions.setRefreshSeconds} />
- </div>
- }
- secondary={<Button onClick={actions.refresh}>{t('common.refresh')}</Button>}
- />
+ <section
+ className={styles.workbench}
+ aria-label={t('monitorMetrics.title')}
+ style={{ '--monitor-history-height': `${historyHeight}px` } as CSSProperties}
+ >
+ {state.favorite.kind === 'unavailable' && <Alert type="warning" showIcon message={t('common.unavailable')} />}
+ {state.favorite.kind === 'error' && <Alert type="error" showIcon message={t('common.routeError.description')} />}
+ <MonitorMetricResults state={state} actions={actions} />
+ </section>
);
}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-card.module.css b/web-app/src/features/monitor/components/monitor-realtime-card.module.css
new file mode 100644
index 0000000000..9c9b75972b
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-card.module.css
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+.realtimeGroup {
+ display: flex;
+ height: 100%;
+ min-width: 0;
+ min-height: 0;
+ flex-direction: column;
+ overflow: hidden;
+ border: 1px solid var(--hb-border-subtle);
+ border-radius: var(--hb-radius-control);
+ background: var(--hb-bg-raised);
+ scroll-margin-top: var(--hb-space-3);
+}
+
+.realtimeGroupHeader {
+ display: flex;
+ flex: none;
+ min-height: 36px;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--hb-space-2);
+ padding: 4px 8px 4px 10px;
+ border-bottom: 1px solid var(--hb-border-subtle);
+}
+
+.realtimeGroupIdentity {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ gap: 7px;
+}
+
+.realtimeGroupIdentity h5 {
+ margin: 0;
+ overflow: hidden;
+ color: var(--hb-text-primary);
+ font-size: 13px;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.realtimeGroupIdentity span {
+ flex: none;
+ padding: 1px 5px;
+ border-radius: 999px;
+ color: var(--hb-brand-accent);
+ background: var(--hb-bg-selected);
+ font-size: 10px;
+}
+
+.realtimeGroupIdentity time,
+.realtimeGroupActions > span {
+ flex: none;
+ color: var(--hb-text-muted);
+ font-size: 10px;
+ white-space: nowrap;
+}
+
+.realtimeGroupActions {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ gap: 1px;
+}
+
+.realtimeGroupActions :global(.ant-btn) {
+ width: 26px;
+ min-width: 26px;
+ height: 26px;
+ padding: 0;
+}
+
+.realtimeGroup :global(.ant-table-thead > tr > th:not(:last-child)),
+.realtimeGroup :global(.ant-table-tbody > tr > td:not(:last-child)) {
+ border-inline-end: 1px solid var(--hb-border-subtle);
+}
+
+.realtimeGroup :global(.ant-table-thead > tr > th::before) {
+ display: none;
+}
+
+.realtimeGroupBody {
+ min-height: 0;
+ flex: 1;
+ overflow: auto;
+ scrollbar-gutter: stable;
+}
+
+.loadMore {
+ grid-column: 1 / -1;
+ justify-self: center;
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-evidence.tsx b/web-app/src/features/monitor/components/monitor-realtime-evidence.tsx
new file mode 100644
index 0000000000..04dc1af1e3
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-evidence.tsx
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { useTranslation } from 'react-i18next';
+
+import { OperationalStatePanel } from '@/shared/operational-page';
+
+import type { MonitorMetricWorkbenchController, monitorRealtimeRows } from '../model/monitor-detail-model';
+import { MonitorRealtimeTable } from './monitor-realtime-table';
+
+export function RealtimeEvidence({
+ evidence,
+ ...tableProps
+}: {
+ evidence: MonitorMetricWorkbenchController['state']['realtime'];
+ group?: string | undefined;
+ metricOptions?: MonitorMetricWorkbenchController['state']['catalog']['options'] | undefined;
+ selectedMetricKey?: string | undefined;
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
+ const { t } = useTranslation();
+ if (evidence.kind === 'unavailable') {
+ return <OperationalStatePanel kind="unavailable" title={t('common.unavailable')} />;
+ }
+ if (evidence.kind === 'error') {
+ return <OperationalStatePanel kind="error" title={t('common.routeError.description')} />;
+ }
+ if (evidence.kind === 'empty') {
+ return <OperationalStatePanel kind="empty" title={t('monitorMetrics.empty')} />;
+ }
+ return <RealtimeTable rows={evidence.rows} pending={evidence.kind === 'loading'} {...tableProps} />;
+}
+
+function RealtimeTable({
+ rows,
+ pending,
+ ...props
+}: { rows: ReturnType<typeof monitorRealtimeRows>; pending: boolean } & Omit<
+ Parameters<typeof MonitorRealtimeTable>[0],
+ 'rows' | 'pending'
+>) {
+ return <MonitorRealtimeTable rows={rows} pending={pending} {...props} />;
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-group-card.tsx b/web-app/src/features/monitor/components/monitor-realtime-group-card.tsx
new file mode 100644
index 0000000000..9ca2bfac86
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-group-card.tsx
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { useTranslation } from 'react-i18next';
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import styles from './monitor-realtime-card.module.css';
+import { RealtimeEvidence } from './monitor-realtime-evidence';
+import { RealtimeFavoriteButton } from './monitor-realtime-group-support';
+import { formatGroupTime } from './monitor-realtime-group-time';
+
+export function RealtimeGroupCard({
+ group,
+ state,
+ onSelectMetric,
+ onToggleGroup,
+ collapsed = false
+}: {
+ group: MonitorMetricWorkbenchController['state']['realtimeGroups'][number];
+ state: MonitorMetricWorkbenchController['state'];
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+ onToggleGroup: MonitorMetricWorkbenchController['actions']['toggleRealtimeFavorite'];
+ collapsed?: boolean | undefined;
+}) {
+ return (
+ <article className={styles.realtimeGroup} data-monitor-group={group.group}>
+ <RealtimeGroupHeader group={group} onToggle={onToggleGroup} />
+ {collapsed ? null : <RealtimeGroupBody group={group} state={state} onSelectMetric={onSelectMetric} />}
+ </article>
+ );
+}
+
+function RealtimeGroupHeader({
+ group,
+ onToggle
+}: {
+ group: MonitorMetricWorkbenchController['state']['realtimeGroups'][number];
+ onToggle: MonitorMetricWorkbenchController['actions']['toggleRealtimeFavorite'];
+}) {
+ const { t } = useTranslation();
+ return (
+ <header className={styles.realtimeGroupHeader} data-layout-panel-header="">
+ <div className={styles.realtimeGroupIdentity}>
+ <h5>{group.group}</h5>
+ <time>{formatGroupTime(group.result)}</time>
+ </div>
+ <div className={styles.realtimeGroupActions}>
+ <span>{t('monitorMetrics.itemCount', { count: group.result.rows.length })}</span>
+ <RealtimeFavoriteButton group={group} onToggle={onToggle} />
+ </div>
+ </header>
+ );
+}
+
+function RealtimeGroupBody({
+ group,
+ state,
+ onSelectMetric
+}: {
+ group: MonitorMetricWorkbenchController['state']['realtimeGroups'][number];
+ state: MonitorMetricWorkbenchController['state'];
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
+ return (
+ <div className={styles.realtimeGroupBody}>
+ <RealtimeEvidence
+ evidence={group.result}
+ group={group.group}
+ metricOptions={state.catalog.options}
+ selectedMetricKey={state.metricKey}
+ onSelectMetric={onSelectMetric}
+ />
+ </div>
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-group-support.tsx b/web-app/src/features/monitor/components/monitor-realtime-group-support.tsx
new file mode 100644
index 0000000000..90f31e1c1e
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-group-support.tsx
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { StarFilled, StarOutlined } from '@ant-design/icons';
+import { Button } from 'antd';
+import { useTranslation } from 'react-i18next';
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+
+export function RealtimeFavoriteButton({
+ group,
+ onToggle
+}: {
+ group: MonitorMetricWorkbenchController['state']['realtimeGroups'][number];
+ onToggle: MonitorMetricWorkbenchController['actions']['toggleRealtimeFavorite'];
+}) {
+ const { t } = useTranslation();
+ const favorited = group.favorite.kind === 'ready' && group.favorite.value;
+ return (
+ <Button
+ type="text"
+ size="small"
+ icon={favorited ? <StarFilled /> : <StarOutlined />}
+ aria-label={t(favorited ? 'monitorMetrics.unfavorite' : 'monitorMetrics.favorite')}
+ disabled={group.favorite.kind !== 'ready' || group.favoriteBusy}
+ loading={group.favoriteBusy}
+ onClick={() => void onToggle(group.group)}
+ data-realtime-favorite-group={group.group}
+ />
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-group-time.ts b/web-app/src/features/monitor/components/monitor-realtime-group-time.ts
new file mode 100644
index 0000000000..e39ed66a38
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-group-time.ts
@@ -0,0 +1,17 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+
+export function formatGroupTime(evidence: MonitorMetricWorkbenchController['state']['realtime']) {
+ if (evidence.kind !== 'ready' && evidence.kind !== 'loading') return '—';
+ const values = evidence.rows.flatMap(row =>
+ (row.collectedAt ?? row.time) == null ? [] : [row.collectedAt ?? row.time!]
+ );
+ const latest = values.length > 0 ? Math.max(...values) : undefined;
+ return latest == null ? '—' : new Intl.DateTimeFormat(undefined, { timeStyle: 'medium' }).format(latest);
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-layout-grid.test.tsx b/web-app/src/features/monitor/components/monitor-realtime-layout-grid.test.tsx
new file mode 100644
index 0000000000..f2e0431b88
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-layout-grid.test.tsx
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import type { MonitorMetricLayoutActions, MonitorMetricLayoutState } from '../model/monitor-metric-layout-model';
+import { MonitorRealtimeLayoutGrid } from './monitor-realtime-layout-grid';
+
+const gridHarness = vi.hoisted(() => ({ width: 876 }));
+
+vi.mock('react-grid-layout', () => ({
+ default: ({
+ children,
+ dragConfig,
+ gridConfig,
+ layout,
+ resizeConfig
+ }: {
+ children: ReactNode;
+ dragConfig: { enabled: boolean; handle?: string; cancel?: string };
+ gridConfig: { cols: number };
+ layout: Array<{ i: string; x: number; w: number }>;
+ resizeConfig: { enabled: boolean };
+ }) => (
+ <div
+ data-testid="grid-layout"
+ data-cols={gridConfig.cols}
+ data-drag-enabled={dragConfig.enabled}
+ data-drag-handle={dragConfig.handle}
+ data-drag-cancel={dragConfig.cancel}
+ data-resize-enabled={resizeConfig.enabled}
+ data-layout={JSON.stringify(layout)}
+ >
+ {children}
+ </div>
+ ),
+ useContainerWidth: () => ({ width: gridHarness.width, containerRef: { current: null }, mounted: true }),
+ verticalCompactor: {}
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+afterEach(cleanup);
+
+describe('MonitorRealtimeLayoutGrid', () => {
+ it('opens a canonical desktop editing canvas at an ordinary tablet-width work surface', () => {
+ renderGrid(layoutState({ editing: true }));
+
+ const grid = screen.getByTestId('grid-layout');
+ expect(grid).toHaveAttribute('data-cols', '12');
+ expect(grid).toHaveAttribute('data-drag-enabled', 'true');
+ expect(grid).toHaveAttribute('data-resize-enabled', 'true');
+ expect(grid).toHaveAttribute('data-drag-handle', '[data-layout-panel-header]');
+ expect(grid).toHaveAttribute('data-drag-cancel', 'button, a');
+ expect(screen.queryByRole('toolbar', { name: 'monitorMetrics.layout.card basic' })).not.toBeInTheDocument();
+ expect(JSON.parse(grid.getAttribute('data-layout') ?? '[]')).toEqual([
+ expect.objectContaining({ i: 'basic', x: 0, w: 4 }),
+ expect.objectContaining({ i: 'cache', x: 4, w: 4 })
+ ]);
+ });
+
+ it('keeps a saved custom layout on the same desktop grid after editing ends', () => {
+ renderGrid(layoutState());
+
+ const grid = screen.getByTestId('grid-layout');
+ expect(grid).toHaveAttribute('data-cols', '12');
+ expect(grid).toHaveAttribute('data-drag-enabled', 'false');
+ expect(JSON.parse(grid.getAttribute('data-layout') ?? '[]')).toEqual([
+ expect.objectContaining({ i: 'basic', x: 0, w: 4 }),
+ expect.objectContaining({ i: 'cache', x: 4, w: 4 })
+ ]);
+ });
+
+ it('keeps automatic layouts responsive at an ordinary tablet-width work surface', () => {
+ renderGrid(layoutState({ layout: { ...layoutState().layout, mode: 'auto' } }));
+
+ const grid = screen.getByTestId('grid-layout');
+ expect(grid).toHaveAttribute('data-cols', '6');
+ expect(grid).toHaveAttribute('data-drag-enabled', 'false');
+ expect(JSON.parse(grid.getAttribute('data-layout') ?? '[]')).toEqual([
+ expect.objectContaining({ i: 'basic', x: 0, w: 3 }),
+ expect.objectContaining({ i: 'cache', x: 3, w: 3 })
+ ]);
+ });
+});
+
+function renderGrid(state: MonitorMetricLayoutState) {
+ const groups = [
+ { group: 'basic' },
+ { group: 'cache' }
+ ] as MonitorMetricWorkbenchController['state']['realtimeGroups'];
+ render(
+ <MonitorRealtimeLayoutGrid
+ state={state}
+ actions={layoutActions()}
+ groups={groups}
+ renderGroup={group => <article>{group.group}</article>}
+ />
+ );
+}
+
+function layoutState(overrides: Partial<MonitorMetricLayoutState> = {}): MonitorMetricLayoutState {
+ return {
+ readState: 'ready',
+ editing: false,
+ saving: false,
+ revision: 'layout-r1',
+ hasSavedLayout: true,
+ layout: {
+ schemaVersion: 1,
+ mode: 'custom',
+ columns: 12,
+ items: [
+ { group: 'basic', x: 0, y: 0, w: 4, h: 10, collapsed: false, order: 0 },
+ { group: 'cache', x: 4, y: 0, w: 4, h: 10, collapsed: false, order: 1 }
+ ],
+ historyDock: { collapsed: false, height: 12 }
+ },
+ ...overrides
+ };
+}
+
+function layoutActions(): MonitorMetricLayoutActions {
+ return {
+ beginEdit: vi.fn(),
+ cancelEdit: vi.fn(),
+ changeItems: vi.fn(),
+ changeHistoryDock: vi.fn(),
+ save: vi.fn().mockResolvedValue(undefined),
+ reset: vi.fn().mockResolvedValue(undefined)
+ };
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-layout-grid.tsx b/web-app/src/features/monitor/components/monitor-realtime-layout-grid.tsx
new file mode 100644
index 0000000000..ebee6079ff
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-layout-grid.tsx
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import ReactGridLayout, { useContainerWidth, verticalCompactor, type Layout } from 'react-grid-layout';
+import type { ReactNode, RefObject } from 'react';
+
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import {
+ mergeMonitorMetricLayout,
+ mergeMonitorMetricGridChange,
+ monitorMetricLayoutViewport,
+ projectMonitorMetricLayout,
+ type MonitorMetricLayoutActions,
+ type MonitorMetricLayoutItem,
+ type MonitorMetricLayoutState
+} from '../model/monitor-metric-layout-model';
+import workbenchStyles from './monitor-metric-workbench.module.css';
+import styles from './monitor-metric-layout.module.css';
+
+type RealtimeGroup = MonitorMetricWorkbenchController['state']['realtimeGroups'][number];
+type RealtimeLayoutProps = {
+ state: MonitorMetricLayoutState;
+ actions: MonitorMetricLayoutActions;
+ groups: RealtimeGroup[];
+ renderGroup: (group: RealtimeGroup, item: MonitorMetricLayoutItem) => ReactNode;
+};
+
+export function MonitorRealtimeLayoutGrid({ state, actions, groups, renderGroup }: RealtimeLayoutProps) {
+ const { width, containerRef, mounted } = useContainerWidth({ initialWidth: 960 });
+ const model = realtimeLayoutModel(state, groups, width);
+ if (!mounted) {
+ return (
+ <div ref={containerRef} className={workbenchStyles.realtimeGrid}>
+ {groups.map(group => (
+ <div key={group.group}>{renderGroup(group, model.byGroup.get(group.group)!)}</div>
+ ))}
+ </div>
+ );
+ }
+ return (
+ <RealtimeGrid
+ containerRef={containerRef}
+ width={width}
+ model={model}
+ state={state}
+ actions={actions}
+ groups={groups}
+ renderGroup={renderGroup}
+ />
+ );
+}
+
+function realtimeLayoutModel(state: MonitorMetricLayoutState, groups: RealtimeGroup[], width: number) {
+ const viewport = monitorMetricLayoutViewport(width);
+ const groupNames = new Set(groups.map(group => group.group));
+ const canonical = mergeMonitorMetricLayout(
+ { ...state.layout, application: '', revision: state.revision },
+ groups.map(group => group.group)
+ ).items.filter(item => groupNames.has(item.group));
+ const layoutViewport = state.layout.mode === 'custom' && viewport === 'tablet' ? 'desktop' : viewport;
+ const projected = projectMonitorMetricLayout(canonical, layoutViewport);
+ const editable = state.editing && layoutViewport === 'desktop';
+ return {
+ viewport,
+ layoutViewport,
+ projected,
+ editable,
+ byGroup: new Map(projected.map(item => [item.group, item]))
+ };
+}
+
+function RealtimeGrid({
+ containerRef,
+ width,
+ model,
+ state,
+ actions,
+ groups,
+ renderGroup
+}: RealtimeLayoutProps & {
+ containerRef: RefObject<HTMLDivElement | null>;
+ width: number;
+ model: ReturnType<typeof realtimeLayoutModel>;
+}) {
+ return (
+ <div ref={containerRef} className={styles.realtimeLayoutHost} data-layout-viewport={model.viewport}>
+ <ReactGridLayout
+ width={width}
+ layout={toGridLayout(model.projected, model.editable)}
+ gridConfig={{
+ cols: columnsFor(model.layoutViewport),
+ rowHeight: 22,
+ margin: [12, 12],
+ containerPadding: [0, 0]
+ }}
+ dragConfig={{ enabled: model.editable, handle: '[data-layout-panel-header]', cancel: 'button, a' }}
+ resizeConfig={{ enabled: model.editable, handles: ['se'] }}
+ compactor={verticalCompactor}
+ onDragStop={layout => applyGridChange(layout, state, actions)}
+ onResizeStop={layout => applyGridChange(layout, state, actions)}
+ >
+ {groups.map(group => {
+ const item = model.byGroup.get(group.group);
+ if (!item) return null;
+ return (
+ <div
+ key={group.group}
+ className={state.editing ? styles.realtimeLayoutItemEditing : styles.realtimeLayoutItem}
+ data-layout-group={group.group}
+ >
+ {renderGroup(group, item)}
+ </div>
+ );
+ })}
+ </ReactGridLayout>
+ </div>
+ );
+}
+
+function toGridLayout(items: MonitorMetricLayoutItem[], editable: boolean): Layout {
+ return items.map(item => ({
+ i: item.group,
+ x: item.x,
+ y: item.y,
+ w: item.w,
+ h: item.h,
+ minW: 4,
+ minH: item.collapsed ? 4 : 8,
+ maxW: 12,
+ maxH: 24,
+ static: !editable
+ }));
+}
+
+function applyGridChange(layout: Layout, state: MonitorMetricLayoutState, actions: MonitorMetricLayoutActions) {
+ if (!state.editing) return;
+ actions.changeItems(
+ mergeMonitorMetricGridChange(
+ state.layout.items,
+ layout.map(item => ({ group: item.i, x: item.x, y: item.y, w: item.w, h: item.h }))
+ )
+ );
+}
+
+function columnsFor(viewport: ReturnType<typeof monitorMetricLayoutViewport>) {
+ if (viewport === 'desktop') return 12;
+ if (viewport === 'tablet') return 6;
+ return 1;
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-matrix-table.tsx b/web-app/src/features/monitor/components/monitor-realtime-matrix-table.tsx
new file mode 100644
index 0000000000..fe44ef3cdb
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-matrix-table.tsx
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { Table, Tag, type TableColumnsType } from 'antd';
+import type { ReactNode } from 'react';
+
+import type { monitorRealtimeRows } from '../model/monitor-detail-model';
+import styles from './monitor-realtime-table.module.css';
+
+type RealtimeRow = ReturnType<typeof monitorRealtimeRows>[number];
+type MatrixRow = { key: string } & Record<string, ReactNode>;
+
+export function MatrixRealtimeTable({ rows, pending }: { rows: RealtimeRow[]; pending: boolean }) {
+ const { columns, data } = realtimeMatrix(rows);
+ return (
+ <Table
+ rowKey="key"
+ size="small"
+ loading={pending}
+ dataSource={data}
+ columns={columns}
+ pagination={false}
+ scroll={{ x: 'max-content' }}
+ />
+ );
+}
+
+function realtimeMatrix(rows: RealtimeRow[]) {
+ const labelKeys = unique(rows.flatMap(row => Object.keys(row.labels)));
+ const fields = unique(rows.map(row => row.field));
+ const units = new Map(rows.map(row => [row.field, row.unit]));
+ const samples = new Map<string, MatrixRow>();
+ for (const row of rows) {
+ const key = sampleKey(row);
+ const sample = samples.get(key) ?? { key };
+ for (const label of labelKeys) sample[`label:${label}`] = row.labels[label] ?? '—';
+ sample[`field:${row.field}`] = row.value;
+ samples.set(key, sample);
+ }
+ const columns: TableColumnsType<MatrixRow> = [
+ ...labelKeys.map(label => ({ title: label, dataIndex: `label:${label}` })),
+ ...fields.map(field => ({ title: renderField(field, units.get(field)), dataIndex: `field:${field}` }))
+ ];
+ return { columns, data: [...samples.values()] };
+}
+
+function renderField(field: string, unit?: string | null) {
+ return (
+ <span className={styles.realtimeField}>
+ <span>{field}</span>
+ {unit ? <Tag bordered={false}>{unit}</Tag> : null}
+ </span>
+ );
+}
+
+function sampleKey(row: RealtimeRow) {
+ const separator = row.key.indexOf(':');
+ return separator < 0 ? row.key : row.key.slice(0, separator);
+}
+
+function unique(values: string[]) {
+ return [...new Set(values)];
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-results.tsx b/web-app/src/features/monitor/components/monitor-realtime-results.tsx
index 6191d27226..565f84d904 100644
--- a/web-app/src/features/monitor/components/monitor-realtime-results.tsx
+++ b/web-app/src/features/monitor/components/monitor-realtime-results.tsx
@@ -5,114 +5,66 @@
* The ASF licenses this file to You under the Apache License, Version 2.0.
*/
-import { StarFilled, StarOutlined } from '@ant-design/icons';
-import { Button, Table, Tag } from 'antd';
+import { Button } from 'antd';
import { useTranslation } from 'react-i18next';
-import { OperationalStatePanel } from '@/shared/operational-page';
-
-import type { MonitorMetricWorkbenchController, monitorRealtimeRows } from '../model/monitor-detail-model';
-import styles from './monitor-metric-workbench.module.css';
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import styles from './monitor-realtime-card.module.css';
+import { RealtimeEvidence } from './monitor-realtime-evidence';
+import { RealtimeGroupCard } from './monitor-realtime-group-card';
+import { MonitorRealtimeLayoutGrid } from './monitor-realtime-layout-grid';
import { useActivateWhenVisible } from './use-activate-when-visible';
-export function MonitorRealtimeResult({ state, actions }: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'>) {
- if (state.realtimeGroups.length > 0) return <RealtimeGroupGrid state={state} actions={actions} />;
- return <RealtimeEvidence evidence={state.realtime} />;
-}
-
-export function SelectedRealtimeResult({ state }: Pick<MonitorMetricWorkbenchController, 'state'>) {
+export function MonitorRealtimeResult({
+ state,
+ actions,
+ groups = state.realtimeGroups,
+ onSelectMetric
+}: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'> & {
+ groups?: MonitorMetricWorkbenchController['state']['realtimeGroups'] | undefined;
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
+ if (groups.length > 0) {
+ return <RealtimeGroupGrid state={state} actions={actions} groups={groups} onSelectMetric={onSelectMetric} />;
+ }
return <RealtimeEvidence evidence={state.realtime} />;
}
-function RealtimeGroupGrid({ state, actions }: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'>) {
+function RealtimeGroupGrid({
+ state,
+ actions,
+ groups,
+ onSelectMetric
+}: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'> & {
+ groups: MonitorMetricWorkbenchController['state']['realtimeGroups'];
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
const { t } = useTranslation();
const loadMoreRef = useActivateWhenVisible<HTMLButtonElement>(
state.hasMoreRealtimeGroups,
actions.loadMoreRealtimeGroups
);
return (
- <div className={styles.realtimeGrid}>
- {state.realtimeGroups.map(group => (
- <article key={group.group} className={styles.realtimeGroup}>
- <header className={styles.realtimeGroupHeader}>
- <h5>{group.group}</h5>
- <RealtimeFavoriteButton group={group} onToggle={actions.toggleRealtimeFavorite} />
- </header>
- <RealtimeEvidence evidence={group.result} />
- </article>
- ))}
+ <>
+ <MonitorRealtimeLayoutGrid
+ state={state.layout}
+ actions={actions.layout}
+ groups={groups}
+ renderGroup={(group, item) => (
+ <RealtimeGroupCard
+ group={group}
+ state={state}
+ onSelectMetric={onSelectMetric}
+ onToggleGroup={actions.toggleRealtimeFavorite}
+ collapsed={item.collapsed}
+ />
+ )}
+ />
{state.hasMoreRealtimeGroups ? (
<Button ref={loadMoreRef} className={styles.loadMore!} onClick={actions.loadMoreRealtimeGroups}>
{t('monitorMetrics.loadMore')}
</Button>
) : null}
- </div>
- );
-}
-
-function RealtimeFavoriteButton({
- group,
- onToggle
-}: {
- group: MonitorMetricWorkbenchController['state']['realtimeGroups'][number];
- onToggle: MonitorMetricWorkbenchController['actions']['toggleRealtimeFavorite'];
-}) {
- const { t } = useTranslation();
- const favorited = group.favorite.kind === 'ready' && group.favorite.value;
- return (
- <Button
- type="text"
- size="small"
- icon={favorited ? <StarFilled /> : <StarOutlined />}
- aria-label={t(favorited ? 'monitorMetrics.unfavorite' : 'monitorMetrics.favorite')}
- disabled={group.favorite.kind !== 'ready' || group.favoriteBusy}
- loading={group.favoriteBusy}
- onClick={() => void onToggle(group.group)}
- data-realtime-favorite-group={group.group}
- />
+ </>
);
}
-
-function RealtimeEvidence({ evidence }: { evidence: MonitorMetricWorkbenchController['state']['realtime'] }) {
- const { t } = useTranslation();
- if (evidence.kind === 'unavailable') {
- return <OperationalStatePanel kind="unavailable" title={t('common.unavailable')} />;
- }
- if (evidence.kind === 'error') {
- return <OperationalStatePanel kind="error" title={t('common.routeError.description')} />;
- }
- if (evidence.kind === 'empty') {
- return <OperationalStatePanel kind="empty" title={t('monitorMetrics.empty')} />;
- }
- return <RealtimeTable rows={evidence.rows} pending={evidence.kind === 'loading'} />;
-}
-
-function RealtimeTable({ rows, pending }: { rows: ReturnType<typeof monitorRealtimeRows>; pending: boolean }) {
- const { t } = useTranslation();
- const columns = [
- {
- title: t('monitorMetrics.labels'),
- dataIndex: 'labels',
- render: (labels: Record<string, string>) => (
- <div className={styles.labels}>
- {Object.entries(labels).map(([key, value]) => (
- <Tag key={key}>
- {key}={value}
- </Tag>
- ))}
- </div>
- )
- },
- { title: t('monitorMetrics.field'), dataIndex: 'field' },
- { title: t('monitorMetrics.unit'), dataIndex: 'unit', render: (value: string | null) => value ?? '—' },
- { title: t('monitorMetrics.time'), dataIndex: 'time', render: formatMetricTime },
- { title: t('monitorMetrics.value'), dataIndex: 'value' }
- ];
- return <Table rowKey="key" size="small" loading={pending} dataSource={rows} columns={columns} pagination={false} />;
-}
-
-function formatMetricTime(value?: number | null) {
- return value == null
- ? '—'
- : new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'medium' }).format(value);
-}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-table.module.css b/web-app/src/features/monitor/components/monitor-realtime-table.module.css
new file mode 100644
index 0000000000..08b72309d6
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-table.module.css
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+.realtimeTable {
+ min-width: 0;
+}
+
+.compactMetricTable {
+ width: 100%;
+ border-collapse: collapse;
+ table-layout: fixed;
+}
+
+.compactMetricTable tr + tr {
+ border-top: 1px solid var(--hb-border-subtle);
+}
+
+.compactMetricTable tr:hover {
+ background: var(--hb-bg-hover);
+}
+
+.metricIdentityColumn {
+ width: 60%;
+}
+
+.compactMetricTable td {
+ height: 27px;
+ padding: 2px 8px;
+ overflow: hidden;
+ color: var(--hb-text-secondary);
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.compactMetricTable td:first-child {
+ padding-inline-start: 10px;
+}
+
+.compactMetricTable td.metricValue {
+ width: auto;
+ color: var(--hb-text-primary);
+ font-variant-numeric: tabular-nums;
+ font-weight: 500;
+ text-align: end;
+}
+
+.metricValueText {
+ display: block;
+ width: 100%;
+ min-width: 0;
+ overflow: hidden;
+ cursor: text;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.metricValueText[role='button'] {
+ cursor: pointer;
+}
+
+.metricValueText:focus-visible {
+ outline: 2px solid var(--hb-focus-ring);
+ outline-offset: 1px;
+}
+
+.metricValuePopover {
+ display: grid;
+ width: min(420px, calc(100vw - 48px));
+ max-height: 240px;
+ gap: var(--hb-space-2);
+}
+
+.metricValuePopoverText {
+ max-height: 180px;
+ padding: var(--hb-space-2);
+ overflow: auto;
+ border: 1px solid var(--hb-border-subtle);
+ border-radius: var(--hb-radius-control);
+ background: var(--hb-bg-subtle);
+ color: var(--hb-text-primary);
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ overflow-wrap: anywhere;
+ user-select: text;
+ white-space: pre-wrap;
+}
+
+.metricValuePopover :global(.ant-btn) {
+ justify-self: end;
+}
+
+.selectedMetricRow {
+ background: var(--hb-bg-selected);
+ box-shadow: inset 2px 0 0 var(--hb-brand-accent);
+}
+
+.metricFieldButton {
+ display: flex;
+ width: 100%;
+ height: 23px;
+ min-width: 0;
+ justify-content: flex-start;
+ padding: 0;
+ color: inherit;
+ font-size: inherit;
+ text-align: start;
+}
+
+.metricFieldButton > span {
+ min-width: 0;
+}
+
+.realtimeField {
+ display: inline-flex;
+ max-width: 100%;
+ min-width: 0;
+ align-items: center;
+ gap: 5px;
+}
+
+.realtimeField > span:first-child {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.realtimeField :global(.ant-tag) {
+ flex: none;
+ margin-inline-end: 0;
+ padding-inline: 4px;
+ font-size: 9px;
+ line-height: 16px;
+}
+
+.visuallyHidden {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+}
diff --git a/web-app/src/features/monitor/components/monitor-realtime-table.test.tsx b/web-app/src/features/monitor/components/monitor-realtime-table.test.tsx
new file mode 100644
index 0000000000..aff41e07c0
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-table.test.tsx
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MonitorRealtimeTable } from './monitor-realtime-table';
+
+const clipboardWrite = vi.fn();
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, string>) => (values?.field == null ? key : `${key}:${values.field}`)
+ })
+}));
+
+afterEach(cleanup);
+
+describe('MonitorRealtimeTable', () => {
+ beforeEach(() => {
+ clipboardWrite.mockReset();
+ clipboardWrite.mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: clipboardWrite }
+ });
+ });
+
+ it('shows a tooltip and compact copy popover only when the value overflows', async () => {
+ const value = '/opt/homebrew/var/mysql/a-very-long-runtime-directory-that-does-not-fit-in-the-cell';
+ render(
+ <MonitorRealtimeTable
+ rows={[{ key: '0:datadir', labels: {}, field: 'datadir', unit: null, value, time: null, collectedAt: null }]}
+ pending={false}
+ />
+ );
+
+ const renderedValue = screen.getByText(value);
+ Object.defineProperties(renderedValue, {
+ clientWidth: { configurable: true, value: 90 },
+ scrollWidth: { configurable: true, value: 320 }
+ });
+
+ fireEvent.mouseEnter(renderedValue);
+ await waitFor(() => expect(document.querySelector('.ant-tooltip')).toHaveTextContent(value));
+ expect(renderedValue).toHaveAttribute('aria-label', 'monitorMetrics.value.open:datadir');
+
+ fireEvent.click(renderedValue);
+ const dialog = await screen.findByRole('dialog', { name: 'monitorMetrics.value.title:datadir' });
+ expect(dialog).toHaveTextContent(value);
+ fireEvent.click(screen.getByRole('button', { name: 'monitorMetrics.value.copy' }));
+ await waitFor(() => expect(clipboardWrite).toHaveBeenCalledWith(value));
+ expect(await screen.findByRole('button', { name: 'monitorMetrics.value.copied' })).toBeInTheDocument();
+ fireEvent.click(renderedValue);
+ await waitFor(() => expect(renderedValue).toHaveAttribute('aria-expanded', 'false'));
+ });
+
+ it('keeps a fitting value as plain non-focusable table text', () => {
+ render(
+ <MonitorRealtimeTable
+ rows={[{ key: '0:port', labels: {}, field: 'port', unit: null, value: '3306', time: null, collectedAt: null }]}
+ pending={false}
+ />
+ );
+
+ const renderedValue = screen.getByText('3306');
+ fireEvent.mouseEnter(renderedValue);
+ expect(renderedValue).not.toHaveAttribute('tabindex');
+ expect(renderedValue).not.toHaveAttribute('aria-label');
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('opens and dismisses the compact value popover from the keyboard', async () => {
+ const value = '/opt/homebrew/var/mysql/a-very-long-runtime-directory';
+ render(
+ <MonitorRealtimeTable
+ rows={[{ key: '0:datadir', labels: {}, field: 'datadir', unit: null, value, time: null, collectedAt: null }]}
+ pending={false}
+ />
+ );
+
+ const renderedValue = screen.getByText(value);
+ Object.defineProperties(renderedValue, {
+ clientWidth: { configurable: true, value: 80 },
+ scrollWidth: { configurable: true, value: 240 }
+ });
+ fireEvent.focus(renderedValue);
+ await waitFor(() => expect(renderedValue).toHaveAttribute('tabindex', '0'));
+ expect(await screen.findByRole('tooltip')).toHaveTextContent(value);
+
+ fireEvent.keyDown(renderedValue, { key: 'Enter' });
+ expect(await screen.findByRole('dialog', { name: 'monitorMetrics.value.title:datadir' })).toBeInTheDocument();
+ fireEvent.keyDown(renderedValue, { key: 'Escape' });
+ await waitFor(() => expect(renderedValue).toHaveAttribute('aria-expanded', 'false'));
+ });
+});
diff --git a/web-app/src/features/monitor/components/monitor-realtime-table.tsx b/web-app/src/features/monitor/components/monitor-realtime-table.tsx
new file mode 100644
index 0000000000..eaa6b3d79f
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-realtime-table.tsx
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { Button, Spin, Tag } from 'antd';
+import { useTranslation } from 'react-i18next';
+
+import type { MonitorMetricOption } from '../model/monitor-contract';
+import type { monitorRealtimeRows } from '../model/monitor-detail-model';
+import { MonitorMetricValue } from './monitor-metric-value';
+import { MatrixRealtimeTable } from './monitor-realtime-matrix-table';
+import styles from './monitor-realtime-table.module.css';
+
+type RealtimeRow = ReturnType<typeof monitorRealtimeRows>[number];
+type CompactRow = {
+ key: string;
+ field: string;
+ unit: string | null;
+ value: string;
+ metricKey: string | undefined;
+};
+
+export function MonitorRealtimeTable({
+ rows,
+ pending,
+ group,
+ metricOptions = [],
+ selectedMetricKey,
+ onSelectMetric
+}: {
+ rows: RealtimeRow[];
+ pending: boolean;
+ group?: string | undefined;
+ metricOptions?: MonitorMetricOption[] | undefined;
+ selectedMetricKey?: string | undefined;
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
+ const sampleKeys = new Set(rows.map(sampleKey));
+ return (
+ <div className={styles.realtimeTable}>
+ {sampleKeys.size <= 1 ? (
+ <CompactRealtimeTable
+ rows={rows}
+ pending={pending}
+ group={group}
+ metricOptions={metricOptions}
+ selectedMetricKey={selectedMetricKey}
+ onSelectMetric={onSelectMetric}
+ />
+ ) : (
+ <MatrixRealtimeTable rows={rows} pending={pending} />
+ )}
+ </div>
+ );
+}
+
+function CompactRealtimeTable({
+ rows,
+ pending,
+ group,
+ metricOptions,
+ selectedMetricKey,
+ onSelectMetric
+}: {
+ rows: RealtimeRow[];
+ pending: boolean;
+ group?: string | undefined;
+ metricOptions: MonitorMetricOption[];
+ selectedMetricKey?: string | undefined;
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
+ const { t } = useTranslation();
+ const data = compactRows(rows, metricOptions, group);
+ return (
+ <Spin spinning={pending}>
+ <table className={styles.compactMetricTable}>
+ <caption className={styles.visuallyHidden}>{t('monitorMetrics.currentValues')}</caption>
+ <colgroup>
+ <col className={styles.metricIdentityColumn} data-metric-column="identity" />
+ <col />
+ </colgroup>
+ <tbody>
+ {data.map(row => (
+ <CompactRealtimeRow
+ key={row.key}
+ row={row}
+ selectedMetricKey={selectedMetricKey}
+ onSelectMetric={onSelectMetric}
+ />
+ ))}
+ </tbody>
+ </table>
+ </Spin>
+ );
+}
+
+function CompactRealtimeRow({
+ row,
+ selectedMetricKey,
+ onSelectMetric
+}: {
+ row: CompactRow;
+ selectedMetricKey?: string | undefined;
+ onSelectMetric?: ((metricKey: string) => void) | undefined;
+}) {
+ const metricKey = row.metricKey;
+ const selected = metricKey === selectedMetricKey;
+ return (
+ <tr
+ className={selected ? styles.selectedMetricRow : undefined}
+ {...(metricKey ? { 'data-monitor-metric': metricKey } : {})}
+ >
+ <td>
+ {metricKey && onSelectMetric ? (
+ <Button
+ type="text"
+ className={styles.metricFieldButton ?? ''}
+ aria-label={metricKey}
+ onClick={() => onSelectMetric(metricKey)}
+ >
+ {renderField(row.field, row.unit)}
+ </Button>
+ ) : (
+ renderField(row.field, row.unit)
+ )}
+ </td>
+ <td className={styles.metricValue}>
+ <MonitorMetricValue field={row.field} value={row.value} />
+ </td>
+ </tr>
+ );
+}
+
+function compactRows(
+ rows: RealtimeRow[],
+ metricOptions: MonitorMetricOption[],
+ group: string | undefined
+): CompactRow[] {
+ const labels: CompactRow[] = Object.entries(rows[0]?.labels ?? {}).map(([field, value]) => ({
+ key: `label:${field}`,
+ field,
+ unit: null,
+ value,
+ metricKey: undefined
+ }));
+ return [
+ ...labels,
+ ...rows.map(row => ({
+ key: row.key,
+ field: row.field,
+ unit: row.unit,
+ value: row.value,
+ metricKey: metricOptions.find(option => option.group === group && option.field === row.field)?.key
+ }))
+ ];
+}
+
+function renderField(field: string, unit?: string | null) {
+ return (
+ <span className={styles.realtimeField}>
+ <span>{field}</span>
+ {unit ? <Tag bordered={false}>{unit}</Tag> : null}
+ </span>
+ );
+}
+
+function sampleKey(row: RealtimeRow) {
+ const separator = row.key.indexOf(':');
+ return separator < 0 ? row.key : row.key.slice(0, separator);
+}
diff --git a/web-app/src/features/monitor/components/monitor-segmented-switch.module.css b/web-app/src/features/monitor/components/monitor-segmented-switch.module.css
new file mode 100644
index 0000000000..bc6eb17682
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-segmented-switch.module.css
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+.switch:global(.ant-segmented) {
+ padding: 2px;
+ border: 1px solid var(--hb-border-subtle);
+ background: var(--hb-bg-hover);
+}
+
+.switch :global(.ant-segmented-item) {
+ min-width: 56px;
+ color: var(--hb-text-secondary);
+}
+
+.switch :global(.ant-segmented-item-selected) {
+ background: var(--hb-brand-accent);
+ box-shadow: none;
+ color: var(--hb-text-on-accent);
+}
+
+.switch :global(.ant-segmented-item:not(.ant-segmented-item-selected):hover) {
+ color: var(--hb-text-primary);
+}
diff --git a/web-app/src/features/monitor/components/monitor-segmented-switch.tsx b/web-app/src/features/monitor/components/monitor-segmented-switch.tsx
new file mode 100644
index 0000000000..0b19b74ee8
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-segmented-switch.tsx
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { Segmented } from 'antd';
+
+import styles from './monitor-segmented-switch.module.css';
+
+type MonitorSegmentedSwitchProps<Value extends string> = {
+ label: string;
+ value: Value;
+ options: Array<{ label: string; value: Value }>;
+ disabled?: boolean;
+ size?: 'middle' | 'small';
+ onChange: (value: Value) => void;
+};
+
+export function MonitorSegmentedSwitch<Value extends string>({
+ label,
+ value,
+ options,
+ disabled = false,
+ size = 'middle',
+ onChange
+}: MonitorSegmentedSwitchProps<Value>) {
+ return (
+ <Segmented<Value>
+ aria-label={label}
+ className={styles.switch}
+ value={value}
+ options={options}
+ disabled={disabled}
+ size={size}
+ onChange={onChange}
+ />
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-selected-history-controls.tsx b/web-app/src/features/monitor/components/monitor-selected-history-controls.tsx
new file mode 100644
index 0000000000..4e6486de96
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-selected-history-controls.tsx
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { ReloadOutlined } from '@ant-design/icons';
+import { Button, Select } from 'antd';
+import { useTranslation } from 'react-i18next';
+
+import {
+ monitorMetricHistoryRanges,
+ type MonitorHistoryChart,
+ type MonitorMetricWorkbenchController
+} from '../model/monitor-detail-model';
+import styles from './monitor-history-results.module.css';
+import { MonitorSegmentedSwitch } from './monitor-segmented-switch';
+
+export function SelectedHistoryControls({
+ chart,
+ actions
+}: {
+ chart: MonitorHistoryChart;
+ actions: MonitorMetricWorkbenchController['actions'];
+}) {
+ const { t } = useTranslation();
+ const aggregated = chart.interval;
+ return (
+ <div className={styles.selectedHistoryControls}>
+ <Select
+ size="small"
+ value={chart.history}
+ aria-label={t('monitorMetrics.historyRange')}
+ onChange={value => actions.setHistoryChartRange(chart.metric.key, value)}
+ options={monitorMetricHistoryRanges.map(value => ({ value, label: value }))}
+ />
+ <MonitorSegmentedSwitch<'raw' | 'aggregated'>
+ label={t('monitorMetrics.historyMode')}
+ value={aggregated ? 'aggregated' : 'raw'}
+ options={[
+ { value: 'raw', label: t('monitorMetrics.rawValues') },
+ { value: 'aggregated', label: t('monitorMetrics.aggregatedValues') }
+ ]}
+ size="small"
+ onChange={value => actions.setHistoryChartMode(chart.metric.key, value === 'aggregated')}
+ />
+ <Button
+ type="text"
+ size="small"
+ icon={<ReloadOutlined />}
+ aria-label={t('monitorMetrics.refreshHistory')}
+ onClick={() => actions.refreshHistoryChart(chart.metric.key)}
+ />
+ </div>
+ );
+}
diff --git a/web-app/src/features/monitor/components/monitor-selected-history-tray.tsx b/web-app/src/features/monitor/components/monitor-selected-history-tray.tsx
new file mode 100644
index 0000000000..9fa326ef3b
--- /dev/null
+++ b/web-app/src/features/monitor/components/monitor-selected-history-tray.tsx
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import type { CSSProperties, KeyboardEvent, PointerEvent } from 'react';
+import { useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { MonitorHistoryChart, MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import { HistoryAvailabilityBoundary, HistoryChartEvidence } from './monitor-history-chart';
+import styles from './monitor-history-results.module.css';
+import { formatMetricTime, historyStatistics, selectedCurrentValue } from './monitor-history-values';
+import { SelectedHistoryControls } from './monitor-selected-history-controls';
+
+export function MonitorSelectedHistoryTray({
+ state,
+ actions
+}: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'>) {
+ const { t } = useTranslation();
+ const dock = state.layout.layout.historyDock;
+ const resize = useHistoryDockResize(state, actions);
+ const chart = state.selectedHistoryChart;
+ if (!chart) return null;
+ return (
+ <section
+ className={styles.selectedHistoryTray}
+ data-monitor-history-tray=""
+ data-history-metric={chart.metric.key}
+ data-layout-editing={state.layout.editing}
+ style={{ '--monitor-history-height': `${dock.height * 22}px` } as CSSProperties}
+ aria-label={`${t('monitorMetrics.historyTrend')} ${chart.metric.key}`}
+ >
+ <SelectedHistoryHeader state={state} actions={actions} chart={chart} />
+ <SelectedHistoryContent state={state} actions={actions} chart={chart} resize={resize} />
+ </section>
+ );
+}
+
+function SelectedHistoryContent({
+ state,
+ chart,
+ resize
+}: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'> & {
+ chart: MonitorHistoryChart;
+ resize: ReturnType<typeof useHistoryDockResize>;
+}) {
+ const { t } = useTranslation();
+ return (
+ <>
+ {state.layout.editing ? (
+ <div
+ className={styles.historyDockResizeHandle}
+ role="separator"
+ tabIndex={0}
+ aria-orientation="horizontal"
+ aria-label={t('monitorMetrics.layout.resizeHistory')}
+ {...resize}
+ />
+ ) : null}
+ <SelectedHistoryStatistics chart={chart} />
+ <HistoryAvailabilityBoundary availability={state.historyAvailability}>
+ <HistoryChartEvidence chart={chart} />
+ </HistoryAvailabilityBoundary>
+ </>
+ );
+}
+
+function SelectedHistoryHeader({
+ state,
+ actions,
+ chart
+}: Pick<MonitorMetricWorkbenchController, 'state' | 'actions'> & {
+ chart: MonitorHistoryChart;
+}) {
+ const { t } = useTranslation();
+ const current = selectedCurrentValue(state, chart.metric.field);
+ return (
+ <header className={styles.selectedHistoryHeader}>
+ <div className={styles.selectedHistoryIdentity}>
+ <strong>{t('monitorMetrics.historyTrend')}:</strong>
+ <span>{chart.metric.key}</span>
+ <span className={styles.currentMetricValue}>
+ {t('monitorMetrics.currentValue')}: {current.value}
+ {chart.metric.unit ? ` ${chart.metric.unit}` : ''}
+ </span>
+ <time>{formatMetricTime(current.time)}</time>
+ </div>
+ <SelectedHistoryControls chart={chart} actions={actions} />
+ </header>
+ );
+}
+
+function useHistoryDockResize(
+ state: MonitorMetricWorkbenchController['state'],
+ actions: MonitorMetricWorkbenchController['actions']
+) {
+ const drag = useRef<{ startY: number; height: number } | null>(null);
+ const update = (height: number) =>
+ actions.layout.changeHistoryDock({
+ ...state.layout.layout.historyDock,
+ collapsed: false,
+ height: Math.min(20, Math.max(8, height))
+ });
+ return {
+ onPointerDown: (event: PointerEvent<HTMLDivElement>) => {
+ drag.current = { startY: event.clientY, height: state.layout.layout.historyDock.height };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ },
+ onPointerMove: (event: PointerEvent<HTMLDivElement>) => {
+ if (drag.current) update(drag.current.height + Math.round((event.clientY - drag.current.startY) / 22));
+ },
+ onPointerUp: (event: PointerEvent<HTMLDivElement>) => {
+ drag.current = null;
+ if (event.currentTarget.hasPointerCapture(event.pointerId))
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ },
+ onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
+ event.preventDefault();
+ update(state.layout.layout.historyDock.height + (event.key === 'ArrowDown' ? 1 : -1));
+ }
+ };
+}
+
+function SelectedHistoryStatistics({ chart }: { chart: MonitorHistoryChart }) {
+ const { t } = useTranslation();
+ const statistics = historyStatistics(chart);
+ if (!statistics) return null;
+ const items = [
+ [t('monitorMetrics.minimum'), statistics.minimum],
+ [t('monitorMetrics.maximum'), statistics.maximum],
+ [t('monitorMetrics.average'), statistics.average],
+ [t('monitorMetrics.samples'), statistics.samples]
+ ];
+ return (
+ <dl className={styles.historyStatistics}>
+ {items.map(([label, value]) => (
+ <div key={label} className={styles.historyStatistic}>
+ <dt>{label}</dt>
+ <dd>{value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
diff --git a/web-app/src/features/monitor/controller/monitor-history-workbench-evidence.ts b/web-app/src/features/monitor/controller/monitor-history-workbench-evidence.ts
index a263ab29ff..c495d4d707 100644
--- a/web-app/src/features/monitor/controller/monitor-history-workbench-evidence.ts
+++ b/web-app/src/features/monitor/controller/monitor-history-workbench-evidence.ts
@@ -1,10 +1,6 @@
/* Licensed to the Apache Software Foundation (ASF) under the Apache License, Version 2.0. */
-import {
- monitorHistorySeries,
- monitorMetricHistoryUsesInterval,
- type MonitorMetricWorkbenchController
-} from '../model/monitor-detail-model';
+import { monitorHistorySeries, type MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
import { metricEvidence } from './monitor-metric-query-evidence';
import type { useMonitorHistorySelection } from './use-monitor-history-selection';
import type { useMonitorMetricData } from './use-monitor-metric-data';
@@ -13,7 +9,7 @@ export function buildHistoryChartEvidence(
selection: ReturnType<typeof useMonitorHistorySelection>,
queries: ReturnType<typeof useMonitorMetricData>
) {
- return selection.visible.map(item => buildHistoryChart(item.metric, item.history, queries));
+ return selection.visible.map(item => buildHistoryChart(item.metric, item.history, item.interval, queries));
}
export function buildSelectedHistoryChart(
@@ -22,20 +18,22 @@ export function buildSelectedHistoryChart(
queries: ReturnType<typeof useMonitorMetricData>
): MonitorMetricWorkbenchController['state']['selectedHistoryChart'] {
if (!metric || metric.historySupported === false) return undefined;
- return buildHistoryChart(metric, selection.historyFor(metric.key), queries);
+ return buildHistoryChart(metric, selection.historyFor(metric.key), selection.intervalFor(metric.key), queries);
}
function buildHistoryChart(
metric: NonNullable<Parameters<typeof useMonitorMetricData>[0]['metric']>,
history: ReturnType<typeof useMonitorHistorySelection>['visible'][number]['history'],
+ interval: boolean,
queries: ReturnType<typeof useMonitorMetricData>
) {
const query = queries.historyCharts.find(candidate => candidate.metric.key === metric.key)?.query;
return {
metric,
history,
+ interval,
result: query
- ? metricEvidence(query, data => monitorHistorySeries(data, monitorMetricHistoryUsesInterval(history)))
+ ? metricEvidence(query, data => monitorHistorySeries(data, interval))
: { kind: 'loading' as const, rows: [] }
};
}
diff --git a/web-app/src/features/monitor/controller/monitor-metric-query-evidence.test.ts b/web-app/src/features/monitor/controller/monitor-metric-query-evidence.test.ts
index 830e6025e0..1bee8fc5ad 100644
--- a/web-app/src/features/monitor/controller/monitor-metric-query-evidence.test.ts
+++ b/web-app/src/features/monitor/controller/monitor-metric-query-evidence.test.ts
@@ -39,12 +39,12 @@ describe('monitor metric query evidence', () => {
});
it('exposes payloads only after a successful read', () => {
- const query = { isPending: false, isError: false, error: null, data: ['summary.value'] };
+ const query = { isPending: false, isError: false, error: null, data: ['summary'] };
expect(favoriteEvidence(query, { key: 'summary.value', group: 'summary', field: 'value' })).toEqual({
kind: 'ready',
value: true,
- token: 'summary.value'
+ token: 'summary'
});
expect(
favoriteCollectionEvidence(query, [
@@ -53,9 +53,9 @@ describe('monitor metric query evidence', () => {
])
).toEqual({
kind: 'ready',
- items: [{ key: 'summary.value', available: true }]
+ items: [{ key: 'summary', available: true }]
});
- expect(metricEvidence(query, values => values)).toEqual({ kind: 'ready', rows: ['summary.value'] });
+ expect(metricEvidence(query, values => values)).toEqual({ kind: 'ready', rows: ['summary'] });
});
it('keeps unresolved favorite tokens visible without presenting them as queryable metrics', () => {
@@ -63,19 +63,19 @@ describe('monitor metric query evidence', () => {
isPending: false,
isError: false,
error: null,
- data: ['retired.value', 'retired.value', 'summary.value']
+ data: ['retired.value', 'retired.value', 'summary']
};
expect(favoriteCollectionEvidence(query, [{ key: 'summary.value', group: 'summary', field: 'value' }])).toEqual({
kind: 'ready',
items: [
{ key: 'retired.value', available: false },
- { key: 'summary.value', available: true }
+ { key: 'summary', available: true }
]
});
});
- it('resolves legacy group and field favorite tokens to current numeric metrics', () => {
+ it('accepts only group tokens and keeps legacy field tokens unavailable', () => {
const query = { isPending: false, isError: false, error: null, data: ['summary', 'latency'] };
expect(
@@ -87,9 +87,8 @@ describe('monitor metric query evidence', () => {
).toEqual({
kind: 'ready',
items: [
- { key: 'summary.value', available: true },
- { key: 'summary.latency', available: true },
- { key: 'network.latency', available: true }
+ { key: 'summary', available: true },
+ { key: 'latency', available: false }
]
});
expect(favoriteEvidence(query, { key: 'summary.value', group: 'summary', field: 'value' })).toEqual({
diff --git a/web-app/src/features/monitor/controller/monitor-metric-query-evidence.ts b/web-app/src/features/monitor/controller/monitor-metric-query-evidence.ts
index 8bdbe0a000..023041c9a8 100644
--- a/web-app/src/features/monitor/controller/monitor-metric-query-evidence.ts
+++ b/web-app/src/features/monitor/controller/monitor-metric-query-evidence.ts
@@ -41,7 +41,7 @@ export function favoriteEvidence(
if (query.isError) return { kind: classifyMonitorMetricReadError(query.error) };
if (!query.data) return { kind: 'error' };
if (!metric) return { kind: 'ready', value: false };
- const token = [metric.key, metric.group, metric.field].find(candidate => query.data?.includes(candidate));
+ const token = query.data.includes(metric.group) ? metric.group : undefined;
return token ? { kind: 'ready', value: true, token } : { kind: 'ready', value: false };
}
@@ -52,7 +52,7 @@ export function realtimeGroupFavoriteEvidence(
if (query.isPending) return { kind: 'loading' };
if (query.isError) return { kind: classifyMonitorMetricReadError(query.error) };
if (!query.data) return { kind: 'error' };
- const token = query.data.find(candidate => candidate === group || candidate.startsWith(`${group}.`));
+ const token = query.data.find(candidate => candidate === group);
return token ? { kind: 'ready', value: true, token } : { kind: 'ready', value: false };
}
@@ -68,23 +68,8 @@ export function favoriteCollectionEvidence(
}
function resolveFavoriteItems(tokens: string[], options: MonitorMetricOption[]) {
- // Older monitor definitions persisted a group, a field, or a full metric key.
- // Resolve every supported form while retaining orphaned tokens as honest evidence.
- const items: Array<{ key: string; available: boolean }> = [];
- const emitted = new Set<string>();
- for (const token of new Set(tokens)) {
- const matches = options.filter(option => option.key === token || option.group === token || option.field === token);
- if (matches.length === 0) {
- items.push({ key: token, available: false });
- continue;
- }
- for (const option of matches) {
- if (emitted.has(option.key)) continue;
- emitted.add(option.key);
- items.push({ key: option.key, available: true });
- }
- }
- return items;
+ const groups = new Set(options.map(option => option.group));
+ return [...new Set(tokens)].map(token => ({ key: token, available: groups.has(token) }));
}
export function metricEvidence<T, Row>(
diff --git a/web-app/src/features/monitor/controller/monitor-metric-workbench-actions.ts b/web-app/src/features/monitor/controller/monitor-metric-workbench-actions.ts
new file mode 100644
index 0000000000..646f81b40b
--- /dev/null
+++ b/web-app/src/features/monitor/controller/monitor-metric-workbench-actions.ts
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import type { Monitor } from '../model/monitor-contract';
+import type { MonitorMetricWorkbenchController } from '../model/monitor-detail-model';
+import type { useMonitorFavoriteMutation } from './use-monitor-favorite-mutation';
+import type { useMonitorMetricData } from './use-monitor-metric-data';
+import type { useMonitorMetricSources } from './use-monitor-metric-sources';
+
+export function buildWorkbenchActions(input: {
+ monitor: Monitor | undefined;
+ metric: Parameters<typeof useMonitorMetricData>[0]['metric'];
+ favorite: MonitorMetricWorkbenchController['state']['favorite'];
+ realtimeGroups: MonitorMetricWorkbenchController['state']['realtimeGroups'];
+ queries: ReturnType<typeof useMonitorMetricData>;
+ favoriteMutation: ReturnType<typeof useMonitorFavoriteMutation>;
+ realtimeSelection: ReturnType<typeof useMonitorMetricSources>['realtimeSelection'];
+ historySelection: ReturnType<typeof useMonitorMetricSources>['historySelection'];
+ refreshDetail: () => void;
+}) {
+ const selectedGroup = input.metric?.group ?? '';
+ return {
+ toggleFavorite: () => input.favoriteMutation.toggle(selectedGroup, input.favorite),
+ toggleRealtimeFavorite: (group: string) => {
+ const current = input.realtimeGroups.find(item => item.group === group);
+ return current ? input.favoriteMutation.toggle(group, current.favorite) : Promise.resolve();
+ },
+ loadMoreRealtimeGroups: input.realtimeSelection.loadMore,
+ revealRealtimeGroup: input.realtimeSelection.reveal,
+ activateHistoryChart: input.historySelection.activate,
+ setHistoryChartRange: input.historySelection.setRange,
+ setHistoryChartMode: input.historySelection.setMode,
+ refreshHistoryChart: (metricKey: string) => {
+ const chart = input.queries.historyCharts.find(item => item.metric.key === metricKey);
+ if (chart) void chart.query.refetch();
+ else input.historySelection.activate(metricKey);
+ },
+ loadMoreHistoryCharts: input.historySelection.loadMore,
+ refresh: () => {
+ input.refreshDetail();
+ refreshMonitorMetricQueries(
+ input.queries,
+ Boolean(input.monitor && (input.metric || input.realtimeGroups.length > 0)),
+ input.metric?.group
+ );
+ }
+ } satisfies Pick<
+ MonitorMetricWorkbenchController['actions'],
+ | 'toggleFavorite'
+ | 'toggleRealtimeFavorite'
+ | 'revealRealtimeGroup'
+ | 'loadMoreRealtimeGroups'
+ | 'activateHistoryChart'
+ | 'setHistoryChartRange'
+ | 'setHistoryChartMode'
+ | 'refreshHistoryChart'
+ | 'loadMoreHistoryCharts'
+ | 'refresh'
+ >;
+}
+
+function refreshMonitorMetricQueries(
+ queries: ReturnType<typeof useMonitorMetricData>,
+ canRefresh: boolean,
+ selectedGroup: string | undefined
+) {
+ if (!canRefresh) return;
+ void queries.favorites.refetch();
+ if (selectedGroup && !queries.realtimeGroups.some(item => item.group === selectedGroup)) {
+ void queries.realtime.refetch();
+ }
+ for (const group of queries.realtimeGroups) void group.query.refetch();
+ for (const chart of queries.historyCharts) void chart.query.refetch();
+}
diff --git a/web-app/src/features/monitor/controller/monitor-metric-workbench-result.ts b/web-app/src/features/monitor/controller/monitor-metric-workbench-result.ts
index 3d1d80957d..e9f8c93d2e 100644
--- a/web-app/src/features/monitor/controller/monitor-metric-workbench-result.ts
+++ b/web-app/src/features/monitor/controller/monitor-metric-workbench-result.ts
@@ -13,7 +13,7 @@ import type {
type MetricUrlActions = Pick<MonitorMetricWorkbenchController['actions'], 'setMetric' | 'setHistory'>;
-export function buildMonitorMetricWorkbenchResult(input: {
+type MonitorMetricWorkbenchResultInput = {
catalog: MonitorMetricWorkbenchController['state']['catalog'];
metricKey: string;
history: MonitorMetricHistory;
@@ -21,6 +21,7 @@ export function buildMonitorMetricWorkbenchResult(input: {
favorite: MonitorMetricWorkbenchController['state']['favorite'];
favoriteCollection: MonitorMetricWorkbenchController['state']['favoriteCollection'];
favoriteBusy: boolean;
+ realtimeGroupNames: string[];
realtimeGroups: MonitorMetricWorkbenchController['state']['realtimeGroups'];
hasMoreRealtimeGroups: boolean;
historyAvailability: MonitorMetricWorkbenchController['state']['historyAvailability'];
@@ -29,47 +30,65 @@ export function buildMonitorMetricWorkbenchResult(input: {
hasMoreHistoryCharts: boolean;
realtime: MonitorMetricWorkbenchController['state']['realtime'];
historical: MonitorMetricWorkbenchController['state']['historical'];
+ layout: MonitorMetricWorkbenchController['state']['layout'];
+ layoutActions: MonitorMetricWorkbenchController['actions']['layout'];
refreshControl: MonitorDetailRefreshControl;
urlActions: MetricUrlActions;
toggleFavorite: MonitorMetricWorkbenchController['actions']['toggleFavorite'];
toggleRealtimeFavorite: MonitorMetricWorkbenchController['actions']['toggleRealtimeFavorite'];
+ revealRealtimeGroup: MonitorMetricWorkbenchController['actions']['revealRealtimeGroup'];
loadMoreRealtimeGroups: MonitorMetricWorkbenchController['actions']['loadMoreRealtimeGroups'];
activateHistoryChart: MonitorMetricWorkbenchController['actions']['activateHistoryChart'];
setHistoryChartRange: MonitorMetricWorkbenchController['actions']['setHistoryChartRange'];
+ setHistoryChartMode: MonitorMetricWorkbenchController['actions']['setHistoryChartMode'];
refreshHistoryChart: MonitorMetricWorkbenchController['actions']['refreshHistoryChart'];
loadMoreHistoryCharts: MonitorMetricWorkbenchController['actions']['loadMoreHistoryCharts'];
refresh: () => void;
-}): MonitorMetricWorkbenchController {
+};
+
+export function buildMonitorMetricWorkbenchResult(
+ input: MonitorMetricWorkbenchResultInput
+): MonitorMetricWorkbenchController {
+ return { state: buildWorkbenchState(input), actions: buildWorkbenchActions(input) };
+}
+
+function buildWorkbenchState(input: MonitorMetricWorkbenchResultInput): MonitorMetricWorkbenchController['state'] {
+ return {
+ catalog: input.catalog,
+ metricKey: input.metricKey,
+ history: input.history,
+ historySupported: input.historySupported,
+ refreshSeconds: input.refreshControl.refreshSeconds,
+ favorite: input.favorite,
+ favoriteCollection: input.favoriteCollection,
+ favoriteBusy: input.favoriteBusy,
+ realtimeGroupNames: input.realtimeGroupNames,
+ realtimeGroups: input.realtimeGroups,
+ hasMoreRealtimeGroups: input.hasMoreRealtimeGroups,
+ historyAvailability: input.historyAvailability,
+ historyCharts: input.historyCharts,
+ selectedHistoryChart: input.selectedHistoryChart,
+ hasMoreHistoryCharts: input.hasMoreHistoryCharts,
+ realtime: input.realtime,
+ historical: input.historical,
+ layout: input.layout
+ };
+}
+
+function buildWorkbenchActions(input: MonitorMetricWorkbenchResultInput): MonitorMetricWorkbenchController['actions'] {
return {
- state: {
- catalog: input.catalog,
- metricKey: input.metricKey,
- history: input.history,
- historySupported: input.historySupported,
- refreshSeconds: input.refreshControl.refreshSeconds,
- favorite: input.favorite,
- favoriteCollection: input.favoriteCollection,
- favoriteBusy: input.favoriteBusy,
- realtimeGroups: input.realtimeGroups,
- hasMoreRealtimeGroups: input.hasMoreRealtimeGroups,
- historyAvailability: input.historyAvailability,
- historyCharts: input.historyCharts,
- selectedHistoryChart: input.selectedHistoryChart,
- hasMoreHistoryCharts: input.hasMoreHistoryCharts,
- realtime: input.realtime,
- historical: input.historical
- },
- actions: {
- ...input.urlActions,
- setRefreshSeconds: input.refreshControl.setRefreshSeconds,
- toggleFavorite: input.toggleFavorite,
- toggleRealtimeFavorite: input.toggleRealtimeFavorite,
- loadMoreRealtimeGroups: input.loadMoreRealtimeGroups,
- activateHistoryChart: input.activateHistoryChart,
- setHistoryChartRange: input.setHistoryChartRange,
- refreshHistoryChart: input.refreshHistoryChart,
- loadMoreHistoryCharts: input.loadMoreHistoryCharts,
- refresh: input.refresh
- }
+ ...input.urlActions,
+ setRefreshSeconds: input.refreshControl.setRefreshSeconds,
+ toggleFavorite: input.toggleFavorite,
+ toggleRealtimeFavorite: input.toggleRealtimeFavorite,
+ revealRealtimeGroup: input.revealRealtimeGroup,
+ loadMoreRealtimeGroups: input.loadMoreRealtimeGroups,
+ activateHistoryChart: input.activateHistoryChart,
+ setHistoryChartRange: input.setHistoryChartRange,
+ setHistoryChartMode: input.setHistoryChartMode,
+ refreshHistoryChart: input.refreshHistoryChart,
+ loadMoreHistoryCharts: input.loadMoreHistoryCharts,
+ refresh: input.refresh,
+ layout: input.layoutActions
};
}
diff --git a/web-app/src/features/monitor/controller/monitor-query-keys.test.ts b/web-app/src/features/monitor/controller/monitor-query-keys.test.ts
index 2799686769..28b951f1af 100644
--- a/web-app/src/features/monitor/controller/monitor-query-keys.test.ts
+++ b/web-app/src/features/monitor/controller/monitor-query-keys.test.ts
@@ -52,8 +52,8 @@ describe('Monitor Query Key factory', () => {
);
expect(monitorQueryKeys.favorites(7)).toEqual(monitorQueryKeys.favorites(7));
expect(monitorQueryKeys.realtime(7, 'summary')).toEqual(monitorQueryKeys.realtime(7, 'summary'));
- expect(monitorQueryKeys.history(historySource, 'summary.responseTime', '30m')).toEqual(
- monitorQueryKeys.history({ ...historySource }, 'summary.responseTime', '30m')
+ expect(monitorQueryKeys.history(historySource, 'summary.responseTime', '30m', false)).toEqual(
+ monitorQueryKeys.history({ ...historySource }, 'summary.responseTime', '30m', false)
);
});
@@ -90,7 +90,7 @@ describe('Monitor Query Key factory', () => {
for (const candidate of [monitorQueryKeys.realtime(8, 'summary'), monitorQueryKeys.realtime(7, 'cpu')])
expect(candidate).not.toEqual(realtime);
- const history = monitorQueryKeys.history(historySource, 'summary.responseTime', '30m');
+ const history = monitorQueryKeys.history(historySource, 'summary.responseTime', '30m', false);
for (const candidate of [
monitorQueryKeys.history({ ...historySource, id: 8 }, 'summary.responseTime', '30m'),
monitorQueryKeys.history({ ...historySource, instance: '127.0.0.1:9090' }, 'summary.responseTime', '30m'),
@@ -98,7 +98,8 @@ describe('Monitor Query Key factory', () => {
monitorQueryKeys.history({ ...historySource, app: 'prometheus' }, 'summary.responseTime', '30m'),
monitorQueryKeys.history({ ...historySource, scrape: 'http_sd' }, 'summary.responseTime', '30m'),
monitorQueryKeys.history(historySource, 'summary.max', '30m'),
- monitorQueryKeys.history(historySource, 'summary.responseTime', '1h')
+ monitorQueryKeys.history(historySource, 'summary.responseTime', '1h', false),
+ monitorQueryKeys.history(historySource, 'summary.responseTime', '30m', true)
])
expect(candidate).not.toEqual(history);
});
diff --git a/web-app/src/features/monitor/controller/monitor-query-keys.ts b/web-app/src/features/monitor/controller/monitor-query-keys.ts
index 0fa3a333d0..c437242732 100644
--- a/web-app/src/features/monitor/controller/monitor-query-keys.ts
+++ b/web-app/src/features/monitor/controller/monitor-query-keys.ts
@@ -49,9 +49,10 @@ export const monitorQueryKeys = {
metricCatalog: (id: number | undefined, app: string | undefined, scrape: string | null | undefined) =>
[...rootKey, 'metrics', 'catalog', id, app, scrape] as const,
favorites: (id: number | undefined) => [...rootKey, 'metrics', 'favorites', id] as const,
+ layout: (application: string | undefined) => [...rootKey, 'metrics', 'layout', application] as const,
realtime: (id: number | undefined, group: string | undefined) =>
[...rootKey, 'metrics', 'realtime', id, group] as const,
- history: (source: MonitorHistorySource, metricKey: string, history: string) =>
+ history: (source: MonitorHistorySource, metricKey: string, history: string, interval = false) =>
[
...rootKey,
'metrics',
@@ -62,6 +63,7 @@ export const monitorQueryKeys = {
source?.app,
source?.scrape,
metricKey,
- history
+ history,
+ interval
] as const
};
diff --git a/web-app/src/features/monitor/controller/use-monitor-history-selection.ts b/web-app/src/features/monitor/controller/use-monitor-history-selection.ts
index 15f492c296..1efc1a658e 100644
--- a/web-app/src/features/monitor/controller/use-monitor-history-selection.ts
+++ b/web-app/src/features/monitor/controller/use-monitor-history-selection.ts
@@ -8,9 +8,10 @@
import { useCallback, useMemo, useState } from 'react';
import type { RuntimeStatusViewModel } from '@/features/runtime-status';
-import type { MonitorDetailMetric } from '../model/monitor-contract';
+import type { MonitorDetailMetric, MonitorMetricOption } from '../model/monitor-contract';
import {
monitorHistoryMetrics,
+ monitorMetricHistoryUsesInterval,
type MonitorHistoryAvailability,
type MonitorMetricHistory
} from '../model/monitor-detail-model';
@@ -22,6 +23,7 @@ type HistorySelectionState = {
visibleCount: number;
activeKeys: Set<string>;
ranges: Record<string, MonitorMetricHistory>;
+ intervals: Record<string, boolean>;
};
export function useMonitorHistorySelection(input: {
@@ -43,17 +45,8 @@ export function useMonitorHistorySelection(input: {
}
const availability = historyAvailability(runtimeStatus);
const enabled = availability.kind === 'available' || availability.kind === 'degraded';
- const visible = enabled
- ? metrics.slice(0, current.visibleCount).map(metric => ({
- metric,
- history: current.ranges[metric.key] ?? defaultHistory
- }))
- : [];
- const requests = enabled
- ? metrics
- .filter(metric => current.activeKeys.has(metric.key))
- .map(metric => ({ metric, history: current.ranges[metric.key] ?? defaultHistory }))
- : [];
+ const defaultInterval = monitorMetricHistoryUsesInterval(defaultHistory);
+ const evidence = historyEvidence(metrics, current, defaultHistory, defaultInterval, enabled);
const update = useCallback(
(change: (state: HistorySelectionState) => HistorySelectionState) => {
setSelection(state => change(state.sourceKey === sourceKey ? state : createSelection(sourceKey)));
@@ -62,22 +55,58 @@ export function useMonitorHistorySelection(input: {
);
return {
availability,
- visible,
- requests,
+ ...evidence,
historyFor: (metricKey: string) => current.ranges[metricKey] ?? defaultHistory,
+ intervalFor: (metricKey: string) => current.intervals[metricKey] ?? defaultInterval,
hasMore: enabled && current.visibleCount < metrics.length,
+ ...historyActions(metrics, enabled, update)
+ };
+}
+
+function historyEvidence(
+ metrics: MonitorMetricOption[],
+ state: HistorySelectionState,
+ defaultHistory: MonitorMetricHistory,
+ defaultInterval: boolean,
+ enabled: boolean
+) {
+ const project = (metric: MonitorMetricOption) => ({
+ metric,
+ history: state.ranges[metric.key] ?? defaultHistory,
+ interval: state.intervals[metric.key] ?? defaultInterval
+ });
+ return {
+ visible: enabled ? metrics.slice(0, state.visibleCount).map(project) : [],
+ requests: enabled ? metrics.filter(metric => state.activeKeys.has(metric.key)).map(project) : []
+ };
+}
+
+function historyActions(
+ metrics: MonitorMetricOption[],
+ enabled: boolean,
+ update: (change: (state: HistorySelectionState) => HistorySelectionState) => void
+) {
+ const accepts = (metricKey: string) => enabled && metrics.some(metric => metric.key === metricKey);
+ return {
activate: (metricKey: string) => {
- if (!enabled || !metrics.some(metric => metric.key === metricKey)) return;
- update(state => ({ ...state, activeKeys: new Set(state.activeKeys).add(metricKey) }));
+ if (accepts(metricKey)) update(state => ({ ...state, activeKeys: new Set(state.activeKeys).add(metricKey) }));
},
setRange: (metricKey: string, history: MonitorMetricHistory) => {
- if (!enabled || !metrics.some(metric => metric.key === metricKey)) return;
+ if (!accepts(metricKey)) return;
update(state => ({
...state,
activeKeys: new Set(state.activeKeys).add(metricKey),
ranges: { ...state.ranges, [metricKey]: history }
}));
},
+ setMode: (metricKey: string, interval: boolean) => {
+ if (!accepts(metricKey)) return;
+ update(state => ({
+ ...state,
+ activeKeys: new Set(state.activeKeys).add(metricKey),
+ intervals: { ...state.intervals, [metricKey]: interval }
+ }));
+ },
loadMore: () =>
update(state => ({ ...state, visibleCount: Math.min(state.visibleCount + historyChartPageSize, metrics.length) }))
};
@@ -93,5 +122,5 @@ function historyAvailability(runtimeStatus: RuntimeStatusViewModel): MonitorHist
}
function createSelection(sourceKey: string): HistorySelectionState {
- return { sourceKey, visibleCount: historyChartPageSize, activeKeys: new Set(), ranges: {} };
+ return { sourceKey, visibleCount: historyChartPageSize, activeKeys: new Set(), ranges: {}, intervals: {} };
}
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-data.test.ts b/web-app/src/features/monitor/controller/use-monitor-metric-data.test.ts
index 5271ea5241..fee9128c54 100644
--- a/web-app/src/features/monitor/controller/use-monitor-metric-data.test.ts
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-data.test.ts
@@ -50,7 +50,7 @@ describe('useMonitorMetricData refresh interval', () => {
realtimeGroups: [],
historyRequests:
currentMetric && !('historySupported' in currentMetric && currentMetric.historySupported === false)
- ? [{ metric: currentMetric, history: '30m' }]
+ ? [{ metric: currentMetric, history: '30m', interval: false }]
: [],
metricKey: currentMetric?.key ?? '',
refreshSeconds: 30
@@ -71,7 +71,7 @@ describe('useMonitorMetricData refresh interval', () => {
monitor,
metric,
realtimeGroups: [],
- historyRequests: [{ metric, history: '12W' }],
+ historyRequests: [{ metric, history: '12W', interval: true }],
metricKey: metric.key,
refreshSeconds: 30
});
@@ -83,7 +83,7 @@ describe('useMonitorMetricData refresh interval', () => {
expect(api.loadFavoriteMetrics).toHaveBeenCalledWith(7, signal);
expect(api.loadRealtimeMetric).toHaveBeenCalledWith(7, metric, signal);
- expect(api.loadHistoryMetric).toHaveBeenCalledWith(monitor, metric, '12W', signal);
+ expect(api.loadHistoryMetric).toHaveBeenCalledWith(monitor, metric, '12W', true, signal);
});
it('applies the selected interval to favorites, realtime, and history', () => {
@@ -91,7 +91,7 @@ describe('useMonitorMetricData refresh interval', () => {
monitor,
metric,
realtimeGroups: [],
- historyRequests: [{ metric, history: '30m' }],
+ historyRequests: [{ metric, history: '30m', interval: false }],
metricKey: metric.key,
refreshSeconds: 30
});
@@ -108,7 +108,7 @@ describe('useMonitorMetricData refresh interval', () => {
monitor,
metric,
realtimeGroups: [],
- historyRequests: [{ metric, history: '30m' }],
+ historyRequests: [{ metric, history: '30m', interval: false }],
metricKey: metric.key,
refreshSeconds: 0
});
@@ -143,7 +143,7 @@ describe('useMonitorMetricData refresh interval', () => {
monitor,
metric,
realtimeGroups: [],
- historyRequests: [{ metric, history: '12W' }],
+ historyRequests: [{ metric, history: '12W', interval: true }],
metricKey: metric.key,
refreshSeconds: 30
});
@@ -158,7 +158,8 @@ describe('useMonitorMetricData refresh interval', () => {
'website',
undefined,
'summary.value',
- '12W'
+ '12W',
+ true
]);
});
});
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-data.ts b/web-app/src/features/monitor/controller/use-monitor-metric-data.ts
index aeba7c7090..00162cca0a 100644
--- a/web-app/src/features/monitor/controller/use-monitor-metric-data.ts
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-data.ts
@@ -15,7 +15,7 @@ export function useMonitorMetricData(input: {
monitor: Monitor | undefined;
metric: MonitorMetricOption | undefined;
realtimeGroups: Array<{ group: string }>;
- historyRequests: Array<{ metric: MonitorMetricOption; history: MonitorMetricHistory }>;
+ historyRequests: Array<{ metric: MonitorMetricOption; history: MonitorMetricHistory; interval: boolean }>;
metricKey: string;
refreshSeconds: MonitorDetailRefreshSeconds;
}) {
@@ -33,7 +33,14 @@ export function useMonitorMetricData(input: {
});
const historyQueries = useQueries({
queries: historyRequests.map(request =>
- historyMetricQueryOptions(monitor, request.metric, request.metric.key, request.history, refetchInterval)
+ historyMetricQueryOptions(
+ monitor,
+ request.metric,
+ request.metric.key,
+ request.history,
+ request.interval,
+ refetchInterval
+ )
)
});
const historyCharts = historyRequests.map((request, index) => ({ ...request, query: historyQueries[index]! }));
@@ -78,13 +85,14 @@ function historyMetricQueryOptions(
metric: MonitorMetricOption | undefined,
metricKey: string,
history: MonitorMetricHistory,
+ interval: boolean,
refetchInterval: number | false
) {
return {
- queryKey: monitorQueryKeys.history(monitor, metricKey, history),
+ queryKey: monitorQueryKeys.history(monitor, metricKey, history, interval),
queryFn:
monitor && metric
- ? ({ signal }: QueryFunctionContext) => loadHistoryMetric(monitor, metric, history, signal)
+ ? ({ signal }: QueryFunctionContext) => loadHistoryMetric(monitor, metric, history, interval, signal)
: skipToken,
refetchInterval: activeRefreshInterval(Boolean(monitor && metric), refetchInterval)
} as const;
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-layout-controller.test.tsx b/web-app/src/features/monitor/controller/use-monitor-metric-layout-controller.test.tsx
new file mode 100644
index 0000000000..8750b0260e
--- /dev/null
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-layout-controller.test.tsx
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ApiMessageError } from '@/core/http/api-message';
+
+const api = vi.hoisted(() => ({
+ loadMonitorMetricLayout: vi.fn(),
+ resetMonitorMetricLayout: vi.fn(),
+ saveMonitorMetricLayout: vi.fn()
+}));
+const notifications = vi.hoisted(() => ({
+ error: vi.fn(),
+ success: vi.fn(),
+ warning: vi.fn()
+}));
+
+vi.mock('../api/monitor-metric-layout-api', () => api);
+vi.mock('antd', () => ({ App: { useApp: () => ({ message: notifications }) } }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+import { useMonitorMetricLayoutController } from './use-monitor-metric-layout-controller';
+
+describe('useMonitorMetricLayoutController', () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it('falls back to automatic geometry without blocking metric data when the read is unavailable', async () => {
+ api.loadMonitorMetricLayout.mockRejectedValue(new ApiMessageError('redacted', { status: 503 }));
+ const { result } = renderHook(() => useMonitorMetricLayoutController('mysql', ['basic', 'status']), {
+ wrapper: wrapper()
+ });
+
+ await waitFor(() => expect(result.current.state.readState).toBe('unavailable'));
+ expect(result.current.state.layout.items.map(item => item.group)).toEqual(['basic', 'status']);
+ expect(result.current.state.editing).toBe(false);
+ });
+
+ it('cancels an unsaved draft without changing the visible layout', async () => {
+ api.loadMonitorMetricLayout.mockResolvedValue(saved());
+ const { result } = renderHook(() => useMonitorMetricLayoutController('mysql', ['basic', 'status']), {
+ wrapper: wrapper()
+ });
+ await waitFor(() => expect(result.current.state.readState).toBe('ready'));
+
+ act(() => result.current.actions.beginEdit());
+ act(() =>
+ result.current.actions.changeItems([
+ { group: 'basic', x: 0, y: 0, w: 12, h: 16, collapsed: false, order: 0 },
+ { group: 'status', x: 0, y: 16, w: 12, h: 10, collapsed: false, order: 1 }
+ ])
+ );
+ act(() => result.current.actions.cancelEdit());
+
+ expect(result.current.state.layout.items[0]).toMatchObject({ group: 'basic', w: 6, h: 10 });
+ });
+
+ it('saves with the loaded revision and exits edit mode only after confirmation', async () => {
+ api.loadMonitorMetricLayout.mockResolvedValue(saved());
+ api.saveMonitorMetricLayout.mockResolvedValue({ ...saved(), revision: 'layout-r2' });
+ const { result } = renderHook(() => useMonitorMetricLayoutController('mysql', ['basic', 'status']), {
+ wrapper: wrapper()
+ });
+ await waitFor(() => expect(result.current.state.readState).toBe('ready'));
+
+ act(() => result.current.actions.beginEdit());
+ await act(async () => result.current.actions.save());
+
+ expect(api.saveMonitorMetricLayout).toHaveBeenCalledWith(
+ 'mysql',
+ expect.objectContaining({ expectedRevision: 'layout-r1', schemaVersion: 1, mode: 'custom' })
+ );
+ await waitFor(() => expect(result.current.state.editing).toBe(false));
+ expect(result.current.state.revision).toBe('layout-r2');
+ });
+
+ it('keeps the draft open and reloads canonical state after a cross-tab conflict', async () => {
+ api.loadMonitorMetricLayout.mockResolvedValue(saved());
+ api.saveMonitorMetricLayout.mockRejectedValue(new ApiMessageError('redacted', { status: 409 }));
+ const { result } = renderHook(() => useMonitorMetricLayoutController('mysql', ['basic', 'status']), {
+ wrapper: wrapper()
+ });
+ await waitFor(() => expect(result.current.state.readState).toBe('ready'));
+
+ act(() => result.current.actions.beginEdit());
+ await act(async () => result.current.actions.save());
+
+ expect(result.current.state.editing).toBe(true);
+ expect(notifications.warning).toHaveBeenCalledWith('monitorMetrics.layout.conflict');
+ expect(api.loadMonitorMetricLayout).toHaveBeenCalledTimes(2);
+ });
+});
+
+function saved() {
+ return {
+ application: 'mysql',
+ revision: 'layout-r1',
+ schemaVersion: 1 as const,
+ mode: 'custom' as const,
+ columns: 12 as const,
+ items: [
+ { group: 'basic', x: 0, y: 0, w: 6, h: 10, collapsed: false, order: 0 },
+ { group: 'status', x: 6, y: 0, w: 6, h: 10, collapsed: false, order: 1 }
+ ],
+ historyDock: { collapsed: false, height: 12 }
+ };
+}
+
+function wrapper() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ return function Wrapper({ children }: PropsWithChildren) {
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+ };
+}
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-layout-controller.ts b/web-app/src/features/monitor/controller/use-monitor-metric-layout-controller.ts
new file mode 100644
index 0000000000..2ed521d02b
--- /dev/null
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-layout-controller.ts
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { skipToken, useQuery, useQueryClient } from '@tanstack/react-query';
+import { App } from 'antd';
+import type { Dispatch, SetStateAction } from 'react';
+import { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ApiMessageError } from '@/core/http/api-message';
+
+import {
+ loadMonitorMetricLayout,
+ resetMonitorMetricLayout,
+ saveMonitorMetricLayout
+} from '../api/monitor-metric-layout-api';
+import { MonitorMetricLayoutContractError } from '../api/monitor-metric-layout-schema';
+import {
+ mergeMonitorMetricLayout,
+ snapMonitorMetricLayoutItems,
+ type MonitorMetricHistoryDock,
+ type MonitorMetricLayoutDocument,
+ type MonitorMetricLayoutItem
+} from '../model/monitor-metric-layout-model';
+import { monitorQueryKeys } from './monitor-query-keys';
+
+export function useMonitorMetricLayoutController(application: string | undefined, groups: string[]) {
+ const resource = useLayoutResource(application);
+ const [editingApplication, setEditingApplication] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const [draft, setDraft] = useState<MonitorMetricLayoutDocument | null>(null);
+ const editing = application !== undefined && editingApplication === application;
+ const canonical = useMemo(() => mergeMonitorMetricLayout(resource.data, groups), [groups, resource.data]);
+ const layout = editing && draft ? draft : canonical;
+ const commandInput = { application, resource, saving, setSaving, setEditingApplication, setDraft };
+ const save = useSaveLayoutCommand({ ...commandInput, draft });
+ const reset = useResetLayoutCommand(commandInput);
+
+ return {
+ state: {
+ readState: readState(resource.error, resource.isPending),
+ editing,
+ saving,
+ revision: resource.data?.revision ?? 'missing',
+ hasSavedLayout: Boolean(resource.data),
+ layout
+ },
+ actions: {
+ beginEdit: () => {
+ setDraft({ ...canonical, mode: 'custom', items: canonical.items.map(item => ({ ...item })) });
+ setEditingApplication(application ?? null);
+ },
+ cancelEdit: () => {
+ setEditingApplication(null);
+ setDraft(null);
+ },
+ changeItems: (items: MonitorMetricLayoutItem[]) =>
+ setDraft(current =>
+ current ? { ...current, mode: 'custom', items: snapMonitorMetricLayoutItems(items) } : current
+ ),
+ changeHistoryDock: (historyDock: MonitorMetricHistoryDock) =>
+ setDraft(current => (current ? { ...current, mode: 'custom', historyDock } : current)),
+ save,
+ reset
+ }
+ };
+}
+
+function useLayoutResource(application: string | undefined) {
+ return useQuery({
+ queryKey: monitorQueryKeys.layout(application),
+ queryFn: application ? ({ signal }) => loadMonitorMetricLayout(application, signal) : skipToken,
+ retry: false
+ });
+}
+
+type LayoutCommandInput = {
+ application: string | undefined;
+ resource: ReturnType<typeof useLayoutResource>;
+ saving: boolean;
+ setSaving: Dispatch<SetStateAction<boolean>>;
+ setEditingApplication: Dispatch<SetStateAction<string | null>>;
+ setDraft: Dispatch<SetStateAction<MonitorMetricLayoutDocument | null>>;
+};
+
+function useSaveLayoutCommand(input: LayoutCommandInput & { draft: MonitorMetricLayoutDocument | null }) {
+ const { t } = useTranslation();
+ const { message } = App.useApp();
+ const queryClient = useQueryClient();
+ return async () => {
+ if (!input.application || !input.draft || input.saving) return;
+ input.setSaving(true);
+ try {
+ const saved = await saveMonitorMetricLayout(input.application, {
+ ...input.draft,
+ mode: 'custom',
+ expectedRevision: input.resource.data?.revision ?? 'missing'
+ });
+ queryClient.setQueryData(monitorQueryKeys.layout(input.application), saved);
+ input.setEditingApplication(null);
+ input.setDraft(null);
+ void message.success(t('monitorMetrics.layout.saved'));
+ } catch (error) {
+ await reportLayoutCommandError(error, input.resource.refetch, message, t);
+ } finally {
+ input.setSaving(false);
+ }
+ };
+}
+
+function useResetLayoutCommand(input: LayoutCommandInput) {
+ const { t } = useTranslation();
+ const { message } = App.useApp();
+ const queryClient = useQueryClient();
+ return async () => {
+ if (!input.application || input.saving) return;
+ input.setSaving(true);
+ try {
+ if (input.resource.data) await resetMonitorMetricLayout(input.application, input.resource.data.revision);
+ queryClient.setQueryData(monitorQueryKeys.layout(input.application), null);
+ input.setEditingApplication(null);
+ input.setDraft(null);
+ void message.success(t('monitorMetrics.layout.resetDone'));
+ } catch (error) {
+ await reportLayoutCommandError(error, input.resource.refetch, message, t);
+ } finally {
+ input.setSaving(false);
+ }
+ };
+}
+
+async function reportLayoutCommandError(
+ error: unknown,
+ refetch: () => Promise<unknown>,
+ message: ReturnType<typeof App.useApp>['message'],
+ t: ReturnType<typeof useTranslation>['t']
+) {
+ if (error instanceof ApiMessageError && error.status === 409) {
+ void message.warning(t('monitorMetrics.layout.conflict'));
+ await refetch();
+ } else {
+ void message.error(t('monitorMetrics.layout.saveFailed'));
+ }
+}
+
+function readState(error: unknown, pending: boolean) {
+ if (pending) return 'loading' as const;
+ if (!error) return 'ready' as const;
+ if (error instanceof MonitorMetricLayoutContractError) return 'invalid' as const;
+ if (error instanceof ApiMessageError && (error.status === undefined || error.status >= 500)) {
+ return 'unavailable' as const;
+ }
+ return 'error' as const;
+}
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-sources.ts b/web-app/src/features/monitor/controller/use-monitor-metric-sources.ts
index 4fdc1146c1..147dbad834 100644
--- a/web-app/src/features/monitor/controller/use-monitor-metric-sources.ts
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-sources.ts
@@ -49,8 +49,20 @@ function useRealtimeGroupSelection(monitorId: number | undefined, definitions: M
setSelection({ sourceKey, visibleCount });
}
return {
+ names: groups.map(group => group.group),
visible: groups.slice(0, visibleCount),
hasMore: visibleCount < groups.length,
+ reveal: (group: string) => {
+ const index = groups.findIndex(candidate => candidate.group === group);
+ if (index < 0) return;
+ setSelection(current => ({
+ sourceKey,
+ visibleCount: Math.max(
+ current.sourceKey === sourceKey ? current.visibleCount : realtimeGroupPageSize,
+ index + 1
+ )
+ }));
+ },
loadMore: () =>
setSelection(current => ({
sourceKey,
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.test.tsx b/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.test.tsx
index e011ccb7ac..901d1f02d3 100644
--- a/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.test.tsx
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.test.tsx
@@ -132,8 +132,8 @@ describe('useMonitorMetricWorkbenchController', () => {
);
});
- it('exposes the canonical favorite collection without hiding retired metric tokens', async () => {
- api.loadFavoriteMetrics.mockResolvedValue(['retired.value', 'summary.value']);
+ it('exposes group favorites without hiding retired field tokens', async () => {
+ api.loadFavoriteMetrics.mockResolvedValue(['retired.value', 'summary']);
const view = renderController(monitor(), [], '/monitors/7');
await waitFor(() =>
@@ -141,7 +141,7 @@ describe('useMonitorMetricWorkbenchController', () => {
kind: 'ready',
items: [
{ key: 'retired.value', available: false },
- { key: 'summary.value', available: true }
+ { key: 'summary', available: true }
]
})
);
@@ -183,6 +183,7 @@ describe('useMonitorMetricWorkbenchController', () => {
expect.objectContaining({ id: 7 }),
expect.objectContaining({ key: 'group-1.value' }),
'30m',
+ false,
expect.any(AbortSignal)
);
@@ -192,10 +193,24 @@ describe('useMonitorMetricWorkbenchController', () => {
expect.objectContaining({ id: 7 }),
expect.objectContaining({ key: 'group-1.value' }),
'12W',
+ false,
expect.any(AbortSignal)
)
);
expect(view.result.current.controller.state.historyCharts[0]?.history).toBe('12W');
+ expect(view.result.current.controller.state.historyCharts[0]?.interval).toBe(false);
+
+ act(() => view.result.current.controller.actions.setHistoryChartMode('group-1.value', true));
+ await waitFor(() =>
+ expect(api.loadHistoryMetric).toHaveBeenLastCalledWith(
+ expect.objectContaining({ id: 7 }),
+ expect.objectContaining({ key: 'group-1.value' }),
+ '12W',
+ true,
+ expect.any(AbortSignal)
+ )
+ );
+ expect(view.result.current.controller.state.historyCharts[0]?.interval).toBe(true);
act(() => view.result.current.controller.actions.loadMoreHistoryCharts());
await waitFor(() => expect(view.result.current.controller.state.historyCharts).toHaveLength(8));
@@ -260,6 +275,25 @@ describe('useMonitorMetricWorkbenchController', () => {
);
});
+ it('does not promote a field token to the whole-group favorite', async () => {
+ api.loadFavoriteMetrics.mockResolvedValueOnce(['summary.value']).mockResolvedValueOnce(['summary']);
+ const view = renderController(monitor(), [], '/monitors/7');
+
+ await waitFor(() =>
+ expect(view.result.current.controller.state.realtimeGroups[0]).toMatchObject({
+ group: 'summary',
+ favorite: { kind: 'ready', value: false }
+ })
+ );
+ expect(view.result.current.controller.state.favoriteCollection).toEqual({
+ kind: 'ready',
+ items: [{ key: 'summary.value', available: false }]
+ });
+ await act(() => view.result.current.controller.actions.toggleRealtimeFavorite('summary'));
+
+ expect(api.updateFavoriteMetric).toHaveBeenCalledWith(7, 'summary', true);
+ });
+
it('keeps refresh inert until monitor and metric context is available', async () => {
const view = renderController(undefined, [], '/monitors/7');
@@ -349,7 +383,7 @@ describe('useMonitorMetricWorkbenchController', () => {
expect(view.result.current.controller.state.favoriteCollection).toEqual({
kind: 'ready',
- items: [{ key: 'identity.version', available: true }]
+ items: [{ key: 'identity', available: true }]
});
await act(() => view.result.current.controller.actions.toggleFavorite());
@@ -392,6 +426,7 @@ describe('useMonitorMetricWorkbenchController', () => {
expect.objectContaining({ id: 7 }),
expect.objectContaining({ key: 'summary.value' }),
'12W',
+ true,
expect.any(AbortSignal)
);
vi.clearAllMocks();
@@ -445,13 +480,13 @@ describe('useMonitorMetricWorkbenchController', () => {
});
it('marks favorite ready only after canonical reread convergence', async () => {
- api.loadFavoriteMetrics.mockResolvedValueOnce([]).mockResolvedValueOnce(['summary.value']);
+ api.loadFavoriteMetrics.mockResolvedValueOnce([]).mockResolvedValueOnce(['summary']);
const view = renderController(monitor(), [], '/monitors/7');
await waitFor(() =>
expect(view.result.current.controller.state.favorite).toMatchObject({ kind: 'ready', value: false })
);
await act(() => view.result.current.controller.actions.toggleFavorite());
- expect(api.updateFavoriteMetric).toHaveBeenCalledWith(7, 'summary.value', true);
+ expect(api.updateFavoriteMetric).toHaveBeenCalledWith(7, 'summary', true);
expect(api.loadFavoriteMetrics).toHaveBeenCalledTimes(2);
expect(view.result.current.controller.state.favorite).toMatchObject({ kind: 'ready', value: true });
});
@@ -544,7 +579,7 @@ describe('useMonitorMetricWorkbenchController', () => {
});
expect(view.result.current.controller.state.favoriteBusy).toBe(true);
- api.loadFavoriteMetrics.mockResolvedValue(['summary.value']);
+ api.loadFavoriteMetrics.mockResolvedValue(['summary']);
act(() => view.result.current.controller.actions.refresh());
await waitFor(() => {
expect(view.result.current.controller.state.favorite).toMatchObject({ kind: 'ready', value: true });
@@ -581,7 +616,7 @@ describe('useMonitorMetricWorkbenchController', () => {
await waitFor(() => expect(view.result.current.controller.state.metricKey).toBe('summary.value'));
expect(view.result.current.controller.state.favoriteBusy).toBe(false);
api.updateFavoriteMetric.mockResolvedValue(undefined);
- api.loadFavoriteMetrics.mockResolvedValueOnce(['summary.value']);
+ api.loadFavoriteMetrics.mockResolvedValueOnce(['summary']);
await act(() => view.result.current.controller.actions.toggleFavorite());
expect(api.updateFavoriteMetric).toHaveBeenCalledTimes(2);
expect(view.result.current.controller.state.favoriteBusy).toBe(false);
diff --git a/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.ts b/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.ts
index ad995fe6b3..3ed6765562 100644
--- a/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.ts
+++ b/web-app/src/features/monitor/controller/use-monitor-metric-workbench-controller.ts
@@ -23,7 +23,9 @@ import {
type MonitorMetricNotifications as Notifications
} from './use-monitor-favorite-mutation';
import { buildMonitorMetricWorkbenchResult } from './monitor-metric-workbench-result';
+import { buildWorkbenchActions } from './monitor-metric-workbench-actions';
import { useMonitorMetricData } from './use-monitor-metric-data';
+import { useMonitorMetricLayoutController } from './use-monitor-metric-layout-controller';
import { useMonitorMetricSources } from './use-monitor-metric-sources';
type MonitorMetricWorkbenchOptions = {
@@ -37,6 +39,14 @@ export function useMonitorMetricWorkbenchController(
embedded: MonitorDetailMetric[],
options: MonitorMetricWorkbenchOptions
): MonitorMetricWorkbenchController {
+ return composeMonitorMetricWorkbench(useMonitorMetricContext(monitor, embedded, options), options.refreshControl);
+}
+
+function useMonitorMetricContext(
+ monitor: Monitor | undefined,
+ embedded: MonitorDetailMetric[],
+ options: MonitorMetricWorkbenchOptions
+) {
const { t } = useTranslation();
const { message: appMessage } = App.useApp();
const queryClient = useQueryClient();
@@ -55,6 +65,7 @@ export function useMonitorMetricWorkbenchController(
t
});
const realtimeGroups = buildRealtimeGroupEvidence(queries, queries.favorites, favoriteMutation.busyMetricKey);
+ const layout = useMonitorMetricLayoutController(monitorLayoutApplication(monitor), realtimeSelection.names);
const historyCharts = buildHistoryChartEvidence(historySelection, queries);
const selectedHistoryChart = buildSelectedHistoryChart(metric, historySelection, queries);
const actions = buildWorkbenchActions({
@@ -68,28 +79,54 @@ export function useMonitorMetricWorkbenchController(
historySelection,
refreshDetail: options.refreshDetail
});
- return buildMonitorMetricWorkbenchResult({
- catalog,
- metricKey,
- history,
- historySupported,
- favorite,
- favoriteCollection,
- favoriteBusy: favoriteMutation.busyMetricKey === (metric?.historySupported === false ? metric.group : metricKey),
+ const sources = { catalog, history, metric, metricKey, urlActions, queries, realtimeSelection, historySelection };
+ const evidence = { favorite, favoriteCollection, historical, historySupported, realtime };
+ return {
+ ...sources,
+ ...evidence,
+ monitor,
+ favoriteMutation,
realtimeGroups,
- hasMoreRealtimeGroups: realtimeSelection.hasMore,
- historyAvailability: historySelection.availability,
+ layout,
historyCharts,
selectedHistoryChart,
- hasMoreHistoryCharts: historySelection.hasMore,
- realtime,
- historical,
- refreshControl: options.refreshControl,
- urlActions,
- ...actions
+ actions
+ };
+}
+
+function composeMonitorMetricWorkbench(
+ context: ReturnType<typeof useMonitorMetricContext>,
+ refreshControl: MonitorDetailRefreshControl
+) {
+ return buildMonitorMetricWorkbenchResult({
+ catalog: context.catalog,
+ metricKey: context.metricKey,
+ history: context.history,
+ historySupported: context.historySupported,
+ favorite: context.favorite,
+ favoriteCollection: context.favoriteCollection,
+ favoriteBusy: context.favoriteMutation.busyMetricKey === context.metric?.group,
+ realtimeGroupNames: context.realtimeSelection.names,
+ realtimeGroups: context.realtimeGroups,
+ hasMoreRealtimeGroups: context.realtimeSelection.hasMore,
+ historyAvailability: context.historySelection.availability,
+ historyCharts: context.historyCharts,
+ selectedHistoryChart: context.selectedHistoryChart,
+ hasMoreHistoryCharts: context.historySelection.hasMore,
+ realtime: context.realtime,
+ historical: context.historical,
+ layout: context.layout.state,
+ layoutActions: context.layout.actions,
+ refreshControl,
+ urlActions: context.urlActions,
+ ...context.actions
});
}
+function monitorLayoutApplication(monitor: Monitor | undefined) {
+ return monitor?.scrape && monitor.scrape !== 'static' ? monitor.scrape : monitor?.app;
+}
+
function buildRealtimeGroupEvidence(
queries: ReturnType<typeof useMonitorMetricData>,
favorites: ReturnType<typeof useMonitorMetricData>['favorites'],
@@ -102,66 +139,3 @@ function buildRealtimeGroupEvidence(
result: metricEvidence(query, data => monitorRealtimeRows(data))
}));
}
-
-function buildWorkbenchActions(input: {
- monitor: Monitor | undefined;
- metric: Parameters<typeof useMonitorMetricData>[0]['metric'];
- favorite: MonitorMetricWorkbenchController['state']['favorite'];
- realtimeGroups: MonitorMetricWorkbenchController['state']['realtimeGroups'];
- queries: ReturnType<typeof useMonitorMetricData>;
- favoriteMutation: ReturnType<typeof useMonitorFavoriteMutation>;
- realtimeSelection: ReturnType<typeof useMonitorMetricSources>['realtimeSelection'];
- historySelection: ReturnType<typeof useMonitorMetricSources>['historySelection'];
- refreshDetail: () => void;
-}) {
- const selectedToken = input.metric?.historySupported === false ? input.metric.group : (input.metric?.key ?? '');
- return {
- toggleFavorite: () => input.favoriteMutation.toggle(selectedToken, input.favorite),
- toggleRealtimeFavorite: (group: string) => {
- const current = input.realtimeGroups.find(item => item.group === group);
- return current ? input.favoriteMutation.toggle(group, current.favorite) : Promise.resolve();
- },
- loadMoreRealtimeGroups: input.realtimeSelection.loadMore,
- activateHistoryChart: input.historySelection.activate,
- setHistoryChartRange: input.historySelection.setRange,
- refreshHistoryChart: (metricKey: string) => {
- const chart = input.queries.historyCharts.find(item => item.metric.key === metricKey);
- if (chart) void chart.query.refetch();
- else input.historySelection.activate(metricKey);
- },
- loadMoreHistoryCharts: input.historySelection.loadMore,
- refresh: () => {
- input.refreshDetail();
- refreshMonitorMetricQueries(
- input.queries,
- Boolean(input.monitor && (input.metric || input.realtimeGroups.length > 0)),
- input.metric?.group
- );
- }
- } satisfies Pick<
- MonitorMetricWorkbenchController['actions'],
- | 'toggleFavorite'
- | 'toggleRealtimeFavorite'
- | 'loadMoreRealtimeGroups'
- | 'activateHistoryChart'
- | 'setHistoryChartRange'
- | 'refreshHistoryChart'
- | 'loadMoreHistoryCharts'
- | 'refresh'
- >;
-}
-
-function refreshMonitorMetricQueries(
- queries: ReturnType<typeof useMonitorMetricData>,
- canRefresh: boolean,
- selectedGroup: string | undefined
-) {
- // Refresh is one operator action, so do not issue a partial request set under incomplete context.
- if (!canRefresh) return;
- void queries.favorites.refetch();
- if (selectedGroup && !queries.realtimeGroups.some(item => item.group === selectedGroup)) {
- void queries.realtime.refetch();
- }
- for (const group of queries.realtimeGroups) void group.query.refetch();
- for (const chart of queries.historyCharts) void chart.query.refetch();
-}
diff --git a/web-app/src/features/monitor/model/monitor-detail-model.test.ts b/web-app/src/features/monitor/model/monitor-detail-model.test.ts
index 68728a6837..727d8d379e 100644
--- a/web-app/src/features/monitor/model/monitor-detail-model.test.ts
+++ b/web-app/src/features/monitor/model/monitor-detail-model.test.ts
@@ -37,7 +37,7 @@ import {
} from './monitor-detail-model';
describe('monitor detail model', () => {
- it('keeps exact history wire tokens and aggregates only uppercase week ranges', () => {
+ it('keeps exact history wire tokens and Angular-compatible initial interval defaults', () => {
expect(monitorMetricHistoryRanges).toEqual(['30m', '1h', '6h', '24h', '1W', '4W', '12W']);
expect(monitorMetricHistoryRanges.map(monitorMetricHistoryUsesInterval)).toEqual([
false,
@@ -201,7 +201,8 @@ describe('monitor detail model', () => {
field: 'responseTime',
unit: 'ms',
value: '12',
- time: 0
+ time: 0,
+ collectedAt: 2000
},
{
key: '0:status',
@@ -209,7 +210,8 @@ describe('monitor detail model', () => {
field: 'status',
unit: null,
value: 'UP',
- time: 2000
+ time: 2000,
+ collectedAt: 2000
},
{
key: '0:message',
@@ -217,7 +219,8 @@ describe('monitor detail model', () => {
field: 'message',
unit: null,
value: '—',
- time: 2000
+ time: 2000,
+ collectedAt: 2000
}
]);
expect(
@@ -238,7 +241,8 @@ describe('monitor detail model', () => {
field: 'status',
unit: null,
value: 'UP',
- time: null
+ time: null,
+ collectedAt: null
}
]);
});
diff --git a/web-app/src/features/monitor/model/monitor-detail-model.ts b/web-app/src/features/monitor/model/monitor-detail-model.ts
index b721c4df74..4e22be569a 100644
--- a/web-app/src/features/monitor/model/monitor-detail-model.ts
+++ b/web-app/src/features/monitor/model/monitor-detail-model.ts
@@ -27,6 +27,7 @@ import type {
MonitorGrafanaDashboard
} from './monitor-contract';
import type { MonitorHistorySeries } from './monitor-history-model';
+import type { MonitorMetricLayoutActions, MonitorMetricLayoutState } from './monitor-metric-layout-model';
export { monitorHistoryMetrics, monitorHistorySeries } from './monitor-history-model';
@@ -132,6 +133,7 @@ export type MonitorHistoryAvailability = {
export type MonitorHistoryChart = {
metric: MonitorMetricOption;
history: MonitorMetricHistory;
+ interval: boolean;
result: MonitorMetricRowsEvidence<MonitorHistorySeries>;
};
export type MonitorMetricWorkbenchController = {
@@ -144,6 +146,7 @@ export type MonitorMetricWorkbenchController = {
favorite: MonitorMetricFavoriteEvidence;
favoriteCollection: MonitorMetricFavoriteCollectionEvidence;
favoriteBusy: boolean;
+ realtimeGroupNames: string[];
realtimeGroups: MonitorRealtimeGroup[];
hasMoreRealtimeGroups: boolean;
historyAvailability: MonitorHistoryAvailability;
@@ -152,6 +155,7 @@ export type MonitorMetricWorkbenchController = {
hasMoreHistoryCharts: boolean;
realtime: MonitorMetricRowsEvidence<ReturnType<typeof monitorRealtimeRows>[number]>;
historical: MonitorMetricRowsEvidence<ReturnType<typeof monitorHistoryRows>[number]>;
+ layout: MonitorMetricLayoutState;
};
actions: {
setMetric: (value: string) => void;
@@ -159,12 +163,15 @@ export type MonitorMetricWorkbenchController = {
setRefreshSeconds: (value: MonitorDetailRefreshChoice) => void;
toggleFavorite: () => Promise<void>;
toggleRealtimeFavorite: (group: string) => Promise<void>;
+ revealRealtimeGroup: (group: string) => void;
loadMoreRealtimeGroups: () => void;
activateHistoryChart: (metricKey: string) => void;
setHistoryChartRange: (metricKey: string, value: MonitorMetricHistory) => void;
+ setHistoryChartMode: (metricKey: string, interval: boolean) => void;
refreshHistoryChart: (metricKey: string) => void;
loadMoreHistoryCharts: () => void;
refresh: () => void;
+ layout: MonitorMetricLayoutActions;
};
};
@@ -231,7 +238,8 @@ export function monitorRealtimeRows(data: MonitorRealtimeMetric) {
field: field.name,
unit: field.unit,
value: displayMetricValue(value),
- time: value.time ?? data.time ?? null
+ time: value.time ?? data.time ?? null,
+ collectedAt: data.time
}
]
: [];
diff --git a/web-app/src/features/monitor/model/monitor-metric-layout-model.test.ts b/web-app/src/features/monitor/model/monitor-metric-layout-model.test.ts
new file mode 100644
index 0000000000..5805a62939
--- /dev/null
+++ b/web-app/src/features/monitor/model/monitor-metric-layout-model.test.ts
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildDefaultMonitorMetricLayout,
+ mergeMonitorMetricLayout,
+ projectMonitorMetricLayout,
+ snapMonitorMetricLayoutItems
+} from './monitor-metric-layout-model';
+
+describe('monitor metric layout model', () => {
+ it('creates a compact three-column canonical desktop intent', () => {
+ const layout = buildDefaultMonitorMetricLayout(['basic', 'status', 'innodb', 'performance']);
+
+ expect(layout).toMatchObject({ schemaVersion: 1, mode: 'auto', columns: 12 });
+ expect(layout.items.map(item => [item.group, item.x, item.y, item.w, item.order])).toEqual([
+ ['basic', 0, 0, 4, 0],
+ ['status', 4, 0, 4, 1],
+ ['innodb', 8, 0, 4, 2],
+ ['performance', 0, 10, 4, 3]
+ ]);
+ });
+
+ it('keeps saved geometry while appending newly discovered groups without overlap', () => {
+ const merged = mergeMonitorMetricLayout(
+ {
+ application: 'mysql',
+ revision: 'r1',
+ schemaVersion: 1,
+ mode: 'custom',
+ columns: 12,
+ items: [
+ { group: 'status', x: 0, y: 0, w: 8, h: 12, collapsed: false, order: 0 },
+ { group: 'basic', x: 8, y: 0, w: 4, h: 10, collapsed: false, order: 1 }
+ ],
+ historyDock: { collapsed: false, height: 12 }
+ },
+ ['basic', 'status', 'new_group']
+ );
+
+ expect(merged.items.slice(0, 2).map(item => item.group)).toEqual(['status', 'basic']);
+ expect(merged.items[2]).toMatchObject({ group: 'new_group', y: 12, order: 2 });
+ });
+
+ it('projects without mutating canonical desktop geometry', () => {
+ const canonical = buildDefaultMonitorMetricLayout(['a', 'b', 'c']);
+
+ expect(projectMonitorMetricLayout(canonical.items, 'tablet')).toEqual([
+ expect.objectContaining({ group: 'a', x: 0, y: 0, w: 3 }),
+ expect.objectContaining({ group: 'b', x: 3, y: 0, w: 3 }),
+ expect.objectContaining({ group: 'c', x: 0, y: 10, w: 3 })
+ ]);
+ expect(projectMonitorMetricLayout(canonical.items, 'narrow')).toEqual([
+ expect.objectContaining({ group: 'a', x: 0, y: 0, w: 1 }),
+ expect.objectContaining({ group: 'b', x: 0, y: 10, w: 1 }),
+ expect.objectContaining({ group: 'c', x: 0, y: 20, w: 1 })
+ ]);
+ expect(canonical.items[1]).toMatchObject({ x: 4, y: 0, w: 4 });
+ });
+
+ it('snaps arbitrary drag widths and updates narrow-screen order deterministically', () => {
+ const snapped = snapMonitorMetricLayoutItems([
+ { group: 'b', x: 6, y: 0, w: 5, h: 9, collapsed: false, order: 1 },
+ { group: 'a', x: 0, y: 0, w: 7, h: 13, collapsed: false, order: 0 }
+ ]);
+
+ expect(snapped).toEqual([
+ { group: 'a', x: 0, y: 0, w: 8, h: 13, collapsed: false, order: 0 },
+ { group: 'b', x: 6, y: 13, w: 6, h: 9, collapsed: false, order: 1 }
+ ]);
+ });
+});
diff --git a/web-app/src/features/monitor/model/monitor-metric-layout-model.ts b/web-app/src/features/monitor/model/monitor-metric-layout-model.ts
new file mode 100644
index 0000000000..5f0c7e070e
--- /dev/null
+++ b/web-app/src/features/monitor/model/monitor-metric-layout-model.ts
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0.
+ */
+
+const monitorMetricLayoutColumns = 12 as const;
+const monitorMetricLayoutSchemaVersion = 1 as const;
+const monitorMetricLayoutWidths = [4, 6, 8, 12] as const;
+type MonitorMetricLayoutMode = 'auto' | 'custom';
+export type MonitorMetricLayoutViewport = 'desktop' | 'tablet' | 'narrow';
+
+export type MonitorMetricLayoutItem = {
+ group: string;
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ collapsed: boolean;
+ order: number;
+};
+
+export type MonitorMetricHistoryDock = { collapsed: boolean; height: number };
+
+export type MonitorMetricLayoutDocument = {
+ schemaVersion: typeof monitorMetricLayoutSchemaVersion;
+ mode: MonitorMetricLayoutMode;
+ columns: typeof monitorMetricLayoutColumns;
+ items: MonitorMetricLayoutItem[];
+ historyDock: MonitorMetricHistoryDock;
+};
+
+export type MonitorMetricLayoutResource = MonitorMetricLayoutDocument & {
+ application: string;
+ revision: string;
+};
+
+export type MonitorMetricLayoutState = {
+ readState: 'loading' | 'ready' | 'unavailable' | 'invalid' | 'error';
+ editing: boolean;
+ saving: boolean;
+ revision: string;
+ hasSavedLayout: boolean;
+ layout: MonitorMetricLayoutDocument;
+};
+
+export type MonitorMetricLayoutActions = {
+ beginEdit: () => void;
+ cancelEdit: () => void;
+ changeItems: (items: MonitorMetricLayoutItem[]) => void;
+ changeHistoryDock: (historyDock: MonitorMetricHistoryDock) => void;
+ save: () => Promise<void>;
+ reset: () => Promise<void>;
+};
+
+const defaultCardHeight = 10;
+const defaultCardWidth = 4;
+
+export function buildDefaultMonitorMetricLayout(groups: string[]): MonitorMetricLayoutDocument {
+ return {
+ schemaVersion: monitorMetricLayoutSchemaVersion,
+ mode: 'auto',
+ columns: monitorMetricLayoutColumns,
+ items: uniqueGroups(groups).map((group, index) => ({
+ group,
+ x: (index % 3) * defaultCardWidth,
+ y: Math.floor(index / 3) * defaultCardHeight,
+ w: defaultCardWidth,
+ h: defaultCardHeight,
+ collapsed: false,
+ order: index
+ })),
+ historyDock: { collapsed: false, height: 12 }
+ };
+}
+
+export function mergeMonitorMetricLayout(
+ resource: MonitorMetricLayoutResource | null | undefined,
+ groups: string[]
+): MonitorMetricLayoutDocument {
+ const availableGroups = uniqueGroups(groups);
+ if (!resource || resource.mode === 'auto') return buildDefaultMonitorMetricLayout(availableGroups);
+ const available = new Set(availableGroups);
+ const saved = [...resource.items]
+ .filter(item => available.has(item.group))
+ .sort((left, right) => left.order - right.order || left.y - right.y || left.x - right.x);
+ const present = new Set(saved.map(item => item.group));
+ const bottom = saved.reduce((maximum, item) => Math.max(maximum, item.y + item.h), 0);
+ const appended = availableGroups
+ .filter(group => !present.has(group))
+ .map((group, index) => ({
+ group,
+ x: (index % 3) * defaultCardWidth,
+ y: bottom + Math.floor(index / 3) * defaultCardHeight,
+ w: defaultCardWidth,
+ h: defaultCardHeight,
+ collapsed: false,
+ order: saved.length + index
+ }));
+ return { ...resource, items: [...saved, ...appended] };
+}
+
+export function projectMonitorMetricLayout(items: MonitorMetricLayoutItem[], viewport: MonitorMetricLayoutViewport) {
+ const ordered = [...items].sort((left, right) => left.order - right.order);
+ if (viewport === 'desktop') return ordered.map(item => ({ ...item }));
+ if (viewport === 'narrow') return projectRows(ordered, 1, () => 1);
+ return projectRows(ordered, 2, item => (item.w > 6 ? 6 : 3));
+}
+
+export function snapMonitorMetricLayoutItems(items: MonitorMetricLayoutItem[]) {
+ const normalized = items
+ .map(item => {
+ const width = nearestWidth(item.w);
+ return {
+ ...item,
+ x: clamp(item.x, 0, monitorMetricLayoutColumns - width),
+ y: clamp(item.y, 0, 999),
+ w: width,
+ h: clamp(item.h, item.collapsed ? 4 : 8, 24)
+ };
+ })
+ .sort((left, right) => left.y - right.y || left.x - right.x || left.order - right.order);
+ const placed: MonitorMetricLayoutItem[] = [];
+ for (const [order, item] of normalized.entries()) {
+ const candidate = { ...item, order };
+ while (placed.some(other => overlaps(candidate, other))) {
+ candidate.y = Math.max(...placed.filter(other => overlaps(candidate, other)).map(other => other.y + other.h));
+ }
+ placed.push(candidate);
+ }
+ return placed;
+}
+
+export function mergeMonitorMetricGridChange(
+ canonical: MonitorMetricLayoutItem[],
+ changed: Array<Pick<MonitorMetricLayoutItem, 'group' | 'x' | 'y' | 'w' | 'h'>>
+) {
+ const changes = new Map(changed.map(item => [item.group, item]));
+ return snapMonitorMetricLayoutItems(
+ canonical.map(item => {
+ const change = changes.get(item.group);
+ return change ? { ...item, ...change } : item;
+ })
+ );
+}
+
+export function monitorMetricLayoutViewport(width: number): MonitorMetricLayoutViewport {
+ if (width >= 1_260) return 'desktop';
+ if (width >= 660) return 'tablet';
+ return 'narrow';
+}
+
+function projectRows(
+ items: MonitorMetricLayoutItem[],
+ columnsPerRow: number,
+ widthFor: (item: MonitorMetricLayoutItem) => number
+) {
+ const projected: MonitorMetricLayoutItem[] = [];
+ let rowY = 0;
+ for (let index = 0; index < items.length; index += columnsPerRow) {
+ const row = items.slice(index, index + columnsPerRow);
+ let x = 0;
+ for (const item of row) {
+ const width = widthFor(item);
+ projected.push({ ...item, x, y: rowY, w: width });
+ x += width;
+ }
+ rowY += Math.max(...row.map(item => item.h));
+ }
+ return projected;
+}
+
+function nearestWidth(width: number) {
+ return [...monitorMetricLayoutWidths].sort(
+ (left, right) => Math.abs(left - width) - Math.abs(right - width) || right - left
+ )[0]!;
+}
+
+function overlaps(first: MonitorMetricLayoutItem, second: MonitorMetricLayoutItem) {
+ return (
+ first.x < second.x + second.w &&
+ first.x + first.w > second.x &&
+ first.y < second.y + second.h &&
+ first.y + first.h > second.y
+ );
+}
+
+function uniqueGroups(groups: string[]) {
+ return [...new Set(groups.filter(Boolean))];
+}
+
+function clamp(value: number, minimum: number, maximum: number) {
+ return Math.min(maximum, Math.max(minimum, Math.round(value)));
+}
diff --git a/web-app/src/layout/shell/shell-status-style-contract.test.ts b/web-app/src/layout/shell/shell-status-style-contract.test.ts
index 53f80e59c1..b0e0b887b5 100644
--- a/web-app/src/layout/shell/shell-status-style-contract.test.ts
+++ b/web-app/src/layout/shell/shell-status-style-contract.test.ts
@@ -21,7 +21,7 @@ describe('shell runtime status style contract', () => {
it('defines globally resolvable status tokens without adding raw colors to the shell component', () => {
expect(appStyles).toMatch(/--hb-status-loading:\s*var\(--hb-status-unknown\)/);
- const lightTheme = appStyles.match(/:root\[data-theme='default'\]\s*\{[^}]*\}/)?.[0] ?? '';
+ const lightTheme = appStyles.match(/:root\[data-theme='default'\][^{]*\{[^}]*\}/)?.[0] ?? '';
for (const status of ['available', 'degraded', 'unavailable']) {
expect(appStyles).toMatch(new RegExp(`--hb-status-${status}:\\s*#[\\da-f]{6}`, 'i'));
expect(lightTheme).toMatch(new RegExp(`--hb-status-${status}:\\s*#[\\da-f]{6}`, 'i'));
diff --git a/web-app/src/app/theme/hertzbeat-theme.ts b/web-app/src/shared/theme/hertzbeat-theme.ts
similarity index 100%
rename from web-app/src/app/theme/hertzbeat-theme.ts
rename to web-app/src/shared/theme/hertzbeat-theme.ts
diff --git a/web-app/src/shared/time-series-chart/time-series-chart-runtime.ts b/web-app/src/shared/time-series-chart/time-series-chart-runtime.ts
index 03d58e9d2d..0ec0532354 100644
--- a/web-app/src/shared/time-series-chart/time-series-chart-runtime.ts
+++ b/web-app/src/shared/time-series-chart/time-series-chart-runtime.ts
@@ -32,13 +32,23 @@ export type TimeSeriesChartRenderInput = {
unit?: string | undefined;
series: TimeSeriesChartSeries[];
saveImageTitle?: string | undefined;
+ presentation?: 'area' | 'line' | 'soft-area' | 'monitor-history' | undefined;
};
export type TimeSeriesChartRuntime = {
update: (input: TimeSeriesChartRenderInput) => void;
dispose: () => void;
};
-type ChartColors = { text: string; muted: string; border: string; grid: string; background: string };
+type ChartColors = {
+ text: string;
+ muted: string;
+ border: string;
+ grid: string;
+ background: string;
+ accent: string;
+ available: string;
+ degraded: string;
+};
export function createTimeSeriesChart(
element: HTMLDivElement,
@@ -66,13 +76,14 @@ export function buildTimeSeriesChartOption(
input: TimeSeriesChartRenderInput,
colors: ChartColors
): echarts.EChartsCoreOption {
- const seriesColors = input.series.map((item, index) => seriesColor(item.name, index));
+ const seriesColors = input.series.map((item, index) => seriesColor(item.name, index, colors));
const showLegend = input.series.length > 1;
+ const monitorHistory = input.presentation === 'monitor-history';
return {
animationDuration: 220,
color: seriesColors,
textStyle: { color: colors.text },
- tooltip: chartTooltip(colors),
+ tooltip: chartTooltip(colors, monitorHistory),
legend: chartLegend(showLegend, colors),
toolbox: input.saveImageTitle
? {
@@ -88,29 +99,37 @@ export function buildTimeSeriesChartOption(
}
: undefined,
grid: {
- left: 38,
- right: 24,
- top: chartTop(showLegend, input.unit),
- bottom: input.saveImageTitle ? 92 : 48,
+ left: monitorHistory ? 8 : 38,
+ right: monitorHistory ? 16 : 24,
+ top: chartTop(showLegend, input.unit, monitorHistory),
+ bottom: monitorHistory ? 20 : input.saveImageTitle ? 92 : 48,
containLabel: true
},
- xAxis: timeAxis(input.series, colors),
- yAxis: valueAxis(input.unit, colors),
+ xAxis: timeAxis(input.series, colors, monitorHistory),
+ yAxis: valueAxis(input.unit, colors, input.presentation, input.series),
dataZoom: [
- { type: 'inside', zoomOnMouseWheel: true, moveOnMouseMove: false, moveOnMouseWheel: false },
+ {
+ type: 'inside',
+ zoomOnMouseWheel: true,
+ moveOnMouseMove: monitorHistory,
+ moveOnMouseWheel: false
+ },
...(input.saveImageTitle
? [{ type: 'slider' as const, height: 30, bottom: 18, borderColor: colors.border, showDetail: false }]
: [])
],
- series: chartSeries(input.series, seriesColors)
+ series: chartSeries(input.series, seriesColors, input.presentation)
};
}
-function chartTooltip(colors: ChartColors) {
+function chartTooltip(colors: ChartColors, monitorHistory: boolean) {
return {
trigger: 'axis',
confine: true,
- axisPointer: { type: 'cross', lineStyle: { color: colors.border, type: 'dashed' } },
+ axisPointer: {
+ type: monitorHistory ? 'line' : 'cross',
+ lineStyle: { color: colors.border, type: monitorHistory ? 'solid' : 'dashed' }
+ },
backgroundColor: colors.background,
borderColor: colors.border,
textStyle: { color: colors.text }
@@ -129,38 +148,71 @@ function chartLegend(show: boolean, colors: ChartColors) {
};
}
-function valueAxis(unit: string | undefined, colors: ChartColors) {
+function valueAxis(
+ unit: string | undefined,
+ colors: ChartColors,
+ presentation: TimeSeriesChartRenderInput['presentation'],
+ series: TimeSeriesChartSeries[]
+) {
+ const monitorHistory = presentation === 'monitor-history';
+ const monitorBounds = monitorHistory ? monitorHistoryValueAxisBounds(series) : undefined;
return {
type: 'value',
name: unit,
scale: true,
- minInterval: 1,
+ ...(monitorHistory ? { ...monitorBounds, splitNumber: 3 } : {}),
+ ...(presentation === 'area' ? { minInterval: 1 } : {}),
nameTextStyle: { color: colors.muted },
- axisLabel: { color: colors.muted },
- splitLine: { lineStyle: { color: colors.grid, type: 'dashed' } },
- splitArea: { show: true, areaStyle: { color: ['transparent', colors.grid], opacity: 0.28 } }
+ axisLine: { show: false },
+ axisTick: { show: false },
+ axisLabel: {
+ color: colors.muted,
+ fontSize: monitorHistory ? 10 : undefined,
+ margin: monitorHistory ? 8 : undefined,
+ formatter: monitorHistory ? formatTimeSeriesValue : undefined
+ },
+ splitLine: {
+ lineStyle: {
+ color: colors.grid,
+ type: monitorHistory ? 'solid' : 'dashed',
+ opacity: monitorHistory ? 0.55 : 1
+ }
+ },
+ splitArea:
+ presentation !== 'area'
+ ? { show: false }
+ : { show: true, areaStyle: { color: ['transparent', colors.grid], opacity: 0.28 } }
};
}
-function chartSeries(series: TimeSeriesChartSeries[], colors: string[]) {
+function chartSeries(
+ series: TimeSeriesChartSeries[],
+ colors: string[],
+ presentation: TimeSeriesChartRenderInput['presentation']
+) {
return series.map((item, index) => {
const primary = series.length === 1 || isPrimarySeries(item.name);
+ const monitorHistory = presentation === 'monitor-history';
return {
name: item.name,
type: 'line',
data: item.points,
- showSymbol: false,
- smooth: true,
+ showSymbol: monitorHistory && item.points.length <= 16,
+ symbol: monitorHistory ? 'circle' : undefined,
+ symbolSize: monitorHistory ? 5 : undefined,
+ smooth: !monitorHistory,
sampling: 'lttb',
+ connectNulls: false,
emphasis: { focus: 'series' },
- lineStyle: { width: primary ? 2.4 : 1.8, color: colors[index] },
+ lineStyle: { width: monitorHistory ? (primary ? 2 : 1.6) : primary ? 2.4 : 1.8, color: colors[index] },
itemStyle: { color: colors[index] },
- areaStyle: primary ? primaryAreaStyle(colors[index]!) : undefined
+ areaStyle:
+ primary && presentation !== 'line' ? primaryAreaStyle(colors[index]!, monitorHistory ? 0.1 : 0.2) : undefined
};
});
}
-function timeAxis(series: TimeSeriesChartSeries[], colors: ChartColors) {
+function timeAxis(series: TimeSeriesChartSeries[], colors: ChartColors, monitorHistory: boolean) {
let first: number | undefined;
let last: number | undefined;
for (const item of series) {
@@ -173,7 +225,7 @@ function timeAxis(series: TimeSeriesChartSeries[], colors: ChartColors) {
const range = first === undefined || last === undefined ? 0 : Math.max(last - first, 0);
return {
type: 'time',
- splitNumber: 5,
+ splitNumber: monitorHistory ? 4 : 5,
min: first,
max: last,
axisLine: { lineStyle: { color: colors.border } },
@@ -184,15 +236,16 @@ function timeAxis(series: TimeSeriesChartSeries[], colors: ChartColors) {
margin: 12,
hideOverlap: true,
showMinLabel: true,
- showMaxLabel: true,
+ showMaxLabel: !monitorHistory,
formatter: (value: number) => formatTimeSeriesAxisTickLabel(value, range)
},
splitLine: { show: false }
};
}
-function chartTop(showLegend: boolean, unit: string | undefined) {
- if (showLegend) return 52;
+function chartTop(showLegend: boolean, unit: string | undefined, monitorHistory: boolean) {
+ if (showLegend) return monitorHistory ? 44 : 52;
+ if (monitorHistory) return unit ? 26 : 16;
return unit ? 38 : 28;
}
@@ -203,9 +256,9 @@ export function formatTimeSeriesAxisTickLabel(value: number, rangeMs: number) {
return rangeMs <= 24 * 60 * 60 * 1000 ? time : `${pad(date.getMonth() + 1)}/${pad(date.getDate())} ${time}`;
}
-function primaryAreaStyle(color: string) {
+function primaryAreaStyle(color: string, opacity: number) {
return {
- opacity: 0.2,
+ opacity,
color: {
type: 'linear',
x: 0,
@@ -220,12 +273,35 @@ function primaryAreaStyle(color: string) {
};
}
-function seriesColor(name: string, index: number) {
- const colors = ['#60a5fa', '#a78bfa', '#22d3ee', '#fb7185', '#f97316', '#84cc16'];
- if (name.toLowerCase() === 'min') return '#34d399';
- if (name.toLowerCase() === 'max') return '#fbbf24';
- if (isPrimarySeries(name)) return '#60a5fa';
- return colors[index % colors.length]!;
+function seriesColor(name: string, index: number, colors: ChartColors) {
+ const palette = [colors.accent, '#a78bfa', '#22d3ee', '#fb7185', '#f97316', '#84cc16'];
+ if (name.toLowerCase() === 'min') return colors.available;
+ if (name.toLowerCase() === 'max') return colors.degraded;
+ if (isPrimarySeries(name)) return colors.accent;
+ return palette[index % palette.length]!;
+}
+
+function monitorHistoryValueAxisBounds(series: TimeSeriesChartSeries[]) {
+ const values = series.flatMap(item => item.points.map(([, value]) => value)).filter(Number.isFinite);
+ if (values.length === 0) return undefined;
+ const minimum = Math.min(...values);
+ const maximum = Math.max(...values);
+ const span = maximum - minimum;
+ if (span !== 0) {
+ const padding = Math.max(span * 0.08, 0.01);
+ return { min: minimum - padding, max: maximum + padding };
+ }
+ const padding = Math.max(Math.abs(minimum) * 0.01, 1);
+ const lower = Math.floor(minimum - padding);
+ const upper = Math.ceil(maximum + padding);
+ return { min: lower, max: upper, interval: (upper - lower) / 2 };
+}
+
+function formatTimeSeriesValue(value: number) {
+ if (!Number.isFinite(value)) return '';
+ const absolute = Math.abs(value);
+ if (absolute < 1000) return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/\.?0+$/, '');
+ return new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 }).format(value);
}
function isPrimarySeries(name: string) {
@@ -245,6 +321,9 @@ function chartColors(element: HTMLElement): ChartColors {
muted: read('--hb-text-secondary', '#8d96a8'),
border: read('--hb-border-subtle', '#28303d'),
grid: read('--hb-border-muted', '#202733'),
- background: read('--hb-bg-raised', '#11151c')
+ background: read('--hb-bg-raised', '#11151c'),
+ accent: read('--hb-brand-accent', '#9b5bb3'),
+ available: read('--hb-status-available', '#49aa19'),
+ degraded: read('--hb-status-degraded', '#d89614')
};
}
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@hertzbeat.apache.org
For additional commands, e-mail: notifications-help@hertzbeat.apache.org