🤯 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(agent-signal,types,prompts,server): should handle skill intent directly when hintIsSkill on, and reroute the source signal, or otherwise it will be hard to have skill triggers (#14526)
Nekoc760171f493f
diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.tsindex 3f691e0a1d2..a952ae744eb 100644--- a/packages/agent-signal/src/source/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -136,9 +136,10 @@ export interface AgentSignalSourcePayloadMap {};[AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete]: {agentId?: string;+ assistantMessageId?: string;operationId: string;serializedContext?: string;- status?: string;+ status?: 'cancelled' | 'completed' | 'failed';threadId?: string;topicId?: string;};diff --git a/packages/prompts/src/prompts/agentSkillManager/decision.test.ts b/packages/prompts/src/prompts/agentSkillManager/decision.test.tsindex 8026b086e05..0133b84ce25 100644--- a/packages/prompts/src/prompts/agentSkillManager/decision.test.ts+++ b/packages/prompts/src/prompts/agentSkillManager/decision.test.ts@@ -20,6 +20,12 @@ describe('agentSkillManager decision prompt', () => {expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('targetSkillRefs');expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('agent document ids');expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('not backing documents.id values');+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain(+ 'hintIsSkill:true as strong evidence, not automatic authorization',+ );+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain(+ 'Do not force refine or consolidate without targetSkillRefs',+ );expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).not.toContain('targetSkillIds');expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).not.toContain('managed skill package names');});diff --git a/packages/prompts/src/prompts/agentSkillManager/decision.ts b/packages/prompts/src/prompts/agentSkillManager/decision.tsindex 90c763d8b1d..fc9831563e8 100644--- a/packages/prompts/src/prompts/agentSkillManager/decision.ts+++ b/packages/prompts/src/prompts/agentSkillManager/decision.ts@@ -62,6 +62,10 @@ Rules:- No-op for generic praise, style preferences, memory-like facts, or insufficient context.- Reject when the user asked for document-only behavior, forbids skill conversion, or same-turn document evidence makes skill mutation unsafe.- Use read-only tools to inspect same-turn document outcomes before guessing from document names or content shape.+- Treat same-turn document outcomes with hintIsSkill:true as strong evidence, not automatic authorization.+- For hinted ordinary documents, prefer create/register candidates unless exactly one existing managed skill is the target.+- Use refine only with one resolved targetSkillRefs entry; use consolidate only with multiple resolved targetSkillRefs entries.+- Do not force refine or consolidate without targetSkillRefs.- Do not infer skill intent from a filename, title, or SKILL.md-shaped content alone.- Do not author SKILL.md content, YAML frontmatter, or file-operation patches in this decision.- Prefer patch/refine over duplicate creation.diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.tsindex 2988049093b..235890e16df 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts@@ -63,6 +63,7 @@ type DomainSignalInput<TTarget extends SupportedTask4DomainTarget> = {signalId: string;sourceId: string;target: TTarget;+ trigger?: string;};function createDomainSignal(input: DomainSignalInput<'memory'>): SignalFeedbackDomainMemory;@@ -102,6 +103,7 @@ function createDomainSignal(reason: 'test-domain-signal',satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'memory',+ trigger: input.trigger,},signalId: input.signalId,signalType: 'signal.feedback.domain.memory',@@ -124,6 +126,7 @@ function createDomainSignal(reason: 'test-domain-signal',satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'none',+ trigger: input.trigger,},signalId: input.signalId,signalType: 'signal.feedback.domain.none',@@ -146,6 +149,7 @@ function createDomainSignal(reason: 'test-domain-signal',satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'prompt',+ trigger: input.trigger,},signalId: input.signalId,signalType: 'signal.feedback.domain.prompt',@@ -169,6 +173,7 @@ function createDomainSignal(skillIntentReason: input.skillIntentReason,skillRoute: input.skillRoute,target: 'skill',+ trigger: input.trigger,},signalId: input.signalId,signalType: 'signal.feedback.domain.skill',@@ -326,16 +331,15 @@ describe('feedbackActionPlanner', () => {it('plans skill-management actions for skill domain signals', async () => {const handler = createFeedbackActionPlannerSignalHandler();- const skillResult = await handler.handle(- createDomainSignal({- message: 'This successful workflow should become a reusable skill.',- messageId: 'msg_2',- signalId: 'sig_2',- sourceId: 'source_2',- target: 'skill',- }),- context,- );+ const signal = createDomainSignal({+ message: 'This successful workflow should become a reusable skill.',+ messageId: 'msg_2',+ signalId: 'sig_2',+ sourceId: 'source_2',+ target: 'skill',+ trigger: 'client.runtime.complete',+ });+ const skillResult = await handler.handle(signal, context);expect(skillResult).toEqual(expect.objectContaining({@@ -355,6 +359,157 @@ describe('feedbackActionPlanner', () => {);});+ /**+ * @example+ * User-stage direct skill intent is saved as a deferred candidate until completion evidence arrives.+ */+ it('defers direct skill decisions from normal user-message sources', async () => {+ const store = createStore();+ const procedure = createProcedurePolicyOptions({+ now: () => 123,+ policyStateStore: store,+ ttlSeconds: 3600,+ });+ const writeCandidate = vi.spyOn(procedure.procedureState.skillCandidates!, 'write');+ const skillActions = { prepare: vi.fn() };+ const handler = createFeedbackActionPlannerSignalHandler({+ actionServices: {+ memoryActions: { prepare: vi.fn() },+ skillActions: skillActions as never,+ },+ procedure: {+ now: () => 123,+ procedureState: procedure.procedureState,+ },+ });+ const signal = createDomainSignal({+ message: 'Nice work. Can we keep this workflow?',+ messageId: 'msg_skill_defer',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_defer',+ skillActionIntent: 'create',+ skillIntentConfidence: 0.88,+ skillIntentExplicitness: 'implicit_strong_learning',+ skillIntentReason: 'User asked to preserve this workflow.',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_defer',+ target: 'skill',+ trigger: 'client.runtime.start',+ });++ const result = await handler.handle(signal, context);++ expect(result).toEqual({+ concluded: { reason: 'skill mutation deferred until client.runtime.complete' },+ status: 'conclude',+ });+ expect(skillActions.prepare).not.toHaveBeenCalled();+ expect(writeCandidate).toHaveBeenCalledWith(+ expect.objectContaining({+ actionIntent: 'create',+ confidence: 0.88,+ createdAt: 123,+ explicitness: 'implicit_strong_learning',+ feedbackMessageId: 'msg_skill_defer',+ reason: 'User asked to preserve this workflow.',+ route: 'direct_decision',+ scopeKey: 'topic:thread_1',+ sourceId: 'source_skill_defer',+ }),+ );+ await expect(+ procedure.procedureState.skillCandidates!.read({+ scopeKey: 'topic:thread_1',+ sourceId: 'source_skill_defer',+ }),+ ).resolves.toEqual(+ expect.objectContaining({+ feedbackMessageId: 'msg_skill_defer',+ route: 'direct_decision',+ }),+ );+ });++ /**+ * @example+ * Completion-triggered direct skill intent is allowed to mutate skills.+ */+ it('dispatches direct skill decisions from completion-triggered user feedback', async () => {+ const action = {+ actionId: 'action_1',+ actionType: 'action.skill-management.handle' as const,+ payload: {},+ };+ const skillActions = {+ prepare: vi.fn(() => ({ action, reason: 'completion evidence', risk: 'low' as const })),+ };+ const handler = createFeedbackActionPlannerSignalHandler({+ actionServices: {+ memoryActions: { prepare: vi.fn() },+ skillActions: skillActions as never,+ },+ markerReader: { shouldSuppress: vi.fn().mockResolvedValue(false) },+ });+ const signal = createDomainSignal({+ message: 'Nice work. Can we keep this workflow?',+ messageId: 'msg_skill_complete',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_complete',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'implicit_strong_learning',+ skillIntentReason: 'Completion has final evidence.',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_complete',+ target: 'skill',+ trigger: 'client.runtime.complete',+ });++ const result = await handler.handle(signal, context);++ expect(result).toEqual({ actions: [action], status: 'dispatch' });+ expect(skillActions.prepare).toHaveBeenCalledWith(signal);+ });++ /**+ * @example+ * Server-side user-message sources have no client completion event to resume deferred mutations.+ */+ it('dispatches direct skill decisions from server-side user feedback', async () => {+ const action = {+ actionId: 'action_server',+ actionType: 'action.skill-management.handle' as const,+ payload: {},+ };+ const skillActions = {+ prepare: vi.fn(() => ({ action, reason: 'server-side feedback', risk: 'low' as const })),+ };+ const handler = createFeedbackActionPlannerSignalHandler({+ actionServices: {+ memoryActions: { prepare: vi.fn() },+ skillActions: skillActions as never,+ },+ markerReader: { shouldSuppress: vi.fn().mockResolvedValue(false) },+ });+ const signal = createDomainSignal({+ message: '把刚才的 YouTube 评论区分析流程保存为 skill。',+ messageId: 'msg_skill_server',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_server',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'explicit_action',+ skillIntentReason: 'Server-side agent has no client completion event.',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_server',+ target: 'skill',+ trigger: 'chat',+ });++ const result = await handler.handle(signal, context);++ expect(result).toEqual({ actions: [action], status: 'dispatch' });+ expect(skillActions.prepare).toHaveBeenCalledWith(signal);+ });+it('does not directly handle satisfied skill domain signals', async () => {const handler = createFeedbackActionPlannerSignalHandler();const result = await handler.handle(@@ -378,21 +533,20 @@ describe('feedbackActionPlanner', () => {*/it('plans direct skill-management actions for satisfied explicit skill intent', async () => {const handler = createFeedbackActionPlannerSignalHandler();- const result = await handler.handle(- createDomainSignal({- message:- 'The SKILL.md draft from the chat agent is usable. Convert it into a real skills/bundle.',- messageId: 'msg_skill_convert',- satisfactionResult: 'satisfied',- signalId: 'sig_skill_convert',- skillActionIntent: 'create',- skillIntentExplicitness: 'explicit_action',- skillRoute: 'direct_decision',- sourceId: 'source_skill_convert',- target: 'skill',- }),- context,- );+ const signal = createDomainSignal({+ message:+ 'The SKILL.md draft from the chat agent is usable. Convert it into a real skills/bundle.',+ messageId: 'msg_skill_convert',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_convert',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'explicit_action',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_convert',+ target: 'skill',+ trigger: 'client.runtime.complete',+ });+ const result = await handler.handle(signal, context);expect(result).toEqual(expect.objectContaining({@@ -416,20 +570,19 @@ describe('feedbackActionPlanner', () => {*/it('plans direct skill-management actions for implicit strong learning intent', async () => {const handler = createFeedbackActionPlannerSignalHandler();- const result = await handler.handle(- createDomainSignal({- message: 'For future database migration reviews, follow the checklist from earlier.',- messageId: 'msg_skill_implicit',- satisfactionResult: 'satisfied',- signalId: 'sig_skill_implicit',- skillActionIntent: 'create',- skillIntentExplicitness: 'implicit_strong_learning',- skillRoute: 'direct_decision',- sourceId: 'source_skill_implicit',- target: 'skill',- }),- context,- );+ const signal = createDomainSignal({+ message: 'For future database migration reviews, follow the checklist from earlier.',+ messageId: 'msg_skill_implicit',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_implicit',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'implicit_strong_learning',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_implicit',+ target: 'skill',+ trigger: 'client.runtime.complete',+ });+ const result = await handler.handle(signal, context);expect(result).toEqual(expect.objectContaining({diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.tsindex 85b33d4ada3..1c18ddba094 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts@@ -484,8 +484,9 @@ describe('feedbackDomainJudge', () => {expect.objectContaining({payload: expect.objectContaining({skillActionIntent: 'maintain',+ skillIntentConfidence: 0.35,skillIntentExplicitness: 'weak_positive',- skillIntentReason: 'generic positive feedback without durable future-use instruction',+ skillIntentReason: 'insufficient-evidence',skillRoute: 'accumulate',target: 'skill',}),diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillCandidate.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillCandidate.test.tsnew file mode 100644index 00000000000..ace6d2863e9--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillCandidate.test.ts@@ -0,0 +1,217 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { createProcedureStateService } from '@/server/services/agentSignal/services/procedureStateService';+import type { AgentSignalPolicyStateStore } from '@/server/services/agentSignal/store/types';++import { readDeferredSkillCandidate, writeDeferredSkillCandidate } from '../skillCandidate';++const createStore = (): AgentSignalPolicyStateStore => {+ const state = new Map<string, Record<string, string>>();++ return {+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),+ writePolicyState: async (policyId, scopeKey, data) => {+ const key = `${policyId}:${scopeKey}`;+ state.set(key, { ...state.get(key), ...data });+ },+ };+};++describe('deferred skill candidates', () => {+ /**+ * @example+ * User-stage direct skill intent persists as candidate state for completion-stage decisions.+ */+ it('writes and reads one deferred skill candidate by source id', async () => {+ const store = createStore();++ await writeDeferredSkillCandidate(store, {+ candidate: {+ actionIntent: 'create',+ confidence: 0.86,+ createdAt: 1000,+ explicitness: 'implicit_strong_learning',+ feedbackMessageId: 'msg_1',+ reason: 'future workflow reuse',+ route: 'direct_decision',+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ },+ scopeKey: 'topic:topic_1',+ ttlSeconds: 60,+ });++ await expect(+ readDeferredSkillCandidate(store, {+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ }),+ ).resolves.toEqual({+ actionIntent: 'create',+ confidence: 0.86,+ createdAt: 1000,+ explicitness: 'implicit_strong_learning',+ feedbackMessageId: 'msg_1',+ reason: 'future workflow reuse',+ route: 'direct_decision',+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ });+ });++ /**+ * @example+ * Corrupt candidate JSON is ignored instead of crashing policy execution.+ */+ it('returns undefined for malformed candidate JSON', async () => {+ const store = {+ readPolicyState: vi.fn().mockResolvedValue({+ 'skill-candidate:source_1': '{bad-json',+ }),+ writePolicyState: vi.fn(),+ } satisfies AgentSignalPolicyStateStore;++ await expect(+ readDeferredSkillCandidate(store, {+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ }),+ ).resolves.toBeUndefined();+ });++ /**+ * @example+ * Candidate JSON with missing required fields is ignored instead of becoming policy input.+ */+ it('returns undefined for malformed candidate objects', async () => {+ const store = {+ readPolicyState: vi.fn().mockResolvedValue({+ 'skill-candidate:source_1': JSON.stringify({ sourceId: 'source_1' }),+ }),+ writePolicyState: vi.fn(),+ } satisfies AgentSignalPolicyStateStore;++ await expect(+ readDeferredSkillCandidate(store, {+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ }),+ ).resolves.toBeUndefined();+ });++ /**+ * @example+ * Candidate payloads must match the requested source id and scope key after parsing.+ */+ it('returns undefined when parsed candidate identity does not match the read input', async () => {+ const store = {+ readPolicyState: vi.fn().mockResolvedValue({+ 'skill-candidate:source_1': JSON.stringify({+ createdAt: 1000,+ explicitness: 'explicit_action',+ feedbackMessageId: 'msg_1',+ route: 'direct_decision',+ scopeKey: 'topic:topic_2',+ sourceId: 'source_2',+ }),+ }),+ writePolicyState: vi.fn(),+ } satisfies AgentSignalPolicyStateStore;++ await expect(+ readDeferredSkillCandidate(store, {+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ }),+ ).resolves.toBeUndefined();+ });++ /**+ * @example+ * Same source ids in different runtime scopes do not read each other's candidates.+ */+ it('keeps candidates separated by scope key', async () => {+ const store = createStore();++ await writeDeferredSkillCandidate(store, {+ candidate: {+ confidence: 0.72,+ createdAt: 1000,+ explicitness: 'explicit_action',+ feedbackMessageId: 'msg_1',+ reason: 'store only in topic one',+ route: 'direct_decision',+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ },+ scopeKey: 'topic:topic_1',+ ttlSeconds: 60,+ });++ await expect(+ readDeferredSkillCandidate(store, {+ scopeKey: 'topic:topic_2',+ sourceId: 'source_1',+ }),+ ).resolves.toBeUndefined();+ });++ /**+ * @example+ * ProcedureStateService.skillCandidates.write(candidate) applies facade-owned TTL and scope.+ */+ it('wires skill candidate helpers through ProcedureStateService', async () => {+ const writePolicyState = vi.fn(async () => {});+ const store = {+ readPolicyState: vi.fn().mockResolvedValue({+ 'skill-candidate:source_1': JSON.stringify({+ confidence: 0.7,+ createdAt: 1000,+ explicitness: 'explicit_action',+ feedbackMessageId: 'msg_1',+ reason: 'facade read',+ route: 'direct_decision',+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ }),+ }),+ writePolicyState,+ } satisfies AgentSignalPolicyStateStore;+ const service = createProcedureStateService({+ policyStateStore: store,+ ttlSeconds: 90,+ });++ await service.skillCandidates.write({+ confidence: 0.7,+ createdAt: 1000,+ explicitness: 'explicit_action',+ feedbackMessageId: 'msg_1',+ reason: 'facade write',+ route: 'direct_decision',+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ });++ expect(writePolicyState).toHaveBeenCalledWith(+ 'analyze-intent:skill-candidates',+ 'topic:topic_1',+ expect.objectContaining({+ 'skill-candidate:source_1': expect.any(String),+ }),+ 90,+ );+ await expect(+ service.skillCandidates.read({+ scopeKey: 'topic:topic_1',+ sourceId: 'source_1',+ }),+ ).resolves.toEqual(+ expect.objectContaining({+ feedbackMessageId: 'msg_1',+ sourceId: 'source_1',+ }),+ );+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.tsindex 5d9346c4cf4..281a46e56b9 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.ts@@ -27,79 +27,84 @@ describe('skillIntent classifier', () => {/*** @example- * explicit artifact conversion skips the fallback model and routes to direct decision.+ * explicit artifact conversion is semantic and goes through the fallback model.*/- it('classifies explicit SKILL.md conversion as direct create intent', () => {+ it('does not hard-code explicit SKILL.md conversion with deterministic rules', () => {const result = classifySkillIntentByRules({message:'The SKILL.md draft from the chat agent is usable. Convert it into a real skills/bundle.',serializedContext: 'topic=repo-review',});- expect(result).toEqual({- actionIntent: 'create',- confidence: 0.92,- explicitness: 'explicit_action',- reason: 'explicit skill artifact conversion request',- route: 'direct_decision',- });+ expect(result).toBeUndefined();});/*** @example- * named skill edits are explicit refine requests.+ * named skill edits are semantic and go through the fallback model.*/- it('classifies named skill edit requests as direct refine intent', () => {+ it('does not hard-code named skill edit requests with deterministic rules', () => {const result = classifySkillIntentByRules({message: 'Update review-skill to include security checks and rollback checks.',serializedContext: 'topic=repo-review',});- expect(result).toEqual({- actionIntent: 'refine',- confidence: 0.9,- explicitness: 'explicit_action',- reason: 'explicit named skill refinement request',- route: 'direct_decision',- });+ expect(result).toBeUndefined();});/*** @example- * generic praise is weak positive and remains accumulator-only.+ * natural-language praise and durable reuse wording goes through semantic fallback.*/- it('classifies generic helpful feedback as weak positive accumulation', () => {- const result = classifySkillIntentByRules({- message: 'This explanation was helpful.',- serializedContext: 'topic=debugging-help',+ it('does not hard-code natural-language durable reuse with deterministic rules', async () => {+ const fallback = {+ classify: vi.fn().mockResolvedValue({+ actionIntent: 'create',+ confidence: 0.86,+ explicitness: 'implicit_strong_learning',+ reason: 'semantic classifier recognized durable procedure retention intent',+ route: 'direct_decision',+ }),+ };++ const ruleResult = classifySkillIntentByRules({+ message: 'Nice work. Can we keep this workflow?',+ serializedContext: 'topic=youtube-comment-workflow',});+ const result = await classifySkillIntent(+ {+ message: 'Nice work. Can we keep this workflow?',+ serializedContext: 'topic=youtube-comment-workflow',+ },+ { fallback },+ );+ expect(ruleResult).toBeUndefined();+ expect(fallback.classify).toHaveBeenCalledWith({+ message: 'Nice work. Can we keep this workflow?',+ serializedContext: 'topic=youtube-comment-workflow',+ topicLabel: 'youtube-comment-workflow',+ });expect(result).toEqual({- actionIntent: 'maintain',- confidence: 0.78,- explicitness: 'weak_positive',- reason: 'generic positive feedback without durable future-use instruction',- route: 'accumulate',+ actionIntent: 'create',+ confidence: 0.86,+ explicitness: 'implicit_strong_learning',+ reason: 'semantic classifier recognized durable procedure retention intent',+ route: 'direct_decision',});});/*** @example- * negative future preference is durable, but not skill-management.+ * negative future preference is semantic and goes through the fallback model.*/- it('classifies negative future preference as non-skill preference', () => {+ it('does not hard-code negative future preference with deterministic rules', () => {const result = classifySkillIntentByRules({message: 'This approach is not suitable. Please do not do this again.',serializedContext: 'topic=database-migration',});- expect(result).toEqual({- actionIntent: 'noop',- confidence: 0.82,- explicitness: 'non_skill_preference',- reason: 'negative future preference belongs outside skill management',- route: 'non_skill',- });+ expect(result).toBeUndefined();});/**@@ -205,7 +210,58 @@ describe('skillIntent classifier', () => {},confidence: 0.35,explicitness: 'weak_positive',- reason: 'classifier-fallback-failed',+ reason: 'insufficient-evidence',+ route: 'accumulate',+ });+ expect(diagnostics.recordMalformedOutput).toHaveBeenCalledWith({+ error: expect.any(Error),+ reason: 'malformed skill-intent classifier output',+ scopeKey: 'topic:thread_1',+ sourceId: 'source_1',+ stage: 'skill-intent',+ });+ });++ /**+ * @example+ * weak-positive classifier output cannot directly mutate skills even if the model asks for it.+ */+ it('falls back safely when fallback classifier returns an inconsistent direct-decision route', async () => {+ const diagnostics = {+ recordMalformedOutput: vi.fn().mockResolvedValue(undefined),+ };+ const fallback = {+ classify: vi.fn().mockResolvedValue({+ actionIntent: 'create',+ confidence: 0.9,+ explicitness: 'weak_positive',+ reason: 'model mixed weak evidence with direct mutation',+ route: 'direct_decision',+ }),+ };++ const result = await classifySkillIntent(+ {+ message: 'Nice work.',+ serializedContext: 'topic=youtube-comment-workflow',+ },+ {+ diagnostics,+ fallback,+ scopeKey: 'topic:thread_1',+ sourceId: 'source_1',+ },+ );++ expect(result).toEqual({+ actionIntent: 'maintain',+ classifierError: {+ message: expect.stringContaining('Weak-positive skill intent must accumulate'),+ name: 'ZodError',+ },+ confidence: 0.35,+ explicitness: 'weak_positive',+ reason: 'insufficient-evidence',route: 'accumulate',});expect(diagnostics.recordMalformedOutput).toHaveBeenCalledWith({diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.tsindex 34e6270d100..1e810d53f67 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts@@ -11,6 +11,7 @@ import {defineSkillManagementActionHandler,handleSkillManagementSignal,isAgentDocumentRelatedObject,+ readAgentSignalHintIsSkill,runSkillDecisionAgentRuntime,} from '../skillManagement';@@ -226,6 +227,7 @@ describe('defineSkillManagementActionHandler', () => {listSameTurnDocumentOutcomes: vi.fn().mockResolvedValue([{agentDocumentId: 'agent_doc_1',+ hintIsSkill: true,relation: 'created',summary: 'Agent documents created a document.',},@@ -263,6 +265,12 @@ describe('defineSkillManagementActionHandler', () => {topicId: 'topic_1',});expect(tools.readDocument).toHaveBeenCalledWith({ agentDocumentId: 'agent_doc_1' });+ expect(chat.mock.calls[1]?.[0].messages).toContainEqual(+ expect.objectContaining({+ content: expect.stringContaining('"hintIsSkill":true'),+ role: 'tool',+ }),+ );expect(result).toMatchObject({action: 'reject',documentRefs: ['doc_1'],@@ -270,6 +278,109 @@ describe('defineSkillManagementActionHandler', () => {});});+ /**+ * @example+ * Only explicit boolean metadata becomes same-turn hint evidence.+ */+ it('parses hintIsSkill only from explicit boolean agent-signal metadata', () => {+ expect(readAgentSignalHintIsSkill({ agentSignal: { hintIsSkill: true } })).toBe(true);+ expect(readAgentSignalHintIsSkill({ agentSignal: { hintIsSkill: false } })).toBe(false);+ expect(readAgentSignalHintIsSkill({ agentSignal: { hintIsSkill: 'true' } })).toBeUndefined();+ expect(readAgentSignalHintIsSkill({ agentSignal: null })).toBeUndefined();+ expect(readAgentSignalHintIsSkill(undefined)).toBeUndefined();+ });++ /**+ * @example+ * Negative or missing same-turn hints remain evidence only; they do not force mutation actions.+ */+ it('does not force refine or consolidate from hintIsSkill false or missing document snapshots', async () => {+ const response = () =>+ new Response(+ new ReadableStream({+ start(controller) {+ controller.close();+ },+ }),+ );+ const chat = vi+ .fn()+ .mockImplementationOnce(async (_payload, options) => {+ await options.callback.onToolsCalling({+ toolsCalling: [+ {+ function: {+ arguments: '{"messageId":"msg_1","scopeKey":"topic:topic_1"}',+ name: 'agent-signal-skill-decision____listSameTurnDocumentOutcomes',+ },+ id: 'call_list_outcomes',+ type: 'function',+ },+ ],+ });+ return response();+ })+ .mockImplementationOnce(async (_payload, options) => {+ await options.callback.onToolsCalling({+ toolsCalling: [+ {+ function: {+ arguments:+ '{"action":"noop","confidence":0.7,"documentRefs":[],"reason":"Negative or missing hints are not enough to mutate a skill.","requiredReads":[],"targetSkillRefs":[]}',+ name: 'agent-signal-skill-decision____submitDecision',+ },+ id: 'call_submit_decision',+ type: 'function',+ },+ ],+ });+ return response();+ });+ const tools = {+ listCandidateDocuments: vi.fn(),+ listSameTurnDocumentOutcomes: vi.fn().mockResolvedValue([+ {+ agentDocumentId: 'agent_doc_false',+ hintIsSkill: false,+ relation: 'created',+ summary: 'Document outcome explicitly says this is not a skill.',+ },+ {+ agentDocumentId: 'agent_doc_missing_snapshot',+ relation: 'created',+ summary: 'Document snapshot is missing metadata.',+ },+ ]),+ readDocument: vi.fn(),+ };++ const result = await runSkillDecisionAgentRuntime({+ model: 'test-model',+ modelRuntime: { chat },+ payload: {+ agentId: 'agent_1',+ feedbackMessage: 'Keep the result around if useful.',+ messageId: 'msg_1',+ topicId: 'topic_1',+ },+ tools,+ });++ expect(chat.mock.calls[1]?.[0].messages).toContainEqual(+ expect.objectContaining({+ content: expect.stringContaining('"hintIsSkill":false'),+ role: 'tool',+ }),+ );+ expect(tools.readDocument).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ action: 'noop',+ reason: 'Negative or missing hints are not enough to mutate a skill.',+ });+ expect(result.action).not.toBe('refine');+ expect(result.action).not.toBe('consolidate');+ });+/*** @example* Same-turn document receipts emitted by lobe-agent-documents use the agent document binding id.@@ -454,6 +565,104 @@ describe('defineSkillManagementActionHandler', () => {);});+ /**+ * @example+ * Completion-stage skill decisions receive user-stage deferred skill-candidate evidence.+ */+ it('passes deferred skill candidate evidence to the decision runtime on completion-triggered feedback', async () => {+ skillDecisionRunner.mockResolvedValue({+ action: 'create',+ confidence: 0.88,+ documentRefs: [],+ reason: 'Completion confirmed hinted workflow document.',+ requiredReads: [],+ targetSkillRefs: [],+ });+ skillCreateRunner.mockResolvedValue({+ bodyMarkdown: '# YouTube Comment Fetch Workflow',+ name: 'youtube-comment-fetch-workflow',+ reason: 'created reusable workflow',+ title: 'YouTube Comment Fetch Workflow',+ });+ const readCandidate = vi.fn(async (input: { scopeKey: string; sourceId: string }) => {+ if (input.sourceId !== 'msg_1') return undefined;++ return {+ actionIntent: 'create' as const,+ confidence: 0.86,+ createdAt: 1000,+ explicitness: 'implicit_strong_learning' as const,+ feedbackMessageId: 'msg_1',+ reason: 'User asked to preserve this workflow.',+ route: 'direct_decision' as const,+ scopeKey: 'topic:topic-1',+ sourceId: 'msg_1',+ };+ });+ const handler = defineSkillManagementActionHandler({+ db: {} as never,+ procedureState: {+ skillCandidates: { read: readCandidate, write: vi.fn() },+ },+ selfIterationEnabled: true,+ skillCreateRunner,+ skillDecisionRunner,+ userId: 'user_1',+ });++ await handler.handle(+ {+ actionId: 'act_skill_candidate',+ actionType: 'action.skill-management.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ evidence: [{ cue: 'completion', excerpt: 'assistant completed' }],+ feedbackHint: 'satisfied',+ idempotencyKey: 'source_1:skill:msg_1',+ message: 'Nice work. Can we keep this workflow?',+ messageId: 'msg_1',+ reason: 'completion-triggered skill feedback',+ serializedContext: '{"surface":"chat"}',+ topicId: 'topic_1',+ },+ signal: {+ signalId: 'sig_1',+ signalType: 'signal.feedback.domain.skill',+ },+ source: {+ payload: {+ message: 'Nice work. Can we keep this workflow?',+ messageId: 'msg_1',+ trigger: 'client.runtime.complete',+ },+ sourceId: 'assistant_1:completion:msg_1',+ sourceType: 'agent.user.message',+ } as never,+ timestamp: 1,+ },+ context,+ );++ expect(readCandidate).toHaveBeenCalledWith({+ scopeKey: 'topic:topic-1',+ sourceId: 'msg_1',+ });+ expect(skillDecisionRunner).toHaveBeenCalledWith(+ expect.objectContaining({+ evidence: expect.arrayContaining([+ expect.objectContaining({+ cue: 'completion',+ }),+ expect.objectContaining({+ cue: 'deferred_skill_candidate',+ excerpt: expect.stringContaining('User asked to preserve this workflow.'),+ }),+ ]),+ }),+ );+ });+/*** @example* Replayed action keys are skipped without running the document writer.diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 6c9d0dbe30e..79f67d6d3aa 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -56,10 +56,12 @@ import type {import type { RuntimeProcessorContext } from '../../../runtime/context';import { defineActionHandler } from '../../../runtime/middleware';import { createSkillManagementService } from '../../../services/maintenance/skill';+import type { ProcedureStateService } from '../../../services/types';import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';import type { ActionSkillManagementHandle, AgentSignalFeedbackEvidence } from '../../types';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';+import type { DeferredSkillCandidate } from '../skillCandidate';export interface SkillManagementCandidateSkill {id: string;@@ -141,6 +143,8 @@ export interface SkillManagementActionInput {export interface SkillManagementActionHandlerOptions {db: LobeChatDatabase;+ /** Optional procedure state used to read user-stage skill candidates. */+ procedureState?: Pick<ProcedureStateService, 'skillCandidates'>;selfIterationEnabled: boolean;skillCandidateSkillsFactory?: (input: {agentId: string;@@ -155,6 +159,7 @@ export interface SkillManagementActionHandlerOptions {export interface SkillDecisionDocumentOutcome {agentDocumentId: string;+ hintIsSkill?: boolean;relation?: string;summary?: string;}@@ -171,6 +176,7 @@ export interface SkillDecisionDocumentSnapshot {content?: string;documentId?: string;filename?: string;+ metadata?: Record<string, unknown>;title?: string;}@@ -204,6 +210,71 @@ export interface SkillDecisionToolset {export const isAgentDocumentRelatedObject = (object: { objectType: string }) =>object.objectType === 'agent-document';+/**+ * Reads the agent-signal skill hint from an agent-document snapshot.+ *+ * Use when:+ * - Same-turn document evidence may include document creation intent.+ * - Decision agents need a high-context hint without treating malformed metadata as evidence.+ *+ * Expects:+ * - Metadata may be absent, malformed, or intentionally set to false.+ *+ * Returns:+ * - `true` or `false` only when the metadata explicitly stores a boolean hint.+ * - `undefined` when the hint is absent or malformed.+ */+export const readAgentSignalHintIsSkill = (metadata: unknown): boolean | undefined => {+ if (!metadata || typeof metadata !== 'object') return undefined;++ const agentSignal = (metadata as Record<string, unknown>).agentSignal;+ if (!agentSignal || typeof agentSignal !== 'object') return undefined;++ const hintIsSkill = (agentSignal as Record<string, unknown>).hintIsSkill;+ return typeof hintIsSkill === 'boolean' ? hintIsSkill : undefined;+};++const createDeferredSkillCandidateEvidence = (+ candidate: DeferredSkillCandidate | undefined,+): AgentSignalFeedbackEvidence[] => {+ if (!candidate) return [];++ return [+ {+ cue: 'deferred_skill_candidate',+ excerpt: `${candidate.explicitness}/${candidate.route}/${candidate.actionIntent ?? 'none'}: ${+ candidate.reason ?? 'deferred skill intent'+ }`,+ },+ ];+};++const readDeferredSkillCandidateForAction = async (+ options: SkillManagementActionHandlerOptions,+ action: ActionSkillManagementHandle,+ context: RuntimeProcessorContext,+) => {+ const reader = options.procedureState?.skillCandidates?.read;+ if (!reader) return undefined;++ const messageId = action.payload.messageId;+ if (messageId) {+ const candidate = await reader({+ scopeKey: context.scopeKey,+ sourceId: messageId,+ });+ if (candidate) return candidate;+ }++ const sourceId = action.source?.sourceId;+ if (!sourceId || sourceId === messageId) return undefined;++ return reader({+ scopeKey: context.scopeKey,+ sourceId,+ });+};+export interface SkillManagementAgentModelConfig {model: string;provider: string;@@ -905,8 +976,7 @@ const createDefaultSkillDecisionToolset = (if (!scopeKey) return [];const snapshot = await inspector.inspectScope(scopeKey);-- return snapshot.receipts+ const outcomes = snapshot.receipts.filter((receipt) => receipt.domainKey.startsWith('document:')).filter((receipt) => !messageId || receipt.messageId === messageId).flatMap((receipt) =>@@ -916,6 +986,20 @@ const createDefaultSkillDecisionToolset = (summary: receipt.summary,})),);++ return Promise.all(+ outcomes.map(async (outcome) => {+ const document = await agentDocumentsService.getDocumentSnapshotById(+ outcome.agentDocumentId,+ );+ const hintIsSkill = readAgentSignalHintIsSkill(document?.metadata);++ return {+ ...outcome,+ ...(hintIsSkill === undefined ? {} : { hintIsSkill }),+ };+ }),+ );},readDocument: async ({ agentDocumentId }) => {const snapshot = await agentDocumentsService.getDocumentSnapshotById(agentDocumentId);@@ -926,6 +1010,7 @@ const createDefaultSkillDecisionToolset = (content: snapshot.content,documentId: snapshot.documentId,filename: snapshot.filename,+ metadata: snapshot.metadata ?? undefined,title: snapshot.title,};},@@ -1607,10 +1692,15 @@ export const handleSkillManagementAction = async (}const candidateSkills = await resolveSkillDecisionCandidates(options, action.payload.agentId);+ const deferredCandidate = await readDeferredSkillCandidateForAction(options, action, context);+ const evidence = [+ ...(action.payload.evidence ?? []),+ ...createDeferredSkillCandidateEvidence(deferredCandidate),+ ];const runnerInput = {agentId: action.payload.agentId,...(candidateSkills.length > 0 ? { candidateSkills } : {}),- evidence: action.payload.evidence,+ ...(evidence.length > 0 ? { evidence } : {}),feedbackHint: action.payload.feedbackHint,message,messageId: action.payload.messageId,@@ -1623,7 +1713,7 @@ export const handleSkillManagementAction = async (payload: {agentId: action.payload.agentId,...(candidateSkills.length > 0 ? { candidateSkills } : {}),- evidence: action.payload.evidence,+ ...(evidence.length > 0 ? { evidence } : {}),feedbackMessage: message,messageId: action.payload.messageId,scopeKey: context.scopeKey,diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.tsindex 669cdf7141c..9727a09ddb4 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts@@ -2,6 +2,7 @@ import type {RuntimeDispatchProcessorResult,RuntimeProcessorResult,} from '@lobechat/agent-signal';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import type {AgentSignalProcedureMarker,@@ -31,6 +32,7 @@ import { createDefaultActionServices } from '../../services/actionServices';import type { ProcedureMarkerSuppressInput, ProcedureStateService } from '../../services/types';import type { SignalFeedbackDomainMemory } from '../types';import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../types';+import type { DeferredSkillCandidate } from './skillCandidate';/*** Weak positive skill feedback needs repeated observations before the accumulator emits.@@ -108,6 +110,29 @@ const isAccumulatingSkillSignal = ();};+const shouldDeferSkillMutationUntilClientCompletion = (signal: FeedbackDomainSignal) => {+ return signal.payload.trigger === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart;+};++const createDeferredSkillCandidate = (+ signal: NonSatisfiedSkillActionServiceSignal,+ context: RuntimeProcessorContext,+): DeferredSkillCandidate => ({+ ...(signal.payload.skillActionIntent ? { actionIntent: signal.payload.skillActionIntent } : {}),+ ...(typeof signal.payload.skillIntentConfidence === 'number'+ ? { confidence: signal.payload.skillIntentConfidence }+ : { confidence: signal.payload.confidence }),+ createdAt: context.now(),+ explicitness: signal.payload.skillIntentExplicitness ?? 'weak_positive',+ feedbackMessageId: signal.payload.messageId,+ ...(signal.payload.skillIntentReason || signal.payload.reason+ ? { reason: signal.payload.skillIntentReason ?? signal.payload.reason }+ : {}),+ route: signal.payload.skillRoute ?? 'accumulate',+ scopeKey: context.scopeKey,+ sourceId: signal.source?.sourceId ?? signal.signalId,+});+const createPlannerProcedureState = (options: FeedbackActionPlannerOptions,): ProcedureProcessorStateService | undefined => {@@ -323,6 +348,17 @@ export const createFeedbackActionPlannerSignalHandler = (}if (isDirectSkillDecisionSignal(signal)) {+ if (shouldDeferSkillMutationUntilClientCompletion(signal)) {+ await options.procedure?.procedureState?.skillCandidates?.write(+ createDeferredSkillCandidate(signal, procedureContext),+ );++ return {+ concluded: { reason: 'skill mutation deferred until client.runtime.complete' },+ status: 'conclude',+ };+ }+const plan = actionServices.skillActions.prepare(signal);return {diff --git a/src/server/services/agentSignal/policies/analyzeIntent/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/index.tsindex 84f20113516..100845d5061 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/index.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/index.ts@@ -79,7 +79,13 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOptiprocedure: options.procedure,}),...(options.skillManagement- ? [defineSkillManagementActionHandler(options.skillManagement)]+ ? [+ defineSkillManagementActionHandler({+ ...options.skillManagement,+ procedureState:+ options.skillManagement.procedureState ?? options.procedure?.procedureState,+ }),+ ]: []),...(options.userMemory ? [defineUserMemoryActionHandler(options.userMemory)] : []),]);diff --git a/src/server/services/agentSignal/policies/analyzeIntent/skillCandidate.ts b/src/server/services/agentSignal/policies/analyzeIntent/skillCandidate.tsnew file mode 100644index 00000000000..df5019b221f--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/skillCandidate.ts@@ -0,0 +1,119 @@+import { z } from 'zod';++import type { AgentSignalPolicyStateStore } from '../../store/types';+import type {+ AgentSignalSkillActionIntent,+ AgentSignalSkillIntentExplicitness,+ AgentSignalSkillIntentRoute,+} from '../types';++const POLICY_ID = 'analyze-intent:skill-candidates';++const DeferredSkillCandidateSchema = z.object({+ actionIntent: z.enum(['create', 'refine', 'consolidate', 'maintain', 'noop']).optional(),+ confidence: z.number().min(0).max(1).optional(),+ createdAt: z.number(),+ explicitness: z.enum([+ 'explicit_action',+ 'implicit_strong_learning',+ 'weak_positive',+ 'non_skill_preference',+ ]),+ feedbackMessageId: z.string(),+ reason: z.string().optional(),+ route: z.enum(['direct_decision', 'accumulate', 'non_skill']),+ scopeKey: z.string(),+ sourceId: z.string(),+});++/**+ * Deferred skill candidate stored between user-message and completion analysis stages.+ */+export interface DeferredSkillCandidate {+ /** Optional skill-management action hint selected before final-turn evidence is hydrated. */+ actionIntent?: AgentSignalSkillActionIntent;+ /** Optional confidence of the user-stage skill-intent classifier, from 0 to 1. */+ confidence?: number;+ /** Time the candidate was written, in epoch milliseconds. */+ createdAt: number;+ /** Whether the user-stage feedback looked explicit, strong implicit, weak, or non-skill. */+ explicitness: AgentSignalSkillIntentExplicitness;+ /** User feedback message id that produced this candidate. */+ feedbackMessageId: string;+ /** Optional private-safe reason suitable for traces and eval assertions. */+ reason?: string;+ /** Runtime route selected before completion-stage evidence is available. */+ route: AgentSignalSkillIntentRoute;+ /** Runtime scope key where the candidate is visible. */+ scopeKey: string;+ /** Source id that produced this candidate. */+ sourceId: string;+}++const candidateField = (sourceId: string) => `skill-candidate:${sourceId}`;++/**+ * Writes one deferred skill candidate to policy state.+ *+ * Use when:+ * - User-message analysis finds skill intent before assistant completion+ * - Skill mutation should wait for final-turn evidence+ *+ * Expects:+ * - `scopeKey` matches the later completion source scope+ *+ * Returns:+ * - Resolves after the candidate field is stored+ */+export const writeDeferredSkillCandidate = async (+ store: AgentSignalPolicyStateStore,+ input: {+ candidate: DeferredSkillCandidate;+ scopeKey: string;+ ttlSeconds: number;+ },+) => {+ await store.writePolicyState(+ POLICY_ID,+ input.scopeKey,+ {+ [candidateField(input.candidate.sourceId)]: JSON.stringify(input.candidate),+ },+ input.ttlSeconds,+ );+};++/**+ * Reads one deferred skill candidate from policy state.+ *+ * Use when:+ * - Completion-stage skill management needs earlier user-stage intent+ *+ * Expects:+ * - Candidate JSON may be absent, malformed, or structurally invalid+ *+ * Returns:+ * - Parsed candidate, or `undefined` when unavailable+ */+export const readDeferredSkillCandidate = async (+ store: AgentSignalPolicyStateStore,+ input: {+ scopeKey: string;+ sourceId: string;+ },+): Promise<DeferredSkillCandidate | undefined> => {+ const state = await store.readPolicyState(POLICY_ID, input.scopeKey);+ const raw = state?.[candidateField(input.sourceId)];+ if (!raw) return undefined;++ try {+ const candidate = DeferredSkillCandidateSchema.parse(JSON.parse(raw));+ if (candidate.scopeKey !== input.scopeKey || candidate.sourceId !== input.sourceId) {+ return undefined;+ }++ return candidate;+ } catch {+ return undefined;+ }+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts b/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.tsindex e07f3ae1808..91777e85dee 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts@@ -15,8 +15,6 @@ import type {import type {AgentSignalClassifierErrorSummary,AgentSignalSkillIntentClassification,- AgentSignalSkillIntentExplicitness,- AgentSignalSkillIntentRoute,} from '../types';const log = debug('lobe-server:agent-signal:skill-intent:agent');@@ -37,6 +35,35 @@ const SkillIntentClassificationSchema = zreason: z.string(),route: z.enum(['direct_decision', 'accumulate', 'non_skill']),})+ .superRefine((value, context) => {+ if (value.explicitness === 'weak_positive' && value.route !== 'accumulate') {+ context.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Weak-positive skill intent must accumulate instead of mutating skills directly.',+ path: ['route'],+ });+ }++ if (value.explicitness === 'non_skill_preference' && value.route !== 'non_skill') {+ context.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Non-skill preferences must use the non_skill route.',+ path: ['route'],+ });+ }++ if (+ value.route === 'direct_decision' &&+ value.explicitness !== 'explicit_action' &&+ value.explicitness !== 'implicit_strong_learning'+ ) {+ context.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Direct skill decisions require explicit action or implicit strong learning.',+ path: ['explicitness'],+ });+ }+ }).transform(({ actionIntent, ...value }) => ({...value,...(actionIntent ? { actionIntent } : {}),@@ -70,32 +97,6 @@ const SkillIntentGenerateObjectSchema = {strict: true,} satisfies GenerateObjectSchema;-const generateObjectRoles = ['assistant', 'system', 'user'] as const;--const isGenerateObjectRole = (- role: string,-): role is GenerateObjectPayload['messages'][number]['role'] => {- return generateObjectRoles.includes(role as (typeof generateObjectRoles)[number]);-};--const compactText = (value: string | undefined, maxLength = 1800): string | undefined => {- if (!value) return undefined;- if (value.length <= maxLength) return value;-- return `${value.slice(0, maxLength)}...`;-};--const getTopicLabel = (serializedContext: string | undefined): string | undefined => {- if (!serializedContext) return undefined;-- const topicMatch = /topic=([^;\n<]+)/i.exec(serializedContext);- return topicMatch?.[1];-};--const readRecord = (value: unknown): Record<string, unknown> | undefined => {- return value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;-};-const redactErrorText = (value: string, maxLength = 480): string => {const redacted = value.replaceAll(/(bearer\s+)[\w.-]+/gi, '$1[redacted-token]')@@ -106,29 +107,6 @@ const redactErrorText = (value: string, maxLength = 480): string => {return redacted.length <= maxLength ? redacted : `${redacted.slice(0, maxLength)}...`;};-const readErrorMessage = (error: unknown): string => {- if (error instanceof Error) return error.message;- if (typeof error === 'string') return error;-- const record = readRecord(error);- const message = record?.message;- if (typeof message === 'string') return message;-- try {- return JSON.stringify(error);- } catch {- return String(error);- }-};--const readErrorName = (error: unknown): string | undefined => {- if (error instanceof Error) return error.name;-- const record = readRecord(error);- const name = record?.name ?? record?.errorType ?? record?.code;- return typeof name === 'string' ? name : undefined;-};-/*** Normalizes classifier fallback errors for trace-safe diagnostics.*@@ -139,152 +117,64 @@ const readErrorName = (error: unknown): string | undefined => {* - `{ name: "ProviderError", message: "invalid key: [redacted-key]" }`*/const normalizeClassifierError = (error: unknown): AgentSignalClassifierErrorSummary => {- const record = readRecord(error);- const cause = error instanceof Error ? error.cause : record?.cause;-- return {- ...(cause === undefined ? {} : { cause: redactErrorText(readErrorMessage(cause)) }),- message: redactErrorText(readErrorMessage(error)),- ...(readErrorName(error) ? { name: readErrorName(error) } : {}),+ const readRecord = (value: unknown): Record<string, unknown> | undefined => {+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;};-};+ const readMessage = (value: unknown): string => {+ if (value instanceof Error) return value.message;+ if (typeof value === 'string') return value;-const hasSkillArtifactReference = (message: string) => {- return /skill|技能|workflow|工作流|procedure|流程|checklist|检查清单/i.test(message);-};--const hasConversionVerb = (message: string) => {- return /create|convert|turn into|make into|做成|变成|变为|转换|转成|沉淀|固化|整理成/i.test(- message,- );-};+ const message = readRecord(value)?.message;+ if (typeof message === 'string') return message;-const hasRefineVerb = (message: string) => {- return /update|refine|补上|补充|加入|加上|更新|完善|改进|扩展/i.test(message);-};--const hasMergeVerb = (message: string) => {- return /merge|consolidate|combine|deduplicate|合并|整合|去重/i.test(message);-};--const hasFutureProcedureReuse = (message: string) => {- return /(?:以后|之后|下次|每次|遇到).*(?:[按照来]|沿用|复用|参考|执行)|(?:future|next time|going forward|later).*(?:follow|reuse|use|apply|run)/i.test(- message,- );-};+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+ };+ const readName = (value: unknown): string | undefined => {+ if (value instanceof Error) return value.name;-const hasGenericPositive = (message: string) => {- return /有帮助|不错|挺好|清楚|works well|helpful|good/i.test(message);-};+ const record = readRecord(value);+ const name = record?.name ?? record?.errorType ?? record?.code;+ return typeof name === 'string' ? name : undefined;+ };+ const record = readRecord(error);+ const cause = error instanceof Error ? error.cause : record?.cause;+ const name = readName(error);-const hasNegativePreference = (message: string) => {- return /不适合|别这么做|不要.*做|以后.*别|以后.*不要|not suitable|do not do this|don't do this|avoid this/i.test(- message,- );+ return {+ ...(cause === undefined ? {} : { cause: redactErrorText(readMessage(cause)) }),+ message: redactErrorText(readMessage(error)),+ ...(name ? { name } : {}),+ };};-const createClassification = (- explicitness: AgentSignalSkillIntentExplicitness,- route: AgentSignalSkillIntentRoute,- reason: string,- confidence: number,- actionIntent?: AgentSignalSkillIntentClassification['actionIntent'],- classifierError?: AgentSignalClassifierErrorSummary,-): AgentSignalSkillIntentClassification => ({- ...(actionIntent ? { actionIntent } : {}),- ...(classifierError ? { classifierError } : {}),- confidence,- explicitness,- reason,- route,-});-/**- * Classifies obvious skill intent with conservative deterministic rules.+ * Classifies skill intent only when structural evidence is decisive.** Before:- * - "Convert the SKILL.md draft into a real skills/bundle."- * - "This explanation is quite helpful."+ * - "Nice work. Can we keep this workflow?"+ * - "This workflow should become our reusable template."** After:- * - `{ explicitness: "explicit_action", route: "direct_decision" }`- * - `{ explicitness: "weak_positive", route: "accumulate" }`+ * - `undefined`+ * - `undefined`*/export const classifySkillIntentByRules = (- input: SkillIntentClassifierInput,+ _input: SkillIntentClassifierInput,): AgentSignalSkillIntentClassification | undefined => {- const message = input.message.trim();-- if (hasNegativePreference(message) && !hasSkillArtifactReference(message)) {- return createClassification(- 'non_skill_preference',- 'non_skill',- 'negative future preference belongs outside skill management',- 0.82,- 'noop',- );- }-- if (hasSkillArtifactReference(message) && hasMergeVerb(message)) {- return createClassification(- 'explicit_action',- 'direct_decision',- 'explicit skill consolidation request',- 0.9,- 'consolidate',- );- }-- if (/[\w-]+-skill/i.test(message) && hasRefineVerb(message)) {- return createClassification(- 'explicit_action',- 'direct_decision',- 'explicit named skill refinement request',- 0.9,- 'refine',- );- }-- if (hasSkillArtifactReference(message) && hasRefineVerb(message)) {- return createClassification(- 'explicit_action',- 'direct_decision',- 'explicit skill refinement request',- 0.88,- 'refine',- );- }-- if (hasSkillArtifactReference(message) && hasConversionVerb(message)) {- return createClassification(- 'explicit_action',- 'direct_decision',- 'explicit skill artifact conversion request',- 0.92,- 'create',- );- }-- if (hasGenericPositive(message) && !hasFutureProcedureReuse(message)) {- return createClassification(- 'weak_positive',- 'accumulate',- 'generic positive feedback without durable future-use instruction',- 0.78,- 'maintain',- );- }-return undefined;};/**- * Options for resolving skill intent after deterministic rules.+ * Options for resolving skill intent after structural rules and semantic fallback.*/export interface ClassifySkillIntentOptions {/** Diagnostics sink for fallback classifier failures. */diagnostics?: ClassifierDiagnosticsService;- /** Optional classifier used when deterministic rules are intentionally inconclusive. */+ /** Optional classifier used when structural rules are inconclusive. */fallback?: SkillIntentClassifierService;/** Runtime scope key for diagnostics. */scopeKey?: string;@@ -293,7 +183,7 @@ export interface ClassifySkillIntentOptions {}/**- * Resolves skill intent using rules first and a small fallback classifier second.+ * Resolves skill intent using structural rules first and a semantic classifier second.** Use when:* - Domain routing selected `skill`@@ -304,7 +194,7 @@ export interface ClassifySkillIntentOptions {* - `input.serializedContext` is compact same-turn evidence, not full documents** Returns:- * - A safe classification. Fallback failures become weak-positive accumulation.+ * - A safe classification. Semantic fallback failures become weak-positive accumulation.*/export const classifySkillIntent = async (input: SkillIntentClassifierInput,@@ -314,21 +204,24 @@ export const classifySkillIntent = async (if (ruleResult) return ruleResult;if (!options.fallback) {- return createClassification(- 'weak_positive',- 'accumulate',- 'insufficient-evidence',- 0.35,- 'maintain',- );+ return {+ actionIntent: 'maintain',+ confidence: 0.35,+ explicitness: 'weak_positive',+ reason: 'insufficient-evidence',+ route: 'accumulate',+ };}try {+ const topicLabel =+ input.topicLabel ?? /topic=([^;\n<]+)/i.exec(input.serializedContext ?? '')?.[1];+return SkillIntentClassificationSchema.parse(await options.fallback.classify({message: input.message,serializedContext: input.serializedContext,- topicLabel: input.topicLabel ?? getTopicLabel(input.serializedContext),+ topicLabel,}),);} catch (error) {@@ -342,14 +235,14 @@ export const classifySkillIntent = async (stage: 'skill-intent',});- return createClassification(- 'weak_positive',- 'accumulate',- 'classifier-fallback-failed',- 0.35,- 'maintain',+ return {+ actionIntent: 'maintain',classifierError,- );+ confidence: 0.35,+ explicitness: 'weak_positive',+ reason: 'insufficient-evidence',+ route: 'accumulate',+ };}};@@ -361,30 +254,21 @@ export interface SkillIntentClassifierAgentModelConfig {provider: string;}-const normalizeGenerateObjectMessages = (- messages: GenerateObjectPayload['messages'],-): GenerateObjectPayload['messages'] => {- return messages.map((message) => {- if (!isGenerateObjectRole(message.role)) {- throw new TypeError(`Unsupported skill-intent classifier message role: ${message.role}`);- }-- return message;- });-};-const createSkillIntentClassifierMessages = (input: SkillIntentClassifierInput,): GenerateObjectPayload['messages'] => [{content:- 'Classify skill intent for Agent Signal. Return direct_decision only for explicit skill actions or implicit strong future-use procedural learning. Return accumulate for generic praise or weak approval. Return non_skill for user preference that does not belong to skill management. Do not author skills.',+ 'Classify skill intent for Agent Signal using semantic meaning and structured evidence. Return direct_decision only for explicit skill actions or implicit strong future-use procedural learning. Return accumulate for generic praise or weak approval. Return non_skill for user preference that does not belong to skill management. Do not author skills.',role: 'system',},{content: JSON.stringify({message: input.message,- serializedContext: compactText(input.serializedContext),+ serializedContext:+ input.serializedContext && input.serializedContext.length > 1800+ ? `${input.serializedContext.slice(0, 1800)}...`+ : input.serializedContext,topicLabel: input.topicLabel,}),role: 'user',@@ -392,10 +276,10 @@ const createSkillIntentClassifierMessages = (];/**- * Model-backed skill-intent classifier for ambiguous skill-domain feedback.+ * Model-backed skill-intent classifier for skill-domain feedback.** Use when:- * - Deterministic rules cannot safely classify the skill-domain feedback+ * - Structural evidence cannot safely classify the skill-domain feedback* - A small no-document-content model decision is acceptable** Expects:@@ -427,7 +311,7 @@ export class SkillIntentClassifierAgentService implements SkillIntentClassifierS* Classifies one ambiguous skill-domain feedback message.** Use when:- * - Rule classification returned no confident decision+ * - Structural classification returned no confident decision* - Runtime policy wiring provided model dependencies** Expects:@@ -451,7 +335,7 @@ export class SkillIntentClassifierAgentService implements SkillIntentClassifierSconst result = await modelRuntime.generateObject({- messages: normalizeGenerateObjectMessages(createSkillIntentClassifierMessages(input)),+ messages: createSkillIntentClassifierMessages(input),model: this.modelConfig.model,schema: SkillIntentGenerateObjectSchema,},diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.tsindex 0949387af8c..ba48eea928c 100644--- a/src/server/services/agentSignal/policies/types.ts+++ b/src/server/services/agentSignal/policies/types.ts@@ -154,6 +154,8 @@ export interface AgentSignalPolicySignalPayloadMap {sourceHints?: AgentSignalFeedbackSourceHints;target: 'memory';topicId?: string;+ /** Source event trigger copied from the original feedback input when available. */+ trigger?: string;};[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone]: {agentId?: string;@@ -168,6 +170,8 @@ export interface AgentSignalPolicySignalPayloadMap {sourceHints?: AgentSignalFeedbackSourceHints;target: 'none';topicId?: string;+ /** Source event trigger copied from the original feedback input when available. */+ trigger?: string;};[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt]: {agentId?: string;@@ -182,6 +186,8 @@ export interface AgentSignalPolicySignalPayloadMap {sourceHints?: AgentSignalFeedbackSourceHints;target: 'prompt';topicId?: string;+ /** Source event trigger copied from the original feedback input when available. */+ trigger?: string;};[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill]: {agentId?: string;@@ -202,6 +208,8 @@ export interface AgentSignalPolicySignalPayloadMap {sourceHints?: AgentSignalFeedbackSourceHints;target: 'skill';topicId?: string;+ /** Source event trigger copied from the original feedback input when available. */+ trigger?: string;};[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction]: {agentId?: string;@@ -214,6 +222,8 @@ export interface AgentSignalPolicySignalPayloadMap {serializedContext?: string;sourceHints?: AgentSignalFeedbackSourceHints;topicId?: string;+ /** Source event trigger copied from the original feedback input when available. */+ trigger?: string;};[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.nudgeMemoryConditionMatched]: {agentId?: string;diff --git a/src/server/services/agentSignal/processors/classifiers.ts b/src/server/services/agentSignal/processors/classifiers.tsindex 11b6d50016d..f6c8fdeffdf 100644--- a/src/server/services/agentSignal/processors/classifiers.ts+++ b/src/server/services/agentSignal/processors/classifiers.ts@@ -153,6 +153,7 @@ const buildDomainSignal = (sourceHints: signal.payload.sourceHints,target: 'memory',topicId: signal.payload.topicId,+ trigger: signal.payload.trigger,},signalId: `${signal.signalId}:domain:memory`,signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory,@@ -179,6 +180,7 @@ const buildDomainSignal = (sourceHints: signal.payload.sourceHints,target: 'none',topicId: signal.payload.topicId,+ trigger: signal.payload.trigger,},signalId: `${signal.signalId}:domain:none`,signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone,@@ -205,6 +207,7 @@ const buildDomainSignal = (sourceHints: signal.payload.sourceHints,target: 'prompt',topicId: signal.payload.topicId,+ trigger: signal.payload.trigger,},signalId: `${signal.signalId}:domain:prompt`,signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt,@@ -237,6 +240,7 @@ const buildDomainSignal = (sourceHints: signal.payload.sourceHints,target: 'skill',topicId: signal.payload.topicId,+ trigger: signal.payload.trigger,},signalId: `${signal.signalId}:domain:skill`,signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill,@@ -330,6 +334,7 @@ export const classifySatisfaction = async (memoryPayload: source.payload.memoryPayload,},topicId: source.payload.topicId,+ trigger: source.payload.trigger,},signalId: `${source.sourceId}:signal:feedback-satisfaction`,signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,diff --git a/src/server/services/agentSignal/services/procedureStateService.ts b/src/server/services/agentSignal/services/procedureStateService.tsindex b7c352a2505..1cb62fc9beb 100644--- a/src/server/services/agentSignal/services/procedureStateService.ts+++ b/src/server/services/agentSignal/services/procedureStateService.ts@@ -1,3 +1,7 @@+import {+ readDeferredSkillCandidate,+ writeDeferredSkillCandidate,+} from '../policies/analyzeIntent/skillCandidate';import {appendAndScoreProcedureAccumulatorRecord,appendProcedureAccumulatorRecord,@@ -14,6 +18,10 @@ import { writeProcedureRecordField } from '../procedure/record';import type { AgentSignalPolicyStateStore } from '../store/types';import type { ProcedureStateService } from './types';+type ProcedureStateServiceWithSkillCandidates = ProcedureStateService & {+ skillCandidates: NonNullable<ProcedureStateService['skillCandidates']>;+};+/*** Input for creating the procedure state facade.*/@@ -41,7 +49,7 @@ export interface CreateProcedureStateServiceInput {*/export const createProcedureStateService = (input: CreateProcedureStateServiceInput,-): ProcedureStateService => {+): ProcedureStateServiceWithSkillCandidates => {const now = input.now ?? (() => Date.now());const inspector = new AgentSignalProcedureInspector(input.policyStateStore);@@ -57,6 +65,15 @@ export const createProcedureStateService = (inspect: {scope: (scopeKey) => inspector.inspectScope(scopeKey),},+ skillCandidates: {+ read: (candidateInput) => readDeferredSkillCandidate(input.policyStateStore, candidateInput),+ write: (candidate) =>+ writeDeferredSkillCandidate(input.policyStateStore, {+ candidate,+ scopeKey: candidate.scopeKey,+ ttlSeconds: input.ttlSeconds,+ }),+ },markers: {shouldSuppress: async (markerInput) => {const marker = await readFirstActiveHandledProcedureMarker(diff --git a/src/server/services/agentSignal/services/types.ts b/src/server/services/agentSignal/services/types.tsindex a48b7f2ac39..8d18ae130be 100644--- a/src/server/services/agentSignal/services/types.ts+++ b/src/server/services/agentSignal/services/types.ts@@ -1,3 +1,4 @@+import type { DeferredSkillCandidate } from '../policies/analyzeIntent/skillCandidate';import type { ProcedureAccumulatorScoreResult } from '../procedure/accumulators/procedure';import type { AgentSignalProcedureInspectionSnapshot } from '../procedure/inspector';import type { ProcedureMarkerKeyInput } from '../procedure/keys';@@ -75,4 +76,14 @@ export interface ProcedureStateService {/** Writes one compact procedure record field. */write: (record: AgentSignalProcedureRecord) => Promise<void>;};+ /** Deferred skill-candidate operations between user and completion analysis stages. */+ skillCandidates?: {+ /** Reads one deferred skill candidate by source id. */+ read: (input: {+ scopeKey: string;+ sourceId: string;+ }) => Promise<DeferredSkillCandidate | undefined>;+ /** Writes one deferred skill candidate with facade-owned expiry semantics. */+ write: (candidate: DeferredSkillCandidate) => Promise<void>;+ };}diff --git a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.tsnew file mode 100644index 00000000000..286ffade16a--- /dev/null+++ b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts@@ -0,0 +1,435 @@+// @vitest-environment node+import type { AgentSignalSourceEvent } from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { messages, topics, users } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { describe, expect, it } from 'vitest';++import { uuid } from '@/utils/uuid';++import { resolveClientRuntimeCompleteFeedbackSource } from '../clientRuntimeComplete';++const createCompleteSource = (+ payload: Partial<+ AgentSignalSourceEvent<typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete>['payload']+ > = {},+): AgentSignalSourceEvent<typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete> => ({+ payload: {+ agentId: 'client-agent',+ assistantMessageId: 'assistant-1',+ operationId: 'op-1',+ status: 'completed',+ threadId: 'client-thread',+ topicId: 'client-topic',+ ...payload,+ },+ scopeKey: 'topic:client-topic',+ sourceId: 'op-1:client:complete',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ timestamp: 123,+});++describe('resolveClientRuntimeCompleteFeedbackSource', () => {+ /**+ * @example+ * client.runtime.complete({ assistantMessageId }) hydrates a trusted parent user source with an assistant context boundary.+ */+ it('hydrates an assistant completion into the parent agent user message source', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'Please remember this workflow.',+ id: parentMessageId,+ role: 'user',+ topicId,+ userId,+ });+ await db.insert(messages).values({+ content: 'I can remember that.',+ id: assistantMessageId,+ parentId: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({+ assistantMessageId,+ operationId: 'op-success',+ serializedContext: 'client context must not be trusted',+ topicId: 'client-topic',+ }),+ { db, userId },+ );++ expect(result.diagnostic).toEqual({+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ status: 'resolved',+ });+ expect(result.contextBoundaryMessageId).toBe(assistantMessageId);+ expect(result.contextEndAt).toBeInstanceOf(Date);+ expect(result.source).toEqual({+ payload: {+ agentId: 'client-agent',+ message: 'Please remember this workflow.',+ messageId: parentMessageId,+ threadId: 'client-thread',+ topicId,+ trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ },+ scopeKey: `topic:${topicId}`,+ sourceId: `${assistantMessageId}:completion:${parentMessageId}`,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ timestamp: 123,+ });+ expect(result.source?.payload.serializedContext).toBeUndefined();+ });++ /**+ * @example+ * client.runtime.complete({}) cannot hydrate without an assistant message id.+ */+ it('returns a skipped diagnostic when the completion event has no assistant message id', async () => {+ const db = await getTestDB();++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId: undefined }),+ { db, userId: `user_${uuid()}` },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'missing-assistant-message-id',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete({ status: "cancelled" }) is not final successful evidence.+ */+ it('returns a skipped diagnostic when completion status is cancelled or failed', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;++ const cancelled = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ status: 'cancelled' }),+ { db, userId },+ );+ const failed = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ status: 'failed' }),+ { db, userId },+ );+ const missing = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ status: undefined }),+ { db, userId },+ );++ expect(cancelled).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'non-completed-status',+ status: 'skipped',+ },+ });+ expect(failed).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'non-completed-status',+ status: 'skipped',+ },+ });+ expect(missing).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'non-completed-status',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete({ assistantMessageId: "missing" }) skips when the assistant row is absent.+ */+ it('returns a skipped diagnostic when the assistant message cannot be found', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;++ await db.insert(users).values({ id: userId });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId: `msg_${uuid()}` }),+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'assistant-message-not-found',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete must verify the assistant row role before trusting its parent.+ */+ it('returns a skipped diagnostic when the assistant message is not an assistant', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'User row cannot be the assistant completion.',+ id: assistantMessageId,+ role: 'user',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId }),+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'non-assistant-message',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete cannot infer user feedback when the assistant row has no parent id.+ */+ it('returns a skipped diagnostic when the assistant message has no parent id', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'Assistant without parent.',+ id: assistantMessageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId }),+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'missing-parent-message-id',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete skips when the assistant parent row is outside the current user boundary.+ */+ it('returns a skipped diagnostic when the parent message cannot be found', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const otherUserId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const otherTopicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await db.insert(topics).values([+ { id: topicId, title: 'Workflow Topic', userId },+ { id: otherTopicId, title: 'Other Topic', userId: otherUserId },+ ]);+ await db.insert(messages).values({+ content: 'Other user parent.',+ id: parentMessageId,+ role: 'user',+ topicId: otherTopicId,+ userId: otherUserId,+ });+ await db.insert(messages).values({+ content: 'Assistant references a row outside current user scope.',+ id: assistantMessageId,+ parentId: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId }),+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'parent-message-not-found',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete must verify the assistant parent is a persisted user message.+ */+ it('returns a skipped diagnostic when the parent message is not a user message', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'Assistant parent cannot be feedback.',+ id: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ });+ await db.insert(messages).values({+ content: 'Assistant child.',+ id: assistantMessageId,+ parentId: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId }),+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'non-user-parent',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete with an empty persisted user message cannot produce feedback text.+ */+ it('returns a skipped diagnostic when the parent message has empty content', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: '',+ id: parentMessageId,+ role: 'user',+ topicId,+ userId,+ });+ await db.insert(messages).values({+ content: 'Assistant child.',+ id: assistantMessageId,+ parentId: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId }),+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason: 'empty-content',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.complete with mismatched client topic metadata uses trusted persisted topic and scope.+ */+ it('does not let mismatched client scope or payload topic override trusted server rows', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'Persisted topic should win.',+ id: parentMessageId,+ role: 'user',+ topicId,+ userId,+ });+ await db.insert(messages).values({+ content: 'Assistant child.',+ id: assistantMessageId,+ parentId: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ {+ ...createCompleteSource({+ assistantMessageId,+ operationId: 'op-scope',+ topicId: 'client-topic',+ }),+ scopeKey: 'topic:client-topic',+ },+ { db, userId },+ );++ expect(result.diagnostic).toEqual({+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ status: 'resolved',+ });+ expect(result.source?.payload.topicId).toBe(topicId);+ expect(result.source?.scopeKey).toBe(`topic:${topicId}`);+ expect(result.source?.sourceId).toBe(`${assistantMessageId}:completion:${parentMessageId}`);+ });+});diff --git a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.tsnew file mode 100644index 00000000000..9200269a3b1--- /dev/null+++ b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts@@ -0,0 +1,287 @@+// @vitest-environment node+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { messages, topics, users } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { describe, expect, it } from 'vitest';++import { uuid } from '@/utils/uuid';++import { resolveClientRuntimeStartFeedbackSource } from '../clientRuntimeStart';++describe('resolveClientRuntimeStartFeedbackSource', () => {+ /**+ * @example+ * client.runtime.start({ parentMessageType: "assistant" }) skips hydration with a traceable reason.+ */+ it('returns a skipped diagnostic when the runtime start parent is not a user message', async () => {+ const db = await getTestDB();++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ operationId: `op_${uuid()}`,+ parentMessageId: `msg_${uuid()}`,+ parentMessageType: 'assistant',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId: `user_${uuid()}` },+ );++ expect(result).toEqual({+ diagnostic: {+ reason: 'non-user-parent',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.start({ parentMessageId }) hydrates a trusted agent.user.message source.+ */+ it('hydrates a user parent message into an agent user message source', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const messageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: 'topic_1', title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'Nice work. Can we keep this workflow?',+ id: messageId,+ role: 'user',+ topicId: 'topic_1',+ userId,+ });++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ agentId: 'agent_1',+ operationId: `op_${uuid()}`,+ parentMessageId: messageId,+ parentMessageType: 'user',+ serializedContext: 'client supplied context must not be trusted',+ topicId: 'topic_1',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId },+ );++ expect(result.diagnostic).toEqual({ status: 'resolved' });+ expect(result.source?.sourceType).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage);+ expect(result.source?.sourceId).toBe(messageId);+ expect(result.source?.payload).toMatchObject({+ agentId: 'agent_1',+ message: 'Nice work. Can we keep this workflow?',+ messageId,+ topicId: 'topic_1',+ trigger: 'client.runtime.start',+ });+ expect(result.source?.payload.serializedContext).toBeUndefined();+ });++ /**+ * @example+ * client.runtime.start with mismatched client topic metadata uses trusted persisted topic and scope.+ */+ it('does not let mismatched client scope or payload topic override trusted server rows', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const trustedTopicId = `topic_${uuid()}`;+ const clientTopicId = `topic_${uuid()}`;+ const messageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values([+ { id: trustedTopicId, title: 'Trusted Topic', userId },+ { id: clientTopicId, title: 'Client Topic', userId },+ ]);+ await db.insert(messages).values({+ content: 'Persisted topic should win for start hydration.',+ id: messageId,+ role: 'user',+ topicId: trustedTopicId,+ userId,+ });++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ agentId: 'client-agent',+ operationId: `op_${uuid()}`,+ parentMessageId: messageId,+ parentMessageType: 'user',+ threadId: 'client-thread',+ topicId: clientTopicId,+ },+ scopeKey: `topic:${clientTopicId}`,+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId },+ );++ expect(result.diagnostic).toEqual({ status: 'resolved' });+ expect(result.source?.payload.topicId).toBe(trustedTopicId);+ expect(result.source?.scopeKey).toBe(`topic:${trustedTopicId}`);+ expect(result.source?.sourceId).toBe(messageId);+ });++ /**+ * @example+ * client.runtime.start({ parentMessageType: "user" }) without a parent id cannot hydrate.+ */+ it('returns a skipped diagnostic when the runtime start event has no parent message id', async () => {+ const db = await getTestDB();++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ operationId: `op_${uuid()}`,+ parentMessageType: 'user',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId: `user_${uuid()}` },+ );++ expect(result).toEqual({+ diagnostic: {+ reason: 'missing-parent-message-id',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.start({ parentMessageId: "missing" }) cannot hydrate a source.+ */+ it('returns a skipped diagnostic when the parent message cannot be found', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;++ await db.insert(users).values({ id: userId });++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ operationId: `op_${uuid()}`,+ parentMessageId: `msg_${uuid()}`,+ parentMessageType: 'user',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ reason: 'message-not-found',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.start may claim a user parent, but the persisted row must agree.+ */+ it('returns a skipped diagnostic when the persisted parent message is not a user message', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const messageId = `msg_${uuid()}`;+ const topicId = `topic_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: 'Assistant text must not be treated as user feedback.',+ id: messageId,+ role: 'assistant',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ operationId: `op_${uuid()}`,+ parentMessageId: messageId,+ parentMessageType: 'user',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ reason: 'non-user-parent',+ status: 'skipped',+ },+ });+ });++ /**+ * @example+ * client.runtime.start with an empty persisted user message cannot produce feedback text.+ */+ it('returns a skipped diagnostic when the persisted parent message has empty content', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const messageId = `msg_${uuid()}`;+ const topicId = `topic_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values({+ content: '',+ id: messageId,+ role: 'user',+ topicId,+ userId,+ });++ const result = await resolveClientRuntimeStartFeedbackSource(+ {+ payload: {+ operationId: `op_${uuid()}`,+ parentMessageId: messageId,+ parentMessageType: 'user',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ timestamp: Date.now(),+ },+ { db, userId },+ );++ expect(result).toEqual({+ diagnostic: {+ reason: 'empty-content',+ status: 'skipped',+ },+ });+ });+});diff --git a/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts b/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.tsnew file mode 100644index 00000000000..9b03dfbba38--- /dev/null+++ b/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts@@ -0,0 +1,147 @@+import type {+ AgentSignalSourceEvent,+ SourceEventAgentUserMessage,+} from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { MessageModel } from '@/database/models/message';+import type { LobeChatDatabase } from '@/database/type';++/** Reason a `client.runtime.complete` event could not become a feedback source. */+export type ClientRuntimeCompleteHydrationSkipReason =+ | 'assistant-message-not-found'+ | 'empty-content'+ | 'missing-assistant-message-id'+ | 'missing-parent-message-id'+ | 'non-completed-status'+ | 'non-assistant-message'+ | 'non-user-parent'+ | 'parent-message-not-found';++/** Diagnostic emitted while hydrating a client runtime-complete source. */+export interface ClientRuntimeCompleteHydrationDiagnostic {+ /** Lifecycle source type that produced this hydration diagnostic. */+ kind: typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete;+ /** Stable skip reason for tracing when `status` is `skipped`. */+ reason?: ClientRuntimeCompleteHydrationSkipReason;+ /** Whether hydration produced a trusted server source. */+ status: 'resolved' | 'skipped';+}++/** Result of client runtime-complete source hydration. */+export interface ClientRuntimeCompleteHydrationResult {+ /** Trusted assistant message id that should bound later context assembly. */+ contextBoundaryMessageId?: string;+ /** Trusted assistant row timestamp that can cap later context assembly. */+ contextEndAt?: Date;+ /** Trace-safe hydration status and optional skip reason. */+ diagnostic: ClientRuntimeCompleteHydrationDiagnostic;+ /** Hydrated feedback source, present only when `diagnostic.status` is `resolved`. */+ source?: SourceEventAgentUserMessage;+}++const skipped = (+ reason: ClientRuntimeCompleteHydrationSkipReason,+): ClientRuntimeCompleteHydrationResult => ({+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ reason,+ status: 'skipped',+ },+});++const getHydratedSourceId = (assistantMessageId: string, parentMessageId: string) =>+ `${assistantMessageId}:completion:${parentMessageId}`;++const getTrustedScopeKey = (+ trustedTopicId: string | null | undefined,+ fallbackScopeKey: string,+) => {+ return trustedTopicId ? `topic:${trustedTopicId}` : fallbackScopeKey;+};++/**+ * Resolves a client runtime-complete event into a trusted feedback source.+ *+ * Use when:+ * - The browser emitted only `client.runtime.complete`.+ * - Feedback policies need server-owned final-turn user message content.+ *+ * Expects:+ * - `db` and `userId` point at the current user's message store.+ * - `source.payload.assistantMessageId` points to the completed assistant row.+ *+ * Returns:+ * - A hydrated `agent.user.message` source with the parent user message content.+ * - The trusted assistant row boundary for downstream context assembly.+ * - A skipped diagnostic when the client event cannot safely become feedback.+ */+export const resolveClientRuntimeCompleteFeedbackSource = async (+ sourceEvent: AgentSignalSourceEvent<typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete>,+ input: { db: LobeChatDatabase; userId: string },+): Promise<ClientRuntimeCompleteHydrationResult> => {+ if (sourceEvent.payload.status !== 'completed') {+ return skipped('non-completed-status');+ }++ const { assistantMessageId } = sourceEvent.payload;++ if (typeof assistantMessageId !== 'string') {+ return skipped('missing-assistant-message-id');+ }++ const messageModel = new MessageModel(input.db, input.userId);+ const assistantMessage = await messageModel.findById(assistantMessageId);++ if (!assistantMessage) {+ return skipped('assistant-message-not-found');+ }++ if (assistantMessage.role !== 'assistant') {+ return skipped('non-assistant-message');+ }++ if (typeof assistantMessage.parentId !== 'string') {+ return skipped('missing-parent-message-id');+ }++ const parentMessage = await messageModel.findById(assistantMessage.parentId);++ if (!parentMessage) {+ return skipped('parent-message-not-found');+ }++ if (parentMessage.role !== 'user') {+ return skipped('non-user-parent');+ }++ if (!parentMessage.content) {+ return skipped('empty-content');+ }++ const trustedTopicId = parentMessage.topicId ?? assistantMessage.topicId;++ return {+ contextBoundaryMessageId: assistantMessage.id,+ contextEndAt: assistantMessage.updatedAt ?? assistantMessage.createdAt,+ diagnostic: {+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ status: 'resolved',+ },+ source: {+ payload: {+ agentId: parentMessage.agentId ?? assistantMessage.agentId ?? sourceEvent.payload.agentId,+ message: parentMessage.content,+ messageId: parentMessage.id,+ threadId:+ parentMessage.threadId ?? assistantMessage.threadId ?? sourceEvent.payload.threadId,+ topicId: trustedTopicId ?? sourceEvent.payload.topicId,+ trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ },+ scopeKey: getTrustedScopeKey(trustedTopicId, sourceEvent.scopeKey),+ sourceId: getHydratedSourceId(assistantMessage.id, parentMessage.id),+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ timestamp: sourceEvent.timestamp,+ },+ };+};diff --git a/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.ts b/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.tsnew file mode 100644index 00000000000..284cebc3636--- /dev/null+++ b/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.ts@@ -0,0 +1,99 @@+import type {+ SourceEventAgentUserMessage,+ SourceEventClientRuntimeStart,+} from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { MessageModel } from '@/database/models/message';+import type { LobeChatDatabase } from '@/database/type';++/** Reason a `client.runtime.start` event could not become a feedback source. */+export type ClientRuntimeStartHydrationSkipReason =+ | 'empty-content'+ | 'message-not-found'+ | 'missing-parent-message-id'+ | 'non-user-parent';++/** Diagnostic emitted while hydrating a client runtime-start source. */+export interface ClientRuntimeStartHydrationDiagnostic {+ /** Stable skip reason for tracing when `status` is `skipped`. */+ reason?: ClientRuntimeStartHydrationSkipReason;+ /** Whether hydration produced a trusted server source. */+ status: 'resolved' | 'skipped';+}++/** Result of client runtime-start source hydration. */+export interface ClientRuntimeStartHydrationResult {+ /** Trace-safe hydration status and optional skip reason. */+ diagnostic: ClientRuntimeStartHydrationDiagnostic;+ /** Hydrated feedback source, present only when `diagnostic.status` is `resolved`. */+ source?: SourceEventAgentUserMessage;+}++const getTrustedScopeKey = (+ trustedTopicId: string | null | undefined,+ fallbackScopeKey: string,+) => {+ return trustedTopicId ? `topic:${trustedTopicId}` : fallbackScopeKey;+};++/**+ * Resolves a client runtime-start event into a trusted feedback source.+ *+ * Use when:+ * - The browser emitted only `client.runtime.start`.+ * - Feedback policies need server-owned user message content and ids.+ *+ * Expects:+ * - `sourceEvent.payload.parentMessageType === "user"` for hydratable events.+ * - `sourceEvent.payload.parentMessageId` belongs to the current user.+ *+ * Returns:+ * - A hydrated `agent.user.message` source with the parent message content.+ * - A skipped diagnostic when the client event cannot safely become feedback.+ */+export const resolveClientRuntimeStartFeedbackSource = async (+ sourceEvent: SourceEventClientRuntimeStart,+ input: { db: LobeChatDatabase; userId: string },+): Promise<ClientRuntimeStartHydrationResult> => {+ if (sourceEvent.payload.parentMessageType !== 'user') {+ return { diagnostic: { reason: 'non-user-parent', status: 'skipped' } };+ }++ if (typeof sourceEvent.payload.parentMessageId !== 'string') {+ return { diagnostic: { reason: 'missing-parent-message-id', status: 'skipped' } };+ }++ const messageModel = new MessageModel(input.db, input.userId);+ const parentMessage = await messageModel.findById(sourceEvent.payload.parentMessageId);++ if (!parentMessage) {+ return { diagnostic: { reason: 'message-not-found', status: 'skipped' } };+ }++ if (parentMessage.role !== 'user') {+ return { diagnostic: { reason: 'non-user-parent', status: 'skipped' } };+ }++ if (!parentMessage.content) {+ return { diagnostic: { reason: 'empty-content', status: 'skipped' } };+ }++ return {+ diagnostic: { status: 'resolved' },+ source: {+ payload: {+ agentId: parentMessage.agentId ?? sourceEvent.payload.agentId,+ message: parentMessage.content,+ messageId: parentMessage.id,+ threadId: parentMessage.threadId ?? sourceEvent.payload.threadId,+ topicId: parentMessage.topicId ?? sourceEvent.payload.topicId,+ trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ },+ scopeKey: getTrustedScopeKey(parentMessage.topicId, sourceEvent.scopeKey),+ sourceId: parentMessage.id,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ timestamp: sourceEvent.timestamp,+ },+ };+};diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsindex 57b455e25c1..1f73fc74e55 100644--- a/src/server/workflows/agentSignal/__tests__/run.test.ts+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport type { AgentSignalSourceEvent, SourceAgentUserMessage } from '@lobechat/agent-signal/source';import { AGENT_SIGNAL_SOURCE_TYPES, createSourceEvent } from '@lobechat/agent-signal/source';+import type { ISnapshotStore } from '@lobechat/agent-tracing';import { agents, messages, threads, topics, users } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';import { describe, expect, it, vi } from 'vitest';@@ -36,7 +37,7 @@ const createPolicyStateStore = (): AgentSignalPolicyStateStore => {};describe('runAgentSignalWorkflow', () => {- it('bridges client.runtime.start into agent.user.message with serialized root-topic context', async () => {+ it('hydrates client.runtime.start into agent.user.message with serialized root-topic context', async () => {const db = await getTestDB();const userId = `eval_${uuid()}`;const topicId = `topic_${uuid()}`;@@ -205,6 +206,7 @@ describe('runAgentSignalWorkflow', () => {operationId: `op_${uuid()}`,parentMessageId,parentMessageType: 'user',+ serializedContext: 'malicious client supplied context',topicId,},scopeKey: `topic:${topicId}`,@@ -240,6 +242,9 @@ describe('runAgentSignalWorkflow', () => {);expect(capturedSourceEvent?.sourceType).toBe('agent.user.message');expect(capturedSourceEvent?.payload.serializedContext).toContain('<feedback_analysis_context>');+ expect(capturedSourceEvent?.payload.serializedContext).not.toContain(+ 'malicious client supplied context',+ );expect(capturedSourceEvent?.payload.serializedContext).not.toContain('Old question that should be truncated from the serialized context.',);@@ -257,6 +262,311 @@ describe('runAgentSignalWorkflow', () => {);}, 10_000);+ it('records hydration skipped diagnostics in workflow snapshots', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const agentId = `agent_${uuid()}`;+ const saveSnapshot = vi.fn().mockResolvedValue(undefined);+ const snapshotStore = {+ get: vi.fn(),+ getLatest: vi.fn(),+ list: vi.fn(),+ listPartials: vi.fn(),+ loadPartial: vi.fn(),+ removePartial: vi.fn(),+ save: saveSnapshot,+ savePartial: vi.fn(),+ } satisfies ISnapshotStore;++ await db.insert(users).values({ id: userId });++ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async () => undefined,+ );++ await runAgentSignalWorkflow(+ createWorkflowContext({+ agentId,+ sourceEvent: {+ payload: {+ agentId,+ operationId: `op_${uuid()}`,+ parentMessageId: `msg_${uuid()}`,+ parentMessageType: 'assistant',+ topicId: 'topic_1',+ },+ scopeKey: 'topic:topic_1',+ sourceId: 'client:start:assistant-parent',+ sourceType: 'client.runtime.start',+ timestamp: Date.now(),+ },+ userId,+ }),+ {+ createSnapshotStore: () => snapshotStore,+ executeSourceEvent,+ getDb: async () => db,+ },+ );++ expect(saveSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({+ steps: [+ expect.objectContaining({+ context: expect.objectContaining({+ payload: expect.objectContaining({+ hydration: expect.objectContaining({+ kind: 'client.runtime.start',+ reason: 'non-user-parent',+ status: 'skipped',+ }),+ }),+ }),+ events: [+ expect.objectContaining({+ data: expect.objectContaining({+ hydrationKind: 'client.runtime.start',+ hydrationReason: 'non-user-parent',+ hydrationStatus: 'skipped',+ }),+ type: 'agent_signal.workflow.hydration',+ }),+ ],+ }),+ ],+ }),+ );+ });++ it('hydrates client.runtime.complete into paired user feedback with assistant-bound serialized context', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const userMessageId = `msg_${uuid()}`;+ const assistantMessageId = `msg_${uuid()}`;+ const baseTimestamp = new Date('2026-01-03T00:00:00.000Z').getTime();+ let capturedSourceEvent:+ | AgentSignalSourceEvent<typeof AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage>+ | undefined;++ await db.insert(users).values({ id: userId });++ const [agent] = await db+ .insert(agents)+ .values({+ model: 'gpt-4o-mini',+ plugins: [],+ provider: 'openai',+ systemRole: '',+ title: 'Completion Workflow Agent',+ userId,+ })+ .returning();++ await db.insert(topics).values({+ id: topicId,+ title: 'Completion Topic',+ userId,+ });++ await db.insert(messages).values([+ {+ agentId: agent.id,+ content: 'Please keep this exact workflow as a reusable skill.',+ createdAt: new Date(baseTimestamp + 1_000),+ id: userMessageId,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'I created the reusable workflow and attached the result.',+ createdAt: new Date(baseTimestamp + 2_000),+ id: assistantMessageId,+ parentId: userMessageId,+ role: 'assistant',+ topicId,+ updatedAt: new Date(baseTimestamp + 5_000),+ userId,+ },+ {+ agentId: agent.id,+ content: 'Same-turn document outcome that must be visible after the user parent.',+ createdAt: new Date(baseTimestamp + 3_000),+ id: `msg_${uuid()}`,+ role: 'document',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Same-turn tool outcome that must be visible after the user parent.',+ createdAt: new Date(baseTimestamp + 4_000),+ id: `msg_${uuid()}`,+ role: 'tool',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Later message that must be excluded from completion-bound context.',+ createdAt: new Date(baseTimestamp + 6_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ ]);++ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async (sourceEvent) => {+ capturedSourceEvent = sourceEvent as AgentSignalSourceEvent<+ typeof AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage+ >;+ return undefined;+ },+ );++ const result = await runAgentSignalWorkflow(+ createWorkflowContext({+ agentId: agent.id,+ sourceEvent: {+ payload: {+ agentId: agent.id,+ assistantMessageId,+ operationId: 'op_completion_hydration',+ serializedContext: 'client context must not be trusted',+ status: 'completed',+ topicId,+ },+ scopeKey: `topic:${topicId}`,+ sourceId: 'op_completion_hydration:client:complete',+ sourceType: 'client.runtime.complete',+ timestamp: Date.now(),+ },+ userId,+ }),+ {+ executeSourceEvent,+ getDb: async () => db,+ },+ );++ expect(result).toEqual(+ expect.objectContaining({+ sourceId: `${assistantMessageId}:completion:${userMessageId}`,+ success: true,+ }),+ );+ expect(executeSourceEvent).toHaveBeenCalledTimes(1);+ expect(capturedSourceEvent?.sourceType).toBe('agent.user.message');+ expect(capturedSourceEvent?.payload.trigger).toBe('client.runtime.complete');+ expect(capturedSourceEvent?.payload.messageId).toBe(userMessageId);+ expect(capturedSourceEvent?.payload.serializedContext).toContain(+ 'Please keep this exact workflow as a reusable skill.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).toContain(+ 'I created the reusable workflow and attached the result.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).toContain(+ 'Same-turn document outcome that must be visible after the user parent.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).toContain(+ 'Same-turn tool outcome that must be visible after the user parent.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).not.toContain(+ 'client context must not be trusted',+ );+ expect(capturedSourceEvent?.payload.serializedContext).not.toContain(+ 'Later message that must be excluded from completion-bound context.',+ );+ });++ it('skips cancelled client.runtime.complete hydration and records diagnostics without hydrated feedback', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const agentId = `agent_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const saveSnapshot = vi.fn().mockResolvedValue(undefined);+ const snapshotStore = {+ get: vi.fn(),+ getLatest: vi.fn(),+ list: vi.fn(),+ listPartials: vi.fn(),+ loadPartial: vi.fn(),+ removePartial: vi.fn(),+ save: saveSnapshot,+ savePartial: vi.fn(),+ } satisfies ISnapshotStore;+ let capturedSourceEvent: AgentSignalSourceEvent | undefined;++ await db.insert(users).values({ id: userId });++ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async (sourceEvent) => {+ capturedSourceEvent = sourceEvent;+ return undefined;+ },+ );++ await runAgentSignalWorkflow(+ createWorkflowContext({+ agentId,+ sourceEvent: {+ payload: {+ agentId,+ assistantMessageId: `msg_${uuid()}`,+ operationId: 'op_cancelled_completion',+ status: 'cancelled',+ topicId,+ },+ scopeKey: `topic:${topicId}`,+ sourceId: 'op_cancelled_completion:client:complete',+ sourceType: 'client.runtime.complete',+ timestamp: Date.now(),+ },+ userId,+ }),+ {+ createSnapshotStore: () => snapshotStore,+ executeSourceEvent,+ getDb: async () => db,+ },+ );++ expect(executeSourceEvent).toHaveBeenCalledTimes(1);+ expect(capturedSourceEvent?.sourceType).toBe('client.runtime.complete');+ expect(capturedSourceEvent?.sourceId).toBe('op_cancelled_completion:client:complete');+ expect(saveSnapshot).toHaveBeenCalledWith(+ expect.objectContaining({+ steps: [+ expect.objectContaining({+ context: expect.objectContaining({+ payload: expect.objectContaining({+ hydration: {+ kind: 'client.runtime.complete',+ reason: 'non-completed-status',+ status: 'skipped',+ },+ }),+ }),+ events: [+ expect.objectContaining({+ data: expect.objectContaining({+ hydrationKind: 'client.runtime.complete',+ hydrationReason: 'non-completed-status',+ hydrationStatus: 'skipped',+ }),+ type: 'agent_signal.workflow.hydration',+ }),+ ],+ }),+ ],+ }),+ );+ });+it('assembles serializedContext from the matching thread before executing a threaded source event', async () => {const db = await getTestDB();const userId = `eval_${uuid()}`;diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.tsindex 3d186f408c8..10fa01930da 100644--- a/src/server/workflows/agentSignal/run.ts+++ b/src/server/workflows/agentSignal/run.ts@@ -1,6 +1,6 @@import type {+ AgentSignalSourceEvent,SourceEventAgentUserMessage,- SourceEventClientRuntimeStart,} from '@lobechat/agent-signal/source';import {AGENT_SIGNAL_SOURCE_TYPES,@@ -38,17 +38,35 @@ import {createServerSelfIterationIntentPolicyOptions,createServerSelfReflectionPolicyOptions,} from '@/server/services/agentSignal/services/maintenance/serverRuntime';+import type { ClientRuntimeCompleteHydrationDiagnostic } from '@/server/services/agentSignal/sources/hydration/clientRuntimeComplete';+import { resolveClientRuntimeCompleteFeedbackSource } from '@/server/services/agentSignal/sources/hydration/clientRuntimeComplete';+import type { ClientRuntimeStartHydrationDiagnostic } from '@/server/services/agentSignal/sources/hydration/clientRuntimeStart';+import { resolveClientRuntimeStartFeedbackSource } from '@/server/services/agentSignal/sources/hydration/clientRuntimeStart';import type { AgentSignalWorkflowRunPayload } from './types';const log = debug('lobe-server:workflows:agent-signal:run');+type WorkflowHydrationDiagnostic =+ | ClientRuntimeCompleteHydrationDiagnostic+ | (ClientRuntimeStartHydrationDiagnostic & {+ kind: typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart;+ });+const isGeneratedEmission = (value: Awaited<ReturnType<typeof executeAgentSignalSourceEvent>> | undefined,): value is GeneratedAgentSignalEmissionResult => {return Boolean(value && !value.deduped);};+const isClientRuntimeCompleteSource = (+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],+): sourceEvent is AgentSignalSourceEvent<+ typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete+> => {+ return sourceEvent.sourceType === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete;+};+/*** Minimal workflow context contract used by the Agent Signal workflow runner.*@@ -188,59 +206,84 @@ const persistWorkflowSnapshot = async (await store.save(snapshot);};-/**- * Rebuilds one `agent.user.message` source from the client runtime-start event.- *- * Use when:- * - The browser only emits `client.runtime.start`- * - Feedback policies still need the original user message content- *- * Expects:- * - `sourceEvent.payload.parentMessageType === 'user'`- * - `sourceEvent.payload.parentMessageId` belongs to the same `userId`- *- * Returns:- * - One normalized `agent.user.message` source when the parent user message exists- * - Otherwise returns `undefined` so the original client source can continue unchanged- */-const bridgeClientRuntimeStartToAgentUserMessage = async (- sourceEvent: SourceEventClientRuntimeStart,- input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },-): Promise<SourceEventAgentUserMessage | undefined> => {- if (sourceEvent.payload.parentMessageType !== 'user') return undefined;- if (typeof sourceEvent.payload.parentMessageId !== 'string') return undefined;-- const messageModel = new MessageModel(input.db, input.userId);- const parentMessage = await messageModel.findById(sourceEvent.payload.parentMessageId);-- if (!parentMessage?.content) return undefined;+const readSourcePayloadString = (+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],+ field: string,+): string | undefined => {+ const payload = sourceEvent.payload;++ return typeof payload === 'object' &&+ payload !== null &&+ field in payload &&+ typeof payload[field as keyof typeof payload] === 'string'+ ? payload[field as keyof typeof payload]+ : undefined;+};- return {- payload: {- agentId:- typeof sourceEvent.payload.agentId === 'string' ? sourceEvent.payload.agentId : undefined,- message: parentMessage.content,- messageId: parentMessage.id,- serializedContext:- typeof sourceEvent.payload.serializedContext === 'string'- ? sourceEvent.payload.serializedContext- : undefined,- threadId:- typeof sourceEvent.payload.threadId === 'string' ? sourceEvent.payload.threadId : undefined,- topicId:- typeof sourceEvent.payload.topicId === 'string' ? sourceEvent.payload.topicId : undefined,- trigger: 'client.runtime.start',+const persistWorkflowHydrationSkippedSnapshot = async (+ input: {+ hydration: WorkflowHydrationDiagnostic;+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'];+ userId: string;+ },+ store: ISnapshotStore,+) => {+ const startedAt = input.sourceEvent.timestamp;+ const completedAt = Date.now();+ const operationId =+ readSourcePayloadString(input.sourceEvent, 'operationId') ?? input.sourceEvent.sourceId;+ const step: StepSnapshot = {+ completedAt,+ context: {+ payload: {+ hydration: input.hydration,+ scopeKey: input.sourceEvent.scopeKey,+ sourceId: input.sourceEvent.sourceId,+ sourceType: input.sourceEvent.sourceType,+ },+ phase: 'agent_signal_workflow',},- scopeKey: sourceEvent.scopeKey,- sourceId: parentMessage.id,- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,- timestamp: sourceEvent.timestamp,+ events: [+ {+ data: {+ hydrationKind: input.hydration.kind,+ hydrationReason: input.hydration.reason,+ hydrationStatus: input.hydration.status,+ scopeKey: input.sourceEvent.scopeKey,+ sourceId: input.sourceEvent.sourceId,+ sourceType: input.sourceEvent.sourceType,+ },+ timestamp: completedAt,+ type: 'agent_signal.workflow.hydration',+ },+ ],+ executionTimeMs: Math.max(0, completedAt - startedAt),+ startedAt,+ stepIndex: 0,+ stepType: 'call_tool',+ totalCost: 0,+ totalTokens: 0,};++ await store.save({+ agentId: readSourcePayloadString(input.sourceEvent, 'agentId'),+ completedAt,+ completionReason: 'done',+ operationId,+ startedAt,+ steps: [step],+ topicId: readSourcePayloadString(input.sourceEvent, 'topicId'),+ totalCost: 0,+ totalSteps: 1,+ totalTokens: 0,+ traceId: operationId,+ userId: input.userId,+ });};const buildFeedbackSourceSerializedContext = async (sourceEvent: SourceEventAgentUserMessage,- input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },+ input: { contextEndAt?: Date; db: Awaited<ReturnType<typeof getServerDB>>; userId: string },): Promise<string | undefined> => {if (typeof sourceEvent.payload.serializedContext === 'string') {return sourceEvent.payload.serializedContext;@@ -253,6 +296,7 @@ const buildFeedbackSourceSerializedContext = async (if (!anchorMessage?.createdAt) return undefined;+ const contextEndAt = input.contextEndAt ?? anchorMessage.createdAt;const threadScopeFilter =typeof sourceEvent.payload.threadId === 'string'? eq(messages.threadId, sourceEvent.payload.threadId)@@ -264,7 +308,7 @@ const buildFeedbackSourceSerializedContext = async (where: and(eq(messages.userId, input.userId),eq(messages.topicId, sourceEvent.payload.topicId),- lte(messages.createdAt, anchorMessage.createdAt),+ lte(messages.createdAt, contextEndAt),threadScopeFilter,),});@@ -284,7 +328,7 @@ const buildFeedbackSourceSerializedContext = async (const enrichFeedbackSourceSerializedContext = async (sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],- input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },+ input: { contextEndAt?: Date; db: Awaited<ReturnType<typeof getServerDB>>; userId: string },): Promise<AgentSignalWorkflowRunPayload['sourceEvent']> => {if (!isAgentUserMessageSource(sourceEvent)) return sourceEvent;@@ -312,28 +356,52 @@ const enrichFeedbackSourceSerializedContext = async (* - `db` and `userId` point at the same message store used by the originating chat session** Returns:- * - The bridged source when one ingress adapter applies+ * - The hydrated source when a client lifecycle event can be resolved* - Otherwise the original workflow source event** Call stack:** {@link runAgentSignalWorkflow}* -> {@link normalizeWorkflowSourceEvent}- * -> {@link bridgeClientRuntimeStartToAgentUserMessage}+ * -> {@link resolveClientRuntimeCompleteFeedbackSource}+ * -> {@link MessageModel.findById}+ * -> {@link resolveClientRuntimeStartFeedbackSource}* -> {@link MessageModel.findById}*/const normalizeWorkflowSourceEvent = async (sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },-): Promise<AgentSignalWorkflowRunPayload['sourceEvent']> => {+): Promise<{+ hydration?: WorkflowHydrationDiagnostic;+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'];+}> => {+ if (isClientRuntimeCompleteSource(sourceEvent)) {+ const hydration = await resolveClientRuntimeCompleteFeedbackSource(sourceEvent, input);+ const hydratedSourceEvent = hydration.source ?? sourceEvent;++ return {+ hydration: hydration.diagnostic,+ sourceEvent: await enrichFeedbackSourceSerializedContext(hydratedSourceEvent, {+ ...input,+ contextEndAt: hydration.contextEndAt,+ }),+ };+ }+if (isClientRuntimeStartSource(sourceEvent)) {- const bridgedSourceEvent =- (await bridgeClientRuntimeStartToAgentUserMessage(sourceEvent, input)) ?? sourceEvent;+ const hydration = await resolveClientRuntimeStartFeedbackSource(sourceEvent, input);+ const hydratedSourceEvent = hydration.source ?? sourceEvent;- return enrichFeedbackSourceSerializedContext(bridgedSourceEvent, input);+ return {+ hydration: {+ ...hydration.diagnostic,+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,+ },+ sourceEvent: await enrichFeedbackSourceSerializedContext(hydratedSourceEvent, input),+ };}- return enrichFeedbackSourceSerializedContext(sourceEvent, input);+ return { sourceEvent: await enrichFeedbackSourceSerializedContext(sourceEvent, input) };};/**@@ -439,6 +507,7 @@ export const runAgentSignalWorkflow = async (const createGuardBackend =deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;const snapshotStore = (deps.createSnapshotStore ?? createDefaultSnapshotStore)();+ let hydrationDiagnostic: WorkflowHydrationDiagnostic | undefined;let selfIterationEnabled = false;const db = await getDb();@@ -451,9 +520,28 @@ export const runAgentSignalWorkflow = async (db,userId: payload.userId,});+ if (result.hydration) {+ hydrationDiagnostic = result.hydration;+ normalizeSpan.setAttribute(+ 'agent.signal.hydration.status',+ result.hydration.status,+ );+ if (result.hydration.kind) {+ normalizeSpan.setAttribute(+ 'agent.signal.hydration.kind',+ result.hydration.kind,+ );+ }+ if (result.hydration.reason) {+ normalizeSpan.setAttribute(+ 'agent.signal.hydration.reason',+ result.hydration.reason,+ );+ }+ }normalizeSpan.setStatus({ code: SpanStatusCode.OK });- return result;+ return result.sourceEvent;} catch (error) {normalizeSpan.setStatus({code: SpanStatusCode.ERROR,@@ -577,6 +665,25 @@ export const runAgentSignalWorkflow = async (}}+ if (+ snapshotStore &&+ !isGeneratedEmission(result) &&+ hydrationDiagnostic?.status === 'skipped'+ ) {+ try {+ await persistWorkflowHydrationSkippedSnapshot(+ {+ hydration: hydrationDiagnostic,+ sourceEvent: payload.sourceEvent,+ userId: payload.userId,+ },+ snapshotStore,+ );+ } catch (error) {+ log('Persist workflow hydration skipped snapshot failed error=%O', error);+ }+ }+workflowRunCounter.add(1,buildWorkflowMetricAttributes(normalizedSourceEvent.sourceType, workflowStatus),diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex 666eea7b414..ef602bc9d1d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -1,3 +1,4 @@+import type { AgentState } from '@lobechat/agent-runtime';import * as agentRuntime from '@lobechat/agent-runtime';import { type UIChatMessage } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';@@ -11,6 +12,7 @@ import { useAiInfraStore } from '@/store/aiInfra';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { useChatStore } from '../../../../store';+import { messageMapKey } from '../../../../utils/messageMapKey';import {createMockAgentConfig,createMockChatConfig,@@ -22,6 +24,37 @@ import {import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';const serverConfigMock = vi.hoisted(() => ({ enableVisualUnderstanding: false }));+const agentSignalBridgeMock = vi.hoisted(() => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));++vi.hoisted(() => {+ // NOTICE:+ // Ensure store modules see a full Storage-compatible localStorage during import.+ // Vitest can provide a partial localStorage object when invoked with an empty+ // `--localstorage-file`, which breaks packages/utils/src/localStorage.ts at collection time.+ // Source/context: matches the focused store test setup pattern in src/services/chat/chat.test.ts.+ // Removal condition: safe to delete when Vitest setup guarantees getItem/setItem before imports.+ const storage = new Map<string, string>();++ Object.defineProperty(globalThis, 'localStorage', {+ configurable: true,+ value: {+ clear: () => storage.clear(),+ getItem: (key: string) => storage.get(key) ?? null,+ key: (index: number) => Array.from(storage.keys())[index] ?? null,+ get length() {+ return storage.size;+ },+ removeItem: (key: string) => {+ storage.delete(key);+ },+ setItem: (key: string, value: string) => {+ storage.set(key, value);+ },+ },+ });+});interface AgentRuntimeStepContext {agent: {@@ -39,8 +72,40 @@ const getCreatedAgentCompressionConfig = (stepSpy: { mock: { contexts: unknown[]return runtime.agent.config.compressionConfig;};+const createMockRuntimeState = (operationId: string, status: AgentState['status']): AgentState => ({+ status,+ operationId,+ messages: [],+ maxSteps: 10,+ stepCount: 1,+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ toolManifestMap: {},+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },+ usage: {+ llm: { apiCalls: 1, processingTimeMs: 100, tokens: { input: 10, output: 20, total: 30 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ total: 0,+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ },+});+// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');+vi.mock('@/store/chat/slices/aiChat/actions/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: agentSignalBridgeMock.emitClientAgentSignalSourceEvent,+}));vi.mock('@/store/serverConfig', () => ({getServerConfigStoreState: () => ({serverConfig: { enableVisualUnderstanding: serverConfigMock.enableVisualUnderstanding },@@ -52,6 +117,15 @@ vi.mock('@/store/serverConfig', () => ({}));const realExecAgentRuntime = useChatStore.getState().executeClientAgent;+const realCreateAgentState = useChatStore.getState().internal_createAgentState;++const mockInternalCreateAgentState = (value: ReturnType<typeof realCreateAgentState>) => {+ act(() => {+ useChatStore.setState({+ internal_createAgentState: vi.fn<typeof realCreateAgentState>().mockReturnValue(value),+ });+ });+};beforeEach(() => {resetTestEnvironment();@@ -63,6 +137,7 @@ beforeEach(() => {useChatStore.setState({refreshMessages: vi.fn(),executeClientAgent: vi.fn(),+ internal_createAgentState: realCreateAgentState,});});});@@ -486,7 +561,7 @@ describe('StreamingExecutor actions', () => {});// Create operation manually to register callbacks- let operationId: string;+ let operationId!: string;const afterCompletionCallback1 = vi.fn();const afterCompletionCallback2 = vi.fn();@@ -587,7 +662,7 @@ describe('StreamingExecutor actions', () => {plugins: [],});- let operationId: string;+ let operationId!: string;const errorCallback = vi.fn().mockRejectedValue(new Error('Callback error'));const successCallback = vi.fn();@@ -693,7 +768,7 @@ describe('StreamingExecutor actions', () => {plugins: [],});- let operationId: string;+ let operationId!: string;act(() => {const res = result.current.startOperation({@@ -1589,6 +1664,292 @@ describe('StreamingExecutor actions', () => {});describe('operation status handling', () => {+ it('emits client.runtime.complete with the latest assistant message id', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ executeClientAgent: realExecAgentRuntime,+ });+ });++ let operationId!: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ const finalMessages = [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ }),+ ];++ act(() => {+ useChatStore.setState((state) => ({+ messagesMap: {+ ...state.messagesMap,+ [messageMapKey({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID })]:+ finalMessages,+ },+ }));+ });++ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'done'),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });++ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId,+ status: 'completed',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });++ it('does not attach an unrelated assistant message id to client.runtime.complete', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ executeClientAgent: realExecAgentRuntime,+ });+ });++ let operationId!: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ act(() => {+ useChatStore.setState((state) => ({+ messagesMap: {+ ...state.messagesMap,+ [messageMapKey({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID })]: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: 'different-user-message',+ role: 'assistant',+ }),+ ],+ },+ }));+ });++ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'done'),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });++ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ assistantMessageId: undefined,+ operationId,+ status: 'completed',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });++ it('emits client.runtime.complete before returning for queued follow-up messages', async () => {+ vi.useFakeTimers();++ const { result } = renderHook(() => useChatStore());+ const contextKey = messageMapKey({+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ });++ act(() => {+ useChatStore.setState({+ executeClientAgent: realExecAgentRuntime,+ queuedMessages: {+ [contextKey]: [+ {+ content: 'queued follow-up',+ createdAt: Date.now(),+ id: 'queued-message-1',+ interruptMode: 'soft',+ },+ ],+ },+ });+ });++ let operationId!: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'done'),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });++ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ vi.useRealTimers();++ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ operationId,+ status: 'completed',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });++ it('emits cancelled client.runtime.complete when operation status is cancelled', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ executeClientAgent: realExecAgentRuntime,+ });+ });++ let operationId!: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ result.current.cancelOperation(operationId, 'user_cancelled');+ });++ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'done'),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });++ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ operationId,+ status: 'cancelled',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });+it('should complete operation when state is waiting_for_human', async () => {const { result } = renderHook(() => useChatStore());@@ -1607,7 +1968,7 @@ describe('StreamingExecutor actions', () => {plugins: [],});- let operationId: string;+ let operationId!: string;act(() => {const res = result.current.startOperation({@@ -1618,39 +1979,8 @@ describe('StreamingExecutor actions', () => {});// Mock internal_createAgentState to return waiting_for_human status- vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({- state: {- status: 'waiting_for_human' as const,- operationId: operationId!,- messages: [],- maxSteps: 10,- stepCount: 1,- createdAt: new Date().toISOString(),- lastModified: new Date().toISOString(),- toolManifestMap: {},- userInterventionConfig: { approvalMode: 'manual', allowList: [] },- usage: {- llm: {- apiCalls: 1,- processingTimeMs: 100,- tokens: { input: 10, output: 20, total: 30 },- },- tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },- humanInteraction: {- approvalRequests: 1,- promptRequests: 0,- selectRequests: 0,- totalWaitingTimeMs: 0,- },- },- cost: {- calculatedAt: new Date().toISOString(),- currency: 'USD',- total: 0,- llm: { byModel: [], currency: 'USD', total: 0 },- tools: { byTool: [], currency: 'USD', total: 0 },- },- },+ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'waiting_for_human'),context: {phase: 'init',payload: { model: 'gpt-4o-mini', provider: 'openai' },@@ -1663,6 +1993,11 @@ describe('StreamingExecutor actions', () => {},agentConfig: createMockResolvedAgentConfig(),});+ vi.spyOn(agentRuntime.AgentRuntime.prototype, 'step').mockResolvedValue({+ events: [],+ newState: createMockRuntimeState(operationId!, 'waiting_for_human'),+ nextContext: undefined,+ });await act(async () => {await result.current.executeClientAgent({@@ -1682,6 +2017,16 @@ describe('StreamingExecutor actions', () => {// 1. User can see the tool intervention UI without loading indicator// 2. A new operation will be created when user approves/rejectsexpect(result.current.operations[operationId!].status).toBe('completed');+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ operationId,+ status: 'cancelled',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );});it('should fail operation when state is error', async () => {diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.tsindex 752875d46ef..8fe4b7981f2 100644--- a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts@@ -80,8 +80,9 @@ describe('emitClientAgentSignalSourceEvent', () => {await emitClientAgentSignalSourceEvent({payload: {agentId: 'agent-1',+ assistantMessageId: 'asst-1',operationId: 'op-1',- status: 'done',+ status: 'completed',threadId: 'thread-1',topicId: 'topic-1',},@@ -93,8 +94,9 @@ describe('emitClientAgentSignalSourceEvent', () => {expect(agentSignalService.emitClientGatewaySourceEvent).toHaveBeenCalledWith({payload: {agentId: 'agent-1',+ assistantMessageId: 'asst-1',operationId: 'op-1',- status: 'done',+ status: 'completed',threadId: 'thread-1',topicId: 'topic-1',},diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 2963366718b..cf66640edd5 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -33,6 +33,7 @@ import { aiModelSelectors } from '@/store/aiInfra/selectors';import { getAiInfraStoreState } from '@/store/aiInfra/store';import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';+import { type OperationStatus } from '@/store/chat/slices/operation/types';import { type ChatStore, useChatStore } from '@/store/chat/store';import {notifyDesktopHumanApprovalRequired,@@ -85,6 +86,36 @@ const getVisualMediaAvailability = (messages: UIChatMessage[]) => ({hasVideos: messages.some((message) => message.role === 'user' && !!message.videoList?.length),});+/**+ * Normalizes AgentRuntime terminal status into client runtime completion status.+ *+ * Before:+ * - "done"+ * - "waiting_for_human"+ *+ * After:+ * - "completed"+ * - "cancelled"+ */+const normalizeClientRuntimeCompleteStatus = (+ runtimeStatus: AgentState['status'],+ operationStatus?: OperationStatus,+): 'cancelled' | 'completed' | 'failed' | undefined => {+ if (operationStatus === 'cancelled') return 'cancelled';+ if (operationStatus === 'failed') return 'failed';+ if (runtimeStatus === 'waiting_for_human') return 'cancelled';+ if (operationStatus === 'completed') return 'completed';+ if (runtimeStatus === 'done') return 'completed';+ if (runtimeStatus === 'error' || runtimeStatus === 'interrupted') return 'failed';+ return undefined;+};++const findCompletionAssistantMessageId = (messages: UIChatMessage[], parentMessageId: string) => {+ return messages.findLast(+ (message) => message.role === 'assistant' && message.parentId === parentMessageId,+ )?.id;+};+/*** Core streaming execution actions for AI chat*/@@ -581,6 +612,25 @@ export class StreamingExecutorActionImpl {// Compute contextKey for message queue (per-context, not per-operation)const contextKey = messageKey;+ const emitRuntimeCompleteSource = () => {+ const finalMessages = this.#get().messagesMap[messageKey] || [];+ const assistantMessageId = findCompletionAssistantMessageId(finalMessages, parentMessageId);+ const operationStatus = this.#get().operations[operationId]?.status;++ void emitClientAgentSignalSourceEvent({+ payload: {+ agentId,+ assistantMessageId,+ operationId,+ status: normalizeClientRuntimeCompleteStatus(state.status, operationStatus),+ threadId: threadId ?? undefined,+ topicId: topicId ?? undefined,+ },+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ });+ };+// Execute the agent runtime looplet stepCount = 0;while (state.status !== 'done' && state.status !== 'error') {@@ -788,6 +838,8 @@ export class StreamingExecutorActionImpl {this.#get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);}+ emitRuntimeCompleteSource();+const execContext = { ...context };const mergedContent = merged.content;// Rebuild UploadFileItem-shaped objects from the queued file previews so@@ -851,17 +903,7 @@ export class StreamingExecutorActionImpl {}log('[executeClientAgent] completed');- void emitClientAgentSignalSourceEvent({- payload: {- agentId,- operationId,- status: state.status,- threadId: threadId ?? undefined,- topicId: topicId ?? undefined,- },- sourceId: `${operationId}:client:complete`,- sourceType: 'client.runtime.complete',- });+ emitRuntimeCompleteSource();// Desktop notification (if not in tools calling mode)if (isDesktop) {