24 lines
955 B
TypeScript
24 lines
955 B
TypeScript
import "server-only";
|
|
import { unlinkSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
const state = globalThis as typeof globalThis & { __aiChatbotActiveWork?: number };
|
|
const path = join(process.platform === "win32" ? tmpdir() : "/tmp", `ai-chatbot-active-work-${process.pid}.json`);
|
|
|
|
function update(delta: number) {
|
|
state.__aiChatbotActiveWork = (state.__aiChatbotActiveWork || 0) + delta;
|
|
try {
|
|
writeFileSync(path, JSON.stringify({ pid: process.pid, active: state.__aiChatbotActiveWork }), { mode: 0o600 });
|
|
} catch (error) {
|
|
try { unlinkSync(path); } catch {}
|
|
console.warn("[Active Work] Failed to record running work:", error);
|
|
}
|
|
}
|
|
|
|
/** Includes generation that continues after the client connection closes. */
|
|
export async function trackRuntimeWork<T>(execute: () => T | Promise<T>): Promise<T> {
|
|
update(1);
|
|
try { return await execute(); } finally { update(-1); }
|
|
}
|