Compare commits

..

1 Commits

Author SHA1 Message Date
nityanandagohain
2df97d39e2 feat(trace-details): add the API contract for the trace inspect endpoint
Adds GET /api/v1/traces/{traceID}/inspect to the API spec with its query
  parameters and response types. The handler answers 501 for now; the
  implementation follows in separate PRs (overview, open a span, search).

  The response holds one of three parts, named by :
  - overview: identity, errors, failures not marked as errors, slowest spans,
    most expensive spans, span links and the tree
  - span: one span's summary and full record, with its ancestors and descendants
  - find: the spans matching a search, or every span with allSpans

  Every list has total, items and nextCursor, and every item starts with the
  span and its direct parent.

  Refs SigNoz/nerve-pod#651
2026-11-19 16:42:40 +05:30
378 changed files with 4762 additions and 15804 deletions

View File

@@ -86,7 +86,7 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
zeus.Config{},
noopzeus.NewProviderFactory(),
licensing.Config{},
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics, _ cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return nooplicensing.NewFactory()
},
func(_ zeus.Zeus, _ licensing.Licensing) subscription.Subscription {

View File

@@ -103,8 +103,8 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
enterprisezeus.Config(),
httpzeus.NewProviderFactory(),
enterpriselicensing.Config(24*time.Hour, 3),
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics, cache)
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics)
},
func(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
return httpsubscription.New(zeus, licensing)

View File

@@ -261,8 +261,8 @@ alertmanager:
nflog:
# Interval between garbage collection and snapshotting of the notification logs. The snapshot will be stored in the state store.
maintenance_interval: 15m
# Retention of the notification logs. Must be at least twice the longest repeat interval, which is 8760h for rules with re-notify off.
retention: 17520h
# Retention of the notification logs.
retention: 120h
##################### Emailing #####################
emailing:

View File

@@ -4420,8 +4420,7 @@ components:
description: The dashboard title and description.
duration:
description: The default time range, as a Prometheus duration such as 1h
or 7d. The UI opens the dashboard on it, rounded up to whole minutes,
when neither the URL nor the viewer's last pick sets a time range.
or 7d. Stored, but not applied by the UI.
type: string
layouts:
description: The Grid layouts that place panels, at most 500. Each panel
@@ -12681,6 +12680,19 @@ components:
minimum: 0
type: integer
type: object
SpantypesEventV2:
properties:
attributes:
additionalProperties: {}
type: object
isError:
type: boolean
name:
type: string
timeUnixNano:
minimum: 0
type: integer
type: object
SpantypesFieldContext:
enum:
- attribute
@@ -12793,6 +12805,19 @@ components:
required:
- aggregations
type: object
SpantypesGettableTraceInspection:
properties:
find:
$ref: '#/components/schemas/SpantypesTraceSpanList'
overview:
$ref: '#/components/schemas/SpantypesTraceOverview'
span:
$ref: '#/components/schemas/SpantypesTraceSpanDetail'
type:
$ref: '#/components/schemas/SpantypesInspectType'
required:
- type
type: object
SpantypesGettableTraceSummary:
properties:
ai:
@@ -12873,6 +12898,19 @@ components:
nullable: true
type: array
type: object
SpantypesInspectType:
enum:
- overview
- span
- find
type: string
SpantypesLink:
properties:
spanId:
type: string
traceId:
type: string
type: object
SpantypesOtelSpanRef:
properties:
refType:
@@ -13164,6 +13202,100 @@ components:
nullable: true
type: object
type: object
SpantypesSpanRecord:
properties:
attributes:
additionalProperties: {}
type: object
events:
items:
$ref: '#/components/schemas/SpantypesEventV2'
type: array
links:
items:
$ref: '#/components/schemas/SpantypesLink'
type: array
resource:
additionalProperties:
type: string
type: object
spanId:
type: string
statusCode:
type: string
statusMessage:
type: string
truncated:
items:
$ref: '#/components/schemas/SpantypesTruncatedField'
type: array
required:
- spanId
- statusCode
- statusMessage
- attributes
- resource
- events
- links
- truncated
type: object
SpantypesSpanSummary:
properties:
childCount:
minimum: 0
type: integer
durationNano:
minimum: 0
type: integer
hasError:
type: boolean
kind:
type: string
level:
minimum: 0
type: integer
name:
type: string
ownTimeNano:
minimum: 0
type: integer
parentSpanId:
type: string
responseStatusCode:
type: string
serviceName:
type: string
spanId:
type: string
startOffsetNano:
minimum: 0
type: integer
subtreeSpanCount:
minimum: 0
type: integer
required:
- spanId
- name
- serviceName
- kind
- startOffsetNano
- durationNano
- ownTimeNano
- hasError
- level
- childCount
- subtreeSpanCount
type: object
SpantypesSpanTextMatch:
properties:
field:
type: string
snippet:
type: string
required:
- field
- snippet
type: object
SpantypesThreadSpan:
properties:
attributes:
@@ -13230,6 +13362,23 @@ components:
- formattedOutput
- formatterWarnings
type: object
SpantypesTraceAIIdentity:
properties:
modelCallCount:
minimum: 0
type: integer
tokens:
$ref: '#/components/schemas/SpantypesTraceAITokens'
toolCallCount:
minimum: 0
type: integer
totalCost:
type: number
required:
- modelCallCount
- toolCallCount
- tokens
type: object
SpantypesTraceAISummary:
properties:
tokens:
@@ -13263,6 +13412,382 @@ components:
- cacheWrite
- reasoning
type: object
SpantypesTraceErrorItem:
properties:
errorAncestorCount:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
statusMessage:
type: string
required:
- span
- statusMessage
- errorAncestorCount
type: object
SpantypesTraceErrorList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceErrorItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceExpensiveItem:
properties:
cost:
type: number
inputTokens:
minimum: 0
type: integer
outputTokens:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- inputTokens
- outputTokens
type: object
SpantypesTraceExpensiveList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceExpensiveItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceIdentity:
properties:
ai:
$ref: '#/components/schemas/SpantypesTraceAIIdentity'
durationNano:
minimum: 0
type: integer
errorSpanCount:
minimum: 0
type: integer
hasMissingSpans:
type: boolean
root:
$ref: '#/components/schemas/SpantypesSpanSummary'
rootCount:
minimum: 0
type: integer
serviceCount:
minimum: 0
type: integer
services:
items:
$ref: '#/components/schemas/SpantypesTraceServiceStats'
type: array
spanCount:
minimum: 0
type: integer
startTimestampMillis:
minimum: 0
type: integer
traceId:
type: string
truncated:
type: boolean
required:
- traceId
- startTimestampMillis
- durationNano
- spanCount
- errorSpanCount
- rootCount
- hasMissingSpans
- truncated
- serviceCount
- services
type: object
SpantypesTraceLinkItem:
properties:
linkCount:
minimum: 0
type: integer
links:
items:
$ref: '#/components/schemas/SpantypesLink'
type: array
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- linkCount
- links
type: object
SpantypesTraceLinkList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceLinkItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceOverview:
properties:
errors:
$ref: '#/components/schemas/SpantypesTraceErrorList'
expensive:
$ref: '#/components/schemas/SpantypesTraceExpensiveList'
identity:
$ref: '#/components/schemas/SpantypesTraceIdentity'
links:
$ref: '#/components/schemas/SpantypesTraceLinkList'
slowest:
$ref: '#/components/schemas/SpantypesTraceSlowestList'
tree:
$ref: '#/components/schemas/SpantypesTraceTree'
unmarkedFailures:
$ref: '#/components/schemas/SpantypesTraceUnmarkedFailureList'
type: object
SpantypesTraceServiceStats:
properties:
errorSpanCount:
minimum: 0
type: integer
ownTimeNano:
minimum: 0
type: integer
serviceName:
type: string
spanCount:
minimum: 0
type: integer
required:
- serviceName
- spanCount
- errorSpanCount
- ownTimeNano
type: object
SpantypesTraceSlowestItem:
properties:
errorSpanCount:
minimum: 0
type: integer
ownTimeNano:
minimum: 0
type: integer
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
spanCount:
minimum: 0
type: integer
required:
- span
- spanCount
- ownTimeNano
- errorSpanCount
type: object
SpantypesTraceSlowestList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceSlowestItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceSpanDetail:
properties:
ancestorCount:
minimum: 0
type: integer
ancestors:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
descendants:
items:
$ref: '#/components/schemas/SpantypesTraceSpanLevel'
type: array
percentile:
$ref: '#/components/schemas/SpantypesTraceSpanPercentile'
record:
$ref: '#/components/schemas/SpantypesSpanRecord'
summary:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- summary
- record
- ancestors
- ancestorCount
- descendants
type: object
SpantypesTraceSpanLevel:
properties:
level:
minimum: 0
type: integer
spans:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
total:
minimum: 0
type: integer
required:
- level
- total
- spans
type: object
SpantypesTraceSpanList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceSpanMatch'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTraceSpanMatch:
properties:
matches:
items:
$ref: '#/components/schemas/SpantypesSpanTextMatch'
type: array
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- matches
type: object
SpantypesTraceSpanPercentile:
properties:
p50Nano:
minimum: 0
type: integer
p90Nano:
minimum: 0
type: integer
p99Nano:
minimum: 0
type: integer
position:
format: double
type: number
windowMinutes:
minimum: 0
type: integer
required:
- p50Nano
- p90Nano
- p99Nano
- position
- windowMinutes
type: object
SpantypesTraceTree:
properties:
complete:
type: boolean
records:
items:
$ref: '#/components/schemas/SpantypesSpanRecord'
type: array
spans:
items:
$ref: '#/components/schemas/SpantypesSpanSummary'
type: array
total:
minimum: 0
type: integer
required:
- total
- complete
- spans
type: object
SpantypesTraceUnmarkedFailureItem:
properties:
parent:
$ref: '#/components/schemas/SpantypesSpanSummary'
reason:
$ref: '#/components/schemas/SpantypesUnmarkedFailureReason'
span:
$ref: '#/components/schemas/SpantypesSpanSummary'
required:
- span
- reason
type: object
SpantypesTraceUnmarkedFailureList:
properties:
items:
items:
$ref: '#/components/schemas/SpantypesTraceUnmarkedFailureItem'
type: array
nextCursor:
type: string
total:
minimum: 0
type: integer
required:
- total
- items
type: object
SpantypesTruncatedField:
properties:
field:
type: string
length:
minimum: 0
type: integer
required:
- field
- length
type: object
SpantypesUnmarkedFailureReason:
enum:
- http_4xx
- grpc_status
- exception_event
type: string
SpantypesUpdatableSpanMapper:
properties:
config:
@@ -19285,6 +19810,149 @@ paths:
tags:
- tracedetail
x-signoz-stability: alpha
/api/v1/traces/{traceID}/inspect:
get:
deprecated: false
description: 'Returns one of three parts of a trace of any size, named by type,
each within 50,000 characters. Without spanId or search it returns the overview:
the trace''s identity with per-service totals, the spans where each error
started, the failures not marked as errors (a 4xx response, a gRPC status
other than OK, an exception event), the slowest spans by own time with same-name
spans under one parent taken together, the most expensive gen_ai spans, and
the span tree. A trace of up to 100 spans returns every span in the tree,
and a small one also each span''s full record; a larger trace returns the
top levels. With spanId it returns that span''s summary and full record, its
ancestors, and the spans below it level by level, at most 20 per level; values
over 500 characters are cut and listed in truncated. With search it returns
the matching spans, each with where the words were found; allSpans returns
every span instead. Every list carries its total, and every list item the
span''s direct parent. Pass a nextCursor as cursor with the same parameters
to get the next page.'
operationId: InspectTrace
parameters:
- description: Returns this span in full with the spans around it. Cannot be
combined with search.
in: query
name: spanId
schema:
description: Returns this span in full with the spans around it. Cannot
be combined with search.
type: string
- description: 'Returns the spans that match, earliest first: words, a filter
expression, or both, such as worldpay AND has_error = true. Words match
the span name, status message, attribute values and events, ignoring case.'
in: query
name: search
schema:
description: 'Returns the spans that match, earliest first: words, a filter
expression, or both, such as worldpay AND has_error = true. Words match
the span name, status message, attribute values and events, ignoring case.'
type: string
- description: With spanId, the number of levels of ancestors and of descendants
returned, 1 to 10; 2 when not given. The root span is always returned.
in: query
name: depth
schema:
description: With spanId, the number of levels of ancestors and of descendants
returned, 1 to 10; 2 when not given. The root span is always returned.
type: integer
- description: 'Returns a different response: every span of the trace as a short
line, in tree order, or with spanId that span and every span below it. Cannot
be combined with search or depth.'
in: query
name: allSpans
schema:
description: 'Returns a different response: every span of the trace as a
short line, in tree order, or with spanId that span and every span below
it. Cannot be combined with search or depth.'
type: boolean
- description: With spanId, attribute names returned without the 500 character
cut; the record then holds only these attributes.
in: query
name: selectFields
schema:
description: With spanId, attribute names returned without the 500 character
cut; the record then holds only these attributes.
items:
type: string
type: array
- description: Page size for search and for allSpans, at most 1000; when not
given, 20 with search and 400 with allSpans. A page holds fewer spans when
it would pass the 50,000 character limit.
in: query
name: limit
schema:
description: Page size for search and for allSpans, at most 1000; when not
given, 20 with search and 400 with allSpans. A page holds fewer spans
when it would pass the 50,000 character limit.
type: integer
- description: The nextCursor of an earlier response to the same request; returns
the next page.
in: query
name: cursor
schema:
description: The nextCursor of an earlier response to the same request;
returns the next page.
type: string
- in: path
name: traceID
required: true
schema:
type: string
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/SpantypesGettableTraceInspection'
status:
type: string
required:
- status
- data
type: object
description: OK
"400":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Bad Request
"401":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Unauthorized
"403":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Internal Server Error
security:
- api_key:
- VIEWER
- tokenizer:
- VIEWER
summary: Inspect a trace
tags:
- tracedetail
x-signoz-stability: alpha
/api/v1/traces/{traceID}/summary:
get:
deprecated: false

View File

@@ -1,26 +0,0 @@
package httplicensing
import (
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
)
const (
activeLicenseCacheKey string = "active_license"
activeLicenseCacheTTL time.Duration = 5 * time.Minute
)
// A nil License means the organization has no active license.
type cachedActiveLicense struct {
License *licensetypes.License
}
func (typ cachedActiveLicense) MarshalBinary() ([]byte, error) {
return json.Marshal(typ)
}
func (typ *cachedActiveLicense) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, typ)
}

View File

@@ -7,7 +7,6 @@ import (
"github.com/SigNoz/signoz/ee/licensing/licensingstore/sqllicensingstore"
"github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
@@ -26,17 +25,16 @@ type provider struct {
settings factory.ScopedProviderSettings
orgGetter organization.Getter
analytics analytics.Analytics
cache cache.Cache
stopChan chan struct{}
}
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return factory.NewProviderFactory(factory.MustNewName("http"), func(ctx context.Context, providerSettings factory.ProviderSettings, config licensing.Config) (licensing.Licensing, error) {
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics, cache)
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics)
})
}
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) (licensing.Licensing, error) {
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) (licensing.Licensing, error) {
settings := factory.NewScopedProviderSettings(ps, "github.com/SigNoz/signoz/ee/licensing/httplicensing")
licensestore := sqllicensingstore.New(sqlstore)
return &provider{
@@ -47,7 +45,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Conf
orgGetter: orgGetter,
stopChan: make(chan struct{}),
analytics: analytics,
cache: cache,
}, nil
}
@@ -112,7 +109,6 @@ func (provider *provider) Activate(ctx context.Context, organizationID valuer.UU
return nil, err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return license, nil
}
@@ -154,38 +150,25 @@ func (provider *provider) Delete(ctx context.Context, organizationID valuer.UUID
return errors.WithAdditionalf(err, "license %s cannot be deleted", licenseID.StringValue())
}
if err := provider.store.Delete(ctx, organizationID, licenseID); err != nil {
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
return provider.store.Delete(ctx, organizationID, licenseID)
}
// Caches both an active license and no active license, but never a store error.
func (provider *provider) GetActive(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
if cached, ok := provider.getActiveFromCache(ctx, organizationID); ok {
if cached.License == nil {
return nil, licensetypes.ErrActiveLicenseNotFound(organizationID)
}
return cached.License, nil
}
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
if err != nil && !errors.Ast(err, errors.TypeNotFound) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
if cacheErr := provider.cache.Set(ctx, organizationID, activeLicenseCacheKey, &cachedActiveLicense{License: activeLicense}, activeLicenseCacheTTL); cacheErr != nil {
provider.settings.Logger().WarnContext(ctx, "failed to write active license to cache", errors.Attr(cacheErr), slog.String("org_id", organizationID.StringValue()))
activeLicense, err := licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
if err != nil {
return nil, err
}
return activeLicense, err
return activeLicense, nil
}
func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUID) error {
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
activeLicense, err := provider.GetActive(ctx, organizationID)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
return nil
@@ -204,7 +187,6 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
}
return err
@@ -221,8 +203,6 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
stats := licensetypes.NewStatsFromLicense(activeLicense)
provider.analytics.Send(ctx,
analyticstypes.Track{
@@ -269,30 +249,3 @@ func (provider *provider) Collect(ctx context.Context, orgID valuer.UUID) (map[s
return licensetypes.NewStatsFromLicense(activeLicense), nil
}
func (provider *provider) getActiveFromCache(ctx context.Context, organizationID valuer.UUID) (*cachedActiveLicense, bool) {
cached := new(cachedActiveLicense)
err := provider.cache.Get(ctx, organizationID, activeLicenseCacheKey, cached)
if err != nil {
if !errors.Ast(err, errors.TypeNotFound) {
provider.settings.Logger().WarnContext(ctx, "failed to read active license from cache", errors.Attr(err), slog.String("org_id", organizationID.StringValue()))
}
return nil, false
}
if cached.License != nil && cached.License.IsExpired() {
return nil, false
}
return cached, true
}
func (provider *provider) getActiveFromStore(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
return licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
}

View File

@@ -1,214 +0,0 @@
package httplicensing
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/analytics/analyticstest"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/cache/cachetest"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/SigNoz/signoz/pkg/zeus"
"github.com/SigNoz/signoz/pkg/zeus/noopzeus"
)
var (
testOrganizationID = valuer.MustNewUUID("0196f794-ff30-7bee-a5f4-ef5ad315715e")
testLicenseID = valuer.MustNewUUID("0196360e-90cd-7a74-8313-1aa815ce2a67")
licenseColumns = []string{"id", "created_at", "updated_at", "key", "data", "last_validated_at", "org_id"}
)
const (
selectLicensesQuery = `SELECT (.+) FROM "license"`
updateLicenseQuery = `UPDATE "license"`
deleteLicenseQuery = `DELETE FROM "license"`
)
func newTestLicensing(t *testing.T) (licensing.Licensing, sqlmock.Sqlmock, cache.Cache) {
t.Helper()
sqlStore := sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherRegexp)
licenseCache, err := cachetest.New(cache.Config{Provider: "memory", Memory: cache.Memory{NumCounters: 1000, MaxCost: 1 << 20}})
require.NoError(t, err)
providerSettings := instrumentationtest.New().ToProviderSettings()
noopZeus, err := noopzeus.New(context.Background(), providerSettings, zeus.Config{})
require.NoError(t, err)
licensing, err := New(context.Background(), providerSettings, licensing.Config{PollInterval: time.Hour, FailureThreshold: 3}, sqlStore, noopZeus, nil, analyticstest.New(), licenseCache)
require.NoError(t, err)
return licensing, sqlStore.Mock(), licenseCache
}
func newLicenseRows(lastValidatedAt time.Time) *sqlmock.Rows {
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
data := `{"status":"VALID","state":"EVALUATING","platform":"SELF_HOSTED","plan":{"name":"ENTERPRISE"},"valid_from":1732146923,"valid_until":-1,"features":[],"event_queue":{}}`
return sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", data, lastValidatedAt, testOrganizationID.StringValue())
}
func TestGetActiveServesRepeatReadsFromCache(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
fromStore, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
fromCache, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, licensetypes.NewGettableLicenseWithKey(fromStore), licensetypes.NewGettableLicenseWithKey(fromCache))
assert.Equal(t, fromStore.OrganizationID, fromCache.OrganizationID)
assert.True(t, fromStore.LastValidatedAt.Equal(fromCache.LastValidatedAt))
fromStoreData, err := json.Marshal(fromStore.Data)
require.NoError(t, err)
fromCacheData, err := json.Marshal(fromCache.Data)
require.NoError(t, err)
assert.JSONEq(t, string(fromStoreData), string(fromCacheData))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveCachesNoActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
for range 2 {
license, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
assert.Nil(t, license)
}
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveDoesNotCacheErrors(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
licenseRowWithoutStatus := sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", `{"plan":{"name":"ENTERPRISE"}}`, createdAt, testOrganizationID.StringValue())
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(licenseRowWithoutStatus)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.ErrorContains(t, err, "license status is missing")
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveReloadsExpiredCachedLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
expiredLicense := &licensetypes.License{
ID: valuer.GenerateUUID(),
ValidFrom: time.Now().Add(-2 * time.Hour).Unix(),
ValidUntil: time.Now().Add(-time.Hour).Unix(),
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: expiredLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestDeleteClearsCachedActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectExec(deleteLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Delete(ctx, testOrganizationID, testLicenseID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshClearsCachedActiveLicenseOnDowngrade(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(updateLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshWritesActiveLicenseFromStoreNotCache(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
staleCachedLicense := &licensetypes.License{
ID: testLicenseID,
Key: "stale-cached-license-key",
ValidFrom: 1732146923,
ValidUntil: -1,
LastValidatedAt: staleLastValidatedAt,
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: staleCachedLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(`UPDATE "license" .*'test-license-key'`).WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -76,3 +76,49 @@
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>

View File

@@ -36,8 +36,6 @@ const config: Config.InitialOptions = {
'^test-mocks/(.*)$': '<rootDir>/__mocks__/$1',
'^react-syntax-highlighter/dist/esm/(.*)$':
'<rootDir>/node_modules/react-syntax-highlighter/dist/cjs/$1',
// `antd` resolves to lib/ here; es/ deep imports must share its module instances (contexts).
'^antd/es/(.*)$': '<rootDir>/node_modules/antd/lib/$1',
'^@signozhq/(?!ui(?:/|$))([^/]+)$':
'<rootDir>/node_modules/@signozhq/$1/dist/$1.js',
},

View File

@@ -8042,7 +8042,7 @@ export interface DashboardtypesDashboardSpecDTO {
display: DashboardtypesDisplayDTO;
/**
* @type string
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
*/
duration?: string;
/**
@@ -13817,6 +13817,28 @@ export interface SpantypesEventDTO {
timeUnixNano?: number;
}
export type SpantypesEventV2DTOAttributes = { [key: string]: unknown };
export interface SpantypesEventV2DTO {
/**
* @type object
*/
attributes?: SpantypesEventV2DTOAttributes;
/**
* @type boolean
*/
isError?: boolean;
/**
* @type string
*/
name?: string;
/**
* @type integer
* @minimum 0
*/
timeUnixNano?: number;
}
export enum SpantypesFieldContextDTO {
attribute = 'attribute',
resource = 'resource',
@@ -14136,6 +14158,168 @@ export interface SpantypesGettableTraceAggregationsDTO {
aggregations: SpantypesSpanAggregationResultDTO[];
}
export interface SpantypesSpanTextMatchDTO {
/**
* @type string
*/
field: string;
/**
* @type string
*/
snippet: string;
}
export interface SpantypesSpanSummaryDTO {
/**
* @type integer
* @minimum 0
*/
childCount: number;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type boolean
*/
hasError: boolean;
/**
* @type string
*/
kind: string;
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type string
*/
name: string;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
parentSpanId?: string;
/**
* @type string
*/
responseStatusCode?: string;
/**
* @type string
*/
serviceName: string;
/**
* @type string
*/
spanId: string;
/**
* @type integer
* @minimum 0
*/
startOffsetNano: number;
/**
* @type integer
* @minimum 0
*/
subtreeSpanCount: number;
}
export interface SpantypesTraceSpanMatchDTO {
/**
* @type array
*/
matches: SpantypesSpanTextMatchDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanListDTO {
/**
* @type array
*/
items: SpantypesTraceSpanMatchDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceErrorItemDTO {
/**
* @type integer
* @minimum 0
*/
errorAncestorCount: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type string
*/
statusMessage: string;
}
export interface SpantypesTraceErrorListDTO {
/**
* @type array
*/
items: SpantypesTraceErrorItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceExpensiveItemDTO {
/**
* @type number
*/
cost?: number;
/**
* @type integer
* @minimum 0
*/
inputTokens: number;
/**
* @type integer
* @minimum 0
*/
outputTokens: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceExpensiveListDTO {
/**
* @type array
*/
items: SpantypesTraceExpensiveItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceAITokensDTO {
/**
* @type integer
@@ -14164,6 +14348,358 @@ export interface SpantypesTraceAITokensDTO {
reasoning: number;
}
export interface SpantypesTraceAIIdentityDTO {
/**
* @type integer
* @minimum 0
*/
modelCallCount: number;
tokens: SpantypesTraceAITokensDTO;
/**
* @type integer
* @minimum 0
*/
toolCallCount: number;
/**
* @type number
*/
totalCost?: number;
}
export interface SpantypesTraceServiceStatsDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
serviceName: string;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceIdentityDTO {
ai?: SpantypesTraceAIIdentityDTO;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type boolean
*/
hasMissingSpans: boolean;
root?: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
rootCount: number;
/**
* @type integer
* @minimum 0
*/
serviceCount: number;
/**
* @type array
*/
services: SpantypesTraceServiceStatsDTO[];
/**
* @type integer
* @minimum 0
*/
spanCount: number;
/**
* @type integer
* @minimum 0
*/
startTimestampMillis: number;
/**
* @type string
*/
traceId: string;
/**
* @type boolean
*/
truncated: boolean;
}
export interface SpantypesLinkDTO {
/**
* @type string
*/
spanId?: string;
/**
* @type string
*/
traceId?: string;
}
export interface SpantypesTraceLinkItemDTO {
/**
* @type integer
* @minimum 0
*/
linkCount: number;
/**
* @type array
*/
links: SpantypesLinkDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceLinkListDTO {
/**
* @type array
*/
items: SpantypesTraceLinkItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSlowestItemDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceSlowestListDTO {
/**
* @type array
*/
items: SpantypesTraceSlowestItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTruncatedFieldDTO {
/**
* @type string
*/
field: string;
/**
* @type integer
* @minimum 0
*/
length: number;
}
export type SpantypesSpanRecordDTOAttributes = { [key: string]: unknown };
export type SpantypesSpanRecordDTOResource = { [key: string]: string };
export interface SpantypesSpanRecordDTO {
/**
* @type object
*/
attributes: SpantypesSpanRecordDTOAttributes;
/**
* @type array
*/
events: SpantypesEventV2DTO[];
/**
* @type array
*/
links: SpantypesLinkDTO[];
/**
* @type object
*/
resource: SpantypesSpanRecordDTOResource;
/**
* @type string
*/
spanId: string;
/**
* @type string
*/
statusCode: string;
/**
* @type string
*/
statusMessage: string;
/**
* @type array
*/
truncated: SpantypesTruncatedFieldDTO[];
}
export interface SpantypesTraceTreeDTO {
/**
* @type boolean
*/
complete: boolean;
/**
* @type array
*/
records?: SpantypesSpanRecordDTO[];
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export enum SpantypesUnmarkedFailureReasonDTO {
http_4xx = 'http_4xx',
grpc_status = 'grpc_status',
exception_event = 'exception_event',
}
export interface SpantypesTraceUnmarkedFailureItemDTO {
parent?: SpantypesSpanSummaryDTO;
reason: SpantypesUnmarkedFailureReasonDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceUnmarkedFailureListDTO {
/**
* @type array
*/
items: SpantypesTraceUnmarkedFailureItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceOverviewDTO {
errors?: SpantypesTraceErrorListDTO;
expensive?: SpantypesTraceExpensiveListDTO;
identity?: SpantypesTraceIdentityDTO;
links?: SpantypesTraceLinkListDTO;
slowest?: SpantypesTraceSlowestListDTO;
tree?: SpantypesTraceTreeDTO;
unmarkedFailures?: SpantypesTraceUnmarkedFailureListDTO;
}
export interface SpantypesTraceSpanLevelDTO {
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSpanPercentileDTO {
/**
* @type integer
* @minimum 0
*/
p50Nano: number;
/**
* @type integer
* @minimum 0
*/
p90Nano: number;
/**
* @type integer
* @minimum 0
*/
p99Nano: number;
/**
* @type number
* @format double
*/
position: number;
/**
* @type integer
* @minimum 0
*/
windowMinutes: number;
}
export interface SpantypesTraceSpanDetailDTO {
/**
* @type integer
* @minimum 0
*/
ancestorCount: number;
/**
* @type array
*/
ancestors: SpantypesSpanSummaryDTO[];
/**
* @type array
*/
descendants: SpantypesTraceSpanLevelDTO[];
percentile?: SpantypesTraceSpanPercentileDTO;
record: SpantypesSpanRecordDTO;
summary: SpantypesSpanSummaryDTO;
}
export enum SpantypesInspectTypeDTO {
overview = 'overview',
span = 'span',
find = 'find',
}
export interface SpantypesGettableTraceInspectionDTO {
find?: SpantypesTraceSpanListDTO;
overview?: SpantypesTraceOverviewDTO;
span?: SpantypesTraceSpanDetailDTO;
type: SpantypesInspectTypeDTO;
}
export interface SpantypesTraceAISummaryDTO {
tokens: SpantypesTraceAITokensDTO;
/**
@@ -16035,6 +16571,55 @@ export type GetTraceAggregations200 = {
status: string;
};
export type InspectTracePathParameters = {
traceID: string;
};
export type InspectTraceParams = {
/**
* @type string
* @description Returns this span in full with the spans around it. Cannot be combined with search.
*/
spanId?: string;
/**
* @type string
* @description Returns the spans that match, earliest first: words, a filter expression, or both, such as worldpay AND has_error = true. Words match the span name, status message, attribute values and events, ignoring case.
*/
search?: string;
/**
* @type integer
* @description With spanId, the number of levels of ancestors and of descendants returned, 1 to 10; 2 when not given. The root span is always returned.
*/
depth?: number;
/**
* @type boolean
* @description Returns a different response: every span of the trace as a short line, in tree order, or with spanId that span and every span below it. Cannot be combined with search or depth.
*/
allSpans?: boolean;
/**
* @type array
* @description With spanId, attribute names returned without the 500 character cut; the record then holds only these attributes.
*/
selectFields?: string[];
/**
* @type integer
* @description Page size for search and for allSpans, at most 1000; when not given, 20 with search and 400 with allSpans. A page holds fewer spans when it would pass the 50,000 character limit.
*/
limit?: number;
/**
* @type string
* @description The nextCursor of an earlier response to the same request; returns the next page.
*/
cursor?: string;
};
export type InspectTrace200 = {
data: SpantypesGettableTraceInspectionDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSummaryPathParameters = {
traceID: string;
};

View File

@@ -29,6 +29,9 @@ import type {
GetTraceThreadPathParameters,
GetWaterfallV4200,
GetWaterfallV4PathParameters,
InspectTrace200,
InspectTraceParams,
InspectTracePathParameters,
RenderErrorResponseDTO,
SpantypesPostableFlamegraphDTO,
SpantypesPostableTraceAggregationsDTO,
@@ -158,6 +161,117 @@ export const useGetTraceAggregations = <
> => {
return useMutation(getGetTraceAggregationsMutationOptions(options));
};
/**
* Returns one of three parts of a trace of any size, named by type, each within 50,000 characters. Without spanId or search it returns the overview: the trace's identity with per-service totals, the spans where each error started, the failures not marked as errors (a 4xx response, a gRPC status other than OK, an exception event), the slowest spans by own time with same-name spans under one parent taken together, the most expensive gen_ai spans, and the span tree. A trace of up to 100 spans returns every span in the tree, and a small one also each span's full record; a larger trace returns the top levels. With spanId it returns that span's summary and full record, its ancestors, and the spans below it level by level, at most 20 per level; values over 500 characters are cut and listed in truncated. With search it returns the matching spans, each with where the words were found; allSpans returns every span instead. Every list carries its total, and every list item the span's direct parent. Pass a nextCursor as cursor with the same parameters to get the next page.
* @summary Inspect a trace
*/
export const inspectTrace = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTrace200>({
url: `/api/v1/traces/${traceID}/inspect`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceQueryKey = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceQueryKey({ traceID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTrace>>> = ({
signal,
}) => inspectTrace({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTrace>>
>;
export type InspectTraceQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a trace
*/
export function useInspectTrace<
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceQueryOptions({ traceID }, params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a trace
*/
export const invalidateInspectTrace = async (
queryClient: QueryClient,
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
* @summary Get summary for a trace

View File

@@ -302,10 +302,6 @@ export function createAggregation(
reduceTo: haveReduceTo
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
: undefined,
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
comparisonSpaceAggregationParam:
queryData.aggregations[0].comparisonSpaceAggregationParam,
}),
},
];
}

View File

@@ -1,7 +1,6 @@
import React, { Dispatch, SetStateAction, useState } from 'react';
import { Check, Plus, X } from '@signozhq/icons';
import { Button } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex } from 'antd';
import { Pill } from '@signozhq/ui/pill';
import Input from 'components/Input';

View File

@@ -1,7 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
import { Select, Spin } from 'antd';
import { Row, Select, Spin } from 'antd';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import Row from 'periscope/components/Row/Row';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import {

View File

@@ -6,15 +6,15 @@ import { Loader, Search } from '@signozhq/icons';
import { Color } from '@signozhq/design-tokens';
import {
Button,
Flex,
Input,
InputRef,
Space,
Spin,
TableColumnsType,
TableColumnType,
Tooltip,
} from 'antd';
import Space from 'periscope/components/Space/Space';
import Flex from 'periscope/components/Flex/Flex';
import { Progress } from '@signozhq/ui/progress';
import { Typography } from '@signozhq/ui/typography';
import type { FilterDropdownProps } from 'antd/lib/table/interface';

View File

@@ -1,8 +1,7 @@
import { useCallback, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row } from 'antd';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';

View File

@@ -1,6 +1,5 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row } from 'antd';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import useUrlQuery from 'hooks/useUrlQuery';

View File

@@ -1,8 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex, Modal } from 'antd';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';

View File

@@ -1,29 +0,0 @@
import type { ComponentProps } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import type { GlobalMockArgs } from '@/storybook/globals';
import ChangelogModal from '../ChangelogModal';
import { changelog } from './__story_mockdata__/changelog';
type ChangelogModalArgs = ComponentProps<typeof ChangelogModal> &
GlobalMockArgs;
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
args: { changelog, onClose: fn() },
} satisfies Meta<ChangelogModalArgs>;
export default meta;
type Story = StoryObj<ChangelogModalArgs>;
/** A cloud workspace: no upgrade actions, since cloud updates itself. */
export const Default: Story = {};
/** A self-hosted workspace, offered Skip for now and Update my workspace. */
export const SelfHosted: Story = {
args: { license: 'enterprise' },
};

View File

@@ -1,65 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const PUBLISHED_AT = '2026-08-12T09:00:00.000Z';
const feature = (
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] => ({
id,
documentId: `feature-${id}`,
title,
sort_order: id,
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
description,
deployment_type: DeploymentType.ALL,
// Media stays null so no story reaches out to the CMS for an image.
media: null,
});
export const changelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0-99-0',
version: 'v0.99.0',
release_date: '2026-08-12',
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
features: [
feature(
1,
'Metrics explorer',
'Browse every metric you send, inspect its labels and turn it into a panel without writing a query.\n\n- Search metrics by name, type or unit\n- See cardinality per label before you group by it\n- Open any metric straight in the query builder\n\nRead more in the [metrics explorer docs](https://signoz.io/docs/metrics-management/metrics-explorer/).',
),
feature(
2,
'Trace funnels',
'Measure conversion and drop-off across a multi-service request path. Define each step as a span filter, then compare the latency and error rate between any two steps.',
),
feature(
3,
'Saved views for logs',
'Save a logs query with its columns and time range, share it with your team and pin the ones you open most.',
),
feature(
4,
'Alert history',
'Every alert now keeps a timeline of its state changes, with the value that crossed the threshold and the labels it fired for.',
),
],
bug_fixes:
'- Fixed dashboard variables losing their selection on refresh.\n- Fixed alert history pagination skipping a page.\n- Fixed the logs list jumping to the top after a live tail update.',
maintenance:
'- Upgraded the query service to Go 1.24.\n- Reduced the ClickHouse memory used by trace aggregation queries.',
};

View File

@@ -1,28 +0,0 @@
.dotGrid {
position: relative;
}
.canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
// Read by the snake as its colour on the light page.
color: var(--l1-foreground);
}
// 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;
}

View File

@@ -1,35 +0,0 @@
import { useRef } from 'react';
import cx from 'classnames';
import { useIsDarkMode } from 'hooks/useDarkMode';
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;
/** Called when a Snake game starts or ends. */
onGameChange?: (isPlaying: boolean) => void;
}
/** Aurora dot grid that drifts on its own and lights up under the cursor. */
export default function DotGrid({
className,
onGameChange,
}: DotGridProps): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const isDarkMode = useIsDarkMode();
const label = useDotGrid(canvasRef, isDarkMode, onGameChange);
return (
<div
className={cx(styles.dotGrid, className)}
data-testid="ai-dot-grid"
aria-hidden
>
<canvas ref={canvasRef} className={styles.canvas} />
{label && <span className={styles.label}>{label}</span>}
</div>
);
}

View File

@@ -1,103 +0,0 @@
import { useRef } from 'react';
import { act, render, screen, userEvent } from 'tests/test-utils';
import DotGrid from '../DotGrid';
import { useDotGrid } from '../useDotGrid';
const KONAMI =
'{ArrowUp}{ArrowUp}{ArrowDown}{ArrowDown}{ArrowLeft}{ArrowRight}{ArrowLeft}{ArrowRight}ba';
function Chat({
onGameChange,
}: {
onGameChange: (isPlaying: boolean) => void;
}): JSX.Element {
return (
<div>
<DotGrid onGameChange={onGameChange} />
<textarea data-testid="chat-textarea" />
</div>
);
}
function ThemedGrid({ isDarkMode }: { isDarkMode: boolean }): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const label = useDotGrid(canvasRef, isDarkMode);
return (
<>
<canvas ref={canvasRef} />
<span data-testid="score-line">{label}</span>
</>
);
}
describe('DotGrid Snake', () => {
beforeEach(() => {
jest.useFakeTimers();
// jsdom has no canvas or layout: a 9 × 7 game grid is enough for a snake.
jest
.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue(
new Proxy({}, { get: () => jest.fn() }) as CanvasRenderingContext2D,
);
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(120);
jest.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(120);
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('quits the game on Esc and hands the keyboard back', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
expect(onGameChange).toHaveBeenLastCalledWith(true);
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent(
'Snake · score 0 · ↑ ↓ ← → · Esc to quit',
);
await user.keyboard('{Escape}');
expect(onGameChange).toHaveBeenLastCalledWith(false);
expect(screen.getByTestId('ai-dot-grid')).not.toHaveTextContent('Snake');
});
it('leaves arrows in the chat input alone after game over', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
// Heading right, the snake reaches the wall within a few steps.
act(() => {
jest.advanceTimersByTime(1500);
});
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent('Game over');
onGameChange.mockClear();
await user.click(screen.getByTestId('chat-textarea'));
await user.keyboard('{ArrowUp}');
expect(onGameChange).not.toHaveBeenCalled();
});
it('drops the score line when the theme changes mid-game', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const { rerender } = render(<ThemedGrid isDarkMode />);
await user.keyboard(KONAMI);
expect(screen.getByTestId('score-line')).toHaveTextContent('Snake · score 0');
rerender(<ThemedGrid isDarkMode={false} />);
expect(screen.getByTestId('score-line')).toBeEmptyDOMElement();
});
});

View File

@@ -1,32 +0,0 @@
import { getSnakeColors } from '../dotGridTheme';
function canvasWithInk(ink: string): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.style.color = ink;
document.body.appendChild(canvas);
return canvas;
}
describe('getSnakeColors', () => {
afterEach(() => {
document.body.innerHTML = '';
});
it('keeps the snake white on the dark page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), true)).toStrictEqual({
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
});
});
it('draws the snake in the page ink on the light page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), false)).toStrictEqual(
{
head: 'rgba(30,31,36,1)',
body: 'rgba(30,31,36,0.85)',
food: 'rgba(30,31,36,0.95)',
},
);
});
});

View File

@@ -1,112 +0,0 @@
import { SnakeGame, startSnake, stepSnake } from '../snakeGame';
const COLS = 10;
const ROWS = 6;
function newGame(): SnakeGame {
const game = startSnake(COLS, ROWS);
if (!game) {
throw new Error('a 10 × 6 grid fits a game');
}
return game;
}
describe('snakeGame', () => {
beforeEach(() => {
// Food lands on the first free cell, the top-left corner.
jest.spyOn(Math, 'random').mockReturnValue(0);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('needs at least an 8 × 6 grid', () => {
expect(startSnake(7, 6)).toBeNull();
expect(startSnake(8, 5)).toBeNull();
});
it('starts four cells long in the middle, heading right', () => {
expect(newGame()).toStrictEqual({
body: [
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
{ c: 2, r: 3 },
],
dir: { c: 1, r: 0 },
nextDir: { c: 1, r: 0 },
food: { c: 0, r: 0 },
score: 0,
});
});
it('moves one cell in its direction', () => {
const next = stepSnake(newGame(), COLS, ROWS);
expect(next?.body).toStrictEqual([
{ c: 6, r: 3 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
]);
expect(next?.score).toBe(0);
});
it('grows and scores when it eats', () => {
const next = stepSnake({ ...newGame(), food: { c: 6, r: 3 } }, COLS, ROWS);
expect(next?.body).toHaveLength(5);
expect(next?.score).toBe(1);
});
it('ends when it hits a wall', () => {
const atEdge: SnakeGame = {
...newGame(),
body: [
{ c: 9, r: 3 },
{ c: 8, r: 3 },
{ c: 7, r: 3 },
{ c: 6, r: 3 },
],
};
expect(stepSnake(atEdge, COLS, ROWS)).toBeNull();
});
it('ends when it runs into itself', () => {
const coiled: SnakeGame = {
...newGame(),
body: [
{ c: 5, r: 3 },
{ c: 5, r: 4 },
{ c: 6, r: 4 },
{ c: 6, r: 3 },
{ c: 7, r: 3 },
],
};
expect(stepSnake(coiled, COLS, ROWS)).toBeNull();
});
it('moves into the cell its tail is leaving', () => {
const up = { c: 0, r: -1 };
const turnedDownThenLeft: SnakeGame = {
...newGame(),
body: [
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
],
nextDir: up,
};
expect(stepSnake(turnedDownThenLeft, COLS, ROWS)?.body).toStrictEqual([
{ c: 4, r: 3 },
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
]);
});
});

View File

@@ -1,53 +0,0 @@
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,
];
}

View File

@@ -1,34 +0,0 @@
// Colours for the dot grid that depend on the page behind it.
export interface SnakeColors {
head: string;
body: string;
food: string;
}
const DARK_SNAKE: SnakeColors = {
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
};
function withAlpha(rgb: string, alpha: number): string {
const channels = rgb.match(/\d+(\.\d+)?/g)?.slice(0, 3) ?? ['0', '0', '0'];
return `rgba(${channels.join(',')},${alpha})`;
}
/** Snake colours: white on the dark page, the canvas's ink (`color`) on the light one. */
export function getSnakeColors(
canvas: HTMLCanvasElement,
isDarkMode: boolean,
): SnakeColors {
if (isDarkMode) {
return DARK_SNAKE;
}
const ink = getComputedStyle(canvas).color;
return {
head: withAlpha(ink, 1),
body: withAlpha(ink, 0.85),
food: withAlpha(ink, 0.95),
};
}

View File

@@ -1,102 +0,0 @@
// 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';
// Coloured dots on white read fainter than lit ones on black.
const LIGHT_ALPHA_BOOST = 1.6;
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;
/** Light adds up on the dark page; on the light one colours sit on the paper instead. */
isDarkMode: 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, isDarkMode, cutoffY }: AuroraFrame,
): void {
// Overlapping glows add up, as light does.
ctx.globalCompositeOperation = isDarkMode ? 'lighter' : 'source-over';
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);
// The hottest dots burn toward white on the dark page and deepen on the light one.
const heat = Math.min(1, Math.max(0, intensity - 0.9)) * 0.9;
const toward = isDarkMode ? 255 : 0;
const mix = isDarkMode ? heat : heat * 0.4;
const rgb = `${Math.round(red + (toward - red) * mix)},${Math.round(
green + (toward - green) * mix,
)},${Math.round(blue + (toward - blue) * mix)}`;
const alpha = Math.min(1, intensity * (isDarkMode ? 1 : LIGHT_ALPHA_BOOST));
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';
}

View File

@@ -1,100 +0,0 @@
// 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;
// Lowercase: keys are lowercased before matching, so B/b and A/a both count.
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 };
const ate = head.c === game.food.c && head.r === game.food.r;
const kept = ate ? game.body : game.body.slice(0, -1);
if (
head.c < 0 ||
head.c >= cols ||
head.r < 0 ||
head.r >= rows ||
isOn(kept, head)
) {
return null;
}
const body = [head, ...kept];
const food = ate ? placeFood(body, cols, rows) : game.food;
if (!food) {
return null;
}
return { ...game, body, dir, food, score: game.score + (ate ? 1 : 0) };
}

View File

@@ -1,320 +0,0 @@
import { RefObject, useEffect, useLayoutEffect, useRef, 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';
import { getSnakeColors } from './dotGridTheme';
const GAME_OVER_LABEL_MS = 4000;
const REPLAY_LABEL = '↑ to replay';
const playingLabel = (score: number): string =>
`Snake · score ${score} · ↑ ↓ ← → · Esc to quit`;
// 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;
const isField = (target: EventTarget | null): target is HTMLElement =>
target instanceof HTMLElement &&
Boolean(target.closest('input, textarea, select, [contenteditable="true"]'));
/** Draws the aurora dot grid; the Konami code turns it into Snake. Returns the score line. */
export function useDotGrid(
canvasRef: RefObject<HTMLCanvasElement>,
isDarkMode: boolean,
onGameChange?: (isPlaying: boolean) => void,
): string | null {
const [label, setLabel] = useState<string | null>(null);
const onGameChangeRef = useRef(onGameChange);
useLayoutEffect(() => {
onGameChangeRef.current = onGameChange;
});
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx) {
return undefined;
}
const isStill = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const snakeColors = getSnakeColors(canvas, isDarkMode);
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 ? playingLabel(0) : null);
showPlayCursor();
onGameChangeRef.current?.(game !== null);
};
const quit = (): void => {
game = null;
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(null);
showPlayCursor();
onGameChangeRef.current?.(false);
};
const endGame = (score: number): void => {
game = null;
canReplay = true;
showScoreLine(`Game over · score ${score} · ${REPLAY_LABEL}`);
showPlayCursor();
onGameChangeRef.current?.(false);
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 (!isField(target)) {
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) {
if (key === 'escape') {
event.preventDefault();
quit();
return;
}
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;
}
// Arrows in the chat's input move its caret instead.
if (canReplay && key.startsWith('arrow') && !isField(event.target)) {
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(playingLabel(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), snakeColors.food);
game.body.forEach((cell, i) => {
const { x, y } = cellCenter(cell.c, cell.r);
drawDot(
ctx,
x,
y,
sizeAt(y),
i === 0 ? snakeColors.head : snakeColors.body,
);
});
}
};
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,
isDarkMode,
// 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);
setLabel(null);
if (game) {
onGameChangeRef.current?.(false);
}
window.removeEventListener('pointermove', onPointer);
window.removeEventListener('pointerdown', onPointer);
window.removeEventListener('keydown', onKeyDown);
canvas.removeEventListener('click', onClick);
};
}, [canvasRef, isDarkMode]);
return label;
}

View File

@@ -105,3 +105,8 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
font-size: var(--font-size-xs);
color: var(--danger-foreground);
}

View File

@@ -20,7 +20,7 @@ interface Props {
query: string;
grammar: DslGrammar;
// Ids: `${testIdPrefix}-search-zone`, `-list-search*`, `-filter-zone`,
// `-filter-clear`, `-filter-created-by`, `-filter-updated`.
// `-filter-clear`, `-filter-created-by`, `-filter-updated`, `-query-error`.
testIdPrefix: string;
creatorOptions: CreatorOption[];
source: SuggestionSource;
@@ -35,6 +35,8 @@ interface Props {
hasExtraFilters?: boolean;
// Called by Clear after it empties the query.
onClearAll?: () => void;
// Shown under the search row.
error?: string;
// Wraps the search box and the filter controls (e.g. in an authz tooltip).
wrapControl?: (node: ReactElement) => ReactElement;
onSubmitted?: (hasQuery: boolean) => void;
@@ -63,6 +65,7 @@ function FilterZone({
extraFilters,
hasExtraFilters = false,
onClearAll,
error,
wrapControl = identity,
onSubmitted,
onFilterApplied,
@@ -112,6 +115,14 @@ function FilterZone({
)}
{rightSlot}
</div>
{error && (
<Typography.Text
className={styles.error}
testId={`${testIdPrefix}-query-error`}
>
{error}
</Typography.Text>
)}
<div className={styles.filtersRow}>
<Typography.Text className={styles.filtersLabel}>Filters</Typography.Text>
{wrapControl(

View File

@@ -1,49 +0,0 @@
.wrapper {
display: flex;
flex-direction: column;
height: 320px;
margin-top: 16px;
padding: 105px 141px;
gap: 4px;
justify-content: center;
align-items: flex-start;
border-radius: 6px;
border: 1px dashed var(--l1-border);
}
.img {
max-width: 100%;
}
.text {
font-family: Inter;
font-size: var(--font-size-sm);
font-style: normal;
line-height: 18px;
letter-spacing: -0.07px;
}
.title {
composes: text;
color: var(--l1-foreground);
font-weight: var(--font-weight-medium);
}
.detail {
composes: text;
color: var(--l2-foreground);
font-weight: var(--font-weight-normal);
}
.actionButtons {
display: flex;
gap: 24px;
align-items: center;
margin-top: 20px;
}
.learnMoreArrow {
margin-left: -20px;
color: var(--bg-robin-400);
cursor: pointer;
}

View File

@@ -1,64 +0,0 @@
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ArrowUpRight } from '@signozhq/icons';
import { handleContactSupport } from 'container/Integrations/utils';
import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
import { formatQueryErrorMessage } from './utils';
import styles from './InvalidQueryState.module.scss';
interface Props {
/** The backend's parse error for the list's DSL filter. */
errorMessage?: string;
isCloudUser: boolean;
testIdPrefix: string;
/** Runs before support opens, for analytics. */
onContactSupport?: () => void;
}
const INVALID_QUERY_FALLBACK = 'Please review the syntax and try again.';
function InvalidQueryState({
errorMessage,
isCloudUser,
testIdPrefix,
onContactSupport,
}: Props): JSX.Element {
const handleContactSupportClick = (): void => {
onContactSupport?.();
handleContactSupport(isCloudUser);
};
return (
<div className={styles.wrapper} data-testid={`${testIdPrefix}-invalid-query`}>
<img src={awwSnapUrl} alt="something went wrong" className={styles.img} />
<Typography.Text
className={styles.title}
data-testid={`${testIdPrefix}-invalid-query-title`}
>
Invalid query
</Typography.Text>
<Typography.Text
className={styles.detail}
data-testid={`${testIdPrefix}-invalid-query-detail`}
>
{formatQueryErrorMessage(errorMessage) || INVALID_QUERY_FALLBACK}
</Typography.Text>
<section className={styles.actionButtons}>
<Button
size="md"
variant="link"
color="primary"
onClick={handleContactSupportClick}
testId={`${testIdPrefix}-contact-support`}
>
Contact Support
</Button>
<ArrowUpRight size={16} className={styles.learnMoreArrow} />
</section>
</div>
);
}
export default InvalidQueryState;

View File

@@ -1,53 +0,0 @@
import { handleContactSupport } from 'container/Integrations/utils';
import { render, screen, userEvent } from 'tests/test-utils';
import InvalidQueryState from '../InvalidQueryState';
jest.mock('container/Integrations/utils', () => ({
handleContactSupport: jest.fn(),
}));
describe('InvalidQueryState', () => {
it('shows the backend message without its prefix and with quoted hints', () => {
render(
<InvalidQueryState
errorMessage="invalid filter query: unknown field `nme`"
isCloudUser={false}
testIdPrefix="list"
/>,
);
expect(screen.getByTestId('list-invalid-query-title')).toHaveTextContent(
'Invalid query',
);
expect(screen.getByTestId('list-invalid-query-detail')).toHaveTextContent(
/^unknown field "nme"$/,
);
});
it('falls back to a syntax hint without a message', () => {
render(<InvalidQueryState isCloudUser={false} testIdPrefix="list" />);
expect(screen.getByTestId('list-invalid-query-detail')).toHaveTextContent(
'Please review the syntax and try again.',
);
});
it('runs the callback, then opens support', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onContactSupport = jest.fn();
render(
<InvalidQueryState
errorMessage="bad"
isCloudUser
testIdPrefix="list"
onContactSupport={onContactSupport}
/>,
);
await user.click(screen.getByTestId('list-contact-support'));
expect(onContactSupport).toHaveBeenCalledTimes(1);
expect(jest.mocked(handleContactSupport)).toHaveBeenCalledWith(true);
});
});

View File

@@ -1,13 +0,0 @@
// Normalize BE query-parse error messages for display:
// - Drop the "invalid filter query:" prefix (the UI already says "Invalid query").
// - Backticks → double quotes for the format hint that follows the em-dash.
// - Trim surrounding whitespace.
export const formatQueryErrorMessage = (raw: string | undefined): string => {
if (!raw) {
return '';
}
return raw
.replace(/^invalid filter query:\s*/i, '')
.replace(/`([^`]+)`/g, '"$1"')
.trim();
};

View File

@@ -157,7 +157,6 @@ function RawLogView({
return (
<RawLogViewContainer
className="raw-log-row"
data-testid={`logs-raw-row-${data.id}`}
onClick={handleClickExpand}
wrap={false}

View File

@@ -1,8 +1,6 @@
import { blue } from '@ant-design/colors';
import { Color } from '@signozhq/design-tokens';
import Space from 'periscope/components/Space/Space';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row, Space } from 'antd';
import { FontSize } from 'container/OptionsMenu/types';
import { Info } from '@signozhq/icons';
import styled from 'styled-components';

View File

@@ -1,26 +1,2 @@
/** Shared hover copy for every Noz entry point (header, floating trigger, sidebar). */
export const NOZ_TOOLTIP_TITLE = 'Noz, your AI teammate';
/** The mascot's colours, shared by every drawing of Noz. */
export const NOZ_COLORS = {
body: '#E5484D',
eye: '#F5F5F5',
pupil: '#0A0C10',
hat: '#4E74F8',
} as const;
export const NOZ_BODY = {
x: 4.35938,
y: 8.49908,
width: 15.4569,
height: 11.978,
rx: 1.76147,
} as const;
export const NOZ_EYE = { cx: 12.0217, cy: 14.4881, r: 3.87523 } as const;
export const NOZ_PUPIL_PATH =
'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';
export const NOZ_HAT_PATH =
'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';

View File

@@ -1,13 +1,5 @@
import cx from 'classnames';
import {
NOZ_BODY,
NOZ_COLORS,
NOZ_EYE,
NOZ_HAT_PATH,
NOZ_PUPIL_PATH,
} from './Noz.constants';
import styles from './Noz.module.scss';
interface NozProps {
@@ -38,7 +30,14 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
xmlns="http://www.w3.org/2000/svg"
>
{/* body */}
<rect {...NOZ_BODY} fill={NOZ_COLORS.body} />
<rect
x="4.35938"
y="8.49908"
width="15.4569"
height="11.978"
rx="1.76147"
fill="#E5484D"
/>
{/* legs */}
<rect
x="6.87012"
@@ -46,7 +45,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
width="3.34679"
height="3.69908"
rx="0.880734"
fill={NOZ_COLORS.body}
fill="#E5484D"
/>
<rect
x="13.916"
@@ -54,7 +53,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
width="3.34679"
height="3.69908"
rx="0.880734"
fill={NOZ_COLORS.body}
fill="#E5484D"
/>
{/* right arm (static) */}
<rect
@@ -63,7 +62,7 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
width="2.11376"
height="3.69908"
rx="0.880734"
fill={NOZ_COLORS.body}
fill="#E5484D"
/>
{/* left arm: outer group does the "lift", inner does the wiggle */}
<g className="noz-arm-left">
@@ -74,15 +73,21 @@ export default function Noz({ size = 24, className }: NozProps): JSX.Element {
width="2.11376"
height="3.69908"
rx="0.880734"
fill={NOZ_COLORS.body}
fill="#E5484D"
/>
</g>
</g>
{/* head: face + eye + hat tilt together */}
<g className="noz-head">
<circle {...NOZ_EYE} fill={NOZ_COLORS.eye} />
<path d={NOZ_PUPIL_PATH} fill={NOZ_COLORS.pupil} />
<path d={NOZ_HAT_PATH} fill={NOZ_COLORS.hat} />
<circle cx="12.0217" cy="14.4881" r="3.87523" fill="#F5F5F5" />
<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"
/>
<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>
</span>

View File

@@ -215,8 +215,7 @@
padding-left: 8px;
.qb-formula {
.formula-row,
.formula-container {
.ant-row {
row-gap: 8px !important;
}
@@ -230,7 +229,7 @@
padding: 8px;
margin-left: 74px;
.formula-item {
.ant-col {
&::before {
content: '';
position: absolute;

View File

@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
@@ -7,21 +8,9 @@ import ROUTES from 'constants/routes';
import { DataSource } from 'types/common/queryBuilder';
import { QueryBuilderV2 } from '../QueryBuilderV2';
import { traceMatchingQuery } from './__story_mockdata__/queryBuilder';
import {
expectLogsCount,
expectLogsQuery,
expectMeterQuery,
expectMetricsQuery,
expectPanelEditorQuery,
expectTraceMatching,
expectTracesQuery,
hoverAddFormula,
hoverAddFunction,
hoverAddTraceMatching,
} from './__story_mockdata__/queryBuilder.play';
import {
DEFAULT_ARGS,
expectFirstQuery,
meterQuery,
PANEL_EDITOR_ARGS,
PANEL_EDITOR_PATH,
@@ -60,7 +49,12 @@ export const LogsExplorer: Story = {
parameters: {
signoz: { route: routeWith(ROUTES.LOGS_EXPLORER, initialQueriesMap.logs) },
},
play: expectLogsCount,
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, {
signal: 'logs',
aggregations: [{ expression: 'count()' }],
});
},
};
/** Traces explorer: a fixed traces signal, with trace matching offered. */
@@ -74,7 +68,9 @@ export const TracesExplorer: Story = {
route: routeWith(ROUTES.TRACES_EXPLORER, initialQueriesMap.traces),
},
},
play: expectTracesQuery,
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'traces' });
},
};
/** Metrics explorer: a fixed metrics signal, functions hidden. */
@@ -91,7 +87,9 @@ export const MetricsExplorer: Story = {
),
},
},
play: expectMetricsQuery,
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'metrics' });
},
};
/** Meter explorer: metrics read from the meter source. */
@@ -107,7 +105,9 @@ export const MeterExplorer: Story = {
parameters: {
signoz: { route: routeWith(ROUTES.METER_EXPLORER, meterQuery) },
},
play: expectMeterQuery,
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'metrics', source: 'meter' });
},
};
/**
@@ -121,7 +121,12 @@ export const PanelEditor: Story = {
route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs),
},
},
play: expectPanelEditorQuery,
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
await expect(
within(canvasElement).getByTestId('query-data-source-selector-0'),
).toBeVisible();
},
};
/** Logs alert: a fixed logs signal with functions, as the alert form mounts it. */
@@ -134,54 +139,7 @@ export const LogsAlert: Story = {
parameters: {
signoz: { route: routeWith(ROUTES.ALERTS_NEW, initialQueriesMap.logs) },
},
play: expectLogsQuery,
};
const TRACES_EXPLORER_ARGS = {
config: { initialDataSource: DataSource.TRACES, queryVariant: 'static' },
showTraceOperator: true,
} as const;
/** Traces explorer with trace matching: two queries joined by `A => B`. */
export const TraceMatching: Story = {
args: TRACES_EXPLORER_ARGS,
parameters: {
signoz: { route: routeWith(ROUTES.TRACES_EXPLORER, traceMatchingQuery) },
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
},
play: expectTraceMatching,
};
/** The tooltip on Add Formula, with its Learn more link. */
export const AddFormulaTooltip: Story = {
args: TRACES_EXPLORER_ARGS,
parameters: {
signoz: {
route: routeWith(ROUTES.TRACES_EXPLORER, initialQueriesMap.traces),
},
},
play: hoverAddFormula,
};
/** The tooltip on Add Trace Matching, with its Learn more link. */
export const AddTraceMatchingTooltip: Story = {
args: TRACES_EXPLORER_ARGS,
parameters: {
signoz: {
route: routeWith(ROUTES.TRACES_EXPLORER, initialQueriesMap.traces),
},
},
play: hoverAddTraceMatching,
};
/** The tooltip on a query's add-function button, with its Learn more link. */
export const AddFunctionTooltip: Story = {
args: {
config: { initialDataSource: DataSource.LOGS, queryVariant: 'static' },
showFunctions: true,
signalSourceChangeEnabled: true,
},
parameters: {
signoz: { route: routeWith(ROUTES.ALERTS_NEW, initialQueriesMap.logs) },
},
play: hoverAddFunction,
};

View File

@@ -1,199 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { DataSource } from 'types/common/queryBuilder';
import type { QueryBuilderV2 } from '../../QueryBuilderV2';
import { QueryBuilderField } from '../../queryBuilderFields.types';
import {
mergeQueryBuilderFieldsConfig,
RAW_QUERY_FIELDS,
ResolvedQueryBuilderField,
resolveQueryBuilderField,
} from '../../queryBuilderFields.utils';
import { expectFirstQuery, payloadIn } from '../QueryBuilderV2.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: Partial<Parameters<typeof QueryBuilderV2>[0]>;
}
export const expectLogsCount = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, {
signal: 'logs',
aggregations: [{ expression: 'count()' }],
});
};
export const expectLogsQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
};
export const expectTracesQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'traces' });
};
export const expectMetricsQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'metrics' });
};
export const expectMeterQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'metrics', source: 'meter' });
};
export const expectPanelEditorQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
await expect(
within(canvasElement).getByTestId('query-data-source-selector-0'),
).toBeVisible();
};
/** The operator renders only where the host offers trace matching. */
export const expectTraceMatching = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!args.showTraceOperator) {
return;
}
await expect(
await within(canvasElement).findByTestId('trace-operator'),
).toBeVisible();
await waitFor(() =>
expect(payloadIn(canvasElement).queries).toContainEqual(
expect.objectContaining({
type: 'builder_trace_operator',
spec: expect.objectContaining({ expression: 'A => B' }),
}),
),
);
};
const hoverForLearnMore = async (
target: HTMLElement,
title: string,
): Promise<void> => {
await userEvent.hover(target);
await waitFor(async () => {
const tooltip = (await screen.findAllByRole('tooltip')).find((element) =>
element.textContent?.includes(title),
);
await expect(tooltip).toBeDefined();
await expect(
within(tooltip as HTMLElement).getByText('Learn more'),
).toBeVisible();
});
};
const resolvedField = (
args: PlayContext['args'],
field: QueryBuilderField,
): ResolvedQueryBuilderField =>
resolveQueryBuilderField(
field,
mergeQueryBuilderFieldsConfig(
args.isRawQuery ? RAW_QUERY_FIELDS : undefined,
args.fieldsConfig,
),
);
const isTracesBuilder = (args: PlayContext['args']): boolean =>
args.config?.queryVariant === 'static' &&
args.config.initialDataSource === DataSource.TRACES;
const canShowTraceOperator = (args: PlayContext['args']): boolean =>
Boolean(args.showTraceOperator) &&
!resolvedField(args, QueryBuilderField.TraceOperator).hidden;
const isFooterShown = (args: PlayContext['args']): boolean =>
(!args.showOnlyWhereClause && !args.isRawQuery) ||
(isTracesBuilder(args) && canShowTraceOperator(args));
/** A disabled Add Formula shows its reason instead of the Learn more tooltip. */
export const hoverAddFormula = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const formula = resolvedField(args, QueryBuilderField.Formula);
if (
!isFooterShown(args) ||
formula.hidden ||
formula.disabled ||
(isTracesBuilder(args) && args.isRawQuery)
) {
return;
}
await hoverForLearnMore(
await within(canvasElement).findByTestId('add-formula-button'),
'Add New Formula',
);
};
/** Add Trace Matching is offered only with trace matching on and no operator yet. */
export const hoverAddTraceMatching = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canShowTraceOperator(args) || !isFooterShown(args)) {
return;
}
const button = await waitFor(() => {
const element = canvasElement.querySelector<HTMLElement>(
'.add-trace-operator-button',
);
if (!element) {
throw new Error('Add Trace Matching not rendered');
}
return element;
});
await hoverForLearnMore(button, 'Add Trace Matching');
};
/** The function picker sits in the query's options row when functions are shown. */
export const hoverAddFunction = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!args.showFunctions) {
return;
}
const button = await waitFor(() => {
const element = within(canvasElement)
.getByTestId('query-A')
.querySelector<HTMLElement>('.add-function-btn');
if (!element) {
throw new Error('Add function not rendered');
}
return element;
});
await hoverForLearnMore(button, 'Add new function');
};

View File

@@ -1,37 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
initialQueriesMap,
initialQueryBuilderFormTraceOperatorValues,
} from 'constants/queryBuilder';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
const [tracesQuery] = initialQueriesMap.traces.builder.queryData;
/** Two traces queries joined by a trace operator: a span of A with a descendant from B. */
export const traceMatchingQuery: Query = {
...initialQueriesMap.traces,
builder: {
...initialQueriesMap.traces.builder,
queryData: [
{
...tracesQuery,
queryName: 'A',
expression: 'A',
filter: { expression: "service.name = 'frontend'" },
},
{
...tracesQuery,
queryName: 'B',
expression: 'B',
filter: { expression: "service.name = 'payments' AND has_error = true" },
},
],
queryTraceOperator: [
{ ...initialQueryBuilderFormTraceOperatorValues, expression: 'A => B' },
],
},
};

View File

@@ -17,7 +17,6 @@ import {
} from '@/storybook/msw/__story_mockdata__/fields';
import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';
import { DEFAULT_VISIBLE_ITEMS_COUNT } from '../FilterRenderers/Checkbox/constants';
import { FiltersType, QuickFilterCheckboxUseFieldApis } from '../types';
const customFilters = [
@@ -138,9 +137,3 @@ export const selectedServiceQueryBuilder = {
},
},
};
/** More values than the checkbox filter shows before Show More. */
export const MANY_FILTER_VALUES = Array.from(
{ length: 2 * DEFAULT_VISIBLE_ITEMS_COUNT + 5 },
(_, index) => `service-${String(index + 1).padStart(2, '0')}`,
);

View File

@@ -1,15 +1,11 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ComponentProps, ComponentType } from 'react';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
import QuickFilters from '../QuickFilters';
import {
dirtySettings,
openQueryPicker,
openSettings,
} from './__story_mockdata__/quickFilters.play';
import {
checkboxConfig,
fieldApis,
@@ -17,7 +13,6 @@ import {
handlers,
LONG_FILTER_VALUES,
loadingFiltersHandlers,
MANY_FILTER_VALUES,
queryBuilder,
selectedServiceQueryBuilder,
noSavedFiltersHandler,
@@ -52,18 +47,40 @@ export default meta;
type Story = StoryObj<typeof meta>;
type GlobalArgsStory = StoryObj<
type TooltipsStory = StoryObj<
ComponentProps<typeof QuickFilters> & GlobalMockArgs
>;
/**
* The settings control renders disabled while its permission check is in
* flight and is swapped for the enabled one once the check answers, so it is
* looked up again on every attempt; a click on the disabled one is dropped in
* silence.
*/
const settingsControl = (canvasElement: HTMLElement): Promise<HTMLElement> =>
waitFor(() => {
const control = within(canvasElement).getByTestId('settings-icon-container');
expect(control).not.toHaveAttribute('aria-disabled', 'true');
return control;
});
/** Interaction: the settings panel is opened through the admin settings control. */
export const SettingsOpen: GlobalArgsStory = {
play: openSettings,
export const SettingsOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(await settingsControl(canvasElement));
await screen.findByText('Edit quick filters');
},
};
/** Mutation: changing the settings list reveals the fixed save and discard footer. */
export const SettingsDirtyFooter: GlobalArgsStory = {
play: dirtySettings,
export const SettingsDirtyFooter: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(await settingsControl(canvasElement));
await userEvent.click(await screen.findByRole('button', { name: 'Add' }));
await screen.findByRole('button', { name: 'Save changes' });
},
};
/** Loading: dynamic filters are intentionally left pending to display the panel skeleton. */
@@ -83,28 +100,6 @@ export const NoResults: Story = {
},
};
/** A filter with more values than it lists at first: the value search and Show More. */
export const ShowMoreValues: Story = {
parameters: {
msw: {
handlers: [
noSavedFiltersHandler,
fieldValuesHandler(MANY_FILTER_VALUES),
...handlers,
],
},
},
};
/** A filter whose attribute has no values in the time range. */
export const NoValuesFound: Story = {
parameters: {
msw: {
handlers: [noSavedFiltersHandler, fieldValuesHandler([]), ...handlers],
},
},
};
/** Selection: an expanded checkbox shows the actual selected service values. */
export const SelectedExpandedCheckbox: Story = {
parameters: {
@@ -121,7 +116,7 @@ export const SelectedExpandedCheckbox: Story = {
* service names long enough to be cut. The Service name filter carries them, so
* the workspace's own saved filter list is answered empty.
*/
export const Tooltips: GlobalArgsStory = {
export const Tooltips: TooltipsStory = {
args: { tooltipsOpen: true },
parameters: {
msw: {
@@ -137,7 +132,7 @@ export const Tooltips: GlobalArgsStory = {
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
/** Interaction: the query picker lists every query the filters can follow. */
export const QueryPickerOpen: GlobalArgsStory = {
export const QueryPickerOpen: Story = {
parameters: {
signoz: {
queryBuilder: {
@@ -153,5 +148,18 @@ export const QueryPickerOpen: GlobalArgsStory = {
},
},
},
play: openQueryPicker,
play: async ({ canvasElement }): Promise<void> => {
const trigger = await waitFor(() => {
const element = canvasElement.querySelector<HTMLElement>(
'[data-slot="combobox-trigger"]',
);
expect(element).toBeInTheDocument();
return element as HTMLElement;
});
await userEvent.click(trigger);
await screen.findByRole('listbox');
},
};

View File

@@ -1,79 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import type { ComponentProps } from 'react';
import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import type { GlobalMockArgs } from '@/storybook/globals';
import type QuickFilters from '../../QuickFilters';
interface PlayContext {
canvasElement: HTMLElement;
args: ComponentProps<typeof QuickFilters> & GlobalMockArgs;
}
const UNTIL_LOADED = { timeout: 15_000 };
/** The settings control stays enabled when the check itself fails. */
const canManageQuickFilters = (args: PlayContext['args']): boolean =>
args.authzState === 'error' ||
grantsAll(args, ...QuickFilterManagePermissions);
/**
* The settings control renders disabled while its permission check is in
* flight and is swapped for the enabled one once the check answers, so it is
* looked up again on every attempt; a click on the disabled one is dropped in
* silence.
*/
const settingsControl = (canvasElement: HTMLElement): Promise<HTMLElement> =>
waitFor(async () => {
const control = within(canvasElement).getByTestId('settings-icon-container');
await expect(control).not.toHaveAttribute('aria-disabled', 'true');
return control;
}, UNTIL_LOADED);
export const openSettings = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canManageQuickFilters(args)) {
return;
}
await userEvent.click(await settingsControl(canvasElement));
await screen.findByText('Edit quick filters');
};
export const dirtySettings = async (context: PlayContext): Promise<void> => {
if (!canManageQuickFilters(context.args)) {
return;
}
await openSettings(context);
await userEvent.click(await screen.findByRole('button', { name: 'Add' }));
await screen.findByRole('button', { name: 'Save changes' });
};
export const openQueryPicker = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const trigger = await waitFor(async () => {
const element = canvasElement.querySelector<HTMLElement>(
'[data-slot="combobox-trigger"]',
);
await expect(element).toBeInTheDocument();
return element as HTMLElement;
});
await userEvent.click(trigger);
await screen.findByRole('listbox');
};

View File

@@ -4,8 +4,7 @@ import type {
TableColumnsType as ColumnsType,
TableColumnType as ColumnType,
} from 'antd';
import { Button } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex } from 'antd';
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
import { Switch } from '@signozhq/ui/switch';
import logEvent from 'api/common/logEvent';

View File

@@ -1,11 +1,14 @@
import { HTMLAttributes } from 'react';
import { Button, ButtonProps } from 'antd';
import Space from 'periscope/components/Space/Space';
import type { SpaceProps } from 'periscope/components/Space/types';
import Col from 'periscope/components/Col/Col';
import type { ColProps } from 'periscope/components/Col/types';
import Row from 'periscope/components/Row/Row';
import type { RowProps } from 'periscope/components/Row/types';
import {
Button,
ButtonProps,
Col,
ColProps,
Row,
RowProps,
Space,
SpaceProps,
} from 'antd';
import {
Typography,
TypographyTextProps,

View File

@@ -56,8 +56,6 @@
.title {
display: flex;
align-items: center;
flex: 1 1 auto;
min-width: 0;
gap: 7px;
font-size: 13px;
font-weight: 600;
@@ -65,7 +63,6 @@
}
.shortcut {
flex-shrink: 0;
font-size: 10px;
font-family: var(--font-mono, monospace);
font-weight: 500;
@@ -84,7 +81,6 @@
.actions {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 2px;

View File

@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Button } from '@signozhq/ui/button';
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
@@ -18,7 +17,6 @@ import {
normalizePage,
useAIAssistantAnalyticsContext,
} from '../hooks/useAIAssistantAnalyticsContext';
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
@@ -41,7 +39,6 @@ export default function AIAssistantModal(): JSX.Element | null {
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const chatTitle = useActiveChatTitle();
const openModal = useAIAssistantStore((s) => s.openModal);
const closeModal = useAIAssistantStore((s) => s.closeModal);
const minimizeModal = useAIAssistantStore((s) => s.minimizeModal);
@@ -154,7 +151,7 @@ export default function AIAssistantModal(): JSX.Element | null {
<div className={styles.header}>
<div className={`${styles.title} noz-wave`}>
<Noz size={16} />
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
<span>Noz</span>
<kbd className={styles.shortcut}>
<span>⌘</span>
<span>J</span>

View File

@@ -1,5 +1,37 @@
.panel:global(.floating-panel) {
background: var(--l2-background);
.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);
}
}
.header {
@@ -9,14 +41,12 @@
padding: 8px;
border-bottom: 1px solid var(--l1-border);
flex-shrink: 0;
background: var(--l2-background);
background: var(--l1-background);
}
.title {
display: flex;
align-items: center;
flex: 1 1 auto;
min-width: 0;
gap: 6px;
font-size: 13px;
font-weight: 600;
@@ -25,7 +55,6 @@
.actions {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 2px;
}

View File

@@ -1,6 +1,5 @@
import { useCallback, useState } from 'react';
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
import { Button } from '@signozhq/ui/button';
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
import { matchRoute } from 'lib/router/matchRoute';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
@@ -8,9 +7,6 @@ import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Plus, X } from '@signozhq/icons';
import Noz from 'components/Noz/Noz';
import { BOTTOM_STRIP_HEIGHT } from 'container/BottomStrip';
import { supportChatObstacle } from 'container/BottomStrip/SupportButton/supportChatObstacle';
import { FloatingPanel } from 'periscope/components/FloatingPanel';
import logEvent from 'api/common/logEvent';
@@ -18,28 +14,13 @@ import ConversationsList from '../components/ConversationsList';
import ConversationView from '../ConversationView';
import { AIAssistantEvents } from '../events';
import { useAIAssistantAnalyticsContext } from '../hooks/useAIAssistantAnalyticsContext';
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
import styles from './AIAssistantPanel.module.scss';
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,
};
const PANEL_AVOID = [supportChatObstacle];
const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
export default function AIAssistantPanel(): JSX.Element | null {
const { pathname } = useAppLocation();
@@ -57,7 +38,6 @@ export default function AIAssistantPanel(): JSX.Element | null {
(s) => s.startNewConversation,
);
const analyticsCtx = useAIAssistantAnalyticsContext();
const chatTitle = useActiveChatTitle();
const handleExpand = useCallback(() => {
if (!activeConversationId) {
@@ -92,37 +72,75 @@ 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;
document.body.classList.toggle(
AI_ASSISTANT_PANEL_OPEN_CLASS,
shouldOffsetChatSupport,
);
if (shouldOffsetChatSupport) {
document.body.style.setProperty(
AI_ASSISTANT_PANEL_WIDTH_VAR,
`${panelWidth}px`,
);
} else {
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
}
return (): void => {
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],
);
if (!isOpen || isFullScreenPage) {
return null;
}
const availableHeight = Math.max(
0,
window.innerHeight - BOTTOM_STRIP_HEIGHT - 2 * PANEL_MARGIN,
);
const panelHeight = Math.min(PANEL_HEIGHT, availableHeight);
return (
<VariantContext.Provider value="panel">
<FloatingPanel
isOpen
className={styles.panel}
width={PANEL_WIDTH}
height={panelHeight}
minWidth={PANEL_MIN_WIDTH}
minHeight={Math.min(PANEL_MIN_HEIGHT, availableHeight)}
enableResizing={PANEL_RESIZE_EDGES}
keepInViewport
avoid={PANEL_AVOID}
defaultPosition={{
x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN,
y: PANEL_MARGIN + availableHeight - panelHeight,
}}
>
<div className={`${styles.header} floating-panel__drag-handle`}>
<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}>
<div className={`${styles.title} noz-wave`}>
<Noz size={18} />
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
<span>Noz</span>
</div>
<div className={styles.actions}>
@@ -173,7 +191,6 @@ export default function AIAssistantPanel(): JSX.Element | null {
size="sm"
icon
color="secondary"
testId="ai-assistant-panel-close"
onClick={closeDrawer}
aria-label="Close panel"
>
@@ -190,7 +207,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
<ConversationView conversationId={activeConversationId} />
)
)}
</FloatingPanel>
</div>
</VariantContext.Provider>
);
}

View File

@@ -3,41 +3,6 @@
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;
container-type: inline-size;
// Shared by the thread and the input: 768px on laptops, wider on big screens.
--noz-page-column: clamp(768px, 70cqi, 1040px);
padding: calc(var(--spacing-6) + 1px) calc(var(--spacing-6) + 1px) 0 1px;
&::before {
content: '';
position: absolute;
z-index: -1;
inset: var(--spacing-6) var(--spacing-6) var(--spacing-16) 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: calc(var(--spacing-20) + var(--spacing-3));
background: linear-gradient(to bottom, transparent, var(--l1-background));
pointer-events: none;
}
}
}
.loading {
@@ -69,18 +34,7 @@
border-top: 1px solid var(--l1-border);
&.compact {
padding: 0;
// Same colour as the panel's outline.
border-top-color: var(--l2-border);
}
&.fullPage {
position: relative;
z-index: 1;
width: min(var(--noz-page-column), 100%);
margin: 0 auto;
padding: 0 0 var(--spacing-6);
border-top: none;
padding: 8px;
}
}

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import cx from 'classnames';
import { useAppLocation } from 'lib/router/useAppLocation';
@@ -17,8 +17,6 @@ import { useVariant } from '../VariantContext';
import styles from './ConversationView.module.scss';
const SNAKE_PLACEHOLDER = 'Playing Snake · Esc to quit';
interface ConversationViewProps {
conversationId: string;
}
@@ -28,18 +26,8 @@ export default function ConversationView({
}: ConversationViewProps): JSX.Element {
const variant = useVariant();
const isCompact = variant === 'panel';
const isFullPage = variant === 'page';
const location = useAppLocation();
const [isPlayingSnake, setIsPlayingSnake] = useState(false);
const [inputFocusRequest, setInputFocusRequest] = useState(0);
const handleSnakeGameChange = useCallback((isPlaying: boolean): void => {
setIsPlayingSnake(isPlaying);
if (!isPlaying) {
setInputFocusRequest((n) => n + 1);
}
}, []);
const conversation = useAIAssistantStore(
(s) => s.conversations[conversationId],
);
@@ -121,35 +109,38 @@ export default function ConversationView({
[sendMessage, analyticsCtx, pendingClarificationHere],
);
// When the current reply began, kept with the stream so a reopened view carries on from it.
const streamStartedAt = useAIAssistantStore((s) => {
const stream = s.streams[conversationId];
return stream?.isStreaming ? stream.startedAt : null;
});
// 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);
useEffect(() => {
if (!isStreamingHere) {
streamStartedAtRef.current = null;
return;
}
if (streamStartedAtRef.current === null) {
streamStartedAtRef.current = Date.now();
}
}, [isStreamingHere]);
const handleCancel = useCallback(() => {
const startedAt = streamStartedAtRef.current;
void logEvent(AIAssistantEvents.CancelClicked, {
threadId: analyticsCtx.threadId,
secondsSinceStart:
streamStartedAt !== null
? Math.round((Date.now() - streamStartedAt) / 1000)
: null,
startedAt !== null ? Math.round((Date.now() - startedAt) / 1000) : null,
});
cancelStream(conversationId);
}, [cancelStream, conversationId, analyticsCtx.threadId, streamStartedAt]);
}, [cancelStream, conversationId, analyticsCtx.threadId]);
const messages = conversation?.messages ?? [];
const showDisclaimer = messages.length > 0;
const inputDisabled =
isPlayingSnake ||
isStreamingHere ||
isLoadingThread ||
Boolean(pendingApprovalHere) ||
Boolean(pendingClarificationHere);
let inputDisabledTooltip: string | undefined;
if (isPlayingSnake) {
inputDisabledTooltip = SNAKE_PLACEHOLDER;
} else if (isStreamingHere) {
if (isStreamingHere) {
inputDisabledTooltip = 'Wait for the response to finish';
} else if (isLoadingThread) {
inputDisabledTooltip = 'Wait for the conversation to load';
@@ -159,12 +150,8 @@ 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,
@@ -178,7 +165,7 @@ export default function ConversationView({
const isHydrating = Boolean(conversation?.isHydrating);
if ((isLoadingThread || isHydrating) && messages.length === 0) {
return (
<div className={conversationClass}>
<div className={styles.conversation}>
<ConversationSkeleton />
<div className={inputWrapperClass}>
<ChatInput
@@ -195,13 +182,12 @@ export default function ConversationView({
}
return (
<div className={conversationClass}>
<div className={styles.conversation}>
<VirtualizedMessages
key={conversationId}
conversationId={conversationId}
messages={messages}
isStreaming={isStreamingHere}
onSnakeGameChange={handleSnakeGameChange}
onSendSuggestedPrompt={(text): void => {
handleSend(
text,
@@ -222,11 +208,7 @@ export default function ConversationView({
onCancel={handleCancel}
disabled={inputDisabled}
disabledTooltip={inputDisabledTooltip}
placeholder={isPlayingSnake ? SNAKE_PLACEHOLDER : undefined}
focusRequest={inputFocusRequest}
isStreaming={isStreamingHere}
streamStartedAt={streamStartedAt}
showNozPeek={messages.length === 0 && !isStreamingHere}
autoContexts={autoContexts}
onDismissAutoContext={handleDismissAutoContext}
/>

View File

@@ -37,25 +37,7 @@ jest.mock('container/AIAssistant/hooks/useAIAssistantAnalyticsContext', () => ({
// ConversationView imports for its dismissed-context filter.
jest.mock('container/AIAssistant/components/ChatInput', () => ({
__esModule: true,
default: ({
streamStartedAt,
disabled,
placeholder,
focusRequest,
}: {
streamStartedAt?: number | null;
disabled?: boolean;
placeholder?: string;
focusRequest?: number;
}): JSX.Element => (
<div
data-testid="chat-input"
data-stream-started-at={streamStartedAt ?? ''}
data-disabled={String(Boolean(disabled))}
data-placeholder={placeholder ?? ''}
data-focus-request={focusRequest ?? 0}
/>
),
default: (): JSX.Element => <div data-testid="chat-input" />,
autoContextKey: (): string => '',
}));
@@ -71,28 +53,6 @@ jest.mock('components/Noz/Noz', () => ({
default: (): JSX.Element => <div data-testid="noz" />,
}));
jest.mock('components/DotGrid/DotGrid', () => ({
__esModule: true,
default: ({
onGameChange,
}: {
onGameChange?: (isPlaying: boolean) => void;
}): JSX.Element => (
<>
<button
type="button"
data-testid="start-snake"
onClick={(): void => onGameChange?.(true)}
/>
<button
type="button"
data-testid="end-snake"
onClick={(): void => onGameChange?.(false)}
/>
</>
),
}));
jest.mock('container/AIAssistant/components/MessageBubble', () => ({
__esModule: true,
default: (): null => null,
@@ -179,86 +139,3 @@ describe('ConversationView — empty-state chip context', () => {
expect(sendMessage).toHaveBeenCalledWith(CHIP_TEXT, undefined, undefined);
});
});
describe('ConversationView — reply start time', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('carries on from when the reply began when the view is reopened mid-reply', () => {
jest.spyOn(Date, 'now').mockReturnValue(5000);
useAIAssistantStore.setState({
conversations: {
[CONVERSATION_ID]: {
id: CONVERSATION_ID,
messages: [],
createdAt: 1,
updatedAt: 1,
},
},
streams: {
[CONVERSATION_ID]: {
isStreaming: true,
streamingContent: '',
streamingStatus: '',
streamingEvents: [],
streamingMessageId: null,
streamingActions: null,
pendingApproval: null,
pendingClarification: null,
startedAt: 1000,
},
},
activeConversationId: CONVERSATION_ID,
isLoadingThread: false,
});
const { getByTestId } = renderView('panel');
expect(getByTestId('chat-input')).toHaveAttribute(
'data-stream-started-at',
'1000',
);
});
});
describe('ConversationView — Snake on the empty state', () => {
beforeEach(() => {
useAIAssistantStore.setState({
conversations: {
[CONVERSATION_ID]: {
id: CONVERSATION_ID,
messages: [],
createdAt: 1,
updatedAt: 1,
},
},
streams: {},
activeConversationId: CONVERSATION_ID,
isLoadingThread: false,
});
});
it('disables the input while Snake runs', () => {
const { getByTestId } = renderView('page');
fireEvent.click(getByTestId('start-snake'));
expect(getByTestId('chat-input')).toHaveAttribute('data-disabled', 'true');
expect(getByTestId('chat-input')).toHaveAttribute(
'data-placeholder',
'Playing Snake · Esc to quit',
);
});
it('gives the input back, focused, once the game ends', () => {
const { getByTestId } = renderView('page');
fireEvent.click(getByTestId('start-snake'));
fireEvent.click(getByTestId('end-snake'));
expect(getByTestId('chat-input')).toHaveAttribute('data-disabled', 'false');
expect(getByTestId('chat-input')).toHaveAttribute('data-placeholder', '');
expect(getByTestId('chat-input')).toHaveAttribute('data-focus-request', '1');
});
});

View File

@@ -3,32 +3,24 @@
.input {
display: flex;
flex-direction: column;
background: var(--l2-background);
border: 1px solid var(--l2-border);
border-radius: var(--radius-3);
box-shadow: var(--shadow-dialog);
gap: 10px;
background: var(--l1-background);
border-radius: var(--radius-2);
padding: 8px;
border: 1px solid var(--l1-border);
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: var(--spacing-4) var(--spacing-5) 0;
}
.contextTags {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: var(--spacing-4) var(--spacing-5) 0;
}
.contextTag {
@@ -99,78 +91,86 @@
white-space: nowrap;
}
.row {
display: flex;
align-items: center;
gap: 8px;
}
.composer {
position: relative;
padding: calc(var(--spacing-4) + 1px) var(--spacing-8);
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%);
}
}
.footer {
display: flex;
align-items: center;
justify-content: flex-end;
padding: var(--spacing-2) var(--spacing-5) var(--spacing-4);
justify-content: space-between;
gap: 8px;
}
.actions {
.leftActions,
.rightActions {
display: flex;
align-items: center;
gap: 8px;
--button-height: 28px;
--button-width: 28px;
--button-max-width: 28px;
--button-border-radius: var(--radius-round);
}
// 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;
}
.attachBtn {
color: var(--l3-foreground);
}
.contextBtn {
flex-shrink: 0;
gap: 6px;
border-style: dashed !important;
padding-inline: 12px !important;
}
.textarea {
display: block;
width: 100%;
padding: 0;
background: transparent;
border: none;
outline: none;
resize: none;
color: var(--l1-foreground);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
font-size: 12px;
line-height: 1.5;
overflow-y: auto;
font-family: inherit;
// ComposerCaret draws the caret.
caret-color: transparent;
@include scrollbar(0.2rem);
&::placeholder {
color: var(--l2-foreground);
color: var(--l3-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;
margin: 0 var(--spacing-5);
width: 100%;
padding: 6px 8px;
font-size: 11px;
font-weight: 500;
@@ -180,9 +180,24 @@
border-radius: var(--radius-2);
}
.sendBtn {
flex-shrink: 0;
border-radius: var(--radius-2);
&.stop {
background: var(--accent-cherry) !important;
border-color: var(--accent-cherry) !important;
&:hover {
opacity: 0.85;
}
}
}
.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);
@@ -323,3 +338,75 @@
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;
}
}

View File

@@ -11,8 +11,11 @@ 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,
@@ -28,29 +31,34 @@ import type {
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 {
ArrowUp,
AtSign,
Mic,
Plus,
Search,
Send,
Square,
TriangleAlert,
X,
} from '@signozhq/icons';
import styles from './ChatInput.module.scss';
import ComposerCaret from './ComposerCaret/ComposerCaret';
import ContextPickerEmptyState from './ContextPickerEmptyState';
import EdgeSweep from './EdgeSweep/EdgeSweep';
import NozPeek from './NozPeek/NozPeek';
import {
CONTEXT_CATEGORIES,
CONTEXT_CATEGORY_ICONS,
@@ -66,14 +74,7 @@ interface ChatInputProps {
onCancel?: () => void;
disabled?: boolean;
disabledTooltip?: string;
placeholder?: string;
/** Focuses the textarea each time it changes. */
focusRequest?: number;
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
@@ -170,6 +171,8 @@ 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
@@ -239,18 +242,13 @@ export default function ChatInput({
onCancel,
disabled,
disabledTooltip,
placeholder = 'Ask Noz…',
focusRequest,
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<
@@ -290,6 +288,8 @@ 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);
@@ -343,6 +343,7 @@ export default function ChatInput({
const next =
text.slice(0, mentionRange.start) + text.slice(mentionRange.end);
setText(next);
committedTextRef.current = next;
setMentionRange(null);
}
},
@@ -355,6 +356,7 @@ export default function ChatInput({
(prompt: string) => {
const next = capText(prompt);
setText(next);
committedTextRef.current = next;
setMentionRange(null);
setPickerSearchQuery('');
setIsContextPickerOpen(false);
@@ -445,12 +447,6 @@ export default function ChatInput({
textareaRef.current?.focus();
}, []);
useEffect(() => {
if (focusRequest) {
textareaRef.current?.focus();
}
}, [focusRequest]);
// Auto-grow the textarea so long prompts aren't trapped in a 2-line
// scrolling porthole. Reset to `auto` first to let the field shrink back
// down when the user deletes content, then snap to scrollHeight capped at
@@ -501,6 +497,7 @@ export default function ChatInput({
contexts.length > 0 ? contexts : undefined,
);
setText('');
committedTextRef.current = '';
setPendingFiles([]);
setSelectedContexts([]);
textareaRef.current?.focus();
@@ -535,6 +532,209 @@ 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
@@ -700,12 +900,7 @@ export default function ChatInput({
const showTextWarning = currentLength >= WARNING_THRESHOLD;
return (
<div
className={cx(styles.input, { [styles.compact]: isCompact })}
ref={inputRootRef}
>
<EdgeSweep startedAt={streamStartedAt} />
{showNozPeek && <NozPeek />}
<div className={styles.input} ref={inputRootRef}>
{pendingFiles.length > 0 && (
<div className={styles.attachments}>
{pendingFiles.map((f) => (
@@ -788,20 +983,20 @@ export default function ChatInput({
<textarea
ref={textareaRef}
className={styles.textarea}
data-testid="ai-chat-input-textarea"
placeholder={placeholder}
placeholder="Ask anything… (Shift+Enter for new line)"
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={2}
rows={3}
/>
<ComposerCaret textareaRef={textareaRef} value={text} />
</div>
{showTextWarning && (
<div className={styles.charWarning} role="status">
@@ -814,7 +1009,7 @@ export default function ChatInput({
)}
<div className={styles.footer}>
<div className={styles.actions}>
<div className={styles.leftActions}>
<Popover
open={isContextPickerOpen}
onOpenChange={(open): void => {
@@ -825,26 +1020,22 @@ export default function ChatInput({
}
}}
>
<Tooltip title="Add context">
<PopoverTrigger asChild>
<Button
disabledTooltip={disabledTooltip}
variant="ghost"
color="secondary"
size="sm"
icon
disabled={disabled}
onClick={(): void => {
setActiveContextCategory('Dashboards');
setPickerSearchQuery('');
}}
testId="ai-chat-input-add-context"
aria-label="Add context"
>
<AtSign size={14} />
</Button>
</PopoverTrigger>
</Tooltip>
<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>
<PopoverContent
className={styles.contextPopover}
side="top"
@@ -908,7 +1099,6 @@ export default function ChatInput({
<Input
type="text"
placeholder={`Search ${activeContextCategory.toLowerCase()}…`}
testId="ai-context-search"
className={styles.contextPopoverSearchInput}
value={pickerSearchQuery}
onChange={(e): void => setPickerSearchQuery(e.target.value)}
@@ -974,18 +1164,82 @@ 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="sm"
size="md"
icon
color="danger"
onClick={onCancel}
aria-label="Stop generating"
>
<Square size={14} fill="currentColor" />
<Square size={10} fill="currentColor" strokeWidth={0} />
</Button>
</Tooltip>
) : (
@@ -993,14 +1247,14 @@ export default function ChatInput({
<Button
disabledTooltip={disabled ? disabledTooltip : 'Type a message first'}
variant="solid"
size="sm"
size="md"
icon
color="primary"
onClick={handleSend}
onClick={isListening ? handleStopAndSend : handleSend}
disabled={disabled || (!text.trim() && pendingFiles.length === 0)}
aria-label="Send message"
>
<ArrowUp size={14} />
<Send size={14} />
</Button>
</Tooltip>
)}

View File

@@ -1,54 +0,0 @@
.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;
}
}

View File

@@ -1,51 +0,0 @@
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 })}
data-testid="ai-composer-caret"
style={{
transform: `translate(${caret.left}px, ${caret.top}px)`,
height: caret.height,
}}
aria-hidden
/>
)}
</>
);
}

View File

@@ -1,114 +0,0 @@
import { useRef, useState } from 'react';
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
import { getCaretCoordinates } from 'utils/getCaretCoordinates';
import ComposerCaret from '../ComposerCaret';
jest.mock('utils/getCaretCoordinates');
const CHAR_WIDTH = 8;
function Composer(): JSX.Element {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [value, setValue] = useState('');
return (
<>
<textarea
ref={textareaRef}
data-testid="composer"
value={value}
onChange={(event): void => setValue(event.target.value)}
onKeyDown={(event): void => {
if (event.key === 'Enter') {
event.preventDefault();
setValue('');
}
}}
/>
<button type="button" data-testid="elsewhere">
Elsewhere
</button>
<ComposerCaret textareaRef={textareaRef} value={value} />
</>
);
}
describe('ComposerCaret', () => {
beforeEach(() => {
// jsdom has no layout; the caret only shows inside the textarea's visible height.
jest
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
.mockImplementation(function offsetHeight(this: HTMLElement) {
return this instanceof HTMLTextAreaElement ? 40 : 0;
});
// One line of fixed-width text, so the caret's left tracks its index.
jest.mocked(getCaretCoordinates).mockImplementation((_, position) => ({
left: position * CHAR_WIDTH,
top: 0,
height: 16,
}));
});
afterEach(() => {
jest.restoreAllMocks();
});
it('draws its caret while the composer has focus', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<Composer />);
await user.click(screen.getByTestId('composer'));
expect(screen.getByTestId('ai-composer-caret')).toBeInTheDocument();
});
it('hides its caret once the composer loses focus', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<Composer />);
await user.click(screen.getByTestId('composer'));
await user.click(screen.getByTestId('elsewhere'));
expect(screen.queryByTestId('ai-composer-caret')).not.toBeInTheDocument();
});
it('hides its caret while text is selected', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<Composer />);
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
await user.type(composer, 'checkout latency');
composer.setSelectionRange(0, 8);
// jsdom fires no selectionchange for setSelectionRange.
fireEvent(document, new Event('selectionchange'));
expect(screen.queryByTestId('ai-composer-caret')).not.toBeInTheDocument();
});
it('moves its caret when code changes the text', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<Composer />);
await user.type(screen.getByTestId('composer'), 'checkout');
expect(screen.getByTestId('ai-composer-caret')).toHaveStyle({
transform: `translate(${8 * CHAR_WIDTH}px, 0px)`,
});
await user.keyboard('{Enter}');
expect(screen.getByTestId('ai-composer-caret')).toHaveStyle({
transform: 'translate(0px, 0px)',
});
});
it('hides its caret once the composer scrolls it out of view', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<Composer />);
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
await user.type(composer, 'checkout latency');
composer.scrollTop = 30;
fireEvent.scroll(composer);
expect(screen.queryByTestId('ai-composer-caret')).not.toBeInTheDocument();
});
});

View File

@@ -1,11 +0,0 @@
export interface CaretBox {
left: number;
top: number;
height: number;
}
export interface CaretTrail extends CaretBox {
id: number;
width: number;
faint: boolean;
}

View File

@@ -1,159 +0,0 @@
import {
RefObject,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from 'react';
import { getCaretCoordinates } from 'utils/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 };
}

View File

@@ -1,74 +0,0 @@
// 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-primary) 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%);
}
}

View File

@@ -1,48 +0,0 @@
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 })}
data-testid="ai-input-edge-sweep"
onTransitionEnd={(): void => {
if (startedAt === null) {
setRun(null);
}
}}
aria-hidden
>
{run && (
<div
key={run.startedAt}
className={styles.line}
data-testid="ai-input-edge-sweep-line"
style={{ animationDelay: `${-run.elapsedMs}ms` }}
/>
)}
</div>
);
}

View File

@@ -1,41 +0,0 @@
import { render, screen } from 'tests/test-utils';
import EdgeSweep from '../EdgeSweep';
const NOW = 10_000;
describe('EdgeSweep', () => {
beforeEach(() => {
jest.spyOn(Date, 'now').mockReturnValue(NOW);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('stays still while Noz is idle', () => {
render(<EdgeSweep startedAt={null} />);
expect(
screen.queryByTestId('ai-input-edge-sweep-line'),
).not.toBeInTheDocument();
});
it('picks up a reply already under way instead of restarting', () => {
render(<EdgeSweep startedAt={NOW - 1500} />);
expect(screen.getByTestId('ai-input-edge-sweep-line')).toHaveStyle({
animationDelay: '-1500ms',
});
});
it('restarts from the left for the next reply', () => {
const { rerender } = render(<EdgeSweep startedAt={NOW - 1500} />);
rerender(<EdgeSweep startedAt={NOW} />);
expect(screen.getByTestId('ai-input-edge-sweep-line')).toHaveStyle({
animationDelay: '0ms',
});
});
});

View File

@@ -1,109 +0,0 @@
// 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);
}
}

View File

@@ -1,67 +0,0 @@
import { useRef } from 'react';
import {
NOZ_BODY,
NOZ_COLORS,
NOZ_EYE,
NOZ_HAT_PATH,
NOZ_PUPIL_PATH,
} from 'components/Noz/Noz.constants';
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} data-testid="ai-noz-peek" aria-hidden>
<svg
className={styles.bodySvg}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect {...NOZ_BODY} fill={NOZ_COLORS.body} />
<g className={styles.head}>
<circle ref={eyeRef} {...NOZ_EYE} fill={NOZ_COLORS.eye} />
<g
ref={pupilRef}
className={styles.pupil}
data-testid="ai-noz-peek-pupil"
>
<path d={NOZ_PUPIL_PATH} fill={NOZ_COLORS.pupil} />
</g>
<path d={NOZ_HAT_PATH} fill={NOZ_COLORS.hat} />
</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={NOZ_COLORS.body}
/>
<rect
x="30.4775"
width="3.52294"
height="6.16514"
rx="1.46789"
fill={NOZ_COLORS.body}
/>
</svg>
</div>
</>
);
}

View File

@@ -1,72 +0,0 @@
import { render, screen, userEvent } from 'tests/test-utils';
import NozPeek from '../NozPeek';
describe('NozPeek', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('keeps its eye still while it is still climbing over the edge', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
render(<NozPeek />);
await user.pointer({
target: document.body,
coords: { clientX: 200, clientY: 0 },
});
expect(screen.getByTestId('ai-noz-peek-pupil').style.transform).toBe('');
});
it('follows the cursor with its eye once it has settled', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
render(<NozPeek />);
jest.advanceTimersByTime(1900);
await user.pointer({
target: document.body,
coords: { clientX: 200, clientY: 0 },
});
expect(screen.getByTestId('ai-noz-peek-pupil').style.transform).toBe(
'translate(1.250px, 0.000px)',
);
});
it('keeps its eye still with reduced motion, even once it has settled', async () => {
jest
.spyOn(window, 'matchMedia')
.mockImplementation((query: string): MediaQueryList => ({
matches: query === '(prefers-reduced-motion: reduce)',
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}));
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
render(<NozPeek />);
jest.advanceTimersByTime(1900);
await user.pointer({
target: document.body,
coords: { clientX: 200, clientY: 0 },
});
expect(screen.getByTestId('ai-noz-peek-pupil').style.transform).toBe('');
});
});

View File

@@ -1,44 +0,0 @@
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(() => {
// With reduced motion Noz stays still, so the eye does not follow the cursor.
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return undefined;
}
let isSettled = false;
const timer = window.setTimeout(() => {
isSettled = true;
}, 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]);
}

View File

@@ -23,6 +23,24 @@ jest.mock('hooks/useQueryService', () => ({
}),
}));
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
import ChatInput from '../ChatInput';

View File

@@ -1,26 +0,0 @@
import { render, screen } from 'tests/test-utils';
import ChatInput from '../ChatInput';
describe('ChatInput composer', () => {
it('asks the user to ask Noz', () => {
render(<ChatInput onSend={jest.fn()} />);
expect(screen.getByTestId('ai-chat-input-textarea')).toHaveAttribute(
'placeholder',
'Ask Noz…',
);
});
it('focuses the textarea when asked again', () => {
const { rerender } = render(
<ChatInput onSend={jest.fn()} focusRequest={0} />,
);
const textarea = screen.getByTestId('ai-chat-input-textarea');
textarea.blur();
rerender(<ChatInput onSend={jest.fn()} focusRequest={1} />);
expect(textarea).toHaveFocus();
});
});

View File

@@ -3,7 +3,7 @@ import { render, screen, userEvent } from 'tests/test-utils';
import ChatInput from '../ChatInput';
function getComposer(): HTMLTextAreaElement {
return screen.getByTestId<HTMLTextAreaElement>('ai-chat-input-textarea');
return screen.getByPlaceholderText(/Ask anything/i) as HTMLTextAreaElement;
}
describe('ChatInput — @ mention trigger', () => {
@@ -13,7 +13,7 @@ describe('ChatInput — @ mention trigger', () => {
await userEvent.type(getComposer(), 'check @');
await expect(
screen.findByTestId('ai-context-search'),
screen.findByPlaceholderText(/search dashboards/i),
).resolves.toBeInTheDocument();
});
@@ -23,6 +23,8 @@ describe('ChatInput — @ mention trigger', () => {
await userEvent.type(getComposer(), 'mail user@example.com');
expect(getComposer()).toHaveValue('mail user@example.com');
expect(screen.queryByTestId('ai-context-search')).not.toBeInTheDocument();
expect(
screen.queryByPlaceholderText(/search dashboards/i),
).not.toBeInTheDocument();
});
});

View File

@@ -29,6 +29,26 @@ 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';
@@ -38,7 +58,7 @@ function renderChatInput(): void {
}
function getComposer(): HTMLTextAreaElement {
return screen.getByTestId<HTMLTextAreaElement>('ai-chat-input-textarea');
return screen.getByPlaceholderText(/Ask anything/i) as HTMLTextAreaElement;
}
describe('ChatInput — empty-state CTA prefill flow', () => {
@@ -49,8 +69,11 @@ describe('ChatInput — empty-state CTA prefill flow', () => {
await userEvent.type(getComposer(), 'show me something');
// Open the picker and search for an entity that does not exist.
await userEvent.click(screen.getByTestId('ai-chat-input-add-context'));
await userEvent.type(await screen.findByTestId('ai-context-search'), 'chk');
await userEvent.click(screen.getByRole('button', { name: /add context/i }));
await userEvent.type(
await screen.findByPlaceholderText(/search dashboards/i),
'chk',
);
const cta = await screen.findByTestId('ai-context-empty-cta-Dashboards');
expect(cta).toHaveTextContent('Create a dashboard for "chk"');
@@ -73,7 +96,7 @@ describe('ChatInput — empty-state CTA prefill flow', () => {
it('seeds only the prefix (with trailing space) in the onboarding case', async () => {
renderChatInput();
await userEvent.click(screen.getByTestId('ai-chat-input-add-context'));
await userEvent.click(screen.getByRole('button', { name: /add context/i }));
const cta = await screen.findByTestId('ai-context-empty-cta-Dashboards');
expect(cta).toHaveTextContent('Ask me to create one');

View File

@@ -1,16 +0,0 @@
import './__fixtures__/speechRecognitionSupport';
import { render, screen } from 'tests/test-utils';
import ChatInput from '../ChatInput';
describe('ChatInput without voice input', () => {
it('offers no voice input, even where the browser supports speech', () => {
render(<ChatInput onSend={jest.fn()} />);
// The removed mic button never had a test ID, so it is looked up by its label.
expect(
screen.queryByRole('button', { name: /voice input/i }),
).not.toBeInTheDocument();
});
});

View File

@@ -1,5 +0,0 @@
// Imported before ChatInput: speech support was read once, at module load.
Object.defineProperty(window, 'webkitSpeechRecognition', {
configurable: true,
value: class SpeechRecognitionStub {},
});

View File

@@ -37,11 +37,6 @@
.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 {
@@ -55,11 +50,9 @@
max-width: 100%;
.user & {
padding: var(--spacing-4) var(--spacing-6);
border-radius: var(--radius-3);
background: var(--l3-background-60);
color: var(--l1-foreground);
font-size: var(--periscope-font-size-base);
background: var(--accent-primary);
color: var(--primary-foreground);
border-bottom-right-radius: var(--radius-2);
}
.assistant & {

View File

@@ -141,10 +141,7 @@ export default function MessageBubble({
[styles.compact]: isCompact,
},
);
const bodyClass = cx(styles.body, {
[styles.compact]: isCompact,
[styles.fullPage]: variant === 'page',
});
const bodyClass = cx(styles.body, { [styles.compact]: isCompact });
return (
<div className={messageClass} data-testid={`ai-message-${message.id}`}>

View File

@@ -49,7 +49,7 @@ export default function UserMessageActions({
onClick={handleCopy}
aria-label={copied ? 'Copied' : 'Copy message'}
>
{copied ? <Check size={14} /> : <Copy size={14} />}
{copied ? <Check size={12} /> : <Copy size={12} />}
</Button>
</Tooltip>
</div>

View File

@@ -1,133 +0,0 @@
@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: calc(var(--spacing-56) * 3);
// 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: var(--line-height-20);
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: var(--radius-3);
--button-font-weight: var(--font-weight-normal);
--button-size-line-height: var(--line-height-20);
--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: var(--radius-3);
overflow: hidden;
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
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: var(--radius-3);
}
}

View File

@@ -1,86 +0,0 @@
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 DotGrid from 'components/DotGrid/DotGrid';
import { AIAssistantEvents, SuggestedPromptCategory } from '../../../events';
import { useVariant } from '../../../VariantContext';
import { EMPTY_STATE_CHIPS_FALLBACK } from '../emptyStateChipsFallback';
import { useEmptyStateChips } from '../useEmptyStateChips';
import styles from './EmptyState.module.scss';
interface EmptyStateProps {
onSendSuggestedPrompt: (text: string) => void;
onSnakeGameChange?: (isPlaying: boolean) => void;
}
/** A new chat: the dot grid, Noz's intro and the suggested prompts. */
export default function EmptyState({
onSendSuggestedPrompt,
onSnakeGameChange,
}: EmptyStateProps): JSX.Element {
const isCompact = useVariant() === 'panel';
const { chips: emptyStateChips, isLoading: areChipsLoading } =
useEmptyStateChips(true);
return (
<div className={cx(styles.empty, { [styles.compact]: isCompact })}>
<DotGrid className={styles.dotGrid} onGameChange={onSnakeGameChange} />
<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. */}
{areChipsLoading &&
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>
);
}

View File

@@ -1,35 +0,0 @@
import { render, screen, userEvent } from 'tests/test-utils';
import { EMPTY_STATE_CHIPS_FALLBACK } from '../../emptyStateChipsFallback';
import { useEmptyStateChips } from '../../useEmptyStateChips';
import EmptyState from '../EmptyState';
jest.mock('../../useEmptyStateChips');
const mockChips = jest.mocked(useEmptyStateChips);
describe('EmptyState', () => {
it('holds a placeholder for every prompt while they load', () => {
mockChips.mockReturnValue({ chips: [], isLoading: true });
render(<EmptyState onSendSuggestedPrompt={jest.fn()} />);
expect(screen.getAllByTestId('empty-state-chip-skeleton')).toHaveLength(
EMPTY_STATE_CHIPS_FALLBACK.length,
);
});
it('sends a suggestion when it is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onSend = jest.fn();
mockChips.mockReturnValue({
chips: [{ id: 'slow_queries', text: 'Find slow database queries' }],
isLoading: false,
});
render(<EmptyState onSendSuggestedPrompt={onSend} />);
await user.click(screen.getByTestId('empty-state-chip-slow_queries'));
expect(onSend).toHaveBeenCalledWith('Find slow database queries');
});
});

View File

@@ -15,8 +15,64 @@
}
}
// As wide as the full-page input; the extra 32px is the rows' own gutters.
.row.fullPage {
max-width: calc(var(--noz-page-column) + 32px);
margin: 0 auto;
.empty {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 32px 24px;
gap: 8px;
text-align: center;
}
.emptyIcon {
margin-bottom: 4px;
}
.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);
}
}

View File

@@ -1,19 +1,18 @@
import { useCallback, useEffect, useRef } from 'react';
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
import cx from 'classnames';
import Noz from 'components/Noz/Noz';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';
import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Message, StreamingEventItem } from '../../types';
import { useVariant } from '../../VariantContext';
import MessageBubble from '../MessageBubble';
import StreamingMessage from '../StreamingMessage';
import EmptyState from './EmptyState/EmptyState';
import styles from './VirtualizedMessages.module.scss';
import { useEmptyStateChips } from './useEmptyStateChips';
const EMPTY_EVENTS: StreamingEventItem[] = [];
@@ -27,8 +26,6 @@ interface VirtualizedMessagesProps {
* page/mode/context attribution as a normal send.
*/
onSendSuggestedPrompt: (text: string) => void;
/** A Snake game on the empty state's dot grid started or ended. */
onSnakeGameChange?: (isPlaying: boolean) => void;
}
export default function VirtualizedMessages({
@@ -36,7 +33,6 @@ export default function VirtualizedMessages({
messages,
isStreaming,
onSendSuggestedPrompt,
onSnakeGameChange,
}: VirtualizedMessagesProps): JSX.Element {
const regenerateAssistantMessage = useAIAssistantStore(
(s) => s.regenerateAssistantMessage,
@@ -77,7 +73,6 @@ export default function VirtualizedMessages({
// the user was scrolled — sending a message and not seeing it is worse
// than the anti-yank guarantee.
const lastSeenUserMessageIdRef = useRef<string | null>(null);
const isFullPage = useVariant() === 'page';
const handleRegenerate = useCallback(
(messageId: string): void => {
@@ -160,13 +155,37 @@ export default function VirtualizedMessages({
const showStreamingSlot =
isStreaming || Boolean(pendingApproval) || Boolean(pendingClarification);
const isEmptyState = messages.length === 0 && !showStreamingSlot;
const { chips: emptyStateChips } = useEmptyStateChips(isEmptyState);
if (isEmptyState) {
return (
<EmptyState
onSendSuggestedPrompt={onSendSuggestedPrompt}
onSnakeGameChange={onSnakeGameChange}
/>
<div className={styles.empty}>
<div className={`${styles.emptyIcon} noz-wave`}>
<Noz size={48} />
</div>
<h3 className={styles.emptyTitle}>Noz</h3>
<p className={styles.emptySubtitle}>
Ask questions about your traces, logs, metrics, and infrastructure.
</p>
<div className={styles.suggestions}>
{emptyStateChips.map((chip) => (
<div
key={chip.id}
className={styles.suggestion}
onClick={(): void => {
void logEvent(AIAssistantEvents.SuggestedPromptClicked, {
promptId: chip.id,
category: SuggestedPromptCategory.EmptyState,
});
onSendSuggestedPrompt(chip.text);
}}
data-testid={`empty-state-chip-${chip.id}`}
>
{chip.text}
</div>
))}
</div>
</div>
);
}
@@ -185,41 +204,36 @@ export default function VirtualizedMessages({
atBottomThreshold={64}
initialTopMostItemIndex={Math.max(0, totalCount - 1)}
itemContent={(index): JSX.Element => {
const rowClass = cx(styles.row, { [styles.fullPage]: isFullPage });
if (index < messages.length) {
const msg = messages[index];
const isLastAssistant =
msg.role === 'assistant' &&
messages.slice(index + 1).every((m) => m.role !== 'assistant');
return (
<div className={rowClass}>
<MessageBubble
message={msg}
onRegenerate={
isLastAssistant && !showStreamingSlot
? (): void => handleRegenerate(msg.id)
: undefined
}
onRetry={
msg.isError && isLastAssistant && !showStreamingSlot
? handleRetry
: undefined
}
isLastAssistant={isLastAssistant}
/>
</div>
<MessageBubble
message={msg}
onRegenerate={
isLastAssistant && !showStreamingSlot
? (): void => handleRegenerate(msg.id)
: undefined
}
onRetry={
msg.isError && isLastAssistant && !showStreamingSlot
? handleRetry
: undefined
}
isLastAssistant={isLastAssistant}
/>
);
}
return (
<div className={rowClass}>
<StreamingMessage
conversationId={conversationId}
events={streamingEvents}
status={streamingStatus}
pendingApproval={pendingApproval}
pendingClarification={pendingClarification}
/>
</div>
<StreamingMessage
conversationId={conversationId}
events={streamingEvents}
status={streamingStatus}
pendingApproval={pendingApproval}
pendingClarification={pendingClarification}
/>
);
}}
/>

View File

@@ -11,13 +11,12 @@ import { EMPTY_STATE_CHIPS_FALLBACK } from './emptyStateChipsFallback';
interface UseEmptyStateChipsResult {
chips: ChipDTO[];
isLoading: boolean;
}
export function useEmptyStateChips(enabled: boolean): UseEmptyStateChipsResult {
const pageType = useResolvePageType();
const { data, isError, isLoading } = useQuery(
const { data, isError } = useQuery(
[REACT_QUERY_KEY.AI_ASSISTANT_EMPTY_STATE_CHIPS, pageType],
({ signal }) => getEmptyStateChips(pageType, signal),
{ enabled },
@@ -30,5 +29,5 @@ export function useEmptyStateChips(enabled: boolean): UseEmptyStateChipsResult {
return data ?? [];
}, [data, isError]);
return { chips, isLoading };
return { chips };
}

View File

@@ -4,6 +4,58 @@
* requested, Limit hit) are not declared here — they fire from the AI service.
*/
export interface BrowserInfo {
browserName: string;
browserVersion: string;
}
type NavigatorWithBrandHints = Navigator & {
userAgentData?: { brands: { brand: string; version: string }[] };
brave?: { isBrave: () => Promise<boolean> };
};
/**
* We mainly need to distinguish Chrome / Edge (Speech API works) from Chromium
* derivatives (no Google API key → voice fails with `network`). UA sniffing is
* the source of truth for derivative identification; `userAgentData` is used
* only as a fast happy path for Chrome / Edge. Brave needs its own probe — it
* advertises Chrome in both UA and brand hints.
*/
export function getBrowserInfo(): BrowserInfo {
if (typeof navigator === 'undefined') {
return { browserName: 'unknown', browserVersion: 'unknown' };
}
const nav = navigator as NavigatorWithBrandHints;
const ua = nav.userAgent;
// Order matters: derivatives put "Chrome" in their UA; Chrome puts "Safari".
const matchers: { name: string; re: RegExp }[] = [
{ name: 'Edge', re: /Edg(?:e|A|iOS)?\/([\d.]+)/ },
{ name: 'Opera', re: /OPR\/([\d.]+)/ },
{ name: 'Vivaldi', re: /Vivaldi\/([\d.]+)/ },
{ name: 'Chrome', re: /Chrome\/([\d.]+)/ },
{ name: 'Firefox', re: /Firefox\/([\d.]+)/ },
{ name: 'Safari', re: /Version\/([\d.]+).*Safari/ },
];
let browserName = 'unknown';
let browserVersion = 'unknown';
for (const { name, re } of matchers) {
const m = ua.match(re);
if (m) {
browserName = name;
browserVersion = m[1];
break;
}
}
// Brave hides as Chrome in UA + brand hints; its probe is the only tell.
if (nav.brave?.isBrave) {
browserName = 'Brave';
}
return { browserName, browserVersion };
}
export const SuggestedPromptCategory = {
FollowUp: 'follow_up',
EmptyState: 'empty_state',
@@ -24,6 +76,15 @@ export const AIAssistantOpenSource = {
export type AIAssistantOpenSource =
(typeof AIAssistantOpenSource)[keyof typeof AIAssistantOpenSource];
// `source` attribute on the `VoiceInputUsed` event — which surface initiated
// the recording.
export const VoiceInputSource = {
Button: 'button',
Shortcut: 'shortcut',
} as const;
export type VoiceInputSource =
(typeof VoiceInputSource)[keyof typeof VoiceInputSource];
export enum AIAssistantEvents {
Opened = 'AI Assistant: Opened',
MessageSent = 'AI Assistant: Message sent',
@@ -37,5 +98,7 @@ export enum AIAssistantEvents {
DocOpened = 'AI Assistant: Doc opened',
ApplyFilterClicked = 'AI Assistant: Apply filter clicked',
ThreadOpenedFromHistory = 'AI Assistant: Thread opened from history',
VoiceInputUsed = 'AI Assistant: Voice input used',
VoiceInputFailed = 'AI Assistant: Voice input failed',
NewChatClicked = 'AI Assistant: New chat clicked',
}

View File

@@ -1,44 +0,0 @@
import { renderHook } from 'tests/test-utils';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import type { Conversation } from '../../types';
import { NEW_CHAT_TITLE, useActiveChatTitle } from '../useActiveChatTitle';
const initialState = useAIAssistantStore.getState();
const open = (conversation: Conversation): void => {
useAIAssistantStore.setState({
conversations: { [conversation.id]: conversation },
activeConversationId: conversation.id,
});
};
describe('useActiveChatTitle', () => {
afterEach(() => {
useAIAssistantStore.setState(initialState, true);
});
it('is the open chat’s title', () => {
open({ id: 'a', title: 'Checkout p99', messages: [], createdAt: 0 });
const { result } = renderHook(() => useActiveChatTitle());
expect(result.current).toBe('Checkout p99');
});
it('is "New chat" until the chat has a title', () => {
open({ id: 'a', messages: [], createdAt: 0 });
const { result } = renderHook(() => useActiveChatTitle());
expect(result.current).toBe(NEW_CHAT_TITLE);
});
it('is empty while a restored chat loads, rather than flashing "New chat"', () => {
open({ id: 'a', messages: [], createdAt: 0, isHydrating: true });
const { result } = renderHook(() => useActiveChatTitle());
expect(result.current).toBeNull();
});
});

View File

@@ -1,16 +0,0 @@
import { useAIAssistantStore } from '../store/useAIAssistantStore';
export const NEW_CHAT_TITLE = 'New chat';
/** The open chat's title for a header: "New chat" until it has one, null while a restored chat loads. */
export function useActiveChatTitle(): string | null {
return useAIAssistantStore((s) => {
const conversation = s.activeConversationId
? s.conversations[s.activeConversationId]
: undefined;
if (conversation?.title) {
return conversation.title;
}
return conversation?.isHydrating ? null : NEW_CHAT_TITLE;
});
}

View File

@@ -0,0 +1,268 @@
import { useCallback, useEffect, useRef, useState } from 'react';
// ── Web Speech API types (not yet in lib.dom.d.ts) ────────────────────────────
interface SpeechRecognitionResult {
readonly length: number;
readonly isFinal: boolean;
[index: number]: { transcript: string; confidence: number };
}
interface SpeechRecognitionResultList {
readonly length: number;
[index: number]: SpeechRecognitionResult;
}
interface SpeechRecognitionEvent extends Event {
readonly resultIndex: number;
readonly results: SpeechRecognitionResultList;
}
interface SpeechRecognitionErrorEvent extends Event {
readonly error: string;
readonly message: string;
}
interface ISpeechRecognition extends EventTarget {
lang: string;
continuous: boolean;
interimResults: boolean;
onstart: (() => void) | null;
onend: (() => void) | null;
onresult: ((event: SpeechRecognitionEvent) => void) | null;
onerror: ((event: SpeechRecognitionErrorEvent) => void) | null;
start(): void;
stop(): void;
abort(): void;
}
type SpeechRecognitionConstructor = new () => ISpeechRecognition;
// ── Vendor-prefix shim for Safari / older browsers ────────────────────────────
// Some hardened/enterprise browsers install a getter
// on window.SpeechRecognition that THROWS on access ("Web Speech API is disabled
// due to your security policy") instead of leaving the property undefined.
// Because this resolves at module-evaluation time, an uncaught throw here aborts
// the entire bundle and the app renders a blank page. Read defensively so a
// throwing getter degrades to "unsupported" rather than crashing the app.
function resolveSpeechRecognitionAPI(): SpeechRecognitionConstructor | null {
if (typeof window === 'undefined') {
return null;
}
try {
return (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).SpeechRecognition ??
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).webkitSpeechRecognition ??
null
);
} catch {
return null;
}
}
const SpeechRecognitionAPI: SpeechRecognitionConstructor | null =
resolveSpeechRecognitionAPI();
export type SpeechRecognitionError =
| 'not-supported'
| 'not-allowed'
| 'no-speech'
| 'network'
| 'unknown';
export type MicrophonePermission = 'prompt' | 'granted' | 'denied';
interface UseSpeechRecognitionOptions {
onError?: (error: SpeechRecognitionError) => void;
/**
* Called directly from browser recognition events — no React state intermediary.
* `isFinal=false` → interim (live preview), `isFinal=true` → committed text.
*/
onTranscript?: (text: string, isFinal: boolean) => void;
lang?: string;
}
interface UseSpeechRecognitionReturn {
isListening: boolean;
isSupported: boolean;
/**
* Browser microphone permission. Starts as `'prompt'` (or whatever the
* Permissions API reports on mount), flips to `'granted'` once a session
* successfully starts, and to `'denied'` if the user blocks access.
*/
permission: MicrophonePermission;
start: () => void;
stop: () => void;
/** Stop recognition and discard any pending interim text (no onTranscript call). */
discard: () => void;
}
export function useSpeechRecognition({
onError,
onTranscript,
lang = 'en-US',
}: UseSpeechRecognitionOptions = {}): UseSpeechRecognitionReturn {
const [isListening, setIsListening] = useState(false);
const [permission, setPermission] = useState<MicrophonePermission>('prompt');
const recognitionRef = useRef<ISpeechRecognition | null>(null);
const isDiscardingRef = useRef(false);
const isSupported = SpeechRecognitionAPI !== null;
// Seed `permission` from the Permissions API and keep it in sync with
// external changes (e.g. user resets the site permission in browser
// settings). Falls back silently if the API is unavailable (Safari) —
// the recognition lifecycle below will still flip the state on grant
// or deny.
useEffect(() => {
if (typeof navigator === 'undefined' || !navigator.permissions?.query) {
return undefined;
}
let status: PermissionStatus | null = null;
let cancelled = false;
const handleChange = (): void => {
if (status) {
setPermission(status.state as MicrophonePermission);
}
};
navigator.permissions
.query({ name: 'microphone' as PermissionName })
.then((permStatus) => {
if (cancelled) {
return;
}
status = permStatus;
setPermission(permStatus.state as MicrophonePermission);
permStatus.addEventListener('change', handleChange);
})
.catch(() => {
// Permissions API rejected (some browsers don't recognise the
// 'microphone' descriptor) — leave permission as 'prompt'.
});
return (): void => {
cancelled = true;
status?.removeEventListener('change', handleChange);
};
}, []);
// Always-current refs — updated synchronously on every render so closures
// inside recognition event handlers always call the latest version.
const onErrorRef = useRef(onError);
onErrorRef.current = onError;
const onTranscriptRef = useRef(onTranscript);
onTranscriptRef.current = onTranscript;
const stop = useCallback(() => {
recognitionRef.current?.stop();
}, []);
const discard = useCallback(() => {
isDiscardingRef.current = true;
recognitionRef.current?.stop();
}, []);
// eslint-disable-next-line sonarjs/cognitive-complexity
const start = useCallback(() => {
if (!isSupported) {
onErrorRef.current?.('not-supported');
return;
}
// If already listening, stop
if (recognitionRef.current) {
recognitionRef.current.stop();
return;
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const recognition = new SpeechRecognitionAPI!();
recognition.lang = lang;
recognition.continuous = true; // keep listening until user clicks stop
recognition.interimResults = true; // live updates while speaking
// Track the last interim text so we can commit it as final in onend —
// Chrome often skips the isFinal result when stop() is called manually.
let pendingInterim = '';
recognition.onstart = (): void => {
setIsListening(true);
setPermission('granted');
};
recognition.onresult = (event): void => {
// Browser fires a final `onresult` after `recognition.stop()` —
// when the caller invoked `discard()` (e.g. stop-and-send) the
// React state has already been cleared / the message has
// already been dispatched, so a late transcript would
// repopulate the textarea. Drop these events while discarding.
if (isDiscardingRef.current) {
pendingInterim = '';
return;
}
let interim = '';
let finalText = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const text = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalText += text;
} else {
interim += text;
}
}
if (finalText) {
pendingInterim = '';
onTranscriptRef.current?.(finalText, true);
} else if (interim) {
pendingInterim = interim;
onTranscriptRef.current?.(interim, false);
}
};
recognition.onerror = (event): void => {
pendingInterim = '';
let mapped: SpeechRecognitionError = 'unknown';
if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
mapped = 'not-allowed';
setPermission('denied');
} else if (event.error === 'no-speech') {
mapped = 'no-speech';
} else if (event.error === 'network') {
mapped = 'network';
}
onErrorRef.current?.(mapped);
};
recognition.onend = (): void => {
// Commit any interim text that never received a final result,
// unless the session was explicitly discarded.
if (!isDiscardingRef.current && pendingInterim) {
const committed = pendingInterim;
pendingInterim = '';
onTranscriptRef.current?.(committed, true);
}
isDiscardingRef.current = false;
pendingInterim = '';
setIsListening(false);
recognitionRef.current = null;
};
recognitionRef.current = recognition;
recognition.start();
}, [isSupported, lang]);
// Clean up on unmount
useEffect(
() => (): void => {
recognitionRef.current?.abort();
},
[],
);
return { isListening, isSupported, permission, start, stop, discard };
}

View File

@@ -261,53 +261,3 @@ describe('useAIAssistantStore — streaming error handling', () => {
expect(chat.sendMessage).not.toHaveBeenCalled();
});
});
describe('useAIAssistantStore — resumed replies', () => {
beforeEach(() => {
jest.clearAllMocks();
useAIAssistantStore.setState((s) => {
s.conversations = {};
s.streams = {};
s.activeConversationId = null;
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it.each([
[
'approveAction',
(id: string): Promise<void> =>
useAIAssistantStore.getState().approveAction(id, 'approval-1'),
],
[
'submitClarification',
(id: string): Promise<void> =>
useAIAssistantStore.getState().submitClarification(id, 'clar-1', {}),
],
])('%s stamps startedAt on a stream loaded without one', (_, resume) => {
chat.approveExecution.mockReturnValue(new Promise(() => {}));
chat.clarifyExecution.mockReturnValue(new Promise(() => {}));
useAIAssistantStore.setState((s) => {
s.streams['conv-1'] = {
isStreaming: false,
streamingContent: '',
streamingStatus: 'awaiting_approval',
streamingEvents: [],
streamingMessageId: null,
streamingActions: null,
pendingApproval: null,
pendingClarification: null,
startedAt: null,
};
});
jest.spyOn(Date, 'now').mockReturnValue(5000);
void resume('conv-1');
expect(useAIAssistantStore.getState().streams['conv-1'].startedAt).toBe(5000);
});
});

View File

@@ -203,7 +203,6 @@ function resetStreamingState(
streamingActions: null,
pendingApproval: null,
pendingClarification: null,
startedAt: Date.now(),
};
}
@@ -974,7 +973,6 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// compatible with the SSE event DTOs used by ConversationStreamState.
pendingApproval: detail.pendingApproval ?? null,
pendingClarification: detail.pendingClarification ?? null,
startedAt: null,
};
}
s.isLoadingThread = false;
@@ -1283,7 +1281,6 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
st.pendingApproval = null;
st.isStreaming = true;
st.streamingStatus = 'resumed';
st.startedAt ??= Date.now();
} else {
resetStreamingState(s, conversationId);
}
@@ -1411,7 +1408,6 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
st.pendingClarification = null;
st.isStreaming = true;
st.streamingStatus = 'resumed';
st.startedAt ??= Date.now();
} else {
resetStreamingState(s, conversationId);
}

View File

@@ -183,6 +183,4 @@ export interface ConversationStreamState {
streamingActions: MessageActionDTO[] | null;
pendingApproval: ApprovalEventDTO | null;
pendingClarification: ClarificationEventDTO | null;
/** When the reply began; null when nothing is streaming. */
startedAt: number | null;
}

View File

@@ -6,9 +6,7 @@ import { useQueries } from 'react-query';
import { useSelector } from 'react-redux';
import { AppLink } from 'lib/router/AppLink';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Button, Card, Input, TableProps, Tooltip } from 'antd';
import Space from 'periscope/components/Space/Space';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Card, Input, Space, TableProps, Tooltip, Flex } from 'antd';
import { Search } from '@signozhq/icons';
import type { ColumnType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';

View File

@@ -15,7 +15,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import * as Sentry from '@sentry/react';
import { Toaster } from '@signozhq/ui/sonner';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import Flex from 'periscope/components/Flex/Flex';
import { Flex } from 'antd';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
import getChangelogByVersion from 'api/changelog/getChangelogByVersion';

View File

@@ -1,4 +1,4 @@
import LayoutComponent from 'periscope/components/Layout/Layout';
import { Layout as LayoutComponent } from 'antd';
import styled from 'styled-components';
export const Layout = styled(LayoutComponent)`

View File

@@ -5,10 +5,15 @@ import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useMutation } from 'react-query';
import { CircleCheck, Landmark, MonitorDown } from '@signozhq/icons';
import { Card, Skeleton, Table, TableColumnsType as ColumnsType } from 'antd';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import Flex from 'periscope/components/Flex/Flex';
import {
Card,
Col,
Flex,
Row,
Skeleton,
Table,
TableColumnsType as ColumnsType,
} from 'antd';
import { Badge } from '@signozhq/ui/badge';
import logEvent from 'api/common/logEvent';
import type {

View File

@@ -1,6 +1,5 @@
import { useCallback, useMemo, useRef } from 'react';
import { Card } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Card, Flex } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import BarChart from 'lib/visualization/charts/BarChart/BarChart';
import { useIsDarkMode } from 'hooks/useDarkMode';

View File

@@ -23,8 +23,7 @@ import styles from './AskNoz.module.scss';
/**
* Opens the Noz drawer, matching the header entry it replaces. Cmd+K opens the
* modal instead; this is deliberately the drawer. It stays while the drawer is
* open, where it closes the drawer and keeps the chat for the next open.
* modal instead; this is deliberately the drawer.
*
* Carries the header's pending badge: when Noz is blocked on the user
* (`awaiting_approval` / `awaiting_clarification`) a dot pulses. Without it,
@@ -39,28 +38,21 @@ function AskNoz(): JSX.Element | null {
selectPendingUserInputStreamCount,
);
const closeDrawer = useAIAssistantStore((state) => state.closeDrawer);
// Noz is already on screen in the drawer or modal, so the "needs you" dot would be noise.
const showPendingBadge =
pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
// Noz is already on screen in the modal, so the "needs you" dot would be noise.
const showPendingBadge = pendingUserInputCount > 0 && !isModalOpen;
// The drawer does not render on the Noz full page, so the button would be inert.
const isAIAssistantPage = pathname.startsWith(ROUTES.AI_ASSISTANT_BASE);
const handleClick = useCallback((): void => {
if (isDrawerOpen) {
closeDrawer();
return;
}
const handleOpen = useCallback((): void => {
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.BottomStrip,
currentPage: normalizePage(pathname),
});
openAIAssistant();
}, [closeDrawer, isDrawerOpen, pathname]);
}, [pathname]);
if (!isAIAssistantEnabled || isAIAssistantPage) {
if (!isAIAssistantEnabled || isDrawerOpen || isAIAssistantPage) {
return null;
}
@@ -80,9 +72,7 @@ function AskNoz(): JSX.Element | null {
color="secondary"
size="sm"
prefix={<Noz size={16} />}
testId="bottom-strip-ask-noz-button"
onClick={handleClick}
aria-pressed={isDrawerOpen}
onClick={handleOpen}
aria-label={
showPendingBadge
? `Ask Noz, ${pendingUserInputCount} ${

View File

@@ -1,3 +1,4 @@
import { fireEvent } from '@testing-library/react';
import logEvent from 'api/common/logEvent';
import {
AIAssistantEvents,
@@ -5,11 +6,15 @@ import {
} from 'container/AIAssistant/events';
import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { render, userEvent } from 'tests/test-utils';
import { render } from 'tests/test-utils';
import AskNoz from '../AskNoz';
jest.mock('hooks/useIsAIAssistantEnabled');
jest.mock('api/common/logEvent', () => ({
__esModule: true,
default: jest.fn(),
}));
jest.mock('container/AIAssistant/store/useAIAssistantStore', () => ({
openAIAssistant: jest.fn(),
useAIAssistantStore: jest.fn(),
@@ -19,7 +24,6 @@ const mockEnabled = useIsAIAssistantEnabled as jest.MockedFunction<
typeof useIsAIAssistantEnabled
>;
const mockOpen = openAIAssistant as jest.MockedFunction<typeof openAIAssistant>;
const mockClose = jest.fn() as jest.MockedFunction<() => void>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { useAIAssistantStore } = jest.requireMock(
@@ -36,12 +40,7 @@ function mockStore({
isModalOpen?: boolean;
pendingCount?: number;
} = {}): void {
const state = {
isDrawerOpen,
isModalOpen,
streams: {},
closeDrawer: mockClose,
};
const state = { isDrawerOpen, isModalOpen, streams: {} };
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) => {
const picked = selector(state);
// `selectPendingUserInputStreamCount` walks `streams`, which is empty here,
@@ -50,8 +49,9 @@ function mockStore({
});
}
// `TooltipSimple` replaces its trigger's props, so the testId lives on the
// wrapper and the button itself is reached by role — there is only ever one.
const SLOT = 'bottom-strip-ask-noz';
const BUTTON = 'bottom-strip-ask-noz-button';
describe('AskNoz', () => {
beforeEach(() => {
@@ -62,9 +62,9 @@ describe('AskNoz', () => {
describe('visibility', () => {
it('renders when the assistant is enabled', () => {
const { getByTestId } = render(<AskNoz />);
const { getByRole } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toBeInTheDocument();
expect(getByRole('button')).toBeInTheDocument();
});
it('renders nothing when the assistant is disabled', () => {
@@ -75,12 +75,12 @@ describe('AskNoz', () => {
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('stays pressed while the drawer is open', () => {
it('renders nothing while the drawer is open', () => {
mockStore({ isDrawerOpen: true });
const { getByTestId } = render(<AskNoz />);
const { queryByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-pressed', 'true');
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('renders nothing on the Noz full page, where the drawer does not mount', () => {
@@ -93,32 +93,18 @@ describe('AskNoz', () => {
});
describe('what it does', () => {
it('opens the drawer on click', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { getByTestId } = render(<AskNoz />);
it('opens the drawer on click', () => {
const { getByRole } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
fireEvent.click(getByRole('button'));
expect(mockOpen).toHaveBeenCalledTimes(1);
});
it('closes the open drawer on the same chat instead of starting a new one', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
mockStore({ isDrawerOpen: true });
const { getByTestId } = render(<AskNoz />);
it('reports the open as coming from the strip', () => {
const { getByRole } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
expect(mockClose).toHaveBeenCalledTimes(1);
expect(mockOpen).not.toHaveBeenCalled();
expect(logEvent).not.toHaveBeenCalled();
});
it('reports the open as coming from the strip', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { getByTestId } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
fireEvent.click(getByRole('button'));
expect(logEvent).toHaveBeenCalledWith(
AIAssistantEvents.Opened,
@@ -131,9 +117,9 @@ describe('AskNoz', () => {
it('announces the count when Noz is waiting on the user', () => {
mockStore({ pendingCount: 2 });
const { getByTestId } = render(<AskNoz />);
const { getByRole } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute(
expect(getByRole('button')).toHaveAttribute(
'aria-label',
'Ask Noz, 2 actions need your response',
);
@@ -142,34 +128,26 @@ describe('AskNoz', () => {
it('uses the singular for one pending action', () => {
mockStore({ pendingCount: 1 });
const { getByTestId } = render(<AskNoz />);
const { getByRole } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute(
expect(getByRole('button')).toHaveAttribute(
'aria-label',
'Ask Noz, 1 action needs your response',
);
});
it('stays quiet when nothing is pending', () => {
const { getByTestId } = render(<AskNoz />);
const { getByRole } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
it('stays quiet while the drawer is open, Noz is already on screen', () => {
mockStore({ isDrawerOpen: true, pendingCount: 3 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
});
it('stays quiet while the modal is open, Noz is already on screen', () => {
mockStore({ isModalOpen: true, pendingCount: 3 });
const { getByTestId } = render(<AskNoz />);
const { getByRole } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
});
});
});

View File

@@ -1,113 +0,0 @@
import type { FloatingRect } from 'periscope/components/FloatingPanel/types';
import { supportChatObstacle } from '../supportChatObstacle';
type Pylon = Window['Pylon'];
const SUPPORT_CHAT: FloatingRect = { x: 882, y: 286, width: 384, height: 478 };
const CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
const originalPylon = window.Pylon;
const pylonCallbacks = new Map<string, unknown>();
const unsubscribes: (() => void)[] = [];
function subscribe(onChange: () => void): () => void {
const unsubscribe = supportChatObstacle.subscribe(onChange);
unsubscribes.push(unsubscribe);
return unsubscribe;
}
function installPylon(): jest.MockedFunction<Pylon> {
const pylon = jest.fn<ReturnType<Pylon>, Parameters<Pylon>>(
(command, callback) => {
pylonCallbacks.set(command, callback);
},
);
window.Pylon = pylon;
return pylon;
}
function firePylon(event: 'onShow' | 'onHide'): void {
const callback = pylonCallbacks.get(event);
if (typeof callback === 'function') {
callback();
}
}
function renderSupportChat(): HTMLElement {
const element = document.createElement('div');
element.className = 'PylonChat-chatWindowFrameContainer';
Object.defineProperties(element, {
offsetLeft: { value: SUPPORT_CHAT.x },
offsetTop: { value: SUPPORT_CHAT.y },
offsetWidth: { value: SUPPORT_CHAT.width },
offsetHeight: { value: SUPPORT_CHAT.height },
});
document.body.appendChild(element);
return element;
}
describe('supportChatObstacle', () => {
beforeEach(() => pylonCallbacks.clear());
afterEach(() => {
unsubscribes.splice(0).forEach((unsubscribe) => unsubscribe());
window.Pylon = originalPylon;
document.body.innerHTML = '';
});
it('reports the chat window box only while it is open', () => {
const chat = renderSupportChat();
expect(supportChatObstacle.getRect()).toStrictEqual(SUPPORT_CHAT);
chat.classList.add(CLOSED_CLASS);
expect(supportChatObstacle.getRect()).toBeNull();
});
it('treats the chat as closed once Pylon reports it hidden', () => {
installPylon();
renderSupportChat();
subscribe(jest.fn());
firePylon('onHide');
expect(supportChatObstacle.getRect()).toBeNull();
});
it('notifies every subscriber through one Pylon registration', () => {
const pylon = installPylon();
const first = jest.fn() as jest.MockedFunction<() => void>;
const second = jest.fn() as jest.MockedFunction<() => void>;
subscribe(first);
subscribe(second);
firePylon('onShow');
expect(pylon.mock.calls.map(([command]) => command)).toStrictEqual([
'onShow',
'onHide',
]);
expect(first).toHaveBeenCalledTimes(1);
expect(second).toHaveBeenCalledTimes(1);
});
it('unregisters through the loaded widget, not the stub it registered with', () => {
const stub = installPylon();
const unsubscribe = subscribe(jest.fn());
// Pylon's script swaps out the queueing stub, which then can no longer be called.
const widget = installPylon();
unsubscribe();
expect(stub.mock.calls.map(([command]) => command)).toStrictEqual([
'onShow',
'onHide',
]);
expect(widget.mock.calls).toStrictEqual([
['onShow', null],
['onHide', null],
]);
});
});

Some files were not shown because too many files have changed in this diff Show More