Files
AgentCompany/tests/integration/thread-wait-heartbeat.spec.ts
T
ZacharyZhang-NY e94939a562 test(connector-id): migrate fixtures and assertions to pi-mono ids
Replaces legacy adapter ids (codex_local / claude_local / gemini_local /
claude_compatible) across ~42 test files with pi-mono equivalents:
- codex_local → openai-codex
- claude_local → claude-pro
- gemini_local → gemini-cli
- claude_compatible → anthropic

Hand-rewrites where fixture semantics changed:
- connector-matching: TASK_TYPE_PREFERENCE ordering rebased (claude-pro
  first for code/content/management; google first for research)
- connector-model-policy: getModels(provider) from pi-ai instead of the
  deleted adapter.module.models array
- session-management + edge-case-session: adapter exemption removed;
  rotation now uniform under pi-mono
- ipc-core-admin-handlers: CSV compat model replaced with pi-ai anthropic
- connectors.spec: lookup by openai-codex id (catalog now starts with claude-pro)
- onboarding-model-pool: listProviderModels(provider) helper; label text
  changed to "ChatGPT Plus/Pro (Codex)"
- database integration: added vault insecure-fallback env + electron mock
- command-paths: uses new @main/connector-helpers normalizeCommandValue
- pi-mono-migrations: added `as string` casts for 3 negative-existence
  assertions verifying legacy ids were removed

Drops:
- pnpm-workspace.yaml packages: [] (was "packages/*"; directory empty)
- obsolete CONNECTOR_STRENGTHS import; .module.models probing

Verification:
- pnpm typecheck → 0 errors
- pnpm lint → 0 errors / 0 warnings
- pnpm build:verify → 0 errors / 0 warnings
- pnpm test:unit → 508/508 pass
- pnpm test:integration → 96/96 pass
- All 6 adapter hard gates pass (NOT FOUND / 0 matches / empty)
- pi-ai / pi-agent-core / pi-coding-agent all resolved @0.67.6
2026-04-17 02:36:53 -04:00

254 lines
7.9 KiB
TypeScript

import { mkdtemp, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { afterEach, describe, expect, it } from "vitest";
import { AppDatabase } from "../../src/main/database";
import { createThreadIntegration } from "../../src/main/thread-integration";
import { createCheckpointEngine } from "../../src/main/checkpoint-engine";
import { dispatchAgentMessage, HUMAN_SENDER_ID } from "../../src/main/message-dispatch";
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 })));
});
function createNoopLogger() {
return {
info: () => {},
warn: () => {},
error: () => {},
};
}
function createScaffold(db: AppDatabase) {
db.updateConnectorHealth({
id: "openai-codex",
status: "ready",
authState: "authenticated",
version: "test",
lastError: null,
});
const companyId = db.saveCompany({
name: "Thread Wait Co",
description: "Tests cofounder wait states and replies",
status: "active",
executionMode: "ai_cofounder",
});
const workspaceId = db.saveWorkspace({
companyId,
name: "Primary",
localPath: "/tmp/thread-wait",
repoUrl: "",
repoRef: "",
isPrimary: true,
});
const ceoId = db.saveAgent({
companyId,
name: "CEO",
role: "CEO",
title: "Chief Executive Officer",
status: "idle",
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: "idle",
reportsTo: ceoId,
connectorId: "openai-codex",
workspaceId,
model: null,
capabilities: "Ship features",
budgetMonthlyUsd: 180,
});
const taskId = db.saveTask({
companyId,
title: "Ship the feature",
description: "Implement the approved deliverable and wait for co-founder review.",
assigneeAgentId: engineerId,
workspaceId,
priority: "high",
status: "in_progress",
});
return { companyId, workspaceId, ceoId, engineerId, taskId };
}
describe("thread wait + heartbeat integration", () => {
it("pauses the assignee heartbeat on successful run completion until a human reply resolves the wait state", async () => {
const profileDir = await createTempDir("agentcompany-thread-wait-");
const db = new AppDatabase(profileDir);
db.init();
const { companyId, engineerId, taskId } = createScaffold(db);
const notifications: Array<{ title: string; body: string }> = [];
const threadIntegration = createThreadIntegration({
db,
logger: createNoopLogger(),
notify: (notification) => {
notifications.push(notification);
},
});
const checkpointEngine = createCheckpointEngine({
db,
logger: createNoopLogger(),
threadIntegration,
publishDomainChanged: () => {},
notify: () => {},
});
threadIntegration.onTaskCreated(taskId, companyId);
threadIntegration.onRunFinished("run-1", taskId, engineerId, companyId, "succeeded", null);
const thread = db.listThreads({
companyId,
type: "task",
relatedEntityType: "task",
relatedEntityId: taskId,
limit: 1,
})[0];
if (!thread) {
throw new Error("Expected a task thread to exist for the completed run.");
}
let waitStates = db.listThreadWaitStates(companyId).filter((entry) => entry.threadId === thread.id);
expect(waitStates).toHaveLength(1);
expect(waitStates[0]?.waitingFor).toBe("user_reply");
expect(checkpointEngine.shouldPauseHeartbeat(companyId, engineerId)).toBe(true);
const otherAgentId = db.saveAgent({
companyId,
name: "Marketer",
role: "CMO",
title: "Chief Marketing Officer",
status: "idle",
reportsTo: null,
connectorId: "openai-codex",
workspaceId: db.getTask(taskId).workspaceId ?? null,
model: null,
capabilities: "Drive marketing work",
budgetMonthlyUsd: 180,
});
expect(checkpointEngine.shouldPauseHeartbeat(companyId, otherAgentId)).toBe(false);
expect(notifications).toHaveLength(1);
expect(notifications[0]?.body).toContain("@Board review needed");
dispatchAgentMessage({
db,
onHumanMessage: (currentCompanyId, toAgentId, threadId, waitStateId) =>
threadIntegration.onHumanMessage(currentCompanyId, toAgentId, threadId, waitStateId),
}, {
companyId,
fromAgentId: HUMAN_SENDER_ID,
fromHumanUser: true,
channel: "direct",
toAgentId: engineerId,
threadId: thread.id,
body: "Board reviewed this deliverable. Continue.",
});
waitStates = db.listThreadWaitStates(companyId).filter((entry) => entry.threadId === thread.id);
expect(waitStates).toHaveLength(0);
expect(threadIntegration.hasUnresolvedWaitStatesForAgent(companyId, engineerId)).toBe(false);
expect(checkpointEngine.shouldPauseHeartbeat(companyId, engineerId)).toBe(false);
db.close();
});
it("resolves approval-linked wait states only when the approval is actually decided", async () => {
const profileDir = await createTempDir("agentcompany-approval-wait-");
const db = new AppDatabase(profileDir);
db.init();
const { companyId, engineerId, taskId } = createScaffold(db);
const threadIntegration = createThreadIntegration({
db,
logger: createNoopLogger(),
});
const checkpointEngine = createCheckpointEngine({
db,
logger: createNoopLogger(),
threadIntegration,
publishDomainChanged: () => {},
notify: () => {},
});
threadIntegration.onTaskCreated(taskId, companyId);
const thread = db.listThreads({
companyId,
type: "task",
relatedEntityType: "task",
relatedEntityId: taskId,
limit: 1,
})[0];
if (!thread) {
throw new Error("Expected a task thread to exist for approval resolution testing.");
}
const approvalId = db.requestApproval({
companyId,
relatedTaskId: taskId,
requestedByAgentId: engineerId,
type: "draft_review",
payloadSummary: "Review the draft",
impactSummary: "Board approval is required before this work can continue.",
payloadJson: "{}",
});
threadIntegration.onApprovalCreated(approvalId, companyId, taskId, "draft_review", "Draft review needed");
let waitStates = db.listThreadWaitStates(companyId).filter((entry) => entry.relatedApprovalId === approvalId);
expect(waitStates).toHaveLength(1);
expect(waitStates[0]?.waitingFor).toBe("user_approval");
expect(checkpointEngine.shouldPauseHeartbeat(companyId, engineerId)).toBe(true);
dispatchAgentMessage({
db,
onHumanMessage: (currentCompanyId, toAgentId, threadId, waitStateId) =>
threadIntegration.onHumanMessage(currentCompanyId, toAgentId, threadId, waitStateId),
}, {
companyId,
fromAgentId: HUMAN_SENDER_ID,
fromHumanUser: true,
channel: "direct",
toAgentId: engineerId,
threadId: thread.id,
body: "Board left a comment but did not decide approval yet.",
});
waitStates = db.listThreadWaitStates(companyId).filter((entry) => entry.relatedApprovalId === approvalId);
expect(waitStates).toHaveLength(1);
expect(checkpointEngine.shouldPauseHeartbeat(companyId, engineerId)).toBe(true);
db.decideApproval({
approvalId,
state: "approved",
decisionNote: "Approved by board",
});
threadIntegration.onApprovalResolved(approvalId, companyId, "approved");
waitStates = db.listThreadWaitStates(companyId).filter((entry) => entry.relatedApprovalId === approvalId);
expect(waitStates).toHaveLength(0);
expect(checkpointEngine.shouldPauseHeartbeat(companyId, engineerId)).toBe(false);
db.close();
});
});