diff --git a/.gitignore b/.gitignore index 90a65a3..e9dc1e1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,10 +10,12 @@ coverage/ playwright-report/ test-results/ resources/connectors/wechat/ +resources/connectors/wechat-personal/ .omc .codex/ services/share-card-worker/.wrangler/ services/share-card-worker/wrangler.local.jsonc +skills-lock.json docs/design/ docs/ui-redesign-plan.md docs/ui-redesign-spec.md @@ -21,3 +23,4 @@ AGENTS.md findings.md progress.md task_plan.md +.agents diff --git a/docs/third-party/wechat-chatter/LICENSE b/docs/third-party/wechat-chatter/LICENSE new file mode 100644 index 0000000..480c736 --- /dev/null +++ b/docs/third-party/wechat-chatter/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2026 yincongcyincong + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/third-party/wechat-chatter/NOTICE.md b/docs/third-party/wechat-chatter/NOTICE.md new file mode 100644 index 0000000..c4ce5fa --- /dev/null +++ b/docs/third-party/wechat-chatter/NOTICE.md @@ -0,0 +1,28 @@ +# wechat_chatter / OneBot 第三方组件说明 + +TraceMemo 的 macOS 个人微信发送功能会按需使用以下第三方组件: + +- 项目:`yincongcyincong/wechat_chatter` +- 上游仓库:https://github.com/yincongcyincong/wechat_chatter +- 当前运行时版本:`v0.0.18` +- 运行时文件:`onebot_mac_arm64.tar.gz` +- 许可证:GNU General Public License version 3(GPL-3.0) +- 上游版权:Copyright (C) 2026 yincongcyincong +- TraceMemo 修改日期:2026-08-17 + +## 集成方式 + +OneBot 运行时不会随 TraceMemo 安装包一起分发。用户启用该实验性功能时,TraceMemo 会从上述上游项目的 GitHub Release 按需下载运行时,并将其安装到应用的用户数据目录。 + +运行时作为独立进程启动,TraceMemo 通过本机 HTTP 接口与其通信。 + +## 本地修改 + +为适配连续发送、图片上传 Hook 状态检测以及微信核心模块基址定位,TraceMemo 会在用户设备上对上游 `onebot/script.js` 应用兼容性补丁。补丁逻辑位于: + +- `scripts/prepare-wechat-chatter-runtime.cjs` +- `src/main/services/personal-wechat-runtime-manager.ts` + +补丁中源自或修改自上游 `script.js` 的部分,以及补丁应用后产生的修改版 `script.js`,继续按照 GPL-3.0 提供。本说明只针对该第三方组件及相关修改,不用于声明 TraceMemo 仓库其他部分的许可证。 + +GPL-3.0 的完整文本见本目录下的 `LICENSE`。 diff --git a/electron-builder.yml b/electron-builder.yml index 0fce8e7..ca68915 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -25,6 +25,7 @@ extraResources: to: resources filter: - '**/*' + - '!connectors/wechat-personal/**' - from: docs/skill/tracememo-reader to: skill/tracememo-reader filter: diff --git a/package.json b/package.json index eaf305b..2eb282c 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "cp:env": "node scripts/ensure-env.cjs", "prepare:env": "node scripts/ensure-env.cjs", "prepare:ffmpeg:win": "node scripts/prepare-electron-runtime.cjs --platform win32 --arch x64", + "prepare:wechat-personal": "node scripts/prepare-wechat-chatter-runtime.cjs", "start": "electron-vite preview", "dev": "node scripts/ensure-env.cjs && node scripts/build-wechat-connector.cjs && electron-vite dev", "test:wechat-connector": "go -C services/wechat-connector test ./... && go -C services/wechat-connector vet ./...", @@ -135,4 +136,4 @@ "ffmpeg-static" ] } -} \ No newline at end of file +} diff --git a/scripts/manage-wechat-update-block.sh b/scripts/manage-wechat-update-block.sh new file mode 100755 index 0000000..837ca24 --- /dev/null +++ b/scripts/manage-wechat-update-block.sh @@ -0,0 +1,64 @@ +#!/bin/sh +set -eu + +ANCHOR='com.tencent.wechat.update' +ANCHOR_FILE='/etc/pf.anchors/wechat-update' +PF_CONF='/etc/pf.conf' +BACKUP_DIR='/etc/pf.conf.wechat-backups' +CACHE_DIR="${HOME}/Library/Caches/com.tencent.xinWeChat" + +domains='dldir1.qq.com dldir2.qq.com dldir3.qq.com dldir1v6.qq.com' + +die() { printf '%s\n' "error: $*" >&2; exit 1; } +need_root() { [ "$(id -u)" -eq 0 ] || die '请使用 sudo 执行此脚本'; } + +resolve_ips() { + command -v dig >/dev/null 2>&1 || die '需要 dig(macOS 通常已内置)' + for domain in $domains; do + dig +short A "$domain" + dig +short AAAA "$domain" + done | awk '/^[0-9]+(\.[0-9]+){3}$/ || /^[0-9A-Fa-f:]+:[0-9A-Fa-f:]+/' | sort -u +} + +enable() { + need_root + ips="$(resolve_ips)" + [ -n "$ips" ] || die '域名解析没有返回 IP,未修改 PF' + mkdir -p /etc/pf.anchors "$BACKUP_DIR" + backup="$BACKUP_DIR/pf.conf.$(date +%Y%m%d-%H%M%S)" + cp -p "$PF_CONF" "$backup" + { + printf 'table persist { ' + printf '%s' "$ips" | tr '\n' ' ' + printf '}\nblock drop out quick to \n' + } > "$ANCHOR_FILE" + if ! grep -Fq 'anchor "com.tencent.wechat.update"' "$PF_CONF"; then + printf '\n# TraceMemo: block WeChat update endpoints\nanchor "com.tencent.wechat.update"\nload anchor "com.tencent.wechat.update" from "/etc/pf.anchors/wechat-update"\n' >> "$PF_CONF" + fi + pfctl -vnf "$PF_CONF" + pfctl -f "$PF_CONF" + pfctl -E >/dev/null 2>&1 || true + printf '已启用微信更新拦截,规则备份:%s\n' "$backup" + printf '当前 IP:\n%s\n' "$ips" +} + +disable() { + need_root + pfctl -a "$ANCHOR" -F all >/dev/null 2>&1 || true + printf '已清空微信更新 PF anchor。要完全移除配置行,请从 /etc/pf.conf 删除 TraceMemo 标记的三行。\n' +} + +status() { + pfctl -s info 2>&1 | head -20 + printf '\n微信更新 anchor:\n' + pfctl -a "$ANCHOR" -sr 2>&1 || true + printf '\n缓存目录:\n%s\n' "$CACHE_DIR" + ls -ldO "$CACHE_DIR" 2>/dev/null || true +} + +case "${1:-status}" in + enable) enable ;; + disable) disable ;; + status) status ;; + *) die "用法:sudo $0 {enable|disable|status}" ;; +esac diff --git a/scripts/prepare-wechat-chatter-runtime.cjs b/scripts/prepare-wechat-chatter-runtime.cjs new file mode 100644 index 0000000..c196f87 --- /dev/null +++ b/scripts/prepare-wechat-chatter-runtime.cjs @@ -0,0 +1,225 @@ +/* + * wechat_chatter runtime integration + * + * Upstream: https://github.com/yincongcyincong/wechat_chatter + * Runtime version: v0.0.18 + * Upstream license: GNU General Public License version 3 (GPL-3.0) + * + * This file applies local compatibility patches to the upstream + * onebot/script.js. See docs/third-party/wechat-chatter/NOTICE.md. + */ + +/* eslint-disable @typescript-eslint/no-require-imports */ +const { execFileSync } = require('node:child_process') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + +const release = 'v0.0.18' +const asset = 'onebot_mac_arm64.tar.gz' +const url = `https://github.com/yincongcyincong/wechat_chatter/releases/download/${release}/${asset}` +const projectRoot = path.resolve(__dirname, '..') +const outputDir = path.join( + projectRoot, + 'resources', + 'connectors', + 'wechat-personal', + 'darwin-arm64' +) +const archive = path.join(os.tmpdir(), `wechat-chatter-${release}-${asset}`) +const appleSilicon = + process.platform === 'darwin' && + execFileSync('/usr/sbin/sysctl', ['-n', 'hw.optional.arm64'], { encoding: 'utf8' }).trim() === '1' + +if (!appleSilicon) { + throw new Error('个人微信发送运行时当前仅支持 macOS arm64') +} + +fs.mkdirSync(outputDir, { recursive: true }) +let archiveReady = false +if (fs.existsSync(archive)) { + try { + execFileSync('/usr/bin/tar', ['-tzf', archive], { stdio: 'ignore' }) + archiveReady = true + console.log(`[wechat-personal] 复用已下载归档:${archive}`) + } catch { + // The archive is partial or invalid; curl will resume it below. + } +} +if (!archiveReady) { + console.log(`[wechat-personal] 下载 ${release},支持断点续传:${archive}`) + execFileSync( + '/usr/bin/curl', + ['--http1.1', '-L', '--fail', '--retry', '3', '--continue-at', '-', '--output', archive, url], + { stdio: 'inherit' } + ) +} + +const extractionDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wechat-chatter-extract-')) +console.log(`[wechat-personal] 解压并原子安装到 ${outputDir}`) +try { + execFileSync('/usr/bin/tar', ['-xzf', archive, '-C', extractionDir], { stdio: 'inherit' }) + fs.mkdirSync(path.join(outputDir, 'onebot'), { recursive: true }) + fs.mkdirSync(path.join(outputDir, 'wechat_version'), { recursive: true }) + fs.copyFileSync( + path.join(extractionDir, 'onebot', 'script.js'), + path.join(outputDir, 'onebot', 'script.js') + ) + fs.cpSync(path.join(extractionDir, 'wechat_version'), path.join(outputDir, 'wechat_version'), { + recursive: true, + force: true + }) + const stagedExecutable = path.join(outputDir, 'onebot', `.onebot-${process.pid}.tmp`) + fs.copyFileSync(path.join(extractionDir, 'onebot', 'onebot'), stagedExecutable) + fs.chmodSync(stagedExecutable, 0o755) + fs.renameSync(stagedExecutable, path.join(outputDir, 'onebot', 'onebot')) +} finally { + fs.rmSync(extractionDir, { recursive: true, force: true }) +} + +const executable = path.join(outputDir, 'onebot', 'onebot') +const script = path.join(outputDir, 'onebot', 'script.js') +const config = path.join(outputDir, 'wechat_version', '4_1_11_53_mac.json') +for (const required of [executable, script, config]) { + if (!fs.existsSync(required)) throw new Error(`运行时文件缺失:${required}`) +} + +const pythonPackages = path.join(outputDir, 'python') +const pilkPackage = path.join(pythonPackages, 'pilk') +if (!fs.existsSync(pilkPackage)) { + console.log('[wechat-personal] 安装项目内语音编码器 pilk') + fs.mkdirSync(pythonPackages, { recursive: true }) + try { + execFileSync( + 'python3', + [ + '-m', + 'pip', + 'install', + '--disable-pip-version-check', + '--no-compile', + '--target', + pythonPackages, + 'pilk==0.2.4' + ], + { stdio: 'inherit' } + ) + } catch { + console.warn('[wechat-personal] pilk 安装失败,将使用 OneBot 内置的 Go SILK 编码器') + } +} + +function patchPerSendPayload(scriptPath) { + let source = fs.readFileSync(scriptPath, 'utf8') + if (source.includes('var activeTriggerX1Payload = ptr(0);')) return + + const declarations = 'var triggerX1Payload;\nvar triggerX0;' + const patchedDeclarations = + 'var triggerX1Payload;\nvar activeTriggerX1Payload = ptr(0);\nvar triggerX0;' + const originalSend = ` const payloadData = hexToByteArray(payloadHex); + triggerX1Payload.writeByteArray(payloadData); + triggerX1Payload.add(0x18).writePointer(info.cgiAddr); + triggerX1Payload.add(0xb8).writePointer(triggerX1Payload.add(0xc0)); + triggerX1Payload.add(0x190).writePointer(triggerX1Payload.add(0x198));` + const patchedSend = ` const payloadData = hexToByteArray(payloadHex); + activeTriggerX1Payload = Memory.alloc(payloadData.length); + activeTriggerX1Payload.writeByteArray(payloadData); + activeTriggerX1Payload.add(0x18).writePointer(info.cgiAddr); + activeTriggerX1Payload.add(0xb8).writePointer(activeTriggerX1Payload.add(0xc0)); + activeTriggerX1Payload.add(0x190).writePointer(activeTriggerX1Payload.add(0x198));` + + if (!source.includes(declarations) || !source.includes(originalSend)) { + throw new Error('无法定位 wechat_chatter 连续发送补丁位置') + } + source = source.replace(declarations, patchedDeclarations).replace(originalSend, patchedSend) + source = source.replace( + ' MMStartTask(triggerX0, triggerX1Payload);', + ' MMStartTask(triggerX0, activeTriggerX1Payload);' + ) + source = source.replace( + ' } catch (e) {\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);', + ' } catch (e) {\n activeTriggerX1Payload = ptr(0);\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);' + ) + source = source.replace( + '\t\t\t\tpendingSendMsgType = "";\n\t\t\t\treturn', + '\t\t\t\tpendingSendMsgType = "";\n\t\t\t\tactiveTriggerX1Payload = ptr(0);\n\t\t\t\treturn' + ) + fs.writeFileSync(scriptPath, source) + console.log('[wechat-personal] 已应用逐条发送 payload 隔离补丁') +} + +function patchImageHookReadiness(scriptPath) { + let source = fs.readFileSync(scriptPath, 'utf8') + if ( + source.includes('捕获到图片上传上下文,uploadGlobalX0') && + source.includes('图片上传 Hook Setup Complete') + ) + return + const original = `\t\t\tuploadGlobalX0 = this.context.x0;` + const patched = `\t\t\tconst capturedUploadX0 = this.context.x0; +\t\t\tif (uploadGlobalX0.equals(ptr(0)) && !capturedUploadX0.equals(ptr(0))) { +\t\t\t\tconsole.log("[+] 捕获到图片上传上下文,uploadGlobalX0:" + capturedUploadX0); +\t\t\t} +\t\t\tuploadGlobalX0 = capturedUploadX0;` + if (!source.includes(original)) throw new Error('无法定位 wechat_chatter 图片 Hook 状态补丁位置') + source = source.replace(original, patched) + source = source.replace( + ' })\n}\n\n\n\nfunction patchCdnOnComplete()', + ' })\n console.log("[+] 图片上传 Hook Setup Complete.");\n}\n\n\n\nfunction patchCdnOnComplete()' + ) + fs.writeFileSync(scriptPath, source) + console.log('[wechat-personal] 已应用图片 Hook 状态补丁') +} + +function patchWechatCoreModuleBase(scriptPath) { + let source = fs.readFileSync(scriptPath, 'utf8') + if (source.includes('WeChat core module base:')) return + const initMarker = 'function initAddresses() {' + const initIndex = source.indexOf(initMarker) + if (initIndex < 0 || !source.startsWith('var targetPath = ')) { + throw new Error('无法定位 wechat_chatter 基址扫描逻辑') + } + const patchedHeader = `var targetPath = "/Applications/WeChat.app/Contents/Resources/wechat.dylib"; +var module = Process.enumerateModules().find(function(m) { + return m.path === targetPath || m.path.endsWith("/Contents/Resources/wechat.dylib"); +}); +if (!module) { + throw new Error("[-] Cannot find WeChat core module: " + targetPath); +} +var moduleBase = module.base; +var baseAddr = moduleBase; +console.log("[+] WeChat core module base: " + baseAddr + " path=" + module.path); +setImmediate(initAddresses); + +` + source = patchedHeader + source.slice(initIndex) + fs.writeFileSync(scriptPath, source) + console.log('[wechat-personal] 已应用微信核心模块基址补丁') +} + +function addModifiedWorkNotice(scriptPath) { + let source = fs.readFileSync(scriptPath, 'utf8') + if (source.includes('TraceMemo wechat_chatter compatibility modifications')) return + + const notice = `/* + * TraceMemo wechat_chatter compatibility modifications + * Modified: 2026-08-17 + * Upstream: https://github.com/yincongcyincong/wechat_chatter + * Runtime version: v0.0.18 + * License: GNU General Public License version 3 (GPL-3.0) + * Changes: WeChat module discovery, per-send payload isolation, and image Hook readiness logging. + * These modifications are not provided by the upstream author. + */ + +` + source = notice + source + fs.writeFileSync(scriptPath, source) + console.log('[wechat-personal] 已写入 GPL 修改声明') +} + +patchWechatCoreModuleBase(script) +patchPerSendPayload(script) +patchImageHookReadiness(script) +addModifiedWorkNotice(script) +fs.chmodSync(executable, 0o755) +console.log('[wechat-personal] 运行时准备完成') diff --git a/src/main/index.ts b/src/main/index.ts index c1a1e18..2de63a4 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -16,9 +16,8 @@ import { dialog, protocol } from 'electron' -import { dirname, join } from 'path' +import { basename, dirname, extname, join } from 'path' import { existsSync, promises as fsPromises } from 'fs' -import { extname } from 'path' import { electronApp, optimizer, is } from '@electron-toolkit/utils' import icon from '../../resources/icon.png?asset' import { WechatDb } from './wechat-db' @@ -112,6 +111,15 @@ import { } from './services/bootstrap-cache' import { installSafeConsole } from './safe-log' import { agentHubService } from './services/agent-hub-service' +import { personalWechatSendService } from './services/personal-wechat-send-service' +import { PersonalWechatRuntimeManager } from './services/personal-wechat-runtime-manager' +import type { PersonalWechatSendRequest } from '../shared/personal-wechat' +import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service' +import type { + ListTextToSpeechVoicesRequest, + SaveTextToSpeechSettingsRequest, + SynthesizeTextToSpeechRequest +} from '../shared/text-to-speech' import { appLogger } from './app-logger' import type { AppLogEntry } from '../shared/app-log' import { appUpdateService } from './services/app-update-service' @@ -158,6 +166,8 @@ let videoAssetService: VideoAssetService | null = null const databaseKeyStore = new DatabaseKeyStore() const imageKeyConfigService = new ImageKeyConfigService() const aiProviderService = new AIProviderService() +const textToSpeechSettingsService = new TextToSpeechSettingsService() +const personalWechatRuntimeManager = new PersonalWechatRuntimeManager() const keyServiceMac = new KeyServiceMac() const keyServiceWin = new KeyServiceWin() const wechatShareConfigStore = new WechatShareConfigStore() @@ -591,6 +601,11 @@ app.whenReady().then(async () => { if (!window.isDestroyed()) window.webContents.send('voice:modelProgress', status) } }) + personalWechatRuntimeManager.setProgressListener((status) => { + for (const window of BrowserWindow.getAllWindows()) { + if (!window.isDestroyed()) window.webContents.send('wechat-personal:runtimeProgress', status) + } + }) protocol.handle('wxe-media', async (request) => { const filePath = videoAssetService?.pathForUrl(request.url) if (!filePath) return new Response('Not found', { status: 404 }) @@ -1135,6 +1150,28 @@ app.whenReady().then(async () => { aiProviderService.migrateLegacy(config) ) + ipcMain.handle('tts:getSettings', () => textToSpeechSettingsService.get()) + ipcMain.handle('tts:saveSettings', (_, request: SaveTextToSpeechSettingsRequest) => + textToSpeechSettingsService.save(request) + ) + ipcMain.handle('tts:listVoices', (_, request?: ListTextToSpeechVoicesRequest) => + textToSpeechSettingsService.listVoices(request) + ) + ipcMain.handle('tts:synthesize', (_, request: SynthesizeTextToSpeechRequest) => + textToSpeechSettingsService.synthesize(request) + ) + ipcMain.handle('tts:removeGeneratedAudio', (_, filePath: string) => + textToSpeechSettingsService.removeGeneratedAudio(String(filePath || '')) + ) + ipcMain.handle('tts:openApiKeys', async () => { + try { + await shell.openExternal('https://fish.audio/app/api-keys/') + return { success: true } + } catch { + return { success: false, error: '无法打开 Fish Audio API Key 页面' } + } + }) + ipcMain.handle('copy-image', async (_, imageSource: unknown) => { try { if (typeof imageSource !== 'string' || !imageSource) { @@ -1702,6 +1739,59 @@ app.whenReady().then(async () => { ipcMain.handle('agent-hub:cancelLogin', () => agentHubService.cancelLogin()) ipcMain.handle('agent-hub:reconnect', () => agentHubService.reconnect()) ipcMain.handle('agent-hub:disconnect', () => agentHubService.disconnect()) + ipcMain.handle('wechat-personal:getStatus', () => personalWechatSendService.getStatus()) + ipcMain.handle('wechat-personal:getRuntimeStatus', () => + personalWechatRuntimeManager.getStatus() + ) + ipcMain.handle('wechat-personal:downloadRuntime', () => personalWechatRuntimeManager.download()) + ipcMain.handle('wechat-personal:cancelRuntimeDownload', () => ({ + success: personalWechatRuntimeManager.cancelDownload() + })) + ipcMain.handle('wechat-personal:removeRuntime', async () => { + await personalWechatSendService.terminate() + return personalWechatRuntimeManager.remove() + }) + ipcMain.handle('wechat-personal:openRuntimeDirectory', async () => { + const status = await personalWechatRuntimeManager.getStatus() + const directory = status.directory || personalWechatRuntimeManager.directory + await fsPromises.mkdir(directory, { recursive: true }) + const error = await shell.openPath(directory) + return error ? { success: false, error } : { success: true } + }) + ipcMain.handle('wechat-personal:rebind', () => personalWechatSendService.rebind()) + ipcMain.handle('wechat-personal:send', (_, request: PersonalWechatSendRequest) => + personalWechatSendService.send(request) + ) + ipcMain.handle('wechat-personal:selectImage', async (event) => { + const window = BrowserWindow.fromWebContents(event.sender) + const result = await dialog.showOpenDialog(window!, { + title: '选择要通过个人微信测试发送的图片', + properties: ['openFile'], + filters: [ + { name: '图片', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] }, + { name: '所有文件', extensions: ['*'] } + ] + }) + if (result.canceled || !result.filePaths[0]) return { canceled: true } + return { + canceled: false, + path: result.filePaths[0], + name: basename(result.filePaths[0]) + } + }) + ipcMain.handle('wechat-personal:selectVoice', async (event) => { + const window = BrowserWindow.fromWebContents(event.sender) + const result = await dialog.showOpenDialog(window!, { + title: '选择要通过个人微信测试发送的语音', + properties: ['openFile'], + filters: [ + { name: '语音', extensions: ['silk', 'mp3', 'wav', 'm4a', 'aac', 'ogg', 'flac'] }, + { name: '所有文件', extensions: ['*'] } + ] + }) + if (result.canceled || !result.filePaths[0]) return { canceled: true } + return { canceled: false, path: result.filePaths[0], name: basename(result.filePaths[0]) } + }) ipcMain.handle('agent-hub:selectTestImage', async (event) => { const window = BrowserWindow.fromWebContents(event.sender) const result = await dialog.showOpenDialog(window!, { @@ -1761,6 +1851,7 @@ app.on('before-quit', (event) => { void (async () => { agentHubService.stop() + personalWechatSendService.stop() flushBootstrapCacheWritesSync() const [, nativeCallsDrained] = await Promise.all([ apiServer.stop().catch(() => undefined), diff --git a/src/main/services/personal-wechat-runtime-manager.ts b/src/main/services/personal-wechat-runtime-manager.ts new file mode 100644 index 0000000..fa11935 --- /dev/null +++ b/src/main/services/personal-wechat-runtime-manager.ts @@ -0,0 +1,364 @@ +import { createHash } from 'crypto' +import { execFile } from 'child_process' +import { app, net } from 'electron' +import { existsSync, readFileSync, writeFileSync } from 'fs' +import { chmod, copyFile, cp, mkdir, mkdtemp, open, rename, rm, stat } from 'fs/promises' +import { tmpdir } from 'os' +import { dirname, join } from 'path' +import { promisify } from 'util' +import type { + PersonalWechatRuntimeDownloadResult, + PersonalWechatRuntimeStatus +} from '../../shared/personal-wechat-runtime' +import { findPersonalWechatRuntime } from './personal-wechat-send-service' + +const execFileAsync = promisify(execFile) +const RUNTIME_VERSION = 'v0.0.18' +const ARCHIVE_NAME = 'onebot_mac_arm64.tar.gz' +const ARCHIVE_URL = `https://github.com/yincongcyincong/wechat_chatter/releases/download/${RUNTIME_VERSION}/${ARCHIVE_NAME}` +const ARCHIVE_SIZE = 66_599_785 +const ARCHIVE_SHA256 = 'ee1e11bccef7cec1cf944cd8b2ac3fadaadb9376ba24cd823e3409143e107dab' + +function patchPerSendPayload(scriptPath: string): void { + let source = readFileSync(scriptPath, 'utf8') + if (source.includes('var activeTriggerX1Payload = ptr(0);')) return + + const declarations = 'var triggerX1Payload;\nvar triggerX0;' + const patchedDeclarations = + 'var triggerX1Payload;\nvar activeTriggerX1Payload = ptr(0);\nvar triggerX0;' + const originalSend = ` const payloadData = hexToByteArray(payloadHex); + triggerX1Payload.writeByteArray(payloadData); + triggerX1Payload.add(0x18).writePointer(info.cgiAddr); + triggerX1Payload.add(0xb8).writePointer(triggerX1Payload.add(0xc0)); + triggerX1Payload.add(0x190).writePointer(triggerX1Payload.add(0x198));` + const patchedSend = ` const payloadData = hexToByteArray(payloadHex); + activeTriggerX1Payload = Memory.alloc(payloadData.length); + activeTriggerX1Payload.writeByteArray(payloadData); + activeTriggerX1Payload.add(0x18).writePointer(info.cgiAddr); + activeTriggerX1Payload.add(0xb8).writePointer(activeTriggerX1Payload.add(0xc0)); + activeTriggerX1Payload.add(0x190).writePointer(activeTriggerX1Payload.add(0x198));` + + if (!source.includes(declarations) || !source.includes(originalSend)) { + throw new Error('下载的发送组件与当前应用不兼容') + } + source = source.replace(declarations, patchedDeclarations).replace(originalSend, patchedSend) + source = source.replace( + ' MMStartTask(triggerX0, triggerX1Payload);', + ' MMStartTask(triggerX0, activeTriggerX1Payload);' + ) + source = source.replace( + ' } catch (e) {\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);', + ' } catch (e) {\n activeTriggerX1Payload = ptr(0);\n console.error("[!] Error trigger " + msgType + " MMStartTask: " + e);' + ) + source = source.replace( + '\t\t\t\tpendingSendMsgType = "";\n\t\t\t\treturn', + '\t\t\t\tpendingSendMsgType = "";\n\t\t\t\tactiveTriggerX1Payload = ptr(0);\n\t\t\t\treturn' + ) + writeFileSync(scriptPath, source) +} + +function patchImageHookReadiness(scriptPath: string): void { + let source = readFileSync(scriptPath, 'utf8') + if ( + source.includes('捕获到图片上传上下文,uploadGlobalX0') && + source.includes('图片上传 Hook Setup Complete') + ) { + return + } + const original = `\t\t\tuploadGlobalX0 = this.context.x0;` + const patched = `\t\t\tconst capturedUploadX0 = this.context.x0; +\t\t\tif (uploadGlobalX0.equals(ptr(0)) && !capturedUploadX0.equals(ptr(0))) { +\t\t\t\tconsole.log("[+] 捕获到图片上传上下文,uploadGlobalX0:" + capturedUploadX0); +\t\t\t} +\t\t\tuploadGlobalX0 = capturedUploadX0;` + if (!source.includes(original)) throw new Error('下载的媒体组件与当前应用不兼容') + source = source.replace(original, patched) + source = source.replace( + ' })\n}\n\n\n\nfunction patchCdnOnComplete()', + ' })\n console.log("[+] 图片上传 Hook Setup Complete.");\n}\n\n\n\nfunction patchCdnOnComplete()' + ) + writeFileSync(scriptPath, source) +} + +function patchWechatCoreModuleBase(scriptPath: string): void { + let source = readFileSync(scriptPath, 'utf8') + if (source.includes('WeChat core module base:')) return + const initMarker = 'function initAddresses() {' + const initIndex = source.indexOf(initMarker) + if (initIndex < 0 || !source.startsWith('var targetPath = ')) { + throw new Error('下载的微信版本配置与当前应用不兼容') + } + const patchedHeader = `var targetPath = "/Applications/WeChat.app/Contents/Resources/wechat.dylib"; +var module = Process.enumerateModules().find(function(m) { + return m.path === targetPath || m.path.endsWith("/Contents/Resources/wechat.dylib"); +}); +if (!module) { + throw new Error("[-] Cannot find WeChat core module: " + targetPath); +} +var moduleBase = module.base; +var baseAddr = moduleBase; +console.log("[+] WeChat core module base: " + baseAddr + " path=" + module.path); +setImmediate(initAddresses); + +` + source = patchedHeader + source.slice(initIndex) + writeFileSync(scriptPath, source) +} + +function addModifiedWorkNotice(scriptPath: string): void { + let source = readFileSync(scriptPath, 'utf8') + if (source.includes('TraceMemo wechat_chatter compatibility modifications')) return + source = `/* + * TraceMemo wechat_chatter compatibility modifications + * Modified: 2026-08-17 + * Upstream: https://github.com/yincongcyincong/wechat_chatter + * Runtime version: v0.0.18 + * License: GNU General Public License version 3 (GPL-3.0) + * Changes: WeChat module discovery, per-send payload isolation, and image Hook readiness logging. + * These modifications are not provided by the upstream author. + */ + +${source}` + writeFileSync(scriptPath, source) +} + +export class PersonalWechatRuntimeManager { + private downloadController: AbortController | null = null + private downloadPromise: Promise | null = null + private downloadedBytes = 0 + private lastProgressAt = 0 + private progressListener: ((status: PersonalWechatRuntimeStatus) => void) | null = null + + get directory(): string { + return join(app.getPath('userData'), 'connectors', 'wechat-personal', 'darwin-arm64') + } + + private get archivePath(): string { + return join( + app.getPath('userData'), + 'downloads', + `wechat-chatter-${RUNTIME_VERSION}-${ARCHIVE_NAME}` + ) + } + + setProgressListener(listener: ((status: PersonalWechatRuntimeStatus) => void) | null): void { + this.progressListener = listener + } + + async getStatus(): Promise { + if (!this.isSupported()) { + return this.buildStatus( + 'unsupported', + 0, + process.platform === 'win32' + ? 'Windows 暂不支持个人微信发送组件' + : `当前系统暂不支持个人微信发送组件:${process.platform} ${process.arch}` + ) + } + if (this.downloadPromise) return this.buildStatus('downloading', this.downloadedBytes) + + const runtime = findPersonalWechatRuntime() + if (runtime) { + return this.buildStatus('ready', ARCHIVE_SIZE, undefined, runtime.root) + } + + const hasPartialInstall = await this.hasPartialInstall() + return this.buildStatus( + hasPartialInstall ? 'invalid' : 'missing', + 0, + hasPartialInstall ? '发送组件文件不完整,请重新下载' : undefined, + hasPartialInstall ? this.directory : undefined + ) + } + + download(): Promise { + if (!this.isSupported()) { + return this.getStatus().then((status) => ({ success: false, status, error: status.error })) + } + if (this.downloadPromise) return this.downloadPromise + this.downloadedBytes = 0 + this.downloadController = new AbortController() + this.downloadPromise = this.runDownload(this.downloadController.signal).finally(() => { + this.downloadPromise = null + this.downloadController = null + }) + return this.downloadPromise + } + + cancelDownload(): boolean { + if (!this.downloadController) return false + this.downloadController.abort() + return true + } + + async remove(): Promise { + if (this.downloadPromise) return this.buildStatus('downloading', this.downloadedBytes) + await Promise.all([ + rm(this.directory, { recursive: true, force: true }), + rm(this.archivePath, { force: true }), + rm(`${this.archivePath}.partial`, { force: true }) + ]) + return this.getStatus() + } + + private async runDownload(signal: AbortSignal): Promise { + const archive = this.archivePath + const downloadsDirectory = dirname(archive) + const partial = `${archive}.partial` + let extractionDirectory = '' + let stagedDirectory = '' + try { + await mkdir(downloadsDirectory, { recursive: true }) + await rm(partial, { force: true }) + const response = await net.fetch(ARCHIVE_URL, { signal }) + if (!response.ok || !response.body) { + throw new Error(`发送组件下载失败:HTTP ${response.status}`) + } + + const handle = await open(partial, 'w') + const hash = createHash('sha256') + try { + const reader = response.body.getReader() + while (true) { + const { done, value } = await reader.read() + if (done) break + if (signal.aborted) throw new DOMException('Download cancelled', 'AbortError') + const chunk = Buffer.from(value) + await handle.write(chunk) + hash.update(chunk) + this.downloadedBytes += chunk.length + this.reportProgress(this.buildStatus('downloading', this.downloadedBytes)) + } + } finally { + await handle.close() + } + + if (this.downloadedBytes !== ARCHIVE_SIZE || hash.digest('hex') !== ARCHIVE_SHA256) { + throw new Error('发送组件校验失败,请重新下载') + } + await rm(archive, { force: true }) + await rename(partial, archive) + + extractionDirectory = await mkdtemp(join(tmpdir(), 'wechat-chatter-extract-')) + await execFileAsync('/usr/bin/tar', ['-xzf', archive, '-C', extractionDirectory]) + stagedDirectory = `${this.directory}.installing-${process.pid}` + await rm(stagedDirectory, { recursive: true, force: true }) + await mkdir(dirname(stagedDirectory), { recursive: true }) + await mkdir(join(stagedDirectory, 'onebot'), { recursive: true }) + + const sourceOneBot = join(extractionDirectory, 'onebot') + const sourceVersions = join(extractionDirectory, 'wechat_version') + await Promise.all([ + cp(sourceVersions, join(stagedDirectory, 'wechat_version'), { + recursive: true, + force: true + }), + copyFile(join(sourceOneBot, 'onebot'), join(stagedDirectory, 'onebot', 'onebot')), + copyFile(join(sourceOneBot, 'script.js'), join(stagedDirectory, 'onebot', 'script.js')) + ]) + + const executable = join(stagedDirectory, 'onebot', 'onebot') + const script = join(stagedDirectory, 'onebot', 'script.js') + patchWechatCoreModuleBase(script) + patchPerSendPayload(script) + patchImageHookReadiness(script) + addModifiedWorkNotice(script) + await chmod(executable, 0o755) + + const pythonPackages = join(stagedDirectory, 'python') + await mkdir(pythonPackages, { recursive: true }) + try { + await execFileAsync('/usr/bin/env', [ + 'python3', + '-m', + 'pip', + 'install', + '--disable-pip-version-check', + '--no-compile', + '--target', + pythonPackages, + 'pilk==0.2.4' + ]) + } catch (error) { + console.warn( + '[PersonalWechatRuntime] pilk 安装失败,将使用 OneBot 内置的 Go SILK 编码器:', + error + ) + } + + for (const required of [ + executable, + script, + join(stagedDirectory, 'wechat_version', '4_1_11_53_mac.json') + ]) { + if (!existsSync(required)) throw new Error('发送组件解压后文件不完整') + } + + await rm(this.directory, { recursive: true, force: true }) + await rename(stagedDirectory, this.directory) + stagedDirectory = '' + const status = this.buildStatus('ready', ARCHIVE_SIZE, undefined, this.directory) + this.reportProgress(status, true) + return { success: true, status } + } catch (error) { + const cancelled = signal.aborted + const message = cancelled + ? '发送组件下载已取消' + : error instanceof Error + ? error.message + : String(error) + await rm(partial, { force: true }) + const status = this.buildStatus( + cancelled ? 'missing' : 'error', + this.downloadedBytes, + message + ) + this.reportProgress(status, true) + return { success: false, status, error: message } + } finally { + if (extractionDirectory) await rm(extractionDirectory, { recursive: true, force: true }) + if (stagedDirectory) await rm(stagedDirectory, { recursive: true, force: true }) + } + } + + private async hasPartialInstall(): Promise { + try { + await stat(this.directory) + return true + } catch { + return false + } + } + + private isSupported(): boolean { + return process.platform === 'darwin' && process.arch === 'arm64' + } + + private buildStatus( + state: PersonalWechatRuntimeStatus['state'], + downloadedBytes: number, + error?: string, + directory?: string + ): PersonalWechatRuntimeStatus { + return { + version: RUNTIME_VERSION, + state, + downloadedBytes, + totalBytes: ARCHIVE_SIZE, + progress: ARCHIVE_SIZE ? Math.min(1, downloadedBytes / ARCHIVE_SIZE) : 0, + platform: process.platform, + architecture: process.arch, + supported: this.isSupported(), + removable: directory === this.directory, + ...(directory ? { directory } : {}), + ...(error ? { error } : {}) + } + } + + private reportProgress(status: PersonalWechatRuntimeStatus, force = false): void { + const now = Date.now() + if (!force && now - this.lastProgressAt < 100) return + this.lastProgressAt = now + this.progressListener?.(status) + } +} diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts new file mode 100644 index 0000000..6ba6878 --- /dev/null +++ b/src/main/services/personal-wechat-send-service.ts @@ -0,0 +1,880 @@ +import { app } from 'electron' +import { execFile, spawn, type ChildProcess } from 'child_process' +import { createHash } from 'crypto' +import { existsSync, readFileSync, readdirSync, statSync } from 'fs' +import { createConnection } from 'net' +import { homedir } from 'os' +import { delimiter, dirname, join, sep } from 'path' +import ffmpegStaticPath from 'ffmpeg-static' +import { promisify } from 'util' +import type { + PersonalWechatSendRequest, + PersonalWechatSendResult, + PersonalWechatSenderStatus +} from '../../shared/personal-wechat' +import { isPackagedRuntime } from '../runtime-mode' +import { SilkAudioDecoder } from '../voice-pipeline/audio-decoder' + +const execFileAsync = promisify(execFile) +const DEFAULT_HOST = '127.0.0.1:58080' +const START_TIMEOUT_MS = 20_000 +const REQUEST_TIMEOUT_MS = 20_000 +const STOP_TIMEOUT_MS = 3_000 +const MAX_IMAGE_BYTES = 20 * 1024 * 1024 +const MAX_VOICE_BYTES = 20 * 1024 * 1024 +const WECHAT_APP_PATH = '/Applications/WeChat.app' +const WECHAT_FILES_ROOT = join( + homedir(), + 'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files' +) + +export interface RuntimeLayout { + root: string + executable: string + workingDirectory: string + configDirectory: string + logPath: string +} + +export type PersonalWechatHookReadiness = 'unknown' | 'initializing' | 'ready' | 'failed' + +export function parsePersonalWechatHookLog(log: string): { + readiness: PersonalWechatHookReadiness + attached: boolean + baseAddress?: string + textHookInstalled: boolean + textHookReady: boolean + imageHookInstalled: boolean + imageHookReady: boolean + messageListenerReady: boolean + boundWechatPid?: number + error?: string +} { + let readiness: PersonalWechatHookReadiness = 'unknown' + let attached = false + let baseAddress: string | undefined + let textHookInstalled = false + let textHookReady = false + let imageHookInstalled = false + let imageHookReady = false + let messageListenerReady = false + let boundWechatPid: number | undefined + let error: string | undefined + for (const line of log.split(/\r?\n/)) { + if (!line.trim()) continue + try { + const entry = JSON.parse(line) as { + payload?: string + err?: string + message?: string + PID?: number + type?: string + result?: string | number + } + const text = `${entry.payload || ''} ${entry.err || ''} ${entry.message || ''}` + // wechat_chatter writes the task receipt and its result as two separate + // JSON log records: the first has type=send_image, while the next has + // the result and the Chinese result message but no type field. + if ( + (entry.type === 'send_image' || text.includes('发送图片任务执行结果')) && + String(entry.result) === '1' + ) { + imageHookInstalled = true + imageHookReady = true + } + if ( + (entry.type === 'image' || text.includes('上传图片任务执行结果')) && + String(entry.result) === '0' + ) { + imageHookInstalled = true + } + if (text.includes('使用指定的微信进程 PID')) { + readiness = 'unknown' + attached = false + baseAddress = undefined + textHookInstalled = false + textHookReady = false + imageHookInstalled = false + imageHookReady = false + messageListenerReady = false + boundWechatPid = Number(entry.PID) || undefined + error = undefined + } else if ( + text.includes("Cannot find 'req2buf' keyword") || + text.includes('Attach 失败') || + text.includes('unable to intercept function') + ) { + readiness = 'failed' + error = entry.err || entry.message + } else if (text.includes('成功 Attach 微信进程')) { + attached = true + boundWechatPid = Number(entry.PID) || boundWechatPid + } else if (text.includes('Base address from range:')) { + baseAddress = text.match(/Base address from range:\s*(0x[0-9a-f]+)/i)?.[1] + } else if (text.includes('WeChat core module base:')) { + baseAddress = text.match(/WeChat core module base:\s*(0x[0-9a-f]+)/i)?.[1] + } else if (text.includes('triggerX0 或 triggerX1Payload 尚未初始化')) { + readiness = 'initializing' + error = '微信底层 Hook 尚未就绪,消息没有发出' + } else if (text.includes('捕获到 StartTask 调用')) { + readiness = 'ready' + textHookReady = true + error = undefined + } else if (text.includes('Dynamic Text Message Setup Complete')) { + textHookInstalled = true + if (readiness === 'unknown') readiness = 'initializing' + } else if (text.includes('捕获到图片上传上下文')) { + imageHookReady = true + } else if (text.includes('图片上传 Hook Setup Complete')) { + imageHookInstalled = true + } else if (text.includes('HTTP 服务启动在')) { + messageListenerReady = true + } else if (text.includes('发送数据')) { + messageListenerReady = true + } + } catch { + // Ignore non-JSON or partially written log lines. + } + } + return { + readiness, + attached, + ...(baseAddress ? { baseAddress } : {}), + textHookInstalled, + textHookReady, + imageHookInstalled, + imageHookReady, + messageListenerReady, + ...(boundWechatPid ? { boundWechatPid } : {}), + ...(error ? { error } : {}) + } +} + +interface PreflightResult { + status: PersonalWechatSenderStatus + runtime?: RuntimeLayout +} + +function toConfigFileName(version: string): string { + return `${version.replace(/\./g, '_')}_mac.json` +} + +function runtimeCandidates(): string[] { + const override = String(process.env['WECHAT_CHATTER_RUNTIME_DIR'] || '').trim() + const relative = ['connectors', 'wechat-personal', `${process.platform}-${process.arch}`] + const downloaded = join(app.getPath('userData'), ...relative) + const packaged = join(process.resourcesPath, 'resources', ...relative) + const development = join(app.getAppPath(), 'resources', ...relative) + const ordered = isPackagedRuntime() + ? [downloaded, packaged, development] + : [downloaded, development, packaged] + return override ? [override, ...ordered] : ordered +} + +export function findPersonalWechatRuntime(candidates = runtimeCandidates()): RuntimeLayout | null { + for (const root of candidates) { + const nestedExecutable = join(root, 'onebot', 'onebot') + const flatExecutable = join(root, 'onebot') + if (existsSync(nestedExecutable) && existsSync(join(root, 'onebot', 'script.js'))) { + return { + root, + executable: nestedExecutable, + workingDirectory: join(root, 'onebot'), + configDirectory: join(root, 'wechat_version'), + logPath: join(root, 'onebot', 'log', 'macos.log') + } + } + if (existsSync(flatExecutable) && existsSync(join(root, 'script.js'))) { + return { + root, + executable: flatExecutable, + workingDirectory: root, + configDirectory: join(root, 'wechat_version'), + logPath: join(root, 'log', 'macos.log') + } + } + } + return null +} + +export function buildPersonalWechatOneBotRequest( + request: PersonalWechatSendRequest, + fileBase64?: string +): { + endpoint: string + body: Record +} { + const target = request.to.trim() + const isGroup = request.isGroup || target.endsWith('@chatroom') + const message = + request.type === 'text' + ? [{ type: 'text', data: { text: request.text.trim() } }] + : [ + { + type: request.type === 'voice' ? 'record' : 'image', + data: { file: `base64://${fileBase64 || ''}` } + } + ] + return { + endpoint: isGroup ? '/send_group_msg' : '/send_private_msg', + body: { + ...(isGroup ? { group_id: target } : { user_id: target }), + message + } + } +} + +function buildRuntimePath(): string { + const existing = String(process.env['PATH'] || '') + const bundledFfmpeg = String(ffmpegStaticPath || '') + .replace('app.asar', 'app.asar.unpacked') + .trim() + if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing + return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter) +} + +function buildRuntimePythonPath(runtimeRoot: string): string { + return [join(runtimeRoot, 'python'), String(process.env['PYTHONPATH'] || '')] + .filter(Boolean) + .join(delimiter) +} + +function createWavBuffer(pcm: Buffer, sampleRate: number, channels: number): Buffer { + const header = Buffer.alloc(44) + header.write('RIFF', 0) + header.writeUInt32LE(36 + pcm.length, 4) + header.write('WAVE', 8) + header.write('fmt ', 12) + header.writeUInt32LE(16, 16) + header.writeUInt16LE(1, 20) + header.writeUInt16LE(channels, 22) + header.writeUInt32LE(sampleRate, 24) + header.writeUInt32LE(sampleRate * channels * 2, 28) + header.writeUInt16LE(channels * 2, 32) + header.writeUInt16LE(16, 34) + header.write('data', 36) + header.writeUInt32LE(pcm.length, 40) + return Buffer.concat([header, pcm]) +} + +async function prepareVoiceFile(filePath: string): Promise { + const data = readFileSync(filePath) + if (!data.subarray(0, 10).equals(Buffer.from('\x02#!SILK_V3'))) return data + const decoded = await new SilkAudioDecoder().decode({ + data, + codec: 'silk', + sourceHash: createHash('sha256').update(data).digest('hex') + }) + return createWavBuffer(decoded.pcm, decoded.sampleRate, decoded.channels) +} + +async function readWechatVersion(): Promise { + const { stdout } = await execFileAsync('/usr/libexec/PlistBuddy', [ + '-c', + 'Print :WeChatBundleVersion', + join(WECHAT_APP_PATH, 'Contents', 'Info.plist') + ]) + return stdout.trim() +} + +async function readWechatPid(): Promise { + try { + const { stdout } = await execFileAsync('/usr/bin/pgrep', ['-x', 'WeChat']) + const pid = Number(stdout.trim().split(/\s+/)[0]) + return Number.isInteger(pid) && pid > 0 ? pid : undefined + } catch { + return undefined + } +} + +/** Locate the current account's temporary image directory required by the upstream hook. */ +export function findWechatImagePath( + root = WECHAT_FILES_ROOT, + now = new Date() +): string | undefined { + try { + const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}` + const candidates: Array<{ path: string; mtime: number }> = [] + const fallbacks: Array<{ path: string; mtime: number }> = [] + for (const account of readdirSync(root)) { + const tempRoot = join(root, account, 'temp') + if (!existsSync(tempRoot)) continue + fallbacks.push({ + path: join(tempRoot, 'ImageTemp', month), + mtime: statSync(tempRoot).mtimeMs + }) + const imageTempPath = join(tempRoot, 'ImageTemp', month) + if (existsSync(imageTempPath)) { + candidates.push({ path: imageTempPath, mtime: statSync(imageTempPath).mtimeMs }) + } + for (const tempId of readdirSync(tempRoot)) { + const imagePath = join(tempRoot, tempId, month, 'Img') + if (existsSync(imagePath)) { + candidates.push({ path: imagePath, mtime: statSync(imagePath).mtimeMs }) + } + } + } + candidates.sort((a, b) => b.mtime - a.mtime) + fallbacks.sort((a, b) => b.mtime - a.mtime) + const selected = candidates[0]?.path || fallbacks[0]?.path + return selected ? `${selected}${sep}` : undefined + } catch { + return undefined + } +} + +async function isSipDisabled(): Promise { + try { + const { stdout, stderr } = await execFileAsync('/usr/bin/csrutil', ['status']) + return `${stdout}\n${stderr}`.toLowerCase().includes('disabled') + } catch { + return false + } +} + +interface OneBotProcessInfo { + pid: number + boundWechatPid?: number + imagePath?: string + command: string +} + +async function readOneBotProcessInfo(): Promise { + try { + const { stdout } = await execFileAsync('/usr/sbin/lsof', [ + '-nP', + '-t', + `-iTCP:${DEFAULT_HOST.split(':')[1]}`, + '-sTCP:LISTEN' + ]) + const pid = Number(stdout.trim().split(/\s+/)[0]) + if (!Number.isInteger(pid) || pid <= 0) return undefined + const { stdout: commandOutput } = await execFileAsync('/bin/ps', [ + '-p', + String(pid), + '-o', + 'command=' + ]) + const command = commandOutput.trim() + if (!/(^|\/)onebot(?:\s|$)/.test(command)) return undefined + const boundWechatPid = Number(command.match(/-wechat_pid=(\d+)/)?.[1]) || undefined + const imagePath = command.match(/-image_path=(\S+)/)?.[1] + return { + pid, + ...(boundWechatPid ? { boundWechatPid } : {}), + ...(imagePath ? { imagePath } : {}), + command + } + } catch { + return undefined + } +} + +async function terminateOneBot(info: OneBotProcessInfo): Promise { + if (!/(^|\/)onebot(?:\s|$)/.test(info.command)) return + try { + process.kill(info.pid, 'SIGTERM') + } catch { + return + } + const startedAt = Date.now() + while (Date.now() - startedAt < STOP_TIMEOUT_MS) { + try { + process.kill(info.pid, 0) + await new Promise((resolve) => setTimeout(resolve, 100)) + } catch { + return + } + } +} + +async function requestWithTimeout( + url: string, + init?: RequestInit, + timeoutMs = 2_000 +): Promise { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), timeoutMs) + try { + return await fetch(url, { ...init, signal: controller.signal }) + } finally { + clearTimeout(timer) + } +} + +export class PersonalWechatSendService { + private child: ChildProcess | null = null + private startPromise: Promise | null = null + private lastError = '' + + async getStatus(): Promise { + const preflight = await this.preflight() + const [endpointReady, oneBot] = await Promise.all([ + this.isEndpointOnline(), + readOneBotProcessInfo() + ]) + const hook = this.readHookReadiness(preflight.runtime) + const boundWechatPid = oneBot?.boundWechatPid || hook.boundWechatPid + const boundToCurrentWechat = Boolean( + preflight.status.wechatPid && boundWechatPid === preflight.status.wechatPid + ) + const common = { + ...preflight.status, + endpointReady, + ...(oneBot?.pid ? { oneBotPid: oneBot.pid } : {}), + ...(boundWechatPid ? { boundWechatPid } : {}), + attachReady: hook.attached, + ...(hook.baseAddress ? { baseAddress: hook.baseAddress } : {}), + baseAddressReady: Boolean(hook.baseAddress), + textHookInstalled: hook.textHookInstalled, + textHookReady: hook.textHookReady, + imageHookInstalled: hook.imageHookInstalled, + imageHookReady: hook.imageHookReady, + messageListenerReady: hook.messageListenerReady + } + if (!endpointReady) return common + if (!boundToCurrentWechat) { + return { + ...common, + state: 'hook_not_ready', + canSend: false, + canSendText: false, + canSendImage: false, + message: 'OneBot 仍绑定旧微信进程,请点击“尝试重新绑定”' + } + } + if (hook.readiness === 'failed') { + return { + ...common, + state: 'error', + canSend: false, + canSendText: false, + canSendImage: false, + message: '微信发送 Hook 初始化失败,请尝试重新绑定', + ...(hook.error ? { error: hook.error } : {}) + } + } + const baseReady = hook.attached && Boolean(hook.baseAddress) && hook.textHookInstalled + const canSendText = baseReady && hook.textHookReady + const imagePathBound = Boolean(oneBot?.imagePath) + const canSendImage = baseReady && hook.imageHookReady && imagePathBound + const canSendVoice = baseReady && hook.imageHookReady + return { + ...common, + state: canSendText || canSendImage || canSendVoice ? 'online' : 'hook_not_ready', + canSend: canSendText || canSendImage || canSendVoice, + canSendText, + canSendImage, + canSendVoice, + message: + hook.imageHookReady && preflight.status.imagePath && !imagePathBound + ? 'OneBot 尚未绑定微信图片目录,请点击“尝试重新绑定”' + : canSendText || canSendImage || canSendVoice + ? '个人微信已绑定,可使用已初始化的消息类型' + : '个人微信已绑定,发送前请先在微信中手动初始化对应消息类型', + ...(hook.error ? { error: hook.error } : {}) + } + } + + async send(request: PersonalWechatSendRequest): Promise { + const to = String(request?.to || '').trim() + if (!to) { + const status = await this.getStatus() + return { success: false, status, error: '接收者不能为空' } + } + let fileBase64: string | undefined + if (request.type === 'text') { + const text = String(request.text || '').trim() + if (!text) { + const status = await this.getStatus() + return { success: false, status, error: '文字内容不能为空' } + } + if (text.length > 2_000) { + const status = await this.getStatus() + return { success: false, status, error: '测试消息不能超过 2000 个字符' } + } + request = { ...request, to, text } + } else { + const filePath = String(request.filePath || '').trim() + if (!filePath || !existsSync(filePath)) { + const status = await this.getStatus() + return { + success: false, + status, + error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件` + } + } + const size = statSync(filePath).size + const maxBytes = request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES + if (size <= 0 || size > maxBytes) { + const status = await this.getStatus() + return { + success: false, + status, + error: `测试${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB` + } + } + fileBase64 = ( + request.type === 'voice' ? await prepareVoiceFile(filePath) : readFileSync(filePath) + ).toString('base64') + request = { ...request, to, filePath } + } + + const status = await this.ensureRunning() + const typeReady = + request.type === 'text' + ? status.canSendText + : request.type === 'voice' + ? status.canSendVoice + : status.canSendImage + if (!typeReady) { + const guidance = + request.type === 'text' + ? '请先在微信中给任意好友手动发送一条文字,再重新检测' + : request.type === 'voice' + ? '语音复用媒体上传 Hook,请先在微信中手动发送一张普通图片,再重新检测' + : '请先在微信中给任意好友手动发送一张普通图片,再重新检测' + return { success: false, status, error: status.error || guidance } + } + + const oneBot = buildPersonalWechatOneBotRequest(request, fileBase64) + try { + const response = await requestWithTimeout( + `http://${DEFAULT_HOST}${oneBot.endpoint}`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(oneBot.body) + }, + request.type === 'voice' ? 60_000 : REQUEST_TIMEOUT_MS + ) + const responseText = await response.text() + if (!response.ok) throw new Error(responseText || `HTTP ${response.status}`) + const parsed = responseText ? (JSON.parse(responseText) as { status?: string }) : {} + if (parsed.status && parsed.status !== 'ok') throw new Error(responseText) + return { success: true, status: await this.getStatus() } + } catch (error) { + this.lastError = error instanceof Error ? error.message : String(error) + const failedStatus = await this.getStatus() + return { + success: false, + status: { ...failedStatus, state: 'error', error: this.lastError }, + error: `发送失败:${this.lastError}` + } + } + } + + async rebind(): Promise { + const preflight = await this.preflight() + if (!preflight.runtime || !preflight.status.configPath || !preflight.status.wechatPid) { + return preflight.status + } + const currentStatus = await this.getStatus() + const oneBot = await readOneBotProcessInfo() + if ( + oneBot?.boundWechatPid === preflight.status.wechatPid && + currentStatus.attachReady && + currentStatus.baseAddressReady && + currentStatus.textHookInstalled && + currentStatus.imageHookInstalled && + (!preflight.status.imagePath || Boolean(oneBot.imagePath)) && + currentStatus.state !== 'error' + ) { + return { + ...currentStatus, + message: '当前 OneBot 已绑定此微信进程,无需重复注入' + } + } + if (oneBot) await terminateOneBot(oneBot) + this.child = null + this.startPromise = null + this.lastError = '' + let status = await this.startRuntime() + const retryableHookFailure = + status.state === 'error' && + /unable to intercept function|cannot find ['"]req2buf|hook 初始化失败/i.test( + `${status.error || ''} ${status.message || ''}` + ) + if (!retryableHookFailure) return status + const failedOneBot = await readOneBotProcessInfo() + if (failedOneBot) await terminateOneBot(failedOneBot) + this.child = null + this.lastError = '' + await new Promise((resolve) => setTimeout(resolve, 1_500)) + status = await this.startRuntime() + return status + } + + stop(): void { + const child = this.child + this.child = null + this.startPromise = null + // A second Attach to the same WeChat process is unstable. Leave OneBot alive; + // it monitors the WeChat PID and exits when that process ends. + if (child && child.exitCode === null) child.unref() + } + + async terminate(): Promise { + const oneBot = await readOneBotProcessInfo() + if (oneBot) await terminateOneBot(oneBot) + this.child = null + this.startPromise = null + this.lastError = '' + } + + private async ensureRunning(): Promise { + const currentStatus = await this.getStatus() + if (currentStatus.state === 'online' || currentStatus.state === 'hook_not_ready') { + return currentStatus + } + if (this.startPromise) return this.startPromise + this.startPromise = this.startRuntime().finally(() => { + this.startPromise = null + }) + return this.startPromise + } + + private async startRuntime(): Promise { + const preflight = await this.preflight() + if (!preflight.runtime || !preflight.status.configPath) { + return preflight.status + } + + const pid = preflight.status.wechatPid + const imagePath = findWechatImagePath() + this.lastError = '' + const child = spawn( + preflight.runtime.executable, + [ + '-type=local', + `-receive_host=${DEFAULT_HOST}`, + `-wechat_conf=${preflight.status.configPath}`, + `-wechat_pid=${pid}`, + ...(imagePath ? [`-image_path=${imagePath}`] : []), + '-send_interval=1000', + '-log_level=info' + ], + { + cwd: preflight.runtime.workingDirectory, + detached: true, + stdio: 'ignore', + windowsHide: true, + env: { + ...process.env, + PATH: buildRuntimePath(), + PYTHONPATH: buildRuntimePythonPath(preflight.runtime.root) + } + } + ) + this.child = child + child.unref() + child.once('error', (error) => { + this.lastError = error.message + }) + child.once('exit', (code) => { + if (this.child === child) this.child = null + if (code && !this.lastError) this.lastError = `发送服务退出(code=${code})` + }) + + const startedAt = Date.now() + while (Date.now() - startedAt < START_TIMEOUT_MS) { + const status = await this.getStatus() + if (status.state === 'online') return status + if (status.state === 'hook_not_ready' && status.attachReady && status.baseAddressReady) { + return status + } + if (status.state === 'error') return status + if (this.child?.exitCode !== null && this.child?.exitCode !== undefined) break + await new Promise((resolve) => setTimeout(resolve, 300)) + } + const status = await this.preflight() + return { + ...status.status, + state: 'error', + canSend: false, + message: '个人微信发送服务启动失败', + error: this.lastError || '启动超时,请查看应用日志' + } + } + + private async preflight(): Promise { + const base = { + platform: process.platform, + arch: process.arch, + sipDisabled: false, + wechatRunning: false, + runtimeReady: false, + endpoint: DEFAULT_HOST, + endpointReady: false, + attachReady: false, + baseAddressReady: false, + textHookInstalled: false, + textHookReady: false, + imageHookInstalled: false, + imageHookReady: false, + messageListenerReady: false, + canSend: false, + canSendText: false, + canSendImage: false, + canSendVoice: false + } + if (process.platform !== 'darwin' || process.arch !== 'arm64') { + return { + status: { + ...base, + state: 'unsupported_platform', + message: '个人微信测试发送当前仅支持 Apple Silicon Mac' + } + } + } + + const [sipDisabled, wechatPid] = await Promise.all([isSipDisabled(), readWechatPid()]) + if (!wechatPid) { + return { + status: { + ...base, + sipDisabled, + state: 'wechat_not_running', + message: '请先启动并登录 macOS 微信' + } + } + } + if (!sipDisabled) { + return { + status: { + ...base, + wechatRunning: true, + wechatPid, + state: 'sip_enabled', + message: '当前 SIP 未关闭,无法直接连接微信进程' + } + } + } + + let wechatVersion = '' + try { + wechatVersion = await readWechatVersion() + } catch (error) { + return { + status: { + ...base, + sipDisabled, + wechatRunning: true, + wechatPid, + state: 'error', + message: '无法读取微信精确版本', + error: error instanceof Error ? error.message : String(error) + } + } + } + + const runtime = findPersonalWechatRuntime() + if (!runtime) { + return { + status: { + ...base, + sipDisabled, + wechatRunning: true, + wechatPid, + wechatVersion, + state: 'runtime_missing', + message: '个人微信发送组件尚未安装,请前往“设置 → 智能能力 → 文字转语音”下载' + } + } + } + const configPath = join(runtime.configDirectory, toConfigFileName(wechatVersion)) + if (!existsSync(configPath)) { + return { + runtime, + status: { + ...base, + sipDisabled, + wechatRunning: true, + wechatPid, + wechatVersion, + runtimeReady: true, + executablePath: runtime.executable, + state: 'unsupported_version', + message: `当前微信版本 ${wechatVersion} 暂不支持,请前往文字转语音设置查看支持的版本`, + error: `缺少 ${configPath}` + } + } + } + + const imagePath = findWechatImagePath() + return { + runtime, + status: { + ...base, + sipDisabled, + wechatRunning: true, + wechatPid, + wechatVersion, + runtimeReady: true, + executablePath: runtime.executable, + configPath, + ...(imagePath ? { imagePath } : {}), + state: this.child && this.child.exitCode === null ? 'starting' : 'stopped', + message: this.lastError || '尚未绑定当前微信,可点击“尝试重新绑定”' + } + } + } + + private async isEndpointOnline(): Promise { + try { + const [host, portText] = DEFAULT_HOST.split(':') + const port = Number(portText) + await new Promise((resolve, reject) => { + const socket = createConnection({ host, port }) + const timer = setTimeout(() => { + socket.destroy() + reject(new Error('timeout')) + }, 800) + socket.once('connect', () => { + clearTimeout(timer) + socket.destroy() + resolve() + }) + socket.once('error', (error) => { + clearTimeout(timer) + socket.destroy() + reject(error) + }) + }) + return true + } catch { + return false + } + } + + private readHookReadiness( + runtime?: RuntimeLayout + ): ReturnType { + if (!runtime || !existsSync(runtime.logPath)) { + return { + readiness: 'unknown', + attached: false, + textHookInstalled: false, + textHookReady: false, + imageHookInstalled: false, + imageHookReady: false, + messageListenerReady: false + } + } + try { + return parsePersonalWechatHookLog(readFileSync(runtime.logPath, 'utf8')) + } catch { + return { + readiness: 'unknown', + attached: false, + textHookInstalled: false, + textHookReady: false, + imageHookInstalled: false, + imageHookReady: false, + messageListenerReady: false + } + } + } +} + +export const personalWechatSendService = new PersonalWechatSendService() diff --git a/src/main/services/settings-store.ts b/src/main/services/settings-store.ts index dbe4969..b48b252 100644 --- a/src/main/services/settings-store.ts +++ b/src/main/services/settings-store.ts @@ -2,6 +2,7 @@ import { app } from 'electron' import fs from 'fs-extra' import path from 'path' import os from 'os' +import type { TextToSpeechModel } from '../../shared/text-to-speech' /** * 把 V3 时代的 "...\\Documents\\WeChat Files" 路径重定向到 @@ -36,6 +37,8 @@ export interface AppSettings { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + ttsSelectedVoiceId: string + ttsModel: TextToSpeechModel } function getDefaultDbRoot(): string { @@ -135,7 +138,9 @@ const DEFAULT_SETTINGS: AppSettings = { autoLoginPreferenceSet: false, appearanceTheme: 'system', compactMode: false, - showStartupProgress: true + showStartupProgress: true, + ttsSelectedVoiceId: '', + ttsModel: 's2.1-pro-free' } const SETTINGS_FILE = path.join( diff --git a/src/main/services/text-to-speech-settings-service.ts b/src/main/services/text-to-speech-settings-service.ts new file mode 100644 index 0000000..2690008 --- /dev/null +++ b/src/main/services/text-to-speech-settings-service.ts @@ -0,0 +1,358 @@ +import { app } from 'electron' +import fs from 'fs-extra' +import path from 'path' +import { randomUUID } from 'crypto' +import type { + ListTextToSpeechVoicesRequest, + ListTextToSpeechVoicesResult, + SaveTextToSpeechSettingsRequest, + SynthesizeTextToSpeechRequest, + SynthesizeTextToSpeechResult, + TextToSpeechKeySource, + TextToSpeechModel, + TextToSpeechSettingsResult, + TextToSpeechVoice +} from '../../shared/text-to-speech' +import { AIProviderKeyStore } from '../ai-provider-key-store' +import { loadSettings, updateSettings } from './settings-store' + +const FISH_AUDIO_KEY_ID = 'fish-audio-tts' +const FISH_AUDIO_BASE_URL = 'https://api.fish.audio' +const FISH_AUDIO_PUBLIC_ASSET_URL = 'https://public-platform.r2.fish.audio/' +const DEFAULT_PAGE_SIZE = 24 +const MAX_PAGE_SIZE = 100 +const GENERATED_AUDIO_MAX_AGE_MS = 24 * 60 * 60 * 1000 + +interface FishAudioModelEntity { + _id: string + type: 'svc' | 'tts' + title: string + description?: string + cover_image?: string + state: 'created' | 'training' | 'trained' | 'failed' + tags?: string[] + languages?: string[] + default_text?: string + samples?: Array<{ title: string; text: string; task_id: string; audio: string }> + task_count?: number + like_count?: number + mark_count?: number + author?: { _id: string; nickname: string; avatar: string } +} + +interface FishAudioModelListResponse { + total: number + items: FishAudioModelEntity[] + has_more?: boolean | null +} + +export class TextToSpeechSettingsService { + constructor(private readonly keyStore = new AIProviderKeyStore()) {} + + get(): TextToSpeechSettingsResult { + const resolved = this.resolveKey() + const settings = loadSettings() + return { + success: resolved.success, + settings: { + provider: 'fish-audio', + hasApiKey: Boolean(resolved.key), + hasStoredApiKey: resolved.hasStoredApiKey, + hasEnvironmentApiKey: resolved.hasEnvironmentApiKey, + keySource: resolved.source, + encryptionAvailable: resolved.encryptionAvailable, + selectedVoiceId: normalizeSelectedVoiceId(settings.ttsSelectedVoiceId), + outputFormat: 'mp3', + model: normalizeModel(settings.ttsModel), + phase: 'ready' + }, + voices: [], + error: resolved.error + } + } + + save(request: SaveTextToSpeechSettingsRequest): TextToSpeechSettingsResult { + const apiKey = request.apiKey?.trim() + if (request.clearApiKey) { + const cleared = this.keyStore.clear(FISH_AUDIO_KEY_ID) + if (!cleared.success) return { ...this.get(), success: false, error: cleared.error } + } else if (apiKey) { + const saved = this.keyStore.save(FISH_AUDIO_KEY_ID, apiKey) + if (!saved.success) return { ...this.get(), success: false, error: saved.error } + } + + const patch: { ttsSelectedVoiceId?: string; ttsModel?: TextToSpeechModel } = {} + if (request.selectedVoiceId !== undefined) { + patch.ttsSelectedVoiceId = request.selectedVoiceId.trim() + } + if (request.model !== undefined) patch.ttsModel = normalizeModel(request.model) + if (Object.keys(patch).length) updateSettings(patch) + return this.get() + } + + async listVoices( + request: ListTextToSpeechVoicesRequest = {} + ): Promise { + const pageNumber = clampInteger(request.pageNumber, 1, Number.MAX_SAFE_INTEGER, 1) + const pageSize = clampInteger(request.pageSize, 1, MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE) + const resolved = this.resolveKey() + if (!resolved.key) { + return { + success: false, + items: [], + total: 0, + pageNumber, + pageSize, + hasMore: false, + error: resolved.error || '请先配置语音服务 API Key' + } + } + + try { + const url = new URL('/model', FISH_AUDIO_BASE_URL) + url.searchParams.set('page_size', String(pageSize)) + url.searchParams.set('page_number', String(pageNumber)) + url.searchParams.set('sort_by', 'score') + if (request.title?.trim()) url.searchParams.set('title', request.title.trim()) + if (request.language?.trim()) url.searchParams.set('language', request.language.trim()) + for (const tag of request.tags || []) { + if (tag.trim()) url.searchParams.append('tag', tag.trim()) + } + + const response = await fetch(url, { + headers: { Authorization: `Bearer ${resolved.key}` }, + signal: AbortSignal.timeout(30_000) + }) + if (!response.ok) throw await fishAudioError(response) + const payload = (await response.json()) as FishAudioModelListResponse + let items = payload.items + .filter((model) => model.type === 'tts' && model.state === 'trained') + .map(toVoice) + + const selectedVoiceId = normalizeSelectedVoiceId(loadSettings().ttsSelectedVoiceId) + if ( + pageNumber === 1 && + !request.title?.trim() && + !(request.tags || []).length && + selectedVoiceId + ) { + if (!items.some((item) => item.id === selectedVoiceId)) { + const selected = await this.getVoice(selectedVoiceId, resolved.key) + if (selected) items = [selected, ...items] + } + } + + return { + success: true, + items, + total: payload.total, + pageNumber, + pageSize, + hasMore: payload.has_more ?? pageNumber * pageSize < payload.total + } + } catch (error) { + return { + success: false, + items: [], + total: 0, + pageNumber, + pageSize, + hasMore: false, + error: safeFishAudioError(error) + } + } + } + + async synthesize(request: SynthesizeTextToSpeechRequest): Promise { + const text = request.text.trim() + const referenceId = request.referenceId.trim() + if (!text) return { success: false, error: '请输入要生成语音的文字' } + if (text.length > 1000) return { success: false, error: '单次生成文字不能超过 1000 个字符' } + if (!referenceId) return { success: false, error: '请先选择音色' } + + const resolved = this.resolveKey() + if (!resolved.key) { + return { + success: false, + error: resolved.error || '请先配置语音服务 API Key' + } + } + + try { + const response = await fetch(`${FISH_AUDIO_BASE_URL}/v1/tts`, { + method: 'POST', + headers: { + Authorization: `Bearer ${resolved.key}`, + 'Content-Type': 'application/json', + model: normalizeModel(loadSettings().ttsModel) + }, + body: JSON.stringify({ + text, + reference_id: referenceId, + format: 'mp3', + mp3_bitrate: 128, + latency: 'normal', + normalize: true + }), + signal: AbortSignal.timeout(120_000) + }) + if (!response.ok) throw await fishAudioError(response) + const audio = Buffer.from(await response.arrayBuffer()) + if (audio.length < 128) throw new Error('语音服务返回的音频为空') + + const directory = this.generatedAudioDirectory() + fs.ensureDirSync(directory) + this.cleanupGeneratedAudio(directory) + const filePath = path.join(directory, `fish-audio-${Date.now()}-${randomUUID()}.mp3`) + fs.writeFileSync(filePath, audio, { mode: 0o600 }) + return { + success: true, + filePath, + audioDataUrl: `data:audio/mpeg;base64,${audio.toString('base64')}` + } + } catch (error) { + return { success: false, error: safeFishAudioError(error) } + } + } + + removeGeneratedAudio(filePath: string): { success: boolean; error?: string } { + const directory = this.generatedAudioDirectory() + const resolvedPath = path.resolve(filePath) + if (!resolvedPath.startsWith(`${path.resolve(directory)}${path.sep}`)) { + return { success: false, error: '拒绝删除非 Fish Audio 临时文件' } + } + try { + fs.removeSync(resolvedPath) + return { success: true } + } catch { + return { success: false, error: '临时语音文件清理失败' } + } + } + + private resolveKey(): { + success: boolean + key?: string + source: TextToSpeechKeySource + hasStoredApiKey: boolean + hasEnvironmentApiKey: boolean + encryptionAvailable: boolean + error?: string + } { + const stored = this.keyStore.get(FISH_AUDIO_KEY_ID) + const environmentKey = String(process.env.FISH_API_KEY || '').trim() + const storedKey = stored.key?.trim() + const key = storedKey || environmentKey || undefined + return { + success: stored.success || Boolean(environmentKey), + key, + source: storedKey ? 'secure-storage' : environmentKey ? 'environment' : 'missing', + hasStoredApiKey: Boolean(storedKey), + hasEnvironmentApiKey: Boolean(environmentKey), + encryptionAvailable: stored.available, + error: key ? undefined : stored.error + } + } + + private async getVoice(id: string, key: string): Promise { + try { + const response = await fetch(`${FISH_AUDIO_BASE_URL}/model/${encodeURIComponent(id)}`, { + headers: { Authorization: `Bearer ${key}` }, + signal: AbortSignal.timeout(15_000) + }) + if (!response.ok) return null + const model = (await response.json()) as FishAudioModelEntity + return model.type === 'tts' && model.state === 'trained' ? toVoice(model) : null + } catch { + return null + } + } + + private generatedAudioDirectory(): string { + return path.join(app.getPath('temp'), 'wechatexplorer-fish-audio') + } + + private cleanupGeneratedAudio(directory: string): void { + try { + const now = Date.now() + for (const name of fs.readdirSync(directory)) { + const candidate = path.join(directory, name) + if (!name.startsWith('fish-audio-') || !name.endsWith('.mp3')) continue + if (now - fs.statSync(candidate).mtimeMs > GENERATED_AUDIO_MAX_AGE_MS) + fs.removeSync(candidate) + } + } catch { + // 临时文件清理失败不应阻断当前语音生成。 + } + } +} + +function toVoice(model: FishAudioModelEntity): TextToSpeechVoice { + const sample = model.samples?.find((item) => item.audio) || model.samples?.[0] + return { + id: model._id, + name: model.title || '未命名音色', + description: model.description || sample?.text || '公开音色', + tags: Array.isArray(model.tags) ? model.tags : [], + languages: Array.isArray(model.languages) ? model.languages : [], + source: 'fish-audio', + coverImage: resolvePublicAssetUrl(model.cover_image || model.author?.avatar), + previewUrl: sample?.audio || undefined, + previewText: sample?.text || model.default_text || undefined, + authorName: model.author?.nickname || undefined, + taskCount: model.task_count, + likeCount: model.like_count, + markCount: model.mark_count + } +} + +function resolvePublicAssetUrl(value?: string): string | undefined { + const normalized = String(value || '').trim() + if (!normalized) return undefined + if (/^https?:\/\//i.test(normalized)) return normalized + if (normalized.startsWith('//')) return `https:${normalized}` + return new URL(normalized.replace(/^\/+/, ''), FISH_AUDIO_PUBLIC_ASSET_URL).toString() +} + +function normalizeSelectedVoiceId(value: string): string { + const normalized = String(value || '').trim() + return normalized.startsWith('demo-') ? '' : normalized +} + +function normalizeModel(value: unknown): TextToSpeechModel { + return value === 's2.1-pro' ? 's2.1-pro' : 's2.1-pro-free' +} + +function clampInteger(value: unknown, min: number, max: number, fallback: number): number { + const parsed = Number(value) + if (!Number.isFinite(parsed)) return fallback + return Math.min(max, Math.max(min, Math.floor(parsed))) +} + +async function fishAudioError(response: Response): Promise { + let detail = '' + try { + const payload = (await response.json()) as + | { status?: number; message?: string } + | Array<{ msg?: string }> + detail = Array.isArray(payload) + ? payload + .map((item) => item.msg) + .filter(Boolean) + .join(';') + : payload.message || '' + } catch { + detail = await response.text().catch(() => '') + } + if (response.status === 401) return new Error('API Key 无效或已失效') + if (response.status === 402) return new Error('语音服务余额不足') + if (response.status === 404) return new Error('所选音色不存在或不可访问') + if (response.status === 422) return new Error(detail || '语音生成参数不正确') + if (response.status === 503) return new Error('语音服务暂时不可用,请稍后重试') + return new Error(detail || `语音服务请求失败(HTTP ${response.status})`) +} + +function safeFishAudioError(error: unknown): string { + if (error instanceof DOMException && error.name === 'TimeoutError') return '语音服务请求超时' + if (error instanceof Error) return error.message + return '语音服务请求失败' +} diff --git a/src/main/voice-pipeline/audio-decoder.ts b/src/main/voice-pipeline/audio-decoder.ts index 2d0840c..b9a5fbb 100644 --- a/src/main/voice-pipeline/audio-decoder.ts +++ b/src/main/voice-pipeline/audio-decoder.ts @@ -74,12 +74,12 @@ export class SilkAudioDecoder implements VoiceAudioDecoder { decode?: (data: Buffer, sampleRate: number) => Promise<{ data: Uint8Array }> } if (!silkWasm.decode) throw new Error('silk-wasm 运行时无效') - const result = await silkWasm.decode(source.data, 24000) + const result = await silkWasm.decode(source.data, 16000) const pcm = Buffer.from(result.data) if (!pcm.length) throw new Error('Silk 解码结果为空') return { pcm, - sampleRate: 24000, + sampleRate: 16000, channels: 1, sourceHash: source.sourceHash } diff --git a/src/main/voice-service.ts b/src/main/voice-service.ts index f63a648..1257be9 100644 --- a/src/main/voice-service.ts +++ b/src/main/voice-service.ts @@ -62,7 +62,11 @@ export class VoiceService { if (!pcmResult.success) return pcmResult const pcmData = pcmResult.audio.pcm - const wavData = this.createWavBuffer(pcmData, 24000) + const wavData = this.createWavBuffer( + pcmData, + pcmResult.audio.sampleRate, + pcmResult.audio.channels + ) console.log( '[VoiceService] wavData length:', wavData.length, diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 9864fdd..6a7cd75 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -53,6 +53,18 @@ import type { ImageInsight } from '../shared/image-insight' import type { AgentHubActionResult, AgentHubLogEntry, AgentHubStatus } from '../shared/agent-hub' +import type { + PersonalWechatImageSelectionResult, + PersonalWechatVoiceSelectionResult, + PersonalWechatSendRequest, + PersonalWechatSendResult, + PersonalWechatSenderStatus +} from '../shared/personal-wechat' +import type { + PersonalWechatRuntimeDownloadResult, + PersonalWechatRuntimeProgressEvent, + PersonalWechatRuntimeStatus +} from '../shared/personal-wechat-runtime' import type { AppLogEntry } from '../shared/app-log' import type { AppUpdateCheckResult, AppUpdateState } from '../shared/app-update' import type { CacheSummary } from '../shared/cache' @@ -86,6 +98,14 @@ import type { WechatShareServiceConfig, WechatShareServiceConfigResult } from '../shared/wechat-share-card' +import type { + ListTextToSpeechVoicesRequest, + ListTextToSpeechVoicesResult, + SaveTextToSpeechSettingsRequest, + SynthesizeTextToSpeechRequest, + SynthesizeTextToSpeechResult, + TextToSpeechSettingsResult +} from '../shared/text-to-speech' export type ParsedContent = | { type: 'text'; content: string } @@ -250,6 +270,20 @@ declare global { testAIProvider: (providerId: string) => Promise testAIVision: (request: AIVisionTestRequest) => Promise migrateLegacyAIConfig: (config: LegacyAIConfig) => Promise + getTextToSpeechSettings: () => Promise + saveTextToSpeechSettings: ( + request: SaveTextToSpeechSettingsRequest + ) => Promise + listTextToSpeechVoices: ( + request?: ListTextToSpeechVoicesRequest + ) => Promise + synthesizeTextToSpeech: ( + request: SynthesizeTextToSpeechRequest + ) => Promise + removeGeneratedTextToSpeechAudio: ( + filePath: string + ) => Promise<{ success: boolean; error?: string }> + openFishAudioApiKeys: () => Promise<{ success: boolean; error?: string }> copyImage: (base64String: string) => Promise<{ success: boolean; error?: string }> getVoiceData: ( sessionId: string, @@ -383,6 +417,8 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + ttsSelectedVoiceId: string + ttsModel: import('../shared/text-to-speech').TextToSpeechModel imageXorKey: string imageAesKey: string } @@ -420,6 +456,8 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + ttsSelectedVoiceId: string + ttsModel: import('../shared/text-to-speech').TextToSpeechModel imageXorKey: string imageAesKey: string } @@ -440,6 +478,8 @@ declare global { appearanceTheme: 'system' | 'light' | 'dark' compactMode: boolean showStartupProgress: boolean + ttsSelectedVoiceId: string + ttsModel: import('../shared/text-to-speech').TextToSpeechModel imageXorKey: string imageAesKey: string }> @@ -533,6 +573,21 @@ declare global { sessionId: string, limit?: number ) => Promise<{ success: boolean; insights: ImageInsight[] }> + getPersonalWechatSenderStatus: () => Promise + getPersonalWechatRuntimeStatus: () => Promise + downloadPersonalWechatRuntime: () => Promise + cancelPersonalWechatRuntimeDownload: () => Promise<{ success: boolean }> + removePersonalWechatRuntime: () => Promise + openPersonalWechatRuntimeDirectory: () => Promise<{ success: boolean; error?: string }> + onPersonalWechatRuntimeProgress: ( + callback: (status: PersonalWechatRuntimeProgressEvent) => void + ) => () => void + rebindPersonalWechatSender: () => Promise + selectPersonalWechatImage: () => Promise + selectPersonalWechatVoice: () => Promise + sendPersonalWechatMessage: ( + request: PersonalWechatSendRequest + ) => Promise getAgentHubStatus: () => Promise getAgentHubLogs: () => Promise clearAgentHubLogs: () => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index 4f072fa..0b76214 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -25,6 +25,18 @@ import type { ImageInsight } from '../shared/image-insight' import type { AgentHubLogEntry, AgentHubStatus } from '../shared/agent-hub' +import type { + PersonalWechatImageSelectionResult, + PersonalWechatVoiceSelectionResult, + PersonalWechatSendRequest, + PersonalWechatSendResult, + PersonalWechatSenderStatus +} from '../shared/personal-wechat' +import type { + PersonalWechatRuntimeDownloadResult, + PersonalWechatRuntimeProgressEvent, + PersonalWechatRuntimeStatus +} from '../shared/personal-wechat-runtime' import type { AppLogEntry } from '../shared/app-log' import type { AppUpdateState } from '../shared/app-update' import type { CacheSummary } from '../shared/cache' @@ -58,6 +70,11 @@ import type { PublishWechatShareCardRequest, WechatShareServiceConfig } from '../shared/wechat-share-card' +import type { + ListTextToSpeechVoicesRequest, + SaveTextToSpeechSettingsRequest, + SynthesizeTextToSpeechRequest +} from '../shared/text-to-speech' // 渲染器的自定义 API const api = { @@ -138,6 +155,16 @@ const api = { testAIProvider: (providerId: string) => ipcRenderer.invoke('ai:testProvider', providerId), testAIVision: (request: AIVisionTestRequest) => ipcRenderer.invoke('ai:testVision', request), migrateLegacyAIConfig: (config: LegacyAIConfig) => ipcRenderer.invoke('ai:migrateLegacy', config), + getTextToSpeechSettings: () => ipcRenderer.invoke('tts:getSettings'), + saveTextToSpeechSettings: (request: SaveTextToSpeechSettingsRequest) => + ipcRenderer.invoke('tts:saveSettings', request), + listTextToSpeechVoices: (request?: ListTextToSpeechVoicesRequest) => + ipcRenderer.invoke('tts:listVoices', request), + synthesizeTextToSpeech: (request: SynthesizeTextToSpeechRequest) => + ipcRenderer.invoke('tts:synthesize', request), + removeGeneratedTextToSpeechAudio: (filePath: string) => + ipcRenderer.invoke('tts:removeGeneratedAudio', filePath), + openFishAudioApiKeys: () => ipcRenderer.invoke('tts:openApiKeys'), copyImage: (base64String) => ipcRenderer.invoke('copy-image', base64String), getVoiceData: (sessionId: string, localId: number, createTime: number, svrId?: string | number) => ipcRenderer.invoke('db:getVoiceData', sessionId, localId, createTime, svrId), @@ -322,6 +349,37 @@ const api = { limit?: number ): Promise<{ success: boolean; insights: ImageInsight[] }> => ipcRenderer.invoke('image:listInsights', sessionId, limit), + getPersonalWechatSenderStatus: (): Promise => + ipcRenderer.invoke('wechat-personal:getStatus'), + getPersonalWechatRuntimeStatus: (): Promise => + ipcRenderer.invoke('wechat-personal:getRuntimeStatus'), + downloadPersonalWechatRuntime: (): Promise => + ipcRenderer.invoke('wechat-personal:downloadRuntime'), + cancelPersonalWechatRuntimeDownload: (): Promise<{ success: boolean }> => + ipcRenderer.invoke('wechat-personal:cancelRuntimeDownload'), + removePersonalWechatRuntime: (): Promise => + ipcRenderer.invoke('wechat-personal:removeRuntime'), + openPersonalWechatRuntimeDirectory: (): Promise<{ success: boolean; error?: string }> => + ipcRenderer.invoke('wechat-personal:openRuntimeDirectory'), + onPersonalWechatRuntimeProgress: ( + callback: (status: PersonalWechatRuntimeProgressEvent) => void + ) => { + const listener = ( + _event: Electron.IpcRendererEvent, + status: PersonalWechatRuntimeProgressEvent + ): void => callback(status) + ipcRenderer.on('wechat-personal:runtimeProgress', listener) + return () => ipcRenderer.removeListener('wechat-personal:runtimeProgress', listener) + }, + rebindPersonalWechatSender: (): Promise => + ipcRenderer.invoke('wechat-personal:rebind'), + selectPersonalWechatImage: (): Promise => + ipcRenderer.invoke('wechat-personal:selectImage'), + selectPersonalWechatVoice: (): Promise => + ipcRenderer.invoke('wechat-personal:selectVoice'), + sendPersonalWechatMessage: ( + request: PersonalWechatSendRequest + ): Promise => ipcRenderer.invoke('wechat-personal:send', request), getAgentHubStatus: () => ipcRenderer.invoke('agent-hub:getStatus'), getAgentHubLogs: () => ipcRenderer.invoke('agent-hub:getLogs'), clearAgentHubLogs: () => ipcRenderer.invoke('agent-hub:clearLogs'), diff --git a/src/renderer/index.html b/src/renderer/index.html index 9ebc135..a06792c 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -7,7 +7,7 @@ diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 94cd631..f96691f 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -37,6 +37,7 @@ import { import { enrichQuotedMessages } from './utils/quoted-messages' import type { SelectableReportTemplateId } from '../../shared/report-templates' import { switchGeneratedReportTemplate } from './utils/report-template-switch' +import { runtimePlatform } from './utils/runtime-environment' const SIDEBAR_MIN_WIDTH = 260 const SIDEBAR_MAX_WIDTH = 380 @@ -1470,6 +1471,11 @@ function App(): React.ReactElement { setActivePage('settings') } + const openTextToSpeechSettings = (): void => { + setSettingsCategory('text-to-speech') + setActivePage('settings') + } + const dismissFirstUseWelcome = (): void => { try { localStorage.setItem(FIRST_USE_WELCOME_SEEN_KEY, '1') @@ -1619,6 +1625,9 @@ function App(): React.ReactElement { ]) const selectedReport = generatedReports.find((report) => report.id === selectedReportId) || null + const selectedReportContact = selectedReport + ? contacts.find((contact) => contact.md5 === selectedReport.contactId) || null + : null const openReportResult = (): void => { if (isSavingGeneratedReport) { @@ -1727,6 +1736,7 @@ function App(): React.ReactElement { onReloadAvatars={handleReloadCurrentAvatars} onLoadOlderMessages={handleLoadOlderMessages} onCreateGroupReport={handleOpenReportWorkspace} + onOpenTextToSpeechSettings={openTextToSpeechSettings} isAiLoading={reportGeneration.isGenerating} jumpToTime={archiveJumpTime} /> @@ -1755,6 +1765,7 @@ function App(): React.ReactElement { onCopyImage={handleCopyReportImage} onReveal={handleRevealReport} onSwitchTemplate={handleSwitchReportTemplate} + sendTarget={selectedReportContact} /> @@ -2001,7 +2012,7 @@ function App(): React.ReactElement { if (!isAuthenticated) { return ( Promise onLoadOlderMessages?: () => Promise onCreateGroupReport?: () => void + onOpenTextToSpeechSettings?: () => void isAiLoading?: boolean jumpToTime?: number | null } @@ -34,6 +36,7 @@ const ChatWindow: React.FC = ({ onReloadAvatars, onLoadOlderMessages, onCreateGroupReport, + onOpenTextToSpeechSettings, isAiLoading = false, jumpToTime }) => { @@ -53,6 +56,7 @@ const ChatWindow: React.FC = ({ const [showAvatar, setShowAvatar] = useState(true) const [isAtLatest, setIsAtLatest] = useState(true) const [isReloadingAvatars, setIsReloadingAvatars] = useState(false) + const [sendDialogOpen, setSendDialogOpen] = useState(false) const previousScrollTopRef = useRef(0) const scrollToBottom = useCallback((): void => { @@ -199,6 +203,7 @@ const ChatWindow: React.FC = ({ onContentFilterChange={onContentFilterChange || (() => undefined)} onRefresh={onRefresh} onRefreshData={onRefreshData} + onTestSend={() => setSendDialogOpen(true)} onOpenAiSettings={onCreateGroupReport || (() => undefined)} /> @@ -227,6 +232,15 @@ const ChatWindow: React.FC = ({ onJumpToLatest={scrollToBottom} /> + {sendDialogOpen && ( + setSendDialogOpen(false)} + onOpenTextToSpeechSettings={onOpenTextToSpeechSettings} + /> + )} + {previewImage && (
e.stopPropagation()}> diff --git a/src/renderer/src/components/SettingsPanel.tsx b/src/renderer/src/components/SettingsPanel.tsx index 58a88ed..a0963a4 100644 --- a/src/renderer/src/components/SettingsPanel.tsx +++ b/src/renderer/src/components/SettingsPanel.tsx @@ -1,6 +1,7 @@ // Legacy fallback: SETTINGS-01 moved the default entry to features/settings. // Keep this panel intact until its database-key, image-key, AI and API sections are migrated. import React, { useEffect, useState } from 'react' +import { isWindows } from '../utils/runtime-environment' interface SelfInfo { wxid: string @@ -66,7 +67,6 @@ export const SettingsPanel: React.FC = ({ onSaveAiModelConfig, onDbRootChanged }) => { - const isWindows = window.electron.process.platform === 'win32' const dbRootPlaceholder = isWindows ? 'C:\\Users\\你\\Documents\\WeChat Files' : '~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files' diff --git a/src/renderer/src/components/chat/ChatHeader.tsx b/src/renderer/src/components/chat/ChatHeader.tsx index ff4cfec..2ed246d 100644 --- a/src/renderer/src/components/chat/ChatHeader.tsx +++ b/src/renderer/src/components/chat/ChatHeader.tsx @@ -1,7 +1,8 @@ import React, { useEffect, useRef, useState } from 'react' import { Contact } from '../../../../shared/types' import { ConversationContentSearch } from './ConversationContentSearch' -import { AiIcon, MoreIcon, RefreshIcon, SearchIcon } from './icons' +import { AiIcon, MoreIcon, RefreshIcon, SearchIcon, SendIcon } from './icons' +import { supportsPersonalWechatSend } from '../../utils/runtime-environment' interface ChatHeaderProps { contact: Contact @@ -13,6 +14,7 @@ interface ChatHeaderProps { onContentFilterChange: (value: string) => void onRefresh?: () => void onRefreshData?: () => void + onTestSend: () => void onOpenAiSettings: () => void } @@ -26,6 +28,7 @@ export function ChatHeader({ onContentFilterChange, onRefresh, onRefreshData, + onTestSend, onOpenAiSettings }: ChatHeaderProps): React.ReactElement { const [searchOpen, setSearchOpen] = useState(Boolean(contentFilter)) @@ -111,6 +114,22 @@ export function ChatHeader({
)}
+ + + + + +
+ i +

+ 请在其他设备确认发送结果 + 通过测试功能发送的消息不会显示在本机微信会话中,请切换到手机、平板等其他设备确认是否送达。 +

+
+ +
+ {isGroupChat ? '发送到群聊' : '发送给联系人'} + {displayName} + {targetId} +
+ +
+ +
+ {statusLabel(status)} +

{statusDescription(status)}

+ {status?.wechatVersion && 微信版本:{status.wechatVersion}} + {status?.error && + status.state !== 'unsupported_version' && + status.state !== 'runtime_missing' && {status.error}} +
+
+ {(status?.state === 'unsupported_version' || status?.state === 'runtime_missing') && + onOpenTextToSpeechSettings ? ( + + ) : null} + + +
+
+ +
+ {statusItems.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ +
+ + +
+ + {mode === 'image' ? ( +
+ 图片 + + {image ? ( +
+ {image.name} + {image.path} +
+ ) : ( + 支持 PNG、JPG、GIF 和 WebP,最大 20 MB + )} +
+ ) : ( +
+
+ + +
+ + {voiceSource === 'generated' ? ( +
+
+
+ 文字生成语音 + {selectedTtsVoice?.name || '尚未选择音色'} +
+ {onOpenTextToSpeechSettings ? ( + + ) : null} +
+