diff --git a/src/main/http-server.ts b/src/main/http-server.ts index da42712..884eb98 100644 --- a/src/main/http-server.ts +++ b/src/main/http-server.ts @@ -587,7 +587,7 @@ const WECHAT_SEND_MAX_TEXT_LENGTH = 2_000 const WECHAT_SEND_MAX_RECIPIENT_LENGTH = 512 const WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH = 200 -const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice'] as const +const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice', 'file'] as const type WechatSendContentType = (typeof WECHAT_SEND_CONTENT_TYPES)[number] interface WechatSendApiDependencies { @@ -731,7 +731,12 @@ function parseWechatSendPayload(payload: unknown): ParsedWechatSend { message: `filePath 指向的文件不存在:${filePath}` } } - content = { type, path: filePath } + if (type === 'file') { + const fileName = readSendString(body.fileName) + content = { type: 'file', path: filePath, ...(fileName ? { name: fileName } : {}) } + } else { + content = { type, path: filePath } + } } return { @@ -841,7 +846,14 @@ function createWechatSendRoute( } const contentType = parsed.content.type if (!capability.capabilities[contentType]) { - const label = contentType === 'text' ? '文字' : contentType === 'image' ? '图片' : '语音' + const label = + contentType === 'text' + ? '文字' + : contentType === 'image' + ? '图片' + : contentType === 'file' + ? '文件' + : '语音' return sendWechatSendError(res, 503, 'SEND_NOT_READY', `当前微信发送能力不支持发送${label}`, { capabilityStatus: capability.status, capabilities: capability.capabilities diff --git a/src/main/index.ts b/src/main/index.ts index 76998a9..cb6c9cb 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1940,7 +1940,12 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { // 排查「消息到底发没发出去」时恰好缺的就是那份证据。 // 普通手动发送保持 triggerType=user;带 postfixText 的日报图片由 Gateway 编排成 // 两个 automation action,以复用同一条 3s 队列,并严格在图片 sent 后才发后置词。 - if (request.type === 'text' || request.type === 'image' || request.type === 'video') { + if ( + request.type === 'text' || + request.type === 'image' || + request.type === 'video' || + request.type === 'file' + ) { const to = String(request.to || '').trim() const recipient = { type: @@ -1973,7 +1978,9 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { ? 'manual_text' : request.type === 'video' ? 'manual_video' - : 'manual_image', + : request.type === 'file' + ? 'manual_file' + : 'manual_image', triggerType: 'user', recipient, content: @@ -1985,7 +1992,13 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { } : request.type === 'video' ? { type: 'video', path: String(request.filePath || '') } - : { type: 'image', path: String(request.filePath || '') } + : request.type === 'file' + ? { + type: 'file', + path: String(request.filePath || ''), + ...(request.fileName ? { name: request.fileName } : {}) + } + : { type: 'image', path: String(request.filePath || '') } }) // 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。 return toPersonalWechatSendResult(action, await currentPersonalWechatSenderStatus()) @@ -3675,6 +3688,22 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { ipcMain.handle('wechat-personal:getVoiceDiagnostic', () => personalWechatSendService.getLatestVoiceDiagnostic() ) + ipcMain.handle('wechat-personal:selectFile', async (event) => { + const window = BrowserWindow.fromWebContents(event.sender) + const result = await dialog.showOpenDialog(window!, { + title: '选择要发送的文件', + properties: ['openFile'] + }) + if (result.canceled || result.filePaths.length === 0) return { canceled: true } + const filePath = result.filePaths[0] + let size = 0 + try { + size = (await fsPromises.stat(filePath)).size + } catch { + return { canceled: true } + } + return { canceled: false, path: filePath, name: path.basename(filePath), size } + }) ipcMain.handle('agent-hub:selectTestImage', async (event) => { const window = BrowserWindow.fromWebContents(event.sender) const result = await dialog.showOpenDialog(window!, { diff --git a/src/main/services/image-key-config-service.ts b/src/main/services/image-key-config-service.ts index 3c54b42..93448e0 100644 --- a/src/main/services/image-key-config-service.ts +++ b/src/main/services/image-key-config-service.ts @@ -55,7 +55,12 @@ export class ImageKeyConfigService { return migrated.success ? this.getConfig() : legacy } - const envAesKey = String(import.meta.env.VITE_IMAGE_AES_KEY || '').trim() + // 只有 dev 构建读 .env:生产包里带上开发者的 key,会让所有用户拿同一个人的密钥 + // 去解自己的图,直接表现为「图片解密失败」。VITE_* 是编译期字面量,不加这道闸 + // 就会被打进 app.asar。 + const envAesKey = import.meta.env.DEV + ? String(import.meta.env.VITE_IMAGE_AES_KEY || '').trim() + : '' if (!settings.imageKeyFallbackDisabled && envAesKey) { return this.buildResult({ source: 'environment', diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index ccb7f71..a10bfe7 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -188,7 +188,7 @@ export function deriveMacWechatSenderStatus({ } const runtimeCapabilities = new Set(manifest.capabilities) - const supportsCapability = (name: 'text' | 'image' | 'voice'): boolean => { + const supportsCapability = (name: 'text' | 'image' | 'voice' | 'file'): boolean => { if (manifest.capabilitiesByVersion) return versionCapabilities?.[name] === 'verified' return runtimeCapabilities.has(name) } @@ -205,6 +205,10 @@ export function deriveMacWechatSenderStatus({ * 真正的发送结果仍以 Host 返回为准,不在 UI 层假装支持。 */ const canSendVideo = bindingReady && binding?.canSendImage === true + const canSendFile = + bindingReady && + supportsCapability('file') && + versionCapabilities?.textMechanism === 'tm-message-source-send' const sessionAttached = identityMatches && (binding?.sessionAttached ?? false) const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false) @@ -228,11 +232,12 @@ export function deriveMacWechatSenderStatus({ imageHookInstalled: identityMatches && (binding?.canSendImage ?? false), imageHookReady: identityMatches && (binding?.canSendImage ?? false), messageListenerReady: scriptLoaded, - canSend: canSendText || canSendImage || canSendVoice || canSendVideo, + canSend: canSendText || canSendImage || canSendVoice || canSendVideo || canSendFile, canSendText, canSendImage, canSendVoice, canSendVideo, + canSendFile, message, error: state === 'error' ? message : undefined } diff --git a/src/main/services/personal-wechat-capability-service.ts b/src/main/services/personal-wechat-capability-service.ts index 883cb70..2619375 100644 --- a/src/main/services/personal-wechat-capability-service.ts +++ b/src/main/services/personal-wechat-capability-service.ts @@ -38,7 +38,8 @@ export class PersonalWechatCapabilityService { text: Boolean(senderStatus.canSendText), image: Boolean(senderStatus.canSendImage), voice: Boolean(senderStatus.canSendVoice), - video: Boolean(senderStatus.canSendVideo) + video: Boolean(senderStatus.canSendVideo), + file: Boolean(senderStatus.canSendFile) } const status = this.mapState(senderStatus) const ready = status === 'ready' diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index 6b87552..8c87cc3 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -11,7 +11,7 @@ import { writeFileSync } from 'fs' import { homedir, tmpdir } from 'os' -import { delimiter, dirname, extname, join, sep } from 'path' +import { delimiter, dirname, extname, join, sep, basename } from 'path' import { resolveBundledFfmpegPath } from '../ffmpeg-path' import { promisify } from 'util' import type { @@ -36,6 +36,7 @@ const MAX_IMAGE_BYTES = 20 * 1024 * 1024 const MAX_VOICE_BYTES = 20 * 1024 * 1024 /** 视频与扩展发送通道的上限保持一致。 */ const MAX_VIDEO_BYTES = 100 * 1024 * 1024 +const MAX_FILE_BYTES = 100 * 1024 * 1024 // 语音编码由 native runtime 内的 SILK 实现完成,不再是外部编码器进程。 const VOICE_ENCODER_NAME = 'silk' const VOICE_ENCODER_VERSION = 'tm-wechat-native' @@ -398,6 +399,66 @@ export function stageMacWechatVideoForSend( } } +const MAC_FILE_STAGE_PREFIX = 'tm-file-' +const MAC_FILE_STAGE_RETENTION_MS = 10 * 60 * 1000 + +export function stageMacWechatFileForSend( + filePath: string, + wechatFilesRoot = WECHAT_FILES_ROOT +): { stagedPath: string; cleanup: () => void } { + const normalized = String(filePath || '').trim() + const containerDataRoot = dirname(dirname(wechatFilesRoot)) + if ( + containerDataRoot.includes('com.tencent.xinWeChat') && + normalized.startsWith(`${containerDataRoot}${sep}`) + ) { + return { stagedPath: normalized, cleanup: () => {} } + } + + const documentsDir = dirname(wechatFilesRoot) + const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot + mkdirSync(stageDir, { recursive: true }) + + const now = Date.now() + try { + for (const entry of readdirSync(stageDir)) { + if (!entry.startsWith(MAC_FILE_STAGE_PREFIX)) continue + const candidate = join(stageDir, entry) + try { + if (now - statSync(candidate).mtimeMs > MAC_FILE_STAGE_RETENTION_MS) { + unlinkSync(candidate) + } + } catch { + // Best-effort stale file cleanup. + } + } + } catch { + // Ignore directory listing errors. + } + + const extension = extname(normalized).toLowerCase() + const safeExtension = /^\.[a-z0-9]{1,12}$/.test(extension) ? extension : '.bin' + const stagedPath = join( + stageDir, + `${MAC_FILE_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}` + ) + copyFileSync(normalized, stagedPath) + + return { + stagedPath, + cleanup: () => { + const timer = setTimeout(() => { + try { + unlinkSync(stagedPath) + } catch { + // Best-effort delayed cleanup after WeChat finishes asynchronous upload. + } + }, 300_000) + timer.unref?.() + } + } +} + /** Locate the current account's temporary image directory consumed by the image send path. */ export function findWechatImagePath( root = WECHAT_FILES_ROOT, @@ -521,6 +582,13 @@ export function buildWindowsWechatRequest( } } + if (request.type === 'file') { + return { + endpoint: '/SendMsg', + body: { toWxid: target, type: 'file', msg: String(request.filePath || '').trim() } + } + } + const fromId = String(request.fromId || '').trim() const filePath = String(options.filePath || request.filePath || '').trim() const durationMs = options.durationMs ?? request.durationMs @@ -558,6 +626,7 @@ function windowsStatusBase(host = windowsHookHost() || ''): PersonalWechatSender canSendImage: false, canSendVoice: false, canSendVideo: false, + canSendFile: false, message: '正在检查 Windows 微信消息接口' } } @@ -687,6 +756,7 @@ export class PersonalWechatSendService { if (request.type === 'image') return this.sendMacImage(request) if (request.type === 'voice') return this.sendMacVoice(request) if (request.type === 'video') return this.sendMacVideo(request) + if (request.type === 'file') return this.sendMacFile(request) } return { success: false, @@ -907,6 +977,56 @@ export class PersonalWechatSendService { } } + private async sendMacFile( + request: Extract + ): Promise { + await macWechatRuntimeManager.ensureStarted() + const status = await macWechatRuntimeManager.buildSenderStatus() + if (!status.canSendFile) { + return { + success: false, + status, + error: status.message || '当前微信发送组件不支持文件,请升级后重试' + } + } + const filePath = String(request.filePath || '').trim() + if (!filePath || !existsSync(filePath)) { + return { success: false, status, error: '请选择有效的文件' } + } + const size = statSync(filePath).size + if (size <= 0 || size > MAX_FILE_BYTES) { + return { success: false, status, error: '文件必须小于 100 MB' } + } + const fileName = String(request.fileName || '').trim() || basename(filePath) + + let staged: { stagedPath: string; cleanup: () => void } | null = null + try { + staged = stageMacWechatFileForSend(filePath, this.wechatFilesRoot) + } catch (error) { + const latest = await macWechatRuntimeManager.buildSenderStatus() + return { + success: false, + status: latest, + error: error instanceof Error ? error.message : '无法将文件暂存到微信沙盒目录' + } + } + + try { + const result = await this.postMacHost( + '/sendMsg', + { to: request.to, type: 'file', path: staged.stagedPath, name: fileName }, + 180_000 + ) + const latest = await macWechatRuntimeManager.buildSenderStatus() + if (!result?.ok) { + return { success: false, status: latest, error: result?.message || '文件发送失败' } + } + return { success: true, status: latest } + } finally { + staged.cleanup() + } + } + private async sendMacImage( request: Extract ): Promise { @@ -1100,6 +1220,10 @@ export class PersonalWechatSendService { } request = { ...request, to, text } } else { + if (request.type === 'file') { + const status = await this.getWindowsStatus() + return { success: false, status, error: 'Windows 端暂不支持文件发送' } + } const filePath = String(request.filePath || '').trim() const label = request.type === 'voice' ? '语音' : request.type === 'video' ? '视频' : '图片' const limit = diff --git a/src/main/services/wechat-action-gateway.ts b/src/main/services/wechat-action-gateway.ts index 01f7446..6a869b9 100644 --- a/src/main/services/wechat-action-gateway.ts +++ b/src/main/services/wechat-action-gateway.ts @@ -443,7 +443,8 @@ export class WechatActionGateway { (request.content.type !== 'text' && request.content.type !== 'image' && request.content.type !== 'video' && - request.content.type !== 'voice') + request.content.type !== 'voice' && + request.content.type !== 'file') ) { return } @@ -593,9 +594,18 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu content: { type: 'text', text, ...(at ? { at } : {}) } } as WechatActionRequest } - if (contentType !== 'image' && contentType !== 'video' && contentType !== 'voice') return null + if ( + contentType !== 'image' && + contentType !== 'video' && + contentType !== 'voice' && + contentType !== 'file' + ) { + return null + } const filePath = String((content as { path?: unknown }).path || '').trim() if (!filePath) return null + const contentName = + contentType === 'file' ? String((content as { name?: unknown }).name || '').trim() : '' return { ...input, origin, @@ -612,7 +622,10 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu ? { name: String((recipient as { name?: unknown }).name).trim() } : {}) }, - content: { type: contentType, path: filePath } + content: + contentType === 'file' + ? { type: 'file', path: filePath, ...(contentName ? { name: contentName } : {}) } + : { type: contentType, path: filePath } } as WechatActionRequest } @@ -655,6 +668,14 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech if (request.content.type === 'video') { return { ...base, type: 'video', filePath: request.content.path } } + if (request.content.type === 'file') { + return { + ...base, + type: 'file', + filePath: request.content.path, + ...(request.content.name ? { fileName: request.content.name } : {}) + } + } const metadata = request.metadata && typeof request.metadata === 'object' ? request.metadata : {} const fromId = typeof metadata.fromId === 'string' ? metadata.fromId.trim() : '' const durationMs = @@ -700,7 +721,12 @@ function contentAudit( content: WechatActionContent ): Pick { const raw = content.type === 'text' ? content.text : content.path - const preview = content.type === 'text' ? raw : path.basename(raw) + const preview = + content.type === 'text' + ? raw + : content.type === 'file' && content.name + ? content.name + : path.basename(raw) return { contentPreview: preview.slice(0, MAX_CONTENT_PREVIEW_LENGTH), contentHash: createHash('sha256').update(raw).digest('hex') @@ -708,7 +734,15 @@ function contentAudit( } function contentTypeLabel(type: WechatActionContent['type']): string { - return type === 'text' ? '文字' : type === 'image' ? '图片' : type === 'video' ? '视频' : '语音' + return type === 'text' + ? '文字' + : type === 'image' + ? '图片' + : type === 'video' + ? '视频' + : type === 'file' + ? '文件' + : '语音' } function normalizeAuditRecords(values: unknown[]): WechatActionAuditRecord[] { diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 51e0a3d..fe3abed 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -797,6 +797,12 @@ declare global { sendPersonalWechatMessage: ( request: PersonalWechatSendRequest ) => Promise + selectPersonalWechatFile: () => Promise<{ + canceled: boolean + path?: string + name?: string + size?: number + }> /** 定时日报:「立即执行」——与 scheduler 走同一条执行链路(manual trigger)。 */ runScheduledReportRule: ( ruleId: string diff --git a/src/preload/index.ts b/src/preload/index.ts index 71cc670..5043ac8 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -736,6 +736,12 @@ const api = { sendPersonalWechatMessage: ( request: PersonalWechatSendRequest ): Promise => ipcRenderer.invoke('wechat-personal:send', request), + selectPersonalWechatFile: (): Promise<{ + canceled: boolean + path?: string + name?: string + size?: number + }> => ipcRenderer.invoke('wechat-personal:selectFile'), /** * 定时日报(Automation 的 `scheduled_report` 规则类型)。 * diff --git a/src/renderer/src/components/ChatWindow.tsx b/src/renderer/src/components/ChatWindow.tsx index 5ed1f9b..3b5bb88 100644 --- a/src/renderer/src/components/ChatWindow.tsx +++ b/src/renderer/src/components/ChatWindow.tsx @@ -9,6 +9,7 @@ import { MessageList } from './chat/MessageList' import { PersonalWechatSendDialog } from './chat/PersonalWechatSendDialog' import { mergeGroupExitEvents } from '../../../shared/group-exit-event-message' import { useGroupExitEvents } from '../hooks/useGroupExitEvents' +import { isMac } from '../utils/runtime-environment' interface ChatWindowProps { contact: Contact | null @@ -59,6 +60,7 @@ const ChatWindow: React.FC = ({ const [isAtLatest, setIsAtLatest] = useState(true) const [isReloadingAvatars, setIsReloadingAvatars] = useState(false) const [sendDialogOpen, setSendDialogOpen] = useState(false) + const [pendingFile, setPendingFile] = useState<{ path: string; name: string } | null>(null) const previousScrollTopRef = useRef(0) const scrollToBottom = useCallback((): void => { @@ -167,6 +169,17 @@ const ChatWindow: React.FC = ({ setSendDialogOpen(true) }, [onOpenPersonalWechatSettings]) + const handleSendFile = useCallback(async (): Promise => { + try { + const picked = await window.api.selectPersonalWechatFile() + if (picked.canceled || !picked.path || !picked.name) return + setPendingFile({ path: picked.path, name: picked.name }) + setSendDialogOpen(true) + } catch { + // 选择器本身失败(无窗口、无权限)时什么都不做,不要弹出一个空对话框。 + } + }, []) + if (!contact) return return ( @@ -181,6 +194,7 @@ const ChatWindow: React.FC = ({ onContentFilterChange={onContentFilterChange || (() => undefined)} onRefresh={onRefresh} onTestSend={() => void handleOpenPersonalWechatSend()} + onSendFile={isMac ? () => void handleSendFile() : undefined} onOpenAiSettings={onCreateGroupReport || (() => undefined)} onOpenLocalIndexSettings={onOpenLocalIndexSettings} /> @@ -215,9 +229,13 @@ const ChatWindow: React.FC = ({ setSendDialogOpen(false)} + onClose={() => { + setSendDialogOpen(false) + setPendingFile(null) + }} onOpenTextToSpeechSettings={onOpenTextToSpeechSettings} onOpenPersonalWechatSettings={onOpenPersonalWechatSettings} + initialFile={pendingFile} /> )} diff --git a/src/renderer/src/components/chat/ChatHeader.tsx b/src/renderer/src/components/chat/ChatHeader.tsx index 7a4bb7f..b5b16da 100644 --- a/src/renderer/src/components/chat/ChatHeader.tsx +++ b/src/renderer/src/components/chat/ChatHeader.tsx @@ -2,7 +2,7 @@ import React, { useState } from 'react' import { Contact } from '../../../../shared/types' import { Button, IconButton, Tooltip, TooltipContent, TooltipTrigger } from '../ui' import { ConversationContentSearch } from './ConversationContentSearch' -import { AiIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons' +import { AiIcon, ExportIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons' import { supportsPersonalWechatSend } from '../../utils/runtime-environment' import { GroupMemberStatsDialog } from '../group-stats/GroupMemberStatsDialog' @@ -16,6 +16,7 @@ interface ChatHeaderProps { onContentFilterChange: (value: string) => void onRefresh?: () => void onTestSend: () => void + onSendFile?: () => void onOpenAiSettings: () => void /** 跳到「设置 · 本地索引」(群统计发现索引没追平时用)。 */ onOpenLocalIndexSettings?: () => void @@ -31,6 +32,7 @@ export function ChatHeader({ onContentFilterChange, onRefresh, onTestSend, + onSendFile, onOpenAiSettings, onOpenLocalIndexSettings }: ChatHeaderProps): React.ReactElement { @@ -131,6 +133,19 @@ export function ChatHeader({ 仅支持 macOS 和 Windows )} + {supportsPersonalWechatSend && onSendFile ? ( + + ) : null} + + )} + + {setupReady && !initialImage && !initialFile && ( )} - {setupReady && isMac && !initialImage && ( + {setupReady && isMac && !initialImage && !initialFile && (