All files / apps/chatbot/src/services chatbotService.ts

97.94% Statements 143/146
92.56% Branches 112/121
95.23% Functions 20/21
100% Lines 140/140

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371                                                                                                                        6x   35x 15x 3x 1x       41x 41x 41x 41x   41x 78x 78x 39x     39x 39x   39x 69x 30x 30x   39x 39x       39x     41x     6x 64x 35x 35x             64x 18x 18x         18x 18x 3x   15x     64x   16x 16x 16x         16x   16x 4x     12x 12x 2x         10x 10x     10x 10x 1x     10x                   35x 35x   35x 35x 35x 35x 35x   35x 35x 35x 35x 35x     35x 35x 35x 35x 35x   35x 13x 13x 13x 13x 2x   13x             35x 36x   10x 8x 8x   10x     3x 2x 2x       3x     4x 4x     12x 12x 2x   12x 12x     5x 4x 4x   5x       2x       35x 45x   44x 44x 44x   44x 41x 41x 41x   41x 39x 39x 39x 38x 2x 2x 2x   2x   36x               44x 4x 1x 1x 3x   1x         35x 3x 1x 1x     35x           2x                   35x   1x 1x           15x       13x           13x 13x 13x                                             3x 2x                 1x 1x       1x        
import { confirmedCardTitle } from "@/utils/actionLabel";
 
import { Block, ChatbotPendingAction, ChatbotSharedState } from "@/types/chat";
 
import {
  mapBackendBlocks,
  pendingFromOutcome,
  sharedStateFromSnapshot,
  toSuggestionChips,
} from "./chatbotMappers";
 
export { mapBackendBlocks, pendingFromOutcome, sharedStateFromSnapshot, toSuggestionChips };
 
export interface ChatbotServiceConfig {
  baseUrl: string;
  getAccessToken: () => Promise<string | null>;
}
 
export interface ChatbotImagePayload {
  data: string;
  name?: string;
  type?: string;
}
 
export interface SSEEvent {
  event: string;
  data: string;
}
 
export interface StreamCallbacks {
  onDelta: (delta: string) => void;
  onCompleted: (data: {
    message: { text: string; blocks: Block[] };
    pendingAction: ChatbotPendingAction | null;
    sharedState?: ChatbotSharedState | null;
  }) => void;
  onError: (error: Error | any) => void;
}
 
export interface ChatbotService {
  createThread(scope?: string, screenContext?: string): Promise<any>;
  streamMessage(
    threadId: string,
    text: string,
    callbacks: StreamCallbacks,
    images?: ChatbotImagePayload[],
    /**
     * Stable id for THIS composed message. Pass the SAME value when retrying
     * after a dropped connection: the server recognises the repeat and replays
     * the stored turn instead of running the model — and charging for — the
     * same message twice. Omit it and a retry is indistinguishable from a new
     * message.
     */
    clientMessageId?: string,
  ): Promise<{ abort: () => void }>;
  confirmAction(threadId: string, pendingActionId: string, actionType?: string): Promise<any>;
  cancelAction(threadId: string, pendingActionId: string): Promise<any>;
  resetThread(threadId: string): Promise<any>;
}
 
const ENDPOINTS = {
  THREADS: "/api/v1/chat/threads",
  STREAM: (threadId: string) => `/api/v1/chat/threads/${threadId}/messages/stream`,
  ACTIONS_CONFIRM: (threadId: string) => `/api/v1/chat/threads/${threadId}/actions/confirm`,
  ACTIONS_CANCEL: (threadId: string) => `/api/v1/chat/threads/${threadId}/actions/cancel`,
  RESET: (threadId: string) => `/api/v1/chat/threads/${threadId}/reset`,
};
 
function parseSSEEvents(rawChunk: string) {
  const normalized = rawChunk.replace(/\r\n/g, "\n");
  const parts = normalized.split("\n\n");
  const rest = normalized.endsWith("\n\n") ? "" : (parts.pop() ?? "");
  const events: SSEEvent[] = [];
 
  for (const part of parts) {
    const lines = part.split("\n").filter(Boolean);
    if (lines.length === 0) {
      continue;
    }
 
    let eventName = "message";
    const dataLines: string[] = [];
 
    for (const line of lines) {
      if (line.startsWith("event:")) {
        eventName = line.slice(6).trim();
        continue;
      }
      Eif (line.startsWith("data:")) {
        dataLines.push(line.slice(5).trimStart());
      }
    }
 
    events.push({ event: eventName, data: dataLines.join("\n") });
  }
 
  return { events, rest };
}
 
export const createChatbotService = (config: ChatbotServiceConfig): ChatbotService => {
  const getHeaders = async () => {
    const token = await config.getAccessToken();
    return {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      Accept: "application/json",
    };
  };
 
  const postAction = async (path: string, pendingActionId: string) => {
    const headers = await getHeaders();
    const response = await fetch(`${config.baseUrl}${path}`, {
      method: "POST",
      headers,
      body: JSON.stringify({ pendingActionId }),
    });
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(payload?.error?.message || `Action failed (${response.status})`);
    }
    return payload;
  };
 
  return {
    async createThread(scope?: string) {
      const headers = await getHeaders();
      const body = scope ? { scope } : {};
      const response = await fetch(`${config.baseUrl}${ENDPOINTS.THREADS}`, {
        method: "POST",
        headers,
        body: JSON.stringify(body),
      });
      const data = await response.json().catch(() => ({}) as any);
 
      if (!response.ok) {
        throw new Error(data?.error?.message || `Failed to create thread (${response.status})`);
      }
 
      const threadId = data.thread?.id || data.id;
      if (!threadId) {
        throw new Error("Failed to create thread (no thread id in response)");
      }
 
      // The backend seeds a fresh thread with a welcome message (assistant text +
      // default suggestions), mapped through the same block path as streaming.
      const welcomeBlocks = mapBackendBlocks(data.message?.blocks ?? []);
      const welcomeSuggestions = Array.isArray(data.message?.suggestions)
        ? data.message.suggestions
        : [];
      const blocks = [...welcomeBlocks];
      if (welcomeSuggestions.length > 0) {
        blocks.push({ type: "suggestions", items: welcomeSuggestions });
      }
 
      return {
        thread: {
          id: threadId,
          status: data.thread?.status || data.status,
        },
        message: blocks.length > 0 ? { text: data.message?.text || "", blocks } : undefined,
      };
    },
 
    async streamMessage(threadId, text, callbacks, images, clientMessageId) {
      const token = await config.getAccessToken();
      const url = `${config.baseUrl}${ENDPOINTS.STREAM(threadId)}`;
 
      const xhr = new XMLHttpRequest();
      xhr.open("POST", url);
      xhr.setRequestHeader("Authorization", `Bearer ${token}`);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.setRequestHeader("Accept", "text/event-stream");
 
      let seenBytes = 0;
      let aborted = false;
      let sseBuffer = "";
      let hasErrored = false;
      let completed = false;
 
      // Per-turn accumulators — folded from the AG-UI event stream.
      let streamedText = "";
      let finalBlocks: Block[] = [];
      let suggestionItems: string[] = [];
      let pendingAction: ChatbotPendingAction | null = null;
      let sharedState: any = null;
 
      const complete = () => {
        Iif (completed || hasErrored) return;
        completed = true;
        const blocks = [...finalBlocks];
        if (suggestionItems.length > 0) {
          blocks.push({ type: "suggestions", items: suggestionItems });
        }
        callbacks.onCompleted({
          message: { text: streamedText, blocks },
          pendingAction,
          sharedState,
        });
      };
 
      const handleAgUiEvent = (payload: any) => {
        switch (payload?.type) {
          case "TEXT_MESSAGE_CONTENT":
            if (typeof payload.delta === "string" && payload.delta.length > 0) {
              streamedText += payload.delta;
              callbacks.onDelta(payload.delta);
            }
            break;
 
          case "CUSTOM":
            if (payload.name === "message.blocks" && payload.value) {
              finalBlocks = mapBackendBlocks(payload.value.blocks ?? []);
              suggestionItems = Array.isArray(payload.value.suggestions)
                ? payload.value.suggestions
                : [];
            }
            break;
 
          case "STATE_SNAPSHOT":
            sharedState = sharedStateFromSnapshot(payload.snapshot);
            break;
 
          case "RUN_FINISHED":
            pendingAction = pendingFromOutcome(payload.outcome);
            if (pendingAction && sharedState?.pendingAction?.expiresAt) {
              pendingAction.expiresAt = sharedState.pendingAction.expiresAt;
            }
            complete();
            break;
 
          case "RUN_ERROR":
            if (!hasErrored) {
              hasErrored = true;
              callbacks.onError(new Error(payload.message || "Agent run failed."));
            }
            break;
 
          default:
            // RUN_STARTED / TEXT_MESSAGE_START|END / TOOL_CALL_* / message.metadata
            break;
        }
      };
 
      xhr.onreadystatechange = () => {
        if (aborted) return;
 
        Eif (xhr.readyState === 3 || xhr.readyState === 4) {
          const newData = xhr.responseText.substring(seenBytes);
          seenBytes = xhr.responseText.length;
 
          if (newData) {
            sseBuffer += newData;
            const { events, rest } = parseSSEEvents(sseBuffer);
            sseBuffer = rest;
 
            for (const streamEvent of events) {
              Iif (!streamEvent.data) continue;
              try {
                const payload = JSON.parse(streamEvent.data);
                if (streamEvent.event === "error") {
                  Eif (!hasErrored) {
                    hasErrored = true;
                    callbacks.onError(payload.error || payload);
                  }
                  continue;
                }
                handleAgUiEvent(payload);
              } catch {
                // Ignore malformed / keep-alive frames.
              }
            }
          }
        }
 
        if (xhr.readyState === 4) {
          if ((xhr.status < 200 || xhr.status >= 300) && !hasErrored) {
            hasErrored = true;
            callbacks.onError(new Error(`HTTP ${xhr.status}: ${xhr.responseText}`));
          } else if (!completed && !hasErrored) {
            // Stream closed without an explicit RUN_FINISHED — surface what we have.
            complete();
          }
        }
      };
 
      xhr.onerror = () => {
        if (aborted || hasErrored) return;
        hasErrored = true;
        callbacks.onError(new Error("Network error"));
      };
 
      xhr.send(
        JSON.stringify({
          message: text,
          ...(clientMessageId ? { clientMessageId } : {}),
          ...(images && images.length > 0
            ? {
                images: images.map((image, index) => ({
                  name: image.name || `image-${index}`,
                  mimeType: image.type || "image/jpeg",
                  url: image.data,
                })),
              }
            : {}),
        }),
      );
 
      return {
        abort: () => {
          aborted = true;
          xhr.abort();
        },
      };
    },
 
    async confirmAction(threadId: string, pendingActionId: string, actionType?: string) {
      const payload = await postAction(ENDPOINTS.ACTIONS_CONFIRM(threadId), pendingActionId);
      // The backend knows best what it just did; the caller's pending action
      // type is the fallback for agent builds that don't echo it back.
      const resolvedActionType =
        typeof payload?.actionType === "string" ? payload.actionType : actionType;
      // A confirm never runs a turn, so nothing streams in behind the success
      // card. The agent ships its closing line and the next-step chips in the
      // confirm response instead; without them the thread dead-ends on a
      // receipt. Both are optional — an older agent build simply omits them.
      const followUpMessage =
        typeof payload?.followUpMessage === "string" ? payload.followUpMessage.trim() : "";
      const suggestions = toSuggestionChips(payload?.suggestions);
      return {
        message: {
          text: "Request confirmed.",
          blocks: [
            {
              type: "status",
              status: "success",
              title: confirmedCardTitle(resolvedActionType),
              description: `Status: ${payload?.status ?? "completed"}.`,
              // Affected people (username/role/avatar) — rendered as rows
              // inside the success card when the backend provides them.
              ...(payload?.data?.information ? { data: payload.data } : {}),
            },
            ...(followUpMessage ? [{ type: "text", text: followUpMessage }] : []),
            // Chips are read off the latest bot turn's suggestions block, so
            // they have to ride this message to reach the composer strip.
            ...(suggestions.length > 0 ? [{ type: "suggestions", items: suggestions }] : []),
          ] as Block[],
        },
      };
    },
 
    async cancelAction(threadId: string, pendingActionId: string) {
      await postAction(ENDPOINTS.ACTIONS_CANCEL(threadId), pendingActionId);
      return {
        message: {
          text: "Request cancelled.",
          blocks: [{ type: "status", status: "cancelled", title: "Cancelled" }] as Block[],
        },
      };
    },
 
    async resetThread(threadId: string) {
      const headers = await getHeaders();
      const response = await fetch(`${config.baseUrl}${ENDPOINTS.RESET(threadId)}`, {
        method: "POST",
        headers,
      });
      return response.json();
    },
  };
};