🤯 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
✨ feat(agent): add interactive code context selections (#16681)
Inneieaf301369429
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 43754519e6e..0f9144d17d7 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -142,6 +142,8 @@ interface SendPromptParams {operationId: string;prompt: string;sessionId: string;+ /** Extra context injected before the user prompt without mutating the prompt text. */+ systemContext?: string;}interface CancelSessionParams {@@ -834,8 +836,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {private async buildStreamJsonInput(prompt: string,imageList: HeterogeneousAgentImageAttachment[] = [],+ systemContext?: string,): Promise<string> {const blocks: AgentContentBlock[] = [];+ if (systemContext && systemContext.length > 0)+ blocks.push({ text: systemContext, type: 'text' });if (prompt && prompt.length > 0) blocks.push({ text: prompt, type: 'text' });blocks.push(...this.toImageContentBlocks(imageList));@@ -958,13 +963,14 @@ export default class HeterogeneousAgentCtr extends ControllerModule {args: session.args,helpers: {buildClaudeStreamJsonInput: (prompt, imageList) =>- this.buildStreamJsonInput(prompt, imageList),+ this.buildStreamJsonInput(prompt, imageList, params.systemContext),resolveCliImagePaths: (imageList) => this.resolveCliImagePaths(imageList),},imageList: params.imageList ?? [],mcpConfigPath: intervention?.tmpConfigPath,prompt: params.prompt,resumeSessionId: session.agentSessionId,+ systemContext: params.systemContext,});// Fall back to the user's Desktop so the process never inheritsdiff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex aa52090d824..32d05748902 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -229,10 +229,7 @@ describe('HeterogeneousAgentCtr', () => {_file: string,_args: string[],optionsOrCallback: unknown,- callback?: (- error: Error | null,- result: { stderr: string; stdout: string },- ) => void,+ callback?: (error: Error | null, result: { stderr: string; stdout: string }) => void,) => {const resolvedCallback =typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;@@ -287,7 +284,10 @@ describe('HeterogeneousAgentCtr', () => {prompt: string,sessionOverrides: Record<string, any> = {},stdoutLines: string[] = [],- sendPromptOverrides: Partial<{ imageList: Array<{ id: string; url: string }> }> = {},+ sendPromptOverrides: Partial<{+ imageList: Array<{ id: string; url: string }>;+ systemContext: string;+ }> = {},) => {const { proc, writes } = createFakeProc({ stdoutLines });nextFakeProc = proc;@@ -333,6 +333,19 @@ describe('HeterogeneousAgentCtr', () => {});});+ it('places system context before the user prompt in stream-json content blocks', async () => {+ const { writes } = await runSendPrompt('user task', {}, [], {+ systemContext: 'selected code context',+ });++ expect(writes).toHaveLength(1);+ const msg = JSON.parse(writes[0].trimEnd());+ expect(msg.message.content).toEqual([+ { text: 'selected code context', type: 'text' },+ { text: 'user task', type: 'text' },+ ]);+ });+it.each(['-flag-looking-prompt','--help please',@@ -449,7 +462,10 @@ describe('HeterogeneousAgentCtr', () => {prompt: string,sessionOverrides: Record<string, any> = {},stdoutLines: string[] = [],- sendPromptOverrides: Partial<{ imageList: Array<{ id: string; url: string }> }> = {},+ sendPromptOverrides: Partial<{+ imageList: Array<{ id: string; url: string }>;+ systemContext: string;+ }> = {},storeGet?: (key: string, defaultValue?: any) => any,) => {const { proc, writes } = createFakeProc({ stdoutLines });@@ -648,6 +664,14 @@ describe('HeterogeneousAgentCtr', () => {expect(writes).toEqual([prompt]);});+ it('places system context before the user prompt in codex stdin', async () => {+ const { writes } = await runSendPrompt('user task', {}, [], {+ systemContext: 'selected code context',+ });++ expect(writes).toEqual(['selected code context\n\nuser task']);+ });+it('materializes image attachments into local files and forwards them via --image', async () => {const imageList = [{ id: 'image-1', url: 'data:image/png;base64,UE5HX1RFU1Q=' },diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.tsindex 9a92e3303ee..adfbf4df218 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts@@ -21,8 +21,9 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {mcpConfigPath,prompt,resumeSessionId,+ systemContext,}: HeterogeneousAgentBuildPlanParams) {- const stdinPayload = await helpers.buildClaudeStreamJsonInput(prompt, imageList);+ const stdinPayload = await helpers.buildClaudeStreamJsonInput(prompt, imageList, systemContext);return {args: [diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.tsindex 109a714f5f2..fd024e1ff1d 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.ts@@ -30,14 +30,16 @@ export const codexDriver: HeterogeneousAgentDriver = {imageList,prompt,resumeSessionId,+ systemContext,}: HeterogeneousAgentBuildPlanParams) {const optionArgs = await buildCodexOptionArgs({ args, helpers, imageList });+ const stdinPayload = [systemContext, prompt].filter(Boolean).join('\n\n');return {args: resumeSessionId? ['exec', 'resume', ...optionArgs, resumeSessionId, '-']: ['exec', ...optionArgs],- stdinPayload: prompt,+ stdinPayload,};},};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsindex 89803793f71..4060c01c4b9 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -12,6 +12,7 @@ export interface HeterogeneousAgentBuildPlanHelpers {buildClaudeStreamJsonInput: (prompt: string,imageList: HeterogeneousAgentImageAttachment[],+ systemContext?: string,) => Promise<string>;resolveCliImagePaths: (imageList: HeterogeneousAgentImageAttachment[]) => Promise<string[]>;}@@ -28,6 +29,7 @@ export interface HeterogeneousAgentBuildPlanParams {mcpConfigPath?: string;prompt: string;resumeSessionId?: string;+ systemContext?: string;}/**diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex aaef443fdca..97e868cb06d 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -351,11 +351,16 @@ export const aiChatRouter = router({// create user messagelog('creating user message with content length: %d', input.newUserMessage.content.length);- // Build user message metadata with pageSelections if present+ // Build user message metadata with attached context selections if present.const userMessageMetadata =- input.newUserMessage.metadata || input.newUserMessage.pageSelections?.length+ input.newUserMessage.metadata ||+ input.newUserMessage.contextSelections?.length ||+ input.newUserMessage.pageSelections?.length? {...input.newUserMessage.metadata,+ ...(input.newUserMessage.contextSelections?.length+ ? { contextSelections: input.newUserMessage.contextSelections }+ : undefined),...(input.newUserMessage.pageSelections?.length? { pageSelections: input.newUserMessage.pageSelections }: undefined),diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex fd6ae37d2dd..f92fad99eae 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1295,6 +1295,7 @@"workingPanel.resources.updatedAt": "Updated {{time}}","workingPanel.resources.viewMode.list": "List view","workingPanel.resources.viewMode.tree": "Tree view",+ "workingPanel.review.addSelectionToContext.success": "Added selected lines to context","workingPanel.review.baseRef.default": "default","workingPanel.review.baseRef.loading": "Loading branches…","workingPanel.review.baseRef.reset": "Reset to default branch",diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex 0a374fd7808..95655d216b8 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -29,6 +29,7 @@"workingDirectory.detachedHead": "Detached HEAD at {{sha}}","workingDirectory.detachedHeadShort": "detached@{{sha}}","workingDirectory.detachedWorktree": "detached",+ "workingDirectory.diffLineStatTooltip": "Added lines {{added}} · Deleted lines {{deleted}} · Changed files {{files}}","workingDirectory.diffStatTooltip": "Added {{added}} · Modified {{modified}} · Deleted {{deleted}}","workingDirectory.filesAdded": "Added","workingDirectory.filesDeleted": "Deleted",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 437ffd793b5..c49ad0dd2a4 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1295,6 +1295,7 @@"workingPanel.resources.updatedAt": "更新于 {{time}}","workingPanel.resources.viewMode.list": "列表视图","workingPanel.resources.viewMode.tree": "树状视图",+ "workingPanel.review.addSelectionToContext.success": "已将选中代码加入上下文","workingPanel.review.baseRef.default": "默认","workingPanel.review.baseRef.loading": "正在加载分支…","workingPanel.review.baseRef.reset": "恢复默认分支",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex 6dcc05511f0..50b1daa8309 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -29,6 +29,7 @@"workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}","workingDirectory.detachedHeadShort": "detached@{{sha}}","workingDirectory.detachedWorktree": "detached",+ "workingDirectory.diffLineStatTooltip": "新增行 {{added}} · 删除行 {{deleted}} · 变更文件 {{files}}","workingDirectory.diffStatTooltip": "新增 {{added}} · 修改 {{modified}} · 删除 {{deleted}}","workingDirectory.filesAdded": "新增","workingDirectory.filesDeleted": "删除",diff --git a/packages/context-engine/src/providers/PageSelectionsInjector.ts b/packages/context-engine/src/providers/PageSelectionsInjector.tsindex 066d7704463..9b2c34e470d 100644--- a/packages/context-engine/src/providers/PageSelectionsInjector.ts+++ b/packages/context-engine/src/providers/PageSelectionsInjector.ts@@ -1,5 +1,5 @@-import { formatPageSelections } from '@lobechat/prompts';-import type { PageSelection } from '@lobechat/types';+import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';+import type { ContextSelection, PageSelection } from '@lobechat/types';import debug from 'debug';import { BaseEveryUserContentProvider } from '../base/BaseEveryUserContentProvider';@@ -41,7 +41,24 @@ export class PageSelectionsInjector extends BaseEveryUserContentProvider {return null;}- // Check if message has pageSelections in metadata+ const contextSelections = message.metadata?.contextSelections as ContextSelection[] | undefined;++ if (contextSelections && contextSelections.length > 0) {+ const formattedSelections = formatContextSelections(contextSelections);++ if (!formattedSelections) return null;++ log(+ `Building generic context selections for message at index ${index} with ${contextSelections.length} selections`,+ );++ return {+ content: formattedSelections,+ contextType: 'user_context_selections',+ };+ }++ // Check if message has legacy pageSelections in metadataconst pageSelections = message.metadata?.pageSelections as PageSelection[] | undefined;if (!pageSelections || pageSelections.length === 0) {diff --git a/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.tsindex f9f06a5321f..07c2a556fa2 100644--- a/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts@@ -64,6 +64,36 @@ describe('PageSelectionsInjector', () => {expect(result.messages[0].content).toContain('<user_page_selections>');expect(result.messages[0].content).toContain('Selected text');});++ it('should inject generic context selections when present', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Review this code',+ metadata: {+ contextSelections: [+ {+ content: 'const value = 1;',+ filePath: 'src/example.ts',+ id: 'code-1',+ lineRange: { endLine: 12, startLine: 12 },+ source: 'code',+ },+ ],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('Review this code');+ expect(result.messages[0].content).toContain('<user_context_selections>');+ expect(result.messages[0].content).toContain('filePath="src/example.ts"');+ expect(result.messages[0].content).toContain('lines="12-12"');+ expect(result.messages[0].content).toContain('const value = 1;');+ });});describe('injection to every user message', () => {diff --git a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.tsindex a57c1568647..63bca571222 100644--- a/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/signalTurnWithTools.pipeline.test.ts@@ -58,36 +58,74 @@ const flatten = (messages: Message[]) => {const scenario = (parentOfS2: 'SIG' | 'W'): Message[] => [{ content: 'go', createdAt: 0, id: 'u1', role: 'user', updatedAt: 0 },{- agentId: 'a', content: '三个探测都回来了,先给你结论', createdAt: 100, id: 'W',- parentId: 'u1', role: 'assistant', tools: toolArr('bashwait'), updatedAt: 100,+ agentId: 'a',+ content: '三个探测都回来了,先给你结论',+ createdAt: 100,+ id: 'W',+ parentId: 'u1',+ role: 'assistant',+ tools: toolArr('bashwait'),+ updatedAt: 100,},{- content: 'agent done', createdAt: 110, id: 'toolW', parentId: 'W',- role: 'tool', tool_call_id: 'bashwait', updatedAt: 110,+ content: 'agent done',+ createdAt: 110,+ id: 'toolW',+ parentId: 'W',+ role: 'tool',+ tool_call_id: 'bashwait',+ updatedAt: 110,} as any,{- agentId: 'a', content: 'TASKCOMP 明白了。两点都定了', createdAt: 120, id: 'SIG',+ agentId: 'a',+ content: 'TASKCOMP 明白了。两点都定了',+ createdAt: 120,+ id: 'SIG',// Tagged signal at stream_start — but it carries tools, so it is main-chain.metadata: {signal: { sourceToolCallId: 'bashwait', sourceToolName: 'Bash', type: 'task-completion' },} as any,- parentId: 'toolW', role: 'assistant', tools: toolArr('bash2'), updatedAt: 120,+ parentId: 'toolW',+ role: 'assistant',+ tools: toolArr('bash2'),+ updatedAt: 120,},{- content: 'ok', createdAt: 125, id: 'toolSig', parentId: 'SIG',- role: 'tool', tool_call_id: 'bash2', updatedAt: 125,+ content: 'ok',+ createdAt: 125,+ id: 'toolSig',+ parentId: 'SIG',+ role: 'tool',+ tool_call_id: 'bash2',+ updatedAt: 125,} as any,{- agentId: 'a', content: '现在给你完整判断', createdAt: 130, id: 'S2',- parentId: parentOfS2, role: 'assistant', tools: toolArr('bash3'), updatedAt: 130,+ agentId: 'a',+ content: '现在给你完整判断',+ createdAt: 130,+ id: 'S2',+ parentId: parentOfS2,+ role: 'assistant',+ tools: toolArr('bash3'),+ updatedAt: 130,},{- content: 'ok2', createdAt: 135, id: 'toolS2', parentId: 'S2',- role: 'tool', tool_call_id: 'bash3', updatedAt: 135,+ content: 'ok2',+ createdAt: 135,+ id: 'toolS2',+ parentId: 'S2',+ role: 'tool',+ tool_call_id: 'bash3',+ updatedAt: 135,} as any,{- agentId: 'a', content: 'TAILMARKER 两个开关都定位到了,完整方案', createdAt: 140,- id: 'TAIL', parentId: 'S2', role: 'assistant', updatedAt: 140,+ agentId: 'a',+ content: 'TAILMARKER 两个开关都定位到了,完整方案',+ createdAt: 140,+ id: 'TAIL',+ parentId: 'S2',+ role: 'assistant',+ updatedAt: 140,},];diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.tsindex 9b0e3cec9ea..f895eb71588 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts@@ -65,8 +65,7 @@ const normalizeErrorText = (value?: string) => value?.replaceAll(/\s+/g, ' ').tr*/const shouldSuppressTerminalErrorEcho = (content: string, errorData: unknown): boolean => {const body = errorData as- | { clearEchoedContent?: boolean; code?: string; message?: string; stderr?: string }- | undefined;+ { clearEchoedContent?: boolean; code?: string; message?: string; stderr?: string } | undefined;// Keep in sync with the interpreters' ECHO_TRIGGER_CODES.if (!body?.clearEchoedContent && body?.code !== 'AuthRequired') return false;const normalizedContent = normalizeErrorText(content);@@ -182,9 +181,7 @@ const streamInit = (state: MainAgentRunState, data: any): ReduceResult => {// provenance; `openTurn` owns it for every later turn. Only seed it once — a// later non-newStep stream_start must not clobber the open turn's id.const seedMainMessageId =- typeof data?.messageId === 'string' && !state.currentMainMessageId- ? data.messageId- : undefined;+ typeof data?.messageId === 'string' && !state.currentMainMessageId ? data.messageId : undefined;if (Object.keys(update).length === 0 && !seedMainMessageId) return { intents: [], state };diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 522fe9eb1ff..22e4f04c8df 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1410,6 +1410,7 @@ export default {'workingPanel.review.baseRef.loading': 'Loading branches…','workingPanel.review.baseRef.reset': 'Reset to default branch','workingPanel.review.baseRef.unresolved': 'Pick a base branch',+ 'workingPanel.review.addSelectionToContext.success': 'Added selected lines to context','workingPanel.review.binary': 'Binary file — diff not shown','workingPanel.review.collapseAll': 'Collapse all','workingPanel.review.copied': 'Path copied',diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex f5299d3696a..2665db7c2e2 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -30,6 +30,8 @@ export default {'workingDirectory.detachedHead': 'Detached HEAD at {{sha}}','workingDirectory.diffStatTooltip':'Added {{added}} · Modified {{modified}} · Deleted {{deleted}}',+ 'workingDirectory.diffLineStatTooltip':+ 'Added lines {{added}} · Deleted lines {{deleted}} · Changed files {{files}}','workingDirectory.filesAdded': 'Added','workingDirectory.filesDeleted': 'Deleted','workingDirectory.filesEmpty': 'No uncommitted changes',diff --git a/packages/prompts/src/agents/contextSelectionContext.ts b/packages/prompts/src/agents/contextSelectionContext.tsnew file mode 100644index 00000000000..a5f1d7c0eca--- /dev/null+++ b/packages/prompts/src/agents/contextSelectionContext.ts@@ -0,0 +1,54 @@+import type { ContextSelection } from '@lobechat/types';++import { escapeXmlAttr } from '../prompts/search/xmlEscape';++const formatLineRange = (selection: ContextSelection): string => {+ const range = selection.lineRange;+ if (!range) return '';++ return ` lines="${range.startLine}-${range.endLine ?? range.startLine}"`;+};++const formatSelectionAttributes = (selection: ContextSelection): string => {+ const attrs = [`source="${selection.source}"`];++ if (selection.title) attrs.push(`title="${escapeXmlAttr(selection.title)}"`);+ if (selection.source === 'page') attrs.push(`pageId="${escapeXmlAttr(selection.pageId)}"`);+ if (selection.source === 'code') {+ attrs.push(`filePath="${escapeXmlAttr(selection.filePath)}"`);+ if (selection.language) attrs.push(`language="${escapeXmlAttr(selection.language)}"`);+ if (selection.side) attrs.push(`side="${selection.side}"`);+ if (selection.workingDirectory) {+ attrs.push(`workingDirectory="${escapeXmlAttr(selection.workingDirectory)}"`);+ }+ }++ return `${attrs.join(' ')}${formatLineRange(selection)}`;+};++const getSelectionBody = (selection: ContextSelection): string => {+ if (selection.source === 'page') return selection.xml || selection.content;++ return selection.content;+};++/**+ * Format generic context selections into a system prompt context.+ * Each selection carries source metadata so non-page selections, such as code+ * diff lines, can be injected without overloading PageSelection.+ */+export const formatContextSelections = (selections: ContextSelection[]): string => {+ if (!selections || selections.length === 0) return '';++ const formattedSelections = selections+ .map(+ (selection) => `<context_selection ${formatSelectionAttributes(selection)}>+${getSelectionBody(selection)}+</context_selection>`,+ )+ .join('\n');++ return `<user_context_selections count="${selections.length}">+${formattedSelections}+</user_context_selections>`;+};diff --git a/packages/prompts/src/agents/index.ts b/packages/prompts/src/agents/index.tsindex 9a6ae87d44d..a88d6f6df35 100644--- a/packages/prompts/src/agents/index.ts+++ b/packages/prompts/src/agents/index.ts@@ -1,3 +1,4 @@export * from './agentSkillManager';+export * from './contextSelectionContext';export * from './pageContentContext';export * from './pageSelectionContext';diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex ba1d26acd82..83b2413a409 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -3,8 +3,8 @@ import { z } from 'zod';import type { UIChatMessage } from './message';import type { MessageMetadata } from './message/common';import { ChatToolPayloadSchema, MessageMetadataSchema } from './message/common';-import type { CreateMessageParams, PageSelection } from './message/ui/params';-import { PageSelectionSchema } from './message/ui/params';+import type { ContextSelection, CreateMessageParams, PageSelection } from './message/ui/params';+import { ContextSelectionSchema, PageSelectionSchema } from './message/ui/params';import type { OpenAIChatMessage } from './openai/chat';import type { LobeUniformTool } from './tool';import { LobeUniformToolSchema } from './tool';@@ -14,6 +14,8 @@ import { ThreadType } from './topic/thread';export interface SendNewMessage {content: string;+ /** Generic context selections attached to this message */+ contextSelections?: ContextSelection[];/** Lexical editor JSON state for rich text rendering */editorData?: Record<string, any>;// if message has attached with files, then add files to message and the agent@@ -145,6 +147,7 @@ export const AiSendMessageServerSchema = z.object({preloadMessages: z.array(SendPreloadMessageSchema).optional(),newUserMessage: z.object({content: z.string(),+ contextSelections: z.array(ContextSelectionSchema).optional(),editorData: z.record(z.unknown()).optional(),files: z.array(z.string()).optional(),metadata: MessageMetadataSchema.optional(),diff --git a/packages/types/src/message/common/contextSelection.ts b/packages/types/src/message/common/contextSelection.tsnew file mode 100644index 00000000000..1e51f34b405--- /dev/null+++ b/packages/types/src/message/common/contextSelection.ts@@ -0,0 +1,95 @@+import { z } from 'zod';++export const ContextSelectionFormatSchema = z.enum(['markdown', 'text', 'xml']);++export const ContextSelectionLineRangeSchema = z.object({+ endLine: z.number().optional(),+ startLine: z.number(),+});++export const ContextSelectionBaseSchema = z.object({+ content: z.string(),+ format: ContextSelectionFormatSchema.optional(),+ id: z.string(),+ lineRange: ContextSelectionLineRangeSchema.optional(),+ preview: z.string().optional(),+ title: z.string().optional(),+});++export interface ContextSelectionLineRange {+ endLine?: number;+ startLine: number;+}++export interface ContextSelectionBase {+ content: string;+ /**+ * Format of the content. Defaults to text.+ */+ format?: 'markdown' | 'text' | 'xml';+ id: string;+ lineRange?: ContextSelectionLineRange;+ /**+ * Optional short preview for displaying in UI.+ */+ preview?: string;+ title?: string;+}++export const PageContextSelectionSchema = ContextSelectionBaseSchema.extend({+ anchor: z+ .object({+ endNodeId: z.string(),+ endOffset: z.number(),+ startNodeId: z.string(),+ startOffset: z.number(),+ })+ .optional(),+ pageId: z.string(),+ source: z.literal('page'),+ xml: z.string().optional(),+});++export interface PageContextSelection extends ContextSelectionBase {+ anchor?: {+ endNodeId: string;+ endOffset: number;+ startNodeId: string;+ startOffset: number;+ };+ pageId: string;+ source: 'page';+ xml?: string;+}++export const CodeContextSelectionSchema = ContextSelectionBaseSchema.extend({+ filePath: z.string(),+ language: z.string().optional(),+ side: z.enum(['additions', 'context', 'deletions']).optional(),+ source: z.literal('code'),+ workingDirectory: z.string().optional(),+});++export interface CodeContextSelection extends ContextSelectionBase {+ filePath: string;+ language?: string;+ side?: 'additions' | 'context' | 'deletions';+ source: 'code';+ workingDirectory?: string;+}++export const TextContextSelectionSchema = ContextSelectionBaseSchema.extend({+ source: z.literal('text'),+});++export interface TextContextSelection extends ContextSelectionBase {+ source: 'text';+}++export const ContextSelectionSchema = z.discriminatedUnion('source', [+ PageContextSelectionSchema,+ CodeContextSelectionSchema,+ TextContextSelectionSchema,+]);++export type ContextSelection = PageContextSelection | CodeContextSelection | TextContextSelection;diff --git a/packages/types/src/message/common/index.ts b/packages/types/src/message/common/index.tsindex 6c6a75588b1..12ff9775a04 100644--- a/packages/types/src/message/common/index.ts+++ b/packages/types/src/message/common/index.ts@@ -1,4 +1,5 @@export * from './base';+export * from './contextSelection';export * from './image';export * from './messageGroup';export * from './metadata';diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex fca528791d3..eab66a68ef6 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -1,6 +1,8 @@import { z } from 'zod';import { RequestTrigger } from '../../agentRuntime';+import type { ContextSelection } from './contextSelection';+import { ContextSelectionSchema } from './contextSelection';import type { PageSelection } from './pageSelection';import { PageSelectionSchema } from './pageSelection';@@ -180,6 +182,7 @@ export const MessageTaskCallbackSchema = z.object({export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({collapsed: z.boolean().optional(),+ contextSelections: z.array(ContextSelectionSchema).optional(),// Hetero-agent (Claude Code) per-message provenance. Listed here so zod does// NOT strip them from writes going through UpdateMessageParamsSchema /// CreateMessageParamsSchema (the renderer executor's `messageService` path).@@ -262,6 +265,11 @@ export interface MessageMetadata {*/collapsed?: boolean;compare?: boolean;+ /**+ * Generic context selections attached to user messages.+ * Page selections remain mirrored in `pageSelections` for compatibility.+ */+ contextSelections?: ContextSelection[];/** @deprecated use the top-level message `usage` field instead */cost?: number;/** @deprecated use `metadata.performance` instead */diff --git a/packages/types/src/message/common/pageSelection.ts b/packages/types/src/message/common/pageSelection.tsindex 8fe492b356e..8ca2170114a 100644--- a/packages/types/src/message/common/pageSelection.ts+++ b/packages/types/src/message/common/pageSelection.ts@@ -1,10 +1,13 @@import { z } from 'zod';+import type { ContextSelectionBase } from './contextSelection';+import { ContextSelectionBaseSchema } from './contextSelection';+/*** Page selection represents a user-selected text region in a page/document.* Used for Ask AI functionality to persist selection context with user messages.*/-export interface PageSelection {+export interface PageSelection extends Omit<ContextSelectionBase, 'lineRange'> {anchor?: {startNodeId: string;endNodeId: string;@@ -25,11 +28,17 @@ export interface PageSelection {xml?: string;}-export const PageSelectionSchema = z.object({- id: z.string(),- content: z.string(),- xml: z.string().optional(),- pageId: z.string(),+export const PageSelectionSchema = ContextSelectionBaseSchema.omit({ lineRange: true }).extend({+ anchor: z+ .object({+ endNodeId: z.string(),+ endOffset: z.number(),+ startNodeId: z.string(),+ startOffset: z.number(),+ })+ .optional(),startLine: z.number().optional(),endLine: z.number().optional(),+ pageId: z.string(),+ xml: z.string().optional(),});diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex 9bc87863177..94151402a3b 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -5,6 +5,11 @@ import type { UploadFileItem } from '../../files';import type { MessageSemanticSearchChunk } from '../../rag';import type { ChatMessageError } from '../common/base';import { ChatMessageErrorSchema } from '../common/base';+import type {+ ContextSelection,+ ContextSelectionBase,+ ContextSelectionLineRange,+} from '../common/contextSelection';// Import for local useimport type { PageSelection } from '../common/pageSelection';import type { ChatPluginPayload } from '../common/tools';@@ -83,26 +88,25 @@ export interface CreateNewMessageParams {traceId?: string;}-export interface ChatContextContent {- content: string;- /**- * Format of the content. Defaults to text.- */- format?: 'xml' | 'text' | 'markdown';- id: string;- /**- * Page ID the selection belongs to (for page editor selections)- */+export interface ChatContextContent extends ContextSelectionBase {+ filePath?: string;+ language?: string;+ lineRange?: ContextSelectionLineRange;pageId?: string;- /**- * Optional short preview for displaying in UI.- */- preview?: string;- title?: string;+ side?: 'additions' | 'context' | 'deletions';+ source?: ContextSelection['source'];type: 'text';+ workingDirectory?: string;+ xml?: string;}// Re-export PageSelection from common for backwards compatibility+export type { CodeContextSelection, ContextSelection, PageContextSelection } from '../common';+export {+ CodeContextSelectionSchema,+ ContextSelectionSchema,+ PageContextSelectionSchema,+} from '../common';export type { PageSelection } from '../common/pageSelection';export { PageSelectionSchema } from '../common/pageSelection';@@ -112,6 +116,11 @@ export interface SendMessageParams {* @deprecated Use pageSelections instead for page editor selections*/contexts?: ChatContextContent[];+ /**+ * Generic context selections attached to the message.+ * Page selections and code selections should both be represented here.+ */+ contextSelections?: ContextSelection[];/*** create a thread* @deprecated Use ConversationContext.newThread instead@@ -145,7 +154,6 @@ export interface SendMessageParams {* Additional metadata for the message (e.g., mentioned users)*/metadata?: Record<string, any>;-onlyAddUserMessage?: boolean;/*** Page selections attached to the message (for Ask AI functionality)diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsxindex 2df97c39b19..e804d074abc 100644--- a/src/features/ChatInput/ControlBar/GitStatus.tsx+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx@@ -5,7 +5,7 @@ import { toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import isEqual from 'fast-deep-equal';import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucide-react';-import { memo, useCallback, useEffect, useState } from 'react';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import RingLoadingIcon from '@/components/RingLoading';@@ -17,8 +17,8 @@ import {useFetchGitAheadBehind,useFetchGitBranch,useFetchGitLinkedPR,- useFetchGitWorkingTreeStatus,useFetchGitWorktrees,+ useReviewPatches,} from '@/store/device';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -181,9 +181,11 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, dconst branch = branchData?.branch;const detached = branchData?.detached;const { data: prData, mutate: mutatePR } = useFetchGitLinkedPR(deviceId, path, branch, isGithub);- const { data: workingStatus, mutate: mutateWorkingStatus } = useFetchGitWorkingTreeStatus(- deviceId,+ const { data: reviewPatches, mutate: mutateReviewPatches } = useReviewPatches(path,+ 'unstaged',+ undefined,+ deviceId,);const { data: aheadBehind, mutate: mutateAheadBehind } = useFetchGitAheadBehind(deviceId, path);const { data: worktrees = [], mutate: mutateWorktrees } = useFetchGitWorktrees(deviceId, path);@@ -219,11 +221,11 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, dawait Promise.all([mutateBranch(),mutatePR(),- mutateWorkingStatus(),+ mutateReviewPatches(),mutateAheadBehind(),mutateWorktrees(),]);- }, [mutateBranch, mutatePR, mutateWorkingStatus, mutateAheadBehind, mutateWorktrees]);+ }, [mutateBranch, mutatePR, mutateReviewPatches, mutateAheadBehind, mutateWorktrees]);// Flip the displayed branch instantly on checkout. No revalidate here — the// switcher's onAfterCheckout reconciles once the checkout lands. The linked-PR@@ -325,6 +327,23 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d}}, [deviceId, path, pulling, pushing, refreshAfterSync, t]);+ const diffStats = useMemo(() => {+ const patches = [+ ...(reviewPatches?.patches ?? []),+ ...(reviewPatches?.submodules ?? []).flatMap((submodule) => submodule.patches),+ ];+ return patches.reduce(+ (acc, patch) => {+ acc.additions += patch.additions ?? 0;+ acc.deletions += patch.deletions ?? 0;+ acc.files += 1;+ return acc;+ },+ { additions: 0, deletions: 0, files: 0 },+ );+ }, [reviewPatches?.patches, reviewPatches?.submodules]);+ const hasChanges = diffStats.files > 0;+if (!branch) return null;const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;@@ -340,13 +359,11 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d? t('workingDirectory.ghMissing'): undefined;- const hasChanges = !!workingStatus && !workingStatus.clean;-const diffStatTooltip = hasChanges- ? t('workingDirectory.diffStatTooltip', {- added: workingStatus!.added,- deleted: workingStatus!.deleted,- modified: workingStatus!.modified,+ ? t('workingDirectory.diffLineStatTooltip', {+ added: diffStats.additions,+ deleted: diffStats.deletions,+ files: diffStats.files,}): undefined;@@ -393,8 +410,9 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, donAfterCheckout={() => {void mutateBranch();void mutatePR();- void mutateWorkingStatus();+ void mutateReviewPatches();void mutateAheadBehind();+ void mutateWorktrees();}}><Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>@@ -450,18 +468,18 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d);const diffNode = (() => {- if (!hasChanges || !workingStatus) return null;+ if (!hasChanges) return null;const diffButton = (<div className={styles.trigger} role="button" onClick={handleToggleReview}><span className={styles.diffStat}>- {workingStatus.added > 0 && (- <span className={styles.diffStatAdded}>+{workingStatus.added}</span>+ {diffStats.additions > 0 && (+ <span className={styles.diffStatAdded}>+{diffStats.additions}</span>)}- {workingStatus.modified > 0 && (- <span className={styles.diffStatModified}>±{workingStatus.modified}</span>+ {diffStats.deletions > 0 && (+ <span className={styles.diffStatDeleted}>-{diffStats.deletions}</span>)}- {workingStatus.deleted > 0 && (- <span className={styles.diffStatDeleted}>-{workingStatus.deleted}</span>+ {diffStats.additions === 0 && diffStats.deletions === 0 && diffStats.files > 0 && (+ <span className={styles.diffStatModified}>±{diffStats.files}</span>)}</span></div>diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsxindex 0bee5f8bba4..9a21cde02e7 100644--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx@@ -17,12 +17,12 @@ const gitHookMocks = vi.hoisted(() => ({mutateAheadBehind: vi.fn(),mutateBranch: vi.fn(),mutatePR: vi.fn(),- mutateWorkingTreeStatus: vi.fn(),+ mutateReviewPatches: vi.fn(),mutateWorktrees: vi.fn(),useFetchGitAheadBehind: vi.fn(),useFetchGitBranch: vi.fn(),useFetchGitLinkedPR: vi.fn(),- useFetchGitWorkingTreeStatus: vi.fn(),+ useReviewPatches: vi.fn(),useFetchGitWorktrees: vi.fn(),}));@@ -44,7 +44,7 @@ vi.mock('@/store/device', () => ({useFetchGitAheadBehind: gitHookMocks.useFetchGitAheadBehind,useFetchGitBranch: gitHookMocks.useFetchGitBranch,useFetchGitLinkedPR: gitHookMocks.useFetchGitLinkedPR,- useFetchGitWorkingTreeStatus: gitHookMocks.useFetchGitWorkingTreeStatus,+ useReviewPatches: gitHookMocks.useReviewPatches,useFetchGitWorktrees: gitHookMocks.useFetchGitWorktrees,}));@@ -126,9 +126,22 @@ beforeEach(() => {data: { pullRequest: null },mutate: gitHookMocks.mutatePR,});- gitHookMocks.useFetchGitWorkingTreeStatus.mockReturnValue({- data: { added: 1, clean: false, deleted: 0, modified: 2, total: 3 },- mutate: gitHookMocks.mutateWorkingTreeStatus,+ gitHookMocks.useReviewPatches.mockReturnValue({+ data: {+ mode: 'unstaged',+ patches: [+ {+ additions: 3,+ deletions: 1,+ filePath: 'src/example.ts',+ isBinary: false,+ patch: '',+ status: 'modified',+ truncated: false,+ },+ ],+ },+ mutate: gitHookMocks.mutateReviewPatches,});gitHookMocks.useFetchGitAheadBehind.mockReturnValue({data: undefined,@@ -144,6 +157,15 @@ describe('GitStatus', () => {it('opens the review panel when clicking remote device diff stats', () => {render(<GitStatus agentId="agent-1" deviceId="device-1" isGithub={false} path="/repo" />);+ expect(gitHookMocks.useReviewPatches).toHaveBeenCalledWith(+ '/repo',+ 'unstaged',+ undefined,+ 'device-1',+ );+ expect(screen.getByText('+3')).toBeInTheDocument();+ expect(screen.getByText('-1')).toBeInTheDocument();+fireEvent.click(screen.getByRole('button'));expect(globalStoreMock.setWorkingSidebarTab).toHaveBeenCalledWith('review');diff --git a/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx b/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsxindex 377d154a40e..c01bb83b939 100644--- a/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx@@ -1,12 +1,57 @@-import { type ChatContextContent } from '@lobechat/types';+import type { ChatContextContent } from '@lobechat/types';import { Tag, Tooltip } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';-import { TextIcon } from 'lucide-react';+import { createStaticStyles, cssVar } from 'antd-style';+import { Code2Icon, TextIcon } from 'lucide-react';import { memo, useMemo } from 'react';import { useFileStore } from '@/store/file';const styles = createStaticStyles(({ css }) => ({+ codeLine: css`+ display: grid;+ grid-template-columns: 36px minmax(0, 1fr);+ gap: 10px;+ `,+ codePreview: css`+ overflow: auto;++ max-width: min(560px, 80vw);+ max-height: 220px;+ margin: 0;+ padding-block: 8px;+ padding-inline: 0;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ line-height: 1.55;+ `,+ content: css`+ overflow: hidden;++ min-width: 0;++ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: pre;+ `,+ lineNumber: css`+ user-select: none;+ color: ${cssVar.colorTextQuaternary};+ text-align: end;+ `,+ meta: css`+ overflow: hidden;++ max-width: min(560px, 80vw);+ padding-block-end: 6px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,name: css`overflow: hidden;flex: 1;@@ -16,9 +61,19 @@ const styles = createStaticStyles(({ css }) => ({text-overflow: ellipsis;white-space: nowrap;`,+ textPreview: css`+ max-width: min(420px, 70vw);+ color: ${cssVar.colorText};+ white-space: pre-wrap;+ `,+ truncated: css`+ padding-block-start: 4px;+ color: ${cssVar.colorTextQuaternary};+ `,}));const MAX_PREVIEW_LENGTH = 8;+const MAX_CODE_PREVIEW_LINES = 8;const getPreviewText = (content?: string, fallback?: string) => {const source = content || fallback || '';@@ -33,19 +88,76 @@ const getPreviewText = (content?: string, fallback?: string) => {return plain.length > MAX_PREVIEW_LENGTH ? `${plain.slice(0, MAX_PREVIEW_LENGTH)}...` : plain;};-const SelectionItem = memo<ChatContextContent>(({ preview, id }) => {- const [removeSelection] = useFileStore((s) => [s.removeChatContextSelection]);+const getLocationText = ({+ filePath,+ lineRange,+ title,+}: Pick<ChatContextContent, 'filePath' | 'lineRange' | 'title'>) => {+ const location = filePath || title;+ if (!location) return;++ if (!lineRange) return location;++ const endLine = lineRange.endLine ?? lineRange.startLine;+ return `${location}:${lineRange.startLine}-${endLine}`;+};++const SelectionItem = memo<ChatContextContent>(+ ({ content, filePath, id, lineRange, preview, source, title }) => {+ const [removeSelection] = useFileStore((s) => [s.removeChatContextSelection]);++ const displayText = useMemo(+ () => getPreviewText(preview || getLocationText({ filePath, lineRange, title }), content),+ [content, filePath, lineRange, preview, title],+ );+ const isCodeSelection = source === 'code' || Boolean(filePath);++ const tooltip = useMemo(() => {+ if (!isCodeSelection) {+ return <div className={styles.textPreview}>{preview || content}</div>;+ }++ const lines = content.split('\n');+ const previewLines = lines.slice(0, MAX_CODE_PREVIEW_LINES);+ const startLine = lineRange?.startLine ?? 1;- const displayText = useMemo(() => getPreviewText(preview), [preview]);+ return (+ <div>+ <div className={styles.meta}>+ {getLocationText({ filePath, lineRange, title }) || preview || title}+ </div>+ <pre className={styles.codePreview}>+ {previewLines.map((line, index) => (+ <div className={styles.codeLine} key={`${index}-${line}`}>+ <span className={styles.lineNumber}>{startLine + index}</span>+ <code className={styles.content}>{line || ' '}</code>+ </div>+ ))}+ {lines.length > MAX_CODE_PREVIEW_LINES && (+ <div className={`${styles.codeLine} ${styles.truncated}`}>+ <span className={styles.lineNumber}>...</span>+ <code className={styles.content}>...</code>+ </div>+ )}+ </pre>+ </div>+ );+ }, [content, filePath, isCodeSelection, lineRange, preview, title]);- return (- <Tag closable icon={<TextIcon size={16} />} size={'large'} onClose={() => removeSelection(id)}>- <Tooltip title={preview}>- <span className={styles.name}>{displayText}</span>- </Tooltip>- </Tag>- );-});+ return (+ <Tag+ closable+ icon={isCodeSelection ? <Code2Icon size={16} /> : <TextIcon size={16} />}+ size={'large'}+ onClose={() => removeSelection(id)}+ >+ <Tooltip title={tooltip}>+ <span className={styles.name}>{displayText}</span>+ </Tooltip>+ </Tag>+ );+ },+);SelectionItem.displayName = 'SelectionItem';diff --git a/src/features/ChatInput/utils/contextSelections.test.ts b/src/features/ChatInput/utils/contextSelections.test.tsnew file mode 100644index 00000000000..98ee74ba5d2--- /dev/null+++ b/src/features/ChatInput/utils/contextSelections.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';++import { buildMessageContextSelections } from './contextSelections';++describe('buildMessageContextSelections', () => {+ it('derives generic and legacy selections for page context', () => {+ const result = buildMessageContextSelections([+ {+ content: '<p>Selected paragraph</p>',+ format: 'xml',+ id: 'sel-1',+ pageId: 'page-1',+ preview: 'Selected paragraph',+ title: 'Selection',+ type: 'text',+ },+ ]);++ expect(result.contextSelections).toEqual([+ expect.objectContaining({+ content: 'Selected paragraph',+ id: 'sel-1',+ pageId: 'page-1',+ source: 'page',+ xml: '<p>Selected paragraph</p>',+ }),+ ]);+ expect(result.pageSelections).toEqual([+ expect.objectContaining({+ content: 'Selected paragraph',+ id: 'sel-1',+ pageId: 'page-1',+ xml: '<p>Selected paragraph</p>',+ }),+ ]);+ });++ it('keeps code context out of legacy page selections', () => {+ const result = buildMessageContextSelections([+ {+ content: 'const value = 1;',+ filePath: 'src/example.ts',+ id: 'code-1',+ language: 'ts',+ lineRange: { endLine: 12, startLine: 12 },+ side: 'additions',+ source: 'code',+ type: 'text',+ },+ ]);++ expect(result.contextSelections).toEqual([+ expect.objectContaining({+ content: 'const value = 1;',+ filePath: 'src/example.ts',+ language: 'ts',+ lineRange: { endLine: 12, startLine: 12 },+ side: 'additions',+ source: 'code',+ }),+ ]);+ expect(result.pageSelections).toEqual([]);+ });+});diff --git a/src/features/ChatInput/utils/contextSelections.ts b/src/features/ChatInput/utils/contextSelections.tsnew file mode 100644index 00000000000..fea3c6ac62f--- /dev/null+++ b/src/features/ChatInput/utils/contextSelections.ts@@ -0,0 +1,74 @@+import type { ChatContextContent, ContextSelection, PageSelection } from '@lobechat/types';++export interface MessageContextSelections {+ contextSelections: ContextSelection[];+ pageSelections: PageSelection[];+}++const toPageSelection = (context: ChatContextContent): PageSelection | undefined => {+ if (!context.pageId) return;++ return {+ content: context.preview || context.content,+ format: context.format,+ id: context.id,+ pageId: context.pageId,+ preview: context.preview,+ title: context.title,+ xml: context.xml || context.content,+ };+};++const toContextSelection = (context: ChatContextContent): ContextSelection => {+ if (context.source === 'code' || context.filePath) {+ return {+ content: context.content,+ filePath: context.filePath || '',+ format: context.format,+ id: context.id,+ language: context.language,+ lineRange: context.lineRange,+ preview: context.preview,+ side: context.side,+ source: 'code',+ title: context.title,+ workingDirectory: context.workingDirectory,+ };+ }++ if (context.pageId) {+ return {+ content: context.preview || context.content,+ format: context.format,+ id: context.id,+ lineRange: context.lineRange,+ pageId: context.pageId,+ preview: context.preview,+ source: 'page',+ title: context.title,+ xml: context.xml || context.content,+ };+ }++ return {+ content: context.content,+ format: context.format,+ id: context.id,+ lineRange: context.lineRange,+ preview: context.preview,+ source: 'text',+ title: context.title,+ };+};++export const buildMessageContextSelections = (+ contexts: ChatContextContent[],+): MessageContextSelections => {+ const contextSelections = contexts.map(toContextSelection);+ const pageSelections = contexts.flatMap((context) => {+ const pageSelection = toPageSelection(context);+ return pageSelection ? [pageSelection] : [];+ });++ return { contextSelections, pageSelections };+};diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 47896650e2b..e2e4bdee0d1 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -29,6 +29,7 @@ import { selectCurrentTurnTodosFromMessages } from '@/store/chat/slices/message/import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { fileChatSelectors, useFileStore } from '@/store/file';+import { buildMessageContextSelections } from '../../ChatInput/utils/contextSelections';import WideScreenContainer from '../../WideScreenContainer';import InterventionBar from '../InterventionBar';import { dataSelectors, messageStateSelectors, useConversationStore } from '../store';@@ -357,16 +358,17 @@ const ChatInput = memo<ChatInputProps>(fileStore.clearChatUploadFileList();fileStore.clearChatContextSelections();- // Convert ChatContextContent to PageSelection for persistence- const pageSelections = currentContextList.map((ctx) => ({- content: ctx.preview || '',- id: ctx.id,- pageId: ctx.pageId || '',- xml: ctx.content,- }));+ const { contextSelections, pageSelections } =+ buildMessageContextSelections(currentContextList);// Fire and forget - send with captured message- await sendMessage({ editorData, files: currentFileList, message, pageSelections });+ await sendMessage({+ contextSelections,+ editorData,+ files: currentFileList,+ message,+ pageSelections,+ });},[sendMessage, disableQueue, disableSend, isInputQueueBlocked],);diff --git a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx b/src/features/Conversation/Messages/User/components/MessageContent.test.tsxindex c57acd7ae11..d058d5517ae 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx@@ -23,9 +23,6 @@ vi.mock('./FileListViewer', () => ({vi.mock('./ImageFileListViewer', () => ({default: () => null,}));-vi.mock('./PageSelections', () => ({- default: () => null,-}));vi.mock('./VideoFileListViewer', () => ({default: () => null,}));@@ -79,4 +76,31 @@ describe('User MessageContent', () => {expect(screen.getByTestId('audio-viewer')).toHaveTextContent('1');});++ it('should render code context selections in the user message body', () => {+ render(+ <MessageContent+ content={'What does this selected code do?'}+ createdAt={Date.now()}+ id={'msg-4'}+ role={'user'}+ updatedAt={Date.now()}+ metadata={{+ contextSelections: [+ {+ content: 'const answer = 42;',+ filePath: 'src/example.ts',+ id: 'selection-1',+ lineRange: { endLine: 7, startLine: 7 },+ source: 'code',+ },+ ],+ }}+ />,+ );++ expect(screen.getByText('src/example.ts:7-7')).toBeInTheDocument();+ expect(screen.getByText('const answer = 42;')).toBeInTheDocument();+ expect(screen.getByText('What does this selected code do?')).toBeInTheDocument();+ });});diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsxindex 0977ede1a83..d710c237cc7 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx@@ -17,7 +17,9 @@ import VideoFileListViewer from './VideoFileListViewer';const UserMessageContent = memo<UIChatMessage>(({ id, content, editorData, imageList, videoList, audioList, fileList, metadata }) => {const markdownProps = useMarkdown(id);- const pageSelections = metadata?.pageSelections;+ const selections = metadata?.contextSelections?.length+ ? metadata.contextSelections+ : metadata?.pageSelections;const displayContent = useMemo(() => (content ? cleanSpeakerTag(content) : content), [content]);const hasEditorData =@@ -31,9 +33,7 @@ const UserMessageContent = memo<UIChatMessage>(return (<Flexbox gap={8} id={id}>- {pageSelections && pageSelections.length > 0 && (- <PageSelections selections={pageSelections} />- )}+ {selections && selections.length > 0 && <PageSelections selections={selections} />}{textBody && <CollapsibleContent>{textBody}</CollapsibleContent>}{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}{videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}diff --git a/src/features/Conversation/Messages/User/components/PageSelections.test.tsx b/src/features/Conversation/Messages/User/components/PageSelections.test.tsxnew file mode 100644index 00000000000..b09e0e065b7--- /dev/null+++ b/src/features/Conversation/Messages/User/components/PageSelections.test.tsx@@ -0,0 +1,42 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import PageSelections from './PageSelections';++describe('PageSelections', () => {+ it('renders code selections with file line metadata and code content', () => {+ render(+ <PageSelections+ selections={[+ {+ content: 'const answer = 42;',+ filePath: 'src/example.ts',+ id: 'selection-1',+ lineRange: { endLine: 7, startLine: 7 },+ source: 'code',+ },+ ]}+ />,+ );++ expect(screen.getByText('src/example.ts:7-7')).toBeInTheDocument();+ expect(screen.getByText('const answer = 42;')).toBeInTheDocument();+ });++ it('keeps text selections in quote style without synthetic metadata', () => {+ render(+ <PageSelections+ selections={[+ {+ content: 'selected paragraph',+ id: 'selection-1',+ pageId: 'page-1',+ },+ ]}+ />,+ );++ expect(screen.getByText('selected paragraph')).toBeInTheDocument();+ expect(screen.queryByText('page-1')).not.toBeInTheDocument();+ });+});diff --git a/src/features/Conversation/Messages/User/components/PageSelections.tsx b/src/features/Conversation/Messages/User/components/PageSelections.tsxindex f46133b831a..ddfb726da36 100644--- a/src/features/Conversation/Messages/User/components/PageSelections.tsx+++ b/src/features/Conversation/Messages/User/components/PageSelections.tsx@@ -1,10 +1,62 @@import { Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';+import { Code2Icon } from 'lucide-react';import { memo } from 'react';-import { type PageSelection } from '@/types/index';+import type { ContextSelection, PageSelection } from '@/types/index';++type UserContextSelection = ContextSelection | PageSelection;const styles = createStaticStyles(({ css, cssVar }) => ({+ codeContainer: css`+ cursor: pointer;++ overflow: hidden;++ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 8px;++ background: ${cssVar.colorFillQuaternary};++ :hover {+ border-color: ${cssVar.colorBorder};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ codeContent: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 4;++ margin: 0;+ padding-block: 8px;+ padding-inline: 10px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ line-height: 1.55;+ color: ${cssVar.colorTextSecondary};+ white-space: pre;+ `,+ codeHeader: css`+ overflow: hidden;+ align-items: center;++ padding-block: 6px;+ padding-inline: 10px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ color: ${cssVar.colorTextTertiary};+ `,+ codeMeta: css`+ overflow: hidden;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,container: css`cursor: pointer;position: relative;@@ -38,22 +90,63 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface PageSelectionsProps {- selections: PageSelection[];+ selections: UserContextSelection[];}+const isContextSelection = (selection: UserContextSelection): selection is ContextSelection =>+ 'source' in selection;++const isCodeSelection = (selection: UserContextSelection): selection is ContextSelection =>+ isContextSelection(selection) && selection.source === 'code';++const getCodeSelectionMeta = (selection: ContextSelection): string => {+ if (selection.source !== 'code') return selection.title || '';++ const lineRange = selection.lineRange+ ? `:${selection.lineRange.startLine}-${selection.lineRange.endLine ?? selection.lineRange.startLine}`+ : '';++ return `${selection.filePath}${lineRange}`;+};++const CodeSelection = memo<{ selection: ContextSelection }>(({ selection }) => (+ <Flexbox className={styles.codeContainer}>+ <Flexbox horizontal className={styles.codeHeader} gap={6}>+ <Code2Icon size={14} />+ <div className={styles.codeMeta}>{getCodeSelectionMeta(selection)}</div>+ </Flexbox>+ <pre className={styles.codeContent}>{selection.content}</pre>+ </Flexbox>+));++CodeSelection.displayName = 'UserMessageCodeSelection';++const QuoteSelection = memo<{ selection: UserContextSelection }>(({ selection }) => (+ <Flexbox className={styles.container}>+ <Flexbox horizontal className={styles.wrapper} gap={4} padding={4}>+ <span className={styles.quote}>"</span>+ <div className={styles.content}>{selection.content}</div>+ </Flexbox>+ </Flexbox>+));++QuoteSelection.displayName = 'UserMessageQuoteSelection';++const SelectionItem = memo<{ selection: UserContextSelection }>(({ selection }) => {+ if (isCodeSelection(selection)) return <CodeSelection selection={selection} />;++ return <QuoteSelection selection={selection} />;+});++SelectionItem.displayName = 'UserMessageSelectionItem';+const PageSelections = memo<PageSelectionsProps>(({ selections }) => {if (!selections || selections.length === 0) return null;return (<Flexbox gap={8}>{selections.map((selection) => (- <Flexbox className={styles.container} key={selection.id}>- <Flexbox horizontal className={styles.wrapper} gap={4} padding={4}>- {}- <span className={styles.quote}>"</span>- <div className={styles.content}>{selection.content}</div>- </Flexbox>- </Flexbox>+ <SelectionItem key={selection.id} selection={selection} />))}</Flexbox>);diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsxindex e6ffedf76c5..9c52ddab3c6 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileItem.tsx@@ -1,18 +1,23 @@'use client';import type { GitFileDiffStatus } from '@lobechat/electron-client-ipc';+import { nanoid } from '@lobechat/utils';import { ActionIcon, copyToClipboard, Flexbox, PatchDiff } from '@lobehub/ui';import { confirmModal } from '@lobehub/ui/base-ui';-import { createStaticStyles } from 'antd-style';+import { createStaticStyles, cssVar as themeCssVar } from 'antd-style';import { CopyIcon, LocateFixedIcon, Undo2Icon } from 'lucide-react';import path from 'path-browserify-esm';-import { memo, type MouseEvent, useCallback } from 'react';+import { memo, type MouseEvent, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { message } from '@/components/AntdStaticMethods';import { gitService } from '@/services/git';+import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';+import type { DiffSelectedLineRange } from './selection';+import { buildCodeContextSelection } from './selection';+const styles = createStaticStyles(({ css, cssVar }) => ({additions: css`color: ${cssVar.colorSuccess};@@ -112,6 +117,56 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));+const reviewDiffUnsafeCSS = `+ :host {+ --diffs-dark-bg: transparent !important;+ --diffs-light-bg: transparent !important;+ --diffs-gap-fallback: 8px;+ --diffs-added-light: ${themeCssVar.colorSuccessHover};+ --diffs-added-dark: ${themeCssVar.colorSuccessBorderHover};+ --diffs-modified-light: ${themeCssVar.colorInfoHover};+ --diffs-modified-dark: ${themeCssVar.colorInfoBorderHover};+ --diffs-deleted-light: ${themeCssVar.colorErrorHover};+ --diffs-deleted-dark: ${themeCssVar.colorErrorBorderHover};+ }++ [data-gutter-buffer] {+ opacity: 0.2 !important;+ }++ [data-code] {+ padding-top: 0 !important;+ padding-bottom: 0 !important;+ }++ [data-gutter] {+ backdrop-filter: blur(16px) !important;+ }++ [data-utility-button] {+ width: 16px !important;+ min-width: 16px !important;+ height: 16px !important;+ margin-right: calc(1ch - 8px) !important;+ border: 1px solid ${themeCssVar.colorBorderSecondary} !important;+ border-radius: 50% !important;+ background: ${themeCssVar.colorBgContainer} !important;+ color: ${themeCssVar.colorTextSecondary} !important;+ box-shadow: 0 2px 8px ${themeCssVar.colorFillSecondary} !important;+ }++ [data-utility-button]:hover {+ border-color: ${themeCssVar.colorPrimary} !important;+ background: ${themeCssVar.colorPrimaryBg} !important;+ color: ${themeCssVar.colorPrimary} !important;+ }++ [data-utility-button] [data-icon] {+ width: 10px !important;+ height: 10px !important;+ }+`;+interface FileItemHeaderProps {additions: number;deletions: number;@@ -257,11 +312,55 @@ interface FileItemBodyProps {truncated: boolean;viewMode: 'unified' | 'split';wordWrap: boolean;+ workingDirectory: string;}const FileItemBody = memo<FileItemBodyProps>(- ({ filePath, patch, isBinary, truncated, expanded, viewMode, wordWrap, textDiff }) => {+ ({+ filePath,+ patch,+ isBinary,+ truncated,+ expanded,+ viewMode,+ workingDirectory,+ wordWrap,+ textDiff,+ }) => {const { t } = useTranslation('chat');+ const addChatContextSelection = useFileStore((s) => s.addChatContextSelection);+ const fileName = path.basename(filePath);+ const ext = path.extname(filePath).slice(1).toLowerCase();+ const language = ext || undefined;++ const diffOptions = useMemo(+ () => ({+ enableGutterUtility: true,+ enableLineSelection: true,+ lineDiffType: textDiff ? ('word-alt' as const) : ('none' as const),+ onGutterUtilityClick: (range: DiffSelectedLineRange) => {+ const selection = buildCodeContextSelection({+ filePath,+ language,+ patch,+ range,+ workingDirectory,+ });++ if (!selection) return;++ addChatContextSelection({+ ...selection,+ id: `code-selection-${nanoid(6)}`,+ type: 'text',+ });+ message.success(t('workingPanel.review.addSelectionToContext.success'));+ },+ overflow: wordWrap ? ('wrap' as const) : ('scroll' as const),+ unsafeCSS: reviewDiffUnsafeCSS,+ }),+ [addChatContextSelection, filePath, language, patch, t, textDiff, wordWrap, workingDirectory],+ );if (!expanded) return null;@@ -269,21 +368,15 @@ const FileItemBody = memo<FileItemBodyProps>(if (truncated) return <div className={styles.empty}>{t('workingPanel.review.tooLarge')}</div>;if (!patch) return <div className={styles.empty}>{t('workingPanel.review.error')}</div>;- const fileName = path.basename(filePath);- const ext = path.extname(filePath).slice(1).toLowerCase();-return (<PatchDiff+ diffOptions={diffOptions}fileName={fileName}- language={ext || undefined}+ language={language}patch={patch}showHeader={false}variant={'borderless'}viewMode={viewMode}- diffOptions={{- lineDiffType: textDiff ? 'word-alt' : 'none',- overflow: wordWrap ? 'wrap' : 'scroll',- }}/>);},diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsxindex 3f3122ae74c..23b924941cf 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/FileRow.tsx@@ -155,6 +155,7 @@ const FileRow = memo<FileRowProps>(truncated={entry.truncated}viewMode={viewMode}wordWrap={wordWrap}+ workingDirectory={repoAbsolutePath}/></m.div>)}diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsxindex 8d7016c9407..e20125b9536 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx@@ -20,7 +20,7 @@ import {WrapTextIcon,} from 'lucide-react';import path from 'path-browserify-esm';-import { Fragment, memo, useMemo, useRef, useState } from 'react';+import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';@@ -31,7 +31,12 @@ import FileRow from './FileRow';import FileTreeNav from './FileTreeNav';import GroupHeader from './GroupHeader';import { itemKey } from './reviewTreeNodes';-import { type ReviewMode, useGitRemoteBranches, useReviewPatches } from './useReviewPatches';+import {+ invalidateGitReviewCaches,+ type ReviewMode,+ useGitRemoteBranches,+ useReviewPatches,+} from './useReviewPatches';interface RepoGroup {absolutePath: string;@@ -49,6 +54,7 @@ const REVIEW_MODE_STORAGE_KEY = 'lobechat-review-mode';const BASE_REF_OVERRIDES_STORAGE_KEY = 'lobechat-review-base-overrides';interface ReviewProps {+ active: boolean;/*** Target device the working directory lives on. Undefined for local desktop;* set for a remote / web-bound device so git ops route through the device RPCs.@@ -218,7 +224,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const Review = memo<ReviewProps>(({ deviceId, onToggleTree, showTree, workingDirectory }) => {+const Review = memo<ReviewProps>(({ active, deviceId, onToggleTree, showTree, workingDirectory }) => {const { t } = useTranslation('chat');const [mode, setMode] = useLocalStorageState<ReviewMode>(REVIEW_MODE_STORAGE_KEY, 'unstaged');// Per-repo base-ref override — when set, the branch diff compares against@@ -238,12 +244,28 @@ const Review = memo<ReviewProps>(({ deviceId, onToggleTree, showTree, workingDir});};- const { data, isLoading, isValidating, mutate } = useReviewPatches(+ const { data, isLoading, isValidating } = useReviewPatches(workingDirectory,mode,baseOverride,deviceId,+ active,+ );+ const invalidateReviewData = useCallback(+ async () =>+ invalidateGitReviewCaches({+ baseRef: baseOverride,+ deviceId,+ dirPath: workingDirectory,+ mode,+ }),+ [baseOverride, deviceId, mode, workingDirectory],);++ useEffect(() => {+ if (!active) return;+ void invalidateReviewData();+ }, [active, invalidateReviewData]);// Lazy: only fetch remote branches list once the user opens the picker.const [basePickerOpen, setBasePickerOpen] = useState(false);const { data: remoteBranches } = useGitRemoteBranches(@@ -406,7 +428,7 @@ const Review = memo<ReviewProps>(({ deviceId, onToggleTree, showTree, workingDiricon: <RefreshCwIcon size={14} />,key: 'refresh',label: t('workingPanel.review.refresh'),- onClick: () => void mutate(),+ onClick: () => void invalidateReviewData(),},{ type: 'divider' },{@@ -649,7 +671,7 @@ const Review = memo<ReviewProps>(({ deviceId, onToggleTree, showTree, workingDirtextDiff={textDiff}viewMode={viewMode}wordWrap={wordWrap}- onReverted={() => void mutate()}+ onReverted={() => void invalidateReviewData()}onToggle={() => toggleFileKey(key)}/>);diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/selection.test.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/selection.test.tsnew file mode 100644index 00000000000..3df61c5f217--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/selection.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import { buildCodeContextSelection } from './selection';++const patch = `@@ -8,5 +8,6 @@+ keep before+-old line++new line++another new line+ keep after`;++describe('buildCodeContextSelection', () => {+ it('builds a code context selection from selected additions', () => {+ const selection = buildCodeContextSelection({+ filePath: 'src/example.ts',+ language: 'ts',+ patch,+ range: { end: 10, side: 'additions', start: 9 },+ workingDirectory: '/repo',+ });++ expect(selection).toEqual({+ content: 'new line\nanother new line',+ filePath: 'src/example.ts',+ language: 'ts',+ lineRange: { endLine: 10, startLine: 9 },+ preview: 'src/example.ts:9-10',+ side: 'additions',+ source: 'code',+ title: 'src/example.ts:9-10',+ workingDirectory: '/repo',+ });+ });++ it('builds a code context selection from selected deletions', () => {+ const selection = buildCodeContextSelection({+ filePath: 'src/example.ts',+ patch,+ range: { end: 9, side: 'deletions', start: 9 },+ workingDirectory: '/repo',+ });++ expect(selection).toMatchObject({+ content: 'old line',+ lineRange: { endLine: 9, startLine: 9 },+ side: 'deletions',+ source: 'code',+ });+ });++ it('preserves context lines when selected from either side', () => {+ const selection = buildCodeContextSelection({+ filePath: 'src/example.ts',+ patch,+ range: { end: 11, side: 'additions', start: 11 },+ workingDirectory: '/repo',+ });++ expect(selection).toMatchObject({+ content: 'keep after',+ lineRange: { endLine: 11, startLine: 11 },+ side: 'context',+ source: 'code',+ });+ });+});diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/selection.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/selection.tsnew file mode 100644index 00000000000..e687929147b--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/selection.ts@@ -0,0 +1,176 @@+import type { ChatContextContent } from '@lobechat/types';++type DiffSelectionSide = 'additions' | 'deletions';+type CodeSelectionSide = ChatContextContent['side'];++export interface DiffSelectedLineRange {+ end: number;+ endSide?: DiffSelectionSide;+ side?: DiffSelectionSide;+ start: number;+}++interface ParsedDiffLine {+ content: string;+ lineNumber: number;+ order: number;+ selectionSide: DiffSelectionSide;+ side: CodeSelectionSide;+}++interface BuildCodeContextSelectionParams {+ filePath: string;+ language?: string;+ patch: string;+ range: DiffSelectedLineRange;+ workingDirectory: string;+}++const hunkHeaderRegExp = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;++const getRangeSideSet = (range: DiffSelectedLineRange): Set<DiffSelectionSide> => {+ const sides = new Set<DiffSelectionSide>();+ if (range.side) sides.add(range.side);+ if (range.endSide) sides.add(range.endSide);++ if (sides.size === 0) {+ sides.add('additions');+ sides.add('deletions');+ }++ return sides;+};++const parsePatchLines = (patch: string): ParsedDiffLine[] => {+ const lines: ParsedDiffLine[] = [];+ let oldLine = 0;+ let newLine = 0;+ let order = 0;++ for (const rawLine of patch.split('\n')) {+ const hunkMatch = hunkHeaderRegExp.exec(rawLine);+ if (hunkMatch) {+ oldLine = Number(hunkMatch[1]);+ newLine = Number(hunkMatch[2]);+ continue;+ }++ if (rawLine.startsWith('---') || rawLine.startsWith('+++') || rawLine.startsWith('\\')) {+ continue;+ }++ const marker = rawLine[0];+ const content = marker === ' ' || marker === '+' || marker === '-' ? rawLine.slice(1) : rawLine;++ switch (marker) {+ case '+': {+ lines.push({+ content,+ lineNumber: newLine,+ order: order++,+ selectionSide: 'additions',+ side: 'additions',+ });+ newLine += 1;+ break;+ }++ case '-': {+ lines.push({+ content,+ lineNumber: oldLine,+ order: order++,+ selectionSide: 'deletions',+ side: 'deletions',+ });+ oldLine += 1;+ break;+ }++ case ' ': {+ lines.push(+ {+ content,+ lineNumber: oldLine,+ order,+ selectionSide: 'deletions',+ side: 'context',+ },+ {+ content,+ lineNumber: newLine,+ order,+ selectionSide: 'additions',+ side: 'context',+ },+ );+ order += 1;+ oldLine += 1;+ newLine += 1;+ break;+ }+ }+ }++ return lines;+};++const getCommonSide = (lines: ParsedDiffLine[]): CodeSelectionSide | undefined => {+ const [firstLine] = lines;+ if (!firstLine) return;++ return lines.every((line) => line.side === firstLine.side) ? firstLine.side : undefined;+};++export const buildCodeContextSelection = ({+ filePath,+ language,+ patch,+ range,+ workingDirectory,+}: BuildCodeContextSelectionParams): Omit<ChatContextContent, 'id' | 'type'> | undefined => {+ const start = Math.min(range.start, range.end);+ const end = Math.max(range.start, range.end);+ const sides = getRangeSideSet(range);+ const selectedLines = parsePatchLines(patch)+ .filter(+ (line) => sides.has(line.selectionSide) && line.lineNumber >= start && line.lineNumber <= end,+ )+ .sort((a, b) => a.order - b.order || a.lineNumber - b.lineNumber);++ if (selectedLines.length === 0) return;++ const dedupedLines = selectedLines.filter((line, index, lines) => {+ const previous = lines[index - 1];+ return (+ !previous ||+ previous.order !== line.order ||+ previous.content !== line.content ||+ previous.lineNumber !== line.lineNumber+ );+ });++ const lineNumbers = dedupedLines.map((line) => line.lineNumber);+ const lineRange = {+ endLine: Math.max(...lineNumbers),+ startLine: Math.min(...lineNumbers),+ };+ const content = dedupedLines+ .map((line) => line.content)+ .join('\n')+ .trimEnd();++ if (!content.trim()) return;++ return {+ content,+ filePath,+ language,+ lineRange,+ preview: `${filePath}:${lineRange.startLine}-${lineRange.endLine}`,+ side: getCommonSide(dedupedLines),+ source: 'code',+ title: `${filePath}:${lineRange.startLine}-${lineRange.endLine}`,+ workingDirectory,+ };+};diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.tsnew file mode 100644index 00000000000..25031458d3e--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.test.ts@@ -0,0 +1,81 @@+import { mutate, useClientDataSWR } from '@/libs/swr';++import {+ getReviewRefreshInterval,+ invalidateGitReviewCaches,+ useReviewPatches,+} from './useReviewPatches';++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ data: undefined })),+}));++vi.mock('@/services/git', () => ({+ gitService: {+ getGitBranchDiff: vi.fn(),+ getGitWorkingTreePatches: vi.fn(),+ listGitRemoteBranches: vi.fn(),+ },+}));++describe('useReviewPatches', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('polls while the review tab is active and disables polling while hidden', () => {+ expect(getReviewRefreshInterval('unstaged', true)).toBe(10_000);+ expect(getReviewRefreshInterval('branch', true)).toBe(30_000);+ expect(getReviewRefreshInterval('unstaged', false)).toBe(0);++ useReviewPatches('/repo', 'unstaged', undefined, undefined, true);++ expect(useClientDataSWR).toHaveBeenCalledWith(+ ['device:gitReviewPatches', 'local', '/repo', 'unstaged', ''],+ expect.any(Function),+ expect.objectContaining({+ refreshInterval: 10_000,+ refreshWhenHidden: false,+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+ }),+ );++ vi.clearAllMocks();++ useReviewPatches('/repo', 'branch', 'origin/canary', 'device-1', false);++ expect(useClientDataSWR).toHaveBeenCalledWith(+ null,+ expect.any(Function),+ expect.objectContaining({+ refreshInterval: 0,+ }),+ );+ });++ it('invalidates review patches and related git tree status caches together', async () => {+ await invalidateGitReviewCaches({+ baseRef: 'origin/canary',+ deviceId: 'device-1',+ dirPath: '/repo',+ mode: 'branch',+ });++ expect(mutate).toHaveBeenNthCalledWith(1, [+ 'device:gitReviewPatches',+ 'device-1',+ '/repo',+ 'branch',+ 'origin/canary',+ ]);+ expect(mutate).toHaveBeenNthCalledWith(2, ['device:gitWorkingTreeStatus', 'device-1', '/repo']);+ expect(mutate).toHaveBeenNthCalledWith(3, ['device:gitAheadBehind', 'device-1', '/repo']);+ expect(mutate).toHaveBeenNthCalledWith(4, [+ 'localFile:gitWorkingTreeFiles',+ 'device-1',+ '/repo',+ ]);+ });+});diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.tsindex b3684d770e8..498bf098393 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts@@ -1,104 +1,9 @@-import type {- GitWorkingTreePatch,- SubmoduleWorkingTreePatches,-} from '@lobechat/electron-client-ipc';--import { useClientDataSWR } from '@/libs/swr';-import { deviceKeys } from '@/libs/swr/keys';-import { gitService } from '@/services/git';--export type ReviewMode = 'unstaged' | 'branch';--export interface ReviewPatchesData {- baseRef?: string;- headRef?: string;- mode: ReviewMode;- patches: GitWorkingTreePatch[];- /**- * Per-submodule patch groups. Undefined when the parent has no dirty- * submodules (unstaged) or no submodule pointer differences (branch) — the- * Review panel keeps its flat single-repo layout in that case. Branch-mode- * groups carry the submodule's own branch diff against its own origin/HEAD.- */- submodules?: SubmoduleWorkingTreePatches[];-}--const fetchUnstaged = async (- dirPath: string,- deviceId: string | undefined,-): Promise<ReviewPatchesData> => {- const result = await gitService.getGitWorkingTreePatches({ deviceId, path: dirPath });- return { mode: 'unstaged', patches: result?.patches ?? [], submodules: result?.submodules };-};--const fetchBranch = async (- dirPath: string,- baseRef: string | undefined,- deviceId: string | undefined,-): Promise<ReviewPatchesData> => {- const result = await gitService.getGitBranchDiff({ baseRef, deviceId, path: dirPath });- return {- baseRef: result?.baseRef,- headRef: result?.headRef,- mode: 'branch',- patches: result?.patches ?? [],- submodules: result?.submodules,- };-};--/**- * Single SWR entry point for the Review panel — `mode` and `baseRef` both- * participate in the cache key so switching modes or picking a different- * comparison base swaps cleanly without clobbering other tabs' data.- *- * Branch mode runs `git fetch` inside the controller, so we throttle focus- * revalidation more aggressively there to avoid hitting the network on- * every window refocus.- */-export const useReviewPatches = (- dirPath: string | undefined,- mode: ReviewMode,- baseRef?: string,- deviceId?: string,-) => {- const enabled = Boolean(dirPath);- const key = enabled- ? deviceKeys.gitReviewPatches(deviceId ?? 'local', dirPath!, mode, baseRef ?? '')- : null;-- return useClientDataSWR<ReviewPatchesData>(- key,- () =>- mode === 'branch'- ? fetchBranch(dirPath!, baseRef, deviceId)- : fetchUnstaged(dirPath!, deviceId),- {- focusThrottleInterval: mode === 'branch' ? 30 * 1000 : 5 * 1000,- revalidateOnFocus: true,- shouldRetryOnError: false,- },- );-};--/**- * Lazy-loaded list of remote branches under `refs/remotes/origin/*`,- * keyed by working directory. Used to populate the base-ref picker in the- * Review panel. Stays disabled until `enabled` flips true so we don't fork- * a `git for-each-ref` until the user actually opens the dropdown.- */-export const useGitRemoteBranches = (- dirPath: string | undefined,- enabled: boolean,- deviceId?: string,-) => {- const key =- dirPath && enabled ? deviceKeys.gitRemoteBranches(deviceId ?? 'local', dirPath) : null;- return useClientDataSWR(- key,- () => gitService.listGitRemoteBranches({ deviceId, path: dirPath! }),- {- revalidateOnFocus: false,- shouldRetryOnError: false,- },- );-};+export {+ getGitReviewPatchesKey,+ getReviewRefreshInterval,+ invalidateGitReviewCaches,+ type ReviewMode,+ type ReviewPatchesData,+ useGitRemoteBranches,+ useReviewPatches,+} from '@/store/device';diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsxindex df58f36970b..e82ec9a236b 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx@@ -239,6 +239,7 @@ const AgentWorkingSidebar = memo(() => {{reviewAvailable && (<Flexbox className={activeTab === 'review' ? styles.pane : styles.paneHidden}><Review+ active={activeTab === 'review'}deviceId={remoteDeviceId}showTree={showReviewTree}workingDirectory={workingDirectory}diff --git a/src/routes/(main)/home/features/InputArea/useSend.test.ts b/src/routes/(main)/home/features/InputArea/useSend.test.tsindex c77bcf17ce5..9a51357733e 100644--- a/src/routes/(main)/home/features/InputArea/useSend.test.ts+++ b/src/routes/(main)/home/features/InputArea/useSend.test.ts@@ -28,7 +28,7 @@ const chatState = vi.hoisted(() => ({}));const fileState = vi.hoisted(() => ({- chatContextSelections: [],+ chatContextSelections: [] as any[],chatUploadFileList: [],clearChatContextSelections: clearChatContextSelectionsMock,clearChatUploadFileList: clearChatUploadFileListMock,@@ -37,7 +37,7 @@ const fileState = vi.hoisted(() => ({const homeState = vi.hoisted(() => ({agentGroups: [],homeInputLoading: false,- inputActiveMode: null,+ inputActiveMode: null as any,isAgentListInit: true,pinnedAgents: [],privateAgentGroups: [],@@ -142,6 +142,9 @@ describe('Home InputArea useSend', () => {homeDailyBriefState.advance.mockReset();homeDailyBriefState.currentPair = undefined;chatState.inputMessage = 'hello';+ fileState.chatContextSelections = [];+ fileState.chatUploadFileList = [];+ homeState.inputActiveMode = null;});it('routes cold homepage sends to the created topic instead of relying on ChatHydration timing', async () => {@@ -203,4 +206,47 @@ describe('Home InputArea useSend', () => {expect(sentPayload.editorData).toBeUndefined();expect(homeDailyBriefState.advance).toHaveBeenCalledTimes(1);});++ it('passes context selections through starter agent mode sends', async () => {+ homeState.inputActiveMode = 'agent';+ fileState.chatContextSelections = [+ {+ content: 'const selected = true;',+ filePath: 'src/example.ts',+ id: 'code-selection',+ lineRange: { endLine: 12, startLine: 10 },+ preview: 'src/example.ts:10-12',+ source: 'code',+ title: 'src/example.ts:10-12',+ workingDirectory: '/repo',+ },+ ];++ const { result } = renderHook(() => useSend());+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => ({ type: 'doc' }),+ getMarkdownContent: () => 'use this selection',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(homeState.sendAsAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ contextSelections: [+ expect.objectContaining({+ content: 'const selected = true;',+ filePath: 'src/example.ts',+ lineRange: { endLine: 12, startLine: 10 },+ source: 'code',+ }),+ ],+ message: 'use this selection',+ }),+ );+ expect(clearChatContextSelectionsMock).toHaveBeenCalledTimes(1);+ });});diff --git a/src/routes/(main)/home/features/InputArea/useSend.ts b/src/routes/(main)/home/features/InputArea/useSend.tsindex a8bfa364fc6..a9c53f5cc39 100644--- a/src/routes/(main)/home/features/InputArea/useSend.ts+++ b/src/routes/(main)/home/features/InputArea/useSend.ts@@ -2,6 +2,7 @@ import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';import { useCallback } from 'react';import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';+import { buildMessageContextSelections } from '@/features/ChatInput/utils/contextSelections';import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';import { useQueryRoute } from '@/hooks/useQueryRoute';import { agentService } from '@/services/agent';@@ -90,19 +91,21 @@ export const useSend = () => {if (!message && fileList.length === 0 && contextList.length === 0) return;try {+ const { contextSelections, pageSelections } = buildMessageContextSelections(contextList);+switch (inputActiveMode) {case 'agent': {- await sendAsAgent({ editorData, message });+ await sendAsAgent({ contextSelections, editorData, message, pageSelections });break;}case 'group': {- await sendAsGroup({ editorData, message });+ await sendAsGroup({ contextSelections, editorData, message, pageSelections });break;}case 'write': {- await sendAsWrite({ editorData, message });+ await sendAsWrite({ contextSelections, editorData, message, pageSelections });break;}@@ -122,6 +125,7 @@ export const useSend = () => {sendMessage({context: { agentId: activeAgentId, isolatedTopic: true },+ contextSelections,contexts: contextList,editorData,files: fileList,@@ -129,6 +133,7 @@ export const useSend = () => {onTopicCreated: (topicId) => {router.replace(AGENT_CHAT_TOPIC_URL(activeAgentId, topicId, false));},+ pageSelections,});router.push(AGENT_CHAT_URL(activeAgentId, false));diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex e1df062332f..6d8662bf15f 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -26,8 +26,15 @@ class HeterogeneousAgentService {prompt: string,operationId: string,imageList?: Array<{ id: string; url: string }>,+ systemContext?: string,) {- return this.ipc.heterogeneousAgent.sendPrompt({ imageList, operationId, prompt, sessionId });+ return this.ipc.heterogeneousAgent.sendPrompt({+ imageList,+ operationId,+ prompt,+ sessionId,+ systemContext,+ });}async cancelSession(sessionId: string) {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 5e3e7d1c9bd..f7cbb653d80 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -1478,6 +1478,57 @@ describe('ConversationLifecycle actions', () => {);});+ it('should recover heterogeneous context selections from the persisted user message metadata', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ },+ });++ const persistedContextSelections = [+ {+ content: 'const selected = true;',+ filePath: 'src/example.ts',+ id: 'code-selection',+ lineRange: { endLine: 12, startLine: 10 },+ source: 'code' as const,+ },+ ];+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ metadata: { contextSelections: persistedContextSelections },+ role: 'user',+ }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ topics: [],+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ executeHeterogeneousAgentMock.mockResolvedValue(undefined);++ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });+ });++ expect(executeHeterogeneousAgentMock).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({+ contextSelections: persistedContextSelections,+ }),+ );+ });+it('should materialize local file mention editor data into persisted tool-result snapshots', async () => {mockConstEnv.isDesktop = true;setupMockSelectors({diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex b1ae2fee347..8f59e3f2404 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -1231,6 +1231,36 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(mockSendPrompt).toHaveBeenCalledWith('ipc-sess-1', 'test prompt', 'op-1', imageList);});+ it('should forward context selections as heterogeneous system context', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);+ setupIpcCapture();++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ contextSelections: [+ {+ content: 'const answer = 42;',+ filePath: 'src/example.ts',+ id: 'selection-1',+ lineRange: { endLine: 7, startLine: 7 },+ source: 'code',+ },+ ],+ });++ expect(mockSendPrompt).toHaveBeenCalledWith(+ 'ipc-sess-1',+ 'test prompt',+ 'op-1',+ undefined,+ expect.stringContaining('<user_context_selections count="1">'),+ );+ expect(mockSendPrompt.mock.calls[0][4]).toContain('filePath="src/example.ts"');+ expect(mockSendPrompt.mock.calls[0][4]).toContain('lines="7-7"');+ expect(mockSendPrompt.mock.calls[0][4]).toContain('const answer = 42;');+ });+it('should pass Claude Code model and thinking effort as spawn args', async () => {const store = createMockStore();const get = vi.fn(() => store);diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 41f20e4dd7a..20d2890a58d 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -237,6 +237,7 @@ export class ConversationLifecycleActionImpl {metadata,onlyAddUserMessage,context,+ contextSelections,messages: inputMessages,parentId: inputParentId,pageSelections,@@ -291,6 +292,7 @@ export class ConversationLifecycleActionImpl {messages: inputMessages,parentId: inputParentId,pageSelections,+ contextSelections,});// /compact — directly compress context without sending any message@@ -382,9 +384,13 @@ export class ConversationLifecycleActionImpl {? await materializeLocalSystemToolSnapshots(localFileReferences): [];const userMessageMetadata =- metadata || pageSelections?.length || localSystemToolSnapshots.length+ metadata ||+ contextSelections?.length ||+ pageSelections?.length ||+ localSystemToolSnapshots.length? {...metadata,+ ...(contextSelections?.length ? { contextSelections } : undefined),...(pageSelections?.length ? { pageSelections } : undefined),...(localSystemToolSnapshots.length ? { localSystemToolSnapshots } : undefined),}@@ -451,7 +457,11 @@ export class ConversationLifecycleActionImpl {}if (onlyAddUserMessage) {- await this.#get().addUserMessage({ message, fileList: fileIdList });+ await this.#get().addUserMessage({+ message,+ fileList: fileIdList,+ metadata: userMessageMetadata,+ });return;}@@ -763,6 +773,7 @@ export class ConversationLifecycleActionImpl {editorData,files: fileIdList,metadata: userMessageMetadata,+ contextSelections,pageSelections,parentId,},@@ -893,6 +904,13 @@ export class ConversationLifecycleActionImpl {// may already be cleared by this point, so we read from DB instead)const userMsg = heteroData.messages.find((m: any) => m.id === heteroData.userMessageId);const persistedImageList = userMsg?.imageList;+ const persistedMetadata = userMsg?.metadata as MessageMetadata | undefined;+ const effectiveContextSelections = contextSelections?.length+ ? contextSelections+ : persistedMetadata?.contextSelections;+ const effectivePageSelections = pageSelections?.length+ ? pageSelections+ : persistedMetadata?.pageSelections;// Read heterogeneous-agent session id from topic metadata for multi-turn// resume. `resolveHeteroResume` drops the sessionId when the saved cwd@@ -912,10 +930,12 @@ export class ConversationLifecycleActionImpl {await executeHeterogeneousAgent(() => this.#get(), {assistantMessageId: heteroData.assistantMessageId,context: heteroContext,+ contextSelections: effectiveContextSelections,heterogeneousProvider,imageList: persistedImageList?.length ? persistedImageList : undefined,message,operationId: heteroOpId,+ pageSelections: effectivePageSelections,resumeSessionId,workingDirectory,workingDirectoryConfig,@@ -1066,6 +1086,7 @@ export class ConversationLifecycleActionImpl {editorData,files: fileIdList,metadata: userMessageMetadata,+ contextSelections,pageSelections,parentId,},diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex fa42fb107b1..d82b23318eb 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -17,14 +17,17 @@ import {reduceMainAgent,type SubagentIntent,} from '@lobechat/heterogeneous-agents';+import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';import type {ChatMessageError,ChatToolPayload,ChatTopicMetadata,ChatTopicStatus,+ ContextSelection,ConversationContext,HeterogeneousProviderConfig,MessageMapScope,+ PageSelection,UIChatMessage,WorkingDirConfig,} from '@lobechat/types';@@ -221,17 +224,55 @@ const drainWithTimeout = (queue: Promise<unknown>, ms: number): Promise<void> =>export interface HeterogeneousAgentExecutorParams {assistantMessageId: string;context: ConversationContext;+ contextSelections?: ContextSelection[];heterogeneousProvider: HeterogeneousProviderConfig;/** Image attachments from user message — passed to Main for vision support */imageList?: Array<{ id: string; url: string }>;message: string;operationId: string;+ pageSelections?: PageSelection[];/** CC session ID from previous execution in this topic (for --resume) */resumeSessionId?: string;workingDirectory?: string;workingDirectoryConfig?: WorkingDirConfig;}+const buildLocalHeterogeneousSystemContext = ({+ agentSystemContext,+ contextSelections,+ pageSelections,+ workingDirectory,+}: {+ agentSystemContext?: string;+ contextSelections?: ContextSelection[];+ pageSelections?: PageSelection[];+ workingDirectory?: string;+}): string | undefined => {+ const parts: string[] = [];++ if (agentSystemContext?.trim()) parts.push(agentSystemContext.trim());++ if (workingDirectory?.trim()) {+ parts.push(+ [+ '## Workspace',+ `You are running on the user's own machine. Your working directory is \`${workingDirectory.trim()}\`.`,+ ].join('\n'),+ );+ }++ const selectionContext =+ contextSelections && contextSelections.length > 0+ ? formatContextSelections(contextSelections)+ : pageSelections && pageSelections.length > 0+ ? formatPageSelections(pageSelections)+ : '';++ if (selectionContext) parts.push(selectionContext);++ return parts.length > 0 ? parts.join('\n\n') : undefined;+};+const getTopicMetadataById = (store: ChatStore,topicId: string | undefined,@@ -385,11 +426,13 @@ export const executeHeterogeneousAgent = async (): Promise<void> => {const {heterogeneousProvider,+ contextSelections,assistantMessageId,context,imageList,message,operationId,+ pageSelections,resumeSessionId,workingDirectory,workingDirectoryConfig,@@ -1573,8 +1616,25 @@ export const executeHeterogeneousAgent = async (},});+ const systemContext = buildLocalHeterogeneousSystemContext({+ agentSystemContext: heterogeneousProvider.systemContext,+ contextSelections,+ pageSelections,+ workingDirectory,+ });+// Send the prompt — blocks until process exits- await heterogeneousAgentService.sendPrompt(agentSessionId, message, operationId, imageList);+ if (systemContext) {+ await heterogeneousAgentService.sendPrompt(+ agentSessionId,+ message,+ operationId,+ imageList,+ systemContext,+ );+ } else {+ await heterogeneousAgentService.sendPrompt(agentSessionId, message, operationId, imageList);+ }// Persist heterogeneous-agent session id + the cwd it was created under,// for multi-turn resume. CC stores sessions per-cwddiff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex d95891e04be..87458b54984 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -207,6 +207,36 @@ describe('chatMessage actions', () => {threadId: undefined,});});++ it('should pass user message metadata when provided', async () => {+ const message = 'Test user message with selected code';+ const metadata = {+ contextSelections: [+ {+ content: 'const answer = 42;',+ filePath: 'src/example.ts',+ id: 'selection-1',+ source: 'code' as const,+ },+ ],+ };+ useChatStore.setState({ activeAgentId: mockState.activeAgentId });+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.addUserMessage({ message, metadata });+ });++ expect(messageService.createMessage).toHaveBeenCalledWith({+ content: message,+ files: undefined,+ role: 'user',+ agentId: mockState.activeAgentId,+ metadata,+ topicId: mockState.activeTopicId,+ threadId: undefined,+ });+ });});describe('deleteMessage', () => {diff --git a/src/store/chat/slices/message/actions/publicApi.ts b/src/store/chat/slices/message/actions/publicApi.tsindex 6fc2f7e5675..901cc333c90 100644--- a/src/store/chat/slices/message/actions/publicApi.ts+++ b/src/store/chat/slices/message/actions/publicApi.ts@@ -1,4 +1,4 @@-import { TraceEventType } from '@lobechat/types';+import { type MessageMetadata, TraceEventType } from '@lobechat/types';import { copyToClipboard } from '@lobehub/ui';import isEqual from 'fast-deep-equal';@@ -66,9 +66,11 @@ export class MessagePublicApiActionImpl {addUserMessage = async ({message,fileList,+ metadata,}: {message: string;fileList?: string[];+ metadata?: MessageMetadata;}): Promise<void> => {const {optimisticCreateMessage,@@ -91,6 +93,7 @@ export class MessagePublicApiActionImpl {threadId: activeThreadId,groupId: activeGroupId,parentId,+ ...(metadata ? { metadata } : {}),});if (result) {diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.tsindex 6a101ec1064..c5389711b53 100644--- a/src/store/chat/slices/operation/__tests__/actions.test.ts+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts@@ -86,6 +86,48 @@ describe('Operation Actions', () => {expect(merged.filesPreview[0]).toMatchObject({ id: 'f1', name: 'a.png' });expect(merged.filesPreview[2]).toMatchObject({ id: 'f3', mimeType: 'application/pdf' });});++ it('should preserve context selections from queued messages', () => {+ const merged = mergeQueuedMessages([+ {+ content: 'first',+ createdAt: 1,+ id: 'q1',+ interruptMode: 'soft',+ metadata: {+ contextSelections: [+ {+ content: 'const first = true;',+ filePath: 'src/first.ts',+ id: 'selection-1',+ source: 'code',+ },+ ],+ },+ },+ {+ content: 'second',+ createdAt: 2,+ id: 'q2',+ interruptMode: 'soft',+ metadata: {+ contextSelections: [+ {+ content: 'const second = true;',+ filePath: 'src/second.ts',+ id: 'selection-2',+ source: 'code',+ },+ ],+ },+ },+ ]);++ expect(merged.metadata?.contextSelections).toEqual([+ expect.objectContaining({ filePath: 'src/first.ts', id: 'selection-1' }),+ expect.objectContaining({ filePath: 'src/second.ts', id: 'selection-2' }),+ ]);+ });});describe('startOperation', () => {diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 26fca6bb9f9..1ae8e1f734a 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -350,11 +350,16 @@ export const mergeQueuedMessages = (messages: QueuedMessage[]): MergedQueuedMess...(acc?.pageSelections ?? []),...(message.metadata.pageSelections ?? []),];+ const contextSelections = [+ ...(acc?.contextSelections ?? []),+ ...(message.metadata.contextSelections ?? []),+ ];return {...acc,...message.metadata,...(localSystemToolSnapshots.length ? { localSystemToolSnapshots } : undefined),+ ...(contextSelections.length ? { contextSelections } : undefined),...(pageSelections.length ? { pageSelections } : undefined),};}, undefined);diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.tsindex 301f341d0ca..0ef521ffb89 100644--- a/src/store/device/gitHooks.ts+++ b/src/store/device/gitHooks.ts@@ -1,14 +1,35 @@import { isDesktop } from '@lobechat/const';+import type {+ GitWorkingTreePatch,+ SubmoduleWorkingTreePatches,+} from '@lobechat/electron-client-ipc';import type {DeviceGitAheadBehind,DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';-import { useClientDataSWR } from '@/libs/swr';-import { deviceKeys } from '@/libs/swr/keys';+import { mutate, useClientDataSWR } from '@/libs/swr';+import { deviceKeys, localFileKeys } from '@/libs/swr/keys';import { type GitBranchSummary, type GitLinkedPRSummary, gitService } from '@/services/git';+export type ReviewMode = 'unstaged' | 'branch';++const UNSTAGED_REVIEW_REFRESH_INTERVAL = 10 * 1000;+const BRANCH_REVIEW_REFRESH_INTERVAL = 30 * 1000;++export interface ReviewPatchesData {+ baseRef?: string;+ headRef?: string;+ mode: ReviewMode;+ patches: GitWorkingTreePatch[];+ /**+ * Per-submodule patch groups. Undefined when the parent has no dirty+ * submodules (unstaged) or no submodule pointer differences (branch).+ */+ submodules?: SubmoduleWorkingTreePatches[];+}+/*** Git read hooks for a working directory, transport-agnostic: the fetcher goes* through `gitService`, which dispatches Electron IPC (local) vs `device.*` RPC@@ -19,6 +40,93 @@ import { type GitBranchSummary, type GitLinkedPRSummary, gitService } from '@/seconst isEnabled = (deviceId: string | undefined, path: string | undefined): path is string =>!!path && (!!deviceId || isDesktop);+const fetchUnstagedReviewPatches = async (+ dirPath: string,+ deviceId: string | undefined,+): Promise<ReviewPatchesData> => {+ const result = await gitService.getGitWorkingTreePatches({ deviceId, path: dirPath });+ return { mode: 'unstaged', patches: result?.patches ?? [], submodules: result?.submodules };+};++const fetchBranchReviewPatches = async (+ dirPath: string,+ baseRef: string | undefined,+ deviceId: string | undefined,+): Promise<ReviewPatchesData> => {+ const result = await gitService.getGitBranchDiff({ baseRef, deviceId, path: dirPath });+ return {+ baseRef: result?.baseRef,+ headRef: result?.headRef,+ mode: 'branch',+ patches: result?.patches ?? [],+ submodules: result?.submodules,+ };+};++export const getReviewRefreshInterval = (mode: ReviewMode, active: boolean) => {+ if (!active) return 0;+ return mode === 'branch' ? BRANCH_REVIEW_REFRESH_INTERVAL : UNSTAGED_REVIEW_REFRESH_INTERVAL;+};++interface GitReviewCacheParams {+ baseRef?: string;+ deviceId?: string;+ dirPath?: string;+ mode: ReviewMode;+}++export const getGitReviewPatchesKey = ({+ baseRef,+ deviceId,+ dirPath,+ mode,+}: GitReviewCacheParams) =>+ dirPath ? deviceKeys.gitReviewPatches(deviceId ?? 'local', dirPath, mode, baseRef ?? '') : null;++export const invalidateGitReviewCaches = async ({+ baseRef,+ deviceId,+ dirPath,+ mode,+}: GitReviewCacheParams) => {+ if (!dirPath) return;++ const cacheDeviceId = deviceId ?? 'local';+ await Promise.all([+ mutate(deviceKeys.gitReviewPatches(cacheDeviceId, dirPath, mode, baseRef ?? '')),+ mutate(deviceKeys.gitWorkingTreeStatus(cacheDeviceId, dirPath)),+ mutate(deviceKeys.gitAheadBehind(cacheDeviceId, dirPath)),+ mutate(localFileKeys.gitWorkingTreeFiles(deviceId, dirPath)),+ ]);+};++export const useReviewPatches = (+ dirPath: string | undefined,+ mode: ReviewMode,+ baseRef?: string,+ deviceId?: string,+ active = true,+) => {+ const enabled = active && Boolean(dirPath);+ const key = enabled ? getGitReviewPatchesKey({ baseRef, deviceId, dirPath, mode }) : null;++ return useClientDataSWR<ReviewPatchesData>(+ key,+ () =>+ mode === 'branch'+ ? fetchBranchReviewPatches(dirPath!, baseRef, deviceId)+ : fetchUnstagedReviewPatches(dirPath!, deviceId),+ {+ focusThrottleInterval: mode === 'branch' ? 30 * 1000 : 5 * 1000,+ refreshInterval: getReviewRefreshInterval(mode, active),+ refreshWhenHidden: false,+ revalidateOnFocus: true,+ revalidateOnReconnect: true,+ shouldRetryOnError: false,+ },+ );+};+/*** Current branch + detached state. A cheap local git read, so use a short* dedupe window (2s): switching the working directory must refetch the branch@@ -88,3 +196,24 @@ export const useFetchGitWorktrees = (deviceId: string | undefined, path?: string() => gitService.listGitWorktrees({ deviceId, path: path! }),{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },);++/**+ * Lazy-loaded list of remote branches under `refs/remotes/origin/*`.+ * Disabled until the Review base-ref picker opens.+ */+export const useGitRemoteBranches = (+ dirPath: string | undefined,+ enabled: boolean,+ deviceId?: string,+) => {+ const key =+ enabled && dirPath ? deviceKeys.gitRemoteBranches(deviceId ?? 'local', dirPath) : null;+ return useClientDataSWR(+ key,+ () => gitService.listGitRemoteBranches({ deviceId, path: dirPath! }),+ {+ revalidateOnFocus: false,+ shouldRetryOnError: false,+ },+ );+};diff --git a/src/store/home/slices/homeInput/action.test.ts b/src/store/home/slices/homeInput/action.test.tsindex d3e6914efe8..98e8df2ef28 100644--- a/src/store/home/slices/homeInput/action.test.ts+++ b/src/store/home/slices/homeInput/action.test.ts@@ -157,6 +157,28 @@ describe('HomeInputActionImpl', () => {}),);});++ it('forwards context selections to the agent builder message', async () => {+ const action = createAction();+ const contextSelections = [+ {+ content: 'const selected = true;',+ filePath: 'src/example.ts',+ id: 'code-selection',+ lineRange: { endLine: 12, startLine: 10 },+ source: 'code' as const,+ },+ ];++ await action.sendAsAgent({ contextSelections, message: 'use this selected code' });++ expect(sendMessageMock).toHaveBeenCalledWith(+ expect.objectContaining({+ contextSelections,+ message: 'use this selected code',+ }),+ );+ });});describe('sendAsGroup', () => {diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.tsindex afa830f3179..197fab438de 100644--- a/src/store/home/slices/homeInput/action.ts+++ b/src/store/home/slices/homeInput/action.ts@@ -1,5 +1,6 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import type { ContextSelection, PageSelection } from '@lobechat/types';import { stableWorkspaceAwareNavigate } from '@/features/Workspace/stableWorkspaceAwareNavigate';import { chatGroupService } from '@/services/chatGroup';@@ -20,9 +21,11 @@ import { type StarterMode } from './initialState';const n = setNamespace('homeInput');interface SendMessageWithEditorParams {+ contextSelections?: ContextSelection[];editorData?: Record<string, any>;groupId?: string;message: string;+ pageSelections?: PageSelection[];}/**@@ -62,9 +65,11 @@ export class HomeInputActionImpl {};sendAsAgent = async ({+ contextSelections,editorData,groupId,message,+ pageSelections,}: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsAgent/start'));@@ -131,8 +136,10 @@ export class HomeInputActionImpl {if (agentBuilderId) {await sendMessage({context: { agentId: agentBuilderId, scope: 'agent_builder' },+ contextSelections,editorData,message,+ pageSelections,});}}@@ -147,9 +154,11 @@ export class HomeInputActionImpl {};sendAsGroup = async ({+ contextSelections,editorData,groupId,message,+ pageSelections,}: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsGroup/start'));@@ -202,8 +211,10 @@ export class HomeInputActionImpl {const { sendMessage } = useChatStore.getState();await sendMessage({context: { agentId: groupAgentBuilderId, scope: 'group_agent_builder' },+ contextSelections,editorData,message,+ pageSelections,});}@@ -224,7 +235,12 @@ export class HomeInputActionImpl {this.#set({ inputActiveMode: null }, false, n('sendAsResearch'));};- sendAsWrite = async ({ editorData, message }: SendMessageWithEditorParams): Promise<string> => {+ sendAsWrite = async ({+ contextSelections,+ editorData,+ message,+ pageSelections,+ }: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsWrite/start'));try {@@ -265,8 +281,10 @@ export class HomeInputActionImpl {// be bound to the previously open document — relying on its fallback// here would scope server-side PageAgent tools to the wrong document.context: { agentId: pageAgentId, documentId: newDoc.id, scope: 'page' },+ contextSelections,editorData,message,+ pageSelections,});}