File size: 5,267 Bytes
5eefa6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ─── Types ────────────────────────────────────────────────────────────────────

export interface InterviewFramework {
  id: string;
  name: string;
}

export interface CreateSessionResponse {
  session_id: string;
  framework_id: string;
  room_id: string;
  status: string;
  opening_message: string;
  first_question: string;
}

export interface MessageResponse {
  reply: string;
  stage: "in_progress" | "next_question" | "follow_up" | "closing";
  finished: boolean;
}

export interface QAPair {
  question_text: string;
  answer_cleaned: string;
  follow_ups?: QAPair[];
}

export interface SectionResult {
  section_title: string;
  objective: string[];
  qa_pairs: QAPair[];
  section_summary: string;
}

export interface InterviewResult {
  framework_name: string;
  mode: string;
  language: string;
  started_at: string;
  ended_at: string;
  summary: string;
  goals: string[];
  section_results: SectionResult[];
  key_insights: string[];
  unresolved_items: string[];
}

export interface FinishSessionResponse {
  session_id: string;
  room_id: string;
  status: string;
  result: InterviewResult;
}

export interface StreamMetadata {
  finished: boolean;
  stage: "next_question" | "follow_up" | "closing";
}

export type AudioServerEvent =
  | { type: "token_chunk"; payload: string }
  | { type: "assistant_reply"; payload: string }
  | { type: "session_done" }
  | { type: "error"; payload: string };

// ─── Base Client ──────────────────────────────────────────────────────────────

const INTERVIEW_BASE_URL =
  ((import.meta as unknown as { env: Record<string, string> }).env
    .VITE_ORCHESTRATION_API_BASE_URL) ?? "http://localhost:8080";

async function request<T>(path: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${INTERVIEW_BASE_URL}${path}`, {
    headers: { "Content-Type": "application/json", ...options?.headers },
    ...options,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
    throw new Error(err.error ?? `HTTP ${res.status}`);
  }
  return res.json() as Promise<T>;
}

// ─── Endpoints ────────────────────────────────────────────────────────────────

export const getFrameworks = (): Promise<InterviewFramework[]> =>
  request<InterviewFramework[]>("/frameworks");

export const createSession = (
  frameworkId: string,
  userId: string,
  roomId: string,
  mode: "text" | "audio" = "text",
  language = "id-ID"
): Promise<CreateSessionResponse> =>
  request<CreateSessionResponse>("/sessions", {
    method: "POST",
    body: JSON.stringify({ framework_id: frameworkId, user_id: userId, room_id: roomId, mode, language }),
  });

export const sendMessage = (
  sessionId: string,
  message: string
): Promise<MessageResponse> =>
  request<MessageResponse>(`/sessions/${sessionId}/message`, {
    method: "POST",
    body: JSON.stringify({ message }),
  });

export const finishSession = (
  sessionId: string
): Promise<FinishSessionResponse> =>
  request<FinishSessionResponse>(`/sessions/${sessionId}/finish`, {
    method: "POST",
  });

export const getInterviewResult = (roomId: string): Promise<InterviewResult> =>
  request<InterviewResult>(`/rooms/${roomId}/result`);

// SSE streaming β€” returns raw Response so caller can read the stream
export const streamMessage = (
  sessionId: string,
  message: string
): Promise<Response> =>
  fetch(`${INTERVIEW_BASE_URL}/sessions/${sessionId}/stream-message`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ message }),
  });

// ─── Audio WebSocket ──────────────────────────────────────────────────────────

export interface AudioSessionHandle {
  sendAudioChunk: (chunk: ArrayBuffer) => void;
  sendEndUtterance: () => void;
  close: () => void;
}

export function openAudioSession(
  sessionId: string,
  onEvent: (event: AudioServerEvent) => void,
  onAudio: (audioBuffer: ArrayBuffer) => void,
  onClose: () => void
): AudioSessionHandle {
  const wsBase = INTERVIEW_BASE_URL.replace(/^http/, "ws");
  const ws = new WebSocket(`${wsBase}/ws/audio?session_id=${sessionId}`);
  ws.binaryType = "arraybuffer";

  ws.onmessage = (e) => {
    if (e.data instanceof ArrayBuffer) {
      onAudio(e.data);
    } else {
      try {
        const parsed = JSON.parse(e.data) as AudioServerEvent;
        onEvent(parsed);
      } catch {
        // ignore malformed messages
      }
    }
  };

  ws.onclose = onClose;

  return {
    sendAudioChunk: (chunk) => {
      if (ws.readyState === WebSocket.OPEN) ws.send(chunk);
    },
    sendEndUtterance: () => {
      if (ws.readyState === WebSocket.OPEN)
        ws.send(JSON.stringify({ type: "end_utterance" }));
    },
    close: () => ws.close(),
  };
}