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.

♻️ refactor(task-brief): auto-synthesize topic briefs (#14324)

Arvin Xu84df8a999432
diff --git a/packages/database/src/models/__tests__/brief.test.ts b/packages/database/src/models/__tests__/brief.test.ts
index 13eb040f02c..5c2b572f863 100644
--- a/packages/database/src/models/__tests__/brief.test.ts
+++ b/packages/database/src/models/__tests__/brief.test.ts
@@ -44,7 +44,12 @@ describe('BriefModel', () => {
const brief = await model.create({
actions: [{ label: 'Approve', type: 'approve' }],
agentId: 'agent-1',
- artifacts: ['doc-1', 'doc-2'],
+ artifacts: {
+ documents: [
+ { id: 'doc-1', kind: null, title: null },
+ { id: 'doc-2', kind: null, title: null },
+ ],
+ },
priority: 'urgent',
summary: 'Chapter too long, suggest splitting',
taskId: null,
@@ -56,7 +61,12 @@ describe('BriefModel', () => {
expect(brief.priority).toBe('urgent');
expect(brief.agentId).toBe('agent-1');
expect(brief.actions).toEqual([{ label: 'Approve', type: 'approve' }]);
- expect(brief.artifacts).toEqual(['doc-1', 'doc-2']);
+ expect(brief.artifacts).toEqual({
+ documents: [
+ { id: 'doc-1', kind: null, title: null },
+ { id: 'doc-2', kind: null, title: null },
+ ],
+ });
});
});
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index b5566d1c164..0fff2a661c5 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -625,6 +625,51 @@ describe('TaskModel', () => {
const pinned = await model.getPinnedDocuments(task.id);
expect(pinned).toHaveLength(1);
});
+
+ it('getDocumentsPinnedSince filters by createdAt and joins title/kind', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ const [oldDoc] = await serverDB
+ .insert(documents)
+ .values({
+ content: '',
+ fileType: 'text/plain',
+ source: 'test',
+ sourceType: 'file',
+ title: 'Old',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ })
+ .returning();
+ const [newDoc] = await serverDB
+ .insert(documents)
+ .values({
+ content: '',
+ fileType: 'text/markdown',
+ source: 'test',
+ sourceType: 'file',
+ title: 'New',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ })
+ .returning();
+
+ await model.pinDocument(task.id, oldDoc.id);
+ const cutoff = new Date(Date.now() + 100); // pin newDoc after this point
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ await model.pinDocument(task.id, newDoc.id);
+
+ const pinnedSince = await model.getDocumentsPinnedSince(task.id, cutoff);
+ expect(pinnedSince).toHaveLength(1);
+ expect(pinnedSince[0]).toEqual({
+ id: newDoc.id,
+ kind: 'text/markdown',
+ title: 'New',
+ });
+ });
});
describe('checkpoint', () => {
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 27d3631ff6b..c6b791f4593 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -6,10 +6,11 @@ import type {
WorkspaceDocNode,
WorkspaceTreeNode,
} from '@lobechat/types';
-import { and, desc, eq, inArray, isNotNull, isNull, ne, notInArray, sql } from 'drizzle-orm';
+import { and, desc, eq, gte, inArray, isNotNull, isNull, ne, notInArray, sql } from 'drizzle-orm';
import { merge } from '@/utils/merge';
+import { documents } from '../schemas/file';
import type { NewTaskComment, TaskCommentItem } from '../schemas/task';
import { taskComments, taskDependencies, taskDocuments, tasks } from '../schemas/task';
import type { LobeChatDatabase } from '../type';
@@ -619,6 +620,40 @@ export class TaskModel {
.orderBy(taskDocuments.createdAt);
}
+ /**
+ * Documents pinned to a task at or after a given timestamp, joined with the
+ * `documents` table so callers receive `{ id, kind, title }` directly.
+ *
+ * Used by topic-brief synthesis to attribute artifacts to the topic that
+ * just completed: pass the topic's start time as `since`.
+ */
+ async getDocumentsPinnedSince(
+ taskId: string,
+ since: Date,
+ ): Promise<{ id: string; kind: string | null; title: string | null }[]> {
+ const rows = await this.db
+ .select({
+ fileType: documents.fileType,
+ id: documents.id,
+ title: documents.title,
+ })
+ .from(taskDocuments)
+ .innerJoin(documents, eq(taskDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(taskDocuments.taskId, taskId),
+ eq(taskDocuments.userId, this.userId),
+ gte(taskDocuments.createdAt, since),
+ ),
+ );
+
+ return rows.map((row) => ({
+ id: row.id,
+ kind: row.fileType ?? null,
+ title: row.title ?? null,
+ }));
+ }
+
// Get all pinned docs from a task tree (recursive), returns nodeMap + tree structure
async getTreePinnedDocuments(rootTaskId: string): Promise<WorkspaceData> {
const result = await this.db.execute(sql`
diff --git a/packages/database/src/schemas/task.ts b/packages/database/src/schemas/task.ts
index 7e843954dbc..7b2c5d5318e 100644
--- a/packages/database/src/schemas/task.ts
+++ b/packages/database/src/schemas/task.ts
@@ -1,3 +1,4 @@
+import type { BriefArtifacts } from '@lobechat/types';
import {
foreignKey,
index,
@@ -241,7 +242,7 @@ export const briefs = pgTable(
priority: text('priority').default('info'), // 'urgent' | 'normal' | 'info'
title: text('title').notNull(),
summary: text('summary').notNull(),
- artifacts: jsonb('artifacts'), // document ids
+ artifacts: jsonb('artifacts').$type<BriefArtifacts>(), // programmatically collected at synthesis
actions: jsonb('actions'), // BriefAction[]
// Resolution
diff --git a/packages/prompts/src/chains/generateBrief.ts b/packages/prompts/src/chains/generateBrief.ts
new file mode 100644
index 00000000000..fbfc7ffe9f7
--- /dev/null
+++ b/packages/prompts/src/chains/generateBrief.ts
@@ -0,0 +1,97 @@
+import type { BriefArtifacts, ChatStreamPayload, TaskTopicHandoff } from '@lobechat/types';
+
+/**
+ * Generate a user-facing brief for a completed topic.
+ *
+ * Brief and handoff are NOT the same thing:
+ * - handoff is the agent's internal "cheat sheet" for the next tick β€” terse,
+ * tool-aware, action-oriented.
+ * - brief is the user's delivery report β€” written in user-facing language,
+ * focused on what was delivered and why it matters.
+ *
+ * The handoff is passed in as input context (so the brief stays consistent
+ * with what was just summarized), but the LLM rewrites it from scratch in
+ * user-facing tone. Type / priority / artifacts are determined programmatically
+ * outside this chain and are NOT in the schema.
+ */
+export const chainGenerateBrief = (params: {
+ artifacts?: BriefArtifacts | null;
+ handoff?: TaskTopicHandoff | null;
+ lastAssistantContent: string;
+ taskInstruction: string;
+ taskName: string;
+}): Partial<ChatStreamPayload> => {
+ const handoffBlock = params.handoff
+ ? `Handoff summary (internal, agent-to-agent):
+- Topic title: ${params.handoff.title || '(none)'}
+- Summary: ${params.handoff.summary || '(none)'}
+- Key findings: ${(params.handoff.keyFindings || []).join('; ') || '(none)'}
+- Next action: ${params.handoff.nextAction || '(none)'}`
+ : 'Handoff summary: (not available)';
+
+ const artifactsBlock = params.artifacts?.documents?.length
+ ? `Artifacts (documents produced or pinned in this topic):
+${params.artifacts.documents.map((d) => `- ${d.title || '(untitled)'} [id=${d.id}]`).join('\n')}`
+ : 'Artifacts: (none)';
+
+ return {
+ messages: [
+ {
+ content: `You decide whether the topic just completed is worth reporting to the end user as a "brief", and if so, write that brief.
+
+A brief is a short delivery report. Not every topic deserves one β€” many topics are mid-process working steps that the user does not need surfaced. Your job is two-part: judge whether to emit, and if so, produce user-facing title + summary.
+
+Output a JSON object with these fields:
+- "emit": boolean. true if this topic is a delivery moment worth surfacing to the user. false if it is mid-process / a working step / a clarification / a non-deliverable acknowledgement.
+- "title": string. User-facing headline for what was delivered (max 60 chars, same language as the assistant's content). When emit=false, return an empty string.
+- "summary": string. A 2-4 sentence report describing what was accomplished and why it matters to the user. When emit=false, return a one-line note (max 120 chars) explaining why no brief β€” for logs, the user will not see it.
+
+When to emit (emit=true):
+- A finished deliverable (a draft, a report, code, a plan, an analysis result).
+- A meaningful decision or conclusion the user should know about.
+- A milestone or phase boundary the user would care about.
+
+When to skip (emit=false):
+- "I clarified my understanding..." / "I will continue with X next."
+- Mid-process working notes, status pings, internal planning out loud.
+- Trivial acknowledgements or restatements with no new information for the user.
+- Any output where the next step is the actual deliverable, not this one.
+
+Voice and style rules (apply only when emit=true):
+- Write FOR THE USER, not for the agent or developer.
+- Use the same language as the assistant's content.
+- Lead with the delivered outcome, not the process.
+- Do NOT reference internal tool names (e.g. "createBrief", "write_file"), operation IDs, topic IDs, or implementation details.
+- Do NOT say "I" or "the agent" β€” describe the outcome, not the actor.
+- If artifacts are listed, you may mention them by their human title, but do not paste their IDs.
+- Avoid filler ("As requested...", "I have completed..."). Be specific about the result.
+
+Output ONLY the JSON object, no markdown fences or explanations.`,
+ role: 'system',
+ },
+ {
+ content: `Task: ${params.taskName}
+Task instruction: ${params.taskInstruction}
+
+${handoffBlock}
+
+${artifactsBlock}
+
+Last assistant response:
+${params.lastAssistantContent}`,
+ role: 'user',
+ },
+ ],
+ };
+};
+
+export const GENERATE_BRIEF_SCHEMA = {
+ additionalProperties: false,
+ properties: {
+ emit: { type: 'boolean' },
+ summary: { type: 'string' },
+ title: { type: 'string' },
+ },
+ required: ['emit', 'title', 'summary'],
+ type: 'object' as const,
+};
diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.ts
index fabeb6185fe..dde2a19c0f6 100644
--- a/packages/prompts/src/chains/index.ts
+++ b/packages/prompts/src/chains/index.ts
@@ -2,6 +2,7 @@ export * from './abstractChunk';
export * from './agentSignal/analyzeIntent';
export * from './answerWithContext';
export * from './compressContext';
+export * from './generateBrief';
export * from './inputCompletion';
export * from './langDetect';
export * from './pickEmoji';
diff --git a/packages/types/src/brief/index.ts b/packages/types/src/brief/index.ts
index 30ad8b52f6d..954886bf535 100644
--- a/packages/types/src/brief/index.ts
+++ b/packages/types/src/brief/index.ts
@@ -35,3 +35,17 @@ export const DEFAULT_BRIEF_ACTIONS: Record<string, BriefAction[]> = {
/** Brief type β€” must match DEFAULT_BRIEF_ACTIONS keys and DB schema comment */
export type BriefType = 'decision' | 'error' | 'insight' | 'result';
+
+/**
+ * A single artifact (currently only documents) referenced from a brief.
+ * Programmatically collected during topic completion, not produced by the LLM.
+ */
+export interface BriefArtifactDocument {
+ id: string;
+ kind: string | null;
+ title: string | null;
+}
+
+export interface BriefArtifacts {
+ documents?: BriefArtifactDocument[];
+}
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 06210ddc358..5749f8cf67d 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -1,3 +1,5 @@
+import type { BriefArtifacts } from '../brief';
+
// ── Task type aliases ──
export type TaskStatus =
@@ -210,7 +212,7 @@ export interface TaskDetailActivity {
actions?: unknown;
agentId?: string | null;
agents?: TaskDetailActivityAgent[];
- artifacts?: unknown;
+ artifacts?: BriefArtifacts | null;
author?: TaskDetailActivityAuthor;
briefType?: string;
/**
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
index 167bed49bab..f4c301d1f5a 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
@@ -36,7 +36,7 @@ const toBriefItem = (act: TaskDetailActivity): BriefItem | null => {
id: a.id,
title: a.title,
})),
- artifacts: act.artifacts,
+ artifacts: act.artifacts ?? null,
createdAt: act.createdAt ?? act.time ?? new Date().toISOString(),
cronJobId: act.cronJobId ?? null,
id: act.id,
diff --git a/src/server/routers/lambda/brief.ts b/src/server/routers/lambda/brief.ts
index 1b00e7c5c53..c3b9443a939 100644
--- a/src/server/routers/lambda/brief.ts
+++ b/src/server/routers/lambda/brief.ts
@@ -33,7 +33,15 @@ const listSchema = z.object({
export const briefRouter = router({
create: briefProcedure.input(createSchema).mutation(async ({ input, ctx }) => {
try {
- const createData = { ...input };
+ const { artifacts, ...rest } = input;
+ // Legacy clients pass artifacts as a flat doc-id list; the storage shape
+ // is the structured `BriefArtifacts` object. Adapt at the boundary.
+ const createData: Parameters<BriefModel['create']>[0] = {
+ ...rest,
+ artifacts: artifacts?.length
+ ? { documents: artifacts.map((id) => ({ id, kind: null, title: null })) }
+ : undefined,
+ };
// Resolve taskId if it's an identifier
if (createData.taskId) {
diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.ts
index dcfc7735bce..881d206326b 100644
--- a/src/server/services/taskLifecycle/index.ts
+++ b/src/server/services/taskLifecycle/index.ts
@@ -1,5 +1,15 @@
-import { chainTaskTopicHandoff, TASK_TOPIC_HANDOFF_SCHEMA } from '@lobechat/prompts';
-import type { TaskItem, TaskSchedulerContext } from '@lobechat/types';
+import {
+ chainGenerateBrief,
+ chainTaskTopicHandoff,
+ GENERATE_BRIEF_SCHEMA,
+ TASK_TOPIC_HANDOFF_SCHEMA,
+} from '@lobechat/prompts';
+import type {
+ BriefArtifacts,
+ TaskItem,
+ TaskSchedulerContext,
+ TaskTopicHandoff,
+} from '@lobechat/types';
import { DEFAULT_BRIEF_ACTIONS } from '@lobechat/types';
import debug from 'debug';
@@ -13,6 +23,25 @@ import { SystemAgentService } from '@/server/services/systemAgent';
import { TaskReviewService } from '@/server/services/taskReview';
import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
+import {
+ isTrivialAssistantContent,
+ selectBriefPriority,
+ selectBriefType,
+ shouldEmitTopicBrief,
+} from './synthesize';
+
+/**
+ * Read the brief generation mode from `task.config.brief.mode`.
+ *
+ * Defaults to `'auto'` β€” programmatic synthesis in `synthesizeTopicBrief`
+ * is the standard path. `'agent'` is an explicit escape hatch that re-enables
+ * the legacy agent-driven `createBrief` tool flow.
+ */
+const getBriefMode = (task: TaskItem | null): 'agent' | 'auto' => {
+ const mode = (task?.config as { brief?: { mode?: string } } | null)?.brief?.mode;
+ return mode === 'agent' ? 'agent' : 'auto';
+};
+
const log = debug('task-lifecycle');
const TERMINAL_STATUSES = new Set(['canceled', 'completed', 'failed']);
@@ -101,7 +130,21 @@ export class TaskLifecycleService {
if (reviewTerminated) return;
- // 4. Default post-tick transition.
+ // 4. Synthesize a programmatic brief for the user (auto mode only).
+ // The agent-driven `createBrief` tool path stays the default until
+ // the GrowthBook flag flips. See LOBE-8333 for the rollout plan.
+ if (getBriefMode(currentTask) === 'auto' && currentTask && topicId && lastAssistantContent) {
+ await this.synthesizeTopicBrief(
+ taskId,
+ taskIdentifier,
+ topicId,
+ lastAssistantContent,
+ reason,
+ currentTask,
+ );
+ }
+
+ // 5. Default post-tick transition.
// - Automation tasks (heartbeat / schedule) loop running ↔ scheduled, so
// a successful tick parks the task at 'scheduled' to wait for the next
// tick. They never auto-pause on success β€” only `reason === 'error'`
@@ -279,6 +322,131 @@ export class TaskLifecycleService {
}
}
+ /**
+ * Programmatic brief synthesis for a completed topic.
+ *
+ * Fired only in `brief.mode === 'auto'` and only when neither the error nor
+ * the judge path has already produced a brief. Three-layer split:
+ * - decision (whether to emit, which type, which priority): two stages β€”
+ * a pure-rule pre-filter (`shouldEmitTopicBrief`) for cheap structural
+ * skips, then an LLM verdict on the actual content (mid-process working
+ * notes shouldn't surface as a delivery report)
+ * - artifacts: programmatic DB query against task_documents
+ * - title / summary: produced by the same LLM call as the verdict, in
+ * user-facing language (deliberately separate from handoff, which is
+ * agent-internal)
+ *
+ * Failures are swallowed β€” a missing brief should never block the task
+ * lifecycle. The caller still proceeds to the post-tick state transition.
+ */
+ private async synthesizeTopicBrief(
+ taskId: string,
+ taskIdentifier: string,
+ topicId: string,
+ lastAssistantContent: string,
+ reason: string,
+ currentTask: TaskItem,
+ ): Promise<void> {
+ try {
+ const reviewConfig = this.taskModel.getReviewConfig(currentTask);
+ const decisionInput = {
+ hasReviewConfigEnabled: !!reviewConfig?.enabled,
+ isTrivialContent: isTrivialAssistantContent(lastAssistantContent),
+ reason,
+ // We've already returned upstream when reviewTerminated was true; the
+ // remaining decision lives in shouldEmitTopicBrief itself.
+ reviewTerminated: false,
+ task: currentTask,
+ };
+
+ const decision = shouldEmitTopicBrief(decisionInput);
+ if (!decision.emit) {
+ log(
+ 'synthesize: skip task=%s topic=%s reason=%s',
+ taskIdentifier,
+ topicId,
+ decision.reason,
+ );
+ return;
+ }
+
+ const briefType = selectBriefType(decisionInput);
+ const priority = selectBriefPriority(decisionInput);
+
+ const topicLink = await this.taskTopicModel.findByTopicId(topicId);
+ const topicStartedAt = topicLink?.createdAt ?? new Date(0);
+
+ const pinnedDocs = await this.taskModel.getDocumentsPinnedSince(taskId, topicStartedAt);
+ const artifacts: BriefArtifacts = { documents: pinnedDocs };
+
+ const handoff = (topicLink?.handoff as TaskTopicHandoff | null) ?? null;
+
+ const { model, provider } = await (this.systemAgentService as any).getTaskModelConfig(
+ 'topic',
+ );
+
+ const payload = chainGenerateBrief({
+ artifacts,
+ handoff,
+ lastAssistantContent,
+ taskInstruction: currentTask.instruction || '',
+ taskName: currentTask.name || taskIdentifier,
+ });
+
+ const modelRuntime = await initModelRuntimeFromDB(this.db, this.userId, provider);
+ const result = await modelRuntime.generateObject(
+ {
+ messages: payload.messages as any[],
+ model,
+ schema: { name: 'task_topic_brief', schema: GENERATE_BRIEF_SCHEMA },
+ },
+ { metadata: { trigger: 'task-brief' } },
+ );
+
+ const generated = result as { emit?: boolean; summary?: string; title?: string };
+ // The LLM is the second-stage gate: even when the rule layer says "this
+ // could be a delivery", the model judges from actual content whether
+ // it's worth surfacing. Mid-process working notes / clarifications get
+ // emit=false here.
+ if (generated.emit === false) {
+ log(
+ 'synthesize: LLM voted skip task=%s topic=%s reason=%s',
+ taskIdentifier,
+ topicId,
+ generated.summary?.slice(0, 80) || '(none)',
+ );
+ return;
+ }
+ if (!generated.title || !generated.summary) {
+ log(
+ 'synthesize: LLM returned empty title/summary task=%s topic=%s',
+ taskIdentifier,
+ topicId,
+ );
+ return;
+ }
+
+ // `result` briefs render a fixed approval UI and intentionally have no
+ // default actions β€” see DEFAULT_BRIEF_ACTIONS comment.
+ const actions = briefType === 'result' ? null : (DEFAULT_BRIEF_ACTIONS[briefType] ?? null);
+
+ await this.briefModel.create({
+ actions,
+ artifacts,
+ priority,
+ summary: generated.summary,
+ taskId,
+ title: generated.title,
+ topicId,
+ type: briefType,
+ });
+
+ log('synthesize: brief created task=%s topic=%s type=%s', taskIdentifier, topicId, briefType);
+ } catch (e) {
+ console.warn('[TaskLifecycle] brief synthesis failed:', e);
+ }
+ }
+
/**
* Run auto-review if configured.
*
diff --git a/src/server/services/taskLifecycle/onTopicComplete.test.ts b/src/server/services/taskLifecycle/onTopicComplete.test.ts
index 582cf8cdc65..7b5629d820c 100644
--- a/src/server/services/taskLifecycle/onTopicComplete.test.ts
+++ b/src/server/services/taskLifecycle/onTopicComplete.test.ts
@@ -132,6 +132,75 @@ describe('TaskLifecycleService.onTopicComplete', () => {
});
});
+ describe('reason=done with brief.mode', () => {
+ it('calls synthesizeTopicBrief by default (auto mode) when content is substantive', async () => {
+ const task = baseTask({ automationMode: null });
+ findById.mockResolvedValue(task);
+ const synthesize = vi
+ .spyOn(service as any, 'synthesizeTopicBrief')
+ .mockResolvedValue(undefined);
+ vi.spyOn(service as any, 'generateHandoff').mockResolvedValue(undefined);
+
+ await service.onTopicComplete({
+ lastAssistantContent:
+ 'I have completed the analysis and produced a multi-page report covering all sections.',
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(synthesize).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not call synthesizeTopicBrief when brief.mode=agent (legacy escape hatch)', async () => {
+ const task = baseTask({
+ automationMode: null,
+ config: { brief: { mode: 'agent' } },
+ });
+ findById.mockResolvedValue(task);
+ const synthesize = vi
+ .spyOn(service as any, 'synthesizeTopicBrief')
+ .mockResolvedValue(undefined);
+ vi.spyOn(service as any, 'generateHandoff').mockResolvedValue(undefined);
+
+ await service.onTopicComplete({
+ lastAssistantContent: 'enough content to count as substantive output',
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(synthesize).not.toHaveBeenCalled();
+ });
+
+ it('does not call synthesizeTopicBrief when judge terminates (review enabled + passed)', async () => {
+ const task = baseTask({ automationMode: null });
+ findById.mockResolvedValue(task);
+ // runAutoReview returns true β†’ onTopicComplete returns early before
+ // reaching synthesizeTopicBrief.
+ vi.spyOn(service as any, 'runAutoReview').mockResolvedValue(true);
+ const synthesize = vi
+ .spyOn(service as any, 'synthesizeTopicBrief')
+ .mockResolvedValue(undefined);
+ vi.spyOn(service as any, 'generateHandoff').mockResolvedValue(undefined);
+
+ await service.onTopicComplete({
+ lastAssistantContent: 'enough content to count as substantive output',
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(synthesize).not.toHaveBeenCalled();
+ });
+ });
+
describe('reason=error', () => {
it('automation task β†’ status="paused" (error always pauses)', async () => {
const task = baseTask({ automationMode: 'heartbeat' });
diff --git a/src/server/services/taskLifecycle/synthesize.test.ts b/src/server/services/taskLifecycle/synthesize.test.ts
new file mode 100644
index 00000000000..2c3fa2e26bc
--- /dev/null
+++ b/src/server/services/taskLifecycle/synthesize.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import {
+ isTrivialAssistantContent,
+ selectBriefPriority,
+ selectBriefType,
+ shouldEmitTopicBrief,
+} from './synthesize';
+
+const baseInput = (overrides: Partial<Parameters<typeof shouldEmitTopicBrief>[0]> = {}) => ({
+ hasReviewConfigEnabled: false,
+ isTrivialContent: false,
+ reason: 'done' as string,
+ reviewTerminated: false,
+ task: { automationMode: null } as { automationMode: 'heartbeat' | 'schedule' | null },
+ ...overrides,
+});
+
+describe('shouldEmitTopicBrief', () => {
+ it('skips when reason=error (error branch handles its own brief)', () => {
+ const result = shouldEmitTopicBrief(baseInput({ reason: 'error' }));
+ expect(result.emit).toBe(false);
+ expect(result.reason).toBe('error-branch-handled');
+ });
+
+ it('skips when judge already terminated the lifecycle', () => {
+ const result = shouldEmitTopicBrief(baseInput({ reviewTerminated: true }));
+ expect(result.emit).toBe(false);
+ expect(result.reason).toBe('judge-handled');
+ });
+
+ it('skips when review is configured (judge owns the brief on this path)', () => {
+ const result = shouldEmitTopicBrief(baseInput({ hasReviewConfigEnabled: true }));
+ expect(result.emit).toBe(false);
+ expect(result.reason).toBe('review-config-enabled');
+ });
+
+ it('skips heartbeat automation ticks (mid-loop, not a delivery)', () => {
+ const result = shouldEmitTopicBrief(baseInput({ task: { automationMode: 'heartbeat' } }));
+ expect(result.emit).toBe(false);
+ expect(result.reason).toBe('automation-tick');
+ });
+
+ it('skips schedule automation ticks', () => {
+ const result = shouldEmitTopicBrief(baseInput({ task: { automationMode: 'schedule' } }));
+ expect(result.emit).toBe(false);
+ expect(result.reason).toBe('automation-tick');
+ });
+
+ it('skips trivial content (empty / whitespace-only acks)', () => {
+ const result = shouldEmitTopicBrief(baseInput({ isTrivialContent: true }));
+ expect(result.emit).toBe(false);
+ expect(result.reason).toBe('trivial-content');
+ });
+
+ it('emits for a normal manual-mode topic with substantive content', () => {
+ const result = shouldEmitTopicBrief(baseInput());
+ expect(result.emit).toBe(true);
+ });
+
+ it('skips automation even when other conditions look fine', () => {
+ const result = shouldEmitTopicBrief(
+ baseInput({
+ hasReviewConfigEnabled: false,
+ isTrivialContent: false,
+ task: { automationMode: 'heartbeat' },
+ }),
+ );
+ expect(result.emit).toBe(false);
+ });
+});
+
+describe('isTrivialAssistantContent', () => {
+ it('treats undefined as trivial', () => {
+ expect(isTrivialAssistantContent(undefined)).toBe(true);
+ });
+
+ it('treats whitespace-only as trivial', () => {
+ expect(isTrivialAssistantContent(' \n\t ')).toBe(true);
+ });
+
+ it('treats short content as trivial', () => {
+ expect(isTrivialAssistantContent('OK done.')).toBe(true);
+ });
+
+ it('treats substantive content as non-trivial', () => {
+ expect(
+ isTrivialAssistantContent('I have completed the analysis and produced a 3-page report.'),
+ ).toBe(false);
+ });
+});
+
+describe('selectBriefType / selectBriefPriority', () => {
+ it('first cut emits result/normal for every non-skipped topic', () => {
+ expect(selectBriefType(baseInput())).toBe('result');
+ expect(selectBriefPriority(baseInput())).toBe('normal');
+ });
+});
diff --git a/src/server/services/taskLifecycle/synthesize.ts b/src/server/services/taskLifecycle/synthesize.ts
new file mode 100644
index 00000000000..9190427283f
--- /dev/null
+++ b/src/server/services/taskLifecycle/synthesize.ts
@@ -0,0 +1,63 @@
+import type { BriefType, TaskItem } from '@lobechat/types';
+
+/** Inputs for the brief-emission rule. Pure data, no I/O. */
+export interface ShouldEmitTopicBriefInput {
+ hasReviewConfigEnabled: boolean;
+ /** True when content is empty / whitespace-only / a trivial acknowledgement. */
+ isTrivialContent: boolean;
+ reason: string;
+ reviewTerminated: boolean;
+ task: Pick<TaskItem, 'automationMode'> | null;
+}
+
+export interface ShouldEmitTopicBriefResult {
+ emit: boolean;
+ reason?: string;
+}
+
+/**
+ * Decide whether a completed topic should produce a synthesized brief.
+ *
+ * Pure function β€” caller wires inputs from `task` / `reason` / etc. Keeping
+ * the rule pure makes it easy to unit-test and to reason about.
+ *
+ * The error and judge paths build their own briefs upstream; we skip them here
+ * to avoid duplicates. Heartbeat/schedule ticks default to "no brief" because
+ * each tick is just a status nudge, not a delivery moment β€” that policy can be
+ * revisited later if we want periodic insight briefs.
+ */
+export const shouldEmitTopicBrief = (
+ input: ShouldEmitTopicBriefInput,
+): ShouldEmitTopicBriefResult => {
+ if (input.reason === 'error') return { emit: false, reason: 'error-branch-handled' };
+ if (input.reviewTerminated) return { emit: false, reason: 'judge-handled' };
+ // The judge path may not have terminated (e.g. review disabled or threw),
+ // but if review is configured we still defer to it on subsequent runs.
+ if (input.hasReviewConfigEnabled) return { emit: false, reason: 'review-config-enabled' };
+ if (input.task?.automationMode) return { emit: false, reason: 'automation-tick' };
+ if (input.isTrivialContent) return { emit: false, reason: 'trivial-content' };
+ return { emit: true };
+};
+
+/** Heuristic for "this content isn't a real delivery". */
+export const isTrivialAssistantContent = (content?: string): boolean => {
+ if (!content) return true;
+ const trimmed = content.trim();
+ if (trimmed.length < 16) return true;
+ return false;
+};
+
+/**
+ * Pick the brief type for the auto-synthesis path.
+ *
+ * For now we only emit `result` briefs β€” we treat every non-skipped topic
+ * completion as a delivery moment. Adding `insight` (mid-process observation)
+ * is a future product call.
+ */
+export const selectBriefType = (_input: ShouldEmitTopicBriefInput): BriefType => 'result';
+
+/**
+ * Pick the brief priority. `result` briefs default to `normal` so they show up
+ * in the inbox without paging the user. Reserved for future heuristics.
+ */
+export const selectBriefPriority = (_input: ShouldEmitTopicBriefInput): string => 'normal';
diff --git a/src/server/services/taskRunner/index.ts b/src/server/services/taskRunner/index.ts
index 50104559d3f..93fb2c1daef 100644
--- a/src/server/services/taskRunner/index.ts
+++ b/src/server/services/taskRunner/index.ts
@@ -132,8 +132,19 @@ export class TaskRunnerService {
const checkpoint = this.taskModel.getCheckpointConfig(task);
const reviewConfig = this.taskModel.getReviewConfig(task);
+ // Default mode is 'auto' β€” brief synthesis happens programmatically in
+ // TaskLifecycleService.synthesizeTopicBrief. 'agent' is an explicit
+ // escape hatch that re-mounts the legacy createBrief tool surface.
+ const briefMode = (
+ (task.config as { brief?: { mode?: string } } | null)?.brief?.mode === 'agent'
+ ? 'agent'
+ : 'auto'
+ ) as 'agent' | 'auto';
const pluginIds = [TaskSkillIdentifier];
- if (!reviewConfig?.enabled && checkpoint.onAgentRequest !== false) {
+ // Mount BriefIdentifier (createBrief + requestCheckpoint) only in the
+ // legacy 'agent' path; in 'auto' the agent must not also call
+ // createBrief or we'd double up.
+ if (briefMode === 'agent' && !reviewConfig?.enabled && checkpoint.onAgentRequest !== false) {
pluginIds.push(BriefIdentifier);
}
diff --git a/src/store/brief/types.ts b/src/store/brief/types.ts
index eb1531baa1e..00809926be8 100644
--- a/src/store/brief/types.ts
+++ b/src/store/brief/types.ts
@@ -1,4 +1,4 @@
-import { type BriefAction, type BriefType } from '@lobechat/types';
+import { type BriefAction, type BriefArtifacts, type BriefType } from '@lobechat/types';
export interface AgentAvatarInfo {
avatar: string | null;
@@ -11,7 +11,7 @@ export interface BriefItem {
actions: BriefAction[] | null;
agentId: string | null;
agents: AgentAvatarInfo[];
- artifacts: unknown;
+ artifacts: BriefArtifacts | null;
createdAt: Date | string;
cronJobId: string | null;
id: string;