From ff2470481f92161a330e4c714e20b3fc4792c52d Mon Sep 17 00:00:00 2001
From: fish <1770968958@qq.com>
Date: Sun, 15 Nov 2026 15:25:45 +0900
Subject: [PATCH] feat(panel): Antigravity IDE & composer mount, modular
preferences, session charts, and per-model context windows (v1.5.0)
---
.gitignore | 2 +
LICENSE | 683 ++++++++++++++++++
plugin.json | 2 +-
pricing-catalog.json | 12 +-
sidecars/panel/app.js | 390 +++++++++-
.../panel/backend/account-credentials.ps1 | 204 ++++++
sidecars/panel/backend/account-oauth.mjs | 178 +++++
sidecars/panel/backend/account-switch.mjs | 173 +++++
sidecars/panel/backend/api-actions.mjs | 17 +
sidecars/panel/backend/config.mjs | 14 +-
sidecars/panel/backend/local-scanner.mjs | 20 +-
sidecars/panel/backend/ls-rpc.mjs | 18 +-
sidecars/panel/backend/plugin-updater.mjs | 72 +-
sidecars/panel/backend/pricing-catalog.mjs | 38 +-
sidecars/panel/backend/telemetry-builder.mjs | 43 +-
sidecars/panel/backend/usage-aggregator.mjs | 14 +-
sidecars/panel/backend/window-bridge.mjs | 2 +
sidecars/panel/index.html | 4 +-
sidecars/panel/main.mjs | 19 +
sidecars/panel/package.json | 2 +-
sidecars/panel/scripts/build-bundle.mjs | 1 +
sidecars/panel/src/core/httpClient.js | 10 +-
sidecars/panel/src/i18n/en-US.js | 47 ++
sidecars/panel/src/i18n/zh-CN.js | 47 ++
sidecars/panel/src/store/telemetryStore.js | 11 +
sidecars/panel/src/store/uiStore.js | 2 +-
sidecars/panel/src/styles/views-settings.css | 61 +-
sidecars/panel/src/views/SettingsView.js | 42 +-
.../src/views/settings/SettingsAccountTab.js | 235 ++++++
sidecars/panel/styles.css | 61 +-
sidecars/panel/test/account-switch.test.mjs | 128 ++++
sidecars/panel/test/backend-harness.mjs | 6 +-
.../panel/test/cloud-sync-and-update.test.mjs | 102 ++-
sidecars/panel/test/quota-pools.test.mjs | 30 +
sidecars/panel/test/window-bridge.test.mjs | 40 +-
35 files changed, 2602 insertions(+), 128 deletions(-)
create mode 100644 LICENSE
create mode 100644 sidecars/panel/backend/account-credentials.ps1
create mode 100644 sidecars/panel/backend/account-oauth.mjs
create mode 100644 sidecars/panel/backend/account-switch.mjs
create mode 100644 sidecars/panel/src/views/settings/SettingsAccountTab.js
create mode 100644 sidecars/panel/test/account-switch.test.mjs
diff --git a/.gitignore b/.gitignore
index 05d6db2..8739bcb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,5 +2,7 @@
node_modules/
plan/
*.log
+*.dpapi
+.account-test-*
.DS_Store
Thumbs.db
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..2dc6eae
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,683 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
+
+
+## License
+
+Copyright (C) 2026 yuhuan-dev.
+
+This project is licensed under the GNU General Public License v3.0 only (GPL-3.0-only).
+
+See the [LICENSE](LICENSE) file for details.
diff --git a/plugin.json b/plugin.json
index c051043..9296f1d 100644
--- a/plugin.json
+++ b/plugin.json
@@ -1,7 +1,7 @@
{
"name": "usage-monitor",
"displayName": "Usage & Speed Monitor",
- "version": "1.4.4",
+ "version": "1.5.0",
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
"logo": "assets/logo.svg",
"suggestedPrompts": [
diff --git a/pricing-catalog.json b/pricing-catalog.json
index 2f0a691..4bd92ae 100644
--- a/pricing-catalog.json
+++ b/pricing-catalog.json
@@ -1,11 +1,11 @@
{
"schemaVersion": 1,
- "catalogVersion": "2026.11.14.1",
- "updatedAt": "2026-11-14T16:40:00+09:00",
- "latestPluginVersion": "1.4.4",
- "releaseUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest",
- "downloadUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
- "archiveFallbackUrl": "https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main",
+ "catalogVersion": "2026.11.15.1",
+ "updatedAt": "2026-11-15T15:00:00+09:00",
+ "latestPluginVersion": "1.5.0",
+ "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest",
+ "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
+ "archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main",
"pricing": {
"gemini-pro-orchestrator": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" },
"orchestrator-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" },
diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js
index 91d5705..be2ca53 100644
--- a/sidecars/panel/app.js
+++ b/sidecars/panel/app.js
@@ -551,8 +551,55 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
// Preferences (3-Tab Modular Settings)
'settings.subTab.general': '常规',
'settings.subTab.structure': '结构',
+ 'settings.subTab.account': '账号',
'settings.subTab.other': '其他',
'settings.subTab.aria': '偏好设置分类切换',
+ 'settings.account.current': '当前账号',
+ 'settings.account.signedOut': '未登录',
+ 'settings.account.unknown': '暂未获取账号状态',
+ 'settings.account.email': '账号邮箱',
+ 'settings.account.credential': 'OAuth 凭证',
+ 'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。',
+ 'settings.account.save': '导入凭证',
+ 'settings.account.capture': '保存当前凭证',
+ 'settings.account.reload': '刷新列表',
+ 'settings.account.switch': '切换',
+ 'settings.account.remove': '移除',
+ 'settings.account.active': '当前使用',
+ 'settings.account.written': '凭证已写入',
+ 'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。',
+ 'settings.account.savedCredentials': '已保存的凭证',
+ 'settings.account.empty': '暂无已保存的凭证。',
+ 'settings.account.loading': '正在读取已保存的凭证…',
+ 'settings.account.saved': '凭证已保存。',
+ 'settings.account.removed': '已移除保存的凭证。',
+ 'settings.account.switched': '已切换账号,正在刷新当前额度。',
+ 'settings.account.switching': '正在替换凭证并确认宿主账号…',
+ 'settings.account.verifying': '正在验证凭证所属账号…',
+ 'settings.account.loadQuota': '查额度',
+ 'settings.account.loadingQuota': '正在查询此凭证的额度…',
+ 'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。',
+ 'settings.account.quota': '额度池剩余',
+ 'settings.account.quota5h': '5 小时 {percent}%',
+ 'settings.account.quotaWeekly': '每周 {percent}%',
+ 'settings.account.noQuota': '暂未获取当前账号的额度池。',
+ 'settings.account.quotaStale': '额度刷新失败,显示的是当前账号上次获取的数据。',
+ 'settings.account.unsupported': '凭证切换目前支持 Windows 上的 Antigravity 共享登录。',
+ 'settings.account.invalidEmail': '请先选择一个已保存的账号。',
+ 'settings.account.invalidCredential': '请输入有效的 Antigravity 个人账号 OAuth 凭证。',
+ 'settings.account.credentialTooLarge': '凭证超过 Windows 凭据管理器的 2560 字节上限。',
+ 'settings.account.notFound': '该凭证已移除,请刷新列表。',
+ 'settings.account.noCurrentCredential': '暂时无法读取当前账号的共享凭证。',
+ 'settings.account.busy': '另一个窗口正在操作凭证,请稍后重试。',
+ 'settings.account.storeFailed': '凭证操作失败,请重试。',
+ 'settings.account.rollbackFailed': '凭证写入和回滚均失败。请在 Antigravity 中确认当前账号后再继续。',
+ 'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。',
+ 'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。',
+ 'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。',
+ 'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。',
+ 'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。',
+ 'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。',
+ 'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。',
'settings.saving': '保存中…',
'settings.saved': '已保存',
'settings.saveFailed': '保存失败',
@@ -978,7 +1025,54 @@ const I18N_MESSAGES_EN_US = Object.freeze({
// Preferences (3-Tab Modular Settings)
'settings.subTab.general': 'General',
'settings.subTab.structure': 'Structure',
+ 'settings.subTab.account': 'Account',
'settings.subTab.other': 'Other',
+ 'settings.account.current': 'Current account',
+ 'settings.account.signedOut': 'Signed out',
+ 'settings.account.unknown': 'Account status unavailable',
+ 'settings.account.email': 'Account email',
+ 'settings.account.credential': 'OAuth credential',
+ 'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.',
+ 'settings.account.save': 'Import credential',
+ 'settings.account.capture': 'Save current credential',
+ 'settings.account.reload': 'Refresh list',
+ 'settings.account.switch': 'Switch',
+ 'settings.account.remove': 'Remove',
+ 'settings.account.active': 'In use',
+ 'settings.account.written': 'Credential written',
+ 'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.',
+ 'settings.account.savedCredentials': 'Saved credentials',
+ 'settings.account.empty': 'No saved credentials.',
+ 'settings.account.loading': 'Loading saved credentials…',
+ 'settings.account.saved': 'Credential saved.',
+ 'settings.account.removed': 'Saved credential removed.',
+ 'settings.account.switched': 'Account switched. Refreshing the current quota.',
+ 'settings.account.switching': 'Replacing the credential and confirming the active account…',
+ 'settings.account.verifying': 'Verifying the credential owner…',
+ 'settings.account.loadQuota': 'Check quota',
+ 'settings.account.loadingQuota': 'Checking quota for this credential…',
+ 'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.',
+ 'settings.account.quota': 'Quota remaining by pool',
+ 'settings.account.quota5h': '5 hours {percent}%',
+ 'settings.account.quotaWeekly': 'Weekly {percent}%',
+ 'settings.account.noQuota': 'Quota pools are unavailable for the current account.',
+ 'settings.account.quotaStale': 'Quota refresh failed. Showing the last data for the current account.',
+ 'settings.account.unsupported': 'Credential switching currently supports Antigravity shared sign-in on Windows.',
+ 'settings.account.invalidEmail': 'Select a saved account first.',
+ 'settings.account.invalidCredential': 'Enter a valid Antigravity OAuth credential for a personal account.',
+ 'settings.account.credentialTooLarge': 'The credential exceeds the Windows Credential Manager limit of 2560 bytes.',
+ 'settings.account.notFound': 'This credential was removed. Refresh the list.',
+ 'settings.account.noCurrentCredential': 'The shared credential for the current account is unavailable.',
+ 'settings.account.busy': 'Another window is updating credentials. Try again shortly.',
+ 'settings.account.storeFailed': 'The credential operation failed. Try again.',
+ 'settings.account.rollbackFailed': 'Writing and restoring the credential both failed. Check the active account in Antigravity before continuing.',
+ 'settings.account.credentialAccessDenied': 'Windows denied access to Credential Manager. Open Antigravity in your Windows user session and try again.',
+ 'settings.account.credentialChanged': 'This credential was updated in another window. Refresh the list and try again.',
+ 'settings.account.credentialRejected': 'Google rejected this credential. Check that the Antigravity refresh token is still valid.',
+ 'settings.account.identityMismatch': 'The credential belongs to a different account. Import the credential again.',
+ 'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.',
+ 'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.',
+ 'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.',
'settings.subTab.aria': 'Preferences category tabs',
'settings.saving': 'Saving…',
'settings.saved': 'Saved',
@@ -1995,7 +2089,7 @@ function deliverCdpBridgeResponses(responses) {
return delivered;
}
-function callViaCdpBridge(bridge, path, { method, body, signal }) {
+function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
@@ -2017,7 +2111,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
bridge.rpcPending.delete(reqId);
cleanupQueueItem();
reject(new Error('CDP bridge timeout'));
- }, 8000);
+ }, cdpTimeoutMs);
const onAbort = () => {
clearTimeout(timeoutId);
@@ -2056,7 +2150,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
});
}
-async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
+async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 8000 } = {}) {
const upperMethod = method.toUpperCase();
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
@@ -2093,7 +2187,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}
if (bridge) {
headers['X-Usage-Monitor-Token'] = bridge.token;
if (bridge.transportMode === 'cdp') {
- return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
+ return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
}
@@ -2111,7 +2205,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}
}
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
bridge.transportMode = 'cdp';
- return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
+ return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
@@ -2170,7 +2264,7 @@ function getViewTabs() {
const uiStore = createReactiveStore({
activeView: 'overview',
stepsSubTab: 'steps', // 'steps' | 'models'
- settingsSubTab: 'general', // 'general' | 'structure' | 'other'
+ settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
selectedAgentScope: 'all', // 'all' | 'main' |
ctxInspectorAgentId: 'auto', // 'auto' | 'main' |
});
@@ -2863,6 +2957,9 @@ function isEquivalentTelemetry(prev, next) {
// 8. 比对账号订阅档位与动态多配额池
if (
+ prev.account?.email !== next.account?.email ||
+ prev.account?.name !== next.account?.name ||
+ prev.account?.status !== next.account?.status ||
prev.account?.tierName !== next.account?.tierName ||
prev.account?.planName !== next.account?.planName ||
prev.account?.aiCredits !== next.account?.aiCredits
@@ -3040,6 +3137,12 @@ async function fetchTelemetry({ force = false } = {}) {
}
const latestSt = telemetryStore.getState();
+ const previousAccount = latestSt.telemetry?.account;
+ const nextAccount = payload?.account;
+ const accountChanged = previousAccount?.status === 'signedIn' &&
+ (nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' &&
+ (previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name)));
+ const accountPatch = accountChanged ? { selectedConversationId: '' } : {};
if (force) {
const elapsed = Date.now() - startMs;
if (elapsed < 220) {
@@ -3050,6 +3153,7 @@ async function fetchTelemetry({ force = false } = {}) {
}
if (feedbackTimer) clearTimeout(feedbackTimer);
telemetryStore.setState({
+ ...accountPatch,
telemetry: payload,
minuteTick: Math.floor(Date.now() / 30000),
syncState: 'synced',
@@ -3062,6 +3166,7 @@ async function fetchTelemetry({ force = false } = {}) {
const isSame = isEquivalentTelemetry(latestSt.telemetry, payload);
const nextTelemetry = isSame ? latestSt.telemetry : payload;
telemetryStore.setState({
+ ...accountPatch,
telemetry: nextTelemetry,
minuteTick: Math.floor(Date.now() / 30000),
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
@@ -11612,6 +11717,238 @@ const SettingsStructureTab = defineComponent({
},
});
+// --- src/views/settings/SettingsAccountTab.js ---
+/** @fileoverview Saved account credentials and the host's active account quota. */
+
+
+const key = (name) => `settings.account.${name}`;
+const errors = new Set([
+ 'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
+ 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
+ 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
+ 'oauthUnavailable', 'quotaUnavailable',
+]);
+
+function renderQuotaRows(container, quotaPools) {
+ const locale = getEffectiveLocale();
+ const pools = quotaPools.filter((pool) => Number.isFinite(pool.remainingPct) || Number.isFinite(pool.weeklyRemainingPct));
+ patchKeyedList(container, pools, {
+ keyFn: (pool) => pool.poolKey || pool.poolLabel,
+ sigFn: (pool) => JSON.stringify([locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct]),
+ createRow: () => {
+ const label = h('span');
+ const remaining = h('span', { className: 'settings-account-quota' });
+ return { el: h('div', { className: 'settings-action-block' }, [label, remaining]), refs: { label, remaining } };
+ },
+ updateRow: ({ label, remaining }, pool) => {
+ patchText(label, pool.poolLabel || pool.poolKey);
+ const values = [];
+ if (Number.isFinite(pool.remainingPct)) values.push(t(key('quota5h'), { percent: pool.remainingPct }));
+ if (Number.isFinite(pool.weeklyRemainingPct)) values.push(t(key('quotaWeekly'), { percent: pool.weeklyRemainingPct }));
+ patchText(remaining, values.join(' · '));
+ },
+ });
+ return pools.length;
+}
+
+const SettingsAccountTab = defineComponent({
+ name: 'SettingsAccountTab',
+ setup({ props, onCleanup }) {
+ let account = null;
+ let quotas = null;
+ let accounts = [];
+ let selectedEmail = '';
+ let supported = null;
+ let operation = '';
+ let status = '';
+ let disposed = false;
+ const savedQuotas = new Map();
+
+ const title = h('span', { className: 'panel-title' });
+ const identityLabel = h('div', { className: 'settings-action-title' });
+ const identity = h('div', { className: 'settings-action-desc settings-account-identity' });
+ const plan = h('div', { className: 'settings-action-desc' });
+ const quotaTitle = h('div', { className: 'settings-action-title' });
+ const quotaRows = h('div', { className: 'settings-account-list' });
+ const quotaMessage = h('div', { className: 'settings-action-desc' });
+ const savedTitle = h('span', { className: 'panel-title' });
+ const savedRows = h('div', { className: 'settings-account-list' });
+ const savedMessage = h('div', { className: 'settings-action-desc' });
+ const pending = h('div', { className: 'settings-action-desc', role: 'status' });
+ const feedback = h('div', { className: 'settings-action-desc', role: 'status' });
+ const capture = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('capture') });
+ const reload = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('list') });
+ const credentialLabel = h('span');
+ const importHint = h('div', { className: 'settings-action-desc' });
+ const credential = h('input', { type: 'password', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384 });
+ const save = h('button', { type: 'submit', className: 'btn-secondary' });
+ const form = h('form', { className: 'settings-account-form', autocomplete: 'off', onSubmit: importCredential }, [
+ h('label', {}, [credentialLabel, credential]),
+ importHint,
+ save,
+ ]);
+
+ function render() {
+ const signedIn = account?.status === 'signedIn';
+ const activeEmail = signedIn ? account.email?.trim().toLowerCase() : '';
+ const canWrite = supported === true && !operation;
+ const locale = getEffectiveLocale();
+ patchText(title, t(key('current')));
+ patchText(identityLabel, t(key('email')));
+ patchText(identity, signedIn ? account.email || account.name :
+ t(key(account?.status === 'signedOut' ? 'signedOut' : 'unknown')));
+ patchText(plan, signedIn ? account.tierName || account.planName || '' : '');
+ patchAttr(plan, 'hidden', !plan.textContent);
+
+ patchText(quotaTitle, t(key('quota')));
+ const poolCount = renderQuotaRows(quotaRows, signedIn ? quotas?.pools || [] : []);
+ patchText(quotaMessage, t(key(poolCount ? 'quotaStale' : 'noQuota')));
+ patchAttr(quotaMessage, 'hidden', poolCount > 0 && !quotas?.meta?.isStale);
+
+ patchText(savedTitle, t(key('savedCredentials')));
+ patchText(capture, t(key('capture')));
+ patchText(reload, t(key('reload')));
+ patchText(save, t(key('save')));
+ patchText(credentialLabel, t(key('credential')));
+ patchText(importHint, t(key('importHint')));
+ patchAttr(capture, 'disabled', !canWrite || !activeEmail);
+ patchAttr(reload, 'disabled', Boolean(operation));
+ patchAttr(form, 'hidden', supported === false);
+ patchAttr(save, 'disabled', !canWrite);
+ patchAttr(credential, 'disabled', !canWrite);
+ patchText(savedMessage, t(key(supported === null ? 'loading' : 'empty')));
+ patchAttr(savedMessage, 'hidden', accounts.length > 0 || supported === false || Boolean(status));
+ const message = status || (operation === 'switch' ? 'switching' : operation === 'quota' ? 'loadingQuota' :
+ operation === 'save' || operation === 'capture' ? 'verifying' : '');
+ patchText(feedback, message ? t(key(message)) : '');
+ patchAttr(feedback, 'hidden', !message);
+ const waiting = selectedEmail && activeEmail !== selectedEmail;
+ patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : '');
+ patchAttr(pending, 'hidden', !waiting);
+
+ patchKeyedList(savedRows, accounts, {
+ keyFn: (addr) => addr,
+ sigFn: (addr) => JSON.stringify([locale, activeEmail, selectedEmail, canWrite, savedQuotas.get(addr)]),
+ createRow: (addr) => {
+ const state = h('div', { className: 'settings-action-desc' });
+ const select = h('button', {
+ type: 'button', className: 'btn-secondary settings-account-switch', onClick: () => request('switch', { email: addr }),
+ });
+ const remove = h('button', {
+ type: 'button', className: 'btn-secondary', onClick: () => request('remove', { email: addr }),
+ });
+ const loadQuota = h('button', {
+ type: 'button', className: 'btn-secondary settings-account-load-quota', onClick: () => request('quota', { email: addr }),
+ });
+ const rows = h('div', { className: 'settings-account-list' });
+ const empty = h('div', { className: 'settings-action-desc' });
+ return {
+ el: h('div', { className: 'settings-account-entry' }, [
+ h('div', { className: 'settings-action-block' }, [
+ h('div', { className: 'settings-action-info' }, [h('div', { className: 'settings-account-identity', text: addr }), state]),
+ h('div', { className: 'settings-account-buttons' }, [loadQuota, select, remove]),
+ ]), rows, empty,
+ ]),
+ refs: { state, select, remove, loadQuota, rows, empty },
+ };
+ },
+ updateRow: (row, addr) => {
+ const active = addr === activeEmail;
+ const written = addr === selectedEmail && !active;
+ patchText(row.state, active ? t(key('active')) : written ? t(key('written')) : '');
+ patchAttr(row.state, 'hidden', !active && !written);
+ patchText(row.select, t(key('switch')));
+ patchText(row.remove, t(key('remove')));
+ patchText(row.loadQuota, t(key('loadQuota')));
+ patchAttr(row.select, 'disabled', !canWrite);
+ patchAttr(row.remove, 'disabled', !canWrite);
+ patchAttr(row.loadQuota, 'disabled', !canWrite);
+ const cached = savedQuotas.get(addr);
+ const count = renderQuotaRows(row.rows, cached || []);
+ patchText(row.empty, t(key('emptyCredentialQuota')));
+ patchAttr(row.empty, 'hidden', !cached || count > 0);
+ },
+ });
+ props.onLayoutChange?.();
+ }
+
+ async function request(action, fields) {
+ if (operation) return;
+ operation = action;
+ status = '';
+ render();
+ try {
+ const result = action === 'list'
+ ? await callSidecarApi('/api/accounts')
+ : await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields }, cdpTimeoutMs: 40000 });
+ if (disposed) return;
+ if (result?.error) {
+ if (result.error === 'unsupported') supported = false;
+ status = errors.has(result.error) ? result.error : 'storeFailed';
+ return;
+ }
+ if (action === 'quota') {
+ savedQuotas.set(result.email, result.pools);
+ return;
+ }
+ supported = result?.supported === true;
+ accounts = result?.accounts || [];
+ selectedEmail = result?.selectedEmail || '';
+ if (action === 'save' || action === 'capture') status = 'saved';
+ if (action === 'remove') {
+ savedQuotas.delete(fields.email);
+ status = 'removed';
+ }
+ if (action === 'switch') {
+ status = result.confirmed ? 'switched' : '';
+ void fetchTelemetry({ force: true }).catch(() => {});
+ }
+ } catch {
+ status = 'storeFailed';
+ } finally {
+ operation = '';
+ if (!disposed) render();
+ }
+ }
+
+ function importCredential(event) {
+ event.preventDefault();
+ if (operation) return;
+ const input = credential.value;
+ credential.value = '';
+ void request('save', { credential: input });
+ }
+
+ function renderAccount(value, quotaData) {
+ if (account === value && quotas === quotaData) return;
+ account = value;
+ quotas = quotaData;
+ render();
+ }
+
+ const root = h('div', { className: 'settings-tab-stack' }, [
+ h('section', { className: 'panel' }, [
+ h('div', { className: 'panel-header' }, [title]),
+ h('div', { className: 'settings-action-block' }, [
+ h('div', { className: 'settings-action-info' }, [identityLabel, identity, plan]),
+ ]),
+ quotaTitle, quotaRows, quotaMessage, pending,
+ ]),
+ h('section', { className: 'panel' }, [
+ h('div', { className: 'panel-header' }, [savedTitle]),
+ h('div', { className: 'settings-account-buttons' }, [capture, reload]),
+ savedRows, savedMessage, form, feedback,
+ ]),
+ ]);
+ render();
+ onCleanup(() => {
+ disposed = true;
+ credential.value = '';
+ });
+ return { el: root, refs: { renderAccount, refreshLabels: render, load: () => request('list') } };
+ },
+});
+
// --- src/views/settings/SettingsOtherTab.js ---
/**
* @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他").
@@ -14481,16 +14818,19 @@ const StepsDetailView = defineComponent({
// --- src/views/SettingsView.js ---
/**
- * @fileoverview View 4: Modular 3-Tab `SettingsView.js` ("常规" / "结构" / "其他").
- * Orchestrates `SettingsGeneralTab`, `SettingsStructureTab`, and `SettingsOtherTab`
+ * @fileoverview View 4: Modular preferences ("常规" / "结构" / "账号" / "其他").
+ * Orchestrates the four preference tabs
* with top sub-navigation and a shared `CustomScrollbar` viewport.
*/
+const SHOW_ACCOUNT_TAB = false;
+
function getSettingsSubTabOptions() {
return [
{ value: 'general', label: t('settings.subTab.general') },
{ value: 'structure', label: t('settings.subTab.structure') },
+ ...(SHOW_ACCOUNT_TAB ? [{ value: 'account', label: t('settings.subTab.account') }] : []),
{ value: 'other', label: t('settings.subTab.other') },
];
}
@@ -14520,25 +14860,41 @@ const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
+ const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
- function applyActiveSubTab(subTab) {
+ let showingAccount = false;
+ function applyActiveSubTab(subTab, activeView) {
const target =
- subTab === 'structure' || subTab === 'other' ? subTab : 'general';
+ subTab === 'structure' ||
+ subTab === 'other' ||
+ (SHOW_ACCOUNT_TAB && subTab === 'account')
+ ? subTab
+ : 'general';
subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure');
+ patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
patchAttr(otherTab.el, 'hidden', target !== 'other');
+ const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
+ if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
+ showingAccount = nextShowingAccount;
refreshScroll();
}
- const contentContainer = h('div', {}, [generalTab.el, structureTab.el, otherTab.el]);
+ const contentContainer = h(
+ 'div',
+ {},
+ SHOW_ACCOUNT_TAB
+ ? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
+ : [generalTab.el, structureTab.el, otherTab.el]
+ );
viewScrollbar = CustomScrollbar({
contentEl: contentContainer,
className: 'view-pane',
});
- applyActiveSubTab(initialSubTab);
+ applyActiveSubTab(initialSubTab, uiStore.getState().activeView);
const rootEl = h('div', { className: 'settings-view-root' }, [
subNavBar,
@@ -14548,6 +14904,8 @@ const SettingsView = defineComponent({
let latestSettings = null;
let latestCloudStatus = null;
let latestContextWindowModels = [];
+ const initialTelemetry = telemetryStore.getState().telemetry;
+ accountTab.refs.renderAccount(initialTelemetry?.account, initialTelemetry?.quotas);
function syncAllTabs(settings, cloudStatus) {
if (settings) {
@@ -14566,11 +14924,14 @@ const SettingsView = defineComponent({
settings: st.telemetry?.settings,
cloudStatus: st.telemetry?.cloudStatus,
contextWindowModels: st.telemetry?.contextWindowModels,
+ account: st.telemetry?.account,
+ quotas: st.telemetry?.quotas,
}),
(slice) => {
latestSettings = slice.settings;
latestCloudStatus = slice.cloudStatus;
latestContextWindowModels = slice.contextWindowModels || [];
+ accountTab.refs.renderAccount(slice.account, slice.quotas);
if (slice.settings) {
generalTab.refs.renderSettings(slice.settings);
structureTab.refs.renderSettings(slice.settings);
@@ -14589,7 +14950,7 @@ const SettingsView = defineComponent({
settingsSubTab: st.settingsSubTab,
}),
(slice) => {
- applyActiveSubTab(slice.settingsSubTab);
+ applyActiveSubTab(slice.settingsSubTab, slice.activeView);
if (slice.activeView === 'settings') {
syncAllTabs(latestSettings, latestCloudStatus);
}
@@ -14605,6 +14966,7 @@ const SettingsView = defineComponent({
});
generalTab.refs.refreshLabels();
structureTab.refs.refreshLabels();
+ accountTab.refs.refreshLabels();
otherTab.refs.refreshLabels();
refreshScroll();
}
@@ -14617,6 +14979,7 @@ const SettingsView = defineComponent({
subNavSwitch.destroy();
generalTab.destroy();
structureTab.destroy();
+ accountTab.destroy();
otherTab.destroy();
viewScrollbar.destroy();
});
@@ -14627,6 +14990,7 @@ const SettingsView = defineComponent({
subNavSwitch,
generalTab,
structureTab,
+ accountTab,
otherTab,
viewScrollbar,
// Convenience aliases for external callers / tests
diff --git a/sidecars/panel/backend/account-credentials.ps1 b/sidecars/panel/backend/account-credentials.ps1
new file mode 100644
index 0000000..744e0e0
--- /dev/null
+++ b/sidecars/panel/backend/account-credentials.ps1
@@ -0,0 +1,204 @@
+$ErrorActionPreference = 'Stop'
+[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
+[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
+$utf8 = [Console]::OutputEncoding
+
+function Test-AccountFile($path) {
+ if (-not (Test-Path -LiteralPath $path)) { return $false }
+ $item = Get-Item -LiteralPath $path -Force
+ if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
+ throw 'Invalid account file'
+ }
+ return $true
+}
+
+function Write-AccountFile($path, [byte[]]$bytes) {
+ $temp = Join-Path ([IO.Path]::GetDirectoryName($path)) ([guid]::NewGuid().ToString() + '.tmp')
+ try {
+ [IO.File]::WriteAllBytes($temp, $bytes)
+ if (Test-AccountFile $path) {
+ [IO.File]::Replace($temp, $path, [NullString]::Value)
+ } else {
+ [IO.File]::Move($temp, $path)
+ }
+ } finally {
+ [IO.File]::Delete($temp)
+ }
+}
+
+function Save-Vault($path, $vault) {
+ $bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress))
+ $encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
+ [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
+ Write-AccountFile $path $encrypted
+}
+
+function Add-NativeCredentialType {
+ Add-Type -TypeDefinition @'
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+
+public static class NativeAccountCredential {
+ private const uint Generic = 1;
+ private const uint PersistLocalMachine = 2;
+ private const int NotFound = 1168;
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct Credential {
+ public uint Flags, Type;
+ public string TargetName, Comment;
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
+ public uint BlobSize;
+ public IntPtr Blob;
+ public uint Persist, AttributeCount;
+ public IntPtr Attributes;
+ public string TargetAlias, UserName;
+ }
+
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
+ private static extern bool CredReadW(string target, uint type, uint flags, out IntPtr credential);
+
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
+ private static extern bool CredWriteW(ref Credential credential, uint flags);
+
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
+ private static extern bool CredDeleteW(string target, uint type, uint flags);
+
+ [DllImport("advapi32.dll")]
+ private static extern void CredFree(IntPtr buffer);
+
+ public static byte[] Read(string target) {
+ IntPtr pointer;
+ if (!CredReadW(target, Generic, 0, out pointer)) {
+ int error = Marshal.GetLastWin32Error();
+ if (error == NotFound) return null;
+ throw new Win32Exception(error);
+ }
+ try {
+ var credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
+ var bytes = new byte[credential.BlobSize];
+ if (bytes.Length > 0) Marshal.Copy(credential.Blob, bytes, 0, bytes.Length);
+ return bytes;
+ } finally {
+ CredFree(pointer);
+ }
+ }
+
+ public static void Write(string target, byte[] bytes) {
+ var buffer = GCHandle.Alloc(bytes, GCHandleType.Pinned);
+ try {
+ var credential = new Credential {
+ Type = Generic, Persist = PersistLocalMachine, TargetName = target,
+ UserName = "antigravity", Blob = buffer.AddrOfPinnedObject(), BlobSize = (uint)bytes.Length
+ };
+ if (!CredWriteW(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
+ } finally {
+ buffer.Free();
+ }
+ }
+
+ public static void Restore(string target, byte[] bytes) {
+ if (bytes != null) Write(target, bytes);
+ else if (!CredDeleteW(target, Generic, 0)) {
+ int error = Marshal.GetLastWin32Error();
+ if (error != NotFound) throw new Win32Exception(error);
+ }
+ }
+}
+'@
+}
+
+function Invoke-AccountAction($request) {
+ Add-Type -AssemblyName System.Security
+ $vault = @{ entries = @(); selectedEmail = '' }
+ if (Test-AccountFile $request.vault) {
+ $plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser')
+ $vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
+ }
+ $entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1
+ if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) {
+ return @{ error = 'credentialChanged' }
+ }
+
+ switch ($request.action) {
+ 'readCurrent' {
+ Add-NativeCredentialType
+ $bytes = [NativeAccountCredential]::Read($request.target)
+ if (-not $bytes) {
+ foreach ($path in $request.fallbacks) {
+ if (Test-AccountFile $path) {
+ $bytes = [IO.File]::ReadAllBytes($path)
+ if ($bytes) { break }
+ }
+ }
+ }
+ if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
+ return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
+ }
+ 'read' {
+ if (-not $entry) { return @{ error = 'notFound' } }
+ return @{ credential = $entry.credential }
+ }
+ 'save' {
+ if ($entry) { $entry.credential = $request.credential }
+ else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) }
+ Save-Vault $request.vault $vault
+ }
+ 'switch' {
+ if (-not $entry) { return @{ error = 'notFound' } }
+ $replacement = $utf8.GetBytes($request.credential)
+ if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } }
+ Add-NativeCredentialType
+ $previous = [NativeAccountCredential]::Read($request.target)
+ $fallbacks = @(foreach ($path in $request.fallbacks) {
+ if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } }
+ })
+ $written = @()
+ [NativeAccountCredential]::Write($request.target, $replacement)
+ try {
+ foreach ($fallback in $fallbacks) {
+ Write-AccountFile $fallback.path $replacement
+ $written += $fallback
+ }
+ $entry.credential = $request.credential
+ $vault.selectedEmail = $request.email
+ Save-Vault $request.vault $vault
+ } catch {
+ $restored = $true
+ try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
+ foreach ($fallback in $written) {
+ try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false }
+ }
+ if (-not $restored) { return @{ error = 'rollbackFailed' } }
+ throw
+ }
+ }
+ 'remove' {
+ if (-not $entry) { return @{ error = 'notFound' } }
+ $vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email })
+ if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' }
+ Save-Vault $request.vault $vault
+ }
+ }
+ return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail }
+}
+
+$mutex = $null
+$locked = $false
+try {
+ $request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
+ $mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials')
+ try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true }
+ $result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } }
+} catch {
+ $result = @{ error = 'storeFailed' }
+ $nativeError = $_.Exception.InnerException
+ if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) {
+ $result.error = 'credentialAccessDenied'
+ }
+} finally {
+ if ($locked) { $mutex.ReleaseMutex() }
+ if ($mutex) { $mutex.Dispose() }
+}
+[Console]::Write((ConvertTo-Json -InputObject $result -Compress))
diff --git a/sidecars/panel/backend/account-oauth.mjs b/sidecars/panel/backend/account-oauth.mjs
new file mode 100644
index 0000000..28c8daf
--- /dev/null
+++ b/sidecars/panel/backend/account-oauth.mjs
@@ -0,0 +1,178 @@
+/** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */
+
+import { readFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { buildOfficialQuotaPools } from './quota-pools.mjs';
+
+const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
+const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
+const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com'];
+let nativeOAuthClients;
+
+export function extractNativeOAuthClients(binary) {
+ const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0;
+ if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return [];
+ const count = binary.readUInt16LE(pe + 6);
+ const table = pe + 24 + binary.readUInt16LE(pe + 20);
+ if (table + count * 40 > binary.length) return [];
+
+ const sections = Array.from({ length: count }, (_, i) => {
+ const offset = table + i * 40;
+ return {
+ name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''),
+ rva: binary.readUInt32LE(offset + 12),
+ size: binary.readUInt32LE(offset + 16),
+ start: binary.readUInt32LE(offset + 20),
+ };
+ });
+ const text = sections.find(({ name }) => name === '.text');
+ const rodata = sections.find(({ name }) => name === '.rdata');
+ if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return [];
+ const machineCode = binary.subarray(text.start, text.start + text.size);
+
+ function readLiteral(displacementOffset, length) {
+ const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset);
+ const offset = rva - rodata.rva;
+ if (length > 100 || offset < 0 || offset + length > rodata.size) return '';
+ return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length);
+ }
+
+ // Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs.
+ const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
+ const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]);
+ const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
+ const clients = new Map();
+ for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) {
+ if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) ||
+ !machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) ||
+ !machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue;
+ const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4));
+ const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22));
+ if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) {
+ clients.set(id, { id, secret });
+ }
+ }
+ return Array.from(clients.values()).reverse();
+}
+
+async function loadNativeOAuthClients() {
+ if (!nativeOAuthClients) {
+ nativeOAuthClients = (async () => {
+ const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
+ const binaries = [
+ join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'),
+ join(homedir(), '.gemini', 'bin', 'agy.exe'),
+ ];
+ for (const filename of binaries) {
+ const binary = await readFile(filename).catch(() => null);
+ const clients = binary ? extractNativeOAuthClients(binary) : [];
+ if (clients.length) return clients;
+ }
+ return [];
+ })();
+ }
+ const clients = await nativeOAuthClients;
+ if (!clients.length) nativeOAuthClients = null;
+ return clients;
+}
+
+export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) {
+ let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token;
+ let idToken = credential.id_token;
+ if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) {
+ const clients = await getClients();
+ if (!clients.length) throw new Error('oauthClientUnavailable');
+ let refreshed = false;
+ for (const { id, secret } of clients) {
+ const response = await fetchFn(OAUTH_TOKEN_URL, {
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(6000),
+ body: new URLSearchParams({ client_id: id, client_secret: secret, grant_type: 'refresh_token', refresh_token: refreshToken }),
+ });
+ const result = await response.json();
+ if (!response.ok) {
+ if (['invalid_grant', 'invalid_client', 'unauthorized_client'].includes(result?.error)) continue;
+ throw new Error('oauthUnavailable');
+ }
+ if (!result.access_token || !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('oauthUnavailable');
+ accessToken = result.access_token;
+ refreshToken = result.refresh_token || refreshToken;
+ idToken = result.id_token;
+ expiry = new Date(Date.now() + result.expires_in * 1000).toISOString();
+ refreshed = true;
+ break;
+ }
+ if (!refreshed) throw new Error('credentialRejected');
+ }
+ const userResponse = await fetchFn(OAUTH_USER_URL, {
+ redirect: 'error', signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${accessToken}` },
+ });
+ if (!userResponse.ok) throw new Error(userResponse.status === 401 ? 'credentialRejected' : 'oauthUnavailable');
+ const user = await userResponse.json();
+ if (!user.email || user.verified_email === false) throw new Error('credentialRejected');
+ return {
+ email: user.email,
+ credential: {
+ token: { access_token: accessToken, refresh_token: refreshToken, token_type: 'Bearer', expiry },
+ auth_method: 'consumer',
+ id_token_email: user.email,
+ ...(idToken ? { id_token: idToken } : {}),
+ },
+ };
+}
+
+export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
+ async function post(method, data) {
+ for (const host of CLOUD_CODE_HOSTS) {
+ const response = await fetchFn(`https://${host}/v1internal:${method}`, {
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500),
+ headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify(data),
+ }).catch(() => null);
+ if (response?.ok) {
+ const payload = await response.json().catch(() => null);
+ if (payload) return payload.response ?? payload;
+ }
+ if (response?.status === 401 || response?.status === 403) break;
+ }
+ return null;
+ }
+
+ const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } });
+ const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject;
+ if (!setup) throw new Error('quotaUnavailable');
+ const request = {
+ project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise',
+ };
+ const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs;
+ const [summary, available] = await Promise.all([
+ post('retrieveUserQuotaSummary', request),
+ Array.isArray(clientConfigs) && clientConfigs.length ? null : post('fetchAvailableModels', request),
+ ]);
+ const configs = Array.isArray(clientConfigs) && clientConfigs.length ? clientConfigs :
+ Object.entries(available?.models || {}).filter(([, model]) => model?.quotaInfo && !model.disabled)
+ .map(([modelId, model]) => ({ modelId, modelOrAlias: { model: modelId }, label: model.displayName, quotaInfo: model.quotaInfo }));
+ const raw = summary?.quotaSummary ?? summary;
+ if (!Array.isArray(raw?.groups) && !Array.isArray(raw?.buckets) && !configs.length) throw new Error('quotaUnavailable');
+ const adaptBuckets = (buckets) => (Array.isArray(buckets) ? buckets : []).map((bucket) => ({
+ ...bucket,
+ bucketId: bucket?.bucketId ?? bucket?.bucket_id,
+ remainingFraction: bucket?.remainingFraction ?? bucket?.remaining_fraction,
+ resetTime: bucket?.resetTime ?? bucket?.reset_time,
+ }));
+ const quota = {
+ groups: (Array.isArray(raw?.groups) ? raw.groups : []).map((group) => ({
+ ...group, displayName: group?.displayName || group?.name, buckets: adaptBuckets(group?.buckets),
+ })),
+ buckets: adaptBuckets(raw?.buckets),
+ };
+ const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs);
+ return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
+ poolKey: pool.poolKey,
+ poolLabel: pool.poolLabel,
+ remainingPct: pool.remainingPct,
+ weeklyRemainingPct: pool.weeklyRemainingPct,
+ resetTime: pool.resetTime,
+ weeklyResetTime: pool.weeklyResetTime,
+ }));
+}
diff --git a/sidecars/panel/backend/account-switch.mjs b/sidecars/panel/backend/account-switch.mjs
new file mode 100644
index 0000000..3597e95
--- /dev/null
+++ b/sidecars/panel/backend/account-switch.mjs
@@ -0,0 +1,173 @@
+/** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */
+
+import { spawn } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs';
+import { HERE } from './config.mjs';
+import { callLsRpc } from './ls-rpc.mjs';
+
+const ACCOUNT_ERRORS = new Set([
+ 'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
+ 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
+ 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
+ 'oauthUnavailable', 'quotaUnavailable',
+]);
+
+export function normalizeAccountEmail(value) {
+ const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
+ return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : '';
+}
+
+export function normalizeAccountCredential(input) {
+ if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null;
+ const text = input.trim();
+ let source;
+ try { source = JSON.parse(text); } catch {
+ if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null;
+ source = { refresh_token: text };
+ }
+ const token = source?.token || source;
+ if (!token || (source.auth_method && source.auth_method !== 'consumer') ||
+ typeof token.refresh_token !== 'string' || !token.refresh_token.trim() ||
+ /\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null;
+ const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000);
+ const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
+ ? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z');
+ if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null;
+ const payload = {
+ token: {
+ access_token: typeof token.access_token === 'string' ? token.access_token : '',
+ refresh_token: token.refresh_token,
+ token_type: 'Bearer',
+ expiry: new Date(expiry).toISOString(),
+ },
+ auth_method: 'consumer',
+ };
+ const idToken = source.id_token || token.id_token;
+ if (typeof idToken === 'string' && idToken) payload.id_token = idToken;
+ return JSON.stringify(payload);
+}
+
+export function runWindowsCredentialStore(request) {
+ const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8');
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
+ const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+ return new Promise((resolve, reject) => {
+ // The helper exchanges private data over its pipes, keeping it out of process arguments.
+ const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
+ let output = '';
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => { output += chunk; });
+ child.on('error', reject);
+ child.stdin.on('error', reject);
+ child.on('close', (code) => {
+ if (code !== 0) return reject(new Error('storeFailed'));
+ try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); }
+ });
+ child.stdin.end(JSON.stringify(request), 'utf8');
+ });
+}
+
+function serializeHostCredential(credential) {
+ let payload = JSON.stringify(credential);
+ if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) {
+ const { id_token, ...compact } = credential;
+ payload = JSON.stringify(compact);
+ }
+ if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge');
+ return payload;
+}
+
+async function confirmHostCredential(email, rpc) {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ await rpc('GetAuthStatus', {}, 1200).catch(() => null);
+ const status = await rpc('GetUserStatus', {}, 1200).catch(() => null);
+ if (normalizeAccountEmail(status?.userStatus?.email) === email) return true;
+ if (attempt < 2) await delay(300);
+ }
+ return false;
+}
+
+export async function handleAccountCredentialAction(data, {
+ platform = process.platform,
+ store = runWindowsCredentialStore,
+ rpc = callLsRpc,
+ resolveCredential = resolveGoogleCredential,
+ getQuota = retrieveCredentialQuota,
+} = {}) {
+ if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' };
+ const action = data?.action || 'list';
+ if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' };
+ const email = normalizeAccountEmail(data?.email);
+ if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' };
+ const gemini = join(homedir(), '.gemini');
+ const config = {
+ target: 'gemini:antigravity',
+ vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'),
+ fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')],
+ };
+ async function runStore(fields) {
+ const result = await store({ ...config, ...fields });
+ if (!result || result.error) throw new Error(result?.error || 'storeFailed');
+ return result;
+ }
+
+ function publicList(result) {
+ return {
+ supported: true,
+ accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean),
+ selectedEmail: normalizeAccountEmail(result.selectedEmail),
+ };
+ }
+
+ async function verifyCredential(raw, refresh = false) {
+ const normalized = normalizeAccountCredential(raw);
+ if (!normalized) throw new Error('invalidCredential');
+ let result;
+ try {
+ result = await resolveCredential(JSON.parse(normalized), { refresh });
+ } catch (error) {
+ throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable');
+ }
+ result.email = normalizeAccountEmail(result.email);
+ if (!result.email) throw new Error('credentialRejected');
+ return result;
+ }
+
+ try {
+ if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email }));
+ if (action === 'save') {
+ const verified = await verifyCredential(data.credential, true);
+ return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) }));
+ }
+ if (action === 'capture') {
+ const status = await rpc('GetUserStatus', {}, 2000).catch(() => null);
+ const activeEmail = normalizeAccountEmail(status?.userStatus?.email);
+ if (!activeEmail) throw new Error('noCurrentCredential');
+ const { credential } = await runStore({ action: 'readCurrent' });
+ const verified = await verifyCredential(credential);
+ if (verified.email !== activeEmail) throw new Error('identityMismatch');
+ return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) }));
+ }
+
+ const saved = await runStore({ action: 'read', email });
+ const verified = await verifyCredential(saved.credential);
+ if (verified.email !== email) throw new Error('identityMismatch');
+ const credential = serializeHostCredential(verified.credential);
+ if (action === 'quota') {
+ if (credential !== saved.credential) {
+ await runStore({ action: 'save', email, credential, expectedCredential: saved.credential });
+ }
+ const pools = await getQuota(verified.credential.token.access_token);
+ return { email, pools };
+ }
+ const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential });
+ const confirmed = await confirmHostCredential(email, rpc);
+ return { ...publicList(updated), confirmed };
+ } catch (error) {
+ return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' };
+ }
+}
diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs
index 0778710..8374db0 100644
--- a/sidecars/panel/backend/api-actions.mjs
+++ b/sidecars/panel/backend/api-actions.mjs
@@ -8,6 +8,7 @@
import { readFileSync, promises as fsPromises } from 'node:fs';
import { join } from 'node:path';
+import { handleAccountCredentialAction } from './account-switch.mjs';
import {
HERE,
SETTINGS_FILE,
@@ -337,6 +338,16 @@ export async function executePluginUpdateAction() {
};
}
+export async function executeAccountCredentialAction(data) {
+ const result = await handleAccountCredentialAction(data);
+ return {
+ status: 200,
+ contentType: 'application/json',
+ headers: { 'Cache-Control': 'no-store' },
+ body: JSON.stringify(result),
+ };
+}
+
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
if (pathname === '/api/telemetry' && method === 'GET') {
return executeTelemetryAction(data, opts);
@@ -344,6 +355,12 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
if (pathname === '/api/settings' && method === 'POST') {
return executeSettingsAction(data);
}
+ if (pathname === '/api/accounts' && method === 'GET') {
+ return executeAccountCredentialAction();
+ }
+ if (pathname === '/api/accounts/update' && method === 'POST') {
+ return executeAccountCredentialAction(data);
+ }
if (pathname === '/api/context-window' && method === 'POST') {
return executeModelContextWindowAction(data);
}
diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs
index 260f2a9..3c78b59 100644
--- a/sidecars/panel/backend/config.mjs
+++ b/sidecars/panel/backend/config.mjs
@@ -170,15 +170,19 @@ export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken) {
/**
* GitHub 官方云端价格目录与插件发布包地址配置。
*/
+export const OFFICIAL_GITHUB_REPO = 'yuhuan-dev/antigravity-usage-monitor';
+export const LEGACY_GITHUB_REPOS = Object.freeze([
+ 'yuhuan2498281558/antigravity-usage-monitor',
+]);
export const CLOUD_CATALOG_URLS = [
- 'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
+ `https://raw.githubusercontent.com/${OFFICIAL_GITHUB_REPO}/main/pricing-catalog.json`,
];
export const DEFAULT_RELEASE_URL =
- 'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest';
+ `https://github.com/${OFFICIAL_GITHUB_REPO}/releases/latest`;
export const DEFAULT_DOWNLOAD_URL =
- 'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip';
+ `https://github.com/${OFFICIAL_GITHUB_REPO}/releases/latest/download/usage-monitor.zip`;
export const DEFAULT_ARCHIVE_FALLBACK_URL =
- 'https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main';
+ `https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`;
/** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
@@ -363,6 +367,7 @@ export const quotaSummaryCache = {
ts: 0,
lastAttemptTs: 0,
accountName: '',
+ accountGeneration: 0,
data: null,
error: null,
};
@@ -409,6 +414,7 @@ export function clearRuntimeCaches() {
quotaSummaryCache.ts = 0;
quotaSummaryCache.lastAttemptTs = 0;
quotaSummaryCache.accountName = '';
+ quotaSummaryCache.accountGeneration += 1;
quotaSummaryCache.data = null;
quotaSummaryCache.error = null;
return saveJson(CACHE_FILE, {});
diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs
index d9c40f0..198bc79 100644
--- a/sidecars/panel/backend/local-scanner.mjs
+++ b/sidecars/panel/backend/local-scanner.mjs
@@ -537,7 +537,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
*
* @param {{
* summariesObj?: Record,
- * currentAccountName?: string,
+ * currentAccountName?: string|null,
* requestedConvId?: string,
* forceRefresh?: boolean
* }} params
@@ -610,13 +610,11 @@ export async function enumerateAndSyncConversations({
}
// 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表
- for (const [cacheKey, entry] of Object.entries(trajectoryCache)) {
- const cacheKeyLower = String(cacheKey || '').toLowerCase();
+ for (const entry of Object.values(trajectoryCache)) {
if (
entry?.accountName &&
- currentAccountName &&
- entry.accountName !== currentAccountName &&
- !summariesByLower.has(cacheKeyLower)
+ currentAccountName !== '' &&
+ entry.accountName !== currentAccountName
) {
continue;
}
@@ -635,9 +633,8 @@ export async function enumerateAndSyncConversations({
const cached = trajectoryCache[cascadeId];
if (
cached?.accountName &&
- currentAccountName &&
- cached.accountName !== currentAccountName &&
- !item
+ currentAccountName !== '' &&
+ cached.accountName !== currentAccountName
) {
continue;
}
@@ -1262,8 +1259,9 @@ export async function enumerateAndSyncConversations({
))) ||
conversations[0] ||
null;
- const safeReqId =
- requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null;
+ const requestedOwner = trajectoryCache[canonicalIdByLower.get(reqLower)]?.accountName;
+ const safeReqId = requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) &&
+ (!requestedOwner || currentAccountName === '' || requestedOwner === currentAccountName) ? requestedConvId : null;
const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null;
return {
diff --git a/sidecars/panel/backend/ls-rpc.mjs b/sidecars/panel/backend/ls-rpc.mjs
index d2e1794..76170b1 100644
--- a/sidecars/panel/backend/ls-rpc.mjs
+++ b/sidecars/panel/backend/ls-rpc.mjs
@@ -122,9 +122,21 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
*
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
+ * @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
*/
-export async function getOfficialQuotaSummary(forceRefresh = false) {
+export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') {
+ if (quotaSummaryCache.accountName !== accountName) {
+ Object.assign(quotaSummaryCache, {
+ accountName,
+ accountGeneration: quotaSummaryCache.accountGeneration + 1,
+ ts: 0,
+ lastAttemptTs: 0,
+ data: null,
+ error: null,
+ });
+ }
+ const generation = quotaSummaryCache.accountGeneration;
const now = Date.now();
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) {
return {
@@ -155,6 +167,9 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
quotaSummaryCache.lastAttemptTs = now;
try {
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
+ const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000);
+ if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
+ if (generation !== quotaSummaryCache.accountGeneration) return {};
const payload = res?.response !== undefined ? res.response : res;
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
const normalized =
@@ -175,6 +190,7 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
}
quotaSummaryCache.error = 'Quota summary empty';
} catch (err) {
+ if (generation !== quotaSummaryCache.accountGeneration) return {};
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
quotaSummaryCache.error = err.message;
}
diff --git a/sidecars/panel/backend/plugin-updater.mjs b/sidecars/panel/backend/plugin-updater.mjs
index cba63ae..2533705 100644
--- a/sidecars/panel/backend/plugin-updater.mjs
+++ b/sidecars/panel/backend/plugin-updater.mjs
@@ -26,6 +26,9 @@ import {
DATA_DIR,
DEFAULT_ARCHIVE_FALLBACK_URL,
DEFAULT_DOWNLOAD_URL,
+ LEGACY_GITHUB_REPOS,
+ LS_ADDR,
+ OFFICIAL_GITHUB_REPO,
PLUGIN_ROOT,
REMOTE_CATALOG_CACHE_FILE,
cloudSyncState,
@@ -76,13 +79,8 @@ function runExecFile(cmd, args, opts = {}) {
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
*/
export function scheduleSidecarRestart(delayMs = 350) {
- if (
- !lsRuntimeEndpoint.addr ||
- lsRuntimeEndpoint.addr === 'test.invalid' ||
- typeof process?.exit !== 'function'
- ) {
- return;
- }
+ const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
+ if (!activeAddr || activeAddr === 'test.invalid' || typeof process?.exit !== 'function') return;
setTimeout(() => {
try {
process.exit(0);
@@ -164,13 +162,39 @@ function pruneExtraneousFiles(targetDir, referenceDir) {
}
}
+/**
+ * 若本地 Git 仓库的 `origin` 仍指向已迁移的旧官方仓库地址,返回同协议的新官方仓库地址;
+ * 对于非旧官方仓库(如已是新地址或用户自建 Fork)返回空字符串,不做改动。
+ *
+ * @param {string} rawUrl
+ * @returns {string}
+ */
+export function resolveMigratedGitRemoteUrl(rawUrl) {
+ const trimmed = String(rawUrl || '').trim();
+ if (!trimmed) return '';
+ for (const legacyRepo of LEGACY_GITHUB_REPOS) {
+ const escaped = legacyRepo.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ if (new RegExp(`^https://github\\.com/${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
+ return `https://github.com/${OFFICIAL_GITHUB_REPO}.git`;
+ }
+ if (new RegExp(`^git@github\\.com:${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
+ return `git@github.com:${OFFICIAL_GITHUB_REPO}.git`;
+ }
+ if (new RegExp(`^ssh://git@github\\.com/${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
+ return `ssh://git@github.com/${OFFICIAL_GITHUB_REPO}.git`;
+ }
+ }
+ return '';
+}
+
/**
* 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。
*
* @param {string} rootDir 插件根目录或解压目录
*/
async function verifyPluginJsSyntax(rootDir) {
- if (!lsRuntimeEndpoint.addr || lsRuntimeEndpoint.addr === 'test.invalid') return;
+ const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
+ if (!activeAddr || activeAddr === 'test.invalid') return;
const nodeBin = process?.execPath || 'node';
const filesToCheck = [
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
@@ -285,7 +309,31 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
const targetBranch = currentBranch || 'main';
const remoteRef = `origin/${targetBranch}`;
- // 3. 只读拉取远端分支引用,并严格从 origin/:plugin.json 读取远端版本号(严禁回退使用缓存版本)
+ // 3. 存量旧仓库远程地址平滑迁移:若 origin 仍指向已更换的旧官方仓库,自动切换至新仓库地址
+ try {
+ const remoteUrlRes = await runExecFile('git', [
+ '-C',
+ PLUGIN_ROOT,
+ 'remote',
+ 'get-url',
+ 'origin',
+ ]);
+ const migratedRemoteUrl = resolveMigratedGitRemoteUrl(remoteUrlRes.stdout);
+ if (migratedRemoteUrl) {
+ await runExecFile('git', [
+ '-C',
+ PLUGIN_ROOT,
+ 'remote',
+ 'set-url',
+ 'origin',
+ migratedRemoteUrl,
+ ]);
+ }
+ } catch {
+ // 忽略非标准 remote 配置异常,不阻断常规拉取
+ }
+
+ // 4. 只读拉取远端分支引用,并严格从 origin/:plugin.json 读取远端版本号(严禁回退使用缓存版本)
await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', targetBranch, '--tags']);
let remoteVersion = '';
@@ -306,7 +354,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
remoteVersion = '';
}
- // 4. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
+ // 5. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
if (!remoteVersion || compareSemver(remoteVersion, previousVersion) <= 0) {
const msg = `当前已是最新版本 (v${previousVersion})`;
const result = {
@@ -325,7 +373,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
return result;
}
- // 5. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
+ // 6. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
try {
await runExecFile('git', [
'-C',
@@ -351,7 +399,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
return pluginUpdateState.lastResult;
}
- // 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法
+ // 7. 确认全部门禁通过后,执行快进合并并校验 JS 语法
await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', targetBranch]);
await verifyPluginJsSyntax(PLUGIN_ROOT);
rebuildActiveCatalog();
diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs
index 7bedf78..6973592 100644
--- a/sidecars/panel/backend/pricing-catalog.mjs
+++ b/sidecars/panel/backend/pricing-catalog.mjs
@@ -16,7 +16,9 @@ import {
DEFAULT_ARCHIVE_FALLBACK_URL,
DEFAULT_DOWNLOAD_URL,
DEFAULT_RELEASE_URL,
+ LEGACY_GITHUB_REPOS,
LOCAL_CATALOG_FILE,
+ OFFICIAL_GITHUB_REPO,
PLUGIN_MANIFEST_FILE,
PLUGIN_ROOT,
REMOTE_CATALOG_CACHE_FILE,
@@ -44,7 +46,35 @@ export function isValidSemver(v) {
);
}
-const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
+const OFFICIAL_REPO_PATH_PREFIX = `/${OFFICIAL_GITHUB_REPO.toLowerCase()}`;
+const LEGACY_REPO_PATH_PREFIXES = LEGACY_GITHUB_REPOS.map((repo) => `/${repo.toLowerCase()}`);
+
+/**
+ * 判断来源 URL 是否属于已迁移的旧官方 GitHub 仓库地址。
+ *
+ * @param {*} rawUrl
+ * @returns {boolean}
+ */
+function isLegacyGithubRepoUrl(rawUrl) {
+ if (typeof rawUrl !== 'string' || !rawUrl.trim()) return false;
+ try {
+ const parsed = new URL(rawUrl.trim());
+ const host = parsed.hostname.toLowerCase();
+ const pathname = parsed.pathname.toLowerCase();
+ if (
+ host !== 'github.com' &&
+ host !== 'raw.githubusercontent.com' &&
+ host !== 'codeload.github.com'
+ ) {
+ return false;
+ }
+ return LEGACY_REPO_PATH_PREFIXES.some(
+ (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
+ );
+ } catch {
+ return false;
+ }
+}
/**
* 校验更新/下载链接是否属于可信的 GitHub 官方仓库与 HTTPS 域名白名单。
@@ -245,6 +275,8 @@ export function sanitizeCatalogPayload(raw) {
const explicitReleaseUrl = sanitizeTrustedGithubUrl(raw.releaseUrl, '');
const explicitDownloadUrl = sanitizeTrustedGithubUrl(raw.downloadUrl, '');
const explicitArchiveUrl = sanitizeTrustedGithubUrl(raw.archiveFallbackUrl, '');
+ const rawSourceUrl = typeof raw.sourceUrl === 'string' ? raw.sourceUrl.trim() : '';
+ const isLegacySource = isLegacyGithubRepoUrl(rawSourceUrl);
return {
schemaVersion: Number(raw.schemaVersion || 1),
@@ -261,8 +293,8 @@ export function sanitizeCatalogPayload(raw) {
hasReleaseUrl: Boolean(explicitReleaseUrl),
hasDownloadUrl: Boolean(explicitDownloadUrl),
hasArchiveFallbackUrl: Boolean(explicitArchiveUrl),
- fetchedAtMs: Number(raw.fetchedAtMs || 0),
- sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '',
+ fetchedAtMs: isLegacySource ? 0 : Number(raw.fetchedAtMs || 0),
+ sourceUrl: isLegacySource ? '' : rawSourceUrl,
pricing,
placeholders,
};
diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs
index ffc64b6..188cd36 100644
--- a/sidecars/panel/backend/telemetry-builder.mjs
+++ b/sidecars/panel/backend/telemetry-builder.mjs
@@ -20,7 +20,6 @@ import {
computeRuntimeCodeVersion,
inFlightRequests,
loadSettings,
- quotaSummaryCache,
roundMetric,
trajectoryCache,
} from './config.mjs';
@@ -393,39 +392,17 @@ export async function buildTelemetryPayloadInternal(
filterOpts = {}
) {
const settings = loadSettings();
- const [userStatusRes, allTrajRes, initialOfficialQuotaInfo, contextModelCatalog] = await Promise.all([
- callLsRpc('GetUserStatus', {}).catch(() => ({})),
+ const userStatus = await callLsRpc('GetUserStatus', {}).then((data) => data?.userStatus).catch(() => null);
+ const currentAccountName = userStatus?.email || userStatus?.name || '';
+ const accountStatus = currentAccountName ? 'signedIn' :
+ userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
+ const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
+ const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
- getOfficialQuotaSummary(forceQuotaRefresh),
+ userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
getContextModelCatalog(),
]);
- const userStatus = userStatusRes?.userStatus || {};
- const currentAccountName = userStatus?.email || userStatus?.name || '';
- let officialQuotaInfo = initialOfficialQuotaInfo;
-
- // 若检测到账号发生切换:仅当并发的 initialOfficialQuotaInfo 命中了旧账号本地缓存 (fromCache === true) 时才需清空并重刷;
- // 若本轮已经实时穿透请求了上游 RPC (fromCache === false),直接更新归属账号即可,避免二次重复 RPC
- const accountChanged = Boolean(
- currentAccountName &&
- quotaSummaryCache.accountName &&
- quotaSummaryCache.accountName !== currentAccountName
- );
- if (accountChanged) {
- if (initialOfficialQuotaInfo?.fromCache) {
- quotaSummaryCache.data = null;
- quotaSummaryCache.ts = 0;
- quotaSummaryCache.lastAttemptTs = 0;
- quotaSummaryCache.error = null;
- quotaSummaryCache.accountName = currentAccountName;
- officialQuotaInfo = await getOfficialQuotaSummary(true);
- } else {
- quotaSummaryCache.accountName = currentAccountName;
- }
- } else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) {
- quotaSummaryCache.accountName = currentAccountName;
- }
-
const officialQuota = officialQuotaInfo?.data || null;
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
@@ -439,7 +416,7 @@ export async function buildTelemetryPayloadInternal(
const { conversations, activeConvSummary, activeCascadeId } =
await enumerateAndSyncConversations({
summariesObj: allTrajRes?.trajectorySummaries || {},
- currentAccountName,
+ currentAccountName: accountScope,
requestedConvId,
forceRefresh: forceQuotaRefresh,
});
@@ -734,7 +711,7 @@ export async function buildTelemetryPayloadInternal(
} = aggregateMultiWindowUsage({
filterOpts,
cycleAnchors,
- currentAccountName,
+ currentAccountName: accountScope,
activeCascadeId,
activeFamilyCascadeIds,
resolveStepModel,
@@ -1081,6 +1058,8 @@ export async function buildTelemetryPayloadInternal(
}),
cloudStatus: getCloudStatus(),
account: {
+ status: accountStatus,
+ email: userStatus?.email || '',
name: userStatus?.name || '',
tierName: rawTierName || 'Google AI',
planName: resolvedPlanName,
diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs
index 2c0e25f..f8c2d96 100644
--- a/sidecars/panel/backend/usage-aggregator.mjs
+++ b/sidecars/panel/backend/usage-aggregator.mjs
@@ -187,7 +187,7 @@ function createUsageBucket() {
*
* @param {ReturnType} bucket
* @param {object} st 步骤对象
- * @param {ReturnType>} mInfo 模型信息
+ * @param {ReturnType} mInfo 模型信息
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
* @param {string} cascadeId 会话标识
*/
@@ -389,7 +389,7 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
* @param {{
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
- * currentAccountName?: string,
+ * currentAccountName?: string|null,
* activeCascadeId?: string|null,
* activeFamilyCascadeIds?: Set|null,
* resolveStepModel: StepModelResolver
@@ -502,9 +502,8 @@ export function aggregateMultiWindowUsage({
const ownerAccount = ext.accountName || knownLive?.accountName || '';
if (
ownerAccount &&
- currentAccountName &&
- ownerAccount !== currentAccountName &&
- !familySet.has(extCidLower)
+ currentAccountName !== '' &&
+ ownerAccount !== currentAccountName
) {
continue;
}
@@ -519,9 +518,8 @@ export function aggregateMultiWindowUsage({
for (const [cidLower, entry] of allLiveByLower.entries()) {
if (
entry?.accountName &&
- currentAccountName &&
- entry.accountName !== currentAccountName &&
- !familySet.has(cidLower)
+ currentAccountName !== '' &&
+ entry.accountName !== currentAccountName
) {
continue;
}
diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs
index f944449..31236fc 100644
--- a/sidecars/panel/backend/window-bridge.mjs
+++ b/sidecars/panel/backend/window-bridge.mjs
@@ -29,6 +29,8 @@ const ALLOWED_BRIDGE_PATHS = new Set([
'/api/telemetry',
'/api/settings',
'/api/settings/reset',
+ '/api/accounts',
+ '/api/accounts/update',
'/api/context-window',
'/api/cloud-sync',
'/api/plugin-update',
diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html
index a175730..daa8773 100644
--- a/sidecars/panel/index.html
+++ b/sidecars/panel/index.html
@@ -4,11 +4,11 @@
用量监控
-
+
-
+