Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Accounts 2: runners carry an actor, MCP acts for the token's person

Claudee0fea077a066
diff --git a/src/server/ads.ts b/src/server/ads.ts
index c19e89be..2a1f5350 100644
--- a/src/server/ads.ts
+++ b/src/server/ads.ts
@@ -18,6 +18,7 @@ import {
import type { Engine, Generation, GenerationRequest, OutputFile } from "@/lib/catalog/types";
import { getModel } from "@/lib/catalog";
import { getBrand, getProduct, listProducts, parseJsonObject } from "./brand";
+import { currentActor, runAs } from "./access/actor";
import { db } from "./db";
import { llmText } from "./enhance";
import { createGenerations, getGeneration, previewGeneration, recordLocalGeneration } from "./generations";
@@ -294,7 +295,8 @@ export function createBatch(input: BatchInput, fixed: FixedCopy = {}): { batchId
}
})();
running().add(batchId);
- const run = fillBatch(batchId, brand, ids, input, fixed).finally(() => running().delete(batchId));
+ // Copy and pictures follow after the response (the route keeps it going with after()), for the person who asked.
+ const run = runAs(currentActor(), () => fillBatch(batchId, brand, ids, input, fixed)).finally(() => running().delete(batchId));
return { batchId, creatives: listCreatives({ brandId: brand.id, batchId }), run };
}
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index 799c0d8e..58eb84d3 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -26,6 +26,8 @@ import {
type SkillMeta,
} from "@/lib/assist";
import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
+import { currentActor } from "../access/actor";
+import { rowOwner, runAsOwner } from "../access/permissions";
import { db } from "../db";
import { getGeneration } from "../generations";
import { offeredDefault } from "../model-access";
@@ -1110,6 +1112,7 @@ function animateTake(still: { url: string; g: Generation }, take: number, prefer
function toolCtx(s: State): ToolContext {
return {
engine: s.thread.engine,
+ actor: currentActor(),
thread: {
id: s.thread.id,
projectId: s.ext.projectId,
@@ -1286,7 +1289,18 @@ const MODELS: Record<AssistThread["agent"], ModelCall> = { claude, ollama, offli
* Run the agent until it ends its turn or waits for approval. Call it right after addMessage or
* answerApproval: it claims the thread synchronously, so the "running" status they saved stays valid.
*/
+/**
+ * Carry the chat on until the agent stops (or asks for approval). The turn acts for the chat's author (§7.10), whoever's
+ * request or schedule carried it on: tools it runs, generations it starts and what it spends are theirs.
+ */
export async function run(id: string, model?: ModelCall): Promise<void> {
+ if (runs.has(id)) return;
+ const row = db().prepare("SELECT * FROM assist_threads WHERE id = ?").get(id) as Row | undefined;
+ if (!row) return;
+ return runAsOwner(rowOwner(row), () => turn(id, model));
+}
+
+async function turn(id: string, model?: ModelCall): Promise<void> {
if (runs.has(id)) return;
runs.add(id);
try {
diff --git a/src/server/assist/define.ts b/src/server/assist/define.ts
index f1513631..5da0cb14 100644
--- a/src/server/assist/define.ts
+++ b/src/server/assist/define.ts
@@ -2,6 +2,7 @@ import "server-only";
import type Anthropic from "@anthropic-ai/sdk";
import type { z } from "zod";
import type { AssistItem, PlannedJob } from "@/lib/assist";
+import type { Actor } from "../access/actor";
/** Shared shape of Assist's tools (also served over MCP). */
@@ -9,6 +10,8 @@ export type ResultContent = Anthropic.Beta.BetaToolResultBlockParam["content"];
export interface ToolContext {
engine: "cloud" | "open";
+ /** Who the tool acts for: the MCP token's or session's person, or the chat's author (the scoping package narrows by it). */
+ actor?: Actor;
/** The Assist chat running the tool; absent over MCP. */
thread?: {
id: string;
diff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.ts
index d5ae19ed..4e5156c0 100644
--- a/src/server/assist/schedules.ts
+++ b/src/server/assist/schedules.ts
@@ -14,6 +14,8 @@ import {
type ScheduleView,
} from "@/lib/assist-schedule";
import { formatCost } from "@/lib/format";
+import { asSystem } from "../access/actor";
+import { rowOwner, runAsOwner } from "../access/permissions";
import { db } from "../db";
import { addMessage, createThread, getThread, resolveMode, run, type ModelCall } from "./agent";
import { getProject } from "./projects";
@@ -354,10 +356,13 @@ export async function sweepSchedules(now = Date.now(), o: { model?: ModelCall }
const next = nextRun(JSON.parse(r.rule_json) as ScheduleRule, r.tz, now);
const claimed = db().prepare("UPDATE assist_schedules SET next_run_at = ? WHERE id = ? AND next_run_at = ? AND paused = 0").run(next, r.id, r.next_run_at).changes;
if (!claimed) continue;
- const begun = await startSchedule(r.id, { now, model: o.model }).catch((e: Error) => {
- record(r.id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: e.message });
- return null;
- });
+ // A task runs as the person who owns it, never as whoever the sweep's timer started under.
+ const begun = await Promise.resolve()
+ .then(() => runAsOwner(rowOwner(r), () => startSchedule(r.id, { now, model: o.model })))
+ .catch((e: Error) => {
+ record(r.id, { last_run_at: now, last_thread_id: null, last_status: "failed", last_text: e.message });
+ return null;
+ });
if (begun?.threadId) started.push(begun.threadId);
if (begun) runs.push(begun.done);
}
@@ -383,8 +388,11 @@ export function ensureScheduleRunner(o: { soon?: boolean } = {}): void {
cur.tick = tick;
return;
}
- const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };
- state.timer.unref?.();
- globalThis.__fuobeScheduleRunner = state;
- if (o.soon) setTimeout(() => globalThis.__fuobeScheduleRunner?.tick(), BOOT_SWEEP_MS).unref?.();
+ // The server's timers, whichever request started them (creating a task does): each task runs as its owner.
+ asSystem(() => {
+ const state = { tick, timer: setInterval(() => globalThis.__fuobeScheduleRunner?.tick(), SWEEP_MS) };
+ state.timer.unref?.();
+ globalThis.__fuobeScheduleRunner = state;
+ if (o.soon) setTimeout(() => globalThis.__fuobeScheduleRunner?.tick(), BOOT_SWEEP_MS).unref?.();
+ });
}
diff --git a/src/server/brand.ts b/src/server/brand.ts
index dd530131..3b12797a 100644
--- a/src/server/brand.ts
+++ b/src/server/brand.ts
@@ -15,6 +15,7 @@ import {
type BrandStatus,
type Product,
} from "@/lib/catalog/marketing";
+import { currentActor, runAs } from "./access/actor";
import { db } from "./db";
import { llmText } from "./enhance";
import { fetchRemote } from "./remote-fetch";
@@ -968,7 +969,8 @@ const progressAt = (index: number): BrandProgress => ({ index, total: RESEARCH_L
function startResearch(id: string): Promise<void> {
const ac = new AbortController();
runs().set(id, ac);
- return research(id, ac.signal)
+ // It outlives the request (the route keeps it going with after()): it acts for the person who asked for it.
+ return runAs(currentActor(), () => research(id, ac.signal))
.catch((e) => {
if (ac.signal.aborted) return;
const kit = storedKit(id);
diff --git a/src/server/content-factory.ts b/src/server/content-factory.ts
index 544adb34..9508d022 100644
--- a/src/server/content-factory.ts
+++ b/src/server/content-factory.ts
@@ -43,6 +43,7 @@ import {
import { genreInfo, pickerData, type ChannelSettings, type EpisodeSettings, type NarratorVoice, type TimedText } from "@/lib/catalog/faceless";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { probeMedia } from "@/lib/media-probe";
+import { rowOwner, runAsOwner } from "./access/permissions";
import { authEnabled } from "./auth";
import { db } from "./db";
import { llmText, llmTextBackend, type LlmImage } from "./enhance";
@@ -458,8 +459,11 @@ async function writeBrief(id: string): Promise<void> {
});
}
-/** Moves a reading series on: the steps' progress, then the brief once they're all done. */
-function advance(id: string, d: SeriesData): SeriesData {
+/**
+ * Moves a reading series on: the steps' progress, then the brief once they're all done. The brief is written as the
+ * person who started the series (`owner`), whoever's read happened to notice the steps had finished.
+ */
+function advance(id: string, d: SeriesData, owner: string): SeriesData {
const a = d.analysis;
if (!a || a.status !== "reading") return d;
const gens = Object.values(a.steps).map((g) => getGeneration(g, { includeDeleted: true }));
@@ -468,7 +472,8 @@ function advance(id: string, d: SeriesData): SeriesData {
return { ...d, analysis: { ...a, stage: running?.status === "queued" ? "Waiting for its turn…" : a.stage } };
}
if (!writing().has(id)) {
- const job = writeBrief(id)
+ const job = Promise.resolve()
+ .then(() => runAsOwner(owner, () => writeBrief(id)))
.catch((e: Error) => {
patch(id, (cur) => {
if (cur.analysis?.status === "reading") cur.analysis = { ...cur.analysis, status: "failed", stage: undefined, error: e.message || "Couldn't write the brief" };
@@ -511,7 +516,7 @@ function toView(r: SeriesRow, d: SeriesData): SeriesView {
export function seriesView(id: string): SeriesView {
const r = mustRow(id);
- return toView(r, advance(id, dataOf(r)));
+ return toView(r, advance(id, dataOf(r), rowOwner(r)));
}
/** A new series around a reference (reading starts straight away), a preset (its brief is ready), or nothing yet. */
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
index 6826abcb..8906915d 100644
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@ -78,6 +78,8 @@ import { routesFor } from "@/lib/catalog/plan";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { DocxError, docxText } from "./assist/docx";
import { PdfError, pdfText } from "./assist/pdf";
+import { asSystem } from "./access/actor";
+import { rowOwner, runAsOwner } from "./access/permissions";
import { db } from "./db";
import { listElements } from "./elements";
import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
@@ -1154,7 +1156,8 @@ function sweep(): void {
const rows = db().prepare("SELECT * FROM faceless_episodes WHERE status = 'rendering' AND plan_json LIKE '%\"awaiting\":true%'").all() as EpisodeRow[];
for (const r of rows) {
try {
- settle(toEpisode(r));
+ // Stage two starts as the person who started the episode.
+ runAsOwner(rowOwner(r), () => settle(toEpisode(r)));
} catch (e) {
console.warn(`[faceless] couldn't continue ${r.id}: ${(e as Error).message}`);
}
@@ -1169,7 +1172,8 @@ export function ensureFacelessRunner(): void {
cur.tick = sweep;
return;
}
- const state = { tick: sweep, timer: setInterval(() => globalThis.__fuobeFacelessRunner?.tick(), SWEEP_MS) };
+ // The server's timer, whichever request started it; each episode then continues as its owner (sweep).
+ const state = { tick: sweep, timer: asSystem(() => setInterval(() => globalThis.__fuobeFacelessRunner?.tick(), SWEEP_MS)) };
state.timer.unref?.();
globalThis.__fuobeFacelessRunner = state;
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 2d670902..9824ad7a 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -42,6 +42,8 @@ import {
type Preset,
type ProviderId,
} from "@/lib/catalog/types";
+import { asSystem, runAs, type Actor } from "./access/actor";
+import { AccountOffError, ownerActor, rowOwner, runAsOwner } from "./access/permissions";
import { db } from "./db";
import { listElements } from "./elements";
import { pollTrainings } from "./training";
@@ -1035,8 +1037,7 @@ async function advanceDependents(): Promise<void> {
const rows = db().prepare(READY_DEPENDENTS).all(50 + submitting().size) as Row[];
// A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.
let lookedAgain: Promise<boolean> | undefined;
- for (const r of rows) {
- if (submitting().has(r.id)) continue;
+ const advance = async (r: Row): Promise<void> => {
// A step queued before its model was retired runs on what replaced it (and its row says so).
const moved = currentRequest(JSON.parse(r.request_json) as GenerationRequest);
const stored = moved.request;
@@ -1056,12 +1057,12 @@ async function advanceDependents(): Promise<void> {
const skipped = allSlots.flatMap((s, i) => (s.optional && broken(allDeps[i]) ? [i] : []));
if (allDeps.some((d, i) => broken(d) && !skipped.includes(i))) {
fail(waitedOnFailure(!!stored.frame));
- continue;
+ return;
}
const keep = (_: unknown, i: number) => !skipped.includes(i);
const deps = allDeps.filter(keep);
const slots = allSlots.filter(keep);
- if (deps.some((d) => d!.status !== "succeeded")) continue;
+ if (deps.some((d) => d!.status !== "succeeded")) return;
const request = skipped.length ? withoutSkipped(stored, allSlots, skipped) : stored;
// What changed upstream (an earlier fallback) is said on this step too, down to the finished result.
const notices = [request.notice, ...deps.map((d) => (JSON.parse(d!.request_json) as GenerationRequest).notice)].filter((x): x is string => !!x);
@@ -1070,7 +1071,7 @@ async function advanceDependents(): Promise<void> {
const short = slots.map((s, i) => listShortfall(outputs[i], s)).find(Boolean);
if (short) {
fail(`${earlier} ${short}`);
- continue;
+ return;
}
submitting().add(r.id);
let handedOff = false;
@@ -1080,7 +1081,7 @@ async function advanceDependents(): Promise<void> {
const missing = values.findIndex((u) => !u);
if (missing >= 0) {
fail(`${earlier} has no ${slotNoun(slots[missing])} to use`);
- continue;
+ return;
}
// Routing reads cached reachability: make sure it's fresh for local engines. An Original counts with the routes of
// the engine it runs on, ComfyUI taken as answering: one on the cloud doesn't use it, so doesn't wait for it.
@@ -1095,9 +1096,9 @@ async function advanceDependents(): Promise<void> {
if (!back && first === undefined) {
comfyWaits().set(r.id, Date.now());
update(r.id, { message: "Waits for ComfyUI to answer" });
- continue;
+ return;
}
- if (!back && Date.now() - first! < COMFY_WAIT.ms) continue;
+ if (!back && Date.now() - first! < COMFY_WAIT.ms) return;
}
comfyWaits().delete(r.id);
if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();
@@ -1126,6 +1127,19 @@ async function advanceDependents(): Promise<void> {
} finally {
if (!handedOff) submitting().delete(r.id);
}
+ };
+ for (const r of rows) {
+ if (submitting().has(r.id)) continue;
+ // Each step is planned and submitted as the person who started its chain.
+ let owner: Actor;
+ try {
+ owner = ownerActor(rowOwner(r));
+ } catch (e) {
+ if (!(e instanceof AccountOffError)) throw e;
+ update(r.id, { status: "failed", error: e.message, message: null, completed_at: Date.now() });
+ continue;
+ }
+ await runAs(owner, () => advance(r));
}
}
@@ -1314,25 +1328,29 @@ export function ensureRunner(): void {
cur.fast = fastTick;
cur.polling ??= new Set();
if (!cur.fastTimer) {
- cur.fastTimer = setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS);
+ cur.fastTimer = asSystem(() => setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS));
cur.fastTimer.unref?.();
}
return;
}
- const state: RunnerState = {
- busy: false,
- tick,
- fast: fastTick,
- polling: new Set(),
- timer: setInterval(() => void globalThis.__fuobeRunner?.tick(), POLL_MS),
- fastTimer: setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS),
- };
- state.timer.unref?.();
- state.fastTimer?.unref?.();
- globalThis.__fuobeRunner = state;
- void probeComfy().catch(() => false);
- void probeOllama().catch(() => false);
- sweepInterrupted();
+ // The timers belong to the server, not to whichever request happened to start them: each row is then worked on as
+ // its owner (pollGuarded, advanceDependents).
+ asSystem(() => {
+ const state: RunnerState = {
+ busy: false,
+ tick,
+ fast: fastTick,
+ polling: new Set(),
+ timer: setInterval(() => void globalThis.__fuobeRunner?.tick(), POLL_MS),
+ fastTimer: setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS),
+ };
+ state.timer.unref?.();
+ state.fastTimer?.unref?.();
+ globalThis.__fuobeRunner = state;
+ void probeComfy().catch(() => false);
+ void probeOllama().catch(() => false);
+ sweepInterrupted();
+ });
}
/** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. */
@@ -1352,9 +1370,11 @@ async function pollGuarded(r: Row): Promise<void> {
if (polling.has(r.id)) return;
polling.add(r.id);
try {
- await pollOne(r);
+ // Polled, downloaded and saved as the person who started it.
+ await runAsOwner(rowOwner(r), () => pollOne(r));
} catch (e) {
- update(r.id, { message: `Poll error: ${(e as Error).message}` });
+ if (e instanceof AccountOffError) update(r.id, { status: "failed", error: e.message, completed_at: Date.now(), message: null });
+ else update(r.id, { message: `Poll error: ${(e as Error).message}` });
} finally {
polling.delete(r.id);
}
diff --git a/src/server/library.ts b/src/server/library.ts
index 546c9e76..4a0e1b67 100644
--- a/src/server/library.ts
+++ b/src/server/library.ts
@@ -21,6 +21,7 @@ import {
type Folder,
type ReviewFilter,
} from "@/lib/library";
+import { asSystem } from "./access/actor";
import { db } from "./db";
import { assetUses, cancelGeneration, deleteGeneration, getGeneration, type ListOptions } from "./generations";
import { absolutePath, deleteAsset, getAsset } from "./storage";
@@ -185,10 +186,13 @@ declare global {
export function ensureTrashPurge(): void {
if (globalThis.__fuobeTrashPurge) return;
const run = () => void purgeTrash().catch((e) => console.warn(`[fuobe] trash purge failed: ${(e as Error).message}`));
- const timer = setInterval(run, DAY);
- timer.unref?.();
- globalThis.__fuobeTrashPurge = { timer };
- run();
+ // Housekeeping for everyone's Trash: the server's work, whichever library read started it.
+ asSystem(() => {
+ const timer = setInterval(run, DAY);
+ timer.unref?.();
+ globalThis.__fuobeTrashPurge = { timer };
+ run();
+ });
}
export function trashCount(): number {
diff --git a/src/server/mcp.ts b/src/server/mcp.ts
index ebec6419..abb64c54 100644
--- a/src/server/mcp.ts
+++ b/src/server/mcp.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
// The studio modules behind the studio tools (tools.ts imports them too; named here so MCP never runs without them).
import "./assist/studio-routes";
import { apiSchema, executeTool, getTool, planFor, TOOLS, type ToolContext } from "./assist/tools";
+import { currentActor, runAs, type Actor } from "./access/actor";
import { engineMode } from "./settings";
import { recipeMarkdown } from "@/lib/recipe";
import { enabledSkills, getSkill, skillRecipe } from "./skills";
@@ -38,7 +39,8 @@ type JsonRpcResponse = { jsonrpc: "2.0"; id: string | number | null } & ({ resul
const ok = (id: JsonRpcRequest["id"], result: unknown): JsonRpcResponse => ({ jsonrpc: "2.0", id: id ?? null, result });
const fail = (id: JsonRpcRequest["id"], code: number, message: string): JsonRpcResponse => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
-const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cloud" });
+/** The tools' context: the engine, and who the tool acts for (the token's or session's person, from the scope). */
+const ctx = (): ToolContext => ({ engine: engineMode() === "open" ? "open" : "cloud", actor: currentActor() });
const READ_ONLY = new Set(["search_models", "list_elements", "list_recent", "check_generations", "estimate_cost", "estimate_job", "list_skills", "load_skill", "read_source"]);
@@ -160,8 +162,16 @@ function promptGet(params: unknown) {
};
}
-/** Handle one JSON-RPC message; null for notifications (no response). */
-export async function handleMcp(msg: unknown): Promise<JsonRpcResponse | null> {
+/**
+ * Handle one JSON-RPC message as `actor` (the person behind the bearer token or session; by default whoever the scope
+ * says is acting); null for notifications (no response). Everything the message runs — tool calls and what they start —
+ * acts for that person.
+ */
+export async function handleMcp(msg: unknown, actor: Actor = currentActor()): Promise<JsonRpcResponse | null> {
+ return runAs(actor, () => answer(msg));
+}
+
+async function answer(msg: unknown): Promise<JsonRpcResponse | null> {
const m = msg as JsonRpcRequest;
if (!m || m.jsonrpc !== "2.0" || typeof m.method !== "string") return fail(null, -32600, "Invalid request");
const isNotification = m.id === undefined;
diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.ts
index 3601cc11..3070677b 100644
--- a/src/server/swap-studio.ts
+++ b/src/server/swap-studio.ts
@@ -46,6 +46,8 @@ import { cloudMaskCut, frozenTakePlan, planAnchor, planAssembly, planMask, planN
import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
import { ACCESS_PLACE } from "@/lib/model-access";
import { createPipeline } from "./chains";
+import { asSystem } from "./access/actor";
+import { rowOwner, runAsOwner } from "./access/permissions";
import { db } from "./db";
import { cancelGeneration, getGeneration, previewChained } from "./generations";
import { isOffered, offeredLoras } from "./model-access";
@@ -342,10 +344,11 @@ export function ensureSwapStudioRunner(): void {
if (globalThis.__fuobeSwapStudioRunner) return;
const tick = () => {
try {
- const rows = db().prepare("SELECT id FROM swap_projects WHERE waiting > 0").all() as { id: string }[];
+ const rows = db().prepare("SELECT * FROM swap_projects WHERE waiting > 0").all() as { id: string }[];
for (const r of rows) {
try {
- advanceProject(r.id);
+ // Waiting takes launch as the person who started the project.
+ runAsOwner(rowOwner(r), () => advanceProject(r.id));
} catch (e) {
console.error(`[swap-studio] ${r.id}:`, (e as Error).message);
}
@@ -354,9 +357,12 @@ export function ensureSwapStudioRunner(): void {
console.error("[swap-studio] sweep:", (e as Error).message);
}
};
- globalThis.__fuobeSwapStudioRunner = setInterval(tick, 3000);
- globalThis.__fuobeSwapStudioRunner.unref?.();
- setTimeout(tick, 500).unref?.();
+ // The server's timers, whichever request started them; each project then advances as its owner.
+ asSystem(() => {
+ globalThis.__fuobeSwapStudioRunner = setInterval(tick, 3000);
+ globalThis.__fuobeSwapStudioRunner.unref?.();
+ setTimeout(tick, 500).unref?.();
+ });
}
// ---------------------------------------------------------------------------
diff --git a/src/server/training.ts b/src/server/training.ts
index 1c5be9e1..804a6654 100644
--- a/src/server/training.ts
+++ b/src/server/training.ts
@@ -28,6 +28,7 @@ import {
} from "@/lib/catalog/training";
import { TRAINING_REPLACED_BY } from "@/lib/catalog/replaced";
import { DEFAULT_AI_TOOLKIT_URL } from "@/lib/connections";
+import { AccountOffError, rowOwner, runAsOwner } from "./access/permissions";
import { DATA_DIR, db } from "./db";
import { getElement, updateElement } from "./elements";
import { keepTrainedLora, lorasPath, ownCopy, recordTrainedMirror } from "./loras";
@@ -438,15 +439,25 @@ export async function pollTrainings(): Promise<void> {
const sql = `SELECT * FROM trainings WHERE status IN ('queued','running') AND target IN (${retired.map(() => "?").join(", ")})`;
for (const r of db().prepare(sql).all(...retired) as Row[]) fail(r.id, r.element_id, retiredTraining(r.target)!);
// Copies of hosted LoRAs a restart cut off: start them again.
- for (const r of db().prepare(`SELECT * FROM trainings WHERE status = 'succeeded' AND meta_json LIKE '%"keep":"pending"%'`).all() as Row[]) keepInBackground(r);
+ // Each training is polled, and its LoRA kept, as the person who started it.
+ for (const r of db().prepare(`SELECT * FROM trainings WHERE status = 'succeeded' AND meta_json LIKE '%"keep":"pending"%'`).all() as Row[]) {
+ try {
+ runAsOwner(rowOwner(r), () => keepInBackground(r));
+ } catch (e) {
+ if (!(e instanceof AccountOffError)) throw e;
+ setKeep(r.id, "failed", e.message);
+ }
+ }
const rows = db().prepare("SELECT * FROM trainings WHERE status = 'running' AND external_id IS NOT NULL").all() as Row[];
await Promise.all(
- rows.map((r) =>
- pollOne(r).catch((e) => {
- if (permanent(e)) return fail(r.id, r.element_id, (e as Error).message);
+ rows.map(async (r) => {
+ try {
+ await runAsOwner(rowOwner(r), () => pollOne(r));
+ } catch (e) {
+ if (e instanceof AccountOffError || permanent(e)) return fail(r.id, r.element_id, (e as Error).message);
update(r.id, { message: `Checking status failed: ${(e as Error).message}` });
- }),
- ),
+ }
+ }),
);
}