Files
AgentCompany/tests/unit/company-mode-switch.test.ts
T
ZacharyZhang-NY 40040b3dd2 refactor(errors): surface 57 deferred catch-and-swallow sites via logger
The earlier sweep cleaned the hot path (worker/runtime/automation/api-
server/ipc core — 59 sites). This pass finishes the deferred long tail:
main/* services, database/* CRUD modules, api-server/* routes, ipc-*
handlers, thread-integration, automation helpers, browser, skills.

Default strategy: catch (error) { logger.warn("[module] context:", ...) }
— preserve current behavior, make the failure visible instead of
silently hidden. Widened 3 logger interface signatures to include warn
where callers only passed info/error previously (thread-helpers,
host-environment-service, ipc-domain-common).

Legitimate boundaries left intact: JSON.parse on untrusted input, DNS
resolver no-records paths, explicit safe* helpers (safeJson, parseJson,
parseTriggerDetail), URL-parse predicates, and `<unserialisable>`
fallbacks inside the prompt-builder summarisers. Each kept catch now
either has a reason in context or is a documented safe* helper.

Tests adjusted only where test-constructed no-op loggers needed a warn
stub (message-dispatch, company-mode-switch, ipc-agent-graph-handlers).

With the earlier pass, AgentCompany no longer has silently-swallowing
catch blocks in main-process or renderer business code.
2026-04-17 15:25:13 -04:00

159 lines
5.1 KiB
TypeScript

import { mkdtemp, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { IpcMainInvokeEvent } from "electron";
import type { DesktopResult } from "@shared/contracts";
import { IPC_CHANNELS } from "@shared/contracts";
import { AppDatabase } from "../../src/main/database";
import { registerCoreAdminHandlers } from "../../src/main/ipc-core-admin-handlers";
import { createThreadIntegration } from "../../src/main/thread-integration";
type IpcHandler = (
event: IpcMainInvokeEvent,
...args: unknown[]
) => Promise<DesktopResult<unknown>> | DesktopResult<unknown>;
const tempDirs: string[] = [];
async function createTempDir(prefix: string) {
const dir = await mkdtemp(join(tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});
describe("company mode switching", () => {
it("clears cofounder review artifacts when switching back to AI CEO", async () => {
const profileDir = await createTempDir("agentcompany-mode-switch-");
const db = new AppDatabase(profileDir);
db.init();
db.updateConnectorHealth({
id: "openai-codex",
status: "ready",
authState: "authenticated",
version: "test",
lastError: null,
});
const companyId = db.saveCompany({
name: "Mode Switch Co",
description: "Execution mode cleanup",
status: "active",
executionMode: "ai_cofounder",
autoApproveHires: false,
reviewDeliverables: true,
});
const workspaceId = db.saveWorkspace({
companyId,
name: "Primary",
localPath: profileDir,
repoUrl: "",
repoRef: "",
isPrimary: true,
});
const ceoId = db.saveAgent({
companyId,
name: "CEO",
role: "CEO",
title: "Chief Executive Officer",
status: "active",
reportsTo: null,
connectorId: "openai-codex",
workspaceId,
model: null,
capabilities: "Lead the company",
budgetMonthlyUsd: 250,
});
const engineerId = db.saveAgent({
companyId,
name: "Engineer",
role: "Engineer",
title: "Lead Engineer",
status: "active",
reportsTo: ceoId,
connectorId: "openai-codex",
workspaceId,
model: null,
capabilities: "Ship features",
budgetMonthlyUsd: 180,
department: "engineering",
});
const taskId = db.saveTask({
companyId,
title: "Ship feature",
description: "Waits for cofounder review.",
assigneeAgentId: engineerId,
workspaceId,
priority: "high",
status: "in_progress",
});
const threadIntegration = createThreadIntegration({
db,
logger: { info: () => {}, warn: () => {}, error: () => {} },
});
threadIntegration.onTaskCreated(taskId, companyId);
threadIntegration.onRunFinished("run-1", taskId, engineerId, companyId, "succeeded", null);
db.setTaskRequiresUserReview(taskId, true);
const approvalId = db.requestApproval({
companyId,
relatedTaskId: taskId,
requestedByAgentId: engineerId,
type: "deliverable_review",
payloadSummary: "Review deliverable",
impactSummary: "Needs review",
payloadJson: "{}",
});
threadIntegration.onApprovalCreated(approvalId, companyId, taskId, "deliverable_review", "Review deliverable");
expect(db.listThreadWaitStates(companyId).length).toBeGreaterThan(0);
expect(db.getTask(taskId).requiresUserReview).toBe(true);
expect(db.getApprovalRecord(approvalId).state).toBe("pending");
const handlers = new Map<string, IpcHandler>();
registerCoreAdminHandlers({
registerHandle: (channel, handler) => {
handlers.set(channel, handler);
},
db,
ensureCompanyExists: (id) => (db.hasCompany(id) ? null : { ok: false, error: { code: "COMPANY_NOT_FOUND", message: "missing" } }),
publishDomainChanged: vi.fn(),
handleApprovalResolved: (resolvedApprovalId, resolvedCompanyId, decision) => {
threadIntegration.onApprovalResolved(resolvedApprovalId, resolvedCompanyId, decision);
},
checkConnector: vi.fn(),
openConnectorAuthTerminal: vi.fn(),
openGenericTerminal: vi.fn(),
});
const saveCompany = handlers.get(IPC_CHANNELS.saveCompany);
if (!saveCompany) {
throw new Error("saveCompany handler was not registered.");
}
const result = await saveCompany(null as unknown as IpcMainInvokeEvent, {
id: companyId,
name: "Mode Switch Co",
description: "Execution mode cleanup",
status: "active",
autoApproveHires: true,
reviewDeliverables: false,
executionMode: "ai_ceo",
}) as { ok: boolean };
expect(result.ok).toBe(true);
expect(db.getCompanyExecutionMode(companyId)).toBe("ai_ceo");
expect(db.listThreadWaitStates(companyId)).toHaveLength(0);
expect(db.getTask(taskId).requiresUserReview).toBe(false);
expect(db.getApprovalRecord(approvalId).state).toBe("approved");
db.close();
});
});