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 | 8x 8x 8x 8x 8x 14x 14x 6x 8x 8x 8x 17x 8x 8x 9x 9x 8x 8x 4x 4x 4x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 5x 1x 1x 1x 7x 1x 1x 1x 7x 7x 1x 1x 4x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x | import { CHATBOT_BASE_URL, ENDPOINTS } from '@/constants/apis';
import { getAccessToken } from './mainHttpClient';
export interface ChatbotMessage {
id: string;
role: 'user' | 'assistant';
text: string;
}
export interface ChatbotImagePayload {
data: string;
name?: string;
type?: string;
}
export interface ChatbotThread {
id: string;
status: string;
}
export interface ChatbotPendingAction {
id: string;
type: string;
status: string;
summary: any;
}
export interface SSEEvent {
event: string;
data: any;
}
class ChatbotService {
private 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 };
}
private getHeaders = async () => {
const token = await getAccessToken();
return {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
Accept: 'application/json',
};
};
async createThread(scope: string = 'time_off_on_behalf') {
const headers = await this.getHeaders();
const response = await fetch(`${CHATBOT_BASE_URL}${ENDPOINTS.CHATBOT.THREADS}`, {
method: 'POST',
headers,
body: JSON.stringify({ scope, context: { screen: 'on_behalf' } }),
});
return response.json();
}
async streamMessage(
threadId: string,
text: string,
callbacks: {
onDelta: (delta: string) => void;
onCompleted: (data: any) => void;
onError: (error: any) => void;
},
images?: ChatbotImagePayload[],
) {
const token = await getAccessToken();
const url = `${CHATBOT_BASE_URL}${ENDPOINTS.CHATBOT.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;
xhr.onreadystatechange = () => {
if (aborted) return;
Eif (xhr.readyState === 3 || xhr.readyState === 4) {
const newData = xhr.responseText.substring(seenBytes);
seenBytes = xhr.responseText.length;
Eif (newData) {
sseBuffer += newData;
const { events, rest } = this.parseSSEEvents(sseBuffer);
sseBuffer = rest;
for (const streamEvent of events) {
Iif (!streamEvent.data) {
continue;
}
try {
const data = JSON.parse(streamEvent.data);
this.handleSSEEvent(streamEvent.event, data, callbacks);
} catch {
// Ignore malformed SSE event payload
}
}
}
}
if (xhr.readyState === 4) {
Eif ((xhr.status < 200 || xhr.status >= 300) && !hasErrored) {
hasErrored = true;
callbacks.onError(new Error(`HTTP ${xhr.status}: ${xhr.responseText}`));
}
}
};
xhr.onerror = () => {
Iif (aborted || hasErrored) return;
hasErrored = true;
callbacks.onError(new Error('Network error'));
};
xhr.send(
JSON.stringify({
message: {
id: `msg_${Date.now()}`,
role: 'user',
text,
...(images && images.length > 0 ? { images } : {}),
},
}),
);
return {
abort: () => {
aborted = true;
xhr.abort();
},
};
}
private handleSSEEvent(event: string, data: any, callbacks: any) {
switch (event) {
case 'message.delta':
Eif (data.text) callbacks.onDelta(data.text);
break;
case 'message.completed':
callbacks.onCompleted(data);
break;
case 'error':
callbacks.onError(data.error);
break;
default:
// Ignore other events like ready, agent.start, tool.start, tool.finish, ping, done
break;
}
}
async confirmAction(threadId: string, pendingActionId: string) {
const headers = await this.getHeaders();
const response = await fetch(
`${CHATBOT_BASE_URL}${ENDPOINTS.CHATBOT.ACTIONS_CONFIRM(threadId)}`,
{
method: 'POST',
headers,
body: JSON.stringify({ pendingActionId }),
},
);
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload?.error?.message || `Failed to confirm action (${response.status})`);
}
return payload;
}
async cancelAction(threadId: string, pendingActionId: string) {
const headers = await this.getHeaders();
const response = await fetch(
`${CHATBOT_BASE_URL}${ENDPOINTS.CHATBOT.ACTIONS_CANCEL(threadId)}`,
{
method: 'POST',
headers,
body: JSON.stringify({ pendingActionId }),
},
);
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(payload?.error?.message || `Failed to cancel action (${response.status})`);
}
return payload;
}
async resetThread(threadId: string) {
const headers = await this.getHeaders();
const response = await fetch(`${CHATBOT_BASE_URL}${ENDPOINTS.CHATBOT.RESET(threadId)}`, {
method: 'POST',
headers,
});
return response.json();
}
}
export const chatbotService = new ChatbotService();
|