Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ export class CallbackNotificationService {
sessionId,
messageId,
success,
...(error != null ? { error } : {}),
timestamp,
context,
};
Expand Down
10 changes: 8 additions & 2 deletions packages/control-plane/src/session/message-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,12 @@ export class SessionMessageQueue {
message_id: processingMessage.id,
});

const stopError = "Execution was stopped";
const syntheticExecutionComplete: Extract<SandboxEvent, { type: "execution_complete" }> = {
type: "execution_complete",
messageId: processingMessage.id,
success: false,
error: stopError,
sandboxId: "",
timestamp: now / 1000,
};
Expand All @@ -251,7 +253,7 @@ export class SessionMessageQueue {
});

this.deps.ctx.waitUntil(
this.deps.callbackService.notifyComplete(processingMessage.id, false)
this.deps.callbackService.notifyComplete(processingMessage.id, false, stopError)
);

if (!options.suppressStatusReconcile) {
Expand Down Expand Up @@ -281,17 +283,21 @@ export class SessionMessageQueue {

this.deps.repository.updateMessageCompletion(processingMessage.id, "failed", now);

const stuckError = "Execution timed out (stuck processing)";
const syntheticEvent: Extract<SandboxEvent, { type: "execution_complete" }> = {
type: "execution_complete",
messageId: processingMessage.id,
success: false,
error: stuckError,
sandboxId: "",
timestamp: now / 1000,
};
this.deps.repository.upsertExecutionCompleteEvent(processingMessage.id, syntheticEvent, now);
this.deps.broadcast({ type: "sandbox_event", event: syntheticEvent });
this.deps.broadcast({ type: "processing_status", isProcessing: false });
this.deps.ctx.waitUntil(this.deps.callbackService.notifyComplete(processingMessage.id, false));
this.deps.ctx.waitUntil(
this.deps.callbackService.notifyComplete(processingMessage.id, false, stuckError)
);
await this.deps.reconcileSessionStatusAfterExecution(false);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/control-plane/src/session/sandbox-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ export class SessionSandboxEventProcessor {
isProcessing: this.deps.getIsProcessing(),
});
this.deps.ctx.waitUntil(
this.deps.callbackService.notifyComplete(completionMessageId, event.success)
this.deps.callbackService.notifyComplete(completionMessageId, event.success, event.error)
);

await this.deps.reconcileSessionStatusAfterExecution(event.success);
Expand Down
1 change: 1 addition & 0 deletions packages/linear-bot/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export interface CompletionCallback {
sessionId: string;
messageId: string;
success: boolean;
error?: string;
timestamp: number;
signature: string;
context: LinearCallbackContext;
Expand Down
20 changes: 10 additions & 10 deletions packages/sandbox-runtime/src/sandbox_runtime/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,19 +604,19 @@ async def _handle_prompt(self, cmd: dict[str, Any]) -> None:
reasoning_effort=reasoning_effort,
)

scm_name = author_data.get("scmName")
scm_email = author_data.get("scmEmail")
await self._configure_git_identity(
GitUser(
name=scm_name or FALLBACK_GIT_USER.name,
email=scm_email or FALLBACK_GIT_USER.email,
try:
scm_name = author_data.get("scmName")
scm_email = author_data.get("scmEmail")
await self._configure_git_identity(
GitUser(
name=scm_name or FALLBACK_GIT_USER.name,
email=scm_email or FALLBACK_GIT_USER.email,
)
)
)

if not self.opencode_session_id:
await self._create_opencode_session()
if not self.opencode_session_id:
await self._create_opencode_session()

try:
had_error = False
error_message = None
async for event in self._stream_opencode_response_sse(
Expand Down
9 changes: 8 additions & 1 deletion packages/shared/src/completion/extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,13 @@ export async function extractAgentResponse(
const artifacts = await fetchSessionArtifacts(deps, sessionId, headers, base);
const finalArtifacts = artifacts.length > 0 ? artifacts : eventArtifacts;

// Check for completion event to get success status
// Check for completion event to get success status and error message.
// The error may be on execution_complete itself, or on a separate "error" event.
const completionEvent = allEvents.find((e) => e.type === "execution_complete");
const errorEvent = allEvents.find((e) => e.type === "error");
const errorMessage =
(completionEvent?.data.error != null ? String(completionEvent.data.error) : undefined) ??
(errorEvent?.data.error != null ? String(errorEvent.data.error) : undefined);

log.info("control_plane.fetch_events", {
...base,
Expand All @@ -147,6 +152,7 @@ export async function extractAgentResponse(
tool_call_count: toolCalls.length,
artifact_count: finalArtifacts.length,
has_text: Boolean(textContent),
has_error: Boolean(errorMessage),
duration_ms: Date.now() - startTime,
});

Expand All @@ -155,6 +161,7 @@ export async function extractAgentResponse(
toolCalls,
artifacts: finalArtifacts,
success: Boolean(completionEvent?.data.success),
error: errorMessage,
};
} catch (error) {
log.error("control_plane.fetch_events", {
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ export interface AgentResponse {
toolCalls: ToolCallSummary[];
artifacts: ArtifactInfo[];
success: boolean;
error?: string;
}

export interface UserPreferences {
Expand Down
57 changes: 29 additions & 28 deletions packages/slack-bot/src/callbacks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { computeHmacHex, timingSafeEqual } from "@open-inspect/shared";
import { Hono } from "hono";
import type { Env, CompletionCallback } from "./types";
import { extractAgentResponse } from "./completion/extractor";
import { buildCompletionBlocks, getFallbackText } from "./completion/blocks";
import { buildCompletionBlocks, getFallbackText, truncateError } from "./completion/blocks";
import { postMessage, removeReaction } from "./utils/slack-client";
import { createLogger } from "./logger";

Expand Down Expand Up @@ -159,42 +159,43 @@ async function handleCompletionCallback(
// Fetch events to build response (filtered by messageId directly)
const agentResponse = await extractAgentResponse(env, sessionId, payload.messageId, traceId);

// Fall back to the callback payload's error if the extractor didn't find one.
agentResponse.error = agentResponse.error || payload.error;
const errorMessage = agentResponse.error;

// Check if extraction succeeded (has content or was explicitly successful)
if (!agentResponse.textContent && agentResponse.toolCalls.length === 0 && !payload.success) {
const displayError = truncateError(errorMessage || "Unknown error", 2000);
log.error("callback.complete", {
...base,
outcome: "error",
error_message: "empty_agent_response",
agent_error: errorMessage || "Unknown error",
duration_ms: Date.now() - startTime,
});
await postMessage(
env.SLACK_BOT_TOKEN,
context.channel,
"The agent completed but I couldn't retrieve the response. Please check the web UI for details.",
{
thread_ts: context.threadTs,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: ":warning: The agent completed but I couldn't retrieve the response.",
},
},
{
type: "actions",
elements: [
{
type: "button",
text: { type: "plain_text", text: "View Session" },
url: `${env.WEB_APP_URL}/session/${sessionId}`,
action_id: "view_session",
},
],
await postMessage(env.SLACK_BOT_TOKEN, context.channel, `The agent failed: ${displayError}`, {
thread_ts: context.threadTs,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: `:x: *Agent failed:* ${displayError}`,
},
],
}
);
},
{
type: "actions",
elements: [
{
type: "button",
text: { type: "plain_text", text: "View Session" },
url: `${env.WEB_APP_URL}/session/${sessionId}`,
action_id: "view_session",
},
],
},
],
});

if (context.reactionMessageTs) {
await clearThinkingReaction(env, context.channel, context.reactionMessageTs, traceId);
Expand Down
16 changes: 15 additions & 1 deletion packages/slack-bot/src/completion/blocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const STATUS_EMOJI = {
*/
const TRUNCATE_LIMIT = 2000;
const FALLBACK_TEXT_LIMIT = 150;
const ERROR_FOOTER_LIMIT = 200;

/**
* Build Slack blocks for completion message.
Expand Down Expand Up @@ -71,7 +72,11 @@ export function buildCompletionBlocks(

// 4. Status footer
const emoji = response.success ? STATUS_EMOJI.success : STATUS_EMOJI.warning;
const status = response.success ? "Done" : "Completed with issues";
const status = response.success
? "Done"
: response.error
? `Failed: ${truncateError(response.error, ERROR_FOOTER_LIMIT)}`
: "Completed with issues";
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const effortSuffix = context.reasoningEffort ? ` (${context.reasoningEffort})` : "";
blocks.push({
type: "context",
Expand Down Expand Up @@ -137,6 +142,15 @@ function truncateForSlack(text: string, maxLen: number): string {
return truncated + "...\n\n_...truncated_";
}

/**
* Truncate an error string for Slack display, collapsing whitespace.
*/
export function truncateError(text: string, maxLen: number): string {
const normalized = text.replace(/\s+/g, " ").trim();
if (normalized.length <= maxLen) return normalized;
return normalized.slice(0, maxLen - 1) + "…";
}

function getManualCreatePrUrl(artifacts: AgentResponse["artifacts"]): string | null {
const manualBranchArtifact = artifacts.find((artifact) => {
if (artifact.type !== "branch") {
Expand Down
1 change: 1 addition & 0 deletions packages/slack-bot/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export interface CompletionCallback {
sessionId: string;
messageId: string;
success: boolean;
error?: string;
timestamp: number;
signature: string;
context: SlackCallbackContext;
Expand Down
Loading