Compare commits

...

3 Commits

Author SHA1 Message Date
Yunus M
18f89b2ef1 chore: remove local overrides 2026-05-26 19:56:22 +05:30
Yunus M
99102baa94 feat: ai assistant routing, mid-execution auth recovery 2026-05-26 19:56:22 +05:30
Yunus M
4122bea16b feat: update routing and permissions for AI Assistant feature 2026-05-26 19:56:22 +05:30
11 changed files with 452 additions and 261 deletions

View File

@@ -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} />;
}

View File

@@ -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');

View File

@@ -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',

View File

@@ -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}` : '';
}

View File

@@ -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,178 +262,21 @@ export interface ClarifyResponseDTO {
executionId: string;
}
export type CreateMessageRequestDTOContexts = MessageContextDTO[] | null;
export type CreateMessageRequestDTOForkFromMessageId = string | null;
export interface CreateMessageRequestDTO {
/**
* @type string
* @maxLength 20000
* @minLength 1
*/
content: string;
contexts?: CreateMessageRequestDTOContexts;
forkFromMessageId?: CreateMessageRequestDTOForkFromMessageId;
}
export interface CreateMessageResponseDTO {
/**
* @type string
* @format uuid
*/
executionId: string;
}
export type CreateThreadRequestDTOTitle = string | null;
export interface CreateThreadRequestDTO {
title?: CreateThreadRequestDTOTitle;
}
export interface CreateThreadResponseDTO {
/**
* @type string
* @format uuid
*/
threadId: string;
}
export type ErrorBodyDTOErrors = ErrorResponseAdditionalDTO[] | null;
export type ErrorBodyDTOUrl = string | null;
/**
* Inner error object — matches Go ErrorsJSON.
*/
export interface ErrorBodyDTO {
/**
* @type string
* @pattern ^[a-z_]+$
*/
code: string;
/**
* @type string
*/
message: string;
errors?: ErrorBodyDTOErrors;
url?: ErrorBodyDTOUrl;
}
/**
* Top-level error envelope — matches Go RenderErrorResponse.
*/
export interface ErrorResponseDTO {
/**
* @type string
*/
status?: string;
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',
}
export type FeedbackRequestDTOComment = string | null;
export interface FeedbackRequestDTO {
rating: FeedbackRatingDTO;
comment?: FeedbackRequestDTOComment;
}
export interface FeedbackResponseDTO {
[key: string]: unknown;
}
export interface HTTPValidationErrorDTO {
/**
* @type array
*/
detail?: ValidationErrorDTO[];
}
export const HealthResponseDTOValue = {
/**
* @type string
*/
status: 'ok',
} as const;
export type HealthResponseDTO = typeof HealthResponseDTOValue;
export type MessageActionDTOActionMetadataId = string | null;
export type MessageActionDTOResourceType = string | null;
export type MessageActionDTOResourceId = string | null;
export type MessageActionDTOState = string | null;
export type MessageActionDTOInputAnyOf = { [key: string]: unknown };
export type MessageActionDTOInput = MessageActionDTOInputAnyOf | null;
export type MessageActionDTOTooltip = string | null;
export type MessageActionDTOSignal = ApplyFilterSignalDTO | null;
export type MessageActionDTOQueryAnyOf = { [key: string]: unknown };
export type MessageActionDTOQuery = MessageActionDTOQueryAnyOf | null;
export type MessageActionDTOUrl = string | null;
/**
* 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.
*/
export interface MessageActionDTO {
kind: MessageActionKindDTO;
/**
* @type string
*/
label: string;
actionMetadataId?: MessageActionDTOActionMetadataId;
resourceType?: MessageActionDTOResourceType;
resourceId?: MessageActionDTOResourceId;
state?: MessageActionDTOState;
input?: MessageActionDTOInput;
tooltip?: MessageActionDTOTooltip;
signal?: MessageActionDTOSignal;
query?: MessageActionDTOQuery;
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',
* 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.
@@ -482,6 +335,193 @@ export interface MessageContextDTO {
metadata?: MessageContextDTOMetadata;
}
export type CreateMessageRequestDTOContexts = MessageContextDTO[] | null;
export type CreateMessageRequestDTOForkFromMessageId = string | null;
export interface CreateMessageRequestDTO {
/**
* @type string
* @maxLength 20000
* @minLength 1
*/
content: string;
contexts?: CreateMessageRequestDTOContexts;
forkFromMessageId?: CreateMessageRequestDTOForkFromMessageId;
}
export interface CreateMessageResponseDTO {
/**
* @type string
* @format uuid
*/
executionId: string;
}
export type CreateThreadRequestDTOTitle = string | null;
export interface CreateThreadRequestDTO {
title?: CreateThreadRequestDTOTitle;
}
export interface CreateThreadResponseDTO {
/**
* @type string
* @format uuid
*/
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;
/**
* Inner error object — matches Go ErrorsJSON.
*/
export interface ErrorBodyDTO {
/**
* @type string
* @pattern ^[a-z_]+$
*/
code: string;
/**
* @type string
*/
message: string;
errors?: ErrorBodyDTOErrors;
url?: ErrorBodyDTOUrl;
}
/**
* Top-level error envelope — matches Go RenderErrorResponse.
*/
export interface ErrorResponseDTO {
/**
* @type string
*/
status?: string;
error: ErrorBodyDTO;
}
export enum FeedbackRatingDTO {
positive = 'positive',
negative = 'negative',
}
export type FeedbackRequestDTOComment = string | null;
export interface FeedbackRequestDTO {
rating: FeedbackRatingDTO;
comment?: FeedbackRequestDTOComment;
}
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
*/
detail?: ValidationErrorDTO[];
}
export const HealthResponseDTOValue = {
/**
* @type string
*/
status: 'ok',
} as const;
export type HealthResponseDTO = typeof HealthResponseDTOValue;
export type MessageActionDTOActionMetadataId = string | null;
export type MessageActionDTOResourceType = string | null;
export type MessageActionDTOResourceId = string | null;
export type MessageActionDTOState = string | null;
export type MessageActionDTOInputAnyOf = { [key: string]: unknown };
export type MessageActionDTOInput = MessageActionDTOInputAnyOf | null;
export type MessageActionDTOTooltip = string | null;
export type MessageActionDTOSignal = ApplyFilterSignalDTO | null;
export type MessageActionDTOQueryAnyOf = { [key: string]: unknown };
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.
*/
export interface MessageActionDTO {
kind: MessageActionKindDTO;
/**
* @type string
*/
label: string;
actionMetadataId?: MessageActionDTOActionMetadataId;
resourceType?: MessageActionDTOResourceType;
resourceId?: MessageActionDTOResourceId;
state?: MessageActionDTOState;
input?: MessageActionDTOInput;
tooltip?: MessageActionDTOTooltip;
signal?: MessageActionDTOSignal;
query?: MessageActionDTOQuery;
url?: MessageActionDTOUrl;
}
export enum MessageContentTypeDTO {
markdown = 'markdown',
}
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 UsageResponseDTONextPage = string | null;
export type ValidationErrorDTOCtx = { [key: string]: unknown };
/**
* One row in the ``GET /usage`` response.
*/
export interface UsageRowDTO {
type: CounterTypeNameDTO;
scope: ScopeDTO;
used: number;
limit: number;
/**
* @type string
* @format date-time
*/
resetsAt: string;
}
export interface ValidationErrorDTO {
export interface UsageResponseDTO {
/**
* @type array
*/
loc: ValidationErrorDTOLocItem[];
/**
* @type string
*/
msg: string;
/**
* @type string
*/
type: string;
input?: unknown;
/**
* @type object
*/
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;
};

View File

@@ -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;

View File

@@ -178,7 +178,7 @@ export default function MessageBubble({
</div>
</div>
{!isUser && (
{!isUser && !message.isRateLimitError && (
<MessageFeedback
message={message}
onRegenerate={onRegenerate}

View File

@@ -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-complexity
async 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,
);
}
},

View File

@@ -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;
}

View File

@@ -825,4 +825,5 @@ body.ai-assistant-panel-open {
// overrides
:root {
--input-focus-outline-width: 0;
--radius-2: 4px;
}

View File

@@ -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'],
};