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(task): keep a run's report when its last reply is a trailing remark (#21563)

Arvin Xub4beccdaaea6
diff --git a/apps/server/src/services/taskLifecycle/handoff.test.ts b/apps/server/src/services/taskLifecycle/handoff.test.ts
new file mode 100644
index 00000000000..8393e8a5239
--- /dev/null
+++ b/apps/server/src/services/taskLifecycle/handoff.test.ts
@@ -0,0 +1,153 @@
+// @vitest-environment node
+import type { TaskItem } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskLifecycleService } from './index';
+
+const { generateObject } = vi.hoisted(() => ({ generateObject: vi.fn() }));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn().mockResolvedValue({ generateObject }),
+}));
+vi.mock('@/server/services/taskScheduler', () => ({
+ createTaskSchedulerModule: () => ({ cancelScheduled: vi.fn(), scheduleNextTopic: vi.fn() }),
+}));
+vi.mock('@/server/services/taskRunner', () => ({
+ TaskRunnerService: vi.fn(function () {
+ return {
+ cascadeOnCompletion: vi.fn().mockResolvedValue({ failed: [], paused: [], started: [] }),
+ };
+ }),
+}));
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(function () {
+ return { findByOperation: vi.fn().mockResolvedValue(undefined) };
+ }),
+}));
+// A Goal task, so the per-topic brief stays out of the way.
+vi.mock('@/database/models/goal', () => ({
+ GoalModel: vi.fn(function () {
+ return { findByGraphTask: vi.fn().mockResolvedValue({ id: 'goal-1' }) };
+ }),
+}));
+
+const report = `# Verification passed\n\n${'Every path reopened within 500 ms. '.repeat(20)}`;
+const remark =
+ 'The background file search from earlier has finished. I had already used its output, so the verification results are unchanged.';
+
+const task = {
+ automationMode: null,
+ config: {},
+ context: {},
+ id: 'task-1',
+ identifier: 'T-1',
+ instruction: 'Verify the hover fix',
+ name: 'Hover re-verification',
+ parentTaskId: null,
+ status: 'running',
+} as unknown as TaskItem;
+
+describe('TaskLifecycleService handoff', () => {
+ let service: TaskLifecycleService;
+ let updateHandoff: ReturnType<typeof vi.fn>;
+ let updateHandoffContent: ReturnType<typeof vi.fn>;
+ let listLatestTurnAssistantContents: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ generateObject.mockReset();
+ service = new TaskLifecycleService({} as any, 'user-1');
+
+ const taskModel = (service as any).taskModel;
+ taskModel.findById = vi.fn().mockResolvedValue(task);
+ taskModel.updateHeartbeat = vi.fn();
+ taskModel.updateStatusIfCurrent = vi.fn();
+ taskModel.getCheckpointConfig = vi.fn().mockReturnValue({});
+ taskModel.shouldPauseOnTopicComplete = vi.fn().mockReturnValue(false);
+
+ updateHandoff = vi.fn();
+ updateHandoffContent = vi.fn();
+ (service as any).taskTopicModel.updateStatus = vi.fn();
+ (service as any).taskTopicModel.updateHandoff = updateHandoff;
+ (service as any).taskTopicModel.updateHandoffContent = updateHandoffContent;
+ (service as any).topicModel.update = vi.fn();
+
+ listLatestTurnAssistantContents = vi
+ .fn()
+ .mockResolvedValue([{ content: remark }, { content: report }]);
+ (service as any).messageModel.listLatestTurnAssistantContents = listLatestTurnAssistantContents;
+
+ const systemAgent = (service as any).systemAgentService;
+ systemAgent.getTaskModelConfig = vi.fn().mockResolvedValue({ model: 'm', provider: 'p' });
+ systemAgent.getUserLocale = vi.fn().mockResolvedValue('zh-CN');
+ });
+
+ const complete = () =>
+ service.onTopicComplete({
+ lastAssistantContent: remark,
+ operationId: 'op-1',
+ reason: 'done',
+ runTrigger: 'goal',
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ topicId: 'topic-1',
+ });
+
+ /**
+ * Regression: a run delivered its report, then a finished
+ * background job woke it for one remark. The handoff (and so the Goal
+ * finding) said nothing was delivered, and the coordinator re-ran the whole
+ * verification as a new Task.
+ */
+ it('keeps the earlier report as the run output when the last reply is a trailing remark', async () => {
+ generateObject.mockResolvedValue({
+ finalIsTrailingRemark: true,
+ keyFindings: [],
+ nextAction: '',
+ summary: 'All five checks passed on a real run',
+ title: 'Hover fix verified',
+ });
+
+ await complete();
+
+ const userPrompt = generateObject.mock.calls[0][0].messages[1].content as string;
+ expect(userPrompt).toContain(`Earlier report from this run:\n${report.trim()}`);
+ expect(updateHandoff).toHaveBeenCalledWith('task-1', 'topic-1', {
+ keyFindings: [],
+ nextAction: '',
+ summary: 'All five checks passed on a real run',
+ title: 'Hover fix verified',
+ });
+ expect(updateHandoffContent).toHaveBeenCalledWith('task-1', 'topic-1', report.trim());
+ });
+
+ it('keeps the last reply when it reports its own outcome', async () => {
+ generateObject.mockResolvedValue({
+ finalIsTrailingRemark: false,
+ keyFindings: [],
+ nextAction: '',
+ summary: 's',
+ title: 't',
+ });
+
+ await complete();
+
+ expect(updateHandoffContent).toHaveBeenCalledWith('task-1', 'topic-1', remark);
+ });
+
+ it('falls back to the last reply when the run lookup fails', async () => {
+ listLatestTurnAssistantContents.mockRejectedValue(new Error('db down'));
+ generateObject.mockResolvedValue({
+ finalIsTrailingRemark: true,
+ keyFindings: [],
+ nextAction: '',
+ summary: 's',
+ title: 't',
+ });
+
+ await complete();
+
+ const userPrompt = generateObject.mock.calls[0][0].messages[1].content as string;
+ expect(userPrompt).not.toContain('Earlier report');
+ expect(updateHandoffContent).toHaveBeenCalledWith('task-1', 'topic-1', remark);
+ });
+});
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 8d3453783d8..8a0a4d5ea25 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -36,6 +36,7 @@ import { notifyTaskRunFailed } from '@/business/server/task/notifyTaskRunFailed'
import { onTaskRunCompleted } from '@/business/server/task/onTaskRunCompleted';
import { BriefModel } from '@/database/models/brief';
import { GoalModel } from '@/database/models/goal';
+import { MessageModel } from '@/database/models/message';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
@@ -48,6 +49,7 @@ import { SystemAgentService } from '@/server/services/systemAgent';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
+import { RUN_REPORT_LOOKBACK, selectEarlierRunReport } from './runReport';
import {
isTrivialAssistantContent,
selectBriefPriority,
@@ -103,6 +105,7 @@ export interface TopicCompleteParams {
export class TaskLifecycleService {
private briefModel: BriefModel;
private db: LobeChatDatabase;
+ private messageModel: MessageModel;
private systemAgentService: SystemAgentService;
private taskModel: TaskModel;
private taskTopicModel: TaskTopicModel;
@@ -118,6 +121,7 @@ export class TaskLifecycleService {
this.taskModel = new TaskModel(db, userId, workspaceId);
this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);
this.briefModel = new BriefModel(db, userId, workspaceId);
+ this.messageModel = new MessageModel(db, userId, workspaceId);
this.topicModel = new TopicModel(db, userId, workspaceId);
this.systemAgentService = new SystemAgentService(db, userId, workspaceId);
}
@@ -156,23 +160,27 @@ export class TaskLifecycleService {
if (topicId) await this.taskTopicModel.updateStatus(taskId, topicId, 'completed');
// 2. Generate handoff summary + topic title (best-effort LLM synthesis).
+ // It also says which output the run delivered: its earlier report when
+ // the last message is only a trailing remark after it.
+ let runOutput = lastAssistantContent;
if (topicId && lastAssistantContent) {
- await this.generateHandoff(
- taskId,
- taskIdentifier,
- topicId,
- lastAssistantContent,
- currentTask,
- );
+ runOutput =
+ (await this.generateHandoff(
+ taskId,
+ taskIdentifier,
+ topicId,
+ lastAssistantContent,
+ currentTask,
+ )) ?? lastAssistantContent;
}
- // 2b. Persist the raw last message as the run card's result.
+ // 2b. Persist the run's output as the run card's result.
// Done independently of (and after) generateHandoff via a jsonb_set
// patch, so `handoff.content` is written even when the summary LLM in
// step 2 throws — otherwise a completed run would show no result.
- if (topicId && lastAssistantContent) {
+ if (topicId && runOutput) {
try {
- await this.taskTopicModel.updateHandoffContent(taskId, topicId, lastAssistantContent);
+ await this.taskTopicModel.updateHandoffContent(taskId, topicId, runOutput);
} catch (e) {
console.warn('[TaskLifecycle] persisting run last message failed:', e);
}
@@ -762,6 +770,10 @@ export class TaskLifecycleService {
/**
* Generate handoff summary and update topic title via LLM.
* Writes to task_topics handoff fields + updates topic title.
+ *
+ * Returns the run's earlier report when the model judged the last message to
+ * be only a trailing remark after it, so the caller persists the report as
+ * the run's output. Returns undefined otherwise, or when synthesis failed.
*/
private async generateHandoff(
taskId: string,
@@ -769,14 +781,16 @@ export class TaskLifecycleService {
topicId: string,
lastAssistantContent: string,
currentTask: any,
- ): Promise<void> {
+ ): Promise<string | undefined> {
try {
- const [{ model, provider }, responseLanguage] = await Promise.all([
+ const [{ model, provider }, responseLanguage, earlierReport] = await Promise.all([
(this.systemAgentService as any).getTaskModelConfig('topic'),
this.systemAgentService.getUserLocale(),
+ this.findEarlierRunReport(topicId, lastAssistantContent),
]);
const payload = chainTaskTopicHandoff({
+ earlierReport,
lastAssistantContent,
responseLanguage,
taskInstruction: currentTask?.instruction || '',
@@ -805,7 +819,8 @@ export class TaskLifecycleService {
},
);
- const handoff = result as {
+ const { finalIsTrailingRemark, ...handoff } = result as {
+ finalIsTrailingRemark?: boolean;
keyFindings?: string[];
nextAction?: string;
summary?: string;
@@ -823,11 +838,32 @@ export class TaskLifecycleService {
await this.taskTopicModel.updateHandoff(taskId, topicId, handoff);
log('handoff generated for topic %s: title=%s', topicId, handoff.title);
+ if (earlierReport && finalIsTrailingRemark) return earlierReport;
} catch (e) {
console.warn('[TaskLifecycle] handoff generation failed:', e);
}
}
+ /**
+ * The run's earlier report, a candidate for its real output when its last
+ * message may only be a trailing remark. Best-effort: a failed read leaves
+ * the handoff to the last message alone.
+ */
+ private async findEarlierRunReport(
+ topicId: string,
+ lastAssistantContent: string,
+ ): Promise<string | undefined> {
+ try {
+ const replies = await this.messageModel.listLatestTurnAssistantContents({
+ limit: RUN_REPORT_LOOKBACK,
+ topicId,
+ });
+ return selectEarlierRunReport(replies, lastAssistantContent);
+ } catch (e) {
+ log('earlier run report lookup failed for topic %s (non-fatal): %O', topicId, e);
+ }
+ }
+
/**
* Programmatic brief synthesis for a completed topic.
*
diff --git a/apps/server/src/services/taskLifecycle/runReport.test.ts b/apps/server/src/services/taskLifecycle/runReport.test.ts
new file mode 100644
index 00000000000..a55a0ca45b2
--- /dev/null
+++ b/apps/server/src/services/taskLifecycle/runReport.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { selectEarlierRunReport } from './runReport';
+
+const report = `# Verification passed\n\n${'Every path reopened within 500 ms. '.repeat(20)}`;
+const remark =
+ 'The background file search from earlier has finished. I had already used its output, so the verification results are unchanged.';
+
+describe('selectEarlierRunReport', () => {
+ it('returns the report a trailing remark followed', () => {
+ const replies = [
+ { content: remark },
+ { content: report },
+ { content: 'Cleaned up. Saving the new harness lessons to memory.' },
+ ];
+
+ expect(selectEarlierRunReport(replies, remark)).toBe(report.trim());
+ });
+
+ it('considers every row when the final reply was never persisted', () => {
+ expect(selectEarlierRunReport([{ content: report }], remark)).toBe(report.trim());
+ });
+
+ it('ignores a run whose earlier replies are only progress notes', () => {
+ const replies = [{ content: remark }, { content: 'Uploading screenshots.' }, { content: null }];
+
+ expect(selectEarlierRunReport(replies, remark)).toBeUndefined();
+ });
+
+ it('ignores an earlier reply that is not clearly longer than the final one', () => {
+ const final = report.slice(0, Math.ceil(report.length / 2) + 10);
+
+ expect(
+ selectEarlierRunReport([{ content: final }, { content: report }], final),
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/taskLifecycle/runReport.ts b/apps/server/src/services/taskLifecycle/runReport.ts
new file mode 100644
index 00000000000..84c2b6521d3
--- /dev/null
+++ b/apps/server/src/services/taskLifecycle/runReport.ts
@@ -0,0 +1,51 @@
+/**
+ * How many of the run's newest assistant replies are searched for its report.
+ * A run ends with its report plus, at most, a few trailing remarks.
+ */
+export const RUN_REPORT_LOOKBACK = 12;
+
+/** A reply shorter than this is a progress note, not a report. */
+const MIN_REPORT_LENGTH = 400;
+
+/** How much longer than the final reply an earlier reply must be to count as the report. */
+const REPORT_LENGTH_RATIO = 2;
+
+/**
+ * The run's earlier report, when the final reply might only be a trailing
+ * remark after it.
+ *
+ * An agent can keep talking after it delivers. For example, Claude Code is
+ * woken by a background job that finishes and acknowledges it in one line.
+ * The run's last message is then that line, not the report, and a handoff
+ * built from it alone tells the coordinator that nothing was delivered.
+ *
+ * Returns the longest earlier reply in the run's turn when it is clearly
+ * longer than the final reply. Whether the final reply really defers to it is
+ * a semantic call left to the handoff model, so this only supplies the
+ * candidate.
+ *
+ * @param repliesNewestFirst - the turn's assistant replies, newest first
+ * @param finalContent - the run's final reply
+ */
+export const selectEarlierRunReport = (
+ repliesNewestFirst: readonly { content: string | null }[],
+ finalContent: string,
+): string | undefined => {
+ const final = finalContent.trim();
+ // The newest row is normally the final reply itself. Skip it only when it
+ // matches, so a final reply that was never persisted leaves every row a candidate.
+ const earlier =
+ repliesNewestFirst[0]?.content?.trim() === final
+ ? repliesNewestFirst.slice(1)
+ : repliesNewestFirst;
+
+ let report: string | undefined;
+ for (const reply of earlier) {
+ const content = reply.content?.trim();
+ if (content && content.length > (report?.length ?? 0)) report = content;
+ }
+
+ if (!report || report.length < MIN_REPORT_LENGTH) return;
+ if (report.length < final.length * REPORT_LENGTH_RATIO) return;
+ return report;
+};
diff --git a/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts b/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts
index b97c235977c..c86cb5e26f3 100644
--- a/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts
@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import { messages, topics, users } from '../../../schemas';
+import { messages, threads, topics, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
@@ -180,3 +180,99 @@ describe('MessageModel.findVerifyMessageByOperationId', () => {
).resolves.toBeUndefined();
});
});
+
+describe('MessageModel.listLatestTurnAssistantContents', () => {
+ const at = (minute: number) => new Date(Date.UTC(2026, 9, 22, 19, minute));
+ const insert = (
+ rows: { content: string; id: string; minute: number; role: string; threadId?: string }[],
+ ) =>
+ serverDB.insert(messages).values(
+ rows.map(({ minute, ...row }) => ({
+ ...row,
+ createdAt: at(minute),
+ topicId,
+ updatedAt: at(minute),
+ userId,
+ })),
+ );
+
+ it("returns the latest turn's assistant replies newest first", async () => {
+ await insert([
+ { content: 'previous run prompt', id: 'turn-u1', minute: 0, role: 'user' },
+ { content: 'previous run report', id: 'turn-a1', minute: 1, role: 'assistant' },
+ { content: 'run prompt', id: 'turn-u2', minute: 2, role: 'user' },
+ { content: 'progress note', id: 'turn-a2', minute: 3, role: 'assistant' },
+ { content: 'tool output', id: 'turn-t1', minute: 4, role: 'tool' },
+ { content: 'final report', id: 'turn-a3', minute: 5, role: 'assistant' },
+ { content: 'trailing remark', id: 'turn-a4', minute: 6, role: 'assistant' },
+ ]);
+
+ const replies = await messageModel.listLatestTurnAssistantContents({ limit: 10, topicId });
+
+ expect(replies.map((reply) => reply.content)).toEqual([
+ 'trailing remark',
+ 'final report',
+ 'progress note',
+ ]);
+ });
+
+ it('ignores subagent thread rows sharing the topic', async () => {
+ await serverDB
+ .insert(threads)
+ .values({ id: 'turn-thread', topicId, type: 'isolation', userId });
+ await insert([
+ { content: 'run prompt', id: 'sub-u1', minute: 0, role: 'user' },
+ { content: 'parent report', id: 'sub-a1', minute: 1, role: 'assistant' },
+ {
+ content: 'subagent prompt',
+ id: 'sub-u2',
+ minute: 2,
+ role: 'user',
+ threadId: 'turn-thread',
+ },
+ {
+ content: 'subagent partial result',
+ id: 'sub-a2',
+ minute: 3,
+ role: 'assistant',
+ threadId: 'turn-thread',
+ },
+ { content: 'trailing remark', id: 'sub-a3', minute: 4, role: 'assistant' },
+ ]);
+
+ const replies = await messageModel.listLatestTurnAssistantContents({ limit: 10, topicId });
+
+ expect(replies.map((reply) => reply.content)).toEqual(['trailing remark', 'parent report']);
+ });
+
+ it('honors the limit', async () => {
+ await insert([
+ { content: 'run prompt', id: 'limit-u1', minute: 0, role: 'user' },
+ { content: 'a', id: 'limit-a1', minute: 1, role: 'assistant' },
+ { content: 'b', id: 'limit-a2', minute: 2, role: 'assistant' },
+ ]);
+
+ const replies = await messageModel.listLatestTurnAssistantContents({ limit: 1, topicId });
+
+ expect(replies.map((reply) => reply.content)).toEqual(['b']);
+ });
+
+ it('returns every assistant reply of a topic without a user message', async () => {
+ await insert([{ content: 'only reply', id: 'nouser-a1', minute: 1, role: 'assistant' }]);
+
+ await expect(
+ messageModel.listLatestTurnAssistantContents({ limit: 10, topicId }),
+ ).resolves.toEqual([{ content: 'only reply', createdAt: at(1) }]);
+ });
+
+ it("does not read another user's topic", async () => {
+ await insert([{ content: 'mine', id: 'own-a1', minute: 1, role: 'assistant' }]);
+
+ await expect(
+ new MessageModel(serverDB, otherUserId).listLatestTurnAssistantContents({
+ limit: 10,
+ topicId,
+ }),
+ ).resolves.toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.ts
index 81debe12000..7798dc07689 100644
--- a/packages/database/src/models/message/index.ts
+++ b/packages/database/src/models/message/index.ts
@@ -35,6 +35,7 @@ export class MessageModel {
findLatestAssistantMessageByThread: MessageLookupQueries['findLatestAssistantMessageByThread'];
findVerifyMessageByOperationId: MessageLookupQueries['findVerifyMessageByOperationId'];
findLatestAssistantByOperationId: MessageLookupQueries['findLatestAssistantByOperationId'];
+ listLatestTurnAssistantContents: MessageLookupQueries['listLatestTurnAssistantContents'];
getThreadParentMessages: MessageLookupQueries['getThreadParentMessages'];
findMessageQueriesById: MessageLookupQueries['findMessageQueriesById'];
queryBySessionId: MessageLookupQueries['queryBySessionId'];
@@ -147,6 +148,7 @@ export class MessageModel {
this.findLatestAssistantMessageByThread = lookups.findLatestAssistantMessageByThread;
this.findVerifyMessageByOperationId = lookups.findVerifyMessageByOperationId;
this.findLatestAssistantByOperationId = lookups.findLatestAssistantByOperationId;
+ this.listLatestTurnAssistantContents = lookups.listLatestTurnAssistantContents;
this.getThreadParentMessages = lookups.getThreadParentMessages;
this.findMessageQueriesById = lookups.findMessageQueriesById;
this.queryBySessionId = lookups.queryBySessionId;
diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.ts
index bda2655064d..8b6ef4073ae 100644
--- a/packages/database/src/models/message/lookup.ts
+++ b/packages/database/src/models/message/lookup.ts
@@ -201,6 +201,67 @@ export class MessageLookupQueries extends MessageScope {
});
};
+ /**
+ * The newest assistant replies of a topic's latest turn — every main-thread
+ * assistant row written after the main thread's last user message — newest
+ * first, content only.
+ *
+ * Used by the task lifecycle to find a run's final report when the run's very
+ * last reply is only a trailing remark. Heterogeneous runs (Claude Code,
+ * Codex) carry no `metadata.operationId` on their rows, so the latest user
+ * message (the run prompt) is what bounds the run inside its topic.
+ * Subagent rows share the topic under their own `threadId`, so both the
+ * boundary and the replies are read from the main thread only.
+ */
+ listLatestTurnAssistantContents = async ({
+ limit,
+ topicId,
+ }: {
+ limit: number;
+ topicId: string;
+ }): Promise<{ content: string | null; createdAt: Date }[]> => {
+ const lastUserAt = this.db
+ .select({ createdAt: sql`max(${messages.createdAt})` })
+ .from(messages)
+ .where(
+ and(
+ this.ownership(),
+ eq(messages.topicId, topicId),
+ isNull(messages.threadId),
+ eq(messages.role, 'user'),
+ ),
+ );
+
+ return this.db
+ .select({ content: messages.content, createdAt: messages.createdAt })
+ .from(messages)
+ .where(
+ and(
+ this.ownership(),
+ inArray(
+ messages.topicId,
+ this.db
+ .select({ id: topics.id })
+ .from(topics)
+ .where(
+ and(
+ eq(topics.id, topicId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ topics,
+ ),
+ ),
+ ),
+ ),
+ isNull(messages.threadId),
+ eq(messages.role, 'assistant'),
+ sql`${messages.createdAt} >= coalesce((${lastUserAt}), '-infinity'::timestamptz)`,
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(limit);
+ };
+
/**
* Get parent messages for a thread
*
diff --git a/packages/prompts/src/chains/taskTopicHandoff.test.ts b/packages/prompts/src/chains/taskTopicHandoff.test.ts
index 1484c704f63..c40ac9167b0 100644
--- a/packages/prompts/src/chains/taskTopicHandoff.test.ts
+++ b/packages/prompts/src/chains/taskTopicHandoff.test.ts
@@ -16,9 +16,42 @@ describe('chainTaskTopicHandoff', () => {
});
const system = payload.messages![0].content as string;
- expect(TASK_TOPIC_HANDOFF_PROMPT_VERSION).toBe('v1.1');
+ expect(TASK_TOPIC_HANDOFF_PROMPT_VERSION).toBe('v1.2');
expect(system).toContain('what was found, decided or delivered');
expect(system).toContain('never a status such as "Completed X", "Task done" or "完成 X"');
expect(system).toContain('condense that line into the title');
});
+
+ /**
+ * Regression: a Claude Code run delivered its full verification report, then a
+ * finished background job woke it for one more line ("results are unchanged").
+ * The handoff saw only that line and told the Goal coordinator nothing was
+ * delivered, which re-dispatched the whole verification as a new Task.
+ */
+ it('hands the earlier report to the model when the last reply may be a trailing remark', () => {
+ const payload = chainTaskTopicHandoff({
+ earlierReport: '# Verification passed\n\nAll five checks passed.',
+ lastAssistantContent: 'The background file search has finished; the results are unchanged.',
+ taskInstruction: 'Verify the hover fix',
+ taskName: 'T-1',
+ });
+ const system = payload.messages![0].content as string;
+ const user = payload.messages![1].content as string;
+
+ expect(system).toContain('base title, summary and keyFindings on the earlier report');
+ expect(system).toContain('A trailing remark never means the run delivered nothing');
+ expect(user).toContain('Earlier report from this run:\n# Verification passed');
+ expect(user.indexOf('Earlier report')).toBeLessThan(user.indexOf('Last assistant response'));
+ });
+
+ it('omits the earlier-report block when the run has none', () => {
+ const payload = chainTaskTopicHandoff({
+ lastAssistantContent: 'done',
+ taskInstruction: 'x',
+ taskName: 'y',
+ });
+
+ expect(payload.messages![1].content).not.toContain('Earlier report');
+ expect(payload.messages![0].content).toContain('Set "finalIsTrailingRemark" to false');
+ });
});
diff --git a/packages/prompts/src/chains/taskTopicHandoff.ts b/packages/prompts/src/chains/taskTopicHandoff.ts
index 3ea20503747..912ff44e02f 100644
--- a/packages/prompts/src/chains/taskTopicHandoff.ts
+++ b/packages/prompts/src/chains/taskTopicHandoff.ts
@@ -5,7 +5,7 @@ import type { ChatStreamPayload } from '@lobechat/types';
* `tracing.promptVersion` at the call site so per-call tracing groups runs
* by prompt iteration.
*/
-export const TASK_TOPIC_HANDOFF_PROMPT_VERSION = 'v1.1';
+export const TASK_TOPIC_HANDOFF_PROMPT_VERSION = 'v1.2';
export const TASK_TOPIC_HANDOFF_SCHEMA_NAME = 'task_topic_handoff';
@@ -13,10 +13,13 @@ export const TASK_TOPIC_HANDOFF_SCHEMA_NAME = 'task_topic_handoff';
* Generate a handoff summary for a completed task topic.
* Returns both a title and structured handoff data for the next topic.
*
- * Input: the last assistant message content from the topic.
- * Output: JSON with { title, summary, keyFindings?, nextAction? }
+ * Input: the last assistant message content from the topic, plus the run's
+ * earlier report when the last message may only be a trailing remark after it.
+ * Output: JSON with { title, summary, keyFindings?, nextAction, finalIsTrailingRemark }
*/
export const chainTaskTopicHandoff = (params: {
+ /** The run's longest earlier reply, when it is clearly longer than the last one. */
+ earlierReport?: string;
lastAssistantContent: string;
responseLanguage?: string;
taskInstruction: string;
@@ -26,6 +29,20 @@ export const chainTaskTopicHandoff = (params: {
? `Output language: ${params.responseLanguage}. Always use this language for title and summary regardless of the content language.`
: 'Use the same language as the content.';
+ const earlierReportRules = params.earlierReport
+ ? `
+- An earlier report from the same run is included. The last response is the outcome by default. When it is only a trailing remark after that report, base title, summary and keyFindings on the earlier report and set "finalIsTrailingRemark" to true. Trailing remarks include acknowledging a background job that finished, describing cleanup, or saying the results above are unchanged. A trailing remark never means the run delivered nothing
+- Set "finalIsTrailingRemark" to false when the last response reports its own outcome, including one that replaces or corrects the earlier report`
+ : `
+- Set "finalIsTrailingRemark" to false`;
+
+ const earlierReportBlock = params.earlierReport
+ ? `Earlier report from this run:
+${params.earlierReport}
+
+`
+ : '';
+
return {
messages: [
{
@@ -36,6 +53,7 @@ Output a JSON object with these fields:
- "summary": A 1-3 sentence summary of what was done and the key outcome
- "keyFindings": An array of key findings or decisions made (optional, max 5 items)
- "nextAction": What the next topic should do (optional, 1 sentence)
+- "finalIsTrailingRemark": Whether the last response is only a trailing remark after the run's earlier report
Rules:
- Focus on WHAT WAS ACCOMPLISHED, not what was asked
@@ -43,14 +61,14 @@ Rules:
- The title states the result itself, not that work happened: never a status such as "Completed X", "Task done" or "完成 X". If the response opens with an explicit conclusion line, condense that line into the title
- Keep title short and specific
- summary should capture the essential outcome a new topic needs to know
-- Output ONLY the JSON object, no markdown fences or explanations`,
+- Output ONLY the JSON object, no markdown fences or explanations${earlierReportRules}`,
role: 'system',
},
{
content: `Task: ${params.taskName}
Task instruction: ${params.taskInstruction}
-Last assistant response:
+${earlierReportBlock}Last assistant response:
${params.lastAssistantContent}`,
role: 'user',
},
@@ -61,6 +79,7 @@ ${params.lastAssistantContent}`,
export const TASK_TOPIC_HANDOFF_SCHEMA = {
additionalProperties: false,
properties: {
+ finalIsTrailingRemark: { type: 'boolean' },
keyFindings: {
items: { type: 'string' },
type: 'array',
@@ -69,6 +88,6 @@ export const TASK_TOPIC_HANDOFF_SCHEMA = {
summary: { type: 'string' },
title: { type: 'string' },
},
- required: ['title', 'summary', 'keyFindings', 'nextAction'],
+ required: ['title', 'summary', 'keyFindings', 'nextAction', 'finalIsTrailingRemark'],
type: 'object' as const,
};
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 6ef20330b48..4b454d703fc 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -225,7 +225,8 @@ export interface TaskTopicHandoff {
*/
briefDecision?: BriefDecision;
/**
- * Raw last assistant message of the run, captured on completion.
+ * Raw output of the run, captured on completion: its last assistant message,
+ * or its earlier report when that message was only a trailing remark.
* Shown on the run card alongside the LLM-synthesized `summary` so the feed
* surfaces the actual run output, not only the summary.
*/