Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 150 additions & 9 deletions packages/core/src/orchestrator/orchestrator-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ const mockExecuteWorkflow = mock(() => Promise.resolve());
const mockHandleCommand = mock(() =>
Promise.resolve({ success: true, message: 'ok', workflow: undefined })
);
const mockSendQuery = mock(async function* () {
yield { type: 'assistant', content: 'test response' };
yield { type: 'result', sessionId: 'session-1' };
});
const mockGetCodebaseEnvVars = mock(() => Promise.resolve({}));
const mockLoadConfig = mock(() =>
Promise.resolve({
Expand Down Expand Up @@ -104,12 +100,14 @@ mock.module('@archon/workflows/executor', () => ({
executeWorkflow: mockExecuteWorkflow,
}));

const mockSendQuery = mock(async function* () {});
const mockGetAgentProvider = mock(() => ({
sendQuery: mockSendQuery,
getType: mock(() => 'claude'),
getCapabilities: mock(() => ({})),
}));
mock.module('@archon/providers', () => ({
getAgentProvider: mock(() => ({
sendQuery: mockSendQuery,
getType: mock(() => 'claude'),
getCapabilities: mock(() => ({})),
})),
getAgentProvider: mockGetAgentProvider,
getProviderCapabilities: mock(() => ({ envInjection: true })),
}));

Expand Down Expand Up @@ -1566,3 +1564,146 @@ describe('handleMessage — workflow context injection', () => {
await expect(handleMessage(platform, 'conv-1', 'Hello')).resolves.toBeUndefined();
});
});

// ─── AI error result handling (stream + batch) ──────────────────────────────

describe('AI error result handling', () => {
beforeEach(() => {
mockSendQuery.mockReset();
mockGetAgentProvider.mockClear();
mockGetAgentProvider.mockImplementation(() => ({
sendQuery: mockSendQuery,
getType: mock(() => 'claude'),
getCapabilities: mock(() => ({})),
}));
mockGetOrCreateConversation.mockReset();
mockGetCodebase.mockReset();
mockGetOrCreateConversation.mockImplementation(() => Promise.resolve(null));
mockGetCodebase.mockImplementation(() => Promise.resolve(null));
mockLogger.debug.mockClear();
});

describe('stream mode', () => {
function makeStreamPlatform(): IPlatformAdapter {
return {
sendMessage: mock(() => Promise.resolve()),
ensureThread: mock((id: string) => Promise.resolve(id)),
getStreamingMode: mock(() => 'stream' as const),
getPlatformType: mock(() => 'web'),
start: mock(() => Promise.resolve()),
stop: mock(() => {}),
};
}

test('sends error message when result has isError=true and no assistant messages', async () => {
const conversation = makeConversation({ codebase_id: null });
mockGetOrCreateConversation.mockReturnValueOnce(Promise.resolve(conversation));
mockGetPausedWorkflowRun.mockReturnValueOnce(Promise.resolve(null));

mockSendQuery.mockImplementation(async function* () {
yield {
type: 'result',
isError: true,
errorSubtype: 'authentication_error',
};
});

const platform = makeStreamPlatform();
await handleMessage(platform, 'conv-1', 'hello');

expect(platform.sendMessage).toHaveBeenCalledWith(
'conv-1',
'AI error (authentication_error). Check your Claude credentials or use /reset.'
);
});

test('sends generic hint when errorSubtype is not authentication_error', async () => {
const conversation = makeConversation({ codebase_id: null });
mockGetOrCreateConversation.mockReturnValueOnce(Promise.resolve(conversation));
mockGetPausedWorkflowRun.mockReturnValueOnce(Promise.resolve(null));

mockSendQuery.mockImplementation(async function* () {
yield {
type: 'result',
isError: true,
errorSubtype: 'rate_limit',
};
});

const platform = makeStreamPlatform();
await handleMessage(platform, 'conv-1', 'hello');

expect(platform.sendMessage).toHaveBeenCalledWith(
'conv-1',
'AI error (rate_limit). Check server logs for details.'
);
});

test('sends error message without subtype when errorSubtype is undefined', async () => {
const conversation = makeConversation({ codebase_id: null });
mockGetOrCreateConversation.mockReturnValueOnce(Promise.resolve(conversation));
mockGetPausedWorkflowRun.mockReturnValueOnce(Promise.resolve(null));

mockSendQuery.mockImplementation(async function* () {
yield {
type: 'result',
isError: true,
};
});

const platform = makeStreamPlatform();
await handleMessage(platform, 'conv-1', 'hello');

expect(platform.sendMessage).toHaveBeenCalledWith(
'conv-1',
'AI error. Check server logs for details.'
);
});
});

describe('batch mode', () => {
test('sends error message when result has isError=true and no assistant messages', async () => {
const conversation = makeConversation({ codebase_id: null });
mockGetOrCreateConversation.mockReturnValueOnce(Promise.resolve(conversation));
mockGetPausedWorkflowRun.mockReturnValueOnce(Promise.resolve(null));

mockSendQuery.mockImplementation(async function* () {
yield {
type: 'result',
isError: true,
errorSubtype: 'authentication_error',
};
});

const platform = makePlatform(); // batch mode by default
await handleMessage(platform, 'conv-1', 'hello');

expect(platform.sendMessage).toHaveBeenCalledWith(
'conv-1',
'AI error (authentication_error). Check your Claude credentials or use /reset.'
);
});

test('sends generic hint for non-authentication errors', async () => {
const conversation = makeConversation({ codebase_id: null });
mockGetOrCreateConversation.mockReturnValueOnce(Promise.resolve(conversation));
mockGetPausedWorkflowRun.mockReturnValueOnce(Promise.resolve(null));

mockSendQuery.mockImplementation(async function* () {
yield {
type: 'result',
isError: true,
errorSubtype: 'internal_error',
};
});

const platform = makePlatform();
await handleMessage(platform, 'conv-1', 'hello');

expect(platform.sendMessage).toHaveBeenCalledWith(
'conv-1',
'AI error (internal_error). Check server logs for details.'
);
});
});
});
44 changes: 28 additions & 16 deletions packages/core/src/orchestrator/orchestrator-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,7 @@ async function handleStreamMode(
): Promise<void> {
const allMessages: string[] = [];
let newSessionId: string | undefined;
let errorResult: { subtype?: string } | undefined;
let commandDetected = false;

for await (const msg of aiClient.sendQuery(
Expand Down Expand Up @@ -959,13 +960,7 @@ async function handleStreamMode(
newSessionId = msg.sessionId;
}
if (msg.isError) {
getLog().warn({ conversationId, errorSubtype: msg.errorSubtype }, 'ai_result_error');
const syntheticError = new Error(msg.errorSubtype ?? 'AI result error');
await platform.sendMessage(conversationId, classifyAndFormatError(syntheticError));
if (newSessionId) {
await tryPersistSessionId(session.id, newSessionId);
}
return;
errorResult = { subtype: msg.errorSubtype };
}
if (!commandDetected && platform.sendStructuredEvent) {
await platform.sendStructuredEvent(conversationId, msg);
Expand All @@ -978,7 +973,18 @@ async function handleStreamMode(
}

if (allMessages.length === 0) {
getLog().debug({ conversationId }, 'no_ai_response');
if (errorResult) {
const providerLabel = aiClient.getType() === 'claude' ? 'Claude' : 'AI';
const hint =
errorResult.subtype === 'authentication_error'
? `Check your ${providerLabel} credentials or use /reset.`
: 'Check server logs for details.';
await platform.sendMessage(
conversationId,
`AI error${errorResult.subtype ? ` (${errorResult.subtype})` : ''}. ${hint}`
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
getLog().debug({ conversationId, errorResult }, 'no_ai_response');
return;
Comment on lines +987 to 988
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Rename this log event to match the repo convention.

no_ai_response does not follow the {domain}.{action}_{state} format used elsewhere in the project. Please rename both entries to something like orchestrator.ai_response_failed so they stay queryable with the rest of the structured logs.

As per coding guidelines, "Use createLogger('domain') from @archon/paths for structured Pino logging with event naming format {domain}.{action}_{state} and standard states: _started, _completed, _failed, _validated, _rejected".

Also applies to: 1057-1058

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/orchestrator/orchestrator-agent.ts` around lines 906 - 907,
The log event string "no_ai_response" does not follow our
`{domain}.{action}_{state}` convention—update the two log calls that use this
literal (the debug call at getLog().debug({ conversationId, errorResult },
'no_ai_response') and the other instance around lines 1057–1058) to a
domain-prefixed event like "orchestrator.ai_response_failed" so they are
queryable with other structured logs; keep the same metadata object ({
conversationId, errorResult }) and use the existing getLog() logger (created via
createLogger('orchestrator') elsewhere in this module) when replacing the event
name.

}

Expand Down Expand Up @@ -1046,6 +1052,7 @@ async function handleBatchMode(
let assistantChunksTruncated = false;
let totalChunksTruncated = false;
let newSessionId: string | undefined;
let errorResult: { subtype?: string } | undefined;
let commandDetected = false;

for await (const msg of aiClient.sendQuery(
Expand Down Expand Up @@ -1082,13 +1089,7 @@ async function handleBatchMode(
newSessionId = msg.sessionId;
}
if (msg.isError) {
getLog().warn({ conversationId, errorSubtype: msg.errorSubtype }, 'ai_result_error');
const syntheticError = new Error(msg.errorSubtype ?? 'AI result error');
await platform.sendMessage(conversationId, classifyAndFormatError(syntheticError));
if (newSessionId) {
await tryPersistSessionId(session.id, newSessionId);
}
return;
errorResult = { subtype: msg.errorSubtype };
}
}

Expand Down Expand Up @@ -1123,7 +1124,18 @@ async function handleBatchMode(
const finalMessage = filterToolIndicators(assistantMessages);

if (!finalMessage) {
getLog().debug({ conversationId }, 'no_ai_response');
if (errorResult) {
const providerLabel = aiClient.getType() === 'claude' ? 'Claude' : 'AI';
const hint =
errorResult.subtype === 'authentication_error'
? `Check your ${providerLabel} credentials or use /reset.`
: 'Check server logs for details.';
await platform.sendMessage(
conversationId,
`AI error${errorResult.subtype ? ` (${errorResult.subtype})` : ''}. ${hint}`
);
}
getLog().debug({ conversationId, errorResult }, 'no_ai_response');
return;
}

Expand Down
Loading