update
This commit is contained in:
1 parent
09971cabc2
commit
9145572422
163 files changed
+3348
-2874
No files matched your search
@@ -38,7 +38,8 @@ export function handleTaskStatusChange(
|
||||
let task: ReturnType<typeof db.getTask> | null = null;
|
||||
try {
|
||||
task = db.getTask(taskId);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
deps.logger.warn(`[automation] handleTaskStatusChange: task ${taskId} not found:`, error);
|
||||
return;
|
||||
}
|
||||
if (!task) return;
|
||||
@@ -64,8 +65,8 @@ export function handleTaskStatusChange(
|
||||
const agent = db.getAgent(task.assigneeAgentId);
|
||||
context.department = agent.department ?? undefined;
|
||||
}
|
||||
} catch {
|
||||
// Agent may have been deleted after the task update; keep the transition without department context.
|
||||
} catch (error) {
|
||||
deps.logger.warn(`[automation] Agent ${task.assigneeAgentId} deleted after task update — continuing without department context:`, error);
|
||||
}
|
||||
|
||||
dispatchAutomation("task_status_changed", context);
|
||||
@@ -114,7 +115,8 @@ export function handleTaskCreated(
|
||||
let task: ReturnType<typeof db.getTask> | null = null;
|
||||
try {
|
||||
task = db.getTask(taskId);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
deps.logger.warn(`[automation] handleTaskCreated: task ${taskId} not found:`, error);
|
||||
return;
|
||||
}
|
||||
if (!task) return;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AppDatabase } from "../database";
|
||||
import type { RunRecord } from "@shared/types";
|
||||
import type { RunRecord, SectionId } from "@shared/types";
|
||||
import type { NotificationOptions } from "../notification-service";
|
||||
import type { AutomationEventContext, RunFinishedEvent } from "./types";
|
||||
import { IMPORTANT_DOCUMENT_TYPES } from "./types";
|
||||
@@ -25,6 +25,93 @@ export interface RunCompletionCallbacks {
|
||||
handleTaskStatusChange: (taskId: string, companyId: string, previousStatus: string, newStatus: string) => void;
|
||||
}
|
||||
|
||||
// ─── Pure helpers exported for testing ─────────────────────────────────────
|
||||
|
||||
export type DeliverableTaskType = "code" | "research" | "content" | "management" | "general";
|
||||
|
||||
/** Returns true for task types that require a tangible artifact before auto-advancing. */
|
||||
export function needsDeliverableCheck(taskType: DeliverableTaskType | string): boolean {
|
||||
return taskType === "research" || taskType === "content";
|
||||
}
|
||||
|
||||
export interface DeliverableCheckInput {
|
||||
taskType: DeliverableTaskType | string;
|
||||
hasKnowledgeEntry: boolean;
|
||||
hasDocument: boolean;
|
||||
hasSubstantialComment: boolean;
|
||||
}
|
||||
|
||||
/** Returns the next task status and comment after a successful run. */
|
||||
export function determinePostRunStatus(input: DeliverableCheckInput): {
|
||||
nextStatus: "in_review" | "in_progress";
|
||||
comment: string;
|
||||
} {
|
||||
if (!needsDeliverableCheck(input.taskType)) {
|
||||
return {
|
||||
nextStatus: "in_review",
|
||||
comment: "Run completed successfully. Awaiting review.",
|
||||
};
|
||||
}
|
||||
const delivered = input.hasKnowledgeEntry || input.hasDocument || input.hasSubstantialComment;
|
||||
if (delivered) {
|
||||
return {
|
||||
nextStatus: "in_review",
|
||||
comment: "Run completed with deliverable. Awaiting review.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
nextStatus: "in_progress",
|
||||
comment: `${input.taskType} task run completed but no deliverable artifact was detected. Flagging for manager review.`,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BudgetThresholdInput {
|
||||
name: string;
|
||||
budgetMonthlyUsd: number;
|
||||
spentMonthlyUsd: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires budget threshold notifications when utilization >= 80%.
|
||||
* The notify callback receives a NotificationOptions-style object so callers
|
||||
* can forward it directly to the notification service.
|
||||
*/
|
||||
export function checkBudgetThreshold(
|
||||
agent: BudgetThresholdInput,
|
||||
notify: (opts: { title: string; body: string; urgency: "critical" | "informational"; navigation: { section: SectionId }; batchKey?: string }) => void,
|
||||
localizeNotification: (en: string, zh: string) => string,
|
||||
): void {
|
||||
if (agent.budgetMonthlyUsd <= 0) return;
|
||||
const utilization = agent.spentMonthlyUsd / agent.budgetMonthlyUsd;
|
||||
if (utilization < 0.8) return;
|
||||
|
||||
const pct = Math.round(utilization * 100);
|
||||
notify({
|
||||
title: localizeNotification("Budget Warning", "预算警告"),
|
||||
body: localizeNotification(
|
||||
`${agent.name} has used ${pct}% of monthly budget`,
|
||||
`${agent.name} 已使用月度预算的 ${pct}%`,
|
||||
),
|
||||
urgency: "informational",
|
||||
navigation: { section: "costs" },
|
||||
batchKey: "budget_alerts",
|
||||
});
|
||||
|
||||
if (utilization >= 1.0) {
|
||||
notify({
|
||||
title: localizeNotification("Budget Exhausted", "预算耗尽"),
|
||||
body: localizeNotification(
|
||||
`${agent.name} has reached 100% of monthly budget and is paused`,
|
||||
`${agent.name} 已达到月度预算上限并已暂停`,
|
||||
),
|
||||
urgency: "critical",
|
||||
navigation: { section: "costs" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Internal DB-backed deliverable check ───────────────────────────────────
|
||||
|
||||
function checkRunProducedDeliverable(db: AppDatabase, runId: string, companyId: string, taskId: string): boolean {
|
||||
// Prefer causal binding via source_run_id (set when document/knowledge
|
||||
// is created during a run). Falls back to time-window for legacy data
|
||||
@@ -115,6 +202,36 @@ function createDeliverableReviewApproval(
|
||||
return approvalId;
|
||||
}
|
||||
|
||||
/** Advances a task to in_review and optionally flags deliverables for user review. */
|
||||
function advanceToInReview(
|
||||
deps: RunCompletionDeps,
|
||||
callbacks: RunCompletionCallbacks,
|
||||
run: RunRecord,
|
||||
taskId: string,
|
||||
statusMessage: string,
|
||||
): void {
|
||||
const { db, logger, publishDomainChanged } = deps;
|
||||
db.advanceTaskStatus(taskId, "in_review", statusMessage);
|
||||
callbacks.handleTaskStatusChange(taskId, run.companyId, "in_progress", "in_review");
|
||||
const company = db.listSnapshot().companies.find((c) => c.id === run.companyId);
|
||||
if (company?.reviewDeliverables) {
|
||||
const importantDocs = findImportantDocsForRun(db, run.id, run.companyId);
|
||||
if (importantDocs.length > 0) {
|
||||
db.setTaskRequiresUserReview(taskId, true);
|
||||
const agent = db.getAgent(run.agentId);
|
||||
if (agent.heartbeatEnabled) {
|
||||
db.setHeartbeat(agent.id, false, agent.heartbeatIntervalSec || 120);
|
||||
logger.info(`[deliverable-review] Paused heartbeat for ${agent.name} — deliverable flagged for review.`);
|
||||
}
|
||||
const chain = db.getChainOfCommand(agent.id);
|
||||
if (chain.length === 0) {
|
||||
createDeliverableReviewApproval(deps, run.companyId, taskId, run.agentId, importantDocs);
|
||||
}
|
||||
}
|
||||
}
|
||||
publishDomainChanged();
|
||||
}
|
||||
|
||||
export function processRunCompletion(
|
||||
deps: RunCompletionDeps,
|
||||
callbacks: RunCompletionCallbacks,
|
||||
@@ -123,13 +240,14 @@ export function processRunCompletion(
|
||||
isQuitting: () => boolean,
|
||||
): void {
|
||||
if (isQuitting()) return;
|
||||
const { db, logger, publishDomainChanged, notify, wakeAgentIfPossible } = deps;
|
||||
const { db, logger: _logger, publishDomainChanged, notify, wakeAgentIfPossible } = deps;
|
||||
const { dispatchAutomation, handleTaskStatusChange } = callbacks;
|
||||
|
||||
let task: ReturnType<typeof db.getTask> | null = null;
|
||||
try {
|
||||
task = db.getTask(run.taskId);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
deps.logger.warn(`[automation] processRunCompletion: task ${run.taskId} not found for run ${run.id}:`, error);
|
||||
return;
|
||||
}
|
||||
if (!task) return;
|
||||
@@ -141,7 +259,7 @@ export function processRunCompletion(
|
||||
|
||||
if (isSuccess && effectiveStatus === "in_progress") {
|
||||
// Check if non-code task produced a deliverable before auto-advancing
|
||||
const taskType = ((task as unknown as Record<string, unknown>).task_type as string) ?? "general";
|
||||
const taskType = task.taskType ?? "general";
|
||||
const needsDeliverable = taskType === "research" || taskType === "content";
|
||||
|
||||
if (needsDeliverable) {
|
||||
@@ -162,49 +280,13 @@ export function processRunCompletion(
|
||||
publishDomainChanged();
|
||||
// Skip the normal in_review advance
|
||||
} else {
|
||||
db.advanceTaskStatus(task.id, "in_review", "Run completed with deliverable. Awaiting review.");
|
||||
handleTaskStatusChange(task.id, run.companyId, "in_progress", "in_review");
|
||||
advanceToInReview(deps, callbacks, run, task.id, "Run completed with deliverable. Awaiting review.");
|
||||
effectiveStatus = "in_review";
|
||||
const company = db.listSnapshot().companies.find((c) => c.id === run.companyId);
|
||||
if (company?.reviewDeliverables) {
|
||||
const importantDocs = findImportantDocsForRun(db, run.id, run.companyId);
|
||||
if (importantDocs.length > 0) {
|
||||
db.setTaskRequiresUserReview(task.id, true);
|
||||
const agent = db.getAgent(run.agentId);
|
||||
if (agent.heartbeatEnabled) {
|
||||
db.setHeartbeat(agent.id, false, agent.heartbeatIntervalSec || 120);
|
||||
logger.info(`[deliverable-review] Paused heartbeat for ${agent.name} — deliverable flagged for review.`);
|
||||
}
|
||||
const chain = db.getChainOfCommand(agent.id);
|
||||
if (chain.length === 0) {
|
||||
createDeliverableReviewApproval(deps, run.companyId, task.id, run.agentId, importantDocs);
|
||||
}
|
||||
}
|
||||
}
|
||||
publishDomainChanged();
|
||||
}
|
||||
} else {
|
||||
// Code/management/general tasks advance normally
|
||||
db.advanceTaskStatus(task.id, "in_review", "Run completed successfully. Awaiting review.");
|
||||
handleTaskStatusChange(task.id, run.companyId, "in_progress", "in_review");
|
||||
advanceToInReview(deps, callbacks, run, task.id, "Run completed successfully. Awaiting review.");
|
||||
effectiveStatus = "in_review";
|
||||
const company = db.listSnapshot().companies.find((c) => c.id === run.companyId);
|
||||
if (company?.reviewDeliverables) {
|
||||
const importantDocs = findImportantDocsForRun(db, run.id, run.companyId);
|
||||
if (importantDocs.length > 0) {
|
||||
db.setTaskRequiresUserReview(task.id, true);
|
||||
const agent = db.getAgent(run.agentId);
|
||||
if (agent.heartbeatEnabled) {
|
||||
db.setHeartbeat(agent.id, false, agent.heartbeatIntervalSec || 120);
|
||||
logger.info(`[deliverable-review] Paused heartbeat for ${agent.name} — deliverable flagged for review.`);
|
||||
}
|
||||
const chain = db.getChainOfCommand(agent.id);
|
||||
if (chain.length === 0) {
|
||||
createDeliverableReviewApproval(deps, run.companyId, task.id, run.agentId, importantDocs);
|
||||
}
|
||||
}
|
||||
}
|
||||
publishDomainChanged();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,27 +346,14 @@ export function processRunCompletion(
|
||||
...automationContext,
|
||||
agentId: agent.id,
|
||||
});
|
||||
// Fire OS notification for budget threshold warning
|
||||
const pct = Math.round(utilization * 100);
|
||||
const budgetLocale = db.listSnapshot().locale;
|
||||
notify({
|
||||
title: localizeNotification(budgetLocale, "Budget Warning", "预算警告"),
|
||||
body: localizeNotification(budgetLocale, `${agent.name} has used ${pct}% of monthly budget`, `${agent.name} 已使用月度预算的 ${pct}%`),
|
||||
urgency: "informational",
|
||||
navigation: { section: "costs" },
|
||||
batchKey: "budget_alerts",
|
||||
});
|
||||
if (utilization >= 1.0) {
|
||||
// Fire OS notification for budget exhaustion (agent auto-paused by database)
|
||||
notify({
|
||||
title: localizeNotification(budgetLocale, "Budget Exhausted", "预算耗尽"),
|
||||
body: localizeNotification(budgetLocale, `${agent.name} has reached 100% of monthly budget and is paused`, `${agent.name} 已达到月度预算上限并已暂停`),
|
||||
urgency: "critical",
|
||||
navigation: { section: "costs" },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const budgetLocale = db.listSnapshot().locale;
|
||||
checkBudgetThreshold(
|
||||
agent,
|
||||
notify,
|
||||
(en, zh) => localizeNotification(budgetLocale, en, zh),
|
||||
);
|
||||
} catch {
|
||||
// Budget follow-up is best-effort; do not fail run completion if the agent disappeared.
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user