fix: copy markdown to clipboard and codex error handling (#348)

This commit is contained in:
Carlos Florêncio
2026-03-02 18:37:13 +00:00
committed by GitHub
parent 2dbd0e778c
commit fb50b726df
7 changed files with 266 additions and 11 deletions
@@ -69,14 +69,23 @@ func (m *Manager) handleReasoningEvent(execution *AgentExecution, event agentctl
}
}
// extractErrorMessage returns the best error message from an agent event.
// Priority: Error field > Text field > default message.
func extractErrorMessage(event *agentctl.AgentEvent) string {
if event.Error != "" {
return event.Error
}
if event.Text != "" {
return event.Text
}
return "agent error completion"
}
// handleCompleteEventMarkState marks the execution state after a complete event:
// failed+removed on error, ready on success.
func (m *Manager) handleCompleteEventMarkState(execution *AgentExecution, event *agentctl.AgentEvent, isError bool) {
if isError {
errorMsg := "agent error completion"
if event.Error != "" {
errorMsg = event.Error
}
errorMsg := extractErrorMessage(event)
m.logger.Warn("error completion received, marking execution as failed",
zap.String("execution_id", execution.ID),
zap.String("task_id", execution.TaskID),
@@ -106,10 +115,7 @@ func handleCompleteEventSignal(execution *AgentExecution, event *agentctl.AgentE
errorMsg := ""
if isError {
stopReason = "error"
errorMsg = "agent error completion"
if event.Error != "" {
errorMsg = event.Error
}
errorMsg = extractErrorMessage(event)
} else if event.Data != nil {
// Read StopReason from the complete event (set by ACP adapter from PromptResponse)
if sr, ok := event.Data["stop_reason"].(string); ok && sr != "" {
@@ -713,6 +713,90 @@ func TestHandleAgentEvent_ReasoningWithNewlinesThenToolCall(t *testing.T) {
}
}
// TestExtractErrorMessage verifies the priority chain: Error > Text > default.
func TestExtractErrorMessage(t *testing.T) {
tests := []struct {
name string
event *agentctl.AgentEvent
want string
}{
{
name: "Error field takes priority",
event: &agentctl.AgentEvent{Error: "explicit error", Text: "text fallback"},
want: "explicit error",
},
{
name: "Text field used when Error is empty",
event: &agentctl.AgentEvent{Error: "", Text: "text fallback"},
want: "text fallback",
},
{
name: "default when both empty",
event: &agentctl.AgentEvent{Error: "", Text: ""},
want: "agent error completion",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := extractErrorMessage(tt.event)
if got != tt.want {
t.Errorf("extractErrorMessage() = %q, want %q", got, tt.want)
}
})
}
}
// TestHandleAgentEvent_ErrorCompleteWithTextFallback verifies that when an error
// completion has no Error field but has Text, the Text is used as the error message.
func TestHandleAgentEvent_ErrorCompleteWithTextFallback(t *testing.T) {
mgr, _ := createTestManagerWithTracking()
execution := createTestExecution("exec-1", "task-1", "session-1")
mgr.executionStore.Add(execution)
mgr.handleAgentEvent(execution, agentctl.AgentEvent{
Type: "complete",
Text: "Operation timed out",
Data: map[string]any{"is_error": true},
})
select {
case signal := <-execution.promptDoneCh:
if !signal.IsError {
t.Error("expected error signal")
}
if signal.Error != "Operation timed out" {
t.Errorf("expected error 'Operation timed out', got %q", signal.Error)
}
default:
t.Error("expected signal on promptDoneCh, got none")
}
}
// TestHandleAgentEvent_ErrorCompleteWithDefaultMessage verifies that when both
// Error and Text fields are empty, the default message is used.
func TestHandleAgentEvent_ErrorCompleteWithDefaultMessage(t *testing.T) {
mgr, _ := createTestManagerWithTracking()
execution := createTestExecution("exec-1", "task-1", "session-1")
mgr.executionStore.Add(execution)
mgr.handleAgentEvent(execution, agentctl.AgentEvent{
Type: "complete",
Data: map[string]any{"is_error": true},
})
select {
case signal := <-execution.promptDoneCh:
if !signal.IsError {
t.Error("expected error signal")
}
if signal.Error != "agent error completion" {
t.Errorf("expected default error message, got %q", signal.Error)
}
default:
t.Error("expected signal on promptDoneCh, got none")
}
}
// TestHandleCompleteEventMarkState_ErrorDoesNotRemoveExecution verifies that on error
// completion, the execution is NOT removed from the store. The orchestrator's cleanup
// (StopExecution → StopAgentWithReason) handles full teardown including port release;
@@ -12,6 +12,10 @@ import (
// TIMESTAMP ERROR module: error=HTTP_ERROR: Some("JSON")
var codexErrorRegex = regexp.MustCompile(`error=(.+?):\s*Some\("(.+)"\)\s*$`)
// codexLogErrorRegex matches general Codex ERROR log lines:
// TIMESTAMP ERROR module::submodule: Human-readable error message
var codexLogErrorRegex = regexp.MustCompile(`\S+\s+ERROR\s+\S+:\s+(.+)$`)
// CodexParsedError contains the parsed error information from Codex stderr.
type CodexParsedError struct {
// Message is the user-friendly error message
@@ -126,14 +130,47 @@ func ParseCodexStderrError(line string) *CodexParsedError {
return result
}
// ParseCodexLogError attempts to extract an error message from a general
// Codex ERROR log line (e.g., auth failures). Returns empty string if
// the line doesn't match or contains unhelpful content (JSON fragments).
//
// Example input:
//
// 2026-03-02T16:17:50Z ERROR codex_core::auth: Failed to refresh token: Please log out and sign in again.
func ParseCodexLogError(line string) string {
matches := codexLogErrorRegex.FindStringSubmatch(line)
if len(matches) < 2 {
return ""
}
msg := strings.TrimSpace(matches[1])
// Skip JSON fragments from multi-line error output
if msg == "" || strings.HasPrefix(msg, "{") || strings.HasPrefix(msg, "}") || strings.HasPrefix(msg, "\"") {
return ""
}
// Skip lines that end with '{' (start of multi-line JSON block)
if strings.HasSuffix(msg, "{") {
return ""
}
return msg
}
// ParseCodexStderrLines attempts to parse Codex stderr lines and extract
// error information. Searches from the end (most recent) first.
// First tries the structured error=...Some("...") format, then falls back
// to general ERROR log lines (e.g., auth failures).
// Returns nil if no parseable error is found.
func ParseCodexStderrLines(lines []string) *CodexParsedError {
// First pass: try structured error format (rate limits, API errors)
for i := len(lines) - 1; i >= 0; i-- {
if parsed := ParseCodexStderrError(lines[i]); parsed != nil {
return parsed
}
}
// Second pass: try general ERROR log lines (auth errors, etc.)
for i := len(lines) - 1; i >= 0; i-- {
if msg := ParseCodexLogError(lines[i]); msg != "" {
return &CodexParsedError{Message: msg}
}
}
return nil
}
@@ -228,6 +228,132 @@ func TestParseCodexStderrLines(t *testing.T) {
}
}
func TestParseCodexLogError(t *testing.T) {
tests := []struct {
name string
input string
wantMsg string
}{
{
name: "empty string",
input: "",
wantMsg: "",
},
{
name: "INFO line - no match",
input: "2026-03-02T16:17:50Z INFO codex_core::auth: Starting up",
wantMsg: "",
},
{
name: "DEBUG line - no match",
input: "2026-03-02T16:17:50Z DEBUG codex_core::auth: Debug info",
wantMsg: "",
},
{
name: "auth error - human readable",
input: "2026-03-02T16:17:50.825663Z ERROR codex_core::auth: Failed to refresh token: Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.",
wantMsg: "Failed to refresh token: Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.",
},
{
name: "models manager error",
input: "2026-03-02T16:17:51.031854Z ERROR codex_core::models_manager::manager: failed to refresh available models: unexpected status 401 Unauthorized",
wantMsg: "failed to refresh available models: unexpected status 401 Unauthorized",
},
{
name: "multi-line JSON start - skipped",
input: "2026-03-02T16:17:50.825623Z ERROR codex_core::auth: Failed to refresh token: 401 Unauthorized: {",
wantMsg: "",
},
{
name: "JSON fragment starting with brace - skipped",
input: `2026-03-02T16:17:50Z ERROR codex_core::auth: {"error": "something"}`,
wantMsg: "",
},
{
name: "JSON fragment starting with quote - skipped",
input: `2026-03-02T16:17:50Z ERROR codex_core::auth: "message": "something"`,
wantMsg: "",
},
{
name: "closing brace - skipped",
input: `2026-03-02T16:17:50Z ERROR codex_core::auth: }`,
wantMsg: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := ParseCodexLogError(tt.input)
if result != tt.wantMsg {
t.Errorf("ParseCodexLogError() = %q, want %q", result, tt.wantMsg)
}
})
}
}
func TestParseCodexStderrLines_LogErrorFallback(t *testing.T) {
tests := []struct {
name string
lines []string
wantNil bool
wantMsgContains string
}{
{
name: "auth error lines - falls back to log format",
lines: []string{
"npm warn Unknown env config",
"2026-03-02T16:17:50.825623Z ERROR codex_core::auth: Failed to refresh token: 401 Unauthorized: {",
` "error": {`,
` "message": "Your refresh token has already been used"`,
" }",
"}",
"2026-03-02T16:17:50.825663Z ERROR codex_core::auth: Failed to refresh token: Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.",
},
wantNil: false,
wantMsgContains: "Please log out and sign in again",
},
{
name: "structured error takes priority over log error",
lines: []string{
"2026-03-02T16:17:50Z ERROR codex_core::auth: Some auth error message",
`error=http 429 Too Many Requests: Some("{\"error\":{\"message\":\"Rate limited\"}}")`,
},
wantNil: false,
wantMsgContains: "Rate limited",
},
{
name: "only JSON fragments - no match",
lines: []string{
"2026-03-02T16:17:50Z ERROR codex_core::auth: Failed to refresh token: 401 Unauthorized: {",
` "error": {`,
` "message": "something"`,
" }",
"}",
},
wantNil: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := ParseCodexStderrLines(tt.lines)
if tt.wantNil {
if result != nil {
t.Errorf("expected nil, got %+v", result)
}
return
}
if result == nil {
t.Fatal("expected non-nil result, got nil")
} else if !strings.Contains(result.Message, tt.wantMsgContains) {
t.Errorf("Message = %q, want to contain %q", result.Message, tt.wantMsgContains)
}
})
}
}
func TestParseCodexStderrError_ResetsInSeconds(t *testing.T) {
// Test that ResetsInSeconds is correctly extracted
input := `error=http 429 Too Many Requests: Some("{\"error\":{\"type\":\"usage_limit_reached\",\"resets_in_seconds\":3600}}")`
@@ -220,7 +220,8 @@ function computeFooterState(props: TaskCreateDialogFooterProps) {
const splitDisabled =
isCreatingTask ||
!hasTitle ||
(hasRepositorySelection && !branch) ||
!hasRepositorySelection ||
!branch ||
!agentProfileId ||
missingCtx;
const defaultDisabled = isSessionMode
@@ -123,6 +123,7 @@ export function validateCreateInputs(inputs: {
inputs.trimmedTitle &&
inputs.workspaceId &&
inputs.effectiveWorkflowId &&
inputs.agentProfileId,
inputs.agentProfileId &&
(inputs.repositoryId || inputs.selectedLocalRepo),
);
}
@@ -39,7 +39,7 @@ export function InlineCode({ children }: InlineCodeProps) {
className={cn(
"absolute bottom-full left-1/2 -translate-x-1/2 mb-1",
"px-2 py-1 text-xs text-popover-foreground bg-popover border border-border rounded shadow-md whitespace-nowrap",
"pointer-events-none transition-opacity duration-200",
"pointer-events-none select-none transition-opacity duration-200",
"opacity-0 group-hover/inline-code:opacity-100",
showTooltip && "opacity-100",
)}