mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): Antigravity IDE & composer mount, modular preferences, session charts, and per-model context windows (v1.5.0)
This commit is contained in:
@@ -2,5 +2,7 @@
|
||||
node_modules/
|
||||
plan/
|
||||
*.log
|
||||
*.dpapi
|
||||
.account-test-*
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@@ -0,0 +1,683 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
|
||||
## 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.
|
||||
+1
-1
@@ -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": [
|
||||
|
||||
@@ -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" },
|
||||
|
||||
+377
-13
@@ -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' | <subagent cascadeId>
|
||||
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
@@ -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,
|
||||
}));
|
||||
}
|
||||
@@ -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' };
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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, {});
|
||||
|
||||
@@ -537,7 +537,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
||||
*
|
||||
* @param {{
|
||||
* summariesObj?: Record<string, object>,
|
||||
* 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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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/<branch>: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/<branch>: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();
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -187,7 +187,7 @@ function createUsageBucket() {
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<ReturnType<typeof createStepModelResolver>>} mInfo 模型信息
|
||||
* @param {ReturnType<StepModelResolver>} 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<string>|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;
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1794673025095">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794722545161">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794673025095"></script>
|
||||
<script src="/app.js?v=1794722545161"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||
import {
|
||||
bootWindowBridgeRuntime,
|
||||
executeAccountCredentialAction,
|
||||
executeCloudSyncAction,
|
||||
executeModelContextWindowAction,
|
||||
executePluginUpdateAction,
|
||||
@@ -101,6 +102,24 @@ app.api('/api/settings', (data, req) => {
|
||||
return out.updated;
|
||||
});
|
||||
|
||||
async function serveAccountCredentials(data, req) {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeAccountCredentialAction(data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
|
||||
app.api('/api/accounts', (_data, req) => serveAccountCredentials(undefined, req), 'GET');
|
||||
app.api('/api/accounts/update', serveAccountCredentials, 'POST');
|
||||
|
||||
app.api('/api/context-window', async (data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "usage-monitor-panel",
|
||||
"version": "1.4.4",
|
||||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||
|
||||
@@ -484,6 +484,7 @@ export function buildBundle() {
|
||||
'src/components/settings/ThemeColorPicker.js',
|
||||
'src/views/settings/SettingsGeneralTab.js',
|
||||
'src/views/settings/SettingsStructureTab.js',
|
||||
'src/views/settings/SettingsAccountTab.js',
|
||||
'src/views/settings/SettingsOtherTab.js',
|
||||
'src/components/layout/TopSessionHeader.js',
|
||||
'src/views/LiveOverviewView.js',
|
||||
|
||||
@@ -57,7 +57,7 @@ export 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');
|
||||
@@ -79,7 +79,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);
|
||||
@@ -118,7 +118,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 8000 } = {}) {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||
|
||||
@@ -155,7 +155,7 @@ export 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 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ export 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');
|
||||
|
||||
@@ -287,7 +287,54 @@ export 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',
|
||||
|
||||
@@ -287,8 +287,55 @@ export 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': '保存失败',
|
||||
|
||||
@@ -689,6 +689,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
|
||||
@@ -866,6 +869,12 @@ export 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) {
|
||||
@@ -876,6 +885,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
}
|
||||
if (feedbackTimer) clearTimeout(feedbackTimer);
|
||||
telemetryStore.setState({
|
||||
...accountPatch,
|
||||
telemetry: payload,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: 'synced',
|
||||
@@ -888,6 +898,7 @@ export 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',
|
||||
|
||||
@@ -24,7 +24,7 @@ export function getViewTabs() {
|
||||
export const uiStore = createReactiveStore({
|
||||
activeView: 'overview',
|
||||
stepsSubTab: 'steps', // 'steps' | 'models'
|
||||
settingsSubTab: 'general', // 'general' | 'structure' | 'other'
|
||||
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
|
||||
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
|
||||
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
* 模块化偏好设置三栏样式表 (views-settings.css).
|
||||
* 模块化偏好设置样式表 (views-settings.css).
|
||||
* 包含:
|
||||
* 1. 顶部常规 / 结构 / 其他三栏切换导航条 (.settings-view-root, .settings-subnav-bar)
|
||||
* 1. 顶部偏好设置切换导航条 (.settings-view-root, .settings-subnav-bar)
|
||||
* 2. 主题强调色色卡选择器 (.theme-color-picker, .theme-host-chip, .theme-swatch-btn)
|
||||
* 3. 结构页手风琴折叠面板 (.collapsible-section, .collapsible-trigger, .collapsible-body)
|
||||
* 4. 通用 + / - / ↑ / ↓ 自添加排序列表 (.editable-slot-list, .editable-slot-row, .slot-add-btn)
|
||||
@@ -31,7 +31,8 @@
|
||||
.settings-subnav-bar .segmented {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(0, 1fr);
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
@@ -349,6 +350,60 @@
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.settings-account-identity {
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.settings-account-list,
|
||||
.settings-account-form,
|
||||
.settings-account-form label {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-list:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.settings-account-entry {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) 0;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-account-form label {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.settings-account-form input {
|
||||
min-width: 0;
|
||||
padding: var(--space-2);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
font: inherit;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-account-form button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.settings-account-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-quota {
|
||||
text-align: right;
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-context-model .select-option-meta {
|
||||
max-width: 62%;
|
||||
text-align: right;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @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.
|
||||
*/
|
||||
|
||||
@@ -11,14 +11,18 @@ import { telemetryStore } from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
|
||||
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
||||
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
||||
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
||||
|
||||
export 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') },
|
||||
];
|
||||
}
|
||||
@@ -48,25 +52,41 @@ export 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,
|
||||
@@ -76,6 +96,8 @@ export 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) {
|
||||
@@ -94,11 +116,14 @@ export 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);
|
||||
@@ -117,7 +142,7 @@ export const SettingsView = defineComponent({
|
||||
settingsSubTab: st.settingsSubTab,
|
||||
}),
|
||||
(slice) => {
|
||||
applyActiveSubTab(slice.settingsSubTab);
|
||||
applyActiveSubTab(slice.settingsSubTab, slice.activeView);
|
||||
if (slice.activeView === 'settings') {
|
||||
syncAllTabs(latestSettings, latestCloudStatus);
|
||||
}
|
||||
@@ -133,6 +158,7 @@ export const SettingsView = defineComponent({
|
||||
});
|
||||
generalTab.refs.refreshLabels();
|
||||
structureTab.refs.refreshLabels();
|
||||
accountTab.refs.refreshLabels();
|
||||
otherTab.refs.refreshLabels();
|
||||
refreshScroll();
|
||||
}
|
||||
@@ -145,6 +171,7 @@ export const SettingsView = defineComponent({
|
||||
subNavSwitch.destroy();
|
||||
generalTab.destroy();
|
||||
structureTab.destroy();
|
||||
accountTab.destroy();
|
||||
otherTab.destroy();
|
||||
viewScrollbar.destroy();
|
||||
});
|
||||
@@ -155,6 +182,7 @@ export const SettingsView = defineComponent({
|
||||
subNavSwitch,
|
||||
generalTab,
|
||||
structureTab,
|
||||
accountTab,
|
||||
otherTab,
|
||||
viewScrollbar,
|
||||
// Convenience aliases for external callers / tests
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
/** @fileoverview Saved account credentials and the host's active account quota. */
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchKeyedList, patchText } from '../../core/domPatch.js';
|
||||
import { callSidecarApi } from '../../core/httpClient.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { fetchTelemetry } from '../../store/telemetryStore.js';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export 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') } };
|
||||
},
|
||||
});
|
||||
@@ -3081,9 +3081,9 @@ input {
|
||||
|
||||
/* --- src/styles/views-settings.css --- */
|
||||
/*
|
||||
* 模块化偏好设置三栏样式表 (views-settings.css).
|
||||
* 模块化偏好设置样式表 (views-settings.css).
|
||||
* 包含:
|
||||
* 1. 顶部常规 / 结构 / 其他三栏切换导航条 (.settings-view-root, .settings-subnav-bar)
|
||||
* 1. 顶部偏好设置切换导航条 (.settings-view-root, .settings-subnav-bar)
|
||||
* 2. 主题强调色色卡选择器 (.theme-color-picker, .theme-host-chip, .theme-swatch-btn)
|
||||
* 3. 结构页手风琴折叠面板 (.collapsible-section, .collapsible-trigger, .collapsible-body)
|
||||
* 4. 通用 + / - / ↑ / ↓ 自添加排序列表 (.editable-slot-list, .editable-slot-row, .slot-add-btn)
|
||||
@@ -3113,7 +3113,8 @@ input {
|
||||
.settings-subnav-bar .segmented {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(0, 1fr);
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
@@ -3431,6 +3432,60 @@ input {
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.settings-account-identity {
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.settings-account-list,
|
||||
.settings-account-form,
|
||||
.settings-account-form label {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-list:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.settings-account-entry {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) 0;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-account-form label {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.settings-account-form input {
|
||||
min-width: 0;
|
||||
padding: var(--space-2);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
font: inherit;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-account-form button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.settings-account-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-quota {
|
||||
text-align: right;
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-context-model .select-option-meta {
|
||||
max-width: 62%;
|
||||
text-align: right;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, rmdir, unlink } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveGoogleCredential, retrieveCredentialQuota } from '../backend/account-oauth.mjs';
|
||||
import { handleAccountCredentialAction, normalizeAccountCredential, runWindowsCredentialStore } from '../backend/account-switch.mjs';
|
||||
|
||||
test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => {
|
||||
const refreshToken = '1//synthetic-refresh-token-for-test';
|
||||
assert.deepEqual(JSON.parse(normalizeAccountCredential(refreshToken)), {
|
||||
auth_method: 'consumer',
|
||||
token: { access_token: '', token_type: 'Bearer', refresh_token: refreshToken, expiry: '1970-01-01T00:00:00.000Z' },
|
||||
});
|
||||
const saved = JSON.parse(normalizeAccountCredential(JSON.stringify({
|
||||
token: { refresh_token: refreshToken, access_token: 'example-access', expiry_timestamp: 1800000000 },
|
||||
})));
|
||||
assert.equal(saved.token.access_token, 'example-access');
|
||||
assert.equal(saved.token.expiry, '2027-01-15T08:00:00.000Z');
|
||||
assert.equal(normalizeAccountCredential(JSON.stringify({ auth_method: 'enterprise', refresh_token: refreshToken })), null);
|
||||
assert.equal(normalizeAccountCredential('example-api-key'), null);
|
||||
});
|
||||
|
||||
test('import uses the verified email and switches only after checking the credential identity', async () => {
|
||||
const calls = [];
|
||||
const input = '1//synthetic-refresh-token-for-test';
|
||||
const credential = JSON.parse(normalizeAccountCredential(input));
|
||||
const saved = JSON.stringify(credential);
|
||||
let verifiedEmail = 'Next@example.com';
|
||||
const options = {
|
||||
platform: 'win32',
|
||||
resolveCredential: async (_credential, opts) => {
|
||||
calls.push(opts.refresh ? 'refresh-identity' : 'verify-identity');
|
||||
return { email: verifiedEmail, credential };
|
||||
},
|
||||
rpc: async (method) => {
|
||||
calls.push(method);
|
||||
return { userStatus: { email: 'Next@example.com' } };
|
||||
},
|
||||
store: async (request) => {
|
||||
calls.push(request.action);
|
||||
if (request.action === 'read') return { credential: saved };
|
||||
assert.equal(request.target, 'gemini:antigravity');
|
||||
assert.equal(request.email, 'next@example.com');
|
||||
if (request.action === 'switch') assert.equal(request.expectedCredential, saved);
|
||||
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved };
|
||||
},
|
||||
};
|
||||
assert.deepEqual(await handleAccountCredentialAction({ action: 'save', email: 'ignored@example.com', credential: input }, options), {
|
||||
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com',
|
||||
});
|
||||
assert.deepEqual(calls.splice(0), ['refresh-identity', 'save']);
|
||||
const result = await handleAccountCredentialAction({ action: 'switch', email: 'NEXT@example.com' }, options);
|
||||
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', confirmed: true });
|
||||
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'switch', 'GetAuthStatus', 'GetUserStatus']);
|
||||
verifiedEmail = 'different@example.com';
|
||||
assert.deepEqual(await handleAccountCredentialAction({ action: 'switch', email: 'next@example.com' }, options), { error: 'identityMismatch' });
|
||||
assert.deepEqual(calls, ['read', 'verify-identity']);
|
||||
});
|
||||
|
||||
test('a saved credential can query its quota without replacing the active login', async () => {
|
||||
const credential = normalizeAccountCredential(JSON.stringify({ refresh_token: 'test', access_token: 'saved-access' }));
|
||||
const pools = [{ poolKey: 'Gemini', remainingPct: 0, weeklyRemainingPct: 29 }];
|
||||
const result = await handleAccountCredentialAction({ action: 'quota', email: 'next@example.com' }, {
|
||||
platform: 'win32',
|
||||
store: async (request) => {
|
||||
assert.equal(request.action, 'read');
|
||||
return { credential };
|
||||
},
|
||||
resolveCredential: async (stored) => ({ email: 'next@example.com', credential: stored }),
|
||||
getQuota: async (token) => {
|
||||
assert.equal(token, 'saved-access');
|
||||
return pools;
|
||||
},
|
||||
});
|
||||
assert.deepEqual(result, { email: 'next@example.com', pools });
|
||||
});
|
||||
|
||||
test('Google OAuth confirms the email and the same account token retrieves quota pools', async () => {
|
||||
const endpoints = [];
|
||||
const refreshToken = 'first-refresh';
|
||||
const token = { access_token: 'new-access', refresh_token: 'latest-refresh', expires_in: 3600 };
|
||||
const fetchFn = async (url, request) => {
|
||||
endpoints.push(url);
|
||||
assert.equal(request.redirect, 'error');
|
||||
if (url.endsWith('/token')) {
|
||||
assert.equal(request.body.get('refresh_token'), refreshToken);
|
||||
return { ok: true, json: async () => token };
|
||||
}
|
||||
assert.equal(request.headers.Authorization, 'Bearer new-access');
|
||||
if (url.endsWith('/userinfo')) return { ok: true, json: async () => ({ email: 'owner@example.com', verified_email: true }) };
|
||||
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: { id: 'test-project' } }) };
|
||||
assert.equal(JSON.parse(request.body).project, 'test-project');
|
||||
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
|
||||
assert.match(url, /:retrieveUserQuotaSummary$/);
|
||||
return { ok: true, json: async () => ({ response: { quotaSummary: { groups: [
|
||||
{ name: 'Gemini Models', buckets: [{ window: '5h', remaining_fraction: 0 }, { window: 'weekly', remainingFraction: 0.29 }] },
|
||||
] } } }) };
|
||||
};
|
||||
const resolved = await resolveGoogleCredential({ token: { refresh_token: refreshToken } }, {
|
||||
fetchFn, getClients: async () => [{ id: 'desktop-client', secret: 'test-config' }],
|
||||
});
|
||||
assert.equal(resolved.email, 'owner@example.com');
|
||||
assert.equal(resolved.credential.token.refresh_token, token.refresh_token);
|
||||
const pools = await retrieveCredentialQuota(resolved.credential.token.access_token, fetchFn);
|
||||
assert.deepEqual(pools.map(({ poolKey, remainingPct, weeklyRemainingPct }) => [poolKey, remainingPct, weeklyRemainingPct]), [['Gemini', 0, 29]]);
|
||||
assert.equal(endpoints.length, 5);
|
||||
});
|
||||
|
||||
test('Windows vault atomically saves, reloads and removes encrypted entries', { skip: process.platform !== 'win32' }, async () => {
|
||||
const directory = await mkdtemp(fileURLToPath(new URL('../.account-test-', import.meta.url)));
|
||||
const vault = join(directory, 'test.dpapi');
|
||||
const run = (action, email, credential) => runWindowsCredentialStore({ action, email, credential, vault });
|
||||
try {
|
||||
const credential = normalizeAccountCredential('1//synthetic-refresh-token-for-test');
|
||||
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '' });
|
||||
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '' });
|
||||
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
|
||||
assert.deepEqual(await run('read', 'next@example.com'), { credential });
|
||||
assert.deepEqual(await runWindowsCredentialStore({ action: 'save', email: 'next@example.com', credential, expectedCredential: 'stale', vault }), { error: 'credentialChanged' });
|
||||
assert.equal((await readFile(vault)).includes('synthetic-refresh-token-for-test'), false);
|
||||
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
|
||||
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '' });
|
||||
} finally {
|
||||
await unlink(vault).catch((err) => { if (err.code !== 'ENOENT') throw err; });
|
||||
await rmdir(directory);
|
||||
}
|
||||
});
|
||||
@@ -15,6 +15,8 @@ const DEFAULT_BUNDLED_CATALOG = {
|
||||
|
||||
const BACKEND_MODULE_FILES = [
|
||||
'../backend/context-windows.mjs',
|
||||
'../backend/account-oauth.mjs',
|
||||
'../backend/account-switch.mjs',
|
||||
'../backend/settings-schema.mjs',
|
||||
'../backend/config.mjs',
|
||||
'../backend/ls-discovery.mjs',
|
||||
@@ -144,7 +146,7 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data||{}};
|
||||
}
|
||||
if(method==='RetrieveUserQuotaSummary') {
|
||||
const qs=state.quotaSummary;
|
||||
const qs=await state.quotaSummary;
|
||||
if(qs instanceof Error) throw qs;
|
||||
return {ok:true,json:async()=>({response:qs})};
|
||||
}
|
||||
@@ -152,6 +154,6 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs
|
||||
assert.ok(sanitized);
|
||||
assert.equal(sanitized.catalogVersion, '2026.11.03.9');
|
||||
assert.equal(sanitized.latestPluginVersion, '1.5.0');
|
||||
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan2498281558/'));
|
||||
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan-dev/'));
|
||||
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
|
||||
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
|
||||
});
|
||||
@@ -94,7 +94,7 @@ test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newl
|
||||
|
||||
// Sync cloud catalog from GitHub
|
||||
const syncStatus = await h.syncCloudCatalog({ force: true });
|
||||
assert.ok(fetchedUrl.startsWith('https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json'));
|
||||
assert.ok(fetchedUrl.startsWith('https://raw.githubusercontent.com/yuhuan-dev/antigravity-usage-monitor/main/pricing-catalog.json'));
|
||||
assert.equal(syncStatus.source, 'remote');
|
||||
assert.equal(syncStatus.catalogVersion, '2026.11.03.2');
|
||||
assert.equal(syncStatus.latestPluginVersion, '1.5.0');
|
||||
@@ -273,7 +273,103 @@ test('performPluginUpdate pulls fast-forward when git worktree is clean, on main
|
||||
assert.equal(res.mode, 'git');
|
||||
assert.equal(res.previousVersion, '1.3.1');
|
||||
assert.equal(res.currentVersion, '1.4.0');
|
||||
assert.equal(gitCalls.length, 6); // status, rev-parse, fetch, show, merge-base, pull
|
||||
assert.equal(gitCalls.length, 7); // status, rev-parse, remote get-url, fetch, show, merge-base, pull
|
||||
});
|
||||
|
||||
test('repository migration: scrubs legacy yuhuan2498281558 cache URLs/TTL and migrates git origin remote to yuhuan-dev', async () => {
|
||||
let fetchedNewRepoUrl = '';
|
||||
const cacheH = backendHarness({
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.4' },
|
||||
remoteCatalog: {
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.11.4',
|
||||
updatedAt: '2026-11-11T23:20: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',
|
||||
sourceUrl: 'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
|
||||
fetchedAtMs: Date.now() - 60_000,
|
||||
pricing: {
|
||||
'gemini-4-carbon-high': { input: 2.0, cache: 0.1, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
|
||||
},
|
||||
},
|
||||
remoteFetch: async (url) => {
|
||||
fetchedNewRepoUrl = String(url);
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.12.1',
|
||||
updatedAt: '2026-11-12T10:00:00+09:00',
|
||||
latestPluginVersion: '1.4.5',
|
||||
pricing: {
|
||||
'gemini-4-carbon-high': { input: 2.0, cache: 0.1, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const initialStatus = cacheH.getCloudStatus();
|
||||
assert.equal(initialStatus.releaseUrl, 'https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest');
|
||||
assert.equal(initialStatus.downloadUrl, 'https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip');
|
||||
assert.equal(initialStatus.lastSyncedAtMs, 0, 'legacy repo cache TTL must be invalidated so new repo syncs immediately');
|
||||
|
||||
const synced = await cacheH.syncCloudCatalog({ force: false });
|
||||
assert.equal(
|
||||
fetchedNewRepoUrl,
|
||||
'https://raw.githubusercontent.com/yuhuan-dev/antigravity-usage-monitor/main/pricing-catalog.json'
|
||||
);
|
||||
assert.equal(synced.catalogVersion, '2026.11.12.1');
|
||||
assert.equal(synced.latestPluginVersion, '1.4.5');
|
||||
|
||||
assert.equal(
|
||||
cacheH.resolveMigratedGitRemoteUrl('https://github.com/yuhuan2498281558/antigravity-usage-monitor.git'),
|
||||
'https://github.com/yuhuan-dev/antigravity-usage-monitor.git'
|
||||
);
|
||||
assert.equal(
|
||||
cacheH.resolveMigratedGitRemoteUrl('git@github.com:yuhuan2498281558/antigravity-usage-monitor.git'),
|
||||
'git@github.com:yuhuan-dev/antigravity-usage-monitor.git'
|
||||
);
|
||||
assert.equal(
|
||||
cacheH.resolveMigratedGitRemoteUrl('https://github.com/custom-fork/antigravity-usage-monitor.git'),
|
||||
''
|
||||
);
|
||||
|
||||
const gitCalls = [];
|
||||
const migrateH = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.3' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('remote') && args.includes('get-url')) {
|
||||
fn(null, 'https://github.com/yuhuan2498281558/antigravity-usage-monitor.git\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
fn(null, JSON.stringify({ name: 'usage-monitor', version: '1.4.4' }), '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('pull')) {
|
||||
migrateH.state.pluginManifest = { name: 'usage-monitor', version: '1.4.4' };
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const updRes = await migrateH.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(updRes.ok, true);
|
||||
assert.equal(updRes.currentVersion, '1.4.4');
|
||||
const setUrlCall = gitCalls.find((args) => args.includes('remote') && args.includes('set-url'));
|
||||
assert.ok(setUrlCall, 'must run git remote set-url origin before fetching');
|
||||
assert.equal(setUrlCall[setUrlCall.length - 1], 'https://github.com/yuhuan-dev/antigravity-usage-monitor.git');
|
||||
});
|
||||
|
||||
test('pluginUpdateMode supports manual (default), auto, and off with legacy autoUpdatePlugin compatibility', async () => {
|
||||
|
||||
@@ -402,6 +402,36 @@ test('switching accounts within 10s immediately invalidates quotaSummaryCache',
|
||||
assert.equal(second.quotas.pools[0].weeklyRemainingPct, 8.7);
|
||||
});
|
||||
|
||||
test('late quota results from another account cannot replace the current account cache', async () => {
|
||||
const quota = (remainingFraction) => ({ groups: [{
|
||||
displayName: 'Gemini Models',
|
||||
buckets: [{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction }],
|
||||
}] });
|
||||
const pro = { name: 'Same name', userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' } };
|
||||
let resolvePrevious;
|
||||
const h = backendHarness({
|
||||
userStatus: { ...pro, email: 'a@example.com' },
|
||||
quotaSummary: new Promise((resolve) => { resolvePrevious = resolve; }),
|
||||
});
|
||||
const previous = h.buildTelemetryPayloadInternal('none');
|
||||
while (!h.state.calls.some(({ method }) => method === 'RetrieveUserQuotaSummary')) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
h.state.userStatus = { ...pro, email: 'b@example.com' };
|
||||
h.state.quotaSummary = quota(0.24);
|
||||
const switched = await h.buildTelemetryPayloadInternal('none');
|
||||
assert.equal(switched.account.email, 'b@example.com');
|
||||
assert.equal(switched.quotas.pools.find(({ poolKey }) => poolKey === 'Gemini').weeklyRemainingPct, 24);
|
||||
|
||||
resolvePrevious(quota(0.75));
|
||||
const stale = await previous;
|
||||
assert.equal(stale.quotas.meta.hasOfficialData, false);
|
||||
const refreshed = await h.buildTelemetryPayloadInternal('none');
|
||||
assert.equal(refreshed.account.email, 'b@example.com');
|
||||
assert.equal(refreshed.quotas.pools.find(({ poolKey }) => poolKey === 'Gemini').weeklyRemainingPct, 24);
|
||||
});
|
||||
|
||||
test('Orchestrator quota pool binding follows active phase: Carbon/Argon while planning, Gemini when offloaded to Hydrogen', async () => {
|
||||
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
||||
const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681';
|
||||
|
||||
@@ -317,9 +317,9 @@ test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on vers
|
||||
}
|
||||
const ctx = windowContexts.get(this.targetId);
|
||||
const value = vm.runInContext(expr, ctx);
|
||||
queueMicrotask(() =>
|
||||
Promise.resolve(value).then((result) =>
|
||||
this._emit('message', {
|
||||
data: JSON.stringify({ id: msg.id, result: { result: { value } } }),
|
||||
data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }),
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -337,11 +337,13 @@ test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on vers
|
||||
res.end(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 'win1',
|
||||
type: 'page',
|
||||
url: 'https://127.0.0.1:61001/c/11111111-1111-1111-1111-111111111111',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win1`,
|
||||
},
|
||||
{
|
||||
id: 'win2',
|
||||
type: 'page',
|
||||
url: 'https://127.0.0.1:61002/c/22222222-2222-2222-2222-222222222222',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win2`,
|
||||
@@ -705,6 +707,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
|
||||
let reloadCalled = false;
|
||||
let currentBundleVer = 'ver-100';
|
||||
let currentAccountEmail = 'test@example.com';
|
||||
let liveSubagentPollActive = false;
|
||||
const fetchedUrls = [];
|
||||
const fetchedHeaders = [];
|
||||
@@ -769,6 +772,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
};
|
||||
const mockSettings = { ...defaultMockSettings };
|
||||
let cacheRebuildCalls = 0;
|
||||
let selectedEmail = '';
|
||||
const accountRequests = [];
|
||||
|
||||
const mockWindow = {
|
||||
innerWidth: 1440,
|
||||
@@ -796,6 +801,17 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const urlStr = String(url);
|
||||
fetchedUrls.push(urlStr);
|
||||
fetchedHeaders.push(opts.headers || {});
|
||||
if (urlStr.endsWith('/api/accounts') || urlStr.endsWith('/api/accounts/update')) {
|
||||
if (opts.method === 'POST') {
|
||||
const update = JSON.parse(opts.body);
|
||||
accountRequests.push(update);
|
||||
if (update.action === 'quota') {
|
||||
return { ok: true, status: 200, json: async () => ({ email: update.email, pools: [{ poolKey: 'Gemini', remainingPct: 70 }] }) };
|
||||
}
|
||||
if (update.action === 'switch') selectedEmail = update.email;
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ supported: true, accounts: ['next@example.com'], selectedEmail }) };
|
||||
}
|
||||
if (urlStr.includes('/api/settings/reset') && String(opts.method || '').toUpperCase() === 'POST') {
|
||||
for (const k of Object.keys(mockSettings)) delete mockSettings[k];
|
||||
Object.assign(mockSettings, {
|
||||
@@ -856,7 +872,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
{ id: 'MODEL_PLACEHOLDER_M432', label: 'Other', options: [] },
|
||||
],
|
||||
cloudStatus: { updateAvailable: true, currentPluginVersion: '1.4.2', latestPluginVersion: '1.5.0' },
|
||||
account: { tierName: 'Google AI Ultra', planName: 'Pro', totalConversations: 5 },
|
||||
account: { status: 'signedIn', email: currentAccountEmail, tierName: 'Google AI Ultra', planName: 'Pro', totalConversations: 5 },
|
||||
runningConversations: [
|
||||
{
|
||||
cascadeId: 'bbbbbbbb-2222-3333-4444-cccccccccccc',
|
||||
@@ -1195,7 +1211,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
poolKey: 'Gemini',
|
||||
poolLabel: 'Gemini',
|
||||
usedPct: 56,
|
||||
remainingPct: 44,
|
||||
remainingPct: currentAccountEmail === 'test@example.com' ? 44 : 0,
|
||||
resetTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
|
||||
weeklyUsedPct: 74,
|
||||
weeklyRemainingPct: 26,
|
||||
@@ -1419,7 +1435,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath');
|
||||
selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
|
||||
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) & decoupled registries
|
||||
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) with Account tab hidden
|
||||
const pillTabs = popoverEl.querySelectorAll('.pill-tab');
|
||||
pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
@@ -1427,10 +1443,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const allPanes = popoverEl.querySelectorAll('.view-pane');
|
||||
const settingsRoot = popoverEl.querySelector('.settings-view-root');
|
||||
const subNavBtns = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn');
|
||||
assert.equal(subNavBtns.length, 3, 'SettingsView renders 3 sub-tabs: 常规 / 结构 / 其他');
|
||||
assert.equal(subNavBtns[0].textContent, '常规');
|
||||
assert.equal(subNavBtns[1].textContent, '结构');
|
||||
assert.equal(subNavBtns[2].textContent, '其他');
|
||||
assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '其他']);
|
||||
assert.match(
|
||||
stylesCss,
|
||||
/\.settings-subnav-bar\s+\.segmented\s*\{[^}]*grid-auto-flow:\s*column;[^}]*grid-auto-columns:\s*minmax\(0,\s*1fr\);/,
|
||||
'Settings subnav uses auto-sized equal columns regardless of visible tab count'
|
||||
);
|
||||
const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
|
||||
assert.equal(generalPane.hasAttribute('hidden'), false, 'General tab active by default');
|
||||
assert.equal(structurePane.hasAttribute('hidden'), true);
|
||||
@@ -1746,7 +1764,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.equal(mockSettings.stepTableColumns.length, 7);
|
||||
|
||||
// --- Tab 2: 其他 (modelFormat, orchestratorId, contextBaseline reserved pill, cache rebuild, reset all) ---
|
||||
// --- 其他 (model format, context limits, cache rebuild, reset) ---
|
||||
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
assert.equal(otherPane.hasAttribute('hidden'), false);
|
||||
@@ -2179,6 +2197,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
|
||||
// Verify bundle version bump NEVER calls window.location.reload() in overlay mode
|
||||
currentBundleVer = 'ver-200';
|
||||
currentAccountEmail = 'next@example.com';
|
||||
mockLocation.pathname = '/c/cccccccc-4444-5555-6666-dddddddddddd';
|
||||
for (const fn of winListeners.get('popstate') || []) fn({});
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
@@ -2369,6 +2388,7 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
// Live Antigravity IDE CDP server exposing workbench.html + workbench-jetski-agent.html + ignored sharedProcess.html
|
||||
const ideContextObj = {
|
||||
location: { pathname: '/out/vs/code/electron-browser/workbench/workbench.html' },
|
||||
setTimeout,
|
||||
document: {
|
||||
querySelector(sel) {
|
||||
if (sel.includes('conversation-view')) {
|
||||
|
||||
Reference in New Issue
Block a user