diff --git a/apps/client/src/lightweight/browser_router.ts b/apps/client/src/lightweight/browser_router.ts index 5bbb95216..e6dcd74b6 100644 --- a/apps/client/src/lightweight/browser_router.ts +++ b/apps/client/src/lightweight/browser_router.ts @@ -3,6 +3,8 @@ * Supports path parameters (e.g., /api/notes/:noteId) and query strings. */ +import { getContext } from "@triliumnext/core"; + export interface BrowserRequest { method: string; url: string; @@ -166,7 +168,7 @@ export class BrowserRouter { }; try { - const result = await route.handler(request); + const result = await getContext().init(async () => await route.handler(request)); return this.formatResult(result); } catch (error) { return this.formatError(error); diff --git a/apps/client/src/lightweight/cls_provider.ts b/apps/client/src/lightweight/cls_provider.ts index 20ff5dda9..75cb0a3ad 100644 --- a/apps/client/src/lightweight/cls_provider.ts +++ b/apps/client/src/lightweight/cls_provider.ts @@ -24,10 +24,23 @@ export default class BrowserExecutionContext implements ExecutionContext { this.store = new Map(); try { - return callback(); - } finally { - // Always clean up + const result = callback(); + + // If the result is a Promise, we need to handle cleanup after it resolves + if (result && typeof result === 'object' && 'then' in result && 'catch' in result) { + const promise = result as unknown as Promise; + return promise.finally(() => { + this.store = prev; + }) as T; + } else { + // Synchronous result, clean up immediately + this.store = prev; + return result; + } + } catch (error) { + // Always clean up on error (for synchronous errors) this.store = prev; + throw error; } } }