SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(ai-assistant): base route, auth-retry streaming, and rate-limit UX (#11457)
Yunus M99866a91e474
diff --git a/frontend/src/AppRoutes/Private.tsx b/frontend/src/AppRoutes/Private.tsxindex 7e08ef3e80..040d2f1e90 100644--- a/frontend/src/AppRoutes/Private.tsx+++ b/frontend/src/AppRoutes/Private.tsx@@ -102,7 +102,11 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {return <>{children}</>;}- if (pathname.startsWith('/ai-assistant/') && !isAIAssistantEnabled) {+ if (+ (pathname === ROUTES.AI_ASSISTANT_BASE ||+ pathname.startsWith('/ai-assistant/')) &&+ !isAIAssistantEnabled+ ) {return <Redirect to={ROUTES.HOME} />;}diff --git a/frontend/src/AppRoutes/index.tsx b/frontend/src/AppRoutes/index.tsxindex b548006d92..ea8172c565 100644--- a/frontend/src/AppRoutes/index.tsx+++ b/frontend/src/AppRoutes/index.tsx@@ -229,18 +229,18 @@ function App(): JSX.Element {}setRoutes((prev) => {- const hasAi = prev.some((r) => r.path === ROUTES.AI_ASSISTANT);+ const hasAi = prev.some((r) => r.key === 'AI_ASSISTANT');if (isAIAssistantEnabled === hasAi) {return prev;}if (isAIAssistantEnabled) {- const aiRoute = defaultRoutes.find((r) => r.path === ROUTES.AI_ASSISTANT);+ const aiRoute = defaultRoutes.find((r) => r.key === 'AI_ASSISTANT');if (!aiRoute) {return prev;}- return [...prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT), aiRoute];+ return [...prev.filter((r) => r.key !== 'AI_ASSISTANT'), aiRoute];}- return prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT);+ return prev.filter((r) => r.key !== 'AI_ASSISTANT');});}, [isLoggedInState, isAIAssistantEnabled]);@@ -254,6 +254,7 @@ function App(): JSX.Element {if (pathname === ROUTES.ONBOARDING ||pathname.startsWith('/public/dashboard/') ||+ pathname === '/ai-assistant' ||pathname.startsWith('/ai-assistant/')) {window.Pylon?.('hideChatBubble');diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.tsindex e0e0fdfc0f..959b6e6046 100644--- a/frontend/src/AppRoutes/routes.ts+++ b/frontend/src/AppRoutes/routes.ts@@ -501,7 +501,7 @@ const routes: AppRoutes[] = [isPrivate: true,},{- path: ROUTES.AI_ASSISTANT,+ path: [ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT],exact: true,component: AIAssistantPage,key: 'AI_ASSISTANT',diff --git a/frontend/src/api/AIAPIInstance.ts b/frontend/src/api/AIAPIInstance.tsindex ace5a0bb7a..684a193202 100644--- a/frontend/src/api/AIAPIInstance.ts+++ b/frontend/src/api/AIAPIInstance.ts@@ -40,6 +40,7 @@ export function setAIBackendUrl(url: string | null): void {if (aiBackendUrl === url) {return;}+aiBackendUrl = url;AIAssistantInstance.defaults.baseURL = url ? `${url}${AI_API_PATH}` : '';}diff --git a/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts b/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.tsindex baeb39533f..9f69512459 100644--- a/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts+++ b/frontend/src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts@@ -37,6 +37,16 @@ export enum ApplyFilterSignalDTO {traces = 'traces',metrics = 'metrics',}+export enum ApprovalStateDTO {+ pending = 'pending',+ approved = 'approved',+ rejected = 'rejected',+ superseded = 'superseded',+}+export enum ApprovalActionTypeDTO {+ modify = 'modify',+ delete = 'delete',+}/*** Resolved approval (approved/rejected/superseded) anchored on the assistant message that proposed it. Pending approvals never appear here - they live at the top-level pendingApproval slot.*/@@ -63,16 +73,6 @@ export interface ApprovalActionSummaryDTO {resolvedAt: string;}-export enum ApprovalActionTypeDTO {- modify = 'modify',- delete = 'delete',-}-export enum ApprovalStateDTO {- pending = 'pending',- approved = 'approved',- rejected = 'rejected',- superseded = 'superseded',-}export type ApprovalSummaryDTODiff = { [key: string]: unknown };export interface ApprovalSummaryDTO {@@ -139,6 +139,16 @@ export interface CancelRequestDTO {threadId: string;}+export enum ExecutionStateDTO {+ queued = 'queued',+ running = 'running',+ awaiting_approval = 'awaiting_approval',+ awaiting_clarification = 'awaiting_clarification',+ resumed = 'resumed',+ completed = 'completed',+ failed = 'failed',+ canceled = 'canceled',+}export interface CancelResponseDTO {/*** @type string@@ -153,6 +163,13 @@ export type ClarificationFieldDTOOptions = string[] | null;export type ClarificationFieldDTODefault = string | string[] | null;+export enum ClarificationFieldTypeDTO {+ text = 'text',+ number = 'number',+ select = 'select',+ multi_select = 'multi_select',+ boolean = 'boolean',+}export interface ClarificationFieldDTO {/*** @type string@@ -175,13 +192,6 @@ export interface ClarificationFieldDTO {default?: ClarificationFieldDTODefault;}-export enum ClarificationFieldTypeDTO {- text = 'text',- number = 'number',- select = 'select',- multi_select = 'multi_select',- boolean = 'boolean',-}export enum ClarificationStateDTO {pending = 'pending',submitted = 'submitted',@@ -252,6 +262,79 @@ export interface ClarifyResponseDTO {executionId: string;}+/**+ * Identifier exposed on the wire for each counter row.++ Mirrors the ``RateLimitCounterType`` model enum minus the cost+ counter. The daily-cost limit is enforced internally (Redis+ counter + 429 from the pre-flight gate) but never surfaced on the+ customer-facing API: shipping the raw provider cost to tenant users+ pins our public pricing model to what we pay Anthropic and forecloses+ markup, per-seat bundling, or tiered pricing. Cost stays internal on+ ``assistant_executions`` + Redis for billing.+ */+export enum CounterTypeNameDTO {+ hourly_message = 'hourly_message',+ daily_message = 'daily_message',+ daily_token = 'daily_token',+}+/**+ * "auto" if derived from current page; "mention" if explicitly @-picked.+ */+export enum MessageContextDTOSource {+ auto = 'auto',+ mention = 'mention',+}+/**+ * Resource taxonomy. Use metadata.page for concrete page identity.+ */+export enum MessageContextDTOType {+ dashboard = 'dashboard',+ alert = 'alert',+ saved_view = 'saved_view',+ logs_explorer = 'logs_explorer',+ traces_explorer = 'traces_explorer',+ metrics_explorer = 'metrics_explorer',+ service = 'service',+}+/**+ * Required for resource-detail pages: dashboard_detail, panel_edit, panel_fullscreen, alert_edit, service_detail. Always required for saved_view (mention-only — no list page in V1). Must be null for list/index/draft/detail-as-metadata pages such as dashboard_list, alert_list, alert_new, alerts_triggered, services_list, log_detail, and trace_detail.+ */+export type MessageContextDTOResourceId = string | null;++export type MessageContextDTOResourceName = string | null;++export type MessageContextDTOMetadataAnyOf = { [key: string]: unknown };++/**+ * Page-specific extras. metadata.page identifies list/draft pages and detail-as-metadata pages. Required non-empty metadata keys: panel_edit.widgetId, panel_fullscreen.widgetId, trace_detail.traceId. timeRange.{start,end} use Unix milliseconds.+ */+export type MessageContextDTOMetadata = MessageContextDTOMetadataAnyOf | null;++export interface MessageContextDTO {+ /**+ * @enum auto,mention+ * @type string+ * @description "auto" if derived from current page; "mention" if explicitly @-picked.+ */+ source: MessageContextDTOSource;+ /**+ * @enum dashboard,alert,saved_view,logs_explorer,traces_explorer,metrics_explorer,service+ * @type string+ * @description Resource taxonomy. Use metadata.page for concrete page identity.+ */+ type: MessageContextDTOType;+ /**+ * @description Required for resource-detail pages: dashboard_detail, panel_edit, panel_fullscreen, alert_edit, service_detail. Always required for saved_view (mention-only — no list page in V1). Must be null for list/index/draft/detail-as-metadata pages such as dashboard_list, alert_list, alert_new, alerts_triggered, services_list, log_detail, and trace_detail.+ */+ resourceId?: MessageContextDTOResourceId;+ resourceName?: MessageContextDTOResourceName;+ /**+ * @description Page-specific extras. metadata.page identifies list/draft pages and detail-as-metadata pages. Required non-empty metadata keys: panel_edit.widgetId, panel_fullscreen.widgetId, trace_detail.traceId. timeRange.{start,end} use Unix milliseconds.+ */+ metadata?: MessageContextDTOMetadata;+}+export type CreateMessageRequestDTOContexts = MessageContextDTO[] | null;export type CreateMessageRequestDTOForkFromMessageId = string | null;@@ -289,6 +372,16 @@ export interface CreateThreadResponseDTO {threadId: string;}+/**+ * Single sub-error entry — matches Go ErrorsResponseerroradditional.+ */+export interface ErrorResponseAdditionalDTO {+ /**+ * @type string+ */+ message: string;+}+export type ErrorBodyDTOErrors = ErrorResponseAdditionalDTO[] | null;export type ErrorBodyDTOUrl = string | null;@@ -321,26 +414,6 @@ export interface ErrorResponseDTO {error: ErrorBodyDTO;}-/**- * Single sub-error entry — matches Go ErrorsResponseerroradditional.- */-export interface ErrorResponseAdditionalDTO {- /**- * @type string- */- message: string;-}--export enum ExecutionStateDTO {- queued = 'queued',- running = 'running',- awaiting_approval = 'awaiting_approval',- awaiting_clarification = 'awaiting_clarification',- resumed = 'resumed',- completed = 'completed',- failed = 'failed',- canceled = 'canceled',-}export enum FeedbackRatingDTO {positive = 'positive',negative = 'negative',@@ -356,6 +429,30 @@ export interface FeedbackResponseDTO {[key: string]: unknown;}+export type ValidationErrorDTOLocItem = string | number;++export type ValidationErrorDTOCtx = { [key: string]: unknown };++export interface ValidationErrorDTO {+ /**+ * @type array+ */+ loc: ValidationErrorDTOLocItem[];+ /**+ * @type string+ */+ msg: string;+ /**+ * @type string+ */+ type: string;+ input?: unknown;+ /**+ * @type object+ */+ ctx?: ValidationErrorDTOCtx;+}+export interface HTTPValidationErrorDTO {/*** @type array@@ -393,6 +490,15 @@ export type MessageActionDTOQuery = MessageActionDTOQueryAnyOf | null;export type MessageActionDTOUrl = string | null;+export enum MessageActionKindDTO {+ undo = 'undo',+ revert = 'revert',+ restore = 'restore',+ follow_up = 'follow_up',+ open_resource = 'open_resource',+ open_docs = 'open_docs',+ apply_filter = 'apply_filter',+}/*** Assistant action. Kind-specific requirements: rollback actions require actionMetadataId/resourceType/resourceId; follow_up requires input.intent; open_resource requires resourceType/resourceId; apply_filter requires signal and query; open_docs requires a SigNoz docs url.*/@@ -413,75 +519,9 @@ export interface MessageActionDTO {url?: MessageActionDTOUrl;}-export enum MessageActionKindDTO {- undo = 'undo',- revert = 'revert',- restore = 'restore',- follow_up = 'follow_up',- open_resource = 'open_resource',- open_docs = 'open_docs',- apply_filter = 'apply_filter',-}export enum MessageContentTypeDTO {markdown = 'markdown',}-/**- * "auto" if derived from current page; "mention" if explicitly @-picked.- */-export enum MessageContextDTOSource {- auto = 'auto',- mention = 'mention',-}-/**- * Resource taxonomy. Use metadata.page for concrete page identity.- */-export enum MessageContextDTOType {- dashboard = 'dashboard',- alert = 'alert',- saved_view = 'saved_view',- logs_explorer = 'logs_explorer',- traces_explorer = 'traces_explorer',- metrics_explorer = 'metrics_explorer',- service = 'service',-}-/**- * Required for resource-detail pages: dashboard_detail, panel_edit, panel_fullscreen, alert_edit, service_detail. Always required for saved_view (mention-only — no list page in V1). Must be null for list/index/draft/detail-as-metadata pages such as dashboard_list, alert_list, alert_new, alerts_triggered, services_list, log_detail, and trace_detail.- */-export type MessageContextDTOResourceId = string | null;--export type MessageContextDTOResourceName = string | null;--export type MessageContextDTOMetadataAnyOf = { [key: string]: unknown };--/**- * Page-specific extras. metadata.page identifies list/draft pages and detail-as-metadata pages. Required non-empty metadata keys: panel_edit.widgetId, panel_fullscreen.widgetId, trace_detail.traceId. timeRange.{start,end} use Unix milliseconds.- */-export type MessageContextDTOMetadata = MessageContextDTOMetadataAnyOf | null;--export interface MessageContextDTO {- /**- * @enum auto,mention- * @type string- * @description "auto" if derived from current page; "mention" if explicitly @-picked.- */- source: MessageContextDTOSource;- /**- * @enum dashboard,alert,saved_view,logs_explorer,traces_explorer,metrics_explorer,service- * @type string- * @description Resource taxonomy. Use metadata.page for concrete page identity.- */- type: MessageContextDTOType;- /**- * @description Required for resource-detail pages: dashboard_detail, panel_edit, panel_fullscreen, alert_edit, service_detail. Always required for saved_view (mention-only — no list page in V1). Must be null for list/index/draft/detail-as-metadata pages such as dashboard_list, alert_list, alert_new, alerts_triggered, services_list, log_detail, and trace_detail.- */- resourceId?: MessageContextDTOResourceId;- resourceName?: MessageContextDTOResourceName;- /**- * @description Page-specific extras. metadata.page identifies list/draft pages and detail-as-metadata pages. Required non-empty metadata keys: panel_edit.widgetId, panel_fullscreen.widgetId, trace_detail.traceId. timeRange.{start,end} use Unix milliseconds.- */- metadata?: MessageContextDTOMetadata;-}-export enum MessageRoleDTO {user = 'user',assistant = 'assistant',@@ -616,6 +656,10 @@ export interface RevertRequestDTO {actionMetadataId: string;}+export enum ScopeDTO {+ user = 'user',+ org = 'org',+}export type ThreadDetailResponseDTOTitle = string | null;export type ThreadDetailResponseDTOState = ExecutionStateDTO | null;@@ -663,18 +707,6 @@ export interface ThreadDetailResponseDTO {export type ThreadListResponseDTONextCursor = string | null;-export interface ThreadListResponseDTO {- /**- * @type array- */- threads: ThreadSummaryDTO[];- nextCursor?: ThreadListResponseDTONextCursor;- /**- * @type boolean- */- hasMore?: boolean;-}-export type ThreadSummaryDTOTitle = string | null;export type ThreadSummaryDTOState = ExecutionStateDTO | null;@@ -709,6 +741,18 @@ export interface ThreadSummaryDTO {updatedAt: string;}+export interface ThreadListResponseDTO {+ /**+ * @type array+ */+ threads: ThreadSummaryDTO[];+ nextCursor?: ThreadListResponseDTONextCursor;+ /**+ * @type boolean+ */+ hasMore?: boolean;+}+export interface UndoRequestDTO {/*** @type string@@ -726,28 +770,29 @@ export interface UpdateThreadRequestDTO {archived?: UpdateThreadRequestDTOArchived;}-export type ValidationErrorDTOLocItem = string | number;--export type ValidationErrorDTOCtx = { [key: string]: unknown };+export type UsageResponseDTONextPage = string | null;-export interface ValidationErrorDTO {- /**- * @type array- */- loc: ValidationErrorDTOLocItem[];- /**- * @type string- */- msg: string;+/**+ * One row in the ``GET /usage`` response.+ */+export interface UsageRowDTO {+ type: CounterTypeNameDTO;+ scope: ScopeDTO;+ used: number;+ limit: number;/*** @type string+ * @format date-time*/- type: string;- input?: unknown;+ resetsAt: string;+}++export interface UsageResponseDTO {/**- * @type object+ * @type array*/- ctx?: ValidationErrorDTOCtx;+ data: UsageRowDTO[];+ nextPage?: UsageResponseDTONextPage;}export type ApprovalEventDTODiff = { [key: string]: unknown };@@ -909,6 +954,20 @@ export interface ErrorEventDTO {retryAction?: RetryActionDTO;}+/**+ * Per-connection SSE keep-alive emitted every `sse_heartbeat_interval_seconds`.++ Carries no `executionId` and no `eventId` — heartbeats are wire-level+ keep-alives, not part of the replayable event log.+ */+export const HeartbeatEventDTOValue = {+ /**+ * @type string+ */+ type: 'heartbeat',+} as const;+export type HeartbeatEventDTO = typeof HeartbeatEventDTOValue;+export type MessageActionEventDTOActionMetadataId = string | null;export type MessageActionEventDTOResourceType = string | null;@@ -1315,3 +1374,14 @@ export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders = {*/'X-SigNoz-URL'?: string | null;};++export type GetUsageApiV1AssistantUsageGetHeaders = {+ /**+ * @description SigNoz auth token (Bearer or raw JWT)+ */+ authorization?: string | null;+ /**+ * @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.+ */+ 'X-SigNoz-URL'?: string | null;+};diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.tsindex 32fb7bde78..5dd5c61ea5 100644--- a/frontend/src/constants/routes.ts+++ b/frontend/src/constants/routes.ts@@ -88,6 +88,7 @@ const ROUTES = {PUBLIC_DASHBOARD: '/public/dashboard/:dashboardId',SERVICE_ACCOUNTS_SETTINGS: '/settings/service-accounts',AI_ASSISTANT: '/ai-assistant/:conversationId',+ AI_ASSISTANT_BASE: '/ai-assistant',AI_ASSISTANT_ICON_PREVIEW: '/ai-assistant-icon-preview',MCP_SERVER: '/settings/mcp-server',} as const;diff --git a/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsx b/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsxindex dedfcc85f8..f13a5fdf26 100644--- a/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsx+++ b/frontend/src/container/AIAssistant/components/MessageBubble/MessageBubble.tsx@@ -178,7 +178,7 @@ export default function MessageBubble({</div></div>- {!isUser && (+ {!isUser && !message.isRateLimitError && (<MessageFeedbackmessage={message}onRegenerate={onRegenerate}diff --git a/frontend/src/container/AIAssistant/store/useAIAssistantStore.ts b/frontend/src/container/AIAssistant/store/useAIAssistantStore.tsindex ca838c19d8..c881e4c75d 100644--- a/frontend/src/container/AIAssistant/store/useAIAssistantStore.ts+++ b/frontend/src/container/AIAssistant/store/useAIAssistantStore.ts@@ -1,10 +1,12 @@/* eslint-disable sonarjs/cognitive-complexity */+import axios from 'axios';import { v4 as uuidv4 } from 'uuid';import { create } from 'zustand';import { persist } from 'zustand/middleware';import { immer } from 'zustand/middleware/immer';import type {+ ErrorResponseDTO,MessageActionDTO,MessageSummaryDTOBlocksAnyOfItem,} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';@@ -21,7 +23,6 @@ import {regenerateMessage,rejectExecution,sendMessage as sendMessageToThread,- SSEStreamError,streamEvents,submitFeedback,ThreadSummary,@@ -193,13 +194,75 @@ function resetStreamingState(};}+/**+ * Marker thrown by `runStreamingLoop` when an SSE event reports+ * `invalid_token`. Callers that own an originating action (sendMessage /+ * approve / clarify / regenerate) catch this and re-issue that action via+ * `streamWithAuthRetry`; the retry's first REST call will 401, at which point+ * the shared axios `interceptorRejected` rotates the access token and replays.+ */+class AuthExpiredError extends Error {+ constructor() {+ super('Access token expired during execution');+ this.name = 'AuthExpiredError';+ }+}++/**+ * Runs the originating action (e.g. sendMessage POST) and streams the+ * resulting execution. On `AuthExpiredError`, re-issues `start` once — the+ * retry's REST call hits 401, the shared axios interceptor rotates the+ * access token and replays, and the new SSE picks up the rotated token from+ * localStorage. Backend signals `retryAction: 'manual'` for `invalid_token`,+ * so the dead execution can't be resumed — only a fresh one helps.+ */+async function streamWithAuthRetry(+ conversationId: string,+ start: () => Promise<string>,+ set: StoreSetter,+): Promise<void> {+ for (let attempt = 0; attempt <= 1; attempt += 1) {+ if (attempt > 0) {+ // Drop any partial content/events from the previous attempt so the+ // retried execution's stream isn't concatenated with the dead one.+ set((s) => {+ resetStreamingState(s, conversationId);+ });+ }+ // eslint-disable-next-line no-await-in-loop+ const executionId = await start();+ const ctrl = newStreamController(conversationId);+ try {+ // eslint-disable-next-line no-await-in-loop+ await runStreamingLoop(executionId, {+ conversationId,+ set,+ signal: ctrl.signal,+ });+ streamControllers.delete(conversationId);+ return;+ } catch (err) {+ streamControllers.delete(conversationId);+ if (err instanceof AuthExpiredError && attempt < 1) {+ continue;+ }+ throw err;+ }+ }+}+/*** Runs one SSE execution stream, updating the per-conversation stream state.** Breaks early and sets pendingApproval / pendingClarification when the* agent needs user input before it can continue.*- * Throws on `error` events — the caller's catch block handles UI feedback.+ * On an `invalid_token` error event (e.g. MCP auth expired mid-execution),+ * throws `AuthExpiredError` so the caller can re-issue the originating+ * action via `streamWithAuthRetry`. We don't refresh here ourselves — the+ * retry's REST call will 401 and the shared axios `interceptorRejected`+ * handles rotation + replay. Throws on any other `error` event — the+ * caller's catch block handles UI feedback.*/// eslint-disable-next-line sonarjs/cognitive-complexityasync function runStreamingLoop(@@ -325,6 +388,15 @@ async function runStreamingLoop(});break;} else if (event.type === 'error') {+ // MCP/SigNoz auth expired mid-execution — signal the caller to+ // re-issue the originating action. The retry's REST call will hit+ // 401 and the shared axios `interceptorRejected` will rotate the+ // access token + replay, so we don't refresh here ourselves.+ // (Backend sets `retryAction: 'manual'`, so the failed execution+ // can't itself be resumed — only a fresh one helps.)+ if (event.error.code === 'invalid_token') {+ throw new AuthExpiredError();+ }throw Object.assign(new Error(event.error.message), {retryAction: event.retryAction,});@@ -412,13 +484,41 @@ function hasPendingInput(conversationId: string, get: StoreGetter): boolean {return Boolean(stream?.pendingApproval || stream?.pendingClarification);}+function parseErrorBody(value: unknown): string | null {+ if (typeof value === 'string') {+ try {+ return parseErrorBody(JSON.parse(value));+ } catch {+ return null;+ }+ }+ const message = (value as ErrorResponseDTO | undefined)?.error?.message;+ return typeof message === 'string' && message.length > 0 ? message : null;+}+/**- * Commits an error message and removes the stream entry.+ * Returns the backend's `error.message` when `err` is a 429 axios response+ * (typically from the threads API surface — createThread, sendMessage, approve,+ * clarify, regenerate). Returns null for any other error so callers fall+ * through to their generic copy.+ */+function rateLimitMessage(err: unknown): string | null {+ if (axios.isAxiosError(err) && err.response?.status === 429) {+ return parseErrorBody(err.response.data);+ }+ return null;+}++/**+ * Commits an error message and removes the stream entry. When `isRateLimit`+ * is true, the committed message is flagged so the feedback/regenerate bar+ * is hidden — clicking regenerate would just 429 again.*/function finalizeStreamingError(conversationId: string,errorContent: string,set: StoreSetter,+ isRateLimit = false,): void {set((s) => {const conv = s.conversations[conversationId];@@ -428,6 +528,7 @@ function finalizeStreamingError(role: 'assistant',content: errorContent,createdAt: Date.now(),+ ...(isRateLimit ? { isRateLimitError: true } : {}),});conv.updatedAt = Date.now();}@@ -801,7 +902,12 @@ export const useAIAssistantStore = create<AIAssistantStore>()(});// Reconnect to SSE if backend execution is still running- // and we don't already have an active SSE reader for this thread+ // and we don't already have an active SSE reader for this+ // thread. No auth-retry wrapper here: on `invalid_token`+ // there's no "originating action" to redo — reopening the+ // same dead executionId would just re-emit the failure.+ // Let the error bubble; the user can send a new message,+ // which will go through `streamWithAuthRetry`.if (detail.activeExecutionId &&!streamControllers.has(threadId) &&@@ -1052,14 +1158,12 @@ export const useAIAssistantStore = create<AIAssistantStore>()(}});}- const executionId = await sendMessageToThread(threadId, text, contexts);- const ctrl = newStreamController(convId);- await runStreamingLoop(executionId, {- conversationId: convId,+ const tid = threadId;+ await streamWithAuthRetry(+ convId,+ () => sendMessageToThread(tid, text, contexts),set,- signal: ctrl.signal,- });- streamControllers.delete(convId);+ );if (!hasPendingInput(convId, get)) {finalizeStreamingMessage(convId, set, get);@@ -1070,11 +1174,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(return;}console.error('[AIAssistant] sendMessage failed:', err);- const message =- err instanceof SSEStreamError && err.status === 429- ? 'You sent that a bit too quickly. Please wait a moment and try again.'- : 'Something went wrong while fetching the response. Please try again.';- finalizeStreamingError(convId, message, set);+ const rateLimit = rateLimitMessage(err);+ finalizeStreamingError(+ convId,+ rateLimit ??+ 'Something went wrong while fetching the response. Please try again.',+ set,+ rateLimit !== null,+ );}},@@ -1094,14 +1201,11 @@ export const useAIAssistantStore = create<AIAssistantStore>()(});try {- const executionId = await approveExecution(approvalId);- const ctrl = newStreamController(conversationId);- await runStreamingLoop(executionId, {+ await streamWithAuthRetry(conversationId,+ () => approveExecution(approvalId),set,- signal: ctrl.signal,- });- streamControllers.delete(conversationId);+ );if (!hasPendingInput(conversationId, get)) {finalizeStreamingMessage(conversationId, set, get);}@@ -1110,10 +1214,13 @@ export const useAIAssistantStore = create<AIAssistantStore>()(return;}console.error('[AIAssistant] approveAction failed:', err);+ const rateLimit = rateLimitMessage(err);finalizeStreamingError(conversationId,- 'Something went wrong while processing the approval. Please try again.',+ rateLimit ??+ 'Something went wrong while processing the approval. Please try again.',set,+ rateLimit !== null,);}},@@ -1176,14 +1283,11 @@ export const useAIAssistantStore = create<AIAssistantStore>()(});try {- const executionId = await regenerateMessage(messageId);- const ctrl = newStreamController(conversationId);- await runStreamingLoop(executionId, {+ await streamWithAuthRetry(conversationId,+ () => regenerateMessage(messageId),set,- signal: ctrl.signal,- });- streamControllers.delete(conversationId);+ );if (!hasPendingInput(conversationId, get)) {finalizeStreamingMessage(conversationId, set, get);}@@ -1192,10 +1296,13 @@ export const useAIAssistantStore = create<AIAssistantStore>()(return;}console.error('[AIAssistant] regenerateAssistantMessage failed:', err);+ const rateLimit = rateLimitMessage(err);finalizeStreamingError(conversationId,- 'Something went wrong while regenerating the response. Please try again.',+ rateLimit ??+ 'Something went wrong while regenerating the response. Please try again.',set,+ rateLimit !== null,);}},@@ -1245,14 +1352,11 @@ export const useAIAssistantStore = create<AIAssistantStore>()(});try {- const executionId = await clarifyExecution(clarificationId, answers);- const ctrl = newStreamController(conversationId);- await runStreamingLoop(executionId, {+ await streamWithAuthRetry(conversationId,+ () => clarifyExecution(clarificationId, answers),set,- signal: ctrl.signal,- });- streamControllers.delete(conversationId);+ );if (!hasPendingInput(conversationId, get)) {finalizeStreamingMessage(conversationId, set, get);}@@ -1261,10 +1365,13 @@ export const useAIAssistantStore = create<AIAssistantStore>()(return;}console.error('[AIAssistant] submitClarification failed:', err);+ const rateLimit = rateLimitMessage(err);finalizeStreamingError(conversationId,- 'Something went wrong while processing your answers. Please try again.',+ rateLimit ??+ 'Something went wrong while processing your answers. Please try again.',set,+ rateLimit !== null,);}},diff --git a/frontend/src/container/AIAssistant/types.ts b/frontend/src/container/AIAssistant/types.tsindex 57eae04a48..34ca31f975 100644--- a/frontend/src/container/AIAssistant/types.ts+++ b/frontend/src/container/AIAssistant/types.ts@@ -86,6 +86,11 @@ export interface Message {actions?: MessageActionDTO[];/** Persisted feedback rating — set after user votes and the API confirms. */feedbackRating?: FeedbackRating | null;+ /**+ * Set on client-side rate-limit error messages so the feedback/regenerate+ * bar (copy/vote/regenerate) is hidden — retrying would just 429 again.+ */+ isRateLimitError?: boolean;createdAt: number;}diff --git a/frontend/src/styles.scss b/frontend/src/styles.scssindex 60d9d8d7a1..007dd197de 100644--- a/frontend/src/styles.scss+++ b/frontend/src/styles.scss@@ -825,4 +825,5 @@ body.ai-assistant-panel-open {// overrides:root {--input-focus-outline-width: 0;+ --radius-2: 4px;}diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.tsindex 2372e7a153..29792ec9b5 100644--- a/frontend/src/utils/permission/index.ts+++ b/frontend/src/utils/permission/index.ts@@ -135,4 +135,5 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {AI_ASSISTANT: ['ADMIN', 'EDITOR', 'VIEWER'],AI_ASSISTANT_ICON_PREVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],MCP_SERVER: ['ADMIN', 'EDITOR', 'VIEWER'],+ AI_ASSISTANT_BASE: ['ADMIN', 'EDITOR', 'VIEWER'],};