Compare commits

..

10 Commits

Author SHA1 Message Date
Vinícius Lourenço
d6057e6384 chore(orval): update generated types 2026-05-13 08:41:38 -03:00
Vinícius Lourenço
ed969a79b2 chore(pnpm): upgrade deps & add minimum release age 2026-05-13 08:39:51 -03:00
SagarRajput-7
d15065b808 feat(authz): enable multi role assignment for members page (#11269)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
Release Drafter / update_release_draft (push) Waiting to run
* feat(authz): enable multi role assignment for members page

* feat(authz): enable multi role assignemnt for users

---------

Co-authored-by: vikrantgupta25 <vikrant@signoz.io>
2026-05-13 11:16:59 +00:00
Nageshbansal
757c4e8ea9 chore: revert the v0.123.0 release (#11286) 2026-05-13 10:45:12 +00:00
Nityananda Gohain
b55c009c31 fix: disable opamp integration for llm (#11284) 2026-05-13 08:38:29 +00:00
Gaurav Tewari
9cb6228da5 fix: replace logs with list icon (#11283)
Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-05-13 08:11:45 +00:00
Nikhil Mantri
951f55b062 feat(infra-monitoring): v2 deployments list api (#11140)
* chore: baseline setup

* chore: endpoint detail update

* chore: added logic for hosts v3 api

* fix: bug fix

* chore: disk usage

* chore: added validate function

* chore: added some unit tests

* chore: return status as a string

* chore: yarn generate api

* chore: removed isSendingK8sAgentsMetricsCode

* chore: moved funcs

* chore: added validation on order by

* chore: added pods list logic

* chore: updated openapi yml

* chore: updated spec

* chore: pods api meta start time

* chore: nil pointer check

* chore: nil pointer dereference fix in req.Filter

* chore: added temporalities of metrics

* chore: added pods metrics temporality

* chore: unified composite key function

* chore: code improvements

* chore: added pods list api updates

* chore: hostStatusNone added for clarity that this field can be left empty as well in payload

* chore: yarn generate api

* chore: return errors from getMetadata and lint fix

* chore: return errors from getMetadata and lint fix

* chore: added hostName logic

* chore: modified getMetadata query

* chore: add type for response and files rearrange

* chore: warnings added passing from queryResponse warning to host lists response struct

* chore: added better metrics existence check

* chore: added a TODO remark

* chore: added required metrics check

* chore: distributed samples table to local table change for get metadata

* chore: frontend fix

* chore: endpoint correction

* chore: endpoint modification openapi

* chore: escape backtick to prevent sql injection

* chore: rearrage

* chore: improvements

* chore: validate order by to validate function

* chore: improved description

* chore: added TODOs and made filterByStatus a part of filter struct

* chore: ignore empty string hosts in get active hosts

* feat(infra-monitoring): v2 hosts list - return counts of active & inactive hosts for custom group by attributes (#10956)

* chore: add functionality for showing active and inactive counts in custom group by

* chore: bug fix

* chore: added subquery for active and total count

* chore: ignore empty string hosts in get active hosts

* fix: sinceUnixMilli for determining active hosts compute once per request

* chore: refactor code

* chore: rename HostsList -> ListHosts

* chore: rearrangement

* chore: inframonitoring types renaming

* chore: added types package

* chore: file structure further breakdown for clarity

* chore: comments correction

* chore: removed temporalities

* chore: pods code restructuring

* chore: comments resolve

* chore: added json tag required: true

* chore: removed pod metric temporalities

* chore: removed internal server error

* chore: added status unauthorized

* chore: remove a defensive nil map check, the function ensure non-nil map when err nil

* chore: cleanup and rename

* chore: make sort stable in case of tiebreaker by comparing composite group by keys

* chore: regen api client for inframonitoring

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: added phase counts feature

* chore: added queries for pod phase counts in custom group by

* chore: added required tags

* chore: added support for pod phase unknown

* chore: removed pods - order by phase

* chore: improved api description to document -1 as no data in numeric fields

* fix: rebase fixes

* chore: added unknown phase count

* fix: isPodUIDInGroupBy in buildPodRecords

* chore: 3 cte --> 2 cte

* chore: pod phase with local table of time series as counts

* chore: comment correction

* chore: corrected comment

* chore: value column for samples table added

* chore: removed query G for phase counts

* chore: rename variable

* chore: added PodPhaseNum constants to types

* feat(infra-monitoring): v2 pods list apis - phase counts when custom grouping (#11088)

* chore: added phase counts feature

* chore: added queries for pod phase counts in custom group by

* chore: added unknown phase count

* fix: isPodUIDInGroupBy in buildPodRecords

* chore: 3 cte --> 2 cte

* chore: pod phase with local table of time series as counts

* chore: comment correction

* chore: corrected comment

* chore: value column for samples table added

* chore: removed query G for phase counts

* chore: rename variable

* chore: added PodPhaseNum constants to types

* chore: nodes list v2 full blown

* chore: metadata fix

* chore: updated comment

* chore: namespaces code

* chore: v2 nodes api

* chore: rename

* chore: v2 clusters list api

* chore: namespaces code

* chore: rename

* chore: review clusters PR

* chore: pvcs code added

* chore: updated endpoint and spec

* chore: pvcs todo

* chore: added condition

* chore: added filter

* chore: added code for deployments

* chore: query nit

* chore: added base deployments change

* chore: added base condition

* chore: added pod phase counts

* chore: for pods and nodes, replace none with no_data

* chore: node and pod counts structs added

* chore: namespace record uses PodCountsByPhase

* chore: cluster record uses PodCountsByPhase, NodeCountsByReadiness

* chore: deployment record uses PodCountsByPhase

* chore: metrics existence check

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Ashwin Bhatkal <ashwin96@gmail.com>
2026-05-13 06:59:08 +00:00
primus-bot[bot]
42ef704077 chore(release): bump to v0.123.0 (#11282)
Co-authored-by: primus-bot[bot] <171087277+primus-bot[bot]@users.noreply.github.com>
2026-05-13 06:58:11 +00:00
Aditya Singh
515220194d Feat/trace details pending 2 (#11255)
* feat: span details init

* feat: span details header

* feat: details field component

* feat: added span percentile

* feat: key attr section added

* feat: added pretty view

* feat: update yarn lock

* feat: minor change

* feat: search in pretty view

* feat: refactor

* feat: style fix

* feat: json viewer with select dropdown added

* feat: span details floating drawer added

* feat: span details folder rename

* feat: replace draggable package

* feat: fix pinning. fix drag on top

* feat: add bound to drags while floating

* feat: add collapsible sections in trace details

* feat: use resizable for waterfall table as well

* feat: copy link change and url clear on span close

* feat: fix span details headr

* feat: key value label style fixes

* feat: linked spans

* feat: style fixes

* feat: setup types and interface for waterfall v3

v3 is required for udpating the response json of
the waterfall api. There wont' be any logical change.
Using this requirement as an opportunity to move
waterfall api to provider codebase architecture from
older query-service

* refactor: move type conversion logic to types pkg

* chore: add reason for using snake case in response

* fix: update span.attributes to map of string to any

To support otel format of diffrent types of attributes

* fix: remove unused fields and rename span type

To avoid confusing with otel span

* refactor: convert waterfall api to modules format

* chore: add same test cases as for old waterfall api

* chore: avoid sorting on every traversal

* fix: remove unused fields and rename span type

To avoid confusing with otel span

* fix: rename timestamp to milli for readability

* fix: add timeout to module context

* fix: use typed paramter field in logs

* feat: api integration

* feat: add limit

* feat: minor change

* feat: supress click

* chore: generate openapi spec for v3 waterfall

* feat: fix test

* feat: fix test

* feat: lint fix

* feat: span details ux

* feat: analytics

* feat: add icons

* feat: added loading to flamegraph and timeout to webworker

* feat: sync error and loading state for flamegraph for n/w and computation logic

* feat: auto scroll horizontally to span

* feat: show total span count

* feat: disable anaytics span tab for now

* feat: add span details loader

* feat: prevent api call on closing span detail

* fix: remove timeout since waterfall take longer

* fix: use int16 for status code as per db schema

* fix: update openapi specs

* feat: make filter and search work with flamegraph

* feat: filter ui fix

* feat: remove trace header

* feat: new filter ui

* feat: setup types and interface for waterfall v3

v3 is required for udpating the response json of
the waterfall api. There wont' be any logical change.
Using this requirement as an opportunity to move
waterfall api to provider codebase architecture from
older query-service

* refactor: move type conversion logic to types pkg

* chore: add reason for using snake case in response

* fix: update span.attributes to map of string to any

To support otel format of diffrent types of attributes

* fix: remove unused fields and rename span type

To avoid confusing with otel span

* refactor: convert waterfall api to modules format

* chore: add same test cases as for old waterfall api

* chore: avoid sorting on every traversal

* fix: remove unused fields and rename span type

To avoid confusing with otel span

* fix: rename timestamp to milli for readability

* fix: add timeout to module context

* fix: use typed paramter field in logs

* chore: generate openapi spec for v3 waterfall

* fix: remove timeout since waterfall take longer

* fix: use int16 for status code as per db schema

* fix: update openapi specs

* feat: api integration

* feat: automatically scroll left on vertical scroll

* feat: reduce time

* feat: set limit to 100k for flamegraph

* feat: show child count in waterfall

* fix: align timeline and span length in flamegraph and waterfall

* feat: fix flamegraph and waterfall bg color

* feat: show caution on sampled flamegraph

* feat: api integration v3

* feat: disable scroll to view for collapse and uncollapse

* feat: setup types and interface for waterfall v3

v3 is required for udpating the response json of
the waterfall api. There wont' be any logical change.
Using this requirement as an opportunity to move
waterfall api to provider codebase architecture from
older query-service

* refactor: move type conversion logic to types pkg

* chore: add reason for using snake case in response

* fix: update span.attributes to map of string to any

To support otel format of diffrent types of attributes

* fix: remove unused fields and rename span type

To avoid confusing with otel span

* refactor: convert waterfall api to modules format

* chore: add same test cases as for old waterfall api

* chore: avoid sorting on every traversal

* fix: remove unused fields and rename span type

To avoid confusing with otel span

* fix: rename timestamp to milli for readability

* fix: add timeout to module context

* fix: use typed paramter field in logs

* chore: generate openapi spec for v3 waterfall

* fix: remove timeout since waterfall take longer

* fix: use int16 for status code as per db schema

* fix: update openapi specs

* refactor: break down GetWaterfall method for readability

* chore: avoid returning nil, nil

* refactor: move type creation and constants to types package

- Move DB/table/cache/windowing constants to tracedetailtypes package
- Add NewWaterfallTrace and NewWaterfallResponse constructors in types
- Use constructors in module.go instead of inline struct literals
- Reorder waterfall.go so public functions precede private ones

* refactor: extract ClickHouse queries into a store abstraction

Move GetTraceSummary and GetTraceSpans out of module.go into a
traceStore interface backed by clickhouseTraceStore in store.go.
The module struct now holds a traceStore instead of a raw
telemetrystore.TelemetryStore, keeping DB access separate from
business logic.

* refactor: move error to types as well

* refactor: separate out store calls and computations

* refactor: breakdown GetSelectedSpans for readability

* refactor: return 404 on missing trace and other cleanup

* refactor: use same method for cache key creation

* chore: remove unused duration nano field

* chore: use sqlbuilder in clickhouse store where possible

* feat: dropdown added to span details

* feat: fix color duplications

* feat: no data screen

* feat: old trace btn added

* feat: minor fix

* feat: rename copy to copy value

* feat: delete unused file

* feat: use semantic tokens

* feat: use semantic tokens

* feat: add crosshair

* feat: fix test

* feat: disable crosshair in waterfall

* feat: fix colors

* feat: minor fix

* feat: add status codes

* feat: load all spans in waterfall under limit

* feat: uncollapse spans on select from flamegraph

* feat: style fix

* feat: add service name

* feat: open in new tab

* feat: add trace details header

* feat: add trace details header styles

* feat: add trace details header styles

* feat: minor changes

* feat: floating fields set

* feat: filters init

* feat: filter toggle added

* feat: fix color

* fix: scroll to span in frontend mode

* feat: delete waterfall go

* feat: minor change

* feat: minor change

* feat: lint fix

* feat: analytics spans

* feat: color by field

* feat: save color by pref in user pref

* feat: migrate v2 pinned attr

* feat: preview fields

* feat: minor refactors

* feat: minor refactors

* feat: v3 behind feature flag

* feat: minor refactors

* feat: packages remove

* feat: packages remove

* feat: remove common component

* feat: remove antd component usage

* feat: leaf node indent fix

* feat: fix mouse wheel in json view

* feat: update signoz ui

* feat: remove feature flag

* feat: fixed the waterfall span hover card

* feat: fix hidden filters

* feat: trace details always visible

* feat: correct status code

* fix: pagination calls in waterfall

* feat: fix failing test

* feat: show error count

* feat: fix waterfall child sibling indent

* feat: change how we show span hover data in waterfall

* feat: fix logs in span details styles

* feat: minor fixes

* feat: make trace id copyable

* feat: add status message to highlight section

* feat: persist user choosing old view

* feat: add more fields in color by

* feat: add llm as fast filter

* feat: show api error correctly

* feat: update test cases

* feat: revert route change

* feat: revert route change

* feat: replace antd btns

* feat: allow removing all fields in preview

* feat: send selected span when flamegraph is sampled

* feat: only scroll when span is not in view

* feat: auto expand on highlight errors

* feat: move analytics panel

* feat: additional check

* feat: minor fix

* feat: minor fix

* feat: dont use antd button and tooltip

* feat: dont use antd button and tooltip

* feat: update icons

* feat: minor change

* feat: minor change

* feat: move to zustand

* feat: update test cases

* feat: update border color

* feat: add icons

* feat: support filter on parent keys

* feat: add links to non filterable keys

* feat: minor fix

* feat: use pinned attributes accross views

* feat: update tests

* feat: hide v3

---------

Co-authored-by: Nikhil Soni <nikhil.soni@signoz.io>
2026-05-13 06:07:25 +00:00
Yunus M
ac5ccbf186 feat: AI Assistant UI (#10992)
* feat: add AI Assistant with interactive blocks for data visualization

* feat: add AI Assistant with interactive blocks for data visualization

* chore: format taglines for better readability in AIAssistantIconPreview

* feat: add AI Assistant action block and speech recognition capabilities

* feat: enhance voice input functionality and integrate streaming chat

* feat: implement message feedback component and enhance message bubble styling

* feat: enhance AI Assistant SSE event handling and markdown rendering

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: implement thread management and feedback submission in AI Assistant

* feat: refactor AI Assistant state management to support per-conversation streaming

* chore: remove unused icons and page

* feat: introduce thinking step and message block structure in AI Assistant

* refactor: update Tooltip imports to use @signozhq/ui across components

* refactor: migrate button components to @signozhq/ui and update styles for consistency

* feat: enhance home header layout with new HeaderRightSection component and updated styles

* refactor: improve code readability and consistency

* feat: integrate AI assistant feature with conditional routing and environment configuration

* feat: update openapi.yml and improve ui

* feat: add character limit warning to ChatInput component

* feat: enhance AI Assistant button with pending user input badge and styles

* feat: implement conversation archiving and restoration functionality in AI Assistant

* feat: streamline AI Assistant UI components and improve styles

* feat: add MessageContext interface and enhance message sending functionality in AI Assistant

* feat: update AI Assistant styles and components to use new icon library and improve layout

* feat: move to css modules

* feat: enhance AI Assistant with new API integration and UI components

* refactor: update AIAssistant components to use Button from Signoz UI and enhance styling

* refactor: simplify action handling and enhance streaming message indicators

* refactor: improve loading indicators in HistorySidebar component

* refactor: enhance ConversationView loading state and improve action key stability

* refactor: implement AIAssistant axios instance and enhance SSE authentication handling

* refactor: support auto-derived contexts and enhance diff display functionality

* refactor: enhance ChatInput component with improved overflow handling and context fetching logic

* refactor: enhance AIAssistantModal and ConversationItem components with improved key handling and UI

* refactor: streamline Spinner component and update ChatInput styles for improved UI consistency

* feat: implement push-to-talk functionality in ChatInput for improved voice interaction

* feat: add edit and resend functionality to user messages in ConversationView and ChatInput

* feat: implement AI Assistant UI components for enhanced user interaction

* feat: improve tool call instance rendering

* feat: add accessibility attributes and feedback buttons to HeaderRightSection

* chore: update openapi.yaml with improved formatting and structure for API documentation

* feat: enhance AI Assistant components with new enums, improved clarification handling, code block

* refactor: remove edit and resend functionality, streamline message handling

* refactor: remove AI backend URL from environment variables

* refactor: update styles and structure for MessageBubble, ThinkingStep, and ToolCallStep components

* feat: enhance conversation item and history sidebar with search functionality and dropdown actions

* feat: update AI Assistant UI components with new icons

* feat: add displayText property to ToolCallBlock

* feat: implement message regeneration functionality in AI Assistant

* feat: pass comment for negative feedback

* fix(frontend): position chat support around AI assistant

* feat: add SigNoz URL header to AI Assistant requests for multi-tenant support

* feat: add header actions to TraceDetailV2 for sharing and feedback

* chore: remove hardcoded url

* fix: skip custom AI block markers in language validation script

* feat: implement AI API instance with request/response interceptors

* feat: enhance AI Assistant conversation handling with hydration state

* feat: implement SSE backoff strategy and error handling in AI Assistant

* refactor: update color variables in AI Assistant styles for consistency and improved theming

* chore: increase margin for title in Block component for improved spacing

* chore: fmt

* feat: use default domain url for X-SigNoz-URL

* refactor: simplify AIAssistant enabled state management across components

* refactor: replace HistorySidebar with ConversationsList component in AIAssistant

* feat: improve css

* feat: enhance voice input functionality with microphone permission handling

* feat: add rule to enforce subpath imports for @signozhq/ui components

* fix: renameConversation requires reload to render

* refactor: update imports for @signozhq/ui components to use subpath imports

* refactor: adjust imports for @signozhq/ui components to use specific subpath imports

* chore: remove temp files

* chore: remove temp files

* chore: move types to ai assistant folder

* chore: remove unused chart blocks from AI assistant

Removes BarChart, LineChart, PieChart, and Timeseries block components
along with the shared chartSetup and Chart.module.scss. These rendered
hex-color literals outside the design-token system and weren't being
emitted by any current response flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: update header button color to use accent primary

* chore: remove the rule files

* chore: remove react chartjs

* refactor: replace hardcoded radius values with CSS variables

* chore: use css variable

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: makeavish <makeavish786@gmail.com>
2026-05-13 06:03:02 +00:00
249 changed files with 23561 additions and 17560 deletions

View File

@@ -29,7 +29,6 @@ import (
"github.com/SigNoz/signoz/pkg/modules/cloudintegration/implcloudintegration"
"github.com/SigNoz/signoz/pkg/modules/dashboard"
"github.com/SigNoz/signoz/pkg/modules/dashboard/impldashboard"
"github.com/SigNoz/signoz/pkg/modules/tag"
"github.com/SigNoz/signoz/pkg/modules/organization"
"github.com/SigNoz/signoz/pkg/modules/retention"
"github.com/SigNoz/signoz/pkg/modules/rulestatehistory"
@@ -104,8 +103,8 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
return openfgaauthz.NewProviderFactory(sqlstore, openfgaschema.NewSchema().Get(ctx), openfgaDataStore, authtypes.NewRegistry()), nil
},
func(store sqlstore.SQLStore, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, _ querier.Querier, _ licensing.Licensing, tagModule tag.Module) dashboard.Module {
return impldashboard.NewModule(impldashboard.NewStore(store), store, settings, analytics, orgGetter, queryParser, tagModule)
func(store sqlstore.SQLStore, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, _ querier.Querier, _ licensing.Licensing) dashboard.Module {
return impldashboard.NewModule(impldashboard.NewStore(store), settings, analytics, orgGetter, queryParser)
},
func(_ licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config] {
return noopgateway.NewProviderFactory()

View File

@@ -48,7 +48,6 @@ import (
pkgcloudintegration "github.com/SigNoz/signoz/pkg/modules/cloudintegration/implcloudintegration"
"github.com/SigNoz/signoz/pkg/modules/dashboard"
pkgimpldashboard "github.com/SigNoz/signoz/pkg/modules/dashboard/impldashboard"
"github.com/SigNoz/signoz/pkg/modules/tag"
"github.com/SigNoz/signoz/pkg/modules/organization"
"github.com/SigNoz/signoz/pkg/modules/retention"
"github.com/SigNoz/signoz/pkg/modules/rulestatehistory"
@@ -152,8 +151,8 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
}
return openfgaauthz.NewProviderFactory(sqlstore, openfgaschema.NewSchema().Get(ctx), openfgaDataStore, licensing, onBeforeRoleDelete, authtypes.NewRegistry()), nil
},
func(store sqlstore.SQLStore, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, querier querier.Querier, licensing licensing.Licensing, tagModule tag.Module) dashboard.Module {
return impldashboard.NewModule(pkgimpldashboard.NewStore(store), store, settings, analytics, orgGetter, queryParser, querier, licensing, tagModule)
func(store sqlstore.SQLStore, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, querier querier.Querier, licensing licensing.Licensing) dashboard.Module {
return impldashboard.NewModule(pkgimpldashboard.NewStore(store), settings, analytics, orgGetter, queryParser, querier, licensing)
},
func(licensing licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config] {
return httpgateway.NewProviderFactory(licensing)

View File

@@ -213,7 +213,7 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.3
image: signoz/signoz-otel-collector:v0.144.4
entrypoint:
- /bin/sh
command:
@@ -241,7 +241,7 @@ services:
replicas: 3
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.3
image: signoz/signoz-otel-collector:v0.144.4
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster

View File

@@ -139,7 +139,7 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.3
image: signoz/signoz-otel-collector:v0.144.4
entrypoint:
- /bin/sh
command:
@@ -167,7 +167,7 @@ services:
replicas: 3
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.3
image: signoz/signoz-otel-collector:v0.144.4
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster

View File

@@ -204,7 +204,7 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.3}
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.4}
container_name: signoz-otel-collector
entrypoint:
- /bin/sh
@@ -229,7 +229,7 @@ services:
- "4318:4318" # OTLP HTTP receiver
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.3}
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.4}
container_name: signoz-telemetrystore-migrator
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000

View File

@@ -132,7 +132,7 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.3}
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.4}
container_name: signoz-otel-collector
entrypoint:
- /bin/sh
@@ -157,7 +157,7 @@ services:
- "4318:4318" # OTLP HTTP receiver
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.3}
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.4}
container_name: signoz-telemetrystore-migrator
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000

File diff suppressed because it is too large Load Diff

View File

@@ -11,10 +11,8 @@ import (
"github.com/SigNoz/signoz/pkg/modules/dashboard"
pkgimpldashboard "github.com/SigNoz/signoz/pkg/modules/dashboard/impldashboard"
"github.com/SigNoz/signoz/pkg/modules/organization"
"github.com/SigNoz/signoz/pkg/modules/tag"
"github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/queryparser"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/types/ctxtypes"
@@ -32,9 +30,9 @@ type module struct {
licensing licensing.Licensing
}
func NewModule(store dashboardtypes.Store, sqlstore sqlstore.SQLStore, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, querier querier.Querier, licensing licensing.Licensing, tagModule tag.Module) dashboard.Module {
func NewModule(store dashboardtypes.Store, settings factory.ProviderSettings, analytics analytics.Analytics, orgGetter organization.Getter, queryParser queryparser.QueryParser, querier querier.Querier, licensing licensing.Licensing) dashboard.Module {
scopedProviderSettings := factory.NewScopedProviderSettings(settings, "github.com/SigNoz/signoz/ee/modules/dashboard/impldashboard")
pkgDashboardModule := pkgimpldashboard.NewModule(store, sqlstore, settings, analytics, orgGetter, queryParser, tagModule)
pkgDashboardModule := pkgimpldashboard.NewModule(store, settings, analytics, orgGetter, queryParser)
return &module{
pkgDashboardModule: pkgDashboardModule,
@@ -199,68 +197,6 @@ func (module *module) Create(ctx context.Context, orgID valuer.UUID, createdBy s
return module.pkgDashboardModule.Create(ctx, orgID, createdBy, creator, data)
}
func (module *module) CreateV2(ctx context.Context, orgID valuer.UUID, createdBy string, creator valuer.UUID, postable dashboardtypes.PostableDashboardV2) (*dashboardtypes.DashboardV2, error) {
return module.pkgDashboardModule.CreateV2(ctx, orgID, createdBy, creator, postable)
}
func (module *module) GetV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error) {
return module.pkgDashboardModule.GetV2(ctx, orgID, id)
}
func (module *module) UpdateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, updateable dashboardtypes.UpdateableDashboardV2) (*dashboardtypes.DashboardV2, error) {
return module.pkgDashboardModule.UpdateV2(ctx, orgID, id, updatedBy, updateable)
}
func (module *module) PatchV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, patch dashboardtypes.PatchableDashboardV2) (*dashboardtypes.DashboardV2, error) {
return module.pkgDashboardModule.PatchV2(ctx, orgID, id, updatedBy, patch)
}
func (module *module) LockUnlockV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error {
return module.pkgDashboardModule.LockUnlockV2(ctx, orgID, id, updatedBy, isAdmin, lock)
}
func (module *module) CreatePublicV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, postable dashboardtypes.PostablePublicDashboard) (*dashboardtypes.DashboardV2, error) {
if _, err := module.licensing.GetActive(ctx, orgID); err != nil {
return nil, errors.New(errors.TypeLicenseUnavailable, errors.CodeLicenseUnavailable, "a valid license is not available").WithAdditional("this feature requires a valid license").WithAdditional(err.Error())
}
existing, err := module.pkgDashboardModule.GetV2(ctx, orgID, id)
if err != nil {
return nil, err
}
if existing.PublicConfig != nil {
return nil, errors.Newf(errors.TypeAlreadyExists, dashboardtypes.ErrCodePublicDashboardAlreadyExists, "dashboard with id %s is already public", id)
}
publicDashboard := dashboardtypes.NewPublicDashboard(postable.TimeRangeEnabled, postable.DefaultTimeRange, id)
if err := module.store.CreatePublic(ctx, dashboardtypes.NewStorablePublicDashboardFromPublicDashboard(publicDashboard)); err != nil {
return nil, err
}
existing.PublicConfig = publicDashboard
return existing, nil
}
func (module *module) UpdatePublicV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatable dashboardtypes.UpdatablePublicDashboard) (*dashboardtypes.DashboardV2, error) {
if _, err := module.licensing.GetActive(ctx, orgID); err != nil {
return nil, errors.New(errors.TypeLicenseUnavailable, errors.CodeLicenseUnavailable, "a valid license is not available").WithAdditional("this feature requires a valid license").WithAdditional(err.Error())
}
existing, err := module.pkgDashboardModule.GetV2(ctx, orgID, id)
if err != nil {
return nil, err
}
if existing.PublicConfig == nil {
return nil, errors.Newf(errors.TypeNotFound, dashboardtypes.ErrCodePublicDashboardNotFound, "dashboard with id %s isn't public", id)
}
existing.PublicConfig.Update(updatable.TimeRangeEnabled, updatable.DefaultTimeRange)
if err := module.store.UpdatePublic(ctx, dashboardtypes.NewStorablePublicDashboardFromPublicDashboard(existing.PublicConfig)); err != nil {
return nil, err
}
return existing, nil
}
func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.Dashboard, error) {
return module.pkgDashboardModule.Get(ctx, orgID, id)
}

View File

@@ -114,7 +114,7 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
// initiate agent config handler
agentConfMgr, err := agentConf.Initiate(&agentConf.ManagerOptions{
Store: signoz.SQLStore,
AgentFeatures: []agentConf.AgentFeature{logParsingPipelineController, signoz.Modules.LLMPricingRule},
AgentFeatures: []agentConf.AgentFeature{logParsingPipelineController},
})
if err != nil {
return nil, err

View File

@@ -497,7 +497,8 @@
"overrides": [
{
"files": [
"src/api/generated/**/*.ts"
"src/api/generated/**/*.ts",
"src/api/ai-assistant/**/*.ts"
],
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",

View File

@@ -1,5 +1,10 @@
{
"$schema": "https://unpkg.com/knip@5/schema.json",
"project": ["src/**/*.ts", "src/**/*.tsx"],
"ignore": ["src/api/generated/**/*.ts", "src/typings/*.ts"]
"ignore": ["src/api/generated/**/*.ts", "src/typings/*.ts"],
"ignoreDependencies": [
"http-proxy-middleware",
"react-error-boundary",
"@typescript/native-preview"
]
}

View File

@@ -40,12 +40,8 @@
"@dnd-kit/modifiers": "7.0.0",
"@dnd-kit/sortable": "8.0.0",
"@dnd-kit/utilities": "3.2.2",
"@grafana/data": "^11.2.3",
"@mdx-js/loader": "2.3.0",
"@mdx-js/react": "2.3.0",
"@monaco-editor/react": "^4.3.1",
"@radix-ui/react-tabs": "1.0.4",
"@radix-ui/react-tooltip": "1.0.7",
"@grafana/data": "^11.6.14",
"@monaco-editor/react": "^4.7.0",
"@sentry/react": "8.41.0",
"@sentry/vite-plugin": "2.22.6",
"@signozhq/design-tokens": "2.1.4",
@@ -57,7 +53,6 @@
"@uiw/codemirror-theme-copilot": "4.23.11",
"@uiw/codemirror-theme-github": "4.24.1",
"@uiw/react-codemirror": "4.23.10",
"@uiw/react-md-editor": "3.23.5",
"@visx/group": "3.3.0",
"@visx/hierarchy": "3.12.0",
"@visx/shape": "3.5.0",
@@ -67,38 +62,29 @@
"antd": "5.11.0",
"antd-table-saveas-excel": "2.2.1",
"antlr4": "4.13.2",
"axios": "1.12.0",
"axios": "1.16.0",
"babel-jest": "^29.6.4",
"babel-loader": "9.1.3",
"babel-plugin-named-asset-import": "^0.3.7",
"babel-preset-minify": "^0.5.1",
"babel-preset-react-app": "^10.0.1",
"chart.js": "3.9.1",
"chartjs-adapter-date-fns": "^2.0.0",
"chartjs-plugin-annotation": "^1.4.0",
"classnames": "2.3.2",
"color": "^4.2.1",
"color-alpha": "2.0.0",
"cross-env": "^7.0.3",
"crypto-js": "4.2.0",
"d3-hierarchy": "3.1.2",
"dayjs": "^1.10.7",
"dompurify": "3.2.4",
"dotenv": "8.2.0",
"dompurify": "3.4.0",
"event-source-polyfill": "1.0.31",
"eventemitter3": "5.0.1",
"fontfaceobserver": "2.3.0",
"history": "4.10.1",
"http-proxy-middleware": "3.0.5",
"http-proxy-middleware": "4.0.0",
"http-status-codes": "2.3.0",
"i18next": "^21.6.12",
"i18next-browser-languagedetector": "^6.1.3",
"i18next-http-backend": "^1.3.2",
"i18next-http-backend": "^4.0.0",
"immer": "11.1.3",
"jest": "30.2.0",
"js-base64": "^3.7.2",
"lodash-es": "^4.17.21",
"mini-css-extract-plugin": "2.4.5",
"motion": "12.4.13",
"nuqs": "2.8.8",
"overlayscrollbars": "^2.8.1",
@@ -106,7 +92,6 @@
"papaparse": "5.4.1",
"posthog-js": "1.298.0",
"rc-select": "14.10.0",
"rc-tween-one": "3.0.6",
"react": "18.2.0",
"react-addons-update": "15.6.3",
"react-beautiful-dnd": "13.1.1",
@@ -122,31 +107,28 @@
"react-hook-form": "7.71.2",
"react-i18next": "^11.16.1",
"react-json-tree": "^0.20.0",
"react-lottie": "1.2.10",
"react-markdown": "8.0.7",
"react-query": "3.39.3",
"react-redux": "^7.2.2",
"react-rnd": "^10.5.3",
"react-router-dom": "^5.2.0",
"react-router-dom-v5-compat": "6.27.0",
"react-router-dom-v5-compat": "6.30.3",
"react-syntax-highlighter": "15.5.0",
"react-use": "^17.3.2",
"react-virtuoso": "4.0.3",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"rehype-raw": "7.0.0",
"remark-gfm": "^3.0.1",
"rollup-plugin-visualizer": "7.0.0",
"rrule": "2.8.1",
"stream": "^0.0.2",
"styled-components": "^5.3.11",
"timestamp-nano": "^1.0.0",
"ts-node": "^10.2.1",
"typescript": "5.9.3",
"uplot": "1.6.31",
"uuid": "^8.3.2",
"vite": "npm:rolldown-vite@7.3.1",
"vite-plugin-html": "3.2.2",
"web-vitals": "^0.2.4",
"zod": "4.3.6",
"zustand": "5.0.11"
},
@@ -165,28 +147,23 @@
"devDependencies": {
"@babel/core": "^7.22.11",
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-syntax-jsx": "^7.12.13",
"@babel/preset-env": "^7.22.14",
"@babel/preset-react": "^7.12.13",
"@babel/preset-typescript": "^7.21.4",
"@commitlint/cli": "20.4.4",
"@commitlint/config-conventional": "20.4.4",
"@faker-js/faker": "9.3.0",
"@jest/globals": "30.2.0",
"@jest/globals": "30.4.1",
"@jest/types": "30.2.0",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"@types/color": "^3.0.3",
"@types/crypto-js": "4.2.2",
"@types/dompurify": "^2.4.0",
"@types/event-source-polyfill": "^1.0.0",
"@types/d3-hierarchy": "1.1.11",
"@types/fontfaceobserver": "2.1.0",
"@types/history": "4.7.11",
"@types/jest": "30.0.0",
"@jest/types": "30.2.0",
"@types/lodash-es": "^4.17.4",
"@types/mini-css-extract-plugin": "^2.5.1",
"@types/node": "^16.10.3",
"@types/papaparse": "5.3.7",
"@types/react": "18.0.26",
@@ -194,8 +171,6 @@
"@types/react-beautiful-dnd": "13.1.8",
"@types/react-dom": "18.0.10",
"@types/react-grid-layout": "^1.1.2",
"@types/react-helmet-async": "1.0.3",
"@types/react-lottie": "1.2.10",
"@types/react-redux": "^7.1.11",
"@types/react-resizable": "3.0.3",
"@types/react-router-dom": "^5.1.6",
@@ -205,39 +180,27 @@
"@types/testing-library__jest-dom": "^5.14.5",
"@types/uuid": "^8.3.1",
"@typescript/native-preview": "7.0.0-dev.20260430.1",
"autoprefixer": "10.4.19",
"babel-plugin-styled-components": "^1.12.0",
"eslint-plugin-sonarjs": "4.0.2",
"glob": "^13.0.6",
"husky": "^7.0.4",
"imagemin": "^8.0.1",
"imagemin-svgo": "^10.0.1",
"is-ci": "^3.0.1",
"jest-environment-jsdom": "29.7.0",
"jest-environment-node": "29.7.0",
"jest-styled-components": "^7.2.0",
"lint-staged": "^12.5.0",
"lint-staged": "^17.0.4",
"msw": "1.3.2",
"npm-run-all": "latest",
"orval": "7.21.0",
"orval": "8.9.1",
"oxfmt": "0.47.0",
"oxlint": "1.62.0",
"oxlint-tsgolint": "0.22.1",
"portfinder-sync": "^0.0.2",
"postcss": "8.5.6",
"postcss": "8.5.14",
"postcss-scss": "4.0.9",
"prop-types": "15.8.1",
"react-hooks-testing-library": "0.6.0",
"react-resizable": "3.0.4",
"redux-mock-store": "1.5.4",
"sass": "1.97.3",
"sharp": "0.34.5",
"stylelint": "17.7.0",
"stylelint-scss": "7.0.0",
"svgo": "4.0.0",
"ts-api-utils": "2.4.0",
"svgo": "4.0.1",
"ts-jest": "29.4.9",
"ts-node": "^10.2.1",
"typescript-plugin-css-modules": "5.2.0",
"use-sync-external-store": "1.6.0",
"vite-plugin-checker": "0.12.0",
@@ -265,7 +228,7 @@
"xml2js": "0.5.0",
"phin": "^3.7.1",
"body-parser": "1.20.3",
"http-proxy-middleware": "3.0.5",
"http-proxy-middleware": "4.0.0",
"cross-spawn": "7.0.5",
"cookie": "^0.7.1",
"serialize-javascript": "6.0.2",

6300
frontend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
trustPolicy: no-downgrade
minimumReleaseAge: 2880 # 2d
minimumReleaseAgeStrict: true
minimumReleaseAgeExclude:
- '@signozhq/*'
blockExoticSubdeps: true

View File

@@ -17,6 +17,12 @@ registered_languages=$(grep -oP "registerLanguage\('\K[^']+" "$SYNTAX_HIGHLIGHTE
missing_languages=()
for lang in $md_languages; do
# Skip ai-* block markers — these are custom AI block types rendered by
# RichCodeBlock as React components (e.g. ActionBlock, LineChartBlock),
# not real syntax languages, so they don't need highlighter registration.
if [[ "$lang" == ai-* ]]; then
continue
fi
if ! echo "$registered_languages" | grep -qx "$lang"; then
missing_languages+=("$lang")
fi

View File

@@ -8,6 +8,7 @@ import { LOCALSTORAGE } from 'constants/localStorage';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { isEmpty } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
@@ -40,6 +41,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
} = useAppContext();
const isAdmin = user.role === USER_ROLES.ADMIN;
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const mapRoutes = useMemo(
() =>
new Map(
@@ -99,6 +102,10 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
return <>{children}</>;
}
if (pathname.startsWith('/ai-assistant/') && !isAIAssistantEnabled) {
return <Redirect to={ROUTES.HOME} />;
}
// Check for workspace access restriction (cloud only)
const isCloudPlatform = activeLicense?.platform === LicensePlatform.CLOUD;

View File

@@ -164,14 +164,17 @@ function createMockAppContext(
featureFlags: [],
orgPreferences: createMockOrgPreferences(),
userPreferences: [],
hostsData: null,
isLoggedIn: true,
org: [{ createdAt: 0, id: 'org-id', displayName: 'Test Org' }],
isFetchingUser: false,
isFetchingActiveLicense: false,
isFetchingHosts: false,
isFetchingFeatureFlags: false,
isFetchingOrgPreferences: false,
userFetchError: null,
activeLicenseFetchError: null,
hostsFetchError: null,
featureFlagsFetchError: null,
orgPreferencesFetchError: null,
changelog: null,

View File

@@ -18,6 +18,7 @@ import AppLayout from 'container/AppLayout';
import Hex from 'crypto-js/enc-hex';
import HmacSHA256 from 'crypto-js/hmac-sha256';
import { KeyboardHotkeysProvider } from 'hooks/hotkeys/useKeyboardHotkeys';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useIsDarkMode, useThemeConfig } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { NotificationProvider } from 'hooks/useNotifications';
@@ -60,13 +61,21 @@ function App(): JSX.Element {
org,
} = useAppContext();
const [routes, setRoutes] = useState<AppRoutes[]>(defaultRoutes);
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const { hostname, pathname } = window.location;
const { hostname } = window.location;
const [pathname, setPathname] = useState(history.location.pathname);
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const [isSentryInitialized, setIsSentryInitialized] = useState(false);
useEffect(() => {
return history.listen((location) => {
setPathname(location.pathname);
});
}, []);
const enableAnalytics = useCallback(
(user: IUser): void => {
// wait for the required data to be loaded before doing init for anything!
@@ -212,6 +221,27 @@ function App(): JSX.Element {
activeLicenseFetchError,
]);
useEffect(() => {
if (!isLoggedInState) {
return;
}
setRoutes((prev) => {
const hasAi = prev.some((r) => r.path === ROUTES.AI_ASSISTANT);
if (isAIAssistantEnabled === hasAi) {
return prev;
}
if (isAIAssistantEnabled) {
const aiRoute = defaultRoutes.find((r) => r.path === ROUTES.AI_ASSISTANT);
if (!aiRoute) {
return prev;
}
return [...prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT), aiRoute];
}
return prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT);
});
}, [isLoggedInState, isAIAssistantEnabled]);
const isDarkMode = useIsDarkMode();
useEffect(() => {
@@ -221,7 +251,8 @@ function App(): JSX.Element {
useEffect(() => {
if (
pathname === ROUTES.ONBOARDING ||
pathname.startsWith('/public/dashboard/')
pathname.startsWith('/public/dashboard/') ||
pathname.startsWith('/ai-assistant/')
) {
window.Pylon?.('hideChatBubble');
} else {

View File

@@ -324,3 +324,10 @@ export const MeterExplorerPage = Loadable(
() =>
import(/* webpackChunkName: "Meter Explorer Page" */ 'pages/MeterExplorer'),
);
export const AIAssistantPage = Loadable(
() =>
import(
/* webpackChunkName: "AI Assistant Page" */ 'pages/AIAssistantPage/AIAssistantPage'
),
);

View File

@@ -2,6 +2,7 @@ import { RouteProps } from 'react-router-dom';
import ROUTES from 'constants/routes';
import {
AIAssistantPage,
AlertHistory,
AlertOverview,
AlertTypeSelectionPage,
@@ -507,6 +508,13 @@ const routes: AppRoutes[] = [
key: 'API_MONITORING',
isPrivate: true,
},
{
path: ROUTES.AI_ASSISTANT,
exact: true,
component: AIAssistantPage,
key: 'AI_ASSISTANT',
isPrivate: true,
},
];
export const SUPPORT_ROUTE: AppRoutes = {

View File

@@ -21,7 +21,7 @@ i18n
escapeValue: false, // not needed for react as it escapes by default
},
backend: {
loadPath: (language, namespace) => {
loadPath: (language: string, namespace: string): string => {
const ns = namespace[0];
const pathkey = `/${language}/${ns}`;
const hash = cacheBursting[pathkey as keyof typeof cacheBursting] || '';

View File

@@ -0,0 +1,80 @@
import axios, { InternalAxiosRequestConfig } from 'axios';
import {
interceptorRejected,
interceptorsRequestBasePath,
interceptorsRequestResponse,
interceptorsResponse,
} from 'api';
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
/** Path-only base for the AI Assistant API. */
export const AI_API_PATH = '/api/v1/assistant';
/** Header that tells the AI backend which SigNoz instance to query against. */
export const SIGNOZ_URL_HEADER = 'X-SigNoz-URL';
/**
* Sets `X-SigNoz-URL` on every outgoing AI Assistant request. The backend
* needs the originating SigNoz instance URL for multi-tenant deployments;
* when omitted it falls back to its `SIGNOZ_API_URL` env var.
*/
export const interceptorsRequestSigNozUrl = (
value: InternalAxiosRequestConfig,
): InternalAxiosRequestConfig => {
if (value.headers) {
value.headers[SIGNOZ_URL_HEADER] = getSigNozInstanceUrl();
}
return value;
};
/**
* AI backend URL — sourced from the global config's `ai_assistant_url` field
* at runtime. `useIsAIAssistantEnabled` keeps this in sync via `setAIBackendUrl`
* whenever the config response changes; consumers (the axios instance and the
* SSE fetch path) read it lazily so they always see the current value.
*/
let aiBackendUrl: string | null = null;
export function setAIBackendUrl(url: string | null): void {
if (aiBackendUrl === url) {
return;
}
aiBackendUrl = url;
AIAssistantInstance.defaults.baseURL = url ? `${url}${AI_API_PATH}` : '';
}
/**
* Full base URL for the AI Assistant API (host + path). Throws when the
* config hasn't yet provided a URL — should never happen in practice
* because `useIsAIAssistantEnabled` gates every consumer surface.
*/
export function getAIBaseUrl(): string {
if (!aiBackendUrl) {
throw new Error('AI assistant URL is not configured.');
}
return `${aiBackendUrl}${AI_API_PATH}`;
}
/**
* Dedicated axios instance for the AI Assistant.
*
* Mirrors the request/response interceptor stack of the main SigNoz axios
* instance — most importantly `interceptorRejected`, which transparently
* rotates the access token via `/sessions/rotate` on a 401 and replays the
* original request. That's why we don't need any AI-specific 401 handling
* for REST calls: this instance inherits the same flow as the rest of the
* app for free.
*
* Only the SSE stream (`streamEvents`) still needs raw fetch since axios
* doesn't expose `ReadableStream` — that path keeps its own auth wrapper.
*/
export const AIAssistantInstance = axios.create({});
AIAssistantInstance.interceptors.request.use(interceptorsRequestResponse);
AIAssistantInstance.interceptors.request.use(interceptorsRequestBasePath);
AIAssistantInstance.interceptors.request.use(interceptorsRequestSigNozUrl);
AIAssistantInstance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);

View File

@@ -0,0 +1,543 @@
/**
* AI Assistant API client.
*
* Flow:
* 1. POST /api/v1/assistant/threads → { threadId }
* 2. POST /api/v1/assistant/threads/{threadId}/messages → { executionId }
* 3. GET /api/v1/assistant/executions/{executionId}/events → SSE stream (closes on 'done')
*
* For subsequent messages in the same thread, repeat steps 23.
* Approval/clarification events pause the stream; use approveExecution/clarifyExecution
* to resume, which each return a new executionId to open a fresh SSE stream.
*
* Types in this file re-use the OpenAPI-generated DTOs in
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
* Local types are defined only when the UI needs a different shape — for
* example, the SSE event union adds a literal `type` discriminator that the
* generated event DTOs leave loose.
*
* REST calls go through `AIAssistantInstance` (an axios instance configured
* with the same interceptor stack as the rest of the app) — that gives them
* automatic 401-then-rotate behaviour for free. Only the SSE call is still
* a raw `fetch` because axios doesn't expose `ReadableStream`; that one
* path gets its own small auth wrapper.
*/
import axios from 'axios';
import getLocalStorageApi from 'api/browser/localstorage/get';
import { Logout } from 'api/utils';
import rotateSession from 'api/v2/sessions/rotate/post';
import afterLogin from 'AppRoutes/utils';
import type {
ActionResultResponseDTO,
ApprovalEventDTO,
ApproveResponseDTO,
CancelResponseDTO,
ClarificationEventDTO,
ClarifyResponseDTO,
ConversationEventDTO,
CreateMessageResponseDTO,
CreateThreadResponseDTO,
DoneEventDTO,
ErrorEventDTO,
ExecutionStateDTO,
FeedbackRatingDTO,
ListThreadsApiV1AssistantThreadsGetArchived,
ListThreadsApiV1AssistantThreadsGetParams,
MessageContextDTO,
MessageContextDTOSource,
MessageContextDTOType,
MessageEventDTO,
MessageSummaryDTO,
RegenerateResponseDTO,
StatusEventDTO,
ThinkingEventDTO,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
ThreadSummaryDTO,
ToolCallEventDTO,
ToolResultEventDTO,
} from './sigNozAIAssistantAPI.schemas';
import { LOCALSTORAGE } from 'constants/localStorage';
import {
AIAssistantInstance,
getAIBaseUrl,
SIGNOZ_URL_HEADER,
} from '../AIAPIInstance';
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
// ---------------------------------------------------------------------------
// SSE-only auth wrapper.
//
// REST calls go through `AIAssistantInstance` (axios) and get refresh-token
// behaviour from the shared `interceptorRejected`. The SSE call has to use
// raw `fetch` (axios can't stream a `ReadableStream`), so it can't ride that
// interceptor — this small wrapper handles 401 at SSE open time by hitting
// the same rotate endpoint and replaying the request once.
//
// In typical use a REST call (e.g. sendMessage / loadThread) precedes every
// stream open, so axios will already have refreshed the token and `fetch`
// just reads the fresh one from localStorage. The wrapper exists for the
// edge case where SSE is the first call to encounter a 401.
// ---------------------------------------------------------------------------
let pendingRotate: Promise<string | null> | null = null;
async function rotateAccessToken(): Promise<string | null> {
if (pendingRotate) {
return pendingRotate;
}
const refreshToken = getLocalStorageApi(LOCALSTORAGE.REFRESH_AUTH_TOKEN) || '';
if (!refreshToken) {
return null;
}
pendingRotate = (async (): Promise<string | null> => {
try {
const response = await rotateSession({ refreshToken });
afterLogin(response.data.accessToken, response.data.refreshToken, true);
return response.data.accessToken;
} catch {
Logout();
return null;
} finally {
pendingRotate = null;
}
})();
return pendingRotate;
}
// Backoff schedule for 429 retries on SSE open. Three attempts is enough to
// absorb the brief window between cancel→send→stream when the backend is
// rate-limiting the burst, without making real "you're saturated" errors
// take forever to surface.
const SSE_429_BACKOFF_MS = [400, 1200, 2500];
function parseRetryAfterMs(value: string | null): number | null {
if (!value) {
return null;
}
const seconds = Number(value);
if (Number.isFinite(seconds)) {
return Math.max(0, seconds * 1000);
}
const date = Date.parse(value);
if (Number.isFinite(date)) {
return Math.max(0, date - Date.now());
}
return null;
}
async function fetchSSEWithAuth(
url: string,
signal?: AbortSignal,
): Promise<Response> {
const send = async (token: string | null): Promise<Response> => {
const headers: Record<string, string> = {
[SIGNOZ_URL_HEADER]: getSigNozInstanceUrl(),
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return fetch(url, { headers, signal });
};
const sendWithAuth = async (): Promise<Response> => {
const initialToken = getLocalStorageApi(LOCALSTORAGE.AUTH_TOKEN) || '';
const res = await send(initialToken);
if (res.status !== 401) {
return res;
}
const refreshed = await rotateAccessToken();
if (!refreshed) {
return res;
}
return send(refreshed);
};
let res = await sendWithAuth();
for (const baseDelay of SSE_429_BACKOFF_MS) {
if (res.status !== 429 || signal?.aborted) {
return res;
}
const retryAfter = parseRetryAfterMs(res.headers.get('Retry-After'));
const delay = retryAfter ?? baseDelay;
// eslint-disable-next-line no-await-in-loop
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(resolve, delay);
signal?.addEventListener(
'abort',
() => {
clearTimeout(timer);
reject(new DOMException('SSE 429 backoff aborted', 'AbortError'));
},
{ once: true },
);
});
// eslint-disable-next-line no-await-in-loop
res = await sendWithAuth();
}
return res;
}
// ---------------------------------------------------------------------------
// SSE event types
//
// The generated event DTOs each declare `type?: string` (loose). The UI needs
// a discriminated union, so we intersect each variant with a string-literal
// `type` to enable narrowing via `event.type === 'status'`.
// ---------------------------------------------------------------------------
export type SSEEvent =
| (StatusEventDTO & { type: 'status' })
| (MessageEventDTO & { type: 'message' })
| (ThinkingEventDTO & { type: 'thinking' })
| (ToolCallEventDTO & { type: 'tool_call' })
| (ToolResultEventDTO & { type: 'tool_result' })
| (ApprovalEventDTO & { type: 'approval' })
| (ClarificationEventDTO & { type: 'clarification' })
| (ErrorEventDTO & { type: 'error' })
| (ConversationEventDTO & { type: 'conversation' })
| (DoneEventDTO & { type: 'done' });
/** String-literal view of `ExecutionStateDTO` for ergonomic comparisons. */
export type ExecutionState = `${ExecutionStateDTO}`;
// ---------------------------------------------------------------------------
// Re-exported DTOs — the wire shape, used directly without remapping.
// ---------------------------------------------------------------------------
export type ThreadSummary = ThreadSummaryDTO;
export type ThreadListResponse = ThreadListResponseDTO;
export type ThreadDetailResponse = ThreadDetailResponseDTO;
export type MessageSummary = MessageSummaryDTO;
export type CancelResponse = CancelResponseDTO;
/**
* Construction-friendly view of `MessageContextDTO`: enum fields are widened
* to their string-literal unions so call-sites can pass `'mention'` instead
* of `MessageContextDTOSource.mention`.
*/
export type MessageContext = Omit<MessageContextDTO, 'source' | 'type'> & {
source: `${MessageContextDTOSource}`;
type: `${MessageContextDTOType}`;
};
/** Construction-friendly view of `ListThreadsApiV1AssistantThreadsGetParams`. */
export type ListThreadsOptions = Omit<
ListThreadsApiV1AssistantThreadsGetParams,
'archived'
> & {
archived?: `${ListThreadsApiV1AssistantThreadsGetArchived}`;
};
/** String-literal view of `FeedbackRatingDTO` so call-sites can pass `'positive'`/`'negative'`. */
export type FeedbackRating = `${FeedbackRatingDTO}`;
// ---------------------------------------------------------------------------
// Thread listing & detail
// ---------------------------------------------------------------------------
export async function listThreads(
options: ListThreadsOptions = {},
): Promise<ThreadListResponse> {
const {
archived = 'false',
limit = 20,
cursor = null,
sort = 'updated_desc',
} = options;
const response = await AIAssistantInstance.get<ThreadListResponse>(
'/threads',
{
params: {
archived,
limit,
sort,
...(cursor ? { cursor } : {}),
},
},
);
return response.data;
}
export async function updateThread(
threadId: string,
update: { title?: string | null; archived?: boolean | null },
): Promise<ThreadSummary> {
const response = await AIAssistantInstance.patch<ThreadSummary>(
`/threads/${threadId}`,
update,
);
return response.data;
}
export async function getThreadDetail(
threadId: string,
): Promise<ThreadDetailResponse> {
const response = await AIAssistantInstance.get<ThreadDetailResponse>(
`/threads/${threadId}`,
);
return response.data;
}
// ---------------------------------------------------------------------------
// Step 1 — Create thread
// POST /api/v1/assistant/threads → { threadId }
// ---------------------------------------------------------------------------
export async function createThread(signal?: AbortSignal): Promise<string> {
const response = await AIAssistantInstance.post<CreateThreadResponseDTO>(
'/threads',
{},
{ signal },
);
return response.data.threadId;
}
// ---------------------------------------------------------------------------
// Step 2 — Send message
// POST /api/v1/assistant/threads/{threadId}/messages → { executionId }
// ---------------------------------------------------------------------------
/** Fetches the thread's active executionId for reconnect on thread_busy (409). */
async function getActiveExecutionId(threadId: string): Promise<string | null> {
try {
const response = await AIAssistantInstance.get<ThreadDetailResponseDTO>(
`/threads/${threadId}`,
);
return response.data.activeExecutionId ?? null;
} catch {
return null;
}
}
export async function sendMessage(
threadId: string,
content: string,
contexts?: MessageContext[],
signal?: AbortSignal,
): Promise<string> {
try {
const response = await AIAssistantInstance.post<CreateMessageResponseDTO>(
`/threads/${threadId}/messages`,
{
content,
...(contexts && contexts.length > 0 ? { contexts } : {}),
},
{ signal },
);
return response.data.executionId;
} catch (err) {
// Thread already has an active execution — reconnect to it instead of
// failing the user's send.
if (axios.isAxiosError(err) && err.response?.status === 409) {
const executionId = await getActiveExecutionId(threadId);
if (executionId) {
return executionId;
}
}
throw err;
}
}
// ---------------------------------------------------------------------------
// Step 3 — Stream execution events
// GET /api/v1/assistant/executions/{executionId}/events → SSE
// ---------------------------------------------------------------------------
function parseSSELine(line: string): SSEEvent | null {
if (!line.startsWith('data: ')) {
return null;
}
const json = line.slice('data: '.length).trim();
if (!json || json === '[DONE]') {
return null;
}
try {
return JSON.parse(json) as SSEEvent;
} catch {
return null;
}
}
function parseSSEChunk(chunk: string): SSEEvent[] {
return chunk
.split('\n\n')
.map((part) => part.split('\n').find((l) => l.startsWith('data: ')) ?? '')
.map(parseSSELine)
.filter((e): e is SSEEvent => e !== null);
}
async function* readSSEReader(
reader: ReadableStreamDefaultReader<Uint8Array>,
): AsyncGenerator<SSEEvent> {
const decoder = new TextDecoder();
let lineBuffer = '';
try {
// eslint-disable-next-line no-constant-condition
while (true) {
// eslint-disable-next-line no-await-in-loop
const { done, value } = await reader.read();
if (done) {
break;
}
lineBuffer += decoder.decode(value, { stream: true });
const parts = lineBuffer.split('\n\n');
lineBuffer = parts.pop() ?? '';
yield* parts.flatMap(parseSSEChunk);
}
yield* parseSSEChunk(lineBuffer);
} finally {
reader.releaseLock();
}
}
/**
* Thrown by `streamEvents` when the SSE open returns a non-2xx response.
* Carries the HTTP status so callers can branch on rate-limit vs. other
* failures (e.g. show a "please wait a moment" message on 429).
*/
export class SSEStreamError extends Error {
status: number;
constructor(status: number, statusText: string) {
super(`SSE stream failed: ${status} ${statusText}`);
this.name = 'SSEStreamError';
this.status = status;
}
}
export async function* streamEvents(
executionId: string,
signal?: AbortSignal,
): AsyncGenerator<SSEEvent> {
const res = await fetchSSEWithAuth(
`${getAIBaseUrl()}/executions/${executionId}/events`,
signal,
);
if (!res.ok || !res.body) {
throw new SSEStreamError(res.status, res.statusText);
}
yield* readSSEReader(res.body.getReader());
}
// ---------------------------------------------------------------------------
// Approval / Clarification / Cancel actions
// ---------------------------------------------------------------------------
/** Approve a pending action. Returns a new executionId — open a fresh SSE stream for it. */
export async function approveExecution(
approvalId: string,
signal?: AbortSignal,
): Promise<string> {
const response = await AIAssistantInstance.post<ApproveResponseDTO>(
'/approve',
{ approvalId },
{ signal },
);
return response.data.executionId;
}
/** Reject a pending action. */
export async function rejectExecution(
approvalId: string,
signal?: AbortSignal,
): Promise<void> {
await AIAssistantInstance.post('/reject', { approvalId }, { signal });
}
/** Submit clarification answers. Returns a new executionId — open a fresh SSE stream for it. */
export async function clarifyExecution(
clarificationId: string,
answers: Record<string, unknown>,
signal?: AbortSignal,
): Promise<string> {
const response = await AIAssistantInstance.post<ClarifyResponseDTO>(
'/clarify',
{ clarificationId, answers },
{ signal },
);
return response.data.executionId;
}
/**
* Clean-slate regeneration of an assistant response. The backend rewinds the
* conversation up to (excluding) the supplied messageId and starts a fresh
* execution. Returns the new executionId — open an SSE stream for it the
* same way `sendMessage` and `approve` do.
*/
export async function regenerateMessage(
messageId: string,
signal?: AbortSignal,
): Promise<string> {
const response = await AIAssistantInstance.post<RegenerateResponseDTO>(
`/messages/${messageId}/regenerate`,
undefined,
{ signal },
);
return response.data.executionId;
}
export async function cancelExecution(
threadId: string,
signal?: AbortSignal,
): Promise<CancelResponse> {
const response = await AIAssistantInstance.post<CancelResponse>(
'/cancel',
{ threadId },
{ signal },
);
return response.data;
}
// ---------------------------------------------------------------------------
// Rollback actions — undo / revert / restore
// All three POST `{ actionMetadataId }` and return `ActionResultResponseDTO`.
// ---------------------------------------------------------------------------
async function postRollback(
endpoint: 'undo' | 'revert' | 'restore',
actionMetadataId: string,
signal?: AbortSignal,
): Promise<ActionResultResponseDTO> {
const response = await AIAssistantInstance.post<ActionResultResponseDTO>(
`/${endpoint}`,
{ actionMetadataId },
{ signal },
);
return response.data;
}
export const undoExecution = (
actionMetadataId: string,
signal?: AbortSignal,
): Promise<ActionResultResponseDTO> =>
postRollback('undo', actionMetadataId, signal);
export const revertExecution = (
actionMetadataId: string,
signal?: AbortSignal,
): Promise<ActionResultResponseDTO> =>
postRollback('revert', actionMetadataId, signal);
export const restoreExecution = (
actionMetadataId: string,
signal?: AbortSignal,
): Promise<ActionResultResponseDTO> =>
postRollback('restore', actionMetadataId, signal);
// ---------------------------------------------------------------------------
// Feedback
// ---------------------------------------------------------------------------
export async function submitFeedback(
messageId: string,
rating: FeedbackRating,
comment?: string,
): Promise<void> {
await AIAssistantInstance.post(`/messages/${messageId}/feedback`, {
rating,
comment: comment ?? null,
});
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useQuery } from 'react-query';
import type {
@@ -77,9 +78,7 @@ export function useGetAlerts<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -98,9 +99,7 @@ export function useListAuthDomains<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -123,7 +122,7 @@ export const invalidateListAuthDomains = async (
* @summary Create auth domain
*/
export const createAuthDomain = (
authtypesPostableAuthDomainDTO: BodyType<AuthtypesPostableAuthDomainDTO>,
authtypesPostableAuthDomainDTO?: BodyType<AuthtypesPostableAuthDomainDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateAuthDomain201>({
@@ -142,13 +141,13 @@ export const getCreateAuthDomainMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data?: BodyType<AuthtypesPostableAuthDomainDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data?: BodyType<AuthtypesPostableAuthDomainDTO> },
TContext
> => {
const mutationKey = ['createAuthDomain'];
@@ -162,7 +161,7 @@ export const getCreateAuthDomainMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createAuthDomain>>,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> }
{ data?: BodyType<AuthtypesPostableAuthDomainDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -176,7 +175,8 @@ export type CreateAuthDomainMutationResult = NonNullable<
Awaited<ReturnType<typeof createAuthDomain>>
>;
export type CreateAuthDomainMutationBody =
BodyType<AuthtypesPostableAuthDomainDTO>;
| BodyType<AuthtypesPostableAuthDomainDTO>
| undefined;
export type CreateAuthDomainMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -189,27 +189,29 @@ export const useCreateAuthDomain = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data?: BodyType<AuthtypesPostableAuthDomainDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data?: BodyType<AuthtypesPostableAuthDomainDTO> },
TContext
> => {
const mutationOptions = getCreateAuthDomainMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateAuthDomainMutationOptions(options));
};
/**
* This endpoint deletes an auth domain
* @summary Delete auth domain
*/
export const deleteAuthDomain = ({ id }: DeleteAuthDomainPathParameters) => {
export const deleteAuthDomain = (
{ id }: DeleteAuthDomainPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/domains/${id}`,
method: 'DELETE',
signal,
});
};
@@ -275,9 +277,7 @@ export const useDeleteAuthDomain = <
{ pathParams: DeleteAuthDomainPathParameters },
TContext
> => {
const mutationOptions = getDeleteAuthDomainMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteAuthDomainMutationOptions(options));
};
/**
* This endpoint returns an auth domain by ID
@@ -361,9 +361,7 @@ export function useGetAuthDomain<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -388,13 +386,15 @@ export const invalidateGetAuthDomain = async (
*/
export const updateAuthDomain = (
{ id }: UpdateAuthDomainPathParameters,
authtypesUpdatableAuthDomainDTO: BodyType<AuthtypesUpdatableAuthDomainDTO>,
authtypesUpdatableAuthDomainDTO?: BodyType<AuthtypesUpdatableAuthDomainDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/domains/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: authtypesUpdatableAuthDomainDTO,
signal,
});
};
@@ -407,7 +407,7 @@ export const getUpdateAuthDomainMutationOptions = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdatableAuthDomainDTO>;
data?: BodyType<AuthtypesUpdatableAuthDomainDTO>;
},
TContext
>;
@@ -416,7 +416,7 @@ export const getUpdateAuthDomainMutationOptions = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdatableAuthDomainDTO>;
data?: BodyType<AuthtypesUpdatableAuthDomainDTO>;
},
TContext
> => {
@@ -433,7 +433,7 @@ export const getUpdateAuthDomainMutationOptions = <
Awaited<ReturnType<typeof updateAuthDomain>>,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdatableAuthDomainDTO>;
data?: BodyType<AuthtypesUpdatableAuthDomainDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -448,7 +448,8 @@ export type UpdateAuthDomainMutationResult = NonNullable<
Awaited<ReturnType<typeof updateAuthDomain>>
>;
export type UpdateAuthDomainMutationBody =
BodyType<AuthtypesUpdatableAuthDomainDTO>;
| BodyType<AuthtypesUpdatableAuthDomainDTO>
| undefined;
export type UpdateAuthDomainMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -463,7 +464,7 @@ export const useUpdateAuthDomain = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdatableAuthDomainDTO>;
data?: BodyType<AuthtypesUpdatableAuthDomainDTO>;
},
TContext
>;
@@ -472,11 +473,9 @@ export const useUpdateAuthDomain = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdatableAuthDomainDTO>;
data?: BodyType<AuthtypesUpdatableAuthDomainDTO>;
},
TContext
> => {
const mutationOptions = getUpdateAuthDomainMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateAuthDomainMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation } from 'react-query';
import type {
@@ -25,7 +26,7 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
* @summary Check permissions
*/
export const authzCheck = (
authtypesTransactionDTO: BodyType<AuthtypesTransactionDTO[]>,
authtypesTransactionDTO?: BodyType<AuthtypesTransactionDTO[]>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<AuthzCheck200>({
@@ -44,13 +45,13 @@ export const getAuthzCheckMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data?: BodyType<AuthtypesTransactionDTO[]> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data?: BodyType<AuthtypesTransactionDTO[]> },
TContext
> => {
const mutationKey = ['authzCheck'];
@@ -64,7 +65,7 @@ export const getAuthzCheckMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof authzCheck>>,
{ data: BodyType<AuthtypesTransactionDTO[]> }
{ data?: BodyType<AuthtypesTransactionDTO[]> }
> = (props) => {
const { data } = props ?? {};
@@ -77,7 +78,9 @@ export const getAuthzCheckMutationOptions = <
export type AuthzCheckMutationResult = NonNullable<
Awaited<ReturnType<typeof authzCheck>>
>;
export type AuthzCheckMutationBody = BodyType<AuthtypesTransactionDTO[]>;
export type AuthzCheckMutationBody =
| BodyType<AuthtypesTransactionDTO[]>
| undefined;
export type AuthzCheckMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -90,16 +93,14 @@ export const useAuthzCheck = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data?: BodyType<AuthtypesTransactionDTO[]> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data?: BodyType<AuthtypesTransactionDTO[]> },
TContext
> => {
const mutationOptions = getAuthzCheckMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getAuthzCheckMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -98,9 +99,7 @@ export function useListChannels<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -123,7 +122,7 @@ export const invalidateListChannels = async (
* @summary Create notification channel
*/
export const createChannel = (
alertmanagertypesPostableChannelDTO: BodyType<AlertmanagertypesPostableChannelDTO>,
alertmanagertypesPostableChannelDTO?: BodyType<AlertmanagertypesPostableChannelDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateChannel201>({
@@ -142,13 +141,13 @@ export const getCreateChannelMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createChannel>>,
TError,
{ data: BodyType<AlertmanagertypesPostableChannelDTO> },
{ data?: BodyType<AlertmanagertypesPostableChannelDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createChannel>>,
TError,
{ data: BodyType<AlertmanagertypesPostableChannelDTO> },
{ data?: BodyType<AlertmanagertypesPostableChannelDTO> },
TContext
> => {
const mutationKey = ['createChannel'];
@@ -162,7 +161,7 @@ export const getCreateChannelMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createChannel>>,
{ data: BodyType<AlertmanagertypesPostableChannelDTO> }
{ data?: BodyType<AlertmanagertypesPostableChannelDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -176,7 +175,8 @@ export type CreateChannelMutationResult = NonNullable<
Awaited<ReturnType<typeof createChannel>>
>;
export type CreateChannelMutationBody =
BodyType<AlertmanagertypesPostableChannelDTO>;
| BodyType<AlertmanagertypesPostableChannelDTO>
| undefined;
export type CreateChannelMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -189,27 +189,29 @@ export const useCreateChannel = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createChannel>>,
TError,
{ data: BodyType<AlertmanagertypesPostableChannelDTO> },
{ data?: BodyType<AlertmanagertypesPostableChannelDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createChannel>>,
TError,
{ data: BodyType<AlertmanagertypesPostableChannelDTO> },
{ data?: BodyType<AlertmanagertypesPostableChannelDTO> },
TContext
> => {
const mutationOptions = getCreateChannelMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateChannelMutationOptions(options));
};
/**
* This endpoint deletes a notification channel by ID
* @summary Delete notification channel
*/
export const deleteChannelByID = ({ id }: DeleteChannelByIDPathParameters) => {
export const deleteChannelByID = (
{ id }: DeleteChannelByIDPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/channels/${id}`,
method: 'DELETE',
signal,
});
};
@@ -275,9 +277,7 @@ export const useDeleteChannelByID = <
{ pathParams: DeleteChannelByIDPathParameters },
TContext
> => {
const mutationOptions = getDeleteChannelByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteChannelByIDMutationOptions(options));
};
/**
* This endpoint returns a notification channel by ID
@@ -361,9 +361,7 @@ export function useGetChannelByID<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -388,13 +386,15 @@ export const invalidateGetChannelByID = async (
*/
export const updateChannelByID = (
{ id }: UpdateChannelByIDPathParameters,
configReceiverDTO: BodyType<ConfigReceiverDTO>,
configReceiverDTO?: BodyType<ConfigReceiverDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/channels/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: configReceiverDTO,
signal,
});
};
@@ -407,7 +407,7 @@ export const getUpdateChannelByIDMutationOptions = <
TError,
{
pathParams: UpdateChannelByIDPathParameters;
data: BodyType<ConfigReceiverDTO>;
data?: BodyType<ConfigReceiverDTO>;
},
TContext
>;
@@ -416,7 +416,7 @@ export const getUpdateChannelByIDMutationOptions = <
TError,
{
pathParams: UpdateChannelByIDPathParameters;
data: BodyType<ConfigReceiverDTO>;
data?: BodyType<ConfigReceiverDTO>;
},
TContext
> => {
@@ -433,7 +433,7 @@ export const getUpdateChannelByIDMutationOptions = <
Awaited<ReturnType<typeof updateChannelByID>>,
{
pathParams: UpdateChannelByIDPathParameters;
data: BodyType<ConfigReceiverDTO>;
data?: BodyType<ConfigReceiverDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -447,7 +447,9 @@ export const getUpdateChannelByIDMutationOptions = <
export type UpdateChannelByIDMutationResult = NonNullable<
Awaited<ReturnType<typeof updateChannelByID>>
>;
export type UpdateChannelByIDMutationBody = BodyType<ConfigReceiverDTO>;
export type UpdateChannelByIDMutationBody =
| BodyType<ConfigReceiverDTO>
| undefined;
export type UpdateChannelByIDMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -462,7 +464,7 @@ export const useUpdateChannelByID = <
TError,
{
pathParams: UpdateChannelByIDPathParameters;
data: BodyType<ConfigReceiverDTO>;
data?: BodyType<ConfigReceiverDTO>;
},
TContext
>;
@@ -471,20 +473,18 @@ export const useUpdateChannelByID = <
TError,
{
pathParams: UpdateChannelByIDPathParameters;
data: BodyType<ConfigReceiverDTO>;
data?: BodyType<ConfigReceiverDTO>;
},
TContext
> => {
const mutationOptions = getUpdateChannelByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateChannelByIDMutationOptions(options));
};
/**
* This endpoint tests a notification channel by sending a test notification
* @summary Test notification channel
*/
export const testChannel = (
configReceiverDTO: BodyType<ConfigReceiverDTO>,
configReceiverDTO?: BodyType<ConfigReceiverDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -503,13 +503,13 @@ export const getTestChannelMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof testChannel>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof testChannel>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
> => {
const mutationKey = ['testChannel'];
@@ -523,7 +523,7 @@ export const getTestChannelMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof testChannel>>,
{ data: BodyType<ConfigReceiverDTO> }
{ data?: BodyType<ConfigReceiverDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -536,7 +536,7 @@ export const getTestChannelMutationOptions = <
export type TestChannelMutationResult = NonNullable<
Awaited<ReturnType<typeof testChannel>>
>;
export type TestChannelMutationBody = BodyType<ConfigReceiverDTO>;
export type TestChannelMutationBody = BodyType<ConfigReceiverDTO> | undefined;
export type TestChannelMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -549,18 +549,16 @@ export const useTestChannel = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof testChannel>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof testChannel>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
> => {
const mutationOptions = getTestChannelMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getTestChannelMutationOptions(options));
};
/**
* Deprecated: use /api/v1/channels/test instead
@@ -568,7 +566,7 @@ export const useTestChannel = <
* @summary Test notification channel (deprecated)
*/
export const testChannelDeprecated = (
configReceiverDTO: BodyType<ConfigReceiverDTO>,
configReceiverDTO?: BodyType<ConfigReceiverDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -587,13 +585,13 @@ export const getTestChannelDeprecatedMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof testChannelDeprecated>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof testChannelDeprecated>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
> => {
const mutationKey = ['testChannelDeprecated'];
@@ -607,7 +605,7 @@ export const getTestChannelDeprecatedMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof testChannelDeprecated>>,
{ data: BodyType<ConfigReceiverDTO> }
{ data?: BodyType<ConfigReceiverDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -620,7 +618,9 @@ export const getTestChannelDeprecatedMutationOptions = <
export type TestChannelDeprecatedMutationResult = NonNullable<
Awaited<ReturnType<typeof testChannelDeprecated>>
>;
export type TestChannelDeprecatedMutationBody = BodyType<ConfigReceiverDTO>;
export type TestChannelDeprecatedMutationBody =
| BodyType<ConfigReceiverDTO>
| undefined;
export type TestChannelDeprecatedMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -635,16 +635,14 @@ export const useTestChannelDeprecated = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof testChannelDeprecated>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof testChannelDeprecated>>,
TError,
{ data: BodyType<ConfigReceiverDTO> },
{ data?: BodyType<ConfigReceiverDTO> },
TContext
> => {
const mutationOptions = getTestChannelDeprecatedMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getTestChannelDeprecatedMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -56,7 +57,7 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
*/
export const agentCheckInDeprecated = (
{ cloudProvider }: AgentCheckInDeprecatedPathParameters,
cloudintegrationtypesPostableAgentCheckInDTO: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>,
cloudintegrationtypesPostableAgentCheckInDTO?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<AgentCheckInDeprecated200>({
@@ -77,7 +78,7 @@ export const getAgentCheckInDeprecatedMutationOptions = <
TError,
{
pathParams: AgentCheckInDeprecatedPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
>;
@@ -86,7 +87,7 @@ export const getAgentCheckInDeprecatedMutationOptions = <
TError,
{
pathParams: AgentCheckInDeprecatedPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
> => {
@@ -103,7 +104,7 @@ export const getAgentCheckInDeprecatedMutationOptions = <
Awaited<ReturnType<typeof agentCheckInDeprecated>>,
{
pathParams: AgentCheckInDeprecatedPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -118,7 +119,8 @@ export type AgentCheckInDeprecatedMutationResult = NonNullable<
Awaited<ReturnType<typeof agentCheckInDeprecated>>
>;
export type AgentCheckInDeprecatedMutationBody =
BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
| BodyType<CloudintegrationtypesPostableAgentCheckInDTO>
| undefined;
export type AgentCheckInDeprecatedMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -135,7 +137,7 @@ export const useAgentCheckInDeprecated = <
TError,
{
pathParams: AgentCheckInDeprecatedPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
>;
@@ -144,13 +146,11 @@ export const useAgentCheckInDeprecated = <
TError,
{
pathParams: AgentCheckInDeprecatedPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
> => {
const mutationOptions = getAgentCheckInDeprecatedMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getAgentCheckInDeprecatedMutationOptions(options));
};
/**
* This endpoint lists the accounts for the specified cloud provider
@@ -235,9 +235,7 @@ export function useListAccounts<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -262,7 +260,7 @@ export const invalidateListAccounts = async (
*/
export const createAccount = (
{ cloudProvider }: CreateAccountPathParameters,
cloudintegrationtypesPostableAccountDTO: BodyType<CloudintegrationtypesPostableAccountDTO>,
cloudintegrationtypesPostableAccountDTO?: BodyType<CloudintegrationtypesPostableAccountDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateAccount201>({
@@ -283,7 +281,7 @@ export const getCreateAccountMutationOptions = <
TError,
{
pathParams: CreateAccountPathParameters;
data: BodyType<CloudintegrationtypesPostableAccountDTO>;
data?: BodyType<CloudintegrationtypesPostableAccountDTO>;
},
TContext
>;
@@ -292,7 +290,7 @@ export const getCreateAccountMutationOptions = <
TError,
{
pathParams: CreateAccountPathParameters;
data: BodyType<CloudintegrationtypesPostableAccountDTO>;
data?: BodyType<CloudintegrationtypesPostableAccountDTO>;
},
TContext
> => {
@@ -309,7 +307,7 @@ export const getCreateAccountMutationOptions = <
Awaited<ReturnType<typeof createAccount>>,
{
pathParams: CreateAccountPathParameters;
data: BodyType<CloudintegrationtypesPostableAccountDTO>;
data?: BodyType<CloudintegrationtypesPostableAccountDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -324,7 +322,8 @@ export type CreateAccountMutationResult = NonNullable<
Awaited<ReturnType<typeof createAccount>>
>;
export type CreateAccountMutationBody =
BodyType<CloudintegrationtypesPostableAccountDTO>;
| BodyType<CloudintegrationtypesPostableAccountDTO>
| undefined;
export type CreateAccountMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -339,7 +338,7 @@ export const useCreateAccount = <
TError,
{
pathParams: CreateAccountPathParameters;
data: BodyType<CloudintegrationtypesPostableAccountDTO>;
data?: BodyType<CloudintegrationtypesPostableAccountDTO>;
},
TContext
>;
@@ -348,25 +347,24 @@ export const useCreateAccount = <
TError,
{
pathParams: CreateAccountPathParameters;
data: BodyType<CloudintegrationtypesPostableAccountDTO>;
data?: BodyType<CloudintegrationtypesPostableAccountDTO>;
},
TContext
> => {
const mutationOptions = getCreateAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateAccountMutationOptions(options));
};
/**
* This endpoint disconnects an account for the specified cloud provider
* @summary Disconnect account
*/
export const disconnectAccount = ({
cloudProvider,
id,
}: DisconnectAccountPathParameters) => {
export const disconnectAccount = (
{ cloudProvider, id }: DisconnectAccountPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/cloud_integrations/${cloudProvider}/accounts/${id}`,
method: 'DELETE',
signal,
});
};
@@ -432,9 +430,7 @@ export const useDisconnectAccount = <
{ pathParams: DisconnectAccountPathParameters },
TContext
> => {
const mutationOptions = getDisconnectAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDisconnectAccountMutationOptions(options));
};
/**
* This endpoint gets an account for the specified cloud provider
@@ -518,9 +514,7 @@ export function useGetAccount<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -545,13 +539,15 @@ export const invalidateGetAccount = async (
*/
export const updateAccount = (
{ cloudProvider, id }: UpdateAccountPathParameters,
cloudintegrationtypesUpdatableAccountDTO: BodyType<CloudintegrationtypesUpdatableAccountDTO>,
cloudintegrationtypesUpdatableAccountDTO?: BodyType<CloudintegrationtypesUpdatableAccountDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/cloud_integrations/${cloudProvider}/accounts/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: cloudintegrationtypesUpdatableAccountDTO,
signal,
});
};
@@ -564,7 +560,7 @@ export const getUpdateAccountMutationOptions = <
TError,
{
pathParams: UpdateAccountPathParameters;
data: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
data?: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
},
TContext
>;
@@ -573,7 +569,7 @@ export const getUpdateAccountMutationOptions = <
TError,
{
pathParams: UpdateAccountPathParameters;
data: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
data?: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
},
TContext
> => {
@@ -590,7 +586,7 @@ export const getUpdateAccountMutationOptions = <
Awaited<ReturnType<typeof updateAccount>>,
{
pathParams: UpdateAccountPathParameters;
data: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
data?: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -605,7 +601,8 @@ export type UpdateAccountMutationResult = NonNullable<
Awaited<ReturnType<typeof updateAccount>>
>;
export type UpdateAccountMutationBody =
BodyType<CloudintegrationtypesUpdatableAccountDTO>;
| BodyType<CloudintegrationtypesUpdatableAccountDTO>
| undefined;
export type UpdateAccountMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -620,7 +617,7 @@ export const useUpdateAccount = <
TError,
{
pathParams: UpdateAccountPathParameters;
data: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
data?: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
},
TContext
>;
@@ -629,13 +626,11 @@ export const useUpdateAccount = <
TError,
{
pathParams: UpdateAccountPathParameters;
data: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
data?: BodyType<CloudintegrationtypesUpdatableAccountDTO>;
},
TContext
> => {
const mutationOptions = getUpdateAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateAccountMutationOptions(options));
};
/**
* This endpoint updates a service for the specified cloud provider
@@ -643,13 +638,15 @@ export const useUpdateAccount = <
*/
export const updateService = (
{ cloudProvider, id, serviceId }: UpdateServicePathParameters,
cloudintegrationtypesUpdatableServiceDTO: BodyType<CloudintegrationtypesUpdatableServiceDTO>,
cloudintegrationtypesUpdatableServiceDTO?: BodyType<CloudintegrationtypesUpdatableServiceDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/cloud_integrations/${cloudProvider}/accounts/${id}/services/${serviceId}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: cloudintegrationtypesUpdatableServiceDTO,
signal,
});
};
@@ -662,7 +659,7 @@ export const getUpdateServiceMutationOptions = <
TError,
{
pathParams: UpdateServicePathParameters;
data: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
data?: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
},
TContext
>;
@@ -671,7 +668,7 @@ export const getUpdateServiceMutationOptions = <
TError,
{
pathParams: UpdateServicePathParameters;
data: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
data?: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
},
TContext
> => {
@@ -688,7 +685,7 @@ export const getUpdateServiceMutationOptions = <
Awaited<ReturnType<typeof updateService>>,
{
pathParams: UpdateServicePathParameters;
data: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
data?: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -703,7 +700,8 @@ export type UpdateServiceMutationResult = NonNullable<
Awaited<ReturnType<typeof updateService>>
>;
export type UpdateServiceMutationBody =
BodyType<CloudintegrationtypesUpdatableServiceDTO>;
| BodyType<CloudintegrationtypesUpdatableServiceDTO>
| undefined;
export type UpdateServiceMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -718,7 +716,7 @@ export const useUpdateService = <
TError,
{
pathParams: UpdateServicePathParameters;
data: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
data?: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
},
TContext
>;
@@ -727,13 +725,11 @@ export const useUpdateService = <
TError,
{
pathParams: UpdateServicePathParameters;
data: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
data?: BodyType<CloudintegrationtypesUpdatableServiceDTO>;
},
TContext
> => {
const mutationOptions = getUpdateServiceMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateServiceMutationOptions(options));
};
/**
* This endpoint is called by the deployed agent to check in
@@ -741,7 +737,7 @@ export const useUpdateService = <
*/
export const agentCheckIn = (
{ cloudProvider }: AgentCheckInPathParameters,
cloudintegrationtypesPostableAgentCheckInDTO: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>,
cloudintegrationtypesPostableAgentCheckInDTO?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<AgentCheckIn200>({
@@ -762,7 +758,7 @@ export const getAgentCheckInMutationOptions = <
TError,
{
pathParams: AgentCheckInPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
>;
@@ -771,7 +767,7 @@ export const getAgentCheckInMutationOptions = <
TError,
{
pathParams: AgentCheckInPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
> => {
@@ -788,7 +784,7 @@ export const getAgentCheckInMutationOptions = <
Awaited<ReturnType<typeof agentCheckIn>>,
{
pathParams: AgentCheckInPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -803,7 +799,8 @@ export type AgentCheckInMutationResult = NonNullable<
Awaited<ReturnType<typeof agentCheckIn>>
>;
export type AgentCheckInMutationBody =
BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
| BodyType<CloudintegrationtypesPostableAgentCheckInDTO>
| undefined;
export type AgentCheckInMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -818,7 +815,7 @@ export const useAgentCheckIn = <
TError,
{
pathParams: AgentCheckInPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
>;
@@ -827,13 +824,11 @@ export const useAgentCheckIn = <
TError,
{
pathParams: AgentCheckInPathParameters;
data: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
data?: BodyType<CloudintegrationtypesPostableAgentCheckInDTO>;
},
TContext
> => {
const mutationOptions = getAgentCheckInMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getAgentCheckInMutationOptions(options));
};
/**
* This endpoint retrieves the connection credentials required for integration
@@ -923,9 +918,7 @@ export function useGetConnectionCredentials<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1040,9 +1033,7 @@ export function useListServicesMetadata<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1156,9 +1147,7 @@ export function useGetService<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -18,34 +19,19 @@ import type {
} from 'react-query';
import type {
CreateDashboardV2201,
CreatePublicDashboard201,
CreatePublicDashboardPathParameters,
CreatePublicDashboardV2200,
CreatePublicDashboardV2PathParameters,
DashboardtypesJSONPatchDocumentDTO,
DashboardtypesPostableDashboardV2DTO,
DashboardtypesPostablePublicDashboardDTO,
DashboardtypesUpdatablePublicDashboardDTO,
DeletePublicDashboardPathParameters,
GetDashboardV2200,
GetDashboardV2PathParameters,
GetPublicDashboard200,
GetPublicDashboardData200,
GetPublicDashboardDataPathParameters,
GetPublicDashboardPathParameters,
GetPublicDashboardWidgetQueryRange200,
GetPublicDashboardWidgetQueryRangePathParameters,
LockDashboardV2PathParameters,
PatchDashboardV2200,
PatchDashboardV2PathParameters,
RenderErrorResponseDTO,
UnlockDashboardV2PathParameters,
UpdateDashboardV2200,
UpdateDashboardV2PathParameters,
UpdatePublicDashboardPathParameters,
UpdatePublicDashboardV2200,
UpdatePublicDashboardV2PathParameters,
} from '../sigNoz.schemas';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
@@ -55,12 +41,14 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
* This endpoint deletes the public sharing config and disables the public sharing of a dashboard
* @summary Delete public dashboard
*/
export const deletePublicDashboard = ({
id,
}: DeletePublicDashboardPathParameters) => {
export const deletePublicDashboard = (
{ id }: DeletePublicDashboardPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/dashboards/${id}/public`,
method: 'DELETE',
signal,
});
};
@@ -127,9 +115,7 @@ export const useDeletePublicDashboard = <
{ pathParams: DeletePublicDashboardPathParameters },
TContext
> => {
const mutationOptions = getDeletePublicDashboardMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeletePublicDashboardMutationOptions(options));
};
/**
* This endpoint returns public sharing config for a dashboard
@@ -214,9 +200,7 @@ export function useGetPublicDashboard<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -241,7 +225,7 @@ export const invalidateGetPublicDashboard = async (
*/
export const createPublicDashboard = (
{ id }: CreatePublicDashboardPathParameters,
dashboardtypesPostablePublicDashboardDTO: BodyType<DashboardtypesPostablePublicDashboardDTO>,
dashboardtypesPostablePublicDashboardDTO?: BodyType<DashboardtypesPostablePublicDashboardDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreatePublicDashboard201>({
@@ -262,7 +246,7 @@ export const getCreatePublicDashboardMutationOptions = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data?: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
>;
@@ -271,7 +255,7 @@ export const getCreatePublicDashboardMutationOptions = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data?: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
> => {
@@ -288,7 +272,7 @@ export const getCreatePublicDashboardMutationOptions = <
Awaited<ReturnType<typeof createPublicDashboard>>,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data?: BodyType<DashboardtypesPostablePublicDashboardDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -303,7 +287,8 @@ export type CreatePublicDashboardMutationResult = NonNullable<
Awaited<ReturnType<typeof createPublicDashboard>>
>;
export type CreatePublicDashboardMutationBody =
BodyType<DashboardtypesPostablePublicDashboardDTO>;
| BodyType<DashboardtypesPostablePublicDashboardDTO>
| undefined;
export type CreatePublicDashboardMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -319,7 +304,7 @@ export const useCreatePublicDashboard = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data?: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
>;
@@ -328,13 +313,11 @@ export const useCreatePublicDashboard = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data?: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
> => {
const mutationOptions = getCreatePublicDashboardMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreatePublicDashboardMutationOptions(options));
};
/**
* This endpoint updates the public sharing config for a dashboard
@@ -342,13 +325,15 @@ export const useCreatePublicDashboard = <
*/
export const updatePublicDashboard = (
{ id }: UpdatePublicDashboardPathParameters,
dashboardtypesUpdatablePublicDashboardDTO: BodyType<DashboardtypesUpdatablePublicDashboardDTO>,
dashboardtypesUpdatablePublicDashboardDTO?: BodyType<DashboardtypesUpdatablePublicDashboardDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/dashboards/${id}/public`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: dashboardtypesUpdatablePublicDashboardDTO,
signal,
});
};
@@ -361,7 +346,7 @@ export const getUpdatePublicDashboardMutationOptions = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data?: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
>;
@@ -370,7 +355,7 @@ export const getUpdatePublicDashboardMutationOptions = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data?: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
> => {
@@ -387,7 +372,7 @@ export const getUpdatePublicDashboardMutationOptions = <
Awaited<ReturnType<typeof updatePublicDashboard>>,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data?: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -402,7 +387,8 @@ export type UpdatePublicDashboardMutationResult = NonNullable<
Awaited<ReturnType<typeof updatePublicDashboard>>
>;
export type UpdatePublicDashboardMutationBody =
BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
| BodyType<DashboardtypesUpdatablePublicDashboardDTO>
| undefined;
export type UpdatePublicDashboardMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -418,7 +404,7 @@ export const useUpdatePublicDashboard = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data?: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
>;
@@ -427,13 +413,11 @@ export const useUpdatePublicDashboard = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data?: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
> => {
const mutationOptions = getUpdatePublicDashboardMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdatePublicDashboardMutationOptions(options));
};
/**
* This endpoint returns the sanitized dashboard data for public access
@@ -519,9 +503,7 @@ export function useGetPublicDashboardData<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -629,9 +611,7 @@ export function useGetPublicDashboardWidgetQueryRange<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -649,739 +629,3 @@ export const invalidateGetPublicDashboardWidgetQueryRange = async (
return queryClient;
};
/**
* This endpoint creates a v2-shape dashboard with structured metadata, a typed data tree, and resolved tags.
* @summary Create dashboard (v2)
*/
export const createDashboardV2 = (
dashboardtypesPostableDashboardV2DTO: BodyType<DashboardtypesPostableDashboardV2DTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateDashboardV2201>({
url: `/api/v2/dashboards`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: dashboardtypesPostableDashboardV2DTO,
signal,
});
};
export const getCreateDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createDashboardV2>>,
TError,
{ data: BodyType<DashboardtypesPostableDashboardV2DTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createDashboardV2>>,
TError,
{ data: BodyType<DashboardtypesPostableDashboardV2DTO> },
TContext
> => {
const mutationKey = ['createDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createDashboardV2>>,
{ data: BodyType<DashboardtypesPostableDashboardV2DTO> }
> = (props) => {
const { data } = props ?? {};
return createDashboardV2(data);
};
return { mutationFn, ...mutationOptions };
};
export type CreateDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof createDashboardV2>>
>;
export type CreateDashboardV2MutationBody =
BodyType<DashboardtypesPostableDashboardV2DTO>;
export type CreateDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Create dashboard (v2)
*/
export const useCreateDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createDashboardV2>>,
TError,
{ data: BodyType<DashboardtypesPostableDashboardV2DTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createDashboardV2>>,
TError,
{ data: BodyType<DashboardtypesPostableDashboardV2DTO> },
TContext
> => {
const mutationOptions = getCreateDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint returns a v2-shape dashboard with its tags and public sharing config (if any).
* @summary Get dashboard (v2)
*/
export const getDashboardV2 = (
{ id }: GetDashboardV2PathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetDashboardV2200>({
url: `/api/v2/dashboards/${id}`,
method: 'GET',
signal,
});
};
export const getGetDashboardV2QueryKey = ({
id,
}: GetDashboardV2PathParameters) => {
return [`/api/v2/dashboards/${id}`] as const;
};
export const getGetDashboardV2QueryOptions = <
TData = Awaited<ReturnType<typeof getDashboardV2>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ id }: GetDashboardV2PathParameters,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getDashboardV2>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetDashboardV2QueryKey({ id });
const queryFn: QueryFunction<Awaited<ReturnType<typeof getDashboardV2>>> = ({
signal,
}) => getDashboardV2({ id }, signal);
return {
queryKey,
queryFn,
enabled: !!id,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof getDashboardV2>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type GetDashboardV2QueryResult = NonNullable<
Awaited<ReturnType<typeof getDashboardV2>>
>;
export type GetDashboardV2QueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get dashboard (v2)
*/
export function useGetDashboardV2<
TData = Awaited<ReturnType<typeof getDashboardV2>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ id }: GetDashboardV2PathParameters,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getDashboardV2>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetDashboardV2QueryOptions({ id }, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
}
/**
* @summary Get dashboard (v2)
*/
export const invalidateGetDashboardV2 = async (
queryClient: QueryClient,
{ id }: GetDashboardV2PathParameters,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetDashboardV2QueryKey({ id }) },
options,
);
return queryClient;
};
/**
* This endpoint applies an RFC 6902 JSON Patch to a v2-shape dashboard. The patch is applied against the postable view of the dashboard (metadata, data, tags), so individual panels, queries, variables, layouts, or tags can be updated without re-sending the rest of the dashboard. Locked dashboards are rejected.
* @summary Patch dashboard (v2)
*/
export const patchDashboardV2 = (
{ id }: PatchDashboardV2PathParameters,
dashboardtypesJSONPatchDocumentDTO: BodyType<DashboardtypesJSONPatchDocumentDTO>,
) => {
return GeneratedAPIInstance<PatchDashboardV2200>({
url: `/api/v2/dashboards/${id}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: dashboardtypesJSONPatchDocumentDTO,
});
};
export const getPatchDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof patchDashboardV2>>,
TError,
{
pathParams: PatchDashboardV2PathParameters;
data: BodyType<DashboardtypesJSONPatchDocumentDTO>;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof patchDashboardV2>>,
TError,
{
pathParams: PatchDashboardV2PathParameters;
data: BodyType<DashboardtypesJSONPatchDocumentDTO>;
},
TContext
> => {
const mutationKey = ['patchDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof patchDashboardV2>>,
{
pathParams: PatchDashboardV2PathParameters;
data: BodyType<DashboardtypesJSONPatchDocumentDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
return patchDashboardV2(pathParams, data);
};
return { mutationFn, ...mutationOptions };
};
export type PatchDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof patchDashboardV2>>
>;
export type PatchDashboardV2MutationBody =
BodyType<DashboardtypesJSONPatchDocumentDTO>;
export type PatchDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Patch dashboard (v2)
*/
export const usePatchDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof patchDashboardV2>>,
TError,
{
pathParams: PatchDashboardV2PathParameters;
data: BodyType<DashboardtypesJSONPatchDocumentDTO>;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof patchDashboardV2>>,
TError,
{
pathParams: PatchDashboardV2PathParameters;
data: BodyType<DashboardtypesJSONPatchDocumentDTO>;
},
TContext
> => {
const mutationOptions = getPatchDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint updates a v2-shape dashboard's metadata, data, and tag set. Locked dashboards are rejected.
* @summary Update dashboard (v2)
*/
export const updateDashboardV2 = (
{ id }: UpdateDashboardV2PathParameters,
dashboardtypesPostableDashboardV2DTO: BodyType<DashboardtypesPostableDashboardV2DTO>,
) => {
return GeneratedAPIInstance<UpdateDashboardV2200>({
url: `/api/v2/dashboards/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: dashboardtypesPostableDashboardV2DTO,
});
};
export const getUpdateDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateDashboardV2>>,
TError,
{
pathParams: UpdateDashboardV2PathParameters;
data: BodyType<DashboardtypesPostableDashboardV2DTO>;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateDashboardV2>>,
TError,
{
pathParams: UpdateDashboardV2PathParameters;
data: BodyType<DashboardtypesPostableDashboardV2DTO>;
},
TContext
> => {
const mutationKey = ['updateDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateDashboardV2>>,
{
pathParams: UpdateDashboardV2PathParameters;
data: BodyType<DashboardtypesPostableDashboardV2DTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
return updateDashboardV2(pathParams, data);
};
return { mutationFn, ...mutationOptions };
};
export type UpdateDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof updateDashboardV2>>
>;
export type UpdateDashboardV2MutationBody =
BodyType<DashboardtypesPostableDashboardV2DTO>;
export type UpdateDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Update dashboard (v2)
*/
export const useUpdateDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateDashboardV2>>,
TError,
{
pathParams: UpdateDashboardV2PathParameters;
data: BodyType<DashboardtypesPostableDashboardV2DTO>;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateDashboardV2>>,
TError,
{
pathParams: UpdateDashboardV2PathParameters;
data: BodyType<DashboardtypesPostableDashboardV2DTO>;
},
TContext
> => {
const mutationOptions = getUpdateDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint unlocks a v2-shape dashboard. Only the dashboard's creator or an org admin may lock or unlock.
* @summary Unlock dashboard (v2)
*/
export const unlockDashboardV2 = ({ id }: UnlockDashboardV2PathParameters) => {
return GeneratedAPIInstance<string>({
url: `/api/v2/dashboards/${id}/lock`,
method: 'DELETE',
});
};
export const getUnlockDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof unlockDashboardV2>>,
TError,
{ pathParams: UnlockDashboardV2PathParameters },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof unlockDashboardV2>>,
TError,
{ pathParams: UnlockDashboardV2PathParameters },
TContext
> => {
const mutationKey = ['unlockDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof unlockDashboardV2>>,
{ pathParams: UnlockDashboardV2PathParameters }
> = (props) => {
const { pathParams } = props ?? {};
return unlockDashboardV2(pathParams);
};
return { mutationFn, ...mutationOptions };
};
export type UnlockDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof unlockDashboardV2>>
>;
export type UnlockDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Unlock dashboard (v2)
*/
export const useUnlockDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof unlockDashboardV2>>,
TError,
{ pathParams: UnlockDashboardV2PathParameters },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof unlockDashboardV2>>,
TError,
{ pathParams: UnlockDashboardV2PathParameters },
TContext
> => {
const mutationOptions = getUnlockDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint locks a v2-shape dashboard. Only the dashboard's creator or an org admin may lock or unlock.
* @summary Lock dashboard (v2)
*/
export const lockDashboardV2 = ({ id }: LockDashboardV2PathParameters) => {
return GeneratedAPIInstance<string>({
url: `/api/v2/dashboards/${id}/lock`,
method: 'PUT',
});
};
export const getLockDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof lockDashboardV2>>,
TError,
{ pathParams: LockDashboardV2PathParameters },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof lockDashboardV2>>,
TError,
{ pathParams: LockDashboardV2PathParameters },
TContext
> => {
const mutationKey = ['lockDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof lockDashboardV2>>,
{ pathParams: LockDashboardV2PathParameters }
> = (props) => {
const { pathParams } = props ?? {};
return lockDashboardV2(pathParams);
};
return { mutationFn, ...mutationOptions };
};
export type LockDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof lockDashboardV2>>
>;
export type LockDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Lock dashboard (v2)
*/
export const useLockDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof lockDashboardV2>>,
TError,
{ pathParams: LockDashboardV2PathParameters },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof lockDashboardV2>>,
TError,
{ pathParams: LockDashboardV2PathParameters },
TContext
> => {
const mutationOptions = getLockDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint creates the public sharing config for a v2 dashboard and returns the dashboard with the new public config attached. Lock state does not gate this endpoint.
* @summary Make a dashboard v2 public
*/
export const createPublicDashboardV2 = (
{ id }: CreatePublicDashboardV2PathParameters,
dashboardtypesPostablePublicDashboardDTO: BodyType<DashboardtypesPostablePublicDashboardDTO>,
) => {
return GeneratedAPIInstance<CreatePublicDashboardV2200>({
url: `/api/v2/dashboards/${id}/public`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: dashboardtypesPostablePublicDashboardDTO,
});
};
export const getCreatePublicDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createPublicDashboardV2>>,
TError,
{
pathParams: CreatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createPublicDashboardV2>>,
TError,
{
pathParams: CreatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
> => {
const mutationKey = ['createPublicDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createPublicDashboardV2>>,
{
pathParams: CreatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
return createPublicDashboardV2(pathParams, data);
};
return { mutationFn, ...mutationOptions };
};
export type CreatePublicDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof createPublicDashboardV2>>
>;
export type CreatePublicDashboardV2MutationBody =
BodyType<DashboardtypesPostablePublicDashboardDTO>;
export type CreatePublicDashboardV2MutationError =
ErrorType<RenderErrorResponseDTO>;
/**
* @summary Make a dashboard v2 public
*/
export const useCreatePublicDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createPublicDashboardV2>>,
TError,
{
pathParams: CreatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createPublicDashboardV2>>,
TError,
{
pathParams: CreatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
},
TContext
> => {
const mutationOptions = getCreatePublicDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint updates the public sharing config (time range settings) of an already-public v2 dashboard. Lock state does not gate this endpoint.
* @summary Update public sharing config for a dashboard v2
*/
export const updatePublicDashboardV2 = (
{ id }: UpdatePublicDashboardV2PathParameters,
dashboardtypesUpdatablePublicDashboardDTO: BodyType<DashboardtypesUpdatablePublicDashboardDTO>,
) => {
return GeneratedAPIInstance<UpdatePublicDashboardV2200>({
url: `/api/v2/dashboards/${id}/public`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: dashboardtypesUpdatablePublicDashboardDTO,
});
};
export const getUpdatePublicDashboardV2MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updatePublicDashboardV2>>,
TError,
{
pathParams: UpdatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updatePublicDashboardV2>>,
TError,
{
pathParams: UpdatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
> => {
const mutationKey = ['updatePublicDashboardV2'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updatePublicDashboardV2>>,
{
pathParams: UpdatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
return updatePublicDashboardV2(pathParams, data);
};
return { mutationFn, ...mutationOptions };
};
export type UpdatePublicDashboardV2MutationResult = NonNullable<
Awaited<ReturnType<typeof updatePublicDashboardV2>>
>;
export type UpdatePublicDashboardV2MutationBody =
BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
export type UpdatePublicDashboardV2MutationError =
ErrorType<RenderErrorResponseDTO>;
/**
* @summary Update public sharing config for a dashboard v2
*/
export const useUpdatePublicDashboardV2 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updatePublicDashboardV2>>,
TError,
{
pathParams: UpdatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updatePublicDashboardV2>>,
TError,
{
pathParams: UpdatePublicDashboardV2PathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
},
TContext
> => {
const mutationOptions = getUpdatePublicDashboardV2MutationOptions(options);
return useMutation(mutationOptions);
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -111,9 +112,7 @@ export function useListDowntimeSchedules<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -137,7 +136,7 @@ export const invalidateListDowntimeSchedules = async (
* @summary Create downtime schedule
*/
export const createDowntimeSchedule = (
ruletypesPostablePlannedMaintenanceDTO: BodyType<RuletypesPostablePlannedMaintenanceDTO>,
ruletypesPostablePlannedMaintenanceDTO?: BodyType<RuletypesPostablePlannedMaintenanceDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateDowntimeSchedule201>({
@@ -156,13 +155,13 @@ export const getCreateDowntimeScheduleMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createDowntimeSchedule>>,
TError,
{ data: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
{ data?: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createDowntimeSchedule>>,
TError,
{ data: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
{ data?: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
TContext
> => {
const mutationKey = ['createDowntimeSchedule'];
@@ -176,7 +175,7 @@ export const getCreateDowntimeScheduleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createDowntimeSchedule>>,
{ data: BodyType<RuletypesPostablePlannedMaintenanceDTO> }
{ data?: BodyType<RuletypesPostablePlannedMaintenanceDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -190,7 +189,8 @@ export type CreateDowntimeScheduleMutationResult = NonNullable<
Awaited<ReturnType<typeof createDowntimeSchedule>>
>;
export type CreateDowntimeScheduleMutationBody =
BodyType<RuletypesPostablePlannedMaintenanceDTO>;
| BodyType<RuletypesPostablePlannedMaintenanceDTO>
| undefined;
export type CreateDowntimeScheduleMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -204,29 +204,29 @@ export const useCreateDowntimeSchedule = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createDowntimeSchedule>>,
TError,
{ data: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
{ data?: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createDowntimeSchedule>>,
TError,
{ data: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
{ data?: BodyType<RuletypesPostablePlannedMaintenanceDTO> },
TContext
> => {
const mutationOptions = getCreateDowntimeScheduleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateDowntimeScheduleMutationOptions(options));
};
/**
* This endpoint deletes a downtime schedule by ID
* @summary Delete downtime schedule
*/
export const deleteDowntimeScheduleByID = ({
id,
}: DeleteDowntimeScheduleByIDPathParameters) => {
export const deleteDowntimeScheduleByID = (
{ id }: DeleteDowntimeScheduleByIDPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/downtime_schedules/${id}`,
method: 'DELETE',
signal,
});
};
@@ -293,9 +293,7 @@ export const useDeleteDowntimeScheduleByID = <
{ pathParams: DeleteDowntimeScheduleByIDPathParameters },
TContext
> => {
const mutationOptions = getDeleteDowntimeScheduleByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteDowntimeScheduleByIDMutationOptions(options));
};
/**
* This endpoint returns a downtime schedule by ID
@@ -381,9 +379,7 @@ export function useGetDowntimeScheduleByID<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -408,13 +404,15 @@ export const invalidateGetDowntimeScheduleByID = async (
*/
export const updateDowntimeScheduleByID = (
{ id }: UpdateDowntimeScheduleByIDPathParameters,
ruletypesPostablePlannedMaintenanceDTO: BodyType<RuletypesPostablePlannedMaintenanceDTO>,
ruletypesPostablePlannedMaintenanceDTO?: BodyType<RuletypesPostablePlannedMaintenanceDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/downtime_schedules/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: ruletypesPostablePlannedMaintenanceDTO,
signal,
});
};
@@ -427,7 +425,7 @@ export const getUpdateDowntimeScheduleByIDMutationOptions = <
TError,
{
pathParams: UpdateDowntimeScheduleByIDPathParameters;
data: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
data?: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
},
TContext
>;
@@ -436,7 +434,7 @@ export const getUpdateDowntimeScheduleByIDMutationOptions = <
TError,
{
pathParams: UpdateDowntimeScheduleByIDPathParameters;
data: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
data?: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
},
TContext
> => {
@@ -453,7 +451,7 @@ export const getUpdateDowntimeScheduleByIDMutationOptions = <
Awaited<ReturnType<typeof updateDowntimeScheduleByID>>,
{
pathParams: UpdateDowntimeScheduleByIDPathParameters;
data: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
data?: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -468,7 +466,8 @@ export type UpdateDowntimeScheduleByIDMutationResult = NonNullable<
Awaited<ReturnType<typeof updateDowntimeScheduleByID>>
>;
export type UpdateDowntimeScheduleByIDMutationBody =
BodyType<RuletypesPostablePlannedMaintenanceDTO>;
| BodyType<RuletypesPostablePlannedMaintenanceDTO>
| undefined;
export type UpdateDowntimeScheduleByIDMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -484,7 +483,7 @@ export const useUpdateDowntimeScheduleByID = <
TError,
{
pathParams: UpdateDowntimeScheduleByIDPathParameters;
data: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
data?: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
},
TContext
>;
@@ -493,11 +492,9 @@ export const useUpdateDowntimeScheduleByID = <
TError,
{
pathParams: UpdateDowntimeScheduleByIDPathParameters;
data: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
data?: BodyType<RuletypesPostablePlannedMaintenanceDTO>;
},
TContext
> => {
const mutationOptions = getUpdateDowntimeScheduleByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateDowntimeScheduleByIDMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useQuery } from 'react-query';
import type {
@@ -85,9 +86,7 @@ export function useGetFeatures<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useQuery } from 'react-query';
import type {
@@ -101,9 +102,7 @@ export function useGetFieldsKeys<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -198,9 +197,7 @@ export function useGetFieldsValues<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -119,9 +120,7 @@ export function useGetIngestionKeys<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -145,7 +144,7 @@ export const invalidateGetIngestionKeys = async (
* @summary Create ingestion key for workspace
*/
export const createIngestionKey = (
gatewaytypesPostableIngestionKeyDTO: BodyType<GatewaytypesPostableIngestionKeyDTO>,
gatewaytypesPostableIngestionKeyDTO?: BodyType<GatewaytypesPostableIngestionKeyDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateIngestionKey201>({
@@ -164,13 +163,13 @@ export const getCreateIngestionKeyMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data?: BodyType<GatewaytypesPostableIngestionKeyDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data?: BodyType<GatewaytypesPostableIngestionKeyDTO> },
TContext
> => {
const mutationKey = ['createIngestionKey'];
@@ -184,7 +183,7 @@ export const getCreateIngestionKeyMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createIngestionKey>>,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> }
{ data?: BodyType<GatewaytypesPostableIngestionKeyDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -198,7 +197,8 @@ export type CreateIngestionKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof createIngestionKey>>
>;
export type CreateIngestionKeyMutationBody =
BodyType<GatewaytypesPostableIngestionKeyDTO>;
| BodyType<GatewaytypesPostableIngestionKeyDTO>
| undefined;
export type CreateIngestionKeyMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -211,29 +211,29 @@ export const useCreateIngestionKey = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data?: BodyType<GatewaytypesPostableIngestionKeyDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data?: BodyType<GatewaytypesPostableIngestionKeyDTO> },
TContext
> => {
const mutationOptions = getCreateIngestionKeyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateIngestionKeyMutationOptions(options));
};
/**
* This endpoint deletes an ingestion key for the workspace
* @summary Delete ingestion key for workspace
*/
export const deleteIngestionKey = ({
keyId,
}: DeleteIngestionKeyPathParameters) => {
export const deleteIngestionKey = (
{ keyId }: DeleteIngestionKeyPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/gateway/ingestion_keys/${keyId}`,
method: 'DELETE',
signal,
});
};
@@ -299,9 +299,7 @@ export const useDeleteIngestionKey = <
{ pathParams: DeleteIngestionKeyPathParameters },
TContext
> => {
const mutationOptions = getDeleteIngestionKeyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteIngestionKeyMutationOptions(options));
};
/**
* This endpoint updates an ingestion key for the workspace
@@ -309,13 +307,15 @@ export const useDeleteIngestionKey = <
*/
export const updateIngestionKey = (
{ keyId }: UpdateIngestionKeyPathParameters,
gatewaytypesPostableIngestionKeyDTO: BodyType<GatewaytypesPostableIngestionKeyDTO>,
gatewaytypesPostableIngestionKeyDTO?: BodyType<GatewaytypesPostableIngestionKeyDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/gateway/ingestion_keys/${keyId}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: gatewaytypesPostableIngestionKeyDTO,
signal,
});
};
@@ -328,7 +328,7 @@ export const getUpdateIngestionKeyMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyDTO>;
},
TContext
>;
@@ -337,7 +337,7 @@ export const getUpdateIngestionKeyMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyDTO>;
},
TContext
> => {
@@ -354,7 +354,7 @@ export const getUpdateIngestionKeyMutationOptions = <
Awaited<ReturnType<typeof updateIngestionKey>>,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -369,7 +369,8 @@ export type UpdateIngestionKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof updateIngestionKey>>
>;
export type UpdateIngestionKeyMutationBody =
BodyType<GatewaytypesPostableIngestionKeyDTO>;
| BodyType<GatewaytypesPostableIngestionKeyDTO>
| undefined;
export type UpdateIngestionKeyMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -384,7 +385,7 @@ export const useUpdateIngestionKey = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyDTO>;
},
TContext
>;
@@ -393,13 +394,11 @@ export const useUpdateIngestionKey = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyDTO>;
},
TContext
> => {
const mutationOptions = getUpdateIngestionKeyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateIngestionKeyMutationOptions(options));
};
/**
* This endpoint creates an ingestion key limit
@@ -407,7 +406,7 @@ export const useUpdateIngestionKey = <
*/
export const createIngestionKeyLimit = (
{ keyId }: CreateIngestionKeyLimitPathParameters,
gatewaytypesPostableIngestionKeyLimitDTO: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>,
gatewaytypesPostableIngestionKeyLimitDTO?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateIngestionKeyLimit201>({
@@ -428,7 +427,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
},
TContext
>;
@@ -437,7 +436,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
},
TContext
> => {
@@ -454,7 +453,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <
Awaited<ReturnType<typeof createIngestionKeyLimit>>,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -469,7 +468,8 @@ export type CreateIngestionKeyLimitMutationResult = NonNullable<
Awaited<ReturnType<typeof createIngestionKeyLimit>>
>;
export type CreateIngestionKeyLimitMutationBody =
BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
| BodyType<GatewaytypesPostableIngestionKeyLimitDTO>
| undefined;
export type CreateIngestionKeyLimitMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -485,7 +485,7 @@ export const useCreateIngestionKeyLimit = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
},
TContext
>;
@@ -494,24 +494,24 @@ export const useCreateIngestionKeyLimit = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
},
TContext
> => {
const mutationOptions = getCreateIngestionKeyLimitMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateIngestionKeyLimitMutationOptions(options));
};
/**
* This endpoint deletes an ingestion key limit
* @summary Delete limit for the ingestion key
*/
export const deleteIngestionKeyLimit = ({
limitId,
}: DeleteIngestionKeyLimitPathParameters) => {
export const deleteIngestionKeyLimit = (
{ limitId }: DeleteIngestionKeyLimitPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/gateway/ingestion_keys/limits/${limitId}`,
method: 'DELETE',
signal,
});
};
@@ -578,9 +578,7 @@ export const useDeleteIngestionKeyLimit = <
{ pathParams: DeleteIngestionKeyLimitPathParameters },
TContext
> => {
const mutationOptions = getDeleteIngestionKeyLimitMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteIngestionKeyLimitMutationOptions(options));
};
/**
* This endpoint updates an ingestion key limit
@@ -588,13 +586,15 @@ export const useDeleteIngestionKeyLimit = <
*/
export const updateIngestionKeyLimit = (
{ limitId }: UpdateIngestionKeyLimitPathParameters,
gatewaytypesUpdatableIngestionKeyLimitDTO: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>,
gatewaytypesUpdatableIngestionKeyLimitDTO?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/gateway/ingestion_keys/limits/${limitId}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: gatewaytypesUpdatableIngestionKeyLimitDTO,
signal,
});
};
@@ -607,7 +607,7 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
},
TContext
>;
@@ -616,7 +616,7 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
},
TContext
> => {
@@ -633,7 +633,7 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
Awaited<ReturnType<typeof updateIngestionKeyLimit>>,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -648,7 +648,8 @@ export type UpdateIngestionKeyLimitMutationResult = NonNullable<
Awaited<ReturnType<typeof updateIngestionKeyLimit>>
>;
export type UpdateIngestionKeyLimitMutationBody =
BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
| BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>
| undefined;
export type UpdateIngestionKeyLimitMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -664,7 +665,7 @@ export const useUpdateIngestionKeyLimit = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
},
TContext
>;
@@ -673,13 +674,11 @@ export const useUpdateIngestionKeyLimit = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
},
TContext
> => {
const mutationOptions = getUpdateIngestionKeyLimitMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateIngestionKeyLimitMutationOptions(options));
};
/**
* This endpoint returns the ingestion keys for a workspace
@@ -763,9 +762,7 @@ export function useSearchIngestionKeys<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useQuery } from 'react-query';
import type {
@@ -88,9 +89,7 @@ export function useGetGlobalConfig<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useQuery } from 'react-query';
import type {
@@ -83,9 +84,7 @@ export function useHealthz<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -158,9 +157,7 @@ export function useLivez<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -230,9 +227,7 @@ export function useReadyz<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation } from 'react-query';
import type {
@@ -13,12 +14,14 @@ import type {
import type {
InframonitoringtypesPostableClustersDTO,
InframonitoringtypesPostableDeploymentsDTO,
InframonitoringtypesPostableHostsDTO,
InframonitoringtypesPostableNamespacesDTO,
InframonitoringtypesPostableNodesDTO,
InframonitoringtypesPostablePodsDTO,
InframonitoringtypesPostableVolumesDTO,
ListClusters200,
ListDeployments200,
ListHosts200,
ListNamespaces200,
ListNodes200,
@@ -35,7 +38,7 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
* @summary List Clusters for Infra Monitoring
*/
export const listClusters = (
inframonitoringtypesPostableClustersDTO: BodyType<InframonitoringtypesPostableClustersDTO>,
inframonitoringtypesPostableClustersDTO?: BodyType<InframonitoringtypesPostableClustersDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListClusters200>({
@@ -54,13 +57,13 @@ export const getListClustersMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listClusters>>,
TError,
{ data: BodyType<InframonitoringtypesPostableClustersDTO> },
{ data?: BodyType<InframonitoringtypesPostableClustersDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listClusters>>,
TError,
{ data: BodyType<InframonitoringtypesPostableClustersDTO> },
{ data?: BodyType<InframonitoringtypesPostableClustersDTO> },
TContext
> => {
const mutationKey = ['listClusters'];
@@ -74,7 +77,7 @@ export const getListClustersMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listClusters>>,
{ data: BodyType<InframonitoringtypesPostableClustersDTO> }
{ data?: BodyType<InframonitoringtypesPostableClustersDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -88,7 +91,8 @@ export type ListClustersMutationResult = NonNullable<
Awaited<ReturnType<typeof listClusters>>
>;
export type ListClustersMutationBody =
BodyType<InframonitoringtypesPostableClustersDTO>;
| BodyType<InframonitoringtypesPostableClustersDTO>
| undefined;
export type ListClustersMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -101,25 +105,106 @@ export const useListClusters = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listClusters>>,
TError,
{ data: BodyType<InframonitoringtypesPostableClustersDTO> },
{ data?: BodyType<InframonitoringtypesPostableClustersDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listClusters>>,
TError,
{ data: BodyType<InframonitoringtypesPostableClustersDTO> },
{ data?: BodyType<InframonitoringtypesPostableClustersDTO> },
TContext
> => {
const mutationOptions = getListClustersMutationOptions(options);
return useMutation(getListClustersMutationOptions(options));
};
/**
* Returns a paginated list of Kubernetes Deployments with key aggregated pod metrics: CPU usage and memory working set summed across pods owned by the deployment, plus average CPU/memory request and limit utilization (deploymentCPURequest, deploymentCPULimit, deploymentMemoryRequest, deploymentMemoryLimit). Each row also reports the latest known desiredPods (k8s.deployment.desired) and availablePods (k8s.deployment.available) replica counts and per-group podCountsByPhase ({ pending, running, succeeded, failed, unknown } from each pod's latest k8s.pod.phase value). Each deployment includes metadata attributes (k8s.deployment.name, k8s.namespace.name, k8s.cluster.name). The response type is 'list' for the default k8s.deployment.name grouping or 'grouped_list' for custom groupBy keys; in both modes every row aggregates pods owned by deployments in the group. Supports filtering via a filter expression, custom groupBy, ordering by cpu / cpu_request / cpu_limit / memory / memory_request / memory_limit / desired_pods / available_pods, and pagination via offset/limit. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (deploymentCPU, deploymentCPURequest, deploymentCPULimit, deploymentMemory, deploymentMemoryRequest, deploymentMemoryLimit, desiredPods, availablePods) return -1 as a sentinel when no data is available for that field.
* @summary List Deployments for Infra Monitoring
*/
export const listDeployments = (
inframonitoringtypesPostableDeploymentsDTO?: BodyType<InframonitoringtypesPostableDeploymentsDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListDeployments200>({
url: `/api/v2/infra_monitoring/deployments`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: inframonitoringtypesPostableDeploymentsDTO,
signal,
});
};
return useMutation(mutationOptions);
export const getListDeploymentsMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listDeployments>>,
TError,
{ data?: BodyType<InframonitoringtypesPostableDeploymentsDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listDeployments>>,
TError,
{ data?: BodyType<InframonitoringtypesPostableDeploymentsDTO> },
TContext
> => {
const mutationKey = ['listDeployments'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listDeployments>>,
{ data?: BodyType<InframonitoringtypesPostableDeploymentsDTO> }
> = (props) => {
const { data } = props ?? {};
return listDeployments(data);
};
return { mutationFn, ...mutationOptions };
};
export type ListDeploymentsMutationResult = NonNullable<
Awaited<ReturnType<typeof listDeployments>>
>;
export type ListDeploymentsMutationBody =
| BodyType<InframonitoringtypesPostableDeploymentsDTO>
| undefined;
export type ListDeploymentsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary List Deployments for Infra Monitoring
*/
export const useListDeployments = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown,
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listDeployments>>,
TError,
{ data?: BodyType<InframonitoringtypesPostableDeploymentsDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listDeployments>>,
TError,
{ data?: BodyType<InframonitoringtypesPostableDeploymentsDTO> },
TContext
> => {
return useMutation(getListDeploymentsMutationOptions(options));
};
/**
* Returns a paginated list of hosts with key infrastructure metrics: CPU usage (%), memory usage (%), I/O wait (%), disk usage (%), and 15-minute load average. Each host includes its current status (active/inactive based on metrics reported in the last 10 minutes) and metadata attributes (e.g., os.type). Supports filtering via a filter expression, filtering by host status, custom groupBy to aggregate hosts by any attribute, ordering by any of the five metrics, and pagination via offset/limit. The response type is 'list' for the default host.name grouping or 'grouped_list' for custom groupBy keys. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (cpu, memory, wait, load15, diskUsage) return -1 as a sentinel when no data is available for that field.
* @summary List Hosts for Infra Monitoring
*/
export const listHosts = (
inframonitoringtypesPostableHostsDTO: BodyType<InframonitoringtypesPostableHostsDTO>,
inframonitoringtypesPostableHostsDTO?: BodyType<InframonitoringtypesPostableHostsDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListHosts200>({
@@ -138,13 +223,13 @@ export const getListHostsMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listHosts>>,
TError,
{ data: BodyType<InframonitoringtypesPostableHostsDTO> },
{ data?: BodyType<InframonitoringtypesPostableHostsDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listHosts>>,
TError,
{ data: BodyType<InframonitoringtypesPostableHostsDTO> },
{ data?: BodyType<InframonitoringtypesPostableHostsDTO> },
TContext
> => {
const mutationKey = ['listHosts'];
@@ -158,7 +243,7 @@ export const getListHostsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listHosts>>,
{ data: BodyType<InframonitoringtypesPostableHostsDTO> }
{ data?: BodyType<InframonitoringtypesPostableHostsDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -172,7 +257,8 @@ export type ListHostsMutationResult = NonNullable<
Awaited<ReturnType<typeof listHosts>>
>;
export type ListHostsMutationBody =
BodyType<InframonitoringtypesPostableHostsDTO>;
| BodyType<InframonitoringtypesPostableHostsDTO>
| undefined;
export type ListHostsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -185,25 +271,23 @@ export const useListHosts = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listHosts>>,
TError,
{ data: BodyType<InframonitoringtypesPostableHostsDTO> },
{ data?: BodyType<InframonitoringtypesPostableHostsDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listHosts>>,
TError,
{ data: BodyType<InframonitoringtypesPostableHostsDTO> },
{ data?: BodyType<InframonitoringtypesPostableHostsDTO> },
TContext
> => {
const mutationOptions = getListHostsMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getListHostsMutationOptions(options));
};
/**
* Returns a paginated list of Kubernetes namespaces with key aggregated pod metrics: CPU usage and memory working set (summed across pods in the group), plus per-group podCountsByPhase ({ pending, running, succeeded, failed, unknown } from each pod's latest k8s.pod.phase value in the window). Each namespace includes metadata attributes (k8s.namespace.name, k8s.cluster.name). The response type is 'list' for the default k8s.namespace.name grouping or 'grouped_list' for custom groupBy keys; in both modes every row aggregates pods in the group. Supports filtering via a filter expression, custom groupBy, ordering by cpu / memory, and pagination via offset/limit. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (namespaceCPU, namespaceMemory) return -1 as a sentinel when no data is available for that field.
* @summary List Namespaces for Infra Monitoring
*/
export const listNamespaces = (
inframonitoringtypesPostableNamespacesDTO: BodyType<InframonitoringtypesPostableNamespacesDTO>,
inframonitoringtypesPostableNamespacesDTO?: BodyType<InframonitoringtypesPostableNamespacesDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListNamespaces200>({
@@ -222,13 +306,13 @@ export const getListNamespacesMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listNamespaces>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNamespacesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNamespacesDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listNamespaces>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNamespacesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNamespacesDTO> },
TContext
> => {
const mutationKey = ['listNamespaces'];
@@ -242,7 +326,7 @@ export const getListNamespacesMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listNamespaces>>,
{ data: BodyType<InframonitoringtypesPostableNamespacesDTO> }
{ data?: BodyType<InframonitoringtypesPostableNamespacesDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -256,7 +340,8 @@ export type ListNamespacesMutationResult = NonNullable<
Awaited<ReturnType<typeof listNamespaces>>
>;
export type ListNamespacesMutationBody =
BodyType<InframonitoringtypesPostableNamespacesDTO>;
| BodyType<InframonitoringtypesPostableNamespacesDTO>
| undefined;
export type ListNamespacesMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -269,25 +354,23 @@ export const useListNamespaces = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listNamespaces>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNamespacesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNamespacesDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listNamespaces>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNamespacesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNamespacesDTO> },
TContext
> => {
const mutationOptions = getListNamespacesMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getListNamespacesMutationOptions(options));
};
/**
* Returns a paginated list of Kubernetes nodes with key metrics: CPU usage, CPU allocatable, memory working set, memory allocatable, per-group nodeCountsByReadiness ({ ready, notReady } from each node's latest k8s.node.condition_ready in the window) and per-group podCountsByPhase ({ pending, running, succeeded, failed, unknown } for pods scheduled on the listed nodes). Each node includes metadata attributes (k8s.node.uid, k8s.cluster.name). The response type is 'list' for the default k8s.node.name grouping (each row is one node with its current condition string: ready / not_ready / no_data) or 'grouped_list' for custom groupBy keys (each row aggregates nodes in the group; condition stays no_data). Supports filtering via a filter expression, custom groupBy, ordering by cpu / cpu_allocatable / memory / memory_allocatable, and pagination via offset/limit. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (nodeCPU, nodeCPUAllocatable, nodeMemory, nodeMemoryAllocatable) return -1 as a sentinel when no data is available for that field.
* @summary List Nodes for Infra Monitoring
*/
export const listNodes = (
inframonitoringtypesPostableNodesDTO: BodyType<InframonitoringtypesPostableNodesDTO>,
inframonitoringtypesPostableNodesDTO?: BodyType<InframonitoringtypesPostableNodesDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListNodes200>({
@@ -306,13 +389,13 @@ export const getListNodesMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listNodes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNodesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNodesDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listNodes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNodesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNodesDTO> },
TContext
> => {
const mutationKey = ['listNodes'];
@@ -326,7 +409,7 @@ export const getListNodesMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listNodes>>,
{ data: BodyType<InframonitoringtypesPostableNodesDTO> }
{ data?: BodyType<InframonitoringtypesPostableNodesDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -340,7 +423,8 @@ export type ListNodesMutationResult = NonNullable<
Awaited<ReturnType<typeof listNodes>>
>;
export type ListNodesMutationBody =
BodyType<InframonitoringtypesPostableNodesDTO>;
| BodyType<InframonitoringtypesPostableNodesDTO>
| undefined;
export type ListNodesMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -353,25 +437,23 @@ export const useListNodes = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listNodes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNodesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNodesDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listNodes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableNodesDTO> },
{ data?: BodyType<InframonitoringtypesPostableNodesDTO> },
TContext
> => {
const mutationOptions = getListNodesMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getListNodesMutationOptions(options));
};
/**
* Returns a paginated list of Kubernetes pods with key metrics: CPU usage, CPU request/limit utilization, memory working set, memory request/limit utilization, current pod phase (pending/running/succeeded/failed/unknown/no_data), and pod age (ms since start time). Each pod includes metadata attributes (namespace, node, workload owner such as deployment/statefulset/daemonset/job/cronjob, cluster). Supports filtering via a filter expression, custom groupBy to aggregate pods by any attribute, ordering by any of the six metrics (cpu, cpu_request, cpu_limit, memory, memory_request, memory_limit), and pagination via offset/limit. The response type is 'list' for the default k8s.pod.uid grouping (each row is one pod with its current phase) or 'grouped_list' for custom groupBy keys (each row aggregates pods in the group with per-phase counts under podCountsByPhase: { pending, running, succeeded, failed, unknown } derived from each pod's latest phase in the window). Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (podCPU, podCPURequest, podCPULimit, podMemory, podMemoryRequest, podMemoryLimit, podAge) return -1 as a sentinel when no data is available for that field.
* @summary List Pods for Infra Monitoring
*/
export const listPods = (
inframonitoringtypesPostablePodsDTO: BodyType<InframonitoringtypesPostablePodsDTO>,
inframonitoringtypesPostablePodsDTO?: BodyType<InframonitoringtypesPostablePodsDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListPods200>({
@@ -390,13 +472,13 @@ export const getListPodsMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listPods>>,
TError,
{ data: BodyType<InframonitoringtypesPostablePodsDTO> },
{ data?: BodyType<InframonitoringtypesPostablePodsDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listPods>>,
TError,
{ data: BodyType<InframonitoringtypesPostablePodsDTO> },
{ data?: BodyType<InframonitoringtypesPostablePodsDTO> },
TContext
> => {
const mutationKey = ['listPods'];
@@ -410,7 +492,7 @@ export const getListPodsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listPods>>,
{ data: BodyType<InframonitoringtypesPostablePodsDTO> }
{ data?: BodyType<InframonitoringtypesPostablePodsDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -424,7 +506,8 @@ export type ListPodsMutationResult = NonNullable<
Awaited<ReturnType<typeof listPods>>
>;
export type ListPodsMutationBody =
BodyType<InframonitoringtypesPostablePodsDTO>;
| BodyType<InframonitoringtypesPostablePodsDTO>
| undefined;
export type ListPodsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -437,25 +520,23 @@ export const useListPods = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listPods>>,
TError,
{ data: BodyType<InframonitoringtypesPostablePodsDTO> },
{ data?: BodyType<InframonitoringtypesPostablePodsDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listPods>>,
TError,
{ data: BodyType<InframonitoringtypesPostablePodsDTO> },
{ data?: BodyType<InframonitoringtypesPostablePodsDTO> },
TContext
> => {
const mutationOptions = getListPodsMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getListPodsMutationOptions(options));
};
/**
* Returns a paginated list of Kubernetes persistent volume claims (PVCs) with key volume metrics: available bytes, capacity bytes, usage (capacity - available), inodes, free inodes, and used inodes. Each row also includes metadata attributes (k8s.persistentvolumeclaim.name, k8s.pod.uid, k8s.pod.name, k8s.namespace.name, k8s.node.name, k8s.statefulset.name, k8s.cluster.name). Supports filtering via a filter expression, custom groupBy to aggregate volumes by any attribute, ordering by any of the six metrics (available, capacity, usage, inodes, inodes_free, inodes_used), and pagination via offset/limit. The response type is 'list' for the default k8s.persistentvolumeclaim.name grouping or 'grouped_list' for custom groupBy keys; in both modes every row aggregates volumes in the group. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (volumeAvailable, volumeCapacity, volumeUsage, volumeInodes, volumeInodesFree, volumeInodesUsed) return -1 as a sentinel when no data is available for that field.
* @summary List Volumes for Infra Monitoring
*/
export const listVolumes = (
inframonitoringtypesPostableVolumesDTO: BodyType<InframonitoringtypesPostableVolumesDTO>,
inframonitoringtypesPostableVolumesDTO?: BodyType<InframonitoringtypesPostableVolumesDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListVolumes200>({
@@ -474,13 +555,13 @@ export const getListVolumesMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listVolumes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableVolumesDTO> },
{ data?: BodyType<InframonitoringtypesPostableVolumesDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof listVolumes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableVolumesDTO> },
{ data?: BodyType<InframonitoringtypesPostableVolumesDTO> },
TContext
> => {
const mutationKey = ['listVolumes'];
@@ -494,7 +575,7 @@ export const getListVolumesMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof listVolumes>>,
{ data: BodyType<InframonitoringtypesPostableVolumesDTO> }
{ data?: BodyType<InframonitoringtypesPostableVolumesDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -508,7 +589,8 @@ export type ListVolumesMutationResult = NonNullable<
Awaited<ReturnType<typeof listVolumes>>
>;
export type ListVolumesMutationBody =
BodyType<InframonitoringtypesPostableVolumesDTO>;
| BodyType<InframonitoringtypesPostableVolumesDTO>
| undefined;
export type ListVolumesMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -521,16 +603,14 @@ export const useListVolumes = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof listVolumes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableVolumesDTO> },
{ data?: BodyType<InframonitoringtypesPostableVolumesDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof listVolumes>>,
TError,
{ data: BodyType<InframonitoringtypesPostableVolumesDTO> },
{ data?: BodyType<InframonitoringtypesPostableVolumesDTO> },
TContext
> => {
const mutationOptions = getListVolumesMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getListVolumesMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -109,9 +110,7 @@ export function useListLLMPricingRules<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -135,13 +134,15 @@ export const invalidateListLLMPricingRules = async (
* @summary Create or update pricing rules
*/
export const createOrUpdateLLMPricingRules = (
llmpricingruletypesUpdatableLLMPricingRulesDTO: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO>,
llmpricingruletypesUpdatableLLMPricingRulesDTO?: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/llm_pricing_rules`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: llmpricingruletypesUpdatableLLMPricingRulesDTO,
signal,
});
};
@@ -152,13 +153,13 @@ export const getCreateOrUpdateLLMPricingRulesMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
TError,
{ data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
{ data?: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
TError,
{ data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
{ data?: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
TContext
> => {
const mutationKey = ['createOrUpdateLLMPricingRules'];
@@ -172,7 +173,7 @@ export const getCreateOrUpdateLLMPricingRulesMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
{ data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> }
{ data?: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -186,7 +187,8 @@ export type CreateOrUpdateLLMPricingRulesMutationResult = NonNullable<
Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>
>;
export type CreateOrUpdateLLMPricingRulesMutationBody =
BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO>;
| BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO>
| undefined;
export type CreateOrUpdateLLMPricingRulesMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -200,30 +202,29 @@ export const useCreateOrUpdateLLMPricingRules = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
TError,
{ data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
{ data?: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createOrUpdateLLMPricingRules>>,
TError,
{ data: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
{ data?: BodyType<LlmpricingruletypesUpdatableLLMPricingRulesDTO> },
TContext
> => {
const mutationOptions =
getCreateOrUpdateLLMPricingRulesMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateOrUpdateLLMPricingRulesMutationOptions(options));
};
/**
* Hard-deletes a pricing rule. If auto-synced, it will be recreated on the next sync cycle.
* @summary Delete a pricing rule
*/
export const deleteLLMPricingRule = ({
id,
}: DeleteLLMPricingRulePathParameters) => {
export const deleteLLMPricingRule = (
{ id }: DeleteLLMPricingRulePathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/llm_pricing_rules/${id}`,
method: 'DELETE',
signal,
});
};
@@ -290,9 +291,7 @@ export const useDeleteLLMPricingRule = <
{ pathParams: DeleteLLMPricingRulePathParameters },
TContext
> => {
const mutationOptions = getDeleteLLMPricingRuleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteLLMPricingRuleMutationOptions(options));
};
/**
* Returns a single LLM pricing rule by ID.
@@ -377,9 +376,7 @@ export function useGetLLMPricingRule<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -33,7 +34,7 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
* @summary Export raw data
*/
export const handleExportRawDataPOST = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
querybuildertypesv5QueryRangeRequestDTO?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
params?: HandleExportRawDataPOSTParams,
signal?: AbortSignal,
) => {
@@ -55,7 +56,7 @@ export const getHandleExportRawDataPOSTMutationOptions = <
Awaited<ReturnType<typeof handleExportRawDataPOST>>,
TError,
{
data: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: HandleExportRawDataPOSTParams;
},
TContext
@@ -64,7 +65,7 @@ export const getHandleExportRawDataPOSTMutationOptions = <
Awaited<ReturnType<typeof handleExportRawDataPOST>>,
TError,
{
data: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: HandleExportRawDataPOSTParams;
},
TContext
@@ -81,7 +82,7 @@ export const getHandleExportRawDataPOSTMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof handleExportRawDataPOST>>,
{
data: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: HandleExportRawDataPOSTParams;
}
> = (props) => {
@@ -97,7 +98,8 @@ export type HandleExportRawDataPOSTMutationResult = NonNullable<
Awaited<ReturnType<typeof handleExportRawDataPOST>>
>;
export type HandleExportRawDataPOSTMutationBody =
BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
| BodyType<Querybuildertypesv5QueryRangeRequestDTO>
| undefined;
export type HandleExportRawDataPOSTMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -112,7 +114,7 @@ export const useHandleExportRawDataPOST = <
Awaited<ReturnType<typeof handleExportRawDataPOST>>,
TError,
{
data: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: HandleExportRawDataPOSTParams;
},
TContext
@@ -121,14 +123,12 @@ export const useHandleExportRawDataPOST = <
Awaited<ReturnType<typeof handleExportRawDataPOST>>,
TError,
{
data: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
params?: HandleExportRawDataPOSTParams;
},
TContext
> => {
const mutationOptions = getHandleExportRawDataPOSTMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getHandleExportRawDataPOSTMutationOptions(options));
};
/**
* This endpoints promotes and indexes paths
@@ -198,9 +198,7 @@ export function useListPromotedAndIndexedPaths<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -223,7 +221,7 @@ export const invalidateListPromotedAndIndexedPaths = async (
* @summary Promote and index paths
*/
export const handlePromoteAndIndexPaths = (
promotetypesPromotePathDTONull: BodyType<
promotetypesPromotePathDTONull?: BodyType<
PromotetypesPromotePathDTO[] | null
> | null,
signal?: AbortSignal,
@@ -244,13 +242,13 @@ export const getHandlePromoteAndIndexPathsMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data?: BodyType<PromotetypesPromotePathDTO[] | null> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data?: BodyType<PromotetypesPromotePathDTO[] | null> },
TContext
> => {
const mutationKey = ['handlePromoteAndIndexPaths'];
@@ -264,7 +262,7 @@ export const getHandlePromoteAndIndexPathsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> }
{ data?: BodyType<PromotetypesPromotePathDTO[] | null> }
> = (props) => {
const { data } = props ?? {};
@@ -277,9 +275,9 @@ export const getHandlePromoteAndIndexPathsMutationOptions = <
export type HandlePromoteAndIndexPathsMutationResult = NonNullable<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>
>;
export type HandlePromoteAndIndexPathsMutationBody = BodyType<
PromotetypesPromotePathDTO[] | null
>;
export type HandlePromoteAndIndexPathsMutationBody =
| BodyType<PromotetypesPromotePathDTO[] | null>
| undefined;
export type HandlePromoteAndIndexPathsMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -293,16 +291,14 @@ export const useHandlePromoteAndIndexPaths = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data?: BodyType<PromotetypesPromotePathDTO[] | null> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data?: BodyType<PromotetypesPromotePathDTO[] | null> },
TContext
> => {
const mutationOptions = getHandlePromoteAndIndexPathsMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getHandlePromoteAndIndexPathsMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -122,9 +123,7 @@ export function useListMetrics<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -226,9 +225,7 @@ export function useGetMetricAlerts<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -343,9 +340,7 @@ export function useGetMetricAttributes<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -451,9 +446,7 @@ export function useGetMetricDashboards<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -558,9 +551,7 @@ export function useGetMetricHighlights<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -662,9 +653,7 @@ export function useGetMetricMetadata<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -689,7 +678,7 @@ export const invalidateGetMetricMetadata = async (
*/
export const updateMetricMetadata = (
{ metricName }: UpdateMetricMetadataPathParameters,
metricsexplorertypesUpdateMetricMetadataRequestDTO: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>,
metricsexplorertypesUpdateMetricMetadataRequestDTO?: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
@@ -710,7 +699,7 @@ export const getUpdateMetricMetadataMutationOptions = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data?: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
},
TContext
>;
@@ -719,7 +708,7 @@ export const getUpdateMetricMetadataMutationOptions = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data?: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
},
TContext
> => {
@@ -736,7 +725,7 @@ export const getUpdateMetricMetadataMutationOptions = <
Awaited<ReturnType<typeof updateMetricMetadata>>,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data?: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -751,7 +740,8 @@ export type UpdateMetricMetadataMutationResult = NonNullable<
Awaited<ReturnType<typeof updateMetricMetadata>>
>;
export type UpdateMetricMetadataMutationBody =
BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
| BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>
| undefined;
export type UpdateMetricMetadataMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -767,7 +757,7 @@ export const useUpdateMetricMetadata = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data?: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
},
TContext
>;
@@ -776,20 +766,18 @@ export const useUpdateMetricMetadata = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data?: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
},
TContext
> => {
const mutationOptions = getUpdateMetricMetadataMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateMetricMetadataMutationOptions(options));
};
/**
* Returns raw time series data points for a metric within a time range (max 30 minutes). Each series includes labels and timestamp/value pairs.
* @summary Inspect raw metric data points
*/
export const inspectMetrics = (
metricsexplorertypesInspectMetricsRequestDTO: BodyType<MetricsexplorertypesInspectMetricsRequestDTO>,
metricsexplorertypesInspectMetricsRequestDTO?: BodyType<MetricsexplorertypesInspectMetricsRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectMetrics200>({
@@ -808,13 +796,13 @@ export const getInspectMetricsMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof inspectMetrics>>,
TError,
{ data: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof inspectMetrics>>,
TError,
{ data: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
TContext
> => {
const mutationKey = ['inspectMetrics'];
@@ -828,7 +816,7 @@ export const getInspectMetricsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof inspectMetrics>>,
{ data: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> }
{ data?: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -842,7 +830,8 @@ export type InspectMetricsMutationResult = NonNullable<
Awaited<ReturnType<typeof inspectMetrics>>
>;
export type InspectMetricsMutationBody =
BodyType<MetricsexplorertypesInspectMetricsRequestDTO>;
| BodyType<MetricsexplorertypesInspectMetricsRequestDTO>
| undefined;
export type InspectMetricsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -855,18 +844,16 @@ export const useInspectMetrics = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof inspectMetrics>>,
TError,
{ data: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof inspectMetrics>>,
TError,
{ data: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesInspectMetricsRequestDTO> },
TContext
> => {
const mutationOptions = getInspectMetricsMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getInspectMetricsMutationOptions(options));
};
/**
* Lightweight endpoint that checks if any non-SigNoz metrics have been ingested, used for onboarding status detection
@@ -936,9 +923,7 @@ export function useGetMetricsOnboardingStatus<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -961,7 +946,7 @@ export const invalidateGetMetricsOnboardingStatus = async (
* @summary Get metrics statistics
*/
export const getMetricsStats = (
metricsexplorertypesStatsRequestDTO: BodyType<MetricsexplorertypesStatsRequestDTO>,
metricsexplorertypesStatsRequestDTO?: BodyType<MetricsexplorertypesStatsRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetMetricsStats200>({
@@ -980,13 +965,13 @@ export const getGetMetricsStatsMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesStatsRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesStatsRequestDTO> },
TContext
> => {
const mutationKey = ['getMetricsStats'];
@@ -1000,7 +985,7 @@ export const getGetMetricsStatsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof getMetricsStats>>,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> }
{ data?: BodyType<MetricsexplorertypesStatsRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -1014,7 +999,8 @@ export type GetMetricsStatsMutationResult = NonNullable<
Awaited<ReturnType<typeof getMetricsStats>>
>;
export type GetMetricsStatsMutationBody =
BodyType<MetricsexplorertypesStatsRequestDTO>;
| BodyType<MetricsexplorertypesStatsRequestDTO>
| undefined;
export type GetMetricsStatsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -1027,25 +1013,23 @@ export const useGetMetricsStats = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesStatsRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data?: BodyType<MetricsexplorertypesStatsRequestDTO> },
TContext
> => {
const mutationOptions = getGetMetricsStatsMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getGetMetricsStatsMutationOptions(options));
};
/**
* This endpoint returns a treemap visualization showing the proportional distribution of metrics by sample count or time series count
* @summary Get metrics treemap
*/
export const getMetricsTreemap = (
metricsexplorertypesTreemapRequestDTO: BodyType<MetricsexplorertypesTreemapRequestDTO>,
metricsexplorertypesTreemapRequestDTO?: BodyType<MetricsexplorertypesTreemapRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetMetricsTreemap200>({
@@ -1064,13 +1048,13 @@ export const getGetMetricsTreemapMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data?: BodyType<MetricsexplorertypesTreemapRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data?: BodyType<MetricsexplorertypesTreemapRequestDTO> },
TContext
> => {
const mutationKey = ['getMetricsTreemap'];
@@ -1084,7 +1068,7 @@ export const getGetMetricsTreemapMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof getMetricsTreemap>>,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> }
{ data?: BodyType<MetricsexplorertypesTreemapRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -1098,7 +1082,8 @@ export type GetMetricsTreemapMutationResult = NonNullable<
Awaited<ReturnType<typeof getMetricsTreemap>>
>;
export type GetMetricsTreemapMutationBody =
BodyType<MetricsexplorertypesTreemapRequestDTO>;
| BodyType<MetricsexplorertypesTreemapRequestDTO>
| undefined;
export type GetMetricsTreemapMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -1111,16 +1096,14 @@ export const useGetMetricsTreemap = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data?: BodyType<MetricsexplorertypesTreemapRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data?: BodyType<MetricsexplorertypesTreemapRequestDTO> },
TContext
> => {
const mutationOptions = getGetMetricsTreemapMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getGetMetricsTreemapMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -92,9 +93,7 @@ export function useGetMyOrganization<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -117,13 +116,15 @@ export const invalidateGetMyOrganization = async (
* @summary Update my organization
*/
export const updateMyOrganization = (
typesOrganizationDTO: BodyType<TypesOrganizationDTO>,
typesOrganizationDTO?: BodyType<TypesOrganizationDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/orgs/me`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: typesOrganizationDTO,
signal,
});
};
@@ -134,13 +135,13 @@ export const getUpdateMyOrganizationMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data?: BodyType<TypesOrganizationDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data?: BodyType<TypesOrganizationDTO> },
TContext
> => {
const mutationKey = ['updateMyOrganization'];
@@ -154,7 +155,7 @@ export const getUpdateMyOrganizationMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateMyOrganization>>,
{ data: BodyType<TypesOrganizationDTO> }
{ data?: BodyType<TypesOrganizationDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -167,7 +168,9 @@ export const getUpdateMyOrganizationMutationOptions = <
export type UpdateMyOrganizationMutationResult = NonNullable<
Awaited<ReturnType<typeof updateMyOrganization>>
>;
export type UpdateMyOrganizationMutationBody = BodyType<TypesOrganizationDTO>;
export type UpdateMyOrganizationMutationBody =
| BodyType<TypesOrganizationDTO>
| undefined;
export type UpdateMyOrganizationMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -181,16 +184,14 @@ export const useUpdateMyOrganization = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data?: BodyType<TypesOrganizationDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data?: BodyType<TypesOrganizationDTO> },
TContext
> => {
const mutationOptions = getUpdateMyOrganizationMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateMyOrganizationMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -99,9 +100,7 @@ export function useListOrgPreferences<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -202,9 +201,7 @@ export function useGetOrgPreference<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -229,13 +226,15 @@ export const invalidateGetOrgPreference = async (
*/
export const updateOrgPreference = (
{ name }: UpdateOrgPreferencePathParameters,
preferencetypesUpdatablePreferenceDTO: BodyType<PreferencetypesUpdatablePreferenceDTO>,
preferencetypesUpdatablePreferenceDTO?: BodyType<PreferencetypesUpdatablePreferenceDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/org/preferences/${name}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: preferencetypesUpdatablePreferenceDTO,
signal,
});
};
@@ -248,7 +247,7 @@ export const getUpdateOrgPreferenceMutationOptions = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
>;
@@ -257,7 +256,7 @@ export const getUpdateOrgPreferenceMutationOptions = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
> => {
@@ -274,7 +273,7 @@ export const getUpdateOrgPreferenceMutationOptions = <
Awaited<ReturnType<typeof updateOrgPreference>>,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -289,7 +288,8 @@ export type UpdateOrgPreferenceMutationResult = NonNullable<
Awaited<ReturnType<typeof updateOrgPreference>>
>;
export type UpdateOrgPreferenceMutationBody =
BodyType<PreferencetypesUpdatablePreferenceDTO>;
| BodyType<PreferencetypesUpdatablePreferenceDTO>
| undefined;
export type UpdateOrgPreferenceMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -305,7 +305,7 @@ export const useUpdateOrgPreference = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
>;
@@ -314,13 +314,11 @@ export const useUpdateOrgPreference = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
> => {
const mutationOptions = getUpdateOrgPreferenceMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateOrgPreferenceMutationOptions(options));
};
/**
* This endpoint lists all user preferences
@@ -388,9 +386,7 @@ export function useListUserPreferences<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -491,9 +487,7 @@ export function useGetUserPreference<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -518,13 +512,15 @@ export const invalidateGetUserPreference = async (
*/
export const updateUserPreference = (
{ name }: UpdateUserPreferencePathParameters,
preferencetypesUpdatablePreferenceDTO: BodyType<PreferencetypesUpdatablePreferenceDTO>,
preferencetypesUpdatablePreferenceDTO?: BodyType<PreferencetypesUpdatablePreferenceDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/user/preferences/${name}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: preferencetypesUpdatablePreferenceDTO,
signal,
});
};
@@ -537,7 +533,7 @@ export const getUpdateUserPreferenceMutationOptions = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
>;
@@ -546,7 +542,7 @@ export const getUpdateUserPreferenceMutationOptions = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
> => {
@@ -563,7 +559,7 @@ export const getUpdateUserPreferenceMutationOptions = <
Awaited<ReturnType<typeof updateUserPreference>>,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -578,7 +574,8 @@ export type UpdateUserPreferenceMutationResult = NonNullable<
Awaited<ReturnType<typeof updateUserPreference>>
>;
export type UpdateUserPreferenceMutationBody =
BodyType<PreferencetypesUpdatablePreferenceDTO>;
| BodyType<PreferencetypesUpdatablePreferenceDTO>
| undefined;
export type UpdateUserPreferenceMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -594,7 +591,7 @@ export const useUpdateUserPreference = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
>;
@@ -603,11 +600,9 @@ export const useUpdateUserPreference = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data?: BodyType<PreferencetypesUpdatablePreferenceDTO>;
},
TContext
> => {
const mutationOptions = getUpdateUserPreferenceMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateUserPreferenceMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation } from 'react-query';
import type {
@@ -26,7 +27,7 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
* @summary Query range
*/
export const queryRangeV5 = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
querybuildertypesv5QueryRangeRequestDTO?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<QueryRangeV5200>({
@@ -45,13 +46,13 @@ export const getQueryRangeV5MutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationKey = ['queryRangeV5'];
@@ -65,7 +66,7 @@ export const getQueryRangeV5MutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof queryRangeV5>>,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -79,7 +80,8 @@ export type QueryRangeV5MutationResult = NonNullable<
Awaited<ReturnType<typeof queryRangeV5>>
>;
export type QueryRangeV5MutationBody =
BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
| BodyType<Querybuildertypesv5QueryRangeRequestDTO>
| undefined;
export type QueryRangeV5MutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -92,25 +94,23 @@ export const useQueryRangeV5 = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationOptions = getQueryRangeV5MutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getQueryRangeV5MutationOptions(options));
};
/**
* Replace variables in a query
* @summary Replace variables
*/
export const replaceVariables = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
querybuildertypesv5QueryRangeRequestDTO?: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ReplaceVariables200>({
@@ -129,13 +129,13 @@ export const getReplaceVariablesMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationKey = ['replaceVariables'];
@@ -149,7 +149,7 @@ export const getReplaceVariablesMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof replaceVariables>>,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -163,7 +163,8 @@ export type ReplaceVariablesMutationResult = NonNullable<
Awaited<ReturnType<typeof replaceVariables>>
>;
export type ReplaceVariablesMutationBody =
BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
| BodyType<Querybuildertypesv5QueryRangeRequestDTO>
| undefined;
export type ReplaceVariablesMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -176,16 +177,14 @@ export const useReplaceVariables = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data?: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationOptions = getReplaceVariablesMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getReplaceVariablesMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -94,9 +95,7 @@ export function useListRoles<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -119,7 +118,7 @@ export const invalidateListRoles = async (
* @summary Create role
*/
export const createRole = (
authtypesPostableRoleDTO: BodyType<AuthtypesPostableRoleDTO>,
authtypesPostableRoleDTO?: BodyType<AuthtypesPostableRoleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateRole201>({
@@ -138,13 +137,13 @@ export const getCreateRoleMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<AuthtypesPostableRoleDTO> },
{ data?: BodyType<AuthtypesPostableRoleDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<AuthtypesPostableRoleDTO> },
{ data?: BodyType<AuthtypesPostableRoleDTO> },
TContext
> => {
const mutationKey = ['createRole'];
@@ -158,7 +157,7 @@ export const getCreateRoleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createRole>>,
{ data: BodyType<AuthtypesPostableRoleDTO> }
{ data?: BodyType<AuthtypesPostableRoleDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -171,7 +170,9 @@ export const getCreateRoleMutationOptions = <
export type CreateRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof createRole>>
>;
export type CreateRoleMutationBody = BodyType<AuthtypesPostableRoleDTO>;
export type CreateRoleMutationBody =
| BodyType<AuthtypesPostableRoleDTO>
| undefined;
export type CreateRoleMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -184,27 +185,29 @@ export const useCreateRole = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<AuthtypesPostableRoleDTO> },
{ data?: BodyType<AuthtypesPostableRoleDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<AuthtypesPostableRoleDTO> },
{ data?: BodyType<AuthtypesPostableRoleDTO> },
TContext
> => {
const mutationOptions = getCreateRoleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateRoleMutationOptions(options));
};
/**
* This endpoint deletes a role
* @summary Delete role
*/
export const deleteRole = ({ id }: DeleteRolePathParameters) => {
export const deleteRole = (
{ id }: DeleteRolePathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}`,
method: 'DELETE',
signal,
});
};
@@ -270,9 +273,7 @@ export const useDeleteRole = <
{ pathParams: DeleteRolePathParameters },
TContext
> => {
const mutationOptions = getDeleteRoleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteRoleMutationOptions(options));
};
/**
* This endpoint gets a role
@@ -344,9 +345,7 @@ export function useGetRole<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -371,13 +370,15 @@ export const invalidateGetRole = async (
*/
export const patchRole = (
{ id }: PatchRolePathParameters,
authtypesPatchableRoleDTO: BodyType<AuthtypesPatchableRoleDTO>,
authtypesPatchableRoleDTO?: BodyType<AuthtypesPatchableRoleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: authtypesPatchableRoleDTO,
signal,
});
};
@@ -390,7 +391,7 @@ export const getPatchRoleMutationOptions = <
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<AuthtypesPatchableRoleDTO>;
data?: BodyType<AuthtypesPatchableRoleDTO>;
},
TContext
>;
@@ -399,7 +400,7 @@ export const getPatchRoleMutationOptions = <
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<AuthtypesPatchableRoleDTO>;
data?: BodyType<AuthtypesPatchableRoleDTO>;
},
TContext
> => {
@@ -416,7 +417,7 @@ export const getPatchRoleMutationOptions = <
Awaited<ReturnType<typeof patchRole>>,
{
pathParams: PatchRolePathParameters;
data: BodyType<AuthtypesPatchableRoleDTO>;
data?: BodyType<AuthtypesPatchableRoleDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -430,7 +431,9 @@ export const getPatchRoleMutationOptions = <
export type PatchRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof patchRole>>
>;
export type PatchRoleMutationBody = BodyType<AuthtypesPatchableRoleDTO>;
export type PatchRoleMutationBody =
| BodyType<AuthtypesPatchableRoleDTO>
| undefined;
export type PatchRoleMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -445,7 +448,7 @@ export const usePatchRole = <
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<AuthtypesPatchableRoleDTO>;
data?: BodyType<AuthtypesPatchableRoleDTO>;
},
TContext
>;
@@ -454,13 +457,11 @@ export const usePatchRole = <
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<AuthtypesPatchableRoleDTO>;
data?: BodyType<AuthtypesPatchableRoleDTO>;
},
TContext
> => {
const mutationOptions = getPatchRoleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getPatchRoleMutationOptions(options));
};
/**
* Gets all objects connected to the specified role via a given relation type
@@ -544,9 +545,7 @@ export function useGetObjects<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -571,13 +570,15 @@ export const invalidateGetObjects = async (
*/
export const patchObjects = (
{ id, relation }: PatchObjectsPathParameters,
coretypesPatchableObjectsDTO: BodyType<CoretypesPatchableObjectsDTO>,
coretypesPatchableObjectsDTO?: BodyType<CoretypesPatchableObjectsDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}/relations/${relation}/objects`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: coretypesPatchableObjectsDTO,
signal,
});
};
@@ -590,7 +591,7 @@ export const getPatchObjectsMutationOptions = <
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<CoretypesPatchableObjectsDTO>;
data?: BodyType<CoretypesPatchableObjectsDTO>;
},
TContext
>;
@@ -599,7 +600,7 @@ export const getPatchObjectsMutationOptions = <
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<CoretypesPatchableObjectsDTO>;
data?: BodyType<CoretypesPatchableObjectsDTO>;
},
TContext
> => {
@@ -616,7 +617,7 @@ export const getPatchObjectsMutationOptions = <
Awaited<ReturnType<typeof patchObjects>>,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<CoretypesPatchableObjectsDTO>;
data?: BodyType<CoretypesPatchableObjectsDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -630,7 +631,9 @@ export const getPatchObjectsMutationOptions = <
export type PatchObjectsMutationResult = NonNullable<
Awaited<ReturnType<typeof patchObjects>>
>;
export type PatchObjectsMutationBody = BodyType<CoretypesPatchableObjectsDTO>;
export type PatchObjectsMutationBody =
| BodyType<CoretypesPatchableObjectsDTO>
| undefined;
export type PatchObjectsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -645,7 +648,7 @@ export const usePatchObjects = <
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<CoretypesPatchableObjectsDTO>;
data?: BodyType<CoretypesPatchableObjectsDTO>;
},
TContext
>;
@@ -654,11 +657,9 @@ export const usePatchObjects = <
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<CoretypesPatchableObjectsDTO>;
data?: BodyType<CoretypesPatchableObjectsDTO>;
},
TContext
> => {
const mutationOptions = getPatchObjectsMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getPatchObjectsMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -98,9 +99,7 @@ export function useGetAllRoutePolicies<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -123,7 +122,7 @@ export const invalidateGetAllRoutePolicies = async (
* @summary Create route policy
*/
export const createRoutePolicy = (
alertmanagertypesPostableRoutePolicyDTO: BodyType<AlertmanagertypesPostableRoutePolicyDTO>,
alertmanagertypesPostableRoutePolicyDTO?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateRoutePolicy201>({
@@ -142,13 +141,13 @@ export const getCreateRoutePolicyMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRoutePolicy>>,
TError,
{ data: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
{ data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createRoutePolicy>>,
TError,
{ data: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
{ data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
TContext
> => {
const mutationKey = ['createRoutePolicy'];
@@ -162,7 +161,7 @@ export const getCreateRoutePolicyMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createRoutePolicy>>,
{ data: BodyType<AlertmanagertypesPostableRoutePolicyDTO> }
{ data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -176,7 +175,8 @@ export type CreateRoutePolicyMutationResult = NonNullable<
Awaited<ReturnType<typeof createRoutePolicy>>
>;
export type CreateRoutePolicyMutationBody =
BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
| BodyType<AlertmanagertypesPostableRoutePolicyDTO>
| undefined;
export type CreateRoutePolicyMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -189,29 +189,29 @@ export const useCreateRoutePolicy = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRoutePolicy>>,
TError,
{ data: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
{ data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createRoutePolicy>>,
TError,
{ data: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
{ data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO> },
TContext
> => {
const mutationOptions = getCreateRoutePolicyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateRoutePolicyMutationOptions(options));
};
/**
* This endpoint deletes a route policy by ID
* @summary Delete route policy
*/
export const deleteRoutePolicyByID = ({
id,
}: DeleteRoutePolicyByIDPathParameters) => {
export const deleteRoutePolicyByID = (
{ id }: DeleteRoutePolicyByIDPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/route_policies/${id}`,
method: 'DELETE',
signal,
});
};
@@ -278,9 +278,7 @@ export const useDeleteRoutePolicyByID = <
{ pathParams: DeleteRoutePolicyByIDPathParameters },
TContext
> => {
const mutationOptions = getDeleteRoutePolicyByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteRoutePolicyByIDMutationOptions(options));
};
/**
* This endpoint returns a route policy by ID
@@ -365,9 +363,7 @@ export function useGetRoutePolicyByID<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -392,13 +388,15 @@ export const invalidateGetRoutePolicyByID = async (
*/
export const updateRoutePolicy = (
{ id }: UpdateRoutePolicyPathParameters,
alertmanagertypesPostableRoutePolicyDTO: BodyType<AlertmanagertypesPostableRoutePolicyDTO>,
alertmanagertypesPostableRoutePolicyDTO?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<UpdateRoutePolicy200>({
url: `/api/v1/route_policies/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: alertmanagertypesPostableRoutePolicyDTO,
signal,
});
};
@@ -411,7 +409,7 @@ export const getUpdateRoutePolicyMutationOptions = <
TError,
{
pathParams: UpdateRoutePolicyPathParameters;
data: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
},
TContext
>;
@@ -420,7 +418,7 @@ export const getUpdateRoutePolicyMutationOptions = <
TError,
{
pathParams: UpdateRoutePolicyPathParameters;
data: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
},
TContext
> => {
@@ -437,7 +435,7 @@ export const getUpdateRoutePolicyMutationOptions = <
Awaited<ReturnType<typeof updateRoutePolicy>>,
{
pathParams: UpdateRoutePolicyPathParameters;
data: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -452,7 +450,8 @@ export type UpdateRoutePolicyMutationResult = NonNullable<
Awaited<ReturnType<typeof updateRoutePolicy>>
>;
export type UpdateRoutePolicyMutationBody =
BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
| BodyType<AlertmanagertypesPostableRoutePolicyDTO>
| undefined;
export type UpdateRoutePolicyMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -467,7 +466,7 @@ export const useUpdateRoutePolicy = <
TError,
{
pathParams: UpdateRoutePolicyPathParameters;
data: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
},
TContext
>;
@@ -476,11 +475,9 @@ export const useUpdateRoutePolicy = <
TError,
{
pathParams: UpdateRoutePolicyPathParameters;
data: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
data?: BodyType<AlertmanagertypesPostableRoutePolicyDTO>;
},
TContext
> => {
const mutationOptions = getUpdateRoutePolicyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateRoutePolicyMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -110,9 +111,7 @@ export function useListRules<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -135,7 +134,7 @@ export const invalidateListRules = async (
* @summary Create alert rule
*/
export const createRule = (
ruletypesPostableRuleDTO: BodyType<RuletypesPostableRuleDTO>,
ruletypesPostableRuleDTO?: BodyType<RuletypesPostableRuleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateRule201>({
@@ -154,13 +153,13 @@ export const getCreateRuleMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
> => {
const mutationKey = ['createRule'];
@@ -174,7 +173,7 @@ export const getCreateRuleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createRule>>,
{ data: BodyType<RuletypesPostableRuleDTO> }
{ data?: BodyType<RuletypesPostableRuleDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -187,7 +186,9 @@ export const getCreateRuleMutationOptions = <
export type CreateRuleMutationResult = NonNullable<
Awaited<ReturnType<typeof createRule>>
>;
export type CreateRuleMutationBody = BodyType<RuletypesPostableRuleDTO>;
export type CreateRuleMutationBody =
| BodyType<RuletypesPostableRuleDTO>
| undefined;
export type CreateRuleMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -200,27 +201,29 @@ export const useCreateRule = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
> => {
const mutationOptions = getCreateRuleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateRuleMutationOptions(options));
};
/**
* This endpoint deletes an alert rule by ID
* @summary Delete alert rule
*/
export const deleteRuleByID = ({ id }: DeleteRuleByIDPathParameters) => {
export const deleteRuleByID = (
{ id }: DeleteRuleByIDPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/rules/${id}`,
method: 'DELETE',
signal,
});
};
@@ -286,9 +289,7 @@ export const useDeleteRuleByID = <
{ pathParams: DeleteRuleByIDPathParameters },
TContext
> => {
const mutationOptions = getDeleteRuleByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteRuleByIDMutationOptions(options));
};
/**
* This endpoint returns an alert rule by ID
@@ -370,9 +371,7 @@ export function useGetRuleByID<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -397,13 +396,15 @@ export const invalidateGetRuleByID = async (
*/
export const patchRuleByID = (
{ id }: PatchRuleByIDPathParameters,
ruletypesPostableRuleDTO: BodyType<RuletypesPostableRuleDTO>,
ruletypesPostableRuleDTO?: BodyType<RuletypesPostableRuleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<PatchRuleByID200>({
url: `/api/v2/rules/${id}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: ruletypesPostableRuleDTO,
signal,
});
};
@@ -416,7 +417,7 @@ export const getPatchRuleByIDMutationOptions = <
TError,
{
pathParams: PatchRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
>;
@@ -425,7 +426,7 @@ export const getPatchRuleByIDMutationOptions = <
TError,
{
pathParams: PatchRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
> => {
@@ -442,7 +443,7 @@ export const getPatchRuleByIDMutationOptions = <
Awaited<ReturnType<typeof patchRuleByID>>,
{
pathParams: PatchRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -456,7 +457,9 @@ export const getPatchRuleByIDMutationOptions = <
export type PatchRuleByIDMutationResult = NonNullable<
Awaited<ReturnType<typeof patchRuleByID>>
>;
export type PatchRuleByIDMutationBody = BodyType<RuletypesPostableRuleDTO>;
export type PatchRuleByIDMutationBody =
| BodyType<RuletypesPostableRuleDTO>
| undefined;
export type PatchRuleByIDMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -471,7 +474,7 @@ export const usePatchRuleByID = <
TError,
{
pathParams: PatchRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
>;
@@ -480,13 +483,11 @@ export const usePatchRuleByID = <
TError,
{
pathParams: PatchRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
> => {
const mutationOptions = getPatchRuleByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getPatchRuleByIDMutationOptions(options));
};
/**
* This endpoint updates an alert rule by ID
@@ -494,13 +495,15 @@ export const usePatchRuleByID = <
*/
export const updateRuleByID = (
{ id }: UpdateRuleByIDPathParameters,
ruletypesPostableRuleDTO: BodyType<RuletypesPostableRuleDTO>,
ruletypesPostableRuleDTO?: BodyType<RuletypesPostableRuleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/rules/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: ruletypesPostableRuleDTO,
signal,
});
};
@@ -513,7 +516,7 @@ export const getUpdateRuleByIDMutationOptions = <
TError,
{
pathParams: UpdateRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
>;
@@ -522,7 +525,7 @@ export const getUpdateRuleByIDMutationOptions = <
TError,
{
pathParams: UpdateRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
> => {
@@ -539,7 +542,7 @@ export const getUpdateRuleByIDMutationOptions = <
Awaited<ReturnType<typeof updateRuleByID>>,
{
pathParams: UpdateRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -553,7 +556,9 @@ export const getUpdateRuleByIDMutationOptions = <
export type UpdateRuleByIDMutationResult = NonNullable<
Awaited<ReturnType<typeof updateRuleByID>>
>;
export type UpdateRuleByIDMutationBody = BodyType<RuletypesPostableRuleDTO>;
export type UpdateRuleByIDMutationBody =
| BodyType<RuletypesPostableRuleDTO>
| undefined;
export type UpdateRuleByIDMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -568,7 +573,7 @@ export const useUpdateRuleByID = <
TError,
{
pathParams: UpdateRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
>;
@@ -577,13 +582,11 @@ export const useUpdateRuleByID = <
TError,
{
pathParams: UpdateRuleByIDPathParameters;
data: BodyType<RuletypesPostableRuleDTO>;
data?: BodyType<RuletypesPostableRuleDTO>;
},
TContext
> => {
const mutationOptions = getUpdateRuleByIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateRuleByIDMutationOptions(options));
};
/**
* Returns distinct label keys from rule history entries for the selected range.
@@ -681,9 +684,7 @@ export function useGetRuleHistoryFilterKeys<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -800,9 +801,7 @@ export function useGetRuleHistoryFilterValues<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -919,9 +918,7 @@ export function useGetRuleHistoryOverallStatus<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1036,9 +1033,7 @@ export function useGetRuleHistoryStats<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1154,9 +1149,7 @@ export function useGetRuleHistoryTimeline<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1273,9 +1266,7 @@ export function useGetRuleHistoryTopContributors<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1300,7 +1291,7 @@ export const invalidateGetRuleHistoryTopContributors = async (
* @summary Test alert rule
*/
export const testRule = (
ruletypesPostableRuleDTO: BodyType<RuletypesPostableRuleDTO>,
ruletypesPostableRuleDTO?: BodyType<RuletypesPostableRuleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<TestRule200>({
@@ -1319,13 +1310,13 @@ export const getTestRuleMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof testRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof testRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
> => {
const mutationKey = ['testRule'];
@@ -1339,7 +1330,7 @@ export const getTestRuleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof testRule>>,
{ data: BodyType<RuletypesPostableRuleDTO> }
{ data?: BodyType<RuletypesPostableRuleDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -1352,7 +1343,9 @@ export const getTestRuleMutationOptions = <
export type TestRuleMutationResult = NonNullable<
Awaited<ReturnType<typeof testRule>>
>;
export type TestRuleMutationBody = BodyType<RuletypesPostableRuleDTO>;
export type TestRuleMutationBody =
| BodyType<RuletypesPostableRuleDTO>
| undefined;
export type TestRuleMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -1365,16 +1358,14 @@ export const useTestRule = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof testRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof testRule>>,
TError,
{ data: BodyType<RuletypesPostableRuleDTO> },
{ data?: BodyType<RuletypesPostableRuleDTO> },
TContext
> => {
const mutationOptions = getTestRuleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getTestRuleMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -112,9 +113,7 @@ export function useListServiceAccounts<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -137,7 +136,7 @@ export const invalidateListServiceAccounts = async (
* @summary Create service account
*/
export const createServiceAccount = (
serviceaccounttypesPostableServiceAccountDTO: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
serviceaccounttypesPostableServiceAccountDTO?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateServiceAccount201>({
@@ -156,13 +155,13 @@ export const getCreateServiceAccountMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
> => {
const mutationKey = ['createServiceAccount'];
@@ -176,7 +175,7 @@ export const getCreateServiceAccountMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createServiceAccount>>,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> }
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -190,7 +189,8 @@ export type CreateServiceAccountMutationResult = NonNullable<
Awaited<ReturnType<typeof createServiceAccount>>
>;
export type CreateServiceAccountMutationBody =
BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
| BodyType<ServiceaccounttypesPostableServiceAccountDTO>
| undefined;
export type CreateServiceAccountMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -204,29 +204,29 @@ export const useCreateServiceAccount = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
> => {
const mutationOptions = getCreateServiceAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateServiceAccountMutationOptions(options));
};
/**
* This endpoint deletes an existing service account
* @summary Deletes a service account
*/
export const deleteServiceAccount = ({
id,
}: DeleteServiceAccountPathParameters) => {
export const deleteServiceAccount = (
{ id }: DeleteServiceAccountPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/${id}`,
method: 'DELETE',
signal,
});
};
@@ -293,9 +293,7 @@ export const useDeleteServiceAccount = <
{ pathParams: DeleteServiceAccountPathParameters },
TContext
> => {
const mutationOptions = getDeleteServiceAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteServiceAccountMutationOptions(options));
};
/**
* This endpoint gets an existing service account
@@ -380,9 +378,7 @@ export function useGetServiceAccount<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -407,13 +403,15 @@ export const invalidateGetServiceAccount = async (
*/
export const updateServiceAccount = (
{ id }: UpdateServiceAccountPathParameters,
serviceaccounttypesPostableServiceAccountDTO: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
serviceaccounttypesPostableServiceAccountDTO?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: serviceaccounttypesPostableServiceAccountDTO,
signal,
});
};
@@ -426,7 +424,7 @@ export const getUpdateServiceAccountMutationOptions = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
>;
@@ -435,7 +433,7 @@ export const getUpdateServiceAccountMutationOptions = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
> => {
@@ -452,7 +450,7 @@ export const getUpdateServiceAccountMutationOptions = <
Awaited<ReturnType<typeof updateServiceAccount>>,
{
pathParams: UpdateServiceAccountPathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -467,7 +465,8 @@ export type UpdateServiceAccountMutationResult = NonNullable<
Awaited<ReturnType<typeof updateServiceAccount>>
>;
export type UpdateServiceAccountMutationBody =
BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
| BodyType<ServiceaccounttypesPostableServiceAccountDTO>
| undefined;
export type UpdateServiceAccountMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -483,7 +482,7 @@ export const useUpdateServiceAccount = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
>;
@@ -492,13 +491,11 @@ export const useUpdateServiceAccount = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
> => {
const mutationOptions = getUpdateServiceAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateServiceAccountMutationOptions(options));
};
/**
* This endpoint lists the service account keys
@@ -584,9 +581,7 @@ export function useListServiceAccountKeys<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -611,7 +606,7 @@ export const invalidateListServiceAccountKeys = async (
*/
export const createServiceAccountKey = (
{ id }: CreateServiceAccountKeyPathParameters,
serviceaccounttypesPostableFactorAPIKeyDTO: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>,
serviceaccounttypesPostableFactorAPIKeyDTO?: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateServiceAccountKey201>({
@@ -632,7 +627,7 @@ export const getCreateServiceAccountKeyMutationOptions = <
TError,
{
pathParams: CreateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
},
TContext
>;
@@ -641,7 +636,7 @@ export const getCreateServiceAccountKeyMutationOptions = <
TError,
{
pathParams: CreateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
},
TContext
> => {
@@ -658,7 +653,7 @@ export const getCreateServiceAccountKeyMutationOptions = <
Awaited<ReturnType<typeof createServiceAccountKey>>,
{
pathParams: CreateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -673,7 +668,8 @@ export type CreateServiceAccountKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof createServiceAccountKey>>
>;
export type CreateServiceAccountKeyMutationBody =
BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
| BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>
| undefined;
export type CreateServiceAccountKeyMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -689,7 +685,7 @@ export const useCreateServiceAccountKey = <
TError,
{
pathParams: CreateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
},
TContext
>;
@@ -698,25 +694,24 @@ export const useCreateServiceAccountKey = <
TError,
{
pathParams: CreateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesPostableFactorAPIKeyDTO>;
},
TContext
> => {
const mutationOptions = getCreateServiceAccountKeyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateServiceAccountKeyMutationOptions(options));
};
/**
* This endpoint revokes an existing service account key
* @summary Revoke a service account key
*/
export const revokeServiceAccountKey = ({
id,
fid,
}: RevokeServiceAccountKeyPathParameters) => {
export const revokeServiceAccountKey = (
{ id, fid }: RevokeServiceAccountKeyPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/${id}/keys/${fid}`,
method: 'DELETE',
signal,
});
};
@@ -783,9 +778,7 @@ export const useRevokeServiceAccountKey = <
{ pathParams: RevokeServiceAccountKeyPathParameters },
TContext
> => {
const mutationOptions = getRevokeServiceAccountKeyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getRevokeServiceAccountKeyMutationOptions(options));
};
/**
* This endpoint updates an existing service account key
@@ -793,13 +786,15 @@ export const useRevokeServiceAccountKey = <
*/
export const updateServiceAccountKey = (
{ id, fid }: UpdateServiceAccountKeyPathParameters,
serviceaccounttypesUpdatableFactorAPIKeyDTO: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>,
serviceaccounttypesUpdatableFactorAPIKeyDTO?: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/${id}/keys/${fid}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: serviceaccounttypesUpdatableFactorAPIKeyDTO,
signal,
});
};
@@ -812,7 +807,7 @@ export const getUpdateServiceAccountKeyMutationOptions = <
TError,
{
pathParams: UpdateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
},
TContext
>;
@@ -821,7 +816,7 @@ export const getUpdateServiceAccountKeyMutationOptions = <
TError,
{
pathParams: UpdateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
},
TContext
> => {
@@ -838,7 +833,7 @@ export const getUpdateServiceAccountKeyMutationOptions = <
Awaited<ReturnType<typeof updateServiceAccountKey>>,
{
pathParams: UpdateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -853,7 +848,8 @@ export type UpdateServiceAccountKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof updateServiceAccountKey>>
>;
export type UpdateServiceAccountKeyMutationBody =
BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
| BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>
| undefined;
export type UpdateServiceAccountKeyMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -869,7 +865,7 @@ export const useUpdateServiceAccountKey = <
TError,
{
pathParams: UpdateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
},
TContext
>;
@@ -878,13 +874,11 @@ export const useUpdateServiceAccountKey = <
TError,
{
pathParams: UpdateServiceAccountKeyPathParameters;
data: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
data?: BodyType<ServiceaccounttypesUpdatableFactorAPIKeyDTO>;
},
TContext
> => {
const mutationOptions = getUpdateServiceAccountKeyMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateServiceAccountKeyMutationOptions(options));
};
/**
* This endpoint gets all the roles for the existing service account
@@ -970,9 +964,7 @@ export function useGetServiceAccountRoles<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -997,7 +989,7 @@ export const invalidateGetServiceAccountRoles = async (
*/
export const createServiceAccountRole = (
{ id }: CreateServiceAccountRolePathParameters,
serviceaccounttypesPostableServiceAccountRoleDTO: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>,
serviceaccounttypesPostableServiceAccountRoleDTO?: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateServiceAccountRole201>({
@@ -1018,7 +1010,7 @@ export const getCreateServiceAccountRoleMutationOptions = <
TError,
{
pathParams: CreateServiceAccountRolePathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
>;
@@ -1027,7 +1019,7 @@ export const getCreateServiceAccountRoleMutationOptions = <
TError,
{
pathParams: CreateServiceAccountRolePathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
> => {
@@ -1044,7 +1036,7 @@ export const getCreateServiceAccountRoleMutationOptions = <
Awaited<ReturnType<typeof createServiceAccountRole>>,
{
pathParams: CreateServiceAccountRolePathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -1059,7 +1051,8 @@ export type CreateServiceAccountRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof createServiceAccountRole>>
>;
export type CreateServiceAccountRoleMutationBody =
BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
| BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>
| undefined;
export type CreateServiceAccountRoleMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -1075,7 +1068,7 @@ export const useCreateServiceAccountRole = <
TError,
{
pathParams: CreateServiceAccountRolePathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
>;
@@ -1084,25 +1077,24 @@ export const useCreateServiceAccountRole = <
TError,
{
pathParams: CreateServiceAccountRolePathParameters;
data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
data?: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
> => {
const mutationOptions = getCreateServiceAccountRoleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateServiceAccountRoleMutationOptions(options));
};
/**
* This endpoint revokes a role from service account
* @summary Delete service account role
*/
export const deleteServiceAccountRole = ({
id,
rid,
}: DeleteServiceAccountRolePathParameters) => {
export const deleteServiceAccountRole = (
{ id, rid }: DeleteServiceAccountRolePathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/${id}/roles/${rid}`,
method: 'DELETE',
signal,
});
};
@@ -1169,9 +1161,7 @@ export const useDeleteServiceAccountRole = <
{ pathParams: DeleteServiceAccountRolePathParameters },
TContext
> => {
const mutationOptions = getDeleteServiceAccountRoleMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteServiceAccountRoleMutationOptions(options));
};
/**
* This endpoint gets my service account
@@ -1239,9 +1229,7 @@ export function useGetMyServiceAccount<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1264,13 +1252,15 @@ export const invalidateGetMyServiceAccount = async (
* @summary Updates my service account
*/
export const updateMyServiceAccount = (
serviceaccounttypesPostableServiceAccountDTO: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
serviceaccounttypesPostableServiceAccountDTO?: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/me`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: serviceaccounttypesPostableServiceAccountDTO,
signal,
});
};
@@ -1281,13 +1271,13 @@ export const getUpdateMyServiceAccountMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateMyServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
> => {
const mutationKey = ['updateMyServiceAccount'];
@@ -1301,7 +1291,7 @@ export const getUpdateMyServiceAccountMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateMyServiceAccount>>,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> }
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -1315,7 +1305,8 @@ export type UpdateMyServiceAccountMutationResult = NonNullable<
Awaited<ReturnType<typeof updateMyServiceAccount>>
>;
export type UpdateMyServiceAccountMutationBody =
BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
| BodyType<ServiceaccounttypesPostableServiceAccountDTO>
| undefined;
export type UpdateMyServiceAccountMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -1329,16 +1320,14 @@ export const useUpdateMyServiceAccount = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateMyServiceAccount>>,
TError,
{ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
{ data?: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
TContext
> => {
const mutationOptions = getUpdateMyServiceAccountMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateMyServiceAccountMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -103,9 +104,7 @@ export function useCreateSessionByGoogleCallback<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -192,9 +191,7 @@ export function useCreateSessionByOIDCCallback<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -217,18 +214,18 @@ export const invalidateCreateSessionByOIDCCallback = async (
* @summary Create session by saml callback
*/
export const createSessionBySAMLCallback = (
createSessionBySAMLCallbackBody: BodyType<CreateSessionBySAMLCallbackBody>,
createSessionBySAMLCallbackBody?: BodyType<CreateSessionBySAMLCallbackBody>,
params?: CreateSessionBySAMLCallbackParams,
signal?: AbortSignal,
) => {
const formUrlEncoded = new URLSearchParams();
if (createSessionBySAMLCallbackBody.RelayState !== undefined) {
if (createSessionBySAMLCallbackBody?.RelayState !== undefined) {
formUrlEncoded.append(
`RelayState`,
createSessionBySAMLCallbackBody.RelayState,
);
}
if (createSessionBySAMLCallbackBody.SAMLResponse !== undefined) {
if (createSessionBySAMLCallbackBody?.SAMLResponse !== undefined) {
formUrlEncoded.append(
`SAMLResponse`,
createSessionBySAMLCallbackBody.SAMLResponse,
@@ -253,7 +250,7 @@ export const getCreateSessionBySAMLCallbackMutationOptions = <
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data?: BodyType<CreateSessionBySAMLCallbackBody>;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -262,7 +259,7 @@ export const getCreateSessionBySAMLCallbackMutationOptions = <
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data?: BodyType<CreateSessionBySAMLCallbackBody>;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -279,7 +276,7 @@ export const getCreateSessionBySAMLCallbackMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data?: BodyType<CreateSessionBySAMLCallbackBody>;
params?: CreateSessionBySAMLCallbackParams;
}
> = (props) => {
@@ -295,7 +292,8 @@ export type CreateSessionBySAMLCallbackMutationResult = NonNullable<
Awaited<ReturnType<typeof createSessionBySAMLCallback>>
>;
export type CreateSessionBySAMLCallbackMutationBody =
BodyType<CreateSessionBySAMLCallbackBody>;
| BodyType<CreateSessionBySAMLCallbackBody>
| undefined;
export type CreateSessionBySAMLCallbackMutationError = ErrorType<
CreateSessionBySAMLCallback303 | RenderErrorResponseDTO
>;
@@ -311,7 +309,7 @@ export const useCreateSessionBySAMLCallback = <
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data?: BodyType<CreateSessionBySAMLCallbackBody>;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -320,23 +318,22 @@ export const useCreateSessionBySAMLCallback = <
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data?: BodyType<CreateSessionBySAMLCallbackBody>;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
> => {
const mutationOptions = getCreateSessionBySAMLCallbackMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateSessionBySAMLCallbackMutationOptions(options));
};
/**
* This endpoint deletes the session
* @summary Delete session
*/
export const deleteSession = () => {
export const deleteSession = (signal?: AbortSignal) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/sessions`,
method: 'DELETE',
signal,
});
};
@@ -400,9 +397,7 @@ export const useDeleteSession = <
void,
TContext
> => {
const mutationOptions = getDeleteSessionMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteSessionMutationOptions(options));
};
/**
* This endpoint returns the context for the session
@@ -470,9 +465,7 @@ export function useGetSessionContext<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -495,7 +488,7 @@ export const invalidateGetSessionContext = async (
* @summary Create session by email and password
*/
export const createSessionByEmailPassword = (
authtypesPostableEmailPasswordSessionDTO: BodyType<AuthtypesPostableEmailPasswordSessionDTO>,
authtypesPostableEmailPasswordSessionDTO?: BodyType<AuthtypesPostableEmailPasswordSessionDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateSessionByEmailPassword200>({
@@ -514,13 +507,13 @@ export const getCreateSessionByEmailPasswordMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data?: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data?: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
TContext
> => {
const mutationKey = ['createSessionByEmailPassword'];
@@ -534,7 +527,7 @@ export const getCreateSessionByEmailPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> }
{ data?: BodyType<AuthtypesPostableEmailPasswordSessionDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -548,7 +541,8 @@ export type CreateSessionByEmailPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof createSessionByEmailPassword>>
>;
export type CreateSessionByEmailPasswordMutationBody =
BodyType<AuthtypesPostableEmailPasswordSessionDTO>;
| BodyType<AuthtypesPostableEmailPasswordSessionDTO>
| undefined;
export type CreateSessionByEmailPasswordMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -562,26 +556,23 @@ export const useCreateSessionByEmailPassword = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data?: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data?: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
TContext
> => {
const mutationOptions =
getCreateSessionByEmailPasswordMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateSessionByEmailPasswordMutationOptions(options));
};
/**
* This endpoint rotates the session
* @summary Rotate session
*/
export const rotateSession = (
authtypesPostableRotateTokenDTO: BodyType<AuthtypesPostableRotateTokenDTO>,
authtypesPostableRotateTokenDTO?: BodyType<AuthtypesPostableRotateTokenDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<RotateSession200>({
@@ -600,13 +591,13 @@ export const getRotateSessionMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data?: BodyType<AuthtypesPostableRotateTokenDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data?: BodyType<AuthtypesPostableRotateTokenDTO> },
TContext
> => {
const mutationKey = ['rotateSession'];
@@ -620,7 +611,7 @@ export const getRotateSessionMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof rotateSession>>,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> }
{ data?: BodyType<AuthtypesPostableRotateTokenDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -634,7 +625,8 @@ export type RotateSessionMutationResult = NonNullable<
Awaited<ReturnType<typeof rotateSession>>
>;
export type RotateSessionMutationBody =
BodyType<AuthtypesPostableRotateTokenDTO>;
| BodyType<AuthtypesPostableRotateTokenDTO>
| undefined;
export type RotateSessionMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -647,16 +639,14 @@ export const useRotateSession = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data?: BodyType<AuthtypesPostableRotateTokenDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data?: BodyType<AuthtypesPostableRotateTokenDTO> },
TContext
> => {
const mutationOptions = getRotateSessionMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getRotateSessionMutationOptions(options));
};

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -118,9 +119,7 @@ export function useListSpanMapperGroups<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -144,7 +143,7 @@ export const invalidateListSpanMapperGroups = async (
* @summary Create a span attribute mapping group
*/
export const createSpanMapperGroup = (
spantypesPostableSpanMapperGroupDTO: BodyType<SpantypesPostableSpanMapperGroupDTO>,
spantypesPostableSpanMapperGroupDTO?: BodyType<SpantypesPostableSpanMapperGroupDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateSpanMapperGroup201>({
@@ -163,13 +162,13 @@ export const getCreateSpanMapperGroupMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSpanMapperGroup>>,
TError,
{ data: BodyType<SpantypesPostableSpanMapperGroupDTO> },
{ data?: BodyType<SpantypesPostableSpanMapperGroupDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createSpanMapperGroup>>,
TError,
{ data: BodyType<SpantypesPostableSpanMapperGroupDTO> },
{ data?: BodyType<SpantypesPostableSpanMapperGroupDTO> },
TContext
> => {
const mutationKey = ['createSpanMapperGroup'];
@@ -183,7 +182,7 @@ export const getCreateSpanMapperGroupMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createSpanMapperGroup>>,
{ data: BodyType<SpantypesPostableSpanMapperGroupDTO> }
{ data?: BodyType<SpantypesPostableSpanMapperGroupDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -197,7 +196,8 @@ export type CreateSpanMapperGroupMutationResult = NonNullable<
Awaited<ReturnType<typeof createSpanMapperGroup>>
>;
export type CreateSpanMapperGroupMutationBody =
BodyType<SpantypesPostableSpanMapperGroupDTO>;
| BodyType<SpantypesPostableSpanMapperGroupDTO>
| undefined;
export type CreateSpanMapperGroupMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -211,29 +211,29 @@ export const useCreateSpanMapperGroup = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSpanMapperGroup>>,
TError,
{ data: BodyType<SpantypesPostableSpanMapperGroupDTO> },
{ data?: BodyType<SpantypesPostableSpanMapperGroupDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createSpanMapperGroup>>,
TError,
{ data: BodyType<SpantypesPostableSpanMapperGroupDTO> },
{ data?: BodyType<SpantypesPostableSpanMapperGroupDTO> },
TContext
> => {
const mutationOptions = getCreateSpanMapperGroupMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateSpanMapperGroupMutationOptions(options));
};
/**
* Hard-deletes a mapping group and cascades to all its mappers.
* @summary Delete a span attribute mapping group
*/
export const deleteSpanMapperGroup = ({
groupId,
}: DeleteSpanMapperGroupPathParameters) => {
export const deleteSpanMapperGroup = (
{ groupId }: DeleteSpanMapperGroupPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/span_mapper_groups/${groupId}`,
method: 'DELETE',
signal,
});
};
@@ -300,9 +300,7 @@ export const useDeleteSpanMapperGroup = <
{ pathParams: DeleteSpanMapperGroupPathParameters },
TContext
> => {
const mutationOptions = getDeleteSpanMapperGroupMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteSpanMapperGroupMutationOptions(options));
};
/**
* Partially updates an existing mapping group's name, condition, or enabled state.
@@ -310,13 +308,15 @@ export const useDeleteSpanMapperGroup = <
*/
export const updateSpanMapperGroup = (
{ groupId }: UpdateSpanMapperGroupPathParameters,
spantypesUpdatableSpanMapperGroupDTO: BodyType<SpantypesUpdatableSpanMapperGroupDTO>,
spantypesUpdatableSpanMapperGroupDTO?: BodyType<SpantypesUpdatableSpanMapperGroupDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/span_mapper_groups/${groupId}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: spantypesUpdatableSpanMapperGroupDTO,
signal,
});
};
@@ -329,7 +329,7 @@ export const getUpdateSpanMapperGroupMutationOptions = <
TError,
{
pathParams: UpdateSpanMapperGroupPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
},
TContext
>;
@@ -338,7 +338,7 @@ export const getUpdateSpanMapperGroupMutationOptions = <
TError,
{
pathParams: UpdateSpanMapperGroupPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
},
TContext
> => {
@@ -355,7 +355,7 @@ export const getUpdateSpanMapperGroupMutationOptions = <
Awaited<ReturnType<typeof updateSpanMapperGroup>>,
{
pathParams: UpdateSpanMapperGroupPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -370,7 +370,8 @@ export type UpdateSpanMapperGroupMutationResult = NonNullable<
Awaited<ReturnType<typeof updateSpanMapperGroup>>
>;
export type UpdateSpanMapperGroupMutationBody =
BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
| BodyType<SpantypesUpdatableSpanMapperGroupDTO>
| undefined;
export type UpdateSpanMapperGroupMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -386,7 +387,7 @@ export const useUpdateSpanMapperGroup = <
TError,
{
pathParams: UpdateSpanMapperGroupPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
},
TContext
>;
@@ -395,13 +396,11 @@ export const useUpdateSpanMapperGroup = <
TError,
{
pathParams: UpdateSpanMapperGroupPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperGroupDTO>;
},
TContext
> => {
const mutationOptions = getUpdateSpanMapperGroupMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateSpanMapperGroupMutationOptions(options));
};
/**
* Returns all mappers belonging to a mapping group.
@@ -486,9 +485,7 @@ export function useListSpanMappers<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -513,7 +510,7 @@ export const invalidateListSpanMappers = async (
*/
export const createSpanMapper = (
{ groupId }: CreateSpanMapperPathParameters,
spantypesPostableSpanMapperDTO: BodyType<SpantypesPostableSpanMapperDTO>,
spantypesPostableSpanMapperDTO?: BodyType<SpantypesPostableSpanMapperDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateSpanMapper201>({
@@ -534,7 +531,7 @@ export const getCreateSpanMapperMutationOptions = <
TError,
{
pathParams: CreateSpanMapperPathParameters;
data: BodyType<SpantypesPostableSpanMapperDTO>;
data?: BodyType<SpantypesPostableSpanMapperDTO>;
},
TContext
>;
@@ -543,7 +540,7 @@ export const getCreateSpanMapperMutationOptions = <
TError,
{
pathParams: CreateSpanMapperPathParameters;
data: BodyType<SpantypesPostableSpanMapperDTO>;
data?: BodyType<SpantypesPostableSpanMapperDTO>;
},
TContext
> => {
@@ -560,7 +557,7 @@ export const getCreateSpanMapperMutationOptions = <
Awaited<ReturnType<typeof createSpanMapper>>,
{
pathParams: CreateSpanMapperPathParameters;
data: BodyType<SpantypesPostableSpanMapperDTO>;
data?: BodyType<SpantypesPostableSpanMapperDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -575,7 +572,8 @@ export type CreateSpanMapperMutationResult = NonNullable<
Awaited<ReturnType<typeof createSpanMapper>>
>;
export type CreateSpanMapperMutationBody =
BodyType<SpantypesPostableSpanMapperDTO>;
| BodyType<SpantypesPostableSpanMapperDTO>
| undefined;
export type CreateSpanMapperMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -590,7 +588,7 @@ export const useCreateSpanMapper = <
TError,
{
pathParams: CreateSpanMapperPathParameters;
data: BodyType<SpantypesPostableSpanMapperDTO>;
data?: BodyType<SpantypesPostableSpanMapperDTO>;
},
TContext
>;
@@ -599,25 +597,24 @@ export const useCreateSpanMapper = <
TError,
{
pathParams: CreateSpanMapperPathParameters;
data: BodyType<SpantypesPostableSpanMapperDTO>;
data?: BodyType<SpantypesPostableSpanMapperDTO>;
},
TContext
> => {
const mutationOptions = getCreateSpanMapperMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateSpanMapperMutationOptions(options));
};
/**
* Hard-deletes a mapper from a mapping group.
* @summary Delete a span mapper
*/
export const deleteSpanMapper = ({
groupId,
mapperId,
}: DeleteSpanMapperPathParameters) => {
export const deleteSpanMapper = (
{ groupId, mapperId }: DeleteSpanMapperPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/span_mapper_groups/${groupId}/span_mappers/${mapperId}`,
method: 'DELETE',
signal,
});
};
@@ -683,9 +680,7 @@ export const useDeleteSpanMapper = <
{ pathParams: DeleteSpanMapperPathParameters },
TContext
> => {
const mutationOptions = getDeleteSpanMapperMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteSpanMapperMutationOptions(options));
};
/**
* Partially updates an existing mapper's field context, config, or enabled state.
@@ -693,13 +688,15 @@ export const useDeleteSpanMapper = <
*/
export const updateSpanMapper = (
{ groupId, mapperId }: UpdateSpanMapperPathParameters,
spantypesUpdatableSpanMapperDTO: BodyType<SpantypesUpdatableSpanMapperDTO>,
spantypesUpdatableSpanMapperDTO?: BodyType<SpantypesUpdatableSpanMapperDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/span_mapper_groups/${groupId}/span_mappers/${mapperId}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: spantypesUpdatableSpanMapperDTO,
signal,
});
};
@@ -712,7 +709,7 @@ export const getUpdateSpanMapperMutationOptions = <
TError,
{
pathParams: UpdateSpanMapperPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperDTO>;
},
TContext
>;
@@ -721,7 +718,7 @@ export const getUpdateSpanMapperMutationOptions = <
TError,
{
pathParams: UpdateSpanMapperPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperDTO>;
},
TContext
> => {
@@ -738,7 +735,7 @@ export const getUpdateSpanMapperMutationOptions = <
Awaited<ReturnType<typeof updateSpanMapper>>,
{
pathParams: UpdateSpanMapperPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -753,7 +750,8 @@ export type UpdateSpanMapperMutationResult = NonNullable<
Awaited<ReturnType<typeof updateSpanMapper>>
>;
export type UpdateSpanMapperMutationBody =
BodyType<SpantypesUpdatableSpanMapperDTO>;
| BodyType<SpantypesUpdatableSpanMapperDTO>
| undefined;
export type UpdateSpanMapperMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -768,7 +766,7 @@ export const useUpdateSpanMapper = <
TError,
{
pathParams: UpdateSpanMapperPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperDTO>;
},
TContext
>;
@@ -777,11 +775,9 @@ export const useUpdateSpanMapper = <
TError,
{
pathParams: UpdateSpanMapperPathParameters;
data: BodyType<SpantypesUpdatableSpanMapperDTO>;
data?: BodyType<SpantypesUpdatableSpanMapperDTO>;
},
TContext
> => {
const mutationOptions = getUpdateSpanMapperMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateSpanMapperMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation } from 'react-query';
import type {
@@ -27,7 +28,7 @@ import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
*/
export const getWaterfall = (
{ traceID }: GetWaterfallPathParameters,
tracedetailtypesPostableWaterfallDTO: BodyType<TracedetailtypesPostableWaterfallDTO>,
tracedetailtypesPostableWaterfallDTO?: BodyType<TracedetailtypesPostableWaterfallDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetWaterfall200>({
@@ -48,7 +49,7 @@ export const getGetWaterfallMutationOptions = <
TError,
{
pathParams: GetWaterfallPathParameters;
data: BodyType<TracedetailtypesPostableWaterfallDTO>;
data?: BodyType<TracedetailtypesPostableWaterfallDTO>;
},
TContext
>;
@@ -57,7 +58,7 @@ export const getGetWaterfallMutationOptions = <
TError,
{
pathParams: GetWaterfallPathParameters;
data: BodyType<TracedetailtypesPostableWaterfallDTO>;
data?: BodyType<TracedetailtypesPostableWaterfallDTO>;
},
TContext
> => {
@@ -74,7 +75,7 @@ export const getGetWaterfallMutationOptions = <
Awaited<ReturnType<typeof getWaterfall>>,
{
pathParams: GetWaterfallPathParameters;
data: BodyType<TracedetailtypesPostableWaterfallDTO>;
data?: BodyType<TracedetailtypesPostableWaterfallDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -89,7 +90,8 @@ export type GetWaterfallMutationResult = NonNullable<
Awaited<ReturnType<typeof getWaterfall>>
>;
export type GetWaterfallMutationBody =
BodyType<TracedetailtypesPostableWaterfallDTO>;
| BodyType<TracedetailtypesPostableWaterfallDTO>
| undefined;
export type GetWaterfallMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -104,7 +106,7 @@ export const useGetWaterfall = <
TError,
{
pathParams: GetWaterfallPathParameters;
data: BodyType<TracedetailtypesPostableWaterfallDTO>;
data?: BodyType<TracedetailtypesPostableWaterfallDTO>;
},
TContext
>;
@@ -113,11 +115,9 @@ export const useGetWaterfall = <
TError,
{
pathParams: GetWaterfallPathParameters;
data: BodyType<TracedetailtypesPostableWaterfallDTO>;
data?: BodyType<TracedetailtypesPostableWaterfallDTO>;
},
TContext
> => {
const mutationOptions = getGetWaterfallMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getGetWaterfallMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -146,9 +147,7 @@ export function useGetResetPasswordTokenDeprecated<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -173,7 +172,7 @@ export const invalidateGetResetPasswordTokenDeprecated = async (
* @summary Create invite
*/
export const createInvite = (
typesPostableInviteDTO: BodyType<TypesPostableInviteDTO>,
typesPostableInviteDTO?: BodyType<TypesPostableInviteDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateInvite201>({
@@ -192,13 +191,13 @@ export const getCreateInviteMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data?: BodyType<TypesPostableInviteDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data?: BodyType<TypesPostableInviteDTO> },
TContext
> => {
const mutationKey = ['createInvite'];
@@ -212,7 +211,7 @@ export const getCreateInviteMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createInvite>>,
{ data: BodyType<TypesPostableInviteDTO> }
{ data?: BodyType<TypesPostableInviteDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -225,7 +224,9 @@ export const getCreateInviteMutationOptions = <
export type CreateInviteMutationResult = NonNullable<
Awaited<ReturnType<typeof createInvite>>
>;
export type CreateInviteMutationBody = BodyType<TypesPostableInviteDTO>;
export type CreateInviteMutationBody =
| BodyType<TypesPostableInviteDTO>
| undefined;
export type CreateInviteMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -238,25 +239,23 @@ export const useCreateInvite = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data?: BodyType<TypesPostableInviteDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data?: BodyType<TypesPostableInviteDTO> },
TContext
> => {
const mutationOptions = getCreateInviteMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateInviteMutationOptions(options));
};
/**
* This endpoint creates a bulk invite for a user
* @summary Create bulk invite
*/
export const createBulkInvite = (
typesPostableBulkInviteRequestDTO: BodyType<TypesPostableBulkInviteRequestDTO>,
typesPostableBulkInviteRequestDTO?: BodyType<TypesPostableBulkInviteRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -275,13 +274,13 @@ export const getCreateBulkInviteMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableBulkInviteRequestDTO> },
{ data?: BodyType<TypesPostableBulkInviteRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableBulkInviteRequestDTO> },
{ data?: BodyType<TypesPostableBulkInviteRequestDTO> },
TContext
> => {
const mutationKey = ['createBulkInvite'];
@@ -295,7 +294,7 @@ export const getCreateBulkInviteMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createBulkInvite>>,
{ data: BodyType<TypesPostableBulkInviteRequestDTO> }
{ data?: BodyType<TypesPostableBulkInviteRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -309,7 +308,8 @@ export type CreateBulkInviteMutationResult = NonNullable<
Awaited<ReturnType<typeof createBulkInvite>>
>;
export type CreateBulkInviteMutationBody =
BodyType<TypesPostableBulkInviteRequestDTO>;
| BodyType<TypesPostableBulkInviteRequestDTO>
| undefined;
export type CreateBulkInviteMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -322,25 +322,23 @@ export const useCreateBulkInvite = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableBulkInviteRequestDTO> },
{ data?: BodyType<TypesPostableBulkInviteRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableBulkInviteRequestDTO> },
{ data?: BodyType<TypesPostableBulkInviteRequestDTO> },
TContext
> => {
const mutationOptions = getCreateBulkInviteMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateBulkInviteMutationOptions(options));
};
/**
* This endpoint resets the password by token
* @summary Reset password
*/
export const resetPassword = (
typesPostableResetPasswordDTO: BodyType<TypesPostableResetPasswordDTO>,
typesPostableResetPasswordDTO?: BodyType<TypesPostableResetPasswordDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -359,13 +357,13 @@ export const getResetPasswordMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data?: BodyType<TypesPostableResetPasswordDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data?: BodyType<TypesPostableResetPasswordDTO> },
TContext
> => {
const mutationKey = ['resetPassword'];
@@ -379,7 +377,7 @@ export const getResetPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof resetPassword>>,
{ data: BodyType<TypesPostableResetPasswordDTO> }
{ data?: BodyType<TypesPostableResetPasswordDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -392,7 +390,9 @@ export const getResetPasswordMutationOptions = <
export type ResetPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof resetPassword>>
>;
export type ResetPasswordMutationBody = BodyType<TypesPostableResetPasswordDTO>;
export type ResetPasswordMutationBody =
| BodyType<TypesPostableResetPasswordDTO>
| undefined;
export type ResetPasswordMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -405,18 +405,16 @@ export const useResetPassword = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data?: BodyType<TypesPostableResetPasswordDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data?: BodyType<TypesPostableResetPasswordDTO> },
TContext
> => {
const mutationOptions = getResetPasswordMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getResetPasswordMutationOptions(options));
};
/**
* This endpoint lists all users
@@ -484,9 +482,7 @@ export function useListUsersDeprecated<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -508,10 +504,14 @@ export const invalidateListUsersDeprecated = async (
* This endpoint deletes the user by id
* @summary Delete user
*/
export const deleteUser = ({ id }: DeleteUserPathParameters) => {
export const deleteUser = (
{ id }: DeleteUserPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/user/${id}`,
method: 'DELETE',
signal,
});
};
@@ -577,9 +577,7 @@ export const useDeleteUser = <
{ pathParams: DeleteUserPathParameters },
TContext
> => {
const mutationOptions = getDeleteUserMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getDeleteUserMutationOptions(options));
};
/**
* This endpoint returns the user by id
@@ -664,9 +662,7 @@ export function useGetUserDeprecated<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -691,13 +687,15 @@ export const invalidateGetUserDeprecated = async (
*/
export const updateUserDeprecated = (
{ id }: UpdateUserDeprecatedPathParameters,
typesDeprecatedUserDTO: BodyType<TypesDeprecatedUserDTO>,
typesDeprecatedUserDTO?: BodyType<TypesDeprecatedUserDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<UpdateUserDeprecated200>({
url: `/api/v1/user/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: typesDeprecatedUserDTO,
signal,
});
};
@@ -710,7 +708,7 @@ export const getUpdateUserDeprecatedMutationOptions = <
TError,
{
pathParams: UpdateUserDeprecatedPathParameters;
data: BodyType<TypesDeprecatedUserDTO>;
data?: BodyType<TypesDeprecatedUserDTO>;
},
TContext
>;
@@ -719,7 +717,7 @@ export const getUpdateUserDeprecatedMutationOptions = <
TError,
{
pathParams: UpdateUserDeprecatedPathParameters;
data: BodyType<TypesDeprecatedUserDTO>;
data?: BodyType<TypesDeprecatedUserDTO>;
},
TContext
> => {
@@ -736,7 +734,7 @@ export const getUpdateUserDeprecatedMutationOptions = <
Awaited<ReturnType<typeof updateUserDeprecated>>,
{
pathParams: UpdateUserDeprecatedPathParameters;
data: BodyType<TypesDeprecatedUserDTO>;
data?: BodyType<TypesDeprecatedUserDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -750,7 +748,9 @@ export const getUpdateUserDeprecatedMutationOptions = <
export type UpdateUserDeprecatedMutationResult = NonNullable<
Awaited<ReturnType<typeof updateUserDeprecated>>
>;
export type UpdateUserDeprecatedMutationBody = BodyType<TypesDeprecatedUserDTO>;
export type UpdateUserDeprecatedMutationBody =
| BodyType<TypesDeprecatedUserDTO>
| undefined;
export type UpdateUserDeprecatedMutationError =
ErrorType<RenderErrorResponseDTO>;
@@ -766,7 +766,7 @@ export const useUpdateUserDeprecated = <
TError,
{
pathParams: UpdateUserDeprecatedPathParameters;
data: BodyType<TypesDeprecatedUserDTO>;
data?: BodyType<TypesDeprecatedUserDTO>;
},
TContext
>;
@@ -775,13 +775,11 @@ export const useUpdateUserDeprecated = <
TError,
{
pathParams: UpdateUserDeprecatedPathParameters;
data: BodyType<TypesDeprecatedUserDTO>;
data?: BodyType<TypesDeprecatedUserDTO>;
},
TContext
> => {
const mutationOptions = getUpdateUserDeprecatedMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateUserDeprecatedMutationOptions(options));
};
/**
* This endpoint returns the user I belong to
@@ -849,9 +847,7 @@ export function useGetMyUserDeprecated<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -874,7 +870,7 @@ export const invalidateGetMyUserDeprecated = async (
* @summary Forgot password
*/
export const forgotPassword = (
typesPostableForgotPasswordDTO: BodyType<TypesPostableForgotPasswordDTO>,
typesPostableForgotPasswordDTO?: BodyType<TypesPostableForgotPasswordDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -893,13 +889,13 @@ export const getForgotPasswordMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data?: BodyType<TypesPostableForgotPasswordDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data?: BodyType<TypesPostableForgotPasswordDTO> },
TContext
> => {
const mutationKey = ['forgotPassword'];
@@ -913,7 +909,7 @@ export const getForgotPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof forgotPassword>>,
{ data: BodyType<TypesPostableForgotPasswordDTO> }
{ data?: BodyType<TypesPostableForgotPasswordDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -927,7 +923,8 @@ export type ForgotPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof forgotPassword>>
>;
export type ForgotPasswordMutationBody =
BodyType<TypesPostableForgotPasswordDTO>;
| BodyType<TypesPostableForgotPasswordDTO>
| undefined;
export type ForgotPasswordMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -940,18 +937,16 @@ export const useForgotPassword = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data?: BodyType<TypesPostableForgotPasswordDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data?: BodyType<TypesPostableForgotPasswordDTO> },
TContext
> => {
const mutationOptions = getForgotPasswordMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getForgotPasswordMutationOptions(options));
};
/**
* This endpoint returns the users having the role by role id
@@ -1035,9 +1030,7 @@ export function useGetUsersByRoleID<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1114,9 +1107,7 @@ export function useListUsers<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1204,9 +1195,7 @@ export function useGetUser<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1231,13 +1220,15 @@ export const invalidateGetUser = async (
*/
export const updateUser = (
{ id }: UpdateUserPathParameters,
typesUpdatableUserDTO: BodyType<TypesUpdatableUserDTO>,
typesUpdatableUserDTO?: BodyType<TypesUpdatableUserDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/users/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: typesUpdatableUserDTO,
signal,
});
};
@@ -1250,7 +1241,7 @@ export const getUpdateUserMutationOptions = <
TError,
{
pathParams: UpdateUserPathParameters;
data: BodyType<TypesUpdatableUserDTO>;
data?: BodyType<TypesUpdatableUserDTO>;
},
TContext
>;
@@ -1259,7 +1250,7 @@ export const getUpdateUserMutationOptions = <
TError,
{
pathParams: UpdateUserPathParameters;
data: BodyType<TypesUpdatableUserDTO>;
data?: BodyType<TypesUpdatableUserDTO>;
},
TContext
> => {
@@ -1276,7 +1267,7 @@ export const getUpdateUserMutationOptions = <
Awaited<ReturnType<typeof updateUser>>,
{
pathParams: UpdateUserPathParameters;
data: BodyType<TypesUpdatableUserDTO>;
data?: BodyType<TypesUpdatableUserDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -1290,7 +1281,9 @@ export const getUpdateUserMutationOptions = <
export type UpdateUserMutationResult = NonNullable<
Awaited<ReturnType<typeof updateUser>>
>;
export type UpdateUserMutationBody = BodyType<TypesUpdatableUserDTO>;
export type UpdateUserMutationBody =
| BodyType<TypesUpdatableUserDTO>
| undefined;
export type UpdateUserMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -1305,7 +1298,7 @@ export const useUpdateUser = <
TError,
{
pathParams: UpdateUserPathParameters;
data: BodyType<TypesUpdatableUserDTO>;
data?: BodyType<TypesUpdatableUserDTO>;
},
TContext
>;
@@ -1314,13 +1307,11 @@ export const useUpdateUser = <
TError,
{
pathParams: UpdateUserPathParameters;
data: BodyType<TypesUpdatableUserDTO>;
data?: BodyType<TypesUpdatableUserDTO>;
},
TContext
> => {
const mutationOptions = getUpdateUserMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateUserMutationOptions(options));
};
/**
* This endpoint returns the existing reset password token for a user.
@@ -1405,9 +1396,7 @@ export function useGetResetPasswordToken<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1430,12 +1419,14 @@ export const invalidateGetResetPasswordToken = async (
* This endpoint creates or regenerates a reset password token for a user. If a valid token exists, it is returned. If expired, a new one is created.
* @summary Create or regenerate reset password token for a user
*/
export const createResetPasswordToken = ({
id,
}: CreateResetPasswordTokenPathParameters) => {
export const createResetPasswordToken = (
{ id }: CreateResetPasswordTokenPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateResetPasswordToken201>({
url: `/api/v2/users/${id}/reset_password_tokens`,
method: 'PUT',
signal,
});
};
@@ -1502,9 +1493,7 @@ export const useCreateResetPasswordToken = <
{ pathParams: CreateResetPasswordTokenPathParameters },
TContext
> => {
const mutationOptions = getCreateResetPasswordTokenMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getCreateResetPasswordTokenMutationOptions(options));
};
/**
* This endpoint returns the user roles by user id
@@ -1588,9 +1577,7 @@ export function useGetRolesByUserID<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1615,7 +1602,7 @@ export const invalidateGetRolesByUserID = async (
*/
export const setRoleByUserID = (
{ id }: SetRoleByUserIDPathParameters,
typesPostableRoleDTO: BodyType<TypesPostableRoleDTO>,
typesPostableRoleDTO?: BodyType<TypesPostableRoleDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -1636,7 +1623,7 @@ export const getSetRoleByUserIDMutationOptions = <
TError,
{
pathParams: SetRoleByUserIDPathParameters;
data: BodyType<TypesPostableRoleDTO>;
data?: BodyType<TypesPostableRoleDTO>;
},
TContext
>;
@@ -1645,7 +1632,7 @@ export const getSetRoleByUserIDMutationOptions = <
TError,
{
pathParams: SetRoleByUserIDPathParameters;
data: BodyType<TypesPostableRoleDTO>;
data?: BodyType<TypesPostableRoleDTO>;
},
TContext
> => {
@@ -1662,7 +1649,7 @@ export const getSetRoleByUserIDMutationOptions = <
Awaited<ReturnType<typeof setRoleByUserID>>,
{
pathParams: SetRoleByUserIDPathParameters;
data: BodyType<TypesPostableRoleDTO>;
data?: BodyType<TypesPostableRoleDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -1676,7 +1663,9 @@ export const getSetRoleByUserIDMutationOptions = <
export type SetRoleByUserIDMutationResult = NonNullable<
Awaited<ReturnType<typeof setRoleByUserID>>
>;
export type SetRoleByUserIDMutationBody = BodyType<TypesPostableRoleDTO>;
export type SetRoleByUserIDMutationBody =
| BodyType<TypesPostableRoleDTO>
| undefined;
export type SetRoleByUserIDMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -1691,7 +1680,7 @@ export const useSetRoleByUserID = <
TError,
{
pathParams: SetRoleByUserIDPathParameters;
data: BodyType<TypesPostableRoleDTO>;
data?: BodyType<TypesPostableRoleDTO>;
},
TContext
>;
@@ -1700,25 +1689,24 @@ export const useSetRoleByUserID = <
TError,
{
pathParams: SetRoleByUserIDPathParameters;
data: BodyType<TypesPostableRoleDTO>;
data?: BodyType<TypesPostableRoleDTO>;
},
TContext
> => {
const mutationOptions = getSetRoleByUserIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getSetRoleByUserIDMutationOptions(options));
};
/**
* This endpoint removes a role from the user by user id and role id
* @summary Remove a role from user
*/
export const removeUserRoleByUserIDAndRoleID = ({
id,
roleId,
}: RemoveUserRoleByUserIDAndRoleIDPathParameters) => {
export const removeUserRoleByUserIDAndRoleID = (
{ id, roleId }: RemoveUserRoleByUserIDAndRoleIDPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/users/${id}/roles/${roleId}`,
method: 'DELETE',
signal,
});
};
@@ -1785,10 +1773,7 @@ export const useRemoveUserRoleByUserIDAndRoleID = <
{ pathParams: RemoveUserRoleByUserIDAndRoleIDPathParameters },
TContext
> => {
const mutationOptions =
getRemoveUserRoleByUserIDAndRoleIDMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getRemoveUserRoleByUserIDAndRoleIDMutationOptions(options));
};
/**
* This endpoint returns the user I belong to
@@ -1848,9 +1833,7 @@ export function useGetMyUser<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -1873,13 +1856,15 @@ export const invalidateGetMyUser = async (
* @summary Update my user v2
*/
export const updateMyUserV2 = (
typesUpdatableUserDTO: BodyType<TypesUpdatableUserDTO>,
typesUpdatableUserDTO?: BodyType<TypesUpdatableUserDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/users/me`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: typesUpdatableUserDTO,
signal,
});
};
@@ -1890,13 +1875,13 @@ export const getUpdateMyUserV2MutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyUserV2>>,
TError,
{ data: BodyType<TypesUpdatableUserDTO> },
{ data?: BodyType<TypesUpdatableUserDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateMyUserV2>>,
TError,
{ data: BodyType<TypesUpdatableUserDTO> },
{ data?: BodyType<TypesUpdatableUserDTO> },
TContext
> => {
const mutationKey = ['updateMyUserV2'];
@@ -1910,7 +1895,7 @@ export const getUpdateMyUserV2MutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateMyUserV2>>,
{ data: BodyType<TypesUpdatableUserDTO> }
{ data?: BodyType<TypesUpdatableUserDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -1923,7 +1908,9 @@ export const getUpdateMyUserV2MutationOptions = <
export type UpdateMyUserV2MutationResult = NonNullable<
Awaited<ReturnType<typeof updateMyUserV2>>
>;
export type UpdateMyUserV2MutationBody = BodyType<TypesUpdatableUserDTO>;
export type UpdateMyUserV2MutationBody =
| BodyType<TypesUpdatableUserDTO>
| undefined;
export type UpdateMyUserV2MutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -1936,31 +1923,31 @@ export const useUpdateMyUserV2 = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyUserV2>>,
TError,
{ data: BodyType<TypesUpdatableUserDTO> },
{ data?: BodyType<TypesUpdatableUserDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateMyUserV2>>,
TError,
{ data: BodyType<TypesUpdatableUserDTO> },
{ data?: BodyType<TypesUpdatableUserDTO> },
TContext
> => {
const mutationOptions = getUpdateMyUserV2MutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateMyUserV2MutationOptions(options));
};
/**
* This endpoint updates the password of the user I belong to
* @summary Updates my password
*/
export const updateMyPassword = (
typesChangePasswordRequestDTO: BodyType<TypesChangePasswordRequestDTO>,
typesChangePasswordRequestDTO?: BodyType<TypesChangePasswordRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/users/me/factor_password`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: typesChangePasswordRequestDTO,
signal,
});
};
@@ -1971,13 +1958,13 @@ export const getUpdateMyPasswordMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyPassword>>,
TError,
{ data: BodyType<TypesChangePasswordRequestDTO> },
{ data?: BodyType<TypesChangePasswordRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateMyPassword>>,
TError,
{ data: BodyType<TypesChangePasswordRequestDTO> },
{ data?: BodyType<TypesChangePasswordRequestDTO> },
TContext
> => {
const mutationKey = ['updateMyPassword'];
@@ -1991,7 +1978,7 @@ export const getUpdateMyPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateMyPassword>>,
{ data: BodyType<TypesChangePasswordRequestDTO> }
{ data?: BodyType<TypesChangePasswordRequestDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -2005,7 +1992,8 @@ export type UpdateMyPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof updateMyPassword>>
>;
export type UpdateMyPasswordMutationBody =
BodyType<TypesChangePasswordRequestDTO>;
| BodyType<TypesChangePasswordRequestDTO>
| undefined;
export type UpdateMyPasswordMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -2018,16 +2006,14 @@ export const useUpdateMyPassword = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyPassword>>,
TError,
{ data: BodyType<TypesChangePasswordRequestDTO> },
{ data?: BodyType<TypesChangePasswordRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateMyPassword>>,
TError,
{ data: BodyType<TypesChangePasswordRequestDTO> },
{ data?: BodyType<TypesChangePasswordRequestDTO> },
TContext
> => {
const mutationOptions = getUpdateMyPasswordMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getUpdateMyPasswordMutationOptions(options));
};

View File

@@ -3,6 +3,7 @@
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'pnpm generate:api'
* SigNoz
* OpenAPI spec version: 0.0.1
*/
import { useMutation, useQuery } from 'react-query';
import type {
@@ -85,9 +86,7 @@ export function useGetHosts<
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
return { ...query, queryKey: queryOptions.queryKey };
}
/**
@@ -110,13 +109,15 @@ export const invalidateGetHosts = async (
* @summary Put host in Zeus for a deployment.
*/
export const putHost = (
zeustypesPostableHostDTO: BodyType<ZeustypesPostableHostDTO>,
zeustypesPostableHostDTO?: BodyType<ZeustypesPostableHostDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/zeus/hosts`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: zeustypesPostableHostDTO,
signal,
});
};
@@ -127,13 +128,13 @@ export const getPutHostMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data?: BodyType<ZeustypesPostableHostDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data?: BodyType<ZeustypesPostableHostDTO> },
TContext
> => {
const mutationKey = ['putHost'];
@@ -147,7 +148,7 @@ export const getPutHostMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof putHost>>,
{ data: BodyType<ZeustypesPostableHostDTO> }
{ data?: BodyType<ZeustypesPostableHostDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -160,7 +161,9 @@ export const getPutHostMutationOptions = <
export type PutHostMutationResult = NonNullable<
Awaited<ReturnType<typeof putHost>>
>;
export type PutHostMutationBody = BodyType<ZeustypesPostableHostDTO>;
export type PutHostMutationBody =
| BodyType<ZeustypesPostableHostDTO>
| undefined;
export type PutHostMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -173,31 +176,31 @@ export const usePutHost = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data?: BodyType<ZeustypesPostableHostDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data?: BodyType<ZeustypesPostableHostDTO> },
TContext
> => {
const mutationOptions = getPutHostMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getPutHostMutationOptions(options));
};
/**
* This endpoint saves the profile of a deployment to zeus.
* @summary Put profile in Zeus for a deployment.
*/
export const putProfile = (
zeustypesPostableProfileDTO: BodyType<ZeustypesPostableProfileDTO>,
zeustypesPostableProfileDTO?: BodyType<ZeustypesPostableProfileDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/zeus/profiles`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: zeustypesPostableProfileDTO,
signal,
});
};
@@ -208,13 +211,13 @@ export const getPutProfileMutationOptions = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data?: BodyType<ZeustypesPostableProfileDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data?: BodyType<ZeustypesPostableProfileDTO> },
TContext
> => {
const mutationKey = ['putProfile'];
@@ -228,7 +231,7 @@ export const getPutProfileMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof putProfile>>,
{ data: BodyType<ZeustypesPostableProfileDTO> }
{ data?: BodyType<ZeustypesPostableProfileDTO> }
> = (props) => {
const { data } = props ?? {};
@@ -241,7 +244,9 @@ export const getPutProfileMutationOptions = <
export type PutProfileMutationResult = NonNullable<
Awaited<ReturnType<typeof putProfile>>
>;
export type PutProfileMutationBody = BodyType<ZeustypesPostableProfileDTO>;
export type PutProfileMutationBody =
| BodyType<ZeustypesPostableProfileDTO>
| undefined;
export type PutProfileMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -254,16 +259,14 @@ export const usePutProfile = <
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data?: BodyType<ZeustypesPostableProfileDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data?: BodyType<ZeustypesPostableProfileDTO> },
TContext
> => {
const mutationOptions = getPutProfileMutationOptions(options);
return useMutation(mutationOptions);
return useMutation(getPutProfileMutationOptions(options));
};

View File

@@ -4,14 +4,46 @@ import {
interceptorsRequestResponse,
interceptorsResponse,
} from 'api';
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import { ENVIRONMENT } from 'constants/env';
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
// generated API Instance
const generatedAPIAxiosInstance = axios.create({
baseURL: ENVIRONMENT.baseURL,
});
let generatedAPIQueryKeyHeaderContext: Record<string, unknown> | undefined;
export const setGeneratedAPIQueryKeyHeaderContext = <THeaders extends object>(
headers?: THeaders,
): void => {
generatedAPIQueryKeyHeaderContext = headers
? { ...(headers as Record<string, unknown>) }
: undefined;
};
const hashHeaderValue = (value: string): string => {
let hash = 0;
for (let index = 0; index < value.length; index += 1) {
hash = (hash * 31 + value.charCodeAt(index)) >>> 0;
}
return hash.toString(16);
};
const mergeHeaderRecord = (
target: Record<string, unknown>,
source: unknown,
): Record<string, unknown> => {
if (!source || typeof source !== 'object') {
return target;
}
return Object.assign(target, source as Record<string, unknown>);
};
export const GeneratedAPIInstance = <T>(
config: AxiosRequestConfig,
): Promise<T> => {
@@ -26,5 +58,59 @@ generatedAPIAxiosInstance.interceptors.response.use(
interceptorRejected,
);
const getDefaultQueryKeyHeaders = (): Record<string, unknown> => {
const defaults = generatedAPIAxiosInstance.defaults
.headers as unknown as Record<string, unknown>;
const headers: Record<string, unknown> = {};
const methodKeys = new Set([
'common',
'delete',
'get',
'head',
'options',
'patch',
'post',
'put',
]);
mergeHeaderRecord(headers, defaults?.common);
mergeHeaderRecord(headers, defaults?.get);
for (const [key, value] of Object.entries(defaults ?? {})) {
if (!methodKeys.has(key)) {
headers[key] = value;
}
}
return headers;
};
export const getGeneratedAPIQueryKeyHeaders = <THeaders extends object>(
headers?: THeaders,
): [{ headers: Record<string, unknown> }] | [] => {
const mergedHeaders = {
...getDefaultQueryKeyHeaders(),
...generatedAPIQueryKeyHeaderContext,
...(headers as Record<string, unknown> | undefined),
};
const queryKeyHeaders = Object.fromEntries(
Object.entries(mergedHeaders)
.filter(([, value]) => value !== undefined)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, value]) => {
if (key.toLowerCase() === 'authorization' && typeof value === 'string') {
return [key, hashHeaderValue(value)];
}
return [key, value];
}),
);
return Object.keys(queryKeyHeaders).length
? [{ headers: queryKeyHeaders }]
: [];
};
export type ErrorType<Error> = AxiosError<Error>;
export type BodyType<BodyData> = BodyData;

View File

@@ -103,7 +103,7 @@ function EditMemberDrawer({
const { user: currentUser } = useAppContext();
const [localDisplayName, setLocalDisplayName] = useState('');
const [localRole, setLocalRole] = useState('');
const [localRoles, setLocalRoles] = useState<string[]>([]);
const [isSaving, setIsSaving] = useState(false);
const [saveErrors, setSaveErrors] = useState<SaveError[]>([]);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
@@ -141,7 +141,7 @@ function EditMemberDrawer({
} = useRoles();
const {
fetchedRoleIds,
currentRoles: currentMemberRoles,
isLoading: isMemberRolesLoading,
applyDiff,
} = useMemberRoleManager(member?.id ?? '', open && !!member?.id);
@@ -188,16 +188,24 @@ function EditMemberDrawer({
if (!member?.id) {
roleSessionRef.current = null;
} else if (member.id !== roleSessionRef.current && !isMemberRolesLoading) {
setLocalRole(fetchedRoleIds[0] ?? '');
setLocalRoles(
currentMemberRoles.map((r) => r.id).filter(Boolean) as string[],
);
roleSessionRef.current = member.id;
}
}, [member?.id, fetchedRoleIds, isMemberRolesLoading]);
}, [member?.id, currentMemberRoles, isMemberRolesLoading]);
const isDirty =
member !== null &&
fetchedUser != null &&
(localDisplayName !== fetchedDisplayName ||
localRole !== (fetchedRoleIds[0] ?? ''));
JSON.stringify([...localRoles].sort()) !==
JSON.stringify(
currentMemberRoles
.map((r) => r.id)
.filter(Boolean)
.sort(),
));
const { mutateAsync: updateMyUser } = useUpdateMyUserV2();
const { mutateAsync: updateUser } = useUpdateUser();
@@ -272,7 +280,14 @@ function EditMemberDrawer({
setIsSaving(true);
try {
const nameChanged = localDisplayName !== fetchedDisplayName;
const rolesChanged = localRole !== (fetchedRoleIds[0] ?? '');
const rolesChanged =
JSON.stringify([...localRoles].sort()) !==
JSON.stringify(
currentMemberRoles
.map((r) => r.id)
.filter(Boolean)
.sort(),
);
const namePromise = nameChanged
? isSelf
@@ -286,7 +301,7 @@ function EditMemberDrawer({
const [nameResult, rolesResult] = await Promise.allSettled([
namePromise,
rolesChanged
? applyDiff([localRole].filter(Boolean), availableRoles)
? applyDiff([...localRoles], availableRoles)
: Promise.resolve([]),
]);
@@ -305,10 +320,7 @@ function EditMemberDrawer({
context: 'Roles update',
apiError: toSaveApiError(rolesResult.reason),
onRetry: async (): Promise<void> => {
const failures = await applyDiff(
[localRole].filter(Boolean),
availableRoles,
);
const failures = await applyDiff([...localRoles], availableRoles);
setSaveErrors((prev) => {
const rest = prev.filter((e) => e.context !== 'Roles update');
return [
@@ -353,9 +365,9 @@ function EditMemberDrawer({
isDirty,
isSelf,
localDisplayName,
localRole,
localRoles,
fetchedDisplayName,
fetchedRoleIds,
currentMemberRoles,
updateMyUser,
updateUser,
applyDiff,
@@ -503,10 +515,15 @@ function EditMemberDrawer({
>
<div className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled">
<div className="edit-member-drawer__disabled-roles">
{localRole ? (
<Badge color="vanilla">
{availableRoles.find((r) => r.id === localRole)?.name ?? localRole}
</Badge>
{localRoles.length > 0 ? (
localRoles.map((roleId) => {
const role = availableRoles.find((r) => r.id === roleId);
return (
<Badge key={roleId} color="vanilla">
{role?.name ?? roleId}
</Badge>
);
})
) : (
<span className="edit-member-drawer__email-text"></span>
)}
@@ -517,14 +534,15 @@ function EditMemberDrawer({
) : (
<RolesSelect
id="member-role"
mode="multiple"
roles={availableRoles}
loading={rolesLoading}
isError={rolesError}
error={rolesErrorObj}
onRefetch={refetchRoles}
value={localRole}
onChange={(role): void => {
setLocalRole(role ?? '');
value={localRoles}
onChange={(roles): void => {
setLocalRoles(roles);
setSaveErrors((prev) =>
prev.filter(
(err) =>
@@ -532,8 +550,7 @@ function EditMemberDrawer({
),
);
}}
placeholder="Select role"
allowClear={false}
placeholder="Select roles"
/>
)}
</div>

View File

@@ -5,7 +5,9 @@ import {
useCreateResetPasswordToken,
useDeleteUser,
useGetResetPasswordToken,
useGetRolesByUserID,
useGetUser,
useRemoveUserRoleByUserIDAndRoleID,
useSetRoleByUserID,
useUpdateMyUserV2,
useUpdateUser,
@@ -23,11 +25,16 @@ import EditMemberDrawer, { EditMemberDrawerProps } from '../EditMemberDrawer';
jest.mock('api/generated/services/users', () => ({
useDeleteUser: jest.fn(),
useGetUser: jest.fn(),
useGetRolesByUserID: jest.fn(),
useRemoveUserRoleByUserIDAndRoleID: jest.fn(),
useUpdateUser: jest.fn(),
useUpdateMyUserV2: jest.fn(),
useSetRoleByUserID: jest.fn(),
useGetResetPasswordToken: jest.fn(),
useCreateResetPasswordToken: jest.fn(),
getGetRolesByUserIDQueryKey: ({ id }: { id: string }): string[] => [
`/api/v2/users/${id}/roles`,
],
}));
jest.mock('api/ErrorResponseHandlerForGeneratedAPIs', () => ({
@@ -98,6 +105,7 @@ jest.mock('react-use', () => ({
const ROLES_ENDPOINT = '*/api/v1/roles';
const mockDeleteMutate = jest.fn();
const mockRemoveMutateAsync = jest.fn();
const mockCreateTokenMutateAsync = jest.fn();
const showErrorModal = jest.fn();
@@ -186,6 +194,14 @@ describe('EditMemberDrawer', () => {
isLoading: false,
refetch: jest.fn(),
});
(useGetRolesByUserID as jest.Mock).mockReturnValue({
data: { data: [managedRoles[0]] },
isLoading: false,
});
(useRemoveUserRoleByUserIDAndRoleID as jest.Mock).mockReturnValue({
mutateAsync: mockRemoveMutateAsync.mockResolvedValue({}),
isLoading: false,
});
(useUpdateUser as jest.Mock).mockReturnValue({
mutateAsync: jest.fn().mockResolvedValue({}),
isLoading: false,
@@ -296,7 +312,7 @@ describe('EditMemberDrawer', () => {
expect(onClose).not.toHaveBeenCalled();
});
it('selecting a different role calls setRole with the new role name', async () => {
it('adding a new role calls setRole without removing existing ones', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockSet = jest.fn().mockResolvedValue({});
@@ -308,7 +324,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
// Open the roles dropdown and select signoz-editor
// signoz-admin is already selected; add signoz-editor on top
await user.click(screen.getByLabelText('Roles'));
await user.click(await screen.findByTitle('signoz-editor'));
@@ -321,34 +337,31 @@ describe('EditMemberDrawer', () => {
pathParams: { id: 'user-1' },
data: { name: 'signoz-editor' },
});
expect(mockRemoveMutateAsync).not.toHaveBeenCalled();
expect(onComplete).toHaveBeenCalled();
});
});
it('does not call removeRole when the role is changed', async () => {
it('deselecting a role calls removeRole with the role id', async () => {
const onComplete = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockSet = jest.fn().mockResolvedValue({});
(useSetRoleByUserID as jest.Mock).mockReturnValue({
mutateAsync: mockSet,
isLoading: false,
});
renderDrawer({ onComplete });
// Switch from signoz-admin to signoz-viewer using single-select
await user.click(screen.getByLabelText('Roles'));
await user.click(await screen.findByTitle('signoz-viewer'));
// signoz-admin appears as a selected tag — click its remove button to deselect
const adminTag = await screen.findByTitle('signoz-admin');
const removeBtn = adminTag.querySelector(
'.ant-select-selection-item-remove',
) as Element;
await user.click(removeBtn);
const saveBtn = screen.getByRole('button', { name: /save member details/i });
await waitFor(() => expect(saveBtn).not.toBeDisabled());
await user.click(saveBtn);
await waitFor(() => {
expect(mockSet).toHaveBeenCalledWith({
pathParams: { id: 'user-1' },
data: { name: 'signoz-viewer' },
expect(mockRemoveMutateAsync).toHaveBeenCalledWith({
pathParams: { id: 'user-1', roleId: managedRoles[0].id },
});
expect(onComplete).toHaveBeenCalled();
});

View File

@@ -4,6 +4,49 @@
gap: 8px;
}
.header-ai-assistant-btn-container {
display: flex;
align-items: center;
gap: 4px;
}
.header-ai-assistant-btn__prefix {
display: inline-flex;
align-items: center;
gap: 6px;
}
.header-ai-assistant-btn__badge {
flex-shrink: 0;
display: inline-flex;
line-height: 0;
color: var(--accent-primary);
}
.header-ai-assistant-btn__pulse-dot {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
line-height: 0;
animation: header-ai-assistant-dot-pulse 1.5s ease-in-out infinite;
transform: scale(0.8);
margin-right: -12px;
}
@keyframes header-ai-assistant-dot-pulse {
0%,
100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.35;
transform: scale(0.82);
}
}
.share-modal-content,
.feedback-modal-container {
display: flex;

View File

@@ -1,8 +1,17 @@
import { useCallback, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Button, Popover } from 'antd';
import { Dot, Sparkles } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Popover } from 'antd';
import logEvent from 'api/common/logEvent';
import {
openAIAssistant,
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import { selectPendingUserInputStreamCount } from 'container/AIAssistant/store/pendingInputSelectors';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { Globe, Inbox, SquarePen } from '@signozhq/icons';
import AnnouncementsModal from './AnnouncementsModal';
@@ -29,6 +38,7 @@ function HeaderRightSection({
const [openAnnouncementsModal, setOpenAnnouncementsModal] = useState(false);
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const handleOpenFeedbackModal = useCallback((): void => {
logEvent('Feedback: Clicked', {
@@ -67,9 +77,46 @@ function HeaderRightSection({
};
const isLicenseEnabled = isEnterpriseSelfHostedUser || isCloudUser;
const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const isModalOpen = useAIAssistantStore((s) => s.isModalOpen);
const pendingUserInputCount: number = useAIAssistantStore(
selectPendingUserInputStreamCount,
);
const showHeaderPendingBadge =
pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
return (
<div className="header-right-section-container">
{isAIAssistantEnabled && !isDrawerOpen && (
<div className="header-ai-assistant-btn-container">
{showHeaderPendingBadge ? (
<span className="header-ai-assistant-btn__badge" aria-hidden>
<span className="header-ai-assistant-btn__pulse-dot">
<Dot size={36} />
</span>
</span>
) : null}
<Tooltip title="AI Assistant">
<Button
variant="solid"
color="secondary"
onClick={openAIAssistant}
aria-label={
showHeaderPendingBadge
? pendingUserInputCount === 1
? 'Open AI Assistant, 1 action needs your response'
: `Open AI Assistant, ${pendingUserInputCount} actions need your response`
: 'Open AI Assistant'
}
prefix={<Sparkles size={14} color="var(--primary)" />}
>
AI Assistant
</Button>
</Tooltip>
</div>
)}
{enableFeedback && isLicenseEnabled && (
<Popover
rootClassName="header-section-popover-root"
@@ -83,12 +130,13 @@ function HeaderRightSection({
onOpenChange={handleOpenFeedbackModalChange}
>
<Button
className="share-feedback-btn periscope-btn ghost"
icon={<SquarePen size={14} />}
variant="ghost"
size="icon"
className="share-feedback-btn"
aria-label="Feedback"
prefix={<SquarePen size={14} />}
onClick={handleOpenFeedbackModal}
>
Feedback
</Button>
/>
</Popover>
)}
@@ -105,9 +153,10 @@ function HeaderRightSection({
onOpenChange={handleOpenAnnouncementsModalChange}
>
<Button
variant="ghost"
size="icon"
aria-label="Announcements"
icon={<Inbox size={14} />}
className="periscope-btn ghost announcements-btn"
prefix={<Inbox size={14} />}
onClick={(): void => {
logEvent('Announcements: Clicked', {
page: location.pathname,
@@ -130,12 +179,12 @@ function HeaderRightSection({
onOpenChange={handleOpenShareURLModalChange}
>
<Button
className="share-link-btn periscope-btn ghost"
icon={<Globe size={14} />}
variant="ghost"
size="icon"
aria-label="Share"
prefix={<Globe size={14} />}
onClick={handleOpenShareURLModal}
>
Share
</Button>
/>
</Popover>
)}
</div>

View File

@@ -46,6 +46,10 @@ jest.mock('hooks/useGetTenantLicense', () => ({
useGetTenantLicense: jest.fn(),
}));
jest.mock('hooks/useIsAIAssistantEnabled', () => ({
useIsAIAssistantEnabled: (): boolean => false,
}));
const mockLogEvent = logEvent as jest.Mock;
const mockUseLocation = useLocation as jest.Mock;
const mockUseGetTenantLicense = useGetTenantLicense as jest.Mock;

View File

@@ -12,6 +12,7 @@ import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx';
import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';
import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml';
import a11yDark from 'react-syntax-highlighter/dist/esm/styles/prism/a11y-dark';
import oneLight from 'react-syntax-highlighter/dist/esm/styles/prism/one-light';
SyntaxHighlighter.registerLanguage('bash', bash);
SyntaxHighlighter.registerLanguage('docker', docker);
@@ -31,4 +32,4 @@ SyntaxHighlighter.registerLanguage('yaml', yaml);
SyntaxHighlighter.registerLanguage('yml', yaml);
export default SyntaxHighlighter;
export { a11yDark };
export { a11yDark, oneLight };

View File

@@ -41,4 +41,5 @@ export enum LOCALSTORAGE {
TRACE_DETAILS_PREFER_OLD_VIEW = 'TRACE_DETAILS_PREFER_OLD_VIEW',
LICENSE_KEY_CALLOUT_DISMISSED = 'LICENSE_KEY_CALLOUT_DISMISSED',
DASHBOARD_PREFERENCES = 'DASHBOARD_PREFERENCES',
ACTIVE_SIGNOZ_INSTANCE_URL = 'ACTIVE_SIGNOZ_INSTANCE_URL',
}

View File

@@ -88,6 +88,8 @@ const ROUTES = {
HOME_PAGE: '/',
PUBLIC_DASHBOARD: '/public/dashboard/:dashboardId',
SERVICE_ACCOUNTS_SETTINGS: '/settings/service-accounts',
AI_ASSISTANT: '/ai-assistant/:conversationId',
AI_ASSISTANT_ICON_PREVIEW: '/ai-assistant-icon-preview',
MCP_SERVER: '/settings/mcp-server',
} as const;

View File

@@ -0,0 +1,102 @@
import { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Drawer } from 'antd';
import ROUTES from 'constants/routes';
import { Maximize2, MessageSquare, Plus, X } from '@signozhq/icons';
import ConversationView from '../ConversationView';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
export default function AIAssistantDrawer(): JSX.Element {
const history = useHistory();
const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
);
const handleExpand = useCallback(() => {
if (!activeConversationId) {
return;
}
closeDrawer();
history.push(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
);
}, [activeConversationId, closeDrawer, history]);
const handleNewConversation = useCallback(() => {
startNewConversation();
}, [startNewConversation]);
return (
<Drawer
open={isDrawerOpen}
onClose={closeDrawer}
placement="right"
width={420}
// Suppress default close button — we render our own header
closeIcon={null}
title={
<div>
<div>
<MessageSquare size={16} />
<span>AI Assistant</span>
</div>
<div>
<Tooltip title="New conversation">
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={handleNewConversation}
aria-label="New conversation"
>
<Plus size={16} />
</Button>
</Tooltip>
<Tooltip title="Open full screen">
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={handleExpand}
disabled={!activeConversationId}
aria-label="Open full screen"
>
<Maximize2 size={16} />
</Button>
</Tooltip>
<Tooltip title="Close">
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={closeDrawer}
aria-label="Close drawer"
>
<X size={16} />
</Button>
</Tooltip>
</div>
</div>
}
>
<VariantContext.Provider value="panel">
{activeConversationId ? (
<ConversationView conversationId={activeConversationId} />
) : null}
</VariantContext.Provider>
</Drawer>
);
}

View File

@@ -0,0 +1,2 @@
export * from './AIAssistantDrawer';
export { default } from './AIAssistantDrawer';

View File

@@ -0,0 +1,98 @@
.backdrop {
position: fixed;
inset: 0;
z-index: 1050;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.45);
backdrop-filter: blur(2px);
animation: backdropIn 0.15s ease;
}
@keyframes backdropIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.modal {
display: flex;
flex-direction: column;
width: 70vw;
height: 80vh;
background: var(--l1-background);
border: 1px solid var(--l1-border);
border-radius: var(--radius-2);
overflow: hidden;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.35);
animation: modalIn 0.18s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes modalIn {
from {
opacity: 0;
transform: scale(0.96) translateY(-6px);
}
to {
opacity: 1;
transform: scale(1) translateY(0);
}
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
border-bottom: 1px solid var(--l1-border);
flex-shrink: 0;
background: var(--l1-background);
}
.title {
display: flex;
align-items: center;
gap: 7px;
font-size: 13px;
font-weight: 600;
color: var(--l1-foreground);
}
.shortcut {
font-size: 10px;
font-family: var(--font-mono, monospace);
font-weight: 500;
color: var(--l3-foreground);
background: var(--l2-background);
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
padding: 1px 5px;
letter-spacing: 0;
line-height: 1.6;
display: flex;
align-items: center;
gap: 4px;
}
.actions {
display: flex;
align-items: center;
gap: 2px;
}
.body {
flex: 1;
overflow: hidden;
display: flex;
flex-direction: column;
}
.toggleBtnActive {
background: var(--l2-background) !important;
color: var(--accent-primary) !important;
}

View File

@@ -0,0 +1,209 @@
import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useHistory } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Minus, Plus, Sparkles, X } from '@signozhq/icons';
import HistorySidebar from '../components/ConversationsList';
import ConversationView from '../ConversationView';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
import styles from './AIAssistantModal.module.scss';
/**
* Global floating modal for the AI Assistant.
*
* - Triggered by Cmd+J (Mac) / Ctrl+J (Windows/Linux)
* - Escape or the × button fully closes it
* - The (minimize) button collapses to the side panel
* - Mounted once in AppLayout; always in the DOM, conditionally visible
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
export default function AIAssistantModal(): JSX.Element | null {
const history = useHistory();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isModalOpen);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const openModal = useAIAssistantStore((s) => s.openModal);
const closeModal = useAIAssistantStore((s) => s.closeModal);
const minimizeModal = useAIAssistantStore((s) => s.minimizeModal);
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
// Cmd+J (Mac) / Ctrl+J (Win/Linux) — toggle modal. Opening
// always starts a brand-new conversation; resuming earlier
// threads is done via the in-modal history sidebar.
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'j') {
// Don't intercept Cmd+J inside input/textarea — those are for the user
const tag = (e.target as HTMLElement).tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') {
return;
}
e.preventDefault();
if (isOpen) {
closeModal();
} else {
startNewConversation();
setShowHistory(false);
openModal();
}
return;
}
// Escape — close modal
if (e.key === 'Escape' && isOpen) {
closeModal();
}
};
window.addEventListener('keydown', handleKeyDown);
return (): void => window.removeEventListener('keydown', handleKeyDown);
}, [isOpen, openModal, closeModal, startNewConversation]);
// ── Handlers ────────────────────────────────────────────────────────────────
const handleExpand = useCallback(() => {
if (!activeConversationId) {
return;
}
closeModal();
history.push(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
);
}, [activeConversationId, closeModal, history]);
const handleNew = useCallback(() => {
startNewConversation();
setShowHistory(false);
}, [startNewConversation]);
const handleHistorySelect = useCallback(() => {
setShowHistory(false);
}, []);
const handleMinimize = useCallback(() => {
minimizeModal();
setShowHistory(false);
}, [minimizeModal]);
const handleBackdropClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
// Only close when clicking the backdrop itself, not the modal card
if (e.target === e.currentTarget) {
closeModal();
}
},
[closeModal],
);
if (!isOpen) {
return null;
}
return createPortal(
<VariantContext.Provider value="modal">
<div
className={styles.backdrop}
role="dialog"
aria-modal="true"
aria-label="AI Assistant"
onClick={handleBackdropClick}
>
<div className={styles.modal}>
{/* Header */}
<div className={styles.header}>
<div className={styles.title}>
<Sparkles size={16} color="var(--primary)" />
<span>AI Assistant</span>
<kbd className={styles.shortcut}>
<span></span>
<span>J</span>
</kbd>
</div>
<div className={styles.actions}>
<Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
<Button
variant="ghost"
size="icon"
onClick={(): void => setShowHistory((v) => !v)}
aria-label="Toggle conversations"
className={showHistory ? styles.toggleBtnActive : ''}
>
<History size={14} />
</Button>
</Tooltip>
<Tooltip title="New conversation">
<Button
variant="ghost"
size="icon"
onClick={handleNew}
aria-label="New conversation"
>
<Plus size={14} />
</Button>
</Tooltip>
<Tooltip title="Open full screen">
<Button
variant="ghost"
size="icon"
onClick={handleExpand}
disabled={!activeConversationId}
aria-label="Open full screen"
>
<Maximize2 size={14} />
</Button>
</Tooltip>
<Tooltip title="Minimize to side panel">
<Button
variant="ghost"
size="icon"
onClick={handleMinimize}
aria-label="Minimize to side panel"
>
<Minus size={14} />
</Button>
</Tooltip>
<Tooltip title="Close">
<Button
variant="ghost"
size="icon"
onClick={closeModal}
aria-label="Close"
>
<X size={14} />
</Button>
</Tooltip>
</div>
</div>
{/* Body */}
<div className={styles.body}>
{showHistory ? (
<HistorySidebar onSelect={handleHistorySelect} />
) : (
activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)
)}
</div>
</div>
</div>
</VariantContext.Provider>,
document.body,
);
}

View File

@@ -0,0 +1,2 @@
export * from './AIAssistantModal';
export { default } from './AIAssistantModal';

View File

@@ -0,0 +1,60 @@
.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 {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px;
border-bottom: 1px solid var(--l1-border);
flex-shrink: 0;
background: var(--l1-background);
}
.title {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
font-weight: 600;
color: var(--l1-foreground);
}
.actions {
display: flex;
align-items: center;
gap: 2px;
}

View File

@@ -0,0 +1,189 @@
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
import { matchPath, useHistory, useLocation } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Plus, Sparkles, X } from '@signozhq/icons';
import ConversationsList from '../components/ConversationsList';
import ConversationView from '../ConversationView';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
import styles from './AIAssistantPanel.module.scss';
const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
export default function AIAssistantPanel(): JSX.Element | null {
const history = useHistory();
const { pathname } = useLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const isFullScreenPage = !!matchPath(pathname, {
path: ROUTES.AI_ASSISTANT,
exact: true,
});
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
);
const handleExpand = useCallback(() => {
if (!activeConversationId) {
return;
}
closeDrawer();
history.push(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
);
}, [activeConversationId, closeDrawer, history]);
const handleNew = useCallback(() => {
startNewConversation();
setShowHistory(false);
}, [startNewConversation]);
// When user picks a conversation from the list, close the sidebar
const handleHistorySelect = useCallback(() => {
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;
}
return (
<VariantContext.Provider value="panel">
<div className={styles.panel} style={{ width: panelWidth }}>
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div className={styles.resizeHandle} onMouseDown={handleResizeMouseDown} />
<div className={styles.header}>
<div className={styles.title}>
<Sparkles size={18} color="var(--primary)" />
<span>AI Assistant</span>
</div>
<div className={styles.actions}>
<Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={(): void => setShowHistory((v) => !v)}
aria-label="Toggle conversations"
>
<History size={14} />
</Button>
</Tooltip>
<Tooltip title="New conversation">
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={handleNew}
aria-label="New conversation"
>
<Plus size={14} />
</Button>
</Tooltip>
<Tooltip title="Open full screen">
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={handleExpand}
disabled={!activeConversationId}
aria-label="Open full screen"
>
<Maximize2 size={14} />
</Button>
</Tooltip>
<Tooltip title="Close">
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={closeDrawer}
aria-label="Close panel"
>
<X size={14} />
</Button>
</Tooltip>
</div>
</div>
{showHistory ? (
<ConversationsList onSelect={handleHistorySelect} />
) : (
activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)
)}
</div>
</VariantContext.Provider>
);
}

View File

@@ -0,0 +1,2 @@
export * from './AIAssistantPanel';
export { default } from './AIAssistantPanel';

View File

@@ -0,0 +1,32 @@
.trigger {
position: absolute;
bottom: 24px;
right: 24px;
z-index: 10;
width: 44px;
height: 44px;
border-radius: 50%;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
background: var(--accent-primary);
color: var(--accent-primary-foreground);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
transition:
transform 0.15s,
box-shadow 0.15s;
&:hover {
transform: scale(1.08);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.32);
}
&:active {
transform: scale(0.96);
}
}

View File

@@ -0,0 +1,45 @@
import { matchPath, useLocation } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { Bot } from '@signozhq/icons';
import {
openAIAssistant,
useAIAssistantStore,
} from '../store/useAIAssistantStore';
import styles from './AIAssistantTrigger.module.scss';
/**
* Floating action button anchored to the bottom-right of the content area.
* Hidden when the panel is already open or when on the full-screen AI Assistant page.
*/
export default function AIAssistantTrigger(): JSX.Element | null {
const { pathname } = useLocation();
const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const isModalOpen = useAIAssistantStore((s) => s.isModalOpen);
const isFullScreenPage = !!matchPath(pathname, {
path: ROUTES.AI_ASSISTANT,
exact: true,
});
if (isDrawerOpen || isModalOpen || isFullScreenPage) {
return null;
}
return (
<Tooltip title="AI Assistant">
<Button
variant="solid"
color="primary"
className={styles.trigger}
onClick={openAIAssistant}
aria-label="Open AI Assistant"
>
<Bot size={20} />
</Button>
</Tooltip>
);
}

View File

@@ -0,0 +1,2 @@
export * from './AIAssistantTrigger';
export { default } from './AIAssistantTrigger';

View File

@@ -0,0 +1,53 @@
.conversation {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.loading {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 13px;
color: var(--l3-foreground);
}
.spinner {
animation: spin 0.8s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.inputWrapper {
flex-shrink: 0;
padding: 12px;
border-top: 1px solid var(--l1-border);
&.compact {
padding: 8px;
}
}
.disclaimer {
flex-shrink: 0;
padding: 8px 16px;
font-size: 10px;
line-height: 1.4;
margin-top: 4px;
color: var(--l3-foreground);
text-align: center;
&.compact {
padding: 8px 12px;
}
}

View File

@@ -0,0 +1,155 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import cx from 'classnames';
import ChatInput, { autoContextKey } from '../components/ChatInput';
import ConversationSkeleton from '../components/ConversationSkeleton';
import VirtualizedMessages from '../components/VirtualizedMessages';
import { getAutoContexts } from '../getAutoContexts';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { MessageAttachment } from '../types';
import { MessageContext } from '../../../api/ai-assistant/chat';
import { useVariant } from '../VariantContext';
import styles from './ConversationView.module.scss';
interface ConversationViewProps {
conversationId: string;
}
export default function ConversationView({
conversationId,
}: ConversationViewProps): JSX.Element {
const variant = useVariant();
const isCompact = variant === 'panel';
const location = useLocation();
const conversation = useAIAssistantStore(
(s) => s.conversations[conversationId],
);
const isStreamingHere = useAIAssistantStore(
(s) => s.streams[conversationId]?.isStreaming ?? false,
);
const isLoadingThread = useAIAssistantStore((s) => s.isLoadingThread);
const pendingApprovalHere = useAIAssistantStore(
(s) => s.streams[conversationId]?.pendingApproval ?? null,
);
const pendingClarificationHere = useAIAssistantStore(
(s) => s.streams[conversationId]?.pendingClarification ?? null,
);
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const cancelStream = useAIAssistantStore((s) => s.cancelStream);
// Auto-derived contexts come from the route the user is currently looking
// at (dashboard detail, service metrics, an explorer, …). Skip when the
// user is on the standalone AI Assistant page — there's no "underlying"
// page context to attach. ChatInput renders these as chips and merges
// them with the user's `@`-mention picks before invoking onSend.
const allAutoContexts = useMemo(
() =>
variant === 'page'
? []
: getAutoContexts(location.pathname, location.search),
[variant, location.pathname, location.search],
);
// User-dismissed auto-context entries. Reset whenever the URL changes —
// dismissals are scoped to "this page", not the whole conversation.
const [dismissedAutoKeys, setDismissedAutoKeys] = useState<Set<string>>(
() => new Set(),
);
useEffect(() => {
setDismissedAutoKeys(new Set());
}, [location.pathname, location.search]);
const autoContexts = useMemo(
() =>
allAutoContexts.filter((ctx) => !dismissedAutoKeys.has(autoContextKey(ctx))),
[allAutoContexts, dismissedAutoKeys],
);
const handleDismissAutoContext = useCallback((key: string): void => {
setDismissedAutoKeys((prev) => {
const next = new Set(prev);
next.add(key);
return next;
});
}, []);
const handleSend = useCallback(
(
text: string,
attachments?: MessageAttachment[],
contexts?: MessageContext[],
) => {
void sendMessage(text, attachments, contexts);
},
[sendMessage],
);
const handleCancel = useCallback(() => {
cancelStream(conversationId);
}, [cancelStream, conversationId]);
const messages = conversation?.messages ?? [];
const showDisclaimer = messages.length > 0;
const inputDisabled =
isStreamingHere ||
isLoadingThread ||
Boolean(pendingApprovalHere) ||
Boolean(pendingClarificationHere);
const inputWrapperClass = cx(styles.inputWrapper, {
[styles.compact]: isCompact,
});
const disclaimerClass = cx(styles.disclaimer, {
[styles.compact]: isCompact,
});
// Cover the gap between rehydrate (empty primed entry) and the first
// loadThread response. `isHydrating` is set on the rehydrated conversation
// and cleared once fetchThreads resolves; `isLoadingThread` covers the
// per-thread fetch that follows. Together they keep the skeleton visible
// for persisted chats without flashing it on freshly-created ones.
const isHydrating = Boolean(conversation?.isHydrating);
if ((isLoadingThread || isHydrating) && messages.length === 0) {
return (
<div className={styles.conversation}>
<ConversationSkeleton />
<div className={inputWrapperClass}>
<ChatInput
onSend={handleSend}
disabled
autoContexts={autoContexts}
onDismissAutoContext={handleDismissAutoContext}
/>
</div>
</div>
);
}
return (
<div className={styles.conversation}>
<VirtualizedMessages
conversationId={conversationId}
messages={messages}
isStreaming={isStreamingHere}
/>
{showDisclaimer && (
<div className={disclaimerClass} role="note" aria-live="polite">
SigNoz AI can make mistakes. Please double-check responses.
</div>
)}
<div className={inputWrapperClass}>
<ChatInput
onSend={handleSend}
onCancel={handleCancel}
disabled={inputDisabled}
isStreaming={isStreamingHere}
autoContexts={autoContexts}
onDismissAutoContext={handleDismissAutoContext}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ConversationView';
export { default } from './ConversationView';

View File

@@ -0,0 +1,8 @@
// eslint-disable-next-line no-restricted-imports
import { createContext, useContext } from 'react';
export type AIAssistantVariant = 'panel' | 'page' | 'modal';
export const VariantContext = createContext<AIAssistantVariant>('page');
export const useVariant = (): AIAssistantVariant => useContext(VariantContext);

View File

@@ -0,0 +1,32 @@
@mixin scrollbar($width: 0.3rem) {
scrollbar-width: thin;
scrollbar-color: transparent transparent;
transition: scrollbar-color 0.2s;
&:hover {
scrollbar-color: var(--l3-border) transparent;
}
&::-webkit-scrollbar {
width: $width;
height: $width;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 999px;
transition: background 0.2s;
}
&:hover::-webkit-scrollbar-thumb {
background: var(--l3-border);
}
&::-webkit-scrollbar-thumb:hover {
background: var(--l3-foreground);
}
}

View File

@@ -0,0 +1,116 @@
.section {
display: flex;
flex-direction: column;
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
// block, so it matches the bubble's width by definition.
}
.heading {
display: flex;
align-items: center;
gap: 6px;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--l3-foreground);
}
.headingIcon {
color: var(--primary);
flex-shrink: 0;
}
.list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
background: var(--l1-background);
color: var(--l1-foreground);
font-size: 11px;
font-style: normal;
font-weight: 400;
line-height: 18px; /* 163.636% */
letter-spacing: -0.055px;
cursor: pointer;
transition:
background 0.12s ease,
border-color 0.12s ease,
color 0.12s ease;
&:hover:not(:disabled) {
background: var(--l2-background);
border-color: var(--l3-border);
}
&:disabled {
cursor: default;
opacity: 0.55;
}
&.error {
border-color: var(--accent-cherry);
color: var(--accent-cherry);
}
svg {
flex-shrink: 0;
color: var(--l3-foreground);
}
&:hover:not(:disabled) svg {
color: var(--accent-primary);
}
&.error svg {
color: var(--accent-cherry);
}
}
.spin {
color: var(--accent-primary) !important;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.chipLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 220px;
}
.chipState {
font-size: 10px;
font-weight: 500;
color: var(--l3-foreground);
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 1px 5px;
border: 1px solid var(--l2-border);
border-radius: 999px;
margin-left: 2px;
}

View File

@@ -0,0 +1,537 @@
import { useEffect, useState } from 'react';
import { matchPath, useHistory, useLocation } from 'react-router-dom';
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
import {
IBuilderQuery,
Query,
TagFilter,
} from 'types/api/queryBuilder/queryBuilderData';
import cx from 'classnames';
import { v4 as uuidv4 } from 'uuid';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
restoreExecution,
revertExecution,
undoExecution,
} from 'api/ai-assistant/chat';
import ROUTES from 'constants/routes';
import { QueryParams } from 'constants/query';
import { openInNewTab } from 'utils/navigation';
import {
ArchiveRestore,
BookOpen,
Check,
ExternalLink,
Eye,
Filter,
LoaderCircle,
MessageCircle,
RotateCcw,
Sparkles,
TriangleAlert,
Undo,
} from '@signozhq/icons';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import styles from './ActionsSection.module.scss';
interface ActionsSectionProps {
actions: MessageActionDTO[];
}
type ChipState = 'idle' | 'loading' | 'success' | 'error';
interface ChipResult {
state: ChipState;
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} />;
}
}
/**
* Resolves an `open_resource` action to an in-app route.
* Resource taxonomy mirrors `MessageContextDTOType`: dashboard, alert,
* saved_view, service, and the *_explorer signals.
*/
function resourceRoute(
resourceType: string,
resourceId: string,
): string | null {
switch (resourceType) {
case 'dashboard':
return ROUTES.DASHBOARD.replace(':dashboardId', resourceId);
case 'alert': {
const params = new URLSearchParams({ [QueryParams.ruleId]: resourceId });
return `${ROUTES.EDIT_ALERTS}?${params.toString()}`;
}
case 'service':
return ROUTES.SERVICE_METRICS.replace(':servicename', resourceId);
case 'saved_view':
// No detail route — saved views land on the list page.
// Caller may provide signal-aware metadata in future; default to logs.
return ROUTES.LOGS_SAVE_VIEWS;
case 'logs_explorer':
return ROUTES.LOGS_EXPLORER;
case 'traces_explorer':
return ROUTES.TRACES_EXPLORER;
case 'metrics_explorer':
return ROUTES.METRICS_EXPLORER_EXPLORER;
default:
return null;
}
}
/**
* The agent emits `action.query` as the SigNoz REST query-range request body:
*
* - V5 (current backend): `{ ..., compositeQuery: { queries: [{ type, spec }] } }`
* — each `spec` already carries `filter.expression` directly.
* - V3 (legacy): `{ ..., compositeQuery: { builderQueries: { A: {...} } } }`
*
* The URL's `compositeQuery` param expects the in-app shape
* (`{ queryType, builder: { queryData: [...], queryFormulas, queryTraceOperator }, ... }`).
* `mapQueryDataFromApi` already handles both API shapes for query-range
* responses, so we delegate to it instead of maintaining a parallel translator.
*
* Defensive: if the agent ever sends the URL shape directly (top-level
* `builder.queryData`), we pass it through unchanged.
*/
function toUrlCompositeQuery(
actionQuery: Record<string, unknown>,
): Record<string, unknown> | null {
// Already in URL shape — use as-is (with envelope defaults filled in).
if (
actionQuery.builder &&
typeof actionQuery.builder === 'object' &&
Array.isArray((actionQuery.builder as Record<string, unknown>).queryData)
) {
return {
queryType: actionQuery.queryType ?? 'builder',
promql: actionQuery.promql ?? [],
clickhouse_sql: actionQuery.clickhouse_sql ?? [],
id: uuidv4(),
unit: actionQuery.unit ?? '',
...actionQuery,
};
}
// API shape: extract the inner compositeQuery and let the shared mapper
// normalise V3/V5 spec → IBuilderQuery for us.
const composite = (actionQuery.compositeQuery ?? actionQuery) as
| Record<string, unknown>
| undefined;
if (!composite) {
return null;
}
try {
const mapped = mapQueryDataFromApi(
composite as unknown as ICompositeMetricQuery,
);
// `mapQueryDataFromApi` falls back to `initialQueryState.builder` when
// neither `queries` nor `builderQueries` is present — detect that and
// signal "unrecognised payload" instead of silently navigating to an
// empty query.
if (mapped.builder.queryData.length === 0) {
return null;
}
return mapped as unknown as Record<string, unknown>;
} catch {
return null;
}
}
/**
* Tracks apply_filter action keys that have already been auto-applied so we
* don't re-fire on re-renders / re-mounts. Module-level (intentionally) — it's
* not state we'd ever want to reset on a component unmount; the action's
* filters are already on the URL after the first auto-apply.
*/
const autoAppliedFilterKeys = new Set<string>();
/**
* True when the user is currently on the explorer that an apply_filter
* action targets — i.e. when auto-applying makes sense (the page is mounted
* and ready to react to a URL change without a route transition).
*/
function signalMatchesPathname(
signal: ApplyFilterSignalDTO,
pathname: string,
): boolean {
switch (signal) {
case ApplyFilterSignalDTO.logs:
return Boolean(
matchPath(pathname, { path: ROUTES.LOGS_EXPLORER, exact: false }),
);
case ApplyFilterSignalDTO.traces:
return Boolean(
matchPath(pathname, { path: ROUTES.TRACES_EXPLORER, exact: false }),
);
case ApplyFilterSignalDTO.metrics:
return Boolean(
matchPath(pathname, {
path: ROUTES.METRICS_EXPLORER_EXPLORER,
exact: false,
}),
);
default:
return false;
}
}
/**
* Stable per-action key used both to dedupe auto-applies and as the React key
* for the chip. Mirrors the same construction we do in the render loop below.
*/
function actionKey(action: MessageActionDTO, index: number): string {
return action.actionMetadataId
? `${action.kind}:${action.actionMetadataId}`
: `${action.kind}:${action.label}:${index}`;
}
/** Maps a signal to its target explorer route. */
function explorerRouteForSignal(signal: ApplyFilterSignalDTO): string | null {
switch (signal) {
case ApplyFilterSignalDTO.logs:
return ROUTES.LOGS_EXPLORER;
case ApplyFilterSignalDTO.traces:
return ROUTES.TRACES_EXPLORER;
case ApplyFilterSignalDTO.metrics:
return ROUTES.METRICS_EXPLORER_EXPLORER;
default:
return null;
}
}
interface ApplyFilterDeps {
history: ReturnType<typeof useHistory>;
pathname: string;
redirectWithQueryBuilderData: ReturnType<
typeof useQueryBuilder
>['redirectWithQueryBuilderData'];
handleSetQueryData: ReturnType<typeof useQueryBuilder>['handleSetQueryData'];
}
/**
* The V5 query-builder UI binds the WHERE clause CodeMirror editor to
* `builder.queryData[i].filter.expression`. The agent normally only sends
* `filters.items`, so we derive the expression per query before pushing
* state. Same recipe as `pages/<X>/aiActions.ts` — keeps the immediate
* UI update consistent with what the URL parser would produce on reload.
*/
function withDerivedFilterExpressions(query: Query): Query {
const queryData = query.builder.queryData.map((q): IBuilderQuery => {
const items = q.filters?.items ?? [];
if (items.length === 0) {
return q;
}
const filters: TagFilter = { items, op: q.filters?.op || 'AND' };
return {
...q,
filters,
filter: convertFiltersToExpression(filters),
};
});
return { ...query, builder: { ...query.builder, queryData } };
}
/**
* Single entry point for an apply_filter action — used by both the auto-apply
* effect (fired once when the user is already on the matching explorer) and
* the manual chip-click handler.
*
* - On-page: push each builder query into the QueryBuilder provider via
* `handleSetQueryData` so the WHERE clause re-renders immediately, then
* `redirectWithQueryBuilderData` to persist it on the URL. Mirrors the
* page-action recipe — calling redirect alone is not sufficient because
* the URL→state effect runs after the next render and the editor binds
* to `filter.expression`, not `filters.items`.
* - Off-page: use `history.push` so the landing explorer initializes from
* the new URL on mount.
*/
function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
// eslint-disable-next-line no-console
console.log('[apply_filter] enter', {
signal: action.signal,
query: action.query,
pathname: deps.pathname,
});
if (!action.signal || !action.query) {
// eslint-disable-next-line no-console
console.warn('[apply_filter] bail: missing signal or query', action);
return;
}
const urlQuery = toUrlCompositeQuery(action.query as Record<string, unknown>);
if (!urlQuery) {
// eslint-disable-next-line no-console
console.warn(
'[apply_filter] bail: toUrlCompositeQuery returned null — agent payload shape unrecognized',
action.query,
);
return;
}
const normalized = withDerivedFilterExpressions(urlQuery as unknown as Query);
// eslint-disable-next-line no-console
console.log('[apply_filter] normalized', normalized);
if (signalMatchesPathname(action.signal, deps.pathname)) {
// eslint-disable-next-line no-console
console.log('[apply_filter] on-page → handleSetQueryData + redirect');
normalized.builder.queryData.forEach((q, i) => {
deps.handleSetQueryData(i, q);
});
deps.redirectWithQueryBuilderData(normalized);
return;
}
const base = explorerRouteForSignal(action.signal);
if (!base) {
// eslint-disable-next-line no-console
console.warn('[apply_filter] bail: no route for signal', action.signal);
return;
}
// eslint-disable-next-line no-console
console.log('[apply_filter] off-page → history.push', base);
const encoded = encodeURIComponent(JSON.stringify(normalized));
deps.history.push(`${base}?${QueryParams.compositeQuery}=${encoded}`);
}
/** Picks the right rollback API call for a given action kind. */
function rollbackCall(
kind: MessageActionDTO['kind'],
): ((id: string) => Promise<unknown>) | null {
switch (kind) {
case MessageActionKindDTO.undo:
return undoExecution;
case MessageActionKindDTO.revert:
return revertExecution;
case MessageActionKindDTO.restore:
return restoreExecution;
default:
return null;
}
}
/**
* Renders the actions attached to a single assistant message.
*
* Hidden when the message has no actions. Rendered inside `MessageBubble`
* between the message body and the feedback bar.
*/
export default function ActionsSection({
actions,
}: ActionsSectionProps): JSX.Element | null {
const history = useHistory();
const { pathname } = useLocation();
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const { redirectWithQueryBuilderData, handleSetQueryData } = useQueryBuilder();
// Per-chip click state, keyed by chip key (see `key` below). Persists
// loading/success/error so the chip reflects the rollback outcome until
// the underlying action.state catches up via a fresh thread fetch.
const [results, setResults] = useState<Record<string, ChipResult>>({});
// Auto-apply any apply_filter action whose signal matches the page the
// user is currently on (logs/traces/metrics explorer). Same code path as
// the manual click below — just fired automatically once. The chip stays
// clickable as a fallback for the off-page case. Dedupes via a module-
// level set so re-renders / re-mounts don't re-fire.
useEffect(() => {
actions.forEach((action, i) => {
if (action.kind !== MessageActionKindDTO.apply_filter) {
return;
}
if (!action.signal || !action.query) {
return;
}
if (!signalMatchesPathname(action.signal, pathname)) {
return;
}
const key = actionKey(action, i);
if (autoAppliedFilterKeys.has(key)) {
return;
}
autoAppliedFilterKeys.add(key);
applyFilter(action, {
history,
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
});
});
}, [
actions,
pathname,
history,
redirectWithQueryBuilderData,
handleSetQueryData,
]);
if (actions.length === 0) {
return null;
}
const setResult = (key: string, result: ChipResult): void => {
setResults((prev) => ({ ...prev, [key]: result }));
};
const runRollback = async (
key: string,
action: MessageActionDTO,
): Promise<void> => {
const call = rollbackCall(action.kind);
if (!call || !action.actionMetadataId) {
return;
}
setResult(key, { state: 'loading' });
try {
await call(action.actionMetadataId);
setResult(key, { state: 'success' });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed';
setResult(key, { state: 'error', error: message });
}
};
const handleClick = (key: string, action: MessageActionDTO): void => {
switch (action.kind) {
case MessageActionKindDTO.open_docs: {
if (action.url) {
openInNewTab(action.url);
}
break;
}
case MessageActionKindDTO.follow_up: {
if (action.label) {
void sendMessage(action.label);
}
break;
}
case MessageActionKindDTO.open_resource: {
if (action.resourceType && action.resourceId) {
const path = resourceRoute(action.resourceType, action.resourceId);
if (path) {
history.push(path);
}
}
break;
}
case MessageActionKindDTO.undo:
case MessageActionKindDTO.revert:
case MessageActionKindDTO.restore: {
void runRollback(key, action);
break;
}
case MessageActionKindDTO.apply_filter: {
applyFilter(action, {
history,
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
});
break;
}
default:
break;
}
};
return (
<div className={styles.section}>
<div className={styles.heading}>
<Sparkles size={12} className={styles.headingIcon} />
<span className={styles.headingText}>Suggested actions</span>
</div>
<div className={styles.list}>
{actions.map((action, i) => {
// Stable per-action key (shared with the auto-apply dedupe set).
// `actionMetadataId` alone isn't unique — the server can attach
// the same id to multiple kinds (e.g. an `undo` and `revert` chip
// for the same operation), so we always include the kind. Falls
// back to label + index when the id is missing (e.g. follow_up /
// open_docs).
const key = actionKey(action, i);
const result = results[key];
const isLoading = result?.state === 'loading';
const isSuccess = result?.state === 'success';
const isError = result?.state === 'error';
// `action.state` is a free-form string from the server (e.g. "active",
// "applied"). Without a documented terminal vocabulary we don't auto-
// disable on it — only the local in-flight click result does. The state
// is still surfaced visually via the suffix pill below.
const isDisabled = isLoading || isSuccess;
const tooltip = isError ? result.error : (action.tooltip ?? undefined);
let icon: JSX.Element;
if (isLoading) {
icon = <LoaderCircle size={12} className={styles.spin} />;
} else if (isSuccess) {
icon = <Check size={12} />;
} else if (isError) {
icon = <TriangleAlert size={12} />;
} else {
icon = <ActionIcon kind={action.kind} />;
}
const chip = (
<Button
variant="outlined"
color="secondary"
size="sm"
className={cx(styles.chip, { [styles.error]: isError })}
onClick={(): void => handleClick(key, action)}
disabled={isDisabled}
aria-label={action.label}
prefix={icon}
>
<span className={styles.chipLabel}>{action.label}</span>
</Button>
);
return tooltip ? (
<Tooltip key={key} title={tooltip}>
{chip}
</Tooltip>
) : (
<span key={key}>{chip}</span>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ActionsSection';
export { default } from './ActionsSection';

View File

@@ -0,0 +1,282 @@
@use '../../_scrollbar' as *;
.card {
border: 1px solid var(--l1-border);
border-radius: var(--radius-2);
padding: 12px;
background: var(--l1-background);
display: flex;
flex-direction: column;
gap: 16px;
width: 100%;
&.decided {
border-color: var(--l2-border);
background: transparent;
flex-direction: row;
align-items: center;
gap: 6px;
padding: 6px 10px;
}
}
.header {
display: flex;
align-items: center;
gap: 6px;
}
.shieldIcon {
flex-shrink: 0;
color: var(--primary);
}
.headerLabel {
font-size: 12px;
font-weight: 600;
color: var(--l1-foreground);
}
.resourceBadge {
margin-left: auto;
font-size: 10px;
font-family: var(--font-mono, monospace);
background: var(--l2-background);
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
padding: 1px 5px;
color: var(--l2-foreground);
}
.summary {
font-size: 13px;
color: var(--l1-foreground);
margin: 0;
line-height: 1.5;
}
.diffSection {
display: flex;
flex-direction: column;
gap: 6px;
}
.diffHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.diffHeaderLabel {
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--l2-foreground);
}
.diff {
display: flex;
gap: 8px;
// Fixed-height dialog (70vh) — let the diff fill the body and the
// JSON panes scroll internally rather than pushing the dialog taller.
&.expanded {
flex: 1;
min-height: 0;
.diffBlock {
min-height: 0;
}
.diffJson {
flex: 1;
max-height: none;
overflow: auto;
font-size: 12px;
}
}
// Unified view: a single column instead of two side-by-side blocks.
// The block-level flex switches to column so the diff pane fills.
&.unified {
flex-direction: column;
}
}
.diffHeaderActions {
display: flex;
align-items: center;
gap: 4px;
}
// Container for line-by-line diff output. Mirrors `.diffJson` for scroll
// + monospace styling but renders an inner stack of `.diffLine` rows
// instead of a single `<pre>` so individual lines can be colored.
.diffPane {
font-family: var(--font-mono, monospace);
font-size: 12px;
background: var(--l2-background);
border-radius: var(--radius-2);
margin: 0;
overflow: auto;
color: var(--l2-foreground);
flex: 1;
min-height: 0;
@include scrollbar(0.4rem);
&.wrapped .diffLineText {
white-space: pre-wrap;
word-break: break-word;
}
}
.diffLine {
display: flex;
align-items: flex-start;
gap: 6px;
padding: 0 8px;
min-height: 18px;
line-height: 1.5;
}
.diffLineAdd {
background: color-mix(in srgb, var(--accent-forest), transparent 88%);
color: var(--l1-foreground);
.diffGutter {
color: var(--accent-forest);
}
}
.diffLineRemove {
background: color-mix(in srgb, var(--accent-cherry), transparent 88%);
color: var(--l1-foreground);
.diffGutter {
color: var(--accent-cherry);
}
}
// Empty filler row in split view to keep before/after columns aligned
// when one side has an added/removed line. Visible as a faint band so
// the eye still tracks the row.
.diffLinePlaceholder {
background: color-mix(in srgb, var(--l3-foreground), transparent 94%);
min-height: 18px;
}
.diffGutter {
flex-shrink: 0;
width: 12px;
text-align: center;
font-weight: 600;
user-select: none;
color: var(--l3-foreground);
}
.diffLineText {
white-space: pre;
flex: 1;
min-width: 0;
}
.diffBlock {
flex: 1;
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
&.before .diffLabel {
color: var(--accent-cherry);
}
&.after .diffLabel {
color: var(--accent-forest);
}
}
.diffBlockHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-height: 18px;
}
.diffLabel {
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.diffJson {
font-family: var(--font-mono, monospace);
font-size: 11px;
background: var(--l2-background);
border-radius: var(--radius-2);
padding: 5px 7px;
margin: 0;
overflow: auto;
white-space: pre;
max-height: 140px;
color: var(--l2-foreground);
@include scrollbar(0.4rem);
// Wrap long lines instead of horizontal scrolling. Used in the
// expanded modal when the user toggles the "Wrap text" button.
&.wrapped {
white-space: pre-wrap;
word-break: break-word;
overflow-x: hidden;
}
}
.diffModalBody {
display: flex;
flex-direction: column;
gap: 12px;
flex: 1;
min-height: 0;
padding: 16px;
overflow: hidden;
}
.diffToolbarRow {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.diffModalSummary {
font-size: 13px;
color: var(--l2-foreground);
margin: 0;
line-height: 1.5;
flex-shrink: 0;
}
.actions {
display: flex;
gap: 6px;
}
.statusIcon {
flex-shrink: 0;
&.ok {
color: var(--accent-forest);
}
&.no {
color: var(--l3-foreground);
}
}
.statusText {
font-size: 13px;
color: var(--l2-foreground);
}

View File

@@ -0,0 +1,471 @@
import { useEffect, useRef, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import cx from 'classnames';
import { Button } from '@signozhq/ui/button';
import {
Dialog,
DialogCloseButton,
DialogContent,
DialogHeader,
DialogSubtitle,
DialogTitle,
} from '@signozhq/ui/dialog';
import { ToggleGroup, ToggleGroupItem } from '@signozhq/ui/toggle-group';
import type {
ApprovalEventDTO,
ApprovalEventDTODiff,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
Check,
Columns2,
Copy,
List,
Maximize2,
Shield,
WrapText,
X,
} from '@signozhq/icons';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import styles from './ApprovalCard.module.scss';
interface ApprovalCardProps {
conversationId: string;
approval: ApprovalEventDTO;
}
/**
* Rendered when the agent emits an `approval` SSE event.
* The agent has paused execution; the user must approve or reject
* before the stream resumes on a new execution.
*/
export default function ApprovalCard({
conversationId,
approval,
}: ApprovalCardProps): JSX.Element {
const approveAction = useAIAssistantStore((s) => s.approveAction);
const rejectAction = useAIAssistantStore((s) => s.rejectAction);
const isStreaming = useAIAssistantStore(
(s) => s.streams[conversationId]?.isStreaming ?? false,
);
const [decided, setDecided] = useState<'approved' | 'rejected' | null>(null);
const [diffExpanded, setDiffExpanded] = useState(false);
const [wrapText, setWrapText] = useState(false);
const [viewMode, setViewMode] = useState<DiffViewMode>('split');
const handleApprove = async (): Promise<void> => {
setDecided('approved');
await approveAction(conversationId, approval.approvalId);
};
const handleReject = async (): Promise<void> => {
setDecided('rejected');
await rejectAction(conversationId, approval.approvalId);
};
// After decision the card shows a compact confirmation row
if (decided === 'approved') {
return (
<div className={cx(styles.card, styles.decided)}>
<Check size={13} className={cx(styles.statusIcon, styles.ok)} />
<span className={styles.statusText}>Approved resuming</span>
</div>
);
}
if (decided === 'rejected') {
return (
<div className={cx(styles.card, styles.decided)}>
<X size={13} className={cx(styles.statusIcon, styles.no)} />
<span className={styles.statusText}>Rejected.</span>
</div>
);
}
return (
<div className={styles.card}>
<div className={styles.header}>
<Shield size={13} className={styles.shieldIcon} />
<span className={styles.headerLabel}>Action requires approval</span>
<span className={styles.resourceBadge}>
{approval.actionType} · {approval.resourceType}
</span>
</div>
<p className={styles.summary}>{approval.summary}</p>
{approval.diff && (
<div className={styles.diffSection}>
<div className={styles.diffHeader}>
<span className={styles.diffHeaderLabel}>Diff</span>
<Button
variant="link"
size="sm"
color="secondary"
onClick={(): void => setDiffExpanded(true)}
title="Expand diff"
aria-label="Expand diff"
>
<Maximize2 size={12} />
</Button>
</div>
<DiffView diff={approval.diff} />
</div>
)}
<Dialog open={diffExpanded} onOpenChange={setDiffExpanded}>
<DialogContent
className={styles.diffDialog}
style={{ width: '80vw', maxWidth: '80vw', height: '70vh' }}
>
<DialogHeader>
<DialogTitle>Approval diff</DialogTitle>
<DialogSubtitle>
{approval.actionType} · {approval.resourceType}
</DialogSubtitle>
</DialogHeader>
<div className={styles.diffModalBody}>
<p className={styles.diffModalSummary}>{approval.summary}</p>
<div className={styles.diffToolbarRow}>
<ToggleGroup
type="single"
size="sm"
value={viewMode}
onChange={(next): void => {
// Radix `single` group can emit '' when the active item
// is clicked again — preserve the current mode.
if (next === 'split' || next === 'unified') {
setViewMode(next);
}
}}
>
<ToggleGroupItem value="split" aria-label="Split view">
<Columns2 size={12} />
</ToggleGroupItem>
<ToggleGroupItem value="unified" aria-label="Unified view">
<List size={12} />
</ToggleGroupItem>
</ToggleGroup>
<ToggleGroup
type="multiple"
size="sm"
value={wrapText ? ['wrap'] : []}
onChange={(next): void => setWrapText(next.includes('wrap'))}
>
<ToggleGroupItem
value="wrap"
aria-label={wrapText ? 'Disable text wrap' : 'Wrap long lines'}
>
<WrapText size={12} />
</ToggleGroupItem>
</ToggleGroup>
</div>
{approval.diff && (
<DiffView
diff={approval.diff}
expanded
wrapText={wrapText}
viewMode={viewMode}
/>
)}
</div>
<DialogCloseButton onClick={(): void => setDiffExpanded(false)} />
</DialogContent>
</Dialog>
<div className={styles.actions}>
<Button
variant="solid"
size="sm"
onClick={handleApprove}
disabled={isStreaming}
prefix={<Check />}
>
Approve
</Button>
<Button
variant="outlined"
size="sm"
color="secondary"
onClick={handleReject}
disabled={isStreaming}
prefix={<X />}
>
Reject
</Button>
</div>
</div>
);
}
type DiffViewMode = 'split' | 'unified';
interface DiffViewProps {
diff: ApprovalEventDTODiff;
expanded?: boolean;
/** When true, long lines wrap instead of horizontally scrolling. */
wrapText?: boolean;
/** Side-by-side ('split') vs single-column ('unified'). Only honored when expanded. */
viewMode?: DiffViewMode;
}
function DiffView({
diff,
expanded = false,
wrapText = false,
viewMode = 'split',
}: DiffViewProps): JSX.Element {
const beforeText =
diff.before !== undefined ? JSON.stringify(diff.before, null, 2) : '';
const afterText =
diff.after !== undefined ? JSON.stringify(diff.after, null, 2) : '';
// In the inline (collapsed) preview keep the original two-pane layout
// without diff highlighting — diffing is opt-in via the expanded modal.
if (!expanded) {
const jsonClass = cx(styles.diffJson, { [styles.wrapped]: wrapText });
return (
<div className={styles.diff}>
{diff.before !== undefined && (
<div className={cx(styles.diffBlock, styles.before)}>
<div className={styles.diffBlockHeader}>
<span className={styles.diffLabel}>Before</span>
</div>
<pre className={jsonClass}>{beforeText}</pre>
</div>
)}
{diff.after !== undefined && (
<div className={cx(styles.diffBlock, styles.after)}>
<div className={styles.diffBlockHeader}>
<span className={styles.diffLabel}>After</span>
</div>
<pre className={jsonClass}>{afterText}</pre>
</div>
)}
</div>
);
}
const lines = computeLineDiff(beforeText, afterText);
if (viewMode === 'unified') {
// Build the same +/-/space-prefixed text that's on screen so Copy
// gives the user exactly what they see.
const unifiedText = lines
.map((line) => `${prefixFor(line.op)} ${line.text}`)
.join('\n');
return (
<div className={cx(styles.diff, styles.expanded, styles.unified)}>
<div className={styles.diffBlockHeader}>
<span className={styles.diffLabel}>Diff</span>
<div className={styles.diffHeaderActions}>
<CopyButton text={unifiedText} label="diff" />
</div>
</div>
<div className={cx(styles.diffPane, { [styles.wrapped]: wrapText })}>
{lines.map((line, idx) => (
<DiffLine
// stable enough — input strings are immutable for the view's lifetime
// eslint-disable-next-line react/no-array-index-key
key={idx}
op={line.op}
text={line.text}
prefix={prefixFor(line.op)}
/>
))}
</div>
</div>
);
}
// Split view: align side-by-side using the LCS result. `equal` lines
// appear on both sides; `remove` only on the left, `add` only on the
// right (with an empty placeholder on the missing side so rows stay
// aligned vertically).
return (
<div className={cx(styles.diff, styles.expanded)}>
<div className={cx(styles.diffBlock, styles.before)}>
<div className={styles.diffBlockHeader}>
<span className={styles.diffLabel}>Before</span>
<CopyButton text={beforeText} label="before" />
</div>
<div className={cx(styles.diffPane, { [styles.wrapped]: wrapText })}>
{lines.map((line, idx) => {
const op = line.op === 'add' ? 'placeholder' : line.op;
const text = line.op === 'add' ? '' : line.text;
// eslint-disable-next-line react/no-array-index-key
return <DiffLine key={idx} op={op} text={text} />;
})}
</div>
</div>
<div className={cx(styles.diffBlock, styles.after)}>
<div className={styles.diffBlockHeader}>
<span className={styles.diffLabel}>After</span>
<CopyButton text={afterText} label="after" />
</div>
<div className={cx(styles.diffPane, { [styles.wrapped]: wrapText })}>
{lines.map((line, idx) => {
const op = line.op === 'remove' ? 'placeholder' : line.op;
const text = line.op === 'remove' ? '' : line.text;
// eslint-disable-next-line react/no-array-index-key
return <DiffLine key={idx} op={op} text={text} />;
})}
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Line diff — small LCS-based implementation. Avoids pulling in `diff`
// since the inputs are JSON.stringify output (line-oriented, typically
// well under a few hundred lines for resource diffs).
// ---------------------------------------------------------------------------
type LineOp = 'equal' | 'add' | 'remove';
type RenderOp = LineOp | 'placeholder';
interface DiffLineEntry {
op: LineOp;
text: string;
}
// eslint-disable-next-line sonarjs/cognitive-complexity
function computeLineDiff(before: string, after: string): DiffLineEntry[] {
if (before === after) {
return splitLines(before).map((text) => ({ op: 'equal', text }));
}
const a = splitLines(before);
const b = splitLines(after);
const m = a.length;
const n = b.length;
// dp[i][j] = length of LCS between a[0..i] and b[0..j]
const dp: number[][] = Array.from({ length: m + 1 }, () =>
new Array<number>(n + 1).fill(0),
);
for (let i = 1; i <= m; i += 1) {
for (let j = 1; j <= n; j += 1) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// Backtrack to produce the diff
const result: DiffLineEntry[] = [];
let i = m;
let j = n;
while (i > 0 && j > 0) {
if (a[i - 1] === b[j - 1]) {
result.push({ op: 'equal', text: a[i - 1] });
i -= 1;
j -= 1;
} else if (dp[i - 1][j] >= dp[i][j - 1]) {
result.push({ op: 'remove', text: a[i - 1] });
i -= 1;
} else {
result.push({ op: 'add', text: b[j - 1] });
j -= 1;
}
}
while (i > 0) {
result.push({ op: 'remove', text: a[i - 1] });
i -= 1;
}
while (j > 0) {
result.push({ op: 'add', text: b[j - 1] });
j -= 1;
}
result.reverse();
return result;
}
function splitLines(text: string): string[] {
if (text === '') {
return [];
}
return text.split('\n');
}
function prefixFor(op: LineOp): string {
if (op === 'add') {
return '+';
}
if (op === 'remove') {
return '-';
}
return ' ';
}
interface DiffLineProps {
op: RenderOp;
text: string;
/** Optional gutter prefix used in unified view (`+` / `-` / ` `). */
prefix?: string;
}
function DiffLine({ op, text, prefix }: DiffLineProps): JSX.Element {
const cls = cx(styles.diffLine, {
[styles.diffLineAdd]: op === 'add',
[styles.diffLineRemove]: op === 'remove',
[styles.diffLinePlaceholder]: op === 'placeholder',
});
return (
<div className={cls}>
{prefix !== undefined && (
<span className={styles.diffGutter} aria-hidden="true">
{prefix}
</span>
)}
<span className={styles.diffLineText}>{text || ' '}</span>
</div>
);
}
interface CopyButtonProps {
text: string;
label: string;
}
function CopyButton({ text, label }: CopyButtonProps): JSX.Element {
const [copied, setCopied] = useState(false);
const [, copyToClipboard] = useCopyToClipboard();
// Track the timeout so an unmount mid-flight doesn't try to setState on
// a dead component (and so a rapid re-click resets the 1.5s window).
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => (): void => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
},
[],
);
const handleCopy = (): void => {
copyToClipboard(text);
setCopied(true);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => setCopied(false), 1500);
};
return (
<Button
variant="ghost"
size="sm"
color="secondary"
onClick={handleCopy}
title={copied ? `Copied ${label}` : `Copy ${label}`}
aria-label={copied ? `Copied ${label}` : `Copy ${label}`}
>
{copied ? <Check size={12} /> : <Copy size={12} />}
</Button>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ApprovalCard';
export { default } from './ApprovalCard';

View File

@@ -0,0 +1,462 @@
@use '../../_scrollbar' as *;
.input {
display: flex;
flex-direction: column;
gap: 10px;
background: var(--l1-background);
border-radius: var(--radius-2);
padding: 8px;
border: 1px solid var(--l1-border);
transition: border-color 0.15s;
position: relative;
&:focus-within {
border-color: var(--l1-border);
}
}
.attachments {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.contextTags {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.contextTag {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 11px;
background: var(--l2-background);
border: 1px solid var(--l1-border);
border-radius: var(--radius-2);
padding: 4px 6px 4px 8px;
color: var(--l1-foreground);
button {
height: auto !important;
min-height: 0 !important;
width: auto !important;
}
// `auto` chips are derived from the URL (current page) — visually
// distinguished by a dashed border + slightly muted text so the user
// can tell them apart from explicit @-mentions. Tighter padding /
// font-size keeps them visually subordinate to user `@`-picks.
&.auto {
border-style: dashed;
color: var(--l2-foreground);
background: transparent;
font-size: 10px;
padding: 2px 4px 2px 6px;
gap: 3px;
}
}
.contextTagContent {
display: flex;
align-items: center;
gap: 8px;
max-width: 220px;
.contextTagCategory {
flex-shrink: 0;
}
.contextTagLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.contextTagCategory {
flex-shrink: 0;
}
.contextTagLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.contextTagRemove {
flex-shrink: 0;
padding: 0 !important;
height: auto !important;
min-height: 0 !important;
}
.attachmentChip {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 11px;
background: var(--l3-background);
border-radius: var(--radius-2);
padding: 2px 6px 2px 8px;
color: var(--l2-foreground);
max-width: 180px;
}
.attachmentName {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.attachmentRemove {
flex-shrink: 0;
padding: 0 !important;
height: auto !important;
min-height: 0 !important;
}
.row {
display: flex;
align-items: center;
gap: 8px;
}
.composer {
background: var(--l2-background);
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
padding: 4px;
}
.footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.leftActions,
.rightActions {
display: flex;
align-items: center;
gap: 8px;
}
.attachBtn {
color: var(--l3-foreground);
}
.contextBtn {
flex-shrink: 0;
gap: 6px;
border-style: dashed !important;
padding-inline: 12px !important;
}
.textarea {
display: block;
width: 100%;
background: transparent;
border: none;
outline: none;
resize: none;
color: var(--l1-foreground);
font-size: 12px;
line-height: 1.5;
overflow-y: auto;
font-family: inherit;
@include scrollbar(0.2rem);
&::placeholder {
color: var(--l3-foreground);
opacity: 0.6;
}
&:disabled {
opacity: 0.2;
cursor: not-allowed;
}
}
.charWarning {
display: inline-flex;
align-items: center;
gap: 6px;
width: 100%;
padding: 6px 8px;
font-size: 11px;
font-weight: 500;
color: var(--accent-sienna);
background: color-mix(in srgb, var(--accent-sienna), transparent 90%);
border: 1px solid color-mix(in srgb, var(--accent-sienna), transparent 65%);
border-radius: var(--radius-2);
}
.sendBtn {
flex-shrink: 0;
border-radius: var(--radius-2);
&.stop {
background: var(--accent-cherry) !important;
border-color: var(--accent-cherry) !important;
&:hover {
opacity: 0.85;
}
}
}
.contextPopover {
width: 480px !important;
max-width: min(92vw, 480px);
margin-left: 16px;
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
background: var(--l1-background);
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-padding: 0;
z-index: 1000;
}
.contextPopoverContent {
display: grid;
grid-template-columns: 180px 1fr;
min-height: 250px;
min-width: 0;
}
.contextPopoverCategories {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
border-right: 1px solid var(--l2-border);
}
.contextPopoverCategoryItem {
display: flex;
align-items: center;
gap: 8px;
height: 32px;
padding: 0 8px;
border: 1px solid color-mix(in srgb, var(--l1-foreground), transparent 96%);
border-radius: var(--radius-2);
font-size: 12px;
font-weight: 550;
text-align: left;
cursor: pointer;
transition:
background 0.15s ease,
border-color 0.15s ease,
color 0.15s ease;
&:hover {
background: var(--l2-background);
color: var(--l1-foreground);
border-color: var(--l2-border);
}
&.active {
background: color-mix(in srgb, var(--accent-primary), transparent 86%);
color: var(--l1-foreground);
border-color: color-mix(in srgb, var(--accent-primary), transparent 64%);
}
}
.contextPopoverRight {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
// Match the previous fixed entity-list height so the inner search +
// scrolling list have a definite container to size against.
height: 320px;
}
.contextPopoverSearch {
padding: 8px;
flex-shrink: 0;
position: relative;
width: 90%;
}
.contextPopoverSearchInput {
width: 100%;
box-sizing: border-box;
}
.contextPopoverEntities {
display: flex;
flex-direction: column;
gap: 6px;
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
padding: 8px;
min-width: 0;
@include scrollbar(0.2rem);
}
.contextPopoverEntityItem {
display: flex;
align-items: center;
gap: 10px;
padding: 8px;
border: 1px solid color-mix(in srgb, var(--l1-foreground), transparent 96%);
border-radius: var(--radius-2);
color: var(--l1-foreground);
font-size: 12px;
font-weight: 500;
line-height: 1.35;
text-align: left;
cursor: pointer;
// Required for the inner span's `text-overflow: ellipsis` to engage —
// flex items default to `min-width: auto` (intrinsic width) and would
// otherwise grow past their parent's width to fit long titles.
min-width: 0;
transition:
background 0.15s ease,
border-color 0.15s ease,
transform 0.15s ease;
&:hover {
background: var(--l2-background);
border-color: var(--l2-border);
transform: translateY(-1px);
}
&.selected {
background: color-mix(in srgb, var(--accent-primary), transparent 86%);
border-color: color-mix(in srgb, var(--accent-primary), transparent 64%);
span {
color: var(--l1-foreground);
font-weight: 600;
}
}
}
.contextPopoverEntityItemText {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.contextPopoverEmpty {
font-size: 12px;
color: var(--l3-foreground);
padding: 10px 8px;
}
.micBtn {
flex-shrink: 0;
}
.micRecording {
display: flex;
align-items: center;
background: var(--l2-background);
border-radius: 999px;
padding: 2px;
gap: 0;
flex-shrink: 0;
}
.micDiscard,
.micStop {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 24px;
height: 24px;
border-radius: 50%;
border: none;
cursor: pointer;
}
.micDiscard {
background: var(--l2-background);
color: var(--l2-foreground);
transition: color 0.12s;
&:hover {
color: var(--l1-foreground);
}
}
.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;
}
}
.micStop {
background: var(--accent-cherry);
color: var(--accent-cherry-foreground);
transition: opacity 0.12s;
&:hover {
opacity: 0.85;
}
}

View File

@@ -0,0 +1,944 @@
import { useCallback, useEffect, useRef, useState } 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 { Tooltip } from '@signozhq/ui/tooltip';
import type { UploadFile } from 'antd';
import {
getListRulesQueryKey,
useListRules,
} from 'api/generated/services/rules';
import type { ListRules200 } from 'api/generated/services/sigNoz.schemas';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useGetAllDashboard } from 'hooks/dashboard/useGetAllDashboard';
import { useQueryService } from 'hooks/useQueryService';
import type { SuccessResponseV2 } from 'types/api';
import type { Dashboard } from 'types/api/dashboard/getAll';
// eslint-disable-next-line
import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
import { useSpeechRecognition } from '../../hooks/useSpeechRecognition';
import { MessageAttachment } from '../../types';
import { MessageContext } from '../../../../api/ai-assistant/chat';
import {
Bell,
LayoutDashboard,
Mic,
Plus,
Search,
Send,
ShieldCheck,
Square,
TriangleAlert,
X,
} from '@signozhq/icons';
import styles from './ChatInput.module.scss';
interface ChatInputProps {
onSend: (
text: string,
attachments?: MessageAttachment[],
contexts?: MessageContext[],
) => void;
onCancel?: () => void;
disabled?: boolean;
isStreaming?: boolean;
/**
* URL-derived `source: 'auto'` contexts representing the page the user is
* currently looking at. Rendered as chips alongside the user's `@`-mention
* picks and merged into the outgoing `contexts` array.
*/
autoContexts?: MessageContext[];
/**
* Called when the user dismisses an auto-context chip. The parent owns
* the dismissed set and is responsible for filtering the next render's
* `autoContexts` to exclude the key.
*/
onDismissAutoContext?: (key: string) => void;
}
/** Stable identity for an auto-context entry — used as React key + dismissal id. */
export function autoContextKey(ctx: MessageContext): string {
const page = (ctx.metadata as { page?: string } | null | undefined)?.page;
return `auto:${ctx.type}:${ctx.resourceId ?? ''}:${page ?? ''}`;
}
/**
* Friendly label for an auto-derived context chip. We don't fetch resource
* names from the URL alone, so we lean on the page identity that already
* lives in `metadata.page`, falling back to the resource type.
*/
function autoContextLabel(ctx: MessageContext): string {
const page = (ctx.metadata as { page?: string } | null | undefined)?.page;
switch (page) {
case 'dashboard_detail':
return 'Current dashboard';
case 'panel_edit':
return 'Editing panel';
case 'panel_fullscreen':
return 'Panel (fullscreen)';
case 'dashboard_list':
return 'Dashboards';
case 'alert_edit':
return 'Editing alert';
case 'alert_new':
return 'New alert';
case 'alerts_triggered':
return 'Triggered alerts';
case 'alert_list':
return 'Alerts';
case 'service_detail':
return 'Current service';
case 'services_list':
return 'Services';
case 'logs_explorer':
return 'Logs explorer';
case 'log_detail':
return 'Log details';
case 'traces_explorer':
return 'Traces explorer';
case 'trace_detail':
return 'Trace details';
case 'metrics_explorer':
return 'Metrics explorer';
default:
return ctx.type;
}
}
/** 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;
const HOME_SERVICES_INTERVAL = 30 * 60 * 1000;
const CONTEXT_CATEGORIES = ['Dashboards', 'Alerts', 'Services'] as const;
type ContextCategory = (typeof CONTEXT_CATEGORIES)[number];
interface SelectedContextItem {
category: ContextCategory;
entityId: string;
value: string;
}
function toMessageContext(item: SelectedContextItem): MessageContext | null {
switch (item.category) {
case 'Dashboards':
return {
source: 'mention',
type: 'dashboard',
resourceId: item.entityId,
resourceName: item.value,
};
case 'Alerts':
return {
source: 'mention',
type: 'alert',
resourceId: item.entityId,
resourceName: item.value,
};
case 'Services':
return {
source: 'mention',
type: 'service',
resourceId: item.entityId,
resourceName: item.value,
};
default:
return null;
}
}
interface ContextEntityItem {
id: string;
value: string;
}
const CONTEXT_CATEGORY_ICONS = {
Dashboards: LayoutDashboard,
Alerts: Bell,
Services: ShieldCheck,
} satisfies Record<ContextCategory, unknown>;
function fileToDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (): void => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
export default function ChatInput({
onSend,
onCancel,
disabled,
isStreaming = false,
autoContexts,
onDismissAutoContext,
}: ChatInputProps): JSX.Element {
const { selectedTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const [text, setText] = useState('');
const [pendingFiles, setPendingFiles] = useState<UploadFile[]>([]);
const [selectedContexts, setSelectedContexts] = useState<
SelectedContextItem[]
>([]);
const [isContextPickerOpen, setIsContextPickerOpen] = useState(false);
const [activeContextCategory, setActiveContextCategory] =
useState<ContextCategory>('Dashboards');
const [pickerSearchQuery, setPickerSearchQuery] = useState('');
const queryClient = useQueryClient();
// When the picker was opened by typing `@` in the textarea, this holds the
// span of `@<query>` (start / end indices into `text`). Used both for live
// filtering of the entity list and for splicing the trigger out of the
// text once the user picks an item. `null` when the picker is opened via
// the "Add Context" button (no trigger to strip, no query to filter).
const [mentionRange, setMentionRange] = useState<{
start: number;
end: number;
} | null>(null);
const [servicesTimeRange] = useState(() => {
const now = Date.now();
return {
startTime: now - HOME_SERVICES_INTERVAL,
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);
const capText = useCallback(
(value: string) => value.slice(0, MAX_INPUT_LENGTH),
[],
);
const syncContextPickerFromText = useCallback(
(value: string, caret: number) => {
const beforeCaret = value.slice(0, caret);
const atIndex = beforeCaret.lastIndexOf('@');
if (atIndex < 0) {
setIsContextPickerOpen(false);
setMentionRange(null);
return;
}
const query = beforeCaret.slice(atIndex + 1);
if (/\s/.test(query)) {
setIsContextPickerOpen(false);
setMentionRange(null);
return;
}
setIsContextPickerOpen(true);
setMentionRange({ start: atIndex, end: caret });
},
[],
);
const toggleContextSelection = useCallback(
(category: ContextCategory, entityId: string, contextValue: string) => {
const wasSelected = selectedContexts.some(
(item) => item.category === category && item.entityId === entityId,
);
setSelectedContexts((prev) => {
if (wasSelected) {
return prev.filter(
(item) => !(item.category === category && item.entityId === entityId),
);
}
return [...prev, { category, entityId, value: contextValue }];
});
// When the user picks an item via the `@` trigger, splice the
// `@<query>` span out of the textarea so their prose stays clean.
// Skip on remove (no trigger to strip) and when the picker was
// opened from the "Add Context" button (no mention range tracked).
if (!wasSelected && mentionRange) {
const next =
text.slice(0, mentionRange.start) + text.slice(mentionRange.end);
setText(next);
committedTextRef.current = next;
setMentionRange(null);
}
},
[mentionRange, selectedContexts, text],
);
// Focus the textarea when this component mounts (panel/modal open)
useEffect(() => {
textareaRef.current?.focus();
}, []);
const handleSend = useCallback(async () => {
const trimmed = text.trim();
if (!trimmed && pendingFiles.length === 0) {
return;
}
const attachments: MessageAttachment[] = await Promise.all(
pendingFiles.map(async (f) => {
const dataUrl = f.originFileObj ? await fileToDataUrl(f.originFileObj) : '';
return {
name: f.name,
type: f.type ?? 'application/octet-stream',
dataUrl,
};
}),
);
const userContexts = selectedContexts
.map(toMessageContext)
.filter((context): context is MessageContext => context !== null);
// Auto contexts come first so the agent reads "current page" before
// any explicit @-mentions when both are present.
const contexts = [...(autoContexts ?? []), ...userContexts];
const payload = capText(trimmed);
onSend(
payload,
attachments.length > 0 ? attachments : undefined,
contexts.length > 0 ? contexts : undefined,
);
setText('');
committedTextRef.current = '';
setPendingFiles([]);
setSelectedContexts([]);
textareaRef.current?.focus();
}, [text, pendingFiles, onSend, selectedContexts, autoContexts, capText]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Escape' && isContextPickerOpen) {
setIsContextPickerOpen(false);
return;
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void handleSend();
}
},
[handleSend, isContextPickerOpen],
);
const removeFile = useCallback((uid: string) => {
setPendingFiles((prev) => prev.filter((f) => f.uid !== uid));
}, []);
const removeContext = useCallback(
(category: ContextCategory, entityId: string) => {
setSelectedContexts((prev) =>
prev.filter(
(item) => !(item.category === category && item.entityId === entityId),
),
);
},
[],
);
// ── Voice input ────────────────────────────────────────────────────────────
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));
}
},
});
const showMic = isSupported && micPermission !== 'denied';
// 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();
await handleSend();
}, [text, discard, handleSend, capText]);
// Stop recording and revert the textarea to what it was before voice started.
const handleDiscard = useCallback(() => {
discard();
setText(committedTextRef.current);
textareaRef.current?.focus();
}, [discard]);
// ── 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') {
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;
start();
};
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,
disabled,
isStreaming,
start,
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
// refetch. Net effect: assistant-driven fetches happen exactly once
// per resource list per session, on the first cache miss. Gating on
// `isContextPickerOpen` (not just `activeContextCategory`) is important
// — the latter defaults to 'Dashboards' on every mount, so without the
// picker-open check the dashboards list refetches on every new
// conversation.
const {
data: dashboardsResponse,
isLoading: isDashboardsLoading,
isError: isDashboardsError,
} = useGetAllDashboard({
enabled: isContextPickerOpen && activeContextCategory === 'Dashboards',
staleTime: Infinity,
});
const {
data: alertsResponse,
isLoading: isAlertsLoading,
isError: isAlertsError,
} = useListRules({
query: {
enabled: isContextPickerOpen && activeContextCategory === 'Alerts',
staleTime: Infinity,
},
});
const {
data: servicesResponse,
isLoading: isServicesLoading,
isFetching: isServicesFetching,
isError: isServicesError,
} = useQueryService({
minTime: servicesTimeRange.startTime * 1e6,
maxTime: servicesTimeRange.endTime * 1e6,
selectedTime,
selectedTags: [],
options: {
enabled: isContextPickerOpen && activeContextCategory === 'Services',
staleTime: Infinity,
},
});
/**
* Resolves an auto-context to a human label: dashboard title, alert name,
* service name (the service `resourceId` IS the name), or a generic page
* label as fallback while the lookup data is still loading.
*
* Reads passively from the React Query cache via `getQueryData` —
* never triggers a fetch. If the cache is empty (e.g. assistant opened
* on a page that hasn't loaded the resource list yet), the chip falls
* back to a generic label and resolves once the cache fills via the
* picker or another page.
*/
const resolveAutoContextName = useCallback(
(ctx: MessageContext): string => {
if (ctx.type === 'service' && ctx.resourceId) {
return ctx.resourceId;
}
if (ctx.type === 'dashboard' && ctx.resourceId) {
const cached = queryClient.getQueryData<SuccessResponseV2<Dashboard[]>>(
REACT_QUERY_KEY.GET_ALL_DASHBOARDS,
);
const dash = cached?.data?.find((d) => d.id === ctx.resourceId);
if (dash?.data.title) {
return dash.data.title;
}
}
if (ctx.type === 'alert' && ctx.resourceId) {
const cached = queryClient.getQueryData<ListRules200>(
getListRulesQueryKey(),
);
const rule = cached?.data?.find((r) => r.id === ctx.resourceId);
if (rule?.alert) {
return rule.alert;
}
}
const page = (
ctx.metadata as { page?: string; traceId?: string } | null | undefined
)?.page;
if (page === 'trace_detail') {
const traceId = (ctx.metadata as { traceId?: string } | null | undefined)
?.traceId;
if (traceId) {
return `${traceId.slice(0, 8)}`;
}
}
return autoContextLabel(ctx);
},
[queryClient],
);
const contextEntitiesByCategory: Record<ContextCategory, ContextEntityItem[]> =
{
Dashboards:
dashboardsResponse?.data?.map((dashboard) => ({
id: dashboard.id,
value: dashboard.data.title ?? 'Untitled',
})) ?? [],
Alerts:
alertsResponse?.data
?.filter((alertRule) => Boolean(alertRule.alert))
.map((alertRule) => ({
id: alertRule.id,
value: alertRule.alert,
})) ?? [],
Services:
servicesResponse
?.filter((serviceItem) => Boolean(serviceItem.serviceName))
.map((serviceItem, index) => ({
id: serviceItem.serviceName || `service-${index}`,
value: serviceItem.serviceName,
})) ?? [],
};
const contextCategoryStateByCategory: Record<
ContextCategory,
{ isLoading: boolean; isError: boolean }
> = {
Dashboards: {
isLoading: isDashboardsLoading,
isError: isDashboardsError,
},
Alerts: {
isLoading: isAlertsLoading,
isError: isAlertsError,
},
Services: {
isLoading: isServicesLoading || isServicesFetching,
isError: isServicesError,
},
};
// Type-ahead filter against the `@<query>` typed in the textarea. When
// the picker was opened from the "Add Context" button there's no
// mention query, so fall back to the in-popover search input.
const mentionQuery = mentionRange
? text.slice(mentionRange.start + 1, mentionRange.end).toLowerCase()
: '';
const activeQuery = mentionQuery || pickerSearchQuery.trim().toLowerCase();
const filteredContextOptions = activeQuery
? contextEntitiesByCategory[activeContextCategory].filter((entity) =>
entity.value.toLowerCase().includes(activeQuery),
)
: contextEntitiesByCategory[activeContextCategory];
const { isLoading: isActiveContextLoading, isError: isActiveContextError } =
contextCategoryStateByCategory[activeContextCategory];
const currentLength = text.length;
const showTextWarning = currentLength >= WARNING_THRESHOLD;
return (
<div className={styles.input} ref={inputRootRef}>
{pendingFiles.length > 0 && (
<div className={styles.attachments}>
{pendingFiles.map((f) => (
<div key={f.uid} className={styles.attachmentChip}>
<span className={styles.attachmentName}>{f.name}</span>
<Button
variant="ghost"
size="icon"
className={styles.attachmentRemove}
onClick={(): void => removeFile(f.uid)}
aria-label={`Remove ${f.name}`}
>
<X size={11} />
</Button>
</div>
))}
</div>
)}
{(selectedContexts.length > 0 ||
(autoContexts && autoContexts.length > 0)) && (
<div className={styles.contextTags}>
{autoContexts?.map((ctx) => {
const key = autoContextKey(ctx);
const label = resolveAutoContextName(ctx);
const category = autoContextCategory(ctx);
return (
<div key={key} className={cx(styles.contextTag, styles.auto)}>
<div className={styles.contextTagContent}>
<Badge
color="secondary"
variant="outline"
className={styles.contextTagCategory}
>
{category}
</Badge>
<span className={styles.contextTagLabel}>{label}</span>
</div>
{onDismissAutoContext && (
<Button
variant="link"
size="icon"
color="secondary"
className={styles.contextTagRemove}
onClick={(): void => onDismissAutoContext(key)}
aria-label={`Remove ${category}: ${label} context`}
prefix={<X size={10} />}
></Button>
)}
</div>
);
})}
{selectedContexts.map((contextItem) => (
<div
key={`${contextItem.category}:${contextItem.entityId}`}
className={styles.contextTag}
>
<div className={styles.contextTagContent}>
<Badge
color="primary"
variant="outline"
className={styles.contextTagCategory}
>
{contextItem.category}
</Badge>
<span className={styles.contextTagLabel}>{contextItem.value}</span>
</div>
<Button
variant="link"
size="icon"
color="secondary"
className={styles.contextTagRemove}
onClick={(): void =>
removeContext(contextItem.category, contextItem.entityId)
}
aria-label={`Remove ${contextItem.category}: ${contextItem.value} context`}
prefix={<X size={10} />}
></Button>
</div>
))}
</div>
)}
<div className={styles.composer}>
<textarea
ref={textareaRef}
className={styles.textarea}
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}
/>
</div>
{showTextWarning && (
<div className={styles.charWarning} role="status">
<TriangleAlert size={12} />
<span>
{currentLength}/{MAX_INPUT_LENGTH} characters. Limit is {MAX_INPUT_LENGTH}
.
</span>
</div>
)}
<div className={styles.footer}>
<div className={styles.leftActions}>
<Popover
open={isContextPickerOpen}
onOpenChange={(open): void => {
setIsContextPickerOpen(open);
if (!open) {
setActiveContextCategory('Dashboards');
setPickerSearchQuery('');
}
}}
>
<PopoverTrigger asChild>
<Button
variant="solid"
color="secondary"
size="sm"
disabled={disabled}
onClick={(): void => {
setActiveContextCategory('Dashboards');
setPickerSearchQuery('');
}}
prefix={<Plus size={10} />}
>
Add Context
</Button>
</PopoverTrigger>
<PopoverContent
className={styles.contextPopover}
side="top"
align="end"
sideOffset={8}
>
<div className={styles.contextPopoverContent}>
<div className={styles.contextPopoverCategories}>
{CONTEXT_CATEGORIES.map((category) => {
const CategoryIcon = CONTEXT_CATEGORY_ICONS[category];
const isActive = activeContextCategory === category;
return (
<div
key={category}
role="tab"
tabIndex={0}
aria-selected={isActive}
className={cx(styles.contextPopoverCategoryItem, {
[styles.active]: isActive,
})}
onClick={(): void => {
setActiveContextCategory(category);
setPickerSearchQuery('');
}}
onKeyDown={(e): void => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setActiveContextCategory(category);
setPickerSearchQuery('');
}
}}
>
<CategoryIcon size={13} />
<span>{category}</span>
</div>
);
})}
</div>
<div className={styles.contextPopoverRight}>
<div className={styles.contextPopoverSearch}>
<Input
type="text"
placeholder={`Search ${activeContextCategory.toLowerCase()}`}
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 => {
e.stopPropagation();
}}
/>
</div>
<div className={styles.contextPopoverEntities}>
{isActiveContextLoading ? (
<div className={styles.contextPopoverEmpty}>
Loading {activeContextCategory.toLowerCase()}...
</div>
) : isActiveContextError ? (
<div className={styles.contextPopoverEmpty}>
Failed to load {activeContextCategory.toLowerCase()}.
</div>
) : filteredContextOptions.length === 0 ? (
<div className={styles.contextPopoverEmpty}>
No matching entities
</div>
) : (
filteredContextOptions.map((option) => {
const isSelected = selectedContexts.some(
(item) =>
item.category === activeContextCategory &&
item.entityId === option.id,
);
return (
<div
key={option.id}
className={cx(styles.contextPopoverEntityItem, {
[styles.selected]: isSelected,
})}
onClick={(): void =>
toggleContextSelection(
activeContextCategory,
option.id,
option.value,
)
}
>
<span className={styles.contextPopoverEntityItemText}>
{option.value}
</span>
</div>
);
})
)}
</div>
</div>
</div>
</PopoverContent>
</Popover>
</div>
<div className={styles.rightActions}>
{showMic &&
(isListening ? (
<div className={styles.micRecording}>
<div
className={cx(styles.micDiscard, styles.secondary)}
onClick={handleDiscard}
aria-label="Discard recording"
>
<X size={12} />
</div>
<span className={styles.micWaves} aria-hidden="true">
<span />
<span />
<span />
<span />
<span />
<span />
<span />
<span />
</span>
<div
className={cx(styles.micStop, styles.destructive)}
onClick={handleStopAndSend}
aria-label="Stop and send"
>
<Square size={9} fill="currentColor" strokeWidth={0} />
</div>
</div>
) : (
<Tooltip title="Voice input">
<Button
variant="ghost"
size="icon"
onClick={start}
disabled={disabled}
aria-label="Start voice input"
className={styles.micBtn}
>
<Mic size={14} />
</Button>
</Tooltip>
))}
{isStreaming && onCancel ? (
<Tooltip title="Stop generating">
<Button
variant="solid"
size="icon"
color="destructive"
onClick={onCancel}
aria-label="Stop generating"
>
<Square size={10} fill="currentColor" strokeWidth={0} />
</Button>
</Tooltip>
) : (
<Button
variant="solid"
size="icon"
color="primary"
onClick={isListening ? handleStopAndSend : handleSend}
disabled={disabled || (!text.trim() && pendingFiles.length === 0)}
aria-label="Send message"
>
<Send size={14} />
</Button>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ChatInput';
export { default } from './ChatInput';

View File

@@ -0,0 +1,133 @@
.clarification {
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
padding: 10px 12px;
background: var(--l2-background);
display: flex;
flex-direction: column;
gap: 10px;
width: 100%;
&.submitted {
border-color: var(--l2-border);
background: transparent;
flex-direction: row;
align-items: center;
gap: 6px;
padding: 6px 10px;
}
}
.header {
display: flex;
align-items: center;
gap: 6px;
}
.headerIcon {
flex-shrink: 0;
color: var(--accent-primary);
}
.headerLabel {
font-size: 12px;
font-weight: 600;
color: var(--l1-foreground);
}
.message {
font-size: 13px;
color: var(--l1-foreground);
margin: 0;
line-height: 1.5;
}
.icon {
color: var(--accent-forest);
flex-shrink: 0;
}
.statusText {
font-size: 13px;
color: var(--l2-foreground);
}
.fields {
display: flex;
flex-direction: column;
gap: 8px;
}
.field {
display: flex;
flex-direction: column;
gap: 4px;
}
.label {
font-size: 12px;
font-weight: 500;
color: var(--l2-foreground);
}
.required {
color: var(--accent-cherry);
margin-left: 2px;
}
.input,
.select {
background: var(--l2-background);
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
padding: 5px 8px;
font-size: 13px;
color: var(--l1-foreground);
outline: none;
transition: border-color 0.12s;
&:focus {
border-color: var(--accent-primary);
}
}
.select {
cursor: pointer;
}
// Constrain the Radix-based SelectContent popover so it never grows wider
// than the trigger button. `--radix-select-trigger-width` is set by Radix
// at the popper layer when `position: 'popper'` (the default).
.selectContent {
width: var(--radix-select-trigger-width);
min-width: var(--radix-select-trigger-width);
}
.radioGroup,
.checkboxGroup {
display: flex;
flex-direction: column;
gap: 5px;
}
.radioLabel,
.checkboxLabel {
display: flex;
align-items: center;
gap: 7px;
font-size: 13px;
color: var(--l1-foreground);
cursor: pointer;
}
.radio,
.checkbox {
accent-color: var(--accent-primary);
cursor: pointer;
}
.actions {
display: flex;
gap: 6px;
margin-top: 16px;
}

View File

@@ -0,0 +1,352 @@
import { useState } from 'react';
import cx from 'classnames';
import { Button } from '@signozhq/ui/button';
import { Checkbox } from '@signozhq/ui/checkbox';
import { Input } from '@signozhq/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
} from '@signozhq/ui/select';
import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
ClarificationEventDTO,
ClarificationFieldEventDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { CircleHelp, Send, X } from '@signozhq/icons';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import styles from './ClarificationForm.module.scss';
/** Sentinel emitted by the select dropdown when the user picks the custom slot. */
const CUSTOM_OPTION_SENTINEL = '__signoz_ai_custom__';
/** User-facing label for the synthetic "type your own answer" option. */
const CUSTOM_OPTION_LABEL = 'Other (type your own)';
interface ClarificationFormProps {
conversationId: string;
clarification: ClarificationEventDTO;
}
/**
* Rendered when the agent emits a `clarification` SSE event.
* Dynamically renders form fields based on the `fields` array and
* submits answers to resume the agent on a new execution.
*/
export default function ClarificationForm({
conversationId,
clarification,
}: ClarificationFormProps): JSX.Element {
const submitClarification = useAIAssistantStore((s) => s.submitClarification);
const cancelStream = useAIAssistantStore((s) => s.cancelStream);
const isStreaming = useAIAssistantStore(
(s) => s.streams[conversationId]?.isStreaming ?? false,
);
const fields = clarification.fields ?? [];
const initialAnswers = Object.fromEntries(
fields.map((f) => [f.id, initialAnswerFor(f)]),
);
const [answers, setAnswers] =
useState<Record<string, unknown>>(initialAnswers);
const [submitted, setSubmitted] = useState(false);
const [cancelled, setCancelled] = useState(false);
const setField = (id: string, value: unknown): void => {
setAnswers((prev) => ({ ...prev, [id]: value }));
};
const handleSubmit = async (): Promise<void> => {
setSubmitted(true);
await submitClarification(
conversationId,
clarification.clarificationId,
answers,
);
};
const handleCancel = (): void => {
setCancelled(true);
cancelStream(conversationId);
};
if (submitted) {
return (
<div className={cx(styles.clarification, styles.submitted)}>
<Send size={13} className={styles.icon} />
<span className={styles.statusText}>Answers submitted resuming</span>
</div>
);
}
if (cancelled) {
return (
<div className={cx(styles.clarification, styles.submitted)}>
<X size={13} className={styles.icon} />
<span className={styles.statusText}>Request cancelled.</span>
</div>
);
}
return (
<div className={styles.clarification}>
<div className={styles.header}>
<CircleHelp size={13} className={styles.headerIcon} />
<span className={styles.headerLabel}>A few details needed</span>
</div>
<p className={styles.message}>{clarification.message}</p>
<div className={styles.fields}>
{fields.map((field) => (
<FieldInput
key={field.id}
field={field}
value={answers[field.id]}
onChange={(val): void => setField(field.id, val)}
/>
))}
</div>
<div className={styles.actions}>
<Button
variant="solid"
color="primary"
onClick={handleSubmit}
disabled={isStreaming}
prefix={<Send />}
>
Submit
</Button>
<Button
variant="outlined"
color="secondary"
onClick={handleCancel}
disabled={isStreaming}
prefix={<X />}
>
Cancel request
</Button>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Field renderer — covers every variant of ClarificationFieldTypeDTO:
// text, number, select, multi_select, boolean.
// ---------------------------------------------------------------------------
/**
* Per-type seed value. The DTO's `default` is `string | string[] | null`,
* which doesn't fit boolean fields cleanly — we coerce 'true'/'false' strings
* for them, fall back to `[]` for multi_select, and the raw string otherwise.
*/
function initialAnswerFor(f: ClarificationFieldEventDTO): unknown {
const raw = f.default;
if (f.type === ClarificationFieldTypeDTO.boolean) {
// `default` is typed string | string[] | null; backend sends
// 'true'/'false' as strings for boolean fields.
return raw === 'true';
}
if (f.type === ClarificationFieldTypeDTO.multi_select) {
return Array.isArray(raw) ? raw : [];
}
return raw ?? '';
}
interface FieldInputProps {
field: ClarificationFieldEventDTO;
value: unknown;
onChange: (value: unknown) => void;
}
function FieldInput({ field, value, onChange }: FieldInputProps): JSX.Element {
const { id, type, label, required, options, allowCustom } = field;
// Local UI state for the synthetic "custom" option on select /
// multi_select fields with `allowCustom`. The free-text input only renders
// when this is true; the typed value is what's actually sent up via
// `onChange` (never the sentinel / "Other" label).
const [isCustom, setIsCustom] = useState(false);
const [customValue, setCustomValue] = useState('');
// Render the select if the field has options OR if the server marked it
// `allowCustom` (in which case the dropdown still appears with just the
// "Other (type your own)" entry — a plain `options: null` would
// otherwise fall through to the bare text-input renderer).
if (type === ClarificationFieldTypeDTO.select && (options || allowCustom)) {
const handleSelectChange = (next: string | string[]): void => {
// `multiple` is off → callback receives a single string. The wider
// `string | string[]` typing comes from the shared Select root.
const picked = Array.isArray(next) ? (next[0] ?? '') : next;
if (picked === CUSTOM_OPTION_SENTINEL) {
setIsCustom(true);
onChange(customValue);
} else {
setIsCustom(false);
onChange(picked);
}
};
return (
<div className={styles.field}>
<label className={styles.label} htmlFor={id}>
{label}
{required && <span className={styles.required}>*</span>}
</label>
<Select
value={isCustom ? CUSTOM_OPTION_SENTINEL : String(value ?? '')}
onChange={handleSelectChange}
>
<SelectTrigger id={id} placeholder="Select…" />
{/* Pin the dropdown width to the trigger via Radix's
`--radix-select-trigger-width`; otherwise the popover
sizes to its widest item and looks misaligned. */}
<SelectContent className={styles.selectContent}>
{options?.map((opt) => (
<SelectItem key={opt} value={opt}>
{opt}
</SelectItem>
))}
{allowCustom && (
<SelectItem value={CUSTOM_OPTION_SENTINEL}>
{CUSTOM_OPTION_LABEL}
</SelectItem>
)}
</SelectContent>
</Select>
{isCustom && (
<Input
type="text"
className={styles.input}
placeholder="Enter a custom value"
value={customValue}
onChange={(e): void => {
setCustomValue(e.target.value);
onChange(e.target.value);
}}
/>
)}
</div>
);
}
// Boolean — single yes/no checkbox. The label sits inside the checkbox
// so the click target covers both, matching how multi_select rows render.
if (type === ClarificationFieldTypeDTO.boolean) {
const checked = value === true;
return (
<div className={styles.field}>
<Checkbox
className={styles.checkboxLabel}
value={checked}
onChange={(): void => onChange(!checked)}
>
{label}
{required && <span className={styles.required}>*</span>}
</Checkbox>
</div>
);
}
// Same fallback logic as the select branch — render the checkbox group
// when there are options OR when the field is `allowCustom` only.
if (
type === ClarificationFieldTypeDTO.multi_select &&
(options || allowCustom)
) {
const selected = Array.isArray(value) ? (value as string[]) : [];
// Anything in the value array that isn't one of the predefined options
// is treated as a custom entry — we keep at most one custom entry,
// driven by the local `customValue` + `isCustom` state below.
const regularSelected = selected.filter((v) => options?.includes(v));
const toggleRegular = (opt: string): void => {
const nextRegular = regularSelected.includes(opt)
? regularSelected.filter((v) => v !== opt)
: [...regularSelected, opt];
onChange(
isCustom && customValue ? [...nextRegular, customValue] : nextRegular,
);
};
const toggleCustom = (): void => {
if (isCustom) {
setIsCustom(false);
onChange(regularSelected);
} else {
setIsCustom(true);
onChange(customValue ? [...regularSelected, customValue] : regularSelected);
}
};
const updateCustomValue = (next: string): void => {
setCustomValue(next);
if (isCustom) {
onChange(next ? [...regularSelected, next] : regularSelected);
}
};
return (
<div className={styles.field}>
<span className={styles.label}>
{label}
{required && <span className={styles.required}>*</span>}
</span>
<div className={styles.checkboxGroup}>
{options?.map((opt) => (
<Checkbox
key={opt}
className={styles.checkboxLabel}
value={regularSelected.includes(opt)}
onChange={(): void => toggleRegular(opt)}
>
{opt}
</Checkbox>
))}
{allowCustom && (
<Checkbox
className={styles.checkboxLabel}
value={isCustom}
onChange={toggleCustom}
>
{CUSTOM_OPTION_LABEL}
</Checkbox>
)}
</div>
{isCustom && (
<Input
type="text"
className={styles.input}
placeholder="Enter a custom value"
value={customValue}
onChange={(e): void => updateCustomValue(e.target.value)}
/>
)}
</div>
);
}
// text / number (default)
return (
<div className={styles.field}>
<label className={styles.label} htmlFor={id}>
{label}
{required && <span className={styles.required}>*</span>}
</label>
<Input
id={id}
type={type === 'number' ? 'number' : 'text'}
className={styles.input}
value={String(value ?? '')}
onChange={(e): void =>
onChange(type === 'number' ? Number(e.target.value) : e.target.value)
}
placeholder={label}
/>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ClarificationForm';
export { default } from './ClarificationForm';

View File

@@ -0,0 +1,145 @@
.item {
display: flex;
align-items: center;
gap: 7px;
padding: 6px 8px;
border-radius: var(--radius-2);
cursor: pointer;
min-width: 0;
position: relative;
// 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;
.title {
color: var(--l3-foreground);
}
}
}
.icon {
flex-shrink: 0;
color: var(--l3-foreground);
}
.body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1px;
}
.title {
font-size: 12px;
color: var(--l2-foreground);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.4;
}
.time {
font-size: 10px;
color: var(--l3-foreground);
opacity: 0.7;
}
.input {
width: 100%;
background: transparent;
border: none;
border-bottom: 1px solid var(--accent-primary);
outline: none;
color: var(--l1-foreground);
font-size: 12px;
font-family: inherit;
padding: 1px 0;
}
.actions {
display: flex;
align-items: center;
gap: 1px;
flex-shrink: 0;
opacity: var(--actions-opacity, 0);
transition: opacity 0.12s;
// Float over the right edge of the item so the title can keep using
// the full width while the buttons are hidden — no layout shift +
// no premature truncation. The `background` matches the hover/active
// state so the buttons visually mask any title text underneath.
position: absolute;
top: 50%;
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;
}
.btn {
padding: 2px !important;
height: auto !important;
min-height: 0 !important;
&.danger:hover {
color: var(--accent-cherry) !important;
}
}
// Compact menu — narrower than the design-system default so the
// content (Rename / Copy link / Archive) doesn't dwarf the row.
.menu {
min-width: 160px !important;
width: 160px !important;
}
// 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

@@ -0,0 +1,226 @@
import { KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import cx from 'classnames';
import ROUTES from 'constants/routes';
import { getAbsoluteUrl } from 'utils/basePath';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { toast } from '@signozhq/ui/sonner';
import { DropdownMenuSimple } from '@signozhq/ui/dropdown-menu';
import {
Archive,
ArchiveRestore,
EllipsisVertical,
Link,
MessageSquare,
Pencil,
} from '@signozhq/icons';
import { Conversation } from '../../types';
import styles from './ConversationItem.module.scss';
interface ConversationItemProps {
conversation: Conversation;
isActive: boolean;
onSelect: (id: string) => void;
onRename: (id: string, title: string) => void;
onArchive: (id: string) => void;
onRestore: (id: string) => void;
}
function formatRelativeTime(ts: number): string {
if (!Number.isFinite(ts)) {
return '';
}
const diff = Date.now() - ts;
const mins = Math.floor(diff / 60_000);
if (mins < 1) {
return 'just now';
}
if (mins < 60) {
return `${mins}m ago`;
}
const hrs = Math.floor(mins / 60);
if (hrs < 24) {
return `${hrs}h ago`;
}
const days = Math.floor(hrs / 24);
if (days < 7) {
return `${days}d ago`;
}
return new Date(ts).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
});
}
export default function ConversationItem({
conversation,
isActive,
onSelect,
onRename,
onArchive,
onRestore,
}: ConversationItemProps): JSX.Element {
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const [, copyToClipboard] = useCopyToClipboard();
const isArchived = Boolean(conversation.archived);
const displayTitle = conversation.title ?? 'New conversation';
const ts = conversation.updatedAt ?? conversation.createdAt;
const handleCopyLink = useCallback((): void => {
// Prefer the server-side `threadId` so the link resolves for anyone
// with access to this conversation. Fall back to the local id for
// drafts that haven't synced yet — useful for the current session
// even if the URL won't reload elsewhere.
const id = conversation.threadId ?? conversation.id;
const path = ROUTES.AI_ASSISTANT.replace(':conversationId', id);
copyToClipboard(getAbsoluteUrl(path));
toast.success('Conversation link copied to clipboard');
}, [conversation.threadId, conversation.id, copyToClipboard]);
const startEditing = useCallback((): void => {
setEditValue(conversation.title ?? '');
setIsEditing(true);
}, [conversation.title]);
useEffect(() => {
if (isEditing) {
inputRef.current?.focus();
inputRef.current?.select();
}
}, [isEditing]);
const commitEdit = useCallback(() => {
onRename(conversation.id, editValue);
setIsEditing(false);
}, [conversation.id, editValue, onRename]);
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
commitEdit();
}
if (e.key === 'Escape') {
setIsEditing(false);
}
},
[commitEdit],
);
const itemClass = cx(styles.item, {
[styles.active]: isActive,
[styles.archived]: isArchived,
});
// Dropdown items mirror the previous inline buttons but live in a single
// trigger so the row stays compact. Archive/Restore swap based on the
// archived state — same handler wiring as before.
const baseItems = [
{
key: 'rename',
label: 'Rename',
icon: <Pencil size={12} />,
className: styles.menuItem,
onClick: (): void => startEditing(),
},
{
key: 'copy-link',
label: 'Copy link',
icon: <Link size={12} />,
className: styles.menuItem,
onClick: handleCopyLink,
},
{ type: 'divider' as const, key: 'divider' },
];
const menuItems = isArchived
? [
...baseItems,
{
key: 'restore',
label: 'Restore',
icon: <ArchiveRestore size={12} />,
className: cx(styles.menuItem, styles.restoreItem),
onClick: (): void => onRestore(conversation.id),
},
]
: [
...baseItems,
{
key: 'archive',
label: 'Archive',
icon: <Archive size={12} />,
className: cx(styles.menuItem, styles.archiveItem),
onClick: (): void => onArchive(conversation.id),
},
];
return (
<div
className={itemClass}
onClick={(): void => onSelect(conversation.id)}
role="button"
tabIndex={0}
onKeyDown={(e): void => {
if (e.key === 'Enter' || e.key === ' ') {
onSelect(conversation.id);
}
}}
>
<MessageSquare size={12} className={styles.icon} />
<div className={styles.body}>
{isEditing ? (
<Input
ref={inputRef}
className={styles.input}
value={editValue}
onChange={(e): void => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={commitEdit}
onClick={(e): void => e.stopPropagation()}
maxLength={80}
/>
) : (
<>
<span className={styles.title} title={displayTitle}>
{displayTitle}
</span>
<span className={styles.time}>{formatRelativeTime(ts)}</span>
</>
)}
</div>
{!isEditing && (
<div
className={styles.actions}
// Stop the row's onSelect from firing when the user opens the
// menu or clicks an item — the menu lives in a portal so its
// own clicks don't bubble, but the trigger button does.
onClick={(e): void => e.stopPropagation()}
>
<DropdownMenuSimple
menu={{ items: menuItems }}
align="end"
sideOffset={4}
className={styles.menu}
>
<Button
variant="link"
size="icon"
color="none"
className={styles.btn}
aria-label="Conversation actions"
prefix={<EllipsisVertical size={12} />}
/>
</DropdownMenuSimple>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ConversationItem';
export { default } from './ConversationItem';

View File

@@ -0,0 +1,84 @@
.thread {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
padding: 16px 0;
gap: 14px;
}
.message {
display: flex;
padding: 0 16px;
&.compact {
padding: 0 12px;
}
}
.user {
justify-content: flex-end;
}
.assistant {
justify-content: flex-start;
}
.bubble {
display: flex;
flex-direction: column;
gap: 8px;
// `width: 100%` (capped by per-role max-width below) forces the bubble
// to fill its allotted slot rather than collapsing to the longest line —
// otherwise the lines' percent widths cascade into a tiny bubble.
width: 100%;
border-radius: var(--radius-2);
padding: 12px 14px;
&.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);
}
&.assistant {
max-width: 95%;
background: var(--l2-background);
border-bottom-left-radius: var(--radius-2);
}
}
.line {
height: 9px;
border-radius: 3px;
position: relative;
overflow: hidden;
background: color-mix(in srgb, var(--l1-foreground) 10%, transparent);
// Shimmer sweep — same pattern used by HistorySidebar's skeleton rows.
&::after {
content: '';
position: absolute;
inset: 0;
transform: translateX(-100%);
background: linear-gradient(
90deg,
transparent,
color-mix(in srgb, var(--l1-foreground) 10%, transparent),
transparent
);
animation: shimmer 1.15s ease-in-out infinite;
}
}
@keyframes shimmer {
100% {
transform: translateX(100%);
}
}

View File

@@ -0,0 +1,53 @@
import cx from 'classnames';
import { useVariant } from '../../VariantContext';
import styles from './ConversationSkeleton.module.scss';
/**
* Each entry is one bubble in the placeholder thread:
* role: who "sent" the bubble — drives left/right alignment + colour
* lines: list of widths (as % of the bubble) for the shimmer lines inside
*
* Mixed widths and varying line counts produce something that scans as a real
* back-and-forth conversation rather than a uniform grid.
*/
const ROWS: { role: 'user' | 'assistant'; lines: number[] }[] = [
{ role: 'user', lines: [62] },
{ role: 'assistant', lines: [85, 92, 70] },
{ role: 'user', lines: [55, 40] },
{ role: 'assistant', lines: [90, 78, 95, 60] },
{ role: 'user', lines: [48] },
{ role: 'assistant', lines: [80, 88] },
];
/** Skeleton chat thread shown while a single conversation is being loaded. */
export default function ConversationSkeleton(): JSX.Element {
const variant = useVariant();
const isCompact = variant === 'panel';
return (
<div className={styles.thread} aria-busy aria-label="Loading conversation">
{ROWS.map((row, idx) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={idx}
className={cx(styles.message, styles[row.role], {
[styles.compact]: isCompact,
})}
>
<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>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ConversationSkeleton';
export { default } from './ConversationSkeleton';

View File

@@ -0,0 +1,136 @@
@use '../../_scrollbar' as *;
.conversationsList {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
// Page variant: fixed-width left column.
&.variantPage {
width: 280px;
flex-shrink: 0;
border-right: 1px solid var(--l1-border);
}
// Panel variant: full-width overlay (replaces conversation view).
&.variantPanel {
width: 100%;
flex: 1;
}
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
flex-shrink: 0;
}
.heading {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--l2-foreground);
// Collapse the line-box to the glyph height so the loading dots
// (centered against the line-box) line up with the cap-height of the
// uppercase text instead of sitting visually low.
line-height: 24px;
}
.searchBar {
padding: 0px 8px 12px;
flex-shrink: 0;
}
.search {
width: 100%;
font-size: 12px;
}
.list {
position: relative;
flex: 1;
overflow-y: auto;
padding: 0 6px 12px;
@include scrollbar(0.25rem);
}
.empty {
margin: 20px 8px 0;
font-size: 12px;
color: var(--l3-foreground);
text-align: center;
}
.srOnly {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.loadingDots {
display: inline-flex;
align-items: center;
gap: 3px;
}
.loadingDot {
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--l3-foreground);
opacity: 0.4;
animation: historyLoadingDot 1.1s ease-in-out infinite;
&:nth-child(2) {
animation-delay: 0.18s;
}
&:nth-child(3) {
animation-delay: 0.36s;
}
}
@keyframes historyLoadingDot {
0%,
100% {
opacity: 0.25;
transform: translateY(0);
}
50% {
opacity: 1;
transform: translateY(-1px);
}
}
.group {
display: flex;
flex-direction: column;
gap: 2px;
margin-bottom: 8px;
&.archived {
margin-top: 4px;
padding-top: 10px;
border-top: 1px solid var(--l2-border);
}
}
.groupLabel {
display: block;
padding: 8px;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.07em;
color: var(--l3-foreground);
}

View File

@@ -0,0 +1,234 @@
import { useEffect, useMemo, useState } from 'react';
import cx from 'classnames';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Plus, Search } from '@signozhq/icons';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Conversation } from '../../types';
import { useVariant } from '../../VariantContext';
import ConversationItem from '../ConversationItem';
import styles from './ConversationsList.module.scss';
interface ConversationsListProps {
/** Called when a conversation is selected — lets the parent navigate if needed */
onSelect?: (id: string) => void;
onNewConversation?: () => void;
showAddNewConversation?: boolean;
}
function groupByDate(
conversations: Conversation[],
): { label: string; items: Conversation[] }[] {
const now = Date.now();
const DAY = 86_400_000;
const groups: Record<string, Conversation[]> = {
Today: [],
Yesterday: [],
'Last 7 days': [],
'Last 30 days': [],
Older: [],
};
for (const conv of conversations) {
const age = now - (conv.updatedAt ?? conv.createdAt);
if (age < DAY) {
groups.Today.push(conv);
} else if (age < 2 * DAY) {
groups.Yesterday.push(conv);
} else if (age < 7 * DAY) {
groups['Last 7 days'].push(conv);
} else if (age < 30 * DAY) {
groups['Last 30 days'].push(conv);
} else {
groups.Older.push(conv);
}
}
return Object.entries(groups)
.filter(([, items]) => items.length > 0)
.map(([label, items]) => ({ label, items }));
}
/**
* Three-dot loading indicator. Sits inside the sidebar header so the
* conversation list is never bumped down by a skeleton row when threads
* load — visible signal of in-flight work without any layout shift.
*/
function HeaderLoadingDots(): JSX.Element {
return (
<span className={styles.loadingDots} role="status" aria-label="Loading">
<span className={styles.loadingDot} />
<span className={styles.loadingDot} />
<span className={styles.loadingDot} />
</span>
);
}
export default function ConversationsList({
onSelect,
onNewConversation,
showAddNewConversation = false,
}: ConversationsListProps): JSX.Element {
const variant = useVariant();
const conversations = useAIAssistantStore((s) => s.conversations);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const isLoadingThreads = useAIAssistantStore((s) => s.isLoadingThreads);
const setActiveConversation = useAIAssistantStore(
(s) => s.setActiveConversation,
);
const loadThread = useAIAssistantStore((s) => s.loadThread);
const fetchThreads = useAIAssistantStore((s) => s.fetchThreads);
const archiveConversation = useAIAssistantStore((s) => s.archiveConversation);
const restoreConversation = useAIAssistantStore((s) => s.restoreConversation);
const renameConversation = useAIAssistantStore((s) => s.renameConversation);
const [searchQuery, setSearchQuery] = useState('');
// Fetch threads from backend on mount
useEffect(() => {
void fetchThreads();
}, [fetchThreads]);
// Case-insensitive substring match against the conversation title.
// Untitled conversations match the literal placeholder so users
// searching for "new" can still find them.
const trimmedQuery = searchQuery.trim().toLowerCase();
const matchesQuery = (c: Conversation): boolean => {
if (!trimmedQuery) {
return true;
}
const title = (c.title ?? 'New conversation').toLowerCase();
return title.includes(trimmedQuery);
};
const sortedActive = useMemo(
() =>
Object.values(conversations)
.filter((c) => !c.archived && matchesQuery(c))
.sort(
(a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[conversations, trimmedQuery],
);
const sortedArchived = useMemo(
() =>
Object.values(conversations)
.filter((c) => Boolean(c.archived) && c.threadId && matchesQuery(c))
.sort(
(a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[conversations, trimmedQuery],
);
const groups = useMemo(() => groupByDate(sortedActive), [sortedActive]);
const hasAnySidebarRows = groups.length > 0 || sortedArchived.length > 0;
const isSearching = trimmedQuery.length > 0;
const handleSelect = (id: string): void => {
const conv = conversations[id];
if (conv?.threadId) {
// Always load from backend — refreshes messages and reconnects
// to active execution if the thread is still busy.
void loadThread(conv.threadId);
} else {
// Local-only conversation (no backend thread yet)
setActiveConversation(id);
}
onSelect?.(id);
};
const variantClass =
variant === 'page' ? styles.variantPage : styles.variantPanel;
return (
<div className={cx(styles.conversationsList, variantClass)}>
<div className={styles.header}>
<span className={styles.heading}>Conversations</span>
{isLoadingThreads && <HeaderLoadingDots />}
{!isLoadingThreads && showAddNewConversation && (
<Tooltip title="New conversation">
<Button
variant="solid"
size="sm"
color="secondary"
onClick={onNewConversation}
aria-label="New conversation"
>
<Plus size={12} />
</Button>
</Tooltip>
)}
</div>
<div className={styles.searchBar}>
<Input
type="text"
value={searchQuery}
onChange={(e): void => setSearchQuery(e.target.value)}
placeholder="Search conversations…"
prefix={<Search size={12} />}
className={styles.search}
/>
</div>
<div className={styles.list} aria-busy={isLoadingThreads}>
{isLoadingThreads && (
<span className={styles.srOnly} role="status">
Loading conversations
</span>
)}
{!isLoadingThreads && !hasAnySidebarRows && (
<p className={styles.empty}>
{isSearching ? 'No matching conversations.' : 'No conversations yet.'}
</p>
)}
{groups.map(({ label, items }) => (
<div key={label} className={styles.group}>
<span className={styles.groupLabel}>{label}</span>
{items.map((conv) => (
<ConversationItem
key={conv.id}
conversation={conv}
isActive={conv.id === activeConversationId}
onSelect={handleSelect}
onRename={renameConversation}
onArchive={archiveConversation}
onRestore={restoreConversation}
/>
))}
</div>
))}
{sortedArchived.length > 0 && (
<div className={cx(styles.group, styles.archived)}>
<span className={styles.groupLabel}>Archived Conversations</span>
{sortedArchived.map((conv) => (
<ConversationItem
key={conv.id}
conversation={conv}
isActive={conv.id === activeConversationId}
onSelect={handleSelect}
onRename={renameConversation}
onArchive={archiveConversation}
onRestore={restoreConversation}
/>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,2 @@
export * from './ConversationsList';
export { default } from './ConversationsList';

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