Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
companion: import standalone WebBrain systray app
Barack Sokullud23ea607902f
diff --git a/webbrain-systray/.gitignore b/webbrain-systray/.gitignorenew file mode 100644index 000000000..ee6d0fdd2--- /dev/null+++ b/webbrain-systray/.gitignore@@ -0,0 +1,15 @@+# build output+/dist/+*.syso+/wbc+/webbrain-companion+*.exe++# local runs+/.wbc-home/+*.log++# editors and OS+.DS_Store+.idea/+.vscode/diff --git a/webbrain-systray/LICENSE b/webbrain-systray/LICENSEnew file mode 100644index 000000000..464cb1a83--- /dev/null+++ b/webbrain-systray/LICENSE@@ -0,0 +1,687 @@+WebBrain Companion project license notice++Copyright (c) 2026 Emre Sokullu++WebBrain Companion is free software: you may 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. It includes a Go port of WebBrain's GPL-3.0-or-later d1 runtime+adapter. Third-party components keep their own licenses; see+THIRD_PARTY_NOTICES.md.++The unmodified GNU GPL version 3 license text follows.++ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ 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.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ 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 <http://www.gnu.org/licenses/>.++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:++ <program> Copyright (C) <year> <name of author>+ 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+<http://www.gnu.org/licenses/>.++ 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+<http://www.gnu.org/philosophy/why-not-lgpl.html>.diff --git a/webbrain-systray/README.md b/webbrain-systray/README.mdnew file mode 100644index 000000000..532ee0f58--- /dev/null+++ b/webbrain-systray/README.md@@ -0,0 +1,194 @@+# WebBrain Companion++A small tray app for Windows, macOS and Linux that serves your AI subscriptions+to [WebBrain](https://webbrain.one) on `127.0.0.1`, shows how much of each one+you have left, can run PrismML's Bonsai 2 27B on your own machine, and hosts+WebBrain's d1 decision model natively.++- **Subscriptions on localhost.** Sign in with Claude, ChatGPT (Codex), Google+ (Antigravity), Grok, Kimi, Meta Muse or Devin. They become one OpenAI-,+ Anthropic- and Gemini-compatible endpoint at `http://127.0.0.1:8327`. Apps on+ this computer need no API key; web pages are turned away; other devices can+ connect with a key if you allow it. This is+ [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) embedded in the+ app, with a much smaller UI than EasyCLIProxyAPI.+- **Quotas at a glance.** The tray menu shows each subscription's window+ closest to running out and when it resets; the panel shows every 5-hour,+ weekly and model-specific window. Refreshed every few minutes and when you+ open the panel.+- **Bonsai 2 27B locally.** The smallest packing (PTQ1_0, 5.95 GB) plus the Q8_0+ vision projector through PrismML's llama.cpp fork, or the MLX 2-bit pack on+ Apple Silicon. The companion sizes it to your machine and decides whether the+ vision projector runs on the GPU, on the CPU, or not at all.+- **d1 decision model.** `webbrain-one/d1-browser-decision-fp32` on ONNX Runtime,+ answering the same requests as WebBrain's in-browser WebGPU adapter.++## Install++Download the package for your system and run it. The icon appears in the menu+bar (macOS), notification area (Windows) or status tray (Linux). Opening the+app by hand, also while it already runs, shows its panel; starting at login+does not.++The tray menu holds the status, the address (click to copy), one line per+subscription and *Open panel*. The panel is a single page with the address,+your subscriptions and the two local models; click a row for its details+(every usage window, model options), or **Settings** for start at login,+language, network access, the port, the log file and *Quit*.++| System | Package | First start |+|---|---|---|+| Windows 10/11 (x64, Arm64) | `WebBrain-Companion-*-windows-setup.exe` | One installer for both architectures. It installs for the current user (no administrator prompt) into `%LOCALAPPDATA%\Programs\WebBrain Companion`, adds a Start menu entry and an uninstaller in *Settings, Apps*. Until it is code-signed, SmartScreen says *Windows protected your PC*: *More info*, *Run anyway*. |+| macOS 12+ (Apple Silicon and Intel) | `WebBrain-Companion-*-macos-universal.zip` | Move *WebBrain Companion.app* to Applications first (run from Downloads, macOS uses a temporary copy and start at login cannot work). The build is ad-hoc signed, not notarized: allow it once in *System Settings, Privacy & Security* (*Open Anyway*); on macOS 14 and earlier Control-click it and choose *Open*. If the menu bar is full, macOS hides the icon; the panel says so, and opening the app again always brings the panel back. |+| Linux (x64, Arm64) | `WebBrain-Companion-*-linux-*.tar.gz` | Run `webbrain-companion`. The tray uses StatusNotifierItem (KDE, XFCE, GNOME with the AppIndicator extension). |++`--headless` runs the proxy and APIs without a tray icon, `--background` starts+without opening the panel (used at login), `--version` prints the version.++## Connect WebBrain++In WebBrain's **Providers** page (*More…* in the side panel's model menu), pick+**Local OpenAI-compatible Proxy** and paste the address+(`http://127.0.0.1:8327/v1`) from the panel or the tray menu, replacing the+`8317` WebBrain fills in (that is CLIProxyAPI's default port). WebBrain asks for+an API key: type anything, the companion does not check it for apps on this+computer. Then **Load models** and run **Test Connection**. Turn vision on only+for a model that accepts images (the local `bonsai-2-27b` does when its+projector is on). Any OpenAI, Anthropic or Gemini client works the same way:++```bash+curl http://127.0.0.1:8327/v1/chat/completions \+ -H "Content-Type: application/json" \+ -d '{"model":"claude-sonnet-5-5","messages":[{"role":"user","content":"Hi"}]}'+```++### Other devices++*Settings, Allow other devices on this network* makes the companion listen on+`0.0.0.0`. The panel then shows the network address (for example+`http://192.168.1.57:8327/v1`) and the API key; requests from other devices+must carry it (`Authorization: Bearer`, `x-api-key` or `x-goog-api-key`).+Your system may ask to allow incoming connections. Keep it off on public+Wi-Fi.++`GET /v1/models` lists every model your subscriptions (and the local model)+provide. The local model's id is `bonsai-2-27b`.++## Local model: Bonsai 2 27B++Click **Bonsai 2 27B** in the panel to see what will run before anything+downloads:++| Machine | Runtime chosen |+|---|---|+| Apple Silicon | PrismML llama.cpp, Metal (GGUF) or mlx-vlm (MLX) |+| NVIDIA GPU | PrismML llama.cpp CUDA 12.4 / 12.8 / 13.3 build matching the driver |+| AMD/other GPU with ≥ 6 GB | Vulkan build |+| Anything else | CPU build |++Context follows PrismML's RAM tiers (8K up to 128K tokens) and shrinks until+the weights, KV cache (64 KiB per token on the 27B) and compute buffers fit the+GPU budget. **The vision projector (mmproj Q8_0) is then decided from what is+left:** on the GPU when about 1 GB of GPU memory remains, on the CPU+(`--no-mmproj-offload`) when only system RAM has room, otherwise off. Options+let you force *GPU*, *CPU* or *Off*, pick a context size, or start the model+with the companion. The MLX pack carries its own vision tower, so it always+accepts images.++Downloads are pinned to exact Hugging Face revisions and checked against+SHA-256; interrupted downloads resume.++## Decision model (d1)++```bash+curl http://127.0.0.1:8327/companion/v1/decide \+ -H "Content-Type: application/json" \+ -d '{"state":"Order #1042 is confirmed.","questions":{"completion":{"type":"choice",+ "instructions":"Did the task finish?","criteria":{"completed":"Confirmed",+ "not_completed":"Failed or unfinished","unknown":"Not established"}}}}'+```++Requests and answers match the adapter's `evaluate({state, images, questions})`+(`choice`, `noul` and `score` questions, up to four inline PNG/JPEG/WebP+screenshots). The Go port was checked against the JavaScript adapter on the same+graphs: identical tokens, layouts and probabilities. Text-only rows are capped+at 4,096 tokens on the CPU runtime. The model is under the LFM Open License+v1.0; check its commercial terms before commercial use.++`GET /companion/v1/info` describes the running companion (endpoints, models,+decision status, whether network access is on) for the WebBrain extension. It+sends no CORS headers and only answers this computer, so web pages cannot read+it.++## Where things live++| | Windows | macOS | Linux |+|---|---|---|---|+| Settings, logins | `%APPDATA%\WebBrain Companion` | `~/Library/Application Support/WebBrain Companion` | `~/.config/webbrain-companion` |+| Models, runtimes, logs | `%LOCALAPPDATA%\WebBrain Companion` | same as above | `~/.local/share/webbrain-companion` |++## Security notes++- By default everything listens on `127.0.0.1` only, and apps on this computer+ need no API key. Browser requests are told apart by their `Origin` and+ `Sec-Fetch-Site` headers: extensions (WebBrain) and pages served from+ localhost pass; pages from other sites are refused, even when an extension+ rewrites their `Origin` to `127.0.0.1` (a common workaround for Ollama),+ because the browser still marks them cross-site. Non-loopback `Host` headers+ are refused (DNS rebinding).+- With network access on, the proxy listens on `0.0.0.0` and every request from+ another device needs the API key. The panel, its API and the discovery+ document stay reachable from this computer only; the panel also needs its+ own per-install key.+- OAuth tokens stay in the logins folder above and are only sent to their+ provider. Quotas are read through the proxy's own `api-call`, so tokens never+ pass through the panel.+- No analytics. Besides the providers you sign in to, the embedded proxy+ refreshes CLIProxyAPI's public model catalog every few hours, and installing a+ model downloads from Hugging Face, GitHub and (MLX only) PyPI.+- Using consumer subscriptions through a proxy may conflict with a provider's+ terms. Read WebBrain's+ [setup, security and account-risk guide](https://webbrain.one/docs/easy-cli-proxy/)+ before relying on it.++## Build from source++This directory is a standalone app, imported from+[`esokullu/webbrain-systray` main at `c68416b`](https://github.com/esokullu/webbrain-systray/commit/c68416bc7f0dcb767006f0c67aef017b93dc6e8a)+as a source snapshot. Its Go module and packages are independent of the WebBrain+extension.++Go 1.26+. Everything is pure Go (`CGO_ENABLED=0`), so every platform builds from+any host:++```bash+cd webbrain-systray # from the WebBrain repository root+VERSION=0.1.2 ./scripts/build.sh # Windows installer, macOS (universal .app), Linux packages in dist/+go run . --headless # run locally without a tray+WBC_DEMO=1 go run . --headless # panel with sample data (screenshots, UI work)+```++The Windows installer needs NSIS (`apt install nsis` or `brew install makensis`);+`SIGN_WINDOWS` in `scripts/build.sh` signs the executables and the installer+when a code-signing certificate is available.++The repository's `.github/workflows/systray-build.yml` tests and packages this+app separately. Push a `systray-v<version>` tag (for example `systray-v0.1.2`)+to draft a companion release in this repository; extension releases use their+own tags.++`go test ./...` covers the memory planner (which machines get the vision+projector where), the JavaScript-compatible JSON formatting of the d1 port,+archive extraction and who may use the endpoints (keyless local apps,+extensions, refused web pages, DNS rebinding, network access with the key).++The product site lives in `web/` (English and Turkish, built by+`python3 web/build.py`); see `web/README.md`.++The macOS menu-bar code is a small Cocoa binding on purego+(`internal/tray/tray_darwin.go`); Windows and Linux use fyne.io/systray. Icons+are generated from WebBrain's mark by `scripts/make_icons.py`.++## License++GPL-3.0-or-later, like WebBrain. See `LICENSE` and `THIRD_PARTY_NOTICES.md`.diff --git a/webbrain-systray/THIRD_PARTY_NOTICES.md b/webbrain-systray/THIRD_PARTY_NOTICES.mdnew file mode 100644index 000000000..a5db13eac--- /dev/null+++ b/webbrain-systray/THIRD_PARTY_NOTICES.md@@ -0,0 +1,30 @@+# Third-party notices++WebBrain Companion is GPL-3.0-or-later (see `LICENSE`). It builds on the+following components, each under its own license.++## Compiled into the executable++| Component | License | Use |+|---|---|---|+| [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) v8.0.35 (Copyright Luis Pater, Router-For.ME) | MIT | Embedded proxy: subscription logins, OpenAI/Anthropic/Gemini compatible endpoints, management API |+| [fyne.io/systray](https://github.com/fyne-io/systray) | Apache-2.0 | Tray icon on Windows and Linux |+| [purego](https://github.com/ebitengine/purego) | Apache-2.0 | Cocoa status item on macOS and ONNX Runtime loading without cgo |+| [regexp2](https://github.com/dlclark/regexp2) | MIT | Tokenizer pre-split pattern |+| [golang.org/x/image](https://pkg.go.dev/golang.org/x/image), [golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys) | BSD-3-Clause | WebP decoding, OS calls |+| [atotto/clipboard](https://github.com/atotto/clipboard) | BSD-3-Clause | Copy from the tray menu |+| [Bricolage Grotesque](https://github.com/ateliertriay/bricolage) | SIL OFL 1.1 | Panel typeface (`internal/panel/assets/fonts/OFL-BricolageGrotesque.txt`) |+| WebBrain d1 runtime adapter (`d1-runtime.js`, `d1-preprocess.js`) | GPL-3.0-or-later | Ported to Go in `internal/d1` |++Go module licenses for the full dependency graph are listed by+`go-licenses report ./...`.++## Downloaded on demand (not redistributed)++| Component | License | Notes |+|---|---|---|+| [Ternary Bonsai 2 27B](https://huggingface.co/prism-ml/Ternary-Bonsai-2-27B-gguf) GGUF / [MLX](https://huggingface.co/prism-ml/Ternary-Bonsai-2-27B-mlx-2bit) (PrismML) | Apache-2.0 | Pinned revisions, SHA-256 verified |+| [PrismML llama.cpp fork](https://github.com/PrismML-Eng/llama.cpp) release `prism-b10787-73bfe6c` | MIT | Needed for PTQ1_0; stock llama.cpp rejects it |+| MLX, mlx-vlm, mlx-lm, transformers (PyPI, via [uv](https://github.com/astral-sh/uv)) | MIT / Apache-2.0 | Apple Silicon MLX path only |+| [d1-browser-decision-fp32](https://huggingface.co/webbrain-one/d1-browser-decision-fp32) | LFM Open License v1.0 | Derived from LiquidAI d1-omni; commercial-use terms include a US$10M revenue threshold |+| [ONNX Runtime](https://github.com/microsoft/onnxruntime) 1.31.0 | MIT | CPU runtime for the decision model, SHA-256 verified |diff --git a/webbrain-systray/assets/icons/app-128.png b/webbrain-systray/assets/icons/app-128.pngnew file mode 100644index 000000000..b39de0f51Binary files /dev/null and b/webbrain-systray/assets/icons/app-128.png differdiff --git a/webbrain-systray/assets/icons/app-256.png b/webbrain-systray/assets/icons/app-256.pngnew file mode 100644index 000000000..f2abb15d3Binary files /dev/null and b/webbrain-systray/assets/icons/app-256.png differdiff --git a/webbrain-systray/assets/icons/app-512.png b/webbrain-systray/assets/icons/app-512.pngnew file mode 100644index 000000000..3620c12d3Binary files /dev/null and b/webbrain-systray/assets/icons/app-512.png differdiff --git a/webbrain-systray/assets/icons/app.icns b/webbrain-systray/assets/icons/app.icnsnew file mode 100644index 000000000..cce2742f5Binary files /dev/null and b/webbrain-systray/assets/icons/app.icns differdiff --git a/webbrain-systray/assets/icons/app.ico b/webbrain-systray/assets/icons/app.iconew file mode 100644index 000000000..18b8da79bBinary files /dev/null and b/webbrain-systray/assets/icons/app.ico differdiff --git a/webbrain-systray/assets/icons/template-detailed-256.png b/webbrain-systray/assets/icons/template-detailed-256.pngnew file mode 100644index 000000000..07ea37340Binary files /dev/null and b/webbrain-systray/assets/icons/template-detailed-256.png differdiff --git a/webbrain-systray/assets/icons/template-preview-256.png b/webbrain-systray/assets/icons/template-preview-256.pngnew file mode 100644index 000000000..56c1e1d18Binary files /dev/null and b/webbrain-systray/assets/icons/template-preview-256.png differdiff --git a/webbrain-systray/assets/icons/webbrain-logo-mark.png b/webbrain-systray/assets/icons/webbrain-logo-mark.pngnew file mode 100644index 000000000..6f4df384eBinary files /dev/null and b/webbrain-systray/assets/icons/webbrain-logo-mark.png differdiff --git a/webbrain-systray/go.mod b/webbrain-systray/go.modnew file mode 100644index 000000000..1658ab7af--- /dev/null+++ b/webbrain-systray/go.mod@@ -0,0 +1,87 @@+module github.com/esokullu/webbrain-systray++go 1.26.0++toolchain go1.26.10++require (+ fyne.io/systray v1.12.2+ github.com/atotto/clipboard v0.1.4+ github.com/dlclark/regexp2 v1.12.0+ github.com/ebitengine/purego v0.11.2+ github.com/gin-gonic/gin v1.10.1+ github.com/router-for-me/CLIProxyAPI/v8 v8.0.35+ github.com/sirupsen/logrus v1.9.3+ golang.org/x/image v0.47.0+ golang.org/x/sys v0.49.0+)++require (+ cloud.google.com/go/compute/metadata v0.3.0 // indirect+ github.com/andybalholm/brotli v1.0.6 // indirect+ github.com/bytedance/sonic v1.11.6 // indirect+ github.com/bytedance/sonic/loader v0.1.1 // indirect+ github.com/cespare/xxhash/v2 v2.3.0 // indirect+ github.com/cloudwego/base64x v0.1.4 // indirect+ github.com/cloudwego/iasm v0.2.0 // indirect+ github.com/dlclark/regexp2/v2 v2.5.1 // indirect+ github.com/fsnotify/fsnotify v1.9.0 // indirect+ github.com/gabriel-vasile/mimetype v1.4.3 // indirect+ github.com/gin-contrib/sse v0.1.0 // indirect+ github.com/go-playground/locales v0.14.1 // indirect+ github.com/go-playground/universal-translator v0.18.1 // indirect+ github.com/go-playground/validator/v10 v10.20.0 // indirect+ github.com/goccy/go-json v0.10.2 // indirect+ github.com/godbus/dbus/v5 v5.1.0 // indirect+ github.com/google/uuid v1.6.0 // indirect+ github.com/gorilla/websocket v1.5.3 // indirect+ github.com/json-iterator/go v1.1.12 // indirect+ github.com/klauspost/compress v1.17.4 // indirect+ github.com/klauspost/cpuid/v2 v2.3.0 // indirect+ github.com/leodido/go-urn v1.4.0 // indirect+ github.com/libp2p/zeroconf/v2 v2.2.0 // indirect+ github.com/mattn/go-isatty v0.0.20 // indirect+ github.com/miekg/dns v1.1.43 // indirect+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect+ github.com/modern-go/reflect2 v1.0.2 // indirect+ github.com/pelletier/go-toml/v2 v2.2.2 // indirect+ github.com/pierrec/xxHash v0.1.5 // indirect+ github.com/pion/datachannel v1.6.2 // indirect+ github.com/pion/dtls/v3 v3.1.5 // indirect+ github.com/pion/ice/v4 v4.3.0 // indirect+ github.com/pion/interceptor v0.1.45 // indirect+ github.com/pion/logging v0.2.4 // indirect+ github.com/pion/mdns/v2 v2.1.0 // indirect+ github.com/pion/randutil v0.1.0 // indirect+ github.com/pion/rtcp v1.2.17 // indirect+ github.com/pion/rtp v1.10.4 // indirect+ github.com/pion/sctp v1.11.0 // indirect+ github.com/pion/sdp/v3 v3.0.19 // indirect+ github.com/pion/srtp/v3 v3.0.12 // indirect+ github.com/pion/stun/v3 v3.1.6 // indirect+ github.com/pion/transport/v4 v4.0.2 // indirect+ github.com/pion/turn/v5 v5.0.12 // indirect+ github.com/pion/webrtc/v4 v4.2.17 // indirect+ github.com/redis/go-redis/v9 v9.19.0 // indirect+ github.com/refraction-networking/utls v1.8.2 // indirect+ github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect+ github.com/tidwall/gjson v1.18.0 // indirect+ github.com/tidwall/match v1.1.1 // indirect+ github.com/tidwall/pretty v1.2.0 // indirect+ github.com/tidwall/sjson v1.2.5 // indirect+ github.com/tiktoken-go/tokenizer v0.8.1 // indirect+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect+ github.com/ugorji/go/codec v1.2.12 // indirect+ github.com/wlynxg/anet v0.0.5 // indirect+ go.uber.org/atomic v1.11.0 // indirect+ golang.org/x/arch v0.8.0 // indirect+ golang.org/x/crypto v0.54.0 // indirect+ golang.org/x/net v0.57.0 // indirect+ golang.org/x/oauth2 v0.30.0 // indirect+ golang.org/x/sync v0.24.0 // indirect+ golang.org/x/text v0.43.0 // indirect+ golang.org/x/time v0.14.0 // indirect+ google.golang.org/protobuf v1.34.1 // indirect+ gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect+)diff --git a/webbrain-systray/go.sum b/webbrain-systray/go.sumnew file mode 100644index 000000000..70111581d--- /dev/null+++ b/webbrain-systray/go.sum@@ -0,0 +1,213 @@+cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=+cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=+fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA=+fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=+github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=+github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=+github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=+github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=+github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=+github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=+github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=+github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=+github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=+github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=+github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=+github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=+github.com/dlclark/regexp2/v2 v2.5.1 h1:E5Ug7Dh264W1ymdySmiHNcDG7fmsR307APCE5R07a20=+github.com/dlclark/regexp2/v2 v2.5.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=+github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=+github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=+github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=+github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=+github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=+github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=+github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=+github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=+github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=+github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=+github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=+github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=+github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=+github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=+github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=+github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=+github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=+github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=+github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=+github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=+github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=+github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=+github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=+github.com/libp2p/zeroconf/v2 v2.2.0 h1:Cup06Jv6u81HLhIj1KasuNM/RHHrJ8T7wOTS4+Tv53Q=+github.com/libp2p/zeroconf/v2 v2.2.0/go.mod h1:fuJqLnUwZTshS3U/bMRJ3+ow/v9oid1n0DmyYyNO1Xs=+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/miekg/dns v1.1.43 h1:JKfpVSCB84vrAmHzyrsxB5NAr5kLoMXZArPSw7Qlgyg=+github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=+github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=+github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=+github.com/pierrec/xxHash v0.1.5 h1:n/jBpwTHiER4xYvK3/CdPVnLDPchj8eTJFFLUb4QHBo=+github.com/pierrec/xxHash v0.1.5/go.mod h1:w2waW5Zoa/Wc4Yqe0wgrIYAGKqRMf7czn2HNKXmuL+I=+github.com/pion/datachannel v1.6.2 h1:7EXQ8TH3vTouBUdRWYbcX2edSx9Yj6k5zl5P+qyxEPc=+github.com/pion/datachannel v1.6.2/go.mod h1:pzbdAZvyGtXbcHM1hBbsFaOTf40lZizU/dNlvVOak6E=+github.com/pion/dtls/v3 v3.1.5 h1:9xJtVsHwMYeSjPp5Hh1FTis4DchnQWtnOa5o+6ygqfc=+github.com/pion/dtls/v3 v3.1.5/go.mod h1:gz1K4jg6c+fq86oQMH4pilpCEOEPwmEr2jY+VcF/mkU=+github.com/pion/ice/v4 v4.3.0 h1:X8l4s9zV2HeTKX33nulWAFXAEo5KhIVzOsY62/3t/LM=+github.com/pion/ice/v4 v4.3.0/go.mod h1:obAyD+J+Hzs7QA7Y8YXHp5uIn6gb7z87pKedXZkrcFU=+github.com/pion/interceptor v0.1.45 h1:6PUo/5829bIfRFIPPJQzuDn8EjxRTSB/CSD7QVCOaqo=+github.com/pion/interceptor v0.1.45/go.mod h1:gNDYM/uFKcLe/B3gS2/7+aw6z+RDiMy2qKTnF1LO31w=+github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=+github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=+github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=+github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=+github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=+github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=+github.com/pion/rtcp v1.2.17 h1:PxiT6L79yPZKtXIsXdG1eakBl6dtBj4x+4oVEL0DlSw=+github.com/pion/rtcp v1.2.17/go.mod h1:7kBpuBJaWwax4hzc/pgexY8vkOpvh8atgYDbaKZq0iU=+github.com/pion/rtp v1.10.4 h1:4sCUwUd35Nllcpyp8V7lRgb4DV/ulHJaRTjbrkAcpQ4=+github.com/pion/rtp v1.10.4/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk=+github.com/pion/sctp v1.11.0 h1:sAxv9Qp3uIcaF5wu1XntwshtnW93CEuxhpkYzSbnfMs=+github.com/pion/sctp v1.11.0/go.mod h1:7KFmTwLcoYgJs/Z+99nJvsWL0qDpuyloSI0RbAqlrz0=+github.com/pion/sdp/v3 v3.0.19 h1:1VMKs3gIkTQV5M3hNKfTAPrDXSNrYtOlmOD8+mSZUGQ=+github.com/pion/sdp/v3 v3.0.19/go.mod h1:dE5WOSlzXrtiE/iuZqe9n+AcEbOjtAd3k5m5NtlV/qU=+github.com/pion/srtp/v3 v3.0.12 h1:U7V17bckl7sI4mb3sepiojByDuBY0wNCqQE+6IlQBbc=+github.com/pion/srtp/v3 v3.0.12/go.mod h1:EeZOi/sd6glM1EXapg051gdNWO9yWT1YSsgQ4SlJkns=+github.com/pion/stun/v3 v3.1.6 h1:WnhsD0eHCiwCfKNkVx0VJJwr2Y3eV4Ueih3KJ+dfZy8=+github.com/pion/stun/v3 v3.1.6/go.mod h1:zRUghXSQU32Lx5orJsz3uYMkIihweXb3mu5gIns02fs=+github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=+github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=+github.com/pion/transport/v4 v4.0.2 h1:ifYlPqNwsy6aKQ9y8yzxXlHae5431ZrH2avkD/Rn6Tk=+github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=+github.com/pion/turn/v5 v5.0.12 h1:6+b69ivQQXSlyfkp2AKripqD2k3W32qXK8QzCzpJWPI=+github.com/pion/turn/v5 v5.0.12/go.mod h1:CQACsRDJtjQ+6RSrGHrS2PCIerLwbW3uqXRqOvtjAFg=+github.com/pion/webrtc/v4 v4.2.17 h1:no7rmszKV1jkGz7GvErGp/VlnzGu/koVHO9CRjItiVU=+github.com/pion/webrtc/v4 v4.2.17/go.mod h1:xRtWZDJ0FbyW98WVCCgOvxaBM5gxqqJa7pCc4f+x/LI=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k=+github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=+github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=+github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=+github.com/router-for-me/CLIProxyAPI/v8 v8.0.35 h1:Yzo9IByvbAxqSXlIHNOcsa0ZSNqKBbEYlzZeLKQZWWQ=+github.com/router-for-me/CLIProxyAPI/v8 v8.0.35/go.mod h1:j1Mtcj0TrC66O1JwbSBB03lY3uYPx4J7yHNvU6nDBCo=+github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=+github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=+github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=+github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=+github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=+github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=+github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=+github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=+github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=+github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=+github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=+github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=+github.com/tiktoken-go/tokenizer v0.8.1 h1:4obDoB6/dhdBt9xMweX4nww5cjdOq/nYF4ecwPq2+mg=+github.com/tiktoken-go/tokenizer v0.8.1/go.mod h1:eLA0t6nGvn9mDc7gt90qt7pMat+gE9ViqwQ6l9B+tA4=+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=+github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=+github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=+github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=+github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=+go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=+golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=+golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=+golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=+golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=+golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=+golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=+golang.org/x/net v0.0.0-20210423184538-5f58ad60dda6/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=+golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=+golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=+golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=+golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210426080607-c94f62235c83/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=+golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=+golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=+golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=+google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=+gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=+rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=diff --git a/webbrain-systray/internal/accounts/accounts.go b/webbrain-systray/internal/accounts/accounts.gonew file mode 100644index 000000000..01920ccf3--- /dev/null+++ b/webbrain-systray/internal/accounts/accounts.go@@ -0,0 +1,140 @@+// Package accounts knows which subscriptions can be added and turns the+// proxy's credential list into the companion's account model.+package accounts++import (+ "sort"+ "strings"++ "github.com/esokullu/webbrain-systray/internal/core"+ "github.com/esokullu/webbrain-systray/internal/quota"+)++// Provider is a subscription the user can sign in with.+type Provider struct {+ ID string `json:"id"` // login id for the management API+ Matches []string `json:"-"` // credential provider names it produces+ Name string `json:"name"` // short brand name+ Product string `json:"product"` // what the subscription is called+ Flow string `json:"flow"` // "browser" or "device"+ Quota bool `json:"quota"` // usage windows are readable+ Primary bool `json:"primary"` // shown before "more"+ Initials string `json:"initials"` // badge text+ Hue int `json:"hue"` // badge hue (HSL)+}++// Catalog lists the subscriptions supported by the embedded CLIProxyAPI v8.+var Catalog = []Provider{+ {ID: "claude", Matches: []string{"claude", "anthropic"}, Name: "Claude", Product: "Pro, Max or Team plan", Flow: "browser", Quota: true, Primary: true, Initials: "Cl", Hue: 22},+ {ID: "codex", Matches: []string{"codex"}, Name: "ChatGPT", Product: "Plus or Pro, through Codex sign-in", Flow: "browser", Quota: true, Primary: true, Initials: "GP", Hue: 160},+ {ID: "antigravity", Matches: []string{"antigravity"}, Name: "Google", Product: "Gemini through Antigravity", Flow: "browser", Quota: true, Primary: true, Initials: "G", Hue: 215},+ {ID: "xai", Matches: []string{"xai", "grok"}, Name: "Grok", Product: "SuperGrok, through Grok Build", Flow: "device", Quota: true, Primary: true, Initials: "X", Hue: 0},+ {ID: "kimi-ai", Matches: []string{"kimi-ai"}, Name: "Kimi", Product: "Kimi Code on kimi.ai", Flow: "device", Quota: true, Primary: true, Initials: "K", Hue: 265},+ {ID: "kimi", Matches: []string{"kimi"}, Name: "Kimi (CN)", Product: "Kimi Code on kimi.com", Flow: "device", Quota: true, Initials: "K", Hue: 265},+ {ID: "meta", Matches: []string{"meta"}, Name: "Meta Muse", Product: "Muse Code", Flow: "device", Initials: "M", Hue: 205},+ {ID: "devin", Matches: []string{"devin", "cognition"}, Name: "Devin", Product: "Devin account", Flow: "browser", Initials: "D", Hue: 145},+}++// ProviderFor maps a credential's provider name to the catalog entry.+func ProviderFor(name string) Provider {+ name = strings.ToLower(strings.TrimSpace(name))+ for _, p := range Catalog {+ for _, m := range p.Matches {+ if m == name {+ return p+ }+ }+ }+ return Provider{ID: name, Name: strings.ToUpper(name[:min(1, len(name))]) + name[min(1, len(name)):], Initials: strings.ToUpper(name[:min(2, len(name))]), Hue: 250}+}++func Lookup(id string) (Provider, bool) {+ for _, p := range Catalog {+ if p.ID == id {+ return p, true+ }+ }+ return Provider{}, false+}++// Account is one signed-in subscription.+type Account struct {+ Name string `json:"name"` // credential file name (stable id)+ Provider string `json:"provider"`+ ProviderName string `json:"provider_name"`+ Initials string `json:"initials"`+ Hue int `json:"hue"`+ Email string `json:"email,omitempty"`+ Label string `json:"label,omitempty"`+ Disabled bool `json:"disabled"`+ Unavailable bool `json:"unavailable"`+ Status string `json:"status,omitempty"`+ StatusMessage string `json:"status_message,omitempty"`+ Quota quota.State `json:"quota"`+ QuotaKnown bool `json:"quota_supported"`+}++// Who tells logins of the same provider apart: the email (or label), else the+// credential's file name.+func (a Account) Who() string {+ if a.Email != "" {+ return a.Email+ }+ return strings.TrimSuffix(a.Name, ".json")+}++// FromCredentials builds accounts, attaching cached quotas by credential name.+func FromCredentials(creds []core.Credential, quotas map[string]quota.State) []Account {+ out := make([]Account, 0, len(creds))+ for _, c := range creds {+ prov := c.Provider()+ if prov == "" {+ continue+ }+ p := ProviderFor(prov)+ a := Account{+ Name: c.Name(),+ Provider: prov,+ ProviderName: p.Name,+ Initials: p.Initials,+ Hue: p.Hue,+ Email: c.Str("email", "account"),+ Label: c.Str("label"),+ Disabled: c.Bool("disabled"),+ Unavailable: c.Bool("unavailable"),+ Status: c.Str("status"),+ StatusMessage: c.Str("status_message"),+ QuotaKnown: quota.Supported(prov),+ }+ if a.Email == "" {+ a.Email = a.Label+ }+ if q, ok := quotas[a.Name]; ok {+ a.Quota = q+ } else if a.QuotaKnown {+ a.Quota = quota.State{Status: "loading"}+ } else {+ a.Quota = quota.State{Status: "unsupported"}+ }+ out = append(out, a)+ }+ sort.SliceStable(out, func(i, j int) bool {+ pi, pj := providerRank(out[i].Provider), providerRank(out[j].Provider)+ if pi != pj {+ return pi < pj+ }+ return out[i].Email < out[j].Email+ })+ return out+}++func providerRank(p string) int {+ for i, c := range Catalog {+ for _, m := range c.Matches {+ if m == p {+ return i+ }+ }+ }+ return len(Catalog)+}diff --git a/webbrain-systray/internal/app/access.go b/webbrain-systray/internal/app/access.gonew file mode 100644index 000000000..bc41e744d--- /dev/null+++ b/webbrain-systray/internal/app/access.go@@ -0,0 +1,152 @@+package app++import (+ "net"+ "net/http"+ "net/url"+ "strings"++ "github.com/gin-gonic/gin"+)++// Who may use the subscriptions:+//+// - Apps on this computer need no key. That covers native clients (no+// Origin header), browser extensions such as WebBrain, and pages served+// from localhost itself.+// - Web pages from other sites are refused, so a site you visit cannot spend+// your plans. Some extensions rewrite the Origin of every request to+// 127.0.0.1 (a common trick for Ollama); the browser still marks those+// requests Sec-Fetch-Site: cross-site, which is checked too.+// - Other devices can connect only when network access is on, and then need+// the API key (the proxy checks it).++// apiPath reports whether a path is one of the proxy's model endpoints.+func apiPath(p string) bool {+ for _, prefix := range []string{"/v1/", "/v1beta/", "/openai/", "/backend-api/"} {+ if strings.HasPrefix(p, prefix) {+ return true+ }+ }+ return p == "/v1" || p == "/v1beta"+}++// loopbackAddr reports whether the TCP peer is this computer.+func loopbackAddr(remote string) bool {+ host, _, err := net.SplitHostPort(remote)+ if err != nil {+ host = remote+ }+ ip := net.ParseIP(strings.Trim(host, "[]"))+ return ip != nil && ip.IsLoopback()+}++// localHost accepts only loopback Host headers, which defeats DNS rebinding.+func localHost(host string) bool {+ h, _, err := net.SplitHostPort(host)+ if err != nil {+ h = host+ }+ return loopbackName(strings.Trim(h, "[]"))+}++func loopbackName(h string) bool {+ h = strings.ToLower(strings.TrimSuffix(h, "."))+ if h == "localhost" || strings.HasSuffix(h, ".localhost") {+ return true+ }+ ip := net.ParseIP(h)+ return ip != nil && ip.IsLoopback()+}++func extensionOrigin(o string) bool {+ for _, p := range []string{"chrome-extension://", "moz-extension://", "safari-web-extension://"} {+ if strings.HasPrefix(o, p) {+ return true+ }+ }+ return false+}++// loopbackOrigin is a page served from this computer, on any port (extensions+// that rewrite Origin often drop the port).+func loopbackOrigin(o string) bool {+ u, err := url.Parse(o)+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") {+ return false+ }+ return loopbackName(u.Hostname())+}++func crossSite(r *http.Request) bool {+ return strings.EqualFold(strings.TrimSpace(r.Header.Get("Sec-Fetch-Site")), "cross-site")+}++// localClientAllowed decides whether a request that arrived over loopback+// comes from something on this computer that may use the subscriptions+// without a key.+func localClientAllowed(r *http.Request) bool {+ origin := strings.TrimSpace(r.Header.Get("Origin"))+ switch {+ case extensionOrigin(origin):+ return true+ case crossSite(r):+ return false+ case origin == "":+ return true+ }+ return loopbackOrigin(origin)+}++// hasCredential reports whether the client sent an API key in any of the+// forms the proxy accepts.+func hasCredential(r *http.Request) bool {+ if r.Header.Get("Authorization") != "" || r.Header.Get("X-Api-Key") != "" || r.Header.Get("X-Goog-Api-Key") != "" {+ return true+ }+ q := r.URL.Query()+ return q.Get("key") != "" || q.Get("auth_token") != ""+}++func deny(c *gin.Context, msg string) {+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": gin.H{"message": msg, "type": "forbidden", "code": "companion_forbidden"}})+}++const (+ msgRebinding = "WebBrain Companion only answers to 127.0.0.1 or localhost."+ msgWebPage = "Web pages can't use WebBrain Companion. Browser extensions and apps on this computer can; anything else needs the API key."+ msgNetwork = "Network access is off. Turn on \"Allow other devices on this network\" in WebBrain Companion's Settings to connect from another device."+)++// access runs before the proxy's own middleware on its model endpoints.+func (a *App) access(c *gin.Context) {+ r := c.Request+ if !apiPath(r.URL.Path) {+ c.Next()+ return+ }+ if loopbackAddr(r.RemoteAddr) {+ if !localHost(r.Host) {+ deny(c, msgRebinding)+ return+ }+ if localClientAllowed(r) {+ // Authenticate as the companion itself; whatever key the app sent+ // (WebBrain insists on one) does not matter.+ r.Header.Set("Authorization", "Bearer "+a.internalKey)+ c.Next()+ return+ }+ if !hasCredential(r) {+ deny(c, msgWebPage)+ return+ }+ c.Next() // a web page that knows the API key: the proxy checks it+ return+ }+ if !a.Store.Get().Network {+ deny(c, msgNetwork)+ return+ }+ c.Next() // another device: the proxy checks the API key+}diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.gonew file mode 100644index 000000000..ebfe61f45--- /dev/null+++ b/webbrain-systray/internal/app/app.go@@ -0,0 +1,538 @@+// Package app wires the companion together: the embedded proxy, accounts and+// their quotas, the local model, the decision model, the panel API and the+// tray menu.+package app++import (+ "context"++ "errors"+ "fmt"+ "github.com/gin-gonic/gin"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/esokullu/webbrain-systray/internal/accounts"+ "github.com/esokullu/webbrain-systray/internal/core"+ "github.com/esokullu/webbrain-systray/internal/d1"+ "github.com/esokullu/webbrain-systray/internal/i18n"+ "github.com/esokullu/webbrain-systray/internal/localmodel"+ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/osutil"+ "github.com/esokullu/webbrain-systray/internal/quota"+ "github.com/esokullu/webbrain-systray/internal/settings"+)++type login struct {+ Provider string `json:"provider"`+ State string `json:"state"`+ Started time.Time `json:"started"`+ Status string `json:"status"` // wait | ok | error+ Error string `json:"error,omitempty"`+}++type App struct {+ Version string+ Store *settings.Store+ Proxy *core.Proxy+ Local *localmodel.Manager+ D1 *d1.Manager++ mu sync.Mutex+ creds []core.Credential+ credsErr string+ quotas map[string]quota.State+ models []string+ logins map[string]*login+ notice string+ quotaBusy bool++ subsMu sync.Mutex+ subs map[chan struct{}]struct{}++ // OnChange is called (debounced by the tray) whenever state changes.+ OnChange func()+ // Quit exits the app (set by main; the panel offers it when the menu bar+ // icon is out of reach).+ Quit func()+ // OnProxyStart is called with the port after every (re)start, so main can+ // keep the single-instance runtime file current.+ OnProxyStart func(port int)+ // OpenPanel opens the panel window (set by main).+ OpenPanel func(fragment string)++ // internalKey authenticates apps on this computer with the proxy; it never+ // leaves the process.+ internalKey string++ ctx context.Context+ cancel context.CancelFunc+}++func New(version string, store *settings.Store) *App {+ a := &App{+ Version: version,+ Store: store,+ Proxy: core.New(),+ quotas: map[string]quota.State{},+ logins: map[string]*login{},+ subs: map[chan struct{}]struct{}{},++ internalKey: "wbc-local-" + settings.RandomSecret(),+ }+ a.ctx, a.cancel = context.WithCancel(context.Background())+ a.Local = localmodel.NewManager(store, a.Proxy.SetLocal, a.changed)+ a.D1 = d1.NewManager(store, a.changed)+ return a+}++// changed notifies panel listeners and the tray.+func (a *App) changed() {+ a.subsMu.Lock()+ for ch := range a.subs {+ select {+ case ch <- struct{}{}:+ default:+ }+ }+ a.subsMu.Unlock()+ if a.OnChange != nil {+ a.OnChange()+ }+}++// Subscribe returns a channel signalled on every state change.+func (a *App) Subscribe() (chan struct{}, func()) {+ ch := make(chan struct{}, 1)+ a.subsMu.Lock()+ a.subs[ch] = struct{}{}+ a.subsMu.Unlock()+ return ch, func() {+ a.subsMu.Lock()+ delete(a.subs, ch)+ a.subsMu.Unlock()+ }+}++// Start brings the proxy up and starts background refreshes.+func (a *App) Start() error {+ s := a.Store.Get()+ i18n.Set(s.Language)+ err := a.Proxy.Start(a.proxyOptions(s, nil))+ if err != nil && s.Network {+ // The network address may be unavailable; fall back to this computer only.+ logx.Printf("network access: %v; listening on 127.0.0.1 only", err)+ s.Network = false+ err = a.Proxy.Start(a.proxyOptions(s, nil))+ }+ if err != nil {+ return err+ }+ if p := a.Proxy.Port(); p != s.Port {+ a.setNotice(fmt.Sprintf(i18n.T("port_moved"), s.Port, p))+ }+ if s.Autostart || osutil.AutostartEnabled() {+ // Re-register so the login item points at this executable.+ _ = osutil.SetAutostart(s.Autostart)+ }+ go a.loop()+ go func() {+ if s.Local.AutoStart {+ if err := a.Local.Start(); err != nil {+ logx.Printf("local model autostart: %v", err)+ }+ }+ }()+ go func() {+ if s.Decision.Enabled && a.D1.Installed() {+ if err := a.D1.Load(); err != nil {+ logx.Printf("decision model load: %v", err)+ }+ }+ }()+ return nil+}++// Shutdown stops child servers and the proxy.+func (a *App) Shutdown() {+ a.cancel()+ a.Local.Stop()+ a.D1.Unload()+ a.Proxy.Stop()+}++func (a *App) setNotice(s string) {+ a.mu.Lock()+ a.notice = s+ a.mu.Unlock()+ a.changed()+}++func (a *App) loop() {+ a.refreshAccounts()+ a.RefreshQuotas("")+ accT := time.NewTicker(30 * time.Second)+ defer accT.Stop()+ lastQuota := time.Now()+ for {+ select {+ case <-a.ctx.Done():+ return+ case <-accT.C:+ a.refreshAccounts()+ every := time.Duration(a.Store.Get().QuotaRefreshMinutes) * time.Minute+ if every <= 0 {+ every = 5 * time.Minute+ }+ if time.Since(lastQuota) >= every {+ lastQuota = time.Now()+ a.RefreshQuotas("")+ }+ }+ }+}++func (a *App) refreshAccounts() {+ m := a.Proxy.Mgmt()+ if m == nil {+ return+ }+ ctx, cancel := context.WithTimeout(a.ctx, 15*time.Second)+ defer cancel()+ creds, err := m.Credentials(ctx)+ models, _ := m.Models(ctx)+ a.mu.Lock()+ if err != nil {+ a.credsErr = err.Error()+ } else {+ a.credsErr = ""+ a.creds = creds+ // Forget quotas of removed accounts.+ keep := map[string]bool{}+ for _, c := range creds {+ keep[c.Name()] = true+ }+ for k := range a.quotas {+ if !keep[k] {+ delete(a.quotas, k)+ }+ }+ }+ sort.Strings(models)+ a.models = models+ a.mu.Unlock()+ a.changed()+}++// RefreshQuotas re-reads usage for one account (by name) or all of them.+func (a *App) RefreshQuotas(name string) {+ m := a.Proxy.Mgmt()+ if m == nil {+ return+ }+ a.mu.Lock()+ if name == "" && a.quotaBusy {+ a.mu.Unlock()+ return+ }+ if name == "" {+ a.quotaBusy = true+ }+ creds := append([]core.Credential(nil), a.creds...)+ a.mu.Unlock()+ defer func() {+ if name == "" {+ a.mu.Lock()+ a.quotaBusy = false+ a.mu.Unlock()+ }+ }()+ sem := make(chan struct{}, 3)+ var wg sync.WaitGroup+ for _, c := range creds {+ if name != "" && c.Name() != name {+ continue+ }+ if !quota.Supported(c.Provider()) {+ continue+ }+ wg.Add(1)+ go func(c core.Credential) {+ defer wg.Done()+ sem <- struct{}{}+ defer func() { <-sem }()+ ctx, cancel := context.WithTimeout(a.ctx, 40*time.Second)+ defer cancel()+ st := quota.Fetch(ctx, m, c)+ a.mu.Lock()+ prev, had := a.quotas[c.Name()]+ if st.Status == "error" && had && prev.Status == "ok" && time.Since(prev.FetchedAt) < 30*time.Minute {+ // Keep showing the last good numbers; note the failure.+ prev.Error = st.Error+ st = prev+ }+ a.quotas[c.Name()] = st+ a.mu.Unlock()+ a.changed()+ }(c)+ }+ wg.Wait()+}++// --- logins -----------------------------------------------------------------------++func (a *App) StartLogin(provider string) (core.LoginStart, error) {+ if _, ok := accounts.Lookup(provider); !ok {+ return core.LoginStart{}, fmt.Errorf("unknown provider %q", provider)+ }+ m := a.Proxy.Mgmt()+ if m == nil {+ return core.LoginStart{}, errors.New("proxy is not running")+ }+ ctx, cancel := context.WithTimeout(a.ctx, 30*time.Second)+ defer cancel()+ ls, err := m.StartLogin(ctx, provider)+ if err != nil {+ return ls, err+ }+ a.mu.Lock()+ a.logins[ls.State] = &login{Provider: provider, State: ls.State, Started: time.Now(), Status: "wait"}+ a.mu.Unlock()+ if ls.URL != "" {+ _ = osutil.OpenURL(ls.URL)+ }+ go a.watchLogin(ls.State)+ return ls, nil+}++func (a *App) watchLogin(state string) {+ m := a.Proxy.Mgmt()+ deadline := time.Now().Add(31 * time.Minute)+ for time.Now().Before(deadline) {+ select {+ case <-a.ctx.Done():+ return+ case <-time.After(2 * time.Second):+ }+ a.mu.Lock()+ l := a.logins[state]+ a.mu.Unlock()+ if l == nil || l.Status != "wait" {+ return+ }+ ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)+ status, msg, err := m.LoginStatus(ctx, state)+ cancel()+ if err != nil {+ continue+ }+ if status == "ok" || status == "error" {+ a.mu.Lock()+ l.Status, l.Error = status, msg+ a.mu.Unlock()+ if status == "ok" {+ a.refreshAccounts()+ go a.RefreshQuotas("")+ }+ a.changed()+ return+ }+ }+ a.mu.Lock()+ if l := a.logins[state]; l != nil && l.Status == "wait" {+ l.Status, l.Error = "error", "timed out"+ }+ a.mu.Unlock()+ a.changed()+}++func (a *App) Login(state string) (login, bool) {+ a.mu.Lock()+ defer a.mu.Unlock()+ l, ok := a.logins[state]+ if !ok {+ return login{}, false+ }+ return *l, true+}++func (a *App) CancelLogin(state string) {+ a.mu.Lock()+ l := a.logins[state]+ delete(a.logins, state)+ a.mu.Unlock()+ if l != nil {+ if m := a.Proxy.Mgmt(); m != nil {+ ctx, cancel := context.WithTimeout(a.ctx, 10*time.Second)+ _ = m.CancelLogin(ctx, state)+ cancel()+ }+ }+ a.changed()+}++func (a *App) SubmitCallback(state, redirectURL string) error {+ a.mu.Lock()+ l := a.logins[state]+ a.mu.Unlock()+ if l == nil {+ return errors.New("this sign-in is no longer pending")+ }+ if !strings.HasPrefix(redirectURL, "http://") && !strings.HasPrefix(redirectURL, "https://") {+ return errors.New("paste the full address from the browser's address bar")+ }+ // The proxy infers the provider from the pending state in the URL.+ ctx, cancel := context.WithTimeout(a.ctx, 20*time.Second)+ defer cancel()+ return a.Proxy.Mgmt().SubmitCallback(ctx, "", redirectURL)+}++func (a *App) RemoveAccount(name string) error {+ ctx, cancel := context.WithTimeout(a.ctx, 15*time.Second)+ defer cancel()+ if err := a.Proxy.Mgmt().DeleteCredential(ctx, name); err != nil {+ return err+ }+ a.refreshAccounts()+ return nil+}++func (a *App) SetAccountDisabled(name string, disabled bool) error {+ ctx, cancel := context.WithTimeout(a.ctx, 15*time.Second)+ defer cancel()+ if err := a.Proxy.Mgmt().SetCredentialDisabled(ctx, name, disabled); err != nil {+ return err+ }+ a.refreshAccounts()+ if !disabled {+ go a.RefreshQuotas(name)+ }+ return nil+}++// RotateKey issues a new client API key and restarts the proxy with it.+func (a *App) RotateKey() error {+ s, err := a.Store.Update(func(s *settings.Settings) { s.APIKey = settings.NewAPIKey() })+ if err != nil {+ return err+ }+ port := a.Proxy.Port()+ if port == 0 {+ port = s.Port+ }+ return a.restartOn(s, port, false)+}++// proxyOptions builds the proxy configuration from the settings. The internal+// key goes last: the management client uses it.+func (a *App) proxyOptions(s settings.Settings, local []core.LocalUpstream) core.Options {+ return a.proxyOptionsOn(s, local, s.Port, false)+}++func (a *App) proxyOptionsOn(s settings.Settings, local []core.LocalUpstream, port int, strict bool) core.Options {+ host := "127.0.0.1"+ if s.Network {+ host = "0.0.0.0"+ }+ return core.Options{+ PreferredPort: port,+ StrictPort: strict,+ Host: host,+ APIKeys: []string{s.APIKey, a.internalKey},+ Routes: a.routes,+ Local: local,+ Middleware: []gin.HandlerFunc{noCORS, a.access},+ }+}++// SetNetwork turns access from other devices on or off (0.0.0.0 with the API+// key, or 127.0.0.1 only) and restarts the proxy on the same port, so open+// panels and configured apps keep working.+func (a *App) SetNetwork(on bool) error {+ s, err := a.Store.Update(func(s *settings.Settings) { s.Network = on })+ if err != nil {+ return err+ }+ port := a.Proxy.Port()+ if port == 0 {+ port = s.Port+ }+ if err := a.restartOn(s, port, true); err != nil {+ if on {+ // Could not listen on the network on this port: back to this computer only.+ s, _ = a.Store.Update(func(s *settings.Settings) { s.Network = false })+ _ = a.restartOn(s, port, false)+ a.setNotice(fmt.Sprintf(i18n.T("network_failed"), port))+ }+ return err+ }+ return nil+}++// SetPort changes the preferred port and restarts the proxy.+func (a *App) SetPort(port int) error {+ if port < 1024 || port > 65535 {+ return errors.New("choose a port between 1024 and 65535")+ }+ s, err := a.Store.Update(func(s *settings.Settings) { s.Port = port })+ if err != nil {+ return err+ }+ return a.restartProxy(s)+}++func (a *App) restartProxy(s settings.Settings) error {+ return a.restartOn(s, s.Port, false)+}++// restartOn restarts the proxy, preferring port (strict: only that port).+func (a *App) restartOn(s settings.Settings, port int, strict bool) error {+ local := a.Proxy.Local()+ before := a.Proxy.Port()+ panelOpen := a.listeners() > 0+ a.Proxy.Stop()+ err := a.Proxy.Start(a.proxyOptionsOn(s, local, port, strict))+ a.mu.Lock()+ a.notice = ""+ a.mu.Unlock()+ p := a.Proxy.Port()+ if err == nil && p != s.Port {+ a.setNotice(fmt.Sprintf(i18n.T("port_moved"), s.Port, p))+ }+ if err == nil {+ if a.OnProxyStart != nil {+ a.OnProxyStart(p)+ }+ // An open panel was served from the old port; open it on the new one.+ if before != 0 && p != before && a.OpenPanel != nil && panelOpen {+ go a.OpenPanel("")+ }+ }+ go a.refreshAccounts()+ a.changed()+ return err+}++// listeners counts open panels (event streams).+func (a *App) listeners() int {+ a.subsMu.Lock()+ defer a.subsMu.Unlock()+ return len(a.subs)+}++func (a *App) SetAutostart(on bool) error {+ if err := osutil.SetAutostart(on); err != nil {+ return err+ }+ _, err := a.Store.Update(func(s *settings.Settings) { s.Autostart = on })+ a.changed()+ return err+}++func (a *App) SetLanguage(l string) {+ _, _ = a.Store.Update(func(s *settings.Settings) { s.Language = l })+ i18n.Set(l)+ a.changed()+}diff --git a/webbrain-systray/internal/app/demo.go b/webbrain-systray/internal/app/demo.gonew file mode 100644index 000000000..9c73ba5cd--- /dev/null+++ b/webbrain-systray/internal/app/demo.go@@ -0,0 +1,102 @@+package app++import (+ "os"+ "time"++ "github.com/esokullu/webbrain-systray/internal/accounts"+ "github.com/esokullu/webbrain-systray/internal/d1"+ "github.com/esokullu/webbrain-systray/internal/download"+ "github.com/esokullu/webbrain-systray/internal/localmodel"+ "github.com/esokullu/webbrain-systray/internal/quota"+ "github.com/esokullu/webbrain-systray/internal/settings"+ "github.com/esokullu/webbrain-systray/internal/sysinfo"+)++// Demo data for screenshots and UI work: WBC_DEMO=1 (everything connected),+// WBC_DEMO=download (local model downloading) or WBC_DEMO=empty (first run).+func demoMode() bool { return os.Getenv("WBC_DEMO") != "" }++func pct(v float64) *float64 { return &v }++func at(d time.Duration) *time.Time {+ t := time.Now().Add(d).Truncate(time.Minute)+ return &t+}++func applyDemo(s *Snapshot) {+ mode := os.Getenv("WBC_DEMO")+ s.Notice = ""+ if mode == "empty" {+ s.Accounts = []accounts.Account{}+ s.Models = nil+ s.Welcomed = false+ return+ }+ s.Welcomed = true+ now := time.Now()+ mk := func(provider, email, plan string, rows []quota.Row) accounts.Account {+ p := accounts.ProviderFor(provider)+ return accounts.Account{Name: provider + "-" + email + ".json", Provider: provider, ProviderName: p.Name, Initials: p.Initials, Hue: p.Hue,+ Email: email, QuotaKnown: true, Quota: quota.State{Status: "ok", Plan: plan, Rows: rows, FetchedAt: now.Add(-2 * time.Minute)}}+ }+ s.Accounts = []accounts.Account{+ mk("claude", "[email protected]", "Max", []quota.Row{+ {Window: "5h", Label: "5h", Remaining: pct(64), ResetAt: at(2*time.Hour + 14*time.Minute)},+ {Window: "week", Label: "Week", Remaining: pct(83), ResetAt: at(58 * time.Hour)},+ {Window: "week", Scope: "Opus", Label: "Week · Opus", Remaining: pct(41), ResetAt: at(58 * time.Hour)},+ }),+ mk("codex", "[email protected]", "Pro", []quota.Row{+ {Window: "5h", Label: "5h", Remaining: pct(92), ResetAt: at(4*time.Hour + 40*time.Minute)},+ {Window: "week", Label: "Week", Remaining: pct(57), ResetAt: at(97 * time.Hour)},+ }),+ mk("antigravity", "[email protected]", "AI Pro", []quota.Row{+ {Window: "5h", Label: "5h", Remaining: pct(100), ResetAt: at(5 * time.Hour)},+ {Window: "week", Label: "Week", Remaining: pct(71), ResetAt: at(130 * time.Hour)},+ }),+ mk("xai", "[email protected]", "SuperGrok", []quota.Row{+ {Window: "week", Label: "Week", Remaining: pct(12), ResetAt: at(75 * time.Hour)},+ }),+ }+ s.Models = []string{"bonsai-2-27b", "claude-haiku-5-5", "claude-opus-5-5", "claude-sonnet-5-5", "gemini-3.8-flash", "gemini-4-argon",+ "gpt-6-astra", "gpt-6-luna", "gpt-6.1-sol", "grok-4.7", "grok-4.7-build-fast"}++ info := sysinfo.Info{OS: "darwin", Arch: "arm64", CPU: "Apple M4 Max", Cores: 16, MemoryBytes: 64 << 30, AvailableBytes: 41 << 30, AppleSilicon: true,+ GPU: &sysinfo.GPU{Vendor: "apple", Name: "Apple M4 Max GPU", MemoryBytes: 48 << 30}}+ plan := localmodel.MakePlan(info, localSettingsAuto(), "gguf")+ started := now.Add(-37 * time.Minute)+ s.Local.System = info+ s.Local.SystemSummary = info.Summary()+ s.Local.Formats = []string{"gguf", "mlx"}+ s.Local.Format = "gguf"+ s.Local.Plan = plan+ s.Local.VisionMode = "auto"+ s.Local.AutoStart = true+ s.Local.Installed = map[string]bool{"gguf": true, "mlx": false}+ s.Local.DiskBytes = 6575895904+ s.Local.Phase = localmodel.PhaseRunning+ s.Local.Port = 18081+ s.Local.StartedAt = &started+ s.Local.Error = ""+ if mode == "download" {+ s.Local.Installed["gguf"] = false+ s.Local.Phase = localmodel.PhaseDownloading+ s.Local.Step = "Bonsai 2 27B weights (PTQ1_0)"+ s.Local.Progress = &download.Progress{Done: 2_812_000_000, Total: 6_587_469_701, BytesPerSec: 48_600_000}+ s.Local.DownloadBytes = 6_587_469_701+ s.Local.DiskBytes = 0+ s.Local.StartedAt = nil+ }+ s.Decision.Supported = true+ s.Decision.Installed = true+ s.Decision.Enabled = true+ s.Decision.Phase = d1.PhaseReady+ s.Decision.Runtime = "ONNX Runtime 1.31.0 on the CPU"+ s.Decision.Requests = 214+ s.Decision.LastLatencyMs = 182+ s.Decision.DiskBytes = 1904015195+ s.Decision.Error = ""+ s.Autostart = true+}++func localSettingsAuto() settings.Local { return settings.Local{Vision: "auto"} }diff --git a/webbrain-systray/internal/app/guards_test.go b/webbrain-systray/internal/app/guards_test.gonew file mode 100644index 000000000..8b8ecc4c4--- /dev/null+++ b/webbrain-systray/internal/app/guards_test.go@@ -0,0 +1,123 @@+package app++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"++ "github.com/esokullu/webbrain-systray/internal/settings"+)++func TestLocalHost(t *testing.T) {+ ok := []string{"127.0.0.1:8327", "localhost:8327", "[::1]:8327", "127.0.0.1", "localhost", "app.localhost:8327"}+ bad := []string{"evil.example:8327", "127.0.0.1.evil.example", "localhost.evil.example:8327", "192.168.1.5:8327", ""}+ for _, h := range ok {+ if !localHost(h) {+ t.Errorf("%q rejected", h)+ }+ }+ for _, h := range bad {+ if localHost(h) {+ t.Errorf("%q accepted", h)+ }+ }+}++func TestLocalClientAllowed(t *testing.T) {+ cases := []struct {+ origin, site string+ want bool+ }{+ {"", "", true}, // curl, SDKs, native apps+ {"chrome-extension://abcdefgh", "none", true}, // WebBrain+ {"chrome-extension://abcdefgh", "cross-site", true},+ {"moz-extension://1234", "cross-site", true},+ {"http://127.0.0.1:8327", "same-origin", true}, // the panel+ {"http://127.0.0.1", "same-origin", true}, // Origin rewritten by an extension, port dropped+ {"http://localhost:5173", "same-site", true}, // a local web app+ {"http://127.0.0.1", "cross-site", false}, // a web page whose Origin an extension rewrote+ {"https://evil.example", "cross-site", false},+ {"https://evil.example", "", false},+ {"null", "", false}, // sandboxed frames+ {"", "cross-site", false}, // cross-site request without Origin+ }+ for _, c := range cases {+ r := httptest.NewRequest("POST", "http://127.0.0.1:8327/v1/chat/completions", nil)+ if c.origin != "" {+ r.Header.Set("Origin", c.origin)+ }+ if c.site != "" {+ r.Header.Set("Sec-Fetch-Site", c.site)+ }+ if got := localClientAllowed(r); got != c.want {+ t.Errorf("Origin %q Sec-Fetch-Site %q: allowed=%v, want %v", c.origin, c.site, got, c.want)+ }+ }+}++func TestAccessMiddleware(t *testing.T) {+ gin.SetMode(gin.TestMode)+ t.Setenv("WBC_HOME", t.TempDir())+ store, err := settings.Open()+ if err != nil {+ t.Fatal(err)+ }+ a := &App{Store: store, internalKey: "internal"}+ e := gin.New()+ e.Use(a.access)+ e.GET("/v1/models", func(c *gin.Context) { c.String(http.StatusOK, c.GetHeader("Authorization")) })+ e.GET("/anthropic/callback", func(c *gin.Context) { c.String(http.StatusOK, "callback") })++ type req struct {+ name string+ remote, host, origin, site string+ auth string+ network bool+ path string+ wantStatus int+ wantAuth string+ }+ cases := []req{+ {name: "native app, no key", remote: "127.0.0.1:50000", host: "127.0.0.1:8327", wantStatus: 200, wantAuth: "Bearer internal"},+ {name: "native app, any key", remote: "127.0.0.1:50000", host: "127.0.0.1:8327", auth: "Bearer anything", wantStatus: 200, wantAuth: "Bearer internal"},+ {name: "extension", remote: "127.0.0.1:50000", host: "127.0.0.1:8327", origin: "chrome-extension://abc", site: "none", wantStatus: 200, wantAuth: "Bearer internal"},+ {name: "web page", remote: "127.0.0.1:50000", host: "127.0.0.1:8327", origin: "https://evil.example", site: "cross-site", wantStatus: 403},+ {name: "web page with rewritten origin", remote: "127.0.0.1:50000", host: "127.0.0.1:8327", origin: "http://127.0.0.1", site: "cross-site", wantStatus: 403},+ {name: "web page with the key", remote: "127.0.0.1:50000", host: "127.0.0.1:8327", origin: "https://tool.example", site: "cross-site", auth: "Bearer wb-user", wantStatus: 200, wantAuth: "Bearer wb-user"},+ {name: "dns rebinding", remote: "127.0.0.1:50000", host: "evil.example:8327", wantStatus: 403},+ {name: "other device, network off", remote: "192.168.1.20:50000", host: "192.168.1.57:8327", auth: "Bearer wb-user", wantStatus: 403},+ {name: "other device, network on", remote: "192.168.1.20:50000", host: "192.168.1.57:8327", auth: "Bearer wb-user", network: true, wantStatus: 200, wantAuth: "Bearer wb-user"},+ {name: "oauth callback untouched", remote: "127.0.0.1:50000", host: "localhost:8327", origin: "https://claude.ai", site: "cross-site", path: "/anthropic/callback", wantStatus: 200},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ _, _ = store.Update(func(s *settings.Settings) { s.Network = c.network })+ path := c.path+ if path == "" {+ path = "/v1/models"+ }+ r := httptest.NewRequest("GET", "http://"+c.host+path, nil)+ r.RemoteAddr = c.remote+ r.Host = c.host+ if c.origin != "" {+ r.Header.Set("Origin", c.origin)+ }+ if c.site != "" {+ r.Header.Set("Sec-Fetch-Site", c.site)+ }+ if c.auth != "" {+ r.Header.Set("Authorization", c.auth)+ }+ w := httptest.NewRecorder()+ e.ServeHTTP(w, r)+ if w.Code != c.wantStatus {+ t.Fatalf("status %d, want %d (%s)", w.Code, c.wantStatus, w.Body.String())+ }+ if c.wantAuth != "" && w.Body.String() != c.wantAuth {+ t.Fatalf("upstream saw Authorization %q, want %q", w.Body.String(), c.wantAuth)+ }+ })+ }+}diff --git a/webbrain-systray/internal/app/menu.go b/webbrain-systray/internal/app/menu.gonew file mode 100644index 000000000..d73ed49e6--- /dev/null+++ b/webbrain-systray/internal/app/menu.go@@ -0,0 +1,170 @@+package app++import (+ "fmt"+ "math"+ "runtime"+ "strings"+ "time"++ "github.com/esokullu/webbrain-systray/internal/accounts"+ "github.com/esokullu/webbrain-systray/internal/i18n"+ "github.com/esokullu/webbrain-systray/internal/osutil"+ "github.com/esokullu/webbrain-systray/internal/quota"+ "github.com/esokullu/webbrain-systray/internal/tray"+)++// MenuActions are the UI hooks the menu needs from main. OpenPanel takes the+// panel view to show ("" for the main page, "add", "account:<name>").+type MenuActions struct {+ OpenPanel func(view string)+ Quit func()+}++func bar(pct float64) string {+ full, empty := "■", "□"+ if runtime.GOOS == "darwin" {+ full, empty = "▰", "▱"+ }+ n := int(math.Round(pct / 10))+ n = max(0, min(10, n))+ return strings.Repeat(full, n) + strings.Repeat(empty, 10-n)+}++// Until formats a reset time compactly: 45m, 2h 05m, 3d (45 dk, 2 sa 05 dk, 3 gün).+func Until(t *time.Time) string {+ if t == nil {+ return ""+ }+ d := time.Until(*t)+ if d <= 0 {+ return ""+ }+ h := int(d.Hours())+ m := int(d.Minutes()) % 60+ switch {+ case h >= 48:+ return fmt.Sprintf(i18n.T("dur_days"), h/24)+ case h > 0:+ return fmt.Sprintf(i18n.T("dur_hours"), h, m)+ default:+ return fmt.Sprintf(i18n.T("dur_minutes"), max(1, m))+ }+}++// percent writes 64% (English) or %64 (Turkish).+func percent(v float64) string {+ n := fmt.Sprintf("%.0f", v)+ if i18n.Lang() == "tr" {+ return "%" + n+ }+ return n + "%"+}++// Tightest picks the usage window with the least left. Windows that cover the+// whole plan come first; scoped ones (one model, code review, extra usage)+// count only when a plan reports nothing else, as Google's per-model quotas do.+// The panel applies the same rule.+func Tightest(rows []quota.Row) *quota.Row {+ for _, scoped := range []bool{false, true} {+ var best *quota.Row+ for i := range rows {+ r := &rows[i]+ if r.Remaining == nil || (r.Scope != "") != scoped {+ continue+ }+ if best == nil || *r.Remaining < *best.Remaining {+ best = r+ }+ }+ if best != nil {+ return best+ }+ }+ return nil+}++// sharedNames lists the provider names more than one login uses. Their lines+// carry the login's email, or two rows would read the same.+func sharedNames(accs []accounts.Account) map[string]bool {+ count := map[string]int{}+ for _, a := range accs {+ count[a.ProviderName]+++ }+ shared := map[string]bool{}+ for name, n := range count {+ if n > 1 {+ shared[name] = true+ }+ }+ return shared+}++// planLine is one subscription in the tray menu: its name and plan, then the+// window closest to running out. showWho adds the login's email.+func planLine(acc accounts.Account, showWho bool) string {+ name := acc.ProviderName+ if acc.Quota.Plan != "" {+ name += " " + acc.Quota.Plan+ }+ if showWho {+ name += " (" + acc.Who() + ")"+ }+ q := acc.Quota+ note := ""+ switch {+ case acc.Disabled:+ note = i18n.T("paused")+ case q.Status == "loading":+ note = i18n.T("quota_loading")+ case q.Status == "error":+ note = i18n.T("quota_error")+ case q.Status != "ok":+ note = i18n.T("quota_none")+ }+ if note != "" {+ return name + " — " + note+ }+ r := Tightest(q.Rows)+ if r == nil {+ if len(q.Rows) > 0 && q.Rows[0].Detail != "" {+ return name + " — " + q.Rows[0].Detail+ }+ return name + " — " + i18n.T("quota_none")+ }+ line := fmt.Sprintf("%s %s %s", name, bar(*r.Remaining), percent(*r.Remaining))+ if u := Until(r.ResetAt); u != "" {+ line += " · " + u+ }+ return line+}++// Menu renders the tray menu: status, the address, one line per subscription,+// then the panel and Quit. Everything else lives in the panel.+func (a *App) Menu(act MenuActions) []tray.Item {+ s := a.Snapshot()+ status := i18n.T("stopped")+ if s.Running {+ status = i18n.T("running")+ }+ items := []tray.Item{{Title: "WebBrain Companion — " + status, Disabled: true, Secondary: true}}+ if s.Running {+ url := s.BaseURL + "/v1"+ items = append(items, tray.Item{Title: i18n.T("copy") + " " + url, Tooltip: i18n.T("copy_hint"), OnClick: func() { _ = osutil.Copy(url) }})+ }+ items = append(items, tray.Item{Separator: true})++ shared := sharedNames(s.Accounts)+ for _, acc := range s.Accounts {+ view := "account:" + acc.Name+ items = append(items, tray.Item{Title: planLine(acc, shared[acc.ProviderName]), Secondary: acc.Disabled, OnClick: func() { act.OpenPanel(view) }})+ }+ if len(s.Accounts) == 0 {+ items = append(items, tray.Item{Title: i18n.T("add"), OnClick: func() { act.OpenPanel("add") }})+ }+ return append(items,+ tray.Item{Separator: true},+ tray.Item{Title: i18n.T("open_panel"), OnClick: func() { act.OpenPanel("") }},+ tray.Item{Title: i18n.T("quit"), OnClick: act.Quit},+ )+}diff --git a/webbrain-systray/internal/app/menu_test.go b/webbrain-systray/internal/app/menu_test.gonew file mode 100644index 000000000..a3606a040--- /dev/null+++ b/webbrain-systray/internal/app/menu_test.go@@ -0,0 +1,79 @@+package app++import (+ "strings"+ "testing"+ "time"++ "github.com/esokullu/webbrain-systray/internal/accounts"+ "github.com/esokullu/webbrain-systray/internal/i18n"+ "github.com/esokullu/webbrain-systray/internal/quota"+)++func TestTightest(t *testing.T) {+ claude := []quota.Row{+ {Window: "5h", Remaining: pct(64)},+ {Window: "week", Remaining: pct(83)},+ {Window: "week", Scope: "Opus", Remaining: pct(41)},+ {Window: "month", Scope: "Extra", Remaining: pct(5)},+ }+ if r := Tightest(claude); r == nil || *r.Remaining != 64 {+ t.Fatalf("plan-wide windows come first, got %+v", r)+ }+ google := []quota.Row{+ {Window: "5h", Scope: "Gemini Pro", Remaining: pct(90)},+ {Window: "5h", Scope: "Claude", Remaining: pct(20)},+ }+ if r := Tightest(google); r == nil || r.Scope != "Claude" {+ t.Fatalf("scoped windows count when nothing else is reported, got %+v", r)+ }+ if r := Tightest([]quota.Row{{Window: "custom", Scope: "Credits", Detail: "$4"}}); r != nil {+ t.Fatalf("rows without a percentage are skipped, got %+v", r)+ }+}++func TestPlanLine(t *testing.T) {+ i18n.Set("en")+ acc := accounts.Account{ProviderName: "Claude", Quota: quota.State{Status: "ok", Plan: "Max", Rows: []quota.Row{+ {Window: "5h", Remaining: pct(64), ResetAt: at(2*time.Hour + 14*time.Minute + 30*time.Second)},+ {Window: "week", Remaining: pct(83)},+ }}}+ line := planLine(acc, false)+ if !strings.HasPrefix(line, "Claude Max ") || !strings.Contains(line, "64%") || !strings.Contains(line, " · 2h 1") {+ t.Fatalf("unexpected line %q", line)+ }+ acc.Disabled = true+ if got := planLine(acc, false); got != "Claude Max — paused" {+ t.Fatalf("paused line %q", got)+ }+ acc.Disabled = false+ acc.Quota = quota.State{Status: "unsupported"}+ if got := planLine(acc, false); got != "Claude — usage not reported" {+ t.Fatalf("unsupported line %q", got)+ }+}++// Two logins of one provider must not produce identical tray lines.+func TestPlanLineSharedProvider(t *testing.T) {+ i18n.Set("en")+ ok := quota.State{Status: "ok", Plan: "Max", Rows: []quota.Row{{Window: "5h", Remaining: pct(64)}}}+ accs := []accounts.Account{+ {Name: "[email protected]", Provider: "claude", ProviderName: "Claude", Email: "[email protected]", Quota: ok},+ {Name: "anthropic-work.json", Provider: "anthropic", ProviderName: "Claude", Quota: ok},+ {Name: "[email protected]", Provider: "codex", ProviderName: "ChatGPT", Email: "[email protected]", Quota: ok},+ }+ shared := sharedNames(accs)+ if !shared["Claude"] || shared["ChatGPT"] {+ t.Fatalf("shared names %v", shared)+ }+ first, second := planLine(accs[0], shared["Claude"]), planLine(accs[1], shared["Claude"])+ if !strings.HasPrefix(first, "Claude Max ([email protected]) ") {+ t.Fatalf("first login %q", first)+ }+ if !strings.HasPrefix(second, "Claude Max (anthropic-work) ") {+ t.Fatalf("a login without an email falls back to its file name, got %q", second)+ }+ if got := planLine(accs[2], shared["ChatGPT"]); strings.Contains(got, "@") {+ t.Fatalf("a provider with one login keeps the short line, got %q", got)+ }+}diff --git a/webbrain-systray/internal/app/routes.go b/webbrain-systray/internal/app/routes.gonew file mode 100644index 000000000..ffc724aa7--- /dev/null+++ b/webbrain-systray/internal/app/routes.go@@ -0,0 +1,549 @@+package app++import (+ "context"+ "crypto/subtle"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/gin-gonic/gin"++ "github.com/esokullu/webbrain-systray/internal/d1"+ "github.com/esokullu/webbrain-systray/internal/localmodel"+ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/osutil"+ "github.com/esokullu/webbrain-systray/internal/panel"+ "github.com/esokullu/webbrain-systray/internal/settings"+)++// noCORS keeps the proxy's permissive CORS headers off the companion's own+// routes: web pages must not read the panel, the discovery document (it+// carries the API key) or the decision API. Browser extensions with host+// permissions do not need CORS.+func noCORS(c *gin.Context) {+ if !strings.HasPrefix(c.Request.URL.Path, "/companion") {+ c.Next()+ return+ }+ if c.Request.Method == http.MethodOptions {+ c.AbortWithStatus(http.StatusForbidden)+ return+ }+ c.Writer = &stripCORS{ResponseWriter: c.Writer}+ c.Next()+}++type stripCORS struct {+ gin.ResponseWriter+ done bool+}++func (w *stripCORS) strip() {+ if w.done {+ return+ }+ w.done = true+ h := w.ResponseWriter.Header()+ for k := range h {+ if strings.HasPrefix(strings.ToLower(k), "access-control-") {+ h.Del(k)+ }+ }+}++func (w *stripCORS) WriteHeader(code int) { w.strip(); w.ResponseWriter.WriteHeader(code) }+func (w *stripCORS) WriteHeaderNow() { w.strip(); w.ResponseWriter.WriteHeaderNow() }+func (w *stripCORS) Write(b []byte) (int, error) { w.strip(); return w.ResponseWriter.Write(b) }+func (w *stripCORS) WriteString(s string) (int, error) {+ w.strip()+ return w.ResponseWriter.WriteString(s)+}+func (w *stripCORS) Flush() { w.strip(); w.ResponseWriter.Flush() }++// guardLocal admits only requests from this computer addressed to a loopback+// name (DNS rebinding cannot reach the companion's own routes).+func (a *App) guardLocal(c *gin.Context) {+ if !loopbackAddr(c.Request.RemoteAddr) || !localHost(c.Request.Host) {+ deny(c, msgRebinding)+ return+ }+ c.Next()+}++// guardPanel requires the per-install panel key and a request from a page on+// this computer. The origin's port is not compared: some extensions rewrite+// the Origin of every request to 127.0.0.1 to http://127.0.0.1.+func (a *App) guardPanel(c *gin.Context) {+ r := c.Request+ origin := r.Header.Get("Origin")+ if !loopbackAddr(r.RemoteAddr) || !localHost(r.Host) || crossSite(r) || (origin != "" && !loopbackOrigin(origin)) {+ logx.Printf("panel request refused: host=%q origin=%q site=%q", r.Host, origin, r.Header.Get("Sec-Fetch-Site"))+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})+ return+ }+ token := c.GetHeader("X-Companion-Key")+ if token == "" {+ token = c.Query("key")+ }+ want := a.Store.Get().PanelToken+ if subtle.ConstantTimeCompare([]byte(token), []byte(want)) != 1 {+ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "panel key required"})+ return+ }+ c.Header("Cache-Control", "no-store")+ c.Next()+}++// guardClient protects the decision API like the model endpoints: no key from+// this computer, the API key from web pages and (with network access) other+// devices.+func (a *App) guardClient(c *gin.Context) {+ r := c.Request+ if loopbackAddr(r.RemoteAddr) {+ if !localHost(r.Host) {+ deny(c, msgRebinding)+ return+ }+ if localClientAllowed(r) {+ c.Next()+ return+ }+ } else if !a.Store.Get().Network {+ deny(c, msgNetwork)+ return+ }+ key := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))+ if key == "" {+ key = r.Header.Get("X-Api-Key")+ }+ want := a.Store.Get().APIKey+ if key == "" || subtle.ConstantTimeCompare([]byte(key), []byte(want)) != 1 {+ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid API key"})+ return+ }+ c.Next()+}++func fail(c *gin.Context, status int, err error) {+ c.JSON(status, gin.H{"error": err.Error()})+}++// PanelURL is the address the tray opens (the token rides in the fragment).+// view picks what the panel shows first: "add", "settings", "local",+// "decision" or "account:<name>".+func (a *App) PanelURL(view string) string {+ u := fmt.Sprintf("%s/companion/#k=%s", a.Proxy.BaseURL(), a.Store.Get().PanelToken)+ if view != "" {+ u += "&view=" + url.QueryEscape(view)+ }+ return u+}++func (a *App) routes(e *gin.Engine) {+ assets, _ := fs.Sub(panel.FS, "assets")+ static := http.FileServer(http.FS(assets))++ e.GET("/companion", func(c *gin.Context) { c.Redirect(http.StatusFound, "/companion/") })+ e.GET("/companion/", a.guardLocal, func(c *gin.Context) {+ data, err := fs.ReadFile(assets, "index.html")+ if err != nil {+ c.String(http.StatusInternalServerError, "panel missing")+ return+ }+ c.Header("Cache-Control", "no-store")+ c.Header("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'")+ c.Header("X-Frame-Options", "DENY")+ c.Data(http.StatusOK, "text/html; charset=utf-8", data)+ })+ e.GET("/companion/static/*path", a.guardLocal, func(c *gin.Context) {+ c.Request.URL.Path = c.Param("path")+ c.Header("Cache-Control", "no-cache")+ static.ServeHTTP(c.Writer, c.Request)+ })++ // Discovery for the WebBrain extension (no CORS: web pages cannot read it).+ e.GET("/companion/v1/info", a.guardLocal, func(c *gin.Context) {+ s := a.Snapshot()+ var local []gin.H+ if s.Local.Phase == localmodel.PhaseRunning {+ local = append(local, gin.H{"id": localmodel.ModelID, "name": s.Local.ModelName, "vision": s.Local.Plan.Vision != "off", "context": s.Local.Plan.Context})+ }+ c.JSON(http.StatusOK, gin.H{+ "app": "webbrain-companion",+ "version": a.Version,+ "base_url": s.BaseURL,+ "openai_base_url": s.BaseURL + "/v1",+ // Apps on this computer need no key; other devices do (network access).+ "key_required": false,+ "network": s.Network,+ "models": s.Models,+ "local_models": local,+ "accounts": len(s.Accounts),+ "decision": gin.H{+ "endpoint": s.Decision.Endpoint,+ "ready": s.Decision.Phase == d1.PhaseReady,+ "model": d1.ModelName,+ },+ })+ })++ e.POST("/companion/v1/decide", a.guardClient, func(c *gin.Context) {+ body, err := io.ReadAll(io.LimitReader(c.Request.Body, 12<<20))+ if err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ res, err := a.D1.EvaluateJSON(c.Request.Context(), body)+ if err != nil {+ status := http.StatusBadRequest+ if errors.Is(err, d1.ErrNotReady) {+ status = http.StatusServiceUnavailable+ }+ fail(c, status, err)+ return+ }+ c.JSON(http.StatusOK, res)+ })++ api := e.Group("/companion/api", a.guardPanel)+ api.GET("/state", func(c *gin.Context) { c.JSON(http.StatusOK, a.Snapshot()) })+ api.GET("/events", func(c *gin.Context) {+ ch, done := a.Subscribe()+ defer done()+ c.Header("Content-Type", "text/event-stream")+ c.Header("Cache-Control", "no-store")+ c.Header("X-Accel-Buffering", "no")+ send := func() bool {+ data, _ := json.Marshal(a.Snapshot())+ if _, err := fmt.Fprintf(c.Writer, "event: state\ndata: %s\n\n", data); err != nil {+ return false+ }+ c.Writer.Flush()+ return true+ }+ if !send() {+ return+ }+ ping := time.NewTicker(15 * time.Second)+ defer ping.Stop()+ last := time.Now()+ for {+ select {+ case <-c.Request.Context().Done():+ return+ case <-ch:+ // Coalesce bursts (download progress) to ~4 updates/s.+ if wait := 250*time.Millisecond - time.Since(last); wait > 0 {+ time.Sleep(wait)+ }+ last = time.Now()+ if !send() {+ return+ }+ case <-ping.C:+ if _, err := fmt.Fprint(c.Writer, ": ping\n\n"); err != nil {+ return+ }+ c.Writer.Flush()+ }+ }+ })++ api.POST("/accounts/login", func(c *gin.Context) {+ var req struct {+ Provider string `json:"provider"`+ }+ if err := c.ShouldBindJSON(&req); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ ls, err := a.StartLogin(req.Provider)+ if err != nil {+ fail(c, http.StatusBadGateway, err)+ return+ }+ c.JSON(http.StatusOK, ls)+ })+ api.GET("/accounts/login/:state", func(c *gin.Context) {+ l, ok := a.Login(c.Param("state"))+ if !ok {+ fail(c, http.StatusNotFound, errors.New("unknown sign-in"))+ return+ }+ c.JSON(http.StatusOK, l)+ })+ api.DELETE("/accounts/login/:state", func(c *gin.Context) {+ a.CancelLogin(c.Param("state"))+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/accounts/login/:state/callback", func(c *gin.Context) {+ var req struct {+ RedirectURL string `json:"redirect_url"`+ }+ if err := c.ShouldBindJSON(&req); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ if err := a.SubmitCallback(c.Param("state"), strings.TrimSpace(req.RedirectURL)); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/accounts/:name/disabled", func(c *gin.Context) {+ var req struct {+ Disabled bool `json:"disabled"`+ }+ if err := c.ShouldBindJSON(&req); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ if err := a.SetAccountDisabled(c.Param("name"), req.Disabled); err != nil {+ fail(c, http.StatusBadGateway, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.DELETE("/accounts/:name", func(c *gin.Context) {+ if err := a.RemoveAccount(c.Param("name")); err != nil {+ fail(c, http.StatusBadGateway, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/quotas/refresh", func(c *gin.Context) {+ var req struct {+ Name string `json:"name"`+ }+ _ = c.ShouldBindJSON(&req)+ go func() {+ a.refreshAccounts()+ a.RefreshQuotas(req.Name)+ }()+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })++ api.POST("/local/install", func(c *gin.Context) {+ var req struct {+ Format string `json:"format"`+ }+ _ = c.ShouldBindJSON(&req)+ if err := a.Local.Install(req.Format); err != nil {+ fail(c, http.StatusConflict, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/local/cancel", func(c *gin.Context) { a.Local.Cancel(); c.JSON(http.StatusOK, gin.H{"ok": true}) })+ api.POST("/local/start", func(c *gin.Context) {+ if err := a.Local.Start(); err != nil {+ fail(c, http.StatusConflict, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/local/stop", func(c *gin.Context) {+ go a.Local.Stop()+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/local/remove", func(c *gin.Context) {+ var req struct {+ Format string `json:"format"`+ }+ _ = c.ShouldBindJSON(&req)+ if err := a.Local.Remove(req.Format); err != nil {+ fail(c, http.StatusConflict, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.PATCH("/local", func(c *gin.Context) {+ var req struct {+ Format *string `json:"format"`+ Vision *string `json:"vision"`+ AutoStart *bool `json:"auto_start"`+ Context *int `json:"context"`+ }+ if err := c.ShouldBindJSON(&req); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ restart := false+ _, err := a.Store.Update(func(s *settings.Settings) {+ if req.Format != nil && (*req.Format == "gguf" || *req.Format == "mlx") && *req.Format != s.Local.Format {+ s.Local.Format = *req.Format+ }+ if req.Vision != nil {+ switch *req.Vision {+ case "auto", "gpu", "cpu", "off":+ restart = restart || s.Local.Vision != *req.Vision+ s.Local.Vision = *req.Vision+ }+ }+ if req.AutoStart != nil {+ s.Local.AutoStart = *req.AutoStart+ }+ if req.Context != nil && *req.Context >= 0 && *req.Context <= 262144 {+ restart = restart || s.Local.Context != *req.Context+ s.Local.Context = *req.Context+ }+ })+ if err != nil {+ fail(c, http.StatusInternalServerError, err)+ return+ }+ if restart && a.Local.Running() {+ go func() {+ if err := a.Local.Restart(); err != nil {+ logx.Printf("restart local model: %v", err)+ }+ }()+ }+ a.changed()+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })++ api.POST("/decision/install", func(c *gin.Context) {+ if err := a.D1.Install(); err != nil {+ fail(c, http.StatusConflict, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/decision/cancel", func(c *gin.Context) { a.D1.Cancel(); c.JSON(http.StatusOK, gin.H{"ok": true}) })+ api.POST("/decision/remove", func(c *gin.Context) {+ if err := a.D1.Remove(); err != nil {+ fail(c, http.StatusConflict, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/decision/load", func(c *gin.Context) {+ go func() {+ if err := a.D1.Load(); err != nil {+ logx.Printf("decision load: %v", err)+ }+ }()+ _, _ = a.Store.Update(func(s *settings.Settings) { s.Decision.Enabled = true })+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/decision/unload", func(c *gin.Context) {+ a.D1.Unload()+ _, _ = a.Store.Update(func(s *settings.Settings) { s.Decision.Enabled = false })+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/decision/test", func(c *gin.Context) {+ ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute)+ defer cancel()+ res, err := a.D1.SelfTest(ctx)+ if err != nil {+ fail(c, http.StatusServiceUnavailable, err)+ return+ }+ c.JSON(http.StatusOK, res)+ })++ api.PATCH("/settings", func(c *gin.Context) {+ var req struct {+ Autostart *bool `json:"autostart"`+ Port *int `json:"port"`+ Language *string `json:"language"`+ Welcomed *bool `json:"welcomed"`+ Network *bool `json:"network"`+ }+ if err := c.ShouldBindJSON(&req); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ if req.Autostart != nil {+ if err := a.SetAutostart(*req.Autostart); err != nil {+ fail(c, http.StatusInternalServerError, err)+ return+ }+ }+ if req.Language != nil {+ a.SetLanguage(*req.Language)+ }+ if req.Welcomed != nil {+ _, _ = a.Store.Update(func(s *settings.Settings) { s.Welcomed = *req.Welcomed })+ }+ if req.Network != nil && *req.Network != a.Store.Get().Network {+ on := *req.Network+ // Reply first: the proxy restarts on the new address.+ c.JSON(http.StatusOK, gin.H{"ok": true, "restart": true})+ go func() {+ time.Sleep(300 * time.Millisecond)+ if err := a.SetNetwork(on); err != nil {+ logx.Printf("network access: %v", err)+ }+ }()+ return+ }+ if req.Port != nil && *req.Port != a.Store.Get().Port {+ port := *req.Port+ // Reply first: the panel will reconnect on the new port.+ c.JSON(http.StatusOK, gin.H{"ok": true, "restart": true})+ go func() {+ time.Sleep(300 * time.Millisecond)+ if err := a.SetPort(port); err != nil {+ logx.Printf("change port: %v", err)+ }+ }()+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+ api.POST("/quit", func(c *gin.Context) {+ c.JSON(http.StatusOK, gin.H{"ok": true})+ if a.Quit != nil {+ go func() {+ time.Sleep(200 * time.Millisecond)+ a.Quit()+ }()+ }+ })+ api.POST("/key/rotate", func(c *gin.Context) {+ c.JSON(http.StatusOK, gin.H{"ok": true})+ go func() {+ time.Sleep(300 * time.Millisecond)+ if err := a.RotateKey(); err != nil {+ logx.Printf("rotate key: %v", err)+ }+ }()+ })+ api.POST("/open", func(c *gin.Context) {+ var req struct {+ Target string `json:"target"`+ URL string `json:"url"`+ }+ if err := c.ShouldBindJSON(&req); err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ var err error+ switch req.Target {+ case "logs":+ err = osutil.Reveal(logx.Path())+ case "url":+ if !strings.HasPrefix(req.URL, "https://") {+ err = errors.New("only https links can be opened")+ } else {+ err = osutil.OpenURL(req.URL)+ }+ default:+ err = errors.New("unknown target")+ }+ if err != nil {+ fail(c, http.StatusBadRequest, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+ })+}diff --git a/webbrain-systray/internal/app/snapshot.go b/webbrain-systray/internal/app/snapshot.gonew file mode 100644index 000000000..5ffcd5e5e--- /dev/null+++ b/webbrain-systray/internal/app/snapshot.go@@ -0,0 +1,156 @@+package app++import (+ "fmt"+ "net"+ "runtime"+ "sort"+ "strings"++ "github.com/esokullu/webbrain-systray/internal/accounts"+ "github.com/esokullu/webbrain-systray/internal/d1"+ "github.com/esokullu/webbrain-systray/internal/i18n"+ "github.com/esokullu/webbrain-systray/internal/localmodel"+ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/osutil"+ "github.com/esokullu/webbrain-systray/internal/tray"+)++type Endpoint struct {+ ID string `json:"id"`+ Label string `json:"label"`+ URL string `json:"url"`+ Hint string `json:"hint"`+}++// Snapshot is everything the panel and the tray render.+type Snapshot struct {+ Version string `json:"version"`+ Running bool `json:"running"`+ Port int `json:"port"`+ PreferredPort int `json:"preferred_port"`+ BaseURL string `json:"base_url"`+ APIKey string `json:"api_key"`+ // Network: other devices may connect (with the API key) at NetworkURLs.+ Network bool `json:"network"`+ NetworkURLs []string `json:"network_urls,omitempty"`+ // TrayHidden: macOS reports the menu bar icon as not visible (a full+ // menu bar hides it behind the notch).+ TrayHidden bool `json:"tray_hidden"`+ // Translocated: macOS runs the app from a temporary copy because it was+ // not moved to Applications; start at login would point at that copy.+ Translocated bool `json:"translocated"`+ Endpoints []Endpoint `json:"endpoints"`+ Accounts []accounts.Account `json:"accounts"`+ AccountsError string `json:"accounts_error,omitempty"`+ Providers []accounts.Provider `json:"providers"`+ Logins []login `json:"logins"`+ Models []string `json:"models"`+ Local localmodel.Status `json:"local"`+ Decision d1.Status `json:"decision"`+ Autostart bool `json:"autostart"`+ Language string `json:"language"`+ Notice string `json:"notice,omitempty"`+ LogPath string `json:"log_path"`+ OS string `json:"os"`+ QuotaBusy bool `json:"quota_busy"`+ Welcomed bool `json:"welcomed"`+ LocalContext int `json:"local_context"`+}++func (a *App) Snapshot() Snapshot {+ s := a.Store.Get()+ port := a.Proxy.Port()+ base := a.Proxy.BaseURL()+ snap := Snapshot{+ Version: a.Version,+ Running: a.Proxy.Running(),+ Port: port,+ PreferredPort: s.Port,+ BaseURL: base,+ APIKey: s.APIKey,+ Network: s.Network && a.Proxy.Host() == "0.0.0.0",+ TrayHidden: tray.Hidden(),+ Translocated: osutil.Translocated(),+ Endpoints: []Endpoint{+ {ID: "openai", Label: "OpenAI", URL: base + "/v1", Hint: "/v1/chat/completions · /v1/responses · /v1/models"},+ {ID: "anthropic", Label: "Anthropic", URL: base, Hint: "/v1/messages"},+ {ID: "gemini", Label: "Gemini", URL: base, Hint: "/v1beta/models/{model}:generateContent"},+ },+ Providers: accounts.Catalog,+ Local: a.Local.Status(),+ Decision: a.D1.Status(),+ Autostart: osutil.AutostartEnabled(),+ Language: i18n.Lang(),+ LogPath: logx.Path(),+ OS: runtime.GOOS,+ Welcomed: s.Welcomed,+ LocalContext: s.Local.Context,+ }+ snap.Decision.Endpoint = base + "/companion/v1/decide"+ if snap.Network {+ snap.NetworkURLs = networkURLs(port)+ }+ a.mu.Lock()+ snap.Accounts = accounts.FromCredentials(a.creds, a.quotas)+ snap.AccountsError = a.credsErr+ snap.Models = append([]string(nil), a.models...)+ snap.Notice = a.notice+ snap.QuotaBusy = a.quotaBusy+ for _, l := range a.logins {+ snap.Logins = append(snap.Logins, *l)+ }+ a.mu.Unlock()+ sort.Slice(snap.Logins, func(i, j int) bool { return snap.Logins[i].Started.Before(snap.Logins[j].Started) })+ if snap.Accounts == nil {+ snap.Accounts = []accounts.Account{}+ }+ if demoMode() {+ applyDemo(&snap)+ }+ return snap+}++// networkURLs lists the addresses other devices can use, real network+// interfaces first (virtual ones such as Docker bridges or VPN tunnels last).+func networkURLs(port int) []string {+ ifaces, err := net.Interfaces()+ if err != nil {+ return nil+ }+ virtual := []string{"docker", "br-", "veth", "vmnet", "vboxnet", "virbr", "utun", "tun", "tap", "awdl", "llw", "bridge", "zt", "tailscale", "wg", "vEthernet"}+ var real, other []string+ for _, ifc := range ifaces {+ if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {+ continue+ }+ addrs, _ := ifc.Addrs()+ for _, ad := range addrs {+ ipn, ok := ad.(*net.IPNet)+ if !ok {+ continue+ }+ ip := ipn.IP.To4()+ if ip == nil || ip.IsLinkLocalUnicast() {+ continue+ }+ u := fmt.Sprintf("http://%s:%d/v1", ip, port)+ isVirtual := false+ for _, v := range virtual {+ if strings.HasPrefix(strings.ToLower(ifc.Name), strings.ToLower(v)) {+ isVirtual = true+ }+ }+ if isVirtual || !ip.IsPrivate() {+ other = append(other, u)+ } else {+ real = append(real, u)+ }+ }+ }+ out := append(real, other...)+ if len(out) > 4 {+ out = out[:4]+ }+ return out+}diff --git a/webbrain-systray/internal/core/mgmt.go b/webbrain-systray/internal/core/mgmt.gonew file mode 100644index 000000000..21939ebe1--- /dev/null+++ b/webbrain-systray/internal/core/mgmt.go@@ -0,0 +1,231 @@+package core++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"+)++// Mgmt is a small client for the embedded proxy's v8 management API.+type Mgmt struct {+ base string+ pass string+ apiKey string+ http *http.Client+}++func newMgmt(base, pass, apiKey string) *Mgmt {+ return &Mgmt{base: base, pass: pass, apiKey: apiKey, http: &http.Client{Timeout: 60 * time.Second}}+}++type APIError struct {+ Status int+ Body string+}++func (e *APIError) Error() string {+ msg := strings.TrimSpace(e.Body)+ var parsed struct {+ Error string `json:"error"`+ Message string `json:"message"`+ }+ if json.Unmarshal([]byte(msg), &parsed) == nil {+ if parsed.Error != "" {+ msg = parsed.Error+ } else if parsed.Message != "" {+ msg = parsed.Message+ }+ }+ if len(msg) > 300 {+ msg = msg[:300] + "…"+ }+ return fmt.Sprintf("management API %d: %s", e.Status, msg)+}++func (m *Mgmt) do(ctx context.Context, method, path string, body any, out any) error {+ var rd io.Reader+ if body != nil {+ b, err := json.Marshal(body)+ if err != nil {+ return err+ }+ rd = bytes.NewReader(b)+ }+ req, err := http.NewRequestWithContext(ctx, method, m.base+path, rd)+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+m.pass)+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ resp, err := m.http.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ data, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))+ if err != nil {+ return err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return &APIError{Status: resp.StatusCode, Body: string(data)}+ }+ if out != nil && len(data) > 0 {+ return json.Unmarshal(data, out)+ }+ return nil+}++// Credential is one entry of GET /v8/management/credentials. Raw keeps every+// field for provider-specific lookups (id_token claims, project ids, ...).+type Credential struct {+ Raw map[string]any+}++func (c Credential) Str(keys ...string) string {+ for _, k := range keys {+ if v, ok := c.Raw[k]; ok {+ switch t := v.(type) {+ case string:+ if s := strings.TrimSpace(t); s != "" {+ return s+ }+ case float64:+ return fmt.Sprintf("%v", t)+ }+ }+ }+ return ""+}++func (c Credential) Bool(key string) bool {+ v, _ := c.Raw[key].(bool)+ return v+}++func (c Credential) Map(key string) map[string]any {+ v, _ := c.Raw[key].(map[string]any)+ return v+}++func (c Credential) Name() string { return c.Str("name", "id") }+func (c Credential) AuthIndex() string { return c.Str("auth_index", "authIndex") }+func (c Credential) Provider() string {+ return strings.ToLower(c.Str("provider", "type", "account_type"))+}++func (m *Mgmt) Credentials(ctx context.Context) ([]Credential, error) {+ var out struct {+ Files []map[string]any `json:"files"`+ }+ if err := m.do(ctx, http.MethodGet, "/v8/management/credentials", nil, &out); err != nil {+ return nil, err+ }+ creds := make([]Credential, 0, len(out.Files))+ for _, f := range out.Files {+ creds = append(creds, Credential{Raw: f})+ }+ return creds, nil+}++// LoginStart is the reply to starting an OAuth or device login.+type LoginStart struct {+ Status string `json:"status"`+ URL string `json:"url"`+ State string `json:"state"`+ Flow string `json:"flow,omitempty"`+ UserCode string `json:"user_code,omitempty"`+ ExpiresIn int `json:"expires_in,omitempty"`+}++func (m *Mgmt) StartLogin(ctx context.Context, provider string) (LoginStart, error) {+ var out LoginStart+ q := url.Values{"provider": {provider}, "is_webui": {"true"}}+ err := m.do(ctx, http.MethodGet, "/v8/management/oauth/auth-url?"+q.Encode(), nil, &out)+ return out, err+}++// LoginStatus returns "wait", "ok" or "error" (with a message).+func (m *Mgmt) LoginStatus(ctx context.Context, state string) (string, string, error) {+ var out struct {+ Status string `json:"status"`+ Error string `json:"error"`+ }+ err := m.do(ctx, http.MethodGet, "/v8/management/oauth/status?state="+url.QueryEscape(state), nil, &out)+ return out.Status, out.Error, err+}++func (m *Mgmt) CancelLogin(ctx context.Context, state string) error {+ return m.do(ctx, http.MethodDelete, "/v8/management/oauth/session?state="+url.QueryEscape(state), nil, nil)+}++// SubmitCallback hands a pasted redirect URL to a pending login, for when the+// browser could not reach the local callback port.+func (m *Mgmt) SubmitCallback(ctx context.Context, provider, redirectURL string) error {+ body := map[string]string{"redirect_url": redirectURL}+ if provider != "" {+ body["provider"] = provider+ }+ return m.do(ctx, http.MethodPost, "/v8/management/oauth/callback", body, nil)+}++func (m *Mgmt) DeleteCredential(ctx context.Context, name string) error {+ return m.do(ctx, http.MethodDelete, "/v8/management/credentials?name="+url.QueryEscape(name), nil, nil)+}++func (m *Mgmt) SetCredentialDisabled(ctx context.Context, name string, disabled bool) error {+ return m.do(ctx, http.MethodPatch, "/v8/management/credentials/status", map[string]any{"name": name, "disabled": disabled}, nil)+}++// APICallResult is the upstream response relayed by /requests/api-call.+type APICallResult struct {+ StatusCode int `json:"status_code"`+ Header map[string][]string `json:"header"`+ Body string `json:"body"`+}++// APICall performs an upstream request with a stored credential; "$TOKEN$" in+// headers or body is replaced with the credential's (refreshed) access token.+func (m *Mgmt) APICall(ctx context.Context, authIndex, method, rawURL string, header map[string]string, data string) (APICallResult, error) {+ var out APICallResult+ body := map[string]any{"auth_index": authIndex, "method": method, "url": rawURL, "header": header}+ if data != "" {+ body["data"] = data+ }+ err := m.do(ctx, http.MethodPost, "/v8/management/requests/api-call", body, &out)+ return out, err+}++// Models lists the model ids the proxy currently serves to clients.+func (m *Mgmt) Models(ctx context.Context) ([]string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.base+"/v1/models", nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+m.apiKey)+ resp, err := m.http.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ var out struct {+ Data []struct {+ ID string `json:"id"`+ } `json:"data"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {+ return nil, err+ }+ ids := make([]string, 0, len(out.Data))+ for _, d := range out.Data {+ ids = append(ids, d.ID)+ }+ return ids, nil+}diff --git a/webbrain-systray/internal/core/proxy.go b/webbrain-systray/internal/core/proxy.gonew file mode 100644index 000000000..309f5e6c2--- /dev/null+++ b/webbrain-systray/internal/core/proxy.go@@ -0,0 +1,378 @@+// Package core runs the embedded CLIProxyAPI service that turns the user's+// AI subscriptions into OpenAI / Anthropic / Gemini compatible endpoints on+// 127.0.0.1, and talks to its management API on the user's behalf.+package core++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net"+ "net/http"+ "os"+ "strings"+ "sync"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/router-for-me/CLIProxyAPI/v8/sdk/api"+ "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers"+ "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy"+ sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config"++ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/paths"+ "github.com/esokullu/webbrain-systray/internal/settings"+)++// LocalModel describes one model served by a local OpenAI-compatible server+// (llama-server or mlx_vlm.server) that the proxy should route to.+type LocalModel struct {+ Upstream string // model id the local server expects+ Alias string // id clients use through the proxy+ DisplayName string+ Vision bool+ ContextLength int+}++// LocalUpstream is a local inference server registered as an+// OpenAI-compatible upstream.+type LocalUpstream struct {+ Name string+ BaseURL string // e.g. http://127.0.0.1:18081/v1+ Models []LocalModel+}++// Options configure one run of the proxy.+type Options struct {+ PreferredPort int+ // Host is the listen address: 127.0.0.1 (this computer only, the default)+ // or 0.0.0.0 (other devices on the network too).+ Host string+ // StrictPort fails instead of moving to the next free port.+ StrictPort bool+ // APIKeys the proxy accepts. The companion's own middleware lets requests+ // from this computer through with an internal key; other devices need the+ // user's key.+ APIKeys []string+ // Routes installs the companion's own HTTP routes on the proxy's engine.+ Routes func(*gin.Engine)+ // Middleware runs before the proxy's own (CORS) middleware.+ Middleware []gin.HandlerFunc+ // Local upstreams to register (local Bonsai server while it runs).+ Local []LocalUpstream+}++type Proxy struct {+ mu sync.Mutex+ opts Options+ port int+ mgmtPass string+ cancel context.CancelFunc+ done chan struct{}+ runErr error+ mgmt *Mgmt+ secret string+}++func New() *Proxy { return &Proxy{} }++// Port is the port the proxy is listening on (0 when stopped).+func (p *Proxy) Port() int {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.port+}++func (p *Proxy) BaseURL() string { return fmt.Sprintf("http://127.0.0.1:%d", p.Port()) }++// Mgmt returns the management client of the running service.+func (p *Proxy) Mgmt() *Mgmt {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.mgmt+}++// Running reports whether the service goroutine is alive.+func (p *Proxy) Running() bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ if p.done == nil {+ return false+ }+ select {+ case <-p.done:+ return false+ default:+ return true+ }+}++// LastError returns the error the service last exited with, if any.+func (p *Proxy) LastError() error {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.runErr+}++// ErrPortBusy is returned when no port near the preferred one is free.+var ErrPortBusy = errors.New("no free port near the preferred one")++// portFree reports whether nothing serves port on this computer and host:port+// can be bound. Binding alone is not enough: macOS lets 127.0.0.1:8317 be+// bound while another app (CLIProxyAPI's own default is 8317) listens on+// *:8317, and then connections land on either server.+func portFree(host string, port int) bool {+ for _, loop := range []string{"127.0.0.1", "::1"} {+ if c, err := net.DialTimeout("tcp", net.JoinHostPort(loop, fmt.Sprint(port)), 300*time.Millisecond); err == nil {+ _ = c.Close()+ return false+ }+ }+ l, err := net.Listen("tcp", net.JoinHostPort(host, fmt.Sprint(port)))+ if err != nil {+ return false+ }+ _ = l.Close()+ return true+}++// PickPort returns preferred if it is free on host, otherwise the next free+// port (unless strict).+func PickPort(host string, preferred int, strict bool) (int, error) {+ if strict {+ if portFree(host, preferred) {+ return preferred, nil+ }+ return 0, fmt.Errorf("port %d is in use by another app", preferred)+ }+ for p := preferred; p < preferred+40 && p <= 65535; p++ {+ if portFree(host, p) {+ return p, nil+ }+ }+ return 0, ErrPortBusy+}++func (o Options) host() string {+ if o.Host == "" {+ return "127.0.0.1"+ }+ return o.Host+}++// Host is the address the proxy listens on.+func (p *Proxy) Host() string {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.opts.host()+}++// Start launches the service and waits until it answers HTTP requests.+func (p *Proxy) Start(opts Options) error {+ p.mu.Lock()+ if p.done != nil {+ select {+ case <-p.done:+ default:+ p.mu.Unlock()+ return errors.New("proxy already running")+ }+ }+ p.mu.Unlock()++ port, err := PickPort(opts.host(), opts.PreferredPort, opts.StrictPort)+ if err != nil {+ return err+ }+ if len(opts.APIKeys) == 0 {+ return errors.New("no API key configured")+ }+ secret := settings.RandomSecret()+ if err := writeConfig(port, opts, secret, false); err != nil {+ return fmt.Errorf("write proxy config: %w", err)+ }+ cfg, err := sdkconfig.LoadConfig(paths.ProxyConfig())+ if err != nil {+ return fmt.Errorf("load proxy config: %w", err)+ }+ gin.SetMode(gin.ReleaseMode)+ pass := settings.RandomSecret()+ routes := opts.Routes+ svc, err := cliproxy.NewBuilder().+ WithConfig(cfg).+ WithConfigPath(paths.ProxyConfig()).+ WithLocalManagementPassword(pass).+ WithServerOptions(+ api.WithMiddleware(opts.Middleware...),+ api.WithRouterConfigurator(func(e *gin.Engine, _ *handlers.BaseAPIHandler, _ *sdkconfig.Config) {+ e.GET("/healthz-companion", func(c *gin.Context) { c.String(http.StatusOK, "ok") })+ if routes != nil {+ routes(e)+ }+ })).+ Build()+ if err != nil {+ return fmt.Errorf("build proxy: %w", err)+ }++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ p.mu.Lock()+ p.opts = opts+ p.port = port+ p.secret = secret+ p.mgmtPass = pass+ p.cancel = cancel+ p.done = done+ p.runErr = nil+ p.mgmt = newMgmt(fmt.Sprintf("http://127.0.0.1:%d", port), pass, opts.APIKeys[len(opts.APIKeys)-1])+ p.mu.Unlock()++ go func() {+ defer close(done)+ err := svc.Run(ctx)+ if err != nil && !errors.Is(err, context.Canceled) {+ logx.Printf("proxy exited: %v", err)+ p.mu.Lock()+ p.runErr = err+ p.mu.Unlock()+ }+ }()++ // Wait for the listener.+ deadline := time.Now().Add(15 * time.Second)+ client := &http.Client{Timeout: 2 * time.Second}+ for time.Now().Before(deadline) {+ select {+ case <-done:+ if e := p.LastError(); e != nil {+ return e+ }+ return errors.New("proxy stopped during startup")+ default:+ }+ resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/healthz-companion", port))+ if err == nil {+ _ = resp.Body.Close()+ logx.Printf("proxy listening on %s:%d", opts.host(), port)+ return nil+ }+ time.Sleep(150 * time.Millisecond)+ }+ return errors.New("proxy did not start listening in time")+}++// Stop shuts the service down and waits for it to exit.+func (p *Proxy) Stop() {+ p.mu.Lock()+ cancel, done := p.cancel, p.done+ p.mu.Unlock()+ if cancel == nil {+ return+ }+ cancel()+ select {+ case <-done:+ case <-time.After(10 * time.Second):+ logx.Printf("proxy did not stop within 10s")+ }+ p.mu.Lock()+ p.port = 0+ p.mu.Unlock()+}++// Local returns the currently registered local upstreams.+func (p *Proxy) Local() []LocalUpstream {+ p.mu.Lock()+ defer p.mu.Unlock()+ return append([]LocalUpstream(nil), p.opts.Local...)+}++// SetLocal rewrites the registered local upstreams; the service hot-reloads+// its config file.+func (p *Proxy) SetLocal(local []LocalUpstream) error {+ p.mu.Lock()+ p.opts.Local = local+ opts, port, secret := p.opts, p.port, p.secret+ p.mu.Unlock()+ if port == 0 {+ return nil+ }+ // Rewrite in place: the proxy watches the file itself, and a rename would+ // leave its watch on the old inode.+ return writeConfig(port, opts, secret, true)+}++// q renders a YAML double-quoted scalar (JSON strings are valid YAML).+func q(s string) string {+ b, _ := json.Marshal(s)+ return string(b)+}++func writeConfig(port int, opts Options, secret string, inPlace bool) error {+ var b strings.Builder+ b.WriteString("# Generated by WebBrain Companion on every start. Edit companion settings instead.\n")+ b.WriteString("config-version: 8\n")+ fmt.Fprintf(&b, "server:\n host: %s\n", q(opts.host()))+ fmt.Fprintf(&b, " port: %d\n", port)+ b.WriteString("management:\n allow-remote: false\n")+ // A random secret enables the management routes; the companion itself+ // authenticates with a per-process local password instead.+ fmt.Fprintf(&b, " secret-key: %s\n", q(secret))+ b.WriteString(" disable-control-panel: true\n")+ b.WriteString("access:\n api-keys:\n")+ for _, k := range opts.APIKeys {+ fmt.Fprintf(&b, " - %s\n", q(k))+ }+ b.WriteString("routing:\n strategy: \"round-robin\"\n")+ b.WriteString("oauth:\n")+ fmt.Fprintf(&b, " auth-dir: %s\n", q(paths.AuthDir()))+ b.WriteString("observability:\n logs:\n debug: false\n logging-to-file: false\n request-log: false\n")+ if len(opts.Local) > 0 {+ b.WriteString("api-keys:\n openai-compatibility:\n")+ for _, up := range opts.Local {+ fmt.Fprintf(&b, " - name: %s\n", q(up.Name))+ fmt.Fprintf(&b, " base-url: %s\n", q(up.BaseURL))+ b.WriteString(" request-retry: 0\n")+ b.WriteString(" keys:\n - api-key: \"local\"\n")+ b.WriteString(" models:\n")+ for _, m := range up.Models {+ fmt.Fprintf(&b, " - name: %s\n", q(m.Upstream))+ fmt.Fprintf(&b, " alias: %s\n", q(m.Alias))+ if m.DisplayName != "" {+ fmt.Fprintf(&b, " display-name: %s\n", q(m.DisplayName))+ }+ if m.ContextLength > 0 {+ fmt.Fprintf(&b, " max-context-length: %d\n", m.ContextLength)+ }+ if m.Vision {+ b.WriteString(" input-modalities: [text, image]\n")+ } else {+ b.WriteString(" input-modalities: [text]\n")+ }+ b.WriteString(" thinking:\n levels: [\"low\", \"medium\", \"high\", \"xhigh\"]\n")+ }+ }+ }+ if err := os.MkdirAll(paths.Config(), 0o700); err != nil {+ return err+ }+ if inPlace {+ f, err := os.OpenFile(paths.ProxyConfig(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)+ if err != nil {+ return err+ }+ if _, err := f.WriteString(b.String()); err != nil {+ f.Close()+ return err+ }+ return f.Close()+ }+ tmp := paths.ProxyConfig() + ".tmp"+ if err := os.WriteFile(tmp, []byte(b.String()), 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, paths.ProxyConfig())+}diff --git a/webbrain-systray/internal/core/proxy_test.go b/webbrain-systray/internal/core/proxy_test.gonew file mode 100644index 000000000..22e57c34a--- /dev/null+++ b/webbrain-systray/internal/core/proxy_test.go@@ -0,0 +1,18 @@+package core++import "testing"++func TestPickPortMaximum(t *testing.T) {+ const host = "127.0.0.1"+ const port = 65535+ if !portFree(host, port) {+ t.Skip("port 65535 is unavailable")+ }+ got, err := PickPort(host, port, false)+ if err != nil {+ t.Fatalf("PickPort(%q, %d, false): %v", host, port, err)+ }+ if got != port {+ t.Fatalf("PickPort returned %d, want %d", got, port)+ }+}diff --git a/webbrain-systray/internal/d1/engine_export.go b/webbrain-systray/internal/d1/engine_export.gonew file mode 100644index 000000000..1c9d3f65e--- /dev/null+++ b/webbrain-systray/internal/d1/engine_export.go@@ -0,0 +1,48 @@+package d1++import "context"++// Engine is a loaded decision model, usable without the Manager (tests, tools).+type Engine struct{ e *engine }++// OpenEngine loads the graphs in dir with the ONNX Runtime library at lib.+func OpenEngine(dir, lib string, threads int) (*Engine, error) {+ e, err := loadEngine(dir, lib, threads)+ if err != nil {+ return nil, err+ }+ return &Engine{e: e}, nil+}++// EvaluateJSON answers one {state, images, questions} request body.+func (x *Engine) EvaluateJSON(ctx context.Context, body []byte) (any, error) {+ req, err := parseRequest(body)+ if err != nil {+ return nil, err+ }+ return x.e.evaluate(ctx, req, ModelName)+}++// Encode exposes the prompt encoder for parity checks.+func (x *Engine) Encode(body []byte) ([][]int, [][]int, error) {+ req, err := parseRequest(body)+ if err != nil {+ return nil, nil, err+ }+ limit := min(x.e.cfg.MaxLength, cpuMaxTextTokens)+ if len(req.images) > 0 {+ limit = x.e.cfg.ImageTextLength+ }+ var ids, markers [][]int+ for _, q := range req.questions {+ enc, err := encode(x.e.tok, req.stateText, q, limit, len(req.images) > 0)+ if err != nil {+ return nil, nil, err+ }+ ids = append(ids, enc.ids)+ markers = append(markers, enc.markers)+ }+ return ids, markers, nil+}++func (x *Engine) Close() { x.e.close() }diff --git a/webbrain-systray/internal/d1/helpers.go b/webbrain-systray/internal/d1/helpers.gonew file mode 100644index 000000000..8689c9690--- /dev/null+++ b/webbrain-systray/internal/d1/helpers.go@@ -0,0 +1,16 @@+package d1++import "github.com/esokullu/webbrain-systray/internal/osutil"++func execQuiet(name string, args ...string) error {+ return osutil.Command(name, args...).Run()+}++// SHA-256 of the pinned ONNX Runtime 1.31.0 release archives.+var ortSHA = map[string]string{+ "linux-x64": "cc5c72baf5ae5c8238a6841f0897227be2d02826b9cf98eaf02fdefaeeb03a57",+ "linux-aarch64": "c5b8b3cca31f3d643a3b313b8f42e2d0f16a4fcefd02cda343d97bd5306afaab",+ "osx-arm64": "1031b36dd3bdaa8d976a6130d9cf2a05e9be320b93ae804f8427b91dc3432afc",+ "win-x64": "3958d8a44984160692c1b4ffd0de3cb48f8c39f9d34bb31e433db06e30b82195",+ "win-arm64": "ef6206fa8d6975878d93a97035d280240ce5764c126a7430e5427e18923316d5",+}diff --git a/webbrain-systray/internal/d1/manager.go b/webbrain-systray/internal/d1/manager.gonew file mode 100644index 000000000..96407184c--- /dev/null+++ b/webbrain-systray/internal/d1/manager.go@@ -0,0 +1,463 @@+// Package d1 hosts WebBrain's on-device decision model+// (webbrain-one/d1-browser-decision-fp32) natively: it downloads the pinned+// ONNX graphs and an ONNX Runtime build, then answers the same+// {state, images, questions} requests as the extension's WebGPU adapter.+package d1++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "time"++ "github.com/esokullu/webbrain-systray/internal/download"+ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/paths"+ "github.com/esokullu/webbrain-systray/internal/settings"+)++const (+ ModelName = "d1-browser-decision-fp32"+ Provider = "companion_d1"+ repo = "webbrain-one/d1-browser-decision-fp32"+ revision = "9023fa407e3f17e02ad1fba1b921a0dc846dca89"++ ortVersion = "1.31.0"++ PhaseIdle = "idle"+ PhaseDownloading = "downloading"+ PhaseInstalling = "installing"+ PhaseLoading = "loading"+ PhaseReady = "ready"+ PhaseError = "error"+)++// ErrNotReady is returned when a decision is requested before the model is installed.+var ErrNotReady = errors.New("the decision model is not installed; open the companion panel to install it")++type file struct {+ name string+ size int64+ sha string+}++var modelFiles = []file{+ {"onnx/decision.data", 1522925568, "631417aa49dacb602b7e099062cd44c89e3747533a4094a61ff5f1cb3ccb0daf"},+ {"onnx/vision.data", 343372800, "490b694cf9a8770793e1cccc3d698bfb076f4b177216f9036e82eb0735b09390"},+ {"onnx/projector.data", 33566720, "e52c40550fbce097580870a7ddcca3f6992d93942931039ea717878514dd7a47"},+ {"onnx/decision.onnx", 366403, "ef66e7aa7f288fd71578cb6f6b71a04d6f531ad7755536487e155f66f605baf9"},+ {"onnx/vision.onnx", 119183, "aa7cbbabc0ee925ab4dd44a6c85dd7bf92ef36da5f2ebcdf1066f918d1a2ea89"},+ {"onnx/projector.onnx", 5712, "5489cd6636df06e474866ea55a37b06ec30a9fffcc993c89caff76639cc07d1e"},+ {"tokenizer.json", 4733371, "1efc3a6609abf6b63b1f47188d139f3b59973a6a434dffe970a7261a51ed2711"},+ {"config.json", 1765, "68ddf4bd4f3e489455211f80836b36281115cb9206b8e8d47858d062bdb6508d"},+ {"tiling-ratios.json", 681, "256b18bf3b533c9aaa34099b049e688893282341fb078b772b3ecb7b59ab43b6"},+}++type ortAsset struct {+ archive string+ size int64+ sha string+ lib string // library path inside the archive (after the top folder)+}++func ortForPlatform() (ortAsset, bool) {+ switch runtime.GOOS + "/" + runtime.GOARCH {+ case "linux/amd64":+ return ortAsset{"onnxruntime-linux-x64-" + ortVersion + ".tgz", 11408003, ortSHA["linux-x64"], "lib/libonnxruntime.so." + ortVersion}, true+ case "linux/arm64":+ return ortAsset{"onnxruntime-linux-aarch64-" + ortVersion + ".tgz", 10331104, ortSHA["linux-aarch64"], "lib/libonnxruntime.so." + ortVersion}, true+ case "darwin/arm64":+ return ortAsset{"onnxruntime-osx-arm64-" + ortVersion + ".tgz", 36549009, ortSHA["osx-arm64"], "lib/libonnxruntime." + ortVersion + ".dylib"}, true+ case "windows/amd64":+ return ortAsset{"onnxruntime-win-x64-" + ortVersion + ".zip", 82887349, ortSHA["win-x64"], "lib/onnxruntime.dll"}, true+ case "windows/arm64":+ return ortAsset{"onnxruntime-win-arm64-" + ortVersion + ".zip", 85806468, ortSHA["win-arm64"], "lib/onnxruntime.dll"}, true+ }+ return ortAsset{}, false+}++func modelDir() string { return filepath.Join(paths.Models(), ModelName) }+func ortDir() string { return filepath.Join(paths.Runtimes(), "onnxruntime-"+ortVersion) }++func ortLibPath() string {+ a, ok := ortForPlatform()+ if !ok {+ return ""+ }+ return filepath.Join(ortDir(), filepath.FromSlash(a.lib))+}++type Status struct {+ Model string `json:"model"`+ Phase string `json:"phase"`+ Step string `json:"step,omitempty"`+ Progress *download.Progress `json:"progress,omitempty"`+ Error string `json:"error,omitempty"`+ Installed bool `json:"installed"`+ Supported bool `json:"supported"`+ Enabled bool `json:"enabled"`+ Runtime string `json:"runtime,omitempty"`+ DownloadBytes int64 `json:"download_bytes"`+ DiskBytes int64 `json:"disk_bytes"`+ Endpoint string `json:"endpoint"`+ Requests int64 `json:"requests"`+ LastLatencyMs float64 `json:"last_latency_ms,omitempty"`+ License string `json:"license"`+}++type Manager struct {+ mu sync.Mutex+ store *settings.Store+ onChange func()+ phase string+ step string+ progress *download.Progress+ err string+ cancel context.CancelFunc+ eng *engine+ evalMu sync.Mutex+ requests int64+ latency float64+}++func NewManager(store *settings.Store, onChange func()) *Manager {+ return &Manager{store: store, onChange: onChange, phase: PhaseIdle}+}++func (m *Manager) changed() {+ if m.onChange != nil {+ go m.onChange()+ }+}++func okFile(path string, size int64) bool {+ st, err := os.Stat(path)+ return err == nil && st.Size() == size+}++// Installed reports whether the model files and runtime are present.+func (m *Manager) Installed() bool {+ if _, ok := ortForPlatform(); !ok {+ return false+ }+ for _, f := range modelFiles {+ if !okFile(filepath.Join(modelDir(), filepath.FromSlash(f.name)), f.size) {+ return false+ }+ }+ _, err := os.Stat(ortLibPath())+ return err == nil+}++func (m *Manager) Status() Status {+ _, supported := ortForPlatform()+ st := Status{Model: ModelName, Supported: supported, Installed: m.Installed(), Enabled: m.store.Get().Decision.Enabled,+ License: "LFM Open License v1.0"}+ for _, f := range modelFiles {+ p := filepath.Join(modelDir(), filepath.FromSlash(f.name))+ if okFile(p, f.size) {+ st.DiskBytes += f.size+ continue+ }+ rem := f.size+ if s, err := os.Stat(p + ".part"); err == nil && s.Size() < f.size {+ rem -= s.Size()+ }+ st.DownloadBytes += rem+ }+ if a, ok := ortForPlatform(); ok {+ if _, err := os.Stat(ortLibPath()); err != nil {+ st.DownloadBytes += a.size+ }+ }+ m.mu.Lock()+ st.Phase, st.Step, st.Error = m.phase, m.step, m.err+ if m.progress != nil {+ p := *m.progress+ st.Progress = &p+ }+ if m.eng != nil {+ st.Runtime = "ONNX Runtime " + m.eng.ort.version + " on the CPU"+ }+ st.Requests, st.LastLatencyMs = m.requests, m.latency+ m.mu.Unlock()+ return st+}++func (m *Manager) set(phase, step string, err error) {+ m.mu.Lock()+ m.phase, m.step = phase, step+ m.err = ""+ if err != nil {+ m.err = err.Error()+ }+ if phase != PhaseDownloading {+ m.progress = nil+ }+ m.mu.Unlock()+ m.changed()+}++// Install downloads the model and runtime, then loads them.+func (m *Manager) Install() error {+ asset, ok := ortForPlatform()+ if !ok {+ return errors.New("ONNX Runtime " + ortVersion + " has no build for this platform")+ }+ m.mu.Lock()+ if m.phase == PhaseDownloading || m.phase == PhaseInstalling || m.phase == PhaseLoading {+ m.mu.Unlock()+ return errors.New("already installing")+ }+ ctx, cancel := context.WithCancel(context.Background())+ m.cancel = cancel+ m.mu.Unlock()+ go func() {+ defer cancel()+ if err := m.install(ctx, asset); err != nil {+ if errors.Is(err, context.Canceled) {+ m.set(PhaseIdle, "", nil)+ return+ }+ logx.Printf("decision model install: %v", err)+ m.set(PhaseError, "", err)+ return+ }+ _, _ = m.store.Update(func(s *settings.Settings) { s.Decision.Enabled = true })+ if err := m.Load(); err != nil {+ logx.Printf("decision model load: %v", err)+ }+ }()+ return nil+}++func (m *Manager) Cancel() {+ m.mu.Lock()+ c := m.cancel+ m.mu.Unlock()+ if c != nil {+ c()+ }+}++func (m *Manager) install(ctx context.Context, asset ortAsset) error {+ type item struct {+ label, url, dest string+ size int64+ sha string+ }+ var items []item+ for _, f := range modelFiles {+ items = append(items, item{"d1 decision model", fmt.Sprintf("https://huggingface.co/%s/resolve/%s/%s", repo, revision, f.name),+ filepath.Join(modelDir(), filepath.FromSlash(f.name)), f.size, f.sha})+ }+ archive := filepath.Join(paths.Runtimes(), "_downloads", asset.archive)+ needORT := !okFileAny(ortLibPath())+ if needORT {+ items = append(items, item{"ONNX Runtime " + ortVersion, "https://github.com/microsoft/onnxruntime/releases/download/v" + ortVersion + "/" + asset.archive,+ archive, asset.size, asset.sha})+ }+ var total, done int64+ for _, it := range items {+ if !okFile(it.dest, it.size) {+ total += it.size+ }+ }+ for _, it := range items {+ if okFile(it.dest, it.size) {+ continue+ }+ var before int64+ if s, err := os.Stat(it.dest + ".part"); err == nil {+ before = s.Size()+ }+ base := done+ m.mu.Lock()+ m.phase, m.step = PhaseDownloading, it.label+ m.progress = &download.Progress{Done: base + before, Total: total}+ m.mu.Unlock()+ m.changed()+ err := download.File(ctx, it.url, it.dest, it.size, it.sha, func(p download.Progress) {+ m.mu.Lock()+ m.progress = &download.Progress{Done: base + p.Done, Total: total, BytesPerSec: p.BytesPerSec}+ m.mu.Unlock()+ m.changed()+ })+ if err != nil {+ return fmt.Errorf("%s: %w", it.label, err)+ }+ done = base + it.size+ }+ if needORT {+ m.set(PhaseInstalling, "Unpacking ONNX Runtime", nil)+ _ = os.RemoveAll(ortDir())+ keep := func(rel string) bool {+ // Only the runtime libraries: skip headers, symbols (a 430 MB .pdb) and test data.+ if !strings.HasPrefix(rel, "lib/") || strings.Contains(rel, ".dSYM") {+ return false+ }+ return strings.HasSuffix(rel, ".dll") || strings.HasSuffix(rel, ".dylib") || strings.Contains(rel, ".so")+ }+ if err := download.ExtractFiltered(archive, ortDir(), download.CommonPrefixDepth(archive), keep); err != nil {+ return fmt.Errorf("unpack ONNX Runtime: %w", err)+ }+ if runtime.GOOS == "darwin" {+ trustMac(ortDir())+ }+ if !okFileAny(ortLibPath()) {+ return errors.New("ONNX Runtime library missing from the archive")+ }+ _ = os.Remove(archive)+ }+ return nil+}++func okFileAny(p string) bool {+ st, err := os.Stat(p)+ return err == nil && !st.IsDir()+}++// Load creates the ONNX Runtime sessions (about 2 GB of memory).+func (m *Manager) Load() error {+ m.evalMu.Lock()+ defer m.evalMu.Unlock()+ return m.load()+}++// load requires evalMu so sessions cannot be replaced or released during use.+func (m *Manager) load() error {+ if !m.Installed() {+ return ErrNotReady+ }+ m.mu.Lock()+ if m.eng != nil {+ m.mu.Unlock()+ return nil+ }+ m.mu.Unlock()+ m.set(PhaseLoading, "Loading graphs", nil)+ threads := m.store.Get().Decision.Threads+ eng, err := loadEngine(modelDir(), ortLibPath(), threads)+ if err != nil {+ m.set(PhaseError, "", err)+ return err+ }+ m.mu.Lock()+ m.eng = eng+ m.mu.Unlock()+ m.set(PhaseReady, "", nil)+ logx.Printf("decision model ready (ONNX Runtime %s)", eng.ort.version)+ return nil+}++// Unload releases the sessions (the runtime library stays mapped).+func (m *Manager) Unload() {+ m.evalMu.Lock()+ defer m.evalMu.Unlock()+ m.unload()+}++// unload requires evalMu.+func (m *Manager) unload() {+ m.mu.Lock()+ eng := m.eng+ m.eng = nil+ if m.phase == PhaseReady {+ m.phase = PhaseIdle+ }+ m.mu.Unlock()+ if eng != nil {+ eng.close()+ }+ m.changed()+}++// Remove deletes the model files.+func (m *Manager) Remove() error {+ m.Cancel()+ m.evalMu.Lock()+ defer m.evalMu.Unlock()+ m.unload()+ if err := os.RemoveAll(modelDir()); err != nil {+ return err+ }+ _, _ = m.store.Update(func(s *settings.Settings) { s.Decision.Enabled = false })+ m.set(PhaseIdle, "", nil)+ return nil+}++// engine requires evalMu to keep the returned sessions alive for the caller.+func (m *Manager) engine() (*engine, error) {+ m.mu.Lock()+ eng := m.eng+ m.mu.Unlock()+ if eng != nil {+ return eng, nil+ }+ if !m.Installed() {+ return nil, ErrNotReady+ }+ if err := m.load(); err != nil {+ return nil, err+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ if m.eng == nil {+ return nil, ErrNotReady+ }+ return m.eng, nil+}++// EvaluateJSON answers one {state, images, questions} request.+func (m *Manager) EvaluateJSON(ctx context.Context, body []byte) (any, error) {+ req, err := parseRequest(body)+ if err != nil {+ return nil, err+ }+ m.evalMu.Lock()+ defer m.evalMu.Unlock()+ eng, err := m.engine()+ if err != nil {+ return nil, err+ }+ start := time.Now()+ res, err := eng.evaluate(ctx, req, ModelName)+ if err != nil {+ return nil, err+ }+ m.mu.Lock()+ m.requests+++ m.latency = float64(time.Since(start).Microseconds()) / 1000+ m.mu.Unlock()+ m.changed()+ return res, nil+}++// SelfTest runs a small text-only decision.+func (m *Manager) SelfTest(ctx context.Context) (any, error) {+ body, _ := json.Marshal(map[string]any{+ "state": "Checkout complete. Order #1042 is confirmed and a receipt was sent to your email.",+ "questions": json.RawMessage(`{"completion":{"type":"choice","instructions":"Judge only the visible evidence: did the shopping task finish?",` ++ `"criteria":{"completed":"An explicit confirmation shows the order was placed.","not_completed":"The page shows an error or an unfinished checkout.","unknown":"The evidence does not establish the outcome."}}}`),+ })+ return m.EvaluateJSON(ctx, body)+}++func trustMac(dir string) {+ if runtime.GOOS != "darwin" {+ return+ }+ _ = filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {+ if err == nil && !info.IsDir() && strings.HasSuffix(p, ".dylib") {+ _ = execQuiet("/usr/bin/xattr", "-c", p)+ _ = execQuiet("/usr/bin/codesign", "-s", "-", "--force", "--timestamp=none", p)+ }+ return nil+ })+}diff --git a/webbrain-systray/internal/d1/ojson.go b/webbrain-systray/internal/d1/ojson.gonew file mode 100644index 000000000..92d095fbe--- /dev/null+++ b/webbrain-systray/internal/d1/ojson.go@@ -0,0 +1,422 @@+package d1++// JSON values with JavaScript semantics: object keys keep JS property order+// (array-index keys first, ascending; then insertion order) and numbers+// print the way Number.prototype.toString does. The d1 prompt is built from+// these exact strings, so they must match the browser adapter.++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "math"+ "sort"+ "strconv"+ "strings"+ "unicode/utf8"+)++type kind int++const (+ kNull kind = iota+ kBool+ kNum+ kStr+ kArr+ kObj+)++type Value struct {+ K kind+ B bool+ N float64+ S string+ A []*Value+ Keys []string+ M map[string]*Value+}++func (v *Value) IsNull() bool { return v == nil || v.K == kNull }++// Get returns an object member (nil when absent).+func (v *Value) Get(key string) *Value {+ if v == nil || v.K != kObj {+ return nil+ }+ return v.M[key]+}++// Has mirrors Object.hasOwn.+func (v *Value) Has(key string) bool {+ if v == nil || v.K != kObj {+ return false+ }+ _, ok := v.M[key]+ return ok+}++// Len is Object.keys(v).length for objects and arrays.+func (v *Value) Len() int {+ if v == nil {+ return 0+ }+ switch v.K {+ case kObj:+ return len(v.Keys)+ case kArr:+ return len(v.A)+ case kStr:+ return utf8.RuneCountInString(v.S)+ }+ return 0+}++// ParseJSON decodes data into a Value tree.+func ParseJSON(data []byte) (*Value, error) {+ dec := json.NewDecoder(bytes.NewReader(data))+ dec.UseNumber()+ v, err := parseValue(dec)+ if err != nil {+ return nil, err+ }+ if _, err := dec.Token(); err != io.EOF {+ return nil, errors.New("unexpected data after JSON value")+ }+ return v, nil+}++func parseValue(dec *json.Decoder) (*Value, error) {+ tok, err := dec.Token()+ if err != nil {+ return nil, err+ }+ return fromToken(dec, tok)+}++func fromToken(dec *json.Decoder, tok json.Token) (*Value, error) {+ switch t := tok.(type) {+ case nil:+ return &Value{K: kNull}, nil+ case bool:+ return &Value{K: kBool, B: t}, nil+ case json.Number:+ f, err := strconv.ParseFloat(string(t), 64)+ if err != nil {+ // Out-of-range literals become ±Infinity in JS; reject them here.+ return nil, fmt.Errorf("number %s is out of range", t)+ }+ return &Value{K: kNum, N: f}, nil+ case string:+ return &Value{K: kStr, S: t}, nil+ case json.Delim:+ switch t {+ case '[':+ v := &Value{K: kArr, A: []*Value{}}+ for dec.More() {+ el, err := parseValue(dec)+ if err != nil {+ return nil, err+ }+ v.A = append(v.A, el)+ }+ if _, err := dec.Token(); err != nil {+ return nil, err+ }+ return v, nil+ case '{':+ v := &Value{K: kObj, M: map[string]*Value{}}+ for dec.More() {+ kt, err := dec.Token()+ if err != nil {+ return nil, err+ }+ key, ok := kt.(string)+ if !ok {+ return nil, errors.New("object key must be a string")+ }+ el, err := parseValue(dec)+ if err != nil {+ return nil, err+ }+ if _, dup := v.M[key]; !dup {+ v.Keys = append(v.Keys, key)+ }+ v.M[key] = el+ }+ if _, err := dec.Token(); err != nil {+ return nil, err+ }+ v.Keys = jsKeyOrder(v.Keys)+ return v, nil+ }+ }+ return nil, fmt.Errorf("unexpected token %v", tok)+}++// arrayIndex reports whether k is a canonical array index ("0".."4294967294").+func arrayIndex(k string) (uint64, bool) {+ if k == "" || len(k) > 10 || (len(k) > 1 && k[0] == '0') {+ return 0, false+ }+ n, err := strconv.ParseUint(k, 10, 64)+ if err != nil || n >= 4294967295 {+ return 0, false+ }+ return n, true+}++// jsKeyOrder applies OrdinaryOwnPropertyKeys: integer keys ascending first.+func jsKeyOrder(keys []string) []string {+ var ints []string+ var rest []string+ for _, k := range keys {+ if _, ok := arrayIndex(k); ok {+ ints = append(ints, k)+ } else {+ rest = append(rest, k)+ }+ }+ if len(ints) == 0 {+ return keys+ }+ sort.Slice(ints, func(i, j int) bool {+ a, _ := arrayIndex(ints[i])+ b, _ := arrayIndex(ints[j])+ return a < b+ })+ return append(ints, rest...)+}++// jsNumber formats like Number.prototype.toString (radix 10).+func jsNumber(f float64) string {+ if f == 0 {+ return "0"+ }+ if math.IsNaN(f) {+ return "NaN"+ }+ if math.IsInf(f, 1) {+ return "Infinity"+ }+ if math.IsInf(f, -1) {+ return "-Infinity"+ }+ sign := ""+ if f < 0 {+ sign = "-"+ f = -f+ }+ digits, exp := shortest(f)+ k := len(digits)+ n := exp + 1 // position of the decimal point+ switch {+ case k <= n && n <= 21:+ return sign + digits + strings.Repeat("0", n-k)+ case 0 < n && n <= 21:+ return sign + digits[:n] + "." + digits[n:]+ case -6 < n && n <= 0:+ return sign + "0." + strings.Repeat("0", -n) + digits+ }+ e := n - 1+ es := "+"+ if e < 0 {+ es = "-"+ e = -e+ }+ if k == 1 {+ return sign + digits + "e" + es + strconv.Itoa(e)+ }+ return sign + digits[:1] + "." + digits[1:] + "e" + es + strconv.Itoa(e)+}++// shortest returns the shortest round-trip digits and the decimal exponent of+// the first digit (d.ddd × 10^exp).+func shortest(f float64) (string, int) {+ s := strconv.FormatFloat(f, 'e', -1, 64) // d.ddde±XX+ mant, expStr, _ := strings.Cut(s, "e")+ exp, _ := strconv.Atoi(expStr)+ return strings.Replace(mant, ".", "", 1), exp+}++// jsExponential is Number.prototype.toExponential() without fraction digits.+func jsExponential(f float64) string {+ sign := ""+ if f < 0 {+ sign = "-"+ f = -f+ }+ digits, exp := shortest(f)+ es := "+"+ if exp < 0 {+ es = "-"+ exp = -exp+ }+ m := digits[:1]+ if len(digits) > 1 {+ m += "." + digits[1:]+ }+ return sign + m + "e" + es + strconv.Itoa(exp)+}++// jsQuote is JSON.stringify for a string.+func jsQuote(s string) string {+ var b strings.Builder+ b.WriteByte('"')+ for _, r := range s {+ switch r {+ case '"':+ b.WriteString(`\"`)+ case '\\':+ b.WriteString(`\\`)+ case '\b':+ b.WriteString(`\b`)+ case '\f':+ b.WriteString(`\f`)+ case '\n':+ b.WriteString(`\n`)+ case '\r':+ b.WriteString(`\r`)+ case '\t':+ b.WriteString(`\t`)+ default:+ if r < 0x20 {+ fmt.Fprintf(&b, `\u%04x`, r)+ } else {+ b.WriteRune(r)+ }+ }+ }+ b.WriteByte('"')+ return b.String()+}++// jsStringify is JSON.stringify(v) (compact).+func jsStringify(v *Value) string {+ var b strings.Builder+ var walk func(*Value)+ walk = func(v *Value) {+ switch {+ case v == nil || v.K == kNull:+ b.WriteString("null")+ case v.K == kBool:+ b.WriteString(strconv.FormatBool(v.B))+ case v.K == kNum:+ if math.IsInf(v.N, 0) || math.IsNaN(v.N) {+ b.WriteString("null")+ } else {+ b.WriteString(jsNumber(v.N))+ }+ case v.K == kStr:+ b.WriteString(jsQuote(v.S))+ case v.K == kArr:+ b.WriteByte('[')+ for i, el := range v.A {+ if i > 0 {+ b.WriteByte(',')+ }+ walk(el)+ }+ b.WriteByte(']')+ case v.K == kObj:+ b.WriteByte('{')+ for i, k := range v.Keys {+ if i > 0 {+ b.WriteByte(',')+ }+ b.WriteString(jsQuote(k))+ b.WriteByte(':')+ walk(v.M[k])+ }+ b.WriteByte('}')+ }+ }+ walk(v)+ return b.String()+}++// pyJSON reproduces the adapter's Python-style json.dumps rendering.+func pyJSON(v *Value) (string, error) {+ switch {+ case v == nil || v.K == kNull:+ return "null", nil+ case v.K == kArr:+ parts := make([]string, len(v.A))+ for i, el := range v.A {+ s, err := pyJSON(el)+ if err != nil {+ return "", err+ }+ parts[i] = s+ }+ return "[" + strings.Join(parts, ", ") + "]", nil+ case v.K == kObj:+ parts := make([]string, len(v.Keys))+ for i, k := range v.Keys {+ s, err := pyJSON(v.M[k])+ if err != nil {+ return "", err+ }+ parts[i] = jsQuote(k) + ": " + s+ }+ return "{" + strings.Join(parts, ", ") + "}", nil+ case v.K == kNum:+ if math.IsInf(v.N, 0) || math.IsNaN(v.N) {+ return "", errors.New("D1 JSON numbers must be finite")+ }+ if v.N != math.Trunc(v.N) && math.Abs(v.N) < 1e-4 {+ s := jsExponential(v.N)+ if i := strings.LastIndexAny(s, "+-"); i > 0 && s[i-1] == 'e' {+ d := s[i+1:]+ if len(d) < 2 {+ d = "0" + d+ }+ s = s[:i+1] + d+ }+ return s, nil+ }+ return jsNumber(v.N), nil+ case v.K == kBool:+ return strconv.FormatBool(v.B), nil+ default:+ return jsQuote(v.S), nil+ }+}++// ordered is an insertion-ordered JSON object for responses.+type ordered struct {+ keys []string+ vals map[string]any+}++func newOrdered() *ordered { return &ordered{vals: map[string]any{}} }++func (o *ordered) Set(k string, v any) *ordered {+ if _, ok := o.vals[k]; !ok {+ o.keys = append(o.keys, k)+ }+ o.vals[k] = v+ return o+}++func (o *ordered) MarshalJSON() ([]byte, error) {+ var b bytes.Buffer+ b.WriteByte('{')+ for i, k := range jsKeyOrder(append([]string(nil), o.keys...)) {+ if i > 0 {+ b.WriteByte(',')+ }+ kb, _ := json.Marshal(k)+ b.Write(kb)+ b.WriteByte(':')+ vb, err := json.Marshal(o.vals[k])+ if err != nil {+ return nil, err+ }+ b.Write(vb)+ }+ b.WriteByte('}')+ return b.Bytes(), nil+}diff --git a/webbrain-systray/internal/d1/ojson_test.go b/webbrain-systray/internal/d1/ojson_test.gonew file mode 100644index 000000000..46fcbb8bd--- /dev/null+++ b/webbrain-systray/internal/d1/ojson_test.go@@ -0,0 +1,45 @@+package d1++import (+ "reflect"+ "testing"+)++// Expected strings are what V8 prints for the same values.+func TestJSNumber(t *testing.T) {+ cases := map[float64]string{+ 0: "0", 1: "1", -2.5: "-2.5", 0.1: "0.1", 0.30000000000000004: "0.30000000000000004",+ 1e20: "100000000000000000000", 1e21: "1e+21", 123456789012345680000: "123456789012345680000",+ 0.000001: "0.000001", 1e-7: "1e-7", 1.5e-7: "1.5e-7", 2.5e-10: "2.5e-10", 1.7976931348623157e308: "1.7976931348623157e+308",+ }+ for f, want := range cases {+ if got := jsNumber(f); got != want {+ t.Errorf("jsNumber(%v) = %s, want %s", f, got, want)+ }+ }+ if got := jsExponential(12345); got != "1.2345e+4" {+ t.Errorf("jsExponential(12345) = %s", got)+ }+ if got := jsExponential(0.00042); got != "4.2e-4" {+ t.Errorf("jsExponential(0.00042) = %s", got)+ }+}++// Integer-like keys come first in ascending order, then the rest in insertion order.+func TestJSKeyOrder(t *testing.T) {+ got := jsKeyOrder([]string{"b", "10", "a", "2", "01", "1"})+ want := []string{"1", "2", "10", "b", "a", "01"}+ if !reflect.DeepEqual(got, want) {+ t.Errorf("got %v, want %v", got, want)+ }+}++func TestStringifyRoundTrip(t *testing.T) {+ v, err := ParseJSON([]byte(`{"z":1,"a":[true,null,"x\"y"],"5":{"k":0.5}}`))+ if err != nil {+ t.Fatal(err)+ }+ if got, want := jsStringify(v), `{"5":{"k":0.5},"z":1,"a":[true,null,"x\"y"]}`; got != want {+ t.Errorf("got %s, want %s", got, want)+ }+}diff --git a/webbrain-systray/internal/d1/ort.go b/webbrain-systray/internal/d1/ort.gonew file mode 100644index 000000000..3421bfbb8--- /dev/null+++ b/webbrain-systray/internal/d1/ort.go@@ -0,0 +1,378 @@+package d1++// A minimal ONNX Runtime binding over the C API, loaded at runtime with+// purego (no cgo). Function pointers are read from the OrtApi table; the+// indices below come from onnxruntime_c_api.h (the table is append-only, so+// they are stable across ORT releases).++import (+ "errors"+ "fmt"+ "runtime"+ "sync"+ "unicode/utf16"+ "unsafe"++ "github.com/ebitengine/purego"+)++const ortRequestedAPIVersion = 20++const (+ fnGetErrorMessage = 2+ fnCreateEnv = 3+ fnCreateSession = 7+ fnRun = 9+ fnCreateSessionOptions = 10+ fnSetSessionGraphOptimization = 23+ fnSetIntraOpNumThreads = 24+ fnSetInterOpNumThreads = 25+ fnSessionGetInputCount = 30+ fnSessionGetOutputCount = 31+ fnSessionGetInputName = 36+ fnSessionGetOutputName = 37+ fnCreateTensorWithDataAsOrtValue = 49+ fnGetTensorMutableData = 51+ fnGetDimensionsCount = 61+ fnGetDimensions = 62+ fnGetTensorShapeElementCount = 64+ fnGetTensorTypeAndShape = 65+ fnCreateCpuMemoryInfo = 69+ fnAllocatorFree = 76+ fnGetAllocatorWithDefaultOptions = 78+ fnReleaseEnv = 92+ fnReleaseStatus = 93+ fnReleaseMemoryInfo = 94+ fnReleaseSession = 95+ fnReleaseValue = 96+ fnReleaseTensorTypeAndShapeInfo = 99+ fnReleaseSessionOptions = 100+)++// ONNX tensor element types.+const (+ elemFloat = 1+ elemInt64 = 7+ elemBool = 9+)++type ortLib struct {+ api uintptr+ env uintptr+ memInfo uintptr+ alloc uintptr+ version string+}++// cptr turns an address owned by C into a pointer (C memory never moves).+func cptr(p uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&p)) }++func (o *ortLib) fn(idx int) uintptr {+ return *(*uintptr)(unsafe.Add(cptr(o.api), idx*int(unsafe.Sizeof(uintptr(0)))))+}++func (o *ortLib) call(idx int, args ...uintptr) uintptr {+ r, _, _ := purego.SyscallN(o.fn(idx), args...)+ return r+}++// check converts an OrtStatus* into an error and releases it.+func (o *ortLib) check(status uintptr) error {+ if status == 0 {+ return nil+ }+ msg := goString(o.call(fnGetErrorMessage, status))+ o.call(fnReleaseStatus, status)+ return errors.New("onnxruntime: " + msg)+}++func goString(p uintptr) string {+ if p == 0 {+ return ""+ }+ var b []byte+ for i := 0; i < 1<<16; i++ {+ c := *(*byte)(unsafe.Add(cptr(p), i))+ if c == 0 {+ break+ }+ b = append(b, c)+ }+ return string(b)+}++func cString(s string) []byte { return append([]byte(s), 0) }++// ortPath encodes a filesystem path as ORTCHAR_T* (UTF-16 on Windows).+func ortPath(p string) (uintptr, any) {+ if runtime.GOOS == "windows" {+ u := append(utf16.Encode([]rune(p)), 0)+ return uintptr(unsafe.Pointer(&u[0])), u+ }+ b := cString(p)+ return uintptr(unsafe.Pointer(&b[0])), b+}++var (+ ortOnce sync.Mutex+ ortInst *ortLib+)++// loadORT opens the ONNX Runtime shared library and creates the environment.+func loadORT(libPath string) (*ortLib, error) {+ ortOnce.Lock()+ defer ortOnce.Unlock()+ if ortInst != nil {+ return ortInst, nil+ }+ sym, err := openSymbol(libPath, "OrtGetApiBase")+ if err != nil {+ return nil, err+ }+ base, _, _ := purego.SyscallN(sym)+ if base == 0 {+ return nil, errors.New("OrtGetApiBase returned null")+ }+ getAPI := *(*uintptr)(cptr(base))+ getVersion := *(*uintptr)(unsafe.Add(cptr(base), unsafe.Sizeof(uintptr(0))))+ api, _, _ := purego.SyscallN(getAPI, ortRequestedAPIVersion)+ if api == 0 {+ return nil, fmt.Errorf("ONNX Runtime at %s does not support API version %d", libPath, ortRequestedAPIVersion)+ }+ vp, _, _ := purego.SyscallN(getVersion)+ o := &ortLib{api: api, version: goString(vp)}+ logid := cString("webbrain-d1")+ var env uintptr+ if err := o.check(o.call(fnCreateEnv, 3 /* ERROR */, uintptr(unsafe.Pointer(&logid[0])), uintptr(unsafe.Pointer(&env)))); err != nil {+ return nil, err+ }+ runtime.KeepAlive(logid)+ o.env = env+ var mi uintptr+ if err := o.check(o.call(fnCreateCpuMemoryInfo, 1 /* arena */, 0 /* default */, uintptr(unsafe.Pointer(&mi)))); err != nil {+ return nil, err+ }+ o.memInfo = mi+ var alloc uintptr+ if err := o.check(o.call(fnGetAllocatorWithDefaultOptions, uintptr(unsafe.Pointer(&alloc)))); err != nil {+ return nil, err+ }+ o.alloc = alloc+ ortInst = o+ return o, nil+}++type session struct {+ o *ortLib+ ptr uintptr+ inputs []string+ outputs []string+}++func (o *ortLib) newSession(modelPath string, threads int) (*session, error) {+ var opts uintptr+ if err := o.check(o.call(fnCreateSessionOptions, uintptr(unsafe.Pointer(&opts)))); err != nil {+ return nil, err+ }+ defer o.call(fnReleaseSessionOptions, opts)+ if threads > 0 {+ if err := o.check(o.call(fnSetIntraOpNumThreads, opts, uintptr(threads))); err != nil {+ return nil, err+ }+ }+ if err := o.check(o.call(fnSetInterOpNumThreads, opts, 1)); err != nil {+ return nil, err+ }+ // ORT_ENABLE_EXTENDED: fusions without layout transforms.+ if err := o.check(o.call(fnSetSessionGraphOptimization, opts, 2)); err != nil {+ return nil, err+ }+ p, keep := ortPath(modelPath)+ var s uintptr+ err := o.check(o.call(fnCreateSession, o.env, p, opts, uintptr(unsafe.Pointer(&s))))+ runtime.KeepAlive(keep)+ if err != nil {+ return nil, err+ }+ sess := &session{o: o, ptr: s}+ var n uintptr+ if err := o.check(o.call(fnSessionGetInputCount, s, uintptr(unsafe.Pointer(&n)))); err != nil {+ return nil, err+ }+ for i := uintptr(0); i < n; i++ {+ var name uintptr+ if err := o.check(o.call(fnSessionGetInputName, s, i, o.alloc, uintptr(unsafe.Pointer(&name)))); err != nil {+ return nil, err+ }+ sess.inputs = append(sess.inputs, goString(name))+ o.call(fnAllocatorFree, o.alloc, name)+ }+ if err := o.check(o.call(fnSessionGetOutputCount, s, uintptr(unsafe.Pointer(&n)))); err != nil {+ return nil, err+ }+ for i := uintptr(0); i < n; i++ {+ var name uintptr+ if err := o.check(o.call(fnSessionGetOutputName, s, i, o.alloc, uintptr(unsafe.Pointer(&name)))); err != nil {+ return nil, err+ }+ sess.outputs = append(sess.outputs, goString(name))+ o.call(fnAllocatorFree, o.alloc, name)+ }+ return sess, nil+}++func (s *session) release() {+ if s != nil && s.ptr != 0 {+ s.o.call(fnReleaseSession, s.ptr)+ s.ptr = 0+ }+}++// tensor is an input whose bytes stay owned by Go until the run returns.+type tensor struct {+ elem int+ shape []int64+ data unsafe.Pointer+ bytes uintptr+ keep any+}++func floatTensor(data []float32, shape ...int64) tensor {+ var dummy [1]float32+ p := unsafe.Pointer(&dummy[0])+ if len(data) > 0 {+ p = unsafe.Pointer(&data[0])+ }+ return tensor{elemFloat, shape, p, uintptr(len(data) * 4), [2]any{data, &dummy}}+}++func int64Tensor(data []int64, shape ...int64) tensor {+ var dummy [1]int64+ p := unsafe.Pointer(&dummy[0])+ if len(data) > 0 {+ p = unsafe.Pointer(&data[0])+ }+ return tensor{elemInt64, shape, p, uintptr(len(data) * 8), [2]any{data, &dummy}}+}++func boolTensor(data []bool, shape ...int64) tensor {+ var dummy [1]bool+ p := unsafe.Pointer(&dummy[0])+ if len(data) > 0 {+ p = unsafe.Pointer(&data[0])+ }+ return tensor{elemBool, shape, p, uintptr(len(data)), [2]any{data, &dummy}}+}++// output is a float32 result copied out of ORT memory.+type output struct {+ data []float32+ shape []int64+}++// run feeds named inputs and returns the requested float outputs.+func (s *session) run(inputs map[string]tensor, outputs ...string) (map[string]output, error) {+ o := s.o+ names := make([][]byte, 0, len(inputs))+ namePtrs := make([]uintptr, 0, len(inputs))+ values := make([]uintptr, 0, len(inputs))+ keep := make([]any, 0, len(inputs))+ defer func() {+ for _, v := range values {+ o.call(fnReleaseValue, v)+ }+ runtime.KeepAlive(keep)+ runtime.KeepAlive(names)+ }()+ for _, name := range s.inputs {+ t, ok := inputs[name]+ if !ok {+ return nil, fmt.Errorf("missing input %q", name)+ }+ var v uintptr+ shape := t.shape+ if len(shape) == 0 {+ shape = []int64{}+ }+ var shapePtr uintptr+ if len(shape) > 0 {+ shapePtr = uintptr(unsafe.Pointer(&shape[0]))+ }+ err := o.check(o.call(fnCreateTensorWithDataAsOrtValue, o.memInfo, uintptr(t.data), t.bytes,+ shapePtr, uintptr(len(shape)), uintptr(t.elem), uintptr(unsafe.Pointer(&v))))+ keep = append(keep, t.keep, shape)+ if err != nil {+ return nil, fmt.Errorf("input %s: %w", name, err)+ }+ values = append(values, v)+ n := cString(name)+ names = append(names, n)+ namePtrs = append(namePtrs, uintptr(unsafe.Pointer(&n[0])))+ }+ outNames := make([][]byte, len(outputs))+ outPtrs := make([]uintptr, len(outputs))+ for i, n := range outputs {+ outNames[i] = cString(n)+ outPtrs[i] = uintptr(unsafe.Pointer(&outNames[i][0]))+ }+ outVals := make([]uintptr, len(outputs))+ var inPtr, valPtr uintptr+ if len(namePtrs) > 0 {+ inPtr, valPtr = uintptr(unsafe.Pointer(&namePtrs[0])), uintptr(unsafe.Pointer(&values[0]))+ }+ err := o.check(o.call(fnRun, s.ptr, 0, inPtr, valPtr, uintptr(len(values)),+ uintptr(unsafe.Pointer(&outPtrs[0])), uintptr(len(outputs)), uintptr(unsafe.Pointer(&outVals[0]))))+ runtime.KeepAlive(namePtrs)+ runtime.KeepAlive(outNames)+ runtime.KeepAlive(outPtrs)+ if err != nil {+ for _, v := range outVals {+ if v != 0 {+ o.call(fnReleaseValue, v)+ }+ }+ return nil, err+ }+ res := make(map[string]output, len(outputs))+ for i, name := range outputs {+ v := outVals[i]+ out, err := o.readFloat(v)+ o.call(fnReleaseValue, v)+ if err != nil {+ return nil, fmt.Errorf("output %s: %w", name, err)+ }+ res[name] = out+ }+ return res, nil+}++func (o *ortLib) readFloat(v uintptr) (output, error) {+ var info uintptr+ if err := o.check(o.call(fnGetTensorTypeAndShape, v, uintptr(unsafe.Pointer(&info)))); err != nil {+ return output{}, err+ }+ defer o.call(fnReleaseTensorTypeAndShapeInfo, info)+ var dims uintptr+ if err := o.check(o.call(fnGetDimensionsCount, info, uintptr(unsafe.Pointer(&dims)))); err != nil {+ return output{}, err+ }+ shape := make([]int64, dims)+ if dims > 0 {+ if err := o.check(o.call(fnGetDimensions, info, uintptr(unsafe.Pointer(&shape[0])), dims)); err != nil {+ return output{}, err+ }+ }+ var count uintptr+ if err := o.check(o.call(fnGetTensorShapeElementCount, info, uintptr(unsafe.Pointer(&count)))); err != nil {+ return output{}, err+ }+ var p uintptr+ if err := o.check(o.call(fnGetTensorMutableData, v, uintptr(unsafe.Pointer(&p)))); err != nil {+ return output{}, err+ }+ data := make([]float32, count)+ if count > 0 && p != 0 {+ copy(data, unsafe.Slice((*float32)(cptr(p)), count))+ }+ return output{data: data, shape: shape}, nil+}diff --git a/webbrain-systray/internal/d1/ortlib_unix.go b/webbrain-systray/internal/d1/ortlib_unix.gonew file mode 100644index 000000000..34725a1a3--- /dev/null+++ b/webbrain-systray/internal/d1/ortlib_unix.go@@ -0,0 +1,13 @@+//go:build darwin || linux++package d1++import "github.com/ebitengine/purego"++func openSymbol(lib, name string) (uintptr, error) {+ h, err := purego.Dlopen(lib, purego.RTLD_NOW|purego.RTLD_LOCAL)+ if err != nil {+ return 0, err+ }+ return purego.Dlsym(h, name)+}diff --git a/webbrain-systray/internal/d1/ortlib_windows.go b/webbrain-systray/internal/d1/ortlib_windows.gonew file mode 100644index 000000000..f669cdc81--- /dev/null+++ b/webbrain-systray/internal/d1/ortlib_windows.go@@ -0,0 +1,15 @@+//go:build windows++package d1++import "golang.org/x/sys/windows"++func openSymbol(lib, name string) (uintptr, error) {+ // Load by full path, resolving its dependencies next to it, so the older+ // onnxruntime.dll that Windows ships in System32 is never picked up.+ h, err := windows.LoadLibraryEx(lib, 0, windows.LOAD_WITH_ALTERED_SEARCH_PATH)+ if err != nil {+ return 0, err+ }+ return windows.GetProcAddress(h, name)+}diff --git a/webbrain-systray/internal/d1/preprocess.go b/webbrain-systray/internal/d1/preprocess.gonew file mode 100644index 000000000..6e1c7f567--- /dev/null+++ b/webbrain-systray/internal/d1/preprocess.go@@ -0,0 +1,566 @@+package d1++// Port of WebBrain's d1-preprocess.js (the package's FP32 adapter helper):+// prompt rendering, token budgets, temperatures and the exact image+// pipeline (Torch-style fixed-point antialias resize, 16×16 patches,+// interpolated position matrices).++import (+ "bytes"+ "encoding/base64"+ "errors"+ "fmt"+ "image"+ "image/color"+ "image/draw"+ _ "image/jpeg"+ _ "image/png"+ "math"+ "regexp"+ "strings"++ _ "golang.org/x/image/webp"+)++type Question struct {+ ID string+ Type string+ Instructions string+ Criteria *Value+}++var specialRe = regexp.MustCompile(`<\|([A-Za-z0-9_]+)\|>`)++// escapeSpecial neutralises special-token spellings inside user text.+func escapeSpecial(s string) string {+ return specialRe.ReplaceAllString(s, "<¦$1¦>")+}++func criterion(v *Value) (string, error) {+ if v != nil && v.K == kStr {+ return v.S, nil+ }+ return pyJSON(v)+}++// empty mirrors JS `v == null || v === ”`.+func emptyCrit(v *Value) bool {+ return v == nil || v.K == kNull || (v.K == kStr && v.S == "")+}++func renderOptions(q Question, image bool) ([]string, error) {+ switch q.Type {+ case "choice":+ var out []string+ for _, k := range q.Criteria.Keys {+ v := q.Criteria.M[k]+ if emptyCrit(v) {+ out = append(out, k)+ continue+ }+ c, err := criterion(v)+ if err != nil {+ return nil, err+ }+ out = append(out, k+": "+c)+ }+ return out, nil+ case "score":+ var out []string+ for i, v := range q.Criteria.A {+ c, err := criterion(v)+ if err != nil {+ return nil, err+ }+ out = append(out, fmt.Sprintf("level %d: %s", i, c))+ }+ return out, nil+ }+ // noul+ c := q.Criteria+ if c == nil || c.K != kObj || len(c.Keys) == 0 {+ if image {+ c = &Value{K: kObj, Keys: []string{"false", "true"}, M: map[string]*Value{+ "false": {K: kStr, S: "no"}, "true": {K: kStr, S: "yes"}}}+ } else {+ c = &Value{K: kObj, M: map[string]*Value{}}+ }+ }+ var no, yes *Value+ if c.Has("false") {+ no = c.Get("false")+ } else {+ no = c.Get("no")+ }+ if c.Has("true") {+ yes = c.Get("true")+ } else {+ yes = c.Get("yes")+ }+ noText, yesText := "no, the statement does not hold", "yes, the statement holds"+ if !emptyCrit(no) {+ s, err := criterion(no)+ if err != nil {+ return nil, err+ }+ noText = s+ }+ if !emptyCrit(yes) {+ s, err := criterion(yes)+ if err != nil {+ return nil, err+ }+ yesText = s+ }+ return []string{"false: " + noText, "true: " + yesText}, nil+}++func validateQuestion(q Question) error {+ switch q.Type {+ case "choice", "noul", "score":+ default:+ return errors.New("Invalid question type or instructions")+ }+ if q.Type == "choice" && (q.Criteria == nil || q.Criteria.K != kObj || len(q.Criteria.Keys) < 2) {+ return errors.New("A choice requires at least two named criteria")+ }+ if q.Type == "score" && (q.Criteria == nil || q.Criteria.K != kArr || len(q.Criteria.A) < 2 || len(q.Criteria.A) > 10) {+ return errors.New("A score requires 2 to 10 levels")+ }+ if q.Type == "noul" && q.Criteria != nil && q.Criteria.K != kNull && q.Criteria.K != kObj {+ return errors.New("noul criteria must be an object")+ }+ return nil+}++type encoded struct {+ ids []int+ markers []int+}++func clampSlice(ids []int, n int) []int {+ if n < 0 {+ n = 0+ }+ if len(ids) > n {+ return ids[:n]+ }+ return ids+}++// encode builds one question row: BOS, state, question, option markers.+func encode(t *Tokenizer, state string, q Question, maxLen int, image bool) (encoded, error) {+ if err := validateQuestion(q); err != nil {+ return encoded{}, err+ }+ enc := func(s string) []int { return t.Encode(escapeSpecial(s)) }+ options, err := renderOptions(q, image)+ if err != nil {+ return encoded{}, err+ }+ n := len(options)+ budget := max(96, min(n*24+32, maxLen/2))+ per := max(2, int(math.Floor(float64(budget-3*n)/float64(n))))+ question := append([]int{t.ID("<|reserved_8|>")}, enc(q.Instructions)...)+ question = clampSlice(question, max(16, budget))+ question = append([]int(nil), question...)+ var markers []int+ for _, opt := range options {+ markers = append(markers, len(question)+1)+ question = append(question, t.ID("<|reserved_9|>"), t.ID("<|mask|>"))+ question = append(question, clampSlice(enc(" "+opt), per)...)+ question = append(question, t.ID("<|reserved_10|>"))+ }+ question = append(question, t.ID("<|reserved_11|>"))+ room := max(0, maxLen-len(question)-2)+ stateIDs := append([]int{t.ID("<|reserved_7|>")}, clampSlice(enc(state), room)...)+ ids := append([]int{t.BosID}, stateIDs...)+ ids = append(ids, question...)+ ids = clampSlice(ids, maxLen)+ pos := make([]int, len(markers))+ for i, m := range markers {+ pos[i] = m + 1 + len(stateIDs)+ }+ if len(pos) > 0 && pos[len(pos)-1] >= maxLen {+ return encoded{}, errors.New("Options do not fit in context")+ }+ return encoded{ids: ids, markers: pos}, nil+}++func questionTemperature(q Question, temps map[string]float64, image bool) float32 {+ if image {+ return 1+ }+ n := 2+ if q.Type != "noul" {+ n = q.Criteria.Len()+ }+ bucket := "11+"+ switch {+ case n <= 2:+ bucket = "2"+ case n <= 5:+ bucket = "3-5"+ case n <= 10:+ bucket = "6-10"+ }+ if v, ok := temps[q.Type+":"+bucket]; ok {+ return float32(v)+ }+ if v, ok := temps[q.Type]; ok {+ return float32(v)+ }+ return 1+}++// --- images -------------------------------------------------------------------++func roundEven(x float64) float64 {+ n := math.Floor(x)+ if x-n == 0.5 {+ return n + math.Mod(n, 2)+ }+ return math.Floor(x + 0.5) // JS Math.round+}++type imagePlan struct {+ Grid [2]int `json:"grid"`+ Thumbnail [2]int `json:"thumbnail"` // h, w+ Tiled bool `json:"tiled"`+}++func layout(width, height int, ratios [][2]int) (imagePlan, error) {+ if min(width, height) < 1 {+ return imagePlan{}, errors.New("Empty image")+ }+ W, H := float64(width), float64(height)+ h := math.Max(32, roundEven(H/32)*32)+ w := math.Max(32, roundEven(W/32)*32)+ if h*w > 262144 {+ beta := math.Sqrt(H * W / 262144)+ h = math.Max(32, math.Floor(H/beta/32)*32)+ w = math.Max(32, math.Floor(W/beta/32)*32)+ } else if h*w < 65536 {+ beta := math.Sqrt(65536 / (H * W))+ h = math.Ceil(H*beta/32) * 32+ w = math.Ceil(W*beta/32) * 32+ }+ tiled := math.Max(16, roundEven(H/32)*32)*math.Max(16, roundEven(W/32)*32) > 524288+ plan := imagePlan{Grid: [2]int{1, 1}, Thumbnail: [2]int{int(h), int(w)}, Tiled: tiled}+ if tiled {+ best := math.Inf(1)+ for _, r := range ratios {+ diff := math.Abs(W/H - float64(r[0])/float64(r[1]))+ if diff < best || (diff == best && W*H > 0.5*512*512*float64(r[0])*float64(r[1])) {+ plan.Grid = r+ best = diff+ }+ }+ }+ return plan, nil+}++type weightRow struct {+ start int+ weights []int64+}++func resizeWeights(input, output int) ([]weightRow, int64) {+ scale := float64(input) / float64(output)+ support := math.Max(1, scale)+ rows := make([]weightRow, output)+ largest := 0.0+ fw := make([][]float64, output)+ for i := 0; i < output; i++ {+ center := scale * (float64(i) + 0.5)+ start := max(0, int(math.Trunc(center-support+0.5)))+ end := min(input, int(math.Trunc(center+support+0.5)))+ ws := make([]float64, end-start)+ total := 0.0+ for j := range ws {+ ws[j] = math.Max(0, 1-math.Abs((float64(j+start)-center+0.5)/support))+ total += ws[j]+ }+ for j := range ws {+ ws[j] /= total+ largest = math.Max(largest, ws[j])+ }+ fw[i] = ws+ rows[i].start = start+ }+ precision := 0+ for ; precision < 22; precision++ {+ if math.Trunc(0.5+largest*math.Pow(2, float64(precision+1))) >= 32768 {+ break+ }+ }+ unit := math.Pow(2, float64(precision))+ for i := range rows {+ rows[i].weights = make([]int64, len(fw[i]))+ for j, w := range fw[i] {+ rows[i].weights[j] = int64(math.Trunc(0.5 + w*unit))+ }+ }+ return rows, int64(unit)+}++// resizeRGB is Torch's uint8 antialias bilinear resize (two rounded passes).+func resizeRGB(rgb []byte, width, height, newWidth, newHeight int) []byte {+ temp := rgb+ if width != newWidth {+ rows, unit := resizeWeights(width, newWidth)+ temp = make([]byte, newWidth*height*3)+ for y := 0; y < height; y++ {+ for x := 0; x < newWidth; x++ {+ row := rows[x]+ for c := 0; c < 3; c++ {+ sum := unit / 2+ for j, w := range row.weights {+ sum += int64(rgb[(y*width+row.start+j)*3+c]) * w+ }+ temp[(y*newWidth+x)*3+c] = clamp8(floorDiv(sum, unit))+ }+ }+ }+ }+ if height == newHeight {+ return temp+ }+ rows, unit := resizeWeights(height, newHeight)+ out := make([]byte, newWidth*newHeight*3)+ for y := 0; y < newHeight; y++ {+ row := rows[y]+ for x := 0; x < newWidth; x++ {+ for c := 0; c < 3; c++ {+ sum := unit / 2+ for j, w := range row.weights {+ sum += int64(temp[((row.start+j)*newWidth+x)*3+c]) * w+ }+ out[(y*newWidth+x)*3+c] = clamp8(floorDiv(sum, unit))+ }+ }+ }+ return out+}++func floorDiv(a, b int64) int64 {+ q := a / b+ if (a%b != 0) && ((a < 0) != (b < 0)) {+ q--+ }+ return q+}++func clamp8(v int64) byte {+ if v < 0 {+ return 0+ }+ if v > 255 {+ return 255+ }+ return byte(v)+}++var dataURLRe = regexp.MustCompile(`^data:image/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$`)++// decodeRGB decodes an inline image to 8-bit RGB the way a canvas read-back+// does (no colour management; alpha un-premultiplied).+func decodeRGB(url string) ([]byte, int, int, error) {+ if !dataURLRe.MatchString(url) {+ return nil, 0, 0, errors.New("D1 accepts at most four inline PNG/JPEG/WebP screenshots; remote image URLs are not allowed.")+ }+ raw, err := base64.StdEncoding.DecodeString(url[strings.Index(url, ",")+1:])+ if err != nil {+ return nil, 0, 0, fmt.Errorf("invalid base64 image: %w", err)+ }+ cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))+ if err != nil {+ return nil, 0, 0, fmt.Errorf("could not decode image: %w", err)+ }+ if err := checkImageSize(cfg.Width, cfg.Height); err != nil {+ return nil, 0, 0, err+ }+ img, _, err := image.Decode(bytes.NewReader(raw))+ if err != nil {+ return nil, 0, 0, fmt.Errorf("could not decode image: %w", err)+ }+ b := img.Bounds()+ w, h := b.Dx(), b.Dy()+ if err := checkImageSize(w, h); err != nil {+ return nil, 0, 0, err+ }+ rgb := make([]byte, w*h*3)+ switch src := img.(type) {+ case *image.NRGBA:+ for y := 0; y < h; y++ {+ for x := 0; x < w; x++ {+ i := src.PixOffset(b.Min.X+x, b.Min.Y+y)+ r, g, bl, a := src.Pix[i], src.Pix[i+1], src.Pix[i+2], src.Pix[i+3]+ o := (y*w + x) * 3+ rgb[o], rgb[o+1], rgb[o+2] = unpremul(r, a), unpremul(g, a), unpremul(bl, a)+ }+ }+ default:+ nrgba := image.NewNRGBA(image.Rect(0, 0, w, h))+ draw.Draw(nrgba, nrgba.Bounds(), img, b.Min, draw.Src)+ for y := 0; y < h; y++ {+ for x := 0; x < w; x++ {+ c := nrgba.NRGBAAt(x, y)+ o := (y*w + x) * 3+ rgb[o], rgb[o+1], rgb[o+2] = unpremul(c.R, c.A), unpremul(c.G, c.A), unpremul(c.B, c.A)+ }+ }+ }+ _ = color.NRGBA{}+ return rgb, w, h, nil+}++func checkImageSize(width, height int) error {+ if width < 1 || height < 1 {+ return errors.New("Empty image")+ }+ // Division keeps malformed dimensions from overflowing the pixel count.+ if width > 40_000_000/height {+ return errors.New("image is too large")+ }+ return nil+}++// unpremul models a canvas round-trip through premultiplied storage.+func unpremul(c, a uint8) uint8 {+ switch a {+ case 255:+ return c+ case 0:+ return 0+ }+ pm := (uint32(c)*uint32(a) + 127) / 255+ v := (pm*255 + uint32(a)/2) / uint32(a)+ if v > 255 {+ v = 255+ }+ return uint8(v)+}++type imageInput struct {+ plan imagePlan+ pixels []float32+ mask []bool+ shapes [][2]int // patch grid (h, w) per crop+}++func imageInputs(url string, ratios [][2]int) (imageInput, error) {+ rgb, width, height, err := decodeRGB(url)+ if err != nil {+ return imageInput{}, err+ }+ plan, err := layout(width, height, ratios)+ if err != nil {+ return imageInput{}, err+ }+ th, tw := plan.Thumbnail[0], plan.Thumbnail[1]+ // Extreme aspect ratios can exceed the patch budget after the minimum+ // thumbnail dimension is applied. Reject them before resizing or packing.+ if th < 16 || tw < 16 || th/16 > patches/(tw/16) {+ return imageInput{}, errors.New("image aspect ratio exceeds the model's patch limit")+ }+ type crop struct {+ rgb []byte+ h, w int+ }+ var crops []crop+ if plan.Tiled {+ gw, gh := plan.Grid[0], plan.Grid[1]+ big := resizeRGB(rgb, width, height, gw*512, gh*512)+ for r := 0; r < gh; r++ {+ for c := 0; c < gw; c++ {+ px := make([]byte, 512*512*3)+ for y := 0; y < 512; y++ {+ src := ((r*512+y)*gw*512 + c*512) * 3+ copy(px[y*512*3:(y+1)*512*3], big[src:src+512*3])+ }+ crops = append(crops, crop{px, 512, 512})+ }+ }+ }+ crops = append(crops, crop{resizeRGB(rgb, width, height, tw, th), th, tw})+ in := imageInput{plan: plan, pixels: make([]float32, len(crops)*1024*768), mask: make([]bool, len(crops)*1024)}+ for i, cr := range crops {+ ph, pw := cr.h/16, cr.w/16+ in.shapes = append(in.shapes, [2]int{ph, pw})+ for k := 0; k < ph*pw; k++ {+ in.mask[i*1024+k] = true+ }+ for r := 0; r < ph; r++ {+ for c := 0; c < pw; c++ {+ base := (i*1024 + r*pw + c) * 768+ for y := 0; y < 16; y++ {+ for x := 0; x < 16; x++ {+ src := ((r*16+y)*cr.w + c*16 + x) * 3+ dst := base + (y*16+x)*3+ for ch := 0; ch < 3; ch++ {+ v := float64(cr.rgb[src+ch])+ in.pixels[dst+ch] = float32(float64(float32(v-127.5)) / 127.5)+ }+ }+ }+ }+ }+ }+ return in, nil+}++// positionMatrix interpolates the 16×16 learned position grid to h×w patches+// (float32 arithmetic, as the adapter's Math.fround chain).+func positionMatrix(h, w int) []float32 {+ matrix := make([]float32, 1024*256)+ type wv struct {+ j int+ v float32+ }+ weights := func(input, output int) [][]wv {+ out := make([][]wv, output)+ for i := 0; i < output; i++ {+ scale := float32(float64(input) / float64(output))+ support := float32(math.Max(1, float64(scale)))+ center := float32(float64(scale) * float64(float32(float64(i)+0.5)))+ start := max(0, int(math.Trunc(float64(float32(float64(float32(float64(center)-float64(support)))+0.5)))))+ end := min(input, int(math.Trunc(float64(float32(float64(float32(float64(center)+float64(support)))+0.5)))))+ inv := float32(1)+ if scale >= 1 {+ inv = float32(1 / float64(scale))+ }+ var a []wv+ sum := float32(0)+ for j := start; j < end; j++ {+ d := float32(float64(j) - float64(center))+ d = float32(float64(d) + 0.5)+ d = float32(float64(d) * float64(inv))+ v := float32(1 - math.Abs(float64(d)))+ v = float32(math.Max(0, float64(v)))+ a = append(a, wv{j, v})+ sum = float32(float64(sum) + float64(v))+ }+ for k := range a {+ a[k].v = float32(float64(a[k].v) / float64(sum))+ }+ out[i] = a+ }+ return out+ }+ wy, wx := weights(16, h), weights(16, w)+ for y := 0; y < h; y++ {+ for x := 0; x < w; x++ {+ row := (y*w + x) * 256+ for _, a := range wy[y] {+ for _, b := range wx[x] {+ matrix[row+a.j*16+b.j] = float32(float64(a.v) * float64(b.v))+ }+ }+ }+ }+ for i := h * w; i < 1024; i++ {+ copy(matrix[i*256:(i+1)*256], matrix[0:256])+ }+ return matrix+}diff --git a/webbrain-systray/internal/d1/preprocess_test.go b/webbrain-systray/internal/d1/preprocess_test.gonew file mode 100644index 000000000..5ad520002--- /dev/null+++ b/webbrain-systray/internal/d1/preprocess_test.go@@ -0,0 +1,80 @@+package d1++import (+ "bytes"+ "encoding/base64"+ "encoding/binary"+ "fmt"+ "hash/crc32"+ "image"+ "image/color"+ "image/png"+ "testing"+)++func TestDecodeRGBRejectsOversizedHeaderBeforePixels(t *testing.T) {+ // A valid IHDR with no pixel stream: rejection must happen from dimensions,+ // before the decoder attempts to allocate or read the oversized image.+ raw := make([]byte, 33)+ copy(raw, "\x89PNG\r\n\x1a\n")+ binary.BigEndian.PutUint32(raw[8:12], 13)+ copy(raw[12:16], "IHDR")+ binary.BigEndian.PutUint32(raw[16:20], 100_000)+ binary.BigEndian.PutUint32(raw[20:24], 100_000)+ raw[24], raw[25] = 8, 2+ binary.BigEndian.PutUint32(raw[29:33], crc32.ChecksumIEEE(raw[12:29]))+ url := "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)+ if _, _, _, err := decodeRGB(url); err == nil || err.Error() != "image is too large" {+ t.Fatalf("decodeRGB oversized header: got %v, want image is too large", err)+ }+}++func TestDecodeRGBValidPNG(t *testing.T) {+ img := image.NewNRGBA(image.Rect(0, 0, 2, 1))+ img.SetNRGBA(0, 0, color.NRGBA{R: 12, G: 34, B: 56, A: 255})+ img.SetNRGBA(1, 0, color.NRGBA{R: 78, G: 90, B: 123, A: 255})+ var encoded bytes.Buffer+ if err := png.Encode(&encoded, img); err != nil {+ t.Fatal(err)+ }+ url := "data:image/png;base64," + base64.StdEncoding.EncodeToString(encoded.Bytes())+ rgb, width, height, err := decodeRGB(url)+ if err != nil {+ t.Fatal(err)+ }+ if width != 2 || height != 1 || !bytes.Equal(rgb, []byte{12, 34, 56, 78, 90, 123}) {+ t.Fatalf("decodeRGB: got %dx%d %v", width, height, rgb)+ }+}++func TestImageInputsRejectsExtremeAspectRatio(t *testing.T) {+ for _, size := range [][2]int{{10_000, 1}, {1, 10_000}} {+ t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) {+ img := image.NewGray(image.Rect(0, 0, size[0], size[1]))+ var encoded bytes.Buffer+ if err := png.Encode(&encoded, img); err != nil {+ t.Fatal(err)+ }+ url := "data:image/png;base64," + base64.StdEncoding.EncodeToString(encoded.Bytes())+ if _, err := imageInputs(url, nil); err == nil || err.Error() != "image aspect ratio exceeds the model's patch limit" {+ t.Fatalf("imageInputs extreme aspect ratio: got %v, want patch limit error", err)+ }+ })+ }+}++func TestImageInputsAcceptsNormalImage(t *testing.T) {+ img := image.NewGray(image.Rect(0, 0, 512, 512))+ var encoded bytes.Buffer+ if err := png.Encode(&encoded, img); err != nil {+ t.Fatal(err)+ }+ url := "data:image/png;base64," + base64.StdEncoding.EncodeToString(encoded.Bytes())+ input, err := imageInputs(url, nil)+ if err != nil {+ t.Fatal(err)+ }+ if len(input.shapes) != 1 || input.shapes[0] != [2]int{32, 32} || len(input.mask) != patches {+ t.Fatalf("unexpected image input shapes %v, mask size %d", input.shapes, len(input.mask))+ }+}diff --git a/webbrain-systray/internal/d1/runtime.go b/webbrain-systray/internal/d1/runtime.gonew file mode 100644index 000000000..da79b60a6--- /dev/null+++ b/webbrain-systray/internal/d1/runtime.go@@ -0,0 +1,475 @@+package d1++// Port of WebBrain's d1-runtime.js evaluate(): split state and screenshots,+// encode the media prefix with the vision tower + projector, then score every+// question's options in padded batches with the decision graph.++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "math"+ "os"+ "path/filepath"+ "sort"+ "strconv"+ "time"+)++const (+ attentionHeads = 16+ visionHeads = 12+ patches = 1024+ hiddenWidth = 768+ prefixWidth = 1024+ sourceBatchTokens = 65536+ attentionBudgetBytes = 512 << 20+ // Text-only rows are capped on the CPU runtime: dense attention memory+ // grows with the square of the row length. Longer states are truncated+ // (the question is never truncated), as the browser runtime does.+ cpuMaxTextTokens = 4096+)++type modelConfig struct {+ MaxLength int `json:"max_length"`+ ImageTextLength int `json:"image_text_length"`+ Temperatures map[string]float64 `json:"temperatures"`+ PadTokenID int `json:"pad_token_id"`+}++type engine struct {+ ort *ortLib+ tok *Tokenizer+ cfg modelConfig+ ratios [][2]int+ decision *session+ vision *session+ projector *session+}++func loadEngine(dir, libPath string, threads int) (*engine, error) {+ o, err := loadORT(libPath)+ if err != nil {+ return nil, fmt.Errorf("load ONNX Runtime: %w", err)+ }+ e := &engine{ort: o}+ raw, err := os.ReadFile(filepath.Join(dir, "config.json"))+ if err != nil {+ return nil, err+ }+ if err := json.Unmarshal(raw, &e.cfg); err != nil {+ return nil, fmt.Errorf("config.json: %w", err)+ }+ if e.cfg.MaxLength == 0 {+ e.cfg.MaxLength = 16384+ }+ if e.cfg.ImageTextLength == 0 {+ e.cfg.ImageTextLength = 896+ }+ rr, err := os.ReadFile(filepath.Join(dir, "tiling-ratios.json"))+ if err != nil {+ return nil, err+ }+ var ratios [][]int+ if err := json.Unmarshal(rr, &ratios); err != nil {+ return nil, fmt.Errorf("tiling-ratios.json: %w", err)+ }+ for _, r := range ratios {+ if len(r) == 2 {+ e.ratios = append(e.ratios, [2]int{r[0], r[1]})+ }+ }+ if e.tok, err = LoadTokenizer(filepath.Join(dir, "tokenizer.json")); err != nil {+ return nil, err+ }+ for _, s := range []struct {+ name string+ dst **session+ }{{"decision", &e.decision}, {"vision", &e.vision}, {"projector", &e.projector}} {+ sess, err := o.newSession(filepath.Join(dir, "onnx", s.name+".onnx"), threads)+ if err != nil {+ e.close()+ return nil, fmt.Errorf("%s graph: %w", s.name, err)+ }+ *s.dst = sess+ }+ return e, nil+}++func (e *engine) close() {+ e.decision.release()+ e.vision.release()+ e.projector.release()+}++var imageURLRe = dataURLRe++type request struct {+ stateText string+ images []string+ questions []Question+}++// parseRequest validates {state, images, questions} like the adapter does.+func parseRequest(body []byte) (request, error) {+ root, err := ParseJSON(body)+ if err != nil {+ return request{}, fmt.Errorf("invalid JSON: %w", err)+ }+ if root.K != kObj {+ return request{}, errors.New("request must be a JSON object")+ }+ var req request+ var media []string+ if imgs := root.Get("images"); !imgs.IsNull() {+ if imgs.K != kArr {+ return req, errors.New("images must be an array of data URLs")+ }+ for _, v := range imgs.A {+ if v.K != kStr {+ return req, errors.New("D1 accepts at most four inline PNG/JPEG/WebP screenshots; remote image URLs are not allowed.")+ }+ media = append(media, v.S)+ }+ }+ state := root.Get("state")+ var text *Value+ switch {+ case state.IsNull():+ text = &Value{K: kStr, S: ""}+ case state.K == kArr:+ kept := &Value{K: kArr, A: []*Value{}}+ for _, part := range state.A {+ if part.K == kObj && part.Get("type") != nil && part.Get("type").K == kStr && part.Get("type").S == "image_url" {+ u := part.Get("image_url").Get("url")+ if u == nil || u.K != kStr {+ return req, errors.New("D1 accepts at most four inline PNG/JPEG/WebP screenshots; remote image URLs are not allowed.")+ }+ media = append(media, u.S)+ continue+ }+ kept.A = append(kept.A, part)+ }+ text = kept+ if len(kept.A) == 0 {+ text = &Value{K: kStr, S: ""}+ }+ default:+ text = state+ }+ if len(media) > 4 {+ return req, errors.New("D1 accepts at most four inline PNG/JPEG/WebP screenshots; remote image URLs are not allowed.")+ }+ for _, u := range media {+ if !imageURLRe.MatchString(u) {+ return req, errors.New("D1 accepts at most four inline PNG/JPEG/WebP screenshots; remote image URLs are not allowed.")+ }+ }+ size := len(jsStringify(text))+ for _, u := range media {+ size += len(u) + 3+ }+ if size > 8*1024*1024 {+ return req, errors.New("D1 input exceeds 8 MiB.")+ }+ if text.K == kStr {+ req.stateText = text.S+ } else if req.stateText, err = pyJSON(text); err != nil {+ return req, err+ }+ req.images = media++ qs := root.Get("questions")+ if qs == nil || qs.K != kObj || len(qs.Keys) == 0 || len(qs.Keys) > 32 {+ return req, errors.New("D1 requires 1 to 32 named questions.")+ }+ for _, id := range qs.Keys {+ q := qs.M[id]+ if q == nil || q.K != kObj {+ return req, errors.New("Invalid question type or instructions")+ }+ t, ins := q.Get("type"), q.Get("instructions")+ if t == nil || t.K != kStr || ins == nil || ins.K != kStr {+ return req, errors.New("Invalid question type or instructions")+ }+ qq := Question{ID: id, Type: t.S, Instructions: ins.S, Criteria: q.Get("criteria")}+ if err := validateQuestion(qq); err != nil {+ return req, err+ }+ req.questions = append(req.questions, qq)+ }+ return req, nil+}++type row struct {+ ids []int+ markers []int+}++type batchInfo struct {+ QuestionIDs []string `json:"question_ids"`+ Batch int `json:"batch"`+ TextLength int `json:"text_length"`+ Options int `json:"options"`+}++func attentionBytes(rows, length int) int64 {+ return int64(rows) * attentionHeads * int64(length) * int64(length) * 4+}++// rowBatches groups rows longest-first under the token and attention budgets.+func rowBatches(rows []row, mediaLength int) [][]int {+ order := make([]int, len(rows))+ for i := range order {+ order[i] = i+ }+ sort.SliceStable(order, func(a, b int) bool { return len(rows[order[a]].ids) > len(rows[order[b]].ids) })+ var batches [][]int+ for len(order) > 0 {+ longest := len(rows[order[0]].ids) + mediaLength+ size := 1+ for size < len(order) && (size+1)*longest <= sourceBatchTokens && attentionBytes(size+1, longest) <= attentionBudgetBytes {+ size+++ }+ batches = append(batches, append([]int(nil), order[:size]...))+ order = order[size:]+ }+ return batches+}++type layoutInfo struct {+ imagePlan+ Shapes [][2]int `json:"shapes"`+}++// mediaPrefix encodes screenshots into the decision graph's media prefix.+func (e *engine) mediaPrefix(ctx context.Context, images []string) ([]float32, []layoutInfo, error) {+ var prefix []float32+ var layouts []layoutInfo+ group := max(1, int(attentionBudgetBytes/(visionHeads*patches*patches*4)))+ for _, url := range images {+ if err := ctx.Err(); err != nil {+ return nil, nil, err+ }+ img, err := imageInputs(url, e.ratios)+ if err != nil {+ return nil, nil, err+ }+ crops := len(img.shapes)+ for start := 0; start < crops; start += group {+ end := min(crops, start+group)+ n := end - start+ pos := make([]float32, n*patches*256)+ for i := 0; i < n; i++ {+ s := img.shapes[start+i]+ copy(pos[i*patches*256:], positionMatrix(s[0], s[1]))+ }+ out, err := e.vision.run(map[string]tensor{+ "pixel_values": floatTensor(img.pixels[start*patches*hiddenWidth:end*patches*hiddenWidth], int64(n), patches, hiddenWidth),+ "pixel_mask": boolTensor(img.mask[start*patches:end*patches], int64(n), patches),+ "position_matrix": floatTensor(pos, int64(n), patches, 256),+ }, "hidden")+ if err != nil {+ return nil, nil, fmt.Errorf("vision: %w", err)+ }+ hidden := out["hidden"].data+ for i := 0; i < n; i++ {+ s := img.shapes[start+i]+ h, w := s[0], s[1]+ chunk := hidden[i*patches*hiddenWidth : i*patches*hiddenWidth+h*w*hiddenWidth]+ proj, err := e.projector.run(map[string]tensor{+ "hidden": floatTensor(chunk, 1, int64(h), int64(w), hiddenWidth),+ }, "prefix")+ if err != nil {+ return nil, nil, fmt.Errorf("projector: %w", err)+ }+ prefix = append(prefix, proj["prefix"].data...)+ }+ }+ layouts = append(layouts, layoutInfo{imagePlan: img.plan, Shapes: img.shapes})+ }+ return prefix, layouts, nil+}++func (e *engine) evaluate(ctx context.Context, req request, model string) (*ordered, error) {+ start := time.Now()+ prefix, layouts, err := e.mediaPrefix(ctx, req.images)+ if err != nil {+ return nil, err+ }+ if len(prefix)%prefixWidth != 0 {+ return nil, errors.New("D1 media exceed the source context budget.")+ }+ mediaLength := len(prefix) / prefixWidth+ hasImages := len(req.images) > 0+ textCap := min(e.cfg.MaxLength, cpuMaxTextTokens)+ if hasImages {+ textCap = e.cfg.ImageTextLength+ }+ limit := min(textCap, e.cfg.MaxLength-mediaLength)+ if limit < 64 {+ return nil, errors.New("D1 media exceed the source context budget.")+ }+ rows := make([]row, len(req.questions))+ for i, q := range req.questions {+ enc, err := encode(e.tok, req.stateText, q, limit, hasImages)+ if err != nil {+ return nil, err+ }+ rows[i] = row{ids: enc.ids, markers: enc.markers}+ }+ answers := map[string]any{}+ var batches []batchInfo+ for _, idx := range rowBatches(rows, mediaLength) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ batch := len(idx)+ length, width := 0, 0+ for _, i := range idx {+ length = max(length, len(rows[i].ids))+ width = max(width, len(rows[i].markers))+ }+ ids := make([]int64, batch*length)+ mask := make([]bool, batch*length)+ markers := make([]int64, batch*width)+ markerMask := make([]bool, batch*width)+ qtype := make([]int64, batch)+ temps := make([]float32, batch)+ media := make([]float32, batch*len(prefix))+ pad := int64(e.tok.PadID)+ if pad < 0 {+ pad = 0+ }+ for k := range ids {+ ids[k] = pad+ }+ for b, i := range idx {+ r := rows[i]+ for k, id := range r.ids {+ ids[b*length+k] = int64(id)+ mask[b*length+k] = true+ }+ for k, m := range r.markers {+ markers[b*width+k] = int64(m)+ markerMask[b*width+k] = true+ }+ q := req.questions[i]+ qtype[b] = map[string]int64{"choice": 0, "score": 1, "noul": 2}[q.Type]+ temps[b] = questionTemperature(q, e.cfg.Temperatures, hasImages)+ copy(media[b*len(prefix):], prefix)+ }+ out, err := e.decision.run(map[string]tensor{+ "input_ids": int64Tensor(ids, int64(batch), int64(length)),+ "text_mask": boolTensor(mask, int64(batch), int64(length)),+ "marker_pos": int64Tensor(markers, int64(batch), int64(width)),+ "marker_mask": boolTensor(markerMask, int64(batch), int64(width)),+ "qtype": int64Tensor(qtype, int64(batch)),+ "temperature": floatTensor(temps, int64(batch)),+ "media_prefix": floatTensor(media, int64(batch), int64(mediaLength), prefixWidth),+ }, "probabilities")+ if err != nil {+ return nil, fmt.Errorf("decision: %w", err)+ }+ probs := out["probabilities"].data+ var qids []string+ for b, i := range idx {+ q := req.questions[i]+ ans, err := answerFor(q, probs[b*width:(b+1)*width])+ if err != nil {+ return nil, err+ }+ answers[q.ID] = ans+ qids = append(qids, q.ID)+ }+ batches = append(batches, batchInfo{QuestionIDs: qids, Batch: batch, TextLength: length, Options: width})+ }+ ordAnswers := newOrdered()+ inputTokens, textLength := 0, 0+ for i, q := range req.questions {+ ordAnswers.Set(q.ID, answers[q.ID])+ inputTokens += len(rows[i].ids) + mediaLength+ textLength = max(textLength, len(rows[i].ids))+ }+ if layouts == nil {+ layouts = []layoutInfo{}+ }+ res := newOrdered().+ Set("model", model).+ Set("provider", Provider).+ Set("answers", ordAnswers).+ Set("usage", newOrdered().Set("input_tokens", inputTokens).Set("output_tokens", 0)).+ Set("diagnostics", newOrdered().+ Set("dtype", "float32").+ Set("generated_tokens", 0).+ Set("batch", len(rows)).+ Set("text_length", textLength).+ Set("media_length", mediaLength).+ Set("layouts", layouts).+ Set("batches", batches).+ Set("source_batch_token_budget", sourceBatchTokens).+ Set("text_token_cap", textCap).+ Set("runtime", "onnxruntime "+e.ort.version+" (CPU)").+ Set("latency_ms", math.Round(float64(time.Since(start).Microseconds())/100)/10))+ return res, nil+}++// answerFor mirrors d1Answers for one question row.+func answerFor(q Question, row []float32) (any, error) {+ var names []string+ switch q.Type {+ case "noul":+ names = []string{"no", "yes"}+ case "score":+ for i := range q.Criteria.A {+ names = append(names, strconv.Itoa(i))+ }+ default:+ names = append(names, q.Criteria.Keys...)+ }+ if len(row) < len(names) {+ return nil, errors.New("Invalid D1 probability output.")+ }+ values := make([]float64, len(names))+ sum := 0.0+ for i := range names {+ v := float64(row[i])+ if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 1 {+ return nil, errors.New("Invalid D1 probability output.")+ }+ values[i] = v+ sum += v+ }+ if math.Abs(sum-1) > .001 {+ return nil, errors.New("Invalid D1 probability output.")+ }+ sel := 0+ for i, v := range values {+ if v > values[sel] {+ sel = i+ }+ }+ if q.Type == "noul" {+ return newOrdered().Set("type", "noul").Set("noul", values[1]), nil+ }+ probs := newOrdered()+ for i, n := range names {+ probs.Set(n, values[i])+ }+ ans := newOrdered().Set("type", q.Type).Set("confidence", values[sel]).Set("probabilities", probs)+ if q.Type == "choice" {+ return ans.Set("choice", names[sel]), nil+ }+ score := 0.0+ legend := newOrdered()+ for i, p := range values {+ score += p * float64(i)+ c, err := criterion(q.Criteria.A[i])+ if err != nil {+ return nil, err+ }+ legend.Set(names[i], c)+ }+ return ans.Set("score", score).Set("legend", legend), nil+}diff --git a/webbrain-systray/internal/d1/tokenizer.go b/webbrain-systray/internal/d1/tokenizer.gonew file mode 100644index 000000000..9411f13a5--- /dev/null+++ b/webbrain-systray/internal/d1/tokenizer.go@@ -0,0 +1,320 @@+package d1++// Byte-level BPE matching Hugging Face tokenizers / Transformers.js for the+// d1 (LFM2.5) tokenizer.json: added-token splitting, the Llama-3 style split+// regex, GPT-2 byte mapping and rank-ordered merges.++import (+ "container/heap"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "sort"+ "strings"+ "sync"++ "github.com/dlclark/regexp2"+)++type addedToken struct {+ ID int `json:"id"`+ Content string `json:"content"`+ Special bool `json:"special"`+}++type Tokenizer struct {+ vocab map[string]int+ ranks map[string]int+ added []addedToken // longest first+ addedBy map[string]int+ split *regexp2.Regexp+ byteEnc [256]string+ cacheMu sync.Mutex+ cache map[string][]int+ BosID int+ PadID int+}++// JavaScript's \s (what Transformers.js' RegExp uses), spelled out so the+// .NET-flavoured engine matches the browser exactly.+var jsSpace = jsSpaceClass()++// jsSpaceClass spells JavaScript's \s as regexp escapes (built at run time so+// the source stays ASCII).+func jsSpaceClass() string {+ var b strings.Builder+ b.WriteString(`\t\n\v\f\r `)+ esc := func(cp int) { fmt.Fprintf(&b, "\\%s%04x", "u", cp) }+ for _, cp := range []int{0x00a0, 0x1680} {+ esc(cp)+ }+ esc(0x2000)+ b.WriteByte('-')+ esc(0x200a)+ for _, cp := range []int{0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff} {+ esc(cp)+ }+ return b.String()+}++func bytesToUnicode() [256]string {+ var bs []int+ for b := '!'; b <= '~'; b++ {+ bs = append(bs, int(b))+ }+ for b := 0xA1; b <= 0xAC; b++ {+ bs = append(bs, b)+ }+ for b := 0xAE; b <= 0xFF; b++ {+ bs = append(bs, b)+ }+ cs := append([]int(nil), bs...)+ n := 0+ in := map[int]bool{}+ for _, b := range bs {+ in[b] = true+ }+ for b := 0; b < 256; b++ {+ if !in[b] {+ bs = append(bs, b)+ cs = append(cs, 256+n)+ n+++ }+ }+ var out [256]string+ for i, b := range bs {+ out[b] = string(rune(cs[i]))+ }+ return out+}++// LoadTokenizer reads a tokenizer.json of the d1 family.+func LoadTokenizer(path string) (*Tokenizer, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, err+ }+ var raw struct {+ AddedTokens []addedToken `json:"added_tokens"`+ PreTok struct {+ Type string `json:"type"`+ Pretokenizers []struct {+ Type string `json:"type"`+ Pattern struct {+ Regex string `json:"Regex"`+ } `json:"pattern"`+ } `json:"pretokenizers"`+ } `json:"pre_tokenizer"`+ Model struct {+ Type string `json:"type"`+ Vocab map[string]int `json:"vocab"`+ Merges []json.RawMessage `json:"merges"`+ } `json:"model"`+ }+ if err := json.Unmarshal(data, &raw); err != nil {+ return nil, fmt.Errorf("tokenizer.json: %w", err)+ }+ if raw.Model.Type != "BPE" {+ return nil, fmt.Errorf("unsupported tokenizer model %q", raw.Model.Type)+ }+ t := &Tokenizer{vocab: raw.Model.Vocab, ranks: make(map[string]int, len(raw.Model.Merges)),+ addedBy: map[string]int{}, cache: map[string][]int{}, byteEnc: bytesToUnicode()}+ for i, m := range raw.Model.Merges {+ var pair []string+ if err := json.Unmarshal(m, &pair); err != nil {+ var s string+ if err := json.Unmarshal(m, &s); err != nil {+ return nil, errors.New("bad merge entry")+ }+ pair = strings.SplitN(s, " ", 2)+ }+ if len(pair) != 2 {+ return nil, errors.New("bad merge entry")+ }+ key := pair[0] + "\x00" + pair[1]+ if _, ok := t.ranks[key]; !ok {+ t.ranks[key] = i+ }+ }+ for _, a := range raw.AddedTokens {+ t.added = append(t.added, a)+ t.addedBy[a.Content] = a.ID+ }+ sort.SliceStable(t.added, func(i, j int) bool { return len(t.added[i].Content) > len(t.added[j].Content) })+ pattern := `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\p{L}\p{N}` + jsSpace + `]+[\r\n]*|[` + jsSpace + `]*[\r\n]+|[` + jsSpace + `]+(?![^` + jsSpace + `])|[` + jsSpace + `]+`+ for _, p := range raw.PreTok.Pretokenizers {+ if p.Type == "Split" && p.Pattern.Regex != "" && !strings.Contains(p.Pattern.Regex, `(?i:'s|'t|'re|'ve|'m|'ll|'d)`) {+ return nil, errors.New("unexpected pre-tokenizer pattern")+ }+ }+ t.split, err = regexp2.Compile(pattern, regexp2.Unicode)+ if err != nil {+ return nil, err+ }+ t.split.MatchTimeout = 0+ t.BosID = t.ID("<|startoftext|>")+ t.PadID = t.ID("<|pad|>")+ return t, nil+}++// ID returns a token's id (added tokens first), or -1.+func (t *Tokenizer) ID(token string) int {+ if id, ok := t.addedBy[token]; ok {+ return id+ }+ if id, ok := t.vocab[token]; ok {+ return id+ }+ return -1+}++// Encode tokenizes text without adding special tokens.+func (t *Tokenizer) Encode(text string) []int {+ var out []int+ for len(text) > 0 {+ pos, tok := t.nextAdded(text)+ if pos < 0 {+ out = append(out, t.encodePlain(text)...)+ break+ }+ if pos > 0 {+ out = append(out, t.encodePlain(text[:pos])...)+ }+ out = append(out, tok.ID)+ text = text[pos+len(tok.Content):]+ }+ return out+}++// nextAdded finds the leftmost added token (longest at that position).+func (t *Tokenizer) nextAdded(text string) (int, addedToken) {+ best := -1+ var bestTok addedToken+ for _, a := range t.added {+ i := strings.Index(text, a.Content)+ if i < 0 {+ continue+ }+ if best < 0 || i < best || (i == best && len(a.Content) > len(bestTok.Content)) {+ best, bestTok = i, a+ }+ }+ return best, bestTok+}++func (t *Tokenizer) encodePlain(text string) []int {+ runes := []rune(text)+ var out []int+ last := 0+ m, _ := t.split.FindRunesMatch(runes)+ for m != nil {+ if m.Index > last {+ out = append(out, t.bpeWord(string(runes[last:m.Index]))...)+ }+ out = append(out, t.bpeWord(string(runes[m.Index:m.Index+m.Length]))...)+ last = m.Index + m.Length+ m, _ = t.split.FindNextMatch(m)+ }+ if last < len(runes) {+ out = append(out, t.bpeWord(string(runes[last:]))...)+ }+ return out+}++type mergeCand struct {+ rank, pos int+ left string+ right string+}++type mergeHeap []mergeCand++func (h mergeHeap) Len() int { return len(h) }+func (h mergeHeap) Less(i, j int) bool {+ if h[i].rank != h[j].rank {+ return h[i].rank < h[j].rank+ }+ return h[i].pos < h[j].pos+}+func (h mergeHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }+func (h *mergeHeap) Push(x any) { *h = append(*h, x.(mergeCand)) }+func (h *mergeHeap) Pop() any {+ old := *h+ x := old[len(old)-1]+ *h = old[:len(old)-1]+ return x+}++func (t *Tokenizer) bpeWord(piece string) []int {+ if piece == "" {+ return nil+ }+ t.cacheMu.Lock()+ if ids, ok := t.cache[piece]; ok {+ t.cacheMu.Unlock()+ return ids+ }+ t.cacheMu.Unlock()++ syms := make([]string, 0, len(piece))+ for i := 0; i < len(piece); i++ {+ syms = append(syms, t.byteEnc[piece[i]])+ }+ // Linked list over symbol slots.+ n := len(syms)+ prev := make([]int, n)+ next := make([]int, n)+ alive := make([]bool, n)+ for i := range syms {+ prev[i], next[i], alive[i] = i-1, i+1, true+ }+ next[n-1] = -1+ h := &mergeHeap{}+ push := func(i int) {+ if i < 0 || !alive[i] || next[i] < 0 {+ return+ }+ j := next[i]+ if r, ok := t.ranks[syms[i]+"\x00"+syms[j]]; ok {+ heap.Push(h, mergeCand{rank: r, pos: i, left: syms[i], right: syms[j]})+ }+ }+ for i := 0; i < n-1; i++ {+ push(i)+ }+ for h.Len() > 0 {+ c := heap.Pop(h).(mergeCand)+ i := c.pos+ if !alive[i] || next[i] < 0 || syms[i] != c.left || syms[next[i]] != c.right {+ continue+ }+ j := next[i]+ syms[i] = c.left + c.right+ alive[j] = false+ next[i] = next[j]+ if next[j] >= 0 {+ prev[next[j]] = i+ }+ push(prev[i])+ push(i)+ }+ var ids []int+ for i := 0; i >= 0; i = next[i] {+ if !alive[i] {+ continue+ }+ if id, ok := t.vocab[syms[i]]; ok {+ ids = append(ids, id)+ }+ }+ if len(piece) < 256 {+ t.cacheMu.Lock()+ if len(t.cache) > 50000 {+ t.cache = map[string][]int{}+ }+ t.cache[piece] = ids+ t.cacheMu.Unlock()+ }+ return ids+}diff --git a/webbrain-systray/internal/download/download.go b/webbrain-systray/internal/download/download.gonew file mode 100644index 000000000..014618af4--- /dev/null+++ b/webbrain-systray/internal/download/download.go@@ -0,0 +1,388 @@+// Package download fetches large files with resume, progress and SHA-256+// verification, and unpacks release archives.+package download++import (+ "archive/tar"+ "archive/zip"+ "compress/gzip"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "time"+)++type Progress struct {+ Done int64 `json:"done"`+ Total int64 `json:"total"`+ BytesPerSec float64 `json:"bytes_per_sec"`+}++var client = &http.Client{+ Transport: &http.Transport{+ Proxy: http.ProxyFromEnvironment,+ ResponseHeaderTimeout: 60 * time.Second,+ IdleConnTimeout: 90 * time.Second,+ },+}++const userAgent = "WebBrain-Companion/1 (+https://webbrain.one)"++// File downloads url to dest. A partial file from an earlier attempt is+// resumed. When sha is set the result is verified before it is moved into+// place; size, when known, lets progress report a total before headers arrive.+func File(ctx context.Context, url, dest string, size int64, sha string, onProgress func(Progress)) error {+ if st, err := os.Stat(dest); err == nil && (size <= 0 || st.Size() == size) {+ if sha == "" {+ return nil+ }+ if ok, _ := verify(dest, sha); ok {+ return nil+ }+ _ = os.Remove(dest)+ }+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {+ return err+ }+ part := dest + ".part"+ var lastErr error+ for attempt := 0; attempt < 6; attempt++ {+ if attempt > 0 {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(time.Duration(attempt*attempt) * time.Second):+ }+ }+ err := fetch(ctx, url, part, size, onProgress)+ if err == nil {+ lastErr = nil+ break+ }+ if ctx.Err() != nil {+ return ctx.Err()+ }+ lastErr = err+ var perm *permanentError+ if errors.As(err, &perm) {+ return err+ }+ }+ if lastErr != nil {+ return lastErr+ }+ if sha != "" {+ ok, got := verify(part, sha)+ if !ok {+ _ = os.Remove(part)+ return fmt.Errorf("checksum mismatch for %s (got %s)", filepath.Base(dest), got)+ }+ }+ return os.Rename(part, dest)+}++type permanentError struct{ msg string }++func (e *permanentError) Error() string { return e.msg }++func fetch(ctx context.Context, url, part string, size int64, onProgress func(Progress)) error {+ var offset int64+ if st, err := os.Stat(part); err == nil {+ offset = st.Size()+ if size > 0 && offset >= size {+ return nil+ }+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return err+ }+ req.Header.Set("User-Agent", userAgent)+ if offset > 0 {+ req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))+ }+ resp, err := client.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ flags := os.O_CREATE | os.O_WRONLY+ switch {+ case resp.StatusCode == http.StatusPartialContent && offset > 0:+ flags |= os.O_APPEND+ case resp.StatusCode == http.StatusOK:+ offset = 0+ flags |= os.O_TRUNC+ case resp.StatusCode == http.StatusRequestedRangeNotSatisfiable:+ _ = os.Remove(part)+ return errors.New("server rejected resume; restarting download")+ case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusUnauthorized:+ return &permanentError{fmt.Sprintf("download failed: HTTP %d for %s", resp.StatusCode, url)}+ default:+ return fmt.Errorf("download failed: HTTP %d", resp.StatusCode)+ }+ total := size+ if total <= 0 && resp.ContentLength > 0 {+ total = offset + resp.ContentLength+ }+ f, err := os.OpenFile(part, flags, 0o644)+ if err != nil {+ return err+ }+ defer f.Close()+ buf := make([]byte, 1<<20)+ done := offset+ start, lastReport := time.Now(), time.Time{}+ startDone := done+ for {+ n, rerr := resp.Body.Read(buf)+ if n > 0 {+ if _, werr := f.Write(buf[:n]); werr != nil {+ return werr+ }+ done += int64(n)+ if onProgress != nil && time.Since(lastReport) > 250*time.Millisecond {+ lastReport = time.Now()+ el := time.Since(start).Seconds()+ bps := 0.0+ if el > 0 {+ bps = float64(done-startDone) / el+ }+ onProgress(Progress{Done: done, Total: total, BytesPerSec: bps})+ }+ }+ if rerr == io.EOF {+ break+ }+ if rerr != nil {+ return rerr+ }+ }+ if onProgress != nil {+ onProgress(Progress{Done: done, Total: total})+ }+ if total > 0 && done < total {+ return fmt.Errorf("download ended early (%d of %d bytes)", done, total)+ }+ return nil+}++func verify(path, want string) (bool, string) {+ f, err := os.Open(path)+ if err != nil {+ return false, ""+ }+ defer f.Close()+ h := sha256.New()+ if _, err := io.Copy(h, f); err != nil {+ return false, ""+ }+ got := hex.EncodeToString(h.Sum(nil))+ return strings.EqualFold(got, want), got+}++// safeJoin rejects archive entries that would escape dst.+func safeJoin(dst, name string, strip int) (string, bool) {+ name = strings.TrimPrefix(strings.ReplaceAll(name, "\\", "/"), "./")+ parts := strings.Split(strings.Trim(name, "/"), "/")+ if len(parts) <= strip {+ return "", false+ }+ rel := filepath.FromSlash(strings.Join(parts[strip:], "/"))+ if rel == "" || rel == "." {+ return "", false+ }+ p := filepath.Join(dst, rel)+ if !strings.HasPrefix(p, filepath.Clean(dst)+string(os.PathSeparator)) {+ return "", false+ }+ return p, true+}++// ExtractZip unpacks src into dst, dropping the first strip path components.+// keep, when set, filters entries by their path after stripping.+func ExtractZip(src, dst string, strip int, keep func(rel string) bool) error {+ r, err := zip.OpenReader(src)+ if err != nil {+ return err+ }+ defer r.Close()+ for _, f := range r.File {+ p, ok := safeJoin(dst, f.Name, strip)+ if !ok || (keep != nil && !f.FileInfo().IsDir() && !keep(relTo(dst, p))) {+ continue+ }+ if f.FileInfo().IsDir() {+ if err := os.MkdirAll(p, 0o755); err != nil {+ return err+ }+ continue+ }+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ return err+ }+ rc, err := f.Open()+ if err != nil {+ return err+ }+ mode := f.Mode().Perm() | 0o600+ out, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)+ if err != nil {+ rc.Close()+ return err+ }+ _, err = io.Copy(out, rc)+ rc.Close()+ out.Close()+ if err != nil {+ return err+ }+ }+ return nil+}++// ExtractTarGz unpacks a .tar.gz into dst, keeping modes and safe symlinks.+func ExtractTarGz(src, dst string, strip int, keep func(rel string) bool) error {+ f, err := os.Open(src)+ if err != nil {+ return err+ }+ defer f.Close()+ gz, err := gzip.NewReader(f)+ if err != nil {+ return err+ }+ defer gz.Close()+ tr := tar.NewReader(gz)+ for {+ h, err := tr.Next()+ if err == io.EOF {+ return nil+ }+ if err != nil {+ return err+ }+ p, ok := safeJoin(dst, h.Name, strip)+ if !ok || (keep != nil && h.Typeflag != tar.TypeDir && !keep(relTo(dst, p))) {+ continue+ }+ switch h.Typeflag {+ case tar.TypeDir:+ if err := os.MkdirAll(p, 0o755); err != nil {+ return err+ }+ case tar.TypeReg:+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ return err+ }+ out, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(h.Mode).Perm()|0o600)+ if err != nil {+ return err+ }+ _, err = io.Copy(out, tr)+ out.Close()+ if err != nil {+ return err+ }+ case tar.TypeSymlink:+ target := h.Linkname+ if filepath.IsAbs(target) {+ continue+ }+ resolved := filepath.Join(filepath.Dir(p), target)+ if !strings.HasPrefix(resolved, filepath.Clean(dst)+string(os.PathSeparator)) {+ continue+ }+ _ = os.MkdirAll(filepath.Dir(p), 0o755)+ _ = os.Remove(p)+ if err := os.Symlink(target, p); err != nil {+ return err+ }+ }+ }+}++func relTo(dst, p string) string {+ r, err := filepath.Rel(dst, p)+ if err != nil {+ return p+ }+ return filepath.ToSlash(r)+}++// Extract picks the unpacker from the file name.+func Extract(src, dst string, strip int) error { return ExtractFiltered(src, dst, strip, nil) }++// ExtractFiltered unpacks only the entries keep accepts (nil keeps all).+func ExtractFiltered(src, dst string, strip int, keep func(rel string) bool) error {+ lower := strings.ToLower(src)+ switch {+ case strings.HasSuffix(lower, ".zip"):+ return ExtractZip(src, dst, strip, keep)+ case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):+ return ExtractTarGz(src, dst, strip, keep)+ }+ return fmt.Errorf("unknown archive type: %s", filepath.Base(src))+}++// TopLevelDirs returns how many path components all entries share, so callers+// can strip a single wrapping directory when present.+func CommonPrefixDepth(src string) int {+ var names []string+ lower := strings.ToLower(src)+ if strings.HasSuffix(lower, ".zip") {+ r, err := zip.OpenReader(src)+ if err != nil {+ return 0+ }+ defer r.Close()+ for _, f := range r.File {+ names = append(names, f.Name)+ }+ } else {+ f, err := os.Open(src)+ if err != nil {+ return 0+ }+ defer f.Close()+ gz, err := gzip.NewReader(f)+ if err != nil {+ return 0+ }+ tr := tar.NewReader(gz)+ for {+ h, err := tr.Next()+ if err != nil {+ break+ }+ names = append(names, h.Name)+ }+ }+ first := ""+ for _, n := range names {+ n = strings.TrimPrefix(strings.ReplaceAll(n, "\\", "/"), "./")+ if strings.Trim(n, "/.") == "" {+ continue // the archive root ("./")+ }+ parts := strings.SplitN(strings.Trim(n, "/"), "/", 2)+ if len(parts) < 2 && !strings.HasSuffix(n, "/") {+ return 0 // a file at the top level+ }+ if first == "" {+ first = parts[0]+ } else if parts[0] != first {+ return 0+ }+ }+ if first == "" {+ return 0+ }+ return 1+}diff --git a/webbrain-systray/internal/download/download_test.go b/webbrain-systray/internal/download/download_test.gonew file mode 100644index 000000000..984f85e0a--- /dev/null+++ b/webbrain-systray/internal/download/download_test.go@@ -0,0 +1,83 @@+package download++import (+ "archive/tar"+ "compress/gzip"+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++func TestSafeJoin(t *testing.T) {+ dst := t.TempDir()+ cases := []struct {+ name string+ strip int+ want string // "" means rejected+ }{+ {"llama/bin/llama-server", 1, "bin/llama-server"},+ {"./llama/bin/llama-server", 1, "bin/llama-server"},+ {`llama\lib\ggml.dll`, 1, "lib/ggml.dll"},+ {"../evil", 0, ""},+ {"a/../../evil", 0, ""},+ {"llama/../../evil", 1, ""},+ {"llama", 1, ""},+ {"/etc/passwd", 0, "etc/passwd"},+ }+ for _, c := range cases {+ got, ok := safeJoin(dst, c.name, c.strip)+ if c.want == "" {+ if ok {+ t.Errorf("%q accepted as %s", c.name, got)+ }+ continue+ }+ if want := filepath.Join(dst, filepath.FromSlash(c.want)); !ok || got != want {+ t.Errorf("%q: got %s %v, want %s", c.name, got, ok, want)+ }+ }+}++func TestExtractTarGzStripsCommonPrefix(t *testing.T) {+ dir := t.TempDir()+ src := filepath.Join(dir, "rt.tar.gz")+ f, _ := os.Create(src)+ gz := gzip.NewWriter(f)+ tw := tar.NewWriter(gz)+ add := func(name string, body string, mode int64) {+ typ := byte(tar.TypeReg)+ if body == "" && name[len(name)-1] == '/' {+ typ = tar.TypeDir+ }+ _ = tw.WriteHeader(&tar.Header{Name: name, Mode: mode, Size: int64(len(body)), Typeflag: typ})+ _, _ = tw.Write([]byte(body))+ }+ add("./", "", 0o755)+ add("./build-1/", "", 0o755)+ add("./build-1/bin/", "", 0o755)+ add("./build-1/bin/llama-server", "#!/bin/sh\n", 0o755)+ add("./build-1/lib/libggml.so", "elf", 0o644)+ _ = tw.Close()+ _ = gz.Close()+ _ = f.Close()++ if d := CommonPrefixDepth(src); d != 1 {+ t.Fatalf("CommonPrefixDepth = %d, want 1", d)+ }+ out := filepath.Join(dir, "out")+ if err := Extract(src, out, CommonPrefixDepth(src)); err != nil {+ t.Fatal(err)+ }+ st, err := os.Stat(filepath.Join(out, "bin", "llama-server"))+ if err != nil {+ t.Fatal(err)+ }+ // Windows does not expose Unix executable permission bits.+ if runtime.GOOS != "windows" && st.Mode()&0o100 == 0 {+ t.Error("executable bit lost")+ }+ if _, err := os.Stat(filepath.Join(out, "lib", "libggml.so")); err != nil {+ t.Error(err)+ }+}diff --git a/webbrain-systray/internal/i18n/i18n.go b/webbrain-systray/internal/i18n/i18n.gonew file mode 100644index 000000000..e9e2143dc--- /dev/null+++ b/webbrain-systray/internal/i18n/i18n.go@@ -0,0 +1,100 @@+// Package i18n holds the tray menu strings (English and Turkish). The panel+// carries its own copy in JavaScript.+package i18n++import (+ "os"+ "strings"+ "sync"+)++var catalog = map[string]map[string]string{+ "en": {+ "running": "Running",+ "stopped": "Not running",+ "copy": "Copy",+ "copy_hint": "Click to copy",+ "add": "Add subscription…",+ "paused": "paused",+ "quota_loading": "reading usage…",+ "quota_error": "usage unavailable",+ "quota_none": "usage not reported",+ "open_panel": "Open panel…",+ "quit": "Quit WebBrain Companion",+ "dur_days": "%dd",+ "dur_hours": "%dh %02dm",+ "dur_minutes": "%dm",+ "port_moved": "Another app (often CLIProxyAPI or EasyCLIProxyAPI) uses port %d, so the companion runs on %d. Use the address shown here in WebBrain.",+ "network_failed": "Network access stays off: another app uses port %d on the network. Pick another port in Settings and try again.",+ },+ "tr": {+ "running": "Çalışıyor",+ "stopped": "Çalışmıyor",+ "copy": "Kopyala",+ "copy_hint": "Kopyalamak için tıkla",+ "add": "Abonelik ekle…",+ "paused": "duraklatıldı",+ "quota_loading": "kullanım okunuyor…",+ "quota_error": "kullanım okunamadı",+ "quota_none": "kullanım bildirilmiyor",+ "open_panel": "Paneli aç…",+ "quit": "WebBrain Companion'dan çık",+ "dur_days": "%d gün",+ "dur_hours": "%d sa %02d dk",+ "dur_minutes": "%d dk",+ "port_moved": "%d portunu başka bir uygulama (çoğu zaman CLIProxyAPI ya da EasyCLIProxyAPI) kullanıyor, bu yüzden Companion %d portunda çalışıyor. WebBrain'de burada gösterilen adresi kullan.",+ "network_failed": "Ağ erişimi kapalı kaldı: %d portunu ağda başka bir uygulama kullanıyor. Ayarlar'dan başka bir port seçip tekrar dene.",+ },+}++var (+ mu sync.RWMutex+ lang = "en"+)++// Set chooses the language ("" detects it from the environment).+func Set(l string) {+ if l == "" {+ l = detect()+ }+ if _, ok := catalog[l]; !ok {+ l = "en"+ }+ mu.Lock()+ lang = l+ mu.Unlock()+}++func Lang() string {+ mu.RLock()+ defer mu.RUnlock()+ return lang+}++// T returns the string for key in the current language.+func T(key string) string {+ mu.RLock()+ l := lang+ mu.RUnlock()+ if s, ok := catalog[l][key]; ok {+ return s+ }+ return catalog["en"][key]+}++func detect() string {+ for _, env := range []string{"LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"} {+ if v := os.Getenv(env); v != "" {+ return normalize(v)+ }+ }+ return normalize(systemLocale())+}++func normalize(v string) string {+ v = strings.ToLower(v)+ if strings.HasPrefix(v, "tr") {+ return "tr"+ }+ return "en"+}diff --git a/webbrain-systray/internal/i18n/locale_other.go b/webbrain-systray/internal/i18n/locale_other.gonew file mode 100644index 000000000..ae17d09eb--- /dev/null+++ b/webbrain-systray/internal/i18n/locale_other.go@@ -0,0 +1,20 @@+//go:build !windows++package i18n++import (+ "os/exec"+ "runtime"+ "strings"+)++func systemLocale() string {+ if runtime.GOOS == "darwin" {+ // GUI apps launched from Finder get no LANG; ask the user defaults.+ out, err := exec.Command("/usr/bin/defaults", "read", "-g", "AppleLocale").Output()+ if err == nil {+ return strings.TrimSpace(string(out))+ }+ }+ return ""+}diff --git a/webbrain-systray/internal/i18n/locale_windows.go b/webbrain-systray/internal/i18n/locale_windows.gonew file mode 100644index 000000000..d7fe3d91b--- /dev/null+++ b/webbrain-systray/internal/i18n/locale_windows.go@@ -0,0 +1,19 @@+//go:build windows++package i18n++import (+ "unsafe"++ "golang.org/x/sys/windows"+)++func systemLocale() string {+ buf := make([]uint16, 85)+ proc := windows.NewLazySystemDLL("kernel32.dll").NewProc("GetUserDefaultLocaleName")+ n, _, _ := proc.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))+ if n == 0 {+ return ""+ }+ return windows.UTF16ToString(buf)+}diff --git a/webbrain-systray/internal/icons/icons.go b/webbrain-systray/internal/icons/icons.gonew file mode 100644index 000000000..fd81174e2--- /dev/null+++ b/webbrain-systray/internal/icons/icons.go@@ -0,0 +1,13 @@+// Package icons embeds the tray artwork (generated by scripts/make_icons.py).+package icons++import _ "embed"++//go:embed tray_template.png+var Template []byte++//go:embed tray.png+var PNG []byte++//go:embed tray.ico+var ICO []bytediff --git a/webbrain-systray/internal/icons/tray.ico b/webbrain-systray/internal/icons/tray.iconew file mode 100644index 000000000..450449d75Binary files /dev/null and b/webbrain-systray/internal/icons/tray.ico differdiff --git a/webbrain-systray/internal/icons/tray.png b/webbrain-systray/internal/icons/tray.pngnew file mode 100644index 000000000..58563961eBinary files /dev/null and b/webbrain-systray/internal/icons/tray.png differdiff --git a/webbrain-systray/internal/icons/tray_template.png b/webbrain-systray/internal/icons/tray_template.pngnew file mode 100644index 000000000..88b23befaBinary files /dev/null and b/webbrain-systray/internal/icons/tray_template.png differdiff --git a/webbrain-systray/internal/localmodel/catalog.go b/webbrain-systray/internal/localmodel/catalog.gonew file mode 100644index 000000000..458f5976f--- /dev/null+++ b/webbrain-systray/internal/localmodel/catalog.go@@ -0,0 +1,147 @@+// Package localmodel installs and runs PrismML's Ternary Bonsai 2 27B on the+// user's machine (GGUF through PrismML's llama.cpp fork, or MLX on Apple+// Silicon) and registers it with the proxy as an OpenAI-compatible model.+package localmodel++import (+ "fmt"+ "os"+)++// File is one pinned download.+type File struct {+ Name string // path inside the repository+ Size int64+ SHA256 string // empty for files we only size-check+}++func hfURL(repo, rev, name string) string {+ return fmt.Sprintf("https://huggingface.co/%s/resolve/%s/%s", repo, rev, name)+}++const (+ ModelID = "bonsai-2-27b"+ ModelName = "Bonsai 2 27B"+ ModelVendor = "PrismML"+ ModelPageURL = "https://huggingface.co/prism-ml/Ternary-Bonsai-2-27B-gguf"+)++// GGUF: the smallest packing (PTQ1_0, dense trits) plus the Q8_0 vision projector.+var gguf = struct {+ Repo, Rev string+ Model, Proj File+}{+ Repo: "prism-ml/Ternary-Bonsai-2-27B-gguf",+ Rev: "b072e1d3b35a0a630cece372c2127528e0994386",+ Model: File{"Ternary-Bonsai-2-27B-PTQ1_0.gguf", 5946648928, "53107f530aa52eb00912263ab1ee29bd199261c87cd7b4ad4ca1318c1fe33ee3"},+ Proj: File{"Ternary-Bonsai-2-27B-mmproj-Q8_0.gguf", 629246976, "6807ede61d570bb86ba34b756a0fa109edc33668604de867c6ea6d8f1d631903"},+}++// MLX: the 2-bit pack (vision tower included) served by native mlx-vlm.+var mlxPack = struct {+ Repo, Rev, Dir string+ Files []File+}{+ Repo: "prism-ml/Ternary-Bonsai-2-27B-mlx-2bit",+ Rev: "fcba37d2117a7077eac6b613b2668d14d9779edd",+ Dir: "Ternary-Bonsai-2-27B-mlx-2bit",+ Files: []File{+ {"model.safetensors", 8595477990, "130de5925082c168b7866b2e91b52e44abbafc99017e3ca352b77b5b55a269ed"},+ {"tokenizer.json", 12809320, "0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3"},+ {"config.json", 58145, "238de7c512cc56a733421e3fd011d88f8260739e3d00e32c5d65b7943cc9f837"},+ {"hadamard.json", 297903, "7132a3ec364f0bdac1f08f905f24f0ad2f14245060f592637a0396826d3b5fe6"},+ {"tokenizer_config.json", 17928, "b11349aafa7cdc6a320767cf7ceb29ed82f7eda5d65e8e0819e76f0ce947bf27"},+ {"chat_template.jinja", 8952, "c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041"},+ {"generation_config.json", 202, "e70c136c1b78ddc1fb0905bac8e733a4dc448d4f852a5dd75143fffc70be550e"},+ {"preprocessor_config.json", 390, "27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516"},+ {"video_preprocessor_config.json", 385, "7768af27c1fafa9cc9011c1dc20067e03f8915e03b63504550e11d5066986d13"},+ {"files.json", 3122, "f0d3b0108d8e52685b81da7916e9943ff9cf2f470fbcc6b24f66a3d562492f1c"},+ {"tokenizer-validation.json", 63, "b36f33d09bd3de3e19de3fd2cf493a69ec0a5e24acf648b0c9fba120d9357554"},+ {"reload-validation.json", 86, "41ec215fe19fa8ad59527fca6594a782d1b7f23b69948ef063311c768217788e"},+ {"PACK-RUNTIME.md", 969, "486bf73b40dab072792cb2e48961a3698d4ca599f1355f3e628e4c64d8aa4cce"},+ {"quickstart.py", 3882, "094ecaee12c0800cec2a68358c3370db7d31abe7757f95f7bf1edde4f4e48cbb"},+ {"runtime/artifact.py", 5621, "5279718d7671bd799e866f53099e82b0260117fec811f83011ba47a0abc7943e"},+ {"runtime/codec.py", 2572, "7f7fd67637a7d9363eab8ebf7db59771830b690330ffef772379a0169ddb9608"},+ {"runtime/requirements.txt", 115, "358bc104a02ea598f1e6cde8e7eeed169b9ec34f69f3543b47b390706446a1e0"},+ {"runtime/runtime.py", 10674, "30ad3905775040a8167360a009168b9ede1436cb02dc43e9e743432482eafbbf"},+ {"runtime/vision_artifact.py", 5285, "b3d9645300d913cc09abff04bf25f31621daac4d507e7e1a8b00a64442a05a3e"},+ },+}++// The tested native MLX dependency set from PrismML's Bonsai-demo+// (scripts/requirements-mlx-vlm.txt).+var mlxRequirements = []string{"mlx==0.32.3", "mlx-vlm==0.7.8", "mlx-lm==0.32.0", "transformers==5.19.0"}++const (+ mlxPython = "3.11"+ uvVersion = "0.13.3"+)++// PrismML's llama.cpp fork release pinned by Bonsai-demo; stock llama.cpp+// rejects PTQ1_0.+const llamaTag = "prism-b10787-73bfe6c"++func llamaURL(asset string) string {+ return fmt.Sprintf("https://github.com/PrismML-Eng/llama.cpp/releases/download/%s/%s", llamaTag, asset)+}++// Runtime archive sizes (bytes), for progress before headers arrive.+var llamaAssetSizes = map[string]int64{+ "llama-" + llamaTag + "-bin-macos-arm64.tar.gz": 11573797,+ "llama-" + llamaTag + "-bin-macos-x64.tar.gz": 11616912,+ "llama-" + llamaTag + "-bin-linux-cuda-12.4-x64.tar.gz": 327551187,+ "llama-" + llamaTag + "-bin-linux-cuda-12.8-x64.tar.gz": 208658605,+ "llama-" + llamaTag + "-bin-linux-cuda-13.3-x64.tar.gz": 184320718,+ "llama-" + llamaTag + "-bin-ubuntu-vulkan-x64.tar.gz": 35952782,+ "llama-" + llamaTag + "-bin-ubuntu-vulkan-arm64.tar.gz": 28382711,+ "llama-" + llamaTag + "-bin-ubuntu-x64.tar.gz": 17896259,+ "llama-" + llamaTag + "-bin-ubuntu-arm64.tar.gz": 13892127,+ "llama-" + llamaTag + "-bin-win-cuda-12.4-x64.zip": 314639598,+ "llama-" + llamaTag + "-bin-win-cuda-13.3-x64.zip": 179514746,+ "cudart-llama-bin-win-cuda-12.4-x64.zip": 391443627,+ "cudart-llama-bin-win-cuda-13.3-x64.zip": 390970417,+ "llama-" + llamaTag + "-bin-win-vulkan-x64.zip": 31308770,+ "llama-" + llamaTag + "-bin-win-cpu-x64.zip": 19539022,+ "llama-" + llamaTag + "-bin-win-cpu-arm64.zip": 12412126,+}++func uvAsset(arch string) string {+ if arch == "arm64" {+ return "uv-aarch64-apple-darwin.tar.gz"+ }+ return "uv-x86_64-apple-darwin.tar.gz"+}++func uvURL(arch string) string {+ return fmt.Sprintf("https://github.com/astral-sh/uv/releases/download/%s/%s", uvVersion, uvAsset(arch))+}++const (+ gib = int64(1) << 30+ // FP16 KV cache per token on the 27B: 16 full-attention layers × K,V × 4+ // heads × 256 dims × 2 bytes. The 48 linear-attention layers keep a small+ // fixed recurrent state instead.+ kvBytesPerToken = 64 << 10+ // Compute buffers for batch prefill, measured loosely on llama.cpp.+ computeBytes = 900 << 20+ // The Q8_0 projector plus its working buffers when offloaded to the GPU+ // (Bonsai-demo: --no-mmproj-offload frees ~0.9 GiB of VRAM).+ visionGPUBytes = 960 << 20+ // The projector kept in system RAM (CPU image encoding).+ visionCPUBytes = 1300 << 20+ // Fixed recurrent state and runtime overhead.+ stateBytes = 300 << 20+)++// WBC_DEV_BONSAI_2B=1 swaps in the 2B GGUF pack (0.8 GB) so the install and+// serving pipeline can be exercised on small machines and in CI. It is not+// shown in the UI.+func init() {+ if os.Getenv("WBC_DEV_BONSAI_2B") == "" {+ return+ }+ gguf.Repo = "prism-ml/Ternary-Bonsai-2-2B-gguf"+ gguf.Rev = "683f7be2629342a50987627b40881e54761a2430"+ gguf.Model = File{"Ternary-Bonsai-2-2B-PTQ1_0.gguf", 429183456, "36061ad406df8a4903a6db005be350c50fabfaf717f9ef0acf4b76adcd9929fa"}+ gguf.Proj = File{"Ternary-Bonsai-2-2B-mmproj-Q8_0.gguf", 364664352, "ac9934e8d7966d0d62442c202ec8fdad99a045dea79366c1a4a246a46f5c0533"}+}diff --git a/webbrain-systray/internal/localmodel/manager.go b/webbrain-systray/internal/localmodel/manager.gonew file mode 100644index 000000000..b9e46ea6d--- /dev/null+++ b/webbrain-systray/internal/localmodel/manager.go@@ -0,0 +1,701 @@+package localmodel++import (+ "context"+ "errors"+ "fmt"+ "io/fs"+ "net"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "time"++ "github.com/esokullu/webbrain-systray/internal/core"+ "github.com/esokullu/webbrain-systray/internal/download"+ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/osutil"+ "github.com/esokullu/webbrain-systray/internal/paths"+ "github.com/esokullu/webbrain-systray/internal/settings"+ "github.com/esokullu/webbrain-systray/internal/sysinfo"+)++const (+ PhaseIdle = "idle"+ PhaseDownloading = "downloading"+ PhaseInstalling = "installing"+ PhaseStarting = "starting"+ PhaseRunning = "running"+ PhaseStopping = "stopping"+ PhaseError = "error"+)++// Status is the local model's state, as the panel shows it.+type Status struct {+ ModelID string `json:"model_id"`+ ModelName string `json:"model_name"`+ Vendor string `json:"vendor"`+ PageURL string `json:"page_url"`+ Format string `json:"format"`+ Formats []string `json:"formats"`+ Installed map[string]bool `json:"installed"`+ Plan Plan `json:"plan"`+ Phase string `json:"phase"`+ Step string `json:"step,omitempty"`+ Progress *download.Progress `json:"progress,omitempty"`+ Error string `json:"error,omitempty"`+ Port int `json:"port,omitempty"`+ DownloadBytes int64 `json:"download_bytes"`+ DiskBytes int64 `json:"disk_bytes"`+ AutoStart bool `json:"auto_start"`+ VisionMode string `json:"vision_mode"`+ System sysinfo.Info `json:"system"`+ SystemSummary string `json:"system_summary"`+ StartedAt *time.Time `json:"started_at,omitempty"`+}++type Manager struct {+ mu sync.Mutex+ store *settings.Store+ register func([]core.LocalUpstream) error+ onChange func()++ phase string+ step string+ progress *download.Progress+ err string+ port int+ startedAt *time.Time+ plan Plan+ cancel context.CancelFunc+ cmd *exec.Cmd+ exited chan struct{}+ stopping bool+ stopErr error // why the server was stopped, when it was not the user+}++func NewManager(store *settings.Store, register func([]core.LocalUpstream) error, onChange func()) *Manager {+ return &Manager{store: store, register: register, onChange: onChange, phase: PhaseIdle}+}++func (m *Manager) changed() {+ if m.onChange != nil {+ go m.onChange()+ }+}++// Formats available on this machine.+func Formats(info sysinfo.Info) []string {+ if info.AppleSilicon {+ return []string{"gguf", "mlx"}+ }+ return []string{"gguf"}+}++func (m *Manager) format(info sysinfo.Info) string {+ f := m.store.Get().Local.Format+ for _, ok := range Formats(info) {+ if ok == f {+ return f+ }+ }+ return "gguf"+}++// --- locations -----------------------------------------------------------------++func ggufDir() string { return filepath.Join(paths.Models(), "bonsai-2-27b-gguf") }+func mlxDir() string { return filepath.Join(paths.Models(), mlxPack.Dir) }+func uvDir() string { return filepath.Join(paths.Runtimes(), "uv-"+uvVersion) }+func mlxVenv() string { return filepath.Join(paths.Runtimes(), "mlx-venv") }+func runtimeDir(p Plan) string {+ return filepath.Join(paths.Runtimes(), "llama-"+llamaTag+"-"+strings.ReplaceAll(strings.Join(assetKeys(p.Assets), "+"), " ", ""))+}++func assetKeys(assets []string) []string {+ var out []string+ for _, a := range assets {+ a = strings.TrimPrefix(a, "llama-"+llamaTag+"-bin-")+ a = strings.TrimSuffix(strings.TrimSuffix(a, ".zip"), ".tar.gz")+ out = append(out, a)+ }+ return out+}++func fileOK(path string, size int64) bool {+ st, err := os.Stat(path)+ return err == nil && !st.IsDir() && (size <= 0 || st.Size() == size)+}++func ggufInstalled(p Plan) bool {+ return fileOK(filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size) &&+ fileOK(filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size) &&+ fileOK(filepath.Join(runtimeDir(p), ".installed"), 0)+}++func mlxInstalled() bool {+ for _, f := range mlxPack.Files {+ if !fileOK(filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size) {+ return false+ }+ }+ return fileOK(filepath.Join(mlxVenv(), ".installed"), 0)+}++func dirSize(dir string) int64 {+ var n int64+ _ = filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {+ if err == nil && !d.IsDir() {+ if info, e := d.Info(); e == nil {+ n += info.Size()+ }+ }+ return nil+ })+ return n+}++func remaining(path string, size int64) int64 {+ if fileOK(path, size) {+ return 0+ }+ if st, err := os.Stat(path + ".part"); err == nil && st.Size() < size {+ return size - st.Size()+ }+ return size+}++// --- status ----------------------------------------------------------------------++func (m *Manager) Status() Status {+ info := sysinfo.Get()+ s := m.store.Get()+ format := m.format(info)+ plan := MakePlan(info, s.Local, format)+ st := Status{+ ModelID: ModelID, ModelName: ModelName, Vendor: ModelVendor, PageURL: ModelPageURL,+ Format: format, Formats: Formats(info), Plan: plan,+ Installed: map[string]bool{"gguf": ggufInstalled(MakePlan(info, s.Local, "gguf"))},+ AutoStart: s.Local.AutoStart,+ VisionMode: s.Local.Vision,+ System: info, SystemSummary: info.Summary(),+ }+ if info.AppleSilicon {+ st.Installed["mlx"] = mlxInstalled()+ }+ if format == "gguf" {+ st.DownloadBytes = remaining(filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size) ++ remaining(filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size)+ if !fileOK(filepath.Join(runtimeDir(plan), ".installed"), 0) {+ for _, a := range plan.Assets {+ st.DownloadBytes += llamaAssetSizes[a]+ }+ }+ st.DiskBytes = dirSize(ggufDir())+ } else {+ for _, f := range mlxPack.Files {+ st.DownloadBytes += remaining(filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size)+ }+ st.DiskBytes = dirSize(mlxDir())+ }+ m.mu.Lock()+ st.Phase, st.Step, st.Error, st.Port, st.StartedAt = m.phase, m.step, m.err, m.port, m.startedAt+ if m.progress != nil {+ p := *m.progress+ st.Progress = &p+ }+ if m.phase == PhaseRunning || m.phase == PhaseStarting {+ st.Plan = m.plan // what is actually running+ }+ m.mu.Unlock()+ return st+}++func (m *Manager) setPhase(phase, step string, err error) {+ m.mu.Lock()+ m.phase, m.step = phase, step+ m.err = ""+ if err != nil {+ m.err = err.Error()+ }+ if phase != PhaseDownloading && phase != PhaseInstalling {+ m.progress = nil+ }+ m.mu.Unlock()+ m.changed()+}++// Busy reports whether an install or start is in progress.+func (m *Manager) Busy() bool {+ m.mu.Lock()+ defer m.mu.Unlock()+ return m.phase == PhaseDownloading || m.phase == PhaseInstalling || m.phase == PhaseStarting || m.phase == PhaseStopping+}++// --- install ---------------------------------------------------------------------++type item struct {+ label string+ url string+ dest string+ size int64+ sha string+}++// Install downloads everything the selected format needs, then starts it.+func (m *Manager) Install(format string) error {+ info := sysinfo.Get()+ if format == "" {+ format = m.format(info)+ }+ if format == "mlx" && !info.AppleSilicon {+ return errors.New("MLX needs a Mac with Apple Silicon")+ }+ m.mu.Lock()+ if m.phase == PhaseDownloading || m.phase == PhaseInstalling || m.phase == PhaseStarting {+ m.mu.Unlock()+ return errors.New("an install is already running")+ }+ ctx, cancel := context.WithCancel(context.Background())+ m.cancel = cancel+ m.mu.Unlock()+ _, _ = m.store.Update(func(s *settings.Settings) { s.Local.Format = format })++ go func() {+ defer cancel()+ var err error+ if format == "mlx" {+ err = m.installMLX(ctx, info)+ } else {+ err = m.installGGUF(ctx, info)+ }+ if err != nil {+ if errors.Is(err, context.Canceled) {+ m.setPhase(PhaseIdle, "", nil)+ return+ }+ logx.Printf("local model install failed: %v", err)+ m.setPhase(PhaseError, "", err)+ return+ }+ _, _ = m.store.Update(func(s *settings.Settings) { s.Local.AutoStart = true })+ if err := m.Start(); err != nil {+ m.setPhase(PhaseError, "", err)+ }+ }()+ return nil+}++// Cancel stops a running download; partial files are kept for resume.+func (m *Manager) Cancel() {+ m.mu.Lock()+ c := m.cancel+ m.mu.Unlock()+ if c != nil {+ c()+ }+}++func (m *Manager) fetchAll(ctx context.Context, items []item) error {+ var total, done int64+ for _, it := range items {+ total += remaining(it.dest, it.size)+ }+ for _, it := range items {+ if fileOK(it.dest, it.size) && it.sha == "" {+ continue+ }+ before := it.size - remaining(it.dest, it.size)+ step := it.label+ if fileOK(it.dest, it.size) {+ step = "Verifying " + it.label // complete file: download.File only re-checks its SHA-256+ }+ m.mu.Lock()+ m.phase, m.step = PhaseDownloading, step+ m.progress = &download.Progress{Done: done, Total: total}+ m.mu.Unlock()+ m.changed()+ base := done+ err := download.File(ctx, it.url, it.dest, it.size, it.sha, func(p download.Progress) {+ m.mu.Lock()+ m.progress = &download.Progress{Done: base + (p.Done - before), Total: total, BytesPerSec: p.BytesPerSec}+ m.mu.Unlock()+ m.changed()+ })+ if err != nil {+ return fmt.Errorf("%s: %w", it.label, err)+ }+ done = base + (it.size - before)+ }+ return nil+}++func (m *Manager) installGGUF(ctx context.Context, info sysinfo.Info) error {+ plan := MakePlan(info, m.store.Get().Local, "gguf")+ rdir := runtimeDir(plan)+ dl := filepath.Join(paths.Runtimes(), "_downloads")+ items := []item{+ {"Bonsai 2 27B weights (PTQ1_0)", hfURL(gguf.Repo, gguf.Rev, gguf.Model.Name), filepath.Join(ggufDir(), gguf.Model.Name), gguf.Model.Size, gguf.Model.SHA256},+ {"Vision projector (mmproj Q8_0)", hfURL(gguf.Repo, gguf.Rev, gguf.Proj.Name), filepath.Join(ggufDir(), gguf.Proj.Name), gguf.Proj.Size, gguf.Proj.SHA256},+ }+ runtimeReady := fileOK(filepath.Join(rdir, ".installed"), 0)+ if !runtimeReady {+ for _, a := range plan.Assets {+ items = append(items, item{"llama.cpp runtime (" + strings.Join(assetKeys([]string{a}), "") + ")", llamaURL(a), filepath.Join(dl, a), llamaAssetSizes[a], ""})+ }+ }+ if err := m.fetchAll(ctx, items); err != nil {+ return err+ }+ if !runtimeReady {+ m.setPhase(PhaseInstalling, "Unpacking llama.cpp runtime", nil)+ _ = os.RemoveAll(rdir)+ for _, a := range plan.Assets {+ src := filepath.Join(dl, a)+ if err := download.Extract(src, rdir, download.CommonPrefixDepth(src)); err != nil {+ return fmt.Errorf("unpack %s: %w", a, err)+ }+ }+ if runtime.GOOS == "darwin" {+ trustMacBinaries(rdir)+ }+ if findBinary(rdir, "llama-server") == "" {+ return errors.New("llama-server not found in the runtime archive")+ }+ if err := os.WriteFile(filepath.Join(rdir, ".installed"), []byte(llamaTag+"\n"), 0o644); err != nil {+ return err+ }+ for _, a := range plan.Assets {+ _ = os.Remove(filepath.Join(dl, a))+ }+ }+ return nil+}++func (m *Manager) installMLX(ctx context.Context, info sysinfo.Info) error {+ var items []item+ for _, f := range mlxPack.Files {+ label := "Bonsai 2 27B MLX pack"+ if f.Name != "model.safetensors" {+ label = "Model files"+ }+ items = append(items, item{label, hfURL(mlxPack.Repo, mlxPack.Rev, f.Name), filepath.Join(mlxDir(), filepath.FromSlash(f.Name)), f.Size, f.SHA256})+ }+ uvBin := filepath.Join(uvDir(), "uv")+ if !fileOK(uvBin, 0) {+ items = append(items, item{"uv (Python manager)", uvURL(info.Arch), filepath.Join(paths.Runtimes(), "_downloads", uvAsset(info.Arch)), 0, ""})+ }+ if err := m.fetchAll(ctx, items); err != nil {+ return err+ }+ if !fileOK(uvBin, 0) {+ src := filepath.Join(paths.Runtimes(), "_downloads", uvAsset(info.Arch))+ if err := download.Extract(src, uvDir(), download.CommonPrefixDepth(src)); err != nil {+ return fmt.Errorf("unpack uv: %w", err)+ }+ _ = os.Remove(src)+ trustMacBinaries(uvDir())+ }+ if fileOK(filepath.Join(mlxVenv(), ".installed"), 0) {+ return nil+ }+ env := append(os.Environ(),+ "UV_CACHE_DIR="+filepath.Join(paths.Runtimes(), "uv-cache"),+ "UV_PYTHON_INSTALL_DIR="+filepath.Join(paths.Runtimes(), "uv-python"),+ )+ runStep := func(step string, args ...string) error {+ m.setPhase(PhaseInstalling, step, nil)+ cmd := osutil.CommandContext(ctx, uvBin, args...)+ cmd.Env = env+ cmd.Stdout = logx.Writer("[uv]")+ cmd.Stderr = logx.Writer("[uv]")+ if err := cmd.Run(); err != nil {+ if ctx.Err() != nil {+ return ctx.Err()+ }+ return fmt.Errorf("%s: %w (see log)", step, err)+ }+ return nil+ }+ _ = os.RemoveAll(mlxVenv())+ if err := runStep("Creating Python "+mlxPython+" environment", "venv", mlxVenv(), "--python", mlxPython); err != nil {+ return err+ }+ py := filepath.Join(mlxVenv(), "bin", "python")+ args := append([]string{"pip", "install", "--python", py}, mlxRequirements...)+ if err := runStep("Installing MLX and mlx-vlm", args...); err != nil {+ return err+ }+ m.setPhase(PhaseInstalling, "Checking the native Bonsai loader", nil)+ check := osutil.CommandContext(ctx, py, "-c", "from mlx_vlm.models.prism_hadamard_qwen35 import Model")+ check.Stdout, check.Stderr = logx.Writer("[mlx]"), logx.Writer("[mlx]")+ if err := check.Run(); err != nil {+ return errors.New("mlx-vlm installed but its Bonsai 2 loader is missing (see log)")+ }+ return os.WriteFile(filepath.Join(mlxVenv(), ".installed"), []byte(strings.Join(mlxRequirements, "\n")+"\n"), 0o644)+}++// trustMacBinaries clears quarantine and ad-hoc signs downloaded executables+// so Gatekeeper lets them run (what Bonsai-demo's setup does).+func trustMacBinaries(dir string) {+ if runtime.GOOS != "darwin" {+ return+ }+ _ = osutil.Command("/usr/bin/xattr", "-cr", dir).Run()+ _ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {+ if err != nil || d.IsDir() {+ return nil+ }+ info, e := d.Info()+ if e != nil {+ return nil+ }+ if info.Mode()&0o111 != 0 || strings.HasSuffix(p, ".dylib") || strings.HasSuffix(p, ".so") {+ _ = osutil.Command("/usr/bin/codesign", "-s", "-", "--force", "--timestamp=none", p).Run()+ }+ return nil+ })+}++func findBinary(dir, name string) string {+ if runtime.GOOS == "windows" {+ name += ".exe"+ }+ found := ""+ _ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {+ if err == nil && !d.IsDir() && d.Name() == name && found == "" {+ found = p+ }+ return nil+ })+ return found+}++// --- run -------------------------------------------------------------------------++func freePort(preferred int) int {+ for p := preferred; p < preferred+50; p++ {+ l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p))+ if err == nil {+ _ = l.Close()+ return p+ }+ }+ return preferred+}++// Start launches the local server for the selected format and registers it+// with the proxy once it answers.+func (m *Manager) Start() error {+ info := sysinfo.Get()+ s := m.store.Get()+ format := m.format(info)+ plan := MakePlan(info, s.Local, format)++ m.mu.Lock()+ if m.cmd != nil {+ m.mu.Unlock()+ return nil+ }+ m.mu.Unlock()++ port := freePort(max(s.Local.Port, 18081))+ var (+ cmd *exec.Cmd+ upstream string+ health string+ )+ switch format {+ case "mlx":+ if !mlxInstalled() {+ return errors.New("the MLX pack is not installed")+ }+ py := filepath.Join(mlxVenv(), "bin", "python")+ upstream = mlxDir()+ cmd = osutil.Command(py, "-m", "mlx_vlm.server", "--model", mlxDir(), "--host", "127.0.0.1",+ "--port", fmt.Sprint(port), "--enable-thinking")+ cmd.Env = append(os.Environ(), "HF_HOME="+filepath.Join(paths.Runtimes(), "hf-home"), "HF_HUB_OFFLINE=1")+ health = fmt.Sprintf("http://127.0.0.1:%d/v1/models", port)+ default:+ if !ggufInstalled(plan) {+ return errors.New("the GGUF model or its runtime is not installed")+ }+ bin := findBinary(runtimeDir(plan), "llama-server")+ if bin == "" {+ return errors.New("llama-server is missing; reinstall the runtime")+ }+ args := []string{+ "-m", filepath.Join(ggufDir(), gguf.Model.Name),+ "--host", "127.0.0.1", "--port", fmt.Sprint(port),+ "-ngl", fmt.Sprint(plan.GPULayers), "-fa", "on", "-c", fmt.Sprint(plan.Context),+ "--temp", "1.0", "--top-p", "0.95", "--top-k", "20", "--min-p", "0.05",+ "--jinja", "--alias", ModelID,+ }+ if plan.Vision != "off" {+ args = append(args, "--mmproj", filepath.Join(ggufDir(), gguf.Proj.Name))+ if plan.Vision == "cpu" {+ args = append(args, "--no-mmproj-offload")+ }+ if plan.ImageMaxTokens > 0 {+ args = append(args, "--image-max-tokens", fmt.Sprint(plan.ImageMaxTokens))+ }+ }+ upstream = ModelID+ cmd = osutil.Command(bin, args...)+ cmd.Dir = filepath.Dir(bin)+ env := os.Environ()+ if runtime.GOOS == "linux" {+ env = append(env, "LD_LIBRARY_PATH="+filepath.Dir(bin)+string(os.PathListSeparator)+os.Getenv("LD_LIBRARY_PATH"))+ }+ cmd.Env = env+ health = fmt.Sprintf("http://127.0.0.1:%d/health", port)+ }+ cmd.Stdout = logx.Writer("[bonsai]")+ cmd.Stderr = logx.Writer("[bonsai]")+ logx.Printf("starting local model: %s %s", cmd.Path, strings.Join(cmd.Args[1:], " "))+ if err := cmd.Start(); err != nil {+ return fmt.Errorf("start local server: %w", err)+ }+ exited := make(chan struct{})+ m.mu.Lock()+ m.cmd, m.exited, m.port, m.plan, m.stopping, m.stopErr = cmd, exited, port, plan, false, nil+ m.phase, m.step, m.err = PhaseStarting, "Loading the model", ""+ m.mu.Unlock()+ m.changed()++ go m.waitForExit(cmd, exited)++ go func() {+ client := &http.Client{Timeout: 3 * time.Second}+ deadline := time.Now().Add(10 * time.Minute)+ for time.Now().Before(deadline) {+ select {+ case <-exited:+ return+ case <-time.After(time.Second):+ }+ resp, err := client.Get(health)+ if err != nil {+ continue+ }+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ continue+ }+ vision := plan.Vision != "off"+ if err := m.register([]core.LocalUpstream{{+ Name: "local-bonsai",+ BaseURL: fmt.Sprintf("http://127.0.0.1:%d/v1", port),+ Models: []core.LocalModel{{Upstream: upstream, Alias: ModelID, DisplayName: ModelName + " (local)",+ Vision: vision, ContextLength: plan.Context}},+ }}); err != nil {+ logx.Printf("register local model: %v", err)+ }+ now := time.Now()+ m.mu.Lock()+ m.startedAt = &now+ m.mu.Unlock()+ m.setPhase(PhaseRunning, "", nil)+ return+ }+ logx.Printf("local model: not ready after 10 minutes, stopping it")+ m.mu.Lock()+ m.stopErr = errors.New("the local model did not become ready within 10 minutes (see log)")+ m.mu.Unlock()+ m.Stop()+ }()+ return nil+}++// waitForExit finishes cleanup before Stop can return and Restart can launch+// another server. Keeping cmd set until then also prevents an early Start.+func (m *Manager) waitForExit(cmd *exec.Cmd, exited chan struct{}) {+ defer close(exited)+ err := cmd.Wait()+ _ = m.register(nil)+ m.mu.Lock()+ why := m.stopErr+ if !m.stopping {+ msg := "the local model server exited"+ if err != nil {+ msg += ": " + err.Error()+ }+ logx.Printf("%s", msg)+ why = errors.New(msg + " (see log)")+ }+ m.cmd, m.port, m.startedAt, m.stopErr = nil, 0, nil, nil+ m.phase, m.step, m.err, m.progress = PhaseIdle, "", "", nil+ if why != nil {+ m.phase, m.err = PhaseError, why.Error()+ }+ m.mu.Unlock()+ m.changed()+}++// Stop terminates the local server.+func (m *Manager) Stop() {+ m.mu.Lock()+ cmd, exited := m.cmd, m.exited+ m.stopping = true+ if cmd != nil {+ m.phase = PhaseStopping+ }+ m.mu.Unlock()+ _ = m.register(nil)+ if cmd == nil || cmd.Process == nil {+ return+ }+ m.changed()+ terminate(cmd)+ select {+ case <-exited:+ case <-time.After(8 * time.Second):+ _ = cmd.Process.Kill()+ <-exited+ }+}++// Running reports whether the local server is up.+func (m *Manager) Running() bool {+ m.mu.Lock()+ defer m.mu.Unlock()+ return m.phase == PhaseRunning+}++// Remove deletes the files of one format (stopping the server first).+func (m *Manager) Remove(format string) error {+ if m.Busy() && !m.Running() {+ return errors.New("wait for the current operation to finish")+ }+ m.Stop()+ switch format {+ case "mlx":+ _ = os.RemoveAll(mlxDir())+ _ = os.RemoveAll(mlxVenv())+ default:+ _ = os.RemoveAll(ggufDir())+ entries, _ := os.ReadDir(paths.Runtimes())+ for _, e := range entries {+ if strings.HasPrefix(e.Name(), "llama-") {+ _ = os.RemoveAll(filepath.Join(paths.Runtimes(), e.Name()))+ }+ }+ }+ _, _ = m.store.Update(func(s *settings.Settings) { s.Local.AutoStart = false })+ m.setPhase(PhaseIdle, "", nil)+ return nil+}++// Restart applies new settings (vision mode, context) to a running server.+func (m *Manager) Restart() error {+ running := m.Running()+ m.Stop()+ if running {+ return m.Start()+ }+ return nil+}diff --git a/webbrain-systray/internal/localmodel/manager_test.go b/webbrain-systray/internal/localmodel/manager_test.gonew file mode 100644index 000000000..15414fbb9--- /dev/null+++ b/webbrain-systray/internal/localmodel/manager_test.go@@ -0,0 +1,71 @@+package localmodel++import (+ "os"+ "sync/atomic"+ "testing"+ "time"++ "github.com/esokullu/webbrain-systray/internal/core"+ "github.com/esokullu/webbrain-systray/internal/osutil"+)++func TestLocalModelExitHelper(t *testing.T) {+ if os.Getenv("WBC_EXIT_HELPER") == "1" {+ os.Exit(0)+ }+}++func TestStopWaitsForExitCleanup(t *testing.T) {+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ cmd := osutil.Command(executable, "-test.run=^TestLocalModelExitHelper$")+ cmd.Env = append(os.Environ(), "WBC_EXIT_HELPER=1")+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = cmd.Process.Kill() })++ cleanupStarted := make(chan struct{})+ finishCleanup := make(chan struct{})+ stopStarted := make(chan struct{})+ var calls atomic.Int32+ m := NewManager(nil, func([]core.LocalUpstream) error {+ switch calls.Add(1) {+ case 1:+ close(cleanupStarted)+ <-finishCleanup+ case 2:+ close(stopStarted)+ }+ return nil+ }, nil)+ m.cmd, m.exited, m.phase = cmd, make(chan struct{}), PhaseRunning+ go m.waitForExit(cmd, m.exited)+ <-cleanupStarted+ stopped := make(chan struct{})+ go func() {+ m.Stop()+ close(stopped)+ }()+ <-stopStarted+ select {+ case <-stopped:+ close(finishCleanup)+ t.Fatal("Stop returned before the previous server finished cleanup")+ case <-time.After(25 * time.Millisecond):+ }+ close(finishCleanup)+ select {+ case <-stopped:+ case <-time.After(5 * time.Second):+ t.Fatal("Stop did not return after cleanup finished")+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ if m.cmd != nil || m.phase != PhaseIdle {+ t.Fatalf("server remains active after Stop: cmd=%v phase=%s", m.cmd, m.phase)+ }+}diff --git a/webbrain-systray/internal/localmodel/plan.go b/webbrain-systray/internal/localmodel/plan.gonew file mode 100644index 000000000..954088cb6--- /dev/null+++ b/webbrain-systray/internal/localmodel/plan.go@@ -0,0 +1,240 @@+package localmodel++import (+ "fmt"+ "math"++ "github.com/esokullu/webbrain-systray/internal/settings"+ "github.com/esokullu/webbrain-systray/internal/sysinfo"+)++const totalLayers = 64++// Plan is what the companion will run on this machine and why.+type Plan struct {+ Format string `json:"format"`+ Backend string `json:"backend"` // metal | cuda | vulkan | cpu | mlx+ BackendLabel string `json:"backend_label"`+ Assets []string `json:"-"`+ GPULayers int `json:"gpu_layers"`+ Context int `json:"context"`+ Vision string `json:"vision"` // gpu | cpu | off | builtin+ VisionReason string `json:"vision_reason"`+ Fits bool `json:"fits"`+ Warning string `json:"warning,omitempty"`+ NeedBytes int64 `json:"need_bytes"`+ BudgetBytes int64 `json:"budget_bytes"`+ ImageMaxTokens int `json:"image_max_tokens,omitempty"`+}++func gb(b int64) string { return fmt.Sprintf("%.1f GB", float64(b)/1e9) }++// contextForRAM mirrors Bonsai-demo's RAM-tiered default context.+func contextForRAM(totalGiB int) int {+ switch {+ case totalGiB <= 11:+ return 8192+ case totalGiB <= 23:+ return 16384+ case totalGiB <= 35:+ return 32768+ case totalGiB <= 71:+ return 65536+ default:+ return 131072+ }+}++// backendFor picks the PrismML llama.cpp build for this machine.+func backendFor(info sysinfo.Info) (backend, label string, assets []string, ngl int, budget int64) {+ ram := int64(info.MemoryBytes)+ avail := int64(info.AvailableBytes)+ if avail <= 0 || avail > ram {+ avail = ram * 7 / 10+ }+ cpuBudget := avail - int64(1536<<20)+ switch info.OS {+ case "darwin":+ if info.AppleSilicon {+ b := ram * 2 / 3+ if ram > 36*gib {+ b = ram * 3 / 4+ }+ return "metal", "Metal on the Apple GPU", []string{"llama-" + llamaTag + "-bin-macos-arm64.tar.gz"}, 99, b+ }+ return "cpu", "CPU (Intel Mac)", []string{"llama-" + llamaTag + "-bin-macos-x64.tar.gz"}, 0, cpuBudget+ case "linux":+ arch := "x64"+ if info.Arch == "arm64" {+ arch = "arm64"+ }+ if g := info.GPU; g != nil && g.Vendor == "nvidia" && arch == "x64" && g.CUDA != "" {+ var maj, min int+ fmt.Sscanf(g.CUDA, "%d.%d", &maj, &min)+ tag := ""+ switch {+ case maj > 13 || (maj == 13 && min >= 3):+ tag = "13.3"+ case maj == 13 || (maj == 12 && min >= 8):+ tag = "12.8"+ case maj == 12:+ tag = "12.4"+ }+ if tag != "" {+ return "cuda", "CUDA " + tag + " on " + g.Name, []string{"llama-" + llamaTag + "-bin-linux-cuda-" + tag + "-x64.tar.gz"}, 99, vram(g)+ }+ }+ if g := info.GPU; info.Vulkan && g != nil && g.MemoryBytes >= 6*uint64(gib) {+ return "vulkan", "Vulkan on " + g.Name, []string{"llama-" + llamaTag + "-bin-ubuntu-vulkan-" + arch + ".tar.gz"}, 99, vram(g)+ }+ return "cpu", "CPU", []string{"llama-" + llamaTag + "-bin-ubuntu-" + arch + ".tar.gz"}, 0, cpuBudget+ case "windows":+ if info.Arch == "arm64" {+ return "cpu", "CPU (Arm64)", []string{"llama-" + llamaTag + "-bin-win-cpu-arm64.zip"}, 0, cpuBudget+ }+ if g := info.GPU; g != nil && g.Vendor == "nvidia" && g.CUDA != "" {+ var maj, min int+ fmt.Sscanf(g.CUDA, "%d.%d", &maj, &min)+ tag := ""+ switch {+ case maj > 13 || (maj == 13 && min >= 3):+ tag = "13.3"+ case maj > 12 || (maj == 12 && min >= 4):+ tag = "12.4"+ }+ if tag != "" {+ return "cuda", "CUDA " + tag + " on " + g.Name,+ []string{"llama-" + llamaTag + "-bin-win-cuda-" + tag + "-x64.zip", "cudart-llama-bin-win-cuda-" + tag + "-x64.zip"}, 99, vram(g)+ }+ }+ if g := info.GPU; info.Vulkan && g != nil && g.MemoryBytes >= 6*uint64(gib) {+ return "vulkan", "Vulkan on " + g.Name,+ []string{"llama-" + llamaTag + "-bin-win-cpu-x64.zip", "llama-" + llamaTag + "-bin-win-vulkan-x64.zip"}, 99, vram(g)+ }+ return "cpu", "CPU", []string{"llama-" + llamaTag + "-bin-win-cpu-x64.zip"}, 0, cpuBudget+ }+ return "cpu", "CPU", nil, 0, cpuBudget+}++// vram is the usable dedicated memory: what is free now (other programs may+// hold some), less a small reserve for the driver and display.+func vram(g *sysinfo.GPU) int64 {+ if g.FreeBytes > 0 {+ return int64(g.FreeBytes) - 400<<20+ }+ return int64(g.MemoryBytes) - 1*gib+}++// MakePlan decides backend, context and — the user's ask — whether the+// vision projector (mmproj) is worth loading on this machine.+func MakePlan(info sysinfo.Info, s settings.Local, format string) Plan {+ ram := int64(info.MemoryBytes)+ if format == "mlx" {+ p := Plan{Format: "mlx", Backend: "mlx", BackendLabel: "MLX on the Apple GPU", GPULayers: 99, Vision: "builtin"}+ p.VisionReason = "The MLX pack ships its vision tower; image input is always on."+ p.Context = s.Context+ if p.Context == 0 {+ p.Context = contextForRAM(info.MemoryGiB())+ }+ weights := mlxPack.Files[0].Size+ p.BudgetBytes = ram * 2 / 3+ if ram > 36*gib {+ p.BudgetBytes = ram * 3 / 4+ }+ p.NeedBytes = weights + int64(p.Context)*kvBytesPerToken + computeBytes + stateBytes+ p.Fits = info.AppleSilicon && p.NeedBytes <= p.BudgetBytes+ if !info.AppleSilicon {+ p.Warning = "MLX needs a Mac with Apple Silicon."+ } else if !p.Fits {+ p.Warning = fmt.Sprintf("Needs about %s of GPU memory; this Mac offers %s. Use GGUF instead.", gb(p.NeedBytes), gb(p.BudgetBytes))+ }+ return p+ }++ backend, label, assets, ngl, budget := backendFor(info)+ p := Plan{Format: "gguf", Backend: backend, BackendLabel: label, Assets: assets, GPULayers: ngl, BudgetBytes: budget}+ weights := gguf.Model.Size+ ctx := s.Context+ auto := ctx == 0+ if auto {+ ctx = contextForRAM(info.MemoryGiB())+ }+ need := func(c int) int64 { return weights + int64(c)*kvBytesPerToken + computeBytes + stateBytes }+ if auto {+ for need(ctx) > budget && ctx > 8192 {+ ctx /= 2+ }+ }+ p.Context = ctx+ p.NeedBytes = need(ctx)++ // Whatever does not fit on the GPU stays in system RAM.+ if ngl > 0 && p.NeedBytes > budget {+ free := budget - int64(ctx)*kvBytesPerToken - computeBytes - stateBytes+ layers := int(math.Floor(float64(totalLayers) * float64(free) / float64(weights)))+ if layers < 4 {+ p.GPULayers = 0+ p.Warning = fmt.Sprintf("The GPU has %s free; the model needs %s, so it runs on the CPU.", gb(budget), gb(p.NeedBytes))+ } else {+ p.GPULayers = layers+ p.Warning = fmt.Sprintf("Only %d of %d layers fit in %s of GPU memory; the rest run on the CPU (slower).", layers, totalLayers, gb(budget))+ }+ }+ cpuShare := weights+ if p.GPULayers >= totalLayers || (p.GPULayers == 99) {+ cpuShare = 0+ } else if p.GPULayers > 0 {+ cpuShare = weights * int64(totalLayers-p.GPULayers) / totalLayers+ }+ ramFree := int64(info.AvailableBytes)+ if ramFree <= 0 || ramFree > ram {+ ramFree = ram * 7 / 10+ }+ if backend == "metal" {+ p.Fits = p.NeedBytes <= budget+ if !p.Fits {+ p.Warning = fmt.Sprintf("Needs about %s of GPU memory but this Mac offers %s; expect swapping.", gb(p.NeedBytes), gb(budget))+ }+ } else {+ p.Fits = ram >= weights+2*gib && (cpuShare == 0 || cpuShare+int64(ctx)*kvBytesPerToken <= ramFree)+ if !p.Fits && p.Warning == "" {+ p.Warning = fmt.Sprintf("Needs about %s of memory; %s is available.", gb(p.NeedBytes), gb(ramFree))+ }+ }++ // Vision projector decision.+ mode := s.Vision+ if mode == "" {+ mode = "auto"+ }+ gpuFull := p.GPULayers > 0 && p.NeedBytes <= budget+ ramHeadroom := ramFree - cpuShare+ switch mode {+ case "off":+ p.Vision, p.VisionReason = "off", "Turned off in settings."+ case "gpu":+ p.Vision, p.VisionReason = "gpu", "Forced on in settings."+ case "cpu":+ p.Vision, p.VisionReason = "cpu", "Projector kept in system RAM (settings)."+ default:+ switch {+ case gpuFull && p.NeedBytes+visionGPUBytes <= budget*95/100:+ p.Vision = "gpu"+ p.VisionReason = fmt.Sprintf("On: %s of %s GPU memory leaves room for the projector.", gb(p.NeedBytes+visionGPUBytes), gb(budget))+ case backend != "metal" && ramHeadroom >= visionCPUBytes+gib:+ p.Vision = "cpu"+ if gpuFull {+ p.VisionReason = "On, encoded on the CPU: GPU memory is too tight for the projector."+ } else {+ p.VisionReason = "On, encoded on the CPU from system RAM."+ }+ default:+ p.Vision = "off"+ p.VisionReason = "Off: not enough memory left for image input on this machine."+ }+ }+ if p.Vision != "off" && backend != "cuda" {+ p.ImageMaxTokens = 1024 // Bonsai-demo caps images off CUDA for latency+ }+ return p+}diff --git a/webbrain-systray/internal/localmodel/plan_test.go b/webbrain-systray/internal/localmodel/plan_test.gonew file mode 100644index 000000000..7b5997190--- /dev/null+++ b/webbrain-systray/internal/localmodel/plan_test.go@@ -0,0 +1,102 @@+package localmodel++import (+ "strings"+ "testing"++ "github.com/esokullu/webbrain-systray/internal/settings"+ "github.com/esokullu/webbrain-systray/internal/sysinfo"+)++const g = uint64(sysinfo.GiB)++func nvidia(name string, vram, free uint64, cuda string) *sysinfo.GPU {+ return &sysinfo.GPU{Vendor: "nvidia", Name: name, MemoryBytes: vram * g, FreeBytes: free * g, CUDA: cuda}+}++// The mmproj decision for typical machines: on the GPU when about 1 GB of GPU+// memory is left after the model, on the CPU when only system RAM has room+// (never on Apple Silicon, where it would compete for the same memory), else off.+func TestPlanVisionByMachine(t *testing.T) {+ cases := []struct {+ name string+ info sysinfo.Info+ backend string+ layers string // full | partial | none+ vision string+ fits bool+ }{+ {"MacBook Air 8 GB", sysinfo.Info{OS: "darwin", Arch: "arm64", AppleSilicon: true, MemoryBytes: 8 * g, AvailableBytes: 5 * g}, "metal", "partial", "off", false},+ {"MacBook Pro 16 GB", sysinfo.Info{OS: "darwin", Arch: "arm64", AppleSilicon: true, MemoryBytes: 16 * g, AvailableBytes: 10 * g}, "metal", "full", "gpu", true},+ {"Mac Studio 64 GB", sysinfo.Info{OS: "darwin", Arch: "arm64", AppleSilicon: true, MemoryBytes: 64 * g, AvailableBytes: 40 * g}, "metal", "full", "gpu", true},+ {"RTX 4060 Laptop 8 GB", sysinfo.Info{OS: "windows", Arch: "amd64", MemoryBytes: 16 * g, AvailableBytes: 10 * g, GPU: nvidia("RTX 4060 Laptop GPU", 8, 7, "12.8")}, "cuda", "partial", "cpu", true},+ {"RTX 3060 12 GB", sysinfo.Info{OS: "windows", Arch: "amd64", MemoryBytes: 32 * g, AvailableBytes: 20 * g, GPU: nvidia("RTX 3060", 12, 11, "13.0")}, "cuda", "full", "gpu", true},+ {"RTX 4090 24 GB", sysinfo.Info{OS: "linux", Arch: "amd64", MemoryBytes: 64 * g, AvailableBytes: 50 * g, GPU: nvidia("RTX 4090", 24, 23, "13.0")}, "cuda", "full", "gpu", true},+ {"Radeon 8 GB (Vulkan)", sysinfo.Info{OS: "linux", Arch: "amd64", MemoryBytes: 32 * g, AvailableBytes: 24 * g, Vulkan: true, GPU: &sysinfo.GPU{Vendor: "amd", Name: "Radeon RX 7600", MemoryBytes: 8 * g}}, "vulkan", "partial", "cpu", true},+ {"CPU only, 16 GB", sysinfo.Info{OS: "windows", Arch: "amd64", MemoryBytes: 16 * g, AvailableBytes: 9 * g}, "cpu", "none", "cpu", true},+ {"CPU only, 8 GB", sysinfo.Info{OS: "windows", Arch: "amd64", MemoryBytes: 8 * g, AvailableBytes: 4 * g}, "cpu", "none", "off", false},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ p := MakePlan(c.info, settings.Local{}, "gguf")+ layers := "partial"+ switch {+ case p.GPULayers >= totalLayers:+ layers = "full"+ case p.GPULayers == 0:+ layers = "none"+ }+ if p.Backend != c.backend || layers != c.layers || p.Vision != c.vision || p.Fits != c.fits {+ t.Fatalf("got backend=%s layers=%s(%d) vision=%s fits=%v; want %s %s %s %v (%s)",+ p.Backend, layers, p.GPULayers, p.Vision, p.Fits, c.backend, c.layers, c.vision, c.fits, p.VisionReason)+ }+ if p.Context < 8192 || p.Context > 131072 {+ t.Fatalf("context %d out of range", p.Context)+ }+ if p.Vision != "off" && p.Backend != "cuda" && p.ImageMaxTokens != 1024 {+ t.Fatalf("image tokens not capped off CUDA: %d", p.ImageMaxTokens)+ }+ if len(p.Assets) == 0 {+ t.Fatal("no runtime assets")+ }+ })+ }+}++func TestPlanVisionOverrides(t *testing.T) {+ info := sysinfo.Info{OS: "windows", Arch: "amd64", MemoryBytes: 8 * g, AvailableBytes: 4 * g}+ for mode, want := range map[string]string{"off": "off", "gpu": "gpu", "cpu": "cpu", "auto": "off", "": "off"} {+ if got := MakePlan(info, settings.Local{Vision: mode}, "gguf").Vision; got != want {+ t.Errorf("mode %q: vision %s, want %s", mode, got, want)+ }+ }+}++func TestPlanRuntimeAssets(t *testing.T) {+ win := MakePlan(sysinfo.Info{OS: "windows", Arch: "amd64", MemoryBytes: 32 * g, GPU: nvidia("RTX 3060", 12, 11, "12.6")}, settings.Local{}, "gguf")+ if len(win.Assets) != 2 || !strings.Contains(win.Assets[0], "win-cuda-12.4-x64") || !strings.HasPrefix(win.Assets[1], "cudart-") {+ t.Errorf("windows CUDA 12.6 driver: %v", win.Assets)+ }+ old := MakePlan(sysinfo.Info{OS: "linux", Arch: "amd64", MemoryBytes: 32 * g, GPU: nvidia("GTX 1080", 8, 7, "11.8")}, settings.Local{}, "gguf")+ if old.Backend != "cpu" {+ t.Errorf("CUDA 11 driver should fall back to the CPU build, got %s", old.Backend)+ }+ for _, p := range [][]string{win.Assets, old.Assets} {+ for _, a := range p {+ if _, ok := llamaAssetSizes[a]; !ok {+ t.Errorf("asset %s has no pinned size", a)+ }+ }+ }+}++func TestPlanMLX(t *testing.T) {+ mac := MakePlan(sysinfo.Info{OS: "darwin", Arch: "arm64", AppleSilicon: true, MemoryBytes: 16 * g}, settings.Local{}, "mlx")+ if mac.Vision != "builtin" || !mac.Fits {+ t.Errorf("16 GB Apple Silicon MLX: vision=%s fits=%v (%s)", mac.Vision, mac.Fits, mac.Warning)+ }+ intel := MakePlan(sysinfo.Info{OS: "darwin", Arch: "amd64", MemoryBytes: 32 * g}, settings.Local{}, "mlx")+ if intel.Fits || intel.Warning == "" {+ t.Errorf("Intel Mac must not run MLX: fits=%v", intel.Fits)+ }+}diff --git a/webbrain-systray/internal/localmodel/terminate_unix.go b/webbrain-systray/internal/localmodel/terminate_unix.gonew file mode 100644index 000000000..89e5c7b75--- /dev/null+++ b/webbrain-systray/internal/localmodel/terminate_unix.go@@ -0,0 +1,16 @@+//go:build !windows++package localmodel++import (+ "os/exec"+ "syscall"+)++// terminate asks the server's process group to exit cleanly.+func terminate(cmd *exec.Cmd) {+ if cmd.Process == nil {+ return+ }+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)+}diff --git a/webbrain-systray/internal/localmodel/terminate_windows.go b/webbrain-systray/internal/localmodel/terminate_windows.gonew file mode 100644index 000000000..afdd44dff--- /dev/null+++ b/webbrain-systray/internal/localmodel/terminate_windows.go@@ -0,0 +1,12 @@+//go:build windows++package localmodel++import "os/exec"++// terminate kills the server; llama-server holds no state worth flushing.+func terminate(cmd *exec.Cmd) {+ if cmd.Process != nil {+ _ = cmd.Process.Kill()+ }+}diff --git a/webbrain-systray/internal/logx/logx.go b/webbrain-systray/internal/logx/logx.gonew file mode 100644index 000000000..2c5ea240e--- /dev/null+++ b/webbrain-systray/internal/logx/logx.go@@ -0,0 +1,134 @@+// Package logx sends everything the process prints (our logs, the embedded+// proxy's logrus output, stray fmt.Println calls) to a size-capped file, so a+// GUI build without a console still leaves a readable trail.+package logx++import (+ "fmt"+ "io"+ "log"+ "os"+ "path/filepath"+ "sync"+ "time"++ "github.com/sirupsen/logrus"+)++const maxSize = 8 << 20 // rotate at 8 MiB, keep one previous file++type rotating struct {+ mu sync.Mutex+ path string+ f *os.File+ size int64+}++func (r *rotating) Write(p []byte) (int, error) {+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.f == nil {+ if err := r.open(); err != nil {+ return len(p), nil // logging must never break the app+ }+ }+ if r.size+int64(len(p)) > maxSize {+ _ = r.f.Close()+ _ = os.Remove(r.path + ".1")+ _ = os.Rename(r.path, r.path+".1")+ if err := r.open(); err != nil {+ return len(p), nil+ }+ }+ n, err := r.f.Write(p)+ r.size += int64(n)+ return n, err+}++func (r *rotating) open() error {+ f, err := os.OpenFile(r.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)+ if err != nil {+ return err+ }+ st, _ := f.Stat()+ r.f = f+ if st != nil {+ r.size = st.Size()+ }+ return nil+}++var (+ file *rotating+ logger = log.New(os.Stderr, "", log.LstdFlags)+)++// Path is the current log file (empty before Init).+func Path() string {+ if file == nil {+ return ""+ }+ return file.path+}++// Init routes logs to dir/companion.log. When alsoConsole is true (a terminal is+// attached) lines are mirrored to the original stderr.+func Init(dir string, alsoConsole bool) {+ _ = os.MkdirAll(dir, 0o700)+ file = &rotating{path: filepath.Join(dir, "companion.log")}+ var w io.Writer = file+ if alsoConsole {+ w = io.MultiWriter(file, os.Stderr)+ }+ logger = log.New(w, "", log.LstdFlags)+ logrus.SetOutput(w)+ logrus.SetFormatter(&logrus.TextFormatter{DisableColors: true, FullTimestamp: true})+ if !alsoConsole {+ // The embedded proxy prints a few progress lines with fmt.Println.+ if f, err := os.OpenFile(file.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); err == nil {+ os.Stdout = f+ os.Stderr = f+ }+ }+ fmt.Fprintf(w, "\n==== WebBrain Companion started %s ====\n", time.Now().Format(time.RFC3339))+}++func Printf(format string, args ...any) { logger.Printf(format, args...) }++// Writer returns a writer that appends to the companion log with a prefix,+// for child process output.+func Writer(prefix string) io.Writer {+ return &prefixWriter{prefix: prefix}+}++type prefixWriter struct {+ prefix string+ mu sync.Mutex+ buf []byte+}++func (p *prefixWriter) Write(b []byte) (int, error) {+ p.mu.Lock()+ defer p.mu.Unlock()+ p.buf = append(p.buf, b...)+ for {+ i := -1+ for j, c := range p.buf {+ if c == '\n' {+ i = j+ break+ }+ }+ if i < 0 {+ break+ }+ line := string(p.buf[:i])+ p.buf = p.buf[i+1:]+ logger.Printf("%s %s", p.prefix, line)+ }+ if len(p.buf) > 64<<10 { // a runaway line without newline+ logger.Printf("%s %s", p.prefix, string(p.buf))+ p.buf = p.buf[:0]+ }+ return len(b), nil+}diff --git a/webbrain-systray/internal/osutil/autostart.go b/webbrain-systray/internal/osutil/autostart.gonew file mode 100644index 000000000..cb416ee4d--- /dev/null+++ b/webbrain-systray/internal/osutil/autostart.go@@ -0,0 +1,104 @@+package osutil++import (+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+)++const autostartName = "WebBrain Companion"++// Executable is the path that should be launched at login: the .app bundle's+// binary on macOS, the program itself elsewhere.+func Executable() string {+ exe, err := os.Executable()+ if err != nil {+ return ""+ }+ if r, err := filepath.EvalSymlinks(exe); err == nil {+ exe = r+ }+ return exe+}++func launchAgentPath() string {+ home, _ := os.UserHomeDir()+ return filepath.Join(home, "Library", "LaunchAgents", "one.webbrain.companion.plist")+}++func desktopEntryPath() string {+ dir := os.Getenv("XDG_CONFIG_HOME")+ if dir == "" {+ home, _ := os.UserHomeDir()+ dir = filepath.Join(home, ".config")+ }+ return filepath.Join(dir, "autostart", "webbrain-companion.desktop")+}++func xmlEscape(s string) string {+ r := strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """)+ return r.Replace(s)+}++// SetAutostart registers or removes the login item.+func SetAutostart(on bool) error {+ exe := Executable()+ switch runtime.GOOS {+ case "darwin":+ p := launchAgentPath()+ if !on {+ err := os.Remove(p)+ if os.IsNotExist(err) {+ return nil+ }+ return err+ }+ plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>one.webbrain.companion</string>+ <key>ProgramArguments</key><array><string>%s</string><string>--background</string></array>+ <key>RunAtLoad</key><true/>+ <key>ProcessType</key><string>Interactive</string>+</dict>+</plist>+`, xmlEscape(exe))+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ return err+ }+ return os.WriteFile(p, []byte(plist), 0o644)+ case "windows":+ return setRunKey(on, `"`+exe+`" --background`)+ default:+ p := desktopEntryPath()+ if !on {+ err := os.Remove(p)+ if os.IsNotExist(err) {+ return nil+ }+ return err+ }+ entry := fmt.Sprintf("[Desktop Entry]\nType=Application\nName=%s\nExec=\"%s\" --background\nX-GNOME-Autostart-enabled=true\nTerminal=false\n", autostartName, exe)+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ return err+ }+ return os.WriteFile(p, []byte(entry), 0o644)+ }+}++// AutostartEnabled reports whether the login item exists.+func AutostartEnabled() bool {+ switch runtime.GOOS {+ case "darwin":+ _, err := os.Stat(launchAgentPath())+ return err == nil+ case "windows":+ return runKeyExists()+ default:+ _, err := os.Stat(desktopEntryPath())+ return err == nil+ }+}diff --git a/webbrain-systray/internal/osutil/autostart_other.go b/webbrain-systray/internal/osutil/autostart_other.gonew file mode 100644index 000000000..d7ddafbb4--- /dev/null+++ b/webbrain-systray/internal/osutil/autostart_other.go@@ -0,0 +1,6 @@+//go:build !windows++package osutil++func setRunKey(bool, string) error { return nil }+func runKeyExists() bool { return false }diff --git a/webbrain-systray/internal/osutil/autostart_windows.go b/webbrain-systray/internal/osutil/autostart_windows.gonew file mode 100644index 000000000..eb1c9fc22--- /dev/null+++ b/webbrain-systray/internal/osutil/autostart_windows.go@@ -0,0 +1,33 @@+//go:build windows++package osutil++import "golang.org/x/sys/windows/registry"++const runKey = `Software\Microsoft\Windows\CurrentVersion\Run`++func setRunKey(on bool, command string) error {+ k, _, err := registry.CreateKey(registry.CURRENT_USER, runKey, registry.SET_VALUE|registry.QUERY_VALUE)+ if err != nil {+ return err+ }+ defer k.Close()+ if !on {+ err := k.DeleteValue(autostartName)+ if err == registry.ErrNotExist {+ return nil+ }+ return err+ }+ return k.SetStringValue(autostartName, command)+}++func runKeyExists() bool {+ k, err := registry.OpenKey(registry.CURRENT_USER, runKey, registry.QUERY_VALUE)+ if err != nil {+ return false+ }+ defer k.Close()+ _, _, err = k.GetStringValue(autostartName)+ return err == nil+}diff --git a/webbrain-systray/internal/osutil/exec.go b/webbrain-systray/internal/osutil/exec.gonew file mode 100644index 000000000..c95597d16--- /dev/null+++ b/webbrain-systray/internal/osutil/exec.go@@ -0,0 +1,21 @@+package osutil++import (+ "context"+ "os/exec"+)++// Command is exec.Command with the platform tweaks every child process of a+// tray app needs (no console window flashing up on Windows).+func Command(name string, args ...string) *exec.Cmd {+ cmd := exec.Command(name, args...)+ hideWindow(cmd)+ return cmd+}++// CommandContext is the context-aware variant of Command.+func CommandContext(ctx context.Context, name string, args ...string) *exec.Cmd {+ cmd := exec.CommandContext(ctx, name, args...)+ hideWindow(cmd)+ return cmd+}diff --git a/webbrain-systray/internal/osutil/exec_other.go b/webbrain-systray/internal/osutil/exec_other.gonew file mode 100644index 000000000..0e0ecf18f--- /dev/null+++ b/webbrain-systray/internal/osutil/exec_other.go@@ -0,0 +1,17 @@+//go:build !windows++package osutil++import (+ "os/exec"+ "syscall"+)++// Child processes get their own process group so a whole server tree can be+// stopped together.+func hideWindow(cmd *exec.Cmd) {+ if cmd.SysProcAttr == nil {+ cmd.SysProcAttr = &syscall.SysProcAttr{}+ }+ cmd.SysProcAttr.Setpgid = true+}diff --git a/webbrain-systray/internal/osutil/exec_windows.go b/webbrain-systray/internal/osutil/exec_windows.gonew file mode 100644index 000000000..4dd4bc067--- /dev/null+++ b/webbrain-systray/internal/osutil/exec_windows.go@@ -0,0 +1,18 @@+//go:build windows++package osutil++import (+ "os/exec"+ "syscall"+)++const createNoWindow = 0x08000000++func hideWindow(cmd *exec.Cmd) {+ if cmd.SysProcAttr == nil {+ cmd.SysProcAttr = &syscall.SysProcAttr{}+ }+ cmd.SysProcAttr.HideWindow = true+ cmd.SysProcAttr.CreationFlags |= createNoWindow+}diff --git a/webbrain-systray/internal/osutil/open.go b/webbrain-systray/internal/osutil/open.gonew file mode 100644index 000000000..cadbd3028--- /dev/null+++ b/webbrain-systray/internal/osutil/open.go@@ -0,0 +1,135 @@+// Package osutil wraps the small OS integrations a tray app needs: opening+// URLs and folders, a chromeless panel window, the clipboard and autostart.+package osutil++import (+ "os"+ "os/exec"+ "path/filepath"+ "runtime"++ "github.com/atotto/clipboard"+)++// OpenURL opens a link in the user's default browser.+func OpenURL(url string) error {+ switch runtime.GOOS {+ case "darwin":+ return Command("/usr/bin/open", url).Start()+ case "windows":+ return Command("rundll32", "url.dll,FileProtocolHandler", url).Start()+ default:+ return Command("xdg-open", url).Start()+ }+}++// Reveal opens a folder (or the folder containing a file) in the file manager.+func Reveal(path string) error {+ switch runtime.GOOS {+ case "darwin":+ if st, err := os.Stat(path); err == nil && !st.IsDir() {+ return Command("/usr/bin/open", "-R", path).Start()+ }+ return Command("/usr/bin/open", path).Start()+ case "windows":+ if st, err := os.Stat(path); err == nil && !st.IsDir() {+ return Command("explorer", "/select,", path).Start()+ }+ return Command("explorer", path).Start()+ default:+ if st, err := os.Stat(path); err == nil && !st.IsDir() {+ path = filepath.Dir(path)+ }+ return Command("xdg-open", path).Start()+ }+}++// Copy puts text on the clipboard.+func Copy(text string) error { return clipboard.WriteAll(text) }++// chromiumCandidates lists Chromium-family browsers that support --app.+func chromiumCandidates() []string {+ switch runtime.GOOS {+ case "darwin":+ home, _ := os.UserHomeDir()+ var out []string+ for _, app := range []string{"Google Chrome", "Microsoft Edge", "Brave Browser", "Chromium", "Vivaldi", "Arc"} {+ for _, root := range []string{"/Applications", filepath.Join(home, "Applications")} {+ p := filepath.Join(root, app+".app")+ if _, err := os.Stat(p); err == nil {+ out = append(out, p)+ }+ }+ }+ return out+ case "windows":+ var out []string+ roots := []string{os.Getenv("ProgramFiles"), os.Getenv("ProgramFiles(x86)"), os.Getenv("LOCALAPPDATA")}+ rels := []string{+ `Google\Chrome\Application\chrome.exe`,+ `Microsoft\Edge\Application\msedge.exe`,+ `BraveSoftware\Brave-Browser\Application\brave.exe`,+ }+ for _, rel := range rels {+ for _, root := range roots {+ if root == "" {+ continue+ }+ p := filepath.Join(root, rel)+ if _, err := os.Stat(p); err == nil {+ out = append(out, p)+ }+ }+ }+ return out+ default:+ var out []string+ for _, name := range []string{"google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge", "brave-browser"} {+ if p, err := exec.LookPath(name); err == nil {+ out = append(out, p)+ }+ }+ return out+ }+}++// OpenAppWindow shows url in a chromeless browser window (Chrome/Edge "app"+// mode) sized like a small panel, falling back to a normal browser tab.+func OpenAppWindow(url string, width, height int) error {+ size := "--window-size=" + itoa(width) + "," + itoa(height)+ for _, c := range chromiumCandidates() {+ var cmd *exec.Cmd+ if runtime.GOOS == "darwin" {+ cmd = Command("/usr/bin/open", "-na", c, "--args", "--app="+url, size)+ } else {+ cmd = Command(c, "--app="+url, size)+ }+ if err := cmd.Start(); err == nil {+ go func() { _ = cmd.Wait() }()+ return nil+ }+ }+ return OpenURL(url)+}++func itoa(n int) string {+ if n == 0 {+ return "0"+ }+ var b [20]byte+ i := len(b)+ neg := n < 0+ if neg {+ n = -n+ }+ for n > 0 {+ i--+ b[i] = byte('0' + n%10)+ n /= 10+ }+ if neg {+ i--+ b[i] = '-'+ }+ return string(b[i:])+}diff --git a/webbrain-systray/internal/osutil/translocate.go b/webbrain-systray/internal/osutil/translocate.gonew file mode 100644index 000000000..acf9bc363--- /dev/null+++ b/webbrain-systray/internal/osutil/translocate.go@@ -0,0 +1,19 @@+package osutil++import (+ "os"+ "runtime"+ "strings"+)++// Translocated reports whether macOS runs the app from a temporary read-only+// copy (Gatekeeper path randomization) because it was opened where it was+// downloaded instead of from Applications. Start at login would point at that+// copy, which disappears.+func Translocated() bool {+ if runtime.GOOS != "darwin" {+ return false+ }+ exe, err := os.Executable()+ return err == nil && strings.Contains(exe, "/AppTranslocation/")+}diff --git a/webbrain-systray/internal/panel/assets/app.css b/webbrain-systray/internal/panel/assets/app.cssnew file mode 100644index 000000000..0a1bb182a--- /dev/null+++ b/webbrain-systray/internal/panel/assets/app.css@@ -0,0 +1,451 @@+@font-face {+ font-family: "Bricolage";+ font-style: normal;+ font-display: swap;+ font-weight: 200 800;+ src: url(fonts/bricolage-grotesque-latin-opsz-normal.woff2) format("woff2-variations");+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: "Bricolage";+ font-style: normal;+ font-display: swap;+ font-weight: 200 800;+ src: url(fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2) format("woff2-variations");+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;+}++/* Brain tissue palette, taken from the WebBrain mark. */+:root {+ --paper: #fbf6f8;+ --raised: #ffffff;+ --ink: #2b1426;+ --muted: #7a5c6e;+ --brain: #d9396f;+ --brain-ink: #ffffff;+ --tissue: #f1dbe5;+ --line: #ecdbe3;+ --hover: #f5e6ed;+ --low: #b85c12;+ --ok: #217a5c;+ --danger: #b3261e;+ --focus: #8a2d63;+ --shadow: 0 18px 50px rgba(64, 18, 48, .18);+ --display: "Bricolage", ui-sans-serif, system-ui, sans-serif;+ --ui: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ --code: ui-monospace, "SF Mono", "Cascadia Mono", Menlo, Consolas, monospace;+ color-scheme: light;+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) {+ --paper: #1a0f18;+ --raised: #231520;+ --ink: #f7e9f0;+ --muted: #b693a8;+ --brain: #ff6fa5;+ --brain-ink: #2b0c1f;+ --tissue: #3a2233;+ --line: #33202d;+ --hover: #2a1926;+ --low: #f0a04b;+ --ok: #4cc79a;+ --danger: #ff8a80;+ --focus: #ffb3cf;+ --shadow: 0 18px 50px rgba(0, 0, 0, .5);+ color-scheme: dark;+ }+}+:root[data-theme="dark"] {+ --paper: #1a0f18;+ --raised: #231520;+ --ink: #f7e9f0;+ --muted: #b693a8;+ --brain: #ff6fa5;+ --brain-ink: #2b0c1f;+ --tissue: #3a2233;+ --line: #33202d;+ --hover: #2a1926;+ --low: #f0a04b;+ --ok: #4cc79a;+ --danger: #ff8a80;+ --focus: #ffb3cf;+ --shadow: 0 18px 50px rgba(0, 0, 0, .5);+ color-scheme: dark;+}++* { box-sizing: border-box; }+html, body { margin: 0; }+body {+ background: var(--paper);+ color: var(--ink);+ font: 14px/1.45 var(--ui);+ -webkit-font-smoothing: antialiased;+}+main {+ max-width: 520px;+ margin: 0 auto;+ padding: 18px 20px 22px;+}+button, input, select { font: inherit; color: inherit; }+:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 6px; }+.hidden { display: none !important; }+.nowrap { white-space: nowrap; }++/* Header */+.top {+ display: grid;+ grid-template-columns: 34px 1fr;+ column-gap: 11px;+ align-items: center;+ margin-bottom: 16px;+}+.top img { grid-row: span 2; }+.top h1 {+ font: 650 19px/1.15 var(--display);+ font-variation-settings: "opsz" 32;+ letter-spacing: -.01em;+ margin: 0;+}+.top .status {+ display: flex;+ align-items: center;+ gap: 7px;+ margin: 2px 0 0;+ color: var(--muted);+ font-size: 12.5px;+}+.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); flex: none; display: inline-block; }+.dot.on { background: var(--ok); box-shadow: 0 0 0 2.5px color-mix(in srgb, var(--ok) 22%, transparent); }+.dot.warn { background: var(--low); }+.dot.busy { background: var(--brain); animation: pulse 1.4s ease-in-out infinite; }+@keyframes pulse { 50% { opacity: .35; } }++.notice {+ margin: 0 0 14px;+ padding: 10px 12px;+ border-left: 3px solid var(--low);+ background: color-mix(in srgb, var(--low) 9%, transparent);+ border-radius: 0 8px 8px 0;+ font-size: 13px;+}++/* Buttons */+.btn {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ border: 1px solid var(--line);+ background: var(--raised);+ border-radius: 999px;+ padding: 6px 13px;+ font-size: 13px;+ font-weight: 560;+ cursor: pointer;+ white-space: nowrap;+}+.btn.small { padding: 4px 11px; font-size: 12.5px; }+.btn:hover { border-color: color-mix(in srgb, var(--brain) 45%, var(--line)); }+.btn.primary { background: var(--brain); color: var(--brain-ink); border-color: transparent; }+.btn.primary:hover { filter: brightness(1.06); }+.btn.quiet { border-color: transparent; background: transparent; color: var(--muted); }+.btn.quiet:hover { color: var(--ink); }+.btn.danger { color: var(--danger); }+.btn:disabled { opacity: .5; cursor: default; }+.link { background: none; border: 0; padding: 0; color: var(--muted); text-decoration: underline; text-underline-offset: 2px; cursor: pointer; font-size: inherit; }+.link:hover { color: var(--ink); }+.icon-btn {+ flex: none;+ width: 30px; height: 30px;+ display: grid; place-items: center;+ border: 0; border-radius: 50%;+ background: transparent;+ color: var(--muted);+ cursor: pointer;+}+.icon-btn:hover { background: var(--hover); color: var(--ink); }++/* The address WebBrain needs */+.addr {+ border: 1px solid var(--line);+ background: var(--raised);+ border-radius: 12px;+}+.addr-row {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 7px 6px 7px 12px;+ min-height: 42px;+}+.addr-row + .addr-row { border-top: 1px solid var(--line); }+.addr-label { flex: none; width: 92px; font-size: 12px; color: var(--muted); }+.addr-value {+ flex: 1;+ min-width: 0;+ font: 13px/1.3 var(--code);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.addr-row .btn { flex: none; }+.addr-missing { margin: 0; padding: 10px 12px; font-size: 12.5px; color: var(--low); border-top: 1px solid var(--line); }+.note { margin: 7px 2px 0; font-size: 12.5px; color: var(--muted); }+.note.first-run { color: var(--ink); }++/* Sections and their rows */+section { margin-top: 22px; }+.sec-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ min-height: 28px;+ margin-bottom: 4px;+}+h2 {+ font: 620 15.5px/1.2 var(--display);+ font-variation-settings: "opsz" 20;+ margin: 0;+}+.rows { list-style: none; margin: 0; padding: 0; }+.rows > li + li { border-top: 1px solid var(--line); }+.item {+ display: grid;+ grid-template-columns: 30px minmax(0, 1fr);+ align-items: center;+ column-gap: 11px;+ width: 100%;+ margin: 3px 0;+ padding: 7px 6px;+ border: 0;+ border-radius: 10px;+ background: transparent;+ text-align: left;+ cursor: pointer;+}+.item:hover { background: var(--hover); }+.item.sub-item { grid-template-columns: 30px minmax(0, 1fr) 112px 42px; }+.badge {+ width: 30px; height: 30px; border-radius: 9px;+ display: grid; place-items: center; flex: none;+ font: 700 12.5px/1 var(--display);+ color: #fff;+ background: hsl(var(--h) var(--s, 52%) var(--l, 46%));+}+.txt { display: grid; min-width: 0; }+.name {+ font: 600 14.5px/1.25 var(--display);+ font-variation-settings: "opsz" 18;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.plan { font-weight: 430; color: var(--muted); }+.sub {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ font-size: 12px;+ color: var(--muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sub.warn { color: var(--low); }+li.off .badge { filter: grayscale(1); opacity: .55; }++/* Usage meters: twenty cells, five percent each. */+.cells { display: grid; grid-template-columns: repeat(20, 1fr); gap: 2px; height: 10px; }+.cells i { border-radius: 2px; background: var(--tissue); position: relative; overflow: hidden; }+.cells i::after {+ content: ""; position: absolute; inset: 0;+ background: var(--fill, var(--brain));+ transform-origin: left;+ transform: scaleX(var(--f, 0));+ transition: transform .5s cubic-bezier(.2,.7,.2,1);+ transition-delay: calc(var(--i) * 18ms);+}+.low { --fill: var(--low); }+.pct {+ font: 650 15px/1 var(--display);+ font-variation-settings: "opsz" 16;+ font-variant-numeric: tabular-nums;+ text-align: right;+}+.low .pct { color: var(--low); }++/* Local models: the row opens details, the button acts. */+li.model {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ align-items: center;+ column-gap: 8px;+}+li.model .bar { grid-column: 1 / -1; margin: -2px 6px 9px 47px; }+.bar { height: 4px; border-radius: 999px; background: var(--tissue); overflow: hidden; }+.bar span { display: block; height: 100%; background: var(--brain); border-radius: inherit; transition: width .3s; }+.bar.busy span { width: 35% !important; animation: slide 1.2s ease-in-out infinite; }+@keyframes slide { 0% { transform: translateX(-100%); } 100% { transform: translateX(290%); } }++.empty { padding: 4px 0 6px; color: var(--muted); }+.empty p { margin: 0 0 12px; max-width: 44ch; }+.error-box { margin: 0 0 12px; padding: 9px 12px; border-radius: 10px; background: color-mix(in srgb, var(--danger) 10%, transparent); font-size: 13px; overflow-wrap: anywhere; }++.foot { margin-top: 18px; padding-top: 10px; border-top: 1px solid var(--line); }+.foot .btn { margin-left: -8px; }++/* Sheets: details, settings and adding a subscription */+.scrim { position: fixed; inset: 0; background: rgba(30, 8, 24, .38); z-index: 20; display: flex; align-items: flex-end; justify-content: center; }+.sheet {+ width: 100%; max-width: 560px; max-height: 92vh; overflow: auto;+ background: var(--paper);+ border-radius: 18px 18px 0 0;+ box-shadow: var(--shadow);+ padding: 14px 20px 22px;+ animation: rise .28s cubic-bezier(.2,.8,.2,1);+}+.sheet:focus { outline: none; }+@keyframes rise { from { transform: translateY(40px); opacity: 0; } to { transform: none; opacity: 1; } }+.sheet-head { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 14px; }+.sheet-title { flex: 1; min-width: 0; padding-top: 4px; }+.sheet h3 { font: 640 18px/1.2 var(--display); font-variation-settings: "opsz" 24; margin: 0; }+.sheet .sub { display: block; white-space: normal; margin: 3px 0 0; font-size: 12.5px; }+.badge.big { width: 38px; height: 38px; border-radius: 11px; font-size: 14px; }+.sheet h4 { font: 620 14px/1.2 var(--display); margin: 20px 0 10px; }+.sheet-note { margin: 0; font-size: 12.5px; color: var(--muted); }+.sheet-note.warn { color: var(--low); margin-bottom: 12px; }+.sheet-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-top: 18px; }+.updated { flex: 1; font-size: 12px; color: var(--muted); }+.confirm {+ display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px;+ margin-top: 16px; padding: 10px 12px;+ border-radius: 10px;+ background: color-mix(in srgb, var(--danger) 8%, transparent);+ font-size: 13px;+}+.confirm > span:first-child { flex: 1 1 200px; }+.confirm-actions { display: flex; gap: 6px; }++.meters { display: grid; gap: 9px; }+.meter { display: grid; grid-template-columns: 76px 1fr 46px; align-items: center; column-gap: 10px; }+.meter .cells { height: 12px; }+.meter .win { font-size: 12.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.meter .pct { font-size: 16px; }+.meter .when { grid-column: 2 / 4; font-size: 11.5px; color: var(--muted); margin-top: 2px; }+.meter .when.urgent { color: var(--low); }++.status-block {+ margin: 0 0 14px;+ padding: 10px 12px;+ border: 1px solid var(--line);+ border-radius: 12px;+ background: var(--raised);+}+.status-line { display: flex; align-items: center; gap: 10px; min-height: 30px; }+.status-text { flex: 1; min-width: 0; display: flex; align-items: center; gap: 7px; font-size: 13px; overflow-wrap: anywhere; }+.status-text.warn { color: var(--low); }+.status-actions { flex: none; display: flex; gap: 4px; }+.status-block .bar { margin-top: 8px; }+.test { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin: -4px 0 14px; }+.result { font-size: 12.5px; color: var(--muted); }++.facts { display: grid; grid-template-columns: 104px minmax(0, 1fr); gap: 7px 12px; margin: 0; font-size: 13px; }+.facts dt { color: var(--muted); }+.facts dd { margin: 0; min-width: 0; }+.facts .why { display: block; color: var(--muted); font-size: 12px; margin-top: 1px; }+.vision-on { color: var(--ok); font-weight: 600; }+.vision-off { color: var(--muted); font-weight: 600; }+.chip-code { font: 12.5px/1.4 var(--code); padding: 2px 8px; border-radius: 7px; background: var(--tissue); border: 0; cursor: pointer; }++.seg { display: inline-flex; padding: 3px; border-radius: 999px; background: var(--tissue); gap: 2px; }+.seg button { border: 0; background: transparent; border-radius: 999px; padding: 3px 11px; font-size: 12.5px; font-weight: 560; color: var(--muted); cursor: pointer; }+.seg button[aria-pressed="true"] { background: var(--raised); color: var(--ink); box-shadow: 0 1px 2px rgba(0,0,0,.08); }+.seg button:disabled { cursor: default; }+.seg:has(button:disabled) { opacity: .6; }++.opts { display: grid; gap: 11px; }+.setting, .kv { display: grid; grid-template-columns: 104px minmax(0, 1fr) auto; align-items: center; column-gap: 10px; font-size: 13px; }+.setting > span, .kv .k { color: var(--muted); }+.setting select { justify-self: start; }+.kv .v { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.kv .v.mono { font: 12.5px/1.3 var(--code); }+.kv-actions { display: flex; gap: 2px; }+.kv input { width: 100px; }+select, input[type="number"], input[type="text"] {+ border: 1px solid var(--line);+ background: var(--raised);+ border-radius: 9px;+ padding: 5px 9px;+ font-size: 13px;+}+.chips { list-style: none; padding: 0; margin: 0; display: flex; flex-wrap: wrap; gap: 6px; }+.chips button { border: 1px solid var(--line); background: transparent; border-radius: 7px; padding: 2px 8px; font: 12px/1.5 var(--code); cursor: pointer; }+.chips button:hover { background: var(--hover); }+.sheet-foot {+ display: flex; justify-content: space-between; align-items: center; gap: 12px;+ margin-top: 22px; padding-top: 12px;+ border-top: 1px solid var(--line);+ font-size: 12.5px; color: var(--muted);+}+.sheet-foot + .sheet-actions { margin-top: 10px; }++/* Toggle */+.toggle { display: flex; align-items: center; gap: 10px; cursor: pointer; font-size: 13px; }+.toggle input { flex: none; appearance: none; width: 34px; height: 20px; border-radius: 999px; background: var(--tissue); position: relative; cursor: pointer; margin: 0; transition: background .2s; }+.toggle input::after { content: ""; position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: var(--raised); box-shadow: 0 1px 2px rgba(0,0,0,.2); transition: transform .2s; }+.toggle input:checked { background: var(--brain); }+.toggle input:checked::after { transform: translateX(14px); }+.toggle input:disabled { opacity: .5; cursor: default; }++/* Adding a subscription */+.providers { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }+.providers button {+ width: 100%; display: flex; align-items: center; gap: 12px;+ text-align: left; border: 1px solid transparent; background: transparent; border-radius: 12px; padding: 8px 10px; cursor: pointer;+}+.providers button:hover { background: var(--raised); border-color: var(--line); }+.ptxt { display: grid; min-width: 0; }+.providers .pname { font: 600 15px/1.2 var(--display); }+.providers .pprod { color: var(--muted); font-size: 12.5px; }+.providers .ptag { margin-left: auto; flex: none; font-size: 11.5px; color: var(--muted); }+details.more { margin-top: 10px; }+details.more summary { cursor: pointer; color: var(--muted); font-size: 12.5px; padding: 4px 0; }+details.more .providers { margin-top: 6px; }+.code-big {+ font: 700 34px/1 var(--display);+ font-variation-settings: "opsz" 48;+ letter-spacing: .06em;+ margin: 4px 0 16px;+}+.row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }+.waiting { display: flex; align-items: center; gap: 10px; color: var(--muted); font-size: 13px; margin: 2px 0 14px; }+.row + .waiting { margin-top: 16px; }+.spinner { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--tissue); border-top-color: var(--brain); animation: spin .9s linear infinite; }+@keyframes spin { to { transform: rotate(360deg); } }+.paste { display: grid; gap: 8px; margin-top: 8px; }+.paste input { width: 100%; }+.success-mark { flex: none; width: 38px; height: 38px; border-radius: 50%; display: grid; place-items: center; font: 700 20px/1 var(--display); color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }++/* Toast */+.toast {+ position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%);+ background: var(--ink); color: var(--paper);+ padding: 8px 14px; border-radius: 999px; font-size: 13px; z-index: 40;+ box-shadow: var(--shadow);+}++@media (prefers-reduced-motion: reduce) {+ *, *::before, *::after { animation: none !important; transition: none !important; }+}+@media (max-width: 400px) {+ main { padding: 16px 16px 20px; }+ .item.sub-item { grid-template-columns: 30px minmax(0, 1fr) 76px 38px; column-gap: 9px; }+ .addr-label { width: auto; }+ .addr.multi .addr-row { flex-wrap: wrap; row-gap: 2px; }+ .addr.multi .addr-label { flex-basis: 100%; }+ .meter { grid-template-columns: 60px 1fr 42px; }+ .facts, .setting, .kv { grid-template-columns: 1fr; gap: 3px 0; }+ .kv .btn, .kv .kv-actions, .setting select { justify-self: start; }+ li.model .bar { margin-left: 6px; }+}diff --git a/webbrain-systray/internal/panel/assets/app.js b/webbrain-systray/internal/panel/assets/app.jsnew file mode 100644index 000000000..aab6edb7f--- /dev/null+++ b/webbrain-systray/internal/panel/assets/app.js@@ -0,0 +1,1187 @@+"use strict";+(() => {+ // The tray opens /companion/#k=<panel key>&view=<view>; keep the key for+ // this window only.+ const hash = new URLSearchParams(location.hash.slice(1));+ let key = hash.get("k") || "";+ try {+ if (key) sessionStorage.setItem("wbc-key", key);+ else key = sessionStorage.getItem("wbc-key") || "";+ } catch (_) {}+ const startView = hash.get("view") || "";+ if (location.hash) history.replaceState(null, "", location.pathname);++ const I18N = {+ en: {+ running: "Running",+ stopped: "Not running",+ reconnecting: "Reconnecting…",+ thisComputer: "This computer",+ otherDevices: "Other devices",+ apiKey: "API key",+ copy: "Copy",+ copied: "Copied",+ show: "Show",+ hide: "Hide",+ noKey: "No API key needed on this computer. If an app asks for one, type anything.",+ firstRun: "In WebBrain, open Providers, choose Local OpenAI-compatible Proxy and paste this address. When it asks for an API key, type anything.",+ gotIt: "Got it",+ networkNote: "Other devices connect with the API key. Anyone on this network who has it can use your subscriptions.",+ noNetworkAddr: "No network address found. Is this computer on a network?",+ subs: "Subscriptions",+ add: "Add",+ addFirst: "Add a subscription",+ emptySubs: "Sign in with Claude, ChatGPT, Google, Grok or Kimi. Each one shows up here with how much of it is left.",+ resetsIn: "Resets in {d}",+ emptyUntil: "Empty until {when}",+ paused: "Paused",+ reading: "Reading usage…",+ noQuotaShort: "Usage not reported",+ noQuota: "This service does not report usage.",+ quotaErrorShort: "Usage unavailable",+ quotaError: "Usage unavailable: {msg}",+ w5h: "5 hours", wday: "Day", wweek: "Week", wmonth: "Month",+ fivehour: "5-hour limit", daily: "Daily limit", weekly: "Weekly limit", monthly: "Monthly limit",+ updated: "Updated {ago}",+ refreshUsage: "Refresh",+ refreshing: "Refreshing…",+ pause: "Pause",+ resume: "Resume",+ pausedNote: "Paused. WebBrain won't use this login until you resume it.",+ remove: "Remove",+ removeConfirm: "Remove {name}? You can sign in again later.",+ keep: "Keep",+ close: "Close",+ models: "Local models",+ d1Name: "d1 decision model",+ runningAs: "Running as {id}",+ installedSize: "Installed, {size}",+ downloadSize: "{size} download",+ maySlow: "May run slowly on this machine",+ starting: "Loading into memory…",+ stopping: "Stopping…",+ loading: "Loading…",+ ready: "Ready",+ readyServed: "Ready, {n} decisions served",+ notSupported: "Not available for this platform yet",+ install: "Install",+ cancel: "Cancel",+ start: "Start",+ stop: "Stop",+ load: "Load",+ unload: "Unload",+ retry: "Try again",+ showLog: "Show log",+ ofSize: "{done} of {total}",+ eta: "{left} left",+ localLede: "Runs on this machine and appears to WebBrain as {id}.",+ thisMachine: "This machine",+ format: "Format",+ runtime: "Runtime",+ vision: "Images",+ context: "Context",+ onDisk: "On disk",+ download: "Download",+ visionGpu: "On",+ visionCpu: "On, CPU",+ visionOff: "Off",+ visionBuiltin: "On",+ whyBuiltin: "The MLX pack includes its vision tower.",+ whyGpu: "{need} of {budget} GPU memory leaves room for the projector.",+ whyCpu: "GPU memory is tight, so images are encoded on the CPU.",+ whyOff: "Not enough memory left for the vision projector.",+ whyForced: "Set by you below.",+ tokens: "{n} tokens",+ layers: "{n} of 64 layers on the GPU",+ warnFit: "Needs about {need}; this machine offers {budget}. It may run slowly or not at all.",+ warnPartial: "Only {n} of 64 layers fit in GPU memory; the rest run on the CPU and will be slower.",+ warnCpu: "No supported GPU was found, so it runs on the CPU. Expect a few tokens per second.",+ warnMlx: "MLX needs a Mac with Apple Silicon.",+ formatGGUF: "GGUF", formatMLX: "MLX",+ ggufNote: "llama.cpp (PrismML build), PTQ1_0 with Q8_0 vision projector",+ mlxNote: "MLX 2-bit pack with mlx-vlm",+ options: "Options",+ auto: "Auto", gpu: "GPU", cpu: "CPU", off: "Off",+ startWith: "Start with the companion",+ removeFiles: "Delete downloaded files",+ removeFilesConfirm: "Delete {size} of model files?",+ delete: "Delete",+ decisionLede: "WebBrain's d1 model answers yes/no, choice and score questions about a page, here instead of in the browser.",+ endpoint: "Endpoint",+ served: "Served",+ servedValue: "{n} decisions, last in {ms} ms",+ license: "License",+ test: "Run a test decision",+ testing: "Deciding…",+ testResult: "Answer {choice} with {p}% confidence in {ms} ms.",+ settings: "Settings",+ startLogin: "Start at login",+ language: "Language",+ networkToggle: "Allow other devices on this network",+ networkHelp: "Listens on 0.0.0.0 instead of 127.0.0.1. Other devices connect with the API key; your system may ask you to allow incoming connections.",+ newKey: "Make a new API key",+ newKeyConfirm: "Other devices stop working until they get the new key.",+ connection: "Connection",+ port: "Port",+ apply: "Apply",+ portChanged: "The companion moved to port {port}. Reopen the panel from the tray icon.",+ otherFormats: "Anthropic, Gemini",+ modelsLabel: "Models",+ modelsCount: "{n} available",+ modelsNone: "None yet",+ showList: "Show",+ hideList: "Hide",+ logFile: "Show log file",+ version: "Version {v}",+ quit: "Quit WebBrain Companion",+ quitConfirm: "WebBrain loses access to your subscriptions until you open the companion again.",+ trayHidden: "macOS is hiding the WebBrain Companion icon because the menu bar is full. You can always come back here by opening WebBrain Companion again. To make room, hide menu bar icons you don't use in System Settings, Menu Bar.",+ translocated: "WebBrain Companion is running from a temporary copy that macOS made because the app wasn't moved to Applications. Quit it, move it to your Applications folder and open it from there; starting at login needs that.",+ pickTitle: "Add a subscription",+ pickSub: "You sign in on the provider's own page. The companion stores the login on this computer only.",+ more: "More services",+ browserFlow: "Sign in in your browser",+ deviceFlow: "Enter a code",+ waitTitle: "Finish signing in to {name}",+ waitBrowser: "A sign-in page opened in your browser. Approve access there and this panel updates by itself.",+ waitDevice: "Open the page below and enter this code:",+ openPage: "Open the sign-in page",+ openAgain: "Open the page again",+ copyCode: "Copy code",+ waiting: "Waiting for {name}…",+ noReturn: "The browser shows an error after you approve?",+ pasteHelp: "Copy the full address from the browser's address bar and paste it here.",+ pastePh: "http://localhost:…",+ submit: "Finish sign-in",+ doneTitle: "{name} is connected",+ doneSub: "Its models are now on your endpoint. Usage appears in a moment.",+ done: "Done",+ failTitle: "Sign-in didn't finish",+ tokenMissing: "Open this panel from the WebBrain Companion icon in your menu bar or system tray.",+ ago_now: "just now", ago_m: "{n} min ago", ago_h: "{n} h ago",+ phase_installing: "Installing",+ },+ tr: {+ running: "Çalışıyor",+ stopped: "Çalışmıyor",+ reconnecting: "Yeniden bağlanıyor…",+ thisComputer: "Bu bilgisayar",+ otherDevices: "Diğer cihazlar",+ apiKey: "API anahtarı",+ copy: "Kopyala",+ copied: "Kopyalandı",+ show: "Göster",+ hide: "Gizle",+ noKey: "Bu bilgisayarda API anahtarı gerekmez. Bir uygulama isterse herhangi bir şey yaz.",+ firstRun: "WebBrain'de Sağlayıcılar sayfasını aç, Local OpenAI-compatible Proxy'yi seç ve bu adresi yapıştır. API anahtarı isterse herhangi bir şey yaz.",+ gotIt: "Tamam",+ networkNote: "Diğer cihazlar API anahtarıyla bağlanır. Bu ağda anahtara sahip olan herkes aboneliklerini kullanabilir.",+ noNetworkAddr: "Ağ adresi bulunamadı. Bu bilgisayar bir ağa bağlı mı?",+ subs: "Abonelikler",+ add: "Ekle",+ addFirst: "Abonelik ekle",+ emptySubs: "Claude, ChatGPT, Google, Grok ya da Kimi ile giriş yap. Her biri burada ne kadarının kaldığıyla görünür.",+ resetsIn: "{d} sonra sıfırlanır",+ emptyUntil: "{when} tarihine kadar boş",+ paused: "Duraklatıldı",+ reading: "Kullanım okunuyor…",+ noQuotaShort: "Kullanım bildirilmiyor",+ noQuota: "Bu hizmet kullanım bilgisi vermiyor.",+ quotaErrorShort: "Kullanım okunamadı",+ quotaError: "Kullanım okunamadı: {msg}",+ w5h: "5 saat", wday: "Gün", wweek: "Hafta", wmonth: "Ay",+ fivehour: "5 saatlik sınır", daily: "Günlük sınır", weekly: "Haftalık sınır", monthly: "Aylık sınır",+ updated: "{ago} güncellendi",+ refreshUsage: "Yenile",+ refreshing: "Yenileniyor…",+ pause: "Duraklat",+ resume: "Sürdür",+ pausedNote: "Duraklatıldı. Sürdürene kadar WebBrain bu girişi kullanmaz.",+ remove: "Kaldır",+ removeConfirm: "{name} kaldırılsın mı? Daha sonra yeniden giriş yapabilirsin.",+ keep: "Kalsın",+ close: "Kapat",+ models: "Yerel modeller",+ d1Name: "d1 karar modeli",+ runningAs: "{id} olarak çalışıyor",+ installedSize: "Kurulu, {size}",+ downloadSize: "{size} indirme",+ maySlow: "Bu makinede yavaş çalışabilir",+ starting: "Belleğe yükleniyor…",+ stopping: "Durduruluyor…",+ loading: "Yükleniyor…",+ ready: "Hazır",+ readyServed: "Hazır, {n} karar verildi",+ notSupported: "Bu platformda henüz yok",+ install: "Kur",+ cancel: "Vazgeç",+ start: "Başlat",+ stop: "Durdur",+ load: "Yükle",+ unload: "Boşalt",+ retry: "Tekrar dene",+ showLog: "Günlüğü göster",+ ofSize: "{total} içinden {done}",+ eta: "{left} kaldı",+ localLede: "Bu makinede çalışır ve WebBrain'e {id} olarak görünür.",+ thisMachine: "Bu makine",+ format: "Biçim",+ runtime: "Çalışma",+ vision: "Görsel",+ context: "Bağlam",+ onDisk: "Diskte",+ download: "İndirme",+ visionGpu: "Açık",+ visionCpu: "Açık, CPU",+ visionOff: "Kapalı",+ visionBuiltin: "Açık",+ whyBuiltin: "MLX paketi görsel kuleyi içeriyor.",+ whyGpu: "{budget} GPU belleğinin {need} kadarı kullanılınca projektöre yer kalıyor.",+ whyCpu: "GPU belleği dar; görseller CPU'da işleniyor.",+ whyOff: "Görsel projektörü için yeterli bellek kalmıyor.",+ whyForced: "Aşağıda sen ayarladın.",+ tokens: "{n} token",+ layers: "64 katmanın {n} tanesi GPU'da",+ warnFit: "Yaklaşık {need} gerekiyor; bu makinede {budget} var. Yavaş çalışabilir ya da hiç çalışmayabilir.",+ warnPartial: "64 katmanın yalnızca {n} tanesi GPU belleğine sığıyor; kalanı CPU'da çalışır ve daha yavaş olur.",+ warnCpu: "Desteklenen bir GPU bulunamadı, CPU'da çalışacak. Saniyede birkaç token bekle.",+ warnMlx: "MLX için Apple Silicon bir Mac gerekir.",+ formatGGUF: "GGUF", formatMLX: "MLX",+ ggufNote: "llama.cpp (PrismML sürümü), PTQ1_0 ve Q8_0 görsel projektör",+ mlxNote: "mlx-vlm ile MLX 2-bit paket",+ options: "Seçenekler",+ auto: "Otomatik", gpu: "GPU", cpu: "CPU", off: "Kapalı",+ startWith: "Companion ile birlikte başlat",+ removeFiles: "İndirilen dosyaları sil",+ removeFilesConfirm: "{size} model dosyası silinsin mi?",+ delete: "Sil",+ decisionLede: "WebBrain'in d1 modeli sayfa hakkındaki evet/hayır, seçim ve puan sorularını tarayıcı yerine burada yanıtlar.",+ endpoint: "Uç nokta",+ served: "Verilen",+ servedValue: "{n} karar, sonuncusu {ms} ms",+ license: "Lisans",+ test: "Deneme kararı çalıştır",+ testing: "Karar veriliyor…",+ testResult: "Yanıt {choice}, %{p} güvenle, {ms} ms.",+ settings: "Ayarlar",+ startLogin: "Oturum açılınca başlat",+ language: "Dil",+ networkToggle: "Bu ağdaki diğer cihazlara izin ver",+ networkHelp: "127.0.0.1 yerine 0.0.0.0'da dinler. Diğer cihazlar API anahtarıyla bağlanır; sistemin gelen bağlantılara izin vermeni isteyebilir.",+ newKey: "Yeni API anahtarı oluştur",+ newKeyConfirm: "Diğer cihazlar yeni anahtarı alana kadar çalışmaz.",+ connection: "Bağlantı",+ port: "Port",+ apply: "Uygula",+ portChanged: "Companion {port} portuna taşındı. Paneli tepsideki simgeden yeniden aç.",+ otherFormats: "Anthropic, Gemini",+ modelsLabel: "Modeller",+ modelsCount: "{n} kullanılabilir",+ modelsNone: "Henüz yok",+ showList: "Göster",+ hideList: "Gizle",+ logFile: "Günlük dosyasını göster",+ version: "Sürüm {v}",+ quit: "WebBrain Companion'dan çık",+ quitConfirm: "Yeniden açana kadar WebBrain aboneliklerine erişemez.",+ trayHidden: "Menü çubuğu dolu olduğu için macOS, WebBrain Companion simgesini gizliyor. Bu panele her zaman WebBrain Companion'ı yeniden açarak dönebilirsin. Yer açmak için kullanmadığın simgeleri Sistem Ayarları, Menü Çubuğu bölümünden gizle.",+ translocated: "WebBrain Companion, Uygulamalar klasörüne taşınmadığı için macOS'un oluşturduğu geçici bir kopyadan çalışıyor. Uygulamadan çık, Uygulamalar klasörüne taşı ve oradan aç; oturum açılınca başlatma için bu gerekli.",+ pickTitle: "Abonelik ekle",+ pickSub: "Girişi sağlayıcının kendi sayfasında yaparsın. Companion girişi yalnızca bu bilgisayarda saklar.",+ more: "Diğer hizmetler",+ browserFlow: "Tarayıcıda giriş",+ deviceFlow: "Kod gir",+ waitTitle: "{name} girişini tamamla",+ waitBrowser: "Tarayıcında bir giriş sayfası açıldı. Orada erişimi onayla; bu panel kendiliğinden güncellenir.",+ waitDevice: "Aşağıdaki sayfayı aç ve bu kodu gir:",+ openPage: "Giriş sayfasını aç",+ openAgain: "Sayfayı yeniden aç",+ copyCode: "Kodu kopyala",+ waiting: "{name} bekleniyor…",+ noReturn: "Onayladıktan sonra tarayıcı hata mı gösteriyor?",+ pasteHelp: "Tarayıcının adres çubuğundaki tam adresi kopyalayıp buraya yapıştır.",+ pastePh: "http://localhost:…",+ submit: "Girişi tamamla",+ doneTitle: "{name} bağlandı",+ doneSub: "Modelleri artık uç noktanda. Kullanım birazdan görünür.",+ done: "Bitti",+ failTitle: "Giriş tamamlanmadı",+ tokenMissing: "Bu paneli menü çubuğundaki ya da sistem tepsisindeki WebBrain Companion simgesinden aç.",+ ago_now: "az önce", ago_m: "{n} dk önce", ago_h: "{n} sa önce",+ phase_installing: "Kuruluyor",+ },+ };++ let lang = "en";+ const t = (k, vars) => {+ let s = (I18N[lang] && I18N[lang][k]) || I18N.en[k] || k;+ if (vars) for (const [n, v] of Object.entries(vars)) s = s.split("{" + n + "}").join(String(v));+ return s;+ };+ // Install steps, machine and runtime descriptions arrive from the companion in+ // English; Turkish gets a translation.+ const STEP_TR = [+ [/^Verifying (.+)$/, (m) => `${goText(m[1])} doğrulanıyor`],+ [/^Bonsai 2 27B weights \((.+)\)$/, (m) => `Bonsai 2 27B ağırlıkları (${m[1]})`],+ [/^Vision projector \((.+)\)$/, (m) => `Görsel projektör (${m[1]})`],+ [/^llama\.cpp runtime \((.+)\)$/, (m) => `llama.cpp çalışma ortamı (${m[1]})`],+ [/^Unpacking llama\.cpp runtime$/, () => "llama.cpp çalışma ortamı açılıyor"],+ [/^Bonsai 2 27B MLX pack$/, () => "Bonsai 2 27B MLX paketi"],+ [/^Model files$/, () => "Model dosyaları"],+ [/^uv \(Python manager\)$/, () => "uv (Python yöneticisi)"],+ [/^Creating Python (\S+) environment$/, (m) => `Python ${m[1]} ortamı hazırlanıyor`],+ [/^Installing MLX and mlx-vlm$/, () => "MLX ve mlx-vlm kuruluyor"],+ [/^Checking the native Bonsai loader$/, () => "Bonsai yükleyicisi denetleniyor"],+ [/^d1 decision model$/, () => "d1 karar modeli"],+ [/^Unpacking ONNX Runtime$/, () => "ONNX Runtime açılıyor"],+ [/^(.+) with (\d+) GB unified memory$/, (m) => `${m[1]}, ${m[2]} GB birleşik bellek`],+ [/^(.+) \((\d+) GB\) and (\d+) GB RAM$/, (m) => `${m[1]} (${m[2]} GB), ${m[3]} GB RAM`],+ [/^(.+) with (\d+) GB RAM$/, (m) => `${m[1]}, ${m[2]} GB RAM`],+ [/^(Metal|MLX) on the Apple GPU$/, (m) => `Apple GPU'da ${m[1]}`],+ [/^(CUDA [\d.]+|Vulkan) on (.+)$/, (m) => `${m[2]} üzerinde ${m[1]}`],+ [/^(ONNX Runtime [\d.]+) on the CPU$/, (m) => `CPU'da ${m[1]}`],+ ];+ // Provider descriptions come from the companion in English.+ const PRODUCT_TR = {+ claude: "Pro, Max ya da Team planı",+ codex: "Plus ya da Pro, Codex girişiyle",+ antigravity: "Antigravity üzerinden Gemini",+ xai: "SuperGrok, Grok Build ile",+ "kimi-ai": "kimi.ai üzerinde Kimi Code",+ kimi: "kimi.com üzerinde Kimi Code",+ meta: "Muse Code",+ devin: "Devin hesabı",+ };+ const productText = (p) => (lang === "tr" && PRODUCT_TR[p.id]) || p.product || "";+ function goText(s) {+ if (lang !== "tr" || !s) return s || "";+ for (const [re, f] of STEP_TR) {+ const m = s.match(re);+ if (m) return f(m);+ }+ return s;+ }+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));+ // t() for markup: the text is escaped, the values are HTML.+ const th = (k, vars) => {+ let s = esc(t(k));+ for (const [n, v] of Object.entries(vars || {})) s = s.split("{" + n + "}").join(v);+ return s;+ };++ // Icons drawn for this panel.+ const ICON = {+ gear: '<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" fill-rule="evenodd" d="M10.34 4.58 10.56 1.9h2.88l.22 2.68 2.41 1 2.05-1.74 2.04 2.04-1.74 2.05 1 2.41 2.68.22v2.88l-2.68.22-1 2.41 1.74 2.05-2.04 2.04-2.05-1.74-2.41 1-.22 2.68h-2.88l-.22-2.68-2.41-1-2.05 1.74-2.04-2.04 1.74-2.05-1-2.41-2.68-.22v-2.88l2.68-.22 1-2.41-1.74-2.05 2.04-2.04 2.05 1.74ZM8.6 12a3.4 3.4 0 1 0 6.8 0 3.4 3.4 0 1 0-6.8 0Z"/></svg>',+ plus: '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path d="M8 2.5v11M2.5 8h11" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" fill="none"/></svg>',+ close: '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="m3.5 3.5 9 9m0-9-9 9" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" fill="none"/></svg>',+ };++ const $app = document.getElementById("app");+ const $sheet = document.getElementById("sheet-root");+ const $toast = document.getElementById("toast");++ let state = null;+ let connected = false;+ let firstPaint = true;+ const ui = {+ sheet: null, // the open sheet: {view, ...}+ returnId: "", // element to focus when the sheet closes+ confirm: null, // an inline "are you sure" waiting for an answer+ showKey: false,+ showModels: false,+ refreshing: null, // {name, since}: a usage refresh asked for in a sheet+ test: null,+ portNote: "",+ portDraft: null, // a port typed in Settings but not applied yet+ welcomedLocal: false,+ };++ async function api(method, path, body) {+ const res = await fetch("/companion/api" + path, {+ method,+ headers: { "X-Companion-Key": key, "Content-Type": "application/json" },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ let data = {};+ try { data = await res.json(); } catch (_) {}+ if (!res.ok) throw new Error(data.error || res.statusText);+ return data;+ }++ let toastTimer;+ function toast(msg) {+ $toast.textContent = msg;+ $toast.classList.remove("hidden");+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => $toast.classList.add("hidden"), 1800);+ }+ async function copy(text) {+ try { await navigator.clipboard.writeText(text); }+ catch (_) {+ const ta = document.createElement("textarea");+ ta.value = text; document.body.appendChild(ta); ta.select();+ try { document.execCommand("copy"); } catch (_) {}+ ta.remove();+ }+ toast(t("copied"));+ }++ // --- formatting -------------------------------------------------------------+ const gb = (b) => {+ if (b < 1e9) return Math.max(1, Math.round(b / 1e6)) + " MB";+ const digits = b >= 1e10 ? 0 : 1;+ return new Intl.NumberFormat(lang, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(b / 1e9) + " GB";+ };+ const num = (n) => new Intl.NumberFormat(lang).format(n);+ const pctText = (p) => (lang === "tr" ? "%" + Math.round(p) : Math.round(p) + "%");+ function dur(ms) {+ if (ms <= 0) return "";+ const m = Math.round(ms / 60000);+ if (m < 60) return Math.max(1, m) + (lang === "tr" ? " dk" : "m");+ const h = Math.floor(m / 60), mm = m % 60;+ if (h < 48) return lang === "tr" ? `${h} sa ${mm} dk` : `${h}h ${String(mm).padStart(2, "0")}m`;+ const d = Math.round(h / 24);+ return lang === "tr" ? `${d} gün` : `${d}d`;+ }+ function when(iso) {+ const d = new Date(iso);+ if (isNaN(d)) return "";+ const now = new Date();+ const sameDay = d.toDateString() === now.toDateString();+ const opts = sameDay ? { hour: "numeric", minute: "2-digit" } : { weekday: "short", hour: "numeric", minute: "2-digit" };+ if (d - now > 6 * 864e5) Object.assign(opts, { month: "short", day: "numeric", weekday: undefined });+ return new Intl.DateTimeFormat(lang, opts).format(d);+ }+ function ago(iso) {+ const ms = Date.now() - new Date(iso).getTime();+ if (!isFinite(ms) || ms < 60000) return t("ago_now");+ const m = Math.round(ms / 60000);+ return m < 60 ? t("ago_m", { n: m }) : t("ago_h", { n: Math.round(m / 60) });+ }++ // --- usage ---------------------------------------------------------------------+ // The window with the least left. Windows for the whole plan come first;+ // scoped ones (one model, code review, extra usage) count only when a plan+ // reports nothing else. The tray menu uses the same rule.+ function tightest(rows) {+ for (const scoped of [false, true]) {+ let best = null;+ for (const r of rows || []) {+ if (r.remaining === null || r.remaining === undefined || !!r.scope !== scoped) continue;+ if (!best || r.remaining < best.remaining) best = r;+ }+ if (best) return best;+ }+ return null;+ }++ function cells(pct, animate) {+ const out = [];+ for (let i = 0; i < 20; i++) {+ const f = Math.max(0, Math.min(1, pct / 5 - i));+ out.push(`<i style="--i:${i};--f:${animate ? 0 : f}" data-f="${f}"></i>`);+ }+ return `<span class="cells" aria-hidden="true">${out.join("")}</span>`;+ }++ function resetText(r) {+ if (!r.reset_at) return "";+ const ms = new Date(r.reset_at) - Date.now();+ if (r.remaining <= 0) return t("emptyUntil", { when: when(r.reset_at) });+ return ms > 0 ? t("resetsIn", { d: dur(ms) }) : "";+ }+ const windowName = (r) => (r.scope && r.window !== "custom" ? r.scope : { "5h": t("w5h"), day: t("wday"), week: t("wweek"), month: t("wmonth") }[r.window] || r.label);+ const windowKind = (r) => ({ "5h": t("fivehour"), day: t("daily"), week: t("weekly"), month: t("monthly") }[r.window] || "");++ // --- main page -----------------------------------------------------------------+ function header() {+ const on = connected && state.running;+ const text = !connected ? t("reconnecting") : state.running ? t("running") : t("stopped");+ return `<header class="top">+ <img src="static/logo-64.png" alt="" width="34" height="34">+ <h1>WebBrain Companion</h1>+ <p class="status"><span class="dot ${on ? "on" : "warn"}"></span>${esc(text)}</p>+ </header>`;+ }++ function banners() {+ const list = [];+ if (state.notice) list.push(esc(state.notice));+ if (state.translocated) list.push(t("translocated"));+ if (state.tray_hidden) list.push(t("trayHidden"));+ if (ui.portNote) list.push(esc(ui.portNote));+ return list.map((x) => `<p class="notice">${x}</p>`).join("");+ }++ const maskKey = (k, short) => (ui.showKey && !short ? k : k.slice(0, 6) + "•".repeat(short ? 6 : 10) + k.slice(-4));++ function addressCard() {+ const url = state.base_url + "/v1";+ const line = (label, value, copyText) => `<div class="addr-row">+ ${label ? `<span class="addr-label">${label}</span>` : ""}+ <span class="addr-value" title="${esc(value)}">${esc(value)}</span>+ <button class="btn small" data-act="copy" data-text="${esc(copyText)}">${t("copy")}</button>+ </div>`;+ let rows = "", note;+ if (state.network) {+ rows = line(t("thisComputer"), url, url);+ const lan = (state.network_urls || [])[0];+ rows += lan ? line(t("otherDevices"), lan, lan) : `<p class="addr-missing">${t("noNetworkAddr")}</p>`;+ rows += line(t("apiKey"), maskKey(state.api_key, true), state.api_key);+ note = t("networkNote");+ } else {+ rows = line("", url, url);+ note = t("noKey");+ }+ const firstRun = !state.welcomed && !ui.welcomedLocal;+ return `<div class="addr ${state.network ? "multi" : ""}">${rows}</div>+ ${firstRun ? `<p class="note first-run">${t("firstRun")} <button class="link" data-act="welcomed">${t("gotIt")}</button></p>`+ : `<p class="note">${note}</p>`}`;+ }++ function subLine(a) {+ const q = a.quota || {};+ if (a.disabled) return { text: t("paused") };+ if (q.status === "loading") return { text: t("reading") };+ if (q.status === "error") return { text: t("quotaErrorShort"), tone: "warn" };+ if (q.status !== "ok") return { text: t("noQuotaShort") };+ const r = tightest(q.rows);+ if (!r) {+ const d = (q.rows || []).find((x) => x.detail);+ return { text: d ? `${windowName(d)}: ${d.detail}` : t("noQuotaShort") };+ }+ const what = resetText(r) || windowKind(r) || windowName(r);+ const text = r.scope && r.window !== "custom" ? `${what} (${r.scope})` : what;+ return { text, row: r, tone: r.remaining <= 0 ? "warn" : "" };+ }++ // Tells logins of the same provider apart, like Account.Who in Go.+ const whoOf = (a) => a.email || String(a.name || "").replace(/\.json$/, "");++ function subRow(a, i, all) {+ const s = subLine(a);+ const q = a.quota || {};+ // Two logins with the same name show whose each one is, as the tray does.+ const shared = all.filter((x) => x.provider_name === a.provider_name).length > 1;+ const who = whoOf(a);+ const r = s.row;+ const low = r && r.remaining < 20;+ const label = [a.provider_name, q.plan, who, r ? pctText(r.remaining) : "", s.text].filter(Boolean).join(", ");+ return `<li class="${a.disabled ? "off" : ""}">+ <button class="item sub-item ${low ? "low" : ""}" id="acc-${i}" data-act="account" data-name="${esc(a.name)}" aria-label="${esc(label)}" title="${esc(who)}">+ <span class="badge" style="--h:${a.hue}" aria-hidden="true">${esc(a.initials)}</span>+ <span class="txt"><span class="name">${esc(a.provider_name)}${q.plan ? ` <span class="plan">${esc(q.plan)}</span>` : ""}</span>+ ${shared ? `<span class="sub">${esc(who)}</span>` : ""}<span class="sub ${s.tone || ""}">${esc(s.text)}</span></span>+ ${r ? cells(Math.max(0, Math.min(100, r.remaining)), firstPaint) + `<span class="pct">${pctText(Math.max(0, Math.min(100, r.remaining)))}</span>` : ""}+ </button>+ </li>`;+ }++ function subsSection() {+ const accounts = state.accounts || [];+ return `<section aria-labelledby="h-subs">+ <div class="sec-head"><h2 id="h-subs">${t("subs")}</h2>+ ${accounts.length ? `<button class="btn small" id="btn-add" data-act="add">${ICON.plus}${t("add")}</button>` : ""}</div>+ ${state.accounts_error ? `<div class="error-box">${esc(state.accounts_error)}</div>` : ""}+ ${accounts.length ? `<ul class="rows">${accounts.map(subRow).join("")}</ul>`+ : `<div class="empty"><p>${t("emptySubs")}</p><button class="btn primary" id="btn-add" data-act="add">${t("addFirst")}</button></div>`}+ </section>`;+ }++ function progressOf(p, busy) {+ if (busy || !p || !p.total) return { busy: true };+ return { pct: (p.done / p.total) * 100 };+ }+ function progressText(p) {+ if (!p || !p.total) return "";+ let s = t("ofSize", { done: gb(p.done), total: gb(p.total) });+ if (p.bytes_per_sec > 0) s += ", " + t("eta", { left: dur(((p.total - p.done) / p.bytes_per_sec) * 1000) });+ return s;+ }+ const bar = (pr) => `<div class="bar ${pr.busy ? "busy" : ""}" aria-hidden="true"><span style="width:${(pr.pct || 0).toFixed(1)}%"></span></div>`;++ function planWarning(L) {+ const p = L.plan;+ if (p.format === "mlx" && !L.system.apple_silicon) return t("warnMlx");+ if (!p.fits) return t("warnFit", { need: gb(p.need_bytes), budget: gb(p.budget_bytes) });+ if (p.gpu_layers > 0 && p.gpu_layers < 64) return t("warnPartial", { n: p.gpu_layers });+ if (p.backend === "cpu") return t("warnCpu");+ return "";+ }+ const canInstall = (L) => !(L.plan.format === "mlx" && !L.system.apple_silicon);+ const localInstalled = (L) => !!(L.installed && L.installed[L.format]);++ // What the Bonsai row says and offers in each phase.+ function localInfo(L) {+ const installed = localInstalled(L);+ switch (L.phase) {+ case "downloading": return { dot: "busy", text: progressText(L.progress) || goText(L.step), act: ["local-cancel", t("cancel")], prog: progressOf(L.progress) };+ case "installing": return { dot: "busy", text: goText(L.step) || t("phase_installing"), act: ["local-cancel", t("cancel")], prog: { busy: true } };+ case "starting": return { dot: "busy", text: t("starting"), prog: { busy: true } };+ case "stopping": return { dot: "busy", text: t("stopping") };+ case "running": return { dot: "on", text: t("runningAs", { id: L.model_id }), act: ["local-stop", t("stop")] };+ case "error": return { dot: "warn", tone: "warn", text: L.error || t("retry"), act: [installed ? "local-start" : "local-install", t("retry")], log: true };+ }+ if (installed) return { text: t("installedSize", { size: gb(L.disk_bytes) }), act: ["local-start", t("start")] };+ const warn = planWarning(L);+ return { text: t("downloadSize", { size: gb(L.download_bytes) }) + (warn ? `. ${t("maySlow")}` : ""), tone: warn ? "warn" : "", act: ["local-install", t("install"), !canInstall(L)] };+ }++ function d1Info(D) {+ if (!D.supported) return { text: t("notSupported") };+ switch (D.phase) {+ case "downloading": return { dot: "busy", text: progressText(D.progress) || goText(D.step), act: ["d1-cancel", t("cancel")], prog: progressOf(D.progress) };+ case "installing": return { dot: "busy", text: goText(D.step) || t("phase_installing"), act: ["d1-cancel", t("cancel")], prog: { busy: true } };+ case "loading": return { dot: "busy", text: t("loading"), prog: { busy: true } };+ case "ready": return { dot: "on", text: D.requests ? t("readyServed", { n: num(D.requests) }) : t("ready"), act: ["d1-unload", t("unload")] };+ case "error": return { dot: "warn", tone: "warn", text: D.error || t("retry"), act: [D.installed ? "d1-load" : "d1-install", t("retry")], log: true };+ }+ if (D.installed) return { text: t("installedSize", { size: gb(D.disk_bytes) }), act: ["d1-load", t("load")] };+ return { text: t("downloadSize", { size: gb(D.download_bytes) }), act: ["d1-install", t("install")] };+ }++ // a: [action, label, disabled]; what names the model for screen readers.+ const actButton = (a, cls = "", what = "") => (a ? `<button class="btn small ${cls}" data-act="${a[0]}" ${a[2] ? "disabled" : ""}${what ? ` aria-label="${esc(a[1] + ", " + what)}"` : ""}>${esc(a[1])}</button>` : "");++ function modelRow(id, act, badge, color, name, info) {+ return `<li class="model">+ <button class="item" id="${id}" data-act="${act}">+ <span class="badge" style="${color}" aria-hidden="true">${badge}</span>+ <span class="txt"><span class="name">${esc(name)}</span>+ <span class="sub ${info.tone || ""}">${info.dot ? `<span class="dot ${info.dot}"></span>` : ""}${esc(info.text)}</span></span>+ </button>+ ${actButton(info.act, "", name)}+ ${info.prog ? bar(info.prog) : ""}+ </li>`;+ }++ function modelsSection() {+ return `<section aria-labelledby="h-models">+ <div class="sec-head"><h2 id="h-models">${t("models")}</h2></div>+ <ul class="rows">+ ${modelRow("row-local", "local-open", "B", "--h:150;--s:42%;--l:34%", state.local.model_name, localInfo(state.local))}+ ${modelRow("row-d1", "d1-open", "d1", "--h:336;--s:58%;--l:46%", t("d1Name"), d1Info(state.decision))}+ </ul>+ </section>`;+ }++ function footer() {+ return `<footer class="foot"><button class="btn quiet" id="btn-settings" data-act="settings">${ICON.gear}${t("settings")}</button></footer>`;+ }++ // Re-rendering replaces the markup; keep keyboard focus on the same control.+ function focusSelector(el) {+ if (!el || el === document.body) return "";+ if (el.id) return "#" + CSS.escape(el.id);+ const d = el.dataset || {};+ const attrs = ["act", "change", "name", "id", "text", "format"].filter((k) => d[k] !== undefined)+ .map((k) => `[data-${k}="${CSS.escape(d[k])}"]`).join("");+ return attrs;+ }+ function swap(root, html) {+ if (root.__html === html) return;+ const active = document.activeElement;+ const sel = active && root.contains(active) ? focusSelector(active) : "";+ root.innerHTML = html;+ root.__html = html;+ if (sel) {+ const again = root.querySelector(sel);+ if (again) again.focus({ preventScroll: true });+ }+ }+ const editing = (root) => {+ const a = document.activeElement;+ return !!a && root.contains(a) && (a.tagName === "SELECT" || (a.tagName === "INPUT" && a.type !== "checkbox"));+ };++ let pending = false;+ function render() {+ if (!state) return;+ lang = state.language === "tr" ? "tr" : "en";+ document.documentElement.lang = lang;+ swap($app, header() + banners() + addressCard() + subsSection() + modelsSection() + footer());+ if (firstPaint) {+ firstPaint = false;+ requestAnimationFrame(() => requestAnimationFrame(() => {+ $app.querySelectorAll(".cells i").forEach((el) => el.style.setProperty("--f", el.dataset.f));+ }));+ }+ renderSheet();+ }++ // --- sheets --------------------------------------------------------------------+ const sheetHead = (title, sub = "", lead = "") => `<div class="sheet-head">${lead}+ <div class="sheet-title"><h3 id="sheet-title">${title}</h3>${sub ? `<p class="sub">${sub}</p>` : ""}</div>+ <button class="icon-btn" data-act="sheet-close" aria-label="${t("close")}">${ICON.close}</button></div>`;++ function confirmRow(text, act, label, attrs = "") {+ return `<div class="confirm" role="group"><span>${esc(text)}</span>+ <span class="confirm-actions"><button class="btn small danger" data-act="${act}" ${attrs}>${esc(label)}</button>+ <button class="btn small quiet" data-act="cancel-confirm">${t("keep")}</button></span></div>`;+ }+ const confirming = (type, name) => ui.confirm && ui.confirm.type === type && (name === undefined || ui.confirm.name === name);++ function meter(r) {+ if (r.remaining === null || r.remaining === undefined) {+ return `<div class="meter"><span class="win" title="${esc(r.label)}">${esc(windowName(r))}</span><span class="when">${esc(r.detail || "")}</span></div>`;+ }+ const pct = Math.max(0, Math.min(100, r.remaining));+ const reset = r.reset_at ? (pct <= 0 ? resetText(r) : (resetText(r) ? `${resetText(r)} (${when(r.reset_at)})` : "")) : "";+ const kind = r.scope && r.window !== "custom" ? windowKind(r) : "";+ const whenLine = [kind, reset, r.detail].filter(Boolean).join(". ");+ return `<div class="meter ${pct < 20 ? "low" : ""}" role="meter" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(pct)}" aria-label="${esc(windowName(r))}">+ <span class="win" title="${esc(r.label)}">${esc(windowName(r))}</span>+ ${cells(pct, false)}+ <span class="pct">${pctText(pct)}</span>+ ${whenLine ? `<span class="when ${pct <= 0 ? "urgent" : ""}">${esc(whenLine)}</span>` : ""}+ </div>`;+ }++ const refreshingNow = (a) => {+ const r = ui.refreshing;+ return !!r && r.name === a.name && r.since === (a.quota && a.quota.fetched_at) && Date.now() - r.at < 20000;+ };++ function accountSheet(name) {+ const a = (state.accounts || []).find((x) => x.name === name);+ if (!a) return null;+ const q = a.quota || {};+ let body;+ if (a.disabled) body = `<p class="sheet-note">${t("pausedNote")}</p>`;+ else if (q.status === "ok" && (q.rows || []).length) {+ body = `<div class="meters">${q.rows.map(meter).join("")}</div>`+ + (q.error ? `<p class="sheet-note warn">${esc(t("quotaError", { msg: q.error }))}</p>` : "");+ } else if (q.status === "loading") body = `<p class="sheet-note">${t("reading")}</p>`;+ else if (q.status === "error") body = `<p class="sheet-note warn">${esc(t("quotaError", { msg: q.error || "" }))}</p>`;+ else body = `<p class="sheet-note">${t("noQuota")}</p>`;+ const who = `${a.provider_name} (${whoOf(a)})`;+ const actions = confirming("account", a.name)+ ? confirmRow(t("removeConfirm", { name: who }), "remove", t("remove"), `data-name="${esc(a.name)}"`)+ : `<div class="sheet-actions">+ ${a.quota_supported && !a.disabled ? `<span class="updated">${q.fetched_at && q.status === "ok" ? esc(t("updated", { ago: ago(q.fetched_at) })) : ""}</span>+ ${refreshingNow(a) ? `<button class="btn small" disabled>${t("refreshing")}</button>`+ : `<button class="btn small" data-act="refresh-one" data-name="${esc(a.name)}">${t("refreshUsage")}</button>`}` : `<span class="updated"></span>`}+ <button class="btn small" data-act="disable" data-name="${esc(a.name)}" data-off="${!a.disabled}">${a.disabled ? t("resume") : t("pause")}</button>+ <button class="btn small danger" data-act="ask-remove" data-name="${esc(a.name)}">${t("remove")}</button>+ </div>`;+ const title = esc(a.provider_name) + (q.plan ? ` <span class="plan">${esc(q.plan)}</span>` : "");+ return sheetHead(title, esc(whoOf(a)), `<span class="badge big" style="--h:${a.hue}" aria-hidden="true">${esc(a.initials)}</span>`) + body + actions;+ }++ function statusBlock(info) {+ return `<div class="status-block">+ <div class="status-line"><span class="status-text ${info.tone || ""}">${info.dot ? `<span class="dot ${info.dot}"></span>` : ""}${esc(info.text)}</span>+ <span class="status-actions">${info.log ? `<button class="btn small quiet" data-act="logs">${t("showLog")}</button>` : ""}${actButton(info.act, info.dot === "on" || info.dot === "busy" ? "" : "primary")}</span></div>+ ${info.prog ? bar(info.prog) : ""}+ </div>`;+ }++ function visionText(L) {+ const v = L.plan.vision;+ const label = { gpu: t("visionGpu"), cpu: t("visionCpu"), off: t("visionOff"), builtin: t("visionBuiltin") }[v] || v;+ let why;+ if (v === "builtin") why = t("whyBuiltin");+ else if (L.vision_mode && L.vision_mode !== "auto") why = t("whyForced");+ else if (v === "gpu") why = t("whyGpu", { need: gb(L.plan.need_bytes + 960 * 1048576), budget: gb(L.plan.budget_bytes) });+ else if (v === "cpu") why = t("whyCpu");+ else why = t("whyOff");+ return `<span class="${v === "off" ? "vision-off" : "vision-on"}">${esc(label)}</span><span class="why">${esc(why)}</span>`;+ }++ function localSheet() {+ const L = state.local;+ const installed = localInstalled(L);+ const busy = ["downloading", "installing", "starting", "stopping"].includes(L.phase);+ const formats = L.formats || ["gguf"];+ const warn = planWarning(L);+ const info = localInfo(L);+ if (L.phase === "downloading" && L.step) info.text = `${goText(L.step)}: ${info.text}`;+ const fmt = formats.length > 1+ ? `<span class="seg" role="group" aria-label="${t("format")}">${formats.map((f) => `<button data-act="local-format" data-format="${f}" aria-pressed="${f === L.format}" ${busy || L.phase === "running" ? "disabled" : ""}>${t(f === "mlx" ? "formatMLX" : "formatGGUF")}</button>`).join("")}</span>`+ : t("formatGGUF");+ return sheetHead(esc(L.model_name), th("localLede", { id: `<span class="nowrap">${esc(L.model_id)}</span>` }))+ + statusBlock(info)+ + (warn && L.phase !== "running" ? `<p class="sheet-note warn">${esc(warn)}</p>` : "")+ + `<dl class="facts">+ <dt>${t("thisMachine")}</dt><dd>${esc(goText(L.system_summary))}</dd>+ <dt>${t("format")}</dt><dd>${fmt}<span class="why">${t(L.format === "mlx" ? "mlxNote" : "ggufNote")}</span></dd>+ <dt>${t("runtime")}</dt><dd>${esc(goText(L.plan.backend_label))}${L.plan.gpu_layers > 0 && L.plan.gpu_layers < 64 ? `<span class="why">${t("layers", { n: L.plan.gpu_layers })}</span>` : ""}</dd>+ <dt>${t("vision")}</dt><dd>${visionText(L)}</dd>+ <dt>${t("context")}</dt><dd>${esc(t("tokens", { n: num(L.plan.context) }))}</dd>+ ${installed ? `<dt>${t("onDisk")}</dt><dd>${gb(L.disk_bytes)}</dd>` : `<dt>${t("download")}</dt><dd>${gb(L.download_bytes)}</dd>`}+ </dl>+ <h4>${t("options")}</h4>+ <div class="opts">+ ${L.format === "gguf" ? `<label class="setting"><span>${t("vision")}</span>+ <select data-change="local-vision">${["auto", "gpu", "cpu", "off"].map((v) => `<option value="${v}" ${L.vision_mode === v ? "selected" : ""}>${t(v)}</option>`).join("")}</select></label>` : ""}+ <label class="setting"><span>${t("context")}</span>+ <select data-change="local-context">${[0, 8192, 16384, 32768, 65536, 131072, 262144].map((c) => `<option value="${c}" ${state.local_context_setting === c ? "selected" : ""}>${c === 0 ? t("auto") : num(c)}</option>`).join("")}</select></label>+ <label class="toggle"><input type="checkbox" data-change="local-autostart" ${L.auto_start ? "checked" : ""}>${t("startWith")}</label>+ </div>+ ${installed || L.disk_bytes > 0 ? (confirming("local-remove")+ ? confirmRow(t("removeFilesConfirm", { size: gb(L.disk_bytes) }), "local-remove", t("delete"))+ : `<div class="sheet-actions end"><button class="btn small danger" data-act="ask-local-remove" ${busy ? "disabled" : ""}>${t("removeFiles")}</button></div>`) : ""}`;+ }++ function decisionSheet() {+ const D = state.decision;+ const info = d1Info(D);+ if (D.phase === "downloading" && D.step) info.text = `${goText(D.step)}: ${info.text}`;+ let test = "";+ if (D.phase === "ready") {+ test = `<div class="test"><button class="btn small" data-act="d1-test" ${ui.test === "running" ? "disabled" : ""}>${ui.test === "running" ? t("testing") : t("test")}</button>+ ${ui.test && ui.test !== "running" ? `<span class="result">${esc(ui.test)}</span>` : ""}</div>`;+ }+ const busy = ["downloading", "installing", "loading"].includes(D.phase);+ return sheetHead(esc(t("d1Name")), t("decisionLede"))+ + statusBlock(info) + test+ + `<dl class="facts">+ <dt>${t("endpoint")}</dt><dd><button class="chip-code" data-act="copy" data-text="${esc(D.endpoint)}" title="${t("copy")}">POST /companion/v1/decide</button></dd>+ ${D.runtime ? `<dt>${t("runtime")}</dt><dd>${esc(goText(D.runtime))}</dd>` : ""}+ ${D.requests ? `<dt>${t("served")}</dt><dd>${esc(t("servedValue", { n: num(D.requests), ms: Math.round(D.last_latency_ms || 0) }))}</dd>` : ""}+ ${D.installed ? `<dt>${t("onDisk")}</dt><dd>${gb(D.disk_bytes)}</dd>` : `<dt>${t("download")}</dt><dd>${gb(D.download_bytes)}</dd>`}+ <dt>${t("license")}</dt><dd>${esc(D.license)}</dd>+ </dl>+ ${D.installed ? (confirming("d1-remove")+ ? confirmRow(t("removeFilesConfirm", { size: gb(D.disk_bytes) }), "d1-remove", t("delete"))+ : `<div class="sheet-actions end"><button class="btn small danger" data-act="ask-d1-remove" ${busy ? "disabled" : ""}>${t("removeFiles")}</button></div>`) : ""}`;+ }++ function settingsSheet() {+ const s = state;+ const models = s.models || [];+ const copyRow = (label, value) => `<div class="kv"><span class="k">${label}</span><span class="v mono" title="${esc(value)}">${esc(value)}</span>+ <button class="btn small" data-act="copy" data-text="${esc(value)}">${t("copy")}</button></div>`;+ let network = "";+ if (s.network) {+ const urls = s.network_urls || [];+ network = (urls.length ? urls.map((u) => copyRow(t("otherDevices"), u)).join("") : `<p class="sheet-note warn">${t("noNetworkAddr")}</p>`)+ + `<div class="kv"><span class="k">${t("apiKey")}</span><span class="v mono">${esc(maskKey(s.api_key))}</span>+ <span class="kv-actions"><button class="btn small quiet" data-act="toggle-key">${ui.showKey ? t("hide") : t("show")}</button>+ <button class="btn small" data-act="copy" data-text="${esc(s.api_key)}">${t("copy")}</button></span></div>`+ + (confirming("rotate") ? confirmRow(t("newKeyConfirm"), "rotate", t("newKey"))+ : `<div><button class="btn small danger" data-act="ask-rotate">${t("newKey")}</button></div>`);+ }+ return sheetHead(t("settings"))+ + `<div class="opts">+ <label class="toggle"><input type="checkbox" data-change="autostart" ${s.autostart ? "checked" : ""} ${s.translocated ? "disabled" : ""}>${t("startLogin")}</label>+ <label class="setting"><span>${t("language")}</span><select data-change="language"><option value="en" ${lang === "en" ? "selected" : ""}>English</option><option value="tr" ${lang === "tr" ? "selected" : ""}>Türkçe</option></select></label>+ </div>+ <h4>${t("otherDevices")}</h4>+ <div class="opts">+ <label class="toggle"><input type="checkbox" data-change="network" ${s.network ? "checked" : ""}>${t("networkToggle")}</label>+ <p class="sheet-note">${t("networkHelp")}</p>+ ${network}+ </div>+ <h4>${t("connection")}</h4>+ <div class="opts">+ <div class="kv"><label class="k" for="port-input">${t("port")}</label><span class="v"><input type="number" min="1024" max="65535" id="port-input" value="${esc(ui.portDraft ?? s.preferred_port)}"></span>+ <button class="btn small" data-act="port">${t("apply")}</button></div>+ ${copyRow(t("otherFormats"), s.base_url)}+ <div class="kv"><span class="k">${t("modelsLabel")}</span><span class="v">${models.length ? t("modelsCount", { n: models.length }) : t("modelsNone")}</span>+ ${models.length ? `<button class="btn small quiet" data-act="toggle-models" aria-expanded="${ui.showModels}">${ui.showModels ? t("hideList") : t("showList")}</button>` : ""}</div>+ ${ui.showModels && models.length ? `<ul class="chips">${models.map((m) => `<li><button data-act="copy" data-text="${esc(m)}" title="${t("copy")}">${esc(m)}</button></li>`).join("")}</ul>` : ""}+ </div>+ <div class="sheet-foot">+ <button class="link" data-act="logs">${t("logFile")}</button>+ <span>${esc(t("version", { v: s.version }))}</span>+ </div>+ ${confirming("quit") ? confirmRow(t("quitConfirm"), "quit", t("quit"))+ : `<div class="sheet-actions"><button class="btn small danger" data-act="ask-quit">${t("quit")}</button></div>`}`;+ }++ function providerRow(p) {+ return `<li><button data-act="pick" data-id="${p.id}">+ <span class="badge" style="--h:${p.hue}" aria-hidden="true">${esc(p.initials)}</span>+ <span class="ptxt"><span class="pname">${esc(p.name)}</span><span class="pprod">${esc(productText(p))}</span></span>+ <span class="ptag">${p.flow === "device" ? t("deviceFlow") : t("browserFlow")}</span></button></li>`;+ }++ function addSheet(s) {+ const prov = s.provider && state.providers.find((p) => p.id === s.provider);+ const name = prov ? prov.name : "";+ if (s.view === "pick") {+ const primary = state.providers.filter((p) => p.primary), rest = state.providers.filter((p) => !p.primary);+ return sheetHead(t("pickTitle"), t("pickSub"))+ + `<ul class="providers">${primary.map(providerRow).join("")}</ul>+ ${rest.length ? `<details class="more" ${s.more ? "open" : ""} data-key="sheet-more"><summary>${t("more")}</summary><ul class="providers">${rest.map(providerRow).join("")}</ul></details>` : ""}`;+ }+ if (s.view === "wait") {+ const st = s.start || {};+ let host = "";+ try { host = new URL(st.url).host; } catch (_) {}+ const cancel = `<div class="sheet-actions"><button class="btn small" data-act="sheet-cancel">${t("cancel")}</button></div>`;+ if (st.flow === "device") {+ return sheetHead(esc(t("waitTitle", { name })), t("waitDevice"))+ + `<div class="code-big">${esc(st.user_code || "")}</div>+ <div class="row"><button class="btn primary" data-act="open-url" data-url="${esc(st.url)}">${t("openPage")}${host ? " (" + esc(host) + ")" : ""}</button>+ <button class="btn" data-act="copy" data-text="${esc(st.user_code || "")}">${t("copyCode")}</button></div>+ <div class="waiting"><span class="spinner"></span>${esc(t("waiting", { name }))}</div>` + cancel;+ }+ return sheetHead(esc(t("waitTitle", { name })), t("waitBrowser"))+ + `<div class="waiting"><span class="spinner"></span>${esc(t("waiting", { name }))}</div>+ <div class="row"><button class="btn" data-act="open-url" data-url="${esc(st.url || "")}" ${st.url ? "" : "disabled"}>${t("openAgain")}</button></div>+ <details class="more" data-key="paste" ${s.paste ? "open" : ""}><summary>${t("noReturn")}</summary>+ <div class="paste"><span class="sheet-note">${t("pasteHelp")}</span>+ <input type="text" id="paste-url" placeholder="${t("pastePh")}" autocomplete="off" spellcheck="false" value="${esc(s.pasteValue || "")}" aria-label="${t("pasteHelp")}">+ <div><button class="btn primary" data-act="paste-submit">${t("submit")}</button></div>+ ${s.pasteError ? `<div class="error-box">${esc(s.pasteError)}</div>` : ""}</div></details>` + cancel;+ }+ if (s.view === "done") {+ return sheetHead(esc(t("doneTitle", { name })), t("doneSub"), `<span class="success-mark" aria-hidden="true">✓</span>`)+ + `<div class="sheet-actions"><button class="btn primary" data-act="sheet-close">${t("done")}</button></div>`;+ }+ return sheetHead(t("failTitle")) + `<div class="error-box">${esc(s.error || "")}</div>+ <div class="sheet-actions"><button class="btn primary" data-act="pick" data-id="${esc(s.provider)}">${t("retry")}</button></div>`;+ }++ // Sheets in the same family share one window, so moving from "pick" to+ // "wait" does not replay the opening animation.+ const sheetFamily = (s) => (["pick", "wait", "done", "error"].includes(s.view) ? "add" : s.view + ":" + (s.name || ""));++ function renderSheet() {+ const s = ui.sheet;+ if (!s) {+ if ($sheet.firstChild) { $sheet.innerHTML = ""; $sheet.__family = ""; }+ $app.inert = false;+ return;+ }+ const family = sheetFamily(s);+ const sameView = $sheet.__family === family && $sheet.__view === s.view;+ if (sameView && editing($sheet)) { pending = true; return; }+ let html;+ switch (s.view) {+ case "account": html = accountSheet(s.name); break;+ case "local": html = localSheet(); break;+ case "decision": html = decisionSheet(); break;+ case "settings": html = settingsSheet(); break;+ default: html = addSheet(s);+ }+ if (html === null) { closeSheet(); return; } // the account went away+ let box = $sheet.querySelector(".sheet");+ const fresh = !box || $sheet.__family !== family;+ if (fresh) {+ $sheet.innerHTML = `<div class="scrim" data-act="scrim"><div class="sheet" role="dialog" aria-modal="true" aria-labelledby="sheet-title" tabindex="-1"></div></div>`;+ box = $sheet.querySelector(".sheet");+ box.__html = "";+ }+ const viewChanged = $sheet.__view !== s.view;+ $sheet.__family = family;+ $sheet.__view = s.view;+ swap(box, html);+ $app.inert = true;+ // A new sheet (or a new step of adding a subscription) takes focus itself,+ // so screen readers announce its title and Tab starts at its first control.+ if (fresh || viewChanged || !box.contains(document.activeElement)) box.focus({ preventScroll: true });+ }++ function openSheet(sheet, returnId) {+ ui.sheet = sheet;+ ui.confirm = null;+ if (returnId) ui.returnId = returnId;+ renderSheet();+ }+ function closeSheet() {+ ui.sheet = null;+ ui.confirm = null;+ ui.portDraft = null;+ renderSheet();+ const back = ui.returnId && document.getElementById(ui.returnId);+ if (back) back.focus({ preventScroll: true });+ }++ function syncLogin() {+ const s = ui.sheet;+ if (!s || s.view !== "wait" || !s.start) return;+ const l = (state.logins || []).find((x) => x.state === s.start.state);+ if (!l) return;+ if (l.status === "ok") { ui.sheet = { view: "done", provider: s.provider }; renderSheet(); }+ else if (l.status === "error") { ui.sheet = { view: "error", provider: s.provider, error: l.error }; renderSheet(); }+ }++ async function startLogin(id) {+ ui.sheet = { view: "wait", provider: id, start: null };+ renderSheet();+ const still = () => ui.sheet && ui.sheet.view === "wait" && ui.sheet.provider === id && !ui.sheet.start;+ try {+ const st = await api("POST", "/accounts/login", { provider: id });+ if (still()) ui.sheet = { view: "wait", provider: id, start: st };+ else if (st.state) run(api("DELETE", "/accounts/login/" + encodeURIComponent(st.state))); // closed meanwhile+ } catch (e) {+ if (still()) ui.sheet = { view: "error", provider: id, error: e.message };+ }+ renderSheet();+ }++ // --- actions ------------------------------------------------------------------+ const run = (p) => p.catch((e) => toast(e.message));+ const reRender = () => { render(); };++ document.addEventListener("click", async (ev) => {+ const el = ev.target.closest("[data-act]");+ if (!el || el.disabled) return;+ const act = el.dataset.act;+ if (act === "scrim" && ev.target !== el) return;+ const name = el.dataset.name;+ switch (act) {+ case "copy": copy(el.dataset.text); break;+ case "toggle-key": ui.showKey = !ui.showKey; reRender(); break;+ case "toggle-models": ui.showModels = !ui.showModels; reRender(); break;+ case "welcomed": ui.welcomedLocal = true; reRender(); run(api("PATCH", "/settings", { welcomed: true })); break;+ case "add": openSheet({ view: "pick" }, "btn-add"); break;+ case "account": openSheet({ view: "account", name }, el.id); break;+ case "local-open": openSheet({ view: "local" }, "row-local"); break;+ case "d1-open": openSheet({ view: "decision" }, "row-d1"); break;+ case "settings": openSheet({ view: "settings" }, "btn-settings"); break;+ case "pick": startLogin(el.dataset.id); break;+ case "scrim":+ case "sheet-close": closeSheet(); break;+ case "sheet-cancel":+ if (ui.sheet && ui.sheet.start) run(api("DELETE", "/accounts/login/" + encodeURIComponent(ui.sheet.start.state)));+ closeSheet(); break;+ case "open-url": run(api("POST", "/open", { target: "url", url: el.dataset.url })); break;+ case "paste-submit": {+ const s = ui.sheet;+ s.pasteValue = (document.getElementById("paste-url") || {}).value || "";+ s.paste = true;+ try {+ await api("POST", "/accounts/login/" + encodeURIComponent(s.start.state) + "/callback", { redirect_url: s.pasteValue });+ s.pasteError = "";+ } catch (e) { s.pasteError = e.message; }+ renderSheet();+ break;+ }+ case "refresh-one": {+ const a = state.accounts.find((x) => x.name === name);+ ui.refreshing = { name, since: a && a.quota && a.quota.fetched_at, at: Date.now() };+ reRender();+ setTimeout(reRender, 20500);+ run(api("POST", "/quotas/refresh", { name }));+ break;+ }+ case "disable": run(api("POST", "/accounts/" + encodeURIComponent(name) + "/disabled", { disabled: el.dataset.off === "true" })); break;+ case "ask-remove": ui.confirm = { type: "account", name }; reRender(); break;+ case "remove":+ ui.confirm = null;+ try { await api("DELETE", "/accounts/" + encodeURIComponent(name)); closeSheet(); }+ catch (e) { toast(e.message); reRender(); }+ break;+ case "cancel-confirm": ui.confirm = null; reRender(); break;+ case "local-install": run(api("POST", "/local/install", { format: state.local.format })); break;+ case "local-cancel": run(api("POST", "/local/cancel")); break;+ case "local-start": run(api("POST", "/local/start")); break;+ case "local-stop": run(api("POST", "/local/stop")); break;+ case "local-format": run(api("PATCH", "/local", { format: el.dataset.format })); break;+ case "ask-local-remove": ui.confirm = { type: "local-remove" }; reRender(); break;+ case "local-remove": ui.confirm = null; run(api("POST", "/local/remove", { format: state.local.format })); reRender(); break;+ case "d1-install": run(api("POST", "/decision/install")); break;+ case "d1-cancel": run(api("POST", "/decision/cancel")); break;+ case "d1-load": run(api("POST", "/decision/load")); break;+ case "d1-unload": ui.test = null; run(api("POST", "/decision/unload")); break;+ case "ask-d1-remove": ui.confirm = { type: "d1-remove" }; reRender(); break;+ case "d1-remove": ui.confirm = null; run(api("POST", "/decision/remove")); reRender(); break;+ case "d1-test": {+ ui.test = "running"; reRender();+ try {+ const r = await api("POST", "/decision/test");+ const a = r.answers && r.answers.completion;+ ui.test = t("testResult", { choice: a ? a.choice : "?", p: a ? Math.round(a.confidence * 100) : 0, ms: Math.round((r.diagnostics && r.diagnostics.latency_ms) || 0) });+ } catch (e) { ui.test = e.message; }+ reRender();+ break;+ }+ case "logs": run(api("POST", "/open", { target: "logs" })); break;+ case "port": {+ const v = parseInt((document.getElementById("port-input") || {}).value, 10);+ if (!v || v === state.preferred_port) break;+ try { await api("PATCH", "/settings", { port: v }); ui.portNote = t("portChanged", { port: v }); closeSheet(); reRender(); }+ catch (e) { toast(e.message); }+ break;+ }+ case "ask-rotate": ui.confirm = { type: "rotate" }; reRender(); break;+ case "rotate": ui.confirm = null; run(api("POST", "/key/rotate")); reRender(); break;+ case "ask-quit": ui.confirm = { type: "quit" }; reRender(); break;+ case "quit": ui.confirm = null; run(api("POST", "/quit")); break;+ }+ });++ document.addEventListener("change", (ev) => {+ const el = ev.target.closest("[data-change]");+ if (!el) return;+ const v = el.type === "checkbox" ? el.checked : el.value;+ switch (el.dataset.change) {+ case "autostart": run(api("PATCH", "/settings", { autostart: v })); break;+ case "network": run(api("PATCH", "/settings", { network: v })); break;+ case "language": lang = v; state.language = v; run(api("PATCH", "/settings", { language: v })); el.blur(); reRender(); break;+ case "local-vision": run(api("PATCH", "/local", { vision: v })); el.blur(); break;+ case "local-context": state.local_context_setting = parseInt(v, 10); run(api("PATCH", "/local", { context: parseInt(v, 10) })); el.blur(); break;+ case "local-autostart": run(api("PATCH", "/local", { auto_start: v })); break;+ }+ });++ document.addEventListener("toggle", (ev) => {+ const d = ev.target;+ if (!(d instanceof HTMLDetailsElement) || !d.dataset.key || !ui.sheet) return;+ if (d.dataset.key === "paste") ui.sheet.paste = d.open;+ if (d.dataset.key === "sheet-more") ui.sheet.more = d.open;+ }, true);++ document.addEventListener("focusout", () => { if (pending) { pending = false; setTimeout(render, 0); } });+ document.addEventListener("input", (ev) => {+ if (ev.target.id === "paste-url" && ui.sheet) ui.sheet.pasteValue = ev.target.value;+ if (ev.target.id === "port-input") ui.portDraft = ev.target.value; // kept across live updates+ });+ document.addEventListener("keydown", (ev) => {+ if (ev.key === "Enter" && ev.target.id === "port-input") { ev.preventDefault(); document.querySelector('[data-act="port"]').click(); return; }+ if (ev.key !== "Escape") return;+ if (ui.confirm) { ui.confirm = null; reRender(); }+ else if (ui.sheet) closeSheet();+ });++ // --- live state -----------------------------------------------------------------+ function applyState(s) {+ const firstState = !state;+ state = s;+ if (state.local_context_setting === undefined) state.local_context_setting = s.local_context ?? 0;+ connected = true;+ render();+ syncLogin();+ if (firstState) refreshIfStale();+ }++ // Usage refreshes every few minutes in the background; opening the panel+ // asks for fresh numbers when the last ones are older than two minutes.+ function refreshIfStale() {+ const stale = (state.accounts || []).some((a) => a.quota_supported && !a.disabled && a.quota && a.quota.status === "ok"+ && Date.now() - new Date(a.quota.fetched_at).getTime() > 120000);+ if (stale && !state.quota_busy) run(api("POST", "/quotas/refresh", {}));+ }++ function listen() {+ const es = new EventSource("/companion/api/events?key=" + encodeURIComponent(key));+ es.addEventListener("state", (e) => applyState(JSON.parse(e.data)));+ es.onerror = () => {+ connected = false;+ render();+ };+ }++ const fallback = (msg) => {+ $app.innerHTML = `<header class="top"><img src="static/logo-64.png" alt="" width="34" height="34"><h1>WebBrain Companion</h1></header><p class="empty">${msg}</p>`;+ };+ if (!key) { fallback(t("tokenMissing")); return; }+ api("GET", "/state").then((s) => {+ applyState(s);+ if (startView === "add") openSheet({ view: "pick" }, "btn-add");+ else if (startView === "settings") openSheet({ view: "settings" }, "btn-settings");+ else if (startView === "local") openSheet({ view: "local" }, "row-local");+ else if (startView === "decision") openSheet({ view: "decision" }, "row-d1");+ else if (startView.startsWith("account:")) {+ const name = startView.slice(8);+ const i = (state.accounts || []).findIndex((a) => a.name === name);+ if (i >= 0) openSheet({ view: "account", name }, "acc-" + i);+ }+ listen();+ }).catch((e) => fallback(`${esc(e.message)}. ${t("tokenMissing")}`));+ setInterval(() => { if (state) render(); }, 30000); // keep countdowns fresh+})();diff --git a/webbrain-systray/internal/panel/assets/favicon.png b/webbrain-systray/internal/panel/assets/favicon.pngnew file mode 100644index 000000000..61d38c47fBinary files /dev/null and b/webbrain-systray/internal/panel/assets/favicon.png differdiff --git a/webbrain-systray/internal/panel/assets/fonts/OFL-BricolageGrotesque.txt b/webbrain-systray/internal/panel/assets/fonts/OFL-BricolageGrotesque.txtnew file mode 100644index 000000000..49135ef7a--- /dev/null+++ b/webbrain-systray/internal/panel/assets/fonts/OFL-BricolageGrotesque.txt@@ -0,0 +1,93 @@+Copyright 2022 The Bricolage Grotesque Project Authors (https://github.com/ateliertriay/bricolage)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/webbrain-systray/internal/panel/assets/fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2 b/webbrain-systray/internal/panel/assets/fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2new file mode 100644index 000000000..6e8caa8a6Binary files /dev/null and b/webbrain-systray/internal/panel/assets/fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2 differdiff --git a/webbrain-systray/internal/panel/assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2 b/webbrain-systray/internal/panel/assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2new file mode 100644index 000000000..fcc4eb1ebBinary files /dev/null and b/webbrain-systray/internal/panel/assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2 differdiff --git a/webbrain-systray/internal/panel/assets/index.html b/webbrain-systray/internal/panel/assets/index.htmlnew file mode 100644index 000000000..18a5b89e9--- /dev/null+++ b/webbrain-systray/internal/panel/assets/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="color-scheme" content="light dark">+<title>WebBrain Companion</title>+<link rel="icon" href="static/favicon.png">+<link rel="stylesheet" href="static/app.css">+<script src="static/app.js" defer></script>+</head>+<body>+<main id="app"><p class="empty" style="padding-top:40px">Loading…</p></main>+<div id="sheet-root"></div>+<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>+</body>+</html>diff --git a/webbrain-systray/internal/panel/assets/logo-64.png b/webbrain-systray/internal/panel/assets/logo-64.pngnew file mode 100644index 000000000..026e68302Binary files /dev/null and b/webbrain-systray/internal/panel/assets/logo-64.png differdiff --git a/webbrain-systray/internal/panel/panel.go b/webbrain-systray/internal/panel/panel.gonew file mode 100644index 000000000..c8d611f69--- /dev/null+++ b/webbrain-systray/internal/panel/panel.go@@ -0,0 +1,7 @@+// Package panel embeds the companion's mini web UI.+package panel++import "embed"++//go:embed assets+var FS embed.FSdiff --git a/webbrain-systray/internal/paths/paths.go b/webbrain-systray/internal/paths/paths.gonew file mode 100644index 000000000..fe91c872b--- /dev/null+++ b/webbrain-systray/internal/paths/paths.go@@ -0,0 +1,90 @@+// Package paths resolves the per-user directories the companion uses.+//+// Config (settings, proxy config, OAuth logins):+// Windows %APPDATA%\WebBrain Companion+// macOS ~/Library/Application Support/WebBrain Companion+// Linux $XDG_CONFIG_HOME/webbrain-companion (~/.config/webbrain-companion)+// Data (models, runtimes, logs; large and not roaming):+// Windows %LOCALAPPDATA%\WebBrain Companion+// macOS ~/Library/Application Support/WebBrain Companion+// Linux $XDG_DATA_HOME/webbrain-companion (~/.local/share/webbrain-companion)+//+// WBC_HOME overrides both (useful for tests and portable installs).+package paths++import (+ "os"+ "path/filepath"+ "runtime"+)++const (+ appName = "WebBrain Companion"+ unixName = "webbrain-companion"+)++// Config returns the directory for small, user-owned state.+func Config() string {+ if h := os.Getenv("WBC_HOME"); h != "" {+ return h+ }+ switch runtime.GOOS {+ case "windows":+ if d := os.Getenv("APPDATA"); d != "" {+ return filepath.Join(d, appName)+ }+ case "darwin":+ if home, err := os.UserHomeDir(); err == nil {+ return filepath.Join(home, "Library", "Application Support", appName)+ }+ default:+ if d := os.Getenv("XDG_CONFIG_HOME"); d != "" {+ return filepath.Join(d, unixName)+ }+ if home, err := os.UserHomeDir(); err == nil {+ return filepath.Join(home, ".config", unixName)+ }+ }+ return filepath.Join(os.TempDir(), unixName)+}++// Data returns the directory for large artifacts (models, runtimes) and logs.+func Data() string {+ if h := os.Getenv("WBC_HOME"); h != "" {+ return h+ }+ switch runtime.GOOS {+ case "windows":+ if d := os.Getenv("LOCALAPPDATA"); d != "" {+ return filepath.Join(d, appName)+ }+ case "darwin":+ return Config()+ default:+ if d := os.Getenv("XDG_DATA_HOME"); d != "" {+ return filepath.Join(d, unixName)+ }+ if home, err := os.UserHomeDir(); err == nil {+ return filepath.Join(home, ".local", "share", unixName)+ }+ }+ return Config()+}++func AuthDir() string { return filepath.Join(Config(), "auths") }+func ProxyConfig() string { return filepath.Join(Config(), "proxy.yaml") }+func Settings() string { return filepath.Join(Config(), "companion.json") }+func LockFile() string { return filepath.Join(Config(), "companion.lock") }+func Logs() string { return filepath.Join(Data(), "logs") }+func Models() string { return filepath.Join(Data(), "models") }+func Runtimes() string { return filepath.Join(Data(), "runtimes") }++// Ensure creates every directory the companion writes to.+func Ensure() error {+ for _, d := range []string{Config(), AuthDir(), Data(), Logs(), Models(), Runtimes()} {+ if err := os.MkdirAll(d, 0o700); err != nil {+ return err+ }+ }+ return nil+}diff --git a/webbrain-systray/internal/quota/quota.go b/webbrain-systray/internal/quota/quota.gonew file mode 100644index 000000000..a162f87bf--- /dev/null+++ b/webbrain-systray/internal/quota/quota.go@@ -0,0 +1,677 @@+// Package quota reads each subscription's remaining usage from the provider's+// own usage endpoint. Requests go through the proxy's management api-call, so+// tokens are refreshed and never leave the embedded proxy.+package quota++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "math"+ "net/http"+ "sort"+ "strconv"+ "strings"+ "time"++ "github.com/esokullu/webbrain-systray/internal/core"+)++// Row is one usage window, e.g. the 5-hour or weekly limit.+type Row struct {+ // Window is "5h", "day", "week", "month" or "custom"; Scope narrows it+ // (a model family or feature). Label is an English fallback.+ Window string `json:"window"`+ Scope string `json:"scope,omitempty"`+ Label string `json:"label"`+ Remaining *float64 `json:"remaining"` // percent left, 0..100+ ResetAt *time.Time `json:"reset_at,omitempty"`+ Detail string `json:"detail,omitempty"`+}++type State struct {+ Status string `json:"status"` // ok | error | unsupported | loading+ Rows []Row `json:"rows"`+ Plan string `json:"plan,omitempty"`+ Error string `json:"error,omitempty"`+ FetchedAt time.Time `json:"fetched_at"`+}++// Supported reports whether a usage endpoint is known for the provider.+func Supported(provider string) bool {+ switch provider {+ case "claude", "anthropic", "codex", "antigravity", "kimi", "kimi-ai", "xai", "grok":+ return true+ }+ return false+}++// Fetch reads the current usage of one credential.+func Fetch(ctx context.Context, m *core.Mgmt, c core.Credential) State {+ if c.Bool("disabled") {+ return State{Status: "error", Error: "disabled", FetchedAt: time.Now()}+ }+ idx := c.AuthIndex()+ if idx == "" {+ return State{Status: "error", Error: "credential has no auth index", FetchedAt: time.Now()}+ }+ var (+ st State+ err error+ )+ switch c.Provider() {+ case "claude", "anthropic":+ st, err = claude(ctx, m, idx)+ case "codex":+ st, err = codex(ctx, m, c)+ case "antigravity":+ st, err = antigravity(ctx, m, c)+ case "kimi", "kimi-ai":+ st, err = kimi(ctx, m, c)+ case "xai", "grok":+ st, err = xai(ctx, m, c)+ default:+ return State{Status: "unsupported", FetchedAt: time.Now()}+ }+ st.FetchedAt = time.Now()+ if err != nil {+ st.Status = "error"+ st.Error = err.Error()+ return st+ }+ if len(st.Rows) == 0 {+ st.Status = "error"+ st.Error = "usage response not recognised"+ return st+ }+ st.Status = "ok"+ return st+}++// --- helpers -----------------------------------------------------------------++type apiCaller interface {+ APICall(context.Context, string, string, string, map[string]string, string) (core.APICallResult, error)+}++func call(ctx context.Context, m apiCaller, idx, method, url string, header map[string]string, data string) (map[string]any, error) {+ res, err := m.APICall(ctx, idx, method, url, header, data)+ if err != nil {+ return nil, err+ }+ if res.StatusCode < 200 || res.StatusCode >= 300 {+ msg := strings.TrimSpace(res.Body)+ var e struct {+ Error any `json:"error"`+ }+ if json.Unmarshal([]byte(msg), &e) == nil && e.Error != nil {+ switch t := e.Error.(type) {+ case string:+ msg = t+ case map[string]any:+ if s, ok := t["message"].(string); ok {+ msg = s+ }+ }+ }+ if len(msg) > 160 {+ msg = msg[:160] + "…"+ }+ return nil, fmt.Errorf("HTTP %d %s", res.StatusCode, msg)+ }+ var out map[string]any+ if err := json.Unmarshal([]byte(res.Body), &out); err != nil {+ return nil, errors.New("usage response is not JSON")+ }+ return out, nil+}++func obj(v any) map[string]any {+ m, _ := v.(map[string]any)+ return m+}++func first(m map[string]any, keys ...string) any {+ for _, k := range keys {+ if v, ok := m[k]; ok && v != nil {+ return v+ }+ }+ return nil+}++func num(v any) (float64, bool) {+ switch t := v.(type) {+ case float64:+ return t, !math.IsNaN(t) && !math.IsInf(t, 0)+ case string:+ s := strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(t), "%"))+ if s == "" {+ return 0, false+ }+ f, err := strconv.ParseFloat(s, 64)+ return f, err == nil+ case map[string]any:+ if inner, ok := t["val"]; ok {+ return num(inner)+ }+ }+ return 0, false+}++func str(v any) string {+ if s, ok := v.(string); ok {+ return strings.TrimSpace(s)+ }+ return ""+}++func clampPct(f float64) *float64 {+ f = math.Max(0, math.Min(100, f))+ return &f+}++func remainingFromUsed(v any) *float64 {+ if f, ok := num(v); ok {+ return clampPct(100 - f)+ }+ return nil+}++// parseTime accepts RFC3339 strings and unix seconds/milliseconds.+func parseTime(v any) *time.Time {+ switch t := v.(type) {+ case string:+ s := strings.TrimSpace(t)+ if s == "" {+ return nil+ }+ for _, layout := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05.999999999", "2006-01-02 15:04:05"} {+ if ts, err := time.Parse(layout, s); err == nil {+ return &ts+ }+ }+ if f, err := strconv.ParseFloat(s, 64); err == nil {+ return parseTime(f)+ }+ case float64:+ if t <= 0 {+ return nil+ }+ var ts time.Time+ if t < 1e11 {+ ts = time.Unix(int64(t), 0)+ } else {+ ts = time.UnixMilli(int64(t))+ }+ return &ts+ }+ return nil+}++func after(seconds any) *time.Time {+ if f, ok := num(seconds); ok && f > 0 {+ ts := time.Now().Add(time.Duration(f * float64(time.Second)))+ return &ts+ }+ return nil+}++func windowFromSeconds(sec float64, fallback string) (string, string) {+ switch {+ case sec == 18000:+ return "5h", "5h"+ case sec == 86400:+ return "day", "Day"+ case sec == 604800:+ return "week", "Week"+ case sec >= 28*86400 && sec <= 31*86400:+ return "month", "Month"+ case sec > 0:+ h := sec / 3600+ if h == math.Trunc(h) {+ return "custom", fmt.Sprintf("%gh", h)+ }+ return "custom", fmt.Sprintf("%gm", sec/60)+ }+ if fallback == "week" {+ return "week", "Week"+ }+ return "5h", "5h"+}++// --- Claude ------------------------------------------------------------------++var claudeHeaders = map[string]string{+ "Authorization": "Bearer $TOKEN$",+ "Content-Type": "application/json",+ "anthropic-beta": "oauth-2025-04-20",+}++func claude(ctx context.Context, m *core.Mgmt, idx string) (State, error) {+ body, err := call(ctx, m, idx, http.MethodGet, "https://api.anthropic.com/api/oauth/usage", claudeHeaders, "")+ if err != nil {+ return State{}, err+ }+ var st State+ windows := []struct{ key, window, scope, label string }{+ {"five_hour", "5h", "", "5h"},+ {"seven_day", "week", "", "Week"},+ {"seven_day_opus", "week", "Opus", "Week · Opus"},+ {"seven_day_sonnet", "week", "Sonnet", "Week · Sonnet"},+ {"seven_day_oauth_apps", "week", "Apps", "Week · Apps"},+ }+ for _, w := range windows {+ raw := obj(body[w.key])+ if raw == nil {+ continue+ }+ u, ok := raw["utilization"]+ if !ok {+ continue+ }+ st.Rows = append(st.Rows, Row{Window: w.window, Scope: w.scope, Label: w.label,+ Remaining: remainingFromUsed(u), ResetAt: parseTime(first(raw, "resets_at", "resetsAt"))})+ }+ // Model-scoped weekly limits (e.g. a separate allowance for one model).+ if limits, ok := body["limits"].([]any); ok {+ for _, l := range limits {+ lim := obj(l)+ if lim == nil || !strings.EqualFold(str(lim["kind"]), "weekly_scoped") {+ continue+ }+ name := str(first(obj(obj(lim["scope"])["model"]), "display_name", "displayName"))+ if name == "" {+ continue+ }+ pct, ok := num(lim["percent"])+ if !ok {+ continue+ }+ st.Rows = append(st.Rows, Row{Window: "week", Scope: name, Label: "Week · " + name,+ Remaining: clampPct(100 - pct), ResetAt: parseTime(first(lim, "resets_at", "resetsAt"))})+ }+ }+ if extra := obj(first(body, "extra_usage", "extraUsage")); extra != nil {+ if enabled, _ := extra["is_enabled"].(bool); enabled {+ limit, okL := num(first(extra, "monthly_limit", "monthlyLimit"))+ used, okU := num(first(extra, "used_credits", "usedCredits"))+ row := Row{Window: "month", Scope: "Extra", Label: "Extra usage"}+ if u, ok := num(extra["utilization"]); ok {+ row.Remaining = clampPct(100 - u)+ } else if okL && okU && limit > 0 {+ row.Remaining = clampPct((limit - used) / limit * 100)+ }+ if okL && okU {+ row.Detail = fmt.Sprintf("$%.2f / $%.2f", used/100, limit/100)+ }+ st.Rows = append(st.Rows, row)+ }+ }+ if prof, err := call(ctx, m, idx, http.MethodGet, "https://api.anthropic.com/api/oauth/profile", claudeHeaders, ""); err == nil {+ acct, org := obj(prof["account"]), obj(prof["organization"])+ switch {+ case acct["has_claude_max"] == true:+ st.Plan = "Max"+ case acct["has_claude_pro"] == true:+ st.Plan = "Pro"+ case strings.EqualFold(str(org["organization_type"]), "claude_team"):+ st.Plan = "Team"+ case acct["has_claude_max"] == false && acct["has_claude_pro"] == false:+ st.Plan = "Free"+ }+ }+ return st, nil+}++// --- ChatGPT / Codex ---------------------------------------------------------++func codexAccount(c core.Credential) (accountID, plan string) {+ records := []map[string]any{c.Raw, c.Map("metadata"), c.Map("id_token")}+ for _, r := range records {+ if r == nil {+ continue+ }+ if auth := obj(r["https://api.openai.com/auth"]); auth != nil {+ records = append(records, auth)+ }+ }+ for _, r := range records {+ if r == nil {+ continue+ }+ if accountID == "" {+ accountID = str(first(r, "chatgpt_account_id", "chatgptAccountId", "account_id"))+ }+ if plan == "" {+ plan = str(first(r, "plan_type", "planType", "chatgpt_plan_type"))+ }+ }+ return accountID, plan+}++func codex(ctx context.Context, m *core.Mgmt, c core.Credential) (State, error) {+ accountID, plan := codexAccount(c)+ header := map[string]string{+ "Authorization": "Bearer $TOKEN$",+ "Content-Type": "application/json",+ "User-Agent": "codex-tui/0.149.1 (Mac OS 26.5.2; arm64) iTerm.app/3.6.11 (codex-tui; 0.149.1)",+ }+ if accountID != "" {+ header["Chatgpt-Account-Id"] = accountID+ }+ body, err := call(ctx, m, c.AuthIndex(), http.MethodGet, "https://chatgpt.com/backend-api/wham/usage", header, "")+ if err != nil {+ return State{}, err+ }+ st := State{Plan: titlePlan(firstNonEmpty(str(first(body, "plan_type", "planType")), plan))}+ add := func(rl map[string]any, scope string) {+ if rl == nil {+ return+ }+ reached := rl["limit_reached"] == true || rl["allowed"] == false+ for i, key := range []string{"primary_window", "secondary_window"} {+ win := obj(first(rl, key, map[string]string{"primary_window": "primaryWindow", "secondary_window": "secondaryWindow"}[key]))+ if win == nil {+ continue+ }+ sec, _ := num(first(win, "limit_window_seconds", "limitWindowSeconds"))+ fallback := "5h"+ if i == 1 {+ fallback = "week"+ }+ window, label := windowFromSeconds(sec, fallback)+ if scope != "" {+ label += " · " + scope+ }+ row := Row{Window: window, Scope: scope, Label: label,+ Remaining: remainingFromUsed(first(win, "used_percent", "usedPercent"))}+ row.ResetAt = parseTime(first(win, "reset_at", "resetAt"))+ if row.ResetAt == nil {+ row.ResetAt = after(first(win, "reset_after_seconds", "resetAfterSeconds"))+ }+ if row.Remaining == nil && reached {+ row.Remaining = clampPct(0)+ }+ st.Rows = append(st.Rows, row)+ }+ }+ add(obj(first(body, "rate_limit", "rateLimit")), "")+ add(obj(first(body, "code_review_rate_limit", "codeReviewRateLimit")), "Code review")+ if extra, ok := first(body, "additional_rate_limits", "additionalRateLimits").([]any); ok {+ for _, it := range extra {+ item := obj(it)+ if item == nil {+ continue+ }+ name := str(first(item, "limit_name", "limitName", "metered_feature", "meteredFeature"))+ add(obj(first(item, "rate_limit", "rateLimit")), name)+ }+ }+ sort.SliceStable(st.Rows, func(i, j int) bool {+ if (st.Rows[i].Scope == "") != (st.Rows[j].Scope == "") {+ return st.Rows[i].Scope == ""+ }+ return false+ })+ if credits := obj(body["credits"]); credits != nil {+ if bal := str(credits["balance"]); bal != "" && bal != "0" {+ st.Rows = append(st.Rows, Row{Window: "custom", Scope: "Credits", Label: "Credits", Detail: bal})+ }+ }+ return st, nil+}++// --- Google Antigravity -------------------------------------------------------++var antigravityHeaders = map[string]string{+ "Authorization": "Bearer $TOKEN$",+ "Content-Type": "application/json",+ "User-Agent": "antigravity/hub/2.23.0 darwin/arm64",+}++func antigravity(ctx context.Context, m *core.Mgmt, c core.Credential) (State, error) {+ project := c.Str("project_id", "projectId")+ if project == "" {+ if md := c.Map("metadata"); md != nil {+ project = str(first(md, "project_id", "projectId"))+ }+ }+ if project == "" {+ return State{}, errors.New("no Google Cloud project on this login yet; use it once and refresh")+ }+ data, _ := json.Marshal(map[string]string{"project": project})+ var (+ body map[string]any+ lastErr error+ )+ for _, u := range []string{+ "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",+ "https://daily-cloudcode-pa.sandbox.googleapis.com/v1internal:retrieveUserQuotaSummary",+ "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",+ } {+ b, err := call(ctx, m, c.AuthIndex(), http.MethodPost, u, antigravityHeaders, string(data))+ if err != nil {+ lastErr = err+ continue+ }+ if groups, ok := b["groups"].([]any); ok && len(groups) > 0 {+ body = b+ break+ }+ lastErr = errors.New("empty quota summary")+ }+ if body == nil {+ return State{}, lastErr+ }+ var st State+ for _, g := range body["groups"].([]any) {+ group := obj(g)+ if group == nil {+ continue+ }+ gname := str(first(group, "display_name", "displayName"))+ buckets, _ := group["buckets"].([]any)+ for _, bk := range buckets {+ b := obj(bk)+ if b == nil {+ continue+ }+ frac, ok := num(first(b, "remaining_fraction", "remainingFraction"))+ if !ok {+ continue+ }+ if frac > 1 {+ frac /= 100+ }+ bname := str(first(b, "display_name", "displayName", "description"))+ window := strings.ToLower(str(b["window"]) + " " + bname)+ w, label := "custom", bname+ switch {+ case strings.Contains(window, "5h") || strings.Contains(window, "five") || strings.Contains(window, "5-hour"):+ w, label = "5h", "5h"+ case strings.Contains(window, "week"):+ w, label = "week", "Week"+ case strings.Contains(window, "day") || strings.Contains(window, "daily"):+ w, label = "day", "Day"+ }+ if label == "" {+ label = "Quota"+ }+ if gname != "" {+ label += " · " + gname+ }+ st.Rows = append(st.Rows, Row{Window: w, Scope: gname, Label: label,+ Remaining: clampPct(frac * 100), ResetAt: parseTime(first(b, "reset_time", "resetTime"))})+ }+ }+ if tier, err := call(ctx, m, c.AuthIndex(), http.MethodPost,+ "https://daily-cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", antigravityHeaders,+ `{"metadata":{"ideType":"ANTIGRAVITY"}}`); err == nil {+ eff := obj(first(tier, "paidTier", "paid_tier"))+ if str(eff["id"]) == "" {+ eff = obj(first(tier, "currentTier", "current_tier"))+ }+ switch strings.ToLower(str(eff["id"])) {+ case "free-tier":+ st.Plan = "Free"+ case "g1-pro-tier":+ st.Plan = "AI Pro"+ case "g1-ultra-tier":+ st.Plan = "AI Ultra"+ case "g1-ultra-lite-tier":+ st.Plan = "Ultra Lite"+ default:+ st.Plan = str(eff["name"])+ }+ }+ return st, nil+}++// --- Kimi -------------------------------------------------------------------++func kimi(ctx context.Context, m apiCaller, c core.Credential) (State, error) {+ endpoint := "https://api.kimi.com/coding/v1/usages"+ if c.Provider() == "kimi-ai" {+ endpoint = "https://api.kimi.ai/coding/v1/usages"+ }+ body, err := call(ctx, m, c.AuthIndex(), http.MethodGet, endpoint,+ map[string]string{"Authorization": "Bearer $TOKEN$"}, "")+ if err != nil {+ return State{}, err+ }+ var st State+ items, _ := body["limits"].([]any)+ if u := obj(body["usage"]); u != nil {+ items = append(items, u)+ }+ for _, it := range items {+ raw := obj(it)+ if raw == nil {+ continue+ }+ detail := obj(raw["detail"])+ if detail == nil {+ detail = raw+ }+ limit, okL := num(detail["limit"])+ used, okU := num(detail["used"])+ if !okU {+ if rem, okR := num(detail["remaining"]); okR && okL {+ used, okU = limit-rem, true+ }+ }+ if !okL && !okU {+ continue+ }+ win := obj(raw["window"])+ dur, _ := num(first(win, "duration"))+ unit := strings.ToLower(strings.TrimPrefix(strings.ToLower(str(first(win, "timeUnit", "time_unit"))), "time_unit_"))+ window, label := "custom", str(first(raw, "label", "name", "title", "scope"))+ switch {+ case strings.HasPrefix(unit, "week") || (strings.HasPrefix(unit, "day") && dur == 7):+ window, label = "week", "Week"+ case strings.HasPrefix(unit, "hour") && dur == 5, strings.HasPrefix(unit, "minute") && dur == 300:+ window, label = "5h", "5h"+ case strings.HasPrefix(unit, "day") && dur == 1:+ window, label = "day", "Day"+ }+ if label == "" {+ label = "Quota"+ }+ row := Row{Window: window, Label: label}+ if okL && limit > 0 {+ row.Remaining = clampPct(math.Max(0, limit-used) / limit * 100)+ row.Detail = fmt.Sprintf("%g / %g", used, limit)+ }+ row.ResetAt = parseTime(first(detail, "reset_at", "resetAt", "reset_time", "resetTime"))+ if row.ResetAt == nil {+ row.ResetAt = after(first(detail, "reset_in", "resetIn", "ttl"))+ }+ st.Rows = append(st.Rows, row)+ }+ return st, nil+}++// --- xAI / Grok ---------------------------------------------------------------++func xai(ctx context.Context, m *core.Mgmt, c core.Credential) (State, error) {+ header := map[string]string{+ "Authorization": "Bearer $TOKEN$",+ "x-xai-token-auth": "xai-grok-cli",+ "x-grok-client-version": "0.2.91",+ "accept": "*/*",+ "user-agent": "grok-pager/0.2.91 grok-shell/0.2.91 (macos; aarch64)",+ }+ if uid := c.Str("sub", "user_id", "userId"); uid != "" {+ header["x-userid"] = uid+ } else if md := c.Map("metadata"); md != nil {+ if uid := str(first(md, "sub", "user_id", "userId")); uid != "" {+ header["x-userid"] = uid+ }+ }+ var st State+ weekly, errW := call(ctx, m, c.AuthIndex(), http.MethodGet, "https://cli-chat-proxy.grok.com/v1/billing?format=credits", header, "")+ if errW == nil {+ cfg := obj(weekly["config"])+ if cfg == nil {+ cfg = weekly+ }+ period := obj(first(cfg, "currentPeriod", "current_period"))+ if pct, ok := num(first(cfg, "creditUsagePercent", "credit_usage_percent")); ok {+ window, label := "custom", "Period"+ if strings.Contains(strings.ToLower(str(period["type"])), "week") {+ window, label = "week", "Week"+ }+ st.Rows = append(st.Rows, Row{Window: window, Label: label, Remaining: clampPct(100 - pct),+ ResetAt: parseTime(period["end"])})+ }+ }+ monthly, errM := call(ctx, m, c.AuthIndex(), http.MethodGet, "https://cli-chat-proxy.grok.com/v1/billing", header, "")+ if errM == nil {+ cfg := obj(monthly["config"])+ if cfg == nil {+ cfg = monthly+ }+ limit, okL := num(first(cfg, "monthlyLimit", "monthly_limit"))+ used, okU := num(cfg["used"])+ if okL && okU && limit > 0 {+ st.Rows = append(st.Rows, Row{Window: "month", Label: "Month", Remaining: clampPct((limit - used) / limit * 100),+ Detail: fmt.Sprintf("$%.2f / $%.2f", used/100, limit/100),+ ResetAt: parseTime(first(cfg, "billingPeriodEnd", "billing_period_end"))})+ switch limit {+ case 150000:+ st.Plan = "SuperGrok Heavy"+ case 15000:+ st.Plan = "SuperGrok"+ }+ }+ }+ if len(st.Rows) == 0 {+ if errW != nil {+ return st, errW+ }+ if errM != nil {+ return st, errM+ }+ }+ return st, nil+}++func firstNonEmpty(v ...string) string {+ for _, s := range v {+ if s != "" {+ return s+ }+ }+ return ""+}++func titlePlan(p string) string {+ p = strings.TrimSpace(p)+ if p == "" {+ return ""+ }+ return strings.ToUpper(p[:1]) + p[1:]+}diff --git a/webbrain-systray/internal/quota/quota_test.go b/webbrain-systray/internal/quota/quota_test.gonew file mode 100644index 000000000..7c09df55f--- /dev/null+++ b/webbrain-systray/internal/quota/quota_test.go@@ -0,0 +1,49 @@+package quota++import (+ "context"+ "net/http"+ "testing"++ "github.com/esokullu/webbrain-systray/internal/core"+)++type recordingCaller struct {+ index, method, url string+ header map[string]string+}++func (m *recordingCaller) APICall(_ context.Context, index, method, url string, header map[string]string, _ string) (core.APICallResult, error) {+ m.index, m.method, m.url, m.header = index, method, url, header+ return core.APICallResult{+ StatusCode: http.StatusOK,+ Body: `{"limits":[{"window":{"duration":5,"timeUnit":"hour"},"detail":{"limit":100,"used":25}}]}`,+ }, nil+}++func TestKimiUsageEndpoint(t *testing.T) {+ for _, tc := range []struct {+ provider, endpoint string+ }{+ {"kimi", "https://api.kimi.com/coding/v1/usages"},+ {"kimi-ai", "https://api.kimi.ai/coding/v1/usages"},+ } {+ t.Run(tc.provider, func(t *testing.T) {+ m := &recordingCaller{}+ c := core.Credential{Raw: map[string]any{"provider": tc.provider, "auth_index": "account-index"}}+ st, err := kimi(context.Background(), m, c)+ if err != nil {+ t.Fatal(err)+ }+ if m.url != tc.endpoint || m.index != "account-index" || m.method != http.MethodGet {+ t.Fatalf("request: index=%q method=%q url=%q", m.index, m.method, m.url)+ }+ if m.header["Authorization"] != "Bearer $TOKEN$" {+ t.Fatalf("credential substitution header: %q", m.header["Authorization"])+ }+ if len(st.Rows) != 1 || st.Rows[0].Window != "5h" || st.Rows[0].Remaining == nil || *st.Rows[0].Remaining != 75 {+ t.Fatalf("unexpected quota rows: %+v", st.Rows)+ }+ })+ }+}diff --git a/webbrain-systray/internal/settings/settings.go b/webbrain-systray/internal/settings/settings.gonew file mode 100644index 000000000..ec6dde88a--- /dev/null+++ b/webbrain-systray/internal/settings/settings.go@@ -0,0 +1,165 @@+// Package settings persists the companion's own preferences (not the proxy+// config, which is generated from these on every start).+package settings++import (+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "sync"++ "github.com/esokullu/webbrain-systray/internal/paths"+)++// DefaultPort is the companion's own port. 8317, used up to 0.1.1, is also the+// default of CLIProxyAPI, EasyCLIProxyAPI and similar tools, so it was often+// taken and the companion ended up on a different port each time.+const DefaultPort = 8327++const legacyDefaultPort = 8317++// settingsVersion 2 moved the default port off 8317.+const settingsVersion = 2++type Local struct {+ // Format is "gguf" (llama.cpp, every platform) or "mlx" (Apple Silicon).+ Format string `json:"format,omitempty"`+ // AutoStart starts the local model server whenever the companion starts.+ AutoStart bool `json:"auto_start"`+ // Vision is "auto" (decide from memory), "gpu", "cpu" or "off".+ Vision string `json:"vision,omitempty"`+ // Context is the context size in tokens; 0 means automatic.+ Context int `json:"context,omitempty"`+ // Port is the loopback port of the local inference server; 0 picks one.+ Port int `json:"port,omitempty"`+}++type Decision struct {+ // Enabled loads the d1 decision model at startup when it is installed.+ Enabled bool `json:"enabled"`+ // Threads overrides ONNX Runtime intra-op threads; 0 lets the runtime decide.+ Threads int `json:"threads,omitempty"`+}++type Settings struct {+ Version int `json:"version,omitempty"`+ Port int `json:"port"`+ // APIKey is required only from other devices (Network is on); apps on this+ // computer need no key.+ APIKey string `json:"api_key"`+ // Network listens on 0.0.0.0 so other devices on the network can connect+ // with the API key. Off by default: 127.0.0.1 only.+ Network bool `json:"network,omitempty"`+ PanelToken string `json:"panel_token"`+ Autostart bool `json:"autostart"`+ QuotaRefreshMinutes int `json:"quota_refresh_minutes"`+ Language string `json:"language,omitempty"`+ Local Local `json:"local"`+ Decision Decision `json:"decision"`+ // Welcomed is set after the first panel opening so it is not repeated.+ Welcomed bool `json:"welcomed"`+}++type Store struct {+ mu sync.Mutex+ path string+ s Settings+}++func randomHex(n int) string {+ b := make([]byte, n)+ if _, err := rand.Read(b); err != nil {+ panic(err)+ }+ return hex.EncodeToString(b)+}++// NewAPIKey returns a fresh client key in the "wb-" namespace.+func NewAPIKey() string { return "wb-" + randomHex(20) }++// Open loads the settings file, filling in defaults and secrets on first run.+func Open() (*Store, error) {+ st := &Store{path: paths.Settings()}+ data, err := os.ReadFile(st.path)+ switch {+ case err == nil:+ if err := json.Unmarshal(data, &st.s); err != nil {+ // Keep a copy of the unreadable file and start fresh rather than refusing to run.+ _ = os.WriteFile(st.path+".corrupt", data, 0o600)+ st.s = Settings{}+ }+ case errors.Is(err, os.ErrNotExist):+ default:+ return nil, err+ }+ changed := false+ if st.s.Version < settingsVersion {+ if st.s.Port == legacyDefaultPort {+ st.s.Port = DefaultPort+ }+ st.s.Version = settingsVersion+ changed = true+ }+ if st.s.Port == 0 {+ st.s.Port = DefaultPort+ changed = true+ }+ if st.s.APIKey == "" {+ st.s.APIKey = NewAPIKey()+ changed = true+ }+ if st.s.PanelToken == "" {+ st.s.PanelToken = randomHex(24)+ changed = true+ }+ if st.s.QuotaRefreshMinutes == 0 {+ st.s.QuotaRefreshMinutes = 5+ changed = true+ }+ if st.s.Local.Vision == "" {+ st.s.Local.Vision = "auto"+ changed = true+ }+ if changed {+ if err := st.saveLocked(); err != nil {+ return nil, err+ }+ }+ return st, nil+}++// Get returns a copy of the current settings.+func (st *Store) Get() Settings {+ st.mu.Lock()+ defer st.mu.Unlock()+ return st.s+}++// Update applies fn to the settings and persists the result.+func (st *Store) Update(fn func(*Settings)) (Settings, error) {+ st.mu.Lock()+ defer st.mu.Unlock()+ fn(&st.s)+ return st.s, st.saveLocked()+}++func (st *Store) saveLocked() error {+ data, err := json.MarshalIndent(st.s, "", " ")+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(st.path), 0o700); err != nil {+ return err+ }+ tmp := st.path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, st.path)+}++// RandomSecret is exposed for components that need throwaway secrets.+func RandomSecret() string { return randomHex(24) }diff --git a/webbrain-systray/internal/settings/settings_test.go b/webbrain-systray/internal/settings/settings_test.gonew file mode 100644index 000000000..300f404a0--- /dev/null+++ b/webbrain-systray/internal/settings/settings_test.go@@ -0,0 +1,35 @@+package settings++import (+ "os"+ "path/filepath"+ "testing"+)++func TestPortMigration(t *testing.T) {+ cases := []struct {+ file string+ want int+ }{+ {``, DefaultPort}, // fresh install+ {`{"port":8317}`, DefaultPort}, // 0.1.x default moves off CLIProxyAPI's port+ {`{"port":9000}`, 9000}, // a port the user chose stays+ {`{"version":2,"port":8317}`, 8317}, // chosen after the move: respected+ }+ for _, c := range cases {+ home := t.TempDir()+ t.Setenv("WBC_HOME", home)+ if c.file != "" {+ if err := os.WriteFile(filepath.Join(home, "companion.json"), []byte(c.file), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ st, err := Open()+ if err != nil {+ t.Fatal(err)+ }+ if got := st.Get(); got.Port != c.want || got.Version != settingsVersion {+ t.Errorf("%s: port %d version %d, want %d and %d", c.file, got.Port, got.Version, c.want, settingsVersion)+ }+ }+}diff --git a/webbrain-systray/internal/sysinfo/sysinfo.go b/webbrain-systray/internal/sysinfo/sysinfo.gonew file mode 100644index 000000000..b7ca12d63--- /dev/null+++ b/webbrain-systray/internal/sysinfo/sysinfo.go@@ -0,0 +1,196 @@+// Package sysinfo describes the machine well enough to size a local model:+// memory, the GPU and its memory, and which llama.cpp build fits.+package sysinfo++import (+ "bufio"+ "bytes"+ "context"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "runtime"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/esokullu/webbrain-systray/internal/osutil"+)++const GiB = 1 << 30++type GPU struct {+ Vendor string `json:"vendor"` // nvidia | apple | other+ Name string `json:"name"`+ MemoryBytes uint64 `json:"memory_bytes"` // dedicated VRAM; for Apple, the GPU working-set budget+ FreeBytes uint64 `json:"free_bytes,omitempty"`+ CUDA string `json:"cuda,omitempty"` // driver-supported CUDA version, e.g. "13.0"+}++type Info struct {+ OS string `json:"os"`+ Arch string `json:"arch"`+ CPU string `json:"cpu"`+ Cores int `json:"cores"`+ MemoryBytes uint64 `json:"memory_bytes"`+ AvailableBytes uint64 `json:"available_bytes,omitempty"`+ AppleSilicon bool `json:"apple_silicon"`+ Vulkan bool `json:"vulkan"`+ GPU *GPU `json:"gpu,omitempty"`+}++// MemoryGiB is total memory in whole GiB (as Bonsai's tiers count it).+func (i Info) MemoryGiB() int { return int(i.MemoryBytes / GiB) }++// Summary is a one-line human description, e.g. "Apple M4 Max · 64 GB unified".+func (i Info) Summary() string {+ mem := fmt.Sprintf("%d GB", (i.MemoryBytes+GiB/2)/GiB)+ if i.AppleSilicon {+ return fmt.Sprintf("%s with %s unified memory", strings.TrimSpace(i.CPU), mem)+ }+ if i.GPU != nil && i.GPU.Vendor == "nvidia" {+ return fmt.Sprintf("%s (%d GB) and %s RAM", i.GPU.Name, (i.GPU.MemoryBytes+GiB/2)/GiB, mem)+ }+ cpu := strings.TrimSpace(i.CPU)+ if cpu == "" {+ cpu = runtime.GOARCH + " CPU"+ }+ return fmt.Sprintf("%s with %s RAM", cpu, mem)+}++var (+ cacheMu sync.Mutex+ cached *Info+ cacheAt time.Time+)++// Get returns machine info; GPU probing is cached for a few minutes.+func Get() Info {+ cacheMu.Lock()+ defer cacheMu.Unlock()+ if cached != nil && time.Since(cacheAt) < 3*time.Minute {+ c := *cached+ c.AvailableBytes = availableMemory()+ return c+ }+ info := Info{OS: runtime.GOOS, Arch: runtime.GOARCH, Cores: runtime.NumCPU()}+ info.MemoryBytes = totalMemory()+ info.AvailableBytes = availableMemory()+ info.CPU = cpuName()+ if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm64" || rosetta()) {+ info.AppleSilicon = true+ info.Arch = "arm64"+ // Metal may use about three quarters of unified memory by default.+ info.GPU = &GPU{Vendor: "apple", Name: strings.TrimSpace(info.CPU) + " GPU", MemoryBytes: info.MemoryBytes * 3 / 4}+ } else if g := nvidia(); g != nil {+ info.GPU = g+ } else if g := otherGPU(); g != nil {+ info.GPU = g+ }+ if runtime.GOOS != "darwin" {+ info.Vulkan = hasVulkan()+ }+ cached = &info+ cacheAt = time.Now()+ return info+}++func run(timeout time.Duration, name string, args ...string) (string, error) {+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()+ cmd := osutil.CommandContext(ctx, name, args...)+ var out bytes.Buffer+ cmd.Stdout = &out+ cmd.Stderr = &out+ err := cmd.Run()+ return out.String(), err+}++// FindExecutable looks in PATH and then in extra well-known locations.+func FindExecutable(name string, extra ...string) string {+ if runtime.GOOS == "windows" && !strings.HasSuffix(strings.ToLower(name), ".exe") {+ name += ".exe"+ }+ if p, err := exec.LookPath(name); err == nil {+ return p+ }+ for _, dir := range extra {+ p := filepath.Join(os.ExpandEnv(dir), name)+ if st, err := os.Stat(p); err == nil && !st.IsDir() {+ return p+ }+ }+ return ""+}++var cudaRe = regexp.MustCompile(`CUDA(?:\s+UMD)?\s+Version:\s+(\d+)\.(\d+)`)++func nvidia() *GPU {+ smi := FindExecutable("nvidia-smi",+ `${SystemRoot}\System32`, `${ProgramFiles}\NVIDIA Corporation\NVSMI`, "/usr/bin", "/usr/local/bin", "/usr/lib/wsl/lib")+ if smi == "" {+ return nil+ }+ out, err := run(8*time.Second, smi, "--query-gpu=name,memory.total,memory.free", "--format=csv,noheader,nounits")+ if err != nil {+ return nil+ }+ var best *GPU+ sc := bufio.NewScanner(strings.NewReader(out))+ for sc.Scan() {+ parts := strings.Split(sc.Text(), ",")+ if len(parts) < 3 {+ continue+ }+ total, err1 := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)+ free, _ := strconv.ParseFloat(strings.TrimSpace(parts[2]), 64)+ if err1 != nil {+ continue+ }+ g := &GPU{Vendor: "nvidia", Name: strings.TrimSpace(parts[0]),+ MemoryBytes: uint64(total * 1024 * 1024), FreeBytes: uint64(free * 1024 * 1024)}+ // Prefer the card with the most memory (a display-only card may be first).+ if best == nil || g.MemoryBytes > best.MemoryBytes {+ best = g+ }+ }+ if best == nil {+ return nil+ }+ if plain, err := run(8*time.Second, smi); err == nil {+ if m := cudaRe.FindStringSubmatch(plain); m != nil {+ best.CUDA = m[1] + "." + m[2]+ }+ }+ return best+}++// hasVulkan reports a usable Vulkan loader on a machine that also has a+// GPU device; a loader alone (common in containers and on servers) is not+// enough.+func hasVulkan() bool {+ switch runtime.GOOS {+ case "windows":+ if _, err := os.Stat(filepath.Join(os.Getenv("SystemRoot"), "System32", "vulkan-1.dll")); err != nil {+ return false+ }+ return true+ case "linux":+ nodes, _ := filepath.Glob("/dev/dri/renderD*")+ if len(nodes) == 0 {+ return false+ }+ if FindExecutable("vulkaninfo") != "" {+ return true+ }+ for _, p := range []string{"/usr/lib/x86_64-linux-gnu/libvulkan.so.1", "/usr/lib64/libvulkan.so.1", "/usr/lib/libvulkan.so.1", "/usr/lib/aarch64-linux-gnu/libvulkan.so.1"} {+ if _, err := os.Stat(p); err == nil {+ return true+ }+ }+ }+ return false+}diff --git a/webbrain-systray/internal/sysinfo/sysinfo_darwin.go b/webbrain-systray/internal/sysinfo/sysinfo_darwin.gonew file mode 100644index 000000000..c8fe83c19--- /dev/null+++ b/webbrain-systray/internal/sysinfo/sysinfo_darwin.go@@ -0,0 +1,60 @@+//go:build darwin++package sysinfo++import (+ "regexp"+ "strconv"+ "strings"+ "time"++ "golang.org/x/sys/unix"+)++func totalMemory() uint64 {+ v, err := unix.SysctlUint64("hw.memsize")+ if err != nil {+ return 0+ }+ return v+}++var vmStatRe = regexp.MustCompile(`Pages (free|inactive|speculative|purgeable):\s+(\d+)`)++func availableMemory() uint64 {+ out, err := run(3*time.Second, "/usr/bin/vm_stat")+ if err != nil {+ return 0+ }+ page := uint64(16384)+ if i := strings.Index(out, "page size of "); i >= 0 {+ rest := out[i+len("page size of "):]+ if j := strings.Index(rest, " "); j > 0 {+ if v, err := strconv.ParseUint(rest[:j], 10, 64); err == nil {+ page = v+ }+ }+ }+ var pages uint64+ for _, m := range vmStatRe.FindAllStringSubmatch(out, -1) {+ v, _ := strconv.ParseUint(m[2], 10, 64)+ pages += v+ }+ return pages * page+}++// rosetta reports an amd64 build running translated on Apple Silicon.+func rosetta() bool {+ v, err := unix.SysctlUint32("sysctl.proc_translated")+ return err == nil && v == 1+}++func cpuName() string {+ s, err := unix.Sysctl("machdep.cpu.brand_string")+ if err != nil {+ return ""+ }+ return s+}++func otherGPU() *GPU { return nil }diff --git a/webbrain-systray/internal/sysinfo/sysinfo_linux.go b/webbrain-systray/internal/sysinfo/sysinfo_linux.gonew file mode 100644index 000000000..79da1c06b--- /dev/null+++ b/webbrain-systray/internal/sysinfo/sysinfo_linux.go@@ -0,0 +1,74 @@+//go:build linux++package sysinfo++import (+ "bufio"+ "os"+ "path/filepath"+ "strconv"+ "strings"+)++func meminfo(key string) uint64 {+ f, err := os.Open("/proc/meminfo")+ if err != nil {+ return 0+ }+ defer f.Close()+ sc := bufio.NewScanner(f)+ for sc.Scan() {+ line := sc.Text()+ if strings.HasPrefix(line, key+":") {+ fields := strings.Fields(line[len(key)+1:])+ if len(fields) > 0 {+ kb, _ := strconv.ParseUint(fields[0], 10, 64)+ return kb * 1024+ }+ }+ }+ return 0+}++func totalMemory() uint64 { return meminfo("MemTotal") }+func availableMemory() uint64 { return meminfo("MemAvailable") }+func rosetta() bool { return false }++func cpuName() string {+ data, err := os.ReadFile("/proc/cpuinfo")+ if err != nil {+ return ""+ }+ for _, line := range strings.Split(string(data), "\n") {+ if strings.HasPrefix(line, "model name") || strings.HasPrefix(line, "Model") {+ if i := strings.Index(line, ":"); i >= 0 {+ return strings.TrimSpace(line[i+1:])+ }+ }+ }+ return ""+}++// otherGPU reads AMD dedicated VRAM from sysfs (amdgpu exposes it).+func otherGPU() *GPU {+ cards, _ := filepath.Glob("/sys/class/drm/card*/device/mem_info_vram_total")+ var best *GPU+ for _, c := range cards {+ data, err := os.ReadFile(c)+ if err != nil {+ continue+ }+ v, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)+ if err != nil || v < 2<<30 {+ continue+ }+ name := "AMD GPU"+ if b, err := os.ReadFile(filepath.Join(filepath.Dir(c), "product_name")); err == nil && len(strings.TrimSpace(string(b))) > 0 {+ name = strings.TrimSpace(string(b))+ }+ if best == nil || v > best.MemoryBytes {+ best = &GPU{Vendor: "amd", Name: name, MemoryBytes: v}+ }+ }+ return best+}diff --git a/webbrain-systray/internal/sysinfo/sysinfo_windows.go b/webbrain-systray/internal/sysinfo/sysinfo_windows.gonew file mode 100644index 000000000..86916c478--- /dev/null+++ b/webbrain-systray/internal/sysinfo/sysinfo_windows.go@@ -0,0 +1,89 @@+//go:build windows++package sysinfo++import (+ "strings"+ "unsafe"++ "golang.org/x/sys/windows"+ "golang.org/x/sys/windows/registry"+)++type memoryStatusEx struct {+ Length uint32+ MemoryLoad uint32+ TotalPhys uint64+ AvailPhys uint64+ TotalPageFile uint64+ AvailPageFile uint64+ TotalVirtual uint64+ AvailVirtual uint64+ AvailExtendedVirtual uint64+}++var procGlobalMemoryStatusEx = windows.NewLazySystemDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx")++func memStatus() memoryStatusEx {+ var m memoryStatusEx+ m.Length = uint32(unsafe.Sizeof(m))+ _, _, _ = procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&m)))+ return m+}++func totalMemory() uint64 { return memStatus().TotalPhys }+func availableMemory() uint64 { return memStatus().AvailPhys }+func rosetta() bool { return false }++func cpuName() string {+ k, err := registry.OpenKey(registry.LOCAL_MACHINE, `HARDWARE\DESCRIPTION\System\CentralProcessor\0`, registry.QUERY_VALUE)+ if err != nil {+ return ""+ }+ defer k.Close()+ s, _, err := k.GetStringValue("ProcessorNameString")+ if err != nil {+ return ""+ }+ return strings.TrimSpace(s)+}++// otherGPU finds the display adapter with the most dedicated memory from the+// registry (qwMemorySize is exact above 4 GB, unlike WMI's AdapterRAM).+// Integrated adapters report little or no dedicated memory and are skipped.+func otherGPU() *GPU {+ const class = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}`+ k, err := registry.OpenKey(registry.LOCAL_MACHINE, class, registry.ENUMERATE_SUB_KEYS)+ if err != nil {+ return nil+ }+ defer k.Close()+ subs, _ := k.ReadSubKeyNames(-1)+ var best *GPU+ for _, s := range subs {+ sk, err := registry.OpenKey(registry.LOCAL_MACHINE, class+`\`+s, registry.QUERY_VALUE)+ if err != nil {+ continue+ }+ mem, _, err := sk.GetIntegerValue("HardwareInformation.qwMemorySize")+ name, _, _ := sk.GetStringValue("DriverDesc")+ sk.Close()+ if err != nil || mem < 6<<30 {+ continue+ }+ vendor := "other"+ lower := strings.ToLower(name)+ switch {+ case strings.Contains(lower, "nvidia"):+ vendor = "nvidia"+ case strings.Contains(lower, "amd") || strings.Contains(lower, "radeon"):+ vendor = "amd"+ case strings.Contains(lower, "intel"):+ vendor = "intel"+ }+ if best == nil || mem > best.MemoryBytes {+ best = &GPU{Vendor: vendor, Name: name, MemoryBytes: mem}+ }+ }+ return best+}diff --git a/webbrain-systray/internal/tray/tray.go b/webbrain-systray/internal/tray/tray.gonew file mode 100644index 000000000..95ea5a479--- /dev/null+++ b/webbrain-systray/internal/tray/tray.go@@ -0,0 +1,35 @@+// Package tray shows the companion's status-bar / notification-area icon and+// menu. Windows and Linux use fyne.io/systray; macOS uses a small Cocoa+// binding built on purego so the whole app cross-compiles without cgo.+package tray++// Item is one menu entry. A zero Item with Separator set draws a line.+type Item struct {+ Title string+ Tooltip string+ Disabled bool+ Checked bool+ Separator bool+ // Secondary renders the row in a dimmer style where supported (macOS).+ Secondary bool+ OnClick func()+ Children []Item+}++// Icon carries the artwork for every platform.+type Icon struct {+ Template []byte // macOS: monochrome PNG used as a template image (@2x, 144 dpi)+ PNG []byte // Linux: colour PNG+ ICO []byte // Windows: .ico+}++// Options configure Run.+type Options struct {+ Icon Icon+ Tooltip string+ // Menu builds the current menu. It is called when the menu is about to+ // open (macOS) and whenever Refresh is called.+ Menu func() []Item+ OnReady func()+ OnExit func()+}diff --git a/webbrain-systray/internal/tray/tray_darwin.go b/webbrain-systray/internal/tray/tray_darwin.gonew file mode 100644index 000000000..a479b5e76--- /dev/null+++ b/webbrain-systray/internal/tray/tray_darwin.go@@ -0,0 +1,375 @@+//go:build darwin++package tray++import (+ "runtime"+ "sync"+ "sync/atomic"+ "time"+ "unsafe"++ "github.com/ebitengine/purego"+ "github.com/ebitengine/purego/objc"++ "github.com/esokullu/webbrain-systray/internal/logx"+)++// Cocoa must be driven from the main thread: lock it during init so main()+// (which calls Run) stays there.+func init() { runtime.LockOSThread() }++type nsSize struct {+ W, H float64+}++var (+ opts Options+ selCache = map[string]objc.SEL{}+ selMu sync.Mutex+ app objc.ID+ statusItem objc.ID+ menu objc.ID+ target objc.ID++ handlersMu sync.Mutex+ handlers = map[int]func(){}++ queueMu sync.Mutex+ queue []func()++ onTap func()++ hidden atomic.Bool+ loggedVis atomic.Bool+ appDelegate objc.ID+)++func sel(name string) objc.SEL {+ selMu.Lock()+ defer selMu.Unlock()+ s, ok := selCache[name]+ if !ok {+ s = objc.RegisterName(name)+ selCache[name] = s+ }+ return s+}++func cls(name string) objc.ID { return objc.ID(objc.GetClass(name)) }++func nsString(s string) objc.ID {+ return cls("NSString").Send(sel("stringWithUTF8String:"), s)+}++// SetOnTap sets what reopening the app does (double-clicking it in Finder or+// launching it from Spotlight while it runs): open the panel. A click on the+// menu bar icon always shows the menu.+func SetOnTap(fn func()) { onTap = fn }++// Hidden reports whether macOS shows the menu bar icon. A menu bar with more+// items than fit (on notched MacBooks especially) hides the newest ones.+func Hidden() bool { return hidden.Load() }++// Run starts NSApplication with a status item. It never returns normally:+// Quit terminates the process after OnExit.+func Run(o Options) {+ opts = o+ if _, err := purego.Dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", purego.RTLD_GLOBAL|purego.RTLD_NOW); err != nil {+ panic("AppKit: " + err.Error())+ }+ pool := cls("NSAutoreleasePool").Send(sel("alloc")).Send(sel("init"))++ var protocols []*objc.Protocol+ if p := objc.GetProtocol("NSMenuDelegate"); p != nil {+ protocols = append(protocols, p)+ }+ class, err := objc.RegisterClass("WBCompanionTrayTarget", objc.GetClass("NSObject"), protocols, nil, []objc.MethodDef{+ {Cmd: sel("itemClicked:"), Fn: itemClicked},+ {Cmd: sel("menuWillOpen:"), Fn: menuWillOpen},+ {Cmd: sel("runQueued:"), Fn: runQueued},+ })+ if err != nil {+ panic(err)+ }+ target = objc.ID(class).Send(sel("alloc")).Send(sel("init"))++ // The app delegate answers "reopen": macOS sends it to the running app+ // instead of starting a second copy when the user opens the app again.+ var appProtocols []*objc.Protocol+ if p := objc.GetProtocol("NSApplicationDelegate"); p != nil {+ appProtocols = append(appProtocols, p)+ }+ delegateClass, err := objc.RegisterClass("WBCompanionAppDelegate", objc.GetClass("NSObject"), appProtocols, nil, []objc.MethodDef{+ {Cmd: sel("applicationShouldHandleReopen:hasVisibleWindows:"), Fn: shouldHandleReopen},+ })+ if err != nil {+ panic(err)+ }+ appDelegate = objc.ID(delegateClass).Send(sel("alloc")).Send(sel("init"))++ app = cls("NSApplication").Send(sel("sharedApplication"))+ app.Send(sel("setActivationPolicy:"), int64(1)) // accessory: no Dock icon+ app.Send(sel("setDelegate:"), appDelegate)++ statusItem = cls("NSStatusBar").Send(sel("systemStatusBar")).Send(sel("statusItemWithLength:"), float64(-1))+ statusItem.Send(sel("retain"))+ // New status items go to the far left of the others, which on a notched+ // MacBook with a busy menu bar means behind the notch. Until the user+ // places the icon themselves (Command-drag, remembered under the autosave+ // name), ask for a spot just left of the system items, where it fits.+ const autosave = "one.webbrain.companion"+ defaults := cls("NSUserDefaults").Send(sel("standardUserDefaults"))+ posKey := nsString("NSStatusItem Preferred Position " + autosave)+ if defaults.Send(sel("objectForKey:"), posKey) == 0 {+ defaults.Send(sel("setDouble:forKey:"), float64(460), posKey)+ }+ statusItem.Send(sel("setAutosaveName:"), nsString(autosave))+ button := statusItem.Send(sel("button"))+ if img := nsImage(opts.Icon.Template); img != 0 {+ img.Send(sel("setTemplate:"), true)+ size := objc.Send[nsSize](img, sel("size"))+ if size.W > 22 || size.H > 22 || size.W == 0 {+ img.Send(sel("setSize:"), nsSize{18, 18})+ }+ button.Send(sel("setImage:"), img)+ } else {+ button.Send(sel("setTitle:"), nsString("WB"))+ }+ button.Send(sel("setToolTip:"), nsString(opts.Tooltip))++ menu = cls("NSMenu").Send(sel("alloc")).Send(sel("initWithTitle:"), nsString("WebBrain Companion"))+ menu.Send(sel("setAutoenablesItems:"), false)+ menu.Send(sel("setDelegate:"), target)+ statusItem.Send(sel("setMenu:"), menu)+ rebuild()++ pool.Send(sel("drain"))+ if opts.OnReady != nil {+ go opts.OnReady()+ }+ go watchVisibility()+ app.Send(sel("run"))+}++func shouldHandleReopen(self objc.ID, _cmd objc.SEL, sender objc.ID, hasVisibleWindows bool) bool {+ if onTap != nil {+ go onTap()+ }+ return false+}++// watchVisibility asks AppKit whether the status item's window is on screen.+func watchVisibility() {+ for _, wait := range []time.Duration{2500 * time.Millisecond, 8 * time.Second} {+ time.Sleep(wait)+ onMain(checkVisibility)+ }+ for {+ time.Sleep(time.Minute)+ onMain(checkVisibility)+ }+}++func checkVisibility() {+ if statusItem == 0 {+ return+ }+ win := statusItem.Send(sel("button")).Send(sel("window"))+ visible := false+ if win != 0 {+ const occlusionVisible = 1 << 1 // NSWindowOcclusionStateVisible+ visible = objc.Send[uint64](win, sel("occlusionState"))&occlusionVisible != 0+ }+ was := hidden.Swap(!visible)+ if !loggedVis.Swap(true) || was == visible {+ logx.Printf("menu bar icon visible: %v", visible)+ logStatusItem()+ }+}++// logStatusItem records where AppKit put the icon, for support: a busy menu+// bar on a notched MacBook can leave it under the notch while its window+// still counts as visible.+func logStatusItem() {+ button := statusItem.Send(sel("button"))+ win := button.Send(sel("window"))+ var screen objc.ID+ if win != 0 {+ screen = win.Send(sel("screen"))+ }+ logx.Printf("status item: length=%s visible=%s button=%s window=%s screen=%s notch-left=%s notch-right=%s image=%s",+ kv(statusItem, "length"), kv(statusItem, "visible"), kv(button, "frame"), kv(win, "frame"),+ kv(screen, "frame"), kv(screen, "auxiliaryTopLeftArea"), kv(screen, "auxiliaryTopRightArea"),+ kv(button.Send(sel("image")), "size"))+}++// kv is [[obj valueForKey:key] description], safe for struct properties.+func kv(obj objc.ID, key string) string {+ if obj == 0 {+ return "nil"+ }+ if !objc.Send[bool](obj, sel("respondsToSelector:"), sel(key)) {+ return "n/a"+ }+ v := obj.Send(sel("valueForKey:"), nsString(key))+ if v == 0 {+ return "nil"+ }+ return goString(objc.Send[*byte](v.Send(sel("description")), sel("UTF8String")))+}++func goString(p *byte) string {+ if p == nil {+ return ""+ }+ var b []byte+ for i := 0; i < 512; i++ {+ c := *(*byte)(unsafe.Add(unsafe.Pointer(p), i))+ if c == 0 {+ break+ }+ b = append(b, c)+ }+ return string(b)+}++func nsImage(png []byte) objc.ID {+ if len(png) == 0 {+ return 0+ }+ data := cls("NSData").Send(sel("dataWithBytes:length:"), png, uint64(len(png)))+ img := cls("NSImage").Send(sel("alloc")).Send(sel("initWithData:"), data)+ runtime.KeepAlive(png)+ return img+}++// onMain runs fn on the main thread (asynchronously).+func onMain(fn func()) {+ queueMu.Lock()+ queue = append(queue, fn)+ queueMu.Unlock()+ if target != 0 {+ target.Send(sel("performSelectorOnMainThread:withObject:waitUntilDone:"), sel("runQueued:"), objc.ID(0), false)+ }+}++func runQueued(self objc.ID, _cmd objc.SEL, _ objc.ID) {+ queueMu.Lock()+ q := queue+ queue = nil+ queueMu.Unlock()+ for _, fn := range q {+ fn()+ }+}++func itemClicked(self objc.ID, _cmd objc.SEL, sender objc.ID) {+ tag := objc.Send[int](sender, sel("tag"))+ handlersMu.Lock()+ fn := handlers[tag]+ handlersMu.Unlock()+ if fn != nil {+ go fn()+ }+}++func menuWillOpen(self objc.ID, _cmd objc.SEL, m objc.ID) {+ if m == menu {+ rebuild()+ }+}++// Refresh rebuilds the menu (main thread).+func Refresh() { onMain(rebuild) }++// SetTooltip updates the hover text.+func SetTooltip(s string) {+ onMain(func() {+ if statusItem != 0 {+ statusItem.Send(sel("button")).Send(sel("setToolTip:"), nsString(s))+ }+ })+}++// Quit runs OnExit and terminates the app.+func Quit() {+ if opts.OnExit != nil {+ opts.OnExit()+ }+ onMain(func() { app.Send(sel("terminate:"), objc.ID(0)) })+}++var nextTag = 1++func rebuild() {+ if opts.Menu == nil || menu == 0 {+ return+ }+ items := opts.Menu()+ pool := cls("NSAutoreleasePool").Send(sel("alloc")).Send(sel("init"))+ defer pool.Send(sel("drain"))+ handlersMu.Lock()+ handlers = map[int]func(){}+ handlersMu.Unlock()+ nextTag = 1+ menu.Send(sel("removeAllItems"))+ fill(menu, items)+}++func fill(m objc.ID, items []Item) {+ for _, it := range items {+ if it.Separator {+ m.Send(sel("addItem:"), cls("NSMenuItem").Send(sel("separatorItem")))+ continue+ }+ mi := cls("NSMenuItem").Send(sel("alloc")).Send(sel("initWithTitle:action:keyEquivalent:"),+ nsString(it.Title), sel("itemClicked:"), nsString(""))+ mi.Send(sel("setTarget:"), target)+ if it.Tooltip != "" {+ mi.Send(sel("setToolTip:"), nsString(it.Tooltip))+ }+ if it.Checked {+ mi.Send(sel("setState:"), int64(1))+ }+ if it.OnClick != nil {+ tag := nextTag+ nextTag+++ mi.Send(sel("setTag:"), int64(tag))+ handlersMu.Lock()+ handlers[tag] = it.OnClick+ handlersMu.Unlock()+ }+ enabled := !it.Disabled && (it.OnClick != nil || len(it.Children) > 0)+ if it.Secondary && it.OnClick == nil && len(it.Children) == 0 {+ // Informational rows: keep them readable instead of greyed out.+ enabled = true+ mi.Send(sel("setAction:"), objc.SEL(0))+ mi.Send(sel("setAttributedTitle:"), secondaryTitle(it.Title))+ }+ mi.Send(sel("setEnabled:"), enabled)+ if len(it.Children) > 0 {+ sub := cls("NSMenu").Send(sel("alloc")).Send(sel("initWithTitle:"), nsString(it.Title))+ sub.Send(sel("setAutoenablesItems:"), false)+ fill(sub, it.Children)+ mi.Send(sel("setSubmenu:"), sub)+ sub.Send(sel("release"))+ }+ m.Send(sel("addItem:"), mi)+ mi.Send(sel("release"))+ }+}++// secondaryTitle renders text in the system's secondary label colour with+// monospaced digits, so quota rows line up and read as detail.+func secondaryTitle(s string) objc.ID {+ font := cls("NSFont").Send(sel("monospacedDigitSystemFontOfSize:weight:"), float64(13), float64(0))+ color := cls("NSColor").Send(sel("secondaryLabelColor"))+ keys := []objc.ID{nsString("NSFont"), nsString("NSColor")}+ vals := []objc.ID{font, color}+ dict := cls("NSDictionary").Send(sel("dictionaryWithObjects:forKeys:count:"), vals, keys, uint64(2))+ str := cls("NSAttributedString").Send(sel("alloc")).Send(sel("initWithString:attributes:"), nsString(s), dict)+ runtime.KeepAlive(keys)+ runtime.KeepAlive(vals)+ return str.Send(sel("autorelease"))+}diff --git a/webbrain-systray/internal/tray/tray_fyne.go b/webbrain-systray/internal/tray/tray_fyne.gonew file mode 100644index 000000000..b635abbda--- /dev/null+++ b/webbrain-systray/internal/tray/tray_fyne.go@@ -0,0 +1,182 @@+//go:build !darwin++package tray++import (+ "runtime"+ "sync"+ "time"++ "fyne.io/systray"+)++var (+ opts Options+ refreshCh = make(chan struct{}, 1)+ buildMu sync.Mutex+ stopClick chan struct{}+ lastSig string+ onTap func()+)++// SetOnTap sets the action for a primary click on the icon (open the panel);+// the menu stays on the secondary click.+func SetOnTap(fn func()) { onTap = fn }++// Run blocks running the platform event loop. Call it from main.+func Run(o Options) {+ opts = o+ systray.Run(onReady, func() {+ if opts.OnExit != nil {+ opts.OnExit()+ }+ })+}++func onReady() {+ if runtime.GOOS == "windows" {+ systray.SetIcon(opts.Icon.ICO)+ } else {+ systray.SetIcon(opts.Icon.PNG)+ systray.SetTitle("WebBrain")+ }+ systray.SetTooltip(opts.Tooltip)+ if onTap != nil {+ systray.SetOnTapped(func() { go onTap() })+ }+ build(true)+ go loop()+ if opts.OnReady != nil {+ go opts.OnReady()+ }+}++// Hidden reports whether the icon is known to be invisible (macOS only).+func Hidden() bool { return false }++// Refresh rebuilds the menu from Options.Menu.+func Refresh() {+ select {+ case refreshCh <- struct{}{}:+ default:+ }+}++// SetTooltip updates the hover text.+func SetTooltip(s string) { systray.SetTooltip(s) }++// Quit ends Run.+func Quit() { systray.Quit() }++func loop() {+ tick := time.NewTicker(60 * time.Second) // keep "resets in …" texts fresh+ defer tick.Stop()+ for {+ select {+ case <-refreshCh:+ time.Sleep(150 * time.Millisecond) // coalesce bursts+ select {+ case <-refreshCh:+ default:+ }+ build(false)+ case <-tick.C:+ build(false)+ case <-systray.TrayOpenedCh:+ build(false)+ }+ }+}++// signature detects whether anything visible changed, to avoid rebuilding a+// menu the user may have open.+func signature(items []Item) string {+ var b []byte+ var walk func([]Item)+ walk = func(list []Item) {+ for _, it := range list {+ b = append(b, it.Title...)+ b = append(b, '|')+ if it.Disabled {+ b = append(b, 'd')+ }+ if it.Checked {+ b = append(b, 'c')+ }+ if it.Separator {+ b = append(b, '-')+ }+ if len(it.Children) > 0 {+ b = append(b, '[')+ walk(it.Children)+ b = append(b, ']')+ }+ b = append(b, '\n')+ }+ }+ walk(items)+ return string(b)+}++func build(force bool) {+ if opts.Menu == nil {+ return+ }+ items := opts.Menu()+ buildMu.Lock()+ defer buildMu.Unlock()+ sig := signature(items)+ if !force && sig == lastSig {+ return+ }+ lastSig = sig+ if stopClick != nil {+ close(stopClick)+ }+ stopClick = make(chan struct{})+ systray.ResetMenu()+ add(nil, items, stopClick)+}++func add(parent *systray.MenuItem, items []Item, stop chan struct{}) {+ for _, it := range items {+ if it.Separator {+ if parent == nil {+ systray.AddSeparator()+ } else {+ parent.AddSeparator()+ }+ continue+ }+ var mi *systray.MenuItem+ checkable := it.Checked+ switch {+ case parent == nil && checkable:+ mi = systray.AddMenuItemCheckbox(it.Title, it.Tooltip, true)+ case parent == nil:+ mi = systray.AddMenuItem(it.Title, it.Tooltip)+ case checkable:+ mi = parent.AddSubMenuItemCheckbox(it.Title, it.Tooltip, true)+ default:+ mi = parent.AddSubMenuItem(it.Title, it.Tooltip)+ }+ if it.Disabled {+ mi.Disable()+ }+ if len(it.Children) > 0 {+ add(mi, it.Children, stop)+ }+ if it.OnClick != nil {+ go func(ch chan struct{}, fn func()) {+ for {+ select {+ case <-ch:+ go fn()+ case <-stop:+ return+ }+ }+ }(mi.ClickedCh, it.OnClick)+ }+ }+}diff --git a/webbrain-systray/main.go b/webbrain-systray/main.gonew file mode 100644index 000000000..9cfa562fe--- /dev/null+++ b/webbrain-systray/main.go@@ -0,0 +1,172 @@+// WebBrain Companion: a small tray app that exposes your AI subscriptions as+// OpenAI / Anthropic / Gemini compatible endpoints on 127.0.0.1 (via an+// embedded CLIProxyAPI), shows their remaining quotas, can run Bonsai 2 27B+// locally, and hosts WebBrain's d1 decision model.+package main++import (+ "encoding/json"+ "flag"+ "fmt"+ "net/http"+ "os"+ "os/signal"+ "path/filepath"+ "strings"+ "sync"+ "syscall"+ "time"++ "github.com/esokullu/webbrain-systray/internal/app"+ "github.com/esokullu/webbrain-systray/internal/icons"+ "github.com/esokullu/webbrain-systray/internal/logx"+ "github.com/esokullu/webbrain-systray/internal/osutil"+ "github.com/esokullu/webbrain-systray/internal/paths"+ "github.com/esokullu/webbrain-systray/internal/settings"+ "github.com/esokullu/webbrain-systray/internal/tray"+)++var version = "0.1.0-dev"++type runtimeInfo struct {+ PID int `json:"pid"`+ Port int `json:"port"`+}++func runtimeFile() string { return filepath.Join(paths.Config(), "companion.runtime.json") }++// existingInstance finds a companion that is already running for this user.+func existingInstance(store *settings.Store) (int, bool) {+ ports := []int{store.Get().Port}+ if data, err := os.ReadFile(runtimeFile()); err == nil {+ var ri runtimeInfo+ if json.Unmarshal(data, &ri) == nil && ri.Port > 0 && ri.Port != ports[0] {+ ports = append([]int{ri.Port}, ports...)+ }+ }+ client := &http.Client{Timeout: 1500 * time.Millisecond}+ for _, p := range ports {+ resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/companion/v1/info", p))+ if err != nil {+ continue+ }+ var info struct {+ App string `json:"app"`+ }+ _ = json.NewDecoder(resp.Body).Decode(&info)+ _ = resp.Body.Close()+ if info.App == "webbrain-companion" {+ return p, true+ }+ }+ return 0, false+}++func isTerminal() bool {+ st, err := os.Stdout.Stat()+ return err == nil && st.Mode()&os.ModeCharDevice != 0+}++func main() {+ headless := flag.Bool("headless", false, "run the proxy and APIs without a tray icon (servers, CI)")+ background := flag.Bool("background", false, "started at login: do not open the panel")+ _ = flag.Bool("panel", false, "open the panel (the default unless --background)")+ showVersion := flag.Bool("version", false, "print the version and exit")+ flag.Parse()+ if *showVersion {+ fmt.Println("WebBrain Companion", version)+ return+ }+ if err := paths.Ensure(); err != nil {+ fmt.Fprintln(os.Stderr, "cannot create data folders:", err)+ os.Exit(1)+ }+ // logx redirects os.Stdout/os.Stderr into the log file when no terminal is+ // attached; keep the originals for the headless banner and fatal errors.+ stdout, stderr := os.Stdout, os.Stderr+ logx.Init(paths.Logs(), isTerminal())+ store, err := settings.Open()+ if err != nil {+ logx.Printf("settings: %v", err)+ fmt.Fprintln(stderr, "cannot read settings:", err)+ os.Exit(1)+ }+ if port, ok := existingInstance(store); ok {+ url := fmt.Sprintf("http://127.0.0.1:%d/companion/#k=%s", port, store.Get().PanelToken)+ if !*background {+ _ = osutil.OpenAppWindow(url, 460, 820)+ }+ logx.Printf("another instance is running on port %d", port)+ return+ }++ a := app.New(version, store)+ writeRuntime := func(port int) {+ data, _ := json.Marshal(runtimeInfo{PID: os.Getpid(), Port: port})+ _ = os.WriteFile(runtimeFile(), data, 0o600)+ }+ a.OnProxyStart = writeRuntime+ startErr := a.Start()+ if startErr != nil {+ logx.Printf("start: %v", startErr)+ } else {+ writeRuntime(a.Proxy.Port())+ }+ open := func(fragment string) {+ if !a.Proxy.Running() {+ _ = osutil.Reveal(logx.Path())+ return+ }+ _ = osutil.OpenAppWindow(a.PanelURL(fragment), 460, 820)+ }+ a.OpenPanel = open+ shutdown := func() {+ a.Shutdown()+ _ = os.Remove(runtimeFile())+ }++ if *headless {+ if startErr != nil {+ fmt.Fprintln(stderr, "start failed:", startErr)+ os.Exit(1)+ }+ fmt.Fprintf(stdout, "WebBrain Companion %s\n OpenAI base URL: %s/v1\n API key: %s\n Panel: %s\n",+ version, a.Proxy.BaseURL(), store.Get().APIKey, a.PanelURL(""))+ sig := make(chan os.Signal, 1)+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM)+ quit := make(chan struct{})+ var once sync.Once+ a.Quit = func() { once.Do(func() { close(quit) }) }+ select {+ case <-sig:+ case <-quit:+ }+ shutdown()+ return+ }++ tray.SetOnTap(func() { open("") })+ a.OnChange = tray.Refresh+ a.Quit = tray.Quit+ tooltip := "WebBrain Companion"+ if startErr != nil {+ tooltip += " — " + strings.SplitN(startErr.Error(), "\n", 2)[0]+ }+ tray.Run(tray.Options{+ Icon: tray.Icon{Template: icons.Template, PNG: icons.PNG, ICO: icons.ICO},+ Tooltip: tooltip,+ Menu: func() []tray.Item {+ return a.Menu(app.MenuActions{OpenPanel: open, Quit: tray.Quit})+ },+ OnReady: func() {+ // Opening the app by hand shows the panel (the icon can be hidden in a+ // full menu bar or the Windows overflow area); starting at login+ // (--background) stays quiet.+ if !*background && startErr == nil {+ time.Sleep(400 * time.Millisecond)+ open("")+ }+ },+ OnExit: shutdown,+ })+}diff --git a/webbrain-systray/packaging/linux/webbrain-companion.desktop b/webbrain-systray/packaging/linux/webbrain-companion.desktopnew file mode 100644index 000000000..017fe869f--- /dev/null+++ b/webbrain-systray/packaging/linux/webbrain-companion.desktop@@ -0,0 +1,9 @@+[Desktop Entry]+Type=Application+Name=WebBrain Companion+Comment=Your AI subscriptions on localhost for WebBrain+Exec=webbrain-companion+Icon=webbrain-companion+Categories=Network;Utility;+Terminal=false+StartupNotify=falsediff --git a/webbrain-systray/packaging/macos/Info.plist b/webbrain-systray/packaging/macos/Info.plistnew file mode 100644index 000000000..5fcb7b9aa--- /dev/null+++ b/webbrain-systray/packaging/macos/Info.plist@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleName</key><string>WebBrain Companion</string>+ <key>CFBundleDisplayName</key><string>WebBrain Companion</string>+ <key>CFBundleIdentifier</key><string>one.webbrain.companion</string>+ <key>CFBundleVersion</key><string>__VERSION__</string>+ <key>CFBundleShortVersionString</key><string>__VERSION__</string>+ <key>CFBundleExecutable</key><string>WebBrain Companion</string>+ <key>CFBundleIconFile</key><string>app</string>+ <key>CFBundlePackageType</key><string>APPL</string>+ <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>+ <key>LSMinimumSystemVersion</key><string>12.0</string>+ <key>LSUIElement</key><true/>+ <key>NSHighResolutionCapable</key><true/>+ <key>NSHumanReadableCopyright</key><string>© 2026 Emre Sokullu. GPL-3.0-or-later.</string>+</dict>+</plist>diff --git a/webbrain-systray/packaging/windows/installer.nsi b/webbrain-systray/packaging/windows/installer.nsinew file mode 100644index 000000000..7ed1e824c--- /dev/null+++ b/webbrain-systray/packaging/windows/installer.nsi@@ -0,0 +1,115 @@+; WebBrain Companion installer (NSIS 3). One setup.exe for x64 and Arm64: it+; installs the build matching the machine, per user (no administrator prompt),+; adds a Start menu entry and an entry in Settings, Apps.+;+; Built by scripts/build.sh:+; makensis -DVERSION=0.1.0 -DNUMVER=0.1.0.0 -DSRC_X64=... -DSRC_ARM64=...+; -DICON=... -DLICENSE=... -DREADME=... -DOUTFILE=... installer.nsi++Unicode True+SetCompressor /SOLID lzma+RequestExecutionLevel user+ManifestDPIAware true++!include "MUI2.nsh"+!include "x64.nsh"+!include "LogicLib.nsh"+!include "FileFunc.nsh"++!define APPNAME "WebBrain Companion"+!define EXE "WebBrainCompanion.exe"+!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\WebBrainCompanion"+!define RUNKEY "Software\Microsoft\Windows\CurrentVersion\Run"++Name "${APPNAME}"+OutFile "${OUTFILE}"+InstallDir "$LOCALAPPDATA\Programs\${APPNAME}"+InstallDirRegKey HKCU "${UNINSTKEY}" "InstallLocation"+BrandingText "${APPNAME} ${VERSION}"++VIProductVersion "${NUMVER}"+VIAddVersionKey /LANG=0 "ProductName" "${APPNAME}"+VIAddVersionKey /LANG=0 "FileDescription" "${APPNAME} Setup"+VIAddVersionKey /LANG=0 "CompanyName" "WebBrain"+VIAddVersionKey /LANG=0 "LegalCopyright" "Copyright 2026 Emre Sokullu"+VIAddVersionKey /LANG=0 "FileVersion" "${VERSION}"+VIAddVersionKey /LANG=0 "ProductVersion" "${VERSION}"++!define MUI_ICON "${ICON}"+!define MUI_UNICON "${ICON}"+!define MUI_ABORTWARNING+!define MUI_FINISHPAGE_RUN "$INSTDIR\${EXE}"+!define MUI_FINISHPAGE_RUN_TEXT "$(OpenApp)"+!define MUI_FINISHPAGE_TEXT "$(FinishText)"++!insertmacro MUI_PAGE_DIRECTORY+!insertmacro MUI_PAGE_INSTFILES+!insertmacro MUI_PAGE_FINISH++!insertmacro MUI_UNPAGE_CONFIRM+!insertmacro MUI_UNPAGE_INSTFILES++; The first language is the fallback; Windows picks Turkish on Turkish systems.+!insertmacro MUI_LANGUAGE "English"+!insertmacro MUI_LANGUAGE "Turkish"++LangString OpenApp ${LANG_ENGLISH} "Open WebBrain Companion"+LangString OpenApp ${LANG_TURKISH} "WebBrain Companion'ı aç"+LangString FinishText ${LANG_ENGLISH} "WebBrain Companion runs in the notification area next to the clock. Windows may tuck its icon under the ^ arrow; drag it onto the taskbar to keep it in view. Open WebBrain Companion from the Start menu any time to see its panel."+LangString FinishText ${LANG_TURKISH} "WebBrain Companion, saatin yanındaki bildirim alanında çalışır. Windows simgesini ^ okunun altına gizleyebilir; görünür kalması için görev çubuğuna sürükle. Panelini görmek için WebBrain Companion'ı istediğin zaman Başlat menüsünden aç."+LangString RemoveData ${LANG_ENGLISH} "Also delete your WebBrain Companion settings, sign-ins and downloaded models?"+LangString RemoveData ${LANG_TURKISH} "WebBrain Companion ayarların, girişlerin ve indirilen modeller de silinsin mi?"++; Stops a running copy (and the local model server it started) so its files+; can be replaced.+!macro CloseRunning+ nsExec::Exec 'taskkill /F /T /IM "${EXE}"'+ Pop $0+ Sleep 600+!macroend++Section "Install"+ SetOutPath "$INSTDIR"+ !insertmacro CloseRunning+ ${If} ${IsNativeARM64}+ File "/oname=${EXE}" "${SRC_ARM64}"+ ${Else}+ File "/oname=${EXE}" "${SRC_X64}"+ ${EndIf}+ File "/oname=LICENSE.txt" "${LICENSE}"+ File "/oname=README.md" "${README}"+ WriteUninstaller "$INSTDIR\Uninstall.exe"++ CreateShortcut "$SMPROGRAMS\${APPNAME}.lnk" "$INSTDIR\${EXE}"++ WriteRegStr HKCU "${UNINSTKEY}" "DisplayName" "${APPNAME}"+ WriteRegStr HKCU "${UNINSTKEY}" "DisplayVersion" "${VERSION}"+ WriteRegStr HKCU "${UNINSTKEY}" "Publisher" "WebBrain"+ WriteRegStr HKCU "${UNINSTKEY}" "DisplayIcon" "$INSTDIR\${EXE}"+ WriteRegStr HKCU "${UNINSTKEY}" "InstallLocation" "$INSTDIR"+ WriteRegStr HKCU "${UNINSTKEY}" "URLInfoAbout" "https://webbrain.one/companion/"+ WriteRegStr HKCU "${UNINSTKEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'+ WriteRegStr HKCU "${UNINSTKEY}" "QuietUninstallString" '"$INSTDIR\Uninstall.exe" /S'+ WriteRegDWORD HKCU "${UNINSTKEY}" "NoModify" 1+ WriteRegDWORD HKCU "${UNINSTKEY}" "NoRepair" 1+ ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2+ IntFmt $0 "0x%08X" $0+ WriteRegDWORD HKCU "${UNINSTKEY}" "EstimatedSize" "$0"+SectionEnd++Section "Uninstall"+ !insertmacro CloseRunning+ Delete "$INSTDIR\${EXE}"+ Delete "$INSTDIR\LICENSE.txt"+ Delete "$INSTDIR\README.md"+ Delete "$INSTDIR\Uninstall.exe"+ RMDir "$INSTDIR"+ Delete "$SMPROGRAMS\${APPNAME}.lnk"+ DeleteRegValue HKCU "${RUNKEY}" "${APPNAME}"+ DeleteRegKey HKCU "${UNINSTKEY}"++ MessageBox MB_YESNO|MB_ICONQUESTION "$(RemoveData)" /SD IDNO IDNO keep+ RMDir /r "$APPDATA\${APPNAME}"+ RMDir /r "$LOCALAPPDATA\${APPNAME}"+ keep:+SectionEnddiff --git a/webbrain-systray/scripts/build.sh b/webbrain-systray/scripts/build.shnew file mode 100755index 000000000..222c94c21--- /dev/null+++ b/webbrain-systray/scripts/build.sh@@ -0,0 +1,100 @@+#!/usr/bin/env bash+# Builds WebBrain Companion for Windows, macOS and Linux from any host+# (everything is pure Go: CGO_ENABLED=0). Packages land in dist/.+#+# VERSION=0.1.0 ./scripts/build.sh+#+# Optional: RCODESIGN=/path/to/rcodesign ad-hoc signs the macOS app bundle+# on Linux (on macOS the system codesign is used instead).+# Optional: SIGN_WINDOWS is a shell command that signs the file "$1" in place+# (Authenticode), run for both executables and the installer, e.g.+# SIGN_WINDOWS='osslsigncode sign -pkcs12 cert.p12 -readpass pass.txt \+# -t http://timestamp.digicert.com -in "$1" -out "$1.signed" && mv "$1.signed" "$1"'+# The Windows installer needs makensis (NSIS 3, apt install nsis).+set -euo pipefail++VERSION="${VERSION:-0.1.0}"+# Windows version resources want four numbers.+NUMVER=$(printf '%s' "$VERSION" | sed -nE 's/^([0-9]+)\.([0-9]+)\.([0-9]+).*/\1.\2.\3.0/p')+NUMVER="${NUMVER:-0.0.0.0}"+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+DIST="$ROOT/dist"+STAGE="$DIST/.stage"+NAME="WebBrain-Companion-$VERSION"+LDFLAGS="-s -w -X main.version=$VERSION"+export CGO_ENABLED=0+cd "$ROOT"++rm -rf "$STAGE"+mkdir -p "$STAGE" "$DIST"++echo "==> Windows resources (icon, manifest, version info)"+go run github.com/tc-hib/[email protected] simply \+ --icon assets/icons/app.ico --manifest gui \+ --product-name "WebBrain Companion" --file-description "WebBrain Companion" \+ --product-version "$NUMVER" --file-version "$NUMVER" \+ --copyright "Copyright 2026 Emre Sokullu" --original-filename "WebBrainCompanion.exe" \+ --arch amd64,arm64 --out rsrc++build() { # goos goarch out [extra ldflags]+ echo "==> $1/$2"+ GOOS="$1" GOARCH="$2" go build -trimpath -ldflags "$LDFLAGS ${4:-}" -o "$3" .+}++sign_windows() {+ if [ -n "${SIGN_WINDOWS:-}" ]; then+ echo " signing $(basename "$1")"+ bash -c "$SIGN_WINDOWS" _ "$1"+ fi+}++mkdir -p "$STAGE/win"+for arch in amd64 arm64; do+ build windows "$arch" "$STAGE/win/WebBrainCompanion-$arch.exe" "-H windowsgui"+ sign_windows "$STAGE/win/WebBrainCompanion-$arch.exe"+done+echo "==> Windows installer"+makensis -V2 -INPUTCHARSET UTF8 \+ -DVERSION="$VERSION" -DNUMVER="$NUMVER" \+ -DSRC_X64="$STAGE/win/WebBrainCompanion-amd64.exe" -DSRC_ARM64="$STAGE/win/WebBrainCompanion-arm64.exe" \+ -DICON="$ROOT/assets/icons/app.ico" -DLICENSE="$ROOT/LICENSE" -DREADME="$ROOT/README.md" \+ -DOUTFILE="$DIST/$NAME-windows-setup.exe" \+ packaging/windows/installer.nsi+sign_windows "$DIST/$NAME-windows-setup.exe"++echo "==> macOS universal app"+mkdir -p "$STAGE/mac"+build darwin arm64 "$STAGE/mac/companion-arm64"+build darwin amd64 "$STAGE/mac/companion-amd64"+APP="$STAGE/mac/WebBrain Companion.app"+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"+go run github.com/randall77/[email protected] "$APP/Contents/MacOS/WebBrain Companion" "$STAGE/mac/companion-arm64" "$STAGE/mac/companion-amd64"+chmod +x "$APP/Contents/MacOS/WebBrain Companion"+sed "s/__VERSION__/$VERSION/g" packaging/macos/Info.plist > "$APP/Contents/Info.plist"+cp assets/icons/app.icns "$APP/Contents/Resources/app.icns"+printf 'APPL????' > "$APP/Contents/PkgInfo"+if command -v codesign >/dev/null 2>&1; then+ codesign --force --deep -s - "$APP"+elif [ -n "${RCODESIGN:-}" ]; then+ "$RCODESIGN" sign "$APP" >/dev/null+else+ echo " (not signed: set RCODESIGN or build on macOS)"+fi+cp README.md LICENSE "$STAGE/mac/"+(cd "$STAGE/mac" && rm -f "$DIST/$NAME-macos-universal.zip" && zip -qry "$DIST/$NAME-macos-universal.zip" "WebBrain Companion.app" README.md LICENSE)++for arch in amd64 arm64; do+ label=$([ "$arch" = amd64 ] && echo x64 || echo arm64)+ dir="$STAGE/linux-$label/webbrain-companion"+ mkdir -p "$dir"+ build linux "$arch" "$dir/webbrain-companion"+ cp packaging/linux/webbrain-companion.desktop "$dir/"+ cp assets/icons/app-256.png "$dir/webbrain-companion.png"+ cp README.md LICENSE "$dir/"+ tar -C "$STAGE/linux-$label" -czf "$DIST/$NAME-linux-$label.tar.gz" webbrain-companion+done++rm -rf "$STAGE"+(cd "$DIST" && sha256sum "$NAME"-*.exe "$NAME"-*.zip "$NAME"-*.tar.gz > "$NAME-SHA256SUMS.txt")+echo "==> done"+ls -lh "$DIST"diff --git a/webbrain-systray/scripts/make_icons.py b/webbrain-systray/scripts/make_icons.pynew file mode 100644index 000000000..16fcbf553--- /dev/null+++ b/webbrain-systray/scripts/make_icons.py@@ -0,0 +1,85 @@+"""Builds every icon the companion ships from WebBrain's logo mark.++ python3 scripts/make_icons.py++Outputs+ internal/icons/tray_template.png macOS menu-bar template (36 px @144 dpi = 18 pt)+ internal/icons/tray.png Linux status icon (colour, 64 px)+ internal/icons/tray.ico Windows notification-area icon+ assets/icons/app.ico Windows executable icon+ assets/icons/app.icns macOS bundle icon+ assets/icons/app-{128,256,512}.png+"""+import struct, zlib, io, os+import numpy as np+from PIL import Image, ImageFilter++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SRC = os.path.join(ROOT, "assets", "icons", "webbrain-logo-mark.png")++logo = Image.open(SRC).convert("RGBA")+a = np.array(logo)+ys, xs = np.where(a[..., 3] > 10)+pad = 24+box = (xs.min() - pad, ys.min() - pad, xs.max() + pad, ys.max() + pad)+w, h = box[2] - box[0], box[3] - box[1]+side = max(w, h)+cx, cy = (box[0] + box[2]) // 2, (box[1] + box[3]) // 2+square = logo.crop((cx - side // 2, cy - side // 2, cx + side // 2, cy + side // 2))++def colour(size):+ return square.resize((size, size), Image.LANCZOS)++def template(size, detailed=False):+ """Menu-bar glyph: the brain silhouette with the "W" cut out.++ The full logo's folds turn to noise at 18 pt, so small sizes use a solid+ silhouette and a bold W; detailed=True keeps the folds for large previews.+ """+ from PIL import ImageDraw+ arr = np.array(square).astype(np.float32)+ rgb, alpha = arr[..., :3], arr[..., 3] / 255.0+ if detailed:+ lum = rgb.mean(axis=2) / 255.0+ ink = np.clip((lum - 0.22) / 0.25, 0, 1) * alpha+ mask = Image.fromarray((ink * 255).astype(np.uint8))+ else:+ sil = Image.fromarray(((alpha > 0.5) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(6))+ sil = sil.point(lambda v: 255 if v > 127 else 0)+ n = sil.size[0]+ d = ImageDraw.Draw(sil)+ # W geometry, relative to the square crop of the logo.+ pts = [(0.255, 0.38), (0.385, 0.66), (0.5, 0.47), (0.615, 0.66), (0.745, 0.38)]+ pts = [(x * n, y * n) for x, y in pts]+ d.line(pts, fill=0, width=int(n * 0.095), joint="curve")+ for x, y in (pts[0], pts[-1]):+ r = n * 0.0475+ d.ellipse((x - r, y - r, x + r, y + r), fill=0)+ mask = sil+ mask = mask.resize((size, size), Image.LANCZOS)+ out = Image.new("RGBA", (size, size), (0, 0, 0, 0))+ out.putalpha(mask)+ return out++def png_with_dpi(img, dpi):+ buf = io.BytesIO()+ img.save(buf, "PNG", dpi=(dpi, dpi))+ return buf.getvalue()++icons = os.path.join(ROOT, "internal", "icons")+os.makedirs(icons, exist_ok=True)+with open(os.path.join(icons, "tray_template.png"), "wb") as f:+ f.write(png_with_dpi(template(36), 144))+colour(64).save(os.path.join(icons, "tray.png"))+tray_sizes = [16, 20, 24, 32, 40, 48, 64]+colour(256).save(os.path.join(icons, "tray.ico"), sizes=[(s, s) for s in tray_sizes], bitmap_format="bmp")++assets = os.path.join(ROOT, "assets", "icons")+app = colour(1024)+app.save(os.path.join(assets, "app.ico"), sizes=[(s, s) for s in [16, 20, 24, 32, 40, 48, 64, 128, 256]])+app.save(os.path.join(assets, "app.icns"))+for s in (128, 256, 512):+ colour(s).save(os.path.join(assets, f"app-{s}.png"))+template(256).save(os.path.join(assets, "template-preview-256.png"))+template(256, detailed=True).save(os.path.join(assets, "template-detailed-256.png"))+print("icons written")diff --git a/webbrain-systray/tools/d1check/main.go b/webbrain-systray/tools/d1check/main.gonew file mode 100644index 000000000..93eaf0efa--- /dev/null+++ b/webbrain-systray/tools/d1check/main.go@@ -0,0 +1,85 @@+// d1check runs parity cases through the Go decision-model port.+//+// go run ./tools/d1check -model DIR -ort LIB -cases cases.json -out go.json+// go run ./tools/d1check -tokenizer DIR/tokenizer.json -texts texts.json -out ids.json+package main++import (+ "context"+ "encoding/json"+ "flag"+ "fmt"+ "os"+ "time"++ "github.com/esokullu/webbrain-systray/internal/d1"+)++func main() {+ model := flag.String("model", "", "model directory")+ ort := flag.String("ort", "", "ONNX Runtime shared library")+ cases := flag.String("cases", "", "JSON array of requests")+ tok := flag.String("tokenizer", "", "tokenizer.json (tokenizer-only mode)")+ texts := flag.String("texts", "", "JSON array of strings to tokenize")+ encodeOnly := flag.Bool("encode", false, "only print encoded rows")+ out := flag.String("out", "", "output file")+ threads := flag.Int("threads", 0, "intra-op threads")+ flag.Parse()++ if *tok != "" {+ t, err := d1.LoadTokenizer(*tok)+ if err != nil {+ panic(err)+ }+ var list []string+ data, _ := os.ReadFile(*texts)+ if err := json.Unmarshal(data, &list); err != nil {+ panic(err)+ }+ res := make([][]int, len(list))+ start := time.Now()+ for i, s := range list {+ res[i] = t.Encode(s)+ }+ fmt.Fprintf(os.Stderr, "tokenized %d texts in %v\n", len(list), time.Since(start))+ b, _ := json.Marshal(res)+ _ = os.WriteFile(*out, b, 0o644)+ return+ }++ eng, err := d1.OpenEngine(*model, *ort, *threads)+ if err != nil {+ panic(err)+ }+ defer eng.Close()+ data, err := os.ReadFile(*cases)+ if err != nil {+ panic(err)+ }+ var list []json.RawMessage+ if err := json.Unmarshal(data, &list); err != nil {+ panic(err)+ }+ var results []any+ for i, c := range list {+ start := time.Now()+ if *encodeOnly {+ ids, markers, err := eng.Encode(c)+ if err != nil {+ results = append(results, map[string]any{"ok": false, "error": err.Error()})+ continue+ }+ results = append(results, map[string]any{"ok": true, "ids": ids, "markers": markers})+ continue+ }+ res, err := eng.EvaluateJSON(context.Background(), c)+ if err != nil {+ results = append(results, map[string]any{"ok": false, "error": err.Error()})+ } else {+ results = append(results, map[string]any{"ok": true, "result": res})+ }+ fmt.Fprintf(os.Stderr, "case %d: %v\n", i, time.Since(start))+ }+ b, _ := json.MarshalIndent(results, "", " ")+ _ = os.WriteFile(*out, b, 0o644)+}diff --git a/webbrain-systray/web/README.md b/webbrain-systray/web/README.mdnew file mode 100644index 000000000..9e89c34e4--- /dev/null+++ b/webbrain-systray/web/README.md@@ -0,0 +1,36 @@+# WebBrain Companion site++A one-page site in English (`index.html`) and Turkish (`tr/index.html`). Both+pages are generated from one template so they keep the same structure:++```bash+python3 web/build.py # writes web/index.html and web/tr/index.html+python3 -m http.server 8765 --directory web+```++Everything is static: `assets/site.css`, `assets/site.js` (picks the visitor's+system for the download button and the tray illustration), the panel's own+typeface (Bricolage Grotesque, SIL OFL 1.1) and the images in `assets/img`.++## Images++The site never shows a real desktop.++- **Tray menu** (hero): drawn in HTML from the app's actual menu strings, on a+ plain plum field with one status bar. The *macOS / Windows / Linux* switch+ restyles it the way each system draws the menu.+- **Panel windows**: screenshots of the companion's panel only, taken with sample+ data (`WBC_DEMO=1`, accounts like `[email protected]`) by `tools/shots.py`: the+ main page, adding a subscription and the Bonsai 2 27B details, in English and+ Turkish, light and dark. Pages pick the dark set with `prefers-color-scheme`.+- **Social card** (`assets/img/og.png`): rendered from the hero by `tools/og.py`.++## Before publishing++- `SITE` in `build.py` is the public address used for canonical and social+ links (`https://webbrain.one/companion` by default).+- Download links point at the GitHub release `v0.1.2` of+ `esokullu/webbrain-systray`; the CI workflow drafts that release when the tag+ is pushed. While the repository is private those links only work for people+ with access. Update `VERSION` and the file sizes in `build.py` for new+ releases.diff --git a/webbrain-systray/web/assets/fonts/OFL-BricolageGrotesque.txt b/webbrain-systray/web/assets/fonts/OFL-BricolageGrotesque.txtnew file mode 100644index 000000000..49135ef7a--- /dev/null+++ b/webbrain-systray/web/assets/fonts/OFL-BricolageGrotesque.txt@@ -0,0 +1,93 @@+Copyright 2022 The Bricolage Grotesque Project Authors (https://github.com/ateliertriay/bricolage)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/webbrain-systray/web/assets/fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2 b/webbrain-systray/web/assets/fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2new file mode 100644index 000000000..6e8caa8a6Binary files /dev/null and b/webbrain-systray/web/assets/fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2 differdiff --git a/webbrain-systray/web/assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2 b/webbrain-systray/web/assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2new file mode 100644index 000000000..fcc4eb1ebBinary files /dev/null and b/webbrain-systray/web/assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2 differdiff --git a/webbrain-systray/web/assets/img/add-en-dark.webp b/webbrain-systray/web/assets/img/add-en-dark.webpnew file mode 100644index 000000000..c7acec144Binary files /dev/null and b/webbrain-systray/web/assets/img/add-en-dark.webp differdiff --git a/webbrain-systray/web/assets/img/add-en-light.webp b/webbrain-systray/web/assets/img/add-en-light.webpnew file mode 100644index 000000000..a6e485d2fBinary files /dev/null and b/webbrain-systray/web/assets/img/add-en-light.webp differdiff --git a/webbrain-systray/web/assets/img/add-tr-dark.webp b/webbrain-systray/web/assets/img/add-tr-dark.webpnew file mode 100644index 000000000..ecd94331aBinary files /dev/null and b/webbrain-systray/web/assets/img/add-tr-dark.webp differdiff --git a/webbrain-systray/web/assets/img/add-tr-light.webp b/webbrain-systray/web/assets/img/add-tr-light.webpnew file mode 100644index 000000000..0de760580Binary files /dev/null and b/webbrain-systray/web/assets/img/add-tr-light.webp differdiff --git a/webbrain-systray/web/assets/img/favicon.png b/webbrain-systray/web/assets/img/favicon.pngnew file mode 100644index 000000000..0ae05433cBinary files /dev/null and b/webbrain-systray/web/assets/img/favicon.png differdiff --git a/webbrain-systray/web/assets/img/local-en-dark.webp b/webbrain-systray/web/assets/img/local-en-dark.webpnew file mode 100644index 000000000..c931db615Binary files /dev/null and b/webbrain-systray/web/assets/img/local-en-dark.webp differdiff --git a/webbrain-systray/web/assets/img/local-en-light.webp b/webbrain-systray/web/assets/img/local-en-light.webpnew file mode 100644index 000000000..c4c3adbc6Binary files /dev/null and b/webbrain-systray/web/assets/img/local-en-light.webp differdiff --git a/webbrain-systray/web/assets/img/local-tr-dark.webp b/webbrain-systray/web/assets/img/local-tr-dark.webpnew file mode 100644index 000000000..7538d9a43Binary files /dev/null and b/webbrain-systray/web/assets/img/local-tr-dark.webp differdiff --git a/webbrain-systray/web/assets/img/local-tr-light.webp b/webbrain-systray/web/assets/img/local-tr-light.webpnew file mode 100644index 000000000..f267c8336Binary files /dev/null and b/webbrain-systray/web/assets/img/local-tr-light.webp differdiff --git a/webbrain-systray/web/assets/img/logo-128.png b/webbrain-systray/web/assets/img/logo-128.pngnew file mode 100644index 000000000..e078ac372Binary files /dev/null and b/webbrain-systray/web/assets/img/logo-128.png differdiff --git a/webbrain-systray/web/assets/img/og.png b/webbrain-systray/web/assets/img/og.pngnew file mode 100644index 000000000..d738695b3Binary files /dev/null and b/webbrain-systray/web/assets/img/og.png differdiff --git a/webbrain-systray/web/assets/img/panel-en-dark.webp b/webbrain-systray/web/assets/img/panel-en-dark.webpnew file mode 100644index 000000000..285cb20caBinary files /dev/null and b/webbrain-systray/web/assets/img/panel-en-dark.webp differdiff --git a/webbrain-systray/web/assets/img/panel-en-light.webp b/webbrain-systray/web/assets/img/panel-en-light.webpnew file mode 100644index 000000000..6f08448bcBinary files /dev/null and b/webbrain-systray/web/assets/img/panel-en-light.webp differdiff --git a/webbrain-systray/web/assets/img/panel-tr-dark.webp b/webbrain-systray/web/assets/img/panel-tr-dark.webpnew file mode 100644index 000000000..5b214fe1bBinary files /dev/null and b/webbrain-systray/web/assets/img/panel-tr-dark.webp differdiff --git a/webbrain-systray/web/assets/img/panel-tr-light.webp b/webbrain-systray/web/assets/img/panel-tr-light.webpnew file mode 100644index 000000000..a8a6b2461Binary files /dev/null and b/webbrain-systray/web/assets/img/panel-tr-light.webp differdiff --git a/webbrain-systray/web/assets/img/tray-glyph.png b/webbrain-systray/web/assets/img/tray-glyph.pngnew file mode 100644index 000000000..92111753bBinary files /dev/null and b/webbrain-systray/web/assets/img/tray-glyph.png differdiff --git a/webbrain-systray/web/assets/site.css b/webbrain-systray/web/assets/site.cssnew file mode 100644index 000000000..3ae566369--- /dev/null+++ b/webbrain-systray/web/assets/site.css@@ -0,0 +1,308 @@+/* WebBrain Companion site. Palette and typeface come from the app's own panel+ (the "brain tissue" colors of the WebBrain mark, Bricolage Grotesque). */++@font-face {+ font-family: "Bricolage";+ font-style: normal;+ font-display: swap;+ font-weight: 200 800;+ src: url(fonts/bricolage-grotesque-latin-opsz-normal.woff2) format("woff2-variations");+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: "Bricolage";+ font-style: normal;+ font-display: swap;+ font-weight: 200 800;+ src: url(fonts/bricolage-grotesque-latin-ext-opsz-normal.woff2) format("woff2-variations");+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;+}++:root {+ --paper: #fbf6f8;+ --ink: #2b1426;+ --muted: #6e5064;+ --rose: #c42d62;+ --rose-hover: #a92353;+ --rose-ink: #ffffff;+ --rose-mark: #d9396f;+ --tissue: #f1dbe5;+ --line: #e8d4de;+ --plum: #3d1836;+ --code: #f3e5ec;+ --focus: #8a2d63;+ --window: #ffffff;+ --window-bar: #f6edf1;+ --shadow: 0 1px 0 rgba(61, 24, 54, .04), 0 28px 56px -28px rgba(61, 24, 54, .42);++ /* Tray menu, light appearance (menus follow the system theme, not the wallpaper). */+ --menu-bg: rgba(244, 238, 242, .9);+ --menu-ink: #1d1d1f;+ --menu-dim: #65616a;+ --menu-sep: rgba(0, 0, 0, .1);+ --menu-hi: #2e6bdc;++ --font: "Bricolage", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;+ --mono: ui-monospace, "SF Mono", "Cascadia Mono", Menlo, Consolas, monospace;+ --wrap: 1160px;+ --gutter: clamp(16px, 4vw, 40px);+ color-scheme: light;+}++@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) {+ --paper: #1a0f18;+ --ink: #f7e9f0;+ --muted: #c3a5b7;+ --rose: #ff6fa5;+ --rose-hover: #ff8db8;+ --rose-ink: #2b0c1f;+ --rose-mark: #ff6fa5;+ --tissue: #3a2233;+ --line: #3a2535;+ --plum: #2f1429;+ --code: #261521;+ --focus: #ffb3cf;+ --window: #1a0f18;+ --window-bar: #24151f;+ --shadow: 0 0 0 1px rgba(255, 255, 255, .05), 0 28px 56px -28px rgba(0, 0, 0, .8);+ --menu-bg: rgba(42, 36, 41, .9);+ --menu-ink: #f2f2f2;+ --menu-dim: #a19ca3;+ --menu-sep: rgba(255, 255, 255, .12);+ color-scheme: dark;+ }+}++*, *::before, *::after { box-sizing: border-box; }+html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; }+body {+ margin: 0;+ background: var(--paper);+ color: var(--ink);+ font: 400 17px/1.55 var(--font);+ -webkit-font-smoothing: antialiased;+ text-rendering: optimizeLegibility;+}+img { max-width: 100%; }+a { color: inherit; text-decoration-color: color-mix(in srgb, var(--rose) 70%, transparent); text-decoration-thickness: 1.5px; text-underline-offset: .18em; }+a:hover { text-decoration-color: var(--rose); }+:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; border-radius: 6px; }+code, pre { font-family: var(--mono); }+code { font-size: .88em; background: var(--code); padding: .08em .35em; border-radius: 5px; white-space: nowrap; }+pre code { background: none; padding: 0; font-size: inherit; white-space: pre; }+h1, h2, h3 { font-family: var(--font); margin: 0; text-wrap: balance; }+p { margin: 0 0 1em; }++.wrap { max-width: var(--wrap); margin: 0 auto; padding-inline: var(--gutter); }+.skip { position: absolute; left: -999px; top: 8px; background: var(--ink); color: var(--paper); padding: 8px 14px; border-radius: 8px; z-index: 10; }+.skip:focus { left: 8px; }+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }++/* Header */+.site-head { display: flex; align-items: center; gap: 28px; height: 72px; }+.brand { display: inline-flex; align-items: center; gap: 10px; font-weight: 700; font-size: 18px; letter-spacing: -.01em; text-decoration: none; }+.brand img { width: 30px; height: 30px; }+.site-nav { display: flex; gap: 24px; margin-left: auto; font-size: 15px; }+.site-nav a, .lang { text-decoration: none; color: var(--muted); }+.site-nav a:hover, .lang:hover { color: var(--ink); }+.lang { font-size: 15px; padding: 6px 12px; border: 1px solid var(--line); border-radius: 999px; }++/* Hero */+.hero { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.02fr); gap: clamp(32px, 5vw, 72px); align-items: center; padding-block: clamp(24px, 4vw, 48px) clamp(64px, 8vw, 104px); }+.hero h1 {+ font-size: clamp(2.5rem, 3.2vw + 1.2rem, 4.2rem);+ font-weight: 760;+ line-height: .98;+ letter-spacing: -.032em;+ margin-bottom: 26px;+}+.lede { font-size: clamp(1.08rem, .4vw + 1rem, 1.25rem); line-height: 1.5; max-width: 34em; color: color-mix(in srgb, var(--ink) 88%, var(--paper)); }+.cta { display: flex; flex-wrap: wrap; align-items: center; gap: 14px 22px; margin-top: 30px; }+.cta-note { font-size: 15px; color: var(--muted); max-width: 22em; }+.button { display: inline-flex; align-items: center; justify-content: center; min-height: 48px; padding: 0 24px; border-radius: 999px; font-weight: 650; font-size: 17px; text-decoration: none; border: 1.5px solid transparent; transition: background-color .15s; }+.button.primary { background: var(--rose); color: var(--rose-ink); }+.button.primary:hover { background: var(--rose-hover); }++/* The symbolic desktop: a plain plum field with one status bar and the real menu. */+.desk-wrap { margin: 0; }+.desk {+ position: relative;+ height: 460px;+ border-radius: 22px;+ background: var(--plum);+ overflow: hidden;+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .06);+}+.desk .bar { position: absolute; left: 0; right: 0; display: flex; align-items: center; justify-content: flex-end; gap: 14px; padding: 0 14px; color: #fff; }+.desk .bar .s { display: block; background: currentColor; opacity: .5; }+.desk .bar .s1 { width: 15px; height: 9px; border-radius: 3px; }+.desk .bar .s2 { width: 11px; height: 11px; border-radius: 50%; }+.desk .bar .s3 { width: 30px; height: 7px; border-radius: 4px; }+.desk .icon { display: grid; place-items: center; padding: 3px 7px; border-radius: 5px; background: rgba(255, 255, 255, .24); }+.desk .glyph { width: 18px; height: 18px; background: currentColor; -webkit-mask: url(img/tray-glyph.png) center / contain no-repeat; mask: url(img/tray-glyph.png) center / contain no-repeat; }++.menu {+ position: absolute;+ right: 14px;+ width: min(380px, calc(100% - 28px));+ padding: 5px;+ background: var(--menu-bg);+ color: var(--menu-ink);+ -webkit-backdrop-filter: blur(24px) saturate(1.5);+ backdrop-filter: blur(24px) saturate(1.5);+ border-radius: 8px;+ box-shadow: 0 0 0 .5px rgba(0, 0, 0, .35), 0 12px 34px rgba(0, 0, 0, .38);+ font: 13px/1 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif;+ transform-origin: top right;+}+.menu .row { display: flex; align-items: center; gap: 6px; height: 22px; padding: 0 12px 0 24px; border-radius: 4px; white-space: nowrap; position: relative; }+.menu .row > span:first-child { overflow: hidden; text-overflow: ellipsis; }+.menu .dim { color: var(--menu-dim); }+.menu .sep { height: 1px; margin: 5px 12px; background: var(--menu-sep); }+/* One line per plan, spaced the way the app writes it: name, bar, percent. */+.menu .plan { gap: .7em; }+.menu .plan > span:first-child { flex: none; }+.meter { display: inline-flex; gap: 2px; }+.meter i { width: 6px; height: 9px; border: 1px solid currentColor; border-radius: 1px; transform: skewX(-16deg); }+.meter i.on { background: currentColor; }+.menu .hl { background: var(--menu-hi); color: #fff; }++/* Windows: taskbar at the bottom, the menu opens upward. */+.desk[data-os="win"] .bar { bottom: 0; height: 46px; background: rgba(28, 22, 28, .82); gap: 16px; padding-right: 18px; }+.desk[data-os="win"] .icon { padding: 7px 8px; border-radius: 6px; background: rgba(255, 255, 255, .12); }+.desk[data-os="win"] .menu { bottom: 54px; right: 18px; border-radius: 8px; padding: 4px; font: 13px/1 "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif; transform-origin: bottom right; }+.desk[data-os="win"] .menu .row { height: 24px; padding-left: 30px; }+.desk[data-os="win"] .meter i, .desk[data-os="linux"] .meter i { transform: none; width: 7px; height: 7px; border-radius: 0; }++/* Linux (GNOME with AppIndicator): black top bar, rounder menu. */+.desk[data-os="linux"] .bar { top: 0; height: 28px; background: #000; }+.desk[data-os="linux"] .icon { border-radius: 999px; padding: 3px 9px; background: rgba(255, 255, 255, .2); }+.desk[data-os="linux"] .menu { top: 34px; right: 10px; border-radius: 12px; padding: 6px; font: 13px/1 Cantarell, "Noto Sans", Ubuntu, system-ui, sans-serif; }+.desk[data-os="linux"] .menu .row { height: 25px; border-radius: 6px; }+.desk[data-os="mac"] .bar { top: 0; height: 30px; background: rgba(255, 255, 255, .13); -webkit-backdrop-filter: blur(20px); backdrop-filter: blur(20px); }+.desk[data-os="mac"] .menu { top: 33px; }++.os-switch { display: none; align-items: center; gap: 10px; margin-top: 14px; font-size: 14px; color: var(--muted); }+.js .os-switch { display: flex; }+.seg { display: inline-flex; padding: 3px; border-radius: 999px; background: var(--tissue); }+.seg button { font: inherit; font-weight: 600; color: var(--muted); background: none; border: 0; padding: 6px 13px; border-radius: 999px; cursor: pointer; }+.seg button[aria-pressed="true"] { background: var(--paper); color: var(--ink); box-shadow: 0 1px 2px rgba(43, 20, 38, .16); }++/* Sections */+.section { padding-block: clamp(56px, 6.5vw, 96px); border-top: 1px solid var(--line); }+.section h2 { font-size: clamp(2rem, 2.2vw + 1.2rem, 3.1rem); font-weight: 730; line-height: 1.02; letter-spacing: -.028em; max-width: 18em; margin-bottom: 22px; }+.section .intro { max-width: 40em; font-size: 1.1rem; color: color-mix(in srgb, var(--ink) 88%, var(--paper)); }+.split { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: clamp(32px, 5vw, 72px); align-items: start; }+.split.even { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }++/* Panel windows */+.windows { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: clamp(18px, 2.4vw, 36px); margin: 48px 0 0; padding: 0; list-style: none; }+.windows figure { margin: 0; }+.window { border-radius: 12px; overflow: hidden; background: var(--window); box-shadow: 0 0 0 1px var(--line), var(--shadow); }+.titlebar { display: flex; align-items: center; gap: 7px; height: 30px; padding: 0 12px; background: var(--window-bar); border-bottom: 1px solid var(--line); font-size: 12px; color: var(--muted); }+.titlebar i { width: 11px; height: 11px; border-radius: 50%; background: color-mix(in srgb, var(--muted) 35%, transparent); }+.titlebar span { flex: 1; text-align: center; margin-right: 47px; }+.window img { display: block; width: 100%; height: auto; aspect-ratio: 460 / 760; }+.windows figcaption { padding: 18px 2px 0; }+.windows h3 { font-size: 1.2rem; font-weight: 680; letter-spacing: -.01em; margin-bottom: 6px; }+.windows figcaption p { color: var(--muted); font-size: 16px; margin: 0; }++/* Local model planner table */+.machines { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 16px; }+.machines caption { text-align: left; font-weight: 680; font-size: 1.2rem; padding-bottom: 14px; letter-spacing: -.01em; }+.machines th { text-align: left; font-size: 14px; font-weight: 600; color: var(--muted); padding: 0 16px 10px 0; border-bottom: 1.5px solid var(--ink); white-space: nowrap; }+.machines td { padding: 15px 16px 15px 0; border-bottom: 1px solid var(--line); vertical-align: top; }+.machines td:first-child { font-weight: 620; width: 30%; }+.machines td:last-child, .machines th:last-child { white-space: nowrap; padding-right: 0; }+.vis { display: inline-flex; align-items: center; gap: .5em; white-space: nowrap; font-weight: 600; }+.vis::before { content: ""; width: .66em; height: .66em; border-radius: 50%; border: 2px solid var(--rose); flex: none; }+.vis.gpu::before { background: var(--rose); }+.vis.off { color: var(--muted); font-weight: 500; }+.vis.off::before { border: 0; height: 2px; border-radius: 1px; background: var(--muted); }+.note { color: var(--muted); font-size: 15px; margin-top: 18px; max-width: 46em; }++/* Code */+.code-label { font-size: 14px; font-weight: 600; color: var(--muted); margin: 0 0 8px; }+pre { margin: 0 0 22px; padding: 18px 20px; background: var(--code); border-radius: 14px; overflow-x: auto; font-size: 13.5px; line-height: 1.6; tab-size: 2; }+pre .k { color: var(--rose); }++/* Connect steps: a real sequence, so numbered */+.steps { list-style: none; counter-reset: step; margin: 40px 0 0; padding: 0; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 28px clamp(20px, 3vw, 40px); }+.steps li { counter-increment: step; padding-top: 16px; border-top: 1.5px solid var(--ink); }+.steps li::before { content: counter(step); display: block; margin-bottom: 12px; font-weight: 760; font-size: 2.2rem; line-height: 1; letter-spacing: -.02em; color: var(--rose); font-variant-numeric: tabular-nums; }+.steps b { font-weight: 650; }+.after-steps { margin-top: 30px; color: var(--muted); }++/* Downloads */+.downloads { margin-top: 36px; border-top: 1.5px solid var(--ink); }+.dl { display: grid; grid-template-columns: minmax(150px, 1fr) minmax(0, 1.3fr) minmax(0, 1.6fr); gap: 16px 32px; padding: 26px 0; border-bottom: 1px solid var(--line); }+.dl h3 { font-size: 1.6rem; font-weight: 730; letter-spacing: -.02em; }+.dl .req { color: var(--muted); font-size: 15px; margin: 4px 0 0; }+.dl .yours { display: none; margin-top: 10px; font-size: 13px; font-weight: 650; color: var(--rose); }+.dl.current .yours { display: block; }+.files { display: grid; gap: 10px; align-content: start; margin: 0; padding: 0; list-style: none; }+.files a { display: flex; justify-content: space-between; gap: 16px; align-items: baseline; padding: 12px 16px; border-radius: 12px; border: 1.5px solid var(--line); text-decoration: none; font-weight: 620; }+.files a:hover { border-color: var(--rose); }+.files small { color: var(--muted); font-weight: 450; font-size: 14px; white-space: nowrap; }+.dl .how { font-size: 15.5px; color: color-mix(in srgb, var(--ink) 82%, var(--paper)); margin: 0; }+.more-links { display: flex; flex-wrap: wrap; gap: 8px 26px; margin-top: 22px; font-size: 15px; }++/* Safety */+.facts { margin: 0; padding-left: 1.15em; }+.facts li { margin: 0 0 .8em; padding-left: .2em; }+.facts li::marker { color: var(--rose); }+.safety h3 { font-size: 1.25rem; font-weight: 680; margin-bottom: 14px; letter-spacing: -.01em; }++/* Footer */+.site-foot { border-top: 1px solid var(--line); padding-block: 36px 56px; font-size: 14.5px; color: var(--muted); }+.site-foot .wrap { display: grid; grid-template-columns: minmax(0, 2fr) auto; gap: 24px 48px; align-items: start; }+.site-foot nav { display: flex; gap: 22px; flex-wrap: wrap; }+.site-foot p { margin: 0; max-width: 46em; }++/* The one orchestrated moment: the menu opens, then the meters fill. */+@media (prefers-reduced-motion: no-preference) {+ .js .desk .menu { animation: menu-open .2s ease-out .35s both; }+ .js .desk[data-os="win"] .menu { animation-name: menu-open-up; }+ @keyframes menu-open { from { opacity: 0; transform: translateY(-4px) scale(.985); } }+ @keyframes menu-open-up { from { opacity: 0; transform: translateY(4px) scale(.985); } }+}+@media (prefers-reduced-motion: reduce) {+ html { scroll-behavior: auto; }+}++/* Narrower screens */+@media (max-width: 1020px) {+ .site-nav { display: none; }+ .lang { margin-left: auto; }+ .hero { grid-template-columns: 1fr; }+ .desk-wrap { max-width: 560px; }+ .split, .split.even { grid-template-columns: minmax(0, 1fr); }+ .steps { grid-template-columns: repeat(2, minmax(0, 1fr)); }+ .dl { grid-template-columns: 1fr 1fr; }+ .dl > div:first-child { grid-column: 1 / -1; }+}+@media (max-width: 760px) {+ body { font-size: 16px; }+ .windows { grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: min(78%, 330px); overflow-x: auto; scroll-snap-type: x mandatory; padding-bottom: 14px; margin-inline: calc(-1 * var(--gutter)); padding-inline: var(--gutter); scroll-padding-inline: var(--gutter); }+ .windows > li { scroll-snap-align: start; }+ .desk { height: 420px; }+ .menu { font-size: 12px; }+ .menu .row { height: 21px; padding-left: 20px; padding-right: 10px; }+ .meter i, .desk[data-os] .meter i { width: 4px; }+ .desk[data-os="win"] .meter i, .desk[data-os="linux"] .meter i { width: 5px; height: 5px; }+ .dl { grid-template-columns: 1fr; }+ .steps { grid-template-columns: 1fr; }+ .desk[data-os] .menu .row { height: 21px; }+ .machines thead { display: none; }+ .machines caption { display: block; }+ .machines, .machines tbody, .machines tr, .machines td { display: block; width: auto; }+ .machines tr { padding: 14px 0; border-bottom: 1px solid var(--line); }+ .machines td { border: 0; padding: 3px 0; }+ .machines td:first-child { width: auto; font-size: 1.05rem; padding-bottom: 6px; }+ .machines td[data-label]::before { content: attr(data-label) ": "; color: var(--muted); font-weight: 500; }+ .site-foot .wrap { grid-template-columns: 1fr; }+}+@media (max-width: 420px) {+ .desk { height: 340px; border-radius: 16px; }+}diff --git a/webbrain-systray/web/assets/site.js b/webbrain-systray/web/assets/site.jsnew file mode 100644index 000000000..d1f0a39d3--- /dev/null+++ b/webbrain-systray/web/assets/site.js@@ -0,0 +1,55 @@+// WebBrain Companion site: picks the visitor's system for the download button+// and the tray illustration, and fills the illustration's usage meters once.+(() => {+ const desk = document.querySelector(".desk");+ const get = document.getElementById("get");+ const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;++ function detectOS() {+ const ua = navigator.userAgent || "";+ const platform = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || "";+ if (/android|iphone|ipad|ipod/i.test(ua)) return "";+ if (/mac/i.test(platform) || /Mac OS X/.test(ua)) return "mac";+ if (/win/i.test(platform) || /Windows/.test(ua)) return "win";+ if (/linux|x11|cros/i.test(platform + " " + ua)) return "linux";+ return "";+ }++ const buttons = document.querySelectorAll(".seg button");+ function showMenuFor(os) {+ if (!desk) return;+ desk.dataset.os = os;+ buttons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.os === os)));+ }+ buttons.forEach((b) => b.addEventListener("click", () => showMenuFor(b.dataset.os)));++ const os = detectOS();+ if (os) {+ showMenuFor(os);+ if (get && get.dataset[os]) {+ get.textContent = get.dataset[os];+ const href = get.dataset[os + "Href"];+ if (href) get.href = href;+ }+ const row = document.querySelector('.dl[data-os="' + os + '"]');+ if (row) row.classList.add("current");+ }++ // The menu opens (CSS), then each meter fills to its value, one after another.+ if (desk && !reduce) {+ const meters = Array.from(desk.querySelectorAll(".meter"));+ const targets = meters.map((m) => m.querySelectorAll("i.on").length);+ meters.forEach((m) => m.querySelectorAll("i").forEach((i) => i.classList.remove("on")));+ const start = performance.now() + 600;+ const step = (now) => {+ let done = true;+ meters.forEach((m, k) => {+ const n = Math.min(targets[k], Math.max(0, Math.floor((now - start - k * 80) / 50)));+ if (n < targets[k]) done = false;+ m.querySelectorAll("i").forEach((i, j) => i.classList.toggle("on", j < n));+ });+ if (!done) requestAnimationFrame(step);+ };+ requestAnimationFrame(step);+ }+})();diff --git a/webbrain-systray/web/build.py b/webbrain-systray/web/build.pynew file mode 100644index 000000000..c33f42a73--- /dev/null+++ b/webbrain-systray/web/build.py@@ -0,0 +1,545 @@+#!/usr/bin/env python3+"""Builds the WebBrain Companion site: web/index.html (English) and+web/tr/index.html (Turkish) from one template, so both pages keep the same+structure. No dependencies: python3 web/build.py++The pages only show the app's own windows (panel screenshots taken with+WBC_DEMO=1 sample data) and a symbolic tray: a plain field with one status bar+and the companion's real menu, never anyone's desktop.+"""+import html+import os+import re++SITE = "https://webbrain.one/companion" # where the pages are published+VERSION = "0.1.2"+RELEASES = "https://github.com/esokullu/webbrain-systray/releases"+SOURCE = "https://github.com/esokullu/webbrain-systray"+DL = f"{RELEASES}/download/v{VERSION}/WebBrain-Companion-{VERSION}-"+FILES = {+ "mac": DL + "macos-universal.zip",+ "win": DL + "windows-setup.exe",+ "linux_x64": DL + "linux-x64.tar.gz",+ "linux_arm64": DL + "linux-arm64.tar.gz",+ "sums": DL + "SHA256SUMS.txt",+}+GUIDE = "https://webbrain.one/docs/easy-cli-proxy/"++# Tray menu content, as the app renders it (internal/app/menu.go, i18n.go): the+# status, the address, one line per plan with its tightest window, the panel.+MENU = {+ "en": {+ "status": "WebBrain Companion — Running",+ "copy": "Copy",+ "plans": [("Claude Max", 64, "2h 13m"), ("ChatGPT Pro", 57, "4d"), ("Google AI Pro", 71, "5d"), ("Grok SuperGrok", 12, "3d")],+ "open": "Open panel…",+ "quit": "Quit WebBrain Companion",+ "pct": "{}%",+ },+ "tr": {+ "status": "WebBrain Companion — Çalışıyor",+ "copy": "Kopyala",+ "plans": [("Claude Max", 64, "2 sa 13 dk"), ("ChatGPT Pro", 57, "4 gün"), ("Google AI Pro", 71, "5 gün"), ("Grok SuperGrok", 12, "3 gün")],+ "open": "Paneli aç…",+ "quit": "WebBrain Companion'dan çık",+ "pct": "%{}",+ },+}++# What the planner (internal/localmodel/plan.go) picks; see plan_test.go.+MACHINES = {+ "en": [+ ("MacBook Air, 8 GB", "Apple GPU with Metal. It needs more memory than the Mac has, so expect swapping.", "off", "8K"),+ ("MacBook Pro, 16 GB", "Apple GPU with Metal", "gpu", "16K"),+ ("Laptop with an RTX 4060 (8 GB) and 16 GB RAM", "CUDA, 57 of 64 layers on the GPU", "cpu", "8K"),+ ("Desktop with an RTX 4090 (24 GB) and 64 GB RAM", "CUDA, all on the GPU", "gpu", "64K"),+ ("Desktop with a Radeon RX 7600 (8 GB) and 32 GB RAM", "Vulkan, 61 of 64 layers on the GPU", "cpu", "8K"),+ ("PC without a graphics card, 16 GB RAM", "CPU", "cpu", "8K"),+ ("PC without a graphics card, 8 GB RAM", "CPU, with little room to spare", "off", "8K"),+ ],+ "tr": [+ ("MacBook Air, 8 GB", "Apple GPU'da Metal. Mac'teki bellekten fazlasını ister, takas (swap) beklenir.", "off", "8K"),+ ("MacBook Pro, 16 GB", "Apple GPU'da Metal", "gpu", "16K"),+ ("RTX 4060 (8 GB) ve 16 GB RAM'li dizüstü", "CUDA, 64 katmanın 57'si GPU'da", "cpu", "8K"),+ ("RTX 4090 (24 GB) ve 64 GB RAM'li masaüstü", "CUDA, tamamı GPU'da", "gpu", "64K"),+ ("Radeon RX 7600 (8 GB) ve 32 GB RAM'li masaüstü", "Vulkan, 64 katmanın 61'i GPU'da", "cpu", "8K"),+ ("Ekran kartı olmayan, 16 GB RAM'li PC", "CPU", "cpu", "8K"),+ ("Ekran kartı olmayan, 8 GB RAM'li PC", "CPU, payı çok az", "off", "8K"),+ ],+}++T = {+ "en": {+ "title": "WebBrain Companion: your AI subscriptions in WebBrain",+ "og_title": "WebBrain Companion",+ "description": "A small tray app for macOS, Windows and Linux that serves your Claude, ChatGPT, Google, Grok and Kimi subscriptions to WebBrain on 127.0.0.1, shows how much of each plan is left, and runs Bonsai 2 27B on your own machine.",+ "skip": "Skip to content",+ "nav_label": "Sections",+ "nav_panel": "The panel",+ "nav_local": "Local model",+ "nav_connect": "Connect",+ "nav_download": "Download",+ "h1": "The AI plans you already pay for, ready for WebBrain",+ "lede": "WebBrain Companion lives in your menu bar or system tray. Sign in to Claude, ChatGPT, Google, Grok or Kimi once, and WebBrain reaches all of them at one address on your computer. The tray shows how much of each plan is left and when it resets.",+ "get": "Download",+ "get_mac": "Download for macOS",+ "get_win": "Download for Windows",+ "get_linux": "Download for Linux",+ "cta_note": f"Version {VERSION} for macOS, Windows and Linux. Free and open source.",+ "desk_label": "Illustration of the Companion's tray menu: running, the address to copy, and how much is left of Claude Max, ChatGPT Pro, Google AI Pro and SuperGrok.",+ "os_label": "Menu on",+ "panel_h": "Everything else happens in one small panel",+ "panel_intro": "Click the icon to open it. One page holds the address for WebBrain, every plan with what's left, and the two local models; click a row for its details, or the gear for settings. It follows your light or dark setting and speaks English and Turkish.",+ "shot1_h": "One page",+ "shot1_p": "The address WebBrain needs, each plan with the limit closest to running out, and the local models with their main button. No API key on this computer.",+ "shot1_alt": "The panel: the address http://127.0.0.1:8327/v1 with a Copy button, usage meters for Claude Max, ChatGPT Pro, Google AI Pro and SuperGrok, and Bonsai 2 27B running next to the d1 decision model.",+ "shot2_h": "Add a subscription",+ "shot2_p": "Sign in on the provider's own page. The login stays on your computer.",+ "shot2_alt": "The add subscription sheet listing Claude, ChatGPT, Google, Grok and Kimi, each with how you sign in.",+ "shot3_h": "Local models",+ "shot3_p": "Click Bonsai 2 27B to see where it runs and whether images fit, and to change its options. d1 opens the same way.",+ "shot3_alt": "The Bonsai 2 27B details over the panel: running on the Apple GPU with image input on, 65,536 tokens of context, and its options.",+ "local_h": "Bonsai 2 27B, sized to your machine",+ "local_p1": "PrismML's Ternary Bonsai 2 27B packs 27 billion parameters into 5.95 GB. The companion installs it with its Q8_0 vision projector and PrismML's build of llama.cpp, or as the MLX pack on Apple Silicon, and lists it next to your subscriptions as <code>bonsai-2-27b</code>.",+ "local_p2": "Before anything downloads, it works out where the model runs and whether image input fits. The vision projector goes on the GPU when about 1 GB of GPU memory is left after the model and its context, on the CPU when only system RAM has room, and stays off otherwise. You can override the choice in the panel.",+ "table_caption": "What the companion picks on typical machines",+ "th_machine": "Machine",+ "th_runs": "Runs on",+ "th_vision": "Image input",+ "th_context": "Context",+ "vis_gpu": "On, GPU",+ "vis_cpu": "On, CPU",+ "vis_off": "Off",+ "tokens": "{} tokens",+ "local_note": "Worked out by the companion's planner from total and free memory; the numbers on your machine at install time decide. On Apple Silicon the MLX pack carries its own vision tower, so images are always on.",+ "d1_h": "WebBrain's decision model, outside the browser",+ "d1_p": "WebBrain's d1 model answers yes/no, choice and score questions about a page and up to four screenshots, such as whether a task is finished. The companion runs it on ONNX Runtime and answers over HTTP, so a browser tab doesn't have to load 1.9 GB. Its Go port returns the same tokens and probabilities as WebBrain's JavaScript adapter.",+ "d1_ask": "Ask",+ "d1_answer": "Answer (273 ms on the CPU runtime)",+ "connect_h": "Connect WebBrain",+ "connect_p": "You do this once. Apps on this computer need no API key.",+ "step1": "Install the companion and open it. Add a subscription in its panel and finish the sign-in in your browser.",+ "step2": "Copy the address, <code>http://127.0.0.1:8327/v1</code>, from the panel or the tray menu.",+ "step3": "In WebBrain, open the <b>Providers</b> page (<b>More…</b> in the side panel's model menu), choose <b>Local OpenAI-compatible Proxy</b> and paste the address in place of the 8317 WebBrain fills in. WebBrain asks for an API key: type anything.",+ "step4": "Click <b>Load models</b>, pick a model, and run <b>Test Connection</b>. Turn on vision only for a model that accepts images.",+ "after_steps": "Any OpenAI, Anthropic or Gemini client on this computer can use the same address. To use it from another device, turn on network access in the panel's settings; that device then needs the API key the panel shows.",+ "download_h": "Download",+ "download_p": f"Version {VERSION}. Each package holds a single program; your settings and logins live in your user folder.",+ "yours": "Your system",+ "mac_req": "macOS 12 or later, Apple Silicon and Intel",+ "mac_file": "Universal app",+ "mac_how": "Move WebBrain Companion to Applications. The build is not notarized by Apple: the first time, allow it in System Settings, Privacy & Security (Open Anyway). On macOS 14 and earlier, Control-click it and choose Open.",+ "win_req": "Windows 10 and 11, x64 and Arm64",+ "win_file": "Installer",+ "win_how": "Run the installer: it installs for your account, without an administrator prompt, and adds WebBrain Companion to the Start menu. Until the installer is code-signed, SmartScreen may say \"Windows protected your PC\": choose More info, then Run anyway.",+ "linux_req": "x64 and Arm64",+ "linux_how": "Unpack and run webbrain-companion. The icon needs a StatusNotifierItem tray: KDE, XFCE, or GNOME with the AppIndicator extension.",+ "sums": "SHA-256 checksums",+ "source": "Source code",+ "all": "All releases",+ "safety_h": "Before you sign in",+ "stays_h": "What stays on your computer",+ "stays": [+ "On this computer no API key is needed: the companion answers only requests from 127.0.0.1 and turns away web pages, so a site you visit can't spend your plans. Browser extensions such as WebBrain and apps on this computer can use it.",+ "Other devices can connect only if you turn on network access in the panel's settings. It then listens on 0.0.0.0, and they need the API key the panel shows.",+ "Logins are stored in your user folder and sent only to the provider they belong to.",+ "There are no analytics. Apart from the providers you sign in to, it only fetches CLIProxyAPI's public model list, and, when you install a model, its files from Hugging Face, GitHub and, for MLX, PyPI.",+ "Prompts sent to a subscription still go to that provider. Only Bonsai 2 27B and d1 run on your machine.",+ ],+ "provider_h": "What your provider decides",+ "provider": [+ "A subscription that works through a proxy is not the same as one the provider allows. Anthropic's consumer terms restrict automated access outside an API key, and Google's Gemini CLI terms say its sign-in may not be used with third-party tools.",+ "Check the terms of your plan and region before you add it. If an account matters to you, a provider API key is the safer route.",+ "Keep network access off on public Wi-Fi, and never forward port 8327 to the internet. The API key is not internet-grade security.",+ ],+ "guide": "Read WebBrain's guide to subscription proxies",+ "foot": "WebBrain Companion is free software under the GPL-3.0-or-later license and embeds CLIProxyAPI. It is not affiliated with Anthropic, OpenAI, Google, xAI, Moonshot AI, Meta or Cognition.",+ "foot_nav": "More",+ },+ "tr": {+ "title": "WebBrain Companion: yapay zekâ aboneliklerin WebBrain'de",+ "og_title": "WebBrain Companion",+ "description": "Claude, ChatGPT, Google, Grok ve Kimi aboneliklerini WebBrain'e 127.0.0.1 üzerinden sunan, her planda ne kadar hakkın kaldığını gösteren ve Bonsai 2 27B'yi kendi bilgisayarında çalıştıran küçük bir tepsi uygulaması. macOS, Windows ve Linux için.",+ "skip": "İçeriğe geç",+ "nav_label": "Bölümler",+ "nav_panel": "Panel",+ "nav_local": "Yerel model",+ "nav_connect": "Bağlantı",+ "nav_download": "İndir",+ "h1": "Zaten ödediğin yapay zekâ aboneliklerini WebBrain'de kullan",+ "lede": "WebBrain Companion menü çubuğunda ya da sistem tepsisinde durur. Claude, ChatGPT, Google, Grok veya Kimi hesabına bir kez giriş yap; WebBrain hepsine bilgisayarındaki tek bir adresten ulaşsın. Tepsi, her planda ne kadar hakkın kaldığını ve ne zaman sıfırlanacağını gösterir.",+ "get": "İndir",+ "get_mac": "macOS için indir",+ "get_win": "Windows için indir",+ "get_linux": "Linux için indir",+ "cta_note": f"Sürüm {VERSION}; macOS, Windows ve Linux için. Ücretsiz ve açık kaynak.",+ "desk_label": "Companion'ın tepsi menüsünün çizimi: çalışıyor, kopyalanacak adres ve Claude Max, ChatGPT Pro, Google AI Pro ile SuperGrok'ta ne kadar hak kaldığı.",+ "os_label": "Menü",+ "panel_h": "Gerisi tek bir küçük panelde",+ "panel_intro": "Paneli simgeye tıklayarak açarsın. Tek sayfada WebBrain'in adresi, her planda kalan hak ve iki yerel model durur; ayrıntılar için bir satıra, ayarlar için dişli simgesine tıkla. Panel açık ya da koyu temana uyar; Türkçe ve İngilizce konuşur.",+ "shot1_h": "Tek sayfa",+ "shot1_p": "WebBrain'in istediği adres, her planın bitmeye en yakın sınırı ve ana düğmeleriyle yerel modeller. Bu bilgisayarda API anahtarı yok.",+ "shot1_alt": "Panel: Kopyala düğmesiyle http://127.0.0.1:8327/v1 adresi; Claude Max, ChatGPT Pro, Google AI Pro ve SuperGrok kullanım göstergeleri; çalışan Bonsai 2 27B ve d1 karar modeli.",+ "shot2_h": "Abonelik ekleme",+ "shot2_p": "Girişi sağlayıcının kendi sayfasında yaparsın. Oturum bilgisi bilgisayarında kalır.",+ "shot2_alt": "Abonelik ekleme penceresi: Claude, ChatGPT, Google, Grok ve Kimi, her birinin giriş yöntemiyle.",+ "shot3_h": "Yerel modeller",+ "shot3_p": "Bonsai 2 27B'ye tıkla: nerede çalıştığını ve görsellerin sığıp sığmadığını görür, seçeneklerini değiştirirsin. d1 de aynı şekilde açılır.",+ "shot3_alt": "Panelin üzerinde Bonsai 2 27B ayrıntıları: Apple GPU'da görsel girdi açık çalışıyor, 65.536 token bağlam ve seçenekleri.",+ "local_h": "Bonsai 2 27B, makinene göre ayarlanır",+ "local_p1": "PrismML'in Ternary Bonsai 2 27B modeli 27 milyar parametreyi 5,95 GB'a sığdırır. Companion onu Q8_0 görsel projektörüyle ve PrismML'in llama.cpp sürümüyle, Apple Silicon'da istersen MLX paketi olarak kurar ve aboneliklerinin yanında <code>bonsai-2-27b</code> adıyla sunar.",+ "local_p2": "Daha hiçbir şey inmeden modelin nerede çalışacağını ve görsel girdinin sığıp sığmayacağını hesaplar. Model ve bağlamı yerleştikten sonra GPU'da yaklaşık 1 GB yer kalıyorsa görsel projektör GPU'ya, yalnızca sistem belleğinde yer varsa CPU'ya gider; ikisi de yoksa kapalı kalır. Bu seçimi panelden değiştirebilirsin.",+ "table_caption": "Tipik makinelerde Companion'ın seçtikleri",+ "th_machine": "Makine",+ "th_runs": "Nerede çalışır",+ "th_vision": "Görsel girdi",+ "th_context": "Bağlam",+ "vis_gpu": "Açık, GPU",+ "vis_cpu": "Açık, CPU",+ "vis_off": "Kapalı",+ "tokens": "{} token",+ "local_note": "Companion'ın planlayıcısı toplam ve boş belleğe bakarak hesaplar; son kararı kurulum anında makinendeki değerler verir. Apple Silicon'da MLX paketi kendi görsel katmanını taşır, görsel girdi her zaman açıktır.",+ "d1_h": "WebBrain'in karar modeli, tarayıcının dışında",+ "d1_p": "WebBrain'in d1 modeli bir sayfa ve en fazla dört ekran görüntüsü hakkında evet/hayır, seçim ve puan sorularını yanıtlar; örneğin bir görevin bitip bitmediğini. Companion modeli ONNX Runtime ile çalıştırır ve HTTP üzerinden yanıtlar; böylece 1,9 GB'lık modeli bir tarayıcı sekmesi yüklemek zorunda kalmaz. Go'ya taşınan sürüm, WebBrain'in JavaScript adaptörüyle aynı token'ları ve olasılıkları verir.",+ "d1_ask": "Soru",+ "d1_answer": "Yanıt (CPU'da 273 ms)",+ "connect_h": "WebBrain'i bağla",+ "connect_p": "Bunu bir kez yaparsın. Bu bilgisayardaki uygulamaların API anahtarına ihtiyacı yok.",+ "step1": "Companion'ı kur ve aç. Panelinden bir abonelik ekle ve girişi tarayıcında tamamla.",+ "step2": "Adresi (<code>http://127.0.0.1:8327/v1</code>) panelden ya da tepsi menüsünden kopyala.",+ "step3": "WebBrain'de <b>Sağlayıcılar</b> sayfasını aç (yan paneldeki model menüsünde <b>Daha fazla…</b>), <b>Local OpenAI-compatible Proxy</b>'yi seç ve adresi WebBrain'in doldurduğu 8317 yerine yapıştır. WebBrain API anahtarı ister: herhangi bir şey yaz.",+ "step4": "<b>Modelleri yükle</b>'ye bas, bir model seç ve <b>Bağlantıyı sına</b>. Görseli yalnızca resim kabul eden bir model için aç.",+ "after_steps": "Bu bilgisayardaki OpenAI, Anthropic ya da Gemini uyumlu her istemci aynı adresi anahtarsız kullanabilir. Başka bir cihazdan kullanmak için panelin ayarlarından ağ erişimini aç; o cihaz panelin gösterdiği API anahtarını kullanmalı.",+ "download_h": "İndir",+ "download_p": f"Sürüm {VERSION}. Her paket tek bir program içerir; ayarların ve girişlerin kullanıcı klasöründe durur.",+ "yours": "Senin sistemin",+ "mac_req": "macOS 12 ve sonrası, Apple Silicon ve Intel",+ "mac_file": "Universal uygulama",+ "mac_how": "WebBrain Companion'ı Uygulamalar klasörüne taşı. Sürüm Apple onayından (notarization) geçmedi: ilk açılışta Sistem Ayarları, Gizlilik ve Güvenlik bölümünden izin ver (Yine de Aç). macOS 14 ve öncesinde Control tuşuyla tıklayıp Aç'ı seçmen yeterli.",+ "win_req": "Windows 10 ve 11, x64 ve Arm64",+ "win_file": "Kurulum dosyası",+ "win_how": "Kurulum dosyasını çalıştır: yönetici izni istemeden senin hesabına kurar ve WebBrain Companion'ı Başlat menüsüne ekler. Kurulum dosyası kod imzalı olana kadar SmartScreen \"Windows bilgisayarınızı korudu\" diyebilir: Ek bilgi'yi, ardından Yine de çalıştır'ı seç.",+ "linux_req": "x64 ve Arm64",+ "linux_how": "Arşivi aç ve webbrain-companion'ı çalıştır. Simge için StatusNotifierItem destekli bir tepsi gerekir: KDE, XFCE ya da AppIndicator eklentili GNOME.",+ "sums": "SHA-256 özetleri",+ "source": "Kaynak kodu",+ "all": "Tüm sürümler",+ "safety_h": "Giriş yapmadan önce",+ "stays_h": "Bilgisayarında kalanlar",+ "stays": [+ "Bu bilgisayarda API anahtarı gerekmez: Companion yalnızca 127.0.0.1'den gelen istekleri yanıtlar ve web sayfalarını geri çevirir; böylece girdiğin bir site planlarını harcayamaz. WebBrain gibi tarayıcı eklentileri ve bu bilgisayardaki uygulamalar onu kullanabilir.",+ "Diğer cihazlar yalnızca panelin ayarlarından ağ erişimini açarsan bağlanabilir. Companion o zaman 0.0.0.0'da dinler ve o cihazlar panelin gösterdiği API anahtarını kullanmalıdır.",+ "Girişler kullanıcı klasöründe saklanır ve yalnızca ait oldukları sağlayıcıya gönderilir.",+ "Analitik yok. Giriş yaptığın sağlayıcılar dışında yalnızca CLIProxyAPI'nin herkese açık model listesini alır; bir model kurduğunda da dosyalarını Hugging Face'ten, GitHub'dan ve MLX için PyPI'dan indirir.",+ "Bir aboneliğe giden istemler yine o sağlayıcıya gider. Bilgisayarında çalışan yalnızca Bonsai 2 27B ve d1'dir.",+ ],+ "provider_h": "Sağlayıcının belirledikleri",+ "provider": [+ "Bir aboneliğin proxy üzerinden çalışması, sağlayıcının buna izin verdiği anlamına gelmez. Anthropic'in tüketici koşulları API anahtarı dışındaki otomatik erişimi kısıtlar; Google'ın Gemini CLI koşulları da bu girişin üçüncü taraf araçlarla kullanılamayacağını söyler.",+ "Eklemeden önce planının ve bölgenin koşullarına bak. Hesabın senin için önemliyse sağlayıcının API anahtarı daha güvenli yoldur.",+ "Herkese açık Wi-Fi'da ağ erişimini kapalı tut ve 8327 portunu asla internete yönlendirme. API anahtarı internete dayanacak bir güvenlik sağlamaz.",+ ],+ "guide": "WebBrain'in abonelik proxy'leri rehberini oku (İngilizce)",+ "foot": "WebBrain Companion, GPL-3.0-or-later lisanslı özgür bir yazılımdır ve CLIProxyAPI'yi içinde barındırır. Anthropic, OpenAI, Google, xAI, Moonshot AI, Meta ya da Cognition ile bağlantılı değildir.",+ "foot_nav": "Bağlantılar",+ },+}++D1_ASK = r"""curl http://127.0.0.1:8327/companion/v1/decide \+ -H "Content-Type: application/json" \+ -d '{"state": "Order #1042 is confirmed.",+ "questions": {"completion": {+ "type": "choice",+ "instructions": "Did the task finish?",+ "criteria": {"completed": "Confirmed",+ "not_completed": "Failed or unfinished",+ "unknown": "Not established"}}}}'"""++D1_ANSWER = """{"answers": {"completion": {+ "choice": "completed",+ "confidence": 0.99997,+ "probabilities": {"completed": 0.99997,+ "not_completed": 0.000002,+ "unknown": 0.000033}}},+ "diagnostics": {"runtime": "onnxruntime 1.31.0 (CPU)", …}}"""++PAGE = r"""<!doctype html>+<html lang="[[lang]]" class="no-js">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>[[title]]</title>+<meta name="description" content="[[description]]">+<meta name="color-scheme" content="light dark">+<meta name="theme-color" content="#fbf6f8" media="(prefers-color-scheme: light)">+<meta name="theme-color" content="#1a0f18" media="(prefers-color-scheme: dark)">+<link rel="canonical" href="[[canonical]]">+<link rel="alternate" hreflang="en" href="[[site]]/">+<link rel="alternate" hreflang="tr" href="[[site]]/tr/">+<link rel="alternate" hreflang="x-default" href="[[site]]/">+<meta property="og:type" content="website">+<meta property="og:site_name" content="WebBrain">+<meta property="og:title" content="[[og_title]]">+<meta property="og:description" content="[[description]]">+<meta property="og:url" content="[[canonical]]">+<meta property="og:image" content="[[site]]/assets/img/og.png">+<meta property="og:image:width" content="1200">+<meta property="og:image:height" content="630">+<meta name="twitter:card" content="summary_large_image">+<link rel="icon" type="image/png" href="[[root]]assets/img/favicon.png">+<link rel="preload" href="[[root]]assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2" as="font" type="font/woff2" crossorigin>+<link rel="stylesheet" href="[[root]]assets/site.css">+<script>document.documentElement.classList.replace("no-js", "js")</script>+<script defer src="[[root]]assets/site.js"></script>+</head>+<body>+<a class="skip" href="#main">[[skip]]</a>+<header class="wrap site-head">+ <a class="brand" href="[[home]]"><img src="[[root]]assets/img/logo-128.png" alt="" width="30" height="30">WebBrain Companion</a>+ <nav class="site-nav" aria-label="[[nav_label]]">+ <a href="#panel">[[nav_panel]]</a>+ <a href="#local">[[nav_local]]</a>+ <a href="#connect">[[nav_connect]]</a>+ <a href="#download">[[nav_download]]</a>+ </nav>+ <a class="lang" href="[[other_href]]" hreflang="[[other_lang]]" lang="[[other_lang]]">[[other_name]]</a>+</header>++<main id="main">+<section class="wrap hero">+ <div>+ <h1>[[h1]]</h1>+ <p class="lede">[[lede]]</p>+ <div class="cta">+ <a class="button primary" id="get" href="#download" data-mac="[[get_mac]]" data-win="[[get_win]]" data-linux="[[get_linux]]" data-mac-href="[[dl_mac]]" data-win-href="[[dl_win]]" data-linux-href="#download">[[get]]</a>+ <span class="cta-note">[[cta_note]]</span>+ </div>+ </div>+ <div class="desk-wrap">+ <div class="desk" data-os="mac" role="img" aria-label="[[desk_label]]">+ <div class="bar" aria-hidden="true"><span class="s s3"></span><span class="s s2"></span><span class="icon"><span class="glyph"></span></span><span class="s s1"></span></div>+ <div class="menu" aria-hidden="true">+[[menu]]+ </div>+ </div>+ <div class="os-switch"><span id="os-label">[[os_label]]</span><span class="seg" role="group" aria-labelledby="os-label"><button type="button" data-os="mac" aria-pressed="true">macOS</button><button type="button" data-os="win" aria-pressed="false">Windows</button><button type="button" data-os="linux" aria-pressed="false">Linux</button></span></div>+ </div>+</section>++<section class="section" id="panel" aria-labelledby="panel-h">+ <div class="wrap">+ <h2 id="panel-h">[[panel_h]]</h2>+ <p class="intro">[[panel_intro]]</p>+ <ul class="windows">+[[windows]]+ </ul>+ </div>+</section>++<section class="section" id="local" aria-labelledby="local-h">+ <div class="wrap">+ <h2 id="local-h">[[local_h]]</h2>+ <div class="split">+ <p class="intro">[[local_p1]]</p>+ <p class="intro">[[local_p2]]</p>+ </div>+ <table class="machines">+ <caption>[[table_caption]]</caption>+ <thead><tr><th scope="col">[[th_machine]]</th><th scope="col">[[th_runs]]</th><th scope="col">[[th_vision]]</th><th scope="col">[[th_context]]</th></tr></thead>+ <tbody>+[[machines]]+ </tbody>+ </table>+ <p class="note">[[local_note]]</p>+ </div>+</section>++<section class="section" id="decision" aria-labelledby="d1-h">+ <div class="wrap">+ <h2 id="d1-h">[[d1_h]]</h2>+ <div class="split">+ <p class="intro">[[d1_p]]</p>+ <div>+ <p class="code-label">[[d1_ask]]</p>+ <pre><code>[[d1_code]]</code></pre>+ <p class="code-label">[[d1_answer]]</p>+ <pre><code>[[d1_result]]</code></pre>+ </div>+ </div>+ </div>+</section>++<section class="section" id="connect" aria-labelledby="connect-h">+ <div class="wrap">+ <h2 id="connect-h">[[connect_h]]</h2>+ <p class="intro">[[connect_p]]</p>+ <ol class="steps">+ <li>[[step1]]</li>+ <li>[[step2]]</li>+ <li>[[step3]]</li>+ <li>[[step4]]</li>+ </ol>+ <p class="after-steps">[[after_steps]]</p>+ </div>+</section>++<section class="section" id="download" aria-labelledby="download-h">+ <div class="wrap">+ <h2 id="download-h">[[download_h]]</h2>+ <p class="intro">[[download_p]]</p>+ <div class="downloads">+ <div class="dl" data-os="mac">+ <div><h3>macOS</h3><p class="req">[[mac_req]]</p><span class="yours">[[yours]]</span></div>+ <ul class="files"><li><a href="[[dl_mac]]">[[mac_file]] <small>zip, 36 MB</small></a></li></ul>+ <p class="how">[[mac_how]]</p>+ </div>+ <div class="dl" data-os="win">+ <div><h3>Windows</h3><p class="req">[[win_req]]</p><span class="yours">[[yours]]</span></div>+ <ul class="files"><li><a href="[[dl_win]]">[[win_file]] <small>setup.exe, 23 MB</small></a></li></ul>+ <p class="how">[[win_how]]</p>+ </div>+ <div class="dl" data-os="linux">+ <div><h3>Linux</h3><p class="req">[[linux_req]]</p><span class="yours">[[yours]]</span></div>+ <ul class="files"><li><a href="[[dl_linux_x64]]">x64 <small>tar.gz, 20 MB</small></a></li><li><a href="[[dl_linux_arm64]]">Arm64 <small>tar.gz, 18 MB</small></a></li></ul>+ <p class="how">[[linux_how]]</p>+ </div>+ </div>+ <p class="more-links"><a href="[[dl_sums]]">[[sums]]</a><a href="[[source]]">[[source_label]]</a><a href="[[releases]]">[[all]]</a></p>+ </div>+</section>++<section class="section safety" id="safety" aria-labelledby="safety-h">+ <div class="wrap">+ <h2 id="safety-h">[[safety_h]]</h2>+ <div class="split even">+ <div>+ <h3>[[stays_h]]</h3>+ <ul class="facts">+[[stays]]+ </ul>+ </div>+ <div>+ <h3>[[provider_h]]</h3>+ <ul class="facts">+[[provider]]+ </ul>+ <p><a href="[[guide_url]]">[[guide]]</a></p>+ </div>+ </div>+ </div>+</section>+</main>++<footer class="site-foot">+ <div class="wrap">+ <p>[[foot]]</p>+ <nav aria-label="[[foot_nav]]"><a href="https://webbrain.one/">WebBrain</a><a href="[[source]]">[[source_label]]</a><a href="[[other_href]]" hreflang="[[other_lang]]" lang="[[other_lang]]">[[other_name]]</a></nav>+ </div>+</footer>+</body>+</html>+"""+++def esc(s):+ return html.escape(s, quote=True)+++def meter(v):+ n = int(v / 10 + 0.5) # same rounding as the tray (math.Round)+ return '<span class="meter">' + '<i class="on"></i>' * n + "<i></i>" * (10 - n) + "</span>"+++def menu_html(lang):+ m = MENU[lang]+ rows = []+ add = rows.append+ add(f'<div class="row dim"><span>{esc(m["status"])}</span></div>')+ add(f'<div class="row"><span>{esc(m["copy"])} http://127.0.0.1:8327/v1</span></div>')+ add('<div class="sep"></div>')+ for name, v, reset in m["plans"]:+ pct = m["pct"].format(v)+ add(f'<div class="row plan"><span>{esc(name)}</span>{meter(v)}<span>{pct} · {esc(reset)}</span></div>')+ add('<div class="sep"></div>')+ add(f'<div class="row"><span>{esc(m["open"])}</span></div>')+ add(f'<div class="row"><span>{esc(m["quit"])}</span></div>')+ return "\n".join(" " + r for r in rows)+++def windows_html(lang, root, t):+ out = []+ for i, shot in enumerate(["panel", "add", "local"], 1):+ out.append(f""" <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="{root}assets/img/{shot}-{lang}-dark.webp" media="(prefers-color-scheme: dark)"><img src="{root}assets/img/{shot}-{lang}-light.webp" width="460" height="760" alt="{esc(t[f'shot{i}_alt'])}" loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>{esc(t[f'shot{i}_h'])}</h3><p>{esc(t[f'shot{i}_p'])}</p></figcaption>+ </figure></li>""")+ return "\n".join(out)+++def machines_html(lang, t):+ out = []+ for name, runs, vis, ctx in MACHINES[lang]:+ out.append(+ f' <tr><td>{esc(name)}</td><td data-label="{esc(t["th_runs"])}">{esc(runs)}</td>'+ f'<td data-label="{esc(t["th_vision"])}"><span class="vis {vis}">{esc(t["vis_" + vis])}</span></td>'+ f'<td data-label="{esc(t["th_context"])}">{esc(t["tokens"].format(ctx))}</td></tr>'+ )+ return "\n".join(out)+++def render(lang):+ t = T[lang]+ root = "" if lang == "en" else "../"+ v = {k: esc(x) for k, x in t.items() if isinstance(x, str)}+ # Strings that carry inline markup (<code>, <b>) are written as HTML on purpose.+ for k in ("local_p1", "step1", "step2", "step3", "step4"):+ v[k] = t[k]+ v.update(+ lang=lang,+ root=root,+ home="./",+ site=SITE,+ canonical=SITE + ("/" if lang == "en" else "/tr/"),+ other_href="tr/" if lang == "en" else "../",+ other_lang="tr" if lang == "en" else "en",+ other_name="Türkçe" if lang == "en" else "English",+ dl_mac=FILES["mac"],+ dl_win=FILES["win"],+ dl_linux_x64=FILES["linux_x64"],+ dl_linux_arm64=FILES["linux_arm64"],+ dl_sums=FILES["sums"],+ releases=RELEASES,+ source=SOURCE,+ source_label=esc(t["source"]),+ guide_url=GUIDE,+ menu=menu_html(lang),+ windows=windows_html(lang, root, t),+ machines=machines_html(lang, t),+ d1_code=esc(D1_ASK),+ d1_result=esc(D1_ANSWER),+ stays="\n".join(f" <li>{esc(s)}</li>" for s in t["stays"]),+ provider="\n".join(f" <li>{esc(s)}</li>" for s in t["provider"]),+ )++ def sub(m):+ key = m.group(1)+ if key not in v:+ raise KeyError(f"{lang}: missing [[{key}]]")+ return v[key]++ return re.sub(r"\[\[(\w+)\]\]", sub, PAGE)+++def main():+ here = os.path.dirname(os.path.abspath(__file__))+ for lang, path in (("en", "index.html"), ("tr", os.path.join("tr", "index.html"))):+ out = os.path.join(here, path)+ os.makedirs(os.path.dirname(out), exist_ok=True)+ with open(out, "w", encoding="utf-8") as f:+ f.write(render(lang))+ print("wrote", os.path.relpath(out, here))+++if __name__ == "__main__":+ main()diff --git a/webbrain-systray/web/index.html b/webbrain-systray/web/index.htmlnew file mode 100644index 000000000..3152dc814--- /dev/null+++ b/webbrain-systray/web/index.html@@ -0,0 +1,224 @@+<!doctype html>+<html lang="en" class="no-js">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>WebBrain Companion: your AI subscriptions in WebBrain</title>+<meta name="description" content="A small tray app for macOS, Windows and Linux that serves your Claude, ChatGPT, Google, Grok and Kimi subscriptions to WebBrain on 127.0.0.1, shows how much of each plan is left, and runs Bonsai 2 27B on your own machine.">+<meta name="color-scheme" content="light dark">+<meta name="theme-color" content="#fbf6f8" media="(prefers-color-scheme: light)">+<meta name="theme-color" content="#1a0f18" media="(prefers-color-scheme: dark)">+<link rel="canonical" href="https://webbrain.one/companion/">+<link rel="alternate" hreflang="en" href="https://webbrain.one/companion/">+<link rel="alternate" hreflang="tr" href="https://webbrain.one/companion/tr/">+<link rel="alternate" hreflang="x-default" href="https://webbrain.one/companion/">+<meta property="og:type" content="website">+<meta property="og:site_name" content="WebBrain">+<meta property="og:title" content="WebBrain Companion">+<meta property="og:description" content="A small tray app for macOS, Windows and Linux that serves your Claude, ChatGPT, Google, Grok and Kimi subscriptions to WebBrain on 127.0.0.1, shows how much of each plan is left, and runs Bonsai 2 27B on your own machine.">+<meta property="og:url" content="https://webbrain.one/companion/">+<meta property="og:image" content="https://webbrain.one/companion/assets/img/og.png">+<meta property="og:image:width" content="1200">+<meta property="og:image:height" content="630">+<meta name="twitter:card" content="summary_large_image">+<link rel="icon" type="image/png" href="assets/img/favicon.png">+<link rel="preload" href="assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2" as="font" type="font/woff2" crossorigin>+<link rel="stylesheet" href="assets/site.css">+<script>document.documentElement.classList.replace("no-js", "js")</script>+<script defer src="assets/site.js"></script>+</head>+<body>+<a class="skip" href="#main">Skip to content</a>+<header class="wrap site-head">+ <a class="brand" href="./"><img src="assets/img/logo-128.png" alt="" width="30" height="30">WebBrain Companion</a>+ <nav class="site-nav" aria-label="Sections">+ <a href="#panel">The panel</a>+ <a href="#local">Local model</a>+ <a href="#connect">Connect</a>+ <a href="#download">Download</a>+ </nav>+ <a class="lang" href="tr/" hreflang="tr" lang="tr">Türkçe</a>+</header>++<main id="main">+<section class="wrap hero">+ <div>+ <h1>The AI plans you already pay for, ready for WebBrain</h1>+ <p class="lede">WebBrain Companion lives in your menu bar or system tray. Sign in to Claude, ChatGPT, Google, Grok or Kimi once, and WebBrain reaches all of them at one address on your computer. The tray shows how much of each plan is left and when it resets.</p>+ <div class="cta">+ <a class="button primary" id="get" href="#download" data-mac="Download for macOS" data-win="Download for Windows" data-linux="Download for Linux" data-mac-href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-macos-universal.zip" data-win-href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-windows-setup.exe" data-linux-href="#download">Download</a>+ <span class="cta-note">Version 0.1.2 for macOS, Windows and Linux. Free and open source.</span>+ </div>+ </div>+ <div class="desk-wrap">+ <div class="desk" data-os="mac" role="img" aria-label="Illustration of the Companion's tray menu: running, the address to copy, and how much is left of Claude Max, ChatGPT Pro, Google AI Pro and SuperGrok.">+ <div class="bar" aria-hidden="true"><span class="s s3"></span><span class="s s2"></span><span class="icon"><span class="glyph"></span></span><span class="s s1"></span></div>+ <div class="menu" aria-hidden="true">+ <div class="row dim"><span>WebBrain Companion — Running</span></div>+ <div class="row"><span>Copy http://127.0.0.1:8327/v1</span></div>+ <div class="sep"></div>+ <div class="row plan"><span>Claude Max</span><span class="meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i></i><i></i><i></i><i></i></span><span>64% · 2h 13m</span></div>+ <div class="row plan"><span>ChatGPT Pro</span><span class="meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i></i><i></i><i></i><i></i></span><span>57% · 4d</span></div>+ <div class="row plan"><span>Google AI Pro</span><span class="meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i></i><i></i><i></i></span><span>71% · 5d</span></div>+ <div class="row plan"><span>Grok SuperGrok</span><span class="meter"><i class="on"></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></span><span>12% · 3d</span></div>+ <div class="sep"></div>+ <div class="row"><span>Open panel…</span></div>+ <div class="row"><span>Quit WebBrain Companion</span></div>+ </div>+ </div>+ <div class="os-switch"><span id="os-label">Menu on</span><span class="seg" role="group" aria-labelledby="os-label"><button type="button" data-os="mac" aria-pressed="true">macOS</button><button type="button" data-os="win" aria-pressed="false">Windows</button><button type="button" data-os="linux" aria-pressed="false">Linux</button></span></div>+ </div>+</section>++<section class="section" id="panel" aria-labelledby="panel-h">+ <div class="wrap">+ <h2 id="panel-h">Everything else happens in one small panel</h2>+ <p class="intro">Click the icon to open it. One page holds the address for WebBrain, every plan with what's left, and the two local models; click a row for its details, or the gear for settings. It follows your light or dark setting and speaks English and Turkish.</p>+ <ul class="windows">+ <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="assets/img/panel-en-dark.webp" media="(prefers-color-scheme: dark)"><img src="assets/img/panel-en-light.webp" width="460" height="760" alt="The panel: the address http://127.0.0.1:8327/v1 with a Copy button, usage meters for Claude Max, ChatGPT Pro, Google AI Pro and SuperGrok, and Bonsai 2 27B running next to the d1 decision model." loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>One page</h3><p>The address WebBrain needs, each plan with the limit closest to running out, and the local models with their main button. No API key on this computer.</p></figcaption>+ </figure></li>+ <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="assets/img/add-en-dark.webp" media="(prefers-color-scheme: dark)"><img src="assets/img/add-en-light.webp" width="460" height="760" alt="The add subscription sheet listing Claude, ChatGPT, Google, Grok and Kimi, each with how you sign in." loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>Add a subscription</h3><p>Sign in on the provider's own page. The login stays on your computer.</p></figcaption>+ </figure></li>+ <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="assets/img/local-en-dark.webp" media="(prefers-color-scheme: dark)"><img src="assets/img/local-en-light.webp" width="460" height="760" alt="The Bonsai 2 27B details over the panel: running on the Apple GPU with image input on, 65,536 tokens of context, and its options." loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>Local models</h3><p>Click Bonsai 2 27B to see where it runs and whether images fit, and to change its options. d1 opens the same way.</p></figcaption>+ </figure></li>+ </ul>+ </div>+</section>++<section class="section" id="local" aria-labelledby="local-h">+ <div class="wrap">+ <h2 id="local-h">Bonsai 2 27B, sized to your machine</h2>+ <div class="split">+ <p class="intro">PrismML's Ternary Bonsai 2 27B packs 27 billion parameters into 5.95 GB. The companion installs it with its Q8_0 vision projector and PrismML's build of llama.cpp, or as the MLX pack on Apple Silicon, and lists it next to your subscriptions as <code>bonsai-2-27b</code>.</p>+ <p class="intro">Before anything downloads, it works out where the model runs and whether image input fits. The vision projector goes on the GPU when about 1 GB of GPU memory is left after the model and its context, on the CPU when only system RAM has room, and stays off otherwise. You can override the choice in the panel.</p>+ </div>+ <table class="machines">+ <caption>What the companion picks on typical machines</caption>+ <thead><tr><th scope="col">Machine</th><th scope="col">Runs on</th><th scope="col">Image input</th><th scope="col">Context</th></tr></thead>+ <tbody>+ <tr><td>MacBook Air, 8 GB</td><td data-label="Runs on">Apple GPU with Metal. It needs more memory than the Mac has, so expect swapping.</td><td data-label="Image input"><span class="vis off">Off</span></td><td data-label="Context">8K tokens</td></tr>+ <tr><td>MacBook Pro, 16 GB</td><td data-label="Runs on">Apple GPU with Metal</td><td data-label="Image input"><span class="vis gpu">On, GPU</span></td><td data-label="Context">16K tokens</td></tr>+ <tr><td>Laptop with an RTX 4060 (8 GB) and 16 GB RAM</td><td data-label="Runs on">CUDA, 57 of 64 layers on the GPU</td><td data-label="Image input"><span class="vis cpu">On, CPU</span></td><td data-label="Context">8K tokens</td></tr>+ <tr><td>Desktop with an RTX 4090 (24 GB) and 64 GB RAM</td><td data-label="Runs on">CUDA, all on the GPU</td><td data-label="Image input"><span class="vis gpu">On, GPU</span></td><td data-label="Context">64K tokens</td></tr>+ <tr><td>Desktop with a Radeon RX 7600 (8 GB) and 32 GB RAM</td><td data-label="Runs on">Vulkan, 61 of 64 layers on the GPU</td><td data-label="Image input"><span class="vis cpu">On, CPU</span></td><td data-label="Context">8K tokens</td></tr>+ <tr><td>PC without a graphics card, 16 GB RAM</td><td data-label="Runs on">CPU</td><td data-label="Image input"><span class="vis cpu">On, CPU</span></td><td data-label="Context">8K tokens</td></tr>+ <tr><td>PC without a graphics card, 8 GB RAM</td><td data-label="Runs on">CPU, with little room to spare</td><td data-label="Image input"><span class="vis off">Off</span></td><td data-label="Context">8K tokens</td></tr>+ </tbody>+ </table>+ <p class="note">Worked out by the companion's planner from total and free memory; the numbers on your machine at install time decide. On Apple Silicon the MLX pack carries its own vision tower, so images are always on.</p>+ </div>+</section>++<section class="section" id="decision" aria-labelledby="d1-h">+ <div class="wrap">+ <h2 id="d1-h">WebBrain's decision model, outside the browser</h2>+ <div class="split">+ <p class="intro">WebBrain's d1 model answers yes/no, choice and score questions about a page and up to four screenshots, such as whether a task is finished. The companion runs it on ONNX Runtime and answers over HTTP, so a browser tab doesn't have to load 1.9 GB. Its Go port returns the same tokens and probabilities as WebBrain's JavaScript adapter.</p>+ <div>+ <p class="code-label">Ask</p>+ <pre><code>curl http://127.0.0.1:8327/companion/v1/decide \+ -H "Content-Type: application/json" \+ -d '{"state": "Order #1042 is confirmed.",+ "questions": {"completion": {+ "type": "choice",+ "instructions": "Did the task finish?",+ "criteria": {"completed": "Confirmed",+ "not_completed": "Failed or unfinished",+ "unknown": "Not established"}}}}'</code></pre>+ <p class="code-label">Answer (273 ms on the CPU runtime)</p>+ <pre><code>{"answers": {"completion": {+ "choice": "completed",+ "confidence": 0.99997,+ "probabilities": {"completed": 0.99997,+ "not_completed": 0.000002,+ "unknown": 0.000033}}},+ "diagnostics": {"runtime": "onnxruntime 1.31.0 (CPU)", …}}</code></pre>+ </div>+ </div>+ </div>+</section>++<section class="section" id="connect" aria-labelledby="connect-h">+ <div class="wrap">+ <h2 id="connect-h">Connect WebBrain</h2>+ <p class="intro">You do this once. Apps on this computer need no API key.</p>+ <ol class="steps">+ <li>Install the companion and open it. Add a subscription in its panel and finish the sign-in in your browser.</li>+ <li>Copy the address, <code>http://127.0.0.1:8327/v1</code>, from the panel or the tray menu.</li>+ <li>In WebBrain, open the <b>Providers</b> page (<b>More…</b> in the side panel's model menu), choose <b>Local OpenAI-compatible Proxy</b> and paste the address in place of the 8317 WebBrain fills in. WebBrain asks for an API key: type anything.</li>+ <li>Click <b>Load models</b>, pick a model, and run <b>Test Connection</b>. Turn on vision only for a model that accepts images.</li>+ </ol>+ <p class="after-steps">Any OpenAI, Anthropic or Gemini client on this computer can use the same address. To use it from another device, turn on network access in the panel's settings; that device then needs the API key the panel shows.</p>+ </div>+</section>++<section class="section" id="download" aria-labelledby="download-h">+ <div class="wrap">+ <h2 id="download-h">Download</h2>+ <p class="intro">Version 0.1.2. Each package holds a single program; your settings and logins live in your user folder.</p>+ <div class="downloads">+ <div class="dl" data-os="mac">+ <div><h3>macOS</h3><p class="req">macOS 12 or later, Apple Silicon and Intel</p><span class="yours">Your system</span></div>+ <ul class="files"><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-macos-universal.zip">Universal app <small>zip, 36 MB</small></a></li></ul>+ <p class="how">Move WebBrain Companion to Applications. The build is not notarized by Apple: the first time, allow it in System Settings, Privacy & Security (Open Anyway). On macOS 14 and earlier, Control-click it and choose Open.</p>+ </div>+ <div class="dl" data-os="win">+ <div><h3>Windows</h3><p class="req">Windows 10 and 11, x64 and Arm64</p><span class="yours">Your system</span></div>+ <ul class="files"><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-windows-setup.exe">Installer <small>setup.exe, 23 MB</small></a></li></ul>+ <p class="how">Run the installer: it installs for your account, without an administrator prompt, and adds WebBrain Companion to the Start menu. Until the installer is code-signed, SmartScreen may say "Windows protected your PC": choose More info, then Run anyway.</p>+ </div>+ <div class="dl" data-os="linux">+ <div><h3>Linux</h3><p class="req">x64 and Arm64</p><span class="yours">Your system</span></div>+ <ul class="files"><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-linux-x64.tar.gz">x64 <small>tar.gz, 20 MB</small></a></li><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-linux-arm64.tar.gz">Arm64 <small>tar.gz, 18 MB</small></a></li></ul>+ <p class="how">Unpack and run webbrain-companion. The icon needs a StatusNotifierItem tray: KDE, XFCE, or GNOME with the AppIndicator extension.</p>+ </div>+ </div>+ <p class="more-links"><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-SHA256SUMS.txt">SHA-256 checksums</a><a href="https://github.com/esokullu/webbrain-systray">Source code</a><a href="https://github.com/esokullu/webbrain-systray/releases">All releases</a></p>+ </div>+</section>++<section class="section safety" id="safety" aria-labelledby="safety-h">+ <div class="wrap">+ <h2 id="safety-h">Before you sign in</h2>+ <div class="split even">+ <div>+ <h3>What stays on your computer</h3>+ <ul class="facts">+ <li>On this computer no API key is needed: the companion answers only requests from 127.0.0.1 and turns away web pages, so a site you visit can't spend your plans. Browser extensions such as WebBrain and apps on this computer can use it.</li>+ <li>Other devices can connect only if you turn on network access in the panel's settings. It then listens on 0.0.0.0, and they need the API key the panel shows.</li>+ <li>Logins are stored in your user folder and sent only to the provider they belong to.</li>+ <li>There are no analytics. Apart from the providers you sign in to, it only fetches CLIProxyAPI's public model list, and, when you install a model, its files from Hugging Face, GitHub and, for MLX, PyPI.</li>+ <li>Prompts sent to a subscription still go to that provider. Only Bonsai 2 27B and d1 run on your machine.</li>+ </ul>+ </div>+ <div>+ <h3>What your provider decides</h3>+ <ul class="facts">+ <li>A subscription that works through a proxy is not the same as one the provider allows. Anthropic's consumer terms restrict automated access outside an API key, and Google's Gemini CLI terms say its sign-in may not be used with third-party tools.</li>+ <li>Check the terms of your plan and region before you add it. If an account matters to you, a provider API key is the safer route.</li>+ <li>Keep network access off on public Wi-Fi, and never forward port 8327 to the internet. The API key is not internet-grade security.</li>+ </ul>+ <p><a href="https://webbrain.one/docs/easy-cli-proxy/">Read WebBrain's guide to subscription proxies</a></p>+ </div>+ </div>+ </div>+</section>+</main>++<footer class="site-foot">+ <div class="wrap">+ <p>WebBrain Companion is free software under the GPL-3.0-or-later license and embeds CLIProxyAPI. It is not affiliated with Anthropic, OpenAI, Google, xAI, Moonshot AI, Meta or Cognition.</p>+ <nav aria-label="More"><a href="https://webbrain.one/">WebBrain</a><a href="https://github.com/esokullu/webbrain-systray">Source code</a><a href="tr/" hreflang="tr" lang="tr">Türkçe</a></nav>+ </div>+</footer>+</body>+</html>diff --git a/webbrain-systray/web/tools/og.py b/webbrain-systray/web/tools/og.pynew file mode 100644index 000000000..e565a9096--- /dev/null+++ b/webbrain-systray/web/tools/og.py@@ -0,0 +1,39 @@+"""Renders assets/img/og.png (1200x630) from the hero of a locally served site:++ python3 -m http.server 8765 --directory web &+ python3 web/tools/og.py http://127.0.0.1:8765/ web/assets/img/og.png+"""+import sys, time+from playwright.sync_api import sync_playwright+url, out = sys.argv[1], sys.argv[2]+css = """+.site-head, .lede, .cta, .os-switch, main > section:not(.hero), footer { display: none !important; }+.hero { padding: 64px 64px 0 !important; max-width: none !important; gap: 40px !important; grid-template-columns: 1fr 1.05fr !important; align-items: start !important; }+.hero h1 { font-size: 60px !important; margin-top: 18px; }+.desk { height: 420px !important; }+.og-brand { display: flex; align-items: center; gap: 12px; font: 700 24px var(--font); letter-spacing: -.01em; }+.og-brand img { width: 44px; height: 44px; }+.og-url { margin-top: 26px; font: 500 20px var(--font); color: var(--muted); }+"""+with sync_playwright() as p:+ b = p.chromium.launch()+ pg = b.new_page(viewport={"width": 1200, "height": 630}, device_scale_factor=1, color_scheme="light",+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36",+ reduced_motion="reduce")+ pg.goto(url, wait_until="networkidle")+ pg.add_style_tag(content=css)+ pg.evaluate("""() => {+ const h = document.querySelector('.hero > div');+ const brand = document.createElement('div');+ brand.className = 'og-brand';+ brand.innerHTML = '<img src="assets/img/logo-128.png" alt="">WebBrain Companion';+ h.prepend(brand);+ const u = document.createElement('p');+ u.className = 'og-url';+ u.textContent = 'Claude, ChatGPT, Google, Grok and Kimi on 127.0.0.1:8327, with usage in your tray.';+ h.append(u);+ }""")+ pg.evaluate("document.fonts.ready")+ time.sleep(1.2)+ pg.screenshot(path=out)+ b.close()diff --git a/webbrain-systray/web/tools/shots.py b/webbrain-systray/web/tools/shots.pynew file mode 100644index 000000000..1836858f3--- /dev/null+++ b/webbrain-systray/web/tools/shots.py@@ -0,0 +1,45 @@+#!/usr/bin/env python3+"""Captures the panel screenshots used on the site: only the companion's own+window content (sample data from WBC_DEMO=1), never a desktop.++ WBC_HOME=/tmp/wbc-en WBC_DEMO=1 webbrain-companion --headless & # language "en", port 8327 in companion.json+ python3 web/tools/shots.py /tmp/wbc-en web/assets/img en++Writes panel-, add- and local-<lang>-<light|dark>.webp. Needs Playwright with+Chromium and Pillow (pip install playwright pillow).+"""+import io+import json+import sys+import time++from PIL import Image+from playwright.sync_api import sync_playwright++home, out, lang = sys.argv[1], sys.argv[2], sys.argv[3]+s = json.load(open(home + "/companion.json"))+base = f"http://127.0.0.1:{s['port']}/companion/#k={s['panel_token']}"+W, H = 460, 760+SHOTS = {"panel": "", "add": "&view=add", "local": "&view=local"}+++def settle(pg):+ pg.wait_for_selector("#h-subs", timeout=15000)+ pg.evaluate("document.fonts.ready")+ time.sleep(1.2) # the meters fill, a sheet rises+++with sync_playwright() as p:+ b = p.chromium.launch()+ for scheme in ("light", "dark"):+ ctx = b.new_context(viewport={"width": W, "height": H}, device_scale_factor=2, color_scheme=scheme, locale=lang)+ for name, view in SHOTS.items():+ pg = ctx.new_page()+ pg.goto(base + view)+ settle(pg)+ png = pg.screenshot()+ Image.open(io.BytesIO(png)).save(f"{out}/{name}-{lang}-{scheme}.webp", "WEBP", quality=86, method=6)+ pg.close()+ ctx.close()+ b.close()+print("ok", lang)diff --git a/webbrain-systray/web/tr/index.html b/webbrain-systray/web/tr/index.htmlnew file mode 100644index 000000000..16eaaed60--- /dev/null+++ b/webbrain-systray/web/tr/index.html@@ -0,0 +1,224 @@+<!doctype html>+<html lang="tr" class="no-js">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>WebBrain Companion: yapay zekâ aboneliklerin WebBrain'de</title>+<meta name="description" content="Claude, ChatGPT, Google, Grok ve Kimi aboneliklerini WebBrain'e 127.0.0.1 üzerinden sunan, her planda ne kadar hakkın kaldığını gösteren ve Bonsai 2 27B'yi kendi bilgisayarında çalıştıran küçük bir tepsi uygulaması. macOS, Windows ve Linux için.">+<meta name="color-scheme" content="light dark">+<meta name="theme-color" content="#fbf6f8" media="(prefers-color-scheme: light)">+<meta name="theme-color" content="#1a0f18" media="(prefers-color-scheme: dark)">+<link rel="canonical" href="https://webbrain.one/companion/tr/">+<link rel="alternate" hreflang="en" href="https://webbrain.one/companion/">+<link rel="alternate" hreflang="tr" href="https://webbrain.one/companion/tr/">+<link rel="alternate" hreflang="x-default" href="https://webbrain.one/companion/">+<meta property="og:type" content="website">+<meta property="og:site_name" content="WebBrain">+<meta property="og:title" content="WebBrain Companion">+<meta property="og:description" content="Claude, ChatGPT, Google, Grok ve Kimi aboneliklerini WebBrain'e 127.0.0.1 üzerinden sunan, her planda ne kadar hakkın kaldığını gösteren ve Bonsai 2 27B'yi kendi bilgisayarında çalıştıran küçük bir tepsi uygulaması. macOS, Windows ve Linux için.">+<meta property="og:url" content="https://webbrain.one/companion/tr/">+<meta property="og:image" content="https://webbrain.one/companion/assets/img/og.png">+<meta property="og:image:width" content="1200">+<meta property="og:image:height" content="630">+<meta name="twitter:card" content="summary_large_image">+<link rel="icon" type="image/png" href="../assets/img/favicon.png">+<link rel="preload" href="../assets/fonts/bricolage-grotesque-latin-opsz-normal.woff2" as="font" type="font/woff2" crossorigin>+<link rel="stylesheet" href="../assets/site.css">+<script>document.documentElement.classList.replace("no-js", "js")</script>+<script defer src="../assets/site.js"></script>+</head>+<body>+<a class="skip" href="#main">İçeriğe geç</a>+<header class="wrap site-head">+ <a class="brand" href="./"><img src="../assets/img/logo-128.png" alt="" width="30" height="30">WebBrain Companion</a>+ <nav class="site-nav" aria-label="Bölümler">+ <a href="#panel">Panel</a>+ <a href="#local">Yerel model</a>+ <a href="#connect">Bağlantı</a>+ <a href="#download">İndir</a>+ </nav>+ <a class="lang" href="../" hreflang="en" lang="en">English</a>+</header>++<main id="main">+<section class="wrap hero">+ <div>+ <h1>Zaten ödediğin yapay zekâ aboneliklerini WebBrain'de kullan</h1>+ <p class="lede">WebBrain Companion menü çubuğunda ya da sistem tepsisinde durur. Claude, ChatGPT, Google, Grok veya Kimi hesabına bir kez giriş yap; WebBrain hepsine bilgisayarındaki tek bir adresten ulaşsın. Tepsi, her planda ne kadar hakkın kaldığını ve ne zaman sıfırlanacağını gösterir.</p>+ <div class="cta">+ <a class="button primary" id="get" href="#download" data-mac="macOS için indir" data-win="Windows için indir" data-linux="Linux için indir" data-mac-href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-macos-universal.zip" data-win-href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-windows-setup.exe" data-linux-href="#download">İndir</a>+ <span class="cta-note">Sürüm 0.1.2; macOS, Windows ve Linux için. Ücretsiz ve açık kaynak.</span>+ </div>+ </div>+ <div class="desk-wrap">+ <div class="desk" data-os="mac" role="img" aria-label="Companion'ın tepsi menüsünün çizimi: çalışıyor, kopyalanacak adres ve Claude Max, ChatGPT Pro, Google AI Pro ile SuperGrok'ta ne kadar hak kaldığı.">+ <div class="bar" aria-hidden="true"><span class="s s3"></span><span class="s s2"></span><span class="icon"><span class="glyph"></span></span><span class="s s1"></span></div>+ <div class="menu" aria-hidden="true">+ <div class="row dim"><span>WebBrain Companion — Çalışıyor</span></div>+ <div class="row"><span>Kopyala http://127.0.0.1:8327/v1</span></div>+ <div class="sep"></div>+ <div class="row plan"><span>Claude Max</span><span class="meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i></i><i></i><i></i><i></i></span><span>%64 · 2 sa 13 dk</span></div>+ <div class="row plan"><span>ChatGPT Pro</span><span class="meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i></i><i></i><i></i><i></i></span><span>%57 · 4 gün</span></div>+ <div class="row plan"><span>Google AI Pro</span><span class="meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i></i><i></i><i></i></span><span>%71 · 5 gün</span></div>+ <div class="row plan"><span>Grok SuperGrok</span><span class="meter"><i class="on"></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></span><span>%12 · 3 gün</span></div>+ <div class="sep"></div>+ <div class="row"><span>Paneli aç…</span></div>+ <div class="row"><span>WebBrain Companion'dan çık</span></div>+ </div>+ </div>+ <div class="os-switch"><span id="os-label">Menü</span><span class="seg" role="group" aria-labelledby="os-label"><button type="button" data-os="mac" aria-pressed="true">macOS</button><button type="button" data-os="win" aria-pressed="false">Windows</button><button type="button" data-os="linux" aria-pressed="false">Linux</button></span></div>+ </div>+</section>++<section class="section" id="panel" aria-labelledby="panel-h">+ <div class="wrap">+ <h2 id="panel-h">Gerisi tek bir küçük panelde</h2>+ <p class="intro">Paneli simgeye tıklayarak açarsın. Tek sayfada WebBrain'in adresi, her planda kalan hak ve iki yerel model durur; ayrıntılar için bir satıra, ayarlar için dişli simgesine tıkla. Panel açık ya da koyu temana uyar; Türkçe ve İngilizce konuşur.</p>+ <ul class="windows">+ <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="../assets/img/panel-tr-dark.webp" media="(prefers-color-scheme: dark)"><img src="../assets/img/panel-tr-light.webp" width="460" height="760" alt="Panel: Kopyala düğmesiyle http://127.0.0.1:8327/v1 adresi; Claude Max, ChatGPT Pro, Google AI Pro ve SuperGrok kullanım göstergeleri; çalışan Bonsai 2 27B ve d1 karar modeli." loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>Tek sayfa</h3><p>WebBrain'in istediği adres, her planın bitmeye en yakın sınırı ve ana düğmeleriyle yerel modeller. Bu bilgisayarda API anahtarı yok.</p></figcaption>+ </figure></li>+ <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="../assets/img/add-tr-dark.webp" media="(prefers-color-scheme: dark)"><img src="../assets/img/add-tr-light.webp" width="460" height="760" alt="Abonelik ekleme penceresi: Claude, ChatGPT, Google, Grok ve Kimi, her birinin giriş yöntemiyle." loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>Abonelik ekleme</h3><p>Girişi sağlayıcının kendi sayfasında yaparsın. Oturum bilgisi bilgisayarında kalır.</p></figcaption>+ </figure></li>+ <li><figure>+ <div class="window"><div class="titlebar" aria-hidden="true"><i></i><i></i><i></i><span>WebBrain Companion</span></div>+ <picture><source srcset="../assets/img/local-tr-dark.webp" media="(prefers-color-scheme: dark)"><img src="../assets/img/local-tr-light.webp" width="460" height="760" alt="Panelin üzerinde Bonsai 2 27B ayrıntıları: Apple GPU'da görsel girdi açık çalışıyor, 65.536 token bağlam ve seçenekleri." loading="lazy" decoding="async"></picture></div>+ <figcaption><h3>Yerel modeller</h3><p>Bonsai 2 27B'ye tıkla: nerede çalıştığını ve görsellerin sığıp sığmadığını görür, seçeneklerini değiştirirsin. d1 de aynı şekilde açılır.</p></figcaption>+ </figure></li>+ </ul>+ </div>+</section>++<section class="section" id="local" aria-labelledby="local-h">+ <div class="wrap">+ <h2 id="local-h">Bonsai 2 27B, makinene göre ayarlanır</h2>+ <div class="split">+ <p class="intro">PrismML'in Ternary Bonsai 2 27B modeli 27 milyar parametreyi 5,95 GB'a sığdırır. Companion onu Q8_0 görsel projektörüyle ve PrismML'in llama.cpp sürümüyle, Apple Silicon'da istersen MLX paketi olarak kurar ve aboneliklerinin yanında <code>bonsai-2-27b</code> adıyla sunar.</p>+ <p class="intro">Daha hiçbir şey inmeden modelin nerede çalışacağını ve görsel girdinin sığıp sığmayacağını hesaplar. Model ve bağlamı yerleştikten sonra GPU'da yaklaşık 1 GB yer kalıyorsa görsel projektör GPU'ya, yalnızca sistem belleğinde yer varsa CPU'ya gider; ikisi de yoksa kapalı kalır. Bu seçimi panelden değiştirebilirsin.</p>+ </div>+ <table class="machines">+ <caption>Tipik makinelerde Companion'ın seçtikleri</caption>+ <thead><tr><th scope="col">Makine</th><th scope="col">Nerede çalışır</th><th scope="col">Görsel girdi</th><th scope="col">Bağlam</th></tr></thead>+ <tbody>+ <tr><td>MacBook Air, 8 GB</td><td data-label="Nerede çalışır">Apple GPU'da Metal. Mac'teki bellekten fazlasını ister, takas (swap) beklenir.</td><td data-label="Görsel girdi"><span class="vis off">Kapalı</span></td><td data-label="Bağlam">8K token</td></tr>+ <tr><td>MacBook Pro, 16 GB</td><td data-label="Nerede çalışır">Apple GPU'da Metal</td><td data-label="Görsel girdi"><span class="vis gpu">Açık, GPU</span></td><td data-label="Bağlam">16K token</td></tr>+ <tr><td>RTX 4060 (8 GB) ve 16 GB RAM'li dizüstü</td><td data-label="Nerede çalışır">CUDA, 64 katmanın 57'si GPU'da</td><td data-label="Görsel girdi"><span class="vis cpu">Açık, CPU</span></td><td data-label="Bağlam">8K token</td></tr>+ <tr><td>RTX 4090 (24 GB) ve 64 GB RAM'li masaüstü</td><td data-label="Nerede çalışır">CUDA, tamamı GPU'da</td><td data-label="Görsel girdi"><span class="vis gpu">Açık, GPU</span></td><td data-label="Bağlam">64K token</td></tr>+ <tr><td>Radeon RX 7600 (8 GB) ve 32 GB RAM'li masaüstü</td><td data-label="Nerede çalışır">Vulkan, 64 katmanın 61'i GPU'da</td><td data-label="Görsel girdi"><span class="vis cpu">Açık, CPU</span></td><td data-label="Bağlam">8K token</td></tr>+ <tr><td>Ekran kartı olmayan, 16 GB RAM'li PC</td><td data-label="Nerede çalışır">CPU</td><td data-label="Görsel girdi"><span class="vis cpu">Açık, CPU</span></td><td data-label="Bağlam">8K token</td></tr>+ <tr><td>Ekran kartı olmayan, 8 GB RAM'li PC</td><td data-label="Nerede çalışır">CPU, payı çok az</td><td data-label="Görsel girdi"><span class="vis off">Kapalı</span></td><td data-label="Bağlam">8K token</td></tr>+ </tbody>+ </table>+ <p class="note">Companion'ın planlayıcısı toplam ve boş belleğe bakarak hesaplar; son kararı kurulum anında makinendeki değerler verir. Apple Silicon'da MLX paketi kendi görsel katmanını taşır, görsel girdi her zaman açıktır.</p>+ </div>+</section>++<section class="section" id="decision" aria-labelledby="d1-h">+ <div class="wrap">+ <h2 id="d1-h">WebBrain'in karar modeli, tarayıcının dışında</h2>+ <div class="split">+ <p class="intro">WebBrain'in d1 modeli bir sayfa ve en fazla dört ekran görüntüsü hakkında evet/hayır, seçim ve puan sorularını yanıtlar; örneğin bir görevin bitip bitmediğini. Companion modeli ONNX Runtime ile çalıştırır ve HTTP üzerinden yanıtlar; böylece 1,9 GB'lık modeli bir tarayıcı sekmesi yüklemek zorunda kalmaz. Go'ya taşınan sürüm, WebBrain'in JavaScript adaptörüyle aynı token'ları ve olasılıkları verir.</p>+ <div>+ <p class="code-label">Soru</p>+ <pre><code>curl http://127.0.0.1:8327/companion/v1/decide \+ -H "Content-Type: application/json" \+ -d '{"state": "Order #1042 is confirmed.",+ "questions": {"completion": {+ "type": "choice",+ "instructions": "Did the task finish?",+ "criteria": {"completed": "Confirmed",+ "not_completed": "Failed or unfinished",+ "unknown": "Not established"}}}}'</code></pre>+ <p class="code-label">Yanıt (CPU'da 273 ms)</p>+ <pre><code>{"answers": {"completion": {+ "choice": "completed",+ "confidence": 0.99997,+ "probabilities": {"completed": 0.99997,+ "not_completed": 0.000002,+ "unknown": 0.000033}}},+ "diagnostics": {"runtime": "onnxruntime 1.31.0 (CPU)", …}}</code></pre>+ </div>+ </div>+ </div>+</section>++<section class="section" id="connect" aria-labelledby="connect-h">+ <div class="wrap">+ <h2 id="connect-h">WebBrain'i bağla</h2>+ <p class="intro">Bunu bir kez yaparsın. Bu bilgisayardaki uygulamaların API anahtarına ihtiyacı yok.</p>+ <ol class="steps">+ <li>Companion'ı kur ve aç. Panelinden bir abonelik ekle ve girişi tarayıcında tamamla.</li>+ <li>Adresi (<code>http://127.0.0.1:8327/v1</code>) panelden ya da tepsi menüsünden kopyala.</li>+ <li>WebBrain'de <b>Sağlayıcılar</b> sayfasını aç (yan paneldeki model menüsünde <b>Daha fazla…</b>), <b>Local OpenAI-compatible Proxy</b>'yi seç ve adresi WebBrain'in doldurduğu 8317 yerine yapıştır. WebBrain API anahtarı ister: herhangi bir şey yaz.</li>+ <li><b>Modelleri yükle</b>'ye bas, bir model seç ve <b>Bağlantıyı sına</b>. Görseli yalnızca resim kabul eden bir model için aç.</li>+ </ol>+ <p class="after-steps">Bu bilgisayardaki OpenAI, Anthropic ya da Gemini uyumlu her istemci aynı adresi anahtarsız kullanabilir. Başka bir cihazdan kullanmak için panelin ayarlarından ağ erişimini aç; o cihaz panelin gösterdiği API anahtarını kullanmalı.</p>+ </div>+</section>++<section class="section" id="download" aria-labelledby="download-h">+ <div class="wrap">+ <h2 id="download-h">İndir</h2>+ <p class="intro">Sürüm 0.1.2. Her paket tek bir program içerir; ayarların ve girişlerin kullanıcı klasöründe durur.</p>+ <div class="downloads">+ <div class="dl" data-os="mac">+ <div><h3>macOS</h3><p class="req">macOS 12 ve sonrası, Apple Silicon ve Intel</p><span class="yours">Senin sistemin</span></div>+ <ul class="files"><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-macos-universal.zip">Universal uygulama <small>zip, 36 MB</small></a></li></ul>+ <p class="how">WebBrain Companion'ı Uygulamalar klasörüne taşı. Sürüm Apple onayından (notarization) geçmedi: ilk açılışta Sistem Ayarları, Gizlilik ve Güvenlik bölümünden izin ver (Yine de Aç). macOS 14 ve öncesinde Control tuşuyla tıklayıp Aç'ı seçmen yeterli.</p>+ </div>+ <div class="dl" data-os="win">+ <div><h3>Windows</h3><p class="req">Windows 10 ve 11, x64 ve Arm64</p><span class="yours">Senin sistemin</span></div>+ <ul class="files"><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-windows-setup.exe">Kurulum dosyası <small>setup.exe, 23 MB</small></a></li></ul>+ <p class="how">Kurulum dosyasını çalıştır: yönetici izni istemeden senin hesabına kurar ve WebBrain Companion'ı Başlat menüsüne ekler. Kurulum dosyası kod imzalı olana kadar SmartScreen "Windows bilgisayarınızı korudu" diyebilir: Ek bilgi'yi, ardından Yine de çalıştır'ı seç.</p>+ </div>+ <div class="dl" data-os="linux">+ <div><h3>Linux</h3><p class="req">x64 ve Arm64</p><span class="yours">Senin sistemin</span></div>+ <ul class="files"><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-linux-x64.tar.gz">x64 <small>tar.gz, 20 MB</small></a></li><li><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-linux-arm64.tar.gz">Arm64 <small>tar.gz, 18 MB</small></a></li></ul>+ <p class="how">Arşivi aç ve webbrain-companion'ı çalıştır. Simge için StatusNotifierItem destekli bir tepsi gerekir: KDE, XFCE ya da AppIndicator eklentili GNOME.</p>+ </div>+ </div>+ <p class="more-links"><a href="https://github.com/esokullu/webbrain-systray/releases/download/v0.1.2/WebBrain-Companion-0.1.2-SHA256SUMS.txt">SHA-256 özetleri</a><a href="https://github.com/esokullu/webbrain-systray">Kaynak kodu</a><a href="https://github.com/esokullu/webbrain-systray/releases">Tüm sürümler</a></p>+ </div>+</section>++<section class="section safety" id="safety" aria-labelledby="safety-h">+ <div class="wrap">+ <h2 id="safety-h">Giriş yapmadan önce</h2>+ <div class="split even">+ <div>+ <h3>Bilgisayarında kalanlar</h3>+ <ul class="facts">+ <li>Bu bilgisayarda API anahtarı gerekmez: Companion yalnızca 127.0.0.1'den gelen istekleri yanıtlar ve web sayfalarını geri çevirir; böylece girdiğin bir site planlarını harcayamaz. WebBrain gibi tarayıcı eklentileri ve bu bilgisayardaki uygulamalar onu kullanabilir.</li>+ <li>Diğer cihazlar yalnızca panelin ayarlarından ağ erişimini açarsan bağlanabilir. Companion o zaman 0.0.0.0'da dinler ve o cihazlar panelin gösterdiği API anahtarını kullanmalıdır.</li>+ <li>Girişler kullanıcı klasöründe saklanır ve yalnızca ait oldukları sağlayıcıya gönderilir.</li>+ <li>Analitik yok. Giriş yaptığın sağlayıcılar dışında yalnızca CLIProxyAPI'nin herkese açık model listesini alır; bir model kurduğunda da dosyalarını Hugging Face'ten, GitHub'dan ve MLX için PyPI'dan indirir.</li>+ <li>Bir aboneliğe giden istemler yine o sağlayıcıya gider. Bilgisayarında çalışan yalnızca Bonsai 2 27B ve d1'dir.</li>+ </ul>+ </div>+ <div>+ <h3>Sağlayıcının belirledikleri</h3>+ <ul class="facts">+ <li>Bir aboneliğin proxy üzerinden çalışması, sağlayıcının buna izin verdiği anlamına gelmez. Anthropic'in tüketici koşulları API anahtarı dışındaki otomatik erişimi kısıtlar; Google'ın Gemini CLI koşulları da bu girişin üçüncü taraf araçlarla kullanılamayacağını söyler.</li>+ <li>Eklemeden önce planının ve bölgenin koşullarına bak. Hesabın senin için önemliyse sağlayıcının API anahtarı daha güvenli yoldur.</li>+ <li>Herkese açık Wi-Fi'da ağ erişimini kapalı tut ve 8327 portunu asla internete yönlendirme. API anahtarı internete dayanacak bir güvenlik sağlamaz.</li>+ </ul>+ <p><a href="https://webbrain.one/docs/easy-cli-proxy/">WebBrain'in abonelik proxy'leri rehberini oku (İngilizce)</a></p>+ </div>+ </div>+ </div>+</section>+</main>++<footer class="site-foot">+ <div class="wrap">+ <p>WebBrain Companion, GPL-3.0-or-later lisanslı özgür bir yazılımdır ve CLIProxyAPI'yi içinde barındırır. Anthropic, OpenAI, Google, xAI, Moonshot AI, Meta ya da Cognition ile bağlantılı değildir.</p>+ <nav aria-label="Bağlantılar"><a href="https://webbrain.one/">WebBrain</a><a href="https://github.com/esokullu/webbrain-systray">Kaynak kodu</a><a href="../" hreflang="en" lang="en">English</a></nav>+ </div>+</footer>+</body>+</html>