Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

refactor(webv2): centralize backend API helpers

joshistoast5152763aa66a
diff --git a/invokeai/frontend/webv2/src/workbench/backend/http.ts b/invokeai/frontend/webv2/src/workbench/backend/http.ts
new file mode 100644
index 0000000000..a3eee45c7a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/backend/http.ts
@@ -0,0 +1,87 @@
+/**
+ * Shared HTTP client for the InvokeAI backend. Every REST call goes through
+ * `apiFetch` so authentication matches the WebSocket connection: both read the
+ * same `auth_token` and send it as a bearer token. The token is read per
+ * request, so a login that lands mid-session applies without a reload.
+ */
+
+const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';
+const AUTH_TOKEN_STORAGE_KEY = 'auth_token';
+
+export const getAuthToken = (): string | null => {
+ try {
+ return window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);
+ } catch {
+ return null;
+ }
+};
+
+export const getBackendSocketUrl = (): string => {
+ if (!API_BASE_URL.trim()) {
+ return window.location.origin;
+ }
+
+ return new URL(API_BASE_URL, window.location.origin).origin;
+};
+
+export const buildApiUrl = (path: string): string => `${API_BASE_URL}${path}`;
+
+/** Resolve a backend-relative resource URL (e.g. image URLs in DTOs) against the API host. */
+export const absolutizeApiUrl = (url: string): string => {
+ if (!API_BASE_URL || url.startsWith('http://') || url.startsWith('https://')) {
+ return url;
+ }
+
+ return new URL(url, API_BASE_URL).toString();
+};
+
+export class ApiError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = 'ApiError';
+ this.status = status;
+ }
+}
+
+export const assertOk = async (response: Response): Promise<Response> => {
+ if (response.ok) {
+ return response;
+ }
+
+ const text = await response.text();
+ throw new ApiError(text || `${response.status} ${response.statusText}`, response.status);
+};
+
+/** Authenticated fetch that leaves status handling to the caller. */
+export const apiFetchRaw = (path: string, init?: RequestInit): Promise<Response> => {
+ const token = getAuthToken();
+ const headers = new Headers(init?.headers);
+
+ if (token && !headers.has('Authorization')) {
+ headers.set('Authorization', `Bearer ${token}`);
+ }
+
+ return fetch(buildApiUrl(path), { ...init, headers });
+};
+
+export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> =>
+ assertOk(await apiFetchRaw(path, init));
+
+export const apiFetchJson = async <T>(path: string, init?: RequestInit): Promise<T> => {
+ const headers = new Headers(init?.headers);
+
+ if (init?.body !== undefined && !(init.body instanceof FormData) && !headers.has('Content-Type')) {
+ headers.set('Content-Type', 'application/json');
+ }
+
+ const response = await apiFetch(path, { ...init, headers });
+
+ return (await response.json()) as T;
+};
+
+export const sleep = (ms: number): Promise<void> =>
+ new Promise((resolve) => {
+ window.setTimeout(resolve, ms);
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.ts b/invokeai/frontend/webv2/src/workbench/gallery/api.ts
index c1ec3a7815..c067916b84 100644
--- a/invokeai/frontend/webv2/src/workbench/gallery/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/gallery/api.ts
@@ -1,7 +1,6 @@
+import { absolutizeApiUrl, apiFetch, apiFetchJson, apiFetchRaw, sleep } from '../backend/http';
import type { GeneratedImageContract } from '../types';
-const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';
-
export type GalleryView = 'images' | 'assets';
export type GalleryOrderDir = 'ASC' | 'DESC';
@@ -70,27 +69,8 @@ interface ListImagesResponse {
const imageCategories = ['general'];
const assetCategories = ['control', 'mask', 'user', 'other'];
-const buildUrl = (path: string): string => `${API_BASE_URL}${path}`;
-
-const absolutizeImageUrl = (url: string): string => {
- if (!API_BASE_URL || url.startsWith('http://') || url.startsWith('https://')) {
- return url;
- }
-
- return new URL(url, API_BASE_URL).toString();
-};
-
const getImageThumbnailUrl = (imageName: string): string =>
- absolutizeImageUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`);
-
-const assertOk = async (response: Response): Promise<Response> => {
- if (response.ok) {
- return response;
- }
-
- const text = await response.text();
- throw new Error(text || `${response.status} ${response.statusText}`);
-};
+ absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`);
const toSearchParams = (entries: Record<string, boolean | number | string | string[] | undefined>): string => {
const params = new URLSearchParams();
@@ -132,8 +112,7 @@ const getGalleryTotal = async ({ boardId, categories }: { boardId: string; categ
limit: 0,
offset: 0,
});
- const response = await assertOk(await fetch(buildUrl(`/api/v1/images/?${query}`)));
- const body = (await response.json()) as Pick<ListImagesResponse, 'total'>;
+ const body = await apiFetchJson<Pick<ListImagesResponse, 'total'>>(`/api/v1/images/?${query}`);
return body.total;
};
@@ -143,11 +122,11 @@ const mapImage = (image: BackendImageDTO): GalleryImage => ({
height: image.height,
imageCategory: image.image_category,
imageName: image.image_name,
- imageUrl: absolutizeImageUrl(image.image_url),
+ imageUrl: absolutizeApiUrl(image.image_url),
queuedAt: image.created_at,
sourceQueueItemId: 'backend-gallery',
starred: image.starred ?? false,
- thumbnailUrl: absolutizeImageUrl(image.thumbnail_url),
+ thumbnailUrl: absolutizeApiUrl(image.thumbnail_url),
width: image.width,
});
@@ -166,14 +145,15 @@ export const listGalleryBoards = async ({
include_archived: includeArchived,
order_by: orderBy,
});
- const boardsResponsePromise = fetch(buildUrl(`/api/v1/boards/?${boardsQuery}`)).then(assertOk);
+ const boardsBodyPromise = apiFetchJson<BackendBoardDTO[] | { items?: BackendBoardDTO[] }>(
+ `/api/v1/boards/?${boardsQuery}`
+ );
- const [response, uncategorizedImageCount, uncategorizedAssetCount] = await Promise.all([
- boardsResponsePromise,
+ const [body, uncategorizedImageCount, uncategorizedAssetCount] = await Promise.all([
+ boardsBodyPromise,
getGalleryTotal({ boardId: 'none', categories: imageCategories }),
getGalleryTotal({ boardId: 'none', categories: assetCategories }),
]);
- const body = (await response.json()) as BackendBoardDTO[] | { items?: BackendBoardDTO[] };
const boards = Array.isArray(body) ? body : (body.items ?? []);
return [
@@ -199,8 +179,7 @@ interface VirtualDateBoardDTO {
}
export const listGalleryDateBoards = async (): Promise<GalleryBoard[]> => {
- const response = await assertOk(await fetch(buildUrl('/api/v1/virtual_boards/by_date')));
- const body = (await response.json()) as VirtualDateBoardDTO[];
+ const body = await apiFetchJson<VirtualDateBoardDTO[]>('/api/v1/virtual_boards/by_date');
return body.map((board) => ({
archived: false,
@@ -224,15 +203,12 @@ const getGalleryImagesByNames = async (imageNames: string[]): Promise<GalleryIma
return [];
}
- const response = await assertOk(
- await fetch(buildUrl('/api/v1/images/images_by_names'), {
- body: JSON.stringify({ image_names: imageNames }),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- })
- );
+ const body = await apiFetchJson<BackendImageDTO[]>('/api/v1/images/images_by_names', {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ });
- return ((await response.json()) as BackendImageDTO[]).map(mapImage);
+ return body.map(mapImage);
};
/**
@@ -262,12 +238,9 @@ const listGalleryDateBoardImages = async ({
search_term: searchTerm.trim() || undefined,
starred_first: starredFirst,
});
- const response = await assertOk(
- await fetch(
- buildUrl(`/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`)
- )
+ const body = await apiFetchJson<{ image_names: string[]; total_count: number }>(
+ `/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/image_names?${query}`
);
- const body = (await response.json()) as { image_names: string[]; total_count: number };
const images = await getGalleryImagesByNames(body.image_names.slice(offset, offset + limit));
return { images, total: body.total_count };
@@ -304,46 +277,34 @@ export const listGalleryImages = async ({
search_term: searchTerm.trim() || undefined,
starred_first: starredFirst,
});
- const response = await assertOk(await fetch(buildUrl(`/api/v1/images/?${query}`)));
- const body = (await response.json()) as ListImagesResponse;
+ const body = await apiFetchJson<ListImagesResponse>(`/api/v1/images/?${query}`);
return { images: body.items.map(mapImage), total: body.total };
};
export const createGalleryBoard = async (boardName: string): Promise<GalleryBoard> => {
const query = toSearchParams({ board_name: boardName });
- const response = await assertOk(
- await fetch(buildUrl(`/api/v1/boards/?${query}`), {
- method: 'POST',
- })
- );
+ const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/?${query}`, { method: 'POST' });
- return mapBoard((await response.json()) as BackendBoardDTO);
+ return mapBoard(body);
};
export const updateGalleryBoard = async (
boardId: string,
changes: { name?: string; archived?: boolean }
): Promise<GalleryBoard> => {
- const response = await assertOk(
- await fetch(buildUrl(`/api/v1/boards/${encodeURIComponent(boardId)}`), {
- body: JSON.stringify({ archived: changes.archived, board_name: changes.name }),
- headers: { 'Content-Type': 'application/json' },
- method: 'PATCH',
- })
- );
+ const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/${encodeURIComponent(boardId)}`, {
+ body: JSON.stringify({ archived: changes.archived, board_name: changes.name }),
+ method: 'PATCH',
+ });
- return mapBoard((await response.json()) as BackendBoardDTO);
+ return mapBoard(body);
};
export const deleteGalleryBoard = async (boardId: string, includeImages: boolean): Promise<void> => {
const query = toSearchParams({ include_images: includeImages });
- await assertOk(
- await fetch(buildUrl(`/api/v1/boards/${encodeURIComponent(boardId)}?${query}`), {
- method: 'DELETE',
- })
- );
+ await apiFetch(`/api/v1/boards/${encodeURIComponent(boardId)}?${query}`, { method: 'DELETE' });
};
export const addImagesToGalleryBoard = async (boardId: string, imageNames: string[]): Promise<void> => {
@@ -357,13 +318,10 @@ export const addImagesToGalleryBoard = async (boardId: string, imageNames: strin
return;
}
- await assertOk(
- await fetch(buildUrl('/api/v1/board_images/batch'), {
- body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- })
- );
+ await apiFetchJson('/api/v1/board_images/batch', {
+ body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
+ method: 'POST',
+ });
};
export const removeImagesFromGalleryBoard = async (imageNames: string[]): Promise<void> => {
@@ -371,13 +329,10 @@ export const removeImagesFromGalleryBoard = async (imageNames: string[]): Promis
return;
}
- await assertOk(
- await fetch(buildUrl('/api/v1/board_images/batch/delete'), {
- body: JSON.stringify({ image_names: imageNames }),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- })
- );
+ await apiFetchJson('/api/v1/board_images/batch/delete', {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ });
};
const setGalleryImagesStarred = async (imageNames: string[], starred: boolean): Promise<void> => {
@@ -385,13 +340,10 @@ const setGalleryImagesStarred = async (imageNames: string[], starred: boolean):
return;
}
- await assertOk(
- await fetch(buildUrl(`/api/v1/images/${starred ? 'star' : 'unstar'}`), {
- body: JSON.stringify({ image_names: imageNames }),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- })
- );
+ await apiFetchJson(`/api/v1/images/${starred ? 'star' : 'unstar'}`, {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ });
};
export const starGalleryImages = (imageNames: string[]): Promise<void> => setGalleryImagesStarred(imageNames, true);
@@ -403,23 +355,15 @@ export const deleteGalleryImages = async (imageNames: string[]): Promise<void> =
return;
}
- await assertOk(
- await fetch(buildUrl('/api/v1/images/delete'), {
- body: JSON.stringify({ image_names: imageNames }),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- })
- );
+ await apiFetchJson('/api/v1/images/delete', {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ });
};
const BULK_DOWNLOAD_POLL_INTERVAL_MS = 2000;
const BULK_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
-const sleep = (ms: number): Promise<void> =>
- new Promise((resolve) => {
- window.setTimeout(resolve, ms);
- });
-
/**
* Starts a bulk download (a zip prepared in a backend background task) and
* polls the artifact endpoint until it exists. Returns the archive blob and
@@ -432,16 +376,13 @@ export const downloadGalleryArchive = async ({
boardId?: string;
imageNames?: string[];
}): Promise<{ blob: Blob; fileName: string }> => {
- const startResponse = await assertOk(
- await fetch(buildUrl('/api/v1/images/download'), {
+ const { bulk_download_item_name: fileName } = await apiFetchJson<{ bulk_download_item_name?: string | null }>(
+ '/api/v1/images/download',
+ {
body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
- headers: { 'Content-Type': 'application/json' },
method: 'POST',
- })
+ }
);
- const { bulk_download_item_name: fileName } = (await startResponse.json()) as {
- bulk_download_item_name?: string | null;
- };
if (!fileName) {
throw new Error('The bulk download failed to start.');
@@ -450,7 +391,7 @@ export const downloadGalleryArchive = async ({
const startedAt = Date.now();
while (Date.now() - startedAt < BULK_DOWNLOAD_TIMEOUT_MS) {
- const response = await fetch(buildUrl(`/api/v1/images/download/${encodeURIComponent(fileName)}`));
+ const response = await apiFetchRaw(`/api/v1/images/download/${encodeURIComponent(fileName)}`);
if (response.ok) {
return { blob: await response.blob(), fileName };
@@ -475,12 +416,10 @@ export const uploadGalleryImage = async (file: File, boardId: string): Promise<G
const body = new FormData();
body.append('file', file);
- const response = await assertOk(
- await fetch(buildUrl(`/api/v1/images/upload?${query}`), {
- body,
- method: 'POST',
- })
- );
+ const uploadedImage = await apiFetchJson<BackendImageDTO>(`/api/v1/images/upload?${query}`, {
+ body,
+ method: 'POST',
+ });
- return mapImage((await response.json()) as BackendImageDTO);
+ return mapImage(uploadedImage);
};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.ts b/invokeai/frontend/webv2/src/workbench/generation/api.ts
index 75293502cf..0f2bac6cb0 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/api.ts
@@ -1,37 +1,10 @@
+import { absolutizeApiUrl, apiFetchJson } from '../backend/http';
+import { buildQueueItemOrigin } from '../backend/events';
import type { BackendGraphContract } from '../types';
import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, MainModelConfig, QueueItemDTO } from './types';
-const API_BASE_URL = import.meta.env.VITE_INVOKEAI_API_BASE_URL ?? '';
-const POLL_INTERVAL_MS = 1500;
-const POLL_TIMEOUT_MS = 15 * 60 * 1000;
-
-const buildUrl = (path: string): string => `${API_BASE_URL}${path}`;
-
-const sleep = (ms: number): Promise<void> =>
- new Promise((resolve) => {
- window.setTimeout(resolve, ms);
- });
-
-const assertOk = async (response: Response): Promise<Response> => {
- if (response.ok) {
- return response;
- }
-
- const text = await response.text();
- throw new Error(text || `${response.status} ${response.statusText}`);
-};
-
-const absolutizeImageUrl = (url: string): string => {
- if (!API_BASE_URL || url.startsWith('http://') || url.startsWith('https://')) {
- return url;
- }
-
- return new URL(url, API_BASE_URL).toString();
-};
-
export const listMainModels = async (): Promise<MainModelConfig[]> => {
- const response = await assertOk(await fetch(buildUrl('/api/v2/models/?model_type=main')));
- const body = (await response.json()) as { models?: MainModelConfig[] };
+ const body = await apiFetchJson<{ models?: MainModelConfig[] }>('/api/v2/models/?model_type=main');
return body.models ?? [];
};
@@ -48,49 +21,43 @@ export const enqueueGenerateGraph = async (request: EnqueueGenerateRequest): Pro
],
destination: request.destination,
graph: request.graph satisfies BackendGraphContract,
- origin: `webv2:${request.sourceQueueItemId}`,
+ origin: buildQueueItemOrigin(request.sourceQueueItemId),
runs: request.batchCount,
},
prepend: false,
};
-
- const response = await assertOk(
- await fetch(buildUrl('/api/v1/queue/default/enqueue_batch'), {
- body: JSON.stringify(body),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- })
+ const result = await apiFetchJson<{ batch?: { batch_id?: string }; item_ids?: number[] }>(
+ '/api/v1/queue/default/enqueue_batch',
+ { body: JSON.stringify(body), method: 'POST' }
);
- const result = (await response.json()) as { item_ids?: number[] };
- return { itemIds: result.item_ids ?? [] };
+ return { batchId: result.batch?.batch_id, itemIds: result.item_ids ?? [] };
};
-const getQueueItem = async (itemId: number): Promise<QueueItemDTO> => {
- const response = await assertOk(await fetch(buildUrl(`/api/v1/queue/default/i/${itemId}`)));
+export const getQueueItem = (itemId: number): Promise<QueueItemDTO> =>
+ apiFetchJson<QueueItemDTO>(`/api/v1/queue/default/i/${itemId}`);
- return (await response.json()) as QueueItemDTO;
-};
+export const listAllQueueItems = (): Promise<QueueItemDTO[]> =>
+ apiFetchJson<QueueItemDTO[]>('/api/v1/queue/default/list_all');
const getImageDTO = async (imageName: string, queuedAt: string, sourceQueueItemId: string): Promise<ImageDTO> => {
- const response = await assertOk(await fetch(buildUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}`)));
- const body = (await response.json()) as {
+ const body = await apiFetchJson<{
image_name: string;
image_url: string;
thumbnail_url: string;
width: number;
height: number;
is_intermediate: boolean;
- };
+ }>(`/api/v1/images/i/${encodeURIComponent(imageName)}`);
return {
height: body.height,
imageName: body.image_name,
- imageUrl: absolutizeImageUrl(body.image_url),
+ imageUrl: absolutizeApiUrl(body.image_url),
isIntermediate: body.is_intermediate,
queuedAt,
sourceQueueItemId,
- thumbnailUrl: absolutizeImageUrl(body.thumbnail_url),
+ thumbnailUrl: absolutizeApiUrl(body.thumbnail_url),
width: body.width,
};
};
@@ -98,7 +65,7 @@ const getImageDTO = async (imageName: string, queuedAt: string, sourceQueueItemI
const getResultImageNames = (queueItem: QueueItemDTO): string[] => {
const imageNames = new Set<string>();
- for (const result of Object.values(queueItem.session.results)) {
+ for (const result of Object.values(queueItem.session?.results ?? {})) {
if (!result || typeof result !== 'object') {
continue;
}
@@ -112,39 +79,32 @@ const getResultImageNames = (queueItem: QueueItemDTO): string[] => {
return [...imageNames];
};
-export const waitForQueueItemImages = async (
+/** Fetch the result image DTOs of a completed queue item. */
+export const getQueueItemResultImages = async (
itemId: number,
sourceQueueItemId: string,
queuedAt: string
): Promise<ImageDTO[]> => {
- const startedAt = Date.now();
-
- while (Date.now() - startedAt < POLL_TIMEOUT_MS) {
- const queueItem = await getQueueItem(itemId);
+ const queueItem = await getQueueItem(itemId);
- if (queueItem.status === 'completed') {
- const imageNames = getResultImageNames(queueItem);
- return Promise.all(imageNames.map((imageName) => getImageDTO(imageName, queuedAt, sourceQueueItemId)));
- }
-
- if (queueItem.status === 'failed' || queueItem.status === 'canceled') {
- throw new Error(queueItem.error_message ?? queueItem.error_type ?? `Queue item ${itemId} ${queueItem.status}.`);
- }
+ return Promise.all(
+ getResultImageNames(queueItem).map((imageName) => getImageDTO(imageName, queuedAt, sourceQueueItemId))
+ );
+};
- await sleep(POLL_INTERVAL_MS);
+export const cancelQueueItemsByBatchIds = async (batchIds: string[]): Promise<void> => {
+ if (batchIds.length === 0) {
+ return;
}
- throw new Error(`Timed out waiting for queue item ${itemId}.`);
+ await apiFetchJson('/api/v1/queue/default/cancel_by_batch_ids', {
+ body: JSON.stringify({ batch_ids: batchIds }),
+ method: 'PUT',
+ });
};
export const cancelQueueItems = async (itemIds: number[]): Promise<void> => {
await Promise.all(
- itemIds.map(async (itemId) => {
- await assertOk(
- await fetch(buildUrl(`/api/v1/queue/default/i/${itemId}/cancel`), {
- method: 'PUT',
- })
- );
- })
+ itemIds.map((itemId) => apiFetchJson(`/api/v1/queue/default/i/${itemId}/cancel`, { method: 'PUT' }))
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/workbench/generation/types.ts
index 638c9ba273..e4a381a399 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/types.ts
@@ -48,15 +48,19 @@ export interface CompiledGenerateGraph {
}
export interface EnqueueGenerateResult {
+ batchId?: string;
itemIds: number[];
}
export interface QueueItemDTO {
item_id: number;
status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'canceled';
+ batch_id?: string;
+ origin?: string | null;
+ destination?: string | null;
error_type?: string | null;
error_message?: string | null;
- session: {
+ session?: {
results: Record<string, unknown>;
};
}