mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-15 21:00:45 +00:00
Compare commits
55 Commits
nv/exec-st
...
feat/noz-c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4abdd5767 | ||
|
|
d6a439e89e | ||
|
|
319ad72072 | ||
|
|
27e1428cec | ||
|
|
55e882d5b6 | ||
|
|
e6d1089c54 | ||
|
|
3d41374880 | ||
|
|
7eddad124c | ||
|
|
585bac2130 | ||
|
|
87f4c89fe5 | ||
|
|
41d75d42fb | ||
|
|
c9145165e4 | ||
|
|
cbf947795f | ||
|
|
1d297e0c77 | ||
|
|
ea4695e3ef | ||
|
|
36eb22e6de | ||
|
|
7c6658c401 | ||
|
|
e52b9834a9 | ||
|
|
330e7aca38 | ||
|
|
4f336591cc | ||
|
|
4173c54e52 | ||
|
|
09fff48329 | ||
|
|
db8733047d | ||
|
|
f8ef6d478a | ||
|
|
4770657167 | ||
|
|
b5a8e7fb0a | ||
|
|
5a9bbc0e64 | ||
|
|
09784eec6c | ||
|
|
d00471c6b9 | ||
|
|
b91f7e9835 | ||
|
|
0b48326b10 | ||
|
|
95ee58eba5 | ||
|
|
9100d9aea6 | ||
|
|
3acfb0c8c0 | ||
|
|
75994b0d6f | ||
|
|
3bfb8708e9 | ||
|
|
876d84ac53 | ||
|
|
88e9ad73e0 | ||
|
|
7f5bd4d1cf | ||
|
|
86e0e4840b | ||
|
|
9ee433424d | ||
|
|
da8d66b5b9 | ||
|
|
f1d6c988c9 | ||
|
|
f02b5521c6 | ||
|
|
4b1b3092d5 | ||
|
|
d6017f88fd | ||
|
|
9d28014664 | ||
|
|
1997901102 | ||
|
|
84268d00c8 | ||
|
|
628e989bc0 | ||
|
|
74d272a945 | ||
|
|
f8421e81e9 | ||
|
|
e938a10ad5 | ||
|
|
93cc1957d4 | ||
|
|
313ec2d657 |
13
.github/CODEOWNERS
vendored
13
.github/CODEOWNERS
vendored
@@ -194,8 +194,8 @@ go.mod @therealpandey
|
||||
/frontend/src/pages/EditRules/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/AlertHistory/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/CreateAlertRule/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/CreateAlertV2/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/EditAlertV2/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/CreateAlert/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/EditAlert/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/FormAlertRules/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/ListAlertRules/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/TriggeredAlerts/ @SigNoz/pulse-frontend
|
||||
@@ -209,6 +209,10 @@ go.mod @therealpandey
|
||||
/frontend/src/types/api/alerts/ @SigNoz/pulse-frontend
|
||||
/frontend/src/providers/Alert.tsx @SigNoz/pulse-frontend
|
||||
/frontend/src/constants/alerts.ts @SigNoz/pulse-frontend
|
||||
/frontend/src/container/PlannedDowntime/ @SigNoz/pulse-frontend
|
||||
/frontend/src/hooks/alerts/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/Home/AlertRules/ @SigNoz/pulse-frontend
|
||||
/frontend/src/container/Home/__tests__/AlertRules.test.tsx @SigNoz/pulse-frontend
|
||||
|
||||
## Notification Channels
|
||||
/frontend/src/pages/ChannelsEdit/ @SigNoz/pulse-frontend
|
||||
@@ -217,6 +221,11 @@ go.mod @therealpandey
|
||||
/frontend/src/container/FormAlertChannels/ @SigNoz/pulse-frontend
|
||||
/frontend/src/hooks/notificationChannels/ @SigNoz/pulse-frontend
|
||||
|
||||
## List filter + views (dashboards and alerts lists)
|
||||
/frontend/src/components/ListFilter/ @SigNoz/pulse-frontend
|
||||
/frontend/src/components/ListViews/ @SigNoz/pulse-frontend
|
||||
/frontend/src/hooks/listViews/ @SigNoz/pulse-frontend
|
||||
|
||||
## OpenAPI Schema - Generated
|
||||
/frontend/src/api/generated/services/ @therealpandey @vikrantgupta25 @srikanthccv
|
||||
/docs/api/openapi.yml @therealpandey @vikrantgupta25 @srikanthccv
|
||||
|
||||
2
.github/workflows/build-community.yaml
vendored
2
.github/workflows/build-community.yaml
vendored
@@ -63,7 +63,7 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
GO_NAME: signoz-community
|
||||
GO_INPUT_ARTIFACT_CACHE_KEY: community-jsbuild-${{ github.sha }}
|
||||
GO_INPUT_ARTIFACT_PATH: frontend/build
|
||||
|
||||
2
.github/workflows/build-enterprise.yaml
vendored
2
.github/workflows/build-enterprise.yaml
vendored
@@ -89,7 +89,7 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
GO_INPUT_ARTIFACT_CACHE_KEY: enterprise-jsbuild-${{ github.sha }}
|
||||
GO_INPUT_ARTIFACT_PATH: frontend/build
|
||||
GO_BUILD_CONTEXT: ./cmd/enterprise
|
||||
|
||||
2
.github/workflows/build-staging.yaml
vendored
2
.github/workflows/build-staging.yaml
vendored
@@ -95,7 +95,7 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
GO_INPUT_ARTIFACT_CACHE_KEY: staging-jsbuild-${{ github.sha }}
|
||||
GO_INPUT_ARTIFACT_PATH: frontend/build
|
||||
GO_BUILD_CONTEXT: ./cmd/enterprise
|
||||
|
||||
20
.github/workflows/goci.yaml
vendored
20
.github/workflows/goci.yaml
vendored
@@ -22,7 +22,7 @@ jobs:
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_TEST_CONTEXT: ./...
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
fmt:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
lint:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
deps:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
@@ -52,7 +52,7 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
GO_VERSION: 1.24
|
||||
GO_VERSION: 1.25
|
||||
semconv-generated:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: check-semconv-generated-files
|
||||
run: make semconv-check
|
||||
build:
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: qemu-install
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: aarch64-install
|
||||
@@ -116,7 +116,7 @@ jobs:
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: generate-openapi
|
||||
run: |
|
||||
go run cmd/enterprise/*.go generate openapi
|
||||
@@ -133,7 +133,7 @@ jobs:
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: generate-authz
|
||||
run: |
|
||||
go run cmd/enterprise/*.go generate authz
|
||||
@@ -150,7 +150,7 @@ jobs:
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: generate-web-settings
|
||||
run: |
|
||||
go run cmd/enterprise/*.go generate config web-settings
|
||||
@@ -167,7 +167,7 @@ jobs:
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: generate-transaction-groups
|
||||
run: |
|
||||
go run cmd/enterprise/*.go generate config transaction-groups
|
||||
|
||||
4
.github/workflows/gor-signoz-community.yaml
vendored
4
.github/workflows/gor-signoz-community.yaml
vendored
@@ -66,7 +66,7 @@ jobs:
|
||||
- name: setup-go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: cross-compilation-tools
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
@@ -130,7 +130,7 @@ jobs:
|
||||
- name: setup-go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
|
||||
# copy the caches from build
|
||||
- name: get-sha
|
||||
|
||||
4
.github/workflows/gor-signoz.yaml
vendored
4
.github/workflows/gor-signoz.yaml
vendored
@@ -75,7 +75,7 @@ jobs:
|
||||
- name: setup-go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
- name: cross-compilation-tools
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
@@ -138,7 +138,7 @@ jobs:
|
||||
- name: setup-go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
go-version: "1.25"
|
||||
|
||||
# copy the caches from build
|
||||
- name: get-sha
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/SigNoz/signoz/cmd"
|
||||
"github.com/SigNoz/signoz/ee/auditor/fileauditor"
|
||||
"github.com/SigNoz/signoz/ee/auditor/kafkaauditor"
|
||||
"github.com/SigNoz/signoz/ee/auditor/otlphttpauditor"
|
||||
"github.com/SigNoz/signoz/ee/authn/callbackauthn/oidccallbackauthn"
|
||||
"github.com/SigNoz/signoz/ee/authn/callbackauthn/samlcallbackauthn"
|
||||
@@ -156,6 +157,9 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
|
||||
if err := factories.Add(fileauditor.NewFactory(licensing, version.Info)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := factories.Add(kafkaauditor.NewFactory(licensing, version.Info)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return factories
|
||||
},
|
||||
func(ctx context.Context, providerSettings factory.ProviderSettings, flagger pkgflagger.Flagger, licensing licensing.Licensing, telemetryStore telemetrystore.TelemetryStore, retentionGetter retention.Getter, orgGetter organization.Getter, zeus zeus.Zeus) (factory.NamedMap[factory.ProviderFactory[meterreporter.Reporter, meterreporter.Config]], string) {
|
||||
|
||||
@@ -436,6 +436,7 @@ auditor:
|
||||
# Specifies the auditor provider to use.
|
||||
# noop: discards all audit events (community default).
|
||||
# otlphttp: exports audit events via OTLP HTTP (enterprise).
|
||||
# kafka: exports audit events to a Kafka topic as OTLP protobuf (enterprise).
|
||||
provider: noop
|
||||
# The async channel capacity for audit events. Events are dropped when full (fail-open).
|
||||
buffer_size: 1000
|
||||
@@ -461,6 +462,18 @@ auditor:
|
||||
max_interval: 30s
|
||||
# The total maximum time spent retrying.
|
||||
max_elapsed_time: 60s
|
||||
kafka:
|
||||
# The seed broker addresses (host:port) used to discover the cluster.
|
||||
brokers:
|
||||
- localhost:9092
|
||||
# The topic audit events are written to. It must already exist.
|
||||
topic: ""
|
||||
# The client id the producer reports to the brokers.
|
||||
client_id: signoz
|
||||
# The compression codec for produced batches: none, gzip, snappy, lz4 or zstd.
|
||||
compression: lz4
|
||||
# The maximum time to drain buffered events on shutdown. Undelivered events are dropped after it.
|
||||
shutdown_timeout: 30s
|
||||
|
||||
##################### Cloud Integration #####################
|
||||
cloudintegration:
|
||||
|
||||
@@ -553,23 +553,23 @@ components:
|
||||
- apiKey
|
||||
type: object
|
||||
AlertmanagertypesChannelJiraAuth:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/AlertmanagertypesChannelJiraCloudAuth'
|
||||
- $ref: '#/components/schemas/AlertmanagertypesChannelJiraSelfHostedAuth'
|
||||
type: object
|
||||
AlertmanagertypesChannelJiraCloudAuth:
|
||||
properties:
|
||||
apiToken:
|
||||
description: The Atlassian API token paired with email. A secret; returned
|
||||
by create, update and fetch by ID, never by list.
|
||||
description: The Atlassian API token paired with email. Required when deployment
|
||||
is cloud. A secret; returned by create, update and fetch by ID, never
|
||||
by list.
|
||||
format: password
|
||||
type: string
|
||||
email:
|
||||
description: The Atlassian account email used for basic auth.
|
||||
description: The Atlassian account email used for basic auth. Required when
|
||||
deployment is cloud.
|
||||
type: string
|
||||
pat:
|
||||
description: The Jira personal access token, sent as a Bearer header. Required
|
||||
when deployment is selfhosted. A secret; returned by create, update and
|
||||
fetch by ID, never by list.
|
||||
format: password
|
||||
type: string
|
||||
required:
|
||||
- email
|
||||
- apiToken
|
||||
type: object
|
||||
AlertmanagertypesChannelJiraConfig:
|
||||
properties:
|
||||
@@ -642,16 +642,6 @@ components:
|
||||
- issueType
|
||||
- auth
|
||||
type: object
|
||||
AlertmanagertypesChannelJiraSelfHostedAuth:
|
||||
properties:
|
||||
pat:
|
||||
description: The Jira personal access token, sent as a Bearer header. A
|
||||
secret; returned by create, update and fetch by ID, never by list.
|
||||
format: password
|
||||
type: string
|
||||
required:
|
||||
- pat
|
||||
type: object
|
||||
AlertmanagertypesChannelKind:
|
||||
enum:
|
||||
- slack
|
||||
@@ -3970,6 +3960,7 @@ components:
|
||||
- logs-field
|
||||
- traces-field
|
||||
- metrics-field
|
||||
- llm-pricing-rule
|
||||
type: string
|
||||
CoretypesObject:
|
||||
properties:
|
||||
@@ -10231,8 +10222,10 @@ components:
|
||||
having:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5Having'
|
||||
description: Accepted but currently ignored; the computed values are returned
|
||||
unfiltered.
|
||||
description: A filter on the formula values, referencing the formula by
|
||||
its name or as __result, for example F1 > 0. A time series keeps only
|
||||
the points that match and drops a series with none left; a scalar result
|
||||
keeps only the rows that match.
|
||||
legend:
|
||||
description: The display name template for each series; {{field}} placeholders
|
||||
are replaced by label values.
|
||||
@@ -11743,20 +11736,10 @@ components:
|
||||
description: Whether the rule is paused. A disabled rule is neither evaluated
|
||||
nor notifies. Defaults to false.
|
||||
type: boolean
|
||||
evalWindow:
|
||||
description: The lookback window as a Go duration such as 5m. Only read
|
||||
when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec
|
||||
instead.
|
||||
type: string
|
||||
evaluation:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
|
||||
description: The evaluation window, as a kind and spec.
|
||||
frequency:
|
||||
description: How often the rule is evaluated, as a Go duration such as 1m.
|
||||
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
|
||||
it in evaluation.spec instead.
|
||||
type: string
|
||||
labels:
|
||||
additionalProperties:
|
||||
type: string
|
||||
@@ -11768,13 +11751,6 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesNotificationSettings'
|
||||
description: Grouping, re-notification and routing behaviour.
|
||||
preferredChannels:
|
||||
description: The displayName of each notification channel to notify, for
|
||||
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
|
||||
its own channels.
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
ruleType:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesRuleType'
|
||||
@@ -11787,15 +11763,6 @@ components:
|
||||
enum:
|
||||
- v2alpha1
|
||||
type: string
|
||||
source:
|
||||
deprecated: true
|
||||
description: The URL of the page the rule was created from. Informational;
|
||||
it is not used for evaluation.
|
||||
type: string
|
||||
version:
|
||||
deprecated: true
|
||||
description: The query payload version. Nothing reads it.
|
||||
type: string
|
||||
required:
|
||||
- alert
|
||||
- alertType
|
||||
@@ -11884,20 +11851,10 @@ components:
|
||||
description: Whether the rule is paused. A disabled rule is neither evaluated
|
||||
nor notifies. Defaults to false.
|
||||
type: boolean
|
||||
evalWindow:
|
||||
description: The lookback window as a Go duration such as 5m. Only read
|
||||
when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec
|
||||
instead.
|
||||
type: string
|
||||
evaluation:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
|
||||
description: The evaluation window, as a kind and spec.
|
||||
frequency:
|
||||
description: How often the rule is evaluated, as a Go duration such as 1m.
|
||||
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
|
||||
it in evaluation.spec instead.
|
||||
type: string
|
||||
id:
|
||||
description: The unique identifier of the rule.
|
||||
type: string
|
||||
@@ -11912,13 +11869,6 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesNotificationSettings'
|
||||
description: Grouping, re-notification and routing behaviour.
|
||||
preferredChannels:
|
||||
description: The displayName of each notification channel to notify, for
|
||||
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
|
||||
its own channels.
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
ruleType:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesRuleType'
|
||||
@@ -11931,11 +11881,6 @@ components:
|
||||
enum:
|
||||
- v2alpha1
|
||||
type: string
|
||||
source:
|
||||
deprecated: true
|
||||
description: The URL of the page the rule was created from. Informational;
|
||||
it is not used for evaluation.
|
||||
type: string
|
||||
state:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesAlertState'
|
||||
@@ -11946,10 +11891,6 @@ components:
|
||||
type: string
|
||||
updatedBy:
|
||||
type: string
|
||||
version:
|
||||
deprecated: true
|
||||
description: The query payload version. Nothing reads it.
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- state
|
||||
@@ -11972,28 +11913,10 @@ components:
|
||||
description: Whether to fire a nodata alert when the query returns no data.
|
||||
Defaults to false.
|
||||
type: boolean
|
||||
algorithm:
|
||||
description: 'anomaly_rule only: the anomaly detection algorithm. The supported
|
||||
value is standard.'
|
||||
type: string
|
||||
compositeQuery:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesAlertCompositeQuery'
|
||||
description: The queries whose result is compared against the thresholds.
|
||||
matchType:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesMatchType'
|
||||
description: 'schemaVersion v1 only: which points in the window must satisfy
|
||||
op. Accepted as at_least_once, all_the_times, on_average, in_total or
|
||||
last, their aliases avg and sum, or the legacy codes as strings, ''1''
|
||||
to ''5''. Required for v1; v2alpha1 sets matchType on each threshold.'
|
||||
op:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesCompareOperator'
|
||||
description: 'schemaVersion v1 only: how the value is compared with target.
|
||||
Accepted as above, below, equal, not_equal, above_or_equal, below_or_equal
|
||||
or outside_bounds, their symbols, or the legacy codes as strings, ''1''
|
||||
to ''7''. Required for v1; v2alpha1 sets op on each threshold.'
|
||||
requireMinPoints:
|
||||
description: Whether a series is skipped until it has at least requiredNumPoints
|
||||
points in the window. Defaults to false.
|
||||
@@ -12011,17 +11934,6 @@ components:
|
||||
description: The name of the query whose result is evaluated, such as A
|
||||
or F1. Must match a query in compositeQuery.
|
||||
type: string
|
||||
target:
|
||||
description: 'schemaVersion v1 only: the value compared against, in targetUnit.
|
||||
Required for v1; v2alpha1 sets target on each threshold.'
|
||||
format: double
|
||||
nullable: true
|
||||
type: number
|
||||
targetUnit:
|
||||
description: 'schemaVersion v1 only: the unit of target, such as percent
|
||||
or ms. Converted to compositeQuery.unit before comparison when the two
|
||||
differ.'
|
||||
type: string
|
||||
thresholds:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesRuleThresholdData'
|
||||
@@ -16148,9 +16060,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
summary: List pricing rules
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -16195,9 +16107,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:update
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:update
|
||||
summary: Create or update pricing rules
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -16243,9 +16155,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:delete
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- llm-pricing-rule:delete
|
||||
summary: Delete a pricing rule
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -16301,9 +16213,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:read
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:read
|
||||
summary: Get a pricing rule
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -16356,9 +16268,11 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
- traces:read
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- llm-pricing-rule:list
|
||||
- traces:read
|
||||
summary: List unmapped models
|
||||
tags:
|
||||
- llmpricingrules
|
||||
@@ -25528,56 +25442,6 @@ paths:
|
||||
- rules
|
||||
x-signoz-stability: alpha
|
||||
/api/v2/rules:
|
||||
get:
|
||||
deprecated: true
|
||||
description: 'This endpoint lists all alert rules with their current evaluation
|
||||
state. Deprecated: use ListRulesV3, which supports filtering, sorting and
|
||||
pagination.'
|
||||
operationId: ListRules
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
items:
|
||||
$ref: '#/components/schemas/RuletypesRule'
|
||||
type: array
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: List alert rules
|
||||
tags:
|
||||
- rules
|
||||
x-signoz-stability: alpha
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint creates a new alert rule
|
||||
@@ -25667,7 +25531,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
logs_threshold:
|
||||
description: Counts matching log records (ERROR severity + body contains)
|
||||
over a rolling window. Fires at least once per evaluation when the
|
||||
@@ -25734,7 +25597,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_anomaly:
|
||||
description: Wraps a builder query in the `anomaly` function with
|
||||
daily seasonality, so SigNoz compares each point against the forecast
|
||||
@@ -25807,7 +25669,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: anomaly_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_promql:
|
||||
description: PromQL expression instead of the builder. Dotted OTEL
|
||||
resource attributes are quoted ("deployment.environment"). Useful
|
||||
@@ -25863,7 +25724,6 @@ paths:
|
||||
interval: 1h
|
||||
ruleType: promql_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_formula:
|
||||
description: Computes disk utilization as (1 - available/capacity)
|
||||
* 100 by combining two disabled base queries with a builder_formula.
|
||||
@@ -25955,7 +25815,6 @@ paths:
|
||||
interval: 2h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_single:
|
||||
description: Fires when a pod consumes more than 80% of its requested
|
||||
CPU for the whole evaluation window. Uses `k8s.pod.cpu_request_utilization`.
|
||||
@@ -26024,7 +25883,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
notification_settings:
|
||||
description: 'Demonstrates the full notificationSettings surface:
|
||||
`groupBy` merges alerts across labels to cut noise, `newGroupEvalDelay`
|
||||
@@ -26123,7 +25981,6 @@ paths:
|
||||
usePolicy: false
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
tiered_thresholds:
|
||||
description: Two tiers (warning and critical) in a single rule, each
|
||||
with its own target, op, matchType, and channels so warnings and
|
||||
@@ -26223,7 +26080,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_error_rate_formula:
|
||||
description: Two disabled trace count queries (A = error spans where
|
||||
hasError=true, B = total spans) combined via a builder_formula into
|
||||
@@ -26313,7 +26169,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_threshold_latency:
|
||||
description: Builder query against the traces signal with p99(duration_nano).
|
||||
The series unit is ns (compositeQuery.unit), the target is in seconds
|
||||
@@ -26382,7 +26237,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
schema:
|
||||
$ref: '#/components/schemas/RuletypesPostableRule'
|
||||
responses:
|
||||
@@ -26633,7 +26487,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
logs_threshold:
|
||||
description: Counts matching log records (ERROR severity + body contains)
|
||||
over a rolling window. Fires at least once per evaluation when the
|
||||
@@ -26700,7 +26553,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_anomaly:
|
||||
description: Wraps a builder query in the `anomaly` function with
|
||||
daily seasonality, so SigNoz compares each point against the forecast
|
||||
@@ -26773,7 +26625,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: anomaly_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_promql:
|
||||
description: PromQL expression instead of the builder. Dotted OTEL
|
||||
resource attributes are quoted ("deployment.environment"). Useful
|
||||
@@ -26829,7 +26680,6 @@ paths:
|
||||
interval: 1h
|
||||
ruleType: promql_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_formula:
|
||||
description: Computes disk utilization as (1 - available/capacity)
|
||||
* 100 by combining two disabled base queries with a builder_formula.
|
||||
@@ -26921,7 +26771,6 @@ paths:
|
||||
interval: 2h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_single:
|
||||
description: Fires when a pod consumes more than 80% of its requested
|
||||
CPU for the whole evaluation window. Uses `k8s.pod.cpu_request_utilization`.
|
||||
@@ -26990,7 +26839,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
notification_settings:
|
||||
description: 'Demonstrates the full notificationSettings surface:
|
||||
`groupBy` merges alerts across labels to cut noise, `newGroupEvalDelay`
|
||||
@@ -27089,7 +26937,6 @@ paths:
|
||||
usePolicy: false
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
tiered_thresholds:
|
||||
description: Two tiers (warning and critical) in a single rule, each
|
||||
with its own target, op, matchType, and channels so warnings and
|
||||
@@ -27189,7 +27036,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_error_rate_formula:
|
||||
description: Two disabled trace count queries (A = error spans where
|
||||
hasError=true, B = total spans) combined via a builder_formula into
|
||||
@@ -27279,7 +27125,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_threshold_latency:
|
||||
description: Builder query against the traces signal with p99(duration_nano).
|
||||
The series unit is ns (compositeQuery.unit), the target is in seconds
|
||||
@@ -27348,7 +27193,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
schema:
|
||||
$ref: '#/components/schemas/RuletypesPostableRule'
|
||||
responses:
|
||||
@@ -27500,7 +27344,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
logs_threshold:
|
||||
description: Counts matching log records (ERROR severity + body contains)
|
||||
over a rolling window. Fires at least once per evaluation when the
|
||||
@@ -27567,7 +27410,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_anomaly:
|
||||
description: Wraps a builder query in the `anomaly` function with
|
||||
daily seasonality, so SigNoz compares each point against the forecast
|
||||
@@ -27640,7 +27482,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: anomaly_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_promql:
|
||||
description: PromQL expression instead of the builder. Dotted OTEL
|
||||
resource attributes are quoted ("deployment.environment"). Useful
|
||||
@@ -27696,7 +27537,6 @@ paths:
|
||||
interval: 1h
|
||||
ruleType: promql_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_formula:
|
||||
description: Computes disk utilization as (1 - available/capacity)
|
||||
* 100 by combining two disabled base queries with a builder_formula.
|
||||
@@ -27788,7 +27628,6 @@ paths:
|
||||
interval: 2h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_single:
|
||||
description: Fires when a pod consumes more than 80% of its requested
|
||||
CPU for the whole evaluation window. Uses `k8s.pod.cpu_request_utilization`.
|
||||
@@ -27857,7 +27696,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
notification_settings:
|
||||
description: 'Demonstrates the full notificationSettings surface:
|
||||
`groupBy` merges alerts across labels to cut noise, `newGroupEvalDelay`
|
||||
@@ -27956,7 +27794,6 @@ paths:
|
||||
usePolicy: false
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
tiered_thresholds:
|
||||
description: Two tiers (warning and critical) in a single rule, each
|
||||
with its own target, op, matchType, and channels so warnings and
|
||||
@@ -28056,7 +27893,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_error_rate_formula:
|
||||
description: Two disabled trace count queries (A = error spans where
|
||||
hasError=true, B = total spans) combined via a builder_formula into
|
||||
@@ -28146,7 +27982,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_threshold_latency:
|
||||
description: Builder query against the traces signal with p99(duration_nano).
|
||||
The series unit is ns (compositeQuery.unit), the target is in seconds
|
||||
@@ -28215,7 +28050,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
schema:
|
||||
$ref: '#/components/schemas/RuletypesPostableRule'
|
||||
responses:
|
||||
@@ -29129,7 +28963,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
logs_threshold:
|
||||
description: Counts matching log records (ERROR severity + body contains)
|
||||
over a rolling window. Fires at least once per evaluation when the
|
||||
@@ -29196,7 +29029,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_anomaly:
|
||||
description: Wraps a builder query in the `anomaly` function with
|
||||
daily seasonality, so SigNoz compares each point against the forecast
|
||||
@@ -29269,7 +29101,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: anomaly_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_promql:
|
||||
description: PromQL expression instead of the builder. Dotted OTEL
|
||||
resource attributes are quoted ("deployment.environment"). Useful
|
||||
@@ -29325,7 +29156,6 @@ paths:
|
||||
interval: 1h
|
||||
ruleType: promql_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_formula:
|
||||
description: Computes disk utilization as (1 - available/capacity)
|
||||
* 100 by combining two disabled base queries with a builder_formula.
|
||||
@@ -29417,7 +29247,6 @@ paths:
|
||||
interval: 2h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
metric_threshold_single:
|
||||
description: Fires when a pod consumes more than 80% of its requested
|
||||
CPU for the whole evaluation window. Uses `k8s.pod.cpu_request_utilization`.
|
||||
@@ -29486,7 +29315,6 @@ paths:
|
||||
interval: 4h
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
notification_settings:
|
||||
description: 'Demonstrates the full notificationSettings surface:
|
||||
`groupBy` merges alerts across labels to cut noise, `newGroupEvalDelay`
|
||||
@@ -29585,7 +29413,6 @@ paths:
|
||||
usePolicy: false
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
tiered_thresholds:
|
||||
description: Two tiers (warning and critical) in a single rule, each
|
||||
with its own target, op, matchType, and channels so warnings and
|
||||
@@ -29685,7 +29512,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_error_rate_formula:
|
||||
description: Two disabled trace count queries (A = error spans where
|
||||
hasError=true, B = total spans) combined via a builder_formula into
|
||||
@@ -29775,7 +29601,6 @@ paths:
|
||||
interval: 15m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
traces_threshold_latency:
|
||||
description: Builder query against the traces signal with p99(duration_nano).
|
||||
The series unit is ns (compositeQuery.unit), the target is in seconds
|
||||
@@ -29844,7 +29669,6 @@ paths:
|
||||
interval: 30m
|
||||
ruleType: threshold_rule
|
||||
schemaVersion: v2alpha1
|
||||
version: v5
|
||||
schema:
|
||||
$ref: '#/components/schemas/RuletypesPostableRule'
|
||||
responses:
|
||||
@@ -32729,6 +32553,305 @@ paths:
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_anomaly_request_rate:
|
||||
description: 'anomaly is the one function with named arguments. seasonality
|
||||
says which past periods predict the current value: hourly, daily
|
||||
or weekly, daily when absent. z_score_threshold is how many standard
|
||||
deviations from the prediction count as an anomaly. It has no default:
|
||||
a request without it gets bounds of zero width, so send it. 3 is
|
||||
the value the UI sends. The response carries, next to the values,
|
||||
a predicted series, an upper and a lower bound series and an anomaly
|
||||
score series. The scoring runs in the enterprise build; the community
|
||||
build returns the series unchanged.'
|
||||
summary: 'anomaly: request rate scored against its daily pattern'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- metricName: http.server.duration.count
|
||||
spaceAggregation: sum
|
||||
timeAggregation: rate
|
||||
functions:
|
||||
- args:
|
||||
- name: seasonality
|
||||
value: daily
|
||||
- name: z_score_threshold
|
||||
value: 3
|
||||
name: anomaly
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: service.name
|
||||
name: A
|
||||
signal: metrics
|
||||
stepInterval: 300s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_cumulativesum_errors_so_far:
|
||||
description: cumulativeSum replaces each point with the sum of every
|
||||
point up to and including it, so a per-step count becomes a running
|
||||
total whose first point is the first count. It takes no arguments.
|
||||
The total resets with the window, so a longer time range gives a
|
||||
larger final value; it is a view of the window, not a counter.
|
||||
summary: 'cumulativeSum: 5xx responses since the start of the window'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- alias: server_errors
|
||||
expression: count()
|
||||
filter:
|
||||
expression: http.response.status_code >= 500
|
||||
functions:
|
||||
- name: cumulativeSum
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: service.name
|
||||
name: A
|
||||
signal: traces
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_cutoffmin_hide_idle_hosts:
|
||||
description: The four threshold functions take one number. cutOffMin
|
||||
and cutOffMax remove the points below or above the threshold, so
|
||||
an idle host disappears from the chart instead of drawing a line
|
||||
along the bottom. clampMin and clampMax keep the points and replace
|
||||
the value with the threshold, which caps spikes without hiding them.
|
||||
system.cpu.utilization is a ratio, so 0.05 is 5%.
|
||||
summary: 'cutOffMin: drop hosts below 5% CPU from the chart'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- metricName: system.cpu.utilization
|
||||
spaceAggregation: avg
|
||||
timeAggregation: avg
|
||||
functions:
|
||||
- args:
|
||||
- value: 0.05
|
||||
name: cutOffMin
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: host.name
|
||||
name: A
|
||||
signal: metrics
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_ewma_smoothed_latency:
|
||||
description: 'ewma3, ewma5 and ewma7 replace each point with an exponentially
|
||||
weighted average of the point and the points before it. The number
|
||||
in the name is the window the default weight is derived from: alpha
|
||||
= 2 / (n + 1), so 0.5, 0.333 and 0.25. One optional argument overrides
|
||||
alpha; a value close to 1 follows the raw series, a value close
|
||||
to 0 smooths harder. 0.3 here smooths a little more than ewma5''s
|
||||
default.'
|
||||
summary: 'ewma5: smoothed p95 latency'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- metricName: http.server.duration.bucket
|
||||
spaceAggregation: p95
|
||||
functions:
|
||||
- args:
|
||||
- value: 0.3
|
||||
name: ewma5
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: service.name
|
||||
name: A
|
||||
signal: metrics
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_fillzero_sparse_errors:
|
||||
description: A count over sparse events returns a point only for steps
|
||||
that had a match, so a chart of failed spans has gaps where nothing
|
||||
failed. fillZero adds a zero at every missing step. With no arguments
|
||||
the server fills the request window at the query's step, which is
|
||||
the common case. The three optional arguments are start, end and
|
||||
step in milliseconds, for callers that want to fill a different
|
||||
grid.
|
||||
summary: 'fillZero: a zero at every step with no failed spans'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- alias: failed_spans
|
||||
expression: count()
|
||||
filter:
|
||||
expression: has_error = true
|
||||
functions:
|
||||
- name: fillZero
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: service.name
|
||||
name: A
|
||||
signal: traces
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_log10_network_bytes:
|
||||
description: log2 and log10 replace each value with its logarithm,
|
||||
so a loopback device moving kilobytes and an uplink moving gigabytes
|
||||
fit on one chart. They take no arguments. Zero and negative values
|
||||
have no logarithm and are not drawn. absolute, also without arguments,
|
||||
is the usual companion for a signed series before a logarithm.
|
||||
summary: 'log10: network throughput across devices that differ by
|
||||
orders of magnitude'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- metricName: system.network.io
|
||||
spaceAggregation: sum
|
||||
timeAggregation: rate
|
||||
filter:
|
||||
expression: direction = 'transmit'
|
||||
functions:
|
||||
- name: log10
|
||||
groupBy:
|
||||
- fieldContext: attribute
|
||||
name: device
|
||||
name: A
|
||||
signal: metrics
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_median_despiked_request_rate:
|
||||
description: median3, median5 and median7 replace each point with
|
||||
the median of the surrounding 3, 5 or 7 points. A spike that lasts
|
||||
one step vanishes, a shift that lasts longer than half the window
|
||||
stays. The first and last half window, 2 points each for median5,
|
||||
have no full window and keep their values, so the newest spike stays
|
||||
visible; a series shorter than the window is returned unchanged.
|
||||
They take no arguments. Use them when the raw series is noisy and
|
||||
the chart is for a trend, not for catching the spike.
|
||||
summary: 'median5: request rate without one-step spikes'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- metricName: http.server.duration.count
|
||||
spaceAggregation: sum
|
||||
timeAggregation: rate
|
||||
functions:
|
||||
- name: median5
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: service.name
|
||||
name: A
|
||||
signal: metrics
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_runningdiff_disk_growth:
|
||||
description: 'runningDiff turns a gauge into the change between consecutive
|
||||
points, so a filesystem usage gauge becomes bytes written per step.
|
||||
It takes no arguments and drops the first point of the window, since
|
||||
that point has nothing to difference against; the server reads one
|
||||
step before the window to keep the first interval. Functions apply
|
||||
in order: clampMin with 0 runs on the differences and replaces the
|
||||
negative value a cleanup or a volume reset produces with zero.'
|
||||
summary: 'runningDiff then clampMin: bytes written to disk per step'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- metricName: system.filesystem.usage
|
||||
spaceAggregation: sum
|
||||
timeAggregation: latest
|
||||
filter:
|
||||
expression: state = 'used'
|
||||
functions:
|
||||
- name: runningDiff
|
||||
- args:
|
||||
- value: 0
|
||||
name: clampMin
|
||||
groupBy:
|
||||
- fieldContext: resource
|
||||
name: host.name
|
||||
name: A
|
||||
signal: metrics
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
function_timeshift_week_over_week:
|
||||
description: timeShift moves every point of its query forward by the
|
||||
argument, in seconds, so a series read from the past lands on the
|
||||
current timestamps. B here reads the hour exactly seven days (604800
|
||||
s) before the requested window and comes back on this week's timestamps,
|
||||
so it overlays A on a chart and the formula can subtract it point
|
||||
by point. The argument is positive; it says how far back to read.
|
||||
summary: 'timeShift: this week''s error logs next to last week''s'
|
||||
value:
|
||||
compositeQuery:
|
||||
queries:
|
||||
- spec:
|
||||
aggregations:
|
||||
- alias: errors
|
||||
expression: count()
|
||||
filter:
|
||||
expression: severity_text = 'ERROR'
|
||||
name: A
|
||||
signal: logs
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
- spec:
|
||||
aggregations:
|
||||
- alias: errors
|
||||
expression: count()
|
||||
filter:
|
||||
expression: severity_text = 'ERROR'
|
||||
functions:
|
||||
- args:
|
||||
- value: 604800
|
||||
name: timeShift
|
||||
name: B
|
||||
signal: logs
|
||||
stepInterval: 60s
|
||||
type: builder_query
|
||||
- spec:
|
||||
expression: A - B
|
||||
name: F1
|
||||
type: builder_formula
|
||||
end: 1640998800000
|
||||
requestType: time_series
|
||||
schemaVersion: v1
|
||||
start: 1640995200000
|
||||
logs_raw:
|
||||
summary: 'Raw: fetch raw log records'
|
||||
value:
|
||||
|
||||
31
ee/auditor/kafkaauditor/export.go
Normal file
31
ee/auditor/kafkaauditor/export.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package kafkaauditor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/auditor"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/audittypes"
|
||||
)
|
||||
|
||||
// Produces the whole batch as a single record so the collector's otlp_proto unmarshaler reads it as one ExportLogsServiceRequest.
|
||||
func (provider *provider) export(ctx context.Context, events []audittypes.AuditEvent) error {
|
||||
logs := audittypes.NewPLogsFromAuditEvents(events, "signoz", provider.build.Version(), "signoz.audit")
|
||||
|
||||
value, err := provider.marshaler.MarshalLogs(logs)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, errors.TypeInternal, auditor.ErrCodeAuditExportFailed, "failed to marshal audit logs")
|
||||
}
|
||||
|
||||
record := &kgo.Record{Topic: provider.config.Kafka.Topic, Value: value}
|
||||
if err := provider.client.ProduceSync(ctx, record).FirstErr(); err != nil {
|
||||
provider.settings.Logger().ErrorContext(ctx, "audit export failed", errors.Attr(err), slog.Int("dropped_log_records", len(events)))
|
||||
|
||||
return errors.Wrapf(err, errors.TypeInternal, auditor.ErrCodeAuditExportFailed, "failed to produce audit logs to topic %q", provider.config.Kafka.Topic)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
132
ee/auditor/kafkaauditor/provider.go
Normal file
132
ee/auditor/kafkaauditor/provider.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package kafkaauditor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"github.com/twmb/franz-go/plugin/kslog"
|
||||
"go.opentelemetry.io/collector/pdata/plog"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/auditor"
|
||||
"github.com/SigNoz/signoz/pkg/auditor/auditorserver"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/licensing"
|
||||
"github.com/SigNoz/signoz/pkg/types/audittypes"
|
||||
"github.com/SigNoz/signoz/pkg/version"
|
||||
)
|
||||
|
||||
var _ auditor.Auditor = (*provider)(nil)
|
||||
|
||||
type provider struct {
|
||||
settings factory.ScopedProviderSettings
|
||||
config auditor.Config
|
||||
licensing licensing.Licensing
|
||||
build version.Build
|
||||
server *auditorserver.Server
|
||||
marshaler plog.ProtoMarshaler
|
||||
client *kgo.Client
|
||||
}
|
||||
|
||||
func NewFactory(licensing licensing.Licensing, build version.Build) factory.ProviderFactory[auditor.Auditor, auditor.Config] {
|
||||
return factory.NewProviderFactory(factory.MustNewName("kafka"), func(ctx context.Context, providerSettings factory.ProviderSettings, config auditor.Config) (auditor.Auditor, error) {
|
||||
return newProvider(ctx, providerSettings, config, licensing, build)
|
||||
})
|
||||
}
|
||||
|
||||
func newProvider(_ context.Context, providerSettings factory.ProviderSettings, config auditor.Config, licensing licensing.Licensing, build version.Build) (auditor.Auditor, error) {
|
||||
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/ee/auditor/kafkaauditor")
|
||||
|
||||
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
|
||||
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(config.Kafka.Brokers...),
|
||||
kgo.ClientID(config.Kafka.ClientID),
|
||||
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
|
||||
kgo.ProducerLinger(0),
|
||||
kgo.WithLogger(kslog.New(settings.Logger())),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
provider := &provider{
|
||||
settings: settings,
|
||||
config: config,
|
||||
licensing: licensing,
|
||||
build: build,
|
||||
marshaler: plog.ProtoMarshaler{},
|
||||
client: client,
|
||||
}
|
||||
|
||||
server, err := auditorserver.New(settings,
|
||||
auditorserver.Config{
|
||||
BufferSize: config.BufferSize,
|
||||
BatchSize: config.BatchSize,
|
||||
FlushInterval: config.FlushInterval,
|
||||
},
|
||||
provider.export,
|
||||
)
|
||||
if err != nil {
|
||||
client.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
provider.server = server
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (provider *provider) Start(ctx context.Context) error {
|
||||
return provider.server.Start(ctx)
|
||||
}
|
||||
|
||||
func (provider *provider) Audit(ctx context.Context, event audittypes.AuditEvent) {
|
||||
if event.PrincipalAttributes.PrincipalOrgID.IsZero() {
|
||||
provider.settings.Logger().WarnContext(ctx, "audit event dropped as org_id is zero")
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := provider.licensing.GetActive(ctx, event.PrincipalAttributes.PrincipalOrgID); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
provider.server.Add(ctx, event)
|
||||
}
|
||||
|
||||
func (provider *provider) Healthy() <-chan struct{} {
|
||||
return provider.server.Healthy()
|
||||
}
|
||||
|
||||
func (provider *provider) Stop(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, provider.config.Kafka.ShutdownTimeout)
|
||||
defer cancel()
|
||||
|
||||
stoppedC := make(chan error, 1)
|
||||
go func() { stoppedC <- provider.server.Stop(ctx) }()
|
||||
|
||||
select {
|
||||
case err := <-stoppedC:
|
||||
provider.client.Close()
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
provider.settings.Logger().WarnContext(ctx, "audit drain timed out, closing kafka client", slog.Duration("shutdown_timeout", provider.config.Kafka.ShutdownTimeout))
|
||||
// Closing fails buffered and in-flight records, so the blocked export and the rest of the drain return immediately.
|
||||
provider.client.Close()
|
||||
return <-stoppedC
|
||||
}
|
||||
}
|
||||
|
||||
func compressionCodec(name string) kgo.CompressionCodec {
|
||||
switch name {
|
||||
case "gzip":
|
||||
return kgo.GzipCompression()
|
||||
case "snappy":
|
||||
return kgo.SnappyCompression()
|
||||
case "lz4":
|
||||
return kgo.Lz4Compression()
|
||||
case "zstd":
|
||||
return kgo.ZstdCompression()
|
||||
default:
|
||||
return kgo.NoCompression()
|
||||
}
|
||||
}
|
||||
227
ee/auditor/kafkaauditor/provider_test.go
Normal file
227
ee/auditor/kafkaauditor/provider_test.go
Normal file
@@ -0,0 +1,227 @@
|
||||
package kafkaauditor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/twmb/franz-go/pkg/kerr"
|
||||
"github.com/twmb/franz-go/pkg/kfake"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"go.opentelemetry.io/collector/pdata/plog"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/auditor"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
|
||||
"github.com/SigNoz/signoz/pkg/types/audittypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/version"
|
||||
)
|
||||
|
||||
func newTestCluster(t *testing.T, topics ...string) *kfake.Cluster {
|
||||
t.Helper()
|
||||
|
||||
cluster, err := kfake.NewCluster(kfake.NumBrokers(1), kfake.SeedTopics(1, topics...))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(cluster.Close)
|
||||
|
||||
return cluster
|
||||
}
|
||||
|
||||
func newTestProvider(t *testing.T, brokers []string, topic string, compression string) *provider {
|
||||
t.Helper()
|
||||
|
||||
config := auditor.Config{
|
||||
Provider: "kafka",
|
||||
BufferSize: 10,
|
||||
BatchSize: 5,
|
||||
FlushInterval: 50 * time.Millisecond,
|
||||
Kafka: auditor.KafkaConfig{
|
||||
Brokers: brokers,
|
||||
Topic: topic,
|
||||
ClientID: "signoz-test",
|
||||
Compression: compression,
|
||||
ShutdownTimeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
auditor, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, version.Info)
|
||||
require.NoError(t, err)
|
||||
|
||||
return auditor.(*provider)
|
||||
}
|
||||
|
||||
func newTestEvent(resource coretypes.Resource, action coretypes.Verb, body string) audittypes.AuditEvent {
|
||||
return audittypes.AuditEvent{
|
||||
Timestamp: time.Now(),
|
||||
Body: body,
|
||||
EventName: audittypes.NewEventName(action),
|
||||
AuditAttributes: audittypes.AuditAttributes{
|
||||
Action: action,
|
||||
Outcome: audittypes.OutcomeSuccess,
|
||||
},
|
||||
ResourceAttributes: audittypes.ResourceAttributes{
|
||||
Resource: resource,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Polls the topic until the consumed records hold wantLogRecords audit log records in total.
|
||||
func consumeRecords(t *testing.T, brokers []string, topic string, wantLogRecords int) []*kgo.Record {
|
||||
t.Helper()
|
||||
|
||||
client, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(brokers...),
|
||||
kgo.ConsumeTopics(topic),
|
||||
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var records []*kgo.Record
|
||||
gotLogRecords := 0
|
||||
for gotLogRecords < wantLogRecords {
|
||||
fetches := client.PollFetches(ctx)
|
||||
require.NoError(t, ctx.Err(), "timed out waiting for %d log records, got %d", wantLogRecords, gotLogRecords)
|
||||
require.Empty(t, fetches.Errors())
|
||||
|
||||
for _, record := range fetches.Records() {
|
||||
logs, err := (&plog.ProtoUnmarshaler{}).UnmarshalLogs(record.Value)
|
||||
require.NoError(t, err)
|
||||
gotLogRecords += logs.LogRecordCount()
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
|
||||
return records
|
||||
}
|
||||
|
||||
func TestExport(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
compression string
|
||||
compressionType uint8
|
||||
}{
|
||||
{name: "CompressionNone", compression: "none", compressionType: 0},
|
||||
{name: "CompressionGzip", compression: "gzip", compressionType: 1},
|
||||
{name: "CompressionSnappy", compression: "snappy", compressionType: 2},
|
||||
{name: "CompressionLz4", compression: "lz4", compressionType: 3},
|
||||
{name: "CompressionZstd", compression: "zstd", compressionType: 4},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
cluster := newTestCluster(t, "tenant_audit")
|
||||
provider := newTestProvider(t, cluster.ListenAddrs(), "tenant_audit", testCase.compression)
|
||||
defer provider.client.Close()
|
||||
|
||||
events := []audittypes.AuditEvent{
|
||||
newTestEvent(coretypes.ResourceUser, coretypes.VerbUpdate, "user updated"),
|
||||
newTestEvent(coretypes.ResourceMetaResourceDashboard, coretypes.VerbCreate, "dashboard created"),
|
||||
newTestEvent(coretypes.ResourceMetaResourceDashboard, coretypes.VerbDelete, "dashboard deleted"),
|
||||
}
|
||||
require.NoError(t, provider.export(context.Background(), events))
|
||||
|
||||
records := consumeRecords(t, cluster.ListenAddrs(), "tenant_audit", len(events))
|
||||
require.Len(t, records, 1)
|
||||
assert.Equal(t, "tenant_audit", records[0].Topic)
|
||||
assert.Equal(t, testCase.compressionType, records[0].Attrs.CompressionType())
|
||||
|
||||
logs, err := (&plog.ProtoUnmarshaler{}).UnmarshalLogs(records[0].Value)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, len(events), logs.LogRecordCount())
|
||||
|
||||
serviceName, ok := logs.ResourceLogs().At(0).Resource().Attributes().Get("service.name")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "signoz", serviceName.Str())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExport_RecordTooLarge(t *testing.T) {
|
||||
cluster := newTestCluster(t, "large_audit")
|
||||
provider := newTestProvider(t, cluster.ListenAddrs(), "large_audit", "none")
|
||||
defer provider.client.Close()
|
||||
|
||||
event := newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, strings.Repeat("a", 2<<20))
|
||||
|
||||
err := provider.export(context.Background(), []audittypes.AuditEvent{event})
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, kerr.MessageTooLarge))
|
||||
}
|
||||
|
||||
func TestExport_UnknownTopic(t *testing.T) {
|
||||
cluster := newTestCluster(t)
|
||||
provider := newTestProvider(t, cluster.ListenAddrs(), "missing_audit", "lz4")
|
||||
defer provider.client.Close()
|
||||
|
||||
err := provider.export(context.Background(), []audittypes.AuditEvent{newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, "user created")})
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, kerr.UnknownTopicOrPartition))
|
||||
}
|
||||
|
||||
func TestExport_BrokerDown_RetriesUntilContextDone(t *testing.T) {
|
||||
cluster := newTestCluster(t, "down_audit")
|
||||
brokers := cluster.ListenAddrs()
|
||||
cluster.Close()
|
||||
|
||||
provider := newTestProvider(t, brokers, "down_audit", "lz4")
|
||||
defer provider.client.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
err := provider.export(ctx, []audittypes.AuditEvent{newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, "user created")})
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, context.DeadlineExceeded))
|
||||
assert.GreaterOrEqual(t, time.Since(start), 500*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestStop_DrainsQueuedEvents(t *testing.T) {
|
||||
cluster := newTestCluster(t, "drain_audit")
|
||||
provider := newTestProvider(t, cluster.ListenAddrs(), "drain_audit", "lz4")
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- provider.Start(context.Background()) }()
|
||||
<-provider.Healthy()
|
||||
|
||||
for range 7 {
|
||||
provider.server.Add(context.Background(), newTestEvent(coretypes.ResourceUser, coretypes.VerbUpdate, "user updated"))
|
||||
}
|
||||
|
||||
require.NoError(t, provider.Stop(context.Background()))
|
||||
require.NoError(t, <-done)
|
||||
|
||||
records := consumeRecords(t, cluster.ListenAddrs(), "drain_audit", 7)
|
||||
assert.NotEmpty(t, records)
|
||||
}
|
||||
|
||||
func TestStop_BrokerDown_ClosesAfterShutdownTimeout(t *testing.T) {
|
||||
cluster := newTestCluster(t, "stuck_audit")
|
||||
brokers := cluster.ListenAddrs()
|
||||
cluster.Close()
|
||||
|
||||
provider := newTestProvider(t, brokers, "stuck_audit", "lz4")
|
||||
provider.config.Kafka.ShutdownTimeout = 500 * time.Millisecond
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- provider.Start(context.Background()) }()
|
||||
<-provider.Healthy()
|
||||
|
||||
for range 7 {
|
||||
provider.server.Add(context.Background(), newTestEvent(coretypes.ResourceUser, coretypes.VerbUpdate, "user updated"))
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
require.NoError(t, provider.Stop(context.Background()))
|
||||
require.NoError(t, <-done)
|
||||
assert.GreaterOrEqual(t, time.Since(start), 500*time.Millisecond)
|
||||
assert.Less(t, time.Since(start), 5*time.Second)
|
||||
}
|
||||
@@ -34,8 +34,7 @@ type AnomalyRule struct {
|
||||
|
||||
provider anomaly.Provider
|
||||
|
||||
version string
|
||||
logger *slog.Logger
|
||||
logger *slog.Logger
|
||||
|
||||
seasonality anomaly.Seasonality
|
||||
}
|
||||
@@ -63,7 +62,6 @@ func NewAnomalyRule(
|
||||
r := AnomalyRule{
|
||||
BaseRule: baseRule,
|
||||
querier: querier,
|
||||
version: p.Version,
|
||||
logger: logger.With(slog.String("rule.id", id)),
|
||||
}
|
||||
|
||||
@@ -105,15 +103,15 @@ func (r *AnomalyRule) Type() ruletypes.RuleType {
|
||||
}
|
||||
|
||||
func (r *AnomalyRule) prepareQueryRange(ctx context.Context, ts time.Time) *qbtypes.QueryRangeRequest {
|
||||
r.logger.InfoContext(
|
||||
ctx, "prepare query range request", slog.Int64("ts", ts.UnixMilli()),
|
||||
slog.Int64("eval.window_ms", r.EvalWindow().Milliseconds()),
|
||||
slog.Int64("eval.delay_ms", r.EvalDelay().Milliseconds()),
|
||||
)
|
||||
|
||||
startTs, endTs := r.Timestamps(ts)
|
||||
start, end := startTs.UnixMilli(), endTs.UnixMilli()
|
||||
|
||||
r.logger.InfoContext(
|
||||
ctx, "prepare query range request", slog.Int64("ts", ts.UnixMilli()),
|
||||
slog.Int64("eval.window_ms", end-start),
|
||||
slog.Int64("eval.delay_ms", r.EvalDelay().Milliseconds()),
|
||||
)
|
||||
|
||||
req := &qbtypes.QueryRangeRequest{
|
||||
Start: uint64(start),
|
||||
End: uint64(end),
|
||||
@@ -420,12 +418,10 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
|
||||
func (r *AnomalyRule) String() string {
|
||||
|
||||
ar := ruletypes.PostableRule{
|
||||
AlertName: valuer.NewDisplayName(r.Name()),
|
||||
RuleCondition: r.Condition(),
|
||||
EvalWindow: r.EvalWindow(),
|
||||
Labels: r.Labels().Map(),
|
||||
Annotations: r.Annotations().Map(),
|
||||
PreferredChannels: r.PreferredChannels(),
|
||||
AlertName: valuer.NewDisplayName(r.Name()),
|
||||
RuleCondition: r.Condition(),
|
||||
Labels: r.Labels().Map(),
|
||||
Annotations: r.Annotations().Map(),
|
||||
}
|
||||
|
||||
byt, err := json.Marshal(ar)
|
||||
|
||||
@@ -54,9 +54,6 @@ func TestAnomalyRule_NoData_AlertOnAbsent(t *testing.T) {
|
||||
Frequency: valuer.MustParseTextDuration("1m"),
|
||||
}},
|
||||
RuleCondition: &ruletypes.RuleCondition{
|
||||
CompareOperator: ruletypes.ValueIsAbove,
|
||||
MatchType: ruletypes.AtleastOnce,
|
||||
Target: &target,
|
||||
CompositeQuery: &ruletypes.AlertCompositeQuery{
|
||||
QueryType: ruletypes.QueryTypeBuilder,
|
||||
Queries: []qbtypes.QueryEnvelope{{
|
||||
@@ -157,10 +154,7 @@ func TestAnomalyRule_NoData_AbsentFor(t *testing.T) {
|
||||
Frequency: valuer.MustParseTextDuration("1m"),
|
||||
}},
|
||||
RuleCondition: &ruletypes.RuleCondition{
|
||||
CompareOperator: ruletypes.ValueIsAbove,
|
||||
MatchType: ruletypes.AtleastOnce,
|
||||
AlertOnAbsent: true,
|
||||
Target: &target,
|
||||
AlertOnAbsent: true,
|
||||
CompositeQuery: &ruletypes.AlertCompositeQuery{
|
||||
QueryType: ruletypes.QueryTypeBuilder,
|
||||
Queries: []qbtypes.QueryEnvelope{{
|
||||
|
||||
@@ -70,49 +70,3 @@
|
||||
Object.defineProperty(window, 'Date', { value: FrozenDate, writable: true });
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script>
|
||||
// Storybook has no microphone. Chromium's recognizer asks for one and for
|
||||
// Google's speech service, and the `not-allowed` or `network` it reports makes
|
||||
// the assistant hide its mic for the rest of the tab. This one starts
|
||||
// listening at once and hears only what a story passes to `hear`.
|
||||
(() => {
|
||||
class StorySpeechRecognition extends EventTarget {
|
||||
static listening = null;
|
||||
lang = 'en-US';
|
||||
continuous = false;
|
||||
interimResults = false;
|
||||
onstart = null;
|
||||
onresult = null;
|
||||
onerror = null;
|
||||
onend = null;
|
||||
|
||||
start() {
|
||||
StorySpeechRecognition.listening = this;
|
||||
setTimeout(() => this.onstart?.());
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (StorySpeechRecognition.listening === this) {
|
||||
StorySpeechRecognition.listening = null;
|
||||
}
|
||||
setTimeout(() => this.onend?.());
|
||||
}
|
||||
|
||||
abort() {
|
||||
this.stop();
|
||||
}
|
||||
|
||||
/** An interim result: the words so far, still listening. */
|
||||
hear(transcript) {
|
||||
const result = Object.assign([{ transcript, confidence: 1 }], {
|
||||
isFinal: false,
|
||||
});
|
||||
this.onresult?.({ resultIndex: 0, results: [result] });
|
||||
}
|
||||
}
|
||||
|
||||
window.SpeechRecognition = StorySpeechRecognition;
|
||||
window.webkitSpeechRecognition = StorySpeechRecognition;
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ErrorEvent, StackFrame } from '@sentry/react';
|
||||
import { AxiosError, AxiosHeaders } from 'axios';
|
||||
|
||||
import {
|
||||
hasNoAppFrames,
|
||||
isExpectedRequestFailure,
|
||||
isExternalIntegrationError,
|
||||
SENTRY_IGNORE_ERRORS,
|
||||
} from '../sentryFilters';
|
||||
@@ -138,3 +140,36 @@ describe('SENTRY_IGNORE_ERRORS', () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isExpectedRequestFailure', () => {
|
||||
function axiosErrorWithStatus(status: number): AxiosError {
|
||||
const config = { headers: new AxiosHeaders() };
|
||||
return new AxiosError(
|
||||
`Request failed with status code ${status}`,
|
||||
AxiosError.ERR_BAD_REQUEST,
|
||||
config,
|
||||
undefined,
|
||||
{ status, statusText: '', headers: {}, config, data: {} },
|
||||
);
|
||||
}
|
||||
|
||||
it.each([401, 403])('drops a %i response', (status) => {
|
||||
expect(isExpectedRequestFailure(axiosErrorWithStatus(status))).toBe(true);
|
||||
});
|
||||
|
||||
it('drops a network error', () => {
|
||||
expect(
|
||||
isExpectedRequestFailure(
|
||||
new AxiosError('Network Error', AxiosError.ERR_NETWORK),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each([400, 404, 500, 503])('keeps a %i response', (status) => {
|
||||
expect(isExpectedRequestFailure(axiosErrorWithStatus(status))).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error that is not from axios', () => {
|
||||
expect(isExpectedRequestFailure(new Error('Network Error'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -40,6 +40,7 @@ import defaultRoutes, {
|
||||
} from './routes';
|
||||
import {
|
||||
hasNoAppFrames,
|
||||
isExpectedRequestFailure,
|
||||
isExternalIntegrationError,
|
||||
SENTRY_IGNORE_ERRORS,
|
||||
} from './sentryFilters';
|
||||
@@ -341,6 +342,9 @@ function App(): JSX.Element {
|
||||
if (error?.name === 'AbortError') {
|
||||
return null;
|
||||
}
|
||||
if (isExpectedRequestFailure(hint?.originalException)) {
|
||||
return null;
|
||||
}
|
||||
// Ignore benign Monaco cancellation errors (name 'Canceled').
|
||||
if (error?.name === 'Canceled') {
|
||||
return null;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ErrorEvent } from '@sentry/react';
|
||||
import { AxiosError, isAxiosError } from 'axios';
|
||||
|
||||
export const SENTRY_IGNORE_ERRORS = [
|
||||
// A tab that outlived a deploy requests hashed assets the new build no longer
|
||||
@@ -14,6 +15,18 @@ export const SENTRY_IGNORE_ERRORS = [
|
||||
/Called on script loaded before session recording is available/,
|
||||
];
|
||||
|
||||
// Not UI bugs: 401/403 come from the session or role, ERR_NETWORK from a
|
||||
// dropped connection.
|
||||
export function isExpectedRequestFailure(error: unknown): boolean {
|
||||
if (!isAxiosError(error)) {
|
||||
return false;
|
||||
}
|
||||
const status = error.response?.status;
|
||||
return (
|
||||
error.code === AxiosError.ERR_NETWORK || status === 401 || status === 403
|
||||
);
|
||||
}
|
||||
|
||||
const APP_ASSETS_PATH = '/assets/';
|
||||
|
||||
// Frames without a position are `[native code]`, which says nothing about the
|
||||
|
||||
@@ -45,7 +45,6 @@ import type {
|
||||
GetRuleHistoryTopContributorsParams,
|
||||
GetRuleHistoryTopContributorsPathParameters,
|
||||
ListRuleViews200,
|
||||
ListRules200,
|
||||
ListRulesV3200,
|
||||
ListRulesV3Params,
|
||||
PatchRuleByID200,
|
||||
@@ -427,85 +426,6 @@ export const useUpdateRuleView = <
|
||||
> => {
|
||||
return useMutation(getUpdateRuleViewMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint lists all alert rules with their current evaluation state. Deprecated: use ListRulesV3, which supports filtering, sorting and pagination.
|
||||
* @deprecated
|
||||
* @summary List alert rules
|
||||
*/
|
||||
export const listRules = (signal?: AbortSignal) => {
|
||||
return GeneratedAPIInstance<ListRules200>({
|
||||
url: `/api/v2/rules`,
|
||||
method: 'GET',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListRulesQueryKey = () => {
|
||||
return [`/api/v2/rules`] as const;
|
||||
};
|
||||
|
||||
export const getListRulesQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listRules>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(options?: {
|
||||
query?: UseQueryOptions<Awaited<ReturnType<typeof listRules>>, TError, TData>;
|
||||
}) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListRulesQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listRules>>> = ({
|
||||
signal,
|
||||
}) => listRules(signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listRules>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListRulesQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listRules>>
|
||||
>;
|
||||
export type ListRulesQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* @summary List alert rules
|
||||
*/
|
||||
|
||||
export function useListRules<
|
||||
TData = Awaited<ReturnType<typeof listRules>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(options?: {
|
||||
query?: UseQueryOptions<Awaited<ReturnType<typeof listRules>>, TError, TData>;
|
||||
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListRulesQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* @summary List alert rules
|
||||
*/
|
||||
export const invalidateListRules = async (
|
||||
queryClient: QueryClient,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListRulesQueryKey() },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* This endpoint creates a new alert rule
|
||||
* @summary Create alert rule
|
||||
|
||||
@@ -829,33 +829,26 @@ export interface AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTy
|
||||
export enum AlertmanagertypesChannelConfigVariantGithubComSigNozSignozPkgTypesAlertmanagertypesChannelJiraConfigDTOKind {
|
||||
jira = 'jira',
|
||||
}
|
||||
export interface AlertmanagertypesChannelJiraCloudAuthDTO {
|
||||
export interface AlertmanagertypesChannelJiraAuthDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @format password
|
||||
* @description The Atlassian API token paired with email. A secret; returned by create, update and fetch by ID, never by list.
|
||||
* @description The Atlassian API token paired with email. Required when deployment is cloud. A secret; returned by create, update and fetch by ID, never by list.
|
||||
*/
|
||||
apiToken: string;
|
||||
apiToken?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The Atlassian account email used for basic auth.
|
||||
* @description The Atlassian account email used for basic auth. Required when deployment is cloud.
|
||||
*/
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface AlertmanagertypesChannelJiraSelfHostedAuthDTO {
|
||||
email?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @format password
|
||||
* @description The Jira personal access token, sent as a Bearer header. A secret; returned by create, update and fetch by ID, never by list.
|
||||
* @description The Jira personal access token, sent as a Bearer header. Required when deployment is selfhosted. A secret; returned by create, update and fetch by ID, never by list.
|
||||
*/
|
||||
pat: string;
|
||||
pat?: string;
|
||||
}
|
||||
|
||||
export type AlertmanagertypesChannelJiraAuthDTO =
|
||||
| AlertmanagertypesChannelJiraCloudAuthDTO
|
||||
| AlertmanagertypesChannelJiraSelfHostedAuthDTO;
|
||||
|
||||
export enum AlertmanagertypesJiraDeploymentDTO {
|
||||
cloud = 'cloud',
|
||||
selfhosted = 'selfhosted',
|
||||
@@ -3611,6 +3604,7 @@ export enum CoretypesKindDTO {
|
||||
'logs-field' = 'logs-field',
|
||||
'traces-field' = 'traces-field',
|
||||
'metrics-field' = 'metrics-field',
|
||||
'llm-pricing-rule' = 'llm-pricing-rule',
|
||||
}
|
||||
export enum CoretypesTypeDTO {
|
||||
user = 'user',
|
||||
@@ -7079,7 +7073,7 @@ export interface Querybuildertypesv5QueryBuilderFormulaDTO {
|
||||
*/
|
||||
functions?: Querybuildertypesv5FunctionDTO[] | null;
|
||||
/**
|
||||
* @description Accepted but currently ignored; the computed values are returned unfiltered.
|
||||
* @description A filter on the formula values, referencing the formula by its name or as __result, for example F1 > 0. A time series keeps only the points that match and drops a series with none left; a scalar result keeps only the rows that match.
|
||||
*/
|
||||
having?: Querybuildertypesv5HavingDTO;
|
||||
/**
|
||||
@@ -12966,23 +12960,10 @@ export interface RuletypesRuleConditionDTO {
|
||||
* @description Whether to fire a nodata alert when the query returns no data. Defaults to false.
|
||||
*/
|
||||
alertOnAbsent?: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description anomaly_rule only: the anomaly detection algorithm. The supported value is standard.
|
||||
*/
|
||||
algorithm?: string;
|
||||
/**
|
||||
* @description The queries whose result is compared against the thresholds.
|
||||
*/
|
||||
compositeQuery: RuletypesAlertCompositeQueryDTO;
|
||||
/**
|
||||
* @description schemaVersion v1 only: which points in the window must satisfy op. Accepted as at_least_once, all_the_times, on_average, in_total or last, their aliases avg and sum, or the legacy codes as strings, '1' to '5'. Required for v1; v2alpha1 sets matchType on each threshold.
|
||||
*/
|
||||
matchType?: RuletypesMatchTypeDTO;
|
||||
/**
|
||||
* @description schemaVersion v1 only: how the value is compared with target. Accepted as above, below, equal, not_equal, above_or_equal, below_or_equal or outside_bounds, their symbols, or the legacy codes as strings, '1' to '7'. Required for v1; v2alpha1 sets op on each threshold.
|
||||
*/
|
||||
op?: RuletypesCompareOperatorDTO;
|
||||
/**
|
||||
* @type boolean
|
||||
* @description Whether a series is skipped until it has at least requiredNumPoints points in the window. Defaults to false.
|
||||
@@ -13002,17 +12983,6 @@ export interface RuletypesRuleConditionDTO {
|
||||
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery.
|
||||
*/
|
||||
selectedQueryName: string;
|
||||
/**
|
||||
* @type number,null
|
||||
* @format double
|
||||
* @description schemaVersion v1 only: the value compared against, in targetUnit. Required for v1; v2alpha1 sets target on each threshold.
|
||||
*/
|
||||
target?: number | null;
|
||||
/**
|
||||
* @type string
|
||||
* @description schemaVersion v1 only: the unit of target, such as percent or ms. Converted to compositeQuery.unit before comparison when the two differ.
|
||||
*/
|
||||
targetUnit?: string;
|
||||
/**
|
||||
* @description The thresholds to evaluate, as a kind and spec.
|
||||
*/
|
||||
@@ -13048,20 +13018,10 @@ export interface RuletypesPostableRuleDTO {
|
||||
* @description Whether the rule is paused. A disabled rule is neither evaluated nor notifies. Defaults to false.
|
||||
*/
|
||||
disabled?: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description The lookback window as a Go duration such as 5m. Only read when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec instead.
|
||||
*/
|
||||
evalWindow?: string;
|
||||
/**
|
||||
* @description The evaluation window, as a kind and spec.
|
||||
*/
|
||||
evaluation: RuletypesEvaluationEnvelopeDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
|
||||
*/
|
||||
frequency?: string;
|
||||
/**
|
||||
* @type object
|
||||
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
|
||||
@@ -13071,11 +13031,6 @@ export interface RuletypesPostableRuleDTO {
|
||||
* @description Grouping, re-notification and routing behaviour.
|
||||
*/
|
||||
notificationSettings: RuletypesNotificationSettingsDTO;
|
||||
/**
|
||||
* @type array
|
||||
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
|
||||
*/
|
||||
preferredChannels?: string[];
|
||||
/**
|
||||
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries.
|
||||
*/
|
||||
@@ -13086,16 +13041,6 @@ export interface RuletypesPostableRuleDTO {
|
||||
* @description The rule payload schema.
|
||||
*/
|
||||
schemaVersion: RuletypesPostableRuleDTOSchemaVersion;
|
||||
/**
|
||||
* @type string
|
||||
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
|
||||
*/
|
||||
source?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The query payload version. Nothing reads it.
|
||||
*/
|
||||
version?: string;
|
||||
}
|
||||
|
||||
export interface RuletypesPostableRuleViewDTO {
|
||||
@@ -13160,20 +13105,10 @@ export interface RuletypesRuleDTO {
|
||||
* @description Whether the rule is paused. A disabled rule is neither evaluated nor notifies. Defaults to false.
|
||||
*/
|
||||
disabled?: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description The lookback window as a Go duration such as 5m. Only read when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec instead.
|
||||
*/
|
||||
evalWindow?: string;
|
||||
/**
|
||||
* @description The evaluation window, as a kind and spec.
|
||||
*/
|
||||
evaluation: RuletypesEvaluationEnvelopeDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
|
||||
*/
|
||||
frequency?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The unique identifier of the rule.
|
||||
@@ -13188,11 +13123,6 @@ export interface RuletypesRuleDTO {
|
||||
* @description Grouping, re-notification and routing behaviour.
|
||||
*/
|
||||
notificationSettings: RuletypesNotificationSettingsDTO;
|
||||
/**
|
||||
* @type array
|
||||
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
|
||||
*/
|
||||
preferredChannels?: string[];
|
||||
/**
|
||||
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries.
|
||||
*/
|
||||
@@ -13203,11 +13133,6 @@ export interface RuletypesRuleDTO {
|
||||
* @description The rule payload schema.
|
||||
*/
|
||||
schemaVersion: RuletypesRuleDTOSchemaVersion;
|
||||
/**
|
||||
* @type string
|
||||
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
|
||||
*/
|
||||
source?: string;
|
||||
/**
|
||||
* @description The current evaluation state: inactive, pending, recovering, firing, nodata or disabled.
|
||||
*/
|
||||
@@ -13221,11 +13146,6 @@ export interface RuletypesRuleDTO {
|
||||
* @type string
|
||||
*/
|
||||
updatedBy?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The query payload version. Nothing reads it.
|
||||
*/
|
||||
version?: string;
|
||||
}
|
||||
|
||||
export enum RuletypesThresholdKindDTO {
|
||||
@@ -16783,17 +16703,6 @@ export type UpdateRuleView200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListRules200 = {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
data: RuletypesRuleDTO[];
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type CreateRule201 = {
|
||||
data: RuletypesRuleDTO;
|
||||
/**
|
||||
|
||||
1
frontend/src/assets/Logos/pixeltable.svg
Normal file
1
frontend/src/assets/Logos/pixeltable.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><rect x="1.25" y="1.25" width="21.5" height="21.5" rx="3.5" fill="none" stroke="#7A8291" stroke-width="1.5"/><g fill="#7A8291"><circle cx="7" cy="4.5" r="1.05"/><circle cx="9.5" cy="4.5" r="1.05"/><circle cx="12" cy="4.5" r="1.05"/><circle cx="14.5" cy="4.5" r="1.05"/><circle cx="7" cy="7" r="1.05"/><circle cx="17" cy="7" r="1.05"/><circle cx="7" cy="9.5" r="1.05"/><circle cx="17" cy="9.5" r="1.05"/><circle cx="7" cy="12" r="1.05"/><circle cx="9.5" cy="12" r="1.05"/><circle cx="12" cy="12" r="1.05"/><circle cx="14.5" cy="12" r="1.05"/><circle cx="7" cy="14.5" r="1.05"/><circle cx="7" cy="17" r="1.05"/><circle cx="7" cy="19.5" r="1.05"/></g></svg>
|
||||
|
After Width: | Height: | Size: 726 B |
@@ -1,18 +1,13 @@
|
||||
import { ConfigProvider, Select } from 'antd';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
import { Select } from 'antd';
|
||||
import cx from 'classnames';
|
||||
|
||||
import type { UpdatedWindow } from '../dsl/types';
|
||||
import type { CreatorOption } from '../types';
|
||||
import { UPDATED_OPTIONS } from './constants';
|
||||
import MultiSelectFilter from './MultiSelectFilter';
|
||||
|
||||
import styles from './FilterZone.module.scss';
|
||||
|
||||
// The option checkbox already marks selection, so selected rows stay regular weight.
|
||||
const CREATOR_SELECT_THEME = {
|
||||
components: { Select: { optionSelectedFontWeight: 400 } },
|
||||
};
|
||||
|
||||
interface Props {
|
||||
createdBy: string[];
|
||||
updated: UpdatedWindow;
|
||||
@@ -52,36 +47,16 @@ function FilterChips({
|
||||
|
||||
return (
|
||||
<div className={styles.chips}>
|
||||
<ConfigProvider theme={CREATOR_SELECT_THEME}>
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
allowClear
|
||||
className={cx(styles.select, styles.selectWide)}
|
||||
placeholder="Created by"
|
||||
value={createdBy}
|
||||
options={creatorOptionsData}
|
||||
optionFilterProp="label"
|
||||
maxTagCount={1}
|
||||
menuItemSelectedIcon={null}
|
||||
data-testid={`${testIdPrefix}-filter-created-by`}
|
||||
disabled={disabled}
|
||||
onClear={onClearCreatedBy}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div className={styles.creatorOption}>
|
||||
<div className={styles.creatorCheck}>
|
||||
<Checkbox
|
||||
color="primary"
|
||||
value={createdBy.includes(option.value as string)}
|
||||
/>
|
||||
</div>
|
||||
<span className={styles.creatorLabel}>{option.label}</span>
|
||||
</div>
|
||||
)}
|
||||
onChange={(value): void => onCreatedByChange(value as string[])}
|
||||
onDropdownVisibleChange={runOnClose}
|
||||
/>
|
||||
</ConfigProvider>
|
||||
<MultiSelectFilter
|
||||
value={createdBy}
|
||||
options={creatorOptionsData}
|
||||
placeholder="Created by"
|
||||
testId={`${testIdPrefix}-filter-created-by`}
|
||||
disabled={disabled}
|
||||
onClear={onClearCreatedBy}
|
||||
onChange={onCreatedByChange}
|
||||
onDropdownVisibleChange={runOnClose}
|
||||
/>
|
||||
<Select
|
||||
showSearch
|
||||
className={cx(styles.select, styles.selectNarrow)}
|
||||
|
||||
@@ -86,21 +86,21 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Created-by option: a presentational checkbox + label (antd handles the toggle).
|
||||
.creatorOption {
|
||||
// Multi-select option: a presentational checkbox + label (antd handles the toggle).
|
||||
.checkOption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.creatorCheck {
|
||||
.checkOptionBox {
|
||||
// Flex, not block: a line box would shift with the check mark's baseline.
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.creatorLabel {
|
||||
.checkOptionLabel {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { ConfigProvider, Select } from 'antd';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
import cx from 'classnames';
|
||||
|
||||
import styles from './FilterZone.module.scss';
|
||||
|
||||
// The option checkbox already marks selection, so selected rows stay regular weight.
|
||||
const CHECKBOX_SELECT_THEME = {
|
||||
components: { Select: { optionSelectedFontWeight: 400 } },
|
||||
};
|
||||
|
||||
export interface MultiSelectFilterOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
value: string[];
|
||||
options: MultiSelectFilterOption[];
|
||||
placeholder: string;
|
||||
testId: string;
|
||||
onChange: (values: string[]) => void;
|
||||
onClear?: () => void;
|
||||
onDropdownVisibleChange?: (open: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function MultiSelectFilter({
|
||||
value,
|
||||
options,
|
||||
placeholder,
|
||||
testId,
|
||||
onChange,
|
||||
onClear,
|
||||
onDropdownVisibleChange,
|
||||
disabled = false,
|
||||
}: Props): JSX.Element {
|
||||
return (
|
||||
<ConfigProvider theme={CHECKBOX_SELECT_THEME}>
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
allowClear
|
||||
className={cx(styles.select, styles.selectWide)}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
options={options}
|
||||
optionFilterProp="label"
|
||||
maxTagCount={1}
|
||||
menuItemSelectedIcon={null}
|
||||
data-testid={testId}
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div className={styles.checkOption}>
|
||||
<div className={styles.checkOptionBox}>
|
||||
<Checkbox
|
||||
color="primary"
|
||||
value={value.includes(option.value as string)}
|
||||
/>
|
||||
</div>
|
||||
<span className={styles.checkOptionLabel}>{option.label}</span>
|
||||
</div>
|
||||
)}
|
||||
onChange={(next): void => onChange(next as string[])}
|
||||
onDropdownVisibleChange={onDropdownVisibleChange}
|
||||
/>
|
||||
</ConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default MultiSelectFilter;
|
||||
@@ -48,22 +48,59 @@ export function QuerySearchV2Provider({
|
||||
}, [initialExpression, store]);
|
||||
|
||||
const isInitialized = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!isInitialized.current && urlExpression) {
|
||||
const cleanedExpression = getUserExpressionFromCombined(
|
||||
initialExpression,
|
||||
urlExpression,
|
||||
);
|
||||
store.getState().initializeFromUrl(cleanedExpression);
|
||||
isInitialized.current = true;
|
||||
}
|
||||
}, [urlExpression, initialExpression, store]);
|
||||
|
||||
const lastCommittedRef = useRef(committedExpression);
|
||||
useEffect(() => {
|
||||
if (isInitialized.current || !urlExpression) {
|
||||
setUrlExpression(committedExpression || null);
|
||||
return;
|
||||
}
|
||||
}, [committedExpression, setUrlExpression, urlExpression]);
|
||||
isInitialized.current = true;
|
||||
store
|
||||
.getState()
|
||||
.initializeFromUrl(
|
||||
getUserExpressionFromCombined(initialExpression, urlExpression),
|
||||
);
|
||||
}, [urlExpression, initialExpression, store]);
|
||||
|
||||
// Back and Forward. Reads the browser's URL: after a write, nuqs can briefly
|
||||
// report the value it replaced.
|
||||
useEffect(() => {
|
||||
const onPopState = (): void => {
|
||||
isInitialized.current = true;
|
||||
const urlValue = new URLSearchParams(window.location.search).get(
|
||||
queryParamKey,
|
||||
);
|
||||
const expression = urlValue
|
||||
? getUserExpressionFromCombined(initialExpression, urlValue)
|
||||
: '';
|
||||
// Another param changed; keep any text typed but not run.
|
||||
if (expression === store.getState().committedExpression) {
|
||||
return;
|
||||
}
|
||||
// Already in the URL, so the write below must not run for it.
|
||||
lastCommittedRef.current = expression;
|
||||
if (expression) {
|
||||
store.getState().initializeFromUrl(expression);
|
||||
} else {
|
||||
store.getState().resetExpression();
|
||||
}
|
||||
};
|
||||
window.addEventListener('popstate', onPopState);
|
||||
return (): void => window.removeEventListener('popstate', onPopState);
|
||||
}, [queryParamKey, initialExpression, store]);
|
||||
|
||||
// Write only when the committed filter changes, never in reply to a URL change.
|
||||
useEffect(() => {
|
||||
if (committedExpression === lastCommittedRef.current) {
|
||||
return;
|
||||
}
|
||||
lastCommittedRef.current = committedExpression;
|
||||
isInitialized.current = true;
|
||||
const next = committedExpression || null;
|
||||
if (next === urlExpression) {
|
||||
return;
|
||||
}
|
||||
void setUrlExpression(next);
|
||||
}, [committedExpression, urlExpression, setUrlExpression]);
|
||||
|
||||
useEffect(() => {
|
||||
return (): void => {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
|
||||
import {
|
||||
useExpression,
|
||||
useInitialExpression,
|
||||
useInputExpression,
|
||||
useQuerySearchInitialExpressionProp,
|
||||
useQuerySearchOnChange,
|
||||
useQuerySearchOnRun,
|
||||
@@ -34,10 +35,22 @@ function createWrapper(
|
||||
};
|
||||
}
|
||||
|
||||
// Back or Forward. nuqs has not caught up yet, so its value is still the old one.
|
||||
function goTo(expression: string | null): void {
|
||||
act(() => {
|
||||
const search = expression
|
||||
? `?${new URLSearchParams({ testExpression: expression })}`
|
||||
: '';
|
||||
window.history.pushState(null, '', `/${search}`);
|
||||
window.dispatchEvent(new PopStateEvent('popstate'));
|
||||
});
|
||||
}
|
||||
|
||||
function useTestHooks(): {
|
||||
expression: string;
|
||||
userExpression: string;
|
||||
initialExpression: string;
|
||||
inputExpression: string;
|
||||
querySearchInitialExpressionProp: string | undefined;
|
||||
onChange: (expr: string) => void;
|
||||
onRun: (expr: string) => void;
|
||||
@@ -46,6 +59,7 @@ function useTestHooks(): {
|
||||
expression: useExpression(),
|
||||
userExpression: useUserExpression(),
|
||||
initialExpression: useInitialExpression(),
|
||||
inputExpression: useInputExpression(),
|
||||
querySearchInitialExpressionProp: useQuerySearchInitialExpressionProp(),
|
||||
onChange: useQuerySearchOnChange(),
|
||||
onRun: useQuerySearchOnRun(),
|
||||
@@ -56,6 +70,7 @@ describe('QuerySearchExpressionProvider', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockUrlValue = null;
|
||||
window.history.replaceState(null, '', '/');
|
||||
});
|
||||
|
||||
it('should provide initial context values', () => {
|
||||
@@ -110,6 +125,96 @@ describe('QuerySearchExpressionProvider', () => {
|
||||
expect(result.current.expression).toBe('status = 500');
|
||||
});
|
||||
|
||||
it('follows Back and Forward from the browser URL', () => {
|
||||
mockUrlValue = 'status = 500';
|
||||
const { result } = renderHook(() => useTestHooks(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
goTo('status = 404');
|
||||
|
||||
expect(result.current.userExpression).toBe('status = 404');
|
||||
expect(mockSetQueryState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears the filter on Back to a URL without the param', () => {
|
||||
mockUrlValue = 'status = 500';
|
||||
const { result } = renderHook(() => useTestHooks(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
goTo(null);
|
||||
|
||||
expect(result.current.userExpression).toBe('');
|
||||
expect(mockSetQueryState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps text typed but not run when Back changes another param', () => {
|
||||
mockUrlValue = 'status = 500';
|
||||
const { result } = renderHook(() => useTestHooks(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
act(() => {
|
||||
result.current.onChange('status = 404');
|
||||
});
|
||||
|
||||
goTo('status = 500');
|
||||
|
||||
expect(result.current.inputExpression).toBe('status = 404');
|
||||
});
|
||||
|
||||
it('writes a run filter to the URL once and ignores it coming back', () => {
|
||||
const { result, rerender } = renderHook(() => useTestHooks(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.onRun('status = 500');
|
||||
});
|
||||
expect(mockSetQueryState).toHaveBeenCalledTimes(1);
|
||||
expect(mockSetQueryState).toHaveBeenLastCalledWith('status = 500');
|
||||
|
||||
mockUrlValue = 'status = 500';
|
||||
rerender();
|
||||
|
||||
expect(result.current.userExpression).toBe('status = 500');
|
||||
expect(mockSetQueryState).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps a run filter when the URL briefly reports the value it replaced', () => {
|
||||
mockUrlValue = 'status = 500';
|
||||
const { result, rerender } = renderHook(() => useTestHooks(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.onRun('status = 404');
|
||||
});
|
||||
mockUrlValue = 'status = 404';
|
||||
rerender();
|
||||
mockUrlValue = 'status = 500';
|
||||
rerender();
|
||||
|
||||
expect(result.current.userExpression).toBe('status = 404');
|
||||
});
|
||||
|
||||
it('keeps a newer run when a late URL value arrives after an empty mount', () => {
|
||||
const { result, rerender } = renderHook(() => useTestHooks(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.onRun('status = 500');
|
||||
});
|
||||
act(() => {
|
||||
result.current.onRun('status = 404');
|
||||
});
|
||||
mockUrlValue = 'status = 500';
|
||||
rerender();
|
||||
|
||||
expect(result.current.userExpression).toBe('status = 404');
|
||||
});
|
||||
|
||||
it('should throw error when used outside provider', () => {
|
||||
expect(() => {
|
||||
renderHook(() => useExpression());
|
||||
|
||||
@@ -15,11 +15,41 @@ $max-recents-shown: 5;
|
||||
Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
|
||||
'Helvetica Neue', sans-serif;
|
||||
|
||||
.query-where-clause-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
// single-line editor: 36px .cm-line + 1px .cm-content border on each side
|
||||
--button-height: 38px;
|
||||
|
||||
.query-where-clause-editor-container {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.query-where-clause-editor-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
// The field draws one outline around the scope chip and the editor, so
|
||||
// the editor inside draws none
|
||||
&.hasScopeChip {
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
padding-left: var(--spacing-3);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: 2px;
|
||||
background: var(--l1-background);
|
||||
--query-builder-v2-border-color: transparent;
|
||||
--query-builder-v2-background-color: transparent;
|
||||
|
||||
.query-where-clause-editor {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.query-search-initial-scope-label {
|
||||
position: absolute;
|
||||
left: 8px;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CircleCheck, Info, TriangleAlert, Filter } from '@signozhq/icons';
|
||||
import {
|
||||
CircleCheck,
|
||||
Info,
|
||||
TriangleAlert,
|
||||
Filter,
|
||||
Play,
|
||||
} from '@signozhq/icons';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -16,6 +22,7 @@ import { githubLight } from '@uiw/codemirror-theme-github';
|
||||
import CodeMirror, { EditorView, keymap, Prec } from '@uiw/react-codemirror';
|
||||
import { Button, Card, Collapse, Popover, Tooltip } from 'antd';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button as SignozButton } from '@signozhq/ui/button';
|
||||
import cx from 'classnames';
|
||||
import {
|
||||
negationQueryOperatorSuggestions,
|
||||
@@ -59,6 +66,7 @@ import {
|
||||
SUGGESTION_FETCH_DEBOUNCE_MS,
|
||||
SUGGESTIONS_SECTION,
|
||||
} from './constants';
|
||||
import { ScopeChip } from './ScopeChip/ScopeChip';
|
||||
import {
|
||||
combineInitialAndUserExpression,
|
||||
dedupeOptionsByLabel,
|
||||
@@ -105,9 +113,14 @@ interface QuerySearchProps {
|
||||
signalSource?: string;
|
||||
hardcodedAttributeKeys?: QueryKeyDataSuggestionsProps[];
|
||||
onRun?: (query: string) => void;
|
||||
showRunButton?: boolean;
|
||||
/** Shows the Run button busy while the page's queries fetch. */
|
||||
isLoadingQueries?: boolean;
|
||||
showFilterSuggestionsWithoutMetric?: boolean;
|
||||
/** When set, the editor shows only the user expression; API/filter uses `initial AND (user)`. */
|
||||
initialExpression?: string;
|
||||
/** Shows `initialExpression` as a locked chip in the field instead of the scope icon. */
|
||||
showScopeChip?: boolean;
|
||||
/** When set, replaces the generic value-suggestion API with a custom fetcher. */
|
||||
valueSuggestionsOverride?: (
|
||||
key: string,
|
||||
@@ -125,10 +138,13 @@ function QuerySearch({
|
||||
queryData,
|
||||
dataSource,
|
||||
onRun,
|
||||
showRunButton,
|
||||
isLoadingQueries,
|
||||
signalSource,
|
||||
hardcodedAttributeKeys,
|
||||
showFilterSuggestionsWithoutMetric,
|
||||
initialExpression,
|
||||
showScopeChip: showScopeChipProp,
|
||||
metricNamespace,
|
||||
valueSuggestionsOverride,
|
||||
}: QuerySearchProps): JSX.Element {
|
||||
@@ -148,6 +164,7 @@ function QuerySearch({
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
|
||||
const isScopedFilter = initialExpression !== undefined;
|
||||
const showScopeChip = !!showScopeChipProp && !!initialExpression;
|
||||
|
||||
const validateExpressionForEditor = useCallback(
|
||||
(editorDoc: string): void => {
|
||||
@@ -173,6 +190,18 @@ function QuerySearch({
|
||||
[],
|
||||
);
|
||||
|
||||
const handleRun = useCallback((): void => {
|
||||
if (!onRun) {
|
||||
return;
|
||||
}
|
||||
const user = getCurrentExpression();
|
||||
onRun(
|
||||
isScopedFilter
|
||||
? combineInitialAndUserExpression(initialExpression ?? '', user)
|
||||
: user,
|
||||
);
|
||||
}, [onRun, getCurrentExpression, isScopedFilter, initialExpression]);
|
||||
|
||||
const updateEditorValue = useCallback(
|
||||
(value: string, options: { skipOnChange?: boolean } = {}): void => {
|
||||
const view = editorRef.current;
|
||||
@@ -1557,169 +1586,182 @@ function QuerySearch({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="query-where-clause-editor-container">
|
||||
{isScopedFilter ? (
|
||||
<Tooltip title={initialExpression || ''} placement="left">
|
||||
<div className="query-search-initial-scope-label">
|
||||
<Filter
|
||||
<div className="query-where-clause-row">
|
||||
<div
|
||||
className={cx('query-where-clause-editor-container', {
|
||||
hasScopeChip: showScopeChip,
|
||||
})}
|
||||
>
|
||||
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
|
||||
{isScopedFilter && !showScopeChip ? (
|
||||
<Tooltip title={initialExpression || ''} placement="left">
|
||||
<div className="query-search-initial-scope-label">
|
||||
<Filter
|
||||
size={14}
|
||||
style={{
|
||||
opacity: 0.9,
|
||||
color: isDarkMode ? Color.BG_VANILLA_100 : Color.BG_INK_500,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip
|
||||
title={<div data-log-detail-ignore="true">{getTooltipContent()}</div>}
|
||||
placement="left"
|
||||
>
|
||||
<a
|
||||
href="https://signoz.io/docs/userguide/search-syntax/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 8,
|
||||
right: validation.isValid === false && getCurrentExpression() ? 40 : 8, // Move left when error shown
|
||||
cursor: 'help',
|
||||
zIndex: 10,
|
||||
transition: 'right 0.2s ease',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
color: '#8c8c8c',
|
||||
}}
|
||||
onClick={(e): void => e.stopPropagation()}
|
||||
>
|
||||
<Info
|
||||
size={14}
|
||||
style={{
|
||||
opacity: 0.9,
|
||||
color: isDarkMode ? Color.BG_VANILLA_100 : Color.BG_INK_500,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</a>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
<Tooltip
|
||||
title={<div data-log-detail-ignore="true">{getTooltipContent()}</div>}
|
||||
placement="left"
|
||||
>
|
||||
<a
|
||||
href="https://signoz.io/docs/userguide/search-syntax/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 8,
|
||||
right: validation.isValid === false && getCurrentExpression() ? 40 : 8, // Move left when error shown
|
||||
cursor: 'help',
|
||||
zIndex: 10,
|
||||
transition: 'right 0.2s ease',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
color: '#8c8c8c',
|
||||
}}
|
||||
onClick={(e): void => e.stopPropagation()}
|
||||
>
|
||||
<Info
|
||||
size={14}
|
||||
style={{
|
||||
opacity: 0.9,
|
||||
color: isDarkMode ? Color.BG_VANILLA_100 : Color.BG_INK_500,
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
</Tooltip>
|
||||
|
||||
<CodeMirror
|
||||
theme={isDarkMode ? copilot : githubLight}
|
||||
onChange={handleChange}
|
||||
onUpdate={handleUpdate}
|
||||
onCreateEditor={handleEditorCreate}
|
||||
data-testid="query-where-clause-editor"
|
||||
className={cx('query-where-clause-editor', {
|
||||
isValid: validation.isValid === true,
|
||||
hasErrors: validation.errors.length > 0,
|
||||
hasInitialExpression: isScopedFilter,
|
||||
})}
|
||||
extensions={[
|
||||
autocompletion({
|
||||
override: [combinedSuggestions],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
stopEventsExtension,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
...completionKeymap,
|
||||
{
|
||||
key: 'Escape',
|
||||
run: closeCompletion,
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Enter to add new line
|
||||
// and instead run a custom action
|
||||
run: (): boolean => true,
|
||||
},
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Mod-Enter to add new line
|
||||
// and instead run a custom action
|
||||
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
|
||||
run: (): boolean => {
|
||||
if (onRun && typeof onRun === 'function') {
|
||||
const user = getCurrentExpression();
|
||||
onRun(
|
||||
isScopedFilter
|
||||
? combineInitialAndUserExpression(initialExpression ?? '', user)
|
||||
: user,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Shift-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Shift-Enter to add new line
|
||||
run: (): boolean => true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
]}
|
||||
placeholder={placeholder}
|
||||
basicSetup={{
|
||||
lineNumbers: false,
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
/>
|
||||
|
||||
{getCurrentExpression() && validation.isValid === false && !isFocused && (
|
||||
<div
|
||||
className={cx('query-status-container', {
|
||||
<CodeMirror
|
||||
theme={isDarkMode ? copilot : githubLight}
|
||||
onChange={handleChange}
|
||||
onUpdate={handleUpdate}
|
||||
onCreateEditor={handleEditorCreate}
|
||||
data-testid="query-where-clause-editor"
|
||||
className={cx('query-where-clause-editor', {
|
||||
isValid: validation.isValid === true,
|
||||
hasErrors: validation.errors.length > 0,
|
||||
hasInitialExpression: isScopedFilter && !showScopeChip,
|
||||
})}
|
||||
data-testid="query-validation-status"
|
||||
>
|
||||
<Popover
|
||||
placement="bottomRight"
|
||||
showArrow={false}
|
||||
content={
|
||||
<div className="query-status-content">
|
||||
<div className="query-status-content-header">
|
||||
<div className="query-validation">
|
||||
<div className="query-validation-errors">
|
||||
{validation.errors.map((error) => (
|
||||
<div key={error.message} className="query-validation-error">
|
||||
<div className="query-validation-error">
|
||||
{error.line}:{error.column} - {error.message}
|
||||
extensions={[
|
||||
autocompletion({
|
||||
override: [combinedSuggestions],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
stopEventsExtension,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
...completionKeymap,
|
||||
{
|
||||
key: 'Escape',
|
||||
run: closeCompletion,
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Enter to add new line
|
||||
// and instead run a custom action
|
||||
run: (): boolean => true,
|
||||
},
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Mod-Enter to add new line
|
||||
// and instead run a custom action
|
||||
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
|
||||
run: (): boolean => {
|
||||
handleRun();
|
||||
return true;
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Shift-Enter',
|
||||
preventDefault: true,
|
||||
// Prevent default behavior of Shift-Enter to add new line
|
||||
run: (): boolean => true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
]}
|
||||
placeholder={placeholder}
|
||||
basicSetup={{
|
||||
lineNumbers: false,
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
/>
|
||||
|
||||
{getCurrentExpression() && validation.isValid === false && !isFocused && (
|
||||
<div
|
||||
className={cx('query-status-container', {
|
||||
hasErrors: validation.errors.length > 0,
|
||||
})}
|
||||
data-testid="query-validation-status"
|
||||
>
|
||||
<Popover
|
||||
placement="bottomRight"
|
||||
showArrow={false}
|
||||
content={
|
||||
<div className="query-status-content">
|
||||
<div className="query-status-content-header">
|
||||
<div className="query-validation">
|
||||
<div className="query-validation-errors">
|
||||
{validation.errors.map((error) => (
|
||||
<div key={error.message} className="query-validation-error">
|
||||
<div className="query-validation-error">
|
||||
{error.line}:{error.column} - {error.message}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
overlayClassName="query-status-popover"
|
||||
>
|
||||
{validation.isValid ? (
|
||||
<Button
|
||||
type="text"
|
||||
icon={<CircleCheck size="md" />}
|
||||
className="periscope-btn ghost"
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
type="text"
|
||||
icon={<TriangleAlert size={14} color={Color.BG_CHERRY_500} />}
|
||||
className="periscope-btn ghost"
|
||||
/>
|
||||
)}
|
||||
</Popover>
|
||||
</div>
|
||||
}
|
||||
overlayClassName="query-status-popover"
|
||||
>
|
||||
{validation.isValid ? (
|
||||
<Button
|
||||
type="text"
|
||||
icon={<CircleCheck size="md" />}
|
||||
className="periscope-btn ghost"
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
type="text"
|
||||
icon={<TriangleAlert size={14} color={Color.BG_CHERRY_500} />}
|
||||
className="periscope-btn ghost"
|
||||
/>
|
||||
)}
|
||||
</Popover>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{showRunButton && (
|
||||
<SignozButton
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<Play size={14} />}
|
||||
loading={isLoadingQueries}
|
||||
onClick={handleRun}
|
||||
testId="query-search-run-button"
|
||||
>
|
||||
Run
|
||||
</SignozButton>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1813,12 +1855,15 @@ function QuerySearch({
|
||||
|
||||
QuerySearch.defaultProps = {
|
||||
onRun: undefined,
|
||||
showRunButton: false,
|
||||
isLoadingQueries: false,
|
||||
signalSource: '',
|
||||
hardcodedAttributeKeys: undefined,
|
||||
placeholder:
|
||||
"Enter your filter query (e.g., http.status_code >= 500 AND service.name = 'frontend')",
|
||||
showFilterSuggestionsWithoutMetric: false,
|
||||
initialExpression: undefined,
|
||||
showScopeChip: false,
|
||||
};
|
||||
|
||||
export default QuerySearch;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
.scopeChip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 420px;
|
||||
padding: var(--spacing-1) var(--spacing-3);
|
||||
border-radius: 2px;
|
||||
background: var(--l3-background);
|
||||
color: var(--l2-foreground);
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.scopeIcon {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.scopeMore {
|
||||
flex: none;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
// The editor beside it is CodeMirror on the copilot theme in dark and
|
||||
// githubLight in light; the chip borrows those token colours so one filter
|
||||
// does not read as two
|
||||
.scopeKey {
|
||||
color: #939da5;
|
||||
}
|
||||
|
||||
.scopeOperator {
|
||||
color: #939da5;
|
||||
}
|
||||
|
||||
.scopeValue {
|
||||
color: #5bec95;
|
||||
}
|
||||
|
||||
:global(.lightMode) {
|
||||
.scopeKey,
|
||||
.scopeOperator {
|
||||
color: #005cc5;
|
||||
}
|
||||
|
||||
.scopeValue {
|
||||
color: #032f62;
|
||||
}
|
||||
}
|
||||
|
||||
.scopeExpression {
|
||||
font-family: var(--font-mono, monospace);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Lock } from '@signozhq/icons';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { extractQueryPairs } from 'utils/queryContextUtils';
|
||||
|
||||
import styles from './ScopeChip.module.scss';
|
||||
|
||||
interface ScopeChipProps {
|
||||
expression: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The locked half of the filter. It reads like the editor beside it: the last
|
||||
* clause carries the relation, the ones scoping it are counted instead.
|
||||
*/
|
||||
export function ScopeChip({ expression }: ScopeChipProps): JSX.Element {
|
||||
const clauses = useMemo(() => extractQueryPairs(expression), [expression]);
|
||||
const relation = clauses[clauses.length - 1];
|
||||
|
||||
return (
|
||||
<Tooltip title={expression} side="top">
|
||||
<span className={styles.scopeChip} data-testid="query-search-scope-chip">
|
||||
<Lock size={12} className={styles.scopeIcon} />
|
||||
<span className={styles.scopeExpression}>
|
||||
{relation ? (
|
||||
<>
|
||||
<span className={styles.scopeKey}>{relation.key}</span>
|
||||
<span className={styles.scopeOperator}>{` ${relation.operator} `}</span>
|
||||
<span className={styles.scopeValue}>{relation.value}</span>
|
||||
</>
|
||||
) : (
|
||||
expression
|
||||
)}
|
||||
</span>
|
||||
{clauses.length > 1 && (
|
||||
<span className={styles.scopeMore}>{`+${clauses.length - 1}`}</span>
|
||||
)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -224,6 +224,134 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
await waitFor(() => expect(onRun).toHaveBeenCalled(), { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('does not render the run button by default', () => {
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.logs.builder.queryData[0]}
|
||||
dataSource={DataSource.LOGS}
|
||||
onRun={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('query-search-run-button'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onRun with the editor text when the run button is clicked', async () => {
|
||||
const onRun = jest.fn() as jest.MockedFunction<(q: string) => void>;
|
||||
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={{
|
||||
...initialQueriesMap.logs.builder.queryData[0],
|
||||
filter: { expression: SAMPLE_STATUS_QUERY },
|
||||
}}
|
||||
dataSource={DataSource.LOGS}
|
||||
onRun={onRun}
|
||||
showRunButton
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
expect(onRun).toHaveBeenCalledWith(SAMPLE_STATUS_QUERY);
|
||||
});
|
||||
|
||||
it('shows the locked scope as a chip in place of the scope icon', () => {
|
||||
const scope = "kind_string = 'Client' AND http_host = 'api.example.com'";
|
||||
const { container } = render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
dataSource={DataSource.TRACES}
|
||||
initialExpression={scope}
|
||||
showScopeChip
|
||||
/>,
|
||||
);
|
||||
|
||||
const chip = screen.getByTestId('query-search-scope-chip');
|
||||
expect(chip).toHaveTextContent("http_host = 'api.example.com'");
|
||||
expect(chip).toHaveTextContent('+1');
|
||||
expect(chip).not.toHaveTextContent('kind_string');
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the scope icon unless the chip is asked for', () => {
|
||||
const { container } = render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
dataSource={DataSource.TRACES}
|
||||
initialExpression="kind_string = 'Client'"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('query-search-scope-chip'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the run button busy while the queries load', () => {
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.logs.builder.queryData[0]}
|
||||
dataSource={DataSource.LOGS}
|
||||
onRun={jest.fn()}
|
||||
showRunButton
|
||||
isLoadingQueries
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('query-search-run-button')).toHaveAttribute(
|
||||
'aria-busy',
|
||||
'true',
|
||||
);
|
||||
});
|
||||
|
||||
it('runs the locked scope combined with the editor text', async () => {
|
||||
const onRun = jest.fn() as jest.MockedFunction<(q: string) => void>;
|
||||
const scope = "kind_string = 'Client'";
|
||||
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={{
|
||||
...initialQueriesMap.traces.builder.queryData[0],
|
||||
filter: { expression: SAMPLE_STATUS_QUERY },
|
||||
}}
|
||||
dataSource={DataSource.TRACES}
|
||||
onRun={onRun}
|
||||
initialExpression={scope}
|
||||
showRunButton
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
expect(onRun).toHaveBeenCalledWith(`${scope} AND (${SAMPLE_STATUS_QUERY})`);
|
||||
});
|
||||
|
||||
it('initializes CodeMirror with expression from queryData.filter.expression on mount', async () => {
|
||||
const testExpression =
|
||||
"http.status_code >= 500 AND service.name = 'frontend'";
|
||||
|
||||
@@ -53,7 +53,6 @@ export enum QueryParams {
|
||||
variables = 'variables',
|
||||
version = 'version',
|
||||
source = 'source',
|
||||
showClassicCreateAlertsPage = 'showClassicCreateAlertsPage',
|
||||
isTestAlert = 'isTestAlert',
|
||||
yAxisUnit = 'yAxisUnit',
|
||||
ruleName = 'ruleName',
|
||||
|
||||
@@ -26,7 +26,6 @@ export const REACT_QUERY_KEY = {
|
||||
REMOVE_ALERT_RULE: 'REMOVE_ALERT_RULE',
|
||||
CLONE_ALERT_RULE: 'CLONE_ALERT_RULE',
|
||||
GET_HOST_LIST: 'GET_HOST_LIST',
|
||||
UPDATE_ALERT_RULE: 'UPDATE_ALERT_RULE',
|
||||
GET_TRACE_V2_WATERFALL: 'GET_TRACE_V2_WATERFALL',
|
||||
GET_TRACE_V4_WATERFALL: 'GET_TRACE_V4_WATERFALL',
|
||||
GET_TRACE_AGGREGATIONS: 'GET_TRACE_AGGREGATIONS',
|
||||
@@ -70,8 +69,6 @@ export const REACT_QUERY_KEY = {
|
||||
GET_NESTED_ENDPOINTS_LIST: 'GET_NESTED_ENDPOINTS_LIST',
|
||||
GET_ENDPOINT_METRICS_DATA: 'GET_ENDPOINT_METRICS_DATA',
|
||||
GET_ENDPOINT_STATUS_CODE_DATA: 'GET_ENDPOINT_STATUS_CODE_DATA',
|
||||
GET_ENDPOINT_RATE_OVER_TIME_DATA: 'GET_ENDPOINT_RATE_OVER_TIME_DATA',
|
||||
GET_ENDPOINT_LATENCY_OVER_TIME_DATA: 'GET_ENDPOINT_LATENCY_OVER_TIME_DATA',
|
||||
GET_ENDPOINT_DROPDOWN_DATA: 'GET_ENDPOINT_DROPDOWN_DATA',
|
||||
GET_ENDPOINT_DEPENDENT_SERVICES_DATA: 'GET_ENDPOINT_DEPENDENT_SERVICES_DATA',
|
||||
GET_ENDPOINT_STATUS_CODE_BAR_CHARTS_DATA:
|
||||
|
||||
@@ -32,7 +32,7 @@ import styles from './AIAssistantModal.module.scss';
|
||||
*/
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
export default function AIAssistantModal(): JSX.Element | null {
|
||||
const { pathname } = useAppLocation();
|
||||
const { pathname, search } = useAppLocation();
|
||||
const [showHistory, setShowHistory] = useState(false);
|
||||
|
||||
const isOpen = useAIAssistantStore((s) => s.isModalOpen);
|
||||
@@ -93,12 +93,12 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
closeModal();
|
||||
// Router state tells AIAssistantPage to skip its mount-time Opened fire:
|
||||
// the assistant was already open in the modal, so this is a surface
|
||||
// switch, not a new open.
|
||||
// switch, not a new open. `returnTo` is where its minimize button comes back to.
|
||||
navigate(
|
||||
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
|
||||
{ state: { fromInApp: true } },
|
||||
{ state: { fromInApp: true, returnTo: `${pathname}${search}` } },
|
||||
);
|
||||
}, [activeConversationId, closeModal]);
|
||||
}, [activeConversationId, closeModal, pathname, search]);
|
||||
|
||||
const handleNew = useCallback(() => {
|
||||
void logEvent(AIAssistantEvents.NewChatClicked, {
|
||||
|
||||
@@ -1,37 +1,6 @@
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--l1-border);
|
||||
background: var(--l1-background);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 4px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
z-index: 10;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 1px;
|
||||
width: 2px;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
background: var(--accent-primary);
|
||||
}
|
||||
.panel:global(.floating-panel) {
|
||||
background: var(--l2-background);
|
||||
box-shadow: var(--shadow-dialog);
|
||||
}
|
||||
|
||||
.header {
|
||||
@@ -41,7 +10,7 @@
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
flex-shrink: 0;
|
||||
background: var(--l1-background);
|
||||
background: var(--l2-background);
|
||||
}
|
||||
|
||||
.title {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useLayoutEffect, useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { History, Maximize2, Plus, X } from '@signozhq/icons';
|
||||
import { History, Maximize2, Minus, Plus, X } from '@signozhq/icons';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import { BOTTOM_STRIP_HEIGHT } from 'container/BottomStrip';
|
||||
import { FloatingPanel } from 'periscope/components/FloatingPanel';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -22,8 +24,24 @@ import styles from './AIAssistantPanel.module.scss';
|
||||
const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
|
||||
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
|
||||
|
||||
const PANEL_WIDTH = 420;
|
||||
const PANEL_HEIGHT = 601;
|
||||
const PANEL_MIN_WIDTH = 380;
|
||||
const PANEL_MIN_HEIGHT = 500;
|
||||
const PANEL_MARGIN = 8;
|
||||
const PANEL_RESIZE_EDGES = {
|
||||
top: true,
|
||||
right: true,
|
||||
bottom: true,
|
||||
left: true,
|
||||
topRight: false,
|
||||
bottomRight: false,
|
||||
bottomLeft: false,
|
||||
topLeft: false,
|
||||
};
|
||||
|
||||
export default function AIAssistantPanel(): JSX.Element | null {
|
||||
const { pathname } = useAppLocation();
|
||||
const { pathname, search } = useAppLocation();
|
||||
const [showHistory, setShowHistory] = useState(false);
|
||||
|
||||
const isOpen = useAIAssistantStore((s) => s.isDrawerOpen);
|
||||
@@ -46,12 +64,12 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
closeDrawer();
|
||||
// Router state tells AIAssistantPage to skip its mount-time Opened fire:
|
||||
// the assistant was already open in the drawer, so this is a surface
|
||||
// switch, not a new open.
|
||||
// switch, not a new open. `returnTo` is where its minimize button comes back to.
|
||||
navigate(
|
||||
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
|
||||
{ state: { fromInApp: true } },
|
||||
{ state: { fromInApp: true, returnTo: `${pathname}${search}` } },
|
||||
);
|
||||
}, [activeConversationId, closeDrawer]);
|
||||
}, [activeConversationId, closeDrawer, pathname, search]);
|
||||
|
||||
const handleNew = useCallback(() => {
|
||||
void logEvent(AIAssistantEvents.NewChatClicked, {
|
||||
@@ -72,11 +90,6 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
setShowHistory(false);
|
||||
}, []);
|
||||
|
||||
// ── Resize logic ──────────────────────────────────────────────────────────
|
||||
const [panelWidth, setPanelWidth] = useState(380);
|
||||
const dragStartX = useRef(0);
|
||||
const dragStartWidth = useRef(0);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const shouldOffsetChatSupport = isOpen && !isFullScreenPage;
|
||||
|
||||
@@ -88,7 +101,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
if (shouldOffsetChatSupport) {
|
||||
document.body.style.setProperty(
|
||||
AI_ASSISTANT_PANEL_WIDTH_VAR,
|
||||
`${panelWidth}px`,
|
||||
`${PANEL_WIDTH}px`,
|
||||
);
|
||||
} else {
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
@@ -98,46 +111,40 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
document.body.classList.remove(AI_ASSISTANT_PANEL_OPEN_CLASS);
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
};
|
||||
}, [isFullScreenPage, isOpen, panelWidth]);
|
||||
|
||||
const handleResizeMouseDown = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragStartX.current = e.clientX;
|
||||
dragStartWidth.current = panelWidth;
|
||||
|
||||
const onMouseMove = (ev: MouseEvent): void => {
|
||||
// Panel is on the right; dragging left (lower clientX) increases width
|
||||
const delta = dragStartX.current - ev.clientX;
|
||||
const next = Math.min(Math.max(dragStartWidth.current + delta, 380), 800);
|
||||
setPanelWidth(next);
|
||||
};
|
||||
|
||||
const onMouseUp = (): void => {
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
},
|
||||
[panelWidth],
|
||||
);
|
||||
}, [isFullScreenPage, isOpen]);
|
||||
|
||||
if (!isOpen || isFullScreenPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const panelHeight = Math.max(
|
||||
PANEL_MIN_HEIGHT,
|
||||
Math.min(
|
||||
PANEL_HEIGHT,
|
||||
window.innerHeight - BOTTOM_STRIP_HEIGHT - 2 * PANEL_MARGIN,
|
||||
),
|
||||
);
|
||||
|
||||
return (
|
||||
<VariantContext.Provider value="panel">
|
||||
<div className={styles.panel} style={{ width: panelWidth }}>
|
||||
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
|
||||
<div className={styles.resizeHandle} onMouseDown={handleResizeMouseDown} />
|
||||
<div className={styles.header}>
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
className={styles.panel}
|
||||
width={PANEL_WIDTH}
|
||||
height={panelHeight}
|
||||
minWidth={PANEL_MIN_WIDTH}
|
||||
minHeight={PANEL_MIN_HEIGHT}
|
||||
enableResizing={PANEL_RESIZE_EDGES}
|
||||
defaultPosition={{
|
||||
x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN,
|
||||
// Never above the viewport, where the header could not be dragged back.
|
||||
y: Math.max(
|
||||
0,
|
||||
window.innerHeight - BOTTOM_STRIP_HEIGHT - PANEL_MARGIN - panelHeight,
|
||||
),
|
||||
}}
|
||||
>
|
||||
<div className={`${styles.header} floating-panel__drag-handle`}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={18} />
|
||||
<span>Noz</span>
|
||||
@@ -170,6 +177,19 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip title="Minimize">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={closeDrawer}
|
||||
aria-label="Minimize panel"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip title="Open full screen">
|
||||
<Button
|
||||
disabledTooltip="Start a conversation first"
|
||||
@@ -207,7 +227,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
<ConversationView conversationId={activeConversationId} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</FloatingPanel>
|
||||
</VariantContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,38 @@
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
|
||||
// The full page sits the thread in a faint pane whose bottom edge runs behind the input.
|
||||
&.fullPage {
|
||||
position: relative;
|
||||
// Lets the pane sit behind the thread without dropping under the page.
|
||||
isolation: isolate;
|
||||
padding: 13px 13px 0 1px;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: 12px 12px 32px 0;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-3);
|
||||
background: var(--l2-background-60);
|
||||
opacity: 0.4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// Fades the pane's foot into the page on either side of the input.
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 46px;
|
||||
background: linear-gradient(to bottom, transparent, var(--l1-background));
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
@@ -34,7 +66,18 @@
|
||||
border-top: 1px solid var(--l1-border);
|
||||
|
||||
&.compact {
|
||||
padding: 8px;
|
||||
padding: 0;
|
||||
// Same colour as the panel's outline.
|
||||
border-top-color: var(--l2-border);
|
||||
}
|
||||
|
||||
&.fullPage {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
width: min(768px, 100%);
|
||||
margin: 0 auto;
|
||||
padding: 0 0 var(--spacing-6);
|
||||
border-top: none;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
|
||||
@@ -26,6 +26,7 @@ export default function ConversationView({
|
||||
}: ConversationViewProps): JSX.Element {
|
||||
const variant = useVariant();
|
||||
const isCompact = variant === 'panel';
|
||||
const isFullPage = variant === 'page';
|
||||
const location = useAppLocation();
|
||||
|
||||
const conversation = useAIAssistantStore(
|
||||
@@ -110,30 +111,72 @@ export default function ConversationView({
|
||||
);
|
||||
|
||||
// Wall-clock timestamp of the current streaming start, used to compute
|
||||
// `secondsSinceStart` on Cancel clicked. Cleared whenever streaming ends.
|
||||
const streamStartedAtRef = useRef<number | null>(null);
|
||||
// `secondsSinceStart` on Cancel clicked and to keep the input's sweep in step
|
||||
// across a remount. Cleared whenever streaming ends.
|
||||
const [streamStartedAt, setStreamStartedAt] = useState<number | null>(null);
|
||||
useEffect(() => {
|
||||
if (!isStreamingHere) {
|
||||
streamStartedAtRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (streamStartedAtRef.current === null) {
|
||||
streamStartedAtRef.current = Date.now();
|
||||
}
|
||||
setStreamStartedAt((prev) => (isStreamingHere ? (prev ?? Date.now()) : null));
|
||||
}, [isStreamingHere]);
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
const startedAt = streamStartedAtRef.current;
|
||||
void logEvent(AIAssistantEvents.CancelClicked, {
|
||||
threadId: analyticsCtx.threadId,
|
||||
secondsSinceStart:
|
||||
startedAt !== null ? Math.round((Date.now() - startedAt) / 1000) : null,
|
||||
streamStartedAt !== null
|
||||
? Math.round((Date.now() - streamStartedAt) / 1000)
|
||||
: null,
|
||||
});
|
||||
cancelStream(conversationId);
|
||||
}, [cancelStream, conversationId, analyticsCtx.threadId]);
|
||||
}, [cancelStream, conversationId, analyticsCtx.threadId, streamStartedAt]);
|
||||
|
||||
const messages = conversation?.messages ?? [];
|
||||
const showDisclaimer = messages.length > 0;
|
||||
|
||||
// When this chat's first message went out; drives the empty state's exit across a remount.
|
||||
const firstMessageId = messages[0]?.id;
|
||||
const isLoadingHere = isLoadingThread || Boolean(conversation?.isHydrating);
|
||||
const [firstSend, setFirstSend] = useState<{
|
||||
conversationId: string;
|
||||
messageCount: number;
|
||||
firstMessageId: string | undefined;
|
||||
isLoading: boolean;
|
||||
at: number | null;
|
||||
}>({
|
||||
conversationId,
|
||||
messageCount: messages.length,
|
||||
firstMessageId,
|
||||
isLoading: isLoadingHere,
|
||||
at: null,
|
||||
});
|
||||
if (
|
||||
firstSend.conversationId !== conversationId ||
|
||||
firstSend.messageCount !== messages.length ||
|
||||
firstSend.isLoading !== isLoadingHere
|
||||
) {
|
||||
// A loaded thread arrives while loading; a send adds the user's own first message.
|
||||
const isFirstSend =
|
||||
firstSend.conversationId === conversationId &&
|
||||
firstSend.messageCount === 0 &&
|
||||
!firstSend.isLoading &&
|
||||
messages.length === 1 &&
|
||||
messages[0].role === 'user' &&
|
||||
isStreamingHere;
|
||||
// Renaming to the server's thread id keeps the first message; another chat starts clean.
|
||||
const isSameChat =
|
||||
firstSend.firstMessageId !== undefined &&
|
||||
firstSend.firstMessageId === firstMessageId;
|
||||
let at = isSameChat ? firstSend.at : null;
|
||||
if (isFirstSend) {
|
||||
at = Date.now();
|
||||
}
|
||||
setFirstSend({
|
||||
conversationId,
|
||||
messageCount: messages.length,
|
||||
firstMessageId,
|
||||
isLoading: isLoadingHere,
|
||||
at,
|
||||
});
|
||||
}
|
||||
const inputDisabled =
|
||||
isStreamingHere ||
|
||||
isLoadingThread ||
|
||||
@@ -150,8 +193,12 @@ export default function ConversationView({
|
||||
inputDisabledTooltip = 'Answer the pending question first';
|
||||
}
|
||||
|
||||
const conversationClass = cx(styles.conversation, {
|
||||
[styles.fullPage]: isFullPage,
|
||||
});
|
||||
const inputWrapperClass = cx(styles.inputWrapper, {
|
||||
[styles.compact]: isCompact,
|
||||
[styles.fullPage]: isFullPage,
|
||||
});
|
||||
const disclaimerClass = cx(styles.disclaimer, {
|
||||
[styles.compact]: isCompact,
|
||||
@@ -165,7 +212,7 @@ export default function ConversationView({
|
||||
const isHydrating = Boolean(conversation?.isHydrating);
|
||||
if ((isLoadingThread || isHydrating) && messages.length === 0) {
|
||||
return (
|
||||
<div className={styles.conversation}>
|
||||
<div className={conversationClass}>
|
||||
<ConversationSkeleton />
|
||||
<div className={inputWrapperClass}>
|
||||
<ChatInput
|
||||
@@ -182,12 +229,13 @@ export default function ConversationView({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.conversation}>
|
||||
<div className={conversationClass}>
|
||||
<VirtualizedMessages
|
||||
key={conversationId}
|
||||
conversationId={conversationId}
|
||||
messages={messages}
|
||||
isStreaming={isStreamingHere}
|
||||
firstSendAt={firstSend.at}
|
||||
onSendSuggestedPrompt={(text): void => {
|
||||
handleSend(
|
||||
text,
|
||||
@@ -209,6 +257,8 @@ export default function ConversationView({
|
||||
disabled={inputDisabled}
|
||||
disabledTooltip={inputDisabledTooltip}
|
||||
isStreaming={isStreamingHere}
|
||||
streamStartedAt={streamStartedAt}
|
||||
showNozPeek={messages.length === 0 && !isStreamingHere}
|
||||
autoContexts={autoContexts}
|
||||
onDismissAutoContext={handleDismissAutoContext}
|
||||
/>
|
||||
|
||||
18
frontend/src/container/AIAssistant/_bareInput.scss
Normal file
18
frontend/src/container/AIAssistant/_bareInput.scss
Normal file
@@ -0,0 +1,18 @@
|
||||
// Strips a `@signozhq/ui` Input inside this element down to its text: no box, no focus ring.
|
||||
@mixin bare-input {
|
||||
--input-height: 20px;
|
||||
--input-padding: 0;
|
||||
--input-border-width: 0;
|
||||
--input-background: transparent;
|
||||
--input-hover-background: transparent;
|
||||
--input-focus-background: transparent;
|
||||
--input-focus-outline-width: 0;
|
||||
--input-box-shadow: none;
|
||||
--input-font-size: var(--periscope-font-size-base);
|
||||
--input-line-height: 20px;
|
||||
--input-placeholder-color: color-mix(
|
||||
in srgb,
|
||||
var(--l2-foreground),
|
||||
transparent 40%
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: var(--spacing-6);
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
margin-top: 16px;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
|
||||
// Background, padding-x, and rounding are inherited from the parent
|
||||
// bubble — the section sits inside the assistant bubble as its last
|
||||
@@ -15,32 +12,48 @@
|
||||
}
|
||||
|
||||
.heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
font-feature-settings:
|
||||
'tnum' on,
|
||||
'lnum' on,
|
||||
'zero' on,
|
||||
'ss01' on;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
.headingIcon {
|
||||
color: var(--primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// One action per line, each in the sent-message bubble.
|
||||
.list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-5);
|
||||
--button-height: auto;
|
||||
--button-padding: var(--spacing-4) var(--spacing-6);
|
||||
--button-border-radius: 8px;
|
||||
--button-font-size: var(--periscope-font-size-base);
|
||||
--button-size-line-height: 20px;
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-variant-outlined-background-color: var(--l3-background-60);
|
||||
--button-variant-outlined-border: none;
|
||||
--button-variant-outlined-color: var(--l2-foreground);
|
||||
--button-variant-outlined-hover-background-color: var(--l3-background);
|
||||
--button-variant-outlined-hover-color: var(--l1-foreground);
|
||||
|
||||
// Buttons don't inherit the page font; the tooltip takes over their data-slot.
|
||||
> button {
|
||||
font-family: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.chipLabel {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.chipState {
|
||||
|
||||
@@ -28,19 +28,7 @@ import ROUTES from 'constants/routes';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
import {
|
||||
ArchiveRestore,
|
||||
BookOpen,
|
||||
Check,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
Filter,
|
||||
MessageCircle,
|
||||
RotateCcw,
|
||||
Sparkles,
|
||||
TriangleAlert,
|
||||
Undo,
|
||||
} from '@signozhq/icons';
|
||||
import { Check, TriangleAlert } from '@signozhq/icons';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -115,34 +103,6 @@ interface ChipResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** Maps each MessageActionKindDTO to its display icon. */
|
||||
function ActionIcon({
|
||||
kind,
|
||||
size = 12,
|
||||
}: {
|
||||
kind: MessageActionDTO['kind'];
|
||||
size?: number;
|
||||
}): JSX.Element {
|
||||
switch (kind) {
|
||||
case MessageActionKindDTO.undo:
|
||||
return <Undo size={size} />;
|
||||
case MessageActionKindDTO.revert:
|
||||
return <RotateCcw size={size} />;
|
||||
case MessageActionKindDTO.restore:
|
||||
return <ArchiveRestore size={size} />;
|
||||
case MessageActionKindDTO.follow_up:
|
||||
return <MessageCircle size={size} />;
|
||||
case MessageActionKindDTO.open_resource:
|
||||
return <Eye size={size} />;
|
||||
case MessageActionKindDTO.open_docs:
|
||||
return <BookOpen size={size} />;
|
||||
case MessageActionKindDTO.apply_filter:
|
||||
return <Filter size={size} />;
|
||||
default:
|
||||
return <ExternalLink size={size} />;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent emits `action.query` as the SigNoz REST query-range request body:
|
||||
*
|
||||
@@ -578,10 +538,7 @@ export default function ActionsSection({
|
||||
|
||||
return (
|
||||
<div className={styles.section}>
|
||||
<div className={styles.heading}>
|
||||
<Sparkles size={12} className={styles.headingIcon} />
|
||||
<span className={styles.headingText}>Suggested actions</span>
|
||||
</div>
|
||||
<div className={styles.heading}>Suggested actions</div>
|
||||
|
||||
<div className={styles.list}>
|
||||
{actions.map((action, i) => {
|
||||
@@ -607,13 +564,11 @@ export default function ActionsSection({
|
||||
openTarget !== null &&
|
||||
isOnResourcePage(openTarget.path, { pathname, search });
|
||||
|
||||
let icon: JSX.Element;
|
||||
let icon: JSX.Element | undefined;
|
||||
if (isSuccess) {
|
||||
icon = <Check size={12} />;
|
||||
icon = <Check size={14} />;
|
||||
} else if (isError) {
|
||||
icon = <TriangleAlert size={12} />;
|
||||
} else {
|
||||
icon = <ActionIcon kind={action.kind} />;
|
||||
icon = <TriangleAlert size={14} />;
|
||||
}
|
||||
|
||||
const chip = (
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
// Collapsed activity summary — one row that hides the underlying
|
||||
// thinking + tool-call steps. Reuses the same quiet treatment as
|
||||
// ThinkingStep / ToolCallStep so it sits flush in the assistant bubble.
|
||||
// The summary row a finished run of thinking + tool-call steps folds behind.
|
||||
.activityGroup {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
@@ -9,15 +7,17 @@
|
||||
.activityHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 0;
|
||||
gap: 3px;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
color: var(--l3-foreground);
|
||||
color: var(--l2-foreground);
|
||||
user-select: none;
|
||||
transition: color 0.12s ease;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
|
||||
&:hover {
|
||||
@@ -25,31 +25,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
.sparkleIcon {
|
||||
flex-shrink: 0;
|
||||
color: var(--accent-primary);
|
||||
|
||||
&.iconPulsing {
|
||||
animation: activityGroupPulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes activityGroupPulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.55;
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.activitySummary {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 400;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.005em;
|
||||
}
|
||||
|
||||
.toggleChevron {
|
||||
@@ -60,5 +44,19 @@
|
||||
.activityBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 2px 0 4px;
|
||||
padding: var(--spacing-2) 0;
|
||||
}
|
||||
|
||||
.soloBody {
|
||||
padding: var(--spacing-2) 0 var(--spacing-2) var(--spacing-4);
|
||||
}
|
||||
|
||||
.soloThought {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { ChevronDown, ChevronRight, Sparkles } from '@signozhq/icons';
|
||||
|
||||
import { formatTime } from 'utils/timeUtils';
|
||||
import { useState } from 'react';
|
||||
import { ChevronDown, ChevronRight } from '@signozhq/icons';
|
||||
|
||||
import { StreamingToolCall } from '../../types';
|
||||
import ThinkingStep, { ThinkingContent, thinkingLabel } from '../ThinkingStep';
|
||||
import ThinkingStep, { thinkingLabel } from '../ThinkingStep';
|
||||
import ToolCallStep, {
|
||||
getToolDisplayLabel,
|
||||
ToolCallContent,
|
||||
@@ -20,46 +17,30 @@ export type ActivityItem =
|
||||
interface ActivityGroupProps {
|
||||
items: ActivityItem[];
|
||||
/**
|
||||
* True only for the trailing activity group of an active stream — drives
|
||||
* the live "Working…" label and the elapsed-time tick (which re-stamps on
|
||||
* approval/clarification resume so wait time isn't counted).
|
||||
* True only for the trailing activity group of an active stream: its steps
|
||||
* show open with the running one shimmering, and fold away once it ends.
|
||||
*/
|
||||
isLive?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-item groups get a step-specific summary so the user doesn't see a
|
||||
* pointless "Worked through 1 step". Multi-item groups roll up into the
|
||||
* generic "Working… / Worked through N steps" treatment.
|
||||
* pointless "Worked through 1 step".
|
||||
*/
|
||||
function buildSummary(
|
||||
items: ActivityItem[],
|
||||
isLive: boolean,
|
||||
elapsed: number,
|
||||
): string {
|
||||
function buildSummary(items: ActivityItem[]): string {
|
||||
if (items.length === 1) {
|
||||
const [only] = items;
|
||||
if (only.kind === 'thinking') {
|
||||
return thinkingLabel(isLive);
|
||||
return thinkingLabel(false);
|
||||
}
|
||||
return getToolDisplayLabel(only.toolCall);
|
||||
}
|
||||
const stepLabel = `${items.length} steps`;
|
||||
if (!isLive) {
|
||||
return `Worked through ${stepLabel}`;
|
||||
}
|
||||
// Suppress the elapsed token until ≥ 1s — the first tick fires after
|
||||
// 1s anyway, and showing "0s" or "<1s" briefly adds noise.
|
||||
return elapsed >= 1000
|
||||
? `Working… · ${formatTime(elapsed / 1000)} · ${stepLabel}`
|
||||
: `Working… · ${stepLabel}`;
|
||||
return `Worked through ${items.length} steps`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single collapsed summary row that hides a run of thinking + tool-call steps.
|
||||
* Expands to show each underlying step inline. Used for every activity row
|
||||
* (including single-item ones) so all "what the agent did" rows share a
|
||||
* consistent ✨-led visual contract.
|
||||
* A run of thinking + tool-call steps on a timeline. While it runs the steps
|
||||
* show as they happen; once done they fold behind a summary row that opens them.
|
||||
*/
|
||||
export default function ActivityGroup({
|
||||
items,
|
||||
@@ -67,80 +48,56 @@ export default function ActivityGroup({
|
||||
}: ActivityGroupProps): JSX.Element {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
// Captures the moment this live phase started. Re-stamped on every
|
||||
// false→true transition so a stream that pauses on
|
||||
// approval/clarification and resumes doesn't roll the user's wait time
|
||||
// into the elapsed counter.
|
||||
const startedAtRef = useRef<number>(Date.now());
|
||||
const wasLiveRef = useRef<boolean>(isLive);
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLive && !wasLiveRef.current) {
|
||||
startedAtRef.current = Date.now();
|
||||
setElapsed(0);
|
||||
}
|
||||
wasLiveRef.current = isLive;
|
||||
|
||||
if (!isLive) {
|
||||
return undefined;
|
||||
}
|
||||
// Tick once per second — the display is integer-second precision, so
|
||||
// faster ticks would just re-render the bubble for no visible change.
|
||||
const id = window.setInterval(() => {
|
||||
setElapsed(Date.now() - startedAtRef.current);
|
||||
}, 1000);
|
||||
return (): void => window.clearInterval(id);
|
||||
}, [isLive]);
|
||||
|
||||
const summary = buildSummary(items, isLive, elapsed);
|
||||
const isSingle = items.length === 1;
|
||||
|
||||
const toggle = (): void => setExpanded((v) => !v);
|
||||
const [solo] = items;
|
||||
const isSolo = items.length === 1;
|
||||
|
||||
return (
|
||||
<div className={styles.activityGroup}>
|
||||
<div className={styles.activityHeader} onClick={toggle}>
|
||||
<Sparkles
|
||||
size={12}
|
||||
className={cx(styles.sparkleIcon, { [styles.iconPulsing]: isLive })}
|
||||
/>
|
||||
<span className={styles.activitySummary}>{summary}</span>
|
||||
{expanded ? (
|
||||
<ChevronDown size={12} className={styles.toggleChevron} />
|
||||
) : (
|
||||
<ChevronRight size={12} className={styles.toggleChevron} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{expanded && (
|
||||
<div className={styles.activityBody}>
|
||||
{isSingle ? (
|
||||
// Single-item: the outer chevron already provides disclosure,
|
||||
// so render the underlying content directly instead of wrapping
|
||||
// it in a second collapsible step row.
|
||||
items[0].kind === 'thinking' ? (
|
||||
<ThinkingContent content={items[0].content} />
|
||||
) : (
|
||||
<ToolCallContent toolCall={items[0].toolCall} />
|
||||
)
|
||||
{!isLive && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.activityHeader}
|
||||
onClick={toggle}
|
||||
aria-expanded={expanded}
|
||||
data-testid="ai-activity-toggle"
|
||||
>
|
||||
<span className={styles.activitySummary}>{buildSummary(items)}</span>
|
||||
{expanded ? (
|
||||
<ChevronDown size={14} className={styles.toggleChevron} />
|
||||
) : (
|
||||
items.map((item, i) => {
|
||||
// A thinking step is live only while it's the trailing item
|
||||
// in a trailing live group — once any later event (text or
|
||||
// tool) arrives, the pass is done.
|
||||
const isLastItem = i === items.length - 1;
|
||||
return item.kind === 'thinking' ? (
|
||||
<ThinkingStep
|
||||
key={item.id}
|
||||
content={item.content}
|
||||
isLive={isLive && isLastItem}
|
||||
/>
|
||||
) : (
|
||||
<ToolCallStep key={item.id} toolCall={item.toolCall} />
|
||||
);
|
||||
})
|
||||
<ChevronRight size={14} className={styles.toggleChevron} />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* The summary row already names a lone step, so show only what it did. */}
|
||||
{!isLive && expanded && isSolo && (
|
||||
<div className={styles.soloBody}>
|
||||
{solo.kind === 'thinking' ? (
|
||||
<p className={styles.soloThought}>{solo.content.trim()}</p>
|
||||
) : (
|
||||
<ToolCallContent toolCall={solo.toolCall} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(isLive || (expanded && !isSolo)) && (
|
||||
<div className={styles.activityBody}>
|
||||
{items.map((item, i) => {
|
||||
// The newest step of a live group stays live until the next event
|
||||
// lands, so a running reply always shows something in progress.
|
||||
const isStepLive = isLive && i === items.length - 1;
|
||||
return item.kind === 'thinking' ? (
|
||||
<ThinkingStep key={item.id} content={item.content} isLive={isStepLive} />
|
||||
) : (
|
||||
<ToolCallStep
|
||||
key={item.id}
|
||||
toolCall={item.toolCall}
|
||||
isLive={isStepLive}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
.step {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
// The dot sits on the title's line, and a line joins it to the next step's dot.
|
||||
.rail {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
align-self: stretch;
|
||||
width: 6px;
|
||||
padding-top: 7px;
|
||||
|
||||
// 4px clear of this dot and the next one, across both steps' 6px padding.
|
||||
// A lone step is no timeline, so it goes without the dot.
|
||||
.step:only-child & {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.step:not(:last-child) &::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 17px;
|
||||
bottom: -15px;
|
||||
left: 50%;
|
||||
width: 1px;
|
||||
background: var(--l2-border);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.dot {
|
||||
display: block;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--l3-border);
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
display: inline-flex;
|
||||
align-self: flex-start;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
max-width: 100%;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
font: inherit;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l1-foreground);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
button.title {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.live .title {
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
.titleText {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
// A highlight sweeps across the running step's title.
|
||||
.live & {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--shimmer-base) 0%,
|
||||
var(--shimmer-base) 35%,
|
||||
var(--l2-foreground) 50%,
|
||||
var(--shimmer-base) 65%,
|
||||
var(--shimmer-base) 100%
|
||||
);
|
||||
background-size: 300% 100%;
|
||||
background-clip: text;
|
||||
-webkit-background-clip: text;
|
||||
color: transparent;
|
||||
animation: titleShimmer 1.8s linear infinite;
|
||||
--shimmer-base: color-mix(in srgb, var(--l3-foreground), transparent 30%);
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes titleShimmer {
|
||||
from {
|
||||
background-position: 100% 0;
|
||||
}
|
||||
to {
|
||||
background-position: 0% 0;
|
||||
}
|
||||
}
|
||||
|
||||
.detail {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { ChevronDown, ChevronRight } from '@signozhq/icons';
|
||||
|
||||
import styles from './ActivityStep.module.scss';
|
||||
|
||||
interface ActivityStepProps {
|
||||
title: string;
|
||||
/** Still running: the title shimmers. */
|
||||
isLive?: boolean;
|
||||
/** Given only for steps whose detail opens on demand. */
|
||||
onToggle?: () => void;
|
||||
expanded?: boolean;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/** One step of the agent's work on a timeline: a dot, its title, and what it did. */
|
||||
export default function ActivityStep({
|
||||
title,
|
||||
isLive = false,
|
||||
onToggle,
|
||||
expanded = false,
|
||||
children,
|
||||
}: ActivityStepProps): JSX.Element {
|
||||
const titleText = <span className={styles.titleText}>{title}</span>;
|
||||
|
||||
return (
|
||||
<div className={cx(styles.step, { [styles.live]: isLive })}>
|
||||
<div className={styles.rail}>
|
||||
<span className={styles.dot} />
|
||||
</div>
|
||||
<div className={styles.content}>
|
||||
{onToggle ? (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.title}
|
||||
onClick={onToggle}
|
||||
aria-expanded={expanded}
|
||||
data-testid="ai-activity-step-toggle"
|
||||
>
|
||||
{titleText}
|
||||
{expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
</button>
|
||||
) : (
|
||||
<span className={styles.title}>{titleText}</span>
|
||||
)}
|
||||
{children && <div className={styles.detail}>{children}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,25 @@
|
||||
@use '../../_scrollbar' as *;
|
||||
|
||||
.card {
|
||||
border: 1px solid var(--l1-border);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 12px;
|
||||
background: var(--l1-background);
|
||||
padding: var(--spacing-6);
|
||||
background: var(--l2-background);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
gap: var(--spacing-6);
|
||||
width: 100%;
|
||||
|
||||
// Clear of whatever the reply shows above it.
|
||||
&:not(:first-child) {
|
||||
margin-top: var(--spacing-6);
|
||||
}
|
||||
|
||||
// Below the header, everything lines up with the title, clear of the icon.
|
||||
&:not(.decided) > :not(.header) {
|
||||
margin-left: calc(16px + var(--spacing-6));
|
||||
}
|
||||
|
||||
&.decided {
|
||||
border-color: var(--l2-border);
|
||||
background: transparent;
|
||||
@@ -23,7 +33,7 @@
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: var(--spacing-6);
|
||||
}
|
||||
|
||||
.shieldIcon {
|
||||
@@ -32,8 +42,9 @@
|
||||
}
|
||||
|
||||
.headerLabel {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
@@ -49,10 +60,10 @@
|
||||
}
|
||||
|
||||
.summary {
|
||||
font-size: 13px;
|
||||
color: var(--l1-foreground);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.diffSection {
|
||||
@@ -260,9 +271,12 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// The two choices split the row evenly.
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--spacing-6);
|
||||
--button-width: 100%;
|
||||
}
|
||||
|
||||
.statusIcon {
|
||||
|
||||
@@ -88,7 +88,7 @@ export default function ApprovalCard({
|
||||
return (
|
||||
<div className={styles.card}>
|
||||
<div className={styles.header}>
|
||||
<Shield size={13} className={styles.shieldIcon} />
|
||||
<Shield size={16} className={styles.shieldIcon} />
|
||||
<span className={styles.headerLabel}>Action requires approval</span>
|
||||
<span className={styles.resourceBadge}>
|
||||
{approval.actionType} · {approval.resourceType}
|
||||
@@ -194,7 +194,7 @@ export default function ApprovalCard({
|
||||
disabledTooltip="Wait for the response to finish"
|
||||
color="primary"
|
||||
variant="solid"
|
||||
size="sm"
|
||||
size="md"
|
||||
onClick={handleApprove}
|
||||
disabled={isStreaming}
|
||||
prefix={<Check />}
|
||||
@@ -204,7 +204,7 @@ export default function ApprovalCard({
|
||||
<Button
|
||||
disabledTooltip="Wait for the response to finish"
|
||||
variant="outlined"
|
||||
size="sm"
|
||||
size="md"
|
||||
color="secondary"
|
||||
onClick={handleReject}
|
||||
disabled={isStreaming}
|
||||
|
||||
@@ -1,76 +1,35 @@
|
||||
@use '../../_scrollbar' as *;
|
||||
@use '../../_bareInput' as *;
|
||||
|
||||
.input {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
background: var(--l1-background);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 8px;
|
||||
border: 1px solid var(--l1-border);
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-3);
|
||||
box-shadow: var(--shadow-dialog);
|
||||
position: relative;
|
||||
|
||||
// The panel already frames it.
|
||||
&.compact {
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.attachments {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: 8px 10px 0;
|
||||
}
|
||||
|
||||
.contextTags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.contextTag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l1-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 4px 6px 4px 8px;
|
||||
color: var(--l1-foreground);
|
||||
|
||||
button {
|
||||
height: auto !important;
|
||||
min-height: 0 !important;
|
||||
width: auto !important;
|
||||
}
|
||||
|
||||
// `auto` chips are derived from the URL (current page) — visually
|
||||
// distinguished by a dashed border + slightly muted text so the user
|
||||
// can tell them apart from explicit @-mentions. Tighter padding /
|
||||
// font-size keeps them visually subordinate to user `@`-picks.
|
||||
&.auto {
|
||||
border-style: dashed;
|
||||
color: var(--l2-foreground);
|
||||
background: transparent;
|
||||
font-size: 10px;
|
||||
padding: 2px 4px 2px 6px;
|
||||
gap: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
.contextTagContent {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
max-width: 220px;
|
||||
|
||||
.contextTagLabel {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.contextTagLabel {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding: 8px 10px 0;
|
||||
}
|
||||
|
||||
.attachmentChip {
|
||||
@@ -91,86 +50,78 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.composer {
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 4px;
|
||||
transition:
|
||||
border-color 0.15s,
|
||||
box-shadow 0.15s;
|
||||
|
||||
// Scope the focus ring to the textarea row only — the surrounding
|
||||
// chrome (context chips, "Add Context", mic, send) sits outside this
|
||||
// element and stays unaffected when the cursor enters the textarea.
|
||||
&:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
box-shadow: 0 0 0 1px
|
||||
color-mix(in srgb, var(--accent-primary), transparent 70%);
|
||||
}
|
||||
position: relative;
|
||||
padding: 9px 16px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
padding: 4px 10px 8px;
|
||||
}
|
||||
|
||||
.leftActions,
|
||||
.rightActions {
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
--button-height: 28px;
|
||||
--button-width: 28px;
|
||||
--button-max-width: 28px;
|
||||
--button-border-radius: 9999px;
|
||||
|
||||
.attachBtn {
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
.contextBtn {
|
||||
flex-shrink: 0;
|
||||
gap: 6px;
|
||||
border-style: dashed !important;
|
||||
padding-inline: 12px !important;
|
||||
// Send stays a solid grey until there is something to send.
|
||||
[data-color='primary'][aria-disabled='true'] {
|
||||
--button-primary-background-color: var(--l3-background);
|
||||
--button-primary-solid-foreground: var(--l2-foreground);
|
||||
--button-disabled-opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
resize: none;
|
||||
color: var(--l1-foreground);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
overflow-y: auto;
|
||||
font-family: inherit;
|
||||
// ComposerCaret draws the caret.
|
||||
caret-color: transparent;
|
||||
@include scrollbar(0.2rem);
|
||||
|
||||
&::placeholder {
|
||||
color: var(--l3-foreground);
|
||||
color: var(--l2-foreground);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
&::selection {
|
||||
background: var(--accent-primary);
|
||||
color: var(--l1-background);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.2;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
caret-color: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.charWarning {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
margin: 0 10px;
|
||||
padding: 6px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
@@ -180,60 +131,92 @@
|
||||
border-radius: var(--radius-2);
|
||||
}
|
||||
|
||||
.sendBtn {
|
||||
flex-shrink: 0;
|
||||
border-radius: var(--radius-2);
|
||||
// One 34px row: 13/20 text, a full-width band on hover.
|
||||
@mixin picker-row($padding-inline) {
|
||||
--button-height: 34px;
|
||||
// A long list scrolls; without this the rows squash to fit it.
|
||||
--button-flex-shrink: 0;
|
||||
--button-padding: 7px #{$padding-inline};
|
||||
--button-border-radius: 0;
|
||||
--button-justify-content: flex-start;
|
||||
--button-font-size: var(--periscope-font-size-base);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-variant-ghost-color: var(--l2-foreground);
|
||||
--button-variant-ghost-hover-color: var(--l1-foreground);
|
||||
--button-variant-ghost-hover-background-color: var(--l3-background);
|
||||
--button-focus-visible-outline: none;
|
||||
|
||||
&.stop {
|
||||
background: var(--accent-cherry) !important;
|
||||
border-color: var(--accent-cherry) !important;
|
||||
// Buttons don't inherit the page font.
|
||||
> [data-slot='button'] {
|
||||
font-family: inherit;
|
||||
letter-spacing: -0.005em;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
// Keyboard focus shows as the hover band rather than a ring.
|
||||
> [data-slot='button']:focus-visible {
|
||||
--button-variant-ghost-background-color: var(--l3-background);
|
||||
--button-variant-ghost-color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.contextPopover {
|
||||
width: 480px !important;
|
||||
max-width: min(92vw, 480px);
|
||||
margin-left: 16px;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
box-shadow: 0 16px 36px rgba(0, 0, 0, 0.3);
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
max-width: min(92vw, 532px);
|
||||
height: 326px;
|
||||
backdrop-filter: blur(20px);
|
||||
// Clip horizontal overflow so long entity titles can't poke past the
|
||||
// popover's right edge. Vertical overflow is handled inside
|
||||
// `.contextPopoverEntities`.
|
||||
overflow-x: hidden;
|
||||
|
||||
--popover-width: 532px;
|
||||
--popover-padding: 0;
|
||||
|
||||
z-index: 1000;
|
||||
--popover-background: var(--l3-background-60);
|
||||
--popover-border-color: var(--l2-border);
|
||||
--popover-border-radius: var(--radius-2);
|
||||
--popover-box-shadow: var(--shadow-dropdown);
|
||||
// Above the floating panel (999) and the popup chat (1050) it opens from.
|
||||
--popover-z-index: 1100;
|
||||
}
|
||||
|
||||
.contextPopoverContent {
|
||||
display: grid;
|
||||
grid-template-columns: 180px 1fr;
|
||||
min-height: 250px;
|
||||
grid-template-columns: 224px 1fr;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.contextPopoverLeft {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--l2-border);
|
||||
}
|
||||
|
||||
// Both columns open with a 44px header, so their bottom borders run as one divider.
|
||||
.contextPopoverLabel {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding: 0 14px;
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
line-height: 1;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
.contextPopoverCategories {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
border-right: 1px solid var(--l2-border);
|
||||
--button-justify-content: flex-start;
|
||||
padding: 4px 0;
|
||||
@include picker-row(14px);
|
||||
|
||||
> [data-slot='button'][aria-selected='true'] {
|
||||
--button-variant-ghost-background-color: color-mix(
|
||||
in srgb,
|
||||
var(--accent-primary),
|
||||
transparent 86%
|
||||
);
|
||||
--button-variant-ghost-background-color: var(--l2-background-hover);
|
||||
--button-variant-ghost-color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
@@ -243,35 +226,34 @@
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
// Match the previous fixed entity-list height so the inner search +
|
||||
// scrolling list have a definite container to size against.
|
||||
height: 320px;
|
||||
}
|
||||
|
||||
.contextPopoverSearch {
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
width: 90%;
|
||||
align-items: center;
|
||||
height: 44px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
@include bare-input;
|
||||
}
|
||||
|
||||
.contextPopoverSearchInput {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
caret-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.contextPopoverEntities {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 8px;
|
||||
padding: 4px 0;
|
||||
min-width: 0;
|
||||
@include scrollbar(0.2rem);
|
||||
--button-justify-content: flex-start;
|
||||
@include picker-row(12px);
|
||||
|
||||
> [data-slot='button'][aria-pressed='true'] {
|
||||
--button-variant-ghost-background-color: color-mix(
|
||||
@@ -338,75 +320,3 @@
|
||||
overflow-wrap: anywhere;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.micRecording {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: var(--l2-background);
|
||||
border-radius: 999px;
|
||||
padding: 2px;
|
||||
gap: 0;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
--button-icon-size: 12px;
|
||||
|
||||
> :last-child {
|
||||
--button-icon-size: 9px;
|
||||
--button-variant-ghost-color: var(--accent-cherry);
|
||||
--button-variant-ghost-hover-color: var(--accent-cherry);
|
||||
}
|
||||
}
|
||||
|
||||
.micWaves {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
|
||||
span {
|
||||
display: block;
|
||||
width: 2px;
|
||||
border-radius: 2px;
|
||||
background: var(--l1-foreground);
|
||||
animation: voiceWave 0.9s ease-in-out infinite;
|
||||
|
||||
&:nth-child(1) {
|
||||
animation-delay: 0s;
|
||||
}
|
||||
&:nth-child(2) {
|
||||
animation-delay: 0.1s;
|
||||
}
|
||||
&:nth-child(3) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
&:nth-child(4) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
&:nth-child(5) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
&:nth-child(6) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
&:nth-child(7) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
&:nth-child(8) {
|
||||
animation-delay: 0.1s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes voiceWave {
|
||||
0%,
|
||||
100% {
|
||||
height: 2px;
|
||||
opacity: 0.4;
|
||||
}
|
||||
50% {
|
||||
height: 12px;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,60 +7,49 @@ import {
|
||||
} from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import cx from 'classnames';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@signozhq/ui/popover';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import type { UploadFile } from 'antd';
|
||||
import getSessionStorage from 'api/browser/sessionstorage/get';
|
||||
import setSessionStorage from 'api/browser/sessionstorage/set';
|
||||
import {
|
||||
getListDashboardsForUserV2QueryKey,
|
||||
useListDashboardsForUserV2,
|
||||
} from 'api/generated/services/dashboard';
|
||||
import {
|
||||
getListRulesQueryKey,
|
||||
useListRules,
|
||||
getListRulesV3QueryKey,
|
||||
useListRulesV3,
|
||||
} from 'api/generated/services/rules';
|
||||
import type {
|
||||
DashboardtypesListedDashboardForUserV2DTO,
|
||||
ListDashboardsForUserV2200,
|
||||
ListDashboardsForUserV2Params,
|
||||
ListRules200,
|
||||
ListRulesV3200,
|
||||
ListRulesV3Params,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { useQueryService } from 'hooks/useQueryService';
|
||||
// eslint-disable-next-line
|
||||
import { useSelector } from 'react-redux';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import {
|
||||
AIAssistantEvents,
|
||||
VoiceInputSource,
|
||||
getBrowserInfo,
|
||||
} from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useSpeechRecognition } from '../../hooks/useSpeechRecognition';
|
||||
import { MessageAttachment } from '../../types';
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import { MessageContext } from '../../../../api/ai-assistant/chat';
|
||||
import {
|
||||
Mic,
|
||||
Plus,
|
||||
Search,
|
||||
Send,
|
||||
Square,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from '@signozhq/icons';
|
||||
import { ArrowUp, AtSign, Square, TriangleAlert, X } from '@signozhq/icons';
|
||||
|
||||
import styles from './ChatInput.module.scss';
|
||||
import ComposerCaret from './ComposerCaret/ComposerCaret';
|
||||
import ContextPickerEmptyState from './ContextPickerEmptyState';
|
||||
import ContextPill from './ContextPill/ContextPill';
|
||||
import EdgeSweep from './EdgeSweep/EdgeSweep';
|
||||
import NozPeek from './NozPeek/NozPeek';
|
||||
import {
|
||||
AUTO_CONTEXT_ICONS,
|
||||
CONTEXT_CATEGORIES,
|
||||
CONTEXT_CATEGORY_ICONS,
|
||||
CONTEXT_CATEGORY_SINGULAR,
|
||||
CONTEXT_TYPE_LABELS,
|
||||
ContextCategory,
|
||||
} from './contextPicker';
|
||||
|
||||
@@ -74,6 +63,10 @@ interface ChatInputProps {
|
||||
disabled?: boolean;
|
||||
disabledTooltip?: string;
|
||||
isStreaming?: boolean;
|
||||
/** When the current stream began; drives the top-edge sweep. */
|
||||
streamStartedAt?: number | null;
|
||||
/** Noz peeks over the top edge; meant for an empty conversation. */
|
||||
showNozPeek?: boolean;
|
||||
/**
|
||||
* URL-derived `source: 'auto'` contexts representing the page the user is
|
||||
* currently looking at. Rendered as chips alongside the user's `@`-mention
|
||||
@@ -141,28 +134,6 @@ function autoContextLabel(ctx: MessageContext): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** Capitalised category badge text — e.g. "Dashboard", "Logs explorer". */
|
||||
function autoContextCategory(ctx: MessageContext): string {
|
||||
switch (ctx.type) {
|
||||
case 'dashboard':
|
||||
return 'Dashboard';
|
||||
case 'alert':
|
||||
return 'Alert';
|
||||
case 'service':
|
||||
return 'Service';
|
||||
case 'logs_explorer':
|
||||
return 'Logs';
|
||||
case 'traces_explorer':
|
||||
return 'Traces';
|
||||
case 'metrics_explorer':
|
||||
return 'Metrics';
|
||||
case 'saved_view':
|
||||
return 'Saved view';
|
||||
default:
|
||||
return ctx.type;
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_INPUT_LENGTH = 20000;
|
||||
const WARNING_THRESHOLD = 15000;
|
||||
// Cap for the auto-growing composer. Past this, the textarea stops growing
|
||||
@@ -170,8 +141,6 @@ const WARNING_THRESHOLD = 15000;
|
||||
// squeezed in tighter container variants (e.g. the floating panel).
|
||||
const TEXTAREA_MAX_HEIGHT_PX = 200;
|
||||
const HOME_SERVICES_INTERVAL = 30 * 60 * 1000;
|
||||
/** sessionStorage key for the "voice input failed this tab" flag. */
|
||||
const VOICE_UNAVAILABLE_KEY = 'ai-assistant-voice-unavailable';
|
||||
/**
|
||||
* The picker filters client-side, so it pulls one large page instead of
|
||||
* paginating. Shared with `getQueryData` below — the params are part of the
|
||||
@@ -179,6 +148,9 @@ const VOICE_UNAVAILABLE_KEY = 'ai-assistant-voice-unavailable';
|
||||
*/
|
||||
const DASHBOARD_LIST_PARAMS: ListDashboardsForUserV2Params = { limit: 1000 };
|
||||
|
||||
/** Same as dashboards. 200 is the most the rules list returns per call. */
|
||||
const ALERT_RULE_LIST_PARAMS: ListRulesV3Params = { limit: 200 };
|
||||
|
||||
function dashboardTitle(
|
||||
dashboard: DashboardtypesListedDashboardForUserV2DTO,
|
||||
): string {
|
||||
@@ -239,12 +211,15 @@ export default function ChatInput({
|
||||
disabled,
|
||||
disabledTooltip,
|
||||
isStreaming = false,
|
||||
streamStartedAt = null,
|
||||
showNozPeek = false,
|
||||
autoContexts,
|
||||
onDismissAutoContext,
|
||||
}: ChatInputProps): JSX.Element {
|
||||
const { selectedTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
const isCompact = useVariant() === 'panel';
|
||||
const [text, setText] = useState('');
|
||||
const [pendingFiles, setPendingFiles] = useState<UploadFile[]>([]);
|
||||
const [selectedContexts, setSelectedContexts] = useState<
|
||||
@@ -284,8 +259,6 @@ export default function ChatInput({
|
||||
endTime: now,
|
||||
};
|
||||
});
|
||||
// Stores the already-committed final text so interim results don't overwrite it
|
||||
const committedTextRef = useRef('');
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const inputRootRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -339,7 +312,6 @@ export default function ChatInput({
|
||||
const next =
|
||||
text.slice(0, mentionRange.start) + text.slice(mentionRange.end);
|
||||
setText(next);
|
||||
committedTextRef.current = next;
|
||||
setMentionRange(null);
|
||||
}
|
||||
},
|
||||
@@ -352,7 +324,6 @@ export default function ChatInput({
|
||||
(prompt: string) => {
|
||||
const next = capText(prompt);
|
||||
setText(next);
|
||||
committedTextRef.current = next;
|
||||
setMentionRange(null);
|
||||
setPickerSearchQuery('');
|
||||
setIsContextPickerOpen(false);
|
||||
@@ -493,7 +464,6 @@ export default function ChatInput({
|
||||
contexts.length > 0 ? contexts : undefined,
|
||||
);
|
||||
setText('');
|
||||
committedTextRef.current = '';
|
||||
setPendingFiles([]);
|
||||
setSelectedContexts([]);
|
||||
textareaRef.current?.focus();
|
||||
@@ -528,209 +498,6 @@ export default function ChatInput({
|
||||
[],
|
||||
);
|
||||
|
||||
// ── Voice input ────────────────────────────────────────────────────────────
|
||||
|
||||
const analyticsCtx = useAIAssistantAnalyticsContext();
|
||||
// Captured at the start of a voice session, consumed when it ends.
|
||||
// Tracks both the trigger (button vs. PTT shortcut) and the wall-clock
|
||||
// start time so we can attribute `durationMs` on the Voice input used
|
||||
// event regardless of which control ended the session.
|
||||
const voiceStartedAtRef = useRef<number | null>(null);
|
||||
const voiceSourceRef = useRef<VoiceInputSource | null>(null);
|
||||
// Set to true after a `network`, `not-allowed`, or `not-supported` failure
|
||||
// so we hide the mic button for the rest of the tab session — silent
|
||||
// retries don't help, and Chromium derivatives without the Google Speech
|
||||
// API key always fail with `network` no matter how many times the user
|
||||
// clicks. Persisted to sessionStorage so a page reload doesn't surface the
|
||||
// button again (closing the tab still resets, in case the user fixed
|
||||
// permissions or switched browsers).
|
||||
const [voiceUnavailable, setVoiceUnavailable] = useState(
|
||||
() => getSessionStorage(VOICE_UNAVAILABLE_KEY) === 'true',
|
||||
);
|
||||
const markVoiceUnavailable = useCallback((): void => {
|
||||
setVoiceUnavailable(true);
|
||||
setSessionStorage(VOICE_UNAVAILABLE_KEY, 'true');
|
||||
}, []);
|
||||
|
||||
const {
|
||||
isListening,
|
||||
isSupported,
|
||||
permission: micPermission,
|
||||
start,
|
||||
discard,
|
||||
} = useSpeechRecognition({
|
||||
onTranscript: (transcriptText, isFinal) => {
|
||||
if (isFinal) {
|
||||
// Commit: append to whatever the user has already typed
|
||||
const separator = committedTextRef.current ? ' ' : '';
|
||||
const next = capText(committedTextRef.current + separator + transcriptText);
|
||||
committedTextRef.current = next;
|
||||
setText(next);
|
||||
} else {
|
||||
// Interim: live preview appended to committed text, not yet persisted
|
||||
const separator = committedTextRef.current ? ' ' : '';
|
||||
setText(capText(committedTextRef.current + separator + transcriptText));
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
// Guard against double-fire: Chrome can fire `onerror` more than
|
||||
// once per session when `continuous = true` (it retries internally
|
||||
// before giving up). Only fire the analytics event for the first
|
||||
// error in a given session — voiceSourceRef being null means we've
|
||||
// already handled it.
|
||||
const source = voiceSourceRef.current;
|
||||
if (source === null) {
|
||||
return;
|
||||
}
|
||||
voiceStartedAtRef.current = null;
|
||||
voiceSourceRef.current = null;
|
||||
void logEvent(AIAssistantEvents.VoiceInputFailed, {
|
||||
...analyticsCtx,
|
||||
...getBrowserInfo(),
|
||||
source,
|
||||
errorType: error,
|
||||
});
|
||||
if (error === 'network') {
|
||||
markVoiceUnavailable();
|
||||
toast.error('Voice input unavailable in this browser', {
|
||||
description:
|
||||
'This browser cannot reach the speech recognition service. Try Google Chrome or Microsoft Edge.',
|
||||
});
|
||||
} else if (error === 'not-allowed') {
|
||||
markVoiceUnavailable();
|
||||
toast.error('Microphone access denied', {
|
||||
description:
|
||||
'Grant microphone permission in your browser settings to use voice input.',
|
||||
});
|
||||
} else if (error === 'not-supported') {
|
||||
markVoiceUnavailable();
|
||||
toast.error('Voice input is not supported in this browser.');
|
||||
}
|
||||
// `no-speech` is benign (just silence) — don't toast or hide.
|
||||
},
|
||||
});
|
||||
|
||||
const showMic = isSupported && micPermission !== 'denied' && !voiceUnavailable;
|
||||
|
||||
const startVoiceInput = useCallback(
|
||||
(source: VoiceInputSource) => {
|
||||
// Defense in depth: the button is hidden when `voiceUnavailable` is
|
||||
// true, but the PTT shortcut listener can still call us. Bailing here
|
||||
// keeps a single source of truth and prevents repeat `Voice input
|
||||
// failed` events in the same session.
|
||||
if (voiceUnavailable) {
|
||||
return;
|
||||
}
|
||||
voiceStartedAtRef.current = Date.now();
|
||||
voiceSourceRef.current = source;
|
||||
start();
|
||||
},
|
||||
[start, voiceUnavailable],
|
||||
);
|
||||
|
||||
const fireVoiceInputEvent = useCallback(
|
||||
(outcome: 'sent' | 'discarded') => {
|
||||
const startedAt = voiceStartedAtRef.current;
|
||||
const source = voiceSourceRef.current;
|
||||
voiceStartedAtRef.current = null;
|
||||
voiceSourceRef.current = null;
|
||||
if (startedAt === null || source === null) {
|
||||
return;
|
||||
}
|
||||
void logEvent(AIAssistantEvents.VoiceInputUsed, {
|
||||
...analyticsCtx,
|
||||
...getBrowserInfo(),
|
||||
source,
|
||||
outcome,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
},
|
||||
[analyticsCtx],
|
||||
);
|
||||
|
||||
// Stop recording and immediately send whatever is in the textarea.
|
||||
const handleStopAndSend = useCallback(async () => {
|
||||
// Promote the displayed text (interim included) to committed so handleSend sees it.
|
||||
committedTextRef.current = capText(text);
|
||||
// Stop recognition without triggering onTranscript again (would double-append).
|
||||
discard();
|
||||
fireVoiceInputEvent('sent');
|
||||
await handleSend();
|
||||
}, [text, discard, handleSend, capText, fireVoiceInputEvent]);
|
||||
|
||||
// Stop recording and revert the textarea to what it was before voice started.
|
||||
const handleDiscard = useCallback(() => {
|
||||
discard();
|
||||
fireVoiceInputEvent('discarded');
|
||||
setText(committedTextRef.current);
|
||||
textareaRef.current?.focus();
|
||||
}, [discard, fireVoiceInputEvent]);
|
||||
|
||||
// ── Push-to-talk (Cmd/Ctrl + Shift + Space) ────────────────────────────────
|
||||
// Hold the combo to record; release Space to submit. We track which key
|
||||
// triggered PTT in a ref so a late-released modifier (Cmd/Shift) doesn't
|
||||
// accidentally stop the session. Auto-repeat is suppressed via a
|
||||
// "session active" ref so a held key only calls `start()` once.
|
||||
const pttActiveRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!isSupported || micPermission === 'denied' || voiceUnavailable) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent): void => {
|
||||
const isComboKey =
|
||||
(e.metaKey || e.ctrlKey) &&
|
||||
e.shiftKey &&
|
||||
(e.code === 'Space' || e.key === ' ');
|
||||
if (!isComboKey || disabled || isStreaming) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
if (pttActiveRef.current) {
|
||||
return; // ignore auto-repeat
|
||||
}
|
||||
pttActiveRef.current = true;
|
||||
startVoiceInput(VoiceInputSource.Shortcut);
|
||||
};
|
||||
|
||||
const handleKeyUp = (e: KeyboardEvent): void => {
|
||||
if (!pttActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
// End on the *first* released key in the combo. macOS browsers
|
||||
// frequently swallow keyup of regular keys (incl. Space) while
|
||||
// Cmd is held, so we can't rely on Space-up alone — releasing
|
||||
// Cmd/Ctrl/Shift must also stop the session.
|
||||
const isComboKey =
|
||||
e.code === 'Space' ||
|
||||
e.key === ' ' ||
|
||||
e.key === 'Meta' ||
|
||||
e.key === 'Control' ||
|
||||
e.key === 'Shift';
|
||||
if (!isComboKey) {
|
||||
return;
|
||||
}
|
||||
pttActiveRef.current = false;
|
||||
e.preventDefault();
|
||||
void handleStopAndSend();
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
window.addEventListener('keyup', handleKeyUp);
|
||||
return (): void => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
window.removeEventListener('keyup', handleKeyUp);
|
||||
};
|
||||
}, [
|
||||
isSupported,
|
||||
micPermission,
|
||||
voiceUnavailable,
|
||||
disabled,
|
||||
isStreaming,
|
||||
startVoiceInput,
|
||||
handleStopAndSend,
|
||||
]);
|
||||
|
||||
// Each list hook fetches only when its picker tab is actively shown,
|
||||
// AND treats already-cached data as never stale (`staleTime: Infinity`)
|
||||
// so an open with a populated cache doesn't trigger a background
|
||||
@@ -755,7 +522,7 @@ export default function ChatInput({
|
||||
data: alertsResponse,
|
||||
isLoading: isAlertsLoading,
|
||||
isError: isAlertsError,
|
||||
} = useListRules({
|
||||
} = useListRulesV3(ALERT_RULE_LIST_PARAMS, {
|
||||
query: {
|
||||
enabled: isContextPickerOpen && activeContextCategory === 'Alerts',
|
||||
staleTime: Infinity,
|
||||
@@ -804,10 +571,10 @@ export default function ChatInput({
|
||||
}
|
||||
}
|
||||
if (ctx.type === 'alert' && ctx.resourceId) {
|
||||
const cached = queryClient.getQueryData<ListRules200>(
|
||||
getListRulesQueryKey(),
|
||||
const cached = queryClient.getQueryData<ListRulesV3200>(
|
||||
getListRulesV3QueryKey(ALERT_RULE_LIST_PARAMS),
|
||||
);
|
||||
const rule = cached?.data?.find((r) => r.id === ctx.resourceId);
|
||||
const rule = cached?.data.rules.find((r) => r.id === ctx.resourceId);
|
||||
if (rule?.alert) {
|
||||
return rule.alert;
|
||||
}
|
||||
@@ -835,8 +602,8 @@ export default function ChatInput({
|
||||
value: dashboardTitle(dashboard),
|
||||
})) ?? [],
|
||||
Alerts:
|
||||
alertsResponse?.data
|
||||
?.filter((alertRule) => Boolean(alertRule.alert))
|
||||
alertsResponse?.data.rules
|
||||
.filter((alertRule) => Boolean(alertRule.alert))
|
||||
.map((alertRule) => ({
|
||||
id: alertRule.id,
|
||||
value: alertRule.alert,
|
||||
@@ -896,7 +663,12 @@ export default function ChatInput({
|
||||
const showTextWarning = currentLength >= WARNING_THRESHOLD;
|
||||
|
||||
return (
|
||||
<div className={styles.input} ref={inputRootRef}>
|
||||
<div
|
||||
className={cx(styles.input, { [styles.compact]: isCompact })}
|
||||
ref={inputRootRef}
|
||||
>
|
||||
<EdgeSweep startedAt={streamStartedAt} />
|
||||
{showNozPeek && <NozPeek />}
|
||||
{pendingFiles.length > 0 && (
|
||||
<div className={styles.attachments}>
|
||||
{pendingFiles.map((f) => (
|
||||
@@ -922,55 +694,30 @@ export default function ChatInput({
|
||||
<div className={styles.contextTags}>
|
||||
{autoContexts?.map((ctx) => {
|
||||
const key = autoContextKey(ctx);
|
||||
const label = resolveAutoContextName(ctx);
|
||||
const category = autoContextCategory(ctx);
|
||||
return (
|
||||
<div key={key} className={cx(styles.contextTag, styles.auto)}>
|
||||
<div className={styles.contextTagContent}>
|
||||
<Badge textTransform="none" color="secondary" variant="outlined">
|
||||
{category}
|
||||
</Badge>
|
||||
<span className={styles.contextTagLabel}>{label}</span>
|
||||
</div>
|
||||
{onDismissAutoContext && (
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={(): void => onDismissAutoContext(key)}
|
||||
aria-label={`Remove ${category}: ${label} context`}
|
||||
>
|
||||
<X size={10} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<ContextPill
|
||||
key={key}
|
||||
icon={AUTO_CONTEXT_ICONS[ctx.type]}
|
||||
category={CONTEXT_TYPE_LABELS[ctx.type]}
|
||||
label={resolveAutoContextName(ctx)}
|
||||
onRemove={
|
||||
onDismissAutoContext
|
||||
? (): void => onDismissAutoContext(key)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{selectedContexts.map((contextItem) => (
|
||||
<div
|
||||
<ContextPill
|
||||
key={`${contextItem.category}:${contextItem.entityId}`}
|
||||
className={styles.contextTag}
|
||||
>
|
||||
<div className={styles.contextTagContent}>
|
||||
<Badge textTransform="none" color="primary" variant="outlined">
|
||||
{contextItem.category}
|
||||
</Badge>
|
||||
<span className={styles.contextTagLabel}>{contextItem.value}</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={(): void =>
|
||||
removeContext(contextItem.category, contextItem.entityId)
|
||||
}
|
||||
aria-label={`Remove ${contextItem.category}: ${contextItem.value} context`}
|
||||
>
|
||||
<X size={10} />
|
||||
</Button>
|
||||
</div>
|
||||
icon={CONTEXT_CATEGORY_ICONS[contextItem.category]}
|
||||
category={CONTEXT_CATEGORY_SINGULAR[contextItem.category]}
|
||||
label={contextItem.value}
|
||||
onRemove={(): void =>
|
||||
removeContext(contextItem.category, contextItem.entityId)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -979,20 +726,19 @@ export default function ChatInput({
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className={styles.textarea}
|
||||
placeholder="Ask anything… (Shift+Enter for new line)"
|
||||
placeholder="Ask Noz…"
|
||||
value={text}
|
||||
onChange={(e): void => {
|
||||
const next = capText(e.target.value);
|
||||
setText(next);
|
||||
// Keep committed text in sync when the user edits manually
|
||||
committedTextRef.current = next;
|
||||
syncContextPickerFromText(next, e.target.selectionStart ?? next.length);
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={disabled}
|
||||
maxLength={MAX_INPUT_LENGTH}
|
||||
rows={3}
|
||||
rows={2}
|
||||
/>
|
||||
<ComposerCaret textareaRef={textareaRef} value={text} />
|
||||
</div>
|
||||
{showTextWarning && (
|
||||
<div className={styles.charWarning} role="status">
|
||||
@@ -1005,7 +751,7 @@ export default function ChatInput({
|
||||
)}
|
||||
|
||||
<div className={styles.footer}>
|
||||
<div className={styles.leftActions}>
|
||||
<div className={styles.actions}>
|
||||
<Popover
|
||||
open={isContextPickerOpen}
|
||||
onOpenChange={(open): void => {
|
||||
@@ -1016,72 +762,77 @@ export default function ChatInput({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
disabledTooltip={disabledTooltip}
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
disabled={disabled}
|
||||
onClick={(): void => {
|
||||
setActiveContextCategory('Dashboards');
|
||||
setPickerSearchQuery('');
|
||||
}}
|
||||
prefix={<Plus size={10} />}
|
||||
>
|
||||
Add Context
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<Tooltip title="Add context">
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
disabledTooltip={disabledTooltip}
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
disabled={disabled}
|
||||
onClick={(): void => {
|
||||
setActiveContextCategory('Dashboards');
|
||||
setPickerSearchQuery('');
|
||||
}}
|
||||
aria-label="Add context"
|
||||
>
|
||||
<AtSign size={14} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</Tooltip>
|
||||
<PopoverContent
|
||||
className={styles.contextPopover}
|
||||
side="top"
|
||||
align="end"
|
||||
sideOffset={8}
|
||||
sideOffset={4}
|
||||
>
|
||||
<div className={styles.contextPopoverContent}>
|
||||
<div
|
||||
className={styles.contextPopoverCategories}
|
||||
role="tablist"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Context categories"
|
||||
>
|
||||
{CONTEXT_CATEGORIES.map((category) => {
|
||||
const CategoryIcon = CONTEXT_CATEGORY_ICONS[category];
|
||||
const isActive = activeContextCategory === category;
|
||||
return (
|
||||
<Button
|
||||
key={category}
|
||||
ref={(el): void => {
|
||||
categoryTabRefs.current.set(category, el);
|
||||
}}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
id={`ai-context-tab-${category}`}
|
||||
// Single stable panel id shared by every tab: only the
|
||||
// active category's tabpanel is rendered, so per-category
|
||||
// `aria-controls` ids would point at nonexistent nodes
|
||||
// for the two inactive tabs. APG allows a single
|
||||
// dynamic panel whose `aria-labelledby` swaps to the
|
||||
// active tab.
|
||||
aria-controls="ai-context-tabpanel"
|
||||
// Roving tabindex: only the active tab participates in
|
||||
// the Tab sequence; arrow keys move between tabs.
|
||||
tabIndex={isActive ? 0 : -1}
|
||||
aria-selected={isActive}
|
||||
width="100%"
|
||||
onClick={(): void => {
|
||||
setActiveContextCategory(category);
|
||||
setPickerSearchQuery('');
|
||||
}}
|
||||
onKeyDown={(e): void => handleCategoryKeyDown(e, category)}
|
||||
prefix={<CategoryIcon size={13} />}
|
||||
>
|
||||
<span>{category}</span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
<div className={styles.contextPopoverLeft}>
|
||||
<div className={styles.contextPopoverLabel}>Available resources</div>
|
||||
<div
|
||||
className={styles.contextPopoverCategories}
|
||||
role="tablist"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Context categories"
|
||||
>
|
||||
{CONTEXT_CATEGORIES.map((category) => {
|
||||
const isActive = activeContextCategory === category;
|
||||
return (
|
||||
<Button
|
||||
key={category}
|
||||
ref={(el): void => {
|
||||
categoryTabRefs.current.set(category, el);
|
||||
}}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
id={`ai-context-tab-${category}`}
|
||||
testId={`ai-context-tab-${category}`}
|
||||
// Single stable panel id shared by every tab: only the
|
||||
// active category's tabpanel is rendered, so per-category
|
||||
// `aria-controls` ids would point at nonexistent nodes
|
||||
// for the two inactive tabs. APG allows a single
|
||||
// dynamic panel whose `aria-labelledby` swaps to the
|
||||
// active tab.
|
||||
aria-controls="ai-context-tabpanel"
|
||||
// Roving tabindex: only the active tab participates in
|
||||
// the Tab sequence; arrow keys move between tabs.
|
||||
tabIndex={isActive ? 0 : -1}
|
||||
aria-selected={isActive}
|
||||
width="100%"
|
||||
onClick={(): void => {
|
||||
setActiveContextCategory(category);
|
||||
setPickerSearchQuery('');
|
||||
}}
|
||||
onKeyDown={(e): void => handleCategoryKeyDown(e, category)}
|
||||
>
|
||||
<span>{category}</span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -1097,7 +848,6 @@ export default function ChatInput({
|
||||
className={styles.contextPopoverSearchInput}
|
||||
value={pickerSearchQuery}
|
||||
onChange={(e): void => setPickerSearchQuery(e.target.value)}
|
||||
prefix={<Search size={12} />}
|
||||
// Skip the picker's roving keyboard focus — typing here
|
||||
// shouldn't move category selection.
|
||||
onKeyDown={(e): void => {
|
||||
@@ -1159,82 +909,18 @@ export default function ChatInput({
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
<div className={styles.rightActions}>
|
||||
{showMic &&
|
||||
(isListening ? (
|
||||
<div
|
||||
className={styles.micRecording}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label="Recording voice input"
|
||||
>
|
||||
<Tooltip title="Discard recording">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={handleDiscard}
|
||||
aria-label="Discard recording"
|
||||
>
|
||||
<X size={12} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<span className={styles.micWaves} aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</span>
|
||||
<Tooltip title="Stop and send">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={handleStopAndSend}
|
||||
aria-label="Stop and send"
|
||||
>
|
||||
<Square size={9} fill="currentColor" strokeWidth={0} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<Tooltip title="Voice input">
|
||||
<Button
|
||||
disabledTooltip={disabledTooltip}
|
||||
color="secondary"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
icon
|
||||
onClick={(): void => startVoiceInput(VoiceInputSource.Button)}
|
||||
disabled={disabled}
|
||||
aria-label="Start voice input"
|
||||
>
|
||||
<Mic size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
))}
|
||||
|
||||
{isStreaming && onCancel ? (
|
||||
<Tooltip title="Stop generating">
|
||||
<Button
|
||||
variant="solid"
|
||||
size="md"
|
||||
size="sm"
|
||||
icon
|
||||
color="danger"
|
||||
onClick={onCancel}
|
||||
aria-label="Stop generating"
|
||||
>
|
||||
<Square size={10} fill="currentColor" strokeWidth={0} />
|
||||
<Square size={14} fill="currentColor" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
@@ -1242,14 +928,14 @@ export default function ChatInput({
|
||||
<Button
|
||||
disabledTooltip={disabled ? disabledTooltip : 'Type a message first'}
|
||||
variant="solid"
|
||||
size="md"
|
||||
size="sm"
|
||||
icon
|
||||
color="primary"
|
||||
onClick={isListening ? handleStopAndSend : handleSend}
|
||||
onClick={handleSend}
|
||||
disabled={disabled || (!text.trim() && pendingFiles.length === 0)}
|
||||
aria-label="Send message"
|
||||
>
|
||||
<Send size={14} />
|
||||
<ArrowUp size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
.caret {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 2px;
|
||||
// Overhangs the glyph box by 1px each way, like the native caret.
|
||||
margin: -1px 0 0 -1px;
|
||||
padding: 1px 0;
|
||||
border-radius: 1px;
|
||||
pointer-events: none;
|
||||
background: var(--accent-primary);
|
||||
transition: transform 0.05s linear;
|
||||
animation: caretBlink 1s step-end infinite;
|
||||
|
||||
// Solid while keys are going, then blinks again.
|
||||
&.isTyping {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.trail {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
opacity: 0.4;
|
||||
background: var(--accent-primary);
|
||||
animation: trailFade 0.3s ease-out 0.4s forwards;
|
||||
|
||||
&.isFaint {
|
||||
opacity: 0.2;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes caretBlink {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes trailFade {
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.caret,
|
||||
.trail {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { RefObject } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { useComposerCaret } from './useComposerCaret';
|
||||
|
||||
import styles from './ComposerCaret.module.scss';
|
||||
|
||||
interface ComposerCaretProps {
|
||||
textareaRef: RefObject<HTMLTextAreaElement>;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export default function ComposerCaret({
|
||||
textareaRef,
|
||||
value,
|
||||
}: ComposerCaretProps): JSX.Element {
|
||||
const { caret, isTyping, trails, removeTrail } = useComposerCaret(
|
||||
textareaRef,
|
||||
value,
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{trails.map((trail) => (
|
||||
<span
|
||||
key={trail.id}
|
||||
className={cx(styles.trail, { [styles.isFaint]: trail.faint })}
|
||||
style={{
|
||||
left: trail.left,
|
||||
top: trail.top,
|
||||
width: trail.width,
|
||||
height: trail.height,
|
||||
}}
|
||||
onAnimationEnd={(): void => removeTrail(trail.id)}
|
||||
aria-hidden
|
||||
/>
|
||||
))}
|
||||
{caret && (
|
||||
<span
|
||||
className={cx(styles.caret, { [styles.isTyping]: isTyping })}
|
||||
style={{
|
||||
transform: `translate(${caret.left}px, ${caret.top}px)`,
|
||||
height: caret.height,
|
||||
}}
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { CaretBox } from './types';
|
||||
|
||||
// Everything that decides where a line wraps.
|
||||
const MIRRORED_STYLES = [
|
||||
'border-top-width',
|
||||
'border-right-width',
|
||||
'border-bottom-width',
|
||||
'border-left-width',
|
||||
'border-style',
|
||||
'padding-top',
|
||||
'padding-right',
|
||||
'padding-bottom',
|
||||
'padding-left',
|
||||
'font-family',
|
||||
'font-size',
|
||||
'font-style',
|
||||
'font-variant',
|
||||
'font-weight',
|
||||
'font-stretch',
|
||||
'font-feature-settings',
|
||||
'font-variation-settings',
|
||||
'font-kerning',
|
||||
'line-height',
|
||||
'letter-spacing',
|
||||
'word-spacing',
|
||||
'text-align',
|
||||
'text-indent',
|
||||
'text-transform',
|
||||
'tab-size',
|
||||
'white-space',
|
||||
'word-break',
|
||||
'overflow-wrap',
|
||||
];
|
||||
|
||||
// Caret box in the textarea's border box, measured on an off-screen copy of its text.
|
||||
export function getCaretCoordinates(
|
||||
textarea: HTMLTextAreaElement,
|
||||
position: number,
|
||||
): CaretBox {
|
||||
const computed = getComputedStyle(textarea);
|
||||
const borderTop = parseFloat(computed.borderTopWidth) || 0;
|
||||
const borderLeft = parseFloat(computed.borderLeftWidth) || 0;
|
||||
const borderRight = parseFloat(computed.borderRightWidth) || 0;
|
||||
|
||||
const mirror = document.createElement('div');
|
||||
MIRRORED_STYLES.forEach((name) => {
|
||||
mirror.style.setProperty(name, computed.getPropertyValue(name));
|
||||
});
|
||||
Object.assign(mirror.style, {
|
||||
position: 'absolute',
|
||||
top: '0',
|
||||
left: '-9999px',
|
||||
visibility: 'hidden',
|
||||
overflow: 'hidden',
|
||||
boxSizing: 'border-box',
|
||||
width: `${textarea.clientWidth + borderLeft + borderRight}px`,
|
||||
});
|
||||
|
||||
mirror.textContent = textarea.value.slice(0, position);
|
||||
const marker = document.createElement('span');
|
||||
marker.textContent = textarea.value.slice(position) || '.';
|
||||
mirror.appendChild(marker);
|
||||
document.body.appendChild(mirror);
|
||||
|
||||
const box = {
|
||||
left: marker.offsetLeft + borderLeft,
|
||||
top: marker.offsetTop + borderTop,
|
||||
height:
|
||||
marker.getClientRects()[0]?.height || parseFloat(computed.lineHeight) || 0,
|
||||
};
|
||||
mirror.remove();
|
||||
return box;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface CaretBox {
|
||||
left: number;
|
||||
top: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface CaretTrail extends CaretBox {
|
||||
id: number;
|
||||
width: number;
|
||||
faint: boolean;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import {
|
||||
RefObject,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
import { getCaretCoordinates } from './getCaretCoordinates';
|
||||
import type { CaretBox, CaretTrail } from './types';
|
||||
|
||||
interface UseComposerCaretResult {
|
||||
caret: CaretBox | null;
|
||||
isTyping: boolean;
|
||||
trails: CaretTrail[];
|
||||
removeTrail: (id: number) => void;
|
||||
}
|
||||
|
||||
const TYPING_IDLE_MS = 800;
|
||||
const MAX_TRAILS = 4;
|
||||
const ARROW_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);
|
||||
const EDIT_KEYS = new Set(['Backspace', 'Delete']);
|
||||
|
||||
export function useComposerCaret(
|
||||
textareaRef: RefObject<HTMLTextAreaElement>,
|
||||
value: string,
|
||||
): UseComposerCaretResult {
|
||||
const [caret, setCaret] = useState<CaretBox | null>(null);
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const [trails, setTrails] = useState<CaretTrail[]>([]);
|
||||
const lastCaretRef = useRef<CaretBox | null>(null);
|
||||
const trailIdRef = useRef(0);
|
||||
const typingTimerRef = useRef<number>();
|
||||
|
||||
const measure = useCallback((): CaretBox | null => {
|
||||
const el = textareaRef.current;
|
||||
if (
|
||||
!el ||
|
||||
document.activeElement !== el ||
|
||||
el.selectionStart !== el.selectionEnd
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const box = getCaretCoordinates(el, el.selectionEnd);
|
||||
const top = el.offsetTop + box.top - el.scrollTop;
|
||||
const isInView =
|
||||
top >= el.offsetTop && top + box.height <= el.offsetTop + el.offsetHeight;
|
||||
if (!isInView) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
left: el.offsetLeft + box.left - el.scrollLeft,
|
||||
top,
|
||||
height: box.height,
|
||||
};
|
||||
}, [textareaRef]);
|
||||
|
||||
const update = useCallback((): void => {
|
||||
const next = measure();
|
||||
lastCaretRef.current = next;
|
||||
setCaret(next);
|
||||
}, [measure]);
|
||||
|
||||
// Leaves a fading streak over a sideways jump on the same line.
|
||||
const addTrail = useCallback((from: CaretBox, to: CaretBox): void => {
|
||||
if (Math.abs(to.top - from.top) >= 5 || Math.abs(to.left - from.left) <= 2) {
|
||||
return;
|
||||
}
|
||||
trailIdRef.current += 1;
|
||||
const id = trailIdRef.current;
|
||||
setTrails((prev) =>
|
||||
[
|
||||
...prev,
|
||||
{
|
||||
id,
|
||||
left: Math.min(from.left, to.left),
|
||||
top: to.top,
|
||||
width: Math.abs(to.left - from.left),
|
||||
height: to.height,
|
||||
faint: prev.length === 0,
|
||||
},
|
||||
].slice(-MAX_TRAILS),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const removeTrail = useCallback((id: number): void => {
|
||||
setTrails((prev) => prev.filter((trail) => trail.id !== id));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) {
|
||||
return undefined;
|
||||
}
|
||||
let frame = 0;
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent): void => {
|
||||
const isArrow = ARROW_KEYS.has(event.key);
|
||||
if (!isArrow && !EDIT_KEYS.has(event.key) && event.key.length !== 1) {
|
||||
return;
|
||||
}
|
||||
setIsTyping(true);
|
||||
window.clearTimeout(typingTimerRef.current);
|
||||
typingTimerRef.current = window.setTimeout(
|
||||
() => setIsTyping(false),
|
||||
TYPING_IDLE_MS,
|
||||
);
|
||||
if (isArrow) {
|
||||
const from = lastCaretRef.current;
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
const to = measure();
|
||||
if (from && to) {
|
||||
addTrail(from, to);
|
||||
}
|
||||
lastCaretRef.current = to;
|
||||
setCaret(to);
|
||||
});
|
||||
}
|
||||
};
|
||||
const onSelectionChange = (): void => {
|
||||
if (document.activeElement === el) {
|
||||
update();
|
||||
}
|
||||
};
|
||||
const hide = (): void => {
|
||||
lastCaretRef.current = null;
|
||||
setCaret(null);
|
||||
};
|
||||
const observer = new ResizeObserver(() => update());
|
||||
|
||||
el.addEventListener('keydown', onKeyDown);
|
||||
el.addEventListener('focus', update);
|
||||
el.addEventListener('blur', hide);
|
||||
el.addEventListener('scroll', update);
|
||||
document.addEventListener('selectionchange', onSelectionChange);
|
||||
observer.observe(el);
|
||||
update();
|
||||
|
||||
return (): void => {
|
||||
el.removeEventListener('keydown', onKeyDown);
|
||||
el.removeEventListener('focus', update);
|
||||
el.removeEventListener('blur', hide);
|
||||
el.removeEventListener('scroll', update);
|
||||
document.removeEventListener('selectionchange', onSelectionChange);
|
||||
observer.disconnect();
|
||||
cancelAnimationFrame(frame);
|
||||
window.clearTimeout(typingTimerRef.current);
|
||||
};
|
||||
}, [textareaRef, measure, update, addTrail]);
|
||||
|
||||
// Text set from code (prefill, @-mentions, send) moves the caret without a key.
|
||||
useLayoutEffect(() => {
|
||||
update();
|
||||
}, [value, update]);
|
||||
|
||||
return { caret, isTyping, trails, removeTrail };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-width: 24px;
|
||||
max-width: 240px;
|
||||
height: 24px;
|
||||
padding: 0 5.5px 0 3.5px;
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l3-background-60);
|
||||
color: var(--l2-foreground);
|
||||
font-size: 12px;
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 15px;
|
||||
transition:
|
||||
background-color 0.12s,
|
||||
color 0.12s;
|
||||
|
||||
&:hover,
|
||||
&:focus-within {
|
||||
background: var(--l2-background-hover);
|
||||
color: var(--l1-foreground-hover);
|
||||
}
|
||||
|
||||
// Collapsed rather than hidden, so the keyboard can still reach it and open it up.
|
||||
> [data-slot='button'] {
|
||||
max-width: 0;
|
||||
margin-left: 0;
|
||||
overflow: hidden;
|
||||
opacity: 0;
|
||||
transition:
|
||||
max-width 0.12s,
|
||||
margin-left 0.12s,
|
||||
opacity 0.12s;
|
||||
--button-width: 12px;
|
||||
--button-min-width: 0;
|
||||
--button-height: 15px;
|
||||
--button-padding: 0;
|
||||
}
|
||||
|
||||
&:hover > [data-slot='button'],
|
||||
&:focus-within > [data-slot='button'] {
|
||||
max-width: 12px;
|
||||
margin-left: var(--spacing-2);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
flex-shrink: 0;
|
||||
box-sizing: content-box;
|
||||
padding: 0 3px;
|
||||
}
|
||||
|
||||
.category {
|
||||
flex-shrink: 0;
|
||||
margin-right: var(--spacing-2);
|
||||
text-transform: lowercase;
|
||||
}
|
||||
|
||||
.label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Package, X } from '@signozhq/icons';
|
||||
|
||||
import styles from './ContextPill.module.scss';
|
||||
|
||||
interface ContextPillProps {
|
||||
icon: typeof Package;
|
||||
category: string;
|
||||
label: string;
|
||||
onRemove?: () => void;
|
||||
}
|
||||
|
||||
/** A context attached to the next message; the remove button shows on hover or focus. */
|
||||
export default function ContextPill({
|
||||
icon: Icon,
|
||||
category,
|
||||
label,
|
||||
onRemove,
|
||||
}: ContextPillProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.pill} title={`${category}: ${label}`}>
|
||||
<Icon size={14} className={styles.icon} />
|
||||
<span className={styles.category}>{category} :</span>
|
||||
<span className={styles.label}>{label}</span>
|
||||
{onRemove && (
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
onClick={onRemove}
|
||||
aria-label={`Remove ${category}: ${label} context`}
|
||||
testId="ai-context-pill-remove"
|
||||
>
|
||||
<X size={12} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Offsets are from the input's padding box; its top edge, border or separator, sits at -1px.
|
||||
|
||||
.edgeSweep {
|
||||
position: absolute;
|
||||
top: -11px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
opacity: 0;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.3s ease;
|
||||
mask-image: linear-gradient(
|
||||
to right,
|
||||
transparent 11px,
|
||||
var(--l1-background) 60px,
|
||||
var(--l1-background) calc(100% - 60px),
|
||||
transparent calc(100% - 11px)
|
||||
);
|
||||
|
||||
&.isVisible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.line {
|
||||
position: absolute;
|
||||
top: 9px;
|
||||
left: 0;
|
||||
width: 40%;
|
||||
height: 2px;
|
||||
animation: edgeSweep 2s ease-in-out infinite alternate;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
transparent,
|
||||
var(--accent-primary) 20%,
|
||||
var(--accent-sakura) 40%,
|
||||
var(--accent-primary) 60%,
|
||||
var(--accent-sakura) 80%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
&::before {
|
||||
top: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
&::after {
|
||||
top: 0;
|
||||
height: 2px;
|
||||
filter: blur(4px);
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes edgeSweep {
|
||||
from {
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
to {
|
||||
transform: translateX(200%);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import styles from './EdgeSweep.module.scss';
|
||||
|
||||
interface EdgeSweepProps {
|
||||
/** When the current stream began; null while idle. */
|
||||
startedAt: number | null;
|
||||
}
|
||||
|
||||
interface SweepRun {
|
||||
startedAt: number;
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
/** Gradient sweeping the input's top edge while Noz replies. */
|
||||
export default function EdgeSweep({ startedAt }: EdgeSweepProps): JSX.Element {
|
||||
// Outlives the stream so the line keeps moving while it fades out.
|
||||
const [run, setRun] = useState<SweepRun | null>(() =>
|
||||
startedAt === null ? null : { startedAt, elapsedMs: Date.now() - startedAt },
|
||||
);
|
||||
// A new stream restarts from the left; a remount mid-stream picks up where it was.
|
||||
if (startedAt !== null && startedAt !== run?.startedAt) {
|
||||
setRun({ startedAt, elapsedMs: Date.now() - startedAt });
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(styles.edgeSweep, { [styles.isVisible]: startedAt !== null })}
|
||||
onTransitionEnd={(): void => {
|
||||
if (startedAt === null) {
|
||||
setRun(null);
|
||||
}
|
||||
}}
|
||||
aria-hidden
|
||||
>
|
||||
{run && (
|
||||
<div
|
||||
key={run.startedAt}
|
||||
className={styles.line}
|
||||
style={{ animationDelay: `${-run.elapsedMs}ms` }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Offsets are from the input's padding box; its top edge, border or separator, sits at -1px.
|
||||
|
||||
.body {
|
||||
position: absolute;
|
||||
top: -29px;
|
||||
right: 6px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
pointer-events: none;
|
||||
// Hides what is below the top edge, as if Noz stood behind the input.
|
||||
clip-path: inset(-50% -50% 12px -50%);
|
||||
}
|
||||
|
||||
.bodySvg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
animation: bodyPeek 0.7s cubic-bezier(0.34, 1.45, 0.5, 1) 0.95s both;
|
||||
}
|
||||
|
||||
.head {
|
||||
transform-origin: 12px 16px;
|
||||
animation: headBob 0.5s ease-in-out 1.05s 2;
|
||||
}
|
||||
|
||||
.pupil {
|
||||
transition: transform 0.13s ease-out;
|
||||
}
|
||||
|
||||
.hands {
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: 9px;
|
||||
width: 34px;
|
||||
height: 7px;
|
||||
pointer-events: none;
|
||||
// Behind the top edge on the way up, in front of it on the way down.
|
||||
animation: handsClip 0.7s 0.6s both;
|
||||
}
|
||||
|
||||
.handsSvg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
animation: handsPeek 0.7s cubic-bezier(0.22, 1, 0.36, 1) 0.6s both;
|
||||
}
|
||||
|
||||
@keyframes bodyPeek {
|
||||
from {
|
||||
transform: translateY(34px);
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes headBob {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0) rotate(0deg);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-1px) rotate(-6deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes handsPeek {
|
||||
0% {
|
||||
transform: translateY(16px);
|
||||
opacity: 0;
|
||||
}
|
||||
20% {
|
||||
opacity: 1;
|
||||
}
|
||||
50%,
|
||||
51% {
|
||||
transform: translateY(-7px);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(2px);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes handsClip {
|
||||
0%,
|
||||
50% {
|
||||
clip-path: inset(-20px -20px 3px -20px);
|
||||
}
|
||||
51%,
|
||||
100% {
|
||||
clip-path: inset(-20px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bodySvg,
|
||||
.head,
|
||||
.hands,
|
||||
.handsSvg {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.handsSvg {
|
||||
transform: translateY(2px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useRef } from 'react';
|
||||
|
||||
import { useNozPupilTracking } from './useNozPupilTracking';
|
||||
|
||||
import styles from './NozPeek.module.scss';
|
||||
|
||||
/** Noz climbs over the input's top edge, hands first, then watches the cursor. */
|
||||
export default function NozPeek(): JSX.Element {
|
||||
const eyeRef = useRef<SVGCircleElement>(null);
|
||||
const pupilRef = useRef<SVGGElement>(null);
|
||||
useNozPupilTracking(eyeRef, pupilRef);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={styles.body} aria-hidden>
|
||||
<svg
|
||||
className={styles.bodySvg}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<rect
|
||||
x="4.35938"
|
||||
y="8.49908"
|
||||
width="15.4569"
|
||||
height="11.978"
|
||||
rx="1.76147"
|
||||
fill="#E5484D"
|
||||
/>
|
||||
<g className={styles.head}>
|
||||
<circle
|
||||
ref={eyeRef}
|
||||
cx="12.0217"
|
||||
cy="14.4881"
|
||||
r="3.87523"
|
||||
fill="#F5F5F5"
|
||||
/>
|
||||
<g ref={pupilRef} className={styles.pupil}>
|
||||
<path
|
||||
d="M12.0237 12.8024C12.0237 13.7328 11.2673 14.4892 10.337 14.4892C10.0339 14.4892 9.74926 14.4101 9.50152 14.2678C9.47517 14.5551 9.49888 14.8502 9.57795 15.1428C9.93901 16.4921 11.3279 17.2933 12.6773 16.9323C14.0267 16.5712 14.8279 15.1823 14.4668 13.8329C14.1453 12.6285 13.0041 11.8616 11.8023 11.967C11.942 12.2121 12.0237 12.4967 12.0237 12.8024Z"
|
||||
fill="#0A0C10"
|
||||
/>
|
||||
</g>
|
||||
<path
|
||||
d="M8.33833 7.94578L9.83358 4.31319C10.1302 3.59261 10.6676 2.99939 11.355 2.63299L13.9181 1.26684C14.1327 1.15169 14.3804 1.34885 14.3194 1.58439L13.6703 4.06892C13.6511 4.14046 13.6424 4.21374 13.6424 4.28876C13.6424 4.39868 13.6633 4.5086 13.7052 4.61154L15.0382 7.94578H11.4248L11.6307 7.32813L12.3356 7.09259C12.449 7.05421 12.5257 6.94778 12.5257 6.82739C12.5257 6.707 12.449 6.60057 12.3356 6.56218L11.6307 6.32664L11.3951 5.62176C11.3568 5.51009 11.2503 5.43333 11.1299 5.43333C11.0096 5.43333 10.9031 5.5101 10.8647 5.6235L10.6292 6.32839L9.92431 6.56393C9.8109 6.60231 9.73413 6.70874 9.73413 6.82913C9.73413 6.94952 9.8109 7.05595 9.92431 7.09434L10.6292 7.32988L10.8351 7.94752H8.33833V7.94578ZM12.1 3.43558C12.0808 3.378 12.0285 3.33962 11.9674 3.33962C11.9064 3.33962 11.854 3.378 11.8348 3.43558L11.7179 3.78802L11.3655 3.90492C11.3079 3.92411 11.2695 3.97645 11.2695 4.03752C11.2695 4.09859 11.3079 4.15093 11.3655 4.17012L11.7179 4.28702L11.8348 4.63946C11.854 4.69704 11.9064 4.73542 11.9674 4.73542C12.0285 4.73542 12.0808 4.69704 12.1 4.63946L12.2169 4.28702L12.5694 4.17012C12.6269 4.15093 12.6653 4.09859 12.6653 4.03752C12.6653 3.97645 12.6269 3.92411 12.5694 3.90492L12.2169 3.78802L12.1 3.43558ZM7.78 7.91088H15.5965C15.9053 7.91088 16.1548 8.16038 16.1548 8.4692C16.1548 8.77803 15.9053 9.02753 15.5965 9.02753H7.78C7.47118 9.02753 7.22168 8.77803 7.22168 8.4692C7.22168 8.16038 7.47118 7.91088 7.78 7.91088Z"
|
||||
fill="#4E74F8"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<div className={styles.hands} aria-hidden>
|
||||
<svg
|
||||
className={styles.handsSvg}
|
||||
viewBox="0 0 34 7"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<rect width="3.52294" height="6.16514" rx="1.46789" fill="#E5484D" />
|
||||
<rect
|
||||
x="30.4775"
|
||||
width="3.52294"
|
||||
height="6.16514"
|
||||
rx="1.46789"
|
||||
fill="#E5484D"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { RefObject, useEffect } from 'react';
|
||||
|
||||
// Noz has settled on the edge by now.
|
||||
const SETTLE_MS = 1900;
|
||||
// Furthest the pupil moves, in SVG units.
|
||||
const MAX_OFFSET = 1.25;
|
||||
// Cursor distance, in px, at which the pupil reaches MAX_OFFSET.
|
||||
const FULL_REACH_PX = 160;
|
||||
|
||||
export function useNozPupilTracking(
|
||||
eyeRef: RefObject<SVGCircleElement>,
|
||||
pupilRef: RefObject<SVGGElement>,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const prefersReducedMotion = window.matchMedia(
|
||||
'(prefers-reduced-motion: reduce)',
|
||||
).matches;
|
||||
let isSettled = false;
|
||||
const timer = window.setTimeout(
|
||||
() => {
|
||||
isSettled = true;
|
||||
},
|
||||
prefersReducedMotion ? 0 : SETTLE_MS,
|
||||
);
|
||||
|
||||
const onMouseMove = (event: MouseEvent): void => {
|
||||
const eye = eyeRef.current;
|
||||
const pupil = pupilRef.current;
|
||||
if (!isSettled || !eye || !pupil) {
|
||||
return;
|
||||
}
|
||||
const rect = eye.getBoundingClientRect();
|
||||
const dx = event.clientX - (rect.left + rect.width / 2);
|
||||
const dy = event.clientY - (rect.top + rect.height / 2);
|
||||
const distance = Math.hypot(dx, dy) || 1;
|
||||
const reach = Math.min(1, distance / FULL_REACH_PX) * MAX_OFFSET;
|
||||
pupil.style.transform = `translate(${((dx / distance) * reach).toFixed(3)}px, ${((dy / distance) * reach).toFixed(3)}px)`;
|
||||
};
|
||||
|
||||
window.addEventListener('mousemove', onMouseMove);
|
||||
return (): void => {
|
||||
window.clearTimeout(timer);
|
||||
window.removeEventListener('mousemove', onMouseMove);
|
||||
};
|
||||
}, [eyeRef, pupilRef]);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
alertRulesFixture,
|
||||
listRulesV3Response,
|
||||
} from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
jest.mock('api/generated/services/dashboard', () => ({
|
||||
useListDashboardsForUserV2: (): unknown => ({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
}),
|
||||
getListDashboardsForUserV2QueryKey: (): string[] => ['dashboards'],
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useQueryService', () => ({
|
||||
useQueryService: (): unknown => ({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
isFetching: false,
|
||||
isError: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line import/first
|
||||
import ChatInput from '../ChatInput';
|
||||
|
||||
describe('ChatInput — alerts context picker', () => {
|
||||
it('lists the rules from one v3 rules request', async () => {
|
||||
const [first, second] = alertRulesFixture;
|
||||
const requests: string[] = [];
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v3/rules', (req, res, ctx) => {
|
||||
requests.push(req.url.search);
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(listRulesV3Response([first, second], req.url.searchParams)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
render(<ChatInput onSend={jest.fn()} />);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /add context/i }));
|
||||
await userEvent.click(await screen.findByTestId('ai-context-tab-Alerts'));
|
||||
|
||||
await expect(screen.findByText(first.alert)).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText(second.alert)).toBeInTheDocument();
|
||||
expect(requests).toStrictEqual(['?limit=200']);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import ChatInput from '../ChatInput';
|
||||
|
||||
function getComposer(): HTMLTextAreaElement {
|
||||
return screen.getByPlaceholderText(/Ask anything/i) as HTMLTextAreaElement;
|
||||
return screen.getByPlaceholderText(/Ask Noz/i) as HTMLTextAreaElement;
|
||||
}
|
||||
|
||||
describe('ChatInput — @ mention trigger', () => {
|
||||
|
||||
@@ -12,8 +12,12 @@ jest.mock('api/generated/services/dashboard', () => ({
|
||||
}));
|
||||
|
||||
jest.mock('api/generated/services/rules', () => ({
|
||||
useListRules: (): unknown => ({ data: [], isLoading: false, isError: false }),
|
||||
getListRulesQueryKey: (): string[] => ['rules'],
|
||||
useListRulesV3: (): unknown => ({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
}),
|
||||
getListRulesV3QueryKey: (): string[] => ['rules'],
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useQueryService', () => ({
|
||||
@@ -25,26 +29,6 @@ jest.mock('hooks/useQueryService', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// Irrelevant to the prefill flow and otherwise require browser APIs / extra
|
||||
// context providers, so stub them out.
|
||||
jest.mock('../../../hooks/useSpeechRecognition', () => ({
|
||||
useSpeechRecognition: (): unknown => ({
|
||||
isListening: false,
|
||||
isSupported: false,
|
||||
permission: 'prompt',
|
||||
start: jest.fn(),
|
||||
discard: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../../hooks/useAIAssistantAnalyticsContext', () => ({
|
||||
useAIAssistantAnalyticsContext: (): unknown => ({
|
||||
threadId: undefined,
|
||||
page: '/',
|
||||
mode: 'sidepane',
|
||||
}),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line import/first
|
||||
// eslint-disable-next-line import/first
|
||||
import ChatInput from '../ChatInput';
|
||||
@@ -54,7 +38,7 @@ function renderChatInput(): void {
|
||||
}
|
||||
|
||||
function getComposer(): HTMLTextAreaElement {
|
||||
return screen.getByPlaceholderText(/Ask anything/i) as HTMLTextAreaElement;
|
||||
return screen.getByPlaceholderText(/Ask Noz/i) as HTMLTextAreaElement;
|
||||
}
|
||||
|
||||
describe('ChatInput — empty-state CTA prefill flow', () => {
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { Bell, LayoutDashboard, ShieldCheck } from '@signozhq/icons';
|
||||
import {
|
||||
BarChart,
|
||||
Bell,
|
||||
DraftingCompass,
|
||||
LayoutDashboard,
|
||||
Package,
|
||||
ScrollText,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
import { MessageContext } from '../../../../api/ai-assistant/chat';
|
||||
|
||||
/** Ordered category tabs shown in the @-mention context picker. */
|
||||
export const CONTEXT_CATEGORIES = ['Dashboards', 'Alerts', 'Services'] as const;
|
||||
@@ -12,9 +21,41 @@ export type ContextCategory = (typeof CONTEXT_CATEGORIES)[number];
|
||||
export const CONTEXT_CATEGORY_ICONS = {
|
||||
Dashboards: LayoutDashboard,
|
||||
Alerts: Bell,
|
||||
Services: ShieldCheck,
|
||||
Services: Package,
|
||||
} satisfies Record<ContextCategory, unknown>;
|
||||
|
||||
/** What one item of each category is called, e.g. on its context pill. */
|
||||
export const CONTEXT_CATEGORY_SINGULAR: Record<ContextCategory, string> = {
|
||||
Dashboards: 'Dashboard',
|
||||
Alerts: 'Alert',
|
||||
Services: 'Service',
|
||||
};
|
||||
|
||||
/** What one item of each context type is called. */
|
||||
export const CONTEXT_TYPE_LABELS: Record<MessageContext['type'], string> = {
|
||||
dashboard: 'Dashboard',
|
||||
alert: 'Alert',
|
||||
service: 'Service',
|
||||
logs_explorer: 'Logs',
|
||||
traces_explorer: 'Traces',
|
||||
metrics_explorer: 'Metrics',
|
||||
saved_view: 'Saved view',
|
||||
};
|
||||
|
||||
/** Icon per page context: the picker's for the categories it shares, the side nav's for explorers. */
|
||||
export const AUTO_CONTEXT_ICONS: Record<
|
||||
MessageContext['type'],
|
||||
typeof Package
|
||||
> = {
|
||||
dashboard: CONTEXT_CATEGORY_ICONS.Dashboards,
|
||||
alert: CONTEXT_CATEGORY_ICONS.Alerts,
|
||||
service: CONTEXT_CATEGORY_ICONS.Services,
|
||||
logs_explorer: ScrollText,
|
||||
traces_explorer: DraftingCompass,
|
||||
metrics_explorer: BarChart,
|
||||
saved_view: Package,
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolved copy + composer prefill for one render of the context picker's empty
|
||||
* state. The picker is tabbed, so a user only ever views one category at a
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
.clarification {
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: 10px 12px;
|
||||
padding: var(--spacing-6);
|
||||
background: var(--l2-background);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
gap: var(--spacing-6);
|
||||
width: 100%;
|
||||
|
||||
// Clear of whatever the reply shows above it.
|
||||
&:not(:first-child) {
|
||||
margin-top: var(--spacing-6);
|
||||
}
|
||||
|
||||
// Below the header, everything lines up with the title, clear of the icon.
|
||||
&:not(.submitted) > :not(.header) {
|
||||
margin-left: calc(16px + var(--spacing-6));
|
||||
}
|
||||
|
||||
&.submitted {
|
||||
border-color: var(--l2-border);
|
||||
background: transparent;
|
||||
@@ -21,7 +31,7 @@
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: var(--spacing-6);
|
||||
}
|
||||
|
||||
.headerIcon {
|
||||
@@ -30,16 +40,17 @@
|
||||
}
|
||||
|
||||
.headerLabel {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.message {
|
||||
font-size: 13px;
|
||||
color: var(--l1-foreground);
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.icon {
|
||||
@@ -130,8 +141,11 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
// The two choices split the row evenly.
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 16px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--spacing-6);
|
||||
margin-top: var(--spacing-2);
|
||||
--button-width: 100%;
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ export default function ClarificationForm({
|
||||
return (
|
||||
<div className={styles.clarification}>
|
||||
<div className={styles.header}>
|
||||
<CircleHelp size={13} className={styles.headerIcon} />
|
||||
<CircleHelp size={16} className={styles.headerIcon} />
|
||||
<span className={styles.headerLabel}>A few details needed</span>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,30 +1,14 @@
|
||||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 6px 8px;
|
||||
border-radius: var(--radius-2);
|
||||
gap: var(--spacing-3);
|
||||
padding: 7px 0;
|
||||
cursor: pointer;
|
||||
min-width: 0;
|
||||
position: relative;
|
||||
// Driven below: hover and active reveal the action buttons.
|
||||
// Driven below: hover, the open chat, keyboard focus and an open menu reveal the action buttons.
|
||||
--actions-opacity: 0;
|
||||
|
||||
&:hover {
|
||||
background: var(--l2-background);
|
||||
--actions-opacity: 1;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--l2-background);
|
||||
--actions-opacity: 1;
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
&.archived {
|
||||
opacity: 0.92;
|
||||
|
||||
@@ -32,34 +16,63 @@
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&.active,
|
||||
&:focus-visible,
|
||||
&:has(:focus-visible),
|
||||
&:has([data-popup-open]) {
|
||||
--actions-opacity: 1;
|
||||
--actions-pointer: auto;
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
// Lights up while Noz is replying in that chat; the slot keeps every title aligned.
|
||||
.dot {
|
||||
flex-shrink: 0;
|
||||
color: var(--l3-foreground);
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
|
||||
&.isReplying {
|
||||
background: var(--accent-amber);
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 12px;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
// Gives way to the action buttons that float over it.
|
||||
.time {
|
||||
font-size: 10px;
|
||||
flex-shrink: 0;
|
||||
// Wide enough to hold the action buttons that replace it.
|
||||
min-width: 16px;
|
||||
text-align: right;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
line-height: 18px;
|
||||
color: var(--l3-foreground);
|
||||
opacity: 0.7;
|
||||
opacity: calc(1 - var(--actions-opacity, 0));
|
||||
transition: opacity 0.12s;
|
||||
}
|
||||
|
||||
.input {
|
||||
@@ -69,7 +82,7 @@
|
||||
border-bottom: 1px solid var(--accent-primary);
|
||||
outline: none;
|
||||
color: var(--l1-foreground);
|
||||
font-size: 12px;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-family: inherit;
|
||||
padding: 1px 0;
|
||||
}
|
||||
@@ -83,48 +96,40 @@
|
||||
transition: opacity 0.12s;
|
||||
// Float over the right edge of the item so the title can keep using
|
||||
// the full width while the buttons are hidden — no layout shift +
|
||||
// no premature truncation. The `background` matches the hover/active
|
||||
// state so the buttons visually mask any title text underneath.
|
||||
// no premature truncation. They sit in the time's slot, so they never
|
||||
// cover the title.
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 4px;
|
||||
right: 0;
|
||||
transform: translateY(-50%);
|
||||
background: var(--l2-background);
|
||||
padding: 1px 2px;
|
||||
border-radius: var(--radius-2);
|
||||
pointer-events: var(--actions-pointer, none);
|
||||
--button-width: 16px;
|
||||
--button-max-width: 16px;
|
||||
--button-min-width: 16px;
|
||||
--button-height: 20px;
|
||||
--button-padding: 0;
|
||||
}
|
||||
|
||||
.item:hover,
|
||||
.item.active {
|
||||
--actions-pointer: auto;
|
||||
}
|
||||
// The row menu is portalled to the body, so it is reached through the attribute it carries.
|
||||
:global([data-slot='dropdown-popup'][data-conversation-menu]) {
|
||||
--dropdown-min-inline-size: 207px;
|
||||
--dropdown-padding-block: var(--spacing-4);
|
||||
--dropdown-border-radius: var(--radius-2);
|
||||
--dropdown-background-color: var(--l3-background-60);
|
||||
--dropdown-backdrop-filter: blur(20px);
|
||||
--dropdown-item-gap: var(--spacing-3);
|
||||
--dropdown-item-padding: var(--spacing-2) 14px;
|
||||
--dropdown-item-slot-gap: var(--spacing-4);
|
||||
--dropdown-item-icon-size: 16px;
|
||||
--dropdown-item-line-height: 20px;
|
||||
--dropdown-item-border-radius: 0;
|
||||
--dropdown-item-color: var(--l1-foreground);
|
||||
--dropdown-item-icon-color: var(--l1-foreground);
|
||||
--dropdown-item-hover-background-color: var(--l3-background);
|
||||
// Rows sit 20px apart across the divider, 14px elsewhere.
|
||||
--dropdown-separator-margin-block: 0 -1px;
|
||||
|
||||
// Compact menu — narrower than the design-system default so the
|
||||
// content (Rename / Copy link / Archive) doesn't dwarf the row.
|
||||
// Shared sizing for every dropdown item so the menu reads compact —
|
||||
// matches the row's own 12px label scale.
|
||||
.menuItem {
|
||||
font-size: 12px !important;
|
||||
cursor: pointer !important;
|
||||
}
|
||||
|
||||
// Amber treatment for the destructive-but-recoverable Archive action —
|
||||
// less alarming than red since the conversation can be restored later.
|
||||
// Targets both the label text and the leading icon (icons inherit color
|
||||
// via `currentColor`).
|
||||
.archiveItem {
|
||||
color: var(--accent-amber) !important;
|
||||
|
||||
svg {
|
||||
color: inherit !important;
|
||||
}
|
||||
}
|
||||
|
||||
.restoreItem {
|
||||
color: var(--primary) !important;
|
||||
|
||||
svg {
|
||||
color: inherit !important;
|
||||
[data-slot='dropdown-item'] {
|
||||
letter-spacing: -0.005em;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
ArchiveRestore,
|
||||
EllipsisVertical,
|
||||
Link,
|
||||
MessageSquare,
|
||||
Pencil,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
import { Conversation } from '../../types';
|
||||
|
||||
import styles from './ConversationItem.module.scss';
|
||||
@@ -37,18 +37,18 @@ function formatRelativeTime(ts: number): string {
|
||||
const diff = Date.now() - ts;
|
||||
const mins = Math.floor(diff / 60_000);
|
||||
if (mins < 1) {
|
||||
return 'just now';
|
||||
return 'now';
|
||||
}
|
||||
if (mins < 60) {
|
||||
return `${mins}m ago`;
|
||||
return `${mins}m`;
|
||||
}
|
||||
const hrs = Math.floor(mins / 60);
|
||||
if (hrs < 24) {
|
||||
return `${hrs}h ago`;
|
||||
return `${hrs}h`;
|
||||
}
|
||||
const days = Math.floor(hrs / 24);
|
||||
if (days < 7) {
|
||||
return `${days}d ago`;
|
||||
return `${days}d`;
|
||||
}
|
||||
return new Date(ts).toLocaleDateString(undefined, {
|
||||
month: 'short',
|
||||
@@ -70,6 +70,9 @@ export default function ConversationItem({
|
||||
const [, copyToClipboard] = useCopyToClipboard();
|
||||
|
||||
const isArchived = Boolean(conversation.archived);
|
||||
const isReplying = useAIAssistantStore((s) =>
|
||||
Boolean(s.streams[conversation.id]?.isStreaming),
|
||||
);
|
||||
const displayTitle = conversation.title ?? 'New conversation';
|
||||
const ts = conversation.updatedAt ?? conversation.createdAt;
|
||||
|
||||
@@ -126,14 +129,14 @@ export default function ConversationItem({
|
||||
type: 'item',
|
||||
value: 'rename',
|
||||
label: 'Rename',
|
||||
prefix: <Pencil size={12} />,
|
||||
prefix: <Pencil size={16} />,
|
||||
onClick: (): void => startEditing(),
|
||||
},
|
||||
{
|
||||
type: 'item',
|
||||
value: 'copy-link',
|
||||
label: 'Copy link',
|
||||
prefix: <Link size={12} />,
|
||||
prefix: <Link size={16} />,
|
||||
onClick: handleCopyLink,
|
||||
},
|
||||
{ type: 'separator', value: 'divider' },
|
||||
@@ -145,7 +148,7 @@ export default function ConversationItem({
|
||||
type: 'item',
|
||||
value: 'restore',
|
||||
label: 'Restore',
|
||||
prefix: <ArchiveRestore size={12} />,
|
||||
prefix: <ArchiveRestore size={16} />,
|
||||
onClick: (): void => onRestore(conversation.id),
|
||||
},
|
||||
]
|
||||
@@ -155,7 +158,8 @@ export default function ConversationItem({
|
||||
type: 'item',
|
||||
value: 'archive',
|
||||
label: 'Archive',
|
||||
prefix: <Archive size={12} />,
|
||||
prefix: <Archive size={16} />,
|
||||
danger: true,
|
||||
onClick: (): void => onArchive(conversation.id),
|
||||
},
|
||||
];
|
||||
@@ -172,7 +176,7 @@ export default function ConversationItem({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<MessageSquare size={12} className={styles.icon} />
|
||||
<span className={cx(styles.dot, { [styles.isReplying]: isReplying })} />
|
||||
|
||||
<div className={styles.body}>
|
||||
{isEditing ? (
|
||||
@@ -204,7 +208,13 @@ export default function ConversationItem({
|
||||
// own clicks don't bubble, but the trigger button does.
|
||||
onClick={(e): void => e.stopPropagation()}
|
||||
>
|
||||
<Dropdown items={menuItems} nativeButton align="end" side="bottom">
|
||||
<Dropdown
|
||||
items={menuItems}
|
||||
nativeButton
|
||||
align="end"
|
||||
side="bottom"
|
||||
data-conversation-menu
|
||||
>
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
// Laid out like the message list, so the thread lands where its placeholder was.
|
||||
.thread {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 16px 0;
|
||||
gap: 14px;
|
||||
padding: 16px 0 64px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.message {
|
||||
display: flex;
|
||||
padding: 0 16px;
|
||||
padding: 8px 16px;
|
||||
|
||||
&.compact {
|
||||
padding: 0 12px;
|
||||
.compact & {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
// The full page keeps the thread in a 672px column; the extra 32px is the rows' own gutters.
|
||||
.fullPage & {
|
||||
width: 100%;
|
||||
max-width: 704px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,65 +27,46 @@
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.assistant {
|
||||
justify-content: flex-start;
|
||||
.userBubble {
|
||||
display: flex;
|
||||
max-width: 80%;
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
border-radius: 8px;
|
||||
background: var(--l3-background-60);
|
||||
}
|
||||
|
||||
.bubble {
|
||||
// Bare lines of text, inset like a reply.
|
||||
.reply {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
// `width: 100%` (capped by per-role max-width below) forces the bubble
|
||||
// to fill its allotted slot rather than collapsing to the longest line —
|
||||
// otherwise the lines' percent widths cascade into a tiny bubble.
|
||||
width: 100%;
|
||||
border-radius: var(--radius-2);
|
||||
padding: 12px 14px;
|
||||
width: 80%;
|
||||
padding: 0 var(--spacing-4);
|
||||
|
||||
&.user {
|
||||
// Narrower than the assistant bubble so the alternating chat-thread
|
||||
// asymmetry is preserved — but wider than the previous 80% so the
|
||||
// shimmer lines have room to read as a real-looking message.
|
||||
max-width: 75%;
|
||||
// Subtle primary tint so the right-side bubble reads as the user's
|
||||
// message without committing to the full saturated brand color.
|
||||
background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
|
||||
border-bottom-right-radius: var(--radius-2);
|
||||
color: var(--l1-foreground);
|
||||
.compact & {
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
&.assistant {
|
||||
max-width: 95%;
|
||||
background: var(--l2-background);
|
||||
border-bottom-left-radius: var(--radius-2);
|
||||
.fullPage & {
|
||||
width: 100%;
|
||||
padding: 0 0 0 var(--spacing-5);
|
||||
}
|
||||
}
|
||||
|
||||
// A bar in the middle of a 20px line, the height of the text it stands in for.
|
||||
.line {
|
||||
height: 9px;
|
||||
border-radius: 3px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: color-mix(in srgb, var(--l1-foreground) 10%, transparent);
|
||||
|
||||
// Shimmer sweep — same pattern used by HistorySidebar's skeleton rows.
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
transform: translateX(-100%);
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
color-mix(in srgb, var(--l1-foreground) 10%, transparent),
|
||||
transparent
|
||||
);
|
||||
animation: shimmer 1.15s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
100% {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
margin-block: 5px;
|
||||
--skeleton-input-height: 10px;
|
||||
--skeleton-input-width: 100%;
|
||||
--skeleton-input-min-width: 0;
|
||||
--skeleton-input-border-radius: var(--radius-1);
|
||||
--skeleton-background: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground),
|
||||
transparent 92%
|
||||
);
|
||||
--skeleton-shimmer-color: color-mix(
|
||||
in srgb,
|
||||
var(--l1-foreground),
|
||||
transparent 92%
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,51 +1,69 @@
|
||||
import cx from 'classnames';
|
||||
import { Skeleton } from '@signozhq/ui/skeleton';
|
||||
|
||||
import { useVariant } from '../../VariantContext';
|
||||
|
||||
import styles from './ConversationSkeleton.module.scss';
|
||||
|
||||
/**
|
||||
* Each entry is one bubble in the placeholder thread:
|
||||
* role: who "sent" the bubble — drives left/right alignment + colour
|
||||
* lines: list of widths (as % of the bubble) for the shimmer lines inside
|
||||
* Each entry is one message in the placeholder thread:
|
||||
* user: a sent bubble, `width` as % of the row
|
||||
* assistant: a reply, one width per line as % of the reply
|
||||
*
|
||||
* Mixed widths and varying line counts produce something that scans as a real
|
||||
* back-and-forth conversation rather than a uniform grid.
|
||||
*/
|
||||
const ROWS: { role: 'user' | 'assistant'; lines: number[] }[] = [
|
||||
{ role: 'user', lines: [62] },
|
||||
{ role: 'assistant', lines: [85, 92, 70] },
|
||||
{ role: 'user', lines: [55, 40] },
|
||||
{ role: 'assistant', lines: [90, 78, 95, 60] },
|
||||
{ role: 'user', lines: [48] },
|
||||
{ role: 'assistant', lines: [80, 88] },
|
||||
const PATTERN: (
|
||||
| { role: 'user'; width: number }
|
||||
| { role: 'assistant'; lines: number[] }
|
||||
)[] = [
|
||||
{ role: 'user', width: 42 },
|
||||
{ role: 'assistant', lines: [94, 88, 66] },
|
||||
{ role: 'user', width: 30 },
|
||||
{ role: 'assistant', lines: [90, 96, 84, 58] },
|
||||
{ role: 'user', width: 36 },
|
||||
{ role: 'assistant', lines: [86, 70] },
|
||||
];
|
||||
|
||||
// Enough repeats to fill a tall pane down to the input; the thread clips the rest.
|
||||
const ROWS = [...PATTERN, ...PATTERN, ...PATTERN, ...PATTERN];
|
||||
|
||||
/** Skeleton chat thread shown while a single conversation is being loaded. */
|
||||
export default function ConversationSkeleton(): JSX.Element {
|
||||
const variant = useVariant();
|
||||
const isCompact = variant === 'panel';
|
||||
|
||||
return (
|
||||
<div className={styles.thread} aria-busy aria-label="Loading conversation">
|
||||
<div
|
||||
className={cx(styles.thread, {
|
||||
[styles.compact]: variant === 'panel',
|
||||
[styles.fullPage]: variant === 'page',
|
||||
})}
|
||||
aria-busy
|
||||
aria-label="Loading conversation"
|
||||
>
|
||||
{ROWS.map((row, idx) => (
|
||||
<div
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={idx}
|
||||
className={cx(styles.message, styles[row.role], {
|
||||
[styles.compact]: isCompact,
|
||||
})}
|
||||
className={cx(styles.message, { [styles.user]: row.role === 'user' })}
|
||||
>
|
||||
<div className={cx(styles.bubble, styles[row.role])}>
|
||||
{row.lines.map((width, lineIdx) => (
|
||||
<div
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={lineIdx}
|
||||
className={styles.line}
|
||||
style={{ width: `${width}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{row.role === 'user' ? (
|
||||
<div className={styles.userBubble} style={{ width: `${row.width}%` }}>
|
||||
<Skeleton.Input active className={styles.line} />
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.reply}>
|
||||
{row.lines.map((width, lineIdx) => (
|
||||
<Skeleton.Input
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={lineIdx}
|
||||
active
|
||||
className={styles.line}
|
||||
style={{ width: `${width}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
@use '../../_scrollbar' as *;
|
||||
@use '../../_bareInput' as *;
|
||||
|
||||
.conversationsList {
|
||||
display: flex;
|
||||
@@ -6,11 +7,23 @@
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
|
||||
// Page variant: fixed-width left column.
|
||||
// Page variant: fixed-width left column; the thread pane draws the edge beside it.
|
||||
&.variantPage {
|
||||
position: relative;
|
||||
width: 280px;
|
||||
flex-shrink: 0;
|
||||
border-right: 1px solid var(--l1-border);
|
||||
|
||||
// Fades the list's foot into the page.
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 46px;
|
||||
background: linear-gradient(to bottom, transparent, var(--l1-background));
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
// Panel variant: full-width overlay (replaces conversation view).
|
||||
@@ -20,41 +33,47 @@
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.heading {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--l2-foreground);
|
||||
// Collapse the line-box to the glyph height so the loading dots
|
||||
// (centered against the line-box) line up with the cap-height of the
|
||||
// uppercase text instead of sitting visually low.
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
// A bare search line over a divider.
|
||||
.searchBar {
|
||||
padding: 0px 8px 12px;
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-6);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
@include bare-input;
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.newConversation {
|
||||
flex-shrink: 0;
|
||||
padding: var(--spacing-6) var(--spacing-6) var(--spacing-4);
|
||||
--button-width: 100%;
|
||||
--button-max-width: 100%;
|
||||
--button-height: 34px;
|
||||
--button-padding: 7px 11px;
|
||||
--button-border-radius: 3px;
|
||||
--button-justify-content: flex-start;
|
||||
--button-gap: var(--spacing-4);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-variant-outlined-background-color: var(--l2-background);
|
||||
--button-variant-outlined-border: 1px solid var(--l1-border);
|
||||
--button-variant-outlined-color: var(--l2-foreground);
|
||||
|
||||
// Buttons don't inherit the page font.
|
||||
> [data-slot='button'] {
|
||||
font-family: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0 6px 12px;
|
||||
padding: var(--spacing-6);
|
||||
@include scrollbar(0.25rem);
|
||||
}
|
||||
|
||||
@@ -115,8 +134,7 @@
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
margin-bottom: 8px;
|
||||
margin-bottom: var(--spacing-6);
|
||||
|
||||
&.archived {
|
||||
margin-top: 4px;
|
||||
@@ -127,10 +145,11 @@
|
||||
|
||||
.groupLabel {
|
||||
display: block;
|
||||
padding: 8px;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
padding: 0 0 7px;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.07em;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { Plus, Search } from '@signozhq/icons';
|
||||
import { Plus } from '@signozhq/icons';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -57,11 +56,11 @@ function groupByDate(
|
||||
}
|
||||
|
||||
/**
|
||||
* Three-dot loading indicator. Sits inside the sidebar header so the
|
||||
* Three-dot loading indicator. Sits beside the search field so the
|
||||
* conversation list is never bumped down by a skeleton row when threads
|
||||
* load — visible signal of in-flight work without any layout shift.
|
||||
*/
|
||||
function HeaderLoadingDots(): JSX.Element {
|
||||
function LoadingDots(): JSX.Element {
|
||||
return (
|
||||
<span className={styles.loadingDots} role="status" aria-label="Loading">
|
||||
<span className={styles.loadingDot} />
|
||||
@@ -166,37 +165,33 @@ export default function ConversationsList({
|
||||
|
||||
return (
|
||||
<div className={cx(styles.conversationsList, variantClass)}>
|
||||
<div className={styles.header}>
|
||||
<span className={styles.heading}>Conversations</span>
|
||||
{isLoadingThreads && <HeaderLoadingDots />}
|
||||
|
||||
{!isLoadingThreads && showAddNewConversation && (
|
||||
<Tooltip title="New conversation">
|
||||
<Button
|
||||
variant="solid"
|
||||
size="sm"
|
||||
color="secondary"
|
||||
onClick={onNewConversation}
|
||||
aria-label="New conversation"
|
||||
icon
|
||||
>
|
||||
<Plus size={12} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={styles.searchBar}>
|
||||
<Input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e): void => setSearchQuery(e.target.value)}
|
||||
placeholder="Search conversations…"
|
||||
prefix={<Search size={12} />}
|
||||
placeholder="Search…"
|
||||
aria-label="Search conversations"
|
||||
className={styles.search}
|
||||
/>
|
||||
{isLoadingThreads && <LoadingDots />}
|
||||
</div>
|
||||
|
||||
{!isLoadingThreads && showAddNewConversation && (
|
||||
<div className={styles.newConversation}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="md"
|
||||
color="secondary"
|
||||
prefix={<Plus size={16} />}
|
||||
onClick={onNewConversation}
|
||||
testId="ai-assistant-new-conversation"
|
||||
>
|
||||
New conversation
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.list} aria-busy={isLoadingThreads}>
|
||||
{isLoadingThreads && (
|
||||
<span className={styles.srOnly} role="status">
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
.dotGrid {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.canvas {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
// The Snake score line, faint in the grid's bottom-left corner.
|
||||
.label {
|
||||
position: absolute;
|
||||
left: var(--spacing-6);
|
||||
bottom: var(--spacing-1);
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: var(--periscope-font-size-small);
|
||||
letter-spacing: 0.34em;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
color: var(--l3-foreground);
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useRef } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { useDotGrid } from './useDotGrid';
|
||||
|
||||
import styles from './DotGrid.module.scss';
|
||||
|
||||
interface DotGridProps {
|
||||
/** Sizes and places the grid; it fills whatever box it gets. */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Aurora dot grid that drifts on its own and lights up under the cursor. */
|
||||
export default function DotGrid({ className }: DotGridProps): JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const label = useDotGrid(canvasRef);
|
||||
|
||||
return (
|
||||
<div className={cx(styles.dotGrid, className)} aria-hidden>
|
||||
<canvas ref={canvasRef} className={styles.canvas} />
|
||||
{label && <span className={styles.label}>{label}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Tunables and the drifting aurora field from the design's dot-grid prototype.
|
||||
|
||||
export const DOT_SPACING = 12;
|
||||
export const DOT_RADIUS = 1.15;
|
||||
|
||||
export const TRAIL_RADIUS = 72;
|
||||
export const TRAIL_LIFT = 0.24;
|
||||
export const TRAIL_MAX_POINTS = 18;
|
||||
export const TRAIL_LIFE_MS = 1000;
|
||||
export const TRAIL_MIN_STEP = 7;
|
||||
|
||||
// Time the field rests at when motion is reduced.
|
||||
export const STILL_TIME_MS = 12000;
|
||||
|
||||
type Rgb = [number, number, number];
|
||||
|
||||
// Green, teal, blue, violet and pink, in the order the field drifts through them.
|
||||
const AURORA: Rgb[] = [
|
||||
[64, 224, 150],
|
||||
[48, 200, 210],
|
||||
[90, 130, 245],
|
||||
[170, 110, 245],
|
||||
[235, 110, 200],
|
||||
];
|
||||
|
||||
/** Brightness of the field at a point, between -1 and 1. */
|
||||
export function auroraBrightness(x: number, y: number, t: number): number {
|
||||
return (
|
||||
(Math.sin(x * 0.009 + t * 0.0006) +
|
||||
Math.sin(y * 0.015 - t * 0.00085 + x * 0.002) +
|
||||
Math.sin((x + y) * 0.006 + t * 0.0011) +
|
||||
Math.sin((x - y) * 0.0048 - t * 0.0007)) /
|
||||
4
|
||||
);
|
||||
}
|
||||
|
||||
/** Colour of the field at a point, blended along the aurora palette. */
|
||||
export function auroraColor(x: number, y: number, t: number): Rgb {
|
||||
const position =
|
||||
((Math.sin(x * 0.0035 + t * 0.00018) +
|
||||
Math.sin(y * 0.005 - t * 0.00026) +
|
||||
Math.sin((x + y) * 0.0028 + t * 0.0002)) /
|
||||
3 +
|
||||
1) /
|
||||
2;
|
||||
const scaled = position * (AURORA.length - 1);
|
||||
const from = AURORA[Math.floor(scaled)];
|
||||
const to = AURORA[Math.min(Math.floor(scaled) + 1, AURORA.length - 1)];
|
||||
const mix = scaled - Math.floor(scaled);
|
||||
return [
|
||||
from[0] + (to[0] - from[0]) * mix,
|
||||
from[1] + (to[1] - from[1]) * mix,
|
||||
from[2] + (to[2] - from[2]) * mix,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Painting for the dot grid: the aurora field with the cursor's glow, and plain dots.
|
||||
|
||||
import {
|
||||
auroraBrightness,
|
||||
auroraColor,
|
||||
DOT_RADIUS,
|
||||
TRAIL_LIFE_MS,
|
||||
TRAIL_LIFT,
|
||||
TRAIL_RADIUS,
|
||||
} from './dotGridField';
|
||||
|
||||
export interface TrailPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
born: number;
|
||||
}
|
||||
|
||||
interface AuroraFrame {
|
||||
/** Field time; frozen when motion is reduced. */
|
||||
t: number;
|
||||
now: number;
|
||||
height: number;
|
||||
trail: TrailPoint[];
|
||||
isGameOn: boolean;
|
||||
/** Dots below this stay dark. */
|
||||
cutoffY: number;
|
||||
}
|
||||
|
||||
/** The faint light that washes up from the bottom while the game is on. */
|
||||
export function gameFloor(y: number, height: number): number {
|
||||
return 0.07 + 0.16 * (y / height);
|
||||
}
|
||||
|
||||
export function drawDot(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
x: number,
|
||||
y: number,
|
||||
radius: number,
|
||||
fill: string,
|
||||
): void {
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = fill;
|
||||
ctx.arc(x, y, radius, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
/** Paints the aurora dots, brightest at the top and lit along the cursor's trail. */
|
||||
export function drawAuroraDots(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
dots: { x: number; y: number }[],
|
||||
{ t, now, height, trail, isGameOn, cutoffY }: AuroraFrame,
|
||||
): void {
|
||||
// Overlapping glows add up, as light does.
|
||||
ctx.globalCompositeOperation = 'lighter';
|
||||
dots.forEach(({ x, y }) => {
|
||||
if (y > cutoffY) {
|
||||
return;
|
||||
}
|
||||
// Brightest at the top, fading toward the content below.
|
||||
const topWeight = 1 - 0.82 * Math.min(1, y / height);
|
||||
const lum = Math.max(0, auroraBrightness(x, y, t)) ** 1.6;
|
||||
let intensity = (0.06 + lum * 0.4) * topWeight * (isGameOn ? 0.5 : 1);
|
||||
if (isGameOn) {
|
||||
intensity += gameFloor(y, height);
|
||||
}
|
||||
|
||||
let glow = 0;
|
||||
trail.forEach((point) => {
|
||||
const distance2 = (x - point.x) ** 2 + (y - point.y) ** 2;
|
||||
if (distance2 < TRAIL_RADIUS ** 2) {
|
||||
const life = 1 - (now - point.born) / TRAIL_LIFE_MS;
|
||||
glow += (1 - distance2 / TRAIL_RADIUS ** 2) ** 3 * life;
|
||||
}
|
||||
});
|
||||
intensity += Math.min(glow, 1.3) * TRAIL_LIFT * topWeight;
|
||||
|
||||
if (intensity <= 0.02) {
|
||||
return;
|
||||
}
|
||||
const [red, green, blue] = auroraColor(x, y, t);
|
||||
const white = Math.min(1, Math.max(0, intensity - 0.9)) * 0.9;
|
||||
const rgb = `${Math.round(red + (255 - red) * white)},${Math.round(
|
||||
green + (255 - green) * white,
|
||||
)},${Math.round(blue + (255 - blue) * white)}`;
|
||||
const alpha = Math.min(1, intensity);
|
||||
const radius = DOT_RADIUS + Math.min(intensity, 1.2) * 0.7;
|
||||
|
||||
if (intensity > 0.6) {
|
||||
drawDot(ctx, x, y, radius * 2.6, `rgba(${rgb},${alpha * 0.06})`);
|
||||
}
|
||||
drawDot(ctx, x, y, radius, `rgba(${rgb},${alpha})`);
|
||||
});
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Snake on the dot grid, the easter egg the Konami code unlocks.
|
||||
|
||||
interface Cell {
|
||||
c: number;
|
||||
r: number;
|
||||
}
|
||||
|
||||
export interface SnakeGame {
|
||||
body: Cell[];
|
||||
dir: Cell;
|
||||
nextDir: Cell;
|
||||
food: Cell;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export const SNAKE_STEP_MS = 110;
|
||||
|
||||
export const KONAMI_CODE = [
|
||||
'arrowup',
|
||||
'arrowup',
|
||||
'arrowdown',
|
||||
'arrowdown',
|
||||
'arrowleft',
|
||||
'arrowright',
|
||||
'arrowleft',
|
||||
'arrowright',
|
||||
'b',
|
||||
'a',
|
||||
];
|
||||
|
||||
export const SNAKE_DIRECTIONS: Record<string, Cell> = {
|
||||
arrowup: { c: 0, r: -1 },
|
||||
w: { c: 0, r: -1 },
|
||||
arrowdown: { c: 0, r: 1 },
|
||||
s: { c: 0, r: 1 },
|
||||
arrowleft: { c: -1, r: 0 },
|
||||
a: { c: -1, r: 0 },
|
||||
arrowright: { c: 1, r: 0 },
|
||||
d: { c: 1, r: 0 },
|
||||
};
|
||||
|
||||
const isOn = (cells: Cell[], cell: Cell): boolean =>
|
||||
cells.some(({ c, r }) => c === cell.c && r === cell.r);
|
||||
|
||||
/** A free cell for the food, or null when the snake fills the grid. */
|
||||
function placeFood(body: Cell[], cols: number, rows: number): Cell | null {
|
||||
const free: Cell[] = [];
|
||||
for (let r = 0; r < rows; r += 1) {
|
||||
for (let c = 0; c < cols; c += 1) {
|
||||
if (!isOn(body, { c, r })) {
|
||||
free.push({ c, r });
|
||||
}
|
||||
}
|
||||
}
|
||||
return free.length ? free[Math.floor(Math.random() * free.length)] : null;
|
||||
}
|
||||
|
||||
/** A four-cell snake in the middle heading right, or null when the grid is too small. */
|
||||
export function startSnake(cols: number, rows: number): SnakeGame | null {
|
||||
if (cols < 8 || rows < 6) {
|
||||
return null;
|
||||
}
|
||||
const c = Math.floor(cols / 2);
|
||||
const r = Math.floor(rows / 2);
|
||||
const body = [0, 1, 2, 3].map((i) => ({ c: c - i, r }));
|
||||
const food = placeFood(body, cols, rows);
|
||||
if (!food) {
|
||||
return null;
|
||||
}
|
||||
const right = { c: 1, r: 0 };
|
||||
return { body, dir: right, nextDir: right, food, score: 0 };
|
||||
}
|
||||
|
||||
/** Moves the snake one cell; null when it hits a wall, itself, or fills the grid. */
|
||||
export function stepSnake(
|
||||
game: SnakeGame,
|
||||
cols: number,
|
||||
rows: number,
|
||||
): SnakeGame | null {
|
||||
const dir = game.nextDir;
|
||||
const head = { c: game.body[0].c + dir.c, r: game.body[0].r + dir.r };
|
||||
if (
|
||||
head.c < 0 ||
|
||||
head.c >= cols ||
|
||||
head.r < 0 ||
|
||||
head.r >= rows ||
|
||||
isOn(game.body, head)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const ate = head.c === game.food.c && head.r === game.food.r;
|
||||
const body = [head, ...(ate ? game.body : game.body.slice(0, -1))];
|
||||
const food = ate ? placeFood(body, cols, rows) : game.food;
|
||||
if (!food) {
|
||||
return null;
|
||||
}
|
||||
return { ...game, body, dir, food, score: game.score + (ate ? 1 : 0) };
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { RefObject, useEffect, useState } from 'react';
|
||||
|
||||
import {
|
||||
DOT_RADIUS,
|
||||
DOT_SPACING,
|
||||
STILL_TIME_MS,
|
||||
TRAIL_LIFE_MS,
|
||||
TRAIL_MAX_POINTS,
|
||||
TRAIL_MIN_STEP,
|
||||
TRAIL_RADIUS,
|
||||
} from './dotGridField';
|
||||
import { drawAuroraDots, drawDot, gameFloor, TrailPoint } from './drawDots';
|
||||
import {
|
||||
KONAMI_CODE,
|
||||
SNAKE_DIRECTIONS,
|
||||
SNAKE_STEP_MS,
|
||||
SnakeGame,
|
||||
startSnake,
|
||||
stepSnake,
|
||||
} from './snakeGame';
|
||||
|
||||
const GAME_OVER_LABEL_MS = 4000;
|
||||
const REPLAY_LABEL = '↑ to replay';
|
||||
|
||||
// Unlocked once per page load; after that a click on the dots starts a game.
|
||||
let isSnakeUnlocked = false;
|
||||
// Room left under the snake's lowest row for the score line, so the two never touch.
|
||||
const SCORE_LINE_CLEARANCE = 30;
|
||||
|
||||
/** Draws the aurora dot grid, lit under the cursor; the Konami code turns it into Snake. Returns the score line. */
|
||||
export function useDotGrid(
|
||||
canvasRef: RefObject<HTMLCanvasElement>,
|
||||
): string | null {
|
||||
const [label, setLabel] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas?.getContext('2d');
|
||||
if (!canvas || !ctx) {
|
||||
return undefined;
|
||||
}
|
||||
const isStill = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let cols = 0;
|
||||
let rows = 0;
|
||||
let gameRows = 0;
|
||||
let left = 0;
|
||||
let dots: { x: number; y: number }[] = [];
|
||||
const trail: TrailPoint[] = [];
|
||||
let frame = 0;
|
||||
let game: SnakeGame | null = null;
|
||||
let lastStep = 0;
|
||||
// With reduced motion the field stands still, so frames repaint only after a change.
|
||||
let needsDraw = true;
|
||||
let isScoreLineShown = false;
|
||||
const showScoreLine = (text: string | null): void => {
|
||||
isScoreLineShown = text !== null;
|
||||
needsDraw = true;
|
||||
setLabel(text);
|
||||
};
|
||||
const recentKeys: string[] = [];
|
||||
let labelTimer = 0;
|
||||
// An arrow key replays while the game over line is up.
|
||||
let canReplay = false;
|
||||
const showPlayCursor = (): void => {
|
||||
canvas.style.cursor = isSnakeUnlocked && !game ? 'pointer' : '';
|
||||
};
|
||||
|
||||
const cellCenter = (c: number, r: number): { x: number; y: number } => ({
|
||||
x: left + c * DOT_SPACING,
|
||||
y: DOT_SPACING + r * DOT_SPACING,
|
||||
});
|
||||
|
||||
const play = (): void => {
|
||||
game = startSnake(cols, gameRows);
|
||||
lastStep = performance.now();
|
||||
canReplay = false;
|
||||
window.clearTimeout(labelTimer);
|
||||
showScoreLine(game ? 'Snake · score 0 · ↑ ↓ ← →' : null);
|
||||
showPlayCursor();
|
||||
};
|
||||
const endGame = (score: number): void => {
|
||||
game = null;
|
||||
canReplay = true;
|
||||
showScoreLine(`Game over · score ${score} · ${REPLAY_LABEL}`);
|
||||
showPlayCursor();
|
||||
labelTimer = window.setTimeout(() => {
|
||||
canReplay = false;
|
||||
showScoreLine(null);
|
||||
}, GAME_OVER_LABEL_MS);
|
||||
};
|
||||
|
||||
const layout = (): void => {
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
width = canvas.clientWidth;
|
||||
height = canvas.clientHeight;
|
||||
canvas.width = Math.floor(width * dpr);
|
||||
canvas.height = Math.floor(height * dpr);
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
|
||||
cols = Math.max(0, Math.floor((width - DOT_SPACING) / DOT_SPACING));
|
||||
rows = Math.max(0, Math.floor((height - DOT_SPACING) / DOT_SPACING));
|
||||
gameRows = Math.min(
|
||||
rows,
|
||||
Math.max(0, Math.floor((height - SCORE_LINE_CLEARANCE) / DOT_SPACING)),
|
||||
);
|
||||
left = (width - cols * DOT_SPACING) / 2 + DOT_SPACING / 2;
|
||||
dots = [];
|
||||
for (let r = 0; r < rows; r += 1) {
|
||||
for (let c = 0; c < cols; c += 1) {
|
||||
dots.push(cellCenter(c, r));
|
||||
}
|
||||
}
|
||||
needsDraw = true;
|
||||
// A game carries on through a resize unless it no longer fits.
|
||||
if (
|
||||
game &&
|
||||
[...game.body, game.food].some(({ c, r }) => c >= cols || r >= gameRows)
|
||||
) {
|
||||
play();
|
||||
}
|
||||
};
|
||||
|
||||
const onPointer = (event: PointerEvent): void => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
const y = event.clientY - rect.top;
|
||||
if (
|
||||
x < -TRAIL_RADIUS ||
|
||||
y < -TRAIL_RADIUS ||
|
||||
x > width + TRAIL_RADIUS ||
|
||||
y > height + TRAIL_RADIUS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const head = trail[trail.length - 1];
|
||||
// Barely moved: keep the head lit instead of stacking points.
|
||||
if (head && Math.hypot(x - head.x, y - head.y) < TRAIL_MIN_STEP) {
|
||||
head.born = performance.now();
|
||||
return;
|
||||
}
|
||||
trail.push({ x, y, born: performance.now() });
|
||||
if (trail.length > TRAIL_MAX_POINTS) {
|
||||
trail.shift();
|
||||
}
|
||||
};
|
||||
|
||||
// Keys typed into a field outside this chat belong to that field.
|
||||
const isOtherField = (target: EventTarget | null): boolean => {
|
||||
if (
|
||||
!(target instanceof HTMLElement) ||
|
||||
!target.closest('input, textarea, select, [contenteditable="true"]')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let chat = canvas.parentElement;
|
||||
while (chat && !chat.querySelector('textarea')) {
|
||||
chat = chat.parentElement;
|
||||
}
|
||||
return !chat?.contains(target);
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent): void => {
|
||||
if (isOtherField(event.target)) {
|
||||
return;
|
||||
}
|
||||
const key = event.key.toLowerCase();
|
||||
if (game) {
|
||||
const next = SNAKE_DIRECTIONS[key];
|
||||
if (next) {
|
||||
// Steering keys drive the snake, not the input; no turning back onto the neck.
|
||||
event.preventDefault();
|
||||
if (next.c !== -game.dir.c || next.r !== -game.dir.r) {
|
||||
game.nextDir = next;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (canReplay && key.startsWith('arrow')) {
|
||||
event.preventDefault();
|
||||
play();
|
||||
return;
|
||||
}
|
||||
recentKeys.push(key);
|
||||
if (recentKeys.length > KONAMI_CODE.length) {
|
||||
recentKeys.shift();
|
||||
}
|
||||
if (recentKeys.join() === KONAMI_CODE.join()) {
|
||||
recentKeys.length = 0;
|
||||
isSnakeUnlocked = true;
|
||||
play();
|
||||
}
|
||||
};
|
||||
|
||||
const onClick = (): void => {
|
||||
if (isSnakeUnlocked && !game) {
|
||||
play();
|
||||
}
|
||||
};
|
||||
|
||||
// The snake and its food: flat white dots the size of their neighbours.
|
||||
const stepAndDrawSnake = (now: number): void => {
|
||||
if (game && now - lastStep >= SNAKE_STEP_MS) {
|
||||
lastStep = now;
|
||||
const next = stepSnake(game, cols, gameRows);
|
||||
if (next) {
|
||||
if (next.score !== game.score) {
|
||||
showScoreLine(`Snake · score ${next.score} · ↑ ↓ ← →`);
|
||||
}
|
||||
game = next;
|
||||
} else {
|
||||
endGame(game.score);
|
||||
}
|
||||
}
|
||||
if (game) {
|
||||
const sizeAt = (y: number): number =>
|
||||
DOT_RADIUS + Math.min(gameFloor(y, height), 1.2) * 0.7;
|
||||
const food = cellCenter(game.food.c, game.food.r);
|
||||
drawDot(ctx, food.x, food.y, sizeAt(food.y), 'rgba(255,255,255,0.97)');
|
||||
game.body.forEach((cell, i) => {
|
||||
const { x, y } = cellCenter(cell.c, cell.r);
|
||||
drawDot(
|
||||
ctx,
|
||||
x,
|
||||
y,
|
||||
sizeAt(y),
|
||||
i === 0 ? 'rgba(255,255,255,1)' : 'rgba(232,238,245,0.92)',
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const draw = (now: number): void => {
|
||||
const hadTrail = trail.length > 0;
|
||||
for (let i = trail.length - 1; i >= 0; i -= 1) {
|
||||
if (now - trail[i].born >= TRAIL_LIFE_MS) {
|
||||
trail.splice(i, 1);
|
||||
}
|
||||
}
|
||||
if (isStill && !game && !hadTrail && !needsDraw) {
|
||||
frame = requestAnimationFrame(draw);
|
||||
return;
|
||||
}
|
||||
needsDraw = false;
|
||||
|
||||
const t = isStill ? STILL_TIME_MS : now;
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
drawAuroraDots(ctx, dots, {
|
||||
t,
|
||||
now,
|
||||
height,
|
||||
trail,
|
||||
isGameOn: game !== null,
|
||||
// Keeps the score line's strip clear of dots.
|
||||
cutoffY: isScoreLineShown ? gameRows * DOT_SPACING : Infinity,
|
||||
});
|
||||
|
||||
stepAndDrawSnake(now);
|
||||
|
||||
frame = requestAnimationFrame(draw);
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(layout);
|
||||
observer.observe(canvas);
|
||||
layout();
|
||||
window.addEventListener('pointermove', onPointer);
|
||||
window.addEventListener('pointerdown', onPointer);
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
canvas.addEventListener('click', onClick);
|
||||
showPlayCursor();
|
||||
frame = requestAnimationFrame(draw);
|
||||
|
||||
return (): void => {
|
||||
cancelAnimationFrame(frame);
|
||||
observer.disconnect();
|
||||
window.clearTimeout(labelTimer);
|
||||
window.removeEventListener('pointermove', onPointer);
|
||||
window.removeEventListener('pointerdown', onPointer);
|
||||
window.removeEventListener('keydown', onKeyDown);
|
||||
canvas.removeEventListener('click', onClick);
|
||||
};
|
||||
}, [canvasRef]);
|
||||
|
||||
return label;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Sits on the 20px text line without stretching it.
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
box-sizing: border-box;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
max-width: 100%;
|
||||
height: 20px;
|
||||
padding: 0 var(--spacing-2);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l3-background-60);
|
||||
color: var(--l2-foreground);
|
||||
line-height: 18px;
|
||||
text-decoration: none;
|
||||
vertical-align: top;
|
||||
transition:
|
||||
background-color 0.12s,
|
||||
color 0.12s;
|
||||
|
||||
&:hover {
|
||||
background: var(--l2-background-hover);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { Link } from '@signozhq/icons';
|
||||
|
||||
import styles from './MarkdownExternalLink.module.scss';
|
||||
|
||||
type MarkdownExternalLinkProps = ComponentProps<'a'> & {
|
||||
// react-markdown passes `node` — accept and ignore it
|
||||
@@ -18,9 +21,12 @@ export default function MarkdownExternalLink({
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
data-testid="ai-markdown-link"
|
||||
title={href}
|
||||
{...props}
|
||||
className={styles.pill}
|
||||
>
|
||||
{children}
|
||||
<Link size={14} className={styles.icon} />
|
||||
<span className={styles.label}>{children}</span>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
@use '../../_scrollbar' as *;
|
||||
|
||||
.panel {
|
||||
margin: 0 0 0.65em;
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--l1-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l2-background);
|
||||
@include scrollbar(0.25rem);
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
|
||||
import styles from './MarkdownTable.module.scss';
|
||||
|
||||
type MarkdownTableProps = ComponentProps<'table'> & {
|
||||
// react-markdown passes `node` — accept and ignore it
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
node?: any;
|
||||
};
|
||||
|
||||
/** A reply's table in its panel, which scrolls sideways when the table is wider than the reply. */
|
||||
export default function MarkdownTable({
|
||||
node: _node,
|
||||
...props
|
||||
}: MarkdownTableProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.panel}>
|
||||
<table {...props} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Right under the bubble, beside its 28px hover actions rather than below them.
|
||||
.addedContexts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--spacing-3) var(--spacing-4);
|
||||
margin-top: -28px;
|
||||
padding: 0 calc(16px + 28px) 8px 16px;
|
||||
|
||||
&.compact {
|
||||
padding: 0 calc(6px + 28px) 6px 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.note {
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1;
|
||||
font-feature-settings:
|
||||
'tnum' on,
|
||||
'lnum' on,
|
||||
'zero' on,
|
||||
'ss01' on;
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import cx from 'classnames';
|
||||
import { Package } from '@signozhq/icons';
|
||||
|
||||
import { MessageContext } from 'api/ai-assistant/chat';
|
||||
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import {
|
||||
AUTO_CONTEXT_ICONS,
|
||||
CONTEXT_TYPE_LABELS,
|
||||
} from '../ChatInput/contextPicker';
|
||||
import ContextPill from '../ChatInput/ContextPill/ContextPill';
|
||||
|
||||
import styles from './AddedContexts.module.scss';
|
||||
|
||||
interface AddedContextsProps {
|
||||
contexts: MessageContext[];
|
||||
}
|
||||
|
||||
/** The resources a message was sent with, by @-pick; the page it came from is left out. */
|
||||
export default function AddedContexts({
|
||||
contexts,
|
||||
}: AddedContextsProps): JSX.Element | null {
|
||||
const variant = useVariant();
|
||||
const picked = contexts.filter((ctx) => ctx.source === 'mention');
|
||||
if (picked.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(styles.addedContexts, {
|
||||
[styles.compact]: variant === 'panel',
|
||||
})}
|
||||
>
|
||||
{picked.map((ctx) => (
|
||||
<ContextPill
|
||||
key={`${ctx.type}:${ctx.resourceId ?? ctx.resourceName}`}
|
||||
// The server may name a type this client predates.
|
||||
icon={AUTO_CONTEXT_ICONS[ctx.type] ?? Package}
|
||||
category={CONTEXT_TYPE_LABELS[ctx.type] ?? ctx.type}
|
||||
label={ctx.resourceName ?? ctx.resourceId ?? ''}
|
||||
/>
|
||||
))}
|
||||
<span className={styles.note}>added to context</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -37,6 +37,11 @@
|
||||
.assistant & {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
// The full page's column is already narrow, so replies use all of it.
|
||||
.assistant &.fullPage {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.bubble {
|
||||
@@ -47,12 +52,15 @@
|
||||
font-weight: 400;
|
||||
line-height: 20px; /* 153.846% */
|
||||
letter-spacing: -0.065px;
|
||||
font-feature-settings: 'zero' on;
|
||||
max-width: 100%;
|
||||
|
||||
.user & {
|
||||
background: var(--accent-primary);
|
||||
color: var(--primary-foreground);
|
||||
border-bottom-right-radius: var(--radius-2);
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
border-radius: 8px;
|
||||
background: var(--l3-background-60);
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
}
|
||||
|
||||
.assistant & {
|
||||
@@ -65,8 +73,15 @@
|
||||
align-items: flex-start;
|
||||
background: var(--l2-background);
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
border-bottom-left-radius: var(--radius-2);
|
||||
}
|
||||
|
||||
// The full page shows replies as plain text on the pane; errors keep their callout.
|
||||
.assistant .fullPage &:not(.error) {
|
||||
padding: 0 0 0 var(--spacing-5);
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.text {
|
||||
@@ -208,17 +223,6 @@
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent-primary);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
text-decoration-thickness: 1px;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 3px solid var(--l2-border);
|
||||
padding: 0.1em 0 0.1em 0.8em;
|
||||
@@ -266,31 +270,43 @@
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
// No cell borders, alternate rows shaded, the label column brightest; the panel is MarkdownTable's.
|
||||
table {
|
||||
// As wide as its content, at least the panel: rows stay on one line and a wide table scrolls.
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
margin: 0 0 0.65em;
|
||||
width: 100%;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-variant-numeric: tabular-nums;
|
||||
word-break: normal;
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 5px 10px;
|
||||
border: 1px solid var(--l2-border);
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
background: var(--l2-background);
|
||||
color: var(--l1-foreground);
|
||||
font-weight: 600;
|
||||
padding-block: 13px;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
td {
|
||||
color: var(--l1-foreground);
|
||||
line-height: 20px;
|
||||
color: var(--l2-foreground);
|
||||
|
||||
&:first-child {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
tbody tr:nth-child(odd) td {
|
||||
background: var(--l1-background-hover);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,10 +16,12 @@ import ActionsSection from '../ActionsSection';
|
||||
import ActivityGroup, { ActivityItem } from '../ActivityGroup';
|
||||
import { RichCodeBlock } from '../blocks';
|
||||
import MarkdownExternalLink from '../MarkdownExternalLink/MarkdownExternalLink';
|
||||
import MarkdownTable from '../MarkdownTable/MarkdownTable';
|
||||
import { MessageContext } from '../MessageContext';
|
||||
import MessageFeedback from '../MessageFeedback';
|
||||
import UserMessageActions from '../UserMessageActions';
|
||||
|
||||
import AddedContexts from './AddedContexts';
|
||||
import styles from './MessageBubble.module.scss';
|
||||
|
||||
/**
|
||||
@@ -46,6 +48,7 @@ const MD_COMPONENTS = {
|
||||
code: RichCodeBlock,
|
||||
pre: SmartPre,
|
||||
a: MarkdownExternalLink,
|
||||
table: MarkdownTable,
|
||||
};
|
||||
|
||||
type RenderGroup =
|
||||
@@ -141,87 +144,97 @@ export default function MessageBubble({
|
||||
[styles.compact]: isCompact,
|
||||
},
|
||||
);
|
||||
const bodyClass = cx(styles.body, { [styles.compact]: isCompact });
|
||||
const bodyClass = cx(styles.body, {
|
||||
[styles.compact]: isCompact,
|
||||
[styles.fullPage]: variant === 'page',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={messageClass} data-testid={`ai-message-${message.id}`}>
|
||||
<div className={bodyClass}>
|
||||
<div className={styles.bubbleRow}>
|
||||
<div className={cx(styles.bubble, { [styles.error]: isError })}>
|
||||
{message.attachments && message.attachments.length > 0 && (
|
||||
<div className={styles.attachments}>
|
||||
{message.attachments.map((att) => {
|
||||
const isImage = att.type.startsWith('image/');
|
||||
return isImage ? (
|
||||
<img
|
||||
key={att.name}
|
||||
src={att.dataUrl}
|
||||
alt={att.name}
|
||||
className={styles.attachmentImage}
|
||||
/>
|
||||
) : (
|
||||
<div key={att.name} className={styles.attachmentFile}>
|
||||
{att.name}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<>
|
||||
<div
|
||||
className={messageClass}
|
||||
data-testid={`ai-message-${message.id}`}
|
||||
data-message-id={message.id}
|
||||
>
|
||||
<div className={bodyClass}>
|
||||
<div className={styles.bubbleRow}>
|
||||
<div className={cx(styles.bubble, { [styles.error]: isError })}>
|
||||
{message.attachments && message.attachments.length > 0 && (
|
||||
<div className={styles.attachments}>
|
||||
{message.attachments.map((att) => {
|
||||
const isImage = att.type.startsWith('image/');
|
||||
return isImage ? (
|
||||
<img
|
||||
key={att.name}
|
||||
src={att.dataUrl}
|
||||
alt={att.name}
|
||||
className={styles.attachmentImage}
|
||||
/>
|
||||
) : (
|
||||
<div key={att.name} className={styles.attachmentFile}>
|
||||
{att.name}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isUser ? (
|
||||
<p className={styles.text}>{message.content}</p>
|
||||
) : isError ? (
|
||||
<div className={styles.errorContent}>
|
||||
<TriangleAlert size={14} className={styles.errorIcon} />
|
||||
<span className={styles.errorText}>{message.content}</span>
|
||||
</div>
|
||||
) : hasBlocks ? (
|
||||
<MessageContext.Provider value={{ messageId: message.id }}>
|
||||
{groups.map((g) => renderGroup(g))}
|
||||
</MessageContext.Provider>
|
||||
) : (
|
||||
<MessageContext.Provider value={{ messageId: message.id }}>
|
||||
<ReactMarkdown
|
||||
className={styles.markdown}
|
||||
remarkPlugins={MD_PLUGINS}
|
||||
components={MD_COMPONENTS}
|
||||
>
|
||||
{message.content}
|
||||
</ReactMarkdown>
|
||||
</MessageContext.Provider>
|
||||
)}
|
||||
{isUser ? (
|
||||
<p className={styles.text}>{message.content}</p>
|
||||
) : isError ? (
|
||||
<div className={styles.errorContent}>
|
||||
<TriangleAlert size={14} className={styles.errorIcon} />
|
||||
<span className={styles.errorText}>{message.content}</span>
|
||||
</div>
|
||||
) : hasBlocks ? (
|
||||
<MessageContext.Provider value={{ messageId: message.id }}>
|
||||
{groups.map((g) => renderGroup(g))}
|
||||
</MessageContext.Provider>
|
||||
) : (
|
||||
<MessageContext.Provider value={{ messageId: message.id }}>
|
||||
<ReactMarkdown
|
||||
className={styles.markdown}
|
||||
remarkPlugins={MD_PLUGINS}
|
||||
components={MD_COMPONENTS}
|
||||
>
|
||||
{message.content}
|
||||
</ReactMarkdown>
|
||||
</MessageContext.Provider>
|
||||
)}
|
||||
|
||||
{!isUser && message.actions && message.actions.length > 0 && (
|
||||
<ActionsSection actions={message.actions} messageId={message.id} />
|
||||
)}
|
||||
{!isUser && message.actions && message.actions.length > 0 && (
|
||||
<ActionsSection actions={message.actions} messageId={message.id} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showRetry && (
|
||||
<div className={styles.retryButton}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
prefix={<RotateCw size={12} />}
|
||||
onClick={onRetry}
|
||||
testId={`ai-message-retry-${message.id}`}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isUser && !isError && !message.isRateLimitError && (
|
||||
<MessageFeedback
|
||||
message={message}
|
||||
onRegenerate={onRegenerate}
|
||||
isLastAssistant={isLastAssistant}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isUser && <UserMessageActions message={message} />}
|
||||
</div>
|
||||
|
||||
{showRetry && (
|
||||
<div className={styles.retryButton}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
prefix={<RotateCw size={12} />}
|
||||
onClick={onRetry}
|
||||
testId={`ai-message-retry-${message.id}`}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isUser && !isError && !message.isRateLimitError && (
|
||||
<MessageFeedback
|
||||
message={message}
|
||||
onRegenerate={onRegenerate}
|
||||
isLastAssistant={isLastAssistant}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isUser && <UserMessageActions message={message} />}
|
||||
</div>
|
||||
</div>
|
||||
{isUser && message.contexts && <AddedContexts contexts={message.contexts} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
.feedback {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: 8px;
|
||||
padding: 4px 2px 0;
|
||||
// Driven by MessageBubble's --feedback-opacity (0 normally, 1 on hover/visible).
|
||||
opacity: var(--feedback-opacity, 0);
|
||||
@@ -11,6 +11,11 @@
|
||||
--feedback-opacity: 1;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
// Lines the icons up with the full page's indented reply text.
|
||||
&.fullPage {
|
||||
padding-left: var(--spacing-4);
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { AIAssistantEvents } from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
import { FeedbackRating, Message } from '../../types';
|
||||
import { useVariant } from '../../VariantContext';
|
||||
|
||||
import styles from './MessageFeedback.module.scss';
|
||||
|
||||
@@ -72,6 +73,7 @@ export default function MessageFeedback({
|
||||
}: MessageFeedbackProps): JSX.Element {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [, copyToClipboard] = useCopyToClipboard();
|
||||
const isFullPage = useVariant() === 'page';
|
||||
const submitMessageFeedback = useAIAssistantStore(
|
||||
(s) => s.submitMessageFeedback,
|
||||
);
|
||||
@@ -172,7 +174,12 @@ export default function MessageFeedback({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={cx(styles.feedback, { [styles.visible]: isLastAssistant })}>
|
||||
<div
|
||||
className={cx(styles.feedback, {
|
||||
[styles.visible]: isLastAssistant,
|
||||
[styles.fullPage]: isFullPage,
|
||||
})}
|
||||
>
|
||||
<div className={styles.actions}>
|
||||
<Tooltip title={copied ? 'Copied!' : 'Copy'}>
|
||||
<Button
|
||||
@@ -183,7 +190,7 @@ export default function MessageFeedback({
|
||||
color="secondary"
|
||||
aria-label={copied ? 'Copied' : 'Copy message'}
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
@@ -198,7 +205,7 @@ export default function MessageFeedback({
|
||||
aria-label={VOTE_LABEL[FeedbackRatingDTO.positive].ariaLabel}
|
||||
aria-pressed={vote === FeedbackRatingDTO.positive}
|
||||
>
|
||||
<ThumbsUp size={12} />
|
||||
<ThumbsUp size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
@@ -213,26 +220,26 @@ export default function MessageFeedback({
|
||||
aria-label={VOTE_LABEL[FeedbackRatingDTO.negative].ariaLabel}
|
||||
aria-pressed={vote === FeedbackRatingDTO.negative}
|
||||
>
|
||||
<ThumbsDown size={12} />
|
||||
<ThumbsDown size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
{onRegenerate && (
|
||||
<Tooltip title="Regenerate">
|
||||
<Button
|
||||
size="sm"
|
||||
icon
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
onClick={onRegenerate}
|
||||
aria-label="Regenerate response"
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{onRegenerate && (
|
||||
<Tooltip title="Regenerate">
|
||||
<Button
|
||||
size="sm"
|
||||
icon
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
onClick={onRegenerate}
|
||||
aria-label="Regenerate response"
|
||||
>
|
||||
<RefreshCw size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
<span className={styles.time}>
|
||||
{relativeTime} · {absoluteTime}
|
||||
</span>
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
.streamingStatus {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 12px;
|
||||
font-style: italic;
|
||||
color: var(--l3-foreground);
|
||||
margin-bottom: 6px;
|
||||
// Sits where the run's first steps will land.
|
||||
.statusStep {
|
||||
padding: var(--spacing-2) 0;
|
||||
}
|
||||
|
||||
// Spans the reply column, so an approval or clarification card is as wide as the widest reply.
|
||||
.body {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.bubble {
|
||||
align-self: stretch;
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ import type {
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import { StreamingEventItem } from '../../types';
|
||||
import ActivityGroup, { ActivityItem } from '../ActivityGroup';
|
||||
import ActivityStep from '../ActivityStep/ActivityStep';
|
||||
import ApprovalCard from '../ApprovalCard';
|
||||
import { RichCodeBlock } from '../blocks';
|
||||
import MarkdownExternalLink from '../MarkdownExternalLink/MarkdownExternalLink';
|
||||
import MarkdownTable from '../MarkdownTable/MarkdownTable';
|
||||
import ClarificationForm from '../ClarificationForm';
|
||||
|
||||
import messageStyles from '../MessageBubble/MessageBubble.module.scss';
|
||||
@@ -35,6 +37,7 @@ const MD_COMPONENTS = {
|
||||
code: RichCodeBlock,
|
||||
pre: SmartPre,
|
||||
a: MarkdownExternalLink,
|
||||
table: MarkdownTable,
|
||||
};
|
||||
|
||||
type RenderGroup =
|
||||
@@ -52,11 +55,10 @@ type RenderGroup =
|
||||
* events stay standalone. The last group is flagged as trailing so the
|
||||
* caller can drive a "live" indicator on it.
|
||||
*
|
||||
* Invariant relied on by the ActivityGroup elapsed-time timer: once a
|
||||
* group exists at a given array index, later events only extend its
|
||||
* `items` — they never shrink the array or re-key existing groups. That
|
||||
* keeps each ActivityGroup React instance stable across re-renders so the
|
||||
* timer's `wasLive` → `isLive` re-stamp captures the right transition.
|
||||
* Invariant: once a group exists at a given array index, later events only
|
||||
* extend its `items` — they never shrink the array or re-key existing
|
||||
* groups. That keeps each ActivityGroup React instance stable across
|
||||
* re-renders, so a step's opened detail survives the events that follow.
|
||||
* The id fields below piggyback on that invariant: each event's position in
|
||||
* `events` is stable, so the derived id stays stable across re-renders.
|
||||
*/
|
||||
@@ -135,6 +137,11 @@ export default function StreamingMessage({
|
||||
const messageClass = cx(messageStyles.message, messageStyles.assistant, {
|
||||
[messageStyles.compact]: isCompact,
|
||||
});
|
||||
// Same frame as a finished reply, so nothing moves when the stream commits.
|
||||
const bodyClass = cx(messageStyles.body, styles.body, {
|
||||
[messageStyles.compact]: isCompact,
|
||||
[messageStyles.fullPage]: variant === 'page',
|
||||
});
|
||||
|
||||
// Recompute groups only when the events array identity changes. The
|
||||
// streaming reducer pushes new entries into the same array reference
|
||||
@@ -143,52 +150,53 @@ export default function StreamingMessage({
|
||||
|
||||
return (
|
||||
<div className={messageClass}>
|
||||
<div className={messageStyles.bubble}>
|
||||
{/* Pre-output indicator — only before any events arrive. */}
|
||||
{isEmpty && statusLabel && (
|
||||
<span className={styles.streamingStatus}>{statusLabel}</span>
|
||||
)}
|
||||
{isEmpty && !statusLabel && <TypingDots />}
|
||||
<div className={bodyClass}>
|
||||
<div className={cx(messageStyles.bubble, styles.bubble)}>
|
||||
{/* Pre-output indicator — only before any events arrive. */}
|
||||
{isEmpty && statusLabel && (
|
||||
<div className={styles.statusStep}>
|
||||
<ActivityStep title={statusLabel} isLive />
|
||||
</div>
|
||||
)}
|
||||
{isEmpty && !statusLabel && <TypingDots />}
|
||||
|
||||
{/* Runs of consecutive thinking + tool events collapse into a
|
||||
{/* Runs of consecutive thinking + tool events collapse into a
|
||||
single ActivityGroup; text events render inline between
|
||||
them. The trailing group is "live" while streaming is
|
||||
active and not blocked on the user. */}
|
||||
{groups.map((group) => {
|
||||
if (group.kind === 'text') {
|
||||
{groups.map((group) => {
|
||||
if (group.kind === 'text') {
|
||||
return (
|
||||
<ReactMarkdown
|
||||
key={group.id}
|
||||
className={messageStyles.markdown}
|
||||
remarkPlugins={MD_PLUGINS}
|
||||
components={MD_COMPONENTS}
|
||||
>
|
||||
{group.content}
|
||||
</ReactMarkdown>
|
||||
);
|
||||
}
|
||||
const groupIsLive = group.isTrailing && !isWaitingOnUser;
|
||||
return (
|
||||
<ReactMarkdown
|
||||
key={group.id}
|
||||
className={messageStyles.markdown}
|
||||
remarkPlugins={MD_PLUGINS}
|
||||
components={MD_COMPONENTS}
|
||||
>
|
||||
{group.content}
|
||||
</ReactMarkdown>
|
||||
<ActivityGroup key={group.id} items={group.items} isLive={groupIsLive} />
|
||||
);
|
||||
}
|
||||
const groupIsLive = group.isTrailing && !isWaitingOnUser;
|
||||
return (
|
||||
<ActivityGroup key={group.id} items={group.items} isLive={groupIsLive} />
|
||||
);
|
||||
})}
|
||||
})}
|
||||
|
||||
{/* While events are still streaming, append the typing dots so the
|
||||
user has a clear "more is coming" signal. Hidden when the agent
|
||||
is waiting on the user's input (an approval or clarification
|
||||
card already conveys that state). */}
|
||||
{!isEmpty && !isWaitingOnUser && <TypingDots />}
|
||||
|
||||
{/* Approval / clarification cards appended after any streamed text */}
|
||||
{pendingApproval && (
|
||||
<ApprovalCard conversationId={conversationId} approval={pendingApproval} />
|
||||
)}
|
||||
{pendingClarification && (
|
||||
<ClarificationForm
|
||||
conversationId={conversationId}
|
||||
clarification={pendingClarification}
|
||||
/>
|
||||
)}
|
||||
{/* Approval / clarification cards appended after any streamed text */}
|
||||
{pendingApproval && (
|
||||
<ApprovalCard
|
||||
conversationId={conversationId}
|
||||
approval={pendingApproval}
|
||||
/>
|
||||
)}
|
||||
{pendingClarification && (
|
||||
<ClarificationForm
|
||||
conversationId={conversationId}
|
||||
clarification={pendingClarification}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
// Minimal expandable row — chevron + label, no icon, no left rail.
|
||||
// Matches the tool-call row treatment so consecutive thinking + tool
|
||||
// activity reads as one quiet "what the agent did" log.
|
||||
.row {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 4px 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--l3-foreground);
|
||||
transition: color 0.12s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.chevron {
|
||||
flex-shrink: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.body {
|
||||
padding: 4px 0 4px 22px;
|
||||
}
|
||||
|
||||
.content {
|
||||
font-size: 12px;
|
||||
color: var(--l3-foreground);
|
||||
font-style: italic;
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.5;
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { ChevronDown, ChevronRight } from '@signozhq/icons';
|
||||
|
||||
import styles from './ThinkingStep.module.scss';
|
||||
import ActivityStep from '../ActivityStep/ActivityStep';
|
||||
|
||||
interface ThinkingStepProps {
|
||||
content: string;
|
||||
@@ -13,40 +10,18 @@ interface ThinkingStepProps {
|
||||
isLive?: boolean;
|
||||
}
|
||||
|
||||
/** Body of a thinking step — extracted so ActivityGroup can render it directly. */
|
||||
export function ThinkingContent({ content }: { content: string }): JSX.Element {
|
||||
return (
|
||||
<div className={styles.body}>
|
||||
<p className={styles.content}>{content}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function thinkingLabel(isLive: boolean): string {
|
||||
return isLive ? 'Thinking…' : 'Thought for a few seconds';
|
||||
}
|
||||
|
||||
/** Collapsible thinking row — chevron + label, content in the expanded body. */
|
||||
/** A thinking pass on the activity timeline, with what the agent thought as its detail. */
|
||||
export default function ThinkingStep({
|
||||
content,
|
||||
isLive = false,
|
||||
}: ThinkingStepProps): JSX.Element {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const toggle = (): void => setExpanded((v) => !v);
|
||||
|
||||
return (
|
||||
<div className={styles.row}>
|
||||
<div className={styles.header} onClick={toggle}>
|
||||
{expanded ? (
|
||||
<ChevronDown size={12} className={styles.chevron} />
|
||||
) : (
|
||||
<ChevronRight size={12} className={styles.chevron} />
|
||||
)}
|
||||
<span className={styles.label}>{thinkingLabel(isLive)}</span>
|
||||
</div>
|
||||
|
||||
{expanded && <ThinkingContent content={content} />}
|
||||
</div>
|
||||
<ActivityStep title={thinkingLabel(isLive)} isLive={isLive}>
|
||||
{content.trim()}
|
||||
</ActivityStep>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,61 +1,5 @@
|
||||
// Minimal expandable row — chevron + label, no icon, no left rail.
|
||||
// While the tool is running we swap the chevron for a spinner in the
|
||||
// same slot so the row alignment doesn't shift when it completes.
|
||||
.row {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
|
||||
&.running {
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 4px 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--l3-foreground);
|
||||
user-select: none;
|
||||
transition: color 0.12s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.chevron {
|
||||
flex-shrink: 0;
|
||||
color: inherit;
|
||||
|
||||
&.spin {
|
||||
color: var(--accent-primary);
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: 400;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.body {
|
||||
padding: 4px 0 4px 22px;
|
||||
padding: 4px 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { ChevronDown, ChevronRight, LoaderCircle } from '@signozhq/icons';
|
||||
|
||||
import { StreamingToolCall } from '../../types';
|
||||
import ActivityStep from '../ActivityStep/ActivityStep';
|
||||
|
||||
import styles from './ToolCallStep.module.scss';
|
||||
|
||||
interface ToolCallStepProps {
|
||||
toolCall: StreamingToolCall;
|
||||
/** Still the newest step of a running reply, even once its own call is done. */
|
||||
isLive?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,7 +27,7 @@ export function getToolDisplayLabel(toolCall: StreamingToolCall): string {
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
/** Body of a tool-call step — extracted so ActivityGroup can render it directly. */
|
||||
/** The input and output of a tool call. */
|
||||
export function ToolCallContent({
|
||||
toolCall,
|
||||
}: {
|
||||
@@ -55,30 +56,21 @@ export function ToolCallContent({
|
||||
);
|
||||
}
|
||||
|
||||
/** Collapsible tool-call row — chevron + label, in/out detail in the body. */
|
||||
/** A tool call on the activity timeline; its input and output open from the title. */
|
||||
export default function ToolCallStep({
|
||||
toolCall,
|
||||
isLive = false,
|
||||
}: ToolCallStepProps): JSX.Element {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const { done } = toolCall;
|
||||
const label = getToolDisplayLabel(toolCall);
|
||||
|
||||
const toggle = (): void => setExpanded((v) => !v);
|
||||
|
||||
return (
|
||||
<div className={cx(styles.row, { [styles.running]: !done })}>
|
||||
<div className={styles.header} onClick={toggle}>
|
||||
{!done ? (
|
||||
<LoaderCircle size={12} className={cx(styles.chevron, styles.spin)} />
|
||||
) : expanded ? (
|
||||
<ChevronDown size={12} className={styles.chevron} />
|
||||
) : (
|
||||
<ChevronRight size={12} className={styles.chevron} />
|
||||
)}
|
||||
<span className={styles.label}>{label}</span>
|
||||
</div>
|
||||
|
||||
<ActivityStep
|
||||
title={getToolDisplayLabel(toolCall)}
|
||||
isLive={isLive || !toolCall.done}
|
||||
expanded={expanded}
|
||||
onToggle={(): void => setExpanded((v) => !v)}
|
||||
>
|
||||
{expanded && <ToolCallContent toolCall={toolCall} />}
|
||||
</div>
|
||||
</ActivityStep>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ export default function UserMessageActions({
|
||||
onClick={handleCopy}
|
||||
aria-label={copied ? 'Copied' : 'Copy message'}
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
@use '../../../_scrollbar' as *;
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--spacing-6);
|
||||
overflow-y: auto;
|
||||
@include scrollbar;
|
||||
|
||||
// Matches the dot grid's share of the height, so the content stays centred.
|
||||
&::after {
|
||||
content: '';
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
// The panel sits it above the input, clear of the Noz peeking over its corner.
|
||||
&.compact {
|
||||
padding-right: var(--spacing-24);
|
||||
|
||||
&::after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fills the empty space above the content, edge to edge.
|
||||
.dotGrid {
|
||||
display: block;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
margin: calc(-1 * var(--spacing-6)) calc(-1 * var(--spacing-6))
|
||||
var(--spacing-6);
|
||||
|
||||
.compact & {
|
||||
margin-right: calc(-1 * var(--spacing-24));
|
||||
}
|
||||
}
|
||||
|
||||
.emptyContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-10);
|
||||
max-width: 336px;
|
||||
// Auto margins centre it without clipping the top when it outgrows the view.
|
||||
margin: auto;
|
||||
|
||||
.compact & {
|
||||
margin: auto 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
.emptyIntro {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-5);
|
||||
}
|
||||
|
||||
.emptyHeading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.emptyTitle {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-large);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.emptySubtitle {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.suggestions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--spacing-4);
|
||||
--button-height: auto;
|
||||
--button-padding: var(--spacing-3) var(--spacing-5);
|
||||
--button-border-radius: 8px;
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-size-line-height: 20px;
|
||||
--button-white-space: normal;
|
||||
--button-label-white-space: normal;
|
||||
--button-variant-ghost-background-color: var(--l3-background-60);
|
||||
--button-variant-ghost-color: var(--l2-foreground);
|
||||
--button-variant-ghost-hover-background-color: var(--l3-background);
|
||||
--button-variant-ghost-hover-color: var(--l1-foreground);
|
||||
|
||||
// Buttons don't inherit the page font, and long prompts wrap from the left.
|
||||
> [data-slot='button'] {
|
||||
font-family: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
|
||||
// The same box as a chip; the prompt inside is invisible and only sets the size.
|
||||
.suggestionSkeleton {
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
padding: var(--spacing-3) var(--spacing-5);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: transparent;
|
||||
user-select: none;
|
||||
|
||||
// Nested so it outranks the skeleton's own `position: relative`.
|
||||
.suggestionSkeletonFill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
--skeleton-background: var(--l3-background-60);
|
||||
--skeleton-shimmer-color: color-mix(
|
||||
in srgb,
|
||||
var(--l2-foreground),
|
||||
transparent 92%
|
||||
);
|
||||
--skeleton-input-height: 100%;
|
||||
--skeleton-input-border-radius: 8px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import cx from 'classnames';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Skeleton } from '@signozhq/ui/skeleton';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
import { AIAssistantEvents, SuggestedPromptCategory } from '../../../events';
|
||||
import { useVariant } from '../../../VariantContext';
|
||||
import DotGrid from '../../DotGrid/DotGrid';
|
||||
import { EMPTY_STATE_CHIPS_FALLBACK } from '../emptyStateChipsFallback';
|
||||
import { useEmptyStateChips } from '../useEmptyStateChips';
|
||||
|
||||
import styles from './EmptyState.module.scss';
|
||||
|
||||
interface EmptyStateProps {
|
||||
onSendSuggestedPrompt: (text: string) => void;
|
||||
/** Fading out after the first send; shows the cached prompts without fetching. */
|
||||
isLeaving?: boolean;
|
||||
}
|
||||
|
||||
/** A new chat: the dot grid, Noz's intro and the suggested prompts. */
|
||||
export default function EmptyState({
|
||||
onSendSuggestedPrompt,
|
||||
isLeaving = false,
|
||||
}: EmptyStateProps): JSX.Element {
|
||||
const isCompact = useVariant() === 'panel';
|
||||
const { chips: emptyStateChips, isLoading: areChipsLoading } =
|
||||
useEmptyStateChips(!isLeaving);
|
||||
// Fading out before the prompts arrived: keep the placeholders that were showing.
|
||||
const showsSkeletons =
|
||||
areChipsLoading || (isLeaving && emptyStateChips.length === 0);
|
||||
|
||||
return (
|
||||
<div className={cx(styles.empty, { [styles.compact]: isCompact })}>
|
||||
<DotGrid className={styles.dotGrid} />
|
||||
<div className={styles.emptyContent}>
|
||||
<div className={styles.emptyIntro}>
|
||||
<div className={styles.emptyHeading}>
|
||||
<h3 className={styles.emptyTitle}>Noz</h3>
|
||||
<Badge color="secondary" variant="outlined">
|
||||
beta
|
||||
</Badge>
|
||||
</div>
|
||||
<p className={styles.emptySubtitle}>
|
||||
I can help you understand and be the all-seeing eye over your entire
|
||||
infrastructure. What do you need?
|
||||
</p>
|
||||
</div>
|
||||
<div className={styles.suggestions} aria-busy={areChipsLoading}>
|
||||
{/* As many as the backend sends, each the width of a real prompt. */}
|
||||
{showsSkeletons &&
|
||||
EMPTY_STATE_CHIPS_FALLBACK.map((chip) => (
|
||||
<span
|
||||
key={chip.id}
|
||||
className={styles.suggestionSkeleton}
|
||||
data-testid="empty-state-chip-skeleton"
|
||||
aria-hidden
|
||||
>
|
||||
<Skeleton.Input
|
||||
active
|
||||
block
|
||||
className={styles.suggestionSkeletonFill}
|
||||
/>
|
||||
{chip.text}
|
||||
</span>
|
||||
))}
|
||||
{emptyStateChips.map((chip) => (
|
||||
<Button
|
||||
key={chip.id}
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="md"
|
||||
onClick={(): void => {
|
||||
void logEvent(AIAssistantEvents.SuggestedPromptClicked, {
|
||||
promptId: chip.id,
|
||||
category: SuggestedPromptCategory.EmptyState,
|
||||
});
|
||||
onSendSuggestedPrompt(chip.text);
|
||||
}}
|
||||
testId={`empty-state-chip-${chip.id}`}
|
||||
>
|
||||
{chip.text}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,64 +15,57 @@
|
||||
}
|
||||
}
|
||||
|
||||
.empty {
|
||||
// The full page keeps the thread in a 672px column; the extra 32px is the rows' own gutters.
|
||||
.row.fullPage {
|
||||
max-width: 704px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
// The list, and right after the first send the empty state fading out over it.
|
||||
.thread {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 32px 24px;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
// Floats over the foot of the thread while there is more below.
|
||||
.latest {
|
||||
position: absolute;
|
||||
bottom: var(--spacing-6);
|
||||
left: 50%;
|
||||
z-index: 1;
|
||||
transform: translateX(-50%);
|
||||
border-radius: 9999px;
|
||||
box-shadow: var(--shadow-dropdown);
|
||||
--button-height: 32px;
|
||||
--button-padding: 0 var(--spacing-6);
|
||||
--button-border-radius: 9999px;
|
||||
--button-font-size: var(--periscope-font-size-base);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-secondary-background-color: var(--l3-background);
|
||||
--button-secondary-hover-background-color: var(--l3-background-hover);
|
||||
--button-secondary-solid-foreground: var(--l1-foreground);
|
||||
|
||||
.emptyTitle {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--l1-foreground);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.emptySubtitle {
|
||||
font-size: 13px;
|
||||
color: var(--l3-foreground);
|
||||
margin: 0 0 12px;
|
||||
max-width: 320px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.suggestions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
width: 100%;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
color: var(--l2-foreground);
|
||||
font-size: 12.5px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
border-color 0.15s ease,
|
||||
color 0.15s ease;
|
||||
line-height: 1.35;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
&:hover {
|
||||
background: var(--l2-background);
|
||||
border-color: var(--l3-border);
|
||||
color: var(--l1-foreground);
|
||||
// Buttons don't inherit the page font; the outline keeps it apart from code blocks behind it.
|
||||
> [data-slot='button'] {
|
||||
border: 1px solid var(--l3-border);
|
||||
font-family: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.emptyStateExit {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
pointer-events: none;
|
||||
animation: emptyStateExit ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes emptyStateExit {
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user