Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(inbox): localize proposals, show details, notify run failures (#20937)

Arvin Xu99f8a485a1ad
diff --git a/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts b/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts
new file mode 100644
index 00000000000..93c0c94726a
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts
@@ -0,0 +1,110 @@
+import { Hono } from 'hono';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { watchdog } from '../watchdog';
+
+const mocks = vi.hoisted(() => ({
+ briefCreate: vi.fn(),
+ findRecoverableScopes: vi.fn(),
+ findStuckTasks: vi.fn(),
+ getServerDB: vi.fn(),
+ notifyTaskRunFailed: vi.fn(),
+ reconcileOrphanedTaskRuns: vi.fn(),
+ updateStatus: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ getServerDB: mocks.getServerDB }));
+
+vi.mock('@/database/models/task', () => ({
+ TaskModel: Object.assign(
+ vi.fn(function () {
+ return { updateStatus: mocks.updateStatus };
+ }),
+ { findStuckTasks: mocks.findStuckTasks },
+ ),
+}));
+
+vi.mock('@/database/models/brief', () => ({
+ BriefModel: vi.fn(function () {
+ return { create: mocks.briefCreate };
+ }),
+}));
+
+vi.mock('@/business/server/task/notifyTaskRunFailed', () => ({
+ notifyTaskRunFailed: mocks.notifyTaskRunFailed,
+}));
+
+vi.mock('@/server/services/taskLifecycle/reconcile', () => ({
+ reconcileOrphanedTaskRuns: mocks.reconcileOrphanedTaskRuns,
+}));
+
+vi.mock('@/server/services/taskResultBridge', () => ({ TaskResultBridgeService: vi.fn() }));
+
+vi.mock('@/server/services/taskResultBridge/redisStore', () => ({
+ TaskResultCallbackRedisStore: { findRecoverableScopes: mocks.findRecoverableScopes },
+}));
+
+const runWatchdog = async () => {
+ const app = new Hono();
+ app.post('/watchdog', watchdog);
+ const res = await app.request('/watchdog', { method: 'POST' });
+ return { body: await res.json(), status: res.status };
+};
+
+describe('task watchdog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getServerDB.mockResolvedValue({});
+ mocks.findRecoverableScopes.mockResolvedValue([]);
+ mocks.notifyTaskRunFailed.mockResolvedValue(undefined);
+ mocks.reconcileOrphanedTaskRuns.mockResolvedValue({ converged: [] });
+ });
+
+ // A heartbeat timeout is a failure, not a decision: it goes to the
+ // notification center rather than a "Needs you" error brief.
+ it('fails a stuck task and notifies instead of creating an error brief', async () => {
+ mocks.findStuckTasks.mockResolvedValue([
+ {
+ assigneeAgentId: 'agent-1',
+ createdByUserId: 'user-1',
+ heartbeatTimeout: 600,
+ id: 'task-1',
+ identifier: 'T-1',
+ name: 'Nightly sync',
+ workspaceId: 'ws-1',
+ },
+ ]);
+
+ const { body, status } = await runWatchdog();
+
+ expect(status).toBe(200);
+ expect(body.failed).toEqual(['T-1']);
+ expect(mocks.updateStatus).toHaveBeenCalledWith(
+ 'task-1',
+ 'failed',
+ expect.objectContaining({ error: 'Heartbeat timeout' }),
+ );
+ expect(mocks.briefCreate).not.toHaveBeenCalled();
+ expect(mocks.notifyTaskRunFailed).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ reason: 'heartbeat_timeout',
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ taskName: 'Nightly sync',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('keeps sweeping when the notification fails', async () => {
+ mocks.findStuckTasks.mockResolvedValue([
+ { createdByUserId: 'user-1', id: 'task-1', identifier: 'T-1', workspaceId: null },
+ ]);
+ mocks.notifyTaskRunFailed.mockRejectedValue(new Error('push down'));
+
+ const { body, status } = await runWatchdog();
+
+ expect(status).toBe(200);
+ expect(body.failed).toEqual(['T-1']);
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts b/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts
index 324b38b5fa3..551e25ec39e 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts
@@ -1,9 +1,8 @@
import debug from 'debug';
import type { Context } from 'hono';
-import { BriefModel } from '@/database/models/brief';
-import { TaskModel } from '@/database/models/task';
import { getServerDB } from '@/database/server';
+import { failStuckTasks } from '@/server/services/taskLifecycle/failStuckTasks';
import { reconcileOrphanedTaskRuns } from '@/server/services/taskLifecycle/reconcile';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { TaskResultCallbackRedisStore } from '@/server/services/taskResultBridge/redisStore';
@@ -15,7 +14,7 @@ const log = debug('lobe-server:workflows:task:watchdog');
* behind them:
*
* 1. `lastHeartbeatAt + heartbeatTimeout < now()` — the automation-heartbeat
- * net, which marks the Task `failed` with an urgent brief.
+ * net, which marks the Task `failed` and notifies the owner.
* 2. A `running` run row whose operation already ended (see
* {@link reconcileOrphanedTaskRuns}) — the net for a Task the first one
* cannot see, either because it sets no `heartbeatTimeout` or because its
@@ -28,30 +27,7 @@ const log = debug('lobe-server:workflows:task:watchdog');
export async function watchdog(c: Context) {
try {
const db = await getServerDB();
- const stuckTasks = await TaskModel.findStuckTasks(db);
- const failed: string[] = [];
-
- for (const task of stuckTasks) {
- const wsId = task.workspaceId ?? undefined;
- const taskModel = new TaskModel(db, task.createdByUserId, wsId);
- await taskModel.updateStatus(task.id, 'failed', {
- completedAt: new Date(),
- error: 'Heartbeat timeout',
- });
-
- const briefModel = new BriefModel(db, task.createdByUserId, wsId);
- await briefModel.create({
- agentId: task.assigneeAgentId || undefined,
- priority: 'urgent',
- summary: `Task has been running without heartbeat update for more than ${task.heartbeatTimeout} seconds.`,
- taskId: task.id,
- title: `${task.identifier} heartbeat timeout`,
- trigger: 'task',
- type: 'error',
- });
-
- failed.push(task.identifier);
- }
+ const { checked, failed } = await failStuckTasks(db);
// The heartbeat net above cannot see every stuck Task: it requires a
// configured `heartbeatTimeout`, which schedule and goal tasks do not set. A
@@ -87,13 +63,13 @@ export async function watchdog(c: Context) {
log(
'Watchdog scan: checked=%d failed=%d orphaned=%d callbacks=%d',
- stuckTasks.length,
+ checked,
failed.length,
reconciled.converged.length,
recoveredCallbacks.length,
);
return c.json({
- checked: stuckTasks.length,
+ checked,
failed,
orphaned: reconciled,
recoveredCallbacks,
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index db6bbf3c320..a0ddeb3bb22 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -34,6 +34,7 @@ import {
scheduleTimezoneSchema,
} from '@/server/services/task/scheduleValidation';
import { TaskLifecycleService } from '@/server/services/taskLifecycle';
+import { failStuckTasks } from '@/server/services/taskLifecycle/failStuckTasks';
import { TaskRunnerService } from '@/server/services/taskRunner';
import { AcceptanceService } from '@/server/services/verify/acceptanceService';
import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';
@@ -890,34 +891,10 @@ export const taskRouter = router({
watchdog: taskProcedureWrite.mutation(async ({ ctx }) => {
try {
- const stuckTasks = await TaskModel.findStuckTasks(ctx.serverDB);
- const failed: string[] = [];
-
- for (const task of stuckTasks) {
- const wsId = task.workspaceId ?? undefined;
- const model = new TaskModel(ctx.serverDB, task.createdByUserId, wsId);
- await model.updateStatus(task.id, 'failed', {
- completedAt: new Date(),
- error: 'Heartbeat timeout',
- });
-
- // Create error brief
- const briefModel = new BriefModel(ctx.serverDB, task.createdByUserId, wsId);
- await briefModel.create({
- agentId: task.assigneeAgentId || undefined,
- priority: 'urgent',
- summary: `Task has been running without heartbeat update for more than ${task.heartbeatTimeout} seconds.`,
- taskId: task.id,
- title: `${task.identifier} heartbeat timeout`,
- trigger: 'task',
- type: 'error',
- });
-
- failed.push(task.identifier);
- }
+ const { checked, failed } = await failStuckTasks(ctx.serverDB);
return {
- checked: stuckTasks.length,
+ checked,
failed,
message:
failed.length > 0
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/dispatch/resolveResponseLanguage.ts b/apps/server/src/services/agentSignal/services/selfIteration/dispatch/resolveResponseLanguage.ts
new file mode 100644
index 00000000000..f3b677a3690
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/selfIteration/dispatch/resolveResponseLanguage.ts
@@ -0,0 +1,27 @@
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
+
+/**
+ * Resolves the locale a self-iteration run must write user-visible output in.
+ *
+ * Use when:
+ * - A self-iteration handler builds the runtime prompt; proposals, skills and
+ * ideas it produces surface in the owner's inbox and must match their UI
+ * language rather than whatever language the evidence was written in
+ *
+ * Returns:
+ * - The owner's `responseLanguage`, or `undefined` when the lookup fails, so a
+ * settings read error never blocks the run
+ */
+export const resolveSelfIterationResponseLanguage = async (
+ db: LobeChatDatabase,
+ userId: string,
+): Promise<string | undefined> => {
+ try {
+ const { responseLanguage } = await UserModel.getInfoForAIGeneration(db, userId);
+
+ return responseLanguage;
+ } catch {
+ return undefined;
+ }
+};
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts b/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts
index ce5d9ebef8a..cf42f87f826 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/feedback/handler.ts
@@ -8,6 +8,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { defineSourceHandler } from '../../../runtime/middleware';
import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';
+import { resolveSelfIterationResponseLanguage } from '../dispatch/resolveResponseLanguage';
import type { EvidenceRef } from '../types';
import { buildSelfFeedbackIntentSourceId, ReviewRunStatus } from '../types';
@@ -149,6 +150,13 @@ export interface CreateSelfFeedbackIntentSourceHandlerDependencies {
* @default builtin agent default
*/
maxSteps?: number;
+ /**
+ * Resolves the owner's response language for user-visible run output.
+ * Overridable for tests.
+ *
+ * @default reads the user's `responseLanguage` setting
+ */
+ resolveResponseLanguage?: typeof resolveSelfIterationResponseLanguage;
/** Workspace id, threaded so the enqueued run targets the correct workspace. */
workspaceId?: string;
}
@@ -378,10 +386,14 @@ export const createSelfFeedbackIntentSourceHandler = (
};
const timestamp = new Date(source.timestamp).toISOString();
+ const responseLanguage = await (
+ deps.resolveResponseLanguage ?? resolveSelfIterationResponseLanguage
+ )(deps.db, payload.userId);
const prompt = createAgentSignalSelfIterationPrompt({
agentId: payload.agentId,
context: createIntentRuntimeContext({ enrichment, payload, sourceId: source.sourceId }),
mode: 'feedback',
+ responseLanguage,
sourceId: source.sourceId,
userId: payload.userId,
window: { end: timestamp, start: timestamp },
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/reflection/handler.ts b/apps/server/src/services/agentSignal/services/selfIteration/reflection/handler.ts
index 8dca4bfec1c..93bd05ccbac 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/reflection/handler.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/reflection/handler.ts
@@ -8,6 +8,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { defineSourceHandler } from '../../../runtime/middleware';
import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';
+import { resolveSelfIterationResponseLanguage } from '../dispatch/resolveResponseLanguage';
import { buildSelfReflectionSourceId, ReviewRunStatus } from '../types';
/** Runtime scope supported by self-reflection source handlers. */
@@ -131,6 +132,13 @@ export interface CreateSelfReflectionSourceHandlerDependencies {
* @default builtin agent default
*/
maxSteps?: number;
+ /**
+ * Resolves the owner's response language for user-visible run output.
+ * Overridable for tests.
+ *
+ * @default reads the user's `responseLanguage` setting
+ */
+ resolveResponseLanguage?: typeof resolveSelfIterationResponseLanguage;
/** Workspace id, threaded so the enqueued run targets the correct workspace. */
workspaceId?: string;
}
@@ -284,10 +292,14 @@ export const createSelfReflectionSourceHandler = (
const context = await deps.collectContext(toCollectContextInput(payload));
+ const responseLanguage = await (
+ deps.resolveResponseLanguage ?? resolveSelfIterationResponseLanguage
+ )(deps.db, payload.userId);
const prompt = createAgentSignalSelfIterationPrompt({
agentId: payload.agentId,
context,
mode: 'reflection',
+ responseLanguage,
sourceId: source.sourceId,
userId: payload.userId,
window: { end: payload.windowEnd, start: payload.windowStart },
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts
index 814c92769ad..0dfaa378344 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts
@@ -33,9 +33,6 @@ const zhCNBriefText: Record<string, string> = {
'brief.agentSignal.selfReview.applied.summary': '已应用 {{count}} 条夜间回顾更新。',
'brief.agentSignal.selfReview.applied.summary_plural': '已应用 {{count}} 条夜间回顾更新。',
'brief.agentSignal.selfReview.applied.title': '夜间回顾已更新资源',
- 'brief.agentSignal.selfReview.error.heading': '问题',
- 'brief.agentSignal.selfReview.error.summary': '部分夜间回顾内容未能完成。',
- 'brief.agentSignal.selfReview.error.title': '夜间回顾遇到了问题',
'brief.agentSignal.selfReview.ideas.summary': '已保存夜间回顾记录,供后续查看。',
'brief.agentSignal.selfReview.ideas.title': '夜间回顾记录',
'brief.agentSignal.selfReview.proposal.heading': '建议',
@@ -576,9 +573,10 @@ describe('briefSelfReviewService', () => {
/**
* @example
- * Failed nightly runs produce an error brief when there is a user-actionable failure.
+ * Failed nightly runs stay silent: a run failure is not something the user
+ * can decide on, so it must not land in "Needs you".
*/
- it('projects failed nightly outcomes to error briefs', () => {
+ it('does not project failed nightly outcomes to error briefs', () => {
const service = createBriefSelfReviewService();
const brief = service.projectNightlyReviewBrief({
@@ -600,17 +598,7 @@ describe('briefSelfReviewService', () => {
userId: 'user-1',
});
- expect(brief).toMatchObject({
- priority: 'normal',
- type: 'error',
- });
- expect(brief?.metadata).toMatchObject({
- agentSignal: {
- nightlySelfReview: {
- outcome: 'error',
- },
- },
- });
+ expect(brief).toBeUndefined();
});
/**
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts
index 9e96859114c..d3a652af185 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts
@@ -8,9 +8,6 @@ const zhCN: Record<string, string> = {
'brief.agentSignal.selfReview.applied.summary': '已应用 {{count}} 条夜间回顾更新。',
'brief.agentSignal.selfReview.applied.summary_plural': '已应用 {{count}} 条夜间回顾更新。',
'brief.agentSignal.selfReview.applied.title': '夜间回顾已更新资源',
- 'brief.agentSignal.selfReview.error.heading': '问题',
- 'brief.agentSignal.selfReview.error.summary': '部分夜间回顾内容未能完成。',
- 'brief.agentSignal.selfReview.error.title': '夜间回顾遇到了问题',
'brief.agentSignal.selfReview.ideas.summary': '已保存夜间回顾记录,供后续查看。',
'brief.agentSignal.selfReview.ideas.title': '夜间回顾记录',
'brief.agentSignal.selfReview.proposal.heading': '建议',
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
index 5b6134cbf3a..0baf5a4ea2d 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
@@ -174,6 +174,22 @@ describe('nightly review source handler', () => {
});
});
+ it("asks the run to write proposals in the owner's response language", async () => {
+ const resolveResponseLanguage = vi.fn(async () => 'zh-CN');
+ const deps = createDependencies({ resolveResponseLanguage });
+
+ await createNightlyReviewSourceHandler(deps).handle(createReviewSource());
+
+ expect(resolveResponseLanguage).toHaveBeenCalledWith(deps.db, 'user-1');
+ expect(deps.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ prompt: expect.stringContaining(
+ "Write every user-visible field in the user's language (zh-CN)",
+ ),
+ }),
+ );
+ });
+
it('still dispatches when the quota admitted some of the topics', async () => {
const deps = createDependencies({
collectContext: vi.fn(async () => ({
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts
index a39e2605aa3..86ee43ade1c 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/brief.ts
@@ -8,7 +8,7 @@ import type { BriefItem, NewBrief } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import type { EvidenceRef, RunResult } from '../types';
-import { ActionStatus, ReviewRunStatus } from '../types';
+import { ActionStatus } from '../types';
import {
createSelfReviewBriefText,
type SelfReviewBriefTextActionSummaries,
@@ -53,7 +53,7 @@ export interface SelfReviewBriefMetadata {
/** User-local review date in YYYY-MM-DD form. */
localDate: string;
/** Coarse user-visible outcome selected by the projection service. */
- outcome: 'applied' | 'error' | 'ideas' | 'proposal';
+ outcome: 'applied' | 'ideas' | 'proposal';
/** Durable receipt ids linked to this brief. */
receiptIds: string[];
/** Frozen self-review proposal state for approve/dismiss flows. */
@@ -378,13 +378,14 @@ const getReceiptIds = (result: RunResult) => [
];
const getOutcome = (
- result: RunResult,
counts: SelfReviewBriefActionCounts,
ideas: SelfReviewIdea[] = [],
): SelfReviewBriefMetadata['outcome'] | undefined => {
if (counts.proposed > 0) return 'proposal';
if (counts.applied > 0) return 'applied';
- if (counts.failed > 0 || result.status === ReviewRunStatus.Failed) return 'error';
+ // A failed nightly run is housekeeping the user cannot act on, so it no
+ // longer mints an `error` brief in "Needs you"; failures stay in receipts
+ // and traces. Ideas recorded before the failure still surface.
if (ideas.length > 0) return 'ideas';
return;
@@ -529,7 +530,7 @@ export const createBriefSelfReviewService = () => ({
*
* Use when:
* - Nightly review handlers have already executed self-review actions
- * - Noop reviews should remain silent while applied/proposal/error outcomes surface
+ * - Noop and failed reviews stay silent while applied/proposal/ideas outcomes surface
*
* Expects:
* - `result.actions` contains executor-order action results
@@ -542,7 +543,7 @@ export const createBriefSelfReviewService = () => ({
input: ProjectNightlyReviewBriefInput,
): SelfReviewBriefProjection | undefined => {
const actionCounts = countActions(input.result, input.plan);
- const outcome = getOutcome(input.result, actionCounts, input.ideas);
+ const outcome = getOutcome(actionCounts, input.ideas);
if (!outcome) return;
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts
index 115a641738e..050f0f78cc8 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/briefText.ts
@@ -55,7 +55,7 @@ export interface SelfReviewBriefTextInput {
*/
details?: SelfReviewBriefDetails;
/** Coarse outcome selected by the projection service. */
- outcome: 'applied' | 'error' | 'ideas' | 'proposal';
+ outcome: 'applied' | 'ideas' | 'proposal';
/** Locale-aware translator for the `home` namespace. Defaults to English resources. */
t?: SelfReviewBriefTextTranslator;
}
@@ -71,7 +71,7 @@ export interface SelfReviewBriefText {
/** User-visible Daily Brief title. */
title: string;
/** Daily Brief display type. */
- type: 'decision' | 'error' | 'insight';
+ type: 'decision' | 'insight';
}
const defaultTranslate: SelfReviewBriefTextTranslator = (key, options = {}) => {
@@ -156,21 +156,6 @@ export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): Self
};
}
- if (input.outcome === 'error') {
- const summary = t('brief.agentSignal.selfReview.error.summary');
-
- return {
- priority: 'normal',
- summary: withDetails(
- summary,
- t('brief.agentSignal.selfReview.error.heading'),
- input.actionSummaries.failed,
- ),
- title: t('brief.agentSignal.selfReview.error.title'),
- type: 'error',
- };
- }
-
if (input.outcome === 'ideas' && details?.kind === 'ideas') {
return {
priority: 'info',
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts
index 701dd21d48b..a9f457b8815 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts
@@ -12,6 +12,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { AGENT_SIGNAL_DEFAULTS } from '../../../constants';
import { defineSourceHandler } from '../../../runtime/middleware';
import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';
+import { resolveSelfIterationResponseLanguage } from '../dispatch/resolveResponseLanguage';
import { buildNightlyReviewSourceId, ReviewRunStatus } from '../types';
import type { CollectNightlyReviewContextInput, NightlyReviewContext } from './collect';
@@ -110,6 +111,13 @@ export interface CreateNightlyReviewSourceHandlerDependencies {
* @default builtin agent default
*/
maxSteps?: number;
+ /**
+ * Resolves the owner's response language for user-visible run output.
+ * Overridable for tests.
+ *
+ * @default reads the user's `responseLanguage` setting
+ */
+ resolveResponseLanguage?: typeof resolveSelfIterationResponseLanguage;
/** Workspace id, threaded so the enqueued run targets the correct workspace. */
workspaceId?: string;
}
@@ -350,10 +358,14 @@ export const createNightlyReviewSourceHandler = (
};
}
+ const responseLanguage = await (
+ deps.resolveResponseLanguage ?? resolveSelfIterationResponseLanguage
+ )(deps.db, payload.userId);
const prompt = createAgentSignalSelfIterationPrompt({
agentId: payload.agentId,
context,
mode: 'review',
+ responseLanguage,
sourceId: source.sourceId,
userId: payload.userId,
window: {
diff --git a/apps/server/src/services/taskLifecycle/failStuckTasks.ts b/apps/server/src/services/taskLifecycle/failStuckTasks.ts
new file mode 100644
index 00000000000..07ab87d4aeb
--- /dev/null
+++ b/apps/server/src/services/taskLifecycle/failStuckTasks.ts
@@ -0,0 +1,51 @@
+import debug from 'debug';
+
+import { notifyTaskRunFailed } from '@/business/server/task/notifyTaskRunFailed';
+import { TaskModel } from '@/database/models/task';
+import type { LobeChatDatabase } from '@/database/type';
+
+const log = debug('lobe-server:task:fail-stuck-tasks');
+
+/**
+ * Heartbeat net of the task watchdog: marks every Task silent past its
+ * `heartbeatTimeout` as `failed` and tells its owner.
+ *
+ * Use when:
+ * - A watchdog sweep (cron workflow or the manual tRPC trigger) runs
+ *
+ * Returns:
+ * - How many Tasks were checked and the identifiers that were failed
+ */
+export const failStuckTasks = async (
+ db: LobeChatDatabase,
+): Promise<{ checked: number; failed: string[] }> => {
+ const stuckTasks = await TaskModel.findStuckTasks(db);
+ const failed: string[] = [];
+
+ for (const task of stuckTasks) {
+ const workspaceId = task.workspaceId ?? undefined;
+ await new TaskModel(db, task.createdByUserId, workspaceId).updateStatus(task.id, 'failed', {
+ completedAt: new Date(),
+ error: 'Heartbeat timeout',
+ });
+
+ // A timeout is a failure, not a decision: tell the owner through the
+ // notification center instead of a "Needs you" error brief. Fire-and-forget
+ // through the `@/business` slot so a notification failure never stops the sweep.
+ void notifyTaskRunFailed({
+ agentId: task.assigneeAgentId || undefined,
+ reason: 'heartbeat_timeout',
+ taskId: task.id,
+ taskIdentifier: task.identifier,
+ taskName: task.name ?? undefined,
+ userId: task.createdByUserId,
+ workspaceId,
+ }).catch((error) =>
+ log('failure notification failed for task=%s (non-fatal): %O', task.identifier, error),
+ );
+
+ failed.push(task.identifier);
+ }
+
+ return { checked: stuckTasks.length, failed };
+};
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 0c14fb5c48b..ffb58289b00 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -1,6 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { BRANDING_URL } from '@lobechat/business-const';
import { TRACING_SCENARIOS } from '@lobechat/const';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
import {
@@ -18,7 +17,6 @@ import {
TASK_TOPIC_HANDOFF_SCHEMA_NAME,
} from '@lobechat/prompts';
import type {
- BriefAction,
BriefArtifacts,
BriefDecision,
TaskItem,
@@ -27,13 +25,14 @@ import type {
TaskSchedulerContext,
TaskTopicHandoff,
} from '@lobechat/types';
-import { ChatErrorType, DEFAULT_BRIEF_ACTIONS, RequestTrigger } from '@lobechat/types';
+import { DEFAULT_BRIEF_ACTIONS, RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import {
notifyScheduledTaskCompleted,
notifyScheduledTaskFailed,
} from '@/business/server/task/notifyScheduledTaskResult';
+import { notifyTaskRunFailed } from '@/business/server/task/notifyTaskRunFailed';
import { BriefModel } from '@/database/models/brief';
import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
@@ -41,7 +40,6 @@ import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
-import { translation } from '@/libs/i18n/serverTranslation';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';
import { getLLMGenerationTracingService } from '@/server/services/llmGenerationTracing';
@@ -80,20 +78,9 @@ const isTerminal = (status: string) => TERMINAL_STATUSES.has(status);
// for now; move to task.config later if it needs to be tunable per-task.
const AUTOMATION_FAILURE_FUSE = 3;
-// Terminal error codes whose fix lives in billing, not in a retry — running the
-// same task again just reproduces the same wall. For these the error brief leads
-// with an "Upgrade" remedy instead of a futile Retry (ux Feedback §4.2).
-// Everything else keeps the default retry + feedback actions.
-const BILLING_ERROR_CODES = new Set<string>([
- ChatErrorType.InsufficientBudgetForModel,
- ChatErrorType.FreePlanLimit,
- ChatErrorType.SubscriptionPlanLimit,
- ChatErrorType.WorkspaceSubscriptionInactive,
-]);
-
export interface TopicCompleteParams {
/** Structured terminal error type (e.g. `InsufficientBudgetForModel`) from the
- * completion lifecycle event, used to pick the error brief's remedy action. */
+ * completion lifecycle event, forwarded to the failure notification. */
errorCode?: string;
errorMessage?: string;
lastAssistantContent?: string;
@@ -347,78 +334,6 @@ export class TaskLifecycleService {
const errorText = errorMessage || 'Unknown error';
- // A budget / plan failure won't clear on a blind Retry — lead the card with
- // the fix (Upgrade → plans page) instead. Other causes keep retry + feedback.
- const isBillingError = errorCode ? BILLING_ERROR_CODES.has(errorCode) : false;
- const errorActions: BriefAction[] =
- isBillingError && BRANDING_URL.subscription
- ? [
- {
- key: 'upgrade',
- label: 'Upgrade plan',
- type: 'link',
- url: BRANDING_URL.subscription,
- },
- { key: 'feedback', label: '💬 Feedback', type: 'comment' },
- ]
- : DEFAULT_BRIEF_ACTIONS['error'];
-
- // Resolve the user-facing copy in the user's language, at the source (not
- // by string-munging on the client):
- // - title: a plain localized "run failed" — the task identity already sits
- // in the card's meta row, so the headline needn't repeat it.
- // - summary: map the structured error code to the same human, localized
- // message the chat error card shows. The copy for a code lives in exactly
- // one of two namespaces — `modelRuntime:<code>` (runtime codes) or
- // `error:response.<code>` (HTTP status / Cloud ChatErrorType such as
- // `InsufficientBudgetForModel`) — so try both and take whichever resolves
- // (the server `t` returns the key unchanged when it has no entry). Fall
- // back to the raw runtime message for codes with no friendly copy, or copy
- // left with an unresolved `{{…}}` placeholder we can't fill here.
- const locale = await this.systemAgentService.getUserLocale();
- const [{ t: tHome }, { t: tRuntime }, { t: tError }] = await Promise.all([
- translation('home', locale),
- translation('modelRuntime', locale),
- translation('error', locale),
- ]);
- const resolveErrorSummary = () => {
- if (!errorCode) return errorText;
- const runtimeMsg = tRuntime(errorCode);
- if (runtimeMsg !== errorCode && !runtimeMsg.includes('{{')) return runtimeMsg;
- const responseKey = `response.${errorCode}`;
- const responseMsg = tError(responseKey);
- if (responseMsg !== responseKey && !responseMsg.includes('{{')) return responseMsg;
- return errorText;
- };
- const summary = resolveErrorSummary();
-
- // Always surface an urgent error brief — a failed run is visible to the
- // user regardless of what happens to the scheduling state below. The topic
- // id rides the structured `topicId` field (it also powers the card's
- // "View run" shortcut), never the headline.
- // A Goal Task's failed run is the coordinator's to recover: it retries,
- // reroutes or opens a decision gate, and that gate is the brief the
- // person gets. An urgent error card per failed run asked them to act on
- // something the goal was already handling — the same reason Goal rounds
- // never synthesize result briefs above. Only runs the coordinator
- // dispatched count: a manual rerun of a Task kept under a paused or
- // finished goal has nobody recovering it, so its failure still surfaces.
- const coordinatedByGoal = params.runTrigger === 'goal';
- if (!coordinatedByGoal)
- await this.briefModel.create({
- actions: errorActions,
- agentId: currentTask?.assigneeAgentId || undefined,
- // Persist the structured cause for observability / future remedy mapping.
- metadata: errorCode ? { error: { code: errorCode } } : undefined,
- priority: 'urgent',
- summary,
- taskId,
- title: tHome('inbox.error.title'),
- topicId,
- trigger: 'task',
- type: 'error',
- });
-
const runTrigger = params.runTrigger ?? 'manual';
const isAutomationTick = runTrigger === 'schedule' || runTrigger === 'heartbeat';
@@ -490,28 +405,53 @@ export class TaskLifecycleService {
await this.taskModel.updateStatus(taskId, 'scheduled', { error: errorText });
}
- // Tell the user their automation failed: fire-and-forget through the
- // `@/business` slot (default impl is a no-op; a notification failure
- // must never affect the task lifecycle). Manual "run now" failures are
- // ad-hoc debug runs — the error brief above already covers them, and
- // they are not an automation-health signal, so only automation ticks
- // notify. Heartbeat ticks can fire every few seconds, so they only
- // notify at the fuse-stop moment (the automation stopped re-arming);
- // low-frequency scheduled ticks notify on every failure. Only the
- // structured `errorCode` crosses the slot boundary; raw error text
- // stays in the brief.
- if (
- currentTask?.automationMode &&
- isAutomationTick &&
- (runTrigger === 'schedule' || pausedByFuse)
- ) {
- void notifyScheduledTaskFailed({
+ // Tell the user the run failed through the notification center — failures
+ // are not decisions, so they no longer mint a "Needs you" error brief.
+ // Fire-and-forget through the `@/business` slots (default impls are
+ // no-ops; a notification failure must never affect the task lifecycle).
+ // Only the structured `errorCode` crosses the slot boundary; raw error
+ // text stays on the task.
+ // - A Goal Task's failed run is the coordinator's to recover: it retries,
+ // reroutes or opens a decision gate, and that gate is what the person
+ // gets. Only runs the coordinator dispatched count: a manual rerun of a
+ // Task kept under a paused or finished goal has nobody recovering it.
+ // - Automation ticks report as automation health: heartbeat ticks can
+ // fire every few seconds, so they only notify at the fuse-stop moment;
+ // low-frequency scheduled ticks notify on every failure.
+ // - Everything else (manual runs, ad-hoc tasks) notifies once per run.
+ const coordinatedByGoal = runTrigger === 'goal';
+ if (coordinatedByGoal || !currentTask) {
+ // The goal coordinator owns recovery and the user-facing decision; a
+ // task deleted mid-run has no page left to link to.
+ } else if (currentTask.automationMode && isAutomationTick) {
+ if (runTrigger === 'schedule' || pausedByFuse) {
+ void notifyScheduledTaskFailed({
+ agentId: currentTask.assigneeAgentId ?? undefined,
+ consecutiveFailures: scheduleConsecutiveFailures,
+ errorCode,
+ operationId: params.operationId,
+ paused: pausedByFuse,
+ runTrigger: runTrigger === 'schedule' ? 'schedule' : 'heartbeat',
+ taskId,
+ taskIdentifier,
+ taskName: currentTask.name ?? undefined,
+ topicId,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ }).catch((error) =>
+ log(
+ 'scheduled-task failure notification failed for task=%s (non-fatal): %O',
+ taskIdentifier,
+ error,
+ ),
+ );
+ }
+ } else {
+ void notifyTaskRunFailed({
agentId: currentTask.assigneeAgentId ?? undefined,
- consecutiveFailures: scheduleConsecutiveFailures,
errorCode,
operationId: params.operationId,
- paused: pausedByFuse,
- runTrigger: runTrigger === 'schedule' ? 'schedule' : 'heartbeat',
+ reason: 'error',
taskId,
taskIdentifier,
taskName: currentTask.name ?? undefined,
@@ -520,7 +460,7 @@ export class TaskLifecycleService {
workspaceId: this.workspaceId,
}).catch((error) =>
log(
- 'scheduled-task failure notification failed for task=%s (non-fatal): %O',
+ 'task-run failure notification failed for task=%s (non-fatal): %O',
taskIdentifier,
error,
),
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index 693af5d577a..022e649b6ce 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -41,17 +41,6 @@ vi.mock('@/database/models/goal', () => ({
}),
}));
-// Error-brief copy is localized at the source via the server translator; mock it
-// with a tiny table so the error-branch tests can assert both the friendly-copy
-// mapping (a known error code → its human message) and the raw-message fallback
-// (unknown code → the key is returned unchanged, so the code falls back).
-const FAKE_MESSAGES: Record<string, string> = {
- 'response.InsufficientBudgetForModel': 'Not enough credits — top up or upgrade to continue.',
-};
-vi.mock('@/libs/i18n/serverTranslation', () => ({
- translation: async () => ({ t: (key: string) => FAKE_MESSAGES[key] ?? key }),
-}));
-
// Scheduled-task result notifications go through the `@/business` slot
// (default impl is a no-op). Mock both hooks so the tests can assert exactly
// when the lifecycle recalls the user.
@@ -61,6 +50,10 @@ vi.mock('@/business/server/task/notifyScheduledTaskResult', () => ({
notifyScheduledTaskCompleted: (...args: unknown[]) => notifyCompleted(...args),
notifyScheduledTaskFailed: (...args: unknown[]) => notifyFailed(...args),
}));
+const notifyRunFailed = vi.fn().mockResolvedValue(undefined);
+vi.mock('@/business/server/task/notifyTaskRunFailed', () => ({
+ notifyTaskRunFailed: (...args: unknown[]) => notifyRunFailed(...args),
+}));
const baseTask = (overrides: Partial<TaskItem> = {}): TaskItem =>
({
@@ -93,6 +86,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
fakeScheduler.scheduleNextTopic.mockClear().mockResolvedValue('msg-new');
notifyCompleted.mockReset().mockResolvedValue(undefined);
notifyFailed.mockReset().mockResolvedValue(undefined);
+ notifyRunFailed.mockReset().mockResolvedValue(undefined);
cascadeOnCompletion.mockReset().mockResolvedValue({ failed: [], paused: [], started: [] });
service = new TaskLifecycleService({} as any, 'user-1');
@@ -727,12 +721,14 @@ describe('TaskLifecycleService.onTopicComplete', () => {
);
});
- it('every error branch still emits an urgent error brief', async () => {
- const task = baseTask({ automationMode: 'schedule' });
- findById.mockResolvedValue(task);
+ // Failures are not decisions: they go to the notification center, never to
+ // a "Needs you" error brief.
+ it('a failed run notifies instead of creating an error brief', async () => {
+ findById.mockResolvedValue(baseTask({ automationMode: null }));
await service.onTopicComplete({
- errorMessage: 'boom',
+ errorCode: 'InsufficientBudgetForModel',
+ errorMessage: 'Workspace budget exceeded',
operationId: 'op-1',
reason: 'error',
runTrigger: 'manual',
@@ -741,83 +737,50 @@ describe('TaskLifecycleService.onTopicComplete', () => {
topicId: 'topic-1',
});
- expect(createBrief).toHaveBeenCalledWith(
- expect.objectContaining({ priority: 'urgent', type: 'error' }),
- );
- });
-
- // A Goal Task's failed run is the coordinator's to recover, and the gate it
- // opens is the brief the person gets. An urgent error card per failed run
- // asked them to act on something the goal was already handling.
- it('leaves a Goal Task failure to the coordinator instead of an error brief', async () => {
- const task = baseTask({ automationMode: null });
- findById.mockResolvedValue(task);
-
- await service.onTopicComplete({
- errorMessage: 'boom',
- operationId: 'op-1',
- reason: 'error',
- runTrigger: 'goal',
- taskId: 'task-1',
- taskIdentifier: 'TASK-1',
- topicId: 'topic-1',
- });
-
expect(createBrief).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));
- });
-
- // Only the coordinator's own runs are recovered by it: a manual rerun of a
- // Task kept under a paused or finished goal has nobody watching it.
- it('still sends the error brief for a manual rerun of a Goal Task', async () => {
- const task = baseTask({ automationMode: null });
- findById.mockResolvedValue(task);
-
- await service.onTopicComplete({
- errorMessage: 'boom',
+ // Only the structured code crosses the slot — raw error text stays on the task.
+ expect(notifyRunFailed).toHaveBeenCalledWith({
+ agentId: undefined,
+ errorCode: 'InsufficientBudgetForModel',
operationId: 'op-1',
reason: 'error',
- runTrigger: 'manual',
taskId: 'task-1',
taskIdentifier: 'TASK-1',
+ taskName: 'demo',
topicId: 'topic-1',
+ userId: 'user-1',
+ workspaceId: undefined,
});
-
- expect(createBrief).toHaveBeenCalledWith(
- expect.objectContaining({ priority: 'urgent', type: 'error' }),
- );
});
- it('error brief keeps internal ids out of the user-facing copy', async () => {
- const task = baseTask({ automationMode: 'schedule' });
- findById.mockResolvedValue(task);
+ // A Goal Task's failed run is the coordinator's to recover, and the gate it
+ // opens is what the person gets — a failure notification per run would ask
+ // them to act on something the goal was already handling.
+ it('leaves a Goal Task failure to the coordinator', async () => {
+ findById.mockResolvedValue(baseTask({ automationMode: null }));
await service.onTopicComplete({
- errorMessage: 'Workspace budget exceeded',
+ errorMessage: 'boom',
operationId: 'op-1',
reason: 'error',
- runTrigger: 'manual',
+ runTrigger: 'goal',
taskId: 'task-1',
taskIdentifier: 'TASK-1',
topicId: 'topic-1',
});
- const brief = createBrief.mock.calls.at(-1)?.[0];
- // Title/summary are human-facing: no raw topic id, no "topic #N", no
- // "Execution failed:" log framing. The topic id lives on `topicId`.
- expect(brief.title).not.toContain('topic-1');
- expect(brief.title).not.toMatch(/topic #/i);
- expect(brief.summary).not.toMatch(/execution failed/i);
- expect(brief.summary).toBe('Workspace budget exceeded');
- expect(brief.topicId).toBe('topic-1');
+ expect(createBrief).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));
+ expect(notifyRunFailed).not.toHaveBeenCalled();
+ expect(notifyFailed).not.toHaveBeenCalled();
});
- it('a budget error leads with an upgrade remedy instead of a futile retry', async () => {
- const task = baseTask({ automationMode: 'schedule' });
- findById.mockResolvedValue(task);
+ // Only the coordinator's own runs are recovered by it: a manual rerun of a
+ // Task kept under a paused or finished goal has nobody watching it.
+ it('still notifies for a manual rerun of a Goal Task', async () => {
+ findById.mockResolvedValue(baseTask({ automationMode: null }));
await service.onTopicComplete({
- errorCode: 'InsufficientBudgetForModel',
- errorMessage: 'Workspace budget exceeded',
+ errorMessage: 'boom',
operationId: 'op-1',
reason: 'error',
runTrigger: 'manual',
@@ -826,28 +789,14 @@ describe('TaskLifecycleService.onTopicComplete', () => {
topicId: 'topic-1',
});
- const brief = createBrief.mock.calls.at(-1)?.[0];
- const keys = brief.actions.map((a: { key: string }) => a.key);
- // Retrying a budget failure just re-fails — offer the fix, not Retry.
- expect(keys).toContain('upgrade');
- expect(keys).not.toContain('retry');
- const upgrade = brief.actions.find((a: { key: string }) => a.key === 'upgrade');
- expect(upgrade.type).toBe('link');
- expect(upgrade.url).toBeTruthy();
- // Structured cause persisted for observability / future mapping.
- expect(brief.metadata).toEqual({ error: { code: 'InsufficientBudgetForModel' } });
- // Summary is the human, localized message mapped from the error code — not
- // the raw provider string.
- expect(brief.summary).toBe('Not enough credits — top up or upgrade to continue.');
+ expect(notifyRunFailed).toHaveBeenCalledOnce();
});
- it('a non-billing error keeps the default retry action', async () => {
- const task = baseTask({ automationMode: 'schedule' });
- findById.mockResolvedValue(task);
+ it('does not notify for a task deleted mid-run', async () => {
+ findById.mockResolvedValue(null);
await service.onTopicComplete({
- errorCode: 'ProviderBizError',
- errorMessage: 'upstream 500',
+ errorMessage: 'boom',
operationId: 'op-1',
reason: 'error',
runTrigger: 'manual',
@@ -856,10 +805,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
topicId: 'topic-1',
});
- const brief = createBrief.mock.calls.at(-1)?.[0];
- const keys = brief.actions.map((a: { key: string }) => a.key);
- expect(keys).toContain('retry');
- expect(keys).not.toContain('upgrade');
+ expect(notifyRunFailed).not.toHaveBeenCalled();
});
});
@@ -1020,7 +966,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
);
});
- it('manual failure of an automation task → NO failed notification (ad-hoc debug run)', async () => {
+ it('manual failure of an automation task → run-failed notification, not an automation one', async () => {
findById.mockResolvedValue(baseTask({ automationMode: 'schedule' }));
await service.onTopicComplete({
@@ -1034,6 +980,9 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
expect(notifyFailed).not.toHaveBeenCalled();
+ expect(notifyRunFailed).toHaveBeenCalledWith(
+ expect.objectContaining({ reason: 'error', taskId: 'task-1' }),
+ );
});
it('transient heartbeat tick failure → NO notification (high-frequency ticks)', async () => {
diff --git a/locales/en-US/home.json b/locales/en-US/home.json
index de436fcafd8..33fe5a172ce 100644
--- a/locales/en-US/home.json
+++ b/locales/en-US/home.json
@@ -25,10 +25,14 @@
"brief.agentSignal.selfReview.applied.summary": "{{count}} dream update was applied.",
"brief.agentSignal.selfReview.applied.summary_plural": "{{count}} dream updates were applied.",
"brief.agentSignal.selfReview.applied.title": "Dream updated resources",
+ "brief.agentSignal.selfReview.detail.body": "Skill content",
+ "brief.agentSignal.selfReview.detail.description": "Description",
+ "brief.agentSignal.selfReview.detail.memory": "Memory to save",
+ "brief.agentSignal.selfReview.detail.open": "View details",
+ "brief.agentSignal.selfReview.detail.rationale": "Why",
+ "brief.agentSignal.selfReview.detail.systemRole": "New system prompt",
+ "brief.agentSignal.selfReview.detail.title": "Suggestion details",
"brief.agentSignal.selfReview.details.forAgent": "For {{agent}}",
- "brief.agentSignal.selfReview.error.heading": "Issue",
- "brief.agentSignal.selfReview.error.summary": "Some work could not be completed during this dream.",
- "brief.agentSignal.selfReview.error.title": "Dream ran into an issue",
"brief.agentSignal.selfReview.ideas.summary": "Saved dream notes for future review.",
"brief.agentSignal.selfReview.ideas.title": "Dream notes",
"brief.agentSignal.selfReview.kind.consolidate_skill.plain": "Merge skills",
@@ -139,7 +143,6 @@
"homePromoBanner.dismiss": "Dismiss",
"homePromoBanner.label": "{{model}} is now available",
"inbox.author.scheduled": "Scheduled",
- "inbox.error.title": "Run failed",
"inbox.goals.review": "Needs your decision",
"inbox.goals.running": "In progress",
"inbox.goals.showAll": "Show all {{count}}",
diff --git a/locales/en-US/notification.json b/locales/en-US/notification.json
index f3a817e0e90..7d394077e1a 100644
--- a/locales/en-US/notification.json
+++ b/locales/en-US/notification.json
@@ -11,6 +11,12 @@
"agent_intervention_required_title": "{{agent}} needs your review",
"agent_run_completed": "{{preview}}",
"agent_run_completed_title": "Agent task completed",
+ "agent_task_run_failed": "Your task \"{{jobName}}\" failed. Open the task to see the full error.",
+ "agent_task_run_failed_heartbeat_timeout": "Your task \"{{jobName}}\" stopped responding and was marked as failed. Open the task to run it again.",
+ "agent_task_run_failed_heartbeat_timeout_title": "Task timed out",
+ "agent_task_run_failed_insufficient_budget": "Your task \"{{jobName}}\" couldn't run because your account is out of credits. Top up or upgrade your plan to continue.",
+ "agent_task_run_failed_insufficient_budget_title": "Task failed: insufficient credits",
+ "agent_task_run_failed_title": "Task failed",
"agent_transfer_reassigned": "A workspace owner transferred your agent \"{{agentTitle}}\" to {{recipientLabel}}.",
"agent_transfer_reassigned_title": "Agent reassigned",
"agent_transfer_requested": "{{actorLabel}} wants to transfer the agent \"{{agentTitle}}\" to you. Accept or decline it from Notifications.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 54ea1fb138d..eaef4b84c26 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -976,6 +976,7 @@
"notification.item.agent_cron_job_completed": "Scheduled task completed",
"notification.item.agent_cron_job_failed": "Scheduled task failed",
"notification.item.agent_run_completed": "Agent task completed",
+ "notification.item.agent_task_run_failed": "Task failed",
"notification.item.agent_transfer_result": "Transfer request result",
"notification.item.checkout_abandoned": "Unfinished checkout reminders",
"notification.item.credit_balance_low": "Credit balance running low",
diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.json
index e81fcafd9c4..719d8f856c0 100644
--- a/locales/zh-CN/home.json
+++ b/locales/zh-CN/home.json
@@ -25,10 +25,14 @@
"brief.agentSignal.selfReview.applied.summary": "已应用 {{count}} 条夜间回顾更新。",
"brief.agentSignal.selfReview.applied.summary_plural": "已应用 {{count}} 条夜间回顾更新。",
"brief.agentSignal.selfReview.applied.title": "夜间回顾已更新资源",
+ "brief.agentSignal.selfReview.detail.body": "技能内容",
+ "brief.agentSignal.selfReview.detail.description": "描述",
+ "brief.agentSignal.selfReview.detail.memory": "将保存的记忆",
+ "brief.agentSignal.selfReview.detail.open": "查看详情",
+ "brief.agentSignal.selfReview.detail.rationale": "原因",
+ "brief.agentSignal.selfReview.detail.systemRole": "新的系统提示词",
+ "brief.agentSignal.selfReview.detail.title": "建议详情",
"brief.agentSignal.selfReview.details.forAgent": "适用于助理「{{agent}}」",
- "brief.agentSignal.selfReview.error.heading": "问题",
- "brief.agentSignal.selfReview.error.summary": "部分夜间回顾内容未能完成。",
- "brief.agentSignal.selfReview.error.title": "夜间回顾遇到了问题",
"brief.agentSignal.selfReview.ideas.summary": "已保存夜间回顾记录,供后续查看。",
"brief.agentSignal.selfReview.ideas.title": "夜间回顾记录",
"brief.agentSignal.selfReview.kind.consolidate_skill.plain": "合并技能",
@@ -139,7 +143,6 @@
"homePromoBanner.dismiss": "关闭",
"homePromoBanner.label": "{{model}} 现已上线",
"inbox.author.scheduled": "定时触发",
- "inbox.error.title": "运行失败",
"inbox.goals.review": "等你决定",
"inbox.goals.running": "进行中",
"inbox.goals.showAll": "查看全部 {{count}} 个",
diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.json
index f78d36de38b..ef8e248ff3e 100644
--- a/locales/zh-CN/notification.json
+++ b/locales/zh-CN/notification.json
@@ -11,6 +11,12 @@
"agent_intervention_required_title": "{{agent}} 等待你的审核",
"agent_run_completed": "{{preview}}",
"agent_run_completed_title": "Agent 任务已完成",
+ "agent_task_run_failed": "任务「{{jobName}}」执行失败,点击查看详情。",
+ "agent_task_run_failed_heartbeat_timeout": "任务「{{jobName}}」长时间无响应,已标记为失败。打开任务可重新运行。",
+ "agent_task_run_failed_heartbeat_timeout_title": "任务超时",
+ "agent_task_run_failed_insufficient_budget": "任务「{{jobName}}」因账户额度不足未能执行。请充值或升级套餐后继续。",
+ "agent_task_run_failed_insufficient_budget_title": "任务失败:额度不足",
+ "agent_task_run_failed_title": "任务执行失败",
"agent_transfer_reassigned": "工作区所有者已将您的代理 \"{{agentTitle}}\" 转移至 {{recipientLabel}}。",
"agent_transfer_reassigned_title": "代理已重新分配",
"agent_transfer_requested": "{{actorLabel}} 希望将代理 \"{{agentTitle}}\" 转移给您。请在通知中接受或拒绝。",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 22a3bd7b56d..916d7b11849 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -976,6 +976,7 @@
"notification.item.agent_cron_job_completed": "计划任务成功",
"notification.item.agent_cron_job_failed": "计划任务失败",
"notification.item.agent_run_completed": "Agent 任务完成",
+ "notification.item.agent_task_run_failed": "任务失败",
"notification.item.agent_transfer_result": "转移请求结果",
"notification.item.checkout_abandoned": "未完成付款提醒",
"notification.item.credit_balance_low": "积分余额即将用尽",
diff --git a/packages/agent-signal/src/brief/index.ts b/packages/agent-signal/src/brief/index.ts
index 7b33eebbccf..a21e8dc6aaf 100644
--- a/packages/agent-signal/src/brief/index.ts
+++ b/packages/agent-signal/src/brief/index.ts
@@ -1 +1,2 @@
export * from './selfReviewBriefDetails';
+export * from './selfReviewProposalContent';
diff --git a/packages/agent-signal/src/brief/selfReviewProposalContent.test.ts b/packages/agent-signal/src/brief/selfReviewProposalContent.test.ts
new file mode 100644
index 00000000000..e080419e05e
--- /dev/null
+++ b/packages/agent-signal/src/brief/selfReviewProposalContent.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getSelfReviewProposalContent,
+ hasSelfReviewProposalContent,
+} from './selfReviewProposalContent';
+
+const withActions = (actions: unknown[]) => ({
+ agentSignal: { nightlySelfReview: { selfReviewProposal: { actions } } },
+});
+
+describe('getSelfReviewProposalContent', () => {
+ it('reads the full create_skill input', () => {
+ const items = getSelfReviewProposalContent(
+ withActions([
+ {
+ actionType: 'create_skill',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: '# Preflight\n\n- Check the cwd',
+ description: 'Checks before running commands.',
+ name: 'command-preflight',
+ title: 'Command Execution Preflight',
+ userId: 'user-1',
+ },
+ operation: 'create',
+ },
+ rationale: 'Commands kept failing on a wrong cwd.',
+ },
+ ]),
+ );
+
+ expect(items).toEqual([
+ {
+ bodyMarkdown: '# Preflight\n\n- Check the cwd',
+ description: 'Checks before running commands.',
+ kind: 'create_skill',
+ name: 'command-preflight',
+ rationale: 'Commands kept failing on a wrong cwd.',
+ title: 'Command Execution Preflight',
+ },
+ ]);
+ });
+
+ it('reads refine_skill, refine_prompt and write_memory content with their targets', () => {
+ const items = getSelfReviewProposalContent(
+ withActions([
+ {
+ actionType: 'refine_skill',
+ baseSnapshot: { skillName: 'pr-checklist', targetTitle: 'PR checklist' },
+ operation: {
+ domain: 'skill',
+ input: { bodyMarkdown: 'New body', skillDocumentId: 'doc-1', userId: 'u' },
+ operation: 'refine',
+ },
+ rationale: 'Missing steps.',
+ },
+ {
+ actionType: 'refine_prompt',
+ operation: {
+ domain: 'agent',
+ input: { agentId: 'agt', systemRole: 'You are concise.', userId: 'u' },
+ operation: 'refine_prompt',
+ },
+ rationale: 'Too verbose.',
+ },
+ {
+ actionType: 'write_memory',
+ operation: {
+ domain: 'memory',
+ input: { content: 'Prefers pnpm.', userId: 'u' },
+ operation: 'write',
+ },
+ rationale: 'Stated twice.',
+ },
+ ]),
+ );
+
+ expect(items).toEqual([
+ {
+ bodyMarkdown: 'New body',
+ kind: 'refine_skill',
+ rationale: 'Missing steps.',
+ target: 'PR checklist',
+ },
+ { kind: 'refine_prompt', rationale: 'Too verbose.', systemRole: 'You are concise.' },
+ { kind: 'write_memory', memoryContent: 'Prefers pnpm.', rationale: 'Stated twice.' },
+ ]);
+ });
+
+ it('skips noop and proposal_only actions and maps unknown types to other', () => {
+ const items = getSelfReviewProposalContent(
+ withActions([
+ { actionType: 'noop' },
+ { actionType: 'proposal_only', rationale: 'idea' },
+ { actionType: 'future_action', rationale: 'Something new.' },
+ ]),
+ );
+
+ expect(items).toEqual([{ kind: 'other', rationale: 'Something new.' }]);
+ });
+
+ it('tolerates missing or malformed metadata', () => {
+ expect(getSelfReviewProposalContent(undefined)).toEqual([]);
+ expect(getSelfReviewProposalContent({ agentSignal: 'x' })).toEqual([]);
+ expect(
+ getSelfReviewProposalContent({
+ agentSignal: { nightlySelfReview: { selfReviewProposal: { actions: 'x' } } },
+ }),
+ ).toEqual([]);
+ expect(
+ getSelfReviewProposalContent(withActions([{ actionType: 'create_skill', operation: 5 }])),
+ ).toEqual([{ kind: 'create_skill' }]);
+ });
+});
+
+describe('hasSelfReviewProposalContent', () => {
+ it('is true only when an item has text beyond the card rows', () => {
+ expect(hasSelfReviewProposalContent([])).toBe(false);
+ expect(hasSelfReviewProposalContent([{ kind: 'create_skill', rationale: 'why' }])).toBe(false);
+ expect(hasSelfReviewProposalContent([{ bodyMarkdown: '# x', kind: 'create_skill' }])).toBe(
+ true,
+ );
+ expect(hasSelfReviewProposalContent([{ kind: 'refine_prompt', systemRole: 'Be brief.' }])).toBe(
+ true,
+ );
+ });
+});
diff --git a/packages/agent-signal/src/brief/selfReviewProposalContent.ts b/packages/agent-signal/src/brief/selfReviewProposalContent.ts
new file mode 100644
index 00000000000..a25fb70eebe
--- /dev/null
+++ b/packages/agent-signal/src/brief/selfReviewProposalContent.ts
@@ -0,0 +1,121 @@
+/**
+ * Full content of a nightly self-review proposal, for the "view details" view.
+ *
+ * `selfReviewBriefDetails` reduces each proposed action to a one-line row. Before
+ * approving, a reader also needs what the action would actually write: the skill
+ * body, the replacement system prompt, the memory text. The frozen proposal in
+ * the brief metadata (`metadata.agentSignal.nightlySelfReview.selfReviewProposal`)
+ * already carries each action's `operation.input`, so this module reads it
+ * client-side without another request.
+ */
+import type { SelfReviewBriefDetailKind } from './selfReviewBriefDetails';
+
+/** What one proposed action would write when the proposal is approved. */
+export interface SelfReviewProposalContentItem {
+ /** New skill body (create / refine / consolidate skill), as Markdown. */
+ bodyMarkdown?: string;
+ /** Skill description the action would set. */
+ description?: string;
+ /** What kind of change this action proposes. */
+ kind: Exclude<SelfReviewBriefDetailKind, 'idea'>;
+ /** Memory text a `write_memory` action would save. */
+ memoryContent?: string;
+ /** Stable skill name (slug) a `create_skill` action would reserve. */
+ name?: string;
+ /** Reviewer rationale for the change. */
+ rationale?: string;
+ /** Replacement agent system prompt of a `refine_prompt` action. */
+ systemRole?: string;
+ /** Existing target the action changes, e.g. the refined skill's title. */
+ target?: string;
+ /** Skill title the action would set. */
+ title?: string;
+}
+
+const KNOWN_KINDS = new Set<SelfReviewProposalContentItem['kind']>([
+ 'consolidate_skill',
+ 'create_skill',
+ 'refine_prompt',
+ 'refine_skill',
+ 'write_memory',
+]);
+
+const asRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+
+const pickString = (...values: unknown[]) => {
+ for (const value of values) {
+ if (typeof value !== 'string') continue;
+ const trimmed = value.trim();
+ if (trimmed) return trimmed;
+ }
+};
+
+const toContentItem = (value: unknown): SelfReviewProposalContentItem | undefined => {
+ const action = asRecord(value);
+ const actionType = pickString(action.actionType);
+ if (!actionType || actionType === 'noop' || actionType === 'proposal_only') return;
+
+ const kind = KNOWN_KINDS.has(actionType as SelfReviewProposalContentItem['kind'])
+ ? (actionType as SelfReviewProposalContentItem['kind'])
+ : 'other';
+ const input = asRecord(asRecord(action.operation).input);
+ const snapshot = asRecord(action.baseSnapshot);
+ const target = asRecord(action.target);
+
+ const fields: Omit<SelfReviewProposalContentItem, 'kind'> = {
+ bodyMarkdown: pickString(input.bodyMarkdown),
+ description: pickString(input.description),
+ memoryContent: kind === 'write_memory' ? pickString(input.content) : undefined,
+ name: kind === 'create_skill' ? pickString(input.name, target.skillName) : undefined,
+ rationale: pickString(action.rationale),
+ systemRole: pickString(input.systemRole),
+ // A created skill has no existing target; its title/name describe it.
+ target:
+ kind === 'create_skill' || kind === 'write_memory'
+ ? undefined
+ : pickString(snapshot.targetTitle, target.skillName, snapshot.skillName),
+ title: pickString(input.title),
+ };
+
+ const item: SelfReviewProposalContentItem = { kind };
+ for (const [key, field] of Object.entries(fields) as [keyof typeof fields, string?][]) {
+ if (field) item[key] = field;
+ }
+
+ return item;
+};
+
+/**
+ * Reads what each proposed action of a nightly self-review brief would write.
+ *
+ * Use when:
+ * - A card offers "view details" before the user approves a proposal
+ *
+ * Expects:
+ * - `metadata` is the brief's raw `metadata` JSON (any shape is tolerated)
+ *
+ * Returns:
+ * - One item per executable action, in proposal order; an empty array for
+ * ideas-only briefs, other briefs, or malformed metadata
+ */
+export const getSelfReviewProposalContent = (
+ metadata: unknown,
+): SelfReviewProposalContentItem[] => {
+ const nightly = asRecord(asRecord(asRecord(metadata).agentSignal).nightlySelfReview);
+ const actions = asRecord(nightly.selfReviewProposal).actions;
+ if (!Array.isArray(actions)) return [];
+
+ return actions.flatMap((action) => toContentItem(action) ?? []);
+};
+
+/**
+ * Whether any item carries content worth opening a details view for: text the
+ * one-line card rows cannot show in full.
+ */
+export const hasSelfReviewProposalContent = (items: SelfReviewProposalContentItem[]) =>
+ items.some(
+ (item) => item.bodyMarkdown || item.systemRole || item.memoryContent || item.description,
+ );
diff --git a/packages/business-server/src/task/notifyScheduledTaskResult.ts b/packages/business-server/src/task/notifyScheduledTaskResult.ts
index 5d0edba576f..2ff1aa017d3 100644
--- a/packages/business-server/src/task/notifyScheduledTaskResult.ts
+++ b/packages/business-server/src/task/notifyScheduledTaskResult.ts
@@ -19,7 +19,7 @@ export interface NotifyScheduledTaskFailedParams {
/** Consecutive automation-tick failures including this one (schedule fuse). */
consecutiveFailures?: number;
/** Structured terminal error type (e.g. `InsufficientBudgetForModel`). Never
- * the raw error text — that stays in briefs/logs. */
+ * the raw error text — that stays on the task and in logs. */
errorCode?: string;
operationId: string;
/** True when this failure blew the fuse and auto-paused the task. */
diff --git a/packages/business-server/src/task/notifyTaskRunFailed.ts b/packages/business-server/src/task/notifyTaskRunFailed.ts
new file mode 100644
index 00000000000..8183f8441ab
--- /dev/null
+++ b/packages/business-server/src/task/notifyTaskRunFailed.ts
@@ -0,0 +1,30 @@
+export interface NotifyTaskRunFailedParams {
+ /** Agent executing the task — lets inbox surfaces render its avatar. */
+ agentId?: string;
+ /** Structured terminal error type (e.g. `InsufficientBudgetForModel`). Never
+ * the raw error text — that stays on the task and in logs. */
+ errorCode?: string;
+ /** Run that failed; absent for watchdog sweeps that never saw the run end. */
+ operationId?: string;
+ /**
+ * Why the run is considered failed:
+ * - `error`: the run ended with an error
+ * - `heartbeat_timeout`: the watchdog found the task silent past its heartbeat timeout
+ */
+ reason: 'error' | 'heartbeat_timeout';
+ taskId: string;
+ /** Workspace-level task identifier (e.g. 'T-1'), used as the name fallback. */
+ taskIdentifier: string;
+ taskName?: string;
+ topicId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Tells the owner a task run failed outside an automation tick (manual runs,
+ * ad-hoc tasks, watchdog timeouts). Failures go to the notification center
+ * instead of a "Needs you" error brief. Default impl is a no-op; callers fire
+ * it and forget, so a notification failure never affects the task.
+ */
+export async function notifyTaskRunFailed(_params: NotifyTaskRunFailedParams): Promise<void> {}
diff --git a/packages/database/src/models/__tests__/brief.test.ts b/packages/database/src/models/__tests__/brief.test.ts
index 19bddac10c7..c4bdd85fb94 100644
--- a/packages/database/src/models/__tests__/brief.test.ts
+++ b/packages/database/src/models/__tests__/brief.test.ts
@@ -203,6 +203,17 @@ describe('BriefModel', () => {
expect(rows[1].brief.priority).toBe('normal');
});
+ // Run failures go to the notification center; legacy error rows must not
+ // take "Needs you" slots (they are urgent, so they would sort first).
+ it('should leave error briefs out of the home feed', async () => {
+ const model = new BriefModel(serverDB, userId);
+ await model.create({ priority: 'urgent', summary: 'x', title: 'Failed', type: 'error' });
+ await model.create({ priority: 'normal', summary: 'y', title: 'Decide', type: 'decision' });
+
+ const rows = await model.listUnresolvedEnriched();
+ expect(rows.map((row) => row.brief.title)).toEqual(['Decide']);
+ });
+
it('should join the producing agent and parent task status in one query', async () => {
await serverDB.insert(agents).values({
avatar: '🤖',
diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.ts
index 4d09d835f57..bc44da91d74 100644
--- a/packages/database/src/models/brief.ts
+++ b/packages/database/src/models/brief.ts
@@ -1,4 +1,4 @@
-import { NEWS_BRIEF_TYPES } from '@lobechat/types';
+import { HOME_FEED_EXCLUDED_BRIEF_TYPES, NEWS_BRIEF_TYPES } from '@lobechat/types';
import { and, desc, eq, gte, inArray, isNull, lt, notInArray, type SQL, sql } from 'drizzle-orm';
import { agents } from '../schemas/agent';
@@ -105,7 +105,13 @@ export class BriefModel {
.from(briefs)
.leftJoin(agents, eq(briefs.agentId, agents.id))
.leftJoin(tasks, eq(briefs.taskId, tasks.id))
- .where(and(this.ownership(), isNull(briefs.resolvedAt)))
+ .where(
+ and(
+ this.ownership(),
+ isNull(briefs.resolvedAt),
+ notInArray(briefs.type, HOME_FEED_EXCLUDED_BRIEF_TYPES),
+ ),
+ )
.orderBy(
sql`CASE
WHEN ${briefs.priority} = 'urgent' THEN 0
diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.ts
index 7ff008dd57d..3822411ee9b 100644
--- a/packages/locales/src/default/home.ts
+++ b/packages/locales/src/default/home.ts
@@ -31,10 +31,13 @@ export default {
'brief.agentSignal.selfReview.applied.summary': '{{count}} dream update was applied.',
'brief.agentSignal.selfReview.applied.summary_plural': '{{count}} dream updates were applied.',
'brief.agentSignal.selfReview.applied.title': 'Dream updated resources',
- 'brief.agentSignal.selfReview.error.heading': 'Issue',
- 'brief.agentSignal.selfReview.error.summary':
- 'Some work could not be completed during this dream.',
- 'brief.agentSignal.selfReview.error.title': 'Dream ran into an issue',
+ 'brief.agentSignal.selfReview.detail.body': 'Skill content',
+ 'brief.agentSignal.selfReview.detail.description': 'Description',
+ 'brief.agentSignal.selfReview.detail.memory': 'Memory to save',
+ 'brief.agentSignal.selfReview.detail.open': 'View details',
+ 'brief.agentSignal.selfReview.detail.rationale': 'Why',
+ 'brief.agentSignal.selfReview.detail.systemRole': 'New system prompt',
+ 'brief.agentSignal.selfReview.detail.title': 'Suggestion details',
'brief.agentSignal.selfReview.details.forAgent': 'For {{agent}}',
'brief.agentSignal.selfReview.kind.consolidate_skill.plain': 'Merge skills',
'brief.agentSignal.selfReview.kind.consolidate_skill.withTarget': 'Merge skills into {{target}}',
@@ -145,7 +148,6 @@ export default {
'dashboard.task.unsupportedContext':
'Task mode does not support selected context yet. Remove them or switch to Agent mode; your draft has been kept.',
'inbox.author.scheduled': 'Scheduled',
- 'inbox.error.title': 'Run failed',
'inbox.goals.review': 'Needs your decision',
'inbox.goals.running': 'In progress',
'inbox.goals.showAll': 'Show all {{count}}',
diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.ts
index 826125b942b..b90d5bf3a21 100644
--- a/packages/locales/src/default/notification.ts
+++ b/packages/locales/src/default/notification.ts
@@ -14,6 +14,14 @@ export default {
'agent_intervention_required_title': '{{agent}} needs your review',
'agent_run_completed': '{{preview}}',
'agent_run_completed_title': 'Agent task completed',
+ 'agent_task_run_failed': 'Your task "{{jobName}}" failed. Open the task to see the full error.',
+ 'agent_task_run_failed_heartbeat_timeout':
+ 'Your task "{{jobName}}" stopped responding and was marked as failed. Open the task to run it again.',
+ 'agent_task_run_failed_heartbeat_timeout_title': 'Task timed out',
+ 'agent_task_run_failed_insufficient_budget':
+ 'Your task "{{jobName}}" couldn\'t run because your account is out of credits. Top up or upgrade your plan to continue.',
+ 'agent_task_run_failed_insufficient_budget_title': 'Task failed: insufficient credits',
+ 'agent_task_run_failed_title': 'Task failed',
'agent_transfer_reassigned':
'A workspace owner transferred your agent "{{agentTitle}}" to {{recipientLabel}}.',
'agent_transfer_reassigned_title': 'Agent reassigned',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 12f5c31e74e..cf55fb3899a 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -992,6 +992,7 @@ export default {
'notification.category.workspace.title': 'Workspace',
'notification.item.agent_cron_job_completed': 'Scheduled task completed',
'notification.item.agent_cron_job_failed': 'Scheduled task failed',
+ 'notification.item.agent_task_run_failed': 'Task failed',
'notification.item.agent_run_completed': 'Agent task completed',
'notification.item.agent_transfer_result': 'Transfer request result',
'notification.item.checkout_abandoned': 'Unfinished checkout reminders',
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts
index ececec50f08..edc20a39566 100644
--- a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts
@@ -55,6 +55,36 @@ describe('agent signal self-iteration runtime prompt', () => {
).toMatchSnapshot();
});
+ /**
+ * @example
+ * The owner's response language reaches every mode, so proposals and skills
+ * are written in it instead of following the evidence language.
+ */
+ it('asks for user-visible output in the response language when provided', () => {
+ const base = {
+ agentId: 'agent-1',
+ context: {},
+ sourceId: 'source-3',
+ userId: 'user-1',
+ window: { end: '2026-05-09T16:00:00.000Z', start: '2026-05-08T16:00:00.000Z' },
+ };
+
+ for (const mode of ['review', 'reflection', 'feedback'] as const) {
+ const prompt = createAgentSignalSelfIterationPrompt({
+ ...base,
+ mode,
+ responseLanguage: 'zh-CN',
+ });
+
+ expect(prompt).toContain("Write every user-visible field in the user's language (zh-CN)");
+ expect(prompt).toContain('skill title, description and bodyMarkdown');
+ }
+
+ expect(createAgentSignalSelfIterationPrompt({ ...base, mode: 'review' })).not.toContain(
+ 'output_language',
+ );
+ });
+
/**
* @example
* System roles and tool roles stay generated by the prompt package.
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
index 2464d3076df..e130d249f88 100644
--- a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
@@ -9,6 +9,12 @@ export interface AgentSignalSelfIterationPromptInput {
context: unknown;
/** Runtime mode that controls review-specific policy text. */
mode: 'feedback' | 'reflection' | 'review';
+ /**
+ * Locale the owning user reads LobeHub in (e.g. `zh-CN`). User-visible
+ * output — proposals, skills, ideas — must be written in it; omitted when
+ * the language could not be resolved.
+ */
+ responseLanguage?: string;
/** Stable source id used for tracing and idempotency. */
sourceId: string;
/** Stable user id owning the reviewed agent. */
@@ -74,6 +80,13 @@ export const createAgentSignalSelfIterationToolSystemRole = (
? 'Use resource read tools before writes when evidence is incomplete. Use getEvidenceDigest for topic/message/tool_call/agent_document evidenceRefs. Use readSelfReviewProposal only with proposal keys from proposalActivity.active or listSelfReviewProposals, never with evidence ids. Treat write tool results as the source of truth.'
: 'Use resource read tools before writes when evidence is incomplete. Direct-apply only safe user-level memory or bounded skill updates. Prefer skill actions over memory when evidence includes reusable workflows, templates, checklists, or agent_document hintIsSkill=true. Record approval-gated or unsupported reflection output with recordSelfFeedbackIntent, and record non-actionable thoughts with recordReflectionIdea.';
+const createOutputLanguageInstruction = (responseLanguage: string) =>
+ [
+ `Write every user-visible field in the user's language (${responseLanguage}), whatever language the evidence is in:`,
+ 'proposal titles, summaries and rationales; skill title, description and bodyMarkdown; refined systemRole text; ideas and feedback intents.',
+ 'Keep identifiers unchanged: skill name slugs, tool names, ids, code, commands and quoted evidence.',
+ ].join(' ');
+
const createNightlyReviewPromptXml = (input: AgentSignalSelfIterationPromptInput) =>
toXml(
u('root', [
@@ -114,6 +127,9 @@ const createNightlyReviewPromptXml = (input: AgentSignalSelfIterationPromptInput
'If a rule says `createSelfReviewProposal`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.',
].join('\n'),
),
+ ...(input.responseLanguage
+ ? [x('output_language', createOutputLanguageInstruction(input.responseLanguage))]
+ : []),
x('review_window', `Review window: ${input.window.start} to ${input.window.end}`),
x('nightly_review_context_json', JSON.stringify(input.context)),
),
@@ -144,6 +160,9 @@ export const createAgentSignalSelfIterationPrompt = (
`Source id: ${input.sourceId}`,
`Mode: ${input.mode}`,
`Evidence window: ${input.window.start} to ${input.window.end}`,
+ ...(input.responseLanguage
+ ? [`Output language: ${createOutputLanguageInstruction(input.responseLanguage)}`]
+ : []),
'Self-iteration context JSON:',
JSON.stringify(input.context),
].join('\n');
diff --git a/packages/types/src/brief/index.ts b/packages/types/src/brief/index.ts
index 40c4261f8eb..69e6661f0b9 100644
--- a/packages/types/src/brief/index.ts
+++ b/packages/types/src/brief/index.ts
@@ -43,6 +43,14 @@ export type BriefType = 'decision' | 'error' | 'insight' | 'result';
*/
export const NEWS_BRIEF_TYPES: BriefType[] = ['insight', 'result'];
+/**
+ * Brief types kept off the home unresolved feed. Run failures are not
+ * decisions: they now reach the user through the notification center and no
+ * longer mint briefs, so legacy unresolved `error` rows must not crowd
+ * "Needs you" either. They stay readable on their task.
+ */
+export const HOME_FEED_EXCLUDED_BRIEF_TYPES: BriefType[] = ['error'];
+
/**
* A single artifact (currently only documents) referenced from a brief.
* Programmatically collected during topic completion, not produced by the LLM.
diff --git a/src/features/DailyBrief/SelfReviewBriefDetails.tsx b/src/features/DailyBrief/SelfReviewBriefDetails.tsx
index 00203af0008..671cf6a57dc 100644
--- a/src/features/DailyBrief/SelfReviewBriefDetails.tsx
+++ b/src/features/DailyBrief/SelfReviewBriefDetails.tsx
@@ -2,6 +2,7 @@ import {
formatSelfReviewKindLabel,
getSelfReviewBriefLead,
type SelfReviewBriefDetails as SelfReviewBriefDetailsModel,
+ type SelfReviewProposalContentItem,
} from '@lobechat/agent-signal/brief';
import { Flexbox } from '@lobehub/ui';
import { Button, Text } from '@lobehub/ui/base-ui';
@@ -11,6 +12,7 @@ import { useTranslation } from 'react-i18next';
import { homeType } from '@/features/Home/components/homeType';
+import { createSelfReviewProposalModal } from './SelfReviewProposalModal';
import { useSelfReviewTranslator } from './useSelfReviewBriefView';
/** Rows shown before the rest fold behind "N more". */
@@ -48,6 +50,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface SelfReviewBriefDetailsProps {
/** Display name of the agent the proposal is for. */
agentName?: string;
+ /** Full proposal content; when present, a "View details" button opens it. */
+ content?: SelfReviewProposalContentItem[];
details: SelfReviewBriefDetailsModel;
}
@@ -56,7 +60,7 @@ interface SelfReviewBriefDetailsProps {
* is for, a one- or two-line lead, and — when it holds several changes or
* ideas — one row per change (kind · target — why), folded past three rows.
*/
-const SelfReviewBriefDetails = ({ agentName, details }: SelfReviewBriefDetailsProps) => {
+const SelfReviewBriefDetails = ({ agentName, content, details }: SelfReviewBriefDetailsProps) => {
const { t } = useTranslation('home');
const [expanded, setExpanded] = useState(false);
const translate = useSelfReviewTranslator();
@@ -111,15 +115,29 @@ const SelfReviewBriefDetails = ({ agentName, details }: SelfReviewBriefDetailsPr
})}
</Flexbox>
)}
- {hidden > 0 && (
- <Button
- className={styles.more}
- size={'small'}
- type={'text'}
- onClick={() => setExpanded(true)}
- >
- {t('brief.agentSignal.selfReview.list.more', { count: String(hidden) })}
- </Button>
+ {(hidden > 0 || content) && (
+ <Flexbox horizontal align={'center'} gap={12}>
+ {hidden > 0 && (
+ <Button
+ className={styles.more}
+ size={'small'}
+ type={'text'}
+ onClick={() => setExpanded(true)}
+ >
+ {t('brief.agentSignal.selfReview.list.more', { count: String(hidden) })}
+ </Button>
+ )}
+ {content && (
+ <Button
+ className={styles.more}
+ size={'small'}
+ type={'text'}
+ onClick={() => createSelfReviewProposalModal(content)}
+ >
+ {t('brief.agentSignal.selfReview.detail.open')}
+ </Button>
+ )}
+ </Flexbox>
)}
</Flexbox>
);
diff --git a/src/features/DailyBrief/SelfReviewProposalModal/ProposalContent.tsx b/src/features/DailyBrief/SelfReviewProposalModal/ProposalContent.tsx
new file mode 100644
index 00000000000..84c4c020e46
--- /dev/null
+++ b/src/features/DailyBrief/SelfReviewProposalModal/ProposalContent.tsx
@@ -0,0 +1,121 @@
+import {
+ formatSelfReviewItemHeadline,
+ type SelfReviewProposalContentItem,
+} from '@lobechat/agent-signal/brief';
+import { Block, Flexbox, Markdown } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useSelfReviewTranslator } from '../useSelfReviewBriefView';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ overflow-y: auto;
+ max-height: min(70vh, 720px);
+ padding-block: 4px 16px;
+ padding-inline: 20px;
+ `,
+ divider: css`
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ headline: css`
+ font-size: 15px;
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+ label: css`
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ name: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ text: css`
+ font-size: 14px;
+ line-height: 1.6;
+ color: ${cssVar.colorTextSecondary};
+ white-space: pre-wrap;
+ `,
+}));
+
+const Section = ({ children, label }: { children: ReactNode; label: string }) => (
+ <Flexbox gap={4}>
+ <span className={styles.label}>{label}</span>
+ {children}
+ </Flexbox>
+);
+
+const MarkdownBlock = ({ children }: { children: string }) => (
+ <Block padding={12} variant={'outlined'}>
+ <Markdown style={{ overflow: 'unset' }} variant={'chat'}>
+ {children}
+ </Markdown>
+ </Block>
+);
+
+const ProposalItem = ({ item }: { item: SelfReviewProposalContentItem }) => {
+ const { t } = useTranslation('home');
+ const translate = useSelfReviewTranslator();
+
+ // A new skill is named by the title it would get; a changed skill by its
+ // current title. Memory text gets its own section, not the headline.
+ const headline = formatSelfReviewItemHeadline(
+ { kind: item.kind, target: item.title ?? item.name ?? item.target },
+ translate,
+ );
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox gap={2}>
+ <Text className={styles.headline}>{headline}</Text>
+ {item.name && item.name !== item.title && <span className={styles.name}>{item.name}</span>}
+ </Flexbox>
+ {item.rationale && (
+ <Section label={t('brief.agentSignal.selfReview.detail.rationale')}>
+ <span className={styles.text}>{item.rationale}</span>
+ </Section>
+ )}
+ {item.description && (
+ <Section label={t('brief.agentSignal.selfReview.detail.description')}>
+ <span className={styles.text}>{item.description}</span>
+ </Section>
+ )}
+ {item.memoryContent && (
+ <Section label={t('brief.agentSignal.selfReview.detail.memory')}>
+ <span className={styles.text}>{item.memoryContent}</span>
+ </Section>
+ )}
+ {item.systemRole && (
+ <Section label={t('brief.agentSignal.selfReview.detail.systemRole')}>
+ <MarkdownBlock>{item.systemRole}</MarkdownBlock>
+ </Section>
+ )}
+ {item.bodyMarkdown && (
+ <Section label={t('brief.agentSignal.selfReview.detail.body')}>
+ <MarkdownBlock>{item.bodyMarkdown}</MarkdownBlock>
+ </Section>
+ )}
+ </Flexbox>
+ );
+};
+
+interface ProposalContentProps {
+ items: SelfReviewProposalContentItem[];
+}
+
+/** Body of the self-review details modal: every proposed action in full. */
+export const ProposalContent = ({ items }: ProposalContentProps) => (
+ <Flexbox className={styles.container} gap={20}>
+ {items.map((item, index) => (
+ <Flexbox gap={20} key={index}>
+ {index > 0 && <div className={styles.divider} />}
+ <ProposalItem item={item} />
+ </Flexbox>
+ ))}
+ </Flexbox>
+);
diff --git a/src/features/DailyBrief/SelfReviewProposalModal/index.tsx b/src/features/DailyBrief/SelfReviewProposalModal/index.tsx
new file mode 100644
index 00000000000..6657726b675
--- /dev/null
+++ b/src/features/DailyBrief/SelfReviewProposalModal/index.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import { type SelfReviewProposalContentItem } from '@lobechat/agent-signal/brief';
+import { createModal } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { lazy, Suspense } from 'react';
+
+// Markdown rendering stays out of the home bundle until a reader opens details.
+const ProposalContent = lazy(() =>
+ import('./ProposalContent').then((module) => ({ default: module.ProposalContent })),
+);
+
+/**
+ * Opens the full content of a nightly self-review proposal — skill bodies,
+ * replacement system prompt, memory text — so the user can read what they are
+ * about to approve.
+ */
+export const createSelfReviewProposalModal = (items: SelfReviewProposalContentItem[]) =>
+ createModal({
+ content: (
+ <Suspense fallback={<div style={{ minHeight: 200 }} />}>
+ <ProposalContent items={items} />
+ </Suspense>
+ ),
+ footer: null,
+ maskClosable: true,
+ styles: { content: { padding: 0 } },
+ title: t('brief.agentSignal.selfReview.detail.title', { ns: 'home' }),
+ width: 'min(90%, 760px)',
+ });
diff --git a/src/features/DailyBrief/useSelfReviewBriefView.ts b/src/features/DailyBrief/useSelfReviewBriefView.ts
index acdd0a6bfe4..efabb470592 100644
--- a/src/features/DailyBrief/useSelfReviewBriefView.ts
+++ b/src/features/DailyBrief/useSelfReviewBriefView.ts
@@ -1,14 +1,22 @@
import {
formatSelfReviewBriefTitle,
getSelfReviewBriefDetails,
+ getSelfReviewProposalContent,
+ hasSelfReviewProposalContent,
type SelfReviewBriefDetails,
type SelfReviewBriefDetailsTranslator,
+ type SelfReviewProposalContentItem,
} from '@lobechat/agent-signal/brief';
import { useTranslation } from 'react-i18next';
import { type BriefItem } from './types';
export interface SelfReviewBriefView {
+ /**
+ * What each proposed action would write (skill body, system prompt, memory),
+ * present only when there is more to read than the inline rows show.
+ */
+ content?: SelfReviewProposalContentItem[];
details: SelfReviewBriefDetails;
/** Title naming the main proposed change, in the reader's language. */
title: string;
@@ -33,7 +41,13 @@ export const useSelfReviewBriefView = (
const details = getSelfReviewBriefDetails(metadata);
if (!details) return;
- return { details, title: formatSelfReviewBriefTitle(details, translate) };
+ const content = details.kind === 'proposal' ? getSelfReviewProposalContent(metadata) : undefined;
+
+ return {
+ ...(content && hasSelfReviewProposalContent(content) ? { content } : {}),
+ details,
+ title: formatSelfReviewBriefTitle(details, translate),
+ };
};
/**
diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsx
index 5d57cc71362..ddf3076f58a 100644
--- a/src/features/HomeInbox/InboxBriefCard.tsx
+++ b/src/features/HomeInbox/InboxBriefCard.tsx
@@ -145,7 +145,11 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {
{!hasTaskMeta && !goal && <Time date={brief.createdAt} />}
</Flexbox>
{selfReview ? (
- <SelfReviewBriefDetails agentName={agentName} details={selfReview.details} />
+ <SelfReviewBriefDetails
+ agentName={agentName}
+ content={selfReview.content}
+ details={selfReview.details}
+ />
) : (
<BriefCardSummary summary={brief.summary} />
)}
diff --git a/src/features/HomeInbox/NewsList.tsx b/src/features/HomeInbox/NewsList.tsx
index 0ef43f8051d..0c76419087f 100644
--- a/src/features/HomeInbox/NewsList.tsx
+++ b/src/features/HomeInbox/NewsList.tsx
@@ -159,7 +159,7 @@ const NewsItem = memo<NewsItemProps>(({ bare, brief, showTime }) => {
{expanded && (brief.summary || brief.artifacts || hasTopicChat) && (
<Flexbox className={bare ? styles.bareBody : styles.body} gap={8}>
{selfReview ? (
- <SelfReviewBriefDetails details={selfReview.details} />
+ <SelfReviewBriefDetails content={selfReview.content} details={selfReview.details} />
) : (
brief.summary && (
<Suspense fallback={null}>
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index ef99bbf6a5b..f1f108326c4 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -84,9 +84,8 @@ interface InboxSection {
* - **Goals** — the standing exception to "while you were away": goals run for
* days, so the ones still open (waiting on you, or working) are listed here
* rather than left to the agent page nobody visits mid-flight.
- * - **Needs you** — briefs blocking an agent (decide / fix). Errors sink to the
- * bottom: a stuck decision blocks work right now, a failed run has already
- * stopped.
+ * - **Needs you** — decision briefs blocking an agent. Run failures are not
+ * decisions; they go to the notification center instead.
* - **Unread** — runs that finished while you were away, each showing the agent's
* last reply so the answer is right there.
* - **Running** — collapsed to one line, showing who is working; a healthy run
diff --git a/src/features/HomeInbox/splitBriefs.test.ts b/src/features/HomeInbox/splitBriefs.test.ts
index a193530b176..b35b8b1ae41 100644
--- a/src/features/HomeInbox/splitBriefs.test.ts
+++ b/src/features/HomeInbox/splitBriefs.test.ts
@@ -8,7 +8,7 @@ const brief = (id: string, type: BriefItem['type']): BriefItem =>
({ id, summary: '', title: id, type }) as BriefItem;
describe('splitBriefs', () => {
- it('routes insight and result briefs to news, decision and error to needsYou', () => {
+ it('routes insight and result briefs to news and only decisions to needsYou', () => {
const { needsYou, news } = splitBriefs([
brief('a', 'decision'),
brief('b', 'insight'),
@@ -16,7 +16,7 @@ describe('splitBriefs', () => {
brief('d', 'error'),
]);
- expect(needsYou.map((b) => b.id)).toEqual(['a', 'd']);
+ expect(needsYou.map((b) => b.id)).toEqual(['a']);
expect(news.map((b) => b.id)).toEqual(['b', 'c']);
});
@@ -39,10 +39,12 @@ describe('splitBriefs', () => {
]);
});
- it('sinks errors to the bottom of needsYou', () => {
- const { needsYou } = splitBriefs([brief('err', 'error'), brief('dec', 'decision')]);
+ // Failures belong in the notification center, not in the decision queue.
+ it('keeps legacy error briefs out of needsYou and news', () => {
+ const { needsYou, news } = splitBriefs([brief('err', 'error'), brief('dec', 'decision')]);
- expect(needsYou.map((b) => b.id)).toEqual(['dec', 'err']);
+ expect(needsYou.map((b) => b.id)).toEqual(['dec']);
+ expect(news).toEqual([]);
});
it('removes an optimistically resolved decision from needsYou immediately', () => {
diff --git a/src/features/HomeInbox/splitBriefs.ts b/src/features/HomeInbox/splitBriefs.ts
index ed0786192a9..b4991b1bcd5 100644
--- a/src/features/HomeInbox/splitBriefs.ts
+++ b/src/features/HomeInbox/splitBriefs.ts
@@ -1,18 +1,9 @@
-import { NEWS_BRIEF_TYPES } from '@lobechat/types';
+import { HOME_FEED_EXCLUDED_BRIEF_TYPES, NEWS_BRIEF_TYPES } from '@lobechat/types';
import { type BriefItem } from '@/features/DailyBrief/types';
-/**
- * Within "Needs you", failures sink to the bottom: a stuck decision blocks the
- * agent right now, while a failed run has already stopped and can wait.
- */
-const NEEDS_YOU_ORDER: Record<string, number> = {
- decision: 0,
- error: 9,
-};
-
export interface SplitBriefs {
- /** Briefs the user must act on — grouped as "Needs you", errors last. */
+ /** Briefs the user must decide on — grouped as "Needs you". */
needsYou: BriefItem[];
/** `insight` + `result` briefs: nothing to decide, just worth a glance. */
news: BriefItem[];
@@ -28,19 +19,24 @@ export interface SplitBriefs {
const isNewsBrief = (brief: BriefItem): boolean => NEWS_BRIEF_TYPES.includes(brief.type);
/**
- * Splits the unresolved brief feed by whether the user has to *do* something.
- * `decision` / `error` block an agent until answered; `insight` and `result`
- * are pure knowledge and belong in a scannable list, not in a to-do pile.
+ * Splits the unresolved brief feed by whether the user has to *decide*
+ * something. `decision` briefs block an agent until answered; `insight` and
+ * `result` are pure knowledge and belong in a scannable list, not in a to-do
+ * pile. Run failures are not decisions — they live in the notification center,
+ * so legacy `error` briefs are dropped here too (the server already filters
+ * them; this keeps stale caches from showing them).
*
- * The server already sorts by priority then recency, so we only re-order within
- * "Needs you" — a stable sort keeps that ordering inside each rank.
+ * The server already sorts by priority then recency; the filter keeps that order.
*/
export const splitBriefs = (briefs: BriefItem[]): SplitBriefs => ({
- needsYou: briefs
- // A successful optimistic resolve stamps the row before the unresolved-list
- // SWR cache revalidates. Hide it immediately so "Ignore" actually closes the
- // card instead of leaving a resolved tombstone in the queue until remount.
- .filter((brief) => !brief.resolvedAt && !isNewsBrief(brief))
- .sort((a, b) => (NEEDS_YOU_ORDER[a.type] ?? 5) - (NEEDS_YOU_ORDER[b.type] ?? 5)),
+ needsYou: briefs.filter(
+ (brief) =>
+ // A successful optimistic resolve stamps the row before the unresolved-list
+ // SWR cache revalidates. Hide it immediately so "Ignore" actually closes the
+ // card instead of leaving a resolved tombstone in the queue until remount.
+ !brief.resolvedAt &&
+ !isNewsBrief(brief) &&
+ !HOME_FEED_EXCLUDED_BRIEF_TYPES.includes(brief.type),
+ ),
news: briefs.filter(isNewsBrief),
});