Compare commits

..

3 Commits

Author SHA1 Message Date
nityanandagohain
255b6fa1ac feat(trace-details): build the span tree and the overview of the trace inspect endpoint
GET /api/v1/traces/{traceID}/inspect now returns the overview. Like the
  waterfall, each call loads the trace's spans with one narrow query and builds
  the tree in memory, with each span's own time, level and the number of spans
  below it. There is no cache and no cap on the number of spans.

  From the tree it returns:
  - identity, with per-service totals and gen_ai usage
  - the spans where each error started, failures not marked as errors, the
    slowest spans by own time, the most expensive gen_ai spans, span links
  - the tree: the first 50 spans, level by level from the root, in time order;
    a trace of up to 50 spans also carries each span's record when they fit

  Every list pages with its nextCursor, and every item carries the span's
  direct parent. A page loads only what its list needs. Span attributes are
  read from the JSON column when it is filled, without the feature flag.

  spanId, search and allSpans answer 501 until the next PRs.

  Refs SigNoz/nerve-pod#651
2026-11-19 21:49:28 +05:30
nityanandagohain
75686f4004 fix(trace-details): update the trace inspect contract for the tree and the span cap 2026-11-19 21:18:30 +05:30
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
456 changed files with 8844 additions and 19369 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,379 @@ 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
required:
- traceId
- startTimestampMillis
- durationNano
- spanCount
- errorSpanCount
- rootCount
- hasMissingSpans
- 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:
@@ -13655,7 +14177,6 @@ components:
type: string
TelemetrytypesSource:
enum:
- audit
- meter
- ""
type: string
@@ -19286,6 +19807,150 @@ 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. The tree holds the first 50 spans of the trace: level by level
from the root, and in time order on the level that does not fit. A trace of
up to 50 spans also returns each span''s full record when they fit in 20,000
characters. 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

@@ -147,7 +147,6 @@ const preview: Preview = {
'Explorer',
['Overview', 'Span Drawer'],
'Trace Details',
['Overview', 'Thread'],
'Funnel Details',
],
'Metrics',

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

@@ -5284,7 +5284,6 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
}
export enum TelemetrytypesSourceDTO {
audit = 'audit',
meter = 'meter',
'' = '',
}
@@ -8043,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;
/**
@@ -13818,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',
@@ -14137,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
@@ -14165,6 +14348,354 @@ 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;
}
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;
/**
@@ -16036,6 +16567,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. The tree holds the first 50 spans of the trace: level by level from the root, and in time order on the level that does not fit. A trace of up to 50 spans also returns each span's full record when they fit in 20,000 characters. 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

@@ -0,0 +1,61 @@
import { ApiV3Instance as axios } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
TagKeyProps,
TagKeysPayloadProps,
TagValueProps,
TagValuesPayloadProps,
} from 'types/api/metrics/getResourceAttributes';
import { DataSource, MetricAggregateOperator } from 'types/common/queryBuilder';
export const getResourceAttributesTagKeys = async (
props: TagKeyProps,
): Promise<SuccessResponse<TagKeysPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_keys?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
searchText: props.match,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export const getResourceAttributesTagValues = async (
props: TagValueProps,
): Promise<SuccessResponse<TagValuesPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_values?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
attributeKey: props.tagKey,
searchText: '',
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};

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';
@@ -34,14 +32,13 @@ import styles from './AIAssistantModal.module.scss';
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
export default function AIAssistantModal(): JSX.Element | null {
const { pathname, search } = useAppLocation();
const { pathname } = useAppLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isModalOpen);
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);
@@ -96,12 +93,12 @@ export default function AIAssistantModal(): JSX.Element | null {
closeModal();
// Router state tells AIAssistantPage to skip its mount-time Opened fire:
// the assistant was already open in the modal, so this is a surface
// switch, not a new open. `returnTo` is where its minimize button comes back to.
// switch, not a new open.
navigate(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
{ state: { fromInApp: true, returnTo: `${pathname}${search}` } },
{ state: { fromInApp: true } },
);
}, [activeConversationId, closeModal, pathname, search]);
}, [activeConversationId, closeModal]);
const handleNew = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
@@ -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,31 +14,16 @@ 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, search } = useAppLocation();
const { pathname } = useAppLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isDrawerOpen);
@@ -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) {
@@ -66,12 +46,12 @@ export default function AIAssistantPanel(): JSX.Element | null {
closeDrawer();
// Router state tells AIAssistantPage to skip its mount-time Opened fire:
// the assistant was already open in the drawer, so this is a surface
// switch, not a new open. `returnTo` is where its minimize button comes back to.
// switch, not a new open.
navigate(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
{ state: { fromInApp: true, returnTo: `${pathname}${search}` } },
{ state: { fromInApp: true } },
);
}, [activeConversationId, closeDrawer, pathname, search]);
}, [activeConversationId, closeDrawer]);
const handleNew = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
@@ -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

@@ -1,46 +1,8 @@
@use '../_selection' as *;
.conversation {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
@include selection;
// 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 {
@@ -72,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,34 +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 || isLoadingThread;
const sendDisabled =
const inputDisabled =
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';
@@ -158,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,
@@ -177,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
@@ -194,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,
@@ -220,13 +207,8 @@ export default function ConversationView({
onSend={handleSend}
onCancel={handleCancel}
disabled={inputDisabled}
sendDisabled={sendDisabled}
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

@@ -1,18 +0,0 @@
// Strips a `@signozhq/ui` Input inside this element down to its text: no box, no focus ring.
@mixin bare-input {
--input-height: 20px;
--input-padding: 0;
--input-border-width: 0;
--input-background: transparent;
--input-hover-background: transparent;
--input-focus-background: transparent;
--input-focus-outline-width: 0;
--input-box-shadow: none;
--input-font-size: var(--periscope-font-size-base);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,
var(--l2-foreground),
transparent 40%
);
}

View File

@@ -1,6 +0,0 @@
@mixin selection {
& ::selection {
background: var(--accent-primary);
color: var(--l1-background);
}
}

View File

@@ -1,29 +0,0 @@
// A highlight sweeping across text, for work still in progress.
@mixin shimmer-text($base, $highlight) {
background: linear-gradient(
90deg,
$base 0%,
$base 35%,
$highlight 50%,
$base 65%,
$base 100%
);
background-size: 300% 100%;
background-clip: text;
-webkit-background-clip: text;
color: transparent;
animation: shimmer 1.8s linear infinite;
@media (prefers-reduced-motion: reduce) {
animation: none;
}
@keyframes shimmer {
from {
background-position: 100% 0;
}
to {
background-position: 0% 0;
}
}
}

View File

@@ -1,10 +1,13 @@
.section {
display: flex;
flex-direction: column;
gap: var(--spacing-6);
gap: 8px;
flex-shrink: 0;
width: 100%;
padding: 8px;
margin-top: 16px;
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
// Background, padding-x, and rounding are inherited from the parent
// bubble — the section sits inside the assistant bubble as its last
@@ -12,48 +15,32 @@
}
.heading {
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
display: flex;
align-items: center;
gap: 6px;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
font-feature-settings:
'tnum' on,
'lnum' on,
'zero' on,
'ss01' on;
letter-spacing: 0.06em;
color: var(--l3-foreground);
}
// One action per line, each in the sent-message bubble.
.headingIcon {
color: var(--primary);
flex-shrink: 0;
}
.list {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--spacing-5);
--button-height: auto;
--button-padding: var(--spacing-4) var(--spacing-6);
--button-border-radius: var(--radius-3);
--button-font-size: var(--periscope-font-size-base);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);
--button-variant-outlined-hover-background-color: var(--l3-background);
--button-variant-outlined-hover-color: var(--l1-foreground);
// Buttons don't inherit the page font; the tooltip takes over their data-slot.
> button {
font-family: inherit;
}
flex-wrap: wrap;
gap: 6px;
}
.chipLabel {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 220px;
}
.chipState {

View File

@@ -31,7 +31,19 @@ import { QueryParams } from 'constants/query';
import { UpdateTimeInterval } from 'store/actions';
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
import { openInNewTab } from 'utils/navigation';
import { Check, TriangleAlert } from '@signozhq/icons';
import {
ArchiveRestore,
BookOpen,
Check,
ExternalLink,
Eye,
Filter,
MessageCircle,
RotateCcw,
Sparkles,
TriangleAlert,
Undo,
} from '@signozhq/icons';
import logEvent from 'api/common/logEvent';
@@ -107,6 +119,34 @@ interface ChipResult {
error?: string;
}
/** Maps each MessageActionKindDTO to its display icon. */
function ActionIcon({
kind,
size = 12,
}: {
kind: MessageActionDTO['kind'];
size?: number;
}): JSX.Element {
switch (kind) {
case MessageActionKindDTO.undo:
return <Undo size={size} />;
case MessageActionKindDTO.revert:
return <RotateCcw size={size} />;
case MessageActionKindDTO.restore:
return <ArchiveRestore size={size} />;
case MessageActionKindDTO.follow_up:
return <MessageCircle size={size} />;
case MessageActionKindDTO.open_resource:
return <Eye size={size} />;
case MessageActionKindDTO.open_docs:
return <BookOpen size={size} />;
case MessageActionKindDTO.apply_filter:
return <Filter size={size} />;
default:
return <ExternalLink size={size} />;
}
}
/**
* The agent emits `action.query` as the SigNoz REST query-range request body:
*
@@ -579,7 +619,10 @@ export default function ActionsSection({
return (
<div className={styles.section}>
<div className={styles.heading}>Suggested actions</div>
<div className={styles.heading}>
<Sparkles size={12} className={styles.headingIcon} />
<span className={styles.headingText}>Suggested actions</span>
</div>
<div className={styles.list}>
{actions.map((action, i) => {
@@ -605,11 +648,13 @@ export default function ActionsSection({
openTarget !== null &&
isOnResourcePage(openTarget.path, { pathname, search });
let icon: JSX.Element | undefined;
let icon: JSX.Element;
if (isSuccess) {
icon = <Check size={14} />;
icon = <Check size={12} />;
} else if (isError) {
icon = <TriangleAlert size={14} />;
icon = <TriangleAlert size={12} />;
} else {
icon = <ActionIcon kind={action.kind} />;
}
const chip = (

View File

@@ -1,6 +1,6 @@
@use '../../_shimmer' as *;
// The row a run of thinking + tool-call steps folds behind: the running step, then a summary.
// Collapsed activity summary — one row that hides the underlying
// thinking + tool-call steps. Reuses the same quiet treatment as
// ThinkingStep / ToolCallStep so it sits flush in the assistant bubble.
.activityGroup {
width: 100%;
font-size: 12px;
@@ -9,17 +9,15 @@
.activityHeader {
display: flex;
align-items: center;
gap: 3px;
width: fit-content;
max-width: 100%;
padding: 0;
gap: 8px;
padding: 4px 0;
background: transparent;
border: none;
font: inherit;
cursor: pointer;
color: var(--l2-foreground);
color: var(--l3-foreground);
user-select: none;
transition: color 0.12s ease;
width: 100%;
text-align: left;
&:hover {
@@ -27,15 +25,31 @@
}
}
.sparkleIcon {
flex-shrink: 0;
color: var(--accent-primary);
&.iconPulsing {
animation: activityGroupPulse 1.4s ease-in-out infinite;
}
}
@keyframes activityGroupPulse {
0%,
100% {
opacity: 0.55;
}
50% {
opacity: 1;
}
}
.activitySummary {
min-width: 0;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 18px;
letter-spacing: -0.005em;
font-weight: 400;
}
.toggleChevron {
@@ -46,27 +60,5 @@
.activityBody {
display: flex;
flex-direction: column;
padding: var(--spacing-2) 0;
}
.soloBody {
padding: var(--spacing-2) 0 var(--spacing-2) var(--spacing-4);
}
.soloThought {
margin: 0;
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);
white-space: pre-wrap;
word-break: break-word;
}
// While Noz works, the row names the step it's on.
.live .activitySummary {
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
line-height: var(--line-height-20);
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
padding: 2px 0 4px;
}

View File

@@ -1,9 +1,11 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import cx from 'classnames';
import { ChevronDown, ChevronRight } from '@signozhq/icons';
import { ChevronDown, ChevronRight, Sparkles } from '@signozhq/icons';
import { formatTime } from 'utils/timeUtils';
import { StreamingToolCall } from '../../types';
import ThinkingStep, { thinkingLabel } from '../ThinkingStep';
import ThinkingStep, { ThinkingContent, thinkingLabel } from '../ThinkingStep';
import ToolCallStep, {
getToolDisplayLabel,
ToolCallContent,
@@ -17,88 +19,128 @@ export type ActivityItem =
interface ActivityGroupProps {
items: ActivityItem[];
/** The trailing group of an active stream: its row names the running step, shimmering. */
/**
* True only for the trailing activity group of an active stream — drives
* the live "Working…" label and the elapsed-time tick (which re-stamps on
* approval/clarification resume so wait time isn't counted).
*/
isLive?: boolean;
}
/**
* Single-item groups get a step-specific summary so the user doesn't see a
* pointless "Worked through 1 step".
* pointless "Worked through 1 step". Multi-item groups roll up into the
* generic "Working… / Worked through N steps" treatment.
*/
function buildSummary(items: ActivityItem[], isLive: boolean): string {
// While Noz works, the row names the step it's on.
if (isLive) {
const latest = items[items.length - 1];
return latest.kind === 'thinking'
? thinkingLabel(true)
: getToolDisplayLabel(latest.toolCall);
}
function buildSummary(
items: ActivityItem[],
isLive: boolean,
elapsed: number,
): string {
if (items.length === 1) {
const [only] = items;
if (only.kind === 'thinking') {
return thinkingLabel(false);
return thinkingLabel(isLive);
}
return getToolDisplayLabel(only.toolCall);
}
return `Worked through ${items.length} steps`;
const stepLabel = `${items.length} steps`;
if (!isLive) {
return `Worked through ${stepLabel}`;
}
// Suppress the elapsed token until ≥ 1s — the first tick fires after
// 1s anyway, and showing "0s" or "<1s" briefly adds noise.
return elapsed >= 1000
? `Working… · ${formatTime(elapsed / 1000)} · ${stepLabel}`
: `Working… · ${stepLabel}`;
}
/** A run of thinking and tool-call steps on a timeline, folded behind the running step, then a summary. */
/**
* Single collapsed summary row that hides a run of thinking + tool-call steps.
* Expands to show each underlying step inline. Used for every activity row
* (including single-item ones) so all "what the agent did" rows share a
* consistent ✨-led visual contract.
*/
export default function ActivityGroup({
items,
isLive = false,
}: ActivityGroupProps): JSX.Element {
const [expanded, setExpanded] = useState(false);
// Captures the moment this live phase started. Re-stamped on every
// false→true transition so a stream that pauses on
// approval/clarification and resumes doesn't roll the user's wait time
// into the elapsed counter.
const startedAtRef = useRef<number>(Date.now());
const wasLiveRef = useRef<boolean>(isLive);
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
if (isLive && !wasLiveRef.current) {
startedAtRef.current = Date.now();
setElapsed(0);
}
wasLiveRef.current = isLive;
if (!isLive) {
return undefined;
}
// Tick once per second — the display is integer-second precision, so
// faster ticks would just re-render the bubble for no visible change.
const id = window.setInterval(() => {
setElapsed(Date.now() - startedAtRef.current);
}, 1000);
return (): void => window.clearInterval(id);
}, [isLive]);
const summary = buildSummary(items, isLive, elapsed);
const isSingle = items.length === 1;
const toggle = (): void => setExpanded((v) => !v);
const [solo] = items;
const isSolo = items.length === 1;
return (
<div className={cx(styles.activityGroup, { [styles.live]: isLive })}>
<button
type="button"
className={styles.activityHeader}
onClick={toggle}
aria-expanded={expanded}
data-testid="ai-activity-toggle"
>
<span className={styles.activitySummary}>
{buildSummary(items, isLive)}
</span>
<div className={styles.activityGroup}>
<div className={styles.activityHeader} onClick={toggle}>
<Sparkles
size={12}
className={cx(styles.sparkleIcon, { [styles.iconPulsing]: isLive })}
/>
<span className={styles.activitySummary}>{summary}</span>
{expanded ? (
<ChevronDown size={14} className={styles.toggleChevron} />
<ChevronDown size={12} className={styles.toggleChevron} />
) : (
<ChevronRight size={14} className={styles.toggleChevron} />
<ChevronRight size={12} className={styles.toggleChevron} />
)}
</button>
</div>
{/* The summary row already names a lone step, so show only what it did. */}
{expanded && isSolo && (
<div className={styles.soloBody}>
{solo.kind === 'thinking' ? (
<p className={styles.soloThought}>{solo.content.trim()}</p>
) : (
<ToolCallContent toolCall={solo.toolCall} />
)}
</div>
)}
{expanded && !isSolo && (
{expanded && (
<div className={styles.activityBody}>
{items.map((item, i) => {
// The newest step stays live until the next event, so a running reply always shows progress.
const isStepLive = isLive && i === items.length - 1;
return item.kind === 'thinking' ? (
<ThinkingStep key={item.id} content={item.content} isLive={isStepLive} />
{isSingle ? (
// Single-item: the outer chevron already provides disclosure,
// so render the underlying content directly instead of wrapping
// it in a second collapsible step row.
items[0].kind === 'thinking' ? (
<ThinkingContent content={items[0].content} />
) : (
<ToolCallStep
key={item.id}
toolCall={item.toolCall}
isLive={isStepLive}
/>
);
})}
<ToolCallContent toolCall={items[0].toolCall} />
)
) : (
items.map((item, i) => {
// A thinking step is live only while it's the trailing item
// in a trailing live group — once any later event (text or
// tool) arrives, the pass is done.
const isLastItem = i === items.length - 1;
return item.kind === 'thinking' ? (
<ThinkingStep
key={item.id}
content={item.content}
isLive={isLive && isLastItem}
/>
) : (
<ToolCallStep key={item.id} toolCall={item.toolCall} />
);
})
)}
</div>
)}
</div>

View File

@@ -1,49 +0,0 @@
import { render, screen, userEvent } from 'tests/test-utils';
import ActivityGroup, { ActivityItem } from '../ActivityGroup';
const steps: ActivityItem[] = [
{ id: 'thought-1', kind: 'thinking', content: 'Checking the error rate' },
{
id: 'call-1',
kind: 'tool',
toolCall: {
toolName: 'signoz_search_logs',
input: {},
done: false,
},
},
];
describe('ActivityGroup', () => {
it('names the running step and opens the steps so far on request', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<ActivityGroup items={steps} isLive />);
const toggle = screen.getByTestId('ai-activity-toggle');
expect(toggle).toHaveTextContent('Search Logs');
expect(screen.queryByTestId('ai-activity-step')).not.toBeInTheDocument();
await user.click(toggle);
const shown = screen.getAllByTestId('ai-activity-step');
expect(shown).toHaveLength(2);
expect(shown[0]).toHaveTextContent(
'Thought for a few secondsChecking the error rate',
);
expect(shown[1]).toHaveTextContent('Search Logs');
});
it('folds a finished run behind its step count', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<ActivityGroup items={steps} />);
const toggle = screen.getByTestId('ai-activity-toggle');
expect(toggle).toHaveTextContent('Worked through 2 steps');
expect(screen.queryByTestId('ai-activity-step')).not.toBeInTheDocument();
await user.click(toggle);
expect(screen.getAllByTestId('ai-activity-step')).toHaveLength(2);
});
});

View File

@@ -1,99 +0,0 @@
@use '../../_shimmer' as *;
.step {
display: flex;
align-items: flex-start;
gap: var(--spacing-5);
padding: var(--spacing-3) var(--spacing-4);
border-radius: var(--radius-3);
}
// The dot sits on the title's line, and a line runs down beside the step's content.
.rail {
position: relative;
flex-shrink: 0;
align-self: stretch;
width: 6px;
padding-top: 7px;
// A lone step is no timeline, so it goes without the dot.
.step:only-child & {
display: none;
}
// 8px under the dot to the end of the step's content, clear of the next step's dot.
.step:not(:last-child) &::after {
content: '';
position: absolute;
top: 21px;
bottom: 0;
left: 50%;
width: 1px;
background: var(--l2-border);
transform: translateX(-50%);
}
}
.dot {
display: block;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--l2-border);
}
.content {
display: flex;
flex: 1;
flex-direction: column;
min-width: 0;
}
.title {
display: inline-flex;
align-self: flex-start;
align-items: center;
gap: 3px;
max-width: 100%;
padding: 0;
border: none;
background: none;
font: inherit;
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
text-align: left;
}
button.title {
cursor: pointer;
}
.live .title {
color: var(--l3-foreground);
}
.titleText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
// A highlight sweeps across the running step's title.
.live & {
@include shimmer-text(
color-mix(in srgb, var(--l3-foreground), transparent 30%),
var(--l2-foreground)
);
}
}
.detail {
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);
white-space: pre-wrap;
word-break: break-word;
}

View File

@@ -1,54 +0,0 @@
import type { ReactNode } from 'react';
import cx from 'classnames';
import { ChevronDown, ChevronRight } from '@signozhq/icons';
import styles from './ActivityStep.module.scss';
interface ActivityStepProps {
title: string;
/** Still running: the title shimmers. */
isLive?: boolean;
/** Given only for steps whose detail opens on demand. */
onToggle?: () => void;
expanded?: boolean;
children?: ReactNode;
}
/** One step of the agent's work on a timeline: a dot, its title, and what it did. */
export default function ActivityStep({
title,
isLive = false,
onToggle,
expanded = false,
children,
}: ActivityStepProps): JSX.Element {
const titleText = <span className={styles.titleText}>{title}</span>;
return (
<div
className={cx(styles.step, { [styles.live]: isLive })}
data-testid="ai-activity-step"
>
<div className={styles.rail}>
<span className={styles.dot} />
</div>
<div className={styles.content}>
{onToggle ? (
<button
type="button"
className={styles.title}
onClick={onToggle}
aria-expanded={expanded}
data-testid="ai-activity-step-toggle"
>
{titleText}
{expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</button>
) : (
<span className={styles.title}>{titleText}</span>
)}
{children && <div className={styles.detail}>{children}</div>}
</div>
</div>
);
}

View File

@@ -1,25 +1,15 @@
@use '../../_scrollbar' as *;
.card {
border: 1px solid var(--l2-border);
border: 1px solid var(--l1-border);
border-radius: var(--radius-2);
padding: var(--spacing-6);
background: var(--l2-background);
padding: 12px;
background: var(--l1-background);
display: flex;
flex-direction: column;
gap: var(--spacing-6);
gap: 16px;
width: 100%;
// Clear of whatever the reply shows above it.
&:not(:first-child) {
margin-top: var(--spacing-6);
}
// Below the header, everything lines up with the title, clear of the icon.
&:not(.decided) > :not(.header) {
margin-left: calc(16px + var(--spacing-6));
}
&.decided {
border-color: var(--l2-border);
background: transparent;
@@ -33,7 +23,7 @@
.header {
display: flex;
align-items: center;
gap: var(--spacing-6);
gap: 6px;
}
.shieldIcon {
@@ -42,9 +32,8 @@
}
.headerLabel {
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
font-size: 12px;
font-weight: 600;
color: var(--l1-foreground);
}
@@ -60,10 +49,10 @@
}
.summary {
font-size: 13px;
color: var(--l1-foreground);
margin: 0;
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
line-height: 1.5;
}
.diffSection {
@@ -272,9 +261,8 @@
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--spacing-6);
display: flex;
gap: 6px;
}
.statusIcon {

View File

@@ -88,7 +88,7 @@ export default function ApprovalCard({
return (
<div className={styles.card}>
<div className={styles.header}>
<Shield size={16} className={styles.shieldIcon} />
<Shield size={13} className={styles.shieldIcon} />
<span className={styles.headerLabel}>Action requires approval</span>
<span className={styles.resourceBadge}>
{approval.actionType} · {approval.resourceType}
@@ -194,8 +194,7 @@ export default function ApprovalCard({
disabledTooltip="Wait for the response to finish"
color="primary"
variant="solid"
size="md"
width="100%"
size="sm"
onClick={handleApprove}
disabled={isStreaming}
prefix={<Check />}
@@ -205,8 +204,7 @@ export default function ApprovalCard({
<Button
disabledTooltip="Wait for the response to finish"
variant="outlined"
size="md"
width="100%"
size="sm"
color="secondary"
onClick={handleReject}
disabled={isStreaming}

View File

@@ -1,35 +1,76 @@
@use '../../_scrollbar' as *;
@use '../../_bareInput' as *;
.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 {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 11px;
background: var(--l2-background);
border: 1px solid var(--l1-border);
border-radius: var(--radius-2);
padding: 4px 6px 4px 8px;
color: var(--l1-foreground);
button {
height: auto !important;
min-height: 0 !important;
width: auto !important;
}
// `auto` chips are derived from the URL (current page) — visually
// distinguished by a dashed border + slightly muted text so the user
// can tell them apart from explicit @-mentions. Tighter padding /
// font-size keeps them visually subordinate to user `@`-picks.
&.auto {
border-style: dashed;
color: var(--l2-foreground);
background: transparent;
font-size: 10px;
padding: 2px 4px 2px 6px;
gap: 3px;
}
}
.contextTagContent {
display: flex;
align-items: center;
gap: 8px;
max-width: 220px;
.contextTagLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.contextTagLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.attachmentChip {
@@ -50,55 +91,72 @@
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;
}
@@ -106,17 +164,13 @@
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;
@@ -126,88 +180,60 @@
border-radius: var(--radius-2);
}
// One 34px row: 13/20 text, a full-width band on hover.
@mixin picker-row($padding-inline) {
--button-height: 34px;
// A long list scrolls; without this the rows squash to fit it.
--button-flex-shrink: 0;
--button-padding: 7px #{$padding-inline};
--button-border-radius: 0;
--button-justify-content: flex-start;
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-variant-ghost-color: var(--l2-foreground);
--button-variant-ghost-hover-color: var(--l1-foreground);
--button-variant-ghost-hover-background-color: var(--l3-background);
--button-focus-visible-outline: none;
.sendBtn {
flex-shrink: 0;
border-radius: var(--radius-2);
// Buttons don't inherit the page font.
> [data-slot='button'] {
font-family: inherit;
letter-spacing: -0.005em;
}
&.stop {
background: var(--accent-cherry) !important;
border-color: var(--accent-cherry) !important;
// Keyboard focus shows as the hover band rather than a ring.
> [data-slot='button']:focus-visible {
--button-variant-ghost-background-color: var(--l3-background);
--button-variant-ghost-color: var(--l1-foreground);
&:hover {
opacity: 0.85;
}
}
}
.contextPopover {
box-sizing: border-box;
max-width: min(92vw, 532px);
height: 326px;
backdrop-filter: blur(20px);
width: 480px !important;
max-width: min(92vw, 480px);
margin-left: 16px;
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
background: var(--l1-background);
box-shadow: 0 16px 36px rgba(0, 0, 0, 0.3);
padding: 8px;
// Clip horizontal overflow so long entity titles can't poke past the
// popover's right edge. Vertical overflow is handled inside
// `.contextPopoverEntities`.
overflow-x: hidden;
--popover-width: 532px;
--popover-padding: 0;
// Above the floating panel (999) and the popup chat (1050) it opens from.
--popover-z-index: 1100;
z-index: 1000;
}
.contextPopoverContent {
display: grid;
grid-template-columns: 224px 1fr;
height: 100%;
grid-template-columns: 180px 1fr;
min-height: 250px;
min-width: 0;
}
.contextPopoverLeft {
display: flex;
flex-direction: column;
min-height: 0;
border-right: 1px solid var(--l2-border);
}
// Both columns open with a 44px header, so their bottom borders run as one divider.
.contextPopoverLabel {
display: flex;
flex-shrink: 0;
align-items: center;
height: 44px;
padding: 0 var(--spacing-7);
border-bottom: 1px solid var(--l2-border);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--l3-foreground);
}
.contextPopoverCategories {
display: flex;
flex-direction: column;
padding: var(--spacing-2) 0;
@include picker-row(var(--spacing-7));
gap: 6px;
padding: 8px;
border-right: 1px solid var(--l2-border);
--button-justify-content: flex-start;
> [data-slot='button'][aria-selected='true'] {
--button-variant-ghost-background-color: var(--l2-background-hover);
--button-variant-ghost-background-color: color-mix(
in srgb,
var(--accent-primary),
transparent 86%
);
--button-variant-ghost-color: var(--l1-foreground);
}
}
@@ -217,34 +243,35 @@
flex-direction: column;
min-width: 0;
min-height: 0;
// Match the previous fixed entity-list height so the inner search +
// scrolling list have a definite container to size against.
height: 320px;
}
.contextPopoverSearch {
display: flex;
padding: 8px;
flex-shrink: 0;
align-items: center;
height: 44px;
padding: 0 var(--spacing-6);
border-bottom: 1px solid var(--l2-border);
@include bare-input;
position: relative;
width: 90%;
}
.contextPopoverSearchInput {
width: 100%;
caret-color: var(--accent-primary);
box-sizing: border-box;
}
.contextPopoverEntities {
display: flex;
flex-direction: column;
gap: 6px;
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
padding: var(--spacing-2) 0;
padding: 8px;
min-width: 0;
@include scrollbar(0.2rem);
@include picker-row(var(--spacing-6));
--button-justify-content: flex-start;
> [data-slot='button'][aria-pressed='true'] {
--button-variant-ghost-background-color: color-mix(
@@ -311,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

@@ -7,11 +7,15 @@ import {
} from 'react';
import { useQueryClient } from 'react-query';
import cx from 'classnames';
import { Badge } from '@signozhq/ui/badge';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@signozhq/ui/popover';
import { toast } from '@signozhq/ui/sonner';
import { Tooltip } from '@signozhq/ui/tooltip';
import type { UploadFile } from 'antd';
import getSessionStorage from 'api/browser/sessionstorage/get';
import setSessionStorage from 'api/browser/sessionstorage/set';
import {
getListDashboardsForUserV2QueryKey,
useListDashboardsForUserV2,
@@ -27,29 +31,37 @@ 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, Square, TriangleAlert, X } from '@signozhq/icons';
import {
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 ContextPill from './ContextPill/ContextPill';
import EdgeSweep from './EdgeSweep/EdgeSweep';
import NozPeek from './NozPeek/NozPeek';
import {
AUTO_CONTEXT_ICONS,
CONTEXT_CATEGORIES,
CONTEXT_CATEGORY_ICONS,
CONTEXT_CATEGORY_SINGULAR,
CONTEXT_TYPE_LABELS,
ContextCategory,
} from './contextPicker';
@@ -61,17 +73,8 @@ interface ChatInputProps {
) => void;
onCancel?: () => void;
disabled?: boolean;
/** Keeps the field editable but blocks sending. */
sendDisabled?: 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
@@ -139,6 +142,28 @@ function autoContextLabel(ctx: MessageContext): string {
}
}
/** Capitalised category badge text — e.g. "Dashboard", "Logs explorer". */
function autoContextCategory(ctx: MessageContext): string {
switch (ctx.type) {
case 'dashboard':
return 'Dashboard';
case 'alert':
return 'Alert';
case 'service':
return 'Service';
case 'logs_explorer':
return 'Logs';
case 'traces_explorer':
return 'Traces';
case 'metrics_explorer':
return 'Metrics';
case 'saved_view':
return 'Saved view';
default:
return ctx.type;
}
}
const MAX_INPUT_LENGTH = 20000;
const WARNING_THRESHOLD = 15000;
// Cap for the auto-growing composer. Past this, the textarea stops growing
@@ -146,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
@@ -214,20 +241,14 @@ export default function ChatInput({
onSend,
onCancel,
disabled,
sendDisabled = false,
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<
@@ -267,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);
@@ -320,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);
}
},
@@ -332,6 +356,7 @@ export default function ChatInput({
(prompt: string) => {
const next = capText(prompt);
setText(next);
committedTextRef.current = next;
setMentionRange(null);
setPickerSearchQuery('');
setIsContextPickerOpen(false);
@@ -422,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
@@ -449,7 +468,7 @@ export default function ChatInput({
const handleSend = useCallback(async () => {
const trimmed = text.trim();
if (disabled || sendDisabled || (!trimmed && pendingFiles.length === 0)) {
if (!trimmed && pendingFiles.length === 0) {
return;
}
@@ -478,19 +497,11 @@ export default function ChatInput({
contexts.length > 0 ? contexts : undefined,
);
setText('');
committedTextRef.current = '';
setPendingFiles([]);
setSelectedContexts([]);
textareaRef.current?.focus();
}, [
text,
pendingFiles,
disabled,
sendDisabled,
onSend,
selectedContexts,
autoContexts,
capText,
]);
}, [text, pendingFiles, onSend, selectedContexts, autoContexts, capText]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -521,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
@@ -686,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) => (
@@ -717,30 +926,55 @@ export default function ChatInput({
<div className={styles.contextTags}>
{autoContexts?.map((ctx) => {
const key = autoContextKey(ctx);
const label = resolveAutoContextName(ctx);
const category = autoContextCategory(ctx);
return (
<ContextPill
key={key}
icon={AUTO_CONTEXT_ICONS[ctx.type]}
category={CONTEXT_TYPE_LABELS[ctx.type]}
label={resolveAutoContextName(ctx)}
onRemove={
onDismissAutoContext
? (): void => onDismissAutoContext(key)
: undefined
}
/>
<div key={key} className={cx(styles.contextTag, styles.auto)}>
<div className={styles.contextTagContent}>
<Badge textTransform="none" color="secondary" variant="outlined">
{category}
</Badge>
<span className={styles.contextTagLabel}>{label}</span>
</div>
{onDismissAutoContext && (
<Button
variant="link"
size="sm"
icon
color="secondary"
onClick={(): void => onDismissAutoContext(key)}
aria-label={`Remove ${category}: ${label} context`}
>
<X size={10} />
</Button>
)}
</div>
);
})}
{selectedContexts.map((contextItem) => (
<ContextPill
<div
key={`${contextItem.category}:${contextItem.entityId}`}
icon={CONTEXT_CATEGORY_ICONS[contextItem.category]}
category={CONTEXT_CATEGORY_SINGULAR[contextItem.category]}
label={contextItem.value}
onRemove={(): void =>
removeContext(contextItem.category, contextItem.entityId)
}
/>
className={styles.contextTag}
>
<div className={styles.contextTagContent}>
<Badge textTransform="none" color="primary" variant="outlined">
{contextItem.category}
</Badge>
<span className={styles.contextTagLabel}>{contextItem.value}</span>
</div>
<Button
variant="link"
size="sm"
icon
color="secondary"
onClick={(): void =>
removeContext(contextItem.category, contextItem.entityId)
}
aria-label={`Remove ${contextItem.category}: ${contextItem.value} context`}
>
<X size={10} />
</Button>
</div>
))}
</div>
)}
@@ -749,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">
@@ -775,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 => {
@@ -786,78 +1020,73 @@ 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"
align="end"
sideOffset={4}
sideOffset={8}
>
<div className={styles.contextPopoverContent}>
<div className={styles.contextPopoverLeft}>
<div className={styles.contextPopoverLabel}>Available resources</div>
<div
className={styles.contextPopoverCategories}
role="tablist"
aria-orientation="vertical"
aria-label="Context categories"
>
{CONTEXT_CATEGORIES.map((category) => {
const isActive = activeContextCategory === category;
return (
<Button
key={category}
ref={(el): void => {
categoryTabRefs.current.set(category, el);
}}
type="button"
variant="ghost"
color="secondary"
size="sm"
id={`ai-context-tab-${category}`}
testId={`ai-context-tab-${category}`}
// Single stable panel id shared by every tab: only the
// active category's tabpanel is rendered, so per-category
// `aria-controls` ids would point at nonexistent nodes
// for the two inactive tabs. APG allows a single
// dynamic panel whose `aria-labelledby` swaps to the
// active tab.
aria-controls="ai-context-tabpanel"
// Roving tabindex: only the active tab participates in
// the Tab sequence; arrow keys move between tabs.
tabIndex={isActive ? 0 : -1}
aria-selected={isActive}
width="100%"
onClick={(): void => {
setActiveContextCategory(category);
setPickerSearchQuery('');
}}
onKeyDown={(e): void => handleCategoryKeyDown(e, category)}
>
<span>{category}</span>
</Button>
);
})}
</div>
<div
className={styles.contextPopoverCategories}
role="tablist"
aria-orientation="vertical"
aria-label="Context categories"
>
{CONTEXT_CATEGORIES.map((category) => {
const CategoryIcon = CONTEXT_CATEGORY_ICONS[category];
const isActive = activeContextCategory === category;
return (
<Button
key={category}
ref={(el): void => {
categoryTabRefs.current.set(category, el);
}}
type="button"
variant="ghost"
color="secondary"
size="sm"
id={`ai-context-tab-${category}`}
testId={`ai-context-tab-${category}`}
// Single stable panel id shared by every tab: only the
// active category's tabpanel is rendered, so per-category
// `aria-controls` ids would point at nonexistent nodes
// for the two inactive tabs. APG allows a single
// dynamic panel whose `aria-labelledby` swaps to the
// active tab.
aria-controls="ai-context-tabpanel"
// Roving tabindex: only the active tab participates in
// the Tab sequence; arrow keys move between tabs.
tabIndex={isActive ? 0 : -1}
aria-selected={isActive}
width="100%"
onClick={(): void => {
setActiveContextCategory(category);
setPickerSearchQuery('');
}}
onKeyDown={(e): void => handleCategoryKeyDown(e, category)}
prefix={<CategoryIcon size={13} />}
>
<span>{category}</span>
</Button>
);
})}
</div>
<div
@@ -870,10 +1099,10 @@ 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)}
prefix={<Search size={12} />}
// Skip the picker's roving keyboard focus — typing here
// shouldn't move category selection.
onKeyDown={(e): void => {
@@ -916,7 +1145,6 @@ export default function ChatInput({
size="sm"
aria-pressed={isSelected}
width="100%"
testId={`ai-context-option-${activeContextCategory}-${option.id}`}
onClick={(): void =>
toggleContextSelection(
activeContextCategory,
@@ -936,37 +1164,97 @@ 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>
) : (
<Tooltip title="Send message">
<Button
disabledTooltip={
disabled || sendDisabled ? disabledTooltip : 'Type a message first'
}
disabledTooltip={disabled ? disabledTooltip : 'Type a message first'}
variant="solid"
size="sm"
size="md"
icon
color="primary"
onClick={handleSend}
disabled={
disabled || sendDisabled || (!text.trim() && pendingFiles.length === 0)
}
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,62 +0,0 @@
.pill {
display: inline-flex;
align-items: center;
min-width: 24px;
max-width: 240px;
height: 24px;
padding: 0 5.5px 0 3.5px;
border-radius: var(--radius-2);
background: var(--l3-background-60);
color: var(--l2-foreground);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
line-height: 15px;
transition:
background-color 0.12s,
color 0.12s;
&:hover,
&:focus-within {
background: var(--l2-background-hover);
color: var(--l1-foreground-hover);
}
// Collapsed rather than hidden, so the keyboard can still reach it and open it up.
> [data-slot='button'] {
max-width: 0;
margin-left: 0;
overflow: hidden;
opacity: 0;
transition:
max-width 0.12s,
margin-left 0.12s,
opacity 0.12s;
--button-height: 15px;
}
&:hover > [data-slot='button'],
&:focus-within > [data-slot='button'] {
max-width: 12px;
margin-left: var(--spacing-2);
opacity: 1;
}
}
.icon {
flex-shrink: 0;
box-sizing: content-box;
padding: 0 3px;
}
.category {
flex-shrink: 0;
margin-right: var(--spacing-2);
text-transform: lowercase;
}
.label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

View File

@@ -1,44 +0,0 @@
import { Button } from '@signozhq/ui/button';
import { Package, X } from '@signozhq/icons';
import styles from './ContextPill.module.scss';
interface ContextPillProps {
icon: typeof Package;
category: string;
label: string;
onRemove?: () => void;
}
/** A context attached to the next message; the remove button shows on hover or focus. */
export default function ContextPill({
icon: Icon,
category,
label,
onRemove,
}: ContextPillProps): JSX.Element {
return (
<div
className={styles.pill}
title={`${category}: ${label}`}
data-testid="ai-context-pill"
>
<Icon size={14} className={styles.icon} />
<span className={styles.category}>{category} :</span>
<span className={styles.label}>{label}</span>
{onRemove && (
<Button
variant="link"
size="sm"
icon
color="secondary"
onClick={onRemove}
aria-label={`Remove ${category}: ${label} context`}
testId="ai-context-pill-remove"
>
<X size={12} />
</Button>
)}
</div>
);
}

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,41 +0,0 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent } 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();
});
it('lets the user type but not send while sending is blocked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onSend = jest.fn() as jest.MockedFunction<
ComponentProps<typeof ChatInput>['onSend']
>;
render(<ChatInput onSend={onSend} sendDisabled />);
const textarea = screen.getByTestId('ai-chat-input-textarea');
await user.type(textarea, 'next question{Enter}');
expect(textarea).toHaveValue('next question');
expect(onSend).not.toHaveBeenCalled();
});
});

View File

@@ -1,35 +0,0 @@
import type { ComponentProps } from 'react';
import type { MessageContext } from 'api/ai-assistant/chat';
import { render, screen, userEvent } from 'tests/test-utils';
import ChatInput from '../ChatInput';
const serviceContext: MessageContext = {
source: 'auto',
type: 'service',
resourceId: 'checkout',
};
describe('ChatInput — context pills', () => {
it('names a page context by its type and drops it on remove', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onDismissAutoContext = jest.fn() as jest.MockedFunction<
NonNullable<ComponentProps<typeof ChatInput>['onDismissAutoContext']>
>;
render(
<ChatInput
onSend={jest.fn()}
autoContexts={[serviceContext]}
onDismissAutoContext={onDismissAutoContext}
/>,
);
expect(screen.getByTestId('ai-context-pill')).toHaveTextContent(
'Service :checkout',
);
await user.click(screen.getByTestId('ai-context-pill-remove'));
expect(onDismissAutoContext).toHaveBeenCalledWith('auto:service:checkout:');
});
});

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

@@ -1,13 +1,4 @@
import {
BarChart,
Bell,
DraftingCompass,
LayoutDashboard,
Package,
ScrollText,
} from '@signozhq/icons';
import { MessageContext } from '../../../../api/ai-assistant/chat';
import { Bell, LayoutDashboard, ShieldCheck } from '@signozhq/icons';
/** Ordered category tabs shown in the @-mention context picker. */
export const CONTEXT_CATEGORIES = ['Dashboards', 'Alerts', 'Services'] as const;
@@ -21,41 +12,9 @@ export type ContextCategory = (typeof CONTEXT_CATEGORIES)[number];
export const CONTEXT_CATEGORY_ICONS = {
Dashboards: LayoutDashboard,
Alerts: Bell,
Services: Package,
Services: ShieldCheck,
} satisfies Record<ContextCategory, unknown>;
/** What one item of each category is called, e.g. on its context pill. */
export const CONTEXT_CATEGORY_SINGULAR: Record<ContextCategory, string> = {
Dashboards: 'Dashboard',
Alerts: 'Alert',
Services: 'Service',
};
/** What one item of each context type is called. */
export const CONTEXT_TYPE_LABELS: Record<MessageContext['type'], string> = {
dashboard: 'Dashboard',
alert: 'Alert',
service: 'Service',
logs_explorer: 'Logs',
traces_explorer: 'Traces',
metrics_explorer: 'Metrics',
saved_view: 'Saved view',
};
/** Icon per page context: the picker's for the categories it shares, the side nav's for explorers. */
export const AUTO_CONTEXT_ICONS: Record<
MessageContext['type'],
typeof Package
> = {
dashboard: CONTEXT_CATEGORY_ICONS.Dashboards,
alert: CONTEXT_CATEGORY_ICONS.Alerts,
service: CONTEXT_CATEGORY_ICONS.Services,
logs_explorer: ScrollText,
traces_explorer: DraftingCompass,
metrics_explorer: BarChart,
saved_view: Package,
};
/**
* Resolved copy + composer prefill for one render of the context picker's empty
* state. The picker is tabbed, so a user only ever views one category at a

View File

@@ -1,23 +1,13 @@
.clarification {
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
padding: var(--spacing-6);
padding: 10px 12px;
background: var(--l2-background);
display: flex;
flex-direction: column;
gap: var(--spacing-6);
gap: 10px;
width: 100%;
// Clear of whatever the reply shows above it.
&:not(:first-child) {
margin-top: var(--spacing-6);
}
// Below the header, everything lines up with the title, clear of the icon.
&:not(.submitted) > :not(.header) {
margin-left: calc(16px + var(--spacing-6));
}
&.submitted {
border-color: var(--l2-border);
background: transparent;
@@ -31,7 +21,7 @@
.header {
display: flex;
align-items: center;
gap: var(--spacing-6);
gap: 6px;
}
.headerIcon {
@@ -40,17 +30,16 @@
}
.headerLabel {
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
font-size: 12px;
font-weight: 600;
color: var(--l1-foreground);
}
.message {
font-size: 13px;
color: var(--l1-foreground);
margin: 0;
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
line-height: 1.5;
}
.icon {
@@ -142,8 +131,7 @@
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--spacing-6);
margin-top: var(--spacing-2);
display: flex;
gap: 6px;
margin-top: 16px;
}

View File

@@ -121,7 +121,7 @@ export default function ClarificationForm({
return (
<div className={styles.clarification}>
<div className={styles.header}>
<CircleHelp size={16} className={styles.headerIcon} />
<CircleHelp size={13} className={styles.headerIcon} />
<span className={styles.headerLabel}>A few details needed</span>
</div>
@@ -146,7 +146,6 @@ export default function ClarificationForm({
: 'Fill in the required fields first'
}
size="md"
width="100%"
variant="solid"
color="primary"
onClick={handleSubmit}
@@ -158,7 +157,6 @@ export default function ClarificationForm({
<Button
disabledTooltip="Wait for the response to finish"
size="md"
width="100%"
variant="outlined"
color="secondary"
onClick={handleCancel}

View File

@@ -1,14 +1,30 @@
.item {
display: flex;
align-items: center;
gap: var(--spacing-3);
padding: 7px 0;
gap: 7px;
padding: 6px 8px;
border-radius: var(--radius-2);
cursor: pointer;
min-width: 0;
position: relative;
// Driven below: hover, the open chat, keyboard focus and an open menu reveal the action buttons.
// Driven below: hover and active reveal the action buttons.
--actions-opacity: 0;
&:hover {
background: var(--l2-background);
--actions-opacity: 1;
}
&.active {
background: var(--l2-background);
--actions-opacity: 1;
.title {
color: var(--l1-foreground);
font-weight: 500;
}
}
&.archived {
opacity: 0.92;
@@ -16,68 +32,34 @@
color: var(--l3-foreground);
}
}
&:hover,
&.active,
&:focus-visible,
&:has(:focus-visible),
&:has([data-popup-open]) {
--actions-opacity: 1;
--actions-pointer: auto;
.title {
color: var(--l1-foreground);
}
}
}
// Lights up while Noz is replying in that chat; the slot keeps every title aligned.
.dot {
.icon {
flex-shrink: 0;
width: 6px;
height: 6px;
border-radius: 50%;
&.isReplying {
background: var(--accent-amber);
}
color: var(--l3-foreground);
}
.body {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--spacing-4);
flex-direction: column;
gap: 1px;
}
.title {
font-size: var(--periscope-font-size-base);
line-height: 20px;
letter-spacing: -0.005em;
color: var(--text-vanilla-400);
font-size: 12px;
color: var(--l2-foreground);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.4;
}
// vanilla-400 doesn't follow the theme.
:global(.lightMode) .title {
color: var(--l2-foreground);
}
// Gives way to the action buttons that float over it.
.time {
flex-shrink: 0;
// Wide enough to hold the action buttons that replace it.
min-width: 16px;
text-align: right;
font-size: var(--periscope-font-size-small);
line-height: 18px;
font-size: 10px;
color: var(--l3-foreground);
opacity: calc(1 - var(--actions-opacity, 0));
transition: opacity 0.12s;
opacity: 0.7;
}
.input {
@@ -87,7 +69,7 @@
border-bottom: 1px solid var(--accent-primary);
outline: none;
color: var(--l1-foreground);
font-size: var(--periscope-font-size-base);
font-size: 12px;
font-family: inherit;
padding: 1px 0;
}
@@ -101,11 +83,48 @@
transition: opacity 0.12s;
// Float over the right edge of the item so the title can keep using
// the full width while the buttons are hidden — no layout shift +
// no premature truncation. They sit in the time's slot, so they never
// cover the title.
// no premature truncation. The `background` matches the hover/active
// state so the buttons visually mask any title text underneath.
position: absolute;
top: 50%;
right: 0;
right: 4px;
transform: translateY(-50%);
background: var(--l2-background);
padding: 1px 2px;
border-radius: var(--radius-2);
pointer-events: var(--actions-pointer, none);
}
.item:hover,
.item.active {
--actions-pointer: auto;
}
// Compact menu — narrower than the design-system default so the
// content (Rename / Copy link / Archive) doesn't dwarf the row.
// Shared sizing for every dropdown item so the menu reads compact —
// matches the row's own 12px label scale.
.menuItem {
font-size: 12px !important;
cursor: pointer !important;
}
// Amber treatment for the destructive-but-recoverable Archive action —
// less alarming than red since the conversation can be restored later.
// Targets both the label text and the leading icon (icons inherit color
// via `currentColor`).
.archiveItem {
color: var(--accent-amber) !important;
svg {
color: inherit !important;
}
}
.restoreItem {
color: var(--primary) !important;
svg {
color: inherit !important;
}
}

View File

@@ -13,10 +13,10 @@ import {
ArchiveRestore,
EllipsisVertical,
Link,
MessageSquare,
Pencil,
} from '@signozhq/icons';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Conversation } from '../../types';
import styles from './ConversationItem.module.scss';
@@ -37,18 +37,18 @@ function formatRelativeTime(ts: number): string {
const diff = Date.now() - ts;
const mins = Math.floor(diff / 60_000);
if (mins < 1) {
return 'now';
return 'just now';
}
if (mins < 60) {
return `${mins}m`;
return `${mins}m ago`;
}
const hrs = Math.floor(mins / 60);
if (hrs < 24) {
return `${hrs}h`;
return `${hrs}h ago`;
}
const days = Math.floor(hrs / 24);
if (days < 7) {
return `${days}d`;
return `${days}d ago`;
}
return new Date(ts).toLocaleDateString(undefined, {
month: 'short',
@@ -70,9 +70,6 @@ export default function ConversationItem({
const [, copyToClipboard] = useCopyToClipboard();
const isArchived = Boolean(conversation.archived);
const isReplying = useAIAssistantStore((s) =>
Boolean(s.streams[conversation.id]?.isStreaming),
);
const displayTitle = conversation.title ?? 'New conversation';
const ts = conversation.updatedAt ?? conversation.createdAt;
@@ -129,14 +126,14 @@ export default function ConversationItem({
type: 'item',
value: 'rename',
label: 'Rename',
prefix: <Pencil size={16} />,
prefix: <Pencil size={12} />,
onClick: (): void => startEditing(),
},
{
type: 'item',
value: 'copy-link',
label: 'Copy link',
prefix: <Link size={16} />,
prefix: <Link size={12} />,
onClick: handleCopyLink,
},
{ type: 'separator', value: 'divider' },
@@ -148,7 +145,7 @@ export default function ConversationItem({
type: 'item',
value: 'restore',
label: 'Restore',
prefix: <ArchiveRestore size={16} />,
prefix: <ArchiveRestore size={12} />,
onClick: (): void => onRestore(conversation.id),
},
]
@@ -158,8 +155,7 @@ export default function ConversationItem({
type: 'item',
value: 'archive',
label: 'Archive',
prefix: <Archive size={16} />,
danger: true,
prefix: <Archive size={12} />,
onClick: (): void => onArchive(conversation.id),
},
];
@@ -176,7 +172,7 @@ export default function ConversationItem({
}
}}
>
<span className={cx(styles.dot, { [styles.isReplying]: isReplying })} />
<MessageSquare size={12} className={styles.icon} />
<div className={styles.body}>
{isEditing ? (

View File

@@ -1,25 +1,18 @@
// Laid out like the message list, so the thread lands where its placeholder was.
.thread {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
padding: var(--spacing-8) 0 var(--spacing-32);
overflow: hidden;
padding: 16px 0;
gap: 14px;
}
.message {
display: flex;
padding: var(--spacing-4) var(--spacing-8);
padding: 0 16px;
.compact & {
padding: var(--spacing-3);
}
// As wide as the full-page input; the extra 32px is the rows' own gutters.
.fullPage & {
width: 100%;
max-width: calc(var(--noz-page-column) + 32px);
margin: 0 auto;
&.compact {
padding: 0 12px;
}
}
@@ -27,46 +20,65 @@
justify-content: flex-end;
}
.userBubble {
display: flex;
max-width: 80%;
padding: var(--spacing-4) var(--spacing-6);
border-radius: var(--radius-3);
background: var(--l3-background-60);
.assistant {
justify-content: flex-start;
}
// Bare lines of text, inset like a reply.
.reply {
.bubble {
display: flex;
flex-direction: column;
width: 80%;
padding: 0 var(--spacing-4);
gap: 8px;
// `width: 100%` (capped by per-role max-width below) forces the bubble
// to fill its allotted slot rather than collapsing to the longest line —
// otherwise the lines' percent widths cascade into a tiny bubble.
width: 100%;
border-radius: var(--radius-2);
padding: 12px 14px;
.compact & {
width: 90%;
&.user {
// Narrower than the assistant bubble so the alternating chat-thread
// asymmetry is preserved — but wider than the previous 80% so the
// shimmer lines have room to read as a real-looking message.
max-width: 75%;
// Subtle primary tint so the right-side bubble reads as the user's
// message without committing to the full saturated brand color.
background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
border-bottom-right-radius: var(--radius-2);
color: var(--l1-foreground);
}
.fullPage & {
width: 100%;
padding: 0 0 0 var(--spacing-5);
&.assistant {
max-width: 95%;
background: var(--l2-background);
border-bottom-left-radius: var(--radius-2);
}
}
// A bar in the middle of a 20px line, the height of the text it stands in for.
.line {
margin-block: 5px;
--skeleton-input-height: 10px;
--skeleton-input-width: 100%;
--skeleton-input-min-width: 0;
--skeleton-input-border-radius: var(--radius-1);
--skeleton-background: color-mix(
in srgb,
var(--l1-foreground),
transparent 92%
);
--skeleton-shimmer-color: color-mix(
in srgb,
var(--l1-foreground),
transparent 92%
);
height: 9px;
border-radius: 3px;
position: relative;
overflow: hidden;
background: color-mix(in srgb, var(--l1-foreground) 10%, transparent);
// Shimmer sweep — same pattern used by HistorySidebar's skeleton rows.
&::after {
content: '';
position: absolute;
inset: 0;
transform: translateX(-100%);
background: linear-gradient(
90deg,
transparent,
color-mix(in srgb, var(--l1-foreground) 10%, transparent),
transparent
);
animation: shimmer 1.15s ease-in-out infinite;
}
}
@keyframes shimmer {
100% {
transform: translateX(100%);
}
}

View File

@@ -1,69 +1,51 @@
import cx from 'classnames';
import { Skeleton } from '@signozhq/ui/skeleton';
import { useVariant } from '../../VariantContext';
import styles from './ConversationSkeleton.module.scss';
/**
* Each entry is one message in the placeholder thread:
* user: a sent bubble, `width` as % of the row
* assistant: a reply, one width per line as % of the reply
* Each entry is one bubble in the placeholder thread:
* role: who "sent" the bubble — drives left/right alignment + colour
* lines: list of widths (as % of the bubble) for the shimmer lines inside
*
* Mixed widths and varying line counts produce something that scans as a real
* back-and-forth conversation rather than a uniform grid.
*/
const PATTERN: (
| { role: 'user'; width: number }
| { role: 'assistant'; lines: number[] }
)[] = [
{ role: 'user', width: 42 },
{ role: 'assistant', lines: [94, 88, 66] },
{ role: 'user', width: 30 },
{ role: 'assistant', lines: [90, 96, 84, 58] },
{ role: 'user', width: 36 },
{ role: 'assistant', lines: [86, 70] },
const ROWS: { role: 'user' | 'assistant'; lines: number[] }[] = [
{ role: 'user', lines: [62] },
{ role: 'assistant', lines: [85, 92, 70] },
{ role: 'user', lines: [55, 40] },
{ role: 'assistant', lines: [90, 78, 95, 60] },
{ role: 'user', lines: [48] },
{ role: 'assistant', lines: [80, 88] },
];
// Enough repeats to fill a tall pane down to the input; the thread clips the rest.
const ROWS = [...PATTERN, ...PATTERN, ...PATTERN, ...PATTERN];
/** Skeleton chat thread shown while a single conversation is being loaded. */
export default function ConversationSkeleton(): JSX.Element {
const variant = useVariant();
const isCompact = variant === 'panel';
return (
<div
className={cx(styles.thread, {
[styles.compact]: variant === 'panel',
[styles.fullPage]: variant === 'page',
})}
aria-busy
aria-label="Loading conversation"
>
<div className={styles.thread} aria-busy aria-label="Loading conversation">
{ROWS.map((row, idx) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={idx}
className={cx(styles.message, { [styles.user]: row.role === 'user' })}
className={cx(styles.message, styles[row.role], {
[styles.compact]: isCompact,
})}
>
{row.role === 'user' ? (
<div className={styles.userBubble} style={{ width: `${row.width}%` }}>
<Skeleton.Input active className={styles.line} />
</div>
) : (
<div className={styles.reply}>
{row.lines.map((width, lineIdx) => (
<Skeleton.Input
// eslint-disable-next-line react/no-array-index-key
key={lineIdx}
active
className={styles.line}
style={{ width: `${width}%` }}
/>
))}
</div>
)}
<div className={cx(styles.bubble, styles[row.role])}>
{row.lines.map((width, lineIdx) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={lineIdx}
className={styles.line}
style={{ width: `${width}%` }}
/>
))}
</div>
</div>
))}
</div>

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