Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(chat): 补齐任务执行错误详情与诊断入口

nanaf00abec043e4
diff --git a/apps/desktop/scripts/fixtures/task-execution-errors/task-execution-errors-fixture.tsx b/apps/desktop/scripts/fixtures/task-execution-errors/task-execution-errors-fixture.tsx
new file mode 100644
index 0000000000..2cca0952ce
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/task-execution-errors/task-execution-errors-fixture.tsx
@@ -0,0 +1,27 @@
+import { useState } from 'react';
+import { ErrorMessageCard } from '../../../src/renderer/components/chat/ErrorMessageCard';
+import { UnreadFailedScheduleBanner } from '../../../src/renderer/components/chat/UnreadFailedScheduleBanner';
+import { SubagentErrorNotice } from '../../../src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome';
+import { mountPage } from '../../ui-page/harness';
+
+const error = 'queued heartbeat Codex thread provider identity does not match the current session route; api_key=private-fixture-value';
+
+function Fixture({ kind }: { kind: string }) {
+ const [count, setCount] = useState(0);
+ const onDiagnose = () => setCount((value) => value + 1);
+ return (
+ <div className="p-4" data-diagnosis-count={count}>
+ {kind === 'history' ? (
+ <ErrorMessageCard message={error} onDiagnose={onDiagnose} />
+ ) : kind === 'subagent' ? (
+ <SubagentErrorNotice rawError={error} onDiagnose={onDiagnose} />
+ ) : (
+ <UnreadFailedScheduleBanner dataOwnerId="fixture-owner" sessionId="fixture-task"
+ latestFailedRun={{ runId: 'fixture-run', firedAt: 1, errorMsg: error }}
+ onDiagnose={onDiagnose} />
+ )}
+ </div>
+ );
+}
+
+void mountPage({ render: (ctx) => <Fixture kind={ctx.case} /> });
diff --git a/apps/desktop/scripts/fixtures/task-execution-errors/ui-page.mjs b/apps/desktop/scripts/fixtures/task-execution-errors/ui-page.mjs
new file mode 100644
index 0000000000..29f1e0d0ab
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/task-execution-errors/ui-page.mjs
@@ -0,0 +1,26 @@
+import assert from 'node:assert/strict';
+
+export default {
+ name: 'task-execution-errors',
+ entry: './task-execution-errors-fixture.tsx',
+ viewport: { width: 560, height: 440 },
+ real: 'Failed automation banner, historical error card, subagent error notice, ErrorNotice, localized details and redaction',
+ notCovered: 'Live scheduler execution, host transport and new-task navigation; covered separately by targeted tests',
+ cases: {
+ default: { about: 'Historical automatic execution failure' },
+ narrow: { about: 'Automatic execution failure at 320 px', viewport: { width: 320, height: 540 } },
+ history: { about: 'Historical task execution error' },
+ subagent: { about: 'Subagent execution error' },
+ },
+ async check(page, ui) {
+ const show = page.getByRole('button', { name: await ui.t('chat.errorBanner.networkShowRaw'), exact: true });
+ const diagnose = page.getByRole('button', { name: await ui.t('chat.errorBanner.diagnose'), exact: true });
+ assert.equal(await show.getAttribute('aria-expanded'), 'false');
+ assert.equal(await diagnose.count(), 0);
+ await show.click();
+ assert.ok(await page.getByText(/provider identity does not match/).isVisible());
+ assert.equal(await page.getByText(/private-fixture-value/).count(), 0);
+ await diagnose.click();
+ assert.equal(await page.locator('[data-diagnosis-count]').getAttribute('data-diagnosis-count'), '1');
+ },
+};
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
index 79382eaad2..0b69b3b567 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
@@ -141,6 +141,7 @@ const SCHEDULER_DDL = [
interval_ms INTEGER,
agent_kind TEXT NOT NULL,
model_agent_kind TEXT,
+ model_agent_device_id TEXT,
model TEXT,
provider_id TEXT,
agent_device_id TEXT,
@@ -627,7 +628,9 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
stderrTruncated: false, timedOut: false, aborted: false } as const;
const insert = (id: string, scheduleId: string, firedAt: number, status: ScheduleRun['status'], extra: Partial<ScheduleRun> = {}) =>
harness.storage.insertRun({ id, scheduleId, firedAt, status, sessionId: 'recovery-session', ...extra });
- await insert('execution-a', 'recovery-a', 1, 'failed', { readAt: 2 });
+ await insert('execution-a', 'recovery-a', 1, 'failed', { readAt: 2, errorMsg: 'provider mismatch' });
+ expect((await harness.storage.listSidebarIndexRuns()).find((r) => r.runId === 'execution-a'))
+ .toMatchObject({ errorMsg: 'provider mismatch' });
await insert('check-b', 'recovery-b', 3, 'failed', { preRunHookResult: hook });
const before = await harness.storage.listSidebarIndexRuns();
expect(before.find((r) => r.runId === 'check-b')).toMatchObject({ failureKind: 'rate-limit', failureRecovered: false });
diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.ts
index ca38d22214..a08439adb2 100644
--- a/apps/desktop/src/main/scheduler-host/storage.ts
+++ b/apps/desktop/src/main/scheduler-host/storage.ts
@@ -94,6 +94,7 @@ export interface ScheduleSidebarIndexRun {
readAt?: number;
firedAt?: number;
failureKind?: 'precheck' | 'rate-limit' | 'execution';
+ errorMsg?: string;
failureRecovered?: boolean;
}
@@ -727,6 +728,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
firedAt: scheduleRuns.firedAt,
failureRecovered: failureRecoveredSql('schedule_runs'),
failureKind: failureKindSql('schedule_runs'),
+ errorMsg: scheduleRuns.errorMsg,
};
const [latestSessionRows, unreadRows, runningRows, latestFailedRows] = await Promise.all([
db
@@ -797,6 +799,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
...(row.status === 'failed' || row.status === 'interrupted' ? {
failureRecovered: Boolean(row.failureRecovered),
failureKind: row.failureKind,
+ errorMsg: row.errorMsg ?? undefined,
} : {}),
}));
diff --git a/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx b/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx
index fd8cf6c706..533d09f706 100644
--- a/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx
@@ -71,6 +71,17 @@ afterEach(() => {
});
describe('historical failed schedule notice', () => {
+ it('exposes the recorded failure without marking or rerunning it', () => {
+ const onDiagnose = vi.fn();
+ render(<UnreadFailedScheduleBanner dataOwnerId="owner" sessionId="session"
+ latestFailedRun={{ runId: 'failed', firedAt: 1, errorMsg: 'provider mismatch api_key=private-test-value' }}
+ onDiagnose={onDiagnose} />);
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.queryByText(/private-test-value/)).toBeNull();
+ fireEvent.click(screen.getByText('chat.errorBanner.diagnose'));
+ expect(onDiagnose).toHaveBeenCalledWith(expect.objectContaining({ details: 'provider mismatch api_key=private-test-value' }));
+ expect(markRunRead).not.toHaveBeenCalled();
+ });
it('distinguishes precheck failures while preserving the warning', () => {
render(<UnreadFailedScheduleBanner dataOwnerId="owner" sessionId="session"
latestFailedRun={{ runId: 'failed', firedAt: 1, failureKind: 'rate-limit', scheduleId: 'schedule' }} />);
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 48187b57fd..d9fc99708c 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -593,7 +593,16 @@ export function ErrorBanner({
terminalRateLimitRetryProgress ||
isClaudeGatewayOpusPlanMismatch ||
isClaudeSubscriptionOpusPlanMismatch ||
- isGatewayProxyTokenInvalid;
+ isGatewayProxyTokenInvalid ||
+ isPiImageInputUnsupportedError(error) ||
+ isCodexAppServerForceRetired ||
+ isCodexThreadStale ||
+ showInvalidEncryptedContentRecovery ||
+ isOversizedHistoryError ||
+ isCodexRemoteAuthMissing ||
+ isOpenAiConnectionExpired ||
+ isCodexLocalOAuthAuthMissing ||
+ isGatewayQuotaExhausted;
const handleSwitchToClaudeSubscription = async (): Promise<void> => {
if (!onSwitchToClaudeSubscription || switchingClaudeSubscription) return;
diff --git a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
index 75eefa2589..94821b23f1 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
@@ -15,6 +15,7 @@
* 视觉与实时错误共用 ErrorNotice,中性底色与正文,红色仅标识状态图标。
*/
+import type { ErrorDiagnosisSource } from '@/lib/errorDiagnosisPrompt';
import { ErrorNotice } from '@/components/ui/error-notice';
import { useTranslation } from 'react-i18next';
import {
@@ -36,8 +37,10 @@ export function ErrorMessageCard({
toolLoop,
sessionSource,
kind = 'reply-error',
+ onDiagnose,
}: {
message: string;
+ onDiagnose?: (error: ErrorDiagnosisSource) => void;
/** Blocked input has not reached the agent; its explanation is already user-facing. */
kind?: 'reply-error' | 'blocked-input';
reason?: string;
@@ -88,6 +91,7 @@ export function ErrorMessageCard({
message={isAttachmentAccessDenied ? t('chat.errorBanner.attachmentAccessDeniedTitle') : text}
description={isAttachmentAccessDenied ? t('chat.errorBanner.attachmentAccessDeniedRecovery') : undefined}
details={showRawToggle ? message : undefined}
+ onDiagnose={showRawToggle && onDiagnose ? () => onDiagnose({ message: text, details: message, reason }) : undefined}
data-testid="error-message-card"
/>
);
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 0ec908b0c4..a2f6589ad2 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -332,6 +332,7 @@ import { UserMessage } from './UserMessage';
import { AssistantMessage } from './AssistantMessage';
import { MessageSourceLabels } from './MessageSourceLabels';
import { AskUserQuestionBubble } from './AskUserQuestionBubble';
+import type { ErrorDiagnosisSource } from '@/lib/errorDiagnosisPrompt';
import { ErrorMessageCard } from './ErrorMessageCard';
import { APP_EXIT_INTERRUPTED_REASON } from '../../../shared/interruptedTurn';
import { PlanReviewBubble } from './PlanReviewBubble';
@@ -456,6 +457,7 @@ interface MessageStreamProps {
remoteHostId?: string | null;
/** Task origin. Personal WeChat must not be told to switch to Full access. */
sessionSource?: string | null;
+ onDiagnoseError?: (error: ErrorDiagnosisSource) => void;
/** Session working directory; passed down so MarkdownRenderer / UserMessage
* can resolve relative paths in markdown links and inline @-chips
* (text-lightbox-trigger-extension F1 / F2). Stable within a session
@@ -2834,6 +2836,7 @@ function renderWorkGroupChild(
agentKind?: 'cc' | 'codex' | 'pi';
remoteHostId?: string | null;
sessionSource?: string | null;
+ onDiagnoseError?: (error: ErrorDiagnosisSource) => void;
isSessionStreaming: boolean;
firstUserMessageClientId: string | null;
lastUserMessageClientId: string | null;
@@ -2883,6 +2886,7 @@ function renderWorkGroupChild(
agentKind={props.agentKind}
remoteHostId={props.remoteHostId}
sessionSource={props.sessionSource}
+ onDiagnoseError={props.onDiagnoseError}
sessionRunning={props.isSessionStreaming}
assistantForkBlocked={shouldBlockAssistantFork(
props.isSessionStreaming,
@@ -2997,6 +3001,7 @@ export function MessageStream({
agentKind,
remoteHostId,
sessionSource,
+ onDiagnoseError,
workingDir,
assistantAvatar,
simplifiedBotConversation = false,
@@ -6307,6 +6312,7 @@ export function MessageStream({
agentKind,
remoteHostId,
sessionSource,
+ onDiagnoseError,
isSessionStreaming,
firstUserMessageClientId,
lastUserMessageClientId,
@@ -6327,6 +6333,7 @@ export function MessageStream({
agentKind,
remoteHostId,
sessionSource,
+ onDiagnoseError,
isSessionStreaming,
firstUserMessageClientId,
lastUserMessageClientId,
@@ -6736,6 +6743,7 @@ export function MessageStream({
simplifiedBotConversation={simplifiedBotConversation}
starterOptionsLocked={Boolean(lastUserMessageClientId)}
sessionSource={sessionSource}
+ onDiagnoseError={onDiagnoseError}
/>
);
const highlightClass =
@@ -6927,6 +6935,7 @@ const MessageItem = memo(function MessageItem({
simplifiedBotConversation,
starterOptionsLocked,
sessionSource,
+ onDiagnoseError,
}: {
message: ChatMessage;
toolResult?: string;
@@ -6981,6 +6990,7 @@ const MessageItem = memo(function MessageItem({
/** True once the user has written anything in this task, which retires the opening's starter buttons. */
starterOptionsLocked?: boolean;
sessionSource?: string | null;
+ onDiagnoseError?: (error: ErrorDiagnosisSource) => void;
}) {
// silent-stop 自动续跑行(isSyntheticTrigger + systemCardType):渲染成
// 「已自动继续」分隔线,必须在 synthetic early-return 之前检查,否则分隔线被吞。
@@ -7171,6 +7181,7 @@ const MessageItem = memo(function MessageItem({
providerId={message.errorProviderId}
toolLoop={message.toolLoop}
sessionSource={sessionSource}
+ onDiagnose={onDiagnoseError}
/>
);
case 'thinking':
diff --git a/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx b/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx
index c2ae750b4b..2d29761dbe 100644
--- a/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState, type CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
import { ErrorNotice } from '@/components/ui/error-notice';
+import type { ErrorDiagnosisSource } from '@/lib/errorDiagnosisPrompt';
import { cn } from '@/lib/utils';
import { scheduleFailureMessageKey } from '@cindy/maker-shared/schedule-model';
import {
@@ -15,6 +16,7 @@ interface BannerProps {
dataOwnerId: string | null;
sessionId: string;
latestFailedRun: FailedScheduleRunSnapshot;
+ onDiagnose?: (error: ErrorDiagnosisSource) => void;
className?: string;
style?: CSSProperties;
}
@@ -33,6 +35,7 @@ function FailedScheduleNotice({
dataOwnerId,
sessionId,
latestFailedRun,
+ onDiagnose,
className,
style,
}: BannerProps) {
@@ -83,6 +86,11 @@ function FailedScheduleNotice({
data-testid="unread-failed-schedule-banner"
data-banner-kind="unread-failed-schedule"
message={t(`chat.unreadFailedScheduleBanner.${scheduleFailureMessageKey(latestFailedRun)}`)}
+ details={latestFailedRun.errorMsg}
+ onDiagnose={onDiagnose && latestFailedRun.errorMsg ? () => onDiagnose({
+ message: t(`chat.unreadFailedScheduleBanner.${scheduleFailureMessageKey(latestFailedRun)}`),
+ details: latestFailedRun.errorMsg!,
+ }) : undefined}
onDismiss={dismiss}
dismissLabel={t('chat.unreadFailedScheduleBanner.dismissTitle')}
/>
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx
index bde6d171bc..9304d22df8 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorLocalization.test.tsx
@@ -31,6 +31,24 @@ const raw = JSON.stringify({ error: {
} });
afterEach(cleanup);
+it.each(['thread not found', 'app-server force-retired: auth changed'])(
+ 'retains the specific execution failure in details: %s',
+ async (error) => {
+ const i18n = createInstance();
+ await i18n.init({ lng: 'en', resources: { en: { translation: en } } });
+ const onDiagnose = vi.fn();
+ const onRetry = vi.fn();
+ render(<I18nextProvider i18n={i18n}>
+ <ErrorBanner agentKind="codex" error={error} onRetry={onRetry} onDiagnose={onDiagnose} />
+ </I18nextProvider>);
+ fireEvent.click(screen.getByText(en.chat.errorBanner.networkShowRaw));
+ expect(screen.getByText(error)).toBeTruthy();
+ fireEvent.click(screen.getByText(en.chat.errorBanner.diagnose));
+ expect(onDiagnose).toHaveBeenCalledWith(expect.objectContaining({ details: error }));
+ expect(onRetry).not.toHaveBeenCalled();
+ },
+);
+
// 诊断入口只在展开详情后出现;预填给新任务的提示带出错任务链接,且与详情同样脱敏。
it('offers diagnosis after expanding details with a redacted prompt for the failed session', async () => {
const i18n = createInstance();
@@ -75,6 +93,16 @@ it('appends the diagnosis prompt to an unsent new-task draft instead of replacin
});
describe.each(SUPPORTED_LOCALES)('error presentation in %s', locale => {
+ it('builds a localized diagnosis without a task link for early execution failures', async () => {
+ const i18n = createInstance();
+ await i18n.init({ lng: locale, resources: { [locale]: { translation: locales[locale] } }, interpolation: { escapeValue: false } });
+ const prompt = buildErrorDiagnosisPrompt(i18n.t, null, {
+ message: 'Execution failed', details: 'runId: early-run; api_key=private-value',
+ });
+ expect(prompt).toContain('runId: early-run');
+ expect(prompt).not.toMatch(/private-value|cindy:\/\/|\{\{|diagnosePromptWithoutSession/);
+ });
+
it('keeps the localized blocked-input fallback visible instead of a reply-failure summary', async () => {
const i18n = createInstance();
await i18n.init({ lng: locale, fallbackLng: 'en', resources: Object.fromEntries(Object.entries(locales).map(([lng, common]) => [lng, { translation: common }])) });
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx
index 90fc3685ca..f51b76c952 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorMessageCard.test.tsx
@@ -18,6 +18,16 @@ const STREAM_RAW =
afterEach(cleanup);
describe('ErrorMessageCard', () => {
+ // Historical execution failures must offer the same diagnosis as live failures.
+ it('offers diagnosis only after expanding a persisted execution error', () => {
+ const onDiagnose = vi.fn();
+ render(<ErrorMessageCard message="provider failed api_key=private-test-value" onDiagnose={onDiagnose} />);
+ expect(screen.queryByText('chat.errorBanner.diagnose')).toBeNull();
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ expect(screen.queryByText(/private-test-value/)).toBeNull();
+ fireEvent.click(screen.getByText('chat.errorBanner.diagnose'));
+ expect(onDiagnose).toHaveBeenCalledWith(expect.objectContaining({ details: 'provider failed api_key=private-test-value' }));
+ });
it('shows a blocked input explanation directly without treating it as a failed reply', () => {
const message = 'Please remove the credential before sending: api_key=private-test-value';
render(createElement(ErrorMessageCard, { kind: 'blocked-input', message }));
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 19df0538ba..db98316ec1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -5279,6 +5279,7 @@ function CCAgentSessionContent({
agentKind={session?.agentKind}
remoteHostId={session?.remoteHostId ?? null}
sessionSource={session?.source}
+ onDiagnoseError={canDiagnoseError ? handleDiagnoseError : undefined}
// text-lightbox-trigger-extension F1/F2: cwd flows from session
// owner down through MessageStream → AssistantMessage / UserMessage.
// The spec guarantees `session.workingDir` is set; `?? ''` is purely
@@ -5788,6 +5789,7 @@ function CCAgentSessionContent({
dataOwnerId={dataOwnerId}
sessionId={sessionId}
latestFailedRun={scheduleSessionInfo.latestFailedRun}
+ onDiagnose={canDiagnoseError ? handleDiagnoseError : undefined}
style={{ width: inputWidth }}
className="py-1"
/>
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx
index ba118e3db5..7f67a7d784 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx
@@ -66,10 +66,13 @@ import {
runTitle,
} from './subagentFormat';
+import type { ErrorDiagnosisSource } from '@/lib/errorDiagnosisPrompt';
+
export type SubagentControlIntent = 'steer' | 'follow_up' | 'resume';
export interface SubagentDetailViewProps {
detail: SubagentRunDetail | null;
+ onDiagnose?: (source: ErrorDiagnosisSource) => void;
loading: boolean;
workdir: string;
allowPrivilegedLinks: boolean;
@@ -269,6 +272,7 @@ function PiDurableDetailView({
onBack,
onStop,
onControl,
+ onDiagnose,
}: SubagentDetailViewProps) {
const { t } = useTranslation();
const { preference: sendShortcutPreference } = useComposerSendShortcutPreference();
@@ -592,7 +596,15 @@ function PiDurableDetailView({
</div>
) : null}
- {rawError ? <SubagentErrorNotice rawError={rawError} /> : null}
+ {rawError ? (
+ <SubagentErrorNotice
+ rawError={rawError}
+ onDiagnose={onDiagnose ? (source) => onDiagnose({
+ ...source,
+ details: `subagentRunId: ${detail.id}\n${selectedChild ? `childId: ${selectedChild.id}\n` : ''}${source.details}`,
+ }) : undefined}
+ />
+ ) : null}
{selectedOutputTruncated ? (
<p className="text-11 text-[var(--text-tertiary)]">
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx
index 708028e75a..d3423ef907 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx
@@ -18,6 +18,7 @@ import type {
import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
+import type { ErrorDiagnosisSource } from '@/lib/errorDiagnosisPrompt';
import {
classifySubagentError,
formatClockTime,
@@ -129,7 +130,10 @@ export function CenteredState({
* Classified failure card: an actionable sentence up front, the harness's raw
* payload kept collapsed (DESIGN.md §11 — say what happened and what to do).
*/
-export function SubagentErrorNotice({ rawError }: { rawError: string }) {
+export function SubagentErrorNotice({ rawError, onDiagnose }: {
+ rawError: string;
+ onDiagnose?: (source: ErrorDiagnosisSource) => void;
+}) {
const { t } = useTranslation();
const kind = classifySubagentError(rawError);
return (
@@ -137,6 +141,10 @@ export function SubagentErrorNotice({ rawError }: { rawError: string }) {
data-subagent-error-kind={kind}
message={t(`rightSidebar.subagents.errors.${kind}`)}
details={rawError}
+ onDiagnose={onDiagnose ? () => onDiagnose({
+ message: t(`rightSidebar.subagents.errors.${kind}`),
+ details: rawError,
+ }) : undefined}
/>
);
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx
index e535e4cef7..87fa1486e4 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx
@@ -1,3 +1,7 @@
+import { useInRouterContext, useNavigate } from 'react-router-dom';
+import { isSharedTaskPeer } from '@cindy/device-link';
+import { buildErrorDiagnosisPrompt, prefillErrorDiagnosisDraft, type ErrorDiagnosisSource } from '@/lib/errorDiagnosisPrompt';
+import { buildSessionDeepLink } from '@/lib/deepLink';
import { Button } from '@/components/ui/button';
/**
* SubagentsBody — data orchestration for the durable Subagent workspace tab.
@@ -92,7 +96,23 @@ export function SubagentsBody(props: SubagentsBodyProps) {
props.ctx.deviceLinkDeviceId,
props.ctx.remoteHostId,
);
- return <ScopedSubagentsBody key={scopeKey} {...props} />;
+ const canNavigate = useInRouterContext();
+ return canNavigate
+ ? <NavigableSubagentsBody key={scopeKey} {...props} />
+ : <ScopedSubagentsBody key={scopeKey} {...props} />;
+}
+
+function NavigableSubagentsBody(props: SubagentsBodyProps) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const { sessionId, deviceLinkDeviceId } = props.ctx;
+ const diagnose = useCallback((source: ErrorDiagnosisSource) => {
+ prefillErrorDiagnosisDraft(buildErrorDiagnosisPrompt(t,
+ buildSessionDeepLink(sessionId, { deviceId: deviceLinkDeviceId }), source));
+ navigate('/cc-agent/new');
+ }, [t, navigate, sessionId, deviceLinkDeviceId]);
+ return <ScopedSubagentsBody {...props}
+ onDiagnose={deviceLinkDeviceId !== undefined && !isSharedTaskPeer(deviceLinkDeviceId) ? diagnose : undefined} />;
}
function ScopedSubagentsBody({
@@ -100,7 +120,8 @@ function ScopedSubagentsBody({
ctx,
active = true,
shellVisible = true,
-}: SubagentsBodyProps) {
+ onDiagnose,
+}: SubagentsBodyProps & { onDiagnose?: (source: ErrorDiagnosisSource) => void }) {
const { t } = useTranslation();
const visible = active && shellVisible;
const [loadState, setLoadState] = useState<LoadState>('idle');
@@ -602,6 +623,7 @@ function ScopedSubagentsBody({
onBack={back}
onStop={stopRun}
onControl={controlRun}
+ onDiagnose={onDiagnose}
/>
);
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx
index a74b8ddaa4..764fbcc2d9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/__tests__/SubagentsBody.test.tsx
@@ -2,6 +2,7 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { act } from 'react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type {
SubagentRunDetail,
@@ -54,6 +55,16 @@ vi.mock('@/components/chat/AssistantMessage', () => ({
}));
import { SubagentsBody } from '../SubagentsBody';
+import { prefillErrorDiagnosisDraft } from '@/lib/errorDiagnosisPrompt';
+
+vi.mock('@/lib/errorDiagnosisPrompt', () => ({
+ buildErrorDiagnosisPrompt: (_t: unknown, url: string, source: { details: string }) => `${url}\n${source.details}`,
+ prefillErrorDiagnosisDraft: vi.fn(),
+}));
+
+function CurrentRoute() {
+ return <span data-testid="current-route">{useLocation().pathname}</span>;
+}
const OWNER_STAMP = { dataOwnerId: 'owner-1', ownerGeneration: 1 };
@@ -172,6 +183,31 @@ describe('SubagentsBody', () => {
Reflect.deleteProperty(window, 'electronAPI');
});
+ it('opens a diagnosis draft for a failed child without retrying or controlling it', async () => {
+ currentDetail = {
+ ...detail(''), status: 'failed',
+ capabilities: { ...detail('').capabilities, viewFullTranscript: true },
+ children: [{ id: 'child-1', role: 'worker', status: 'failed', error: 'provider mismatch' }],
+ };
+ render(<MemoryRouter initialEntries={['/cc-agent/session-1']}>
+ <CurrentRoute />
+ <SubagentsBody
+ state={{ selectedRunId: 'run-1', selectedProvider: 'pi' }}
+ ctx={{
+ tabId: 'tab-1', sessionId: 'session-1', workdir: '/workspace',
+ remoteHostId: null, deviceLinkDeviceId: null, patchState: vi.fn(),
+ onVisibilityChange: vi.fn(), setCloseInterceptor: vi.fn(() => () => undefined),
+ }}
+ />
+ </MemoryRouter>);
+ fireEvent.click(await screen.findByRole('button', { name: 'chat.errorBanner.networkShowRaw' }));
+ fireEvent.click(screen.getByRole('button', { name: 'chat.errorBanner.diagnose' }));
+ expect(prefillErrorDiagnosisDraft).toHaveBeenLastCalledWith(expect.stringMatching(/session-1[\s\S]*subagentRunId: run-1\nchildId: child-1\nprovider mismatch/));
+ expect(screen.getByTestId('current-route').textContent).toBe('/cc-agent/new');
+ expect(controlPiSubagent).not.toHaveBeenCalled();
+ expect(stopAgentTask).not.toHaveBeenCalled();
+ });
+
it('polls a local run to completion when no change push ever arrives', async () => {
// The local view is push-driven, and the push dies with the root Pi
// process: `onExit` ends its event queue, so a detached run that finishes
diff --git a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
index f9fc1e657a..4d4f6ce7c5 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/RunHistoryCard.tsx
@@ -31,6 +31,8 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
+import { buildErrorDiagnosisPrompt, prefillErrorDiagnosisDraft } from '@/lib/errorDiagnosisPrompt';
+import { buildSessionDeepLink } from '@/lib/deepLink';
import { AgentMark } from './AgentMark';
import { AttentionDot } from '@/components/sidebar/AttentionDot';
import { formatDuration, formatRunTimestamp, formatStartedAgo } from '../lib/formatters';
@@ -357,7 +359,21 @@ export function RunHistoryCard({
)}
</div>
- {showError && (errorKey && i18n.exists(errorKey) ? (
+ {showError && (run.status === 'failed' ? (
+ <ErrorNotice
+ message={errorKey && i18n.exists(errorKey) ? t(errorKey) : t('chat.unreadFailedScheduleBanner.text')}
+ details={run.errorMsg!}
+ onDiagnose={() => {
+ // 当前自动化可能已切换或重新绑定;只信任这次运行记录保存的任务归属。
+ prefillErrorDiagnosisDraft(buildErrorDiagnosisPrompt(t,
+ run.sessionId ? buildSessionDeepLink(run.sessionId) : null, {
+ message: errorKey && i18n.exists(errorKey) ? t(errorKey) : t('chat.unreadFailedScheduleBanner.text'),
+ details: `scheduleId: ${run.scheduleId}\nrunId: ${run.id}\nfiredAt: ${new Date(run.firedAt).toISOString()}\n${run.errorMsg}`,
+ }));
+ navigate('/cc-agent/new');
+ }}
+ />
+ ) : errorKey && i18n.exists(errorKey) ? (
<ErrorNotice message={t(errorKey)} details={run.errorMsg!} />
) : (
<p
diff --git a/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx b/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx
index 03fb6af53c..9c16427dc9 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/__tests__/RunHistoryCard.test.tsx
@@ -3,15 +3,41 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { ScheduleRun } from '@cindy/maker-scheduler';
+import type { Schedule, ScheduleRun } from '@cindy/maker-scheduler';
import type { SessionReference } from '../../../../../shared/sessionReference';
+import { prefillErrorDiagnosisDraft } from '@/lib/errorDiagnosisPrompt';
import { RunHistoryCard } from '../RunHistoryCard';
+import { RunHistoryPane } from '../RunHistoryPane';
+
+const history = vi.hoisted(() => ({
+ runs: [] as ScheduleRun[],
+ runsScheduleId: 'schedule-a',
+}));
+vi.mock('../../hooks/useRuns', () => ({
+ useRuns: () => ({ ...history, hasLoaded: true, loading: false, error: null }),
+}));
+vi.mock('../../hooks/useSessionReferences', () => ({
+ useSessionReferences: () => new Map(),
+}));
+vi.mock('@/hooks/useCCSessions', () => ({
+ useCCSessions: () => ({ sessions: [] }),
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn() }),
+}));
+vi.mock('@/lib/sessionAttentionStore', () => ({
+ clearSessionAttentionMany: vi.fn(),
+}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { exists: () => true } }),
}));
+vi.mock('@/lib/errorDiagnosisPrompt', () => ({
+ buildErrorDiagnosisPrompt: (_t: unknown, url: string | null, source: { details: string }) => `${url ?? 'no session'}\n${source.details}`,
+ prefillErrorDiagnosisDraft: vi.fn(),
+}));
afterEach(cleanup);
function renderRun(run: ScheduleRun, sessionReference?: SessionReference) {
@@ -22,6 +48,51 @@ function renderRun(run: ScheduleRun, sessionReference?: SessionReference) {
);
}
+describe('RunHistoryPane diagnosis ownership', () => {
+ const actions = { onRunNow: vi.fn(), onTogglePause: vi.fn(), onEdit: vi.fn(), onDelete: vi.fn() };
+ const schedule = (id: string, targetSessionId: string) => ({
+ id, targetSessionId, name: id, status: 'active', agentKind: 'codex',
+ manual: true, workspaceKind: 'dialogue', source: 'user',
+ }) as Schedule;
+ const pane = (value: Schedule) => (
+ <MemoryRouter><RunHistoryPane schedule={value} {...actions} /></MemoryRouter>
+ );
+
+ it.each([undefined, 'recorded-task'])(
+ 'keeps retained run identity when switching schedules (recorded task: %s)',
+ (sessionId) => {
+ history.runsScheduleId = 'schedule-a';
+ history.runs = [{
+ id: 'run-a', scheduleId: 'schedule-a', sessionId, status: 'failed',
+ firedAt: 1, finishedAt: 2, readAt: 2, errorMsg: 'failure from A',
+ }];
+ const { rerender } = render(pane(schedule('schedule-a', 'target-a')));
+ // useRuns keeps A's rows visible while B's request is pending.
+ rerender(pane(schedule('schedule-b', 'target-b')));
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ fireEvent.click(screen.getByText('chat.errorBanner.diagnose'));
+ const prompt = vi.mocked(prefillErrorDiagnosisDraft).mock.calls.at(-1)![0];
+ expect(prompt).toContain('scheduleId: schedule-a\nrunId: run-a');
+ expect(prompt).not.toContain('target-b');
+ expect(prompt).toContain(sessionId ?? 'no session');
+ },
+ );
+
+ it('does not assign a later target to a run that never recorded a task', () => {
+ history.runsScheduleId = 'schedule-a';
+ history.runs = [{
+ id: 'early-run', scheduleId: 'schedule-a', status: 'failed',
+ firedAt: 1, finishedAt: 2, readAt: 2, errorMsg: 'early failure',
+ }];
+ render(pane(schedule('schedule-a', 'later-target')));
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ fireEvent.click(screen.getByText('chat.errorBanner.diagnose'));
+ expect(prefillErrorDiagnosisDraft).toHaveBeenLastCalledWith(
+ expect.stringContaining('no session\nscheduleId: schedule-a\nrunId: early-run'),
+ );
+ });
+});
+
describe('RunHistoryCard 会话引用状态', () => {
it('保留历史记录但将软删除会话显示为不可点击状态', () => {
renderRun(
@@ -60,6 +131,14 @@ describe('RunHistoryCard 前置检查结果', () => {
fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
expect(screen.getByText(/Scheduled model test/)).toBeTruthy();
});
+ it('diagnoses an execution failure before a task was created without fabricating a link', () => {
+ renderRun({ id: 'early-run', scheduleId: 'schedule-1', firedAt: 1,
+ finishedAt: 2, status: 'failed', errorMsg: 'provider mismatch' });
+ expect(screen.queryByText('provider mismatch')).toBeNull();
+ fireEvent.click(screen.getByText('chat.errorBanner.networkShowRaw'));
+ fireEvent.click(screen.getByText('chat.errorBanner.diagnose'));
+ expect(prefillErrorDiagnosisDraft).toHaveBeenLastCalledWith(expect.stringContaining('no session\nscheduleId: schedule-1\nrunId: early-run'));
+ });
it('通过结果显示摘要且默认折叠', () => {
const { container } = renderRun({
id: 'run-passed',
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
index dd8713313e..353385aa74 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
@@ -23,7 +23,11 @@ export function projectScheduleSidebarIndex(
if (isRunUnread) unreadRunIds.push(run.runId);
let latestFailedRun = existing?.latestFailedRun;
if (activeFailures.has(run.runId)) {
- const candidate = { runId: run.runId, firedAt: run.firedAt ?? 0, scheduleId: run.scheduleId, failureKind: run.failureKind };
+ const candidate = {
+ runId: run.runId, firedAt: run.firedAt ?? 0, scheduleId: run.scheduleId,
+ failureKind: run.failureKind,
+ errorMsg: run.status === 'failed' ? run.errorMsg : undefined,
+ };
if (!latestFailedRun || compareFailedScheduleRuns(candidate, latestFailedRun) > 0)
latestFailedRun = candidate;
}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
index 1328ca95e9..1b9bbc4938 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
@@ -15,6 +15,7 @@ export interface ScheduleSidebarIndexRun {
readAt?: number;
firedAt?: number;
failureKind?: 'precheck' | 'rate-limit' | 'execution';
+ errorMsg?: string;
failureRecovered?: boolean;
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b0b00f41e8..543c756453 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -12260,6 +12260,7 @@
"diagnose": "Diagnose",
"diagnoseTitle": "Diagnose this error in a new session",
"diagnosePrompt": "Please diagnose this error: find the cause and tell me how to fix it.\n\nSession: {{sessionUrl}}\nError: {{message}}\nDetails:\n{{details}}\n\nIf you find it's a problem with Cindy itself, let me know so I can choose whether to file an issue with the Cindy team.",
+ "diagnosePromptWithoutSession": "Please diagnose this error: find the cause and tell me how to fix it.\n\nError: {{message}}\nDetails:\n{{details}}\n\nIf you find it's a problem with Cindy itself, let me know so I can choose whether to file an issue with the Cindy team.",
"gatewayProxyTokenInvalid": "Cindy AI credentials are no longer valid. Click Retry. If it happens again, sign out and sign back in",
"gatewayProxyTokenInvalidNoRetry": "Cindy AI credentials are no longer valid. If it happens again, sign out and sign back in",
"modelAccessDenied": "The upstream account cannot access this model. Select another model or check its access with the provider",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 298dcea952..8b452820ac 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -12215,6 +12215,7 @@
"diagnose": "診断",
"diagnoseTitle": "新しいセッションでこのエラーを診断",
"diagnosePrompt": "このエラーを診断して、原因と解決方法を教えてください。\n\nエラーが起きたセッション:{{sessionUrl}}\nエラー表示:{{message}}\nエラー詳細:\n{{details}}\n\nCindy 自体の問題だと分かった場合は教えてください。Cindy チームに issue を提出するかどうかは私が選びます。",
+ "diagnosePromptWithoutSession": "このエラーを診断して、原因と解決方法を教えてください。\n\nエラー表示:{{message}}\nエラー詳細:\n{{details}}\n\nCindy 自体の問題だと分かった場合は教えてください。Cindy チームに issue を提出するかどうかは私が選びます。",
"gatewayProxyTokenInvalid": "Cindy AI の認証情報が無効になりました。「再試行」をクリックしてください。繰り返す場合はサインアウトしてから再ログインしてください",
"gatewayProxyTokenInvalidNoRetry": "Cindy AI の認証情報が無効になりました。繰り返す場合はサインアウトしてから再ログインしてください",
"modelAccessDenied": "接続先のアカウントにはこのモデルへのアクセス権限がありません。別のモデルに切り替えるか、プロバイダーにアクセス権限を確認してください",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 536991f92d..25828b37aa 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -12215,6 +12215,7 @@
"diagnose": "진단",
"diagnoseTitle": "새 세션에서 이 오류 진단",
"diagnosePrompt": "이 오류를 진단해서 원인과 해결 방법을 알려 주세요.\n\n오류가 발생한 세션: {{sessionUrl}}\n오류 메시지: {{message}}\n오류 상세:\n{{details}}\n\nCindy 자체의 문제로 확인되면 알려 주세요. Cindy 팀에 issue를 제출할지는 제가 선택할게요.",
+ "diagnosePromptWithoutSession": "이 오류를 진단해서 원인과 해결 방법을 알려 주세요.\n\n오류 메시지: {{message}}\n오류 상세:\n{{details}}\n\nCindy 자체의 문제로 확인되면 알려 주세요. Cindy 팀에 issue를 제출할지는 제가 선택할게요.",
"gatewayProxyTokenInvalid": "Cindy AI 자격 증명이 더 이상 유효하지 않습니다. 재시도를 클릭하세요. 반복되면 로그아웃 후 다시 로그인하세요",
"gatewayProxyTokenInvalidNoRetry": "Cindy AI 자격 증명이 더 이상 유효하지 않습니다. 반복되면 로그아웃 후 다시 로그인하세요",
"modelAccessDenied": "연결된 서비스 계정에 이 모델의 접근 권한이 없습니다. 다른 모델로 전환하거나 제공자에게 모델 접근 권한을 확인하세요",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 24bd342bc9..b9b9a7323f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12215,6 +12215,7 @@
"diagnose": "诊断",
"diagnoseTitle": "在新任务中诊断这个错误",
"diagnosePrompt": "请帮我诊断这个错误:找出原因,并告诉我怎么解决。\n\n出错任务:{{sessionUrl}}\n错误提示:{{message}}\n错误详情:\n{{details}}\n\n如果确认是 Cindy 本身的问题,请告诉我,我可以选择向 Cindy 团队提交 issue。",
+ "diagnosePromptWithoutSession": "请帮我诊断这个错误:找出原因,并告诉我怎么解决。\n\n错误提示:{{message}}\n错误详情:\n{{details}}\n\n如果确认是 Cindy 本身的问题,请告诉我,我可以选择向 Cindy 团队提交 issue。",
"gatewayProxyTokenInvalid": "Cindy AI 凭据已失效。请点击「重试」。若仍失败,请退出后重新登录",
"gatewayProxyTokenInvalidNoRetry": "Cindy AI 凭据已失效。若后续仍失败,请退出后重新登录",
"modelAccessDenied": "当前上游账号无权访问此模型。请切换模型,或向供应商确认模型访问权限",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 4c7c0c0d1d..c32de6dd96 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12214,6 +12214,7 @@
"diagnose": "診斷",
"diagnoseTitle": "在新任務中診斷這個錯誤",
"diagnosePrompt": "請幫我診斷這個錯誤:找出原因,並告訴我怎麼解決。\n\n出錯任務:{{sessionUrl}}\n錯誤提示:{{message}}\n錯誤詳情:\n{{details}}\n\n如果確認是 Cindy 本身的問題,請告訴我,我可以選擇向 Cindy 團隊提交 issue。",
+ "diagnosePromptWithoutSession": "請幫我診斷這個錯誤:找出原因,並告訴我怎麼解決。\n\n錯誤提示:{{message}}\n錯誤詳情:\n{{details}}\n\n如果確認是 Cindy 本身的問題,請告訴我,我可以選擇向 Cindy 團隊提交 issue。",
"gatewayProxyTokenInvalid": "Cindy AI 憑據已失效。請點「重試」。若仍失敗,請退出後重新登入",
"gatewayProxyTokenInvalidNoRetry": "Cindy AI 憑據已失效。若後續仍失敗,請退出後重新登入",
"modelAccessDenied": "目前上游帳號無權存取此模型。請切換模型,或向供應商確認模型存取權限",
diff --git a/apps/desktop/src/renderer/lib/errorDiagnosisPrompt.ts b/apps/desktop/src/renderer/lib/errorDiagnosisPrompt.ts
index 6a6ba5e301..8d3a4607f3 100644
--- a/apps/desktop/src/renderer/lib/errorDiagnosisPrompt.ts
+++ b/apps/desktop/src/renderer/lib/errorDiagnosisPrompt.ts
@@ -25,11 +25,11 @@ export interface ErrorDiagnosisSource {
export function buildErrorDiagnosisPrompt(
t: TFunction,
- sessionUrl: string,
+ sessionUrl: string | null,
source: ErrorDiagnosisSource,
): string {
const details = redactSensitiveText(source.details).trim();
- return t('chat.errorBanner.diagnosePrompt', {
+ return t(sessionUrl ? 'chat.errorBanner.diagnosePrompt' : 'chat.errorBanner.diagnosePromptWithoutSession', {
sessionUrl,
message: redactSensitiveText(source.message).trim(),
details: source.reason
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index e1388a222d..b245de92b2 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -10469,6 +10469,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
onCopyMessageLink={copyMessageLink}
onAddMessageToComposer={canUseComposer ? addMessageToComposer : undefined}
onSideChatMessage={canUseSideChats && currentSession?.source !== 'side-chat' ? askInSideChat : undefined}
+ onDiagnoseError={canDiagnoseError ? handleDiagnoseError : undefined}
onDeleteMessage={isSharedTaskPeer(deviceId) ? undefined : deleteMessage}
onForkMessage={isSharedTaskPeer(deviceId) ? undefined : forkAtMessage}
onLoadEarlier={loadEarlierMessages}
@@ -10529,7 +10530,8 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
streaming: isSessionStreaming, running: remoteSessionRunning,
}) && scheduleFailure?.run ? (
<FailedScheduleNotice key={scheduleNoticeSource}
- source={scheduleNoticeSource} run={scheduleFailure.run} />
+ source={scheduleNoticeSource} run={scheduleFailure.run}
+ onDiagnose={canDiagnoseError ? handleDiagnoseError : undefined} />
) : null}
{/* 队列状态横幅(错误 / 凭证等待 / 停止确认 / 暂停)。待发送气泡
不在这里,它们是消息流里的 pending_send 项。 */}
diff --git a/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx b/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
index 9e7070ae80..8d0b2d7451 100644
--- a/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
+++ b/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
@@ -15,11 +15,11 @@ vi.mock('react-native', async () => {
return { View: view('div'), Text: view('span'), Pressable: view('button'), StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 } };
});
vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));
-vi.mock('lucide-react-native', () => ({ CircleAlert: () => null, X: () => null }));
+vi.mock('lucide-react-native', () => ({ CircleAlert: () => null, X: () => null, ChevronDown: () => null, ChevronRight: () => null, Stethoscope: () => null }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/theme', async () => {
const { lightColors } = await import('@/theme/tokens');
- return { useTheme: () => ({ colors: lightColors }), useThemedStyles: (make: (colors: typeof lightColors) => unknown) => make(lightColors) };
+ return { iconSize: { sm: 12 }, iconStroke: { regular: 1.5 }, useTheme: () => ({ colors: lightColors }), useThemedStyles: (make: (colors: typeof lightColors) => unknown) => make(lightColors) };
});
let root: Root;
let host: HTMLDivElement;
@@ -66,3 +66,22 @@ it('can close for the current view even if preference storage fails', async () =
await act(async () => host.querySelector('button')!.click());
expect(host.textContent).toBe('');
});
+
+// Existing dismissal coverage did not exercise execution details or diagnosis.
+it('discloses the recorded error and keeps it out of dismissal preferences', async () => {
+ const onDiagnose = vi.fn();
+ await act(async () => root.render(<FailedScheduleNotice source="owner/device/task"
+ run={{ ...run, errorMsg: 'provider mismatch api_key=private-test-value' }} onDiagnose={onDiagnose} />));
+ const click = async (text: string) => act(async () => {
+ const button = [...host.querySelectorAll('button')].find(b => b.textContent === text);
+ expect(button).toBeTruthy(); button!.click();
+ });
+ expect(host.textContent).not.toContain('provider mismatch');
+ await click('session.tail.showErrorDetails');
+ expect(host.textContent).toContain('provider mismatch');
+ expect(host.textContent).not.toContain('private-test-value');
+ await click('session.tail.diagnose');
+ expect(onDiagnose).toHaveBeenCalledWith(expect.objectContaining({ details: 'provider mismatch api_key=private-test-value' }));
+ await act(async () => host.querySelector('button')!.click());
+ expect(storage.get('scheduleFailureDismissal:owner/device/task')).toBe(JSON.stringify(run));
+});
diff --git a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx
index 34df14e9b5..3b5fb2167a 100644
--- a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx
+++ b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx
@@ -116,6 +116,7 @@ vi.mock("@legendapp/list/react-native", () => ({
useViewability: () => {},
}));
vi.mock("lucide-react-native", () => ({
+ Stethoscope: () => null,
Mail: () => null, CalendarDays: () => null, Folder: () => null, ChartColumn: () => null, Info: () => null, Clock: () => null, MapPin: () => null, Coffee: () => null, Image: () => null, Users: () => null, Star: () => null,
Database: () => null,
FileArchive: () => null,
@@ -314,6 +315,28 @@ beforeAll(async () => {
await i18n.changeLanguage("zh-CN");
});
+it('diagnoses a historical execution error through the real message renderer', () => {
+ const raw = 'provider mismatch api_key=private-history-value';
+ const onDiagnoseError = vi.fn();
+ const { host, unmount } = mount([{
+ ...msg('historical-error', JSON.stringify({ message: raw }), null), role: 'error',
+ }], { onDiagnoseError });
+ try {
+ expect(host.querySelector('[data-testid="agentError.diagnose"]')).toBeNull();
+ const toggle = [...host.querySelectorAll<HTMLElement>('div')].find(
+ (node) => node.textContent === i18n.t('session.tail.showErrorDetails') && node.onclick,
+ );
+ expect(toggle).toBeTruthy();
+ act(() => toggle!.click());
+ expect(host.textContent).toContain('provider mismatch');
+ expect(host.textContent).not.toContain('private-history-value');
+ act(() => host.querySelector<HTMLElement>('[data-testid="agentError.diagnose"]')!.click());
+ expect(onDiagnoseError).toHaveBeenCalledWith(expect.objectContaining({ details: raw }));
+ } finally {
+ unmount();
+ }
+});
+
describe("device source label", () => {
const fromPhone = msg("m1", "hi", {
sourceDevice: { deviceId: "phone-a", name: "快照名", platform: "mobile" },
diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.ts
index 324c05ab7a..d62d18a6f5 100644
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@ -38,7 +38,7 @@ function makerWithSchedules(
describe('scheduleIndex', () => {
it.each(['lightweight', 'legacy'] as const)('reconciles recovered failure dots with task details through %s reads', async (source) => {
const failure = { id: 'failure', runId: 'failure', scheduleId: 'sched-1', scheduleName: 'Check',
- scheduleStatus: 'active', sessionId: 'task', status: 'failed', firedAt: 1 };
+ scheduleStatus: 'active', sessionId: 'task', status: 'failed', firedAt: 1, errorMsg: 'provider mismatch' };
const success = { ...failure, id: 'success', runId: 'success', status: 'success', firedAt: 2 };
const rows = [failure, success];
const maker = makerWithSchedules(async (id) => id === 'sched-1' ? rows : []);
@@ -57,8 +57,13 @@ describe('scheduleIndex', () => {
// A fresh failure must still be visible both in the task and on its row.
rows.push({ ...failure, id: 'new-failure', runId: 'new-failure', firedAt: 3 });
const failed = (await load()).get('task')!;
- expect(failed.latestFailedRun?.runId).toBe('new-failure');
+ expect(failed.latestFailedRun).toMatchObject({ runId: 'new-failure', errorMsg: 'provider mismatch' });
expect(dot(failed)).toBe('error');
+
+ rows.push({ ...failure, id: 'interrupted', runId: 'interrupted', status: 'interrupted', firedAt: 4 });
+ expect((await load()).get('task')!.latestFailedRun).toMatchObject({
+ runId: 'interrupted', errorMsg: undefined,
+ });
});
it.each([false, true])('peer recovery invalidates only its success or pending snapshot (pending=%s)', async (pending) => {
diff --git a/apps/mobile/src/session/FailedScheduleNotice.tsx b/apps/mobile/src/session/FailedScheduleNotice.tsx
index d7687c33e6..9882d7cdb4 100644
--- a/apps/mobile/src/session/FailedScheduleNotice.tsx
+++ b/apps/mobile/src/session/FailedScheduleNotice.tsx
@@ -1,3 +1,5 @@
+import { AgentErrorDetails } from './AgentErrorDetails';
+import type { ErrorDiagnosisSource } from './errorDiagnosisPrompt';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {
compareFailedScheduleRuns,
@@ -13,9 +15,11 @@ import { spacing } from '@/theme/tokens';
export function FailedScheduleNotice({
source,
run,
+ onDiagnose,
}: {
source: string;
run: FailedScheduleRunSnapshot;
+ onDiagnose?: (error: ErrorDiagnosisSource) => void;
}) {
const key = `scheduleFailureDismissal:${source}`;
const [loaded, setLoaded] = useState(false);
@@ -54,7 +58,7 @@ export function FailedScheduleNotice({
return null;
const dismiss = () => {
setDismissed(run);
- void AsyncStorage.setItem(key, JSON.stringify(run)).catch(() => undefined);
+ void AsyncStorage.setItem(key, JSON.stringify({ runId: run.runId, firedAt: run.firedAt })).catch(() => undefined);
};
return (
<ErrorNotice
@@ -65,6 +69,12 @@ export function FailedScheduleNotice({
)}
onDismiss={dismiss}
dismissLabel={t('session.failedScheduleNotice.dismissTitle')}
- />
+ >
+ {run.errorMsg ? <AgentErrorDetails message={run.errorMsg}
+ onDiagnose={onDiagnose ? () => onDiagnose({
+ message: t(`session.failedScheduleNotice.${scheduleFailureMessageKey(run)}`),
+ details: run.errorMsg!,
+ }) : undefined} /> : null}
+ </ErrorNotice>
);
}
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 25d2867871..7d76dad129 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -12,6 +12,7 @@ import { MessageListVisibility, MessageListVisibilityContext, useMessageListItem
import { CompanionLearningFooter } from './CompanionLearningFooter';
import { CompanionTaskResultCard } from './CompanionTaskResultCard';
import { botTaskResultKey, readBotTaskResults } from '@cindy/maker-shared/botCollaboration';
+import type { ErrorDiagnosisSource } from './errorDiagnosisPrompt';
import { AgentErrorDetails } from './AgentErrorDetails';
import { ErrorNotice } from '@/components/ErrorNotice';
import { FileTypeIcon } from '@/components/FileTypeIcon';
@@ -696,6 +697,7 @@ interface MessageActions {
/** Insert this message's anchored link as an atom in the active composer. */
onAddMessageToComposer?: (clientId: string) => void;
onSideChatMessage?: (text: string) => void;
+ onDiagnoseError?: (error: ErrorDiagnosisSource) => void;
/**
* chat-text-quote:选中消息文字 → 系统选择菜单「添加到对话」项的采集回调
* (会话页写入 chatQuoteStore)。未传时选区采集整体关闭(context 为 null,
@@ -770,6 +772,7 @@ export function MessageRenderer({
onCopyMessageLink,
onAddMessageToComposer,
onSideChatMessage,
+ onDiagnoseError,
onForkMessage,
onDeleteMessage,
onLoadEarlier,
@@ -1836,6 +1839,7 @@ export function MessageRenderer({
remoteDeviceId,
onAddMessageToComposer,
onSideChatMessage,
+ onDiagnoseError,
onCopyMessageLink,
onForkMessage,
onDeleteMessage,
@@ -1888,6 +1892,7 @@ export function MessageRenderer({
onCopyMessageLink,
onAddMessageToComposer,
onSideChatMessage,
+ onDiagnoseError,
onDeleteMessage,
onForkMessage,
onOpenForkOrigin,
@@ -4097,7 +4102,10 @@ function MessageBubble({
) : null}
{item.message.role === 'error' ? (
<ErrorNotice message={displayBubbleBody}>
- {item.message.rawError ? <AgentErrorDetails key={item.message.key} message={item.message.rawError} /> : null}
+ {item.message.rawError ? <AgentErrorDetails key={item.message.key} message={item.message.rawError}
+ onDiagnose={actions.onDiagnoseError ? () => actions.onDiagnoseError!({
+ message: displayBubbleBody, details: item.message.rawError!,
+ }) : undefined} /> : null}
</ErrorNotice>
) : bubbleShown ? bubble : null}
{actions.companion && item.message.kind === 'assistant' && item.message.body.trim() ? (
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index 9dd033142e..427733eff6 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -414,6 +414,7 @@ function scheduleInfoEqual(a: RemoteSessionScheduleInfo, b: RemoteSessionSchedul
&& a.latestFailedRun?.firedAt === b.latestFailedRun?.firedAt
&& a.latestFailedRun?.scheduleId === b.latestFailedRun?.scheduleId
&& a.latestFailedRun?.failureKind === b.latestFailedRun?.failureKind
+ && a.latestFailedRun?.errorMsg === b.latestFailedRun?.errorMsg
&& a.running === b.running
&& a.latestRunAt === b.latestRunAt
&& a.scheduleStatus === b.scheduleStatus
diff --git a/packages/maker-shared/src/scheduleModel.ts b/packages/maker-shared/src/scheduleModel.ts
index c91ac9fde9..d76b5fcd81 100644
--- a/packages/maker-shared/src/scheduleModel.ts
+++ b/packages/maker-shared/src/scheduleModel.ts
@@ -606,6 +606,8 @@ export interface FailedScheduleRunSnapshot {
firedAt: number;
scheduleId?: string;
failureKind?: ScheduleFailureKind;
+ /** Optional on older hosts; error content is only disclosed on demand. */
+ errorMsg?: string;
}
/** Old hosts can omit the classification; keep their warning generic. */
diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.ts
index 4a557c94e3..4daec868d6 100644
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@ -692,7 +692,11 @@ export function buildSessionScheduleIndex(
if (isUnreadScheduleRun(run) && (run.status === 'success' || isUnreadFailure)) {
unreadRunIds.push(run.id);
}
- const candidate = activeFailures.has(run.id) ? { runId: run.id, firedAt, scheduleId: run.scheduleId, failureKind: classifyScheduleFailure(run) } : undefined;
+ const candidate = activeFailures.has(run.id) ? {
+ runId: run.id, firedAt, scheduleId: run.scheduleId,
+ failureKind: classifyScheduleFailure(run),
+ errorMsg: run.status === 'failed' ? run.errorMsg : undefined,
+ } : undefined;
const latestFailedRun = candidate && (!existing?.latestFailedRun || compareFailedScheduleRuns(candidate, existing.latestFailedRun) > 0)
? candidate : existing?.latestFailedRun;
const running = (existing?.running ?? false) || run.status === 'running';