Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
test: add tests for cosRunnerClient.js and agentActionExecutor.js
Adam Eivy96929bb2f9fe
diff --git a/PLAN.md b/PLAN.mdindex ab71277025..ad9c7728f2 100644--- a/PLAN.md+++ b/PLAN.md@@ -10,7 +10,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]## Backlog-- [ ] **Test coverage** — Critical gaps: cos.js, cosRunnerClient.js, agentActionExecutor.js (~29% service, ~12% route coverage)+- [ ] **Test coverage** — cosRunnerClient.js ✅ (37 tests), agentActionExecutor.js ✅ (27 tests). Remaining gap: cos.js (~29% service, ~12% route coverage)- [ ] **M50 P9**: CoS Automation & Rules — Automated email classification, rule-based pre-filtering, email-to-task pipeline- [ ] **M50 P10**: Auto-Send with AI Review Gate — Per-account trust level, second LLM reviews drafts. See [Messages Security](./docs/features/messages-security.md)- [ ] **M34 P5-P7**: Digital Twin — Multi-modal capture, advanced testing, personasdiff --git a/server/services/agentActionExecutor.test.js b/server/services/agentActionExecutor.test.jsnew file mode 100644index 0000000000..49af28a4b5--- /dev/null+++ b/server/services/agentActionExecutor.test.js@@ -0,0 +1,616 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const { mockScheduleEvents, mockMoltbookClient, mockMoltworldClient } = vi.hoisted(() => {+ const { EventEmitter } = require('events');+ return {+ mockScheduleEvents: new EventEmitter(),+ mockMoltbookClient: {+ heartbeat: vi.fn(),+ createPost: vi.fn(),+ getPost: vi.fn(),+ getComments: vi.fn(),+ createComment: vi.fn(),+ replyToComment: vi.fn(),+ upvote: vi.fn(),+ downvote: vi.fn(),+ upvoteComment: vi.fn(),+ getFeed: vi.fn(),+ getPostsByAuthor: vi.fn()+ },+ mockMoltworldClient: {+ joinWorld: vi.fn(),+ build: vi.fn(),+ think: vi.fn()+ }+ };+});++vi.mock('./automationScheduler.js', () => ({+ scheduleEvents: mockScheduleEvents+}));++vi.mock('./agentActivity.js', () => ({+ logActivity: vi.fn().mockResolvedValue(undefined)+}));++vi.mock('./platformAccounts.js', () => ({+ getAccountWithCredentials: vi.fn(),+ recordActivity: vi.fn().mockResolvedValue(undefined),+ updateAccountStatus: vi.fn().mockResolvedValue(undefined)+}));++vi.mock('./agentPersonalities.js', () => ({+ getAgentById: vi.fn()+}));++vi.mock('../integrations/moltbook/index.js', () => ({+ MoltbookClient: vi.fn(function () { return mockMoltbookClient; }),+ checkRateLimit: vi.fn(() => ({ allowed: true })),+ isAccountSuspended: vi.fn(() => false)+}));++vi.mock('../integrations/moltworld/index.js', () => ({+ MoltworldClient: vi.fn(function () { return mockMoltworldClient; })+}));++vi.mock('./agentContentGenerator.js', () => ({+ generatePost: vi.fn().mockResolvedValue({ title: 'AI Title', content: 'AI Content' }),+ generateComment: vi.fn().mockResolvedValue({ content: 'AI Comment' }),+ generateReply: vi.fn().mockResolvedValue({ content: 'AI Reply' })+}));++vi.mock('./agentFeedFilter.js', () => ({+ findRelevantPosts: vi.fn().mockResolvedValue([]),+ findReplyOpportunities: vi.fn().mockResolvedValue([])+}));++import * as agentActivity from './agentActivity.js';+import * as platformAccounts from './platformAccounts.js';+import * as agentPersonalities from './agentPersonalities.js';+import { MoltbookClient, checkRateLimit, isAccountSuspended } from '../integrations/moltbook/index.js';+import { MoltworldClient } from '../integrations/moltworld/index.js';+import { generatePost, generateComment, generateReply } from './agentContentGenerator.js';+import { findRelevantPosts, findReplyOpportunities } from './agentFeedFilter.js';+import { init } from './agentActionExecutor.js';++const makeSchedule = (actionType, params = {}) => ({+ agentId: 'agent-1',+ accountId: 'acc-1',+ action: { type: actionType, params }+});++const makeAccount = (platform = 'moltbook') => ({+ id: 'acc-1',+ platform,+ status: 'active',+ credentials: { apiKey: 'test-key', username: 'testuser', agentId: 'mw-agent-1' }+});++const makeAgent = (overrides = {}) => ({+ id: 'agent-1',+ name: 'TestBot',+ enabled: true,+ aiConfig: { content: { providerId: 'p1', model: 'm1' }, engagement: { providerId: 'p1', model: 'm1' } },+ ...overrides+});++describe('agentActionExecutor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockScheduleEvents.removeAllListeners();+ init();+ });++ afterEach(() => {+ mockScheduleEvents.removeAllListeners();+ });++ // ===========================================================================+ // init() event handler — account/agent validation+ // ===========================================================================+ describe('init — execute event handler', () => {+ it('should log failure when account not found', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(null);++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat'),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'failed',+ error: 'Account not found'+ })+ );+ });+ });++ it('should skip when account is not active', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue({ ...makeAccount(), status: 'suspended' });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat'),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'skipped',+ error: 'Account status: suspended'+ })+ );+ });+ });++ it('should skip when agent not found', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(null);++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat'),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentPersonalities.getAgentById).toHaveBeenCalledWith('agent-1');+ });+ });++ it('should skip when agent is disabled', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent({ enabled: false }));++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat'),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'skipped',+ error: 'Agent disabled'+ })+ );+ });+ });++ it('should execute action and log completion on success', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ mockMoltbookClient.heartbeat.mockResolvedValue({ browsed: 5 });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat', { engageChance: 0.5 }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'completed',+ action: 'heartbeat'+ })+ );+ });+ expect(platformAccounts.recordActivity).toHaveBeenCalledWith('acc-1');+ });++ it('should log failure when action throws', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ mockMoltbookClient.heartbeat.mockRejectedValue(new Error('API down'));++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat'),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'failed',+ error: 'API down'+ })+ );+ });+ });+ });++ describe('heartbeat action', () => {+ beforeEach(() => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ });++ it('should call client.heartbeat with params', async () => {+ mockMoltbookClient.heartbeat.mockResolvedValue({ browsed: 3, engaged: 1 });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat', { engageChance: 0.5, maxEngagements: 2 }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.heartbeat).toHaveBeenCalledWith({+ engageChance: 0.5,+ maxEngagements: 2+ });+ });+ });++ it('should use default params when none provided', async () => {+ mockMoltbookClient.heartbeat.mockResolvedValue({ browsed: 1 });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('heartbeat', {}),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.heartbeat).toHaveBeenCalledWith({+ engageChance: 0.3,+ maxEngagements: 3+ });+ });+ });+ });++ describe('post action', () => {+ beforeEach(() => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ });++ it('should create post with provided title and content', async () => {+ mockMoltbookClient.createPost.mockResolvedValue({ post: { id: 'p1' } });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('post', { submolt: 'tech', title: 'My Title', content: 'My Content' }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.createPost).toHaveBeenCalledWith('tech', 'My Title', 'My Content');+ });+ expect(generatePost).not.toHaveBeenCalled();+ });++ it('should AI-generate content when title/content missing', async () => {+ mockMoltbookClient.createPost.mockResolvedValue({ post: { id: 'p2' } });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('post', { submolt: 'general' }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(generatePost).toHaveBeenCalled();+ expect(mockMoltbookClient.createPost).toHaveBeenCalledWith('general', 'AI Title', 'AI Content');+ });+ });++ it('should throw when no content and aiGenerate is false', async () => {+ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('post', { aiGenerate: false }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'failed',+ error: expect.stringContaining('requires title and content')+ })+ );+ });+ });+ });++ describe('vote action', () => {+ beforeEach(() => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ });++ it('should upvote a specific post', async () => {+ mockMoltbookClient.upvote.mockResolvedValue({});++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('vote', { postId: 'p1', direction: 'up' }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.upvote).toHaveBeenCalledWith('p1');+ });+ });++ it('should downvote when direction is down', async () => {+ mockMoltbookClient.downvote.mockResolvedValue({});++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('vote', { postId: 'p1', direction: 'down' }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.downvote).toHaveBeenCalledWith('p1');+ });+ });++ it('should upvote comment when commentId provided', async () => {+ mockMoltbookClient.upvoteComment.mockResolvedValue({});++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('vote', { commentId: 'c1' }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.upvoteComment).toHaveBeenCalledWith('c1');+ });+ });++ it('should pick random post from feed when no target specified', async () => {+ mockMoltbookClient.getFeed.mockResolvedValue({ posts: [{ id: 'p1', title: 'Post 1' }] });+ mockMoltbookClient.upvote.mockResolvedValue({});++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('vote', {}),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltbookClient.getFeed).toHaveBeenCalledWith('hot', 10);+ expect(mockMoltbookClient.upvote).toHaveBeenCalledWith('p1');+ });+ });++ it('should return none when feed is empty', async () => {+ mockMoltbookClient.getFeed.mockResolvedValue({ posts: [] });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('vote', {}),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'completed',+ result: expect.objectContaining({ action: 'none', reason: 'no posts in feed' })+ })+ );+ });+ });+ });++ describe('comment action', () => {+ beforeEach(() => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ });++ it('should find relevant post and AI-generate comment when no postId', async () => {+ findReplyOpportunities.mockResolvedValue([+ { post: { id: 'p1', title: 'Test' }, comments: [], reason: 'relevant' }+ ]);+ mockMoltbookClient.createComment.mockResolvedValue({ id: 'c1' });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('comment', {}),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(findReplyOpportunities).toHaveBeenCalled();+ expect(generateComment).toHaveBeenCalled();+ expect(mockMoltbookClient.createComment).toHaveBeenCalledWith('p1', 'AI Comment');+ });+ });++ it('should return none when no relevant posts found', async () => {+ findReplyOpportunities.mockResolvedValue([]);++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('comment', {}),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'completed',+ result: expect.objectContaining({ action: 'none', reason: 'no relevant posts found' })+ })+ );+ });+ });++ it('should reply to parent comment when parentId provided', async () => {+ mockMoltbookClient.getPost.mockResolvedValue({ id: 'p1', title: 'Post' });+ mockMoltbookClient.getComments.mockResolvedValue({ comments: [{ id: 'parent-1', content: 'Parent' }] });+ mockMoltbookClient.replyToComment.mockResolvedValue({ id: 'c2' });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('comment', { postId: 'p1', parentId: 'parent-1' }),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(generateReply).toHaveBeenCalled();+ expect(mockMoltbookClient.replyToComment).toHaveBeenCalledWith('p1', 'parent-1', 'AI Reply');+ });+ });+ });++ describe('unknown action type', () => {+ it('should fail with unknown action error', async () => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(makeAccount());+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: makeSchedule('invalid_action'),+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'failed',+ error: 'Unknown action type: invalid_action'+ })+ );+ });+ });+ });++ describe('moltworld actions', () => {+ const mwAccount = makeAccount('moltworld');++ beforeEach(() => {+ platformAccounts.getAccountWithCredentials.mockResolvedValue(mwAccount);+ agentPersonalities.getAgentById.mockResolvedValue(makeAgent());+ });++ it('should execute mw_heartbeat', async () => {+ mockMoltworldClient.joinWorld.mockResolvedValue({ nearby: [{ name: 'bot2' }] });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_heartbeat', { x: 10, y: 20 }), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltworldClient.joinWorld).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'testuser', x: 10, y: 20 })+ );+ });+ });++ it('should execute mw_build', async () => {+ mockMoltworldClient.build.mockResolvedValue({ built: true });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_build', { x: 5, y: 5, z: 1, type: 'wood' }), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltworldClient.build).toHaveBeenCalledWith(+ expect.objectContaining({ x: 5, y: 5, z: 1, type: 'wood', action: 'place' })+ );+ });+ });++ it('should execute mw_say', async () => {+ mockMoltworldClient.joinWorld.mockResolvedValue({ nearby: [] });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_say', { message: 'Hello world', name: 'Bot' }), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltworldClient.joinWorld).toHaveBeenCalledWith(+ expect.objectContaining({ say: 'Hello world', name: 'Bot' })+ );+ });+ });++ it('should execute mw_think', async () => {+ mockMoltworldClient.think.mockResolvedValue({});++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_think', { thought: 'Deep thoughts' }), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltworldClient.think).toHaveBeenCalledWith('Deep thoughts');+ });+ });++ it('should execute mw_explore with random coords when none provided', async () => {+ mockMoltworldClient.joinWorld.mockResolvedValue({ nearby: [] });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_explore', {}), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(mockMoltworldClient.joinWorld).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'testuser',+ thinking: expect.any(String)+ })+ );+ });+ });++ it('should fail for unknown moltworld action', async () => {+ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_unknown', {}), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ await vi.waitFor(() => {+ expect(agentActivity.logActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ status: 'failed',+ error: 'Unknown Moltworld action type: mw_unknown'+ })+ );+ });+ });++ it('should execute mw_interact with build when buildType provided', async () => {+ mockMoltworldClient.joinWorld.mockResolvedValue({ nearby: [] });+ mockMoltworldClient.build.mockResolvedValue({ built: true });++ mockScheduleEvents.emit('execute', {+ scheduleId: 's1',+ schedule: { ...makeSchedule('mw_interact', { x: 1, y: 2, buildType: 'stone', thinking: 'Building...' }), accountId: 'acc-1', agentId: 'agent-1' },+ timestamp: new Date().toISOString()+ });++ // mw_interact has a 1.5s delay before build, so increase timeout+ await vi.waitFor(() => {+ expect(mockMoltworldClient.joinWorld).toHaveBeenCalled();+ expect(mockMoltworldClient.build).toHaveBeenCalledWith(+ expect.objectContaining({ x: 1, y: 2, type: 'stone', action: 'place' })+ );+ }, { timeout: 3000 });+ });+ });+});diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsnew file mode 100644index 0000000000..48c03b2c68--- /dev/null+++ b/server/services/cosRunnerClient.test.js@@ -0,0 +1,460 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock dependencies before importing+vi.mock('socket.io-client', () => ({+ io: vi.fn(() => ({+ on: vi.fn(),+ emit: vi.fn(),+ disconnect: vi.fn()+ }))+}));++vi.mock('../lib/fetchWithTimeout.js', () => ({+ fetchWithTimeout: vi.fn()+}));++import { io } from 'socket.io-client';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import {+ initCosRunnerConnection,+ onCosRunnerEvent,+ isRunnerAvailable,+ getRunnerHealth,+ spawnAgentViaRunner,+ getActiveAgentsFromRunner,+ terminateAgentViaRunner,+ killAgentViaRunner,+ getAgentStatsFromRunner,+ terminateAllAgentsViaRunner,+ sendBtwToAgent,+ getAgentOutputFromRunner,+ executeCliRunViaRunner,+ getActiveRunsFromRunner,+ isRunActiveInRunner,+ getRunOutputFromRunner,+ stopRunViaRunner+} from './cosRunnerClient.js';++const mockResponse = (ok, data) => ({+ ok,+ json: vi.fn().mockResolvedValue(data)+});++describe('cosRunnerClient', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // ===========================================================================+ // initCosRunnerConnection+ // ===========================================================================+ describe('initCosRunnerConnection', () => {+ it('should create a socket connection with correct options', () => {+ initCosRunnerConnection();+ expect(io).toHaveBeenCalledWith(+ expect.stringContaining('5558'),+ expect.objectContaining({+ reconnection: true,+ reconnectionAttempts: 10,+ reconnectionDelay: 1000+ })+ );+ });+ });++ // ===========================================================================+ // onCosRunnerEvent+ // ===========================================================================+ describe('onCosRunnerEvent', () => {+ it('should register event handlers', () => {+ const handler = vi.fn();+ onCosRunnerEvent('agent:output', handler);+ // No assertion on internal map, just verify no throw+ expect(handler).not.toHaveBeenCalled();+ });+ });++ // ===========================================================================+ // isRunnerAvailable+ // ===========================================================================+ describe('isRunnerAvailable', () => {+ it('should return true when health endpoint returns ok', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { status: 'ok' }));+ const result = await isRunnerAvailable();+ expect(result).toBe(true);+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/health'),+ {},+ 10000+ );+ });++ it('should return false when health endpoint returns not ok', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ const result = await isRunnerAvailable();+ expect(result).toBe(false);+ });++ it('should return false when fetch throws', async () => {+ fetchWithTimeout.mockRejectedValue(new Error('Connection refused'));+ const result = await isRunnerAvailable();+ expect(result).toBe(false);+ });+ });++ // ===========================================================================+ // getRunnerHealth+ // ===========================================================================+ describe('getRunnerHealth', () => {+ it('should return health data when runner is available', async () => {+ const healthData = { agents: 3, uptime: 1234 };+ fetchWithTimeout.mockResolvedValue(mockResponse(true, healthData));+ const result = await getRunnerHealth();+ expect(result).toEqual({ available: true, agents: 3, uptime: 1234 });+ });++ it('should return unavailable when response is not ok', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ const result = await getRunnerHealth();+ expect(result).toEqual({ available: false, error: 'Runner not available' });+ });++ it('should return unavailable when fetch throws', async () => {+ fetchWithTimeout.mockRejectedValue(new Error('timeout'));+ const result = await getRunnerHealth();+ expect(result).toEqual({ available: false, error: 'Runner not available' });+ });+ });++ // ===========================================================================+ // spawnAgentViaRunner+ // ===========================================================================+ describe('spawnAgentViaRunner', () => {+ it('should POST spawn request and return result', async () => {+ const spawnResult = { agentId: 'a1', pid: 1234 };+ fetchWithTimeout.mockResolvedValue(mockResponse(true, spawnResult));++ const result = await spawnAgentViaRunner({+ agentId: 'a1',+ taskId: 't1',+ prompt: 'do something',+ workspacePath: '/tmp/ws',+ model: 'opus'+ });++ expect(result).toEqual(spawnResult);+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/spawn'),+ expect.objectContaining({+ method: 'POST',+ headers: { 'Content-Type': 'application/json' }+ }),+ 60000+ );++ // Verify body contains expected fields+ const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);+ expect(callBody.agentId).toBe('a1');+ expect(callBody.taskId).toBe('t1');+ expect(callBody.prompt).toBe('do something');+ expect(callBody.workspacePath).toBe('/tmp/ws');+ expect(callBody.model).toBe('opus');+ });++ it('should throw on non-ok response', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'No capacity' }));+ await expect(spawnAgentViaRunner({ agentId: 'a1' }))+ .rejects.toThrow('No capacity');+ });++ it('should use fallback error message when response has no error field', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ await expect(spawnAgentViaRunner({ agentId: 'a1' }))+ .rejects.toThrow('Failed to spawn agent');+ });++ it('should pass cliCommand and cliArgs when provided', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { agentId: 'a1' }));+ await spawnAgentViaRunner({+ agentId: 'a1',+ cliCommand: 'claude',+ cliArgs: ['--model', 'opus']+ });++ const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);+ expect(callBody.cliCommand).toBe('claude');+ expect(callBody.cliArgs).toEqual(['--model', 'opus']);+ });+ });++ // ===========================================================================+ // getActiveAgentsFromRunner+ // ===========================================================================+ describe('getActiveAgentsFromRunner', () => {+ it('should return agents list', async () => {+ const agents = [{ id: 'a1' }, { id: 'a2' }];+ fetchWithTimeout.mockResolvedValue(mockResponse(true, agents));+ const result = await getActiveAgentsFromRunner();+ expect(result).toEqual(agents);+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/agents'),+ {},+ 10000+ );+ });++ it('should throw on non-ok response', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ await expect(getActiveAgentsFromRunner()).rejects.toThrow('Failed to get agents');+ });+ });++ // ===========================================================================+ // terminateAgentViaRunner+ // ===========================================================================+ describe('terminateAgentViaRunner', () => {+ it('should POST terminate and return result', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { terminated: true }));+ const result = await terminateAgentViaRunner('agent-123');+ expect(result).toEqual({ terminated: true });+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/terminate/agent-123'),+ { method: 'POST' },+ 30000+ );+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Not found' }));+ await expect(terminateAgentViaRunner('bad-id')).rejects.toThrow('Not found');+ });+ });++ // ===========================================================================+ // killAgentViaRunner+ // ===========================================================================+ describe('killAgentViaRunner', () => {+ it('should POST kill and return result', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { killed: true }));+ const result = await killAgentViaRunner('agent-123');+ expect(result).toEqual({ killed: true });+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/kill/agent-123'),+ { method: 'POST' },+ 30000+ );+ });++ it('should throw with fallback message on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ await expect(killAgentViaRunner('bad-id')).rejects.toThrow('Failed to kill agent');+ });+ });++ // ===========================================================================+ // getAgentStatsFromRunner+ // ===========================================================================+ describe('getAgentStatsFromRunner', () => {+ it('should return stats for an agent', async () => {+ const stats = { cpu: 5.2, memory: 128000 };+ fetchWithTimeout.mockResolvedValue(mockResponse(true, stats));+ const result = await getAgentStatsFromRunner('agent-1');+ expect(result).toEqual(stats);+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/agents/agent-1/stats'),+ {},+ 10000+ );+ });++ it('should return null on non-ok response', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ const result = await getAgentStatsFromRunner('agent-1');+ expect(result).toBeNull();+ });+ });++ // ===========================================================================+ // terminateAllAgentsViaRunner+ // ===========================================================================+ describe('terminateAllAgentsViaRunner', () => {+ it('should POST terminate-all and return result', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { terminated: 3 }));+ const result = await terminateAllAgentsViaRunner();+ expect(result).toEqual({ terminated: 3 });+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/terminate-all'),+ { method: 'POST' },+ 30000+ );+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ await expect(terminateAllAgentsViaRunner()).rejects.toThrow('Failed to terminate agents');+ });+ });++ // ===========================================================================+ // sendBtwToAgent+ // ===========================================================================+ describe('sendBtwToAgent', () => {+ it('should POST BTW message and return result', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { sent: true }));+ const result = await sendBtwToAgent('agent-1', 'Hey, check this out');+ expect(result).toEqual({ sent: true });+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/btw/agent-1'),+ expect.objectContaining({+ method: 'POST',+ headers: { 'Content-Type': 'application/json' }+ }),+ 30000+ );++ const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);+ expect(callBody.message).toBe('Hey, check this out');+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Agent not running' }));+ await expect(sendBtwToAgent('bad-id', 'msg')).rejects.toThrow('Agent not running');+ });+ });++ // ===========================================================================+ // getAgentOutputFromRunner+ // ===========================================================================+ describe('getAgentOutputFromRunner', () => {+ it('should return agent output', async () => {+ const output = { output: 'Hello world', lines: 10 };+ fetchWithTimeout.mockResolvedValue(mockResponse(true, output));+ const result = await getAgentOutputFromRunner('agent-1');+ expect(result).toEqual(output);+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/agents/agent-1/output'),+ {},+ 10000+ );+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Not found' }));+ await expect(getAgentOutputFromRunner('bad-id')).rejects.toThrow('Not found');+ });+ });++ // ===========================================================================+ // executeCliRunViaRunner+ // ===========================================================================+ describe('executeCliRunViaRunner', () => {+ it('should POST run request and return result', async () => {+ const runResult = { runId: 'r1', started: true };+ fetchWithTimeout.mockResolvedValue(mockResponse(true, runResult));++ const result = await executeCliRunViaRunner({+ runId: 'r1',+ command: 'npm',+ args: ['test'],+ prompt: 'run tests',+ workspacePath: '/tmp/ws',+ timeout: 30000+ });++ expect(result).toEqual(runResult);+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/run'),+ expect.objectContaining({ method: 'POST' }),+ 60000+ );++ const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);+ expect(callBody.runId).toBe('r1');+ expect(callBody.command).toBe('npm');+ expect(callBody.args).toEqual(['test']);+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'No slots' }));+ await expect(executeCliRunViaRunner({ runId: 'r1' })).rejects.toThrow('No slots');+ });+ });++ // ===========================================================================+ // getActiveRunsFromRunner+ // ===========================================================================+ describe('getActiveRunsFromRunner', () => {+ it('should return active runs', async () => {+ const runs = [{ id: 'r1' }, { id: 'r2' }];+ fetchWithTimeout.mockResolvedValue(mockResponse(true, runs));+ const result = await getActiveRunsFromRunner();+ expect(result).toEqual(runs);+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ await expect(getActiveRunsFromRunner()).rejects.toThrow('Failed to get runs');+ });+ });++ // ===========================================================================+ // isRunActiveInRunner+ // ===========================================================================+ describe('isRunActiveInRunner', () => {+ it('should return true when run is active', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { active: true }));+ const result = await isRunActiveInRunner('r1');+ expect(result).toBe(true);+ });++ it('should return false when run is not active', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { active: false }));+ const result = await isRunActiveInRunner('r1');+ expect(result).toBe(false);+ });++ it('should return false on non-ok response', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ const result = await isRunActiveInRunner('r1');+ expect(result).toBe(false);+ });+ });++ // ===========================================================================+ // getRunOutputFromRunner+ // ===========================================================================+ describe('getRunOutputFromRunner', () => {+ it('should return run output', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { output: 'test passed' }));+ const result = await getRunOutputFromRunner('r1');+ expect(result).toBe('test passed');+ });++ it('should return null on non-ok response', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));+ const result = await getRunOutputFromRunner('r1');+ expect(result).toBeNull();+ });+ });++ // ===========================================================================+ // stopRunViaRunner+ // ===========================================================================+ describe('stopRunViaRunner', () => {+ it('should POST stop and return result', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(true, { stopped: true }));+ const result = await stopRunViaRunner('r1');+ expect(result).toEqual({ stopped: true });+ expect(fetchWithTimeout).toHaveBeenCalledWith(+ expect.stringContaining('/runs/r1/stop'),+ { method: 'POST' },+ 30000+ );+ });++ it('should throw on failure', async () => {+ fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Not running' }));+ await expect(stopRunViaRunner('r1')).rejects.toThrow('Not running');+ });+ });+});