Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 102 additions & 16 deletions dembrane/frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,26 @@

import { i18n } from "@lingui/core";
import { t } from "@lingui/core/macro";
import axios, { type AxiosError, type CreateAxiosDefaults } from "axios";
import axios, {
type AxiosError,
type CreateAxiosDefaults,
type InternalAxiosRequestConfig,
} from "axios";
import { toast } from "@/components/common/Toaster";
import { VOICE_TRANSCRIBE_TIMEOUT_MS } from "@/components/voice/voiceInput";
import { API_BASE_URL } from "@/config";
import { bff } from "./bff";
import { loadErrorMessages } from "./errors/present";
import {
clearParticipantToken,
clearParticipantTokenValue,
isParticipantTokenRejection,
PARTICIPANT_TOKEN_HEADER,
participantTokenConfig,
participantTokenHeaders,
readResponseHeader,
setParticipantToken,
} from "./participantToken";

export const apiCommonConfig: CreateAxiosDefaults = {
baseURL: API_BASE_URL,
Expand All @@ -17,8 +31,44 @@ export const apiCommonConfig: CreateAxiosDefaults = {
export const apiNoAuth = axios.create(apiCommonConfig);

apiNoAuth.interceptors.response.use(
(response) => response.data,
(response) => {
const token = readResponseHeader(
response.headers,
PARTICIPANT_TOKEN_HEADER,
);
const conversationId =
response.data &&
typeof response.data === "object" &&
"id" in response.data &&
typeof (response.data as { id?: unknown }).id === "string"
? (response.data as { id: string }).id
: null;
if (token && conversationId) {
setParticipantToken(conversationId, token);
}
return response.data;
},
(error) => {
const config = (error as AxiosError)?.config as
| (InternalAxiosRequestConfig & { tokenRetried?: boolean })
| undefined;
const sentToken = readResponseHeader(
config?.headers,
PARTICIPANT_TOKEN_HEADER,
);
if (sentToken && isParticipantTokenRejection(error)) {
clearParticipantTokenValue(sentToken);
// The server checks the token before it does anything, so the rejected call did
// nothing: once more without it keeps a recording's chunk instead of losing it.
if (config && !config.tokenRetried) {
console.warn(
`[participant token] rejected on ${config.method?.toUpperCase()} ${config.url}; retrying without it`,
);
config.headers.delete(PARTICIPANT_TOKEN_HEADER);
const retry: typeof config = { ...config, tokenRetried: true };
return apiNoAuth.request(retry);
}
}
// Start loading the error messages now, so the screen that shows this error has
// them by the time it renders (see lib/errors/present.ts).
void loadErrorMessages(i18n);
Expand All @@ -40,6 +90,7 @@ export const getParticipantConversationById = async (
) => {
return apiNoAuth.get<unknown, Conversation>(
`/participant/projects/${projectId}/conversations/${conversationId}`,
participantTokenConfig(conversationId),
);
};

Expand All @@ -49,6 +100,7 @@ export const getParticipantConversationChunks = async (
) => {
return apiNoAuth.get<unknown, TConversationChunk[]>(
`participant/projects/${projectId}/conversations/${conversationId}/chunks`,
participantTokenConfig(conversationId),
);
};

Expand All @@ -63,6 +115,7 @@ export const getParticipantConversationReplies = async (
) => {
return apiNoAuth.get<unknown, ParticipantConversationReply[]>(
`/participant/projects/${projectId}/conversations/${conversationId}/replies`,
participantTokenConfig(conversationId),
);
};

Expand All @@ -73,6 +126,7 @@ export const deleteParticipantConversationChunk = async (
) => {
return apiNoAuth.delete(
`/participant/projects/${projectId}/conversations/${conversationId}/chunks/${chunkId}`,
participantTokenConfig(conversationId),
);
};

Expand Down Expand Up @@ -278,6 +332,8 @@ export const checkS3Connectivity = async (
try {
const { probe_url } = await apiNoAuth.post<unknown, { probe_url: string }>(
`/participant/conversations/${conversationId}/check-s3`,
undefined,
participantTokenConfig(conversationId),
);

await fetch(probe_url, {
Expand Down Expand Up @@ -379,7 +435,7 @@ export const pingConversation = async (
await apiNoAuth.post(
`/participant/conversations/${conversationId}/ping`,
telemetry ?? undefined,
{ timeout: PING_TIMEOUT_MS },
{ timeout: PING_TIMEOUT_MS, ...participantTokenConfig(conversationId) },
);
return true;
} catch {
Expand Down Expand Up @@ -412,7 +468,10 @@ export const pingConversationLeft = (
state: "left",
}),
credentials: "include",
headers: { "Content-Type": "application/json" },
headers: {
"Content-Type": "application/json",
...participantTokenHeaders(conversationId),
},
keepalive: true,
method: "POST",
},
Expand Down Expand Up @@ -469,11 +528,15 @@ export const uploadConversationChunkWithPresignedUrl = async (payload: {
fields: Record<string, string>;
file_url: string;
}
>(`/participant/conversations/${payload.conversationId}/get-upload-url`, {
content_type: payload.chunk.type,
conversation_id: payload.conversationId,
filename: fileName,
});
>(
`/participant/conversations/${payload.conversationId}/get-upload-url`,
{
content_type: payload.chunk.type,
conversation_id: payload.conversationId,
filename: fileName,
},
participantTokenConfig(payload.conversationId),
);
} catch (error) {
console.error("[Upload] Failed to get presigned URL:", error);
if (axios.isAxiosError(error)) {
Expand Down Expand Up @@ -584,6 +647,7 @@ export const confirmConversationChunkUpload = async (payload: {
source: payload.source,
timestamp: payload.timestamp,
},
participantTokenConfig(payload.conversationId),
);

// Report 100% after successful confirmation
Expand All @@ -608,6 +672,7 @@ export const uploadConversationText = async (payload: {
source: payload.source,
timestamp: payload.timestamp.toISOString(),
},
participantTokenConfig(payload.conversationId),
);
};

Expand Down Expand Up @@ -782,6 +847,8 @@ export const initiateAndUploadConversationChunk = async (payload: {
`[Upload] Failed to finish conversation ${conversationId}:`,
error,
);
} finally {
clearParticipantToken(conversationId);
}
}),
);
Expand Down Expand Up @@ -1530,14 +1597,20 @@ export const getProjectParticipantCount = async (projectId: string) => {
export const finishConversation = async (conversationId: string) => {
return apiNoAuth.post<unknown>(
`/participant/conversations/${conversationId}/finish`,
undefined,
participantTokenConfig(conversationId),
);
};

export const generateConversationSummary = async (conversationId: string) => {
return apiNoAuth.post<
unknown,
{ status: string; summary: string } | { status: string; message: string }
>(`/conversations/${conversationId}/summarize`);
>(
`/conversations/${conversationId}/summarize`,
undefined,
participantTokenConfig(conversationId),
);
};

export const generateConversationTitle = async (conversationId: string) => {
Expand Down Expand Up @@ -1652,6 +1725,7 @@ export const generateVerificationArtefact = async (payload: {
topic_list: payload.topicList,
},
{
...participantTokenConfig(payload.conversationId),
signal: payload.signal,
},
);
Expand All @@ -1661,6 +1735,7 @@ export const generateVerificationArtefact = async (payload: {

export type UpdateVerificationArtefactPayload = {
artifactId: string;
conversationId: string;
useConversation?: {
conversationId: string;
timestamp: string;
Expand All @@ -1671,6 +1746,7 @@ export type UpdateVerificationArtefactPayload = {

export const updateVerificationArtefact = async ({
artifactId,
conversationId,
useConversation,
content,
approvedAt,
Expand All @@ -1687,19 +1763,25 @@ export const updateVerificationArtefact = async ({
}
: undefined,
},
participantTokenConfig(conversationId),
);
return response;
};

export const getVerificationArtefacts = async (conversationId: string) => {
return apiNoAuth.get<unknown, VerificationArtifact[]>(
`/verify/artifacts/${conversationId}`,
participantTokenConfig(conversationId),
);
};

export const getVerificationArtefactById = async (artifactId: string) => {
export const getVerificationArtefactById = async (
artifactId: string,
conversationId: string,
) => {
return apiNoAuth.get<unknown, VerificationArtifactDetail>(
`/verify/artifact/${artifactId}`,
participantTokenConfig(conversationId),
);
};

Expand All @@ -1721,11 +1803,15 @@ export const submitNotificationParticipant = async (
conversationId: string,
) => {
try {
const response = await apiNoAuth.post("/participant/report/subscribe", {
conversation_id: conversationId,
emails,
project_id: projectId,
});
const response = await apiNoAuth.post(
"/participant/report/subscribe",
{
conversation_id: conversationId,
emails,
project_id: projectId,
},
participantTokenConfig(conversationId),
);
return response;
} catch (_error) {
throw new Error("Failed to subscribe to notifications");
Expand Down
Loading
Loading