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.

πŸ’„ style(taskDetail): force daily briefs for scheduled tasks; switch activity timestamps to absolute date (#14367)

Arvin Xu3cb06e07e367
diff --git a/package.json b/package.json
index 808028bc481..5a96f028637 100644
--- a/package.json
+++ b/package.json
@@ -193,7 +193,7 @@
"@fal-ai/client": "^1.8.4",
"@floating-ui/react": "^0.27.19",
"@formkit/auto-animate": "^0.9.0",
- "@google/genai": "^1.38.0",
+ "@google/genai": "~1.50.1",
"@henrygd/queue": "^1.2.0",
"@huggingface/inference": "^4.13.10",
"@icons-pack/react-simple-icons": "^13.8.0",
diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.ts
index 8110d65b23c..012f190e8b0 100644
--- a/packages/database/src/models/__tests__/taskTopic.test.ts
+++ b/packages/database/src/models/__tests__/taskTopic.test.ts
@@ -242,6 +242,90 @@ describe('TaskTopicModel', () => {
});
});
+ describe('updateBriefDecision', () => {
+ it('patches briefDecision into a fresh handoff JSONB (no prior handoff)', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_bd_a');
+
+ await topicModel.add(task.id, 'tpc_bd_a', { seq: 1 });
+ await topicModel.updateBriefDecision(task.id, 'tpc_bd_a', {
+ decidedAt: '2026-05-01T12:00:00.000Z',
+ emit: false,
+ reason: 'heartbeat-tick',
+ source: 'rule',
+ });
+
+ const topics = await topicModel.findByTaskId(task.id);
+ const handoff = topics[0].handoff as any;
+ expect(handoff.briefDecision).toEqual({
+ decidedAt: '2026-05-01T12:00:00.000Z',
+ emit: false,
+ reason: 'heartbeat-tick',
+ source: 'rule',
+ });
+ });
+
+ it('preserves existing handoff fields when patching briefDecision', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_bd_b');
+
+ await topicModel.add(task.id, 'tpc_bd_b', { seq: 1 });
+ await topicModel.updateHandoff(task.id, 'tpc_bd_b', {
+ keyFindings: ['F1'],
+ nextAction: 'Next',
+ summary: 'Sum',
+ title: 'T',
+ });
+ await topicModel.updateBriefDecision(task.id, 'tpc_bd_b', {
+ decidedAt: '2026-05-01T12:00:00.000Z',
+ emit: true,
+ model: 'opus-4',
+ reason: 'finished deliverable',
+ source: 'llm-judge',
+ });
+
+ const topics = await topicModel.findByTaskId(task.id);
+ const handoff = topics[0].handoff as any;
+ expect(handoff.title).toBe('T');
+ expect(handoff.summary).toBe('Sum');
+ expect(handoff.nextAction).toBe('Next');
+ expect(handoff.keyFindings).toEqual(['F1']);
+ expect(handoff.briefDecision.emit).toBe(true);
+ expect(handoff.briefDecision.source).toBe('llm-judge');
+ expect(handoff.briefDecision.model).toBe('opus-4');
+ });
+
+ it('overwrites a previous briefDecision on re-emit (e.g. retry)', async () => {
+ const taskModel = new TaskModel(serverDB, userId);
+ const topicModel = new TaskTopicModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Test' });
+ await createTopic('tpc_bd_c');
+
+ await topicModel.add(task.id, 'tpc_bd_c', { seq: 1 });
+ await topicModel.updateBriefDecision(task.id, 'tpc_bd_c', {
+ decidedAt: '2026-05-01T11:00:00.000Z',
+ emit: false,
+ reason: 'first call',
+ source: 'rule',
+ });
+ await topicModel.updateBriefDecision(task.id, 'tpc_bd_c', {
+ decidedAt: '2026-05-01T12:00:00.000Z',
+ emit: true,
+ reason: 'second call',
+ source: 'llm-judge',
+ });
+
+ const topics = await topicModel.findByTaskId(task.id);
+ const handoff = topics[0].handoff as any;
+ expect(handoff.briefDecision.emit).toBe(true);
+ expect(handoff.briefDecision.reason).toBe('second call');
+ });
+ });
+
describe('updateReview', () => {
it('should store review results', async () => {
const taskModel = new TaskModel(serverDB, userId);
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index 5e750afb73c..31a8f4f44b0 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -1,4 +1,4 @@
-import type { TaskTopicHandoff } from '@lobechat/types';
+import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';
import { and, desc, eq, sql } from 'drizzle-orm';
import type { TaskTopicItem } from '../schemas/task';
@@ -115,6 +115,31 @@ export class TaskTopicModel {
);
}
+ /**
+ * Patch the `briefDecision` field inside the handoff JSONB without
+ * disturbing other handoff keys (`title` / `summary` / `keyFindings` /
+ * `nextAction`). Uses `jsonb_set` so the operation is order-independent
+ * with respect to `updateHandoff` β€” either can run first.
+ */
+ async updateBriefDecision(
+ taskId: string,
+ topicId: string,
+ decision: BriefDecision,
+ ): Promise<void> {
+ await this.db
+ .update(taskTopics)
+ .set({
+ handoff: sql`jsonb_set(COALESCE(${taskTopics.handoff}, '{}'::jsonb), '{briefDecision}', ${JSON.stringify(decision)}::jsonb)`,
+ })
+ .where(
+ and(
+ eq(taskTopics.taskId, taskId),
+ eq(taskTopics.topicId, topicId),
+ eq(taskTopics.userId, this.userId),
+ ),
+ );
+ }
+
async updateReview(
taskId: string,
topicId: string,
diff --git a/packages/prompts/src/chains/__tests__/generateBrief.test.ts b/packages/prompts/src/chains/__tests__/generateBrief.test.ts
new file mode 100644
index 00000000000..65134839935
--- /dev/null
+++ b/packages/prompts/src/chains/__tests__/generateBrief.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { chainGenerateBrief, GENERATE_BRIEF_SCHEMA } from '../generateBrief';
+
+describe('chainGenerateBrief', () => {
+ const baseParams = {
+ artifacts: null,
+ handoff: null,
+ lastAssistantContent: 'Drafted the Q2 plan and pinned three documents.',
+ taskInstruction: 'Plan Q2 priorities.',
+ taskName: 'Q2 Planning',
+ };
+
+ it('produces a payload that mandates non-empty title + summary, with no skip option', () => {
+ const payload = chainGenerateBrief(baseParams);
+ const system = (payload.messages?.[0] as { content: string }).content;
+
+ expect(system).toContain('already been judged worth surfacing');
+ expect(system).toContain('no skip option');
+ expect(system).toContain('no emit vote');
+ expect(system).toMatch(/non-empty title and summary/i);
+ });
+
+ it('embeds task name + instruction + assistant content in the user message', () => {
+ const payload = chainGenerateBrief(baseParams);
+ const user = (payload.messages?.[1] as { content: string }).content;
+
+ expect(user).toContain('Q2 Planning');
+ expect(user).toContain('Plan Q2 priorities.');
+ expect(user).toContain('Drafted the Q2 plan and pinned three documents.');
+ });
+
+ it('renders an empty handoff and empty artifacts block when both are null', () => {
+ const payload = chainGenerateBrief(baseParams);
+ const user = (payload.messages?.[1] as { content: string }).content;
+
+ expect(user).toContain('Handoff summary: (not available)');
+ expect(user).toContain('Artifacts: (none)');
+ });
+});
+
+describe('GENERATE_BRIEF_SCHEMA', () => {
+ it('only requires title + summary β€” emit was moved to chainJudgeBriefEmit', () => {
+ expect(GENERATE_BRIEF_SCHEMA.required).toEqual(['title', 'summary']);
+ expect(Object.keys(GENERATE_BRIEF_SCHEMA.properties)).toEqual(['summary', 'title']);
+ expect((GENERATE_BRIEF_SCHEMA.properties as any).emit).toBeUndefined();
+ });
+});
diff --git a/packages/prompts/src/chains/__tests__/judgeBriefEmit.test.ts b/packages/prompts/src/chains/__tests__/judgeBriefEmit.test.ts
new file mode 100644
index 00000000000..761d489473d
--- /dev/null
+++ b/packages/prompts/src/chains/__tests__/judgeBriefEmit.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { chainJudgeBriefEmit, JUDGE_BRIEF_EMIT_SCHEMA } from '../judgeBriefEmit';
+
+describe('chainJudgeBriefEmit', () => {
+ const baseParams = {
+ artifacts: null,
+ handoff: null,
+ lastAssistantContent: 'Drafted the Q2 plan and pinned three documents.',
+ taskInstruction: 'Plan Q2 priorities.',
+ taskName: 'Q2 Planning',
+ };
+
+ it('asks only for an emit/skip verdict, not for title/summary copy', () => {
+ const payload = chainJudgeBriefEmit(baseParams);
+ const system = (payload.messages?.[0] as { content: string }).content;
+
+ expect(system).toContain('decide whether the topic just completed is worth reporting');
+ expect(system).toContain('Your only job here is the emit/skip judgment');
+ expect(system).toMatch(/do NOT write them/i);
+ });
+
+ it('embeds the same task / handoff / artifacts context as the generation chain', () => {
+ const payload = chainJudgeBriefEmit({
+ ...baseParams,
+ handoff: {
+ keyFindings: ['Q1 missed targets'],
+ nextAction: 'review with stakeholders',
+ summary: 'Plan is ready for review.',
+ title: 'Q2 plan ready',
+ },
+ });
+ const user = (payload.messages?.[1] as { content: string }).content;
+
+ expect(user).toContain('Q2 Planning');
+ expect(user).toContain('Q2 plan ready');
+ expect(user).toContain('Q1 missed targets');
+ expect(user).toContain('review with stakeholders');
+ });
+});
+
+describe('JUDGE_BRIEF_EMIT_SCHEMA', () => {
+ it('schema requires emit + reason and forbids extra keys', () => {
+ expect(JUDGE_BRIEF_EMIT_SCHEMA.required).toEqual(['emit', 'reason']);
+ expect(JUDGE_BRIEF_EMIT_SCHEMA.additionalProperties).toBe(false);
+ expect(Object.keys(JUDGE_BRIEF_EMIT_SCHEMA.properties)).toEqual(['emit', 'reason']);
+ });
+});
diff --git a/packages/prompts/src/chains/generateBrief.ts b/packages/prompts/src/chains/generateBrief.ts
index fbfc7ffe9f7..711a641018b 100644
--- a/packages/prompts/src/chains/generateBrief.ts
+++ b/packages/prompts/src/chains/generateBrief.ts
@@ -1,7 +1,14 @@
import type { BriefArtifacts, ChatStreamPayload, TaskTopicHandoff } from '@lobechat/types';
/**
- * Generate a user-facing brief for a completed topic.
+ * Generate the user-facing copy (title + summary) for a brief.
+ *
+ * This chain is invoked ONLY after the emit decision has been made elsewhere
+ * (`shouldEmitTopicBrief` rule layer + optional `chainJudgeBriefEmit` LLM
+ * judge). It assumes the caller has already decided "yes, emit a brief" β€” so
+ * it never votes on emission and never returns an empty title/summary. There
+ * is no skip option, no scheduled-mode fork: every call must produce a real
+ * delivery report.
*
* Brief and handoff are NOT the same thing:
* - handoff is the agent's internal "cheat sheet" for the next tick β€” terse,
@@ -34,39 +41,29 @@ export const chainGenerateBrief = (params: {
${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.
+ const systemContent = `You are writing the user-facing brief for a topic that has already been judged worth surfacing. Your job is to produce a short delivery report β€” no skip option, no emit vote. Always return a non-empty title and 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.
+- "title": string. A non-empty user-facing headline (max 60 chars, same language as the assistant's content). Required.
+- "summary": string. A 2-4 sentence delivery report describing what was produced or observed and why it matters to the user. Required, non-empty.
-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.
+If the topic has little new activity ("no new tickets today", "no changes since last run"), state that outcome plainly in the summary β€” that itself is the report. Do not invent activity that did not occur.
-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):
+Voice and style:
- 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.
+- Lead with the outcome (what changed, what was found, what is unchanged).
+- Do NOT reference internal tool names, 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.`,
+Output ONLY the JSON object, no markdown fences or explanations.`;
+
+ return {
+ messages: [
+ {
+ content: systemContent,
role: 'system',
},
{
@@ -88,10 +85,9 @@ ${params.lastAssistantContent}`,
export const GENERATE_BRIEF_SCHEMA = {
additionalProperties: false,
properties: {
- emit: { type: 'boolean' },
summary: { type: 'string' },
title: { type: 'string' },
},
- required: ['emit', 'title', 'summary'],
+ required: ['title', 'summary'],
type: 'object' as const,
};
diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.ts
index dde2a19c0f6..77db79da101 100644
--- a/packages/prompts/src/chains/index.ts
+++ b/packages/prompts/src/chains/index.ts
@@ -4,6 +4,7 @@ export * from './answerWithContext';
export * from './compressContext';
export * from './generateBrief';
export * from './inputCompletion';
+export * from './judgeBriefEmit';
export * from './langDetect';
export * from './pickEmoji';
export * from './rewriteGenerationPrompt';
diff --git a/packages/prompts/src/chains/judgeBriefEmit.ts b/packages/prompts/src/chains/judgeBriefEmit.ts
new file mode 100644
index 00000000000..aae26d9d778
--- /dev/null
+++ b/packages/prompts/src/chains/judgeBriefEmit.ts
@@ -0,0 +1,87 @@
+import type { BriefArtifacts, ChatStreamPayload, TaskTopicHandoff } from '@lobechat/types';
+
+/**
+ * Decide whether a completed topic is worth surfacing to the user as a brief.
+ *
+ * Split from `chainGenerateBrief` so the two stages stay independent: the
+ * deterministic rule layer (`shouldEmitTopicBrief`) handles the obvious skips
+ * and the obvious emits; this chain is invoked only when the rule returns
+ * `'unknown'`, i.e. a non-trivial manual/non-scheduled topic where whether it
+ * is "delivery" vs "mid-process" requires reading the actual content.
+ *
+ * Returns just an emit verdict + a short reason for logs. Title and summary
+ * are generated separately via `chainGenerateBrief` only when emit=true, so
+ * we never spend tokens drafting copy that will be thrown away.
+ */
+export const chainJudgeBriefEmit = (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)';
+
+ const systemContent = `You decide whether the topic just completed is worth reporting to the end user as a "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 only job here is the emit/skip judgment. Title and summary copy is produced by a separate step; do NOT write them.
+
+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.
+- "reason": string. A short (max ~120 chars) one-line note explaining the verdict, in English. Used for operator logs and audit only β€” the user does 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.
+
+Output ONLY the JSON object, no markdown fences or explanations.`;
+
+ return {
+ messages: [
+ {
+ content: systemContent,
+ role: 'system',
+ },
+ {
+ content: `Task: ${params.taskName}
+Task instruction: ${params.taskInstruction}
+
+${handoffBlock}
+
+${artifactsBlock}
+
+Last assistant response:
+${params.lastAssistantContent}`,
+ role: 'user',
+ },
+ ],
+ };
+};
+
+export const JUDGE_BRIEF_EMIT_SCHEMA = {
+ additionalProperties: false,
+ properties: {
+ emit: { type: 'boolean' },
+ reason: { type: 'string' },
+ },
+ required: ['emit', 'reason'],
+ type: 'object' as const,
+};
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 5749f8cf67d..0e284e81219 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -54,7 +54,33 @@ export interface WorkspaceData {
tree: WorkspaceTreeNode[];
}
+/**
+ * Audit record of the brief-emission decision for a completed topic.
+ *
+ * Persisted under `taskTopics.handoff.briefDecision`. Written for *every*
+ * synthesizeTopicBrief invocation (rule-conclusive and LLM-deferred alike) so
+ * the emit/skip outcome is inspectable per topic.
+ *
+ * - source='rule' β€” the deterministic gate (`shouldEmitTopicBrief`) was
+ * conclusive on its own. `reason` mirrors the rule's reason string.
+ * - source='llm-judge' β€” the rule returned 'unknown' and an LLM made the call
+ * via `chainJudgeBriefEmit`. `model` records which model voted.
+ */
+export interface BriefDecision {
+ decidedAt: string;
+ emit: boolean;
+ model?: string;
+ reason: string;
+ source: 'rule' | 'llm-judge';
+}
+
export interface TaskTopicHandoff {
+ /**
+ * Outcome of the emit-vs-skip decision for the brief on this topic. The
+ * three LLM-produced fields above are agent-internal; this one is metadata
+ * about the brief delivery itself, written by the lifecycle service.
+ */
+ briefDecision?: BriefDecision;
keyFindings?: string[];
nextAction?: string;
summary?: string;
diff --git a/packages/utils/src/time.test.ts b/packages/utils/src/time.test.ts
index 2c363e4d491..c5d8046fa2e 100644
--- a/packages/utils/src/time.test.ts
+++ b/packages/utils/src/time.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
daysAgo,
+ formatActivityTime,
getYYYYmmddHHMMss,
hoursAgo,
isNewReleaseDate,
@@ -291,4 +292,45 @@ describe('time utilities', () => {
expect(isNewReleaseDate(date, 5)).toBe(false);
});
});
+
+ describe('formatActivityTime', () => {
+ it('uses relative phrasing when the gap is below one day', () => {
+ const input = '2026-05-01T05:00:00Z';
+ const result = formatActivityTime(input, {
+ now: '2026-05-01T14:00:00Z',
+ });
+ expect(result.text).toMatch(/hours? ago/);
+ // title is rendered in local timezone β€” derive expected value the same
+ // way so the assertion stays correct regardless of the runner's TZ.
+ expect(result.title).toBe(dayjs(input).format('YYYY-MM-DD HH:mm:ss'));
+ });
+
+ it('switches to absolute date once the gap exceeds one day', () => {
+ const result = formatActivityTime('2026-04-29T10:00:00Z', {
+ now: '2026-05-01T10:00:00Z',
+ });
+ expect(result.text).toBe('Apr 29');
+ });
+
+ it('uses the cross-year format when the year differs', () => {
+ const result = formatActivityTime('2025-12-30T10:00:00Z', {
+ now: '2026-05-01T10:00:00Z',
+ });
+ expect(result.text).toBe('Dec 30, 2025');
+ });
+
+ it('honors custom locale format strings', () => {
+ const result = formatActivityTime('2026-04-29T10:00:00Z', {
+ formatOtherYear: 'YYYYεΉ΄M月Dζ—₯',
+ formatThisYear: 'M月Dζ—₯',
+ now: '2026-05-01T10:00:00Z',
+ });
+ expect(result.text).toBe('4月29ζ—₯');
+ });
+
+ it('returns empty strings for missing or invalid input', () => {
+ expect(formatActivityTime()).toEqual({ text: '', title: '' });
+ expect(formatActivityTime('not a date')).toEqual({ text: '', title: '' });
+ });
+ });
});
diff --git a/packages/utils/src/time.ts b/packages/utils/src/time.ts
index 5470082786d..260c56babd4 100644
--- a/packages/utils/src/time.ts
+++ b/packages/utils/src/time.ts
@@ -1,5 +1,8 @@
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+
+dayjs.extend(relativeTime);
const getQuarterStart = (date: Dayjs) => {
const month = date.month();
@@ -44,3 +47,51 @@ export function getYYYYmmddHHMMss(date: Date) {
export const isNewReleaseDate = (date: string, days = 14) => {
return dayjs().diff(dayjs(date), 'day') < days;
};
+
+export interface FormatActivityTimeOptions {
+ formatOtherYear?: string;
+ formatThisYear?: string;
+ fullDateTimeFormat?: string;
+ now?: Date | string | number;
+ /** Threshold (ms) below which `from()` is used. Default: 1 day. */
+ relativeThresholdMs?: number;
+}
+
+export interface FormattedActivityTime {
+ /** Short label rendered inline. */
+ text: string;
+ /** Full datetime, intended for the native `title` tooltip. */
+ title: string;
+}
+
+const ACTIVITY_TIME_DAY_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * Format a timestamp for an activity-feed entry: relative (`from()`) when
+ * recent, absolute date (`Apr 29` / `4月29ζ—₯`) once the gap crosses one day.
+ */
+export const formatActivityTime = (
+ time?: string | Date | number | null,
+ options: FormatActivityTimeOptions = {},
+): FormattedActivityTime => {
+ if (!time) return { text: '', title: '' };
+ const date = dayjs(time);
+ if (!date.isValid()) return { text: '', title: '' };
+
+ const {
+ formatOtherYear = 'MMM D, YYYY',
+ formatThisYear = 'MMM D',
+ fullDateTimeFormat = 'YYYY-MM-DD HH:mm:ss',
+ now = new Date(),
+ relativeThresholdMs = ACTIVITY_TIME_DAY_MS,
+ } = options;
+
+ const current = dayjs(now);
+ const diff = Math.abs(current.diff(date));
+ const text =
+ diff < relativeThresholdMs
+ ? date.from(current)
+ : date.format(date.isSame(current, 'year') ? formatThisYear : formatOtherYear);
+
+ return { text, title: date.format(fullDateTimeFormat) };
+};
diff --git a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx
index 32a6ae27f18..43597a62112 100644
--- a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx
@@ -1,4 +1,5 @@
import type { TaskDetailActivity } from '@lobechat/types';
+import { formatActivityTime } from '@lobechat/utils/time';
import { Editor, useEditor } from '@lobehub/editor/react';
import {
ActionIcon,
@@ -14,7 +15,6 @@ import {
} from '@lobehub/ui';
import { App } from 'antd';
import { cssVar } from 'antd-style';
-import dayjs from 'dayjs';
import { MessageCircle, MoreHorizontal, Pencil, Trash } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -29,6 +29,7 @@ interface CommentCardProps {
const CommentCard = memo<CommentCardProps>(({ activity }) => {
const { t } = useTranslation('chat');
+ const { t: tDiscover } = useTranslation('discover');
const { modal } = App.useApp();
const deleteComment = useTaskStore((s) => s.deleteComment);
const updateComment = useTaskStore((s) => s.updateComment);
@@ -37,7 +38,10 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {
const [submitting, setSubmitting] = useState(false);
const editor = useEditor();
- const relTime = activity.time ? dayjs(activity.time).fromNow() : '';
+ const { text: relTime, title: relTimeTitle } = formatActivityTime(activity.time, {
+ formatOtherYear: tDiscover('time.formatOtherYear'),
+ formatThisYear: tDiscover('time.formatThisYear'),
+ });
const content = activity.content || t('taskDetail.activities.fallback.comment');
const commentId = activity.id;
@@ -115,7 +119,7 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {
{activity.author?.name || t('taskDetail.activities.fallback.comment')}
</Text>
{relTime && (
- <Text fontSize={12} type={'secondary'}>
+ <Text fontSize={12} title={relTimeTitle} type={'secondary'}>
{relTime}
</Text>
)}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
index f4c301d1f5a..e404fe668c7 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
@@ -1,7 +1,7 @@
import type { BriefType, TaskDetailActivity } from '@lobechat/types';
+import { formatActivityTime } from '@lobechat/utils/time';
import { Accordion, AccordionItem, Avatar, Empty, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import dayjs from 'dayjs';
import type { TFunction } from 'i18next';
import { BotMessageSquare, CircleDot, CirclePlus, MessageCircle } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
@@ -64,8 +64,12 @@ const getRowText = (act: TaskDetailActivity, t: TFunction<'chat'>): string => {
/** Compact one-line row for topic / comment activities. */
const ActivityRow = memo<{ activity: TaskDetailActivity }>(({ activity }) => {
const { t } = useTranslation('chat');
+ const { t: tDiscover } = useTranslation('discover');
const TypeIcon = ROW_TYPE_ICON[activity.type as keyof typeof ROW_TYPE_ICON] ?? MessageCircle;
- const relTime = activity.time ? dayjs(activity.time).fromNow() : '';
+ const { text: relTime, title: relTimeTitle } = formatActivityTime(activity.time, {
+ formatOtherYear: tDiscover('time.formatOtherYear'),
+ formatThisYear: tDiscover('time.formatThisYear'),
+ });
const text = getRowText(activity, t);
const isAgent = activity.author?.type === 'agent';
@@ -112,7 +116,10 @@ const ActivityRow = memo<{ activity: TaskDetailActivity }>(({ activity }) => {
<Text ellipsis style={{ color: cssVar.colorTextSecondary, flex: 1, minWidth: 0 }}>
{text}
{relTime && (
- <span style={{ color: cssVar.colorTextQuaternary, marginInlineStart: 4 }}>
+ <span
+ style={{ color: cssVar.colorTextQuaternary, marginInlineStart: 4 }}
+ title={relTimeTitle}
+ >
Β· {relTime}
</span>
)}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
index 07fe411cbb4..8a576de37dc 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
@@ -1,4 +1,5 @@
import type { TaskDetailActivity } from '@lobechat/types';
+import { formatActivityTime } from '@lobechat/utils/time';
import {
ActionIcon,
Avatar,
@@ -10,7 +11,6 @@ import {
Text,
} from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import dayjs from 'dayjs';
import { CircleDot, Copy, ExternalLink, MoreHorizontal } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -36,6 +36,7 @@ interface TopicCardProps {
const TopicCard = memo<TopicCardProps>(({ activity }) => {
const { t } = useTranslation('chat');
+ const { t: tDiscover } = useTranslation('discover');
const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);
const isRunning = activity.status === 'running';
@@ -68,7 +69,10 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
if (activity.operationId) void navigator.clipboard.writeText(activity.operationId);
}, [activity.operationId]);
- const startedAt = activity.time ? dayjs(activity.time).fromNow() : '';
+ const { text: startedAt, title: startedAtTitle } = formatActivityTime(activity.time, {
+ formatOtherYear: tDiscover('time.formatOtherYear'),
+ formatThisYear: tDiscover('time.formatThisYear'),
+ });
const durationText = isRunning
? formatDuration(elapsed)
: finalDuration != null && finalDuration >= 0
@@ -149,7 +153,7 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
<Flexbox horizontal align={'center'} flex={'none'} gap={8}>
{startedAt && (
- <Text fontSize={12} type={'secondary'}>
+ <Text fontSize={12} title={startedAtTitle} type={'secondary'}>
{startedAt}
</Text>
)}
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 23521889324..61eff7716cd 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -5,7 +5,7 @@ import { type ChatInputActionsProps } from '@lobehub/editor/react';
import { type MenuProps } from '@lobehub/ui';
import { Alert, Flexbox } from '@lobehub/ui';
import { type ReactNode } from 'react';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { type ActionKeys } from '@/features/ChatInput';
@@ -26,6 +26,7 @@ import {
useConversationStore,
useConversationStoreApi,
} from '../store';
+import TodoProgress from '../TodoProgress';
import QueueTray from './QueueTray';
import { getConversationChatInputUiState } from './utils';
@@ -173,6 +174,24 @@ const ChatInput = memo<ChatInputProps>(
]);
const updateInputMessage = useConversationStore((s) => s.updateInputMessage);
const setEditor = useConversationStore((s) => s.setEditor);
+ const setChatInputOverlayHeight = useConversationStore((s) => s.setChatInputOverlayHeight);
+
+ // Observe the floating overlay's height (TodoProgress + QueueTray) and
+ // publish it so the ChatList container can reserve matching bottom
+ // padding β€” keeps the overlay floating without occluding chat content.
+ const overlayRef = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const node = overlayRef.current;
+ if (!node) return;
+ const observer = new ResizeObserver(([entry]) => {
+ setChatInputOverlayHeight(Math.round(entry.contentRect.height));
+ });
+ observer.observe(node);
+ return () => {
+ observer.disconnect();
+ setChatInputOverlayHeight(0);
+ };
+ }, [setChatInputOverlayHeight]);
// Loading state from ConversationStore (bridged from ChatStore)
const isInputLoading = useConversationStore(messageStateSelectors.isInputLoading);
@@ -271,7 +290,7 @@ const ChatInput = memo<ChatInputProps>(
const defaultContent = (
<WideScreenContainer
- style={skipScrollMarginWithList ? { marginTop: -12, position: 'relative' } : undefined}
+ style={{ position: 'relative', ...(skipScrollMarginWithList ? { marginTop: -12 } : null) }}
>
{hasPendingInterventions ? (
<InterventionBar interventions={pendingInterventions} />
@@ -287,20 +306,20 @@ const ChatInput = memo<ChatInputProps>(
/>
</Flexbox>
)}
- {!disableQueue && hasQueuedMessages && (
- <Flexbox
- paddingInline={12}
- style={{
- position: 'absolute',
- zIndex: 10,
- bottom: '100%',
- left: 12,
- right: 12,
- }}
- >
- <QueueTray />
- </Flexbox>
- )}
+ <Flexbox
+ paddingInline={12}
+ ref={overlayRef}
+ style={{
+ bottom: '100%',
+ left: 12,
+ position: 'absolute',
+ right: 12,
+ zIndex: 10,
+ }}
+ >
+ {!disableQueue && hasQueuedMessages && <QueueTray />}
+ <TodoProgress topAttached={!disableQueue && hasQueuedMessages} />
+ </Flexbox>
<DesktopChatInput
actionBarStyle={actionBarStyle}
borderRadius={12}
diff --git a/src/features/Conversation/ChatList/components/BackBottom/index.tsx b/src/features/Conversation/ChatList/components/BackBottom/index.tsx
index fb3c018c544..60499335a8f 100644
--- a/src/features/Conversation/ChatList/components/BackBottom/index.tsx
+++ b/src/features/Conversation/ChatList/components/BackBottom/index.tsx
@@ -10,79 +10,87 @@ import { styles } from './style';
export interface BackBottomProps {
atBottom: boolean;
+ /**
+ * Extra space (px) to lift the button above its default 16px bottom offset.
+ * Used to clear the ChatInput's floating overlay (TodoProgress + QueueTray).
+ */
+ bottomOffset?: number;
onScrollToBottom: () => void;
visible: boolean;
}
-const BackBottom = memo<BackBottomProps>(({ visible, atBottom, onScrollToBottom }) => {
- const { t } = useTranslation('chat');
+const BackBottom = memo<BackBottomProps>(
+ ({ visible, atBottom, bottomOffset = 0, onScrollToBottom }) => {
+ const { t } = useTranslation('chat');
- return (
- <>
- {/* Debug: bottom indicator line */}
- {OPEN_DEV_INSPECTOR && (
- <div
- style={{
- bottom: 0,
- left: 0,
- pointerEvents: 'none',
- position: 'absolute',
- right: 0,
- }}
- >
- {/* Threshold area top boundary line */}
+ return (
+ <>
+ {/* Debug: bottom indicator line */}
+ {OPEN_DEV_INSPECTOR && (
<div
style={{
- background: atBottom ? '#22c55e' : '#ef4444',
- height: 2,
+ bottom: 0,
left: 0,
- opacity: 0.5,
+ pointerEvents: 'none',
position: 'absolute',
right: 0,
- top: -AT_BOTTOM_THRESHOLD,
}}
- />
+ >
+ {/* Threshold area top boundary line */}
+ <div
+ style={{
+ background: atBottom ? '#22c55e' : '#ef4444',
+ height: 2,
+ left: 0,
+ opacity: 0.5,
+ position: 'absolute',
+ right: 0,
+ top: -AT_BOTTOM_THRESHOLD,
+ }}
+ />
- {/* Threshold area mask - displayed above the indicator line */}
- <div
- style={{
- background: atBottom
- ? 'linear-gradient(to top, rgba(34, 197, 94, 0.15), transparent)'
- : 'linear-gradient(to top, rgba(239, 68, 68, 0.1), transparent)',
- height: AT_BOTTOM_THRESHOLD,
- left: 0,
- position: 'absolute',
- right: 0,
- top: -AT_BOTTOM_THRESHOLD,
- }}
- />
+ {/* Threshold area mask - displayed above the indicator line */}
+ <div
+ style={{
+ background: atBottom
+ ? 'linear-gradient(to top, rgba(34, 197, 94, 0.15), transparent)'
+ : 'linear-gradient(to top, rgba(239, 68, 68, 0.1), transparent)',
+ height: AT_BOTTOM_THRESHOLD,
+ left: 0,
+ position: 'absolute',
+ right: 0,
+ top: -AT_BOTTOM_THRESHOLD,
+ }}
+ />
- {/* AutoScroll position indicator line (bottom) */}
- <div
- style={{
- background: atBottom ? '#22c55e' : '#ef4444',
- height: 2,
- width: '100%',
- }}
- />
- </div>
- )}
+ {/* AutoScroll position indicator line (bottom) */}
+ <div
+ style={{
+ background: atBottom ? '#22c55e' : '#ef4444',
+ height: 2,
+ width: '100%',
+ }}
+ />
+ </div>
+ )}
- <ActionIcon
- glass
- className={cx(styles.container, visible && styles.visible)}
- icon={ArrowDownIcon}
- title={t('backToBottom')}
- variant={'outlined'}
- size={{
- blockSize: 36,
- borderRadius: 36,
- size: 18,
- }}
- onClick={onScrollToBottom}
- />
- </>
- );
-});
+ <ActionIcon
+ glass
+ className={cx(styles.container, visible && styles.visible)}
+ icon={ArrowDownIcon}
+ style={bottomOffset ? { insetBlockEnd: 16 + bottomOffset } : undefined}
+ title={t('backToBottom')}
+ variant={'outlined'}
+ size={{
+ blockSize: 36,
+ borderRadius: 36,
+ size: 18,
+ }}
+ onClick={onScrollToBottom}
+ />
+ </>
+ );
+ },
+);
export default BackBottom;
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index e863ceae7ef..3323555a3fd 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -12,6 +12,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import WideScreenContainer from '../../../WideScreenContainer';
import {
dataSelectors,
+ inputSelectors,
messageStateSelectors,
useConversationStore,
virtuaListSelectors,
@@ -202,6 +203,15 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
+ // The ChatInput's floating overlay (TodoProgress + QueueTray) covers the
+ // bottom of this scroll viewport like a layer. Extend VList's internal
+ // padding-bottom by the overlay height so the last message can still be
+ // scrolled into view *above* the overlay; the +12 compensates for the
+ // ChatInput's `marginTop: -12` (skipScrollMarginWithList) so the last
+ // message lands exactly on the overlay's top edge.
+ const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);
+ const paddingBottom = Math.max(24, overlayHeight + 12);
+
return (
<div style={{ height: '100%', position: 'relative' }}>
{/* Debug Inspector - placed outside VList so it won't be recycled by the virtual list */}
@@ -211,7 +221,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
data={listData}
keepMounted={keepMountedIndices}
ref={virtuaRef}
- style={{ height: '100%', overflowAnchor: 'none', paddingBottom: 24 }}
+ style={{ height: '100%', overflowAnchor: 'none', paddingBottom }}
onScroll={handleScroll}
onScrollEnd={handleScrollEnd}
>
@@ -268,6 +278,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
<WideScreenContainer style={{ position: 'relative' }}>
<BackBottom
atBottom={atBottom}
+ bottomOffset={overlayHeight}
visible={!atBottom}
onScrollToBottom={() => scrollToBottom(true)}
/>
diff --git a/src/features/Conversation/TodoProgress/index.tsx b/src/features/Conversation/TodoProgress/index.tsx
index e3f35e94c12..cad6da5bfc0 100644
--- a/src/features/Conversation/TodoProgress/index.tsx
+++ b/src/features/Conversation/TodoProgress/index.tsx
@@ -7,7 +7,6 @@ import { ChevronDown, ChevronUp, CircleArrowRight } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import WideScreenContainer from '@/features/WideScreenContainer';
import { selectCurrentTurnTodosFromMessages } from '@/store/chat/slices/message/selectors/dbMessage';
import { shinyTextStyles } from '@/styles';
@@ -31,11 +30,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
cursor: pointer;
user-select: none;
- margin-block-end: 8px;
- margin-inline: 10px;
padding-block: 8px 10px;
padding-inline: 12px;
border: 1px solid ${cssVar.colorBorderSecondary};
+ border-block-end: none;
border-start-start-radius: 12px;
border-start-end-radius: 12px;
@@ -43,6 +41,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
transition: all 0.2s ${cssVar.motionEaseInOut};
`,
+ containerTopAttached: css`
+ border-start-start-radius: 0;
+ border-start-end-radius: 0;
+ `,
count: css`
font-family: ${cssVar.fontFamilyCode};
font-size: 12px;
@@ -114,9 +116,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface TodoProgressProps {
className?: string;
+ /**
+ * When true, square the top corners β€” used when another panel (e.g.
+ * QueueTray) sits flush above this one in the stack so the seams align.
+ */
+ topAttached?: boolean;
}
-const TodoProgress = memo<TodoProgressProps>(({ className }) => {
+const TodoProgress = memo<TodoProgressProps>(({ className, topAttached }) => {
const { t } = useTranslation('chat');
const [expanded, setExpanded] = useState(false);
@@ -153,93 +160,94 @@ const TodoProgress = memo<TodoProgressProps>(({ className }) => {
const toggleExpanded = () => setExpanded(!expanded);
return (
- <WideScreenContainer>
- <div className={cx(styles.container, className)} onClick={toggleExpanded}>
- {/* Header */}
- <Flexbox horizontal align="center" gap={8} justify="space-between">
- <Flexbox horizontal align="center" gap={8} style={{ flex: 1, minWidth: 0 }}>
- <svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>
- <circle
- className={styles.ringTrack}
- cx={RING_SIZE / 2}
- cy={RING_SIZE / 2}
- fill="none"
- r={RING_RADIUS}
- strokeWidth={RING_STROKE}
- />
- <circle
- className={styles.ringProgress}
- cx={RING_SIZE / 2}
- cy={RING_SIZE / 2}
- fill="none"
- r={RING_RADIUS}
- stroke={ringColor}
- strokeDasharray={RING_CIRCUM}
- strokeDashoffset={ringOffset}
- strokeLinecap="round"
- strokeWidth={RING_STROKE}
- />
- </svg>
- <span className={cx(styles.header, isAIGenerating && shinyTextStyles.shinyText)}>
- {currentPendingTask?.text ||
- t('todoProgress.allCompleted', { defaultValue: 'All tasks completed' })}
+ <div
+ className={cx(styles.container, topAttached && styles.containerTopAttached, className)}
+ onClick={toggleExpanded}
+ >
+ {/* Header */}
+ <Flexbox horizontal align="center" gap={8} justify="space-between">
+ <Flexbox horizontal align="center" gap={8} style={{ flex: 1, minWidth: 0 }}>
+ <svg className={styles.ring} height={RING_SIZE} width={RING_SIZE}>
+ <circle
+ className={styles.ringTrack}
+ cx={RING_SIZE / 2}
+ cy={RING_SIZE / 2}
+ fill="none"
+ r={RING_RADIUS}
+ strokeWidth={RING_STROKE}
+ />
+ <circle
+ className={styles.ringProgress}
+ cx={RING_SIZE / 2}
+ cy={RING_SIZE / 2}
+ fill="none"
+ r={RING_RADIUS}
+ stroke={ringColor}
+ strokeDasharray={RING_CIRCUM}
+ strokeDashoffset={ringOffset}
+ strokeLinecap="round"
+ strokeWidth={RING_STROKE}
+ />
+ </svg>
+ <span className={cx(styles.header, isAIGenerating && shinyTextStyles.shinyText)}>
+ {currentPendingTask?.text ||
+ t('todoProgress.allCompleted', { defaultValue: 'All tasks completed' })}
+ </span>
+ <Tag size="small" style={{ flexShrink: 0 }}>
+ <span className={styles.count}>
+ {completed}/{total}
</span>
- <Tag size="small" style={{ flexShrink: 0 }}>
- <span className={styles.count}>
- {completed}/{total}
- </span>
- </Tag>
- </Flexbox>
- <Icon
- icon={expanded ? ChevronUp : ChevronDown}
- size={16}
- style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }}
- />
+ </Tag>
</Flexbox>
+ <Icon
+ icon={expanded ? ChevronUp : ChevronDown}
+ size={16}
+ style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }}
+ />
+ </Flexbox>
+
+ {/* Expandable Todo List */}
+ <div className={cx(styles.listContainer, expanded ? styles.expanded : styles.collapsed)}>
+ {items.map((item, index) => {
+ const isCompleted = item.status === 'completed';
+ const isProcessing = item.status === 'processing';
- {/* Expandable Todo List */}
- <div className={cx(styles.listContainer, expanded ? styles.expanded : styles.collapsed)}>
- {items.map((item, index) => {
- const isCompleted = item.status === 'completed';
- const isProcessing = item.status === 'processing';
-
- // Processing state uses CircleArrowRight icon
- if (isProcessing) {
- return (
- <div className={cx(styles.itemRow, styles.processingRow)} key={index}>
- <Icon
- icon={CircleArrowRight}
- size={17}
- style={{ color: cssVar.colorTextSecondary }}
- />
- <span className={styles.textProcessing}>{item.text}</span>
- </div>
- );
- }
-
- // Todo and completed states use Checkbox
+ // Processing state uses CircleArrowRight icon
+ if (isProcessing) {
return (
- <Checkbox
- backgroundColor={cssVar.colorSuccess}
- checked={isCompleted}
- key={index}
- shape="circle"
- style={{ borderWidth: 1.5, cursor: 'default', pointerEvents: 'none' }}
- classNames={{
- text: cx(styles.textTodo, isCompleted && styles.textCompleted),
- wrapper: styles.itemRow,
- }}
- textProps={{
- type: isCompleted ? 'secondary' : undefined,
- }}
- >
- {item.text}
- </Checkbox>
+ <div className={cx(styles.itemRow, styles.processingRow)} key={index}>
+ <Icon
+ icon={CircleArrowRight}
+ size={17}
+ style={{ color: cssVar.colorTextSecondary }}
+ />
+ <span className={styles.textProcessing}>{item.text}</span>
+ </div>
);
- })}
- </div>
+ }
+
+ // Todo and completed states use Checkbox
+ return (
+ <Checkbox
+ backgroundColor={cssVar.colorSuccess}
+ checked={isCompleted}
+ key={index}
+ shape="circle"
+ style={{ borderWidth: 1.5, cursor: 'default', pointerEvents: 'none' }}
+ classNames={{
+ text: cx(styles.textTodo, isCompleted && styles.textCompleted),
+ wrapper: styles.itemRow,
+ }}
+ textProps={{
+ type: isCompleted ? 'secondary' : undefined,
+ }}
+ >
+ {item.text}
+ </Checkbox>
+ );
+ })}
</div>
- </WideScreenContainer>
+ </div>
);
});
diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.ts
index be4577b6124..4b023707fcb 100644
--- a/src/features/Conversation/store/selectors.test.ts
+++ b/src/features/Conversation/store/selectors.test.ts
@@ -7,6 +7,7 @@ import { conversationSelectors } from './selectors';
// Helper to create a mock state
const createMockState = (overrides: Partial<State> = {}): State => ({
// Input state
+ chatInputOverlayHeight: 0,
editor: null,
inputMessage: '',
diff --git a/src/features/Conversation/store/slices/input/action.ts b/src/features/Conversation/store/slices/input/action.ts
index b53be909283..b5c3b332811 100644
--- a/src/features/Conversation/store/slices/input/action.ts
+++ b/src/features/Conversation/store/slices/input/action.ts
@@ -10,6 +10,12 @@ export interface InputAction {
*/
cleanupInput: () => void;
+ /**
+ * Report the floating overlay height (TodoProgress + QueueTray) so the
+ * ChatList scroll container can reserve matching bottom padding.
+ */
+ setChatInputOverlayHeight: (height: number) => void;
+
/**
* Set the editor instance
*/
@@ -21,13 +27,18 @@ export interface InputAction {
updateInputMessage: (message: string) => void;
}
-export const inputSlice: StateCreator<State & InputAction, [], [], InputAction> = (set) => ({
+export const inputSlice: StateCreator<State & InputAction, [], [], InputAction> = (set, get) => ({
cleanupInput: () => {
- set({ editor: null, inputMessage: '' });
+ set({ chatInputOverlayHeight: 0, editor: null, inputMessage: '' });
// Also clear ChatStore's mainInputEditor
useChatStore.setState({ mainInputEditor: null });
},
+ setChatInputOverlayHeight: (height) => {
+ if (get().chatInputOverlayHeight === height) return;
+ set({ chatInputOverlayHeight: height });
+ },
+
setEditor: (editor) => {
set({ editor });
// Sync to ChatStore's mainInputEditor for error recovery in sendMessage
diff --git a/src/features/Conversation/store/slices/input/initialState.ts b/src/features/Conversation/store/slices/input/initialState.ts
index 19061361e73..42b1b8e263a 100644
--- a/src/features/Conversation/store/slices/input/initialState.ts
+++ b/src/features/Conversation/store/slices/input/initialState.ts
@@ -1,4 +1,12 @@
export interface InputState {
+ /**
+ * Measured height of the floating overlay that sits above the ChatInput
+ * (TodoProgress + QueueTray). Used by the ChatList scroll container to
+ * reserve matching bottom padding so the overlay doesn't cover the
+ * latest messages.
+ */
+ chatInputOverlayHeight: number;
+
/**
* Editor instance (for ChatInput)
*/
@@ -11,6 +19,7 @@ export interface InputState {
}
export const inputInitialState: InputState = {
+ chatInputOverlayHeight: 0,
editor: null,
inputMessage: '',
};
diff --git a/src/features/Conversation/store/slices/input/selectors.ts b/src/features/Conversation/store/slices/input/selectors.ts
index 3203c03906e..b4acc1bc2be 100644
--- a/src/features/Conversation/store/slices/input/selectors.ts
+++ b/src/features/Conversation/store/slices/input/selectors.ts
@@ -3,8 +3,10 @@ import { type State } from '../../initialState';
const editor = (s: State) => s.editor;
const inputMessage = (s: State) => s.inputMessage;
const hasInput = (s: State) => s.inputMessage.trim().length > 0;
+const chatInputOverlayHeight = (s: State) => s.chatInputOverlayHeight;
export const inputSelectors = {
+ chatInputOverlayHeight,
editor,
hasInput,
inputMessage,
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 3600d776c30..80792fb7d3d 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -6,7 +6,7 @@ import { memo, Suspense, useMemo } from 'react';
import AgentHome from '@/features/AgentHome';
import ChatMiniMap from '@/features/ChatMiniMap';
-import { ChatList, ConversationProvider, TodoProgress } from '@/features/Conversation';
+import { ChatList, ConversationProvider } from '@/features/Conversation';
import ZenModeToast from '@/features/ZenModeToast';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
@@ -90,7 +90,6 @@ const Conversation = memo(() => {
welcome={<AgentHome />}
/>
</Flexbox>
- <TodoProgress />
{isHeterogeneousAgent ? <HeterogeneousChatInput /> : <MainChatInput />}
<ThreadHydration />
<ChatMiniMap />
diff --git a/src/routes/(main)/home/features/components/Time.tsx b/src/routes/(main)/home/features/components/Time.tsx
index 5df369d8b0b..0b1e40f112e 100644
--- a/src/routes/(main)/home/features/components/Time.tsx
+++ b/src/routes/(main)/home/features/components/Time.tsx
@@ -1,11 +1,18 @@
+import { formatActivityTime } from '@lobechat/utils/time';
import { Text } from '@lobehub/ui';
-import dayjs from 'dayjs';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
export const Time = memo<{ date: string | number | Date }>(({ date }) => {
+ const { t } = useTranslation('discover');
+ const { text, title } = formatActivityTime(date, {
+ formatOtherYear: t('time.formatOtherYear'),
+ formatThisYear: t('time.formatThisYear'),
+ });
+ if (!text) return null;
return (
- <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>
- {dayjs(date || dayjs().date()).fromNow()}
+ <Text fontSize={12} style={{ flex: 'none' }} title={title} type={'secondary'}>
+ {text}
</Text>
);
});
diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.ts
index 881d206326b..daf35575277 100644
--- a/src/server/services/taskLifecycle/index.ts
+++ b/src/server/services/taskLifecycle/index.ts
@@ -1,11 +1,14 @@
import {
chainGenerateBrief,
+ chainJudgeBriefEmit,
chainTaskTopicHandoff,
GENERATE_BRIEF_SCHEMA,
+ JUDGE_BRIEF_EMIT_SCHEMA,
TASK_TOPIC_HANDOFF_SCHEMA,
} from '@lobechat/prompts';
import type {
BriefArtifacts,
+ BriefDecision,
TaskItem,
TaskSchedulerContext,
TaskTopicHandoff,
@@ -326,15 +329,19 @@ 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)
+ * the judge path has already produced a brief. Two-stage decision:
+ * 1. Rule layer (`shouldEmitTopicBrief`) β€” deterministic. Returns
+ * `'yes'` / `'no'` (caller persists the verdict and is done with the
+ * decision phase) or `'unknown'` (defer to LLM).
+ * 2. LLM judge (`chainJudgeBriefEmit`) β€” semantic. Runs only on the
+ * `'unknown'` branch, returns `{emit, reason}` for content the rule
+ * can't classify (manual/non-scheduled topic with non-trivial output).
+ *
+ * The verdict (rule or LLM) is persisted to `taskTopics.handoff.briefDecision`
+ * so the emit/skip outcome is auditable per topic. Generation
+ * (`chainGenerateBrief`) is a separate LLM call that runs only when the
+ * decision is `emit: true` β€” never wasting tokens drafting copy for a
+ * brief that won't be persisted.
*
* Failures are swallowed β€” a missing brief should never block the task
* lifecycle. The caller still proceeds to the post-tick state transition.
@@ -359,12 +366,69 @@ export class TaskLifecycleService {
task: currentTask,
};
- const decision = shouldEmitTopicBrief(decisionInput);
+ const ruleVerdict = shouldEmitTopicBrief(decisionInput);
+
+ // Inputs needed by both the LLM judge (when ruleVerdict === 'unknown')
+ // and by chainGenerateBrief (when emit ends up true). Hoisted so we
+ // only fetch them once.
+ 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',
+ );
+
+ let decision: BriefDecision;
+ if (ruleVerdict.emit === 'unknown') {
+ // Rule can't decide β€” ask the LLM judge. Title/summary are NOT
+ // produced here; they come from chainGenerateBrief if emit=true.
+ const judgePayload = chainJudgeBriefEmit({
+ artifacts,
+ handoff,
+ lastAssistantContent,
+ taskInstruction: currentTask.instruction || '',
+ taskName: currentTask.name || taskIdentifier,
+ });
+
+ const modelRuntime = await initModelRuntimeFromDB(this.db, this.userId, provider);
+ const judgeResult = (await modelRuntime.generateObject(
+ {
+ messages: judgePayload.messages as any[],
+ model,
+ schema: { name: 'task_topic_brief_judge', schema: JUDGE_BRIEF_EMIT_SCHEMA },
+ },
+ { metadata: { trigger: 'task-brief-judge' } },
+ )) as { emit?: boolean; reason?: string };
+
+ decision = {
+ decidedAt: new Date().toISOString(),
+ emit: judgeResult.emit === true,
+ model,
+ reason: judgeResult.reason || 'llm-judge-unknown',
+ source: 'llm-judge',
+ };
+ } else {
+ decision = {
+ decidedAt: new Date().toISOString(),
+ emit: ruleVerdict.emit === 'yes',
+ reason: ruleVerdict.reason,
+ source: 'rule',
+ };
+ }
+
+ // Persist the decision regardless of outcome β€” gives the operator a
+ // per-topic audit trail of why a brief was or wasn't produced.
+ await this.taskTopicModel.updateBriefDecision(taskId, topicId, decision);
+
if (!decision.emit) {
log(
- 'synthesize: skip task=%s topic=%s reason=%s',
+ 'synthesize: skip task=%s topic=%s source=%s reason=%s',
taskIdentifier,
topicId,
+ decision.source,
decision.reason,
);
return;
@@ -373,18 +437,6 @@ export class TaskLifecycleService {
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,
@@ -403,20 +455,7 @@ export class TaskLifecycleService {
{ 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;
- }
+ const generated = result as { summary?: string; title?: string };
if (!generated.title || !generated.summary) {
log(
'synthesize: LLM returned empty title/summary task=%s topic=%s',
diff --git a/src/server/services/taskLifecycle/synthesize.test.ts b/src/server/services/taskLifecycle/synthesize.test.ts
index 2c3fa2e26bc..86c5a5505aa 100644
--- a/src/server/services/taskLifecycle/synthesize.test.ts
+++ b/src/server/services/taskLifecycle/synthesize.test.ts
@@ -18,48 +18,56 @@ const baseInput = (overrides: Partial<Parameters<typeof shouldEmitTopicBrief>[0]
});
describe('shouldEmitTopicBrief', () => {
- it('skips when reason=error (error branch handles its own brief)', () => {
+ it("returns 'yes' when reason=error (user must be told the run failed)", () => {
const result = shouldEmitTopicBrief(baseInput({ reason: 'error' }));
- expect(result.emit).toBe(false);
- expect(result.reason).toBe('error-branch-handled');
+ expect(result.emit).toBe('yes');
+ expect(result.reason).toBe('execution-error');
});
- it('skips when judge already terminated the lifecycle', () => {
+ it("returns 'no' when judge already terminated the lifecycle", () => {
const result = shouldEmitTopicBrief(baseInput({ reviewTerminated: true }));
- expect(result.emit).toBe(false);
+ expect(result.emit).toBe('no');
expect(result.reason).toBe('judge-handled');
});
- it('skips when review is configured (judge owns the brief on this path)', () => {
+ it("returns 'no' when review is configured (judge owns the brief on this path)", () => {
const result = shouldEmitTopicBrief(baseInput({ hasReviewConfigEnabled: true }));
- expect(result.emit).toBe(false);
+ expect(result.emit).toBe('no');
expect(result.reason).toBe('review-config-enabled');
});
- it('skips heartbeat automation ticks (mid-loop, not a delivery)', () => {
+ it("returns 'unknown' for heartbeat ticks (defers to LLM β€” most are noise but some warrant surfacing)", () => {
const result = shouldEmitTopicBrief(baseInput({ task: { automationMode: 'heartbeat' } }));
- expect(result.emit).toBe(false);
- expect(result.reason).toBe('automation-tick');
+ expect(result.emit).toBe('unknown');
+ expect(result.reason).toBe('heartbeat-needs-judge');
});
- it('skips schedule automation ticks', () => {
+ it("returns 'yes' on every schedule tick (contractual daily brief)", () => {
const result = shouldEmitTopicBrief(baseInput({ task: { automationMode: 'schedule' } }));
- expect(result.emit).toBe(false);
- expect(result.reason).toBe('automation-tick');
+ expect(result.emit).toBe('yes');
+ expect(result.reason).toBe('scheduled-tick');
});
- it('skips trivial content (empty / whitespace-only acks)', () => {
+ it("still returns 'yes' for a schedule tick even when content looks trivial", () => {
+ const result = shouldEmitTopicBrief(
+ baseInput({ isTrivialContent: true, task: { automationMode: 'schedule' } }),
+ );
+ expect(result.emit).toBe('yes');
+ });
+
+ it("returns 'no' for trivial content on a non-scheduled task", () => {
const result = shouldEmitTopicBrief(baseInput({ isTrivialContent: true }));
- expect(result.emit).toBe(false);
+ expect(result.emit).toBe('no');
expect(result.reason).toBe('trivial-content');
});
- it('emits for a normal manual-mode topic with substantive content', () => {
+ it("returns 'unknown' for a normal manual-mode topic with substantive content (defers to LLM judge)", () => {
const result = shouldEmitTopicBrief(baseInput());
- expect(result.emit).toBe(true);
+ expect(result.emit).toBe('unknown');
+ expect(result.reason).toBe('needs-llm-judge');
});
- it('skips automation even when other conditions look fine', () => {
+ it("returns 'unknown' for heartbeat even when other conditions look fine", () => {
const result = shouldEmitTopicBrief(
baseInput({
hasReviewConfigEnabled: false,
@@ -67,7 +75,7 @@ describe('shouldEmitTopicBrief', () => {
task: { automationMode: 'heartbeat' },
}),
);
- expect(result.emit).toBe(false);
+ expect(result.emit).toBe('unknown');
});
});
diff --git a/src/server/services/taskLifecycle/synthesize.ts b/src/server/services/taskLifecycle/synthesize.ts
index 9190427283f..1477a068ed2 100644
--- a/src/server/services/taskLifecycle/synthesize.ts
+++ b/src/server/services/taskLifecycle/synthesize.ts
@@ -10,9 +10,17 @@ export interface ShouldEmitTopicBriefInput {
task: Pick<TaskItem, 'automationMode'> | null;
}
+/**
+ * Three-state result so the caller can tell "rule has a definite answer" from
+ * "rule is not equipped to decide β€” defer to the LLM judge".
+ *
+ * - `'yes'` / `'no'` β€” deterministic; persist as-is with `source: 'rule'`.
+ * - `'unknown'` β€” pure rules can't tell; caller invokes `chainJudgeBriefEmit`
+ * and records the LLM's verdict with `source: 'llm-judge'`.
+ */
export interface ShouldEmitTopicBriefResult {
- emit: boolean;
- reason?: string;
+ emit: 'no' | 'unknown' | 'yes';
+ reason: string;
}
/**
@@ -21,22 +29,42 @@ export interface ShouldEmitTopicBriefResult {
* 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.
+ * Conclusive branches:
+ * - `'yes'` β€” scheduled tick (contractually owes the user a brief every
+ * run); execution error (the user must be told the run failed). Note:
+ * today the error branch in `onTopicComplete` builds its own urgent
+ * error brief inline, so this rule only fires once that path is folded
+ * into `synthesizeTopicBrief`. The verdict is correct ahead of time.
+ * - `'no'` β€” review-judge already produced a brief upstream, review is
+ * configured (judge owns the next run), or trivial content on a manual
+ * tick. Heartbeat used to be `'no'` here too, but is now deferred to the
+ * judge: most heartbeat ticks are mid-loop noise, but the occasional one
+ * surfaces something the user would want to see, and that judgment
+ * requires reading the content.
+ *
+ * Non-conclusive branch:
+ * - `'unknown'` β€” heartbeat tick, OR non-trivial content on a manual /
+ * non-scheduled task with no review configured. Caller defers to
+ * `chainJudgeBriefEmit`.
*/
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' };
+ if (input.reason === 'error') return { emit: 'yes', reason: 'execution-error' };
+ if (input.reviewTerminated) return { emit: 'no', 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 };
+ if (input.hasReviewConfigEnabled) return { emit: 'no', reason: 'review-config-enabled' };
+ if (input.task?.automationMode === 'heartbeat') {
+ return { emit: 'unknown', reason: 'heartbeat-needs-judge' };
+ }
+ if (input.task?.automationMode === 'schedule') {
+ return { emit: 'yes', reason: 'scheduled-tick' };
+ }
+ if (input.isTrivialContent) {
+ return { emit: 'no', reason: 'trivial-content' };
+ }
+ return { emit: 'unknown', reason: 'needs-llm-judge' };
};
/** Heuristic for "this content isn't a real delivery". */