Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

fix(desktop): carry an AI request's abort signal to the main process

Luis Ortiz29e67406eb2d
diff --git a/apps/desktop/src/main/ai-fetch.ts b/apps/desktop/src/main/ai-fetch.ts
index b678445..e209b1a 100644
--- a/apps/desktop/src/main/ai-fetch.ts
+++ b/apps/desktop/src/main/ai-fetch.ts
@@ -1,6 +1,7 @@
import { ipcMain, net } from 'electron';
export interface AiRequest {
+ id: string;
url: string;
method?: string;
headers?: Record<string, string>;
@@ -17,6 +18,8 @@ export interface AiResponse {
const ALLOWED = new Set(['http:', 'https:']);
+const inFlight = new Map<string, AbortController>();
+
export function allowedEndpoint(url: string): boolean {
try {
return ALLOWED.has(new URL(url).protocol);
@@ -26,24 +29,32 @@ export function allowedEndpoint(url: string): boolean {
}
export function registerAiFetch(): void {
+ ipcMain.on('mimik:ai:abort', (_event, id: string) => inFlight.get(id)?.abort());
ipcMain.handle('mimik:ai:fetch', async (_event, request: AiRequest): Promise<AiResponse> => {
if (!allowedEndpoint(request.url)) throw new Error('unsupported url');
- const response = await net.fetch(request.url, {
- method: request.method ?? 'GET',
- headers: request.headers,
- body: request.body,
- });
- const headers: Record<string, string> = {};
- response.headers.forEach((value, key) => {
- headers[key] = value;
- });
- const textual = /^text\/|json|xml|event-stream/.test(response.headers.get('content-type') ?? '');
- return {
- status: response.status,
- statusText: response.statusText,
- headers,
- body: textual ? await response.text() : Buffer.from(await response.arrayBuffer()).toString('base64'),
- encoding: textual ? 'text' : 'base64',
- };
+ const controller = new AbortController();
+ inFlight.set(request.id, controller);
+ try {
+ const response = await net.fetch(request.url, {
+ method: request.method ?? 'GET',
+ headers: request.headers,
+ body: request.body,
+ signal: controller.signal,
+ });
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, key) => {
+ headers[key] = value;
+ });
+ const textual = /^text\/|json|xml|event-stream/.test(response.headers.get('content-type') ?? '');
+ return {
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ body: textual ? await response.text() : Buffer.from(await response.arrayBuffer()).toString('base64'),
+ encoding: textual ? 'text' : 'base64',
+ };
+ } finally {
+ inFlight.delete(request.id);
+ }
});
}
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index d7b08bc..87448e1 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -33,6 +33,7 @@ const api = {
},
ai: {
fetch: (request: unknown): Promise<unknown> => ipcRenderer.invoke('mimik:ai:fetch', request),
+ abort: (id: string): void => ipcRenderer.send('mimik:ai:abort', id),
},
onRequest: (channel: string, handler: (payload: unknown) => Promise<unknown>): void => {
ipcRenderer.on(channel, async (_event, replyChannel: string, payload: unknown) => {
diff --git a/apps/desktop/src/renderer/__tests__/main-fetch.test.ts b/apps/desktop/src/renderer/__tests__/main-fetch.test.ts
new file mode 100644
index 0000000..4788ead
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/main-fetch.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mainFetch } from '../lib/main-fetch';
+
+function stubBridge(fetch: (request: { id: string }) => Promise<unknown>) {
+ const abort = vi.fn();
+ vi.stubGlobal('window', { mimik: { ai: { fetch: vi.fn(fetch), abort } } });
+ return abort;
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('mainFetch', () => {
+ it('gives up on a request main never answers once its signal fires, and tells main to drop it', async () => {
+ const abort = stubBridge(() => new Promise(() => {}));
+ const controller = new AbortController();
+
+ const pending = mainFetch('https://api.openai.com/v1/audio/speech', { method: 'POST', signal: controller.signal });
+ controller.abort(new DOMException('timed out', 'TimeoutError'));
+
+ await expect(pending).rejects.toMatchObject({ name: 'TimeoutError' });
+ const [{ id }] = (window.mimik.ai.fetch as ReturnType<typeof vi.fn>).mock.calls[0] as [{ id: string }];
+ expect(abort).toHaveBeenCalledWith(id);
+ });
+
+ it('decodes a binary reply back into bytes', async () => {
+ stubBridge(async () => ({
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ body: btoa('\x01\x02\xff'),
+ encoding: 'base64',
+ }));
+
+ const response = await mainFetch('https://api.openai.com/v1/audio/speech');
+
+ expect([...new Uint8Array(await response.arrayBuffer())]).toEqual([1, 2, 255]);
+ });
+});
diff --git a/apps/desktop/src/renderer/core-env.ts b/apps/desktop/src/renderer/core-env.ts
index cba4230..7a26a21 100644
--- a/apps/desktop/src/renderer/core-env.ts
+++ b/apps/desktop/src/renderer/core-env.ts
@@ -8,28 +8,7 @@ import fr from '@mimik/locales/fr.yml';
import ptBR from '@mimik/locales/pt-BR.yml';
import zhCN from '@mimik/locales/zh-CN.yml';
import { type AppLocale, appLocale } from './lib/app-locale';
-
-async function mainFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
- const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
- const headers: Record<string, string> = {};
- new Headers(init?.headers).forEach((value, key) => {
- headers[key] = value;
- });
- const reply = (await window.mimik.ai.fetch({
- url,
- method: init?.method ?? 'GET',
- headers,
- body: typeof init?.body === 'string' ? init.body : undefined,
- })) as {
- status: number;
- statusText: string;
- headers: Record<string, string>;
- body: string;
- encoding: 'text' | 'base64';
- };
- const body = reply.encoding === 'base64' ? Uint8Array.from(atob(reply.body), (c) => c.charCodeAt(0)) : reply.body;
- return new Response(body, { status: reply.status, statusText: reply.statusText, headers: reply.headers });
-}
+import { mainFetch } from './lib/main-fetch';
const MESSAGES: Record<AppLocale, Messages> = {
en: en as Messages,
diff --git a/apps/desktop/src/renderer/lib/main-fetch.ts b/apps/desktop/src/renderer/lib/main-fetch.ts
new file mode 100644
index 0000000..d80694f
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/main-fetch.ts
@@ -0,0 +1,44 @@
+interface MainReply {
+ status: number;
+ statusText: string;
+ headers: Record<string, string>;
+ body: string;
+ encoding: 'text' | 'base64';
+}
+
+export async function mainFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key] = value;
+ });
+ const signal = init?.signal ?? undefined;
+ signal?.throwIfAborted();
+
+ const id = crypto.randomUUID();
+ let onAbort = () => {};
+ const aborted = new Promise<never>((_, reject) => {
+ onAbort = () => {
+ window.mimik.ai.abort(id);
+ reject(signal?.reason);
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
+
+ try {
+ const reply = (await Promise.race([
+ window.mimik.ai.fetch({
+ id,
+ url,
+ method: init?.method ?? 'GET',
+ headers,
+ body: typeof init?.body === 'string' ? init.body : undefined,
+ }),
+ aborted,
+ ])) as MainReply;
+ const body = reply.encoding === 'base64' ? Uint8Array.from(atob(reply.body), (c) => c.charCodeAt(0)) : reply.body;
+ return new Response(body, { status: reply.status, statusText: reply.statusText, headers: reply.headers });
+ } finally {
+ signal?.removeEventListener('abort', onAbort);
+ }
+}