Files
AgentCompany/src/main/ipc-domain-common.ts
ZacharyZhang-NY b1d1fbc54f Drain document lifecycle events through a durable processor
Before this commit `createDocumentWithLifecycle` enqueued ledger rows
inside the save transaction but consumed them from an in-memory
`pendingSideEffects` array straight after commit. A crash between the
commit and the drain stranded rows as `pending` forever; a crash mid
handler left them as `running`; and there was no retry budget.

The new `DocumentLifecycleProcessor` is the single drainer. It:

  - claims work via `claimPendingBatch`, an atomic `UPDATE … RETURNING`
    that flips rows from `pending` to `running` while incrementing
    `attempts`, so two drainers cannot race onto the same row;
  - dispatches each row through a handler registered by `hookType`,
    parsing the frozen `payload_json` back into the call arguments;
  - records `succeeded` / `failed` / `retryable` outcomes through the
    ledger, so a transient failure stays on the queue until the attempt
    cap expires, after which it is marked `failed` for operators;
  - reclaims rows stuck in `running` past `staleRunningMs` back to
    `pending` on every sweep tick plus at startup, so a crashed process
    never leaves a row orphaned;
  - runs a periodic sweep so every document — including those whose
    immediate post-commit drain failed — is eventually advanced.

`createDocumentWithLifecycle` now only enqueues and then calls
`lifecycleProcessor.drainForDocument` for the immediate happy-path pass.
Handlers live in `document-lifecycle-handlers.ts` so the processor stays
free of service-graph knowledge. The processor is constructed in
`bootstrap-application`, started there, and stopped on `before-quit`.
2026-04-19 16:14:51 -04:00

68 lines
3.3 KiB
TypeScript

import type { IpcMainInvokeEvent } from "electron";
import { z } from "zod";
import type { DesktopResult } from "@shared/contracts";
import type { bootstrapOnboardingSchema } from "@shared/contracts";
import type { DesktopEvent, SectionId } from "@shared/types";
import type { AppDatabase } from "./database";
import type { createSkillService } from "./skill-service";
import type { createBudgetEnforcementService } from "./budget-enforcement-service";
import type { CheckpointEngineLike } from "./document-lifecycle";
import type { DocumentLifecycleProcessor } from "./document-lifecycle-processor";
import type { ThreadIntegrationService } from "./thread-integration";
interface BrowserActionControl {
clearSocialAccountData: (socialAccountId: string, screenshotPaths?: string[]) => Promise<void>;
cancelAction: (actionId: string) => boolean;
launchLoginBrowser: (socialAccountId: string, platform: string, loginUrl?: string) => Promise<{
success: boolean;
cancelled: boolean;
summary: string;
screenshotPath: string | null;
error: string | null;
}>;
extractProfileFromSession: (socialAccountId: string, platform: string) => Promise<{
accountName: string;
displayName: string;
}>;
}
export interface RegisterDomainHandlersDependencies {
registerHandle: (
channel: string,
handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => Promise<DesktopResult<unknown>> | DesktopResult<unknown>,
) => void;
db: AppDatabase;
logger: {
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
};
ensureCompanyExists: (companyId: string) => DesktopResult<never> | null;
findInvalidReference: (
companyId: string,
refs: Array<{ id: string | null | undefined; table: string; label: string }>,
) => { id: string | null | undefined; table: string; label: string } | null;
publishDomainChanged: () => void;
emitEvent: (event: DesktopEvent) => void;
notify: (options: { title: string; body: string; urgency: "critical" | "informational"; navigation?: { section: SectionId; entityId?: string }; batchKey?: string }) => void;
wakeAgentIfPossible: (agentId: string | null | undefined, companyId: string, trigger: string) => string | null;
dispatchAutomation: (trigger: string, ctx: { companyId: string; [key: string]: unknown }) => void;
runWorkflowPipeline: (workflowId: string, companyId: string) => Promise<void>;
bootstrapOnboarding: (input: z.infer<typeof bootstrapOnboardingSchema>) => unknown;
getBrowserActions: () => BrowserActionControl | null;
randomFallbackCompanyId: () => string;
skillService: ReturnType<typeof createSkillService> | null;
budgetService: ReturnType<typeof createBudgetEnforcementService> | null;
/** Called when a human sends a message to resolve thread wait states. */
onHumanMessage?: (companyId: string, toAgentId?: string | null, threadId?: string | null, waitStateId?: string | null) => void;
/**
* Shared document-creation lifecycle collaborators. Routed through the
* dependency bag so both the IPC save path and the HTTP save path call
* the same `createDocumentWithLifecycle` fan-out.
*/
threadIntegration: ThreadIntegrationService;
checkpointEngine: CheckpointEngineLike;
lifecycleProcessor: Pick<DocumentLifecycleProcessor, "drainForDocument">;
}
export { ok, fail } from "./ipc-core-common";