π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(task): let hetero agents in Tasks Copilot see the viewed task (#21047)
Rdmclin23c1df75f83a3
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.tsnew file mode 100644index 00000000000..ac40a86c2e1--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroViewedTask.test.ts@@ -0,0 +1,356 @@+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskModel } from '@/database/models/task';+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';+import { TaskDetailService } from '@/server/services/task/detail';++import { AiAgentService } from '../index';++const {+ mockDeviceFindByDeviceId,+ mockDeviceFindWorkspaceDeviceById,+ mockBuildRemoteDeviceHeteroContext,+ mockCreateOperationMetadata,+ mockDispatchAgentRun,+ mockExecuteToolCall,+ mockInterruptOperation,+ mockGetHeterogeneousResumeSessionId,+ mockMessageCreate,+ mockMessageQuery,+ mockMessageUpdate,+ mockResolveAttachmentsByFileIds,+ mockSpawnHeteroSandbox,+ mockIngestAttachment,+ mockPublishAgentRuntimeInit,+ mockPublishAgentRuntimeEnd,+} = vi.hoisted(() => ({+ mockBuildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),+ mockCreateOperationMetadata: vi.fn().mockResolvedValue(undefined),+ mockDeviceFindByDeviceId: vi.fn(),+ mockDeviceFindWorkspaceDeviceById: vi.fn(),+ mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),+ mockExecuteToolCall: vi.fn().mockResolvedValue({ success: true }),+ mockInterruptOperation: vi.fn().mockResolvedValue(true),+ mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),+ mockIngestAttachment: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),+ mockMessageUpdate: vi.fn().mockResolvedValue({}),+ mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),+ mockPublishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),+ mockResolveAttachmentsByFileIds: vi.fn(),+ mockSpawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),+}));++// Local hetero (claude-code / codebuddy / codex / cursor / opencode / pi / qoder) seeds+// publishAgentRuntimeInit so the agent-gateway DO reports `running` on a later reconnect. Stub the factory so+// the assertion below can verify the init, and so the real one (which probes+// Redis synchronously) doesn't throw a server-env error in the test env.+vi.mock('@/server/modules/AgentRuntime/factory', () => ({+ createAgentStateManager: vi.fn(function () {+ return {+ createOperationMetadata: mockCreateOperationMetadata,+ };+ }),+ createStreamEventManager: () => ({+ publishAgentRuntimeEnd: mockPublishAgentRuntimeEnd,+ publishAgentRuntimeInit: mockPublishAgentRuntimeInit,+ }),+ isRedisAvailable: vi.fn(function () {+ return false;+ }),+}));++const emptyResolvedAttachments = {+ audioList: [],+ fileList: [],+ imageList: [],+ orderedFileIds: [],+ videoList: [],+ warnings: [],+};++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {};+ }),+}));++vi.mock('../ingestAttachment', () => ({+ ingestAttachment: mockIngestAttachment,+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signHeteroOperationJWT: vi.fn().mockResolvedValue('op-jwt'),+ signUserJWT: vi.fn().mockResolvedValue('user-jwt'),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ query: mockMessageQuery,+ update: mockMessageUpdate,+ };+ }),+}));++const heteroAgentConfig = {+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'claude-code',+ plugins: [],+ provider: 'anthropic',+ systemRole: 'You are a helpful assistant',+};++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),+ queryAgents: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(function () {+ return {+ findByDeviceId: mockDeviceFindByDeviceId,+ findWorkspaceDeviceById: mockDeviceFindWorkspaceDeviceById,+ };+ }),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+}));++const topicMock = {+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),+ findById: vi.fn().mockResolvedValue(undefined),+ patchRunningOperation: vi.fn().mockResolvedValue(true),+ settleRunningOperation: vi.fn().mockResolvedValue({ status: 'settled' }),+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ updateMetadata: vi.fn().mockResolvedValue(undefined),+};+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return topicMock;+ }),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ market: {+ creds: {+ get: vi.fn(),+ list: vi.fn().mockResolvedValue({ data: [] }),+ },+ },+ };+ }),+}));++vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {+ return {+ getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,+ };+ }),+}));++vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({+ spawnHeteroSandbox: mockSpawnHeteroSandbox,+}));++vi.mock('@/server/services/file/resolveAttachments', () => ({+ resolveAttachmentsByFileIds: mockResolveAttachmentsByFileIds,+}));++vi.mock('@/server/services/document', () => ({+ DocumentService: vi.fn().mockImplementation(function () {+ return {+ parseFile: vi.fn().mockResolvedValue({ content: '' }),+ };+ }),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ interruptOperation: mockInterruptOperation,+ };+ }),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ dispatchAgentRun: mockDispatchAgentRun,+ executeToolCall: mockExecuteToolCall,+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),+ },+}));++vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({+ buildRemoteDeviceHeteroContext: mockBuildRemoteDeviceHeteroContext,+}));++describe('AiAgentService.execAgent - hetero runs see the task viewed in Tasks', () => {+ let service: AiAgentService;+ const spies: MockInstance[] = [];++ const taskAppContext = {+ defaultTaskAssigneeAgentId: 'agt_inbox',+ scope: 'task' as const,+ taskId: 'T-858',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ spies.push(+ vi.spyOn(AgentOperationModel.prototype, 'settleRunning').mockResolvedValue(true),+ vi.spyOn(CompletionLifecycle.prototype, 'recordStart').mockResolvedValue(true),+ vi.spyOn(TaskModel.prototype, 'resolve').mockResolvedValue({+ id: 'task-row-858',+ } as NonNullable<Awaited<ReturnType<TaskModel['resolve']>>>),+ vi.spyOn(TaskDetailService.prototype, 'getTaskDetail').mockResolvedValue({+ identifier: 'T-858',+ instruction: 'Make images in the task content draggable',+ name: 'Task content images cannot be dragged',+ status: 'running',+ }),+ );+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });+ topicMock.findById.mockResolvedValue(undefined);+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockMessageQuery.mockResolvedValue([]);+ mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });+ mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);+ mockBuildRemoteDeviceHeteroContext.mockReturnValue('device context');+ mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });+ mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);+ heteroAgentConfig.model = 'claude-code';+ heteroAgentConfig.provider = 'anthropic';++ service = new AiAgentService({} as any, 'test-user-id');+ });++ afterEach(() => {+ for (const spy of spies.splice(0)) spy.mockRestore();+ });++ it('adds the viewed task to the device run system context', async () => {+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { systemContext: 'Agent rules', type: 'claude-code' },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ appContext: taskAppContext,+ prompt: 'Which issue are we working on?',+ });++ expect(TaskDetailService.prototype.getTaskDetail).toHaveBeenCalledWith('task-row-858');+ const { agentSystemContext } = mockBuildRemoteDeviceHeteroContext.mock.calls[0][0];+ expect(agentSystemContext).toMatch(/^Agent rules\n\n<page_context>/);+ expect(agentSystemContext).toContain('viewing the detail page of task T-858');+ expect(agentSystemContext).toContain('Make images in the task content draggable');+ });++ it('adds the viewed task to the cloud sandbox system context', async () => {+ heteroAgentConfig.agencyConfig = {+ executionTarget: 'sandbox',+ heterogeneousProvider: { type: 'claude-code' },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ appContext: taskAppContext,+ prompt: 'Which issue are we working on?',+ });++ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(+ expect.objectContaining({+ systemContext: expect.stringContaining('viewing the detail page of task T-858'),+ }),+ );+ });++ it('leaves runs outside the Tasks side conversation untouched', async () => {+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Run the task',+ taskId: 'T-858',+ });++ expect(TaskDetailService.prototype.getTaskDetail).not.toHaveBeenCalled();+ expect(mockBuildRemoteDeviceHeteroContext.mock.calls[0][0].agentSystemContext).toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex 0e635410069..f69ddb56e7e 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -66,6 +66,7 @@ import { selectCodexDeviceDispatch } from './codexDeviceRuntime';import { finalizeHeteroDispatchError } from './finalizeHeteroDispatchError';import { heteroOperationCapabilities } from './heteroOperationCapabilities';import type { RunAttachments } from './turnSetup';+import { buildViewedTaskContextPrompt, joinSystemContext } from './viewedTaskContext';const log = debug('lobe-server:ai-agent-service');@@ -398,13 +399,12 @@ export const dispatchHeteroAgent = async (: undefined;const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };- // Build the primary context without conversation history. If native resume- // fails, the CLI switches to the complete fallback prompt on its fresh- // retry; successful same-session runs never consume the duplicate history.- // `/goal` reaches a hetero agent as instructions, not a tool: it creates and- // plans the goal through `lh` in this same run.+ // Primary context omits history (a failed native resume retries with the full+ // fallback). `/goal` and the task viewed in a Tasks side chat ride along.+ const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;+ const viewedTaskContext = await buildViewedTaskContextPrompt(deps, appContext, operationTaskId);const agentSystemContext = withConversationGoalPrompt(- agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,+ joinSystemContext(providerContext, viewedTaskContext),prompt,);const systemContext = buildCloudHeteroContext({diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 4e02bab0bdf..ea86e9e0ee1 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -4,7 +4,6 @@ import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import type { OperationSkillSet, ProjectInstructionFile } from '@lobechat/context-engine';import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';-import { buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';import type { LobeAgentAgencyConfig, WorkspaceInitResult } from '@lobechat/types';import { buildGoalOverviewContext, getWorkingDirEffectivePath } from '@lobechat/types';import debug from 'debug';@@ -36,6 +35,7 @@ import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCachimport { buildOperationSkillSet, collectSelectedSkillIds } from './operationSkillSet';import type { ToolDiscoveryResult } from './toolDiscovery';import type { RunAttachments } from './turnSetup';+import { buildViewedTaskContextPrompt } from './viewedTaskContext';const log = debug('lobe-server:ai-agent-service');@@ -685,16 +685,14 @@ export const prepareOperation = async (}}- if (appContext?.scope === 'task' && appContext.defaultTaskAssigneeAgentId) {+ // Tasks side conversation: the viewed task (or just the assignee defaults).+ const taskManagerPrompt = await buildViewedTaskContextPrompt(deps, appContext, input.taskId);+ if (taskManagerPrompt) {initialContext = {...initialContext,initialContext: {...initialContext.initialContext,- taskManager: {- contextPrompt: buildTaskManagerDefaultsPrompt({- defaultAssigneeAgentId: appContext.defaultTaskAssigneeAgentId,- }),- },+ taskManager: { contextPrompt: taskManagerPrompt },},};}diff --git a/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.ts b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.tsnew file mode 100644index 00000000000..68c007fe03c--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.test.ts@@ -0,0 +1,83 @@+import type { TaskDetailData } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TaskDetailService } from '@/server/services/task/detail';++import { buildViewedTaskContextPrompt, joinSystemContext } from './viewedTaskContext';++const deps = { db: {} as any, userId: 'user-1' };++const taskDetail: TaskDetailData = {+ identifier: 'T-858',+ instruction: 'Make images in the task content draggable',+ name: 'Task content images cannot be dragged',+ priority: 3,+ status: 'running',+};++describe('buildViewedTaskContextPrompt', () => {+ let getTaskDetail: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ getTaskDetail = vi+ .spyOn(TaskDetailService.prototype, 'getTaskDetail')+ .mockResolvedValue(taskDetail as never);+ });++ it('describes the task viewed on a task detail page', async () => {+ const prompt = await buildViewedTaskContextPrompt(+ deps,+ { defaultTaskAssigneeAgentId: 'agt_inbox', scope: 'task' },+ 'task-row-1',+ );++ expect(getTaskDetail).toHaveBeenCalledWith('task-row-1');+ expect(prompt).toContain('The user is currently viewing the detail page of task T-858');+ expect(prompt).toContain('Make images in the task content draggable');+ expect(prompt).toContain('Default Lobe AI agent id: agt_inbox');+ });++ it('keeps only the assignee defaults on the task list', async () => {+ const prompt = await buildViewedTaskContextPrompt(+ deps,+ { defaultTaskAssigneeAgentId: 'agt_inbox', scope: 'task' },+ undefined,+ );++ expect(getTaskDetail).not.toHaveBeenCalled();+ expect(prompt).toContain('Default Lobe AI agent id: agt_inbox');+ expect(prompt).not.toContain('<task>');+ });++ it('falls back to the assignee defaults when the task cannot be loaded', async () => {+ getTaskDetail.mockRejectedValue(new Error('db down'));++ const prompt = await buildViewedTaskContextPrompt(+ deps,+ { defaultTaskAssigneeAgentId: 'agt_inbox', scope: 'task' },+ 'task-row-1',+ );++ expect(prompt).toContain('Default Lobe AI agent id: agt_inbox');+ expect(prompt).not.toContain('T-858');+ });++ it('ignores task ids outside the Tasks side conversation', async () => {+ // Task runs carry their own task prompt; only the side chat gets this one.+ expect(await buildViewedTaskContextPrompt(deps, { topicId: 'topic-1' }, 'task-row-1')).toBe(+ undefined,+ );+ expect(await buildViewedTaskContextPrompt(deps, undefined, 'task-row-1')).toBe(undefined);+ expect(getTaskDetail).not.toHaveBeenCalled();+ });+});++describe('joinSystemContext', () => {+ it('joins the non-empty parts', () => {+ expect(joinSystemContext(' agent rules ', undefined, 'task')).toBe('agent rules\n\ntask');+ });++ it('returns undefined when nothing remains', () => {+ expect(joinSystemContext(undefined, ' ')).toBe(undefined);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.ts b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.tsnew file mode 100644index 00000000000..3cfd5723b30--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/viewedTaskContext.ts@@ -0,0 +1,57 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { buildTaskDetailPrompt, buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';+import debug from 'debug';++import { TaskDetailService } from '@/server/services/task/detail';++import type { InternalExecAgentParams } from '../types';++const log = debug('lobe-server:ai-agent-service');++export interface ViewedTaskContextDeps {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/**+ * Task Manager context for a run started from the Tasks side conversation.+ *+ * Server-run counterpart of the client streaming executor's `viewedTask`+ * injection: the gateway forwards the viewed task as `taskId`, so a run on a+ * task detail page answers "this task" from the task itself. Without a task+ * (list view) or when it cannot be loaded, only the assignee defaults remain.+ */+export const buildViewedTaskContextPrompt = async (+ deps: ViewedTaskContextDeps,+ appContext: InternalExecAgentParams['appContext'],+ taskId: string | undefined,+): Promise<string | undefined> => {+ if (appContext?.scope !== 'task') return;++ const defaultAssigneeAgentId = appContext.defaultTaskAssigneeAgentId;++ if (taskId) {+ try {+ const task = await new TaskDetailService(+ deps.db,+ deps.userId,+ deps.workspaceId,+ ).getTaskDetail(taskId);+ if (task) return buildTaskDetailPrompt({ defaultAssigneeAgentId, task });+ } catch (error) {+ log('failed to load viewed task %s: %O', taskId, error);+ }+ }++ if (!defaultAssigneeAgentId) return;++ return buildTaskManagerDefaultsPrompt({ defaultAssigneeAgentId });+};++/** Appends the viewed-task prompt to a hetero agent's static system context. */+export const joinSystemContext = (...parts: (string | undefined)[]): string | undefined =>+ parts+ .map((part) => part?.trim())+ .filter(Boolean)+ .join('\n\n') || undefined;diff --git a/apps/server/src/services/task/detail.ts b/apps/server/src/services/task/detail.tsnew file mode 100644index 00000000000..c632a010553--- /dev/null+++ b/apps/server/src/services/task/detail.ts@@ -0,0 +1,561 @@+import type {+ TaskAssignmentKind,+ TaskAutomationSnapshot,+ TaskDetailActivity,+ TaskDetailActivityAuthor,+ TaskDetailData,+ TaskDetailSubtask,+ TaskDetailWorkspaceNode,+ TaskStatus,+ TaskTopicHandoff,+ WorkspaceData,+} from '@lobechat/types';+import pMap from 'p-map';++import { AgentModel } from '@/database/models/agent';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { UserModel } from '@/database/models/user';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type { LobeChatDatabase } from '@/database/type';++import { extractFileIdsFromEditorData } from '../file/extractFileIdsFromEditorData';+import { resolveAttachmentMetadata } from '../file/resolveAttachments';+import { resolveTaskAcceptance } from '../verify/taskAcceptance';+import { collapseActivityLog } from './collapseActivityLog';+import { projectTaskDetailState } from './detailProjection';++const emptyWorkspace: WorkspaceData = { nodeMap: {}, tree: [] };+const UNTITLED_TOPIC_TITLE = 'Untitled';+const TASK_DETAIL_DIRECT_TOPIC_LIMIT = 100;+/**+ * Newest raw activity rows read per detail fetch, before collapsing. The+ * detail page polls every few seconds while work is in flight, so it must not+ * ship a long-lived task's whole append-only history each time; the table+ * keeps everything for an audit view.+ */+const TASK_DETAIL_ACTIVITY_LIMIT = 200;+const TASK_DETAIL_DESCENDANT_TOPIC_LIMIT = 300;++type DirectTaskTopicActivityRow = Awaited<ReturnType<TaskTopicModel['findWithHandoff']>>[number];+type DescendantTaskTopicActivityRow = Awaited<+ ReturnType<TaskTopicModel['findWithHandoffByTaskIds']>+>[number];+type TaskTopicActivityRow = DirectTaskTopicActivityRow &+ Partial<+ Pick<+ DescendantTaskTopicActivityRow,+ 'sourceTaskAssigneeAgentId' | 'sourceTaskId' | 'sourceTaskIdentifier' | 'sourceTaskName'+ >+ >;++/**+ * Assembles the task detail payload. Kept apart from `TaskService` so readers+ * that `TaskService` itself depends on (the agent runtime) can load a task+ * without an import cycle.+ */+export class TaskDetailService {+ private agentModel: AgentModel;+ private db: LobeChatDatabase;+ private taskModel: TaskModel;+ private taskTopicModel: TaskTopicModel;+ private userId: string;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ this.agentModel = new AgentModel(db, userId, workspaceId);+ this.taskModel = new TaskModel(db, userId, workspaceId);+ this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);+ }++ async getTaskDetail(taskIdOrIdentifier: string): Promise<TaskDetailData | null> {+ let task = await this.taskModel.resolve(taskIdOrIdentifier);+ if (!task) return null;++ // Auto-detect heartbeat timeout for running tasks before assembling detail.+ if (task.status === 'running' && task.heartbeatTimeout && task.lastHeartbeatAt) {+ const elapsed = (Date.now() - new Date(task.lastHeartbeatAt).getTime()) / 1000;+ if (elapsed > task.heartbeatTimeout) {+ await this.taskModel.updateStatus(task.id, 'paused', { error: 'Heartbeat timeout' });+ await this.taskTopicModel.timeoutRunning(task.id);+ task = await this.taskModel.resolve(taskIdOrIdentifier);+ if (!task) return null;+ }+ }++ // Clear stale heartbeat timeout error once the task is no longer running.+ if (task.status !== 'running' && task.error === 'Heartbeat timeout') {+ await this.taskModel.update(task.id, { error: null });+ task = { ...task, error: null };+ }++ // Brief hidden: the task detail activity feed no longer carries+ // brief-type activities β the UI converges on Task Run. Briefs are therefore+ // not fetched/enriched here (see the omitted brief spread below). The brief+ // lifecycle, model and data are untouched; revert this to bring them back.+ const [+ allDescendants,+ dependencies,+ directTopics,+ comments,+ activityLogs,+ workspace,+ acceptance,+ goal,+ ] = await Promise.all([+ this.taskModel.findAllDescendants(task.id),+ this.taskModel.getDependencies(task.id),+ this.taskTopicModel.findWithHandoff(task.id, TASK_DETAIL_DIRECT_TOPIC_LIMIT).catch(() => []),+ this.taskModel.getComments(task.id).catch(() => []),+ this.taskModel.getActivities(task.id, TASK_DETAIL_ACTIVITY_LIMIT).catch(() => []),+ this.taskModel.getTreePinnedDocuments(task.id).catch(() => emptyWorkspace),+ resolveTaskAcceptance(this.db, this.userId, task.id, this.workspaceId).catch(() => undefined),+ // The goal this task belongs to, so the page can link back to it+ new GoalGraphModel(this.db, this.userId, this.workspaceId)+ .findGoalByTaskId(task.id)+ .catch(() => undefined),+ ]);++ // What the reader is shown, not what was written: a burst of edits to one+ // property by one person folds into a single "from A to C", and a value+ // that ended up where it started is not shown at all. The rows themselves+ // stay append-only.+ const shownLogs = collapseActivityLog(activityLogs);++ const allDescendantIds = allDescendants.map((s) => s.id);+ const descendantTaskMap = new Map(allDescendants.map((s) => [s.id, s]));+ const descendantTopics =+ allDescendantIds.length > 0+ ? await this.taskTopicModel+ .findWithHandoffByTaskIds(allDescendantIds, TASK_DETAIL_DESCENDANT_TOPIC_LIMIT)+ .catch(() => [])+ : [];++ const topics: TaskTopicActivityRow[] = [+ ...directTopics,+ ...descendantTopics.map((topic) => {+ const sourceTask = descendantTaskMap.get(topic.sourceTaskId);+ return {+ ...topic,+ sourceTaskAssigneeAgentId:+ topic.sourceTaskAssigneeAgentId ?? sourceTask?.assigneeAgentId ?? null,+ sourceTaskId: topic.sourceTaskId ?? sourceTask?.id ?? null,+ sourceTaskIdentifier: topic.sourceTaskIdentifier ?? sourceTask?.identifier ?? null,+ sourceTaskName: topic.sourceTaskName ?? sourceTask?.name ?? null,+ };+ }),+ ];++ // Derive fileIds from persisted editor_data (single source of truth).+ const extractCtx = { db: this.db, userId: this.userId, workspaceId: this.workspaceId };+ const [taskFileIds, commentFileIdLists] = await Promise.all([+ extractFileIdsFromEditorData(task.editorData, extractCtx),+ pMap(comments, (c) => extractFileIdsFromEditorData(c.editorData, extractCtx), {+ concurrency: 10,+ }),+ ]);+ const commentFileIdsMap: Record<string, string[]> = {};+ comments.forEach((c, i) => {+ const ids = commentFileIdLists[i];+ if (ids.length > 0) commentFileIdsMap[c.id] = ids;+ });++ const allFileIds = [...taskFileIds, ...Object.values(commentFileIdsMap).flat()];+ const allFileMetadata = await resolveAttachmentMetadata({+ db: this.db,+ fileIds: allFileIds,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ const fileById = new Map(allFileMetadata.map((f) => [f.id, f]));+ const taskFiles = taskFileIds.map((id) => fileById.get(id)).filter((f) => !!f);++ const [allDescendantDeps, allDescendantTopics] =+ allDescendantIds.length > 0+ ? await Promise.all([+ this.taskModel.getDependenciesByTaskIds(allDescendantIds).catch(() => []),+ this.taskTopicModel.findRunningByTaskIds(allDescendantIds).catch(() => []),+ ])+ : [[], []];++ // Build dependency map for all descendants+ const idToIdentifier = new Map(allDescendants.map((s) => [s.id, s.identifier]));+ const depMap = new Map<string, string>();+ for (const dep of allDescendantDeps) {+ const depId = idToIdentifier.get(dep.dependsOnId);+ if (depId) depMap.set(dep.taskId, depId);+ }++ const runningTopicByTaskId = new Map<string, (typeof allDescendantTopics)[number]>();+ for (const topic of allDescendantTopics) {+ if (!runningTopicByTaskId.has(topic.taskId)) runningTopicByTaskId.set(topic.taskId, topic);+ }++ // Build nested subtask tree+ const childrenMap = new Map<string, typeof allDescendants>();+ for (const t of allDescendants) {+ const parentId = t.parentTaskId!;+ if (!childrenMap.has(parentId)) childrenMap.set(parentId, []);+ childrenMap.get(parentId)!.push(t);+ }++ // Resolve subtask assignee agents in batch so the UI can render avatars+ // without depending on client-side agent store state.+ const subtaskAssigneeIds = [+ ...new Set(+ allDescendants.map((s) => s.assigneeAgentId).filter((id): id is string => Boolean(id)),+ ),+ ];+ const subtaskAgents =+ subtaskAssigneeIds.length > 0+ ? await this.agentModel.getAgentAvatarsByIds(subtaskAssigneeIds)+ : [];+ const subtaskAgentMap = new Map(subtaskAgents.map((a) => [a.id, a]));++ const buildSubtaskTree = (parentId: string): TaskDetailSubtask[] | undefined => {+ const children = childrenMap.get(parentId);+ if (!children || children.length === 0) return undefined;+ return children.map((s) => {+ const agent = s.assigneeAgentId ? subtaskAgentMap.get(s.assigneeAgentId) : undefined;+ const runningTopic = runningTopicByTaskId.get(s.id);+ return {+ ...(agent+ ? {+ assignee: {+ avatar: agent.avatar,+ backgroundColor: agent.backgroundColor,+ id: agent.id,+ title: agent.title,+ },+ }+ : {}),+ ...(s.archivedAt ? { archivedAt: new Date(s.archivedAt).toISOString() } : {}),+ assigneeUserId: s.assigneeUserId,+ automationMode: s.automationMode,+ blockedBy: depMap.get(s.id),+ createdByUserId: s.createdByUserId,+ visibility: s.visibility,+ children: buildSubtaskTree(s.id),+ ...(s.heartbeatInterval != null ? { heartbeat: { interval: s.heartbeatInterval } } : {}),+ identifier: s.identifier,+ name: s.name,+ priority: s.priority,+ ...(runningTopic?.topicId+ ? {+ runningTopic: {+ id: runningTopic.topicId,+ operationId: runningTopic.operationId ?? null,+ },+ }+ : {}),+ ...(s.schedulePattern || s.scheduleTimezone+ ? { schedule: { pattern: s.schedulePattern, timezone: s.scheduleTimezone } }+ : {}),+ status: s.status,+ updatedAt: s.updatedAt ? new Date(s.updatedAt).toISOString() : undefined,+ };+ });+ };++ // Root level: always return array (empty [] when no subtasks) for consistent API shape+ const subtasks = buildSubtaskTree(task.id) ?? [];++ // Resolve dependency task identifiers+ const depTaskIds = [...new Set(dependencies.map((d) => d.dependsOnId))];+ const depTasks = await this.taskModel.findByIds(depTaskIds);+ const depIdToInfo = new Map(+ depTasks.map((t) => [t.id, { identifier: t.identifier, name: t.name }]),+ );++ // Resolve parent+ let parent: { agentId: string | null; identifier: string; name: string | null } | null = null;+ if (task.parentTaskId) {+ const parentTask = await this.taskModel.findById(task.parentTaskId);+ if (parentTask) {+ parent = {+ agentId: parentTask.assigneeAgentId,+ identifier: parentTask.identifier,+ name: parentTask.name,+ };+ }+ }++ // Build workspace tree (recursive)+ const buildWorkspaceNodes = (treeNodes: typeof workspace.tree): TaskDetailWorkspaceNode[] =>+ treeNodes.map((node) => {+ const doc = workspace.nodeMap[node.id];+ return {+ children: node.children.length > 0 ? buildWorkspaceNodes(node.children) : undefined,+ createdAt: doc?.createdAt ? new Date(doc.createdAt).toISOString() : undefined,+ documentId: node.id,+ fileType: doc?.fileType,+ inaccessible: doc?.inaccessible,+ size: doc?.charCount,+ sourceTaskId: doc?.sourceTaskId,+ sourceTaskIdentifier: doc?.sourceTaskIdentifier,+ title: doc?.title,+ };+ });++ const workspaceFolders = buildWorkspaceNodes(workspace.tree);++ // Build activities (merged & sorted desc by time)+ const toISO = (d: Date | string | null | undefined) =>+ d ? new Date(d).toISOString() : undefined;++ // Collect unique agent/user IDs for author resolution+ const agentIds = new Set<string>();+ const userIds = new Set<string>();++ // Each topic keeps the agent that actually ran it (topics.agentId), so an+ // earlier run's avatar stays correct after the task is reassigned. Fall back+ // to the source task assignee, then the current task assignee, only when a+ // topic has no recorded agent.+ for (const t of topics) {+ const topicAgentId = t.agentId ?? t.sourceTaskAssigneeAgentId ?? task.assigneeAgentId;+ if (topicAgentId) agentIds.add(topicAgentId);+ }+ // Comments have authorAgentId or authorUserId+ for (const c of comments) {+ if (c.authorAgentId) agentIds.add(c.authorAgentId);+ if (c.authorUserId) userIds.add(c.authorUserId);+ }+ // Creator of the task itself (agent takes precedence over user)+ if (task.createdByAgentId) agentIds.add(task.createdByAgentId);+ else if (task.createdByUserId) userIds.add(task.createdByUserId);+ // Assignment events carry an actor plus both sides of the change; which+ // set an id belongs to is decided by the event type, not by the column.+ for (const log of shownLogs) {+ if (log.actorAgentId) agentIds.add(log.actorAgentId);+ if (log.actorUserId) userIds.add(log.actorUserId);+ // Property events carry values, not participant ids.+ if (log.type !== 'assignee_agent' && log.type !== 'assignee_user') continue;+ const target = log.type === 'assignee_agent' ? agentIds : userIds;+ for (const id of [log.payload?.fromId, log.payload?.toId]) if (id) target.add(id);+ }++ const authorMap = await this.resolveAuthors(agentIds, userIds);++ // Every run row answers "and did it pass?" on its own (with counts). Without this the+ // activity feed lists rounds that all look alike, and the only way to learn+ // a round's verdict is to leave for the acceptance page.+ const verifyByOperation = await new VerifyRunModel(this.db, this.userId, this.workspaceId)+ .findByOperations(topics.map((t) => t.operationId).filter((id): id is string => Boolean(id)))+ .catch(() => new Map());++ const creatorId = task.createdByAgentId ?? task.createdByUserId;+ const createdActivity: TaskDetailActivity | null =+ task.createdAt && creatorId+ ? {+ author: authorMap.get(creatorId),+ time: toISO(task.createdAt),+ type: 'created' as const,+ }+ : null;++ const activities: TaskDetailActivity[] = [+ ...(createdActivity ? [createdActivity] : []),+ ...topics.map((t) => {+ const handoff = t.handoff as TaskTopicHandoff | null;+ const topicAgentId = t.agentId ?? t.sourceTaskAssigneeAgentId ?? task.assigneeAgentId;+ const verifyRun = t.operationId ? verifyByOperation.get(t.operationId) : undefined;+ return {+ author: topicAgentId ? authorMap.get(topicAgentId) : undefined,+ completedAt: toISO(t.completedAt),+ cost: t.totalCost == null ? null : Number(t.totalCost),+ // Raw last assistant message of the run, shown alongside+ // the synthesized summary on the run card.+ content: handoff?.content,+ id: t.topicId ?? undefined,+ operationId: t.operationId ?? null,+ runningOperation: t.metadata?.runningOperation ?? null,+ seq: t.seq,+ status: t.status,+ summary: handoff?.summary,+ sourceTaskId: t.sourceTaskId,+ sourceTaskIdentifier: t.sourceTaskIdentifier,+ sourceTaskName: t.sourceTaskName,+ time: toISO(t.createdAt),+ title: handoff?.title || t.title || UNTITLED_TOPIC_TITLE,+ // What opened this round. Without it the feed cannot distinguish a run+ // the user started from one the goal coordinator / scheduler opened on its+ // own β they render identically apart from `#seq`.+ trigger: t.trigger ?? null,+ verify: verifyRun+ ? {+ acceptanceId: verifyRun.acceptanceId,+ passed: verifyRun.passed,+ roundIndex: verifyRun.roundIndex,+ runId: verifyRun.id,+ status: verifyRun.status,+ total: verifyRun.total,+ }+ : null,+ type: 'topic' as const,+ };+ }),+ // Brief activities intentionally omitted β see the fetch note above.+ ...comments.map((c) => {+ const ids = commentFileIdsMap[c.id] ?? [];+ const files = ids.map((id) => fileById.get(id)).filter((f) => !!f);+ return {+ agentId: c.authorAgentId,+ author: c.authorAgentId+ ? authorMap.get(c.authorAgentId)+ : c.authorUserId+ ? authorMap.get(c.authorUserId)+ : undefined,+ content: c.content,+ editorData: c.editorData ?? undefined,+ files: files.length > 0 ? files : undefined,+ id: c.id,+ time: toISO(c.createdAt),+ type: 'comment' as const,+ };+ }),+ ...shownLogs.map((log): TaskDetailActivity => {+ const stub = (id: string, type: 'agent' | 'user'): TaskDetailActivityAuthor => ({+ id,+ name: null,+ type,+ unresolved: true,+ });+ const actorKind = log.payload?.actorKind;+ const author = log.actorAgentId+ ? (authorMap.get(log.actorAgentId) ?? stub(log.actorAgentId, 'agent'))+ : log.actorUserId+ ? (authorMap.get(log.actorUserId) ?? stub(log.actorUserId, 'user'))+ : actorKind === 'agent' || actorKind === 'user'+ ? // Somebody did it but their row is gone: the actor columns are+ // cleared on delete, and only the payload remembers there was+ // a person. Must not read as the system.+ stub('', actorKind)+ : // Genuinely nobody: the runner's system fallback.+ undefined;++ if (log.type === 'status' || log.type === 'priority' || log.type === 'automation') {+ const from = log.payload?.from ?? null;+ const to = log.payload?.to ?? null;+ const propertyChange: NonNullable<TaskDetailActivity['propertyChange']> =+ log.type === 'status'+ ? { field: 'status', from: from as TaskStatus | null, to: to as TaskStatus }+ : log.type === 'priority'+ ? { field: 'priority', from: from as number | null, to: to as number | null }+ : {+ field: 'automation',+ from: from as TaskAutomationSnapshot | null,+ to: to as TaskAutomationSnapshot | null,+ };+ return {+ author,+ id: log.id,+ propertyChange,+ time: toISO(log.createdAt),+ type: 'property',+ };+ }++ const kind: TaskAssignmentKind = log.type === 'assignee_agent' ? 'agent' : 'member';+ // A missing author row means the participant is gone, or is private to+ // another member and filtered out of this viewer's scope. Keep a stub+ // instead of collapsing to `null`/`undefined`: `null` reads as+ // "unassigned" (turning a reassignment into a removal) and an absent+ // actor reads as the system (falsely crediting it for an agent's work).+ const resolveSide = (id?: string | null): TaskDetailActivityAuthor | null => {+ if (!id) return null;+ return authorMap.get(id) ?? stub(id, kind === 'agent' ? 'agent' : 'user');+ };+ return {+ assignment: {+ from: resolveSide(log.payload?.fromId),+ kind,+ to: resolveSide(log.payload?.toId),+ },+ author,+ id: log.id,+ time: toISO(log.createdAt),+ type: 'assignment' as const,+ };+ }),+ ].sort((a, b) => {+ if (!a.time) return 1;+ if (!b.time) return -1;+ return a.time.localeCompare(b.time);+ });++ const taskConfig = task.config ? (task.config as Record<string, unknown>) : undefined;++ return {+ ...projectTaskDetailState(task, taskConfig),+ agentId: task.assigneeAgentId,+ automationMode: task.automationMode ?? null,+ checkpoint: this.taskModel.getCheckpointConfig(task),+ config: taskConfig,+ createdAt: task.createdAt ? new Date(task.createdAt).toISOString() : undefined,+ createdByUserId: task.createdByUserId,+ dependencies: dependencies.map((d) => {+ const info = depIdToInfo.get(d.dependsOnId);+ return {+ dependsOn: info?.identifier ?? d.dependsOnId,+ name: info?.name,+ type: d.type,+ };+ }),+ description: task.description,+ editorData: task.editorData ?? undefined,+ error: task.error,+ goal: goal ?? null,+ files: taskFiles.length > 0 ? taskFiles : undefined,+ id: task.id,+ identifier: task.identifier,+ instruction: task.instruction,+ name: task.name,+ parent,+ priority: task.priority,+ startedAt: task.startedAt ? new Date(task.startedAt).toISOString() : undefined,+ status: task.status,+ userId: task.assigneeUserId,+ verify: acceptance+ ? { ...acceptance.config, requirement: acceptance.requirement }+ : this.taskModel.getVerifyConfig(task),+ visibility: task.visibility,+ subtasks,+ activities: activities.length > 0 ? activities : undefined,+ topicCount: topics.length > 0 ? topics.length : undefined,+ updatedAt: task.updatedAt ? new Date(task.updatedAt).toISOString() : undefined,+ workspace: workspaceFolders.length > 0 ? workspaceFolders : undefined,+ workspaceId: task.workspaceId ?? null,+ };+ }++ /**+ * Batch-resolve agent and user IDs to author info (name + avatar).+ */+ private async resolveAuthors(+ agentIds: Set<string>,+ userIds: Set<string>,+ ): Promise<Map<string, TaskDetailActivityAuthor>> {+ const map = new Map<string, TaskDetailActivityAuthor>();++ const [agentRows, userRows] = await Promise.all([+ this.agentModel.getAgentAvatarsByIds([...agentIds]),+ UserModel.findByIds(this.db, [...userIds]),+ ]);++ // Both display columns are nullable, so fall back to the other one the+ // query already returns rather than letting a live participant render as+ // nameless β the UI reserves its nameless labels for absent identities.+ for (const a of agentRows) {+ map.set(a.id, { avatar: a.avatar, id: a.id, name: a.title || a.name, type: 'agent' });+ }+ for (const u of userRows) {+ map.set(u.id, { avatar: u.avatar, id: u.id, name: u.fullName || u.username, type: 'user' });+ }++ return map;+ }+}diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex e4cef46412b..ec0744e3094 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -3,24 +3,15 @@ import { randomUUID } from 'node:crypto';import { UNFINISHED_TASK_STATUSES } from '@lobechat/builtin-tool-task';import { TASK_ASSIGNEE_PERMISSION_CODES } from '@lobechat/const/rbac';import type {- TaskAssignmentKind,- TaskAutomationSnapshot,TaskContext,- TaskDetailActivity,- TaskDetailActivityAuthor,TaskDetailData,- TaskDetailSubtask,- TaskDetailWorkspaceNode,TaskItem,TaskSchedulerContext,TaskStatus,- TaskTopicHandoff,- WorkspaceData,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import { AgentModel } from '@/database/models/agent';-import { GoalGraphModel } from '@/database/models/goalGraph';import { ProjectModel } from '@/database/models/project';import { RbacModel } from '@/database/models/rbac';import {@@ -30,50 +21,21 @@ import {} from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';import { TopicModel } from '@/database/models/topic';-import { UserModel } from '@/database/models/user';-import { VerifyRunModel } from '@/database/models/verifyRun';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '../aiAgent';-import { extractFileIdsFromEditorData } from '../file/extractFileIdsFromEditorData';-import { resolveAttachmentMetadata } from '../file/resolveAttachments';import { type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';import { type ReviewResult, TaskReviewService } from '../taskReview';import { TaskRunnerService } from '../taskRunner';import { createTaskSchedulerModule } from '../taskScheduler';-import { resolveTaskAcceptance } from '../verify/taskAcceptance';import { assertArchivedTaskStaysIdle, writeKeepingArchivedIdle } from './archiveGuard';-import { collapseActivityLog } from './collapseActivityLog';-import { projectTaskDetailState } from './detailProjection';+import { TaskDetailService } from './detail';import { resolveMissingTaskModelConfig } from './modelSnapshot';-const emptyWorkspace: WorkspaceData = { nodeMap: {}, tree: [] };-const UNTITLED_TOPIC_TITLE = 'Untitled';-const TASK_DETAIL_DIRECT_TOPIC_LIMIT = 100;-/**- * Newest raw activity rows read per detail fetch, before collapsing. The- * detail page polls every few seconds while work is in flight, so it must not- * ship a long-lived task's whole append-only history each time; the table- * keeps everything for an audit view.- */-const TASK_DETAIL_ACTIVITY_LIMIT = 200;-const TASK_DETAIL_DESCENDANT_TOPIC_LIMIT = 300;/** How long after a run starts a task may have no recorded operation yet. */const TASK_RUN_STARTING_GRACE_MS = 2 * 60 * 1000;-type DirectTaskTopicActivityRow = Awaited<ReturnType<TaskTopicModel['findWithHandoff']>>[number];-type DescendantTaskTopicActivityRow = Awaited<- ReturnType<TaskTopicModel['findWithHandoffByTaskIds']>->[number];-type TaskTopicActivityRow = DirectTaskTopicActivityRow &- Partial<- Pick<- DescendantTaskTopicActivityRow,- 'sourceTaskAssigneeAgentId' | 'sourceTaskId' | 'sourceTaskIdentifier' | 'sourceTaskName'- >- >;-export interface CreateTaskInput {assigneeAgentId?: string;assigneeUserId?: string;@@ -1024,487 +986,8 @@ export class TaskService {}async getTaskDetail(taskIdOrIdentifier: string): Promise<TaskDetailData | null> {- let task = await this.taskModel.resolve(taskIdOrIdentifier);- if (!task) return null;-- // Auto-detect heartbeat timeout for running tasks before assembling detail.- if (task.status === 'running' && task.heartbeatTimeout && task.lastHeartbeatAt) {- const elapsed = (Date.now() - new Date(task.lastHeartbeatAt).getTime()) / 1000;- if (elapsed > task.heartbeatTimeout) {- await this.taskModel.updateStatus(task.id, 'paused', { error: 'Heartbeat timeout' });- await this.taskTopicModel.timeoutRunning(task.id);- task = await this.taskModel.resolve(taskIdOrIdentifier);- if (!task) return null;- }- }-- // Clear stale heartbeat timeout error once the task is no longer running.- if (task.status !== 'running' && task.error === 'Heartbeat timeout') {- await this.taskModel.update(task.id, { error: null });- task = { ...task, error: null };- }-- // Brief hidden: the task detail activity feed no longer carries- // brief-type activities β the UI converges on Task Run. Briefs are therefore- // not fetched/enriched here (see the omitted brief spread below). The brief- // lifecycle, model and data are untouched; revert this to bring them back.- const [- allDescendants,- dependencies,- directTopics,- comments,- activityLogs,- workspace,- acceptance,- goal,- ] = await Promise.all([- this.taskModel.findAllDescendants(task.id),- this.taskModel.getDependencies(task.id),- this.taskTopicModel.findWithHandoff(task.id, TASK_DETAIL_DIRECT_TOPIC_LIMIT).catch(() => []),- this.taskModel.getComments(task.id).catch(() => []),- this.taskModel.getActivities(task.id, TASK_DETAIL_ACTIVITY_LIMIT).catch(() => []),- this.taskModel.getTreePinnedDocuments(task.id).catch(() => emptyWorkspace),- resolveTaskAcceptance(this.db, this.userId, task.id, this.workspaceId).catch(() => undefined),- // The goal this task belongs to, so the page can link back to it- new GoalGraphModel(this.db, this.userId, this.workspaceId)- .findGoalByTaskId(task.id)- .catch(() => undefined),- ]);-- // What the reader is shown, not what was written: a burst of edits to one- // property by one person folds into a single "from A to C", and a value- // that ended up where it started is not shown at all. The rows themselves- // stay append-only.- const shownLogs = collapseActivityLog(activityLogs);-- const allDescendantIds = allDescendants.map((s) => s.id);- const descendantTaskMap = new Map(allDescendants.map((s) => [s.id, s]));- const descendantTopics =- allDescendantIds.length > 0- ? await this.taskTopicModel- .findWithHandoffByTaskIds(allDescendantIds, TASK_DETAIL_DESCENDANT_TOPIC_LIMIT)- .catch(() => [])- : [];-- const topics: TaskTopicActivityRow[] = [- ...directTopics,- ...descendantTopics.map((topic) => {- const sourceTask = descendantTaskMap.get(topic.sourceTaskId);- return {- ...topic,- sourceTaskAssigneeAgentId:- topic.sourceTaskAssigneeAgentId ?? sourceTask?.assigneeAgentId ?? null,- sourceTaskId: topic.sourceTaskId ?? sourceTask?.id ?? null,- sourceTaskIdentifier: topic.sourceTaskIdentifier ?? sourceTask?.identifier ?? null,- sourceTaskName: topic.sourceTaskName ?? sourceTask?.name ?? null,- };- }),- ];-- // Derive fileIds from persisted editor_data (single source of truth).- const extractCtx = { db: this.db, userId: this.userId, workspaceId: this.workspaceId };- const [taskFileIds, ...commentFileIdLists] = await Promise.all([- extractFileIdsFromEditorData(task.editorData, extractCtx),- ...comments.map((c) => extractFileIdsFromEditorData(c.editorData, extractCtx)),- ]);- const commentFileIdsMap: Record<string, string[]> = {};- comments.forEach((c, i) => {- const ids = commentFileIdLists[i];- if (ids.length > 0) commentFileIdsMap[c.id] = ids;- });-- const allFileIds = [...taskFileIds, ...Object.values(commentFileIdsMap).flat()];- const allFileMetadata = await resolveAttachmentMetadata({- db: this.db,- fileIds: allFileIds,- userId: this.userId,- workspaceId: this.workspaceId,- });- const fileById = new Map(allFileMetadata.map((f) => [f.id, f]));- const taskFiles = taskFileIds.map((id) => fileById.get(id)).filter((f) => !!f);-- const [allDescendantDeps, allDescendantTopics] =- allDescendantIds.length > 0- ? await Promise.all([- this.taskModel.getDependenciesByTaskIds(allDescendantIds).catch(() => []),- this.taskTopicModel.findRunningByTaskIds(allDescendantIds).catch(() => []),- ])- : [[], []];-- // Build dependency map for all descendants- const idToIdentifier = new Map(allDescendants.map((s) => [s.id, s.identifier]));- const depMap = new Map<string, string>();- for (const dep of allDescendantDeps) {- const depId = idToIdentifier.get(dep.dependsOnId);- if (depId) depMap.set(dep.taskId, depId);- }-- const runningTopicByTaskId = new Map<string, (typeof allDescendantTopics)[number]>();- for (const topic of allDescendantTopics) {- if (!runningTopicByTaskId.has(topic.taskId)) runningTopicByTaskId.set(topic.taskId, topic);- }-- // Build nested subtask tree- const childrenMap = new Map<string, typeof allDescendants>();- for (const t of allDescendants) {- const parentId = t.parentTaskId!;- if (!childrenMap.has(parentId)) childrenMap.set(parentId, []);- childrenMap.get(parentId)!.push(t);- }-- // Resolve subtask assignee agents in batch so the UI can render avatars- // without depending on client-side agent store state.- const subtaskAssigneeIds = [- ...new Set(- allDescendants.map((s) => s.assigneeAgentId).filter((id): id is string => Boolean(id)),- ),- ];- const subtaskAgents =- subtaskAssigneeIds.length > 0- ? await this.agentModel.getAgentAvatarsByIds(subtaskAssigneeIds)- : [];- const subtaskAgentMap = new Map(subtaskAgents.map((a) => [a.id, a]));-- const buildSubtaskTree = (parentId: string): TaskDetailSubtask[] | undefined => {- const children = childrenMap.get(parentId);- if (!children || children.length === 0) return undefined;- return children.map((s) => {- const agent = s.assigneeAgentId ? subtaskAgentMap.get(s.assigneeAgentId) : undefined;- const runningTopic = runningTopicByTaskId.get(s.id);- return {- ...(agent- ? {- assignee: {- avatar: agent.avatar,- backgroundColor: agent.backgroundColor,- id: agent.id,- title: agent.title,- },- }- : {}),- ...(s.archivedAt ? { archivedAt: new Date(s.archivedAt).toISOString() } : {}),- assigneeUserId: s.assigneeUserId,- automationMode: s.automationMode,- blockedBy: depMap.get(s.id),- createdByUserId: s.createdByUserId,- visibility: s.visibility,- children: buildSubtaskTree(s.id),- ...(s.heartbeatInterval != null ? { heartbeat: { interval: s.heartbeatInterval } } : {}),- identifier: s.identifier,- name: s.name,- priority: s.priority,- ...(runningTopic?.topicId- ? {- runningTopic: {- id: runningTopic.topicId,- operationId: runningTopic.operationId ?? null,- },- }- : {}),- ...(s.schedulePattern || s.scheduleTimezone- ? { schedule: { pattern: s.schedulePattern, timezone: s.scheduleTimezone } }- : {}),- status: s.status,- updatedAt: s.updatedAt ? new Date(s.updatedAt).toISOString() : undefined,- };- });- };-- // Root level: always return array (empty [] when no subtasks) for consistent API shape- const subtasks = buildSubtaskTree(task.id) ?? [];-- // Resolve dependency task identifiers- const depTaskIds = [...new Set(dependencies.map((d) => d.dependsOnId))];- const depTasks = await this.taskModel.findByIds(depTaskIds);- const depIdToInfo = new Map(- depTasks.map((t) => [t.id, { identifier: t.identifier, name: t.name }]),+ return new TaskDetailService(this.db, this.userId, this.workspaceId).getTaskDetail(+ taskIdOrIdentifier,);-- // Resolve parent- let parent: { agentId: string | null; identifier: string; name: string | null } | null = null;- if (task.parentTaskId) {- const parentTask = await this.taskModel.findById(task.parentTaskId);- if (parentTask) {- parent = {- agentId: parentTask.assigneeAgentId,- identifier: parentTask.identifier,- name: parentTask.name,- };- }- }-- // Build workspace tree (recursive)- const buildWorkspaceNodes = (treeNodes: typeof workspace.tree): TaskDetailWorkspaceNode[] =>- treeNodes.map((node) => {- const doc = workspace.nodeMap[node.id];- return {- children: node.children.length > 0 ? buildWorkspaceNodes(node.children) : undefined,- createdAt: doc?.createdAt ? new Date(doc.createdAt).toISOString() : undefined,- documentId: node.id,- fileType: doc?.fileType,- inaccessible: doc?.inaccessible,- size: doc?.charCount,- sourceTaskId: doc?.sourceTaskId,- sourceTaskIdentifier: doc?.sourceTaskIdentifier,- title: doc?.title,- };- });-- const workspaceFolders = buildWorkspaceNodes(workspace.tree);-- // Build activities (merged & sorted desc by time)- const toISO = (d: Date | string | null | undefined) =>- d ? new Date(d).toISOString() : undefined;-- // Collect unique agent/user IDs for author resolution- const agentIds = new Set<string>();- const userIds = new Set<string>();-- // Each topic keeps the agent that actually ran it (topics.agentId), so an- // earlier run's avatar stays correct after the task is reassigned. Fall back- // to the source task assignee, then the current task assignee, only when a- // topic has no recorded agent.- for (const t of topics) {- const topicAgentId = t.agentId ?? t.sourceTaskAssigneeAgentId ?? task.assigneeAgentId;- if (topicAgentId) agentIds.add(topicAgentId);- }- // Comments have authorAgentId or authorUserId- for (const c of comments) {- if (c.authorAgentId) agentIds.add(c.authorAgentId);- if (c.authorUserId) userIds.add(c.authorUserId);- }- // Creator of the task itself (agent takes precedence over user)- if (task.createdByAgentId) agentIds.add(task.createdByAgentId);- else if (task.createdByUserId) userIds.add(task.createdByUserId);- // Assignment events carry an actor plus both sides of the change; which- // set an id belongs to is decided by the event type, not by the column.- for (const log of shownLogs) {- if (log.actorAgentId) agentIds.add(log.actorAgentId);- if (log.actorUserId) userIds.add(log.actorUserId);- // Property events carry values, not participant ids.- if (log.type !== 'assignee_agent' && log.type !== 'assignee_user') continue;- const target = log.type === 'assignee_agent' ? agentIds : userIds;- for (const id of [log.payload?.fromId, log.payload?.toId]) if (id) target.add(id);- }-- const authorMap = await this.resolveAuthors(agentIds, userIds);-- // Every run row answers "and did it pass?" on its own (with counts). Without this the- // activity feed lists rounds that all look alike, and the only way to learn- // a round's verdict is to leave for the acceptance page.- const verifyByOperation = await new VerifyRunModel(this.db, this.userId, this.workspaceId)- .findByOperations(topics.map((t) => t.operationId).filter((id): id is string => Boolean(id)))- .catch(() => new Map());-- const creatorId = task.createdByAgentId ?? task.createdByUserId;- const createdActivity: TaskDetailActivity | null =- task.createdAt && creatorId- ? {- author: authorMap.get(creatorId),- time: toISO(task.createdAt),- type: 'created' as const,- }- : null;-- const activities: TaskDetailActivity[] = [- ...(createdActivity ? [createdActivity] : []),- ...topics.map((t) => {- const handoff = t.handoff as TaskTopicHandoff | null;- const topicAgentId = t.agentId ?? t.sourceTaskAssigneeAgentId ?? task.assigneeAgentId;- const verifyRun = t.operationId ? verifyByOperation.get(t.operationId) : undefined;- return {- author: topicAgentId ? authorMap.get(topicAgentId) : undefined,- completedAt: toISO(t.completedAt),- cost: t.totalCost == null ? null : Number(t.totalCost),- // Raw last assistant message of the run, shown alongside- // the synthesized summary on the run card.- content: handoff?.content,- id: t.topicId ?? undefined,- operationId: t.operationId ?? null,- runningOperation: t.metadata?.runningOperation ?? null,- seq: t.seq,- status: t.status,- summary: handoff?.summary,- sourceTaskId: t.sourceTaskId,- sourceTaskIdentifier: t.sourceTaskIdentifier,- sourceTaskName: t.sourceTaskName,- time: toISO(t.createdAt),- title: handoff?.title || t.title || UNTITLED_TOPIC_TITLE,- // What opened this round. Without it the feed cannot distinguish a run- // the user started from one the goal coordinator / scheduler opened on its- // own β they render identically apart from `#seq`.- trigger: t.trigger ?? null,- verify: verifyRun- ? {- acceptanceId: verifyRun.acceptanceId,- passed: verifyRun.passed,- roundIndex: verifyRun.roundIndex,- runId: verifyRun.id,- status: verifyRun.status,- total: verifyRun.total,- }- : null,- type: 'topic' as const,- };- }),- // Brief activities intentionally omitted β see the fetch note above.- ...comments.map((c) => {- const ids = commentFileIdsMap[c.id] ?? [];- const files = ids.map((id) => fileById.get(id)).filter((f) => !!f);- return {- agentId: c.authorAgentId,- author: c.authorAgentId- ? authorMap.get(c.authorAgentId)- : c.authorUserId- ? authorMap.get(c.authorUserId)- : undefined,- content: c.content,- editorData: c.editorData ?? undefined,- files: files.length > 0 ? files : undefined,- id: c.id,- time: toISO(c.createdAt),- type: 'comment' as const,- };- }),- ...shownLogs.map((log): TaskDetailActivity => {- const stub = (id: string, type: 'agent' | 'user'): TaskDetailActivityAuthor => ({- id,- name: null,- type,- unresolved: true,- });- const actorKind = log.payload?.actorKind;- const author = log.actorAgentId- ? (authorMap.get(log.actorAgentId) ?? stub(log.actorAgentId, 'agent'))- : log.actorUserId- ? (authorMap.get(log.actorUserId) ?? stub(log.actorUserId, 'user'))- : actorKind === 'agent' || actorKind === 'user'- ? // Somebody did it but their row is gone: the actor columns are- // cleared on delete, and only the payload remembers there was- // a person. Must not read as the system.- stub('', actorKind)- : // Genuinely nobody: the runner's system fallback.- undefined;-- if (log.type === 'status' || log.type === 'priority' || log.type === 'automation') {- const from = log.payload?.from ?? null;- const to = log.payload?.to ?? null;- const propertyChange: NonNullable<TaskDetailActivity['propertyChange']> =- log.type === 'status'- ? { field: 'status', from: from as TaskStatus | null, to: to as TaskStatus }- : log.type === 'priority'- ? { field: 'priority', from: from as number | null, to: to as number | null }- : {- field: 'automation',- from: from as TaskAutomationSnapshot | null,- to: to as TaskAutomationSnapshot | null,- };- return {- author,- id: log.id,- propertyChange,- time: toISO(log.createdAt),- type: 'property',- };- }-- const kind: TaskAssignmentKind = log.type === 'assignee_agent' ? 'agent' : 'member';- // A missing author row means the participant is gone, or is private to- // another member and filtered out of this viewer's scope. Keep a stub- // instead of collapsing to `null`/`undefined`: `null` reads as- // "unassigned" (turning a reassignment into a removal) and an absent- // actor reads as the system (falsely crediting it for an agent's work).- const resolveSide = (id?: string | null): TaskDetailActivityAuthor | null => {- if (!id) return null;- return authorMap.get(id) ?? stub(id, kind === 'agent' ? 'agent' : 'user');- };- return {- assignment: {- from: resolveSide(log.payload?.fromId),- kind,- to: resolveSide(log.payload?.toId),- },- author,- id: log.id,- time: toISO(log.createdAt),- type: 'assignment' as const,- };- }),- ].sort((a, b) => {- if (!a.time) return 1;- if (!b.time) return -1;- return a.time.localeCompare(b.time);- });-- const taskConfig = task.config ? (task.config as Record<string, unknown>) : undefined;-- return {- ...projectTaskDetailState(task, taskConfig),- agentId: task.assigneeAgentId,- automationMode: task.automationMode ?? null,- checkpoint: this.taskModel.getCheckpointConfig(task),- config: taskConfig,- createdAt: task.createdAt ? new Date(task.createdAt).toISOString() : undefined,- createdByUserId: task.createdByUserId,- dependencies: dependencies.map((d) => {- const info = depIdToInfo.get(d.dependsOnId);- return {- dependsOn: info?.identifier ?? d.dependsOnId,- name: info?.name,- type: d.type,- };- }),- description: task.description,- editorData: task.editorData ?? undefined,- error: task.error,- goal: goal ?? null,- files: taskFiles.length > 0 ? taskFiles : undefined,- id: task.id,- identifier: task.identifier,- instruction: task.instruction,- name: task.name,- parent,- priority: task.priority,- startedAt: task.startedAt ? new Date(task.startedAt).toISOString() : undefined,- status: task.status,- userId: task.assigneeUserId,- verify: acceptance- ? { ...acceptance.config, requirement: acceptance.requirement }- : this.taskModel.getVerifyConfig(task),- visibility: task.visibility,- subtasks,- activities: activities.length > 0 ? activities : undefined,- topicCount: topics.length > 0 ? topics.length : undefined,- updatedAt: task.updatedAt ? new Date(task.updatedAt).toISOString() : undefined,- workspace: workspaceFolders.length > 0 ? workspaceFolders : undefined,- workspaceId: task.workspaceId ?? null,- };- }-- /**- * Batch-resolve agent and user IDs to author info (name + avatar).- */- private async resolveAuthors(- agentIds: Set<string>,- userIds: Set<string>,- ): Promise<Map<string, TaskDetailActivityAuthor>> {- const map = new Map<string, TaskDetailActivityAuthor>();-- const [agentRows, userRows] = await Promise.all([- this.agentModel.getAgentAvatarsByIds([...agentIds]),- UserModel.findByIds(this.db, [...userIds]),- ]);-- // Both display columns are nullable, so fall back to the other one the- // query already returns rather than letting a live participant render as- // nameless β the UI reserves its nameless labels for absent identities.- for (const a of agentRows) {- map.set(a.id, { avatar: a.avatar, id: a.id, name: a.title || a.name, type: 'agent' });- }- for (const u of userRows) {- map.set(u.id, { avatar: u.avatar, id: u.id, name: u.fullName || u.username, type: 'user' });- }-- return map;}}diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex e8695ace5f0..44a45292058 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -23,12 +23,7 @@ import {resolveSubAgentModel,} from '@lobechat/const';import { type ToolsEngine } from '@lobechat/context-engine';-import {- buildTaskDetailPrompt,- buildTaskListPrompt,- FILE_PREVIEW_CHARS,- isOversizedFileContent,-} from '@lobechat/prompts';+import { FILE_PREVIEW_CHARS, isOversizedFileContent } from '@lobechat/prompts';import {buildGoalOverviewContext,type ConversationContext,@@ -68,7 +63,6 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { getElectronStoreState } from '@/store/electron';import { getGoalStoreState } from '@/store/goal';import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';-import { getTaskStoreState } from '@/store/task';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';import { type StoreSetter } from '@/store/types';import { toolInterventionSelectors } from '@/store/user/selectors';@@ -76,6 +70,7 @@ import { getUserStoreState } from '@/store/user/store';import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import type { RunParkedReason, RunScope } from '../../lifecycle/types';+import { buildViewedTaskPrompt } from '../viewedTaskPrompt';const log = debug('lobe-store:streaming-executor');@@ -433,28 +428,7 @@ export class StreamingExecutorActionImpl {const viewedTask = operation?.context.viewedTask;if (viewedTask) {try {- const taskState = getTaskStoreState();- let contextPrompt: string | undefined;-- if (viewedTask.type === 'list') {- const viewedList = taskState.activeTaskListKey- ? taskState.taskListMap[taskState.activeTaskListKey]- : undefined;- const tasks = viewedList?.items ?? [];- contextPrompt = buildTaskListPrompt({- defaultAssigneeAgentId: operation.context.defaultTaskAssigneeAgentId,- tasks,- total: viewedList?.total || tasks.length,- });- } else {- const detail = taskState.taskDetailMap[viewedTask.taskId];- if (detail)- contextPrompt = buildTaskDetailPrompt({- defaultAssigneeAgentId: operation.context.defaultTaskAssigneeAgentId,- task: detail,- });- }-+ const contextPrompt = buildViewedTaskPrompt(operation.context);if (contextPrompt) {runtimeInitialContext = {...runtimeInitialContext,diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 4250bf8f404..b681919cf1d 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -3,7 +3,7 @@ import type {AgentInterventionResponseData,AgentStreamEvent,} from '@lobechat/agent-gateway-client';-import { stripGoalCommand, withConversationGoalPrompt } from '@lobechat/builtin-tool-goal';+import { stripGoalCommand } from '@lobechat/builtin-tool-goal';import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import {@@ -91,6 +91,7 @@ import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectorsimport { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';+import { withHeteroContext } from '../viewedTaskPrompt';import { getNativeHeteroSessionBindingKey } from './heteroResume';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';@@ -2618,9 +2619,8 @@ export const executeHeterogeneousAgent = async (get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined;const systemContext = buildLocalHeterogeneousSystemContext({- // `/goal` reaches a hetero agent as instructions, not a tool: it creates- // and plans the goal through `lh` in this same run.- agentSystemContext: withConversationGoalPrompt(heterogeneousProvider.systemContext, message),+ // `/goal` and the viewed Tasks page reach a hetero agent as instructions.+ agentSystemContext: withHeteroContext(heterogeneousProvider.systemContext, message, context),contextSelections,pageSelections,// Only a topic created by Codex edit-and-resend starts with copieddiff --git a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.ts b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.tsnew file mode 100644index 00000000000..9ee12730b4d--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.test.ts@@ -0,0 +1,62 @@+import type { TaskDetailData } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { useTaskStore } from '@/store/task';++import { buildViewedTaskPrompt, withHeteroContext } from './viewedTaskPrompt';++const taskDetail: TaskDetailData = {+ identifier: 'T-858',+ instruction: 'Make images in the task content draggable',+ name: 'Task content images cannot be dragged',+ status: 'running',+};++const detailContext = {+ defaultTaskAssigneeAgentId: 'agt_inbox',+ viewedTask: { taskId: 'T-858', type: 'detail' as const },+};++describe('buildViewedTaskPrompt', () => {+ beforeEach(() => {+ useTaskStore.setState({ taskDetailMap: { 'T-858': taskDetail } });+ });++ it('describes the viewed task detail', () => {+ const prompt = buildViewedTaskPrompt(detailContext);++ expect(prompt).toContain('The user is currently viewing the detail page of task T-858');+ expect(prompt).toContain('Default Lobe AI agent id: agt_inbox');+ });++ it('returns undefined before the viewed task loads or outside Tasks', () => {+ useTaskStore.setState({ taskDetailMap: {} });++ expect(buildViewedTaskPrompt(detailContext)).toBeUndefined();+ expect(buildViewedTaskPrompt({})).toBeUndefined();+ expect(buildViewedTaskPrompt(undefined)).toBeUndefined();+ });+});++describe('withHeteroContext', () => {+ beforeEach(() => {+ useTaskStore.setState({ taskDetailMap: { 'T-858': taskDetail } });+ });++ it('appends the viewed task to the agent system context', () => {+ const systemContext = withHeteroContext(' Agent rules ', 'Which task is this?', detailContext);++ expect(systemContext).toMatch(/^Agent rules\n\n<page_context>/);+ expect(systemContext).toContain('Make images in the task content draggable');+ });++ it('keeps the agent system context as is outside Tasks', () => {+ expect(withHeteroContext('Agent rules', 'hello', {})).toBe('Agent rules');+ expect(withHeteroContext(undefined, 'hello', {})).toBeUndefined();+ });++ it('still carries the /goal instructions', () => {+ expect(withHeteroContext(undefined, '/goal ship it', detailContext)).toContain('T-858');+ expect(withHeteroContext(undefined, '/goal ship it', {})).toBeTruthy();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.tsnew file mode 100644index 00000000000..7003d8badc4--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/viewedTaskPrompt.ts@@ -0,0 +1,53 @@+import { withConversationGoalPrompt } from '@lobechat/builtin-tool-goal';+import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';+import type { ConversationContext } from '@lobechat/types';++import { getTaskStoreState } from '@/store/task';++/**+ * Task Manager context for the task list or task detail page the Tasks side+ * conversation is opened on, built from the task store the page renders.+ * Returns undefined outside Tasks or before the viewed task has loaded.+ */+export const buildViewedTaskPrompt = (+ context: Pick<ConversationContext, 'defaultTaskAssigneeAgentId' | 'viewedTask'> | undefined,+): string | undefined => {+ const viewedTask = context?.viewedTask;+ if (!viewedTask) return;++ const taskState = getTaskStoreState();+ const defaultAssigneeAgentId = context.defaultTaskAssigneeAgentId;++ if (viewedTask.type === 'list') {+ const viewedList = taskState.activeTaskListKey+ ? taskState.taskListMap[taskState.activeTaskListKey]+ : undefined;+ const tasks = viewedList?.items ?? [];+ return buildTaskListPrompt({+ defaultAssigneeAgentId,+ tasks,+ total: viewedList?.total || tasks.length,+ });+ }++ const task = taskState.taskDetailMap[viewedTask.taskId];+ if (task) return buildTaskDetailPrompt({ defaultAssigneeAgentId, task });+};++/**+ * Static instructions for a local hetero agent: its own system context, the+ * `/goal` instructions (it plans through `lh` in the same run, not a tool) and+ * the Tasks page it was asked from.+ */+export const withHeteroContext = (+ agentSystemContext: string | undefined,+ message: string,+ context: Pick<ConversationContext, 'defaultTaskAssigneeAgentId' | 'viewedTask'>,+): string | undefined => {+ const viewedTaskPrompt = buildViewedTaskPrompt(context);+ const systemContext = viewedTaskPrompt+ ? [agentSystemContext?.trim(), viewedTaskPrompt].filter(Boolean).join('\n\n')+ : agentSystemContext;++ return withConversationGoalPrompt(systemContext, message);+};