Add local repo contents

This commit is contained in:
willchen96 2026-04-29 19:49:06 +02:00
parent 65739ef1ce
commit d9690965b5
176 changed files with 68998 additions and 0 deletions

18
.gitignore vendored Normal file
View file

@ -0,0 +1,18 @@
node_modules
.next
dist
out
build
.open-next
.env
.env.*
!.env.example
!.env.local.example
*.log
*.tsbuildinfo
next-env.d.ts
.DS_Store
.vercel
coverage

661
LICENSE Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

60
README.md Normal file
View file

@ -0,0 +1,60 @@
# Mike
Open-source release containing the Mike frontend and backend.
## Contents
- `frontend/` - Next.js application
- `backend/` - Express API, Supabase access, document processing, and migrations
- `backend/migrations/000_one_shot_schema.sql` - one-shot Supabase schema for fresh databases
## Setup
Install dependencies:
```bash
npm install --prefix backend
npm install --prefix frontend
```
Create local env files from the examples:
```bash
cp backend/.env.example backend/.env
cp frontend/.env.local.example frontend/.env.local
```
Run `backend/migrations/000_one_shot_schema.sql` in the Supabase SQL editor for a fresh database.
Start the backend:
```bash
npm run dev --prefix backend
```
Start the frontend:
```bash
npm run dev --prefix frontend
```
Open `http://localhost:3000`.
## Required Services
- Supabase Auth and Postgres
- S3-compatible object storage, such as Cloudflare R2
- At least one supported model provider key, depending on which models you enable
- LibreOffice for DOC/DOCX to PDF conversion
## Checks
```bash
npm run build --prefix backend
npm run build --prefix frontend
npm run lint --prefix frontend
```
## License
AGPL-3.0-only. See `LICENSE`.

14
backend/.env.example Normal file
View file

@ -0,0 +1,14 @@
PORT=3001
FRONTEND_URL=http://localhost:3000
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SECRET_KEY=your-supabase-service-role-key
R2_ENDPOINT_URL=https://your-account-id.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=your-r2-access-key
R2_SECRET_ACCESS_KEY=your-r2-secret-key
R2_BUCKET_NAME=mike
GEMINI_API_KEY=your-gemini-key
ANTHROPIC_API_KEY=your-anthropic-key
OPENROUTER_API_KEY=your-openrouter-key
RESEND_API_KEY=your-resend-key

6
backend/.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
node_modules
dist
.env*
!.env.example
*.log
.DS_Store

768
backend/bun.lock Normal file
View file

@ -0,0 +1,768 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "mike-backend",
"dependencies": {
"@anthropic-ai/sdk": "^0.90.0",
"@aws-sdk/client-s3": "^3.787.0",
"@aws-sdk/s3-request-presigner": "^3.787.0",
"@google/genai": "^1.50.1",
"@supabase/supabase-js": "^2.49.4",
"cors": "^2.8.5",
"docx": "^9.5.0",
"dotenv": "^17.4.1",
"express": "^4.21.2",
"fast-diff": "^1.3.0",
"fast-xml-parser": "^5.7.1",
"jszip": "^3.10.1",
"libreoffice-convert": "^1.6.0",
"mammoth": "^1.9.0",
"multer": "^1.4.5-lts.2",
"pdfjs-dist": "^4.10.38",
"resend": "^4.5.1",
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/multer": "^1.4.12",
"@types/node": "^22.14.1",
"prettier": "^3.8.1",
"tsx": "^4.19.3",
"typescript": "^5.8.3",
},
},
},
"packages": {
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.90.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-MzZtPabJF1b0FTDl6Z6H5ljphPwACLGP13lu8MTiB8jXaW/YXlpOp+Po2cVou3MPM5+f5toyLnul9whKCy7fBg=="],
"@aws-crypto/crc32": ["@aws-crypto/crc32@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg=="],
"@aws-crypto/crc32c": ["@aws-crypto/crc32c@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag=="],
"@aws-crypto/sha1-browser": ["@aws-crypto/sha1-browser@5.2.0", "", { "dependencies": { "@aws-crypto/supports-web-crypto": "^5.2.0", "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "@aws-sdk/util-locate-window": "^3.0.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg=="],
"@aws-crypto/sha256-browser": ["@aws-crypto/sha256-browser@5.2.0", "", { "dependencies": { "@aws-crypto/sha256-js": "^5.2.0", "@aws-crypto/supports-web-crypto": "^5.2.0", "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "@aws-sdk/util-locate-window": "^3.0.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw=="],
"@aws-crypto/sha256-js": ["@aws-crypto/sha256-js@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA=="],
"@aws-crypto/supports-web-crypto": ["@aws-crypto/supports-web-crypto@5.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg=="],
"@aws-crypto/util": ["@aws-crypto/util@5.2.0", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="],
"@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.1026.0", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/credential-provider-node": "^3.972.30", "@aws-sdk/middleware-bucket-endpoint": "^3.972.9", "@aws-sdk/middleware-expect-continue": "^3.972.9", "@aws-sdk/middleware-flexible-checksums": "^3.974.7", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-location-constraint": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-sdk-s3": "^3.972.28", "@aws-sdk/middleware-ssec": "^3.972.9", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/signature-v4-multi-region": "^3.996.16", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/eventstream-serde-browser": "^4.2.13", "@smithy/eventstream-serde-config-resolver": "^4.3.13", "@smithy/eventstream-serde-node": "^4.2.13", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-blob-browser": "^4.2.14", "@smithy/hash-node": "^4.2.13", "@smithy/hash-stream-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/md5-js": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-stream": "^4.5.22", "@smithy/util-utf8": "^4.2.2", "@smithy/util-waiter": "^4.2.15", "tslib": "^2.6.2" } }, "sha512-tMP+s641FLSXdJazvYvuf38F7suWWv+wagTvShykPTffuFpBj5J9f7Rw0eKsauBcsjPSntiwBz9Gm0Tlh+cKfQ=="],
"@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="],
"@aws-sdk/crc64-nvme": ["@aws-sdk/crc64-nvme@3.972.6", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-NMbiqKdruhwwgI6nzBVe2jWMkXjaoQz2YOs3rFX+2F3gGyrJDkDPwMpV/RsTFeq2vAQ055wZNtOXFK4NYSkM8g=="],
"@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.25", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6QfI0wv4jpG5CrdO/AO0JfZ2ux+tKwJPrUwmvxXF50vI5KIypKVGNF6b4vlkYEnKumDTI1NX2zUBi8JoU5QU3A=="],
"@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.27", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/node-http-handler": "^4.5.2", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-stream": "^4.5.22", "tslib": "^2.6.2" } }, "sha512-3V3Usj9Gs93h865DqN4M2NWJhC5kXU9BvZskfN3+69omuYlE3TZxOEcVQtBGLOloJB7BVfJKXVLqeNhOzHqSlQ=="],
"@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/credential-provider-env": "^3.972.25", "@aws-sdk/credential-provider-http": "^3.972.27", "@aws-sdk/credential-provider-login": "^3.972.29", "@aws-sdk/credential-provider-process": "^3.972.25", "@aws-sdk/credential-provider-sso": "^3.972.29", "@aws-sdk/credential-provider-web-identity": "^3.972.29", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-SiBuAnXecCbT/OpAf3vqyI/AVE3mTaYr9ShXLybxZiPLBiPCCOIWSGAtYYGQWMRvobBTiqOewaB+wcgMMZI2Aw=="],
"@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-OGOslTbOlxXexKMqhxCEbBQbUIfuhGxU5UXw3Fm56ypXHvrXH4aTt/xb5Y884LOoteP1QST1lVZzHfcTnWhiPQ=="],
"@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.30", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.25", "@aws-sdk/credential-provider-http": "^3.972.27", "@aws-sdk/credential-provider-ini": "^3.972.29", "@aws-sdk/credential-provider-process": "^3.972.25", "@aws-sdk/credential-provider-sso": "^3.972.29", "@aws-sdk/credential-provider-web-identity": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-FMnAnWxc8PG+ZrZ2OBKzY4luCUJhe9CG0B9YwYr4pzrYGLXBS2rl+UoUvjGbAwiptxRL6hyA3lFn03Bv1TLqTw=="],
"@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.25", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HR7ynNRdNhNsdVCOCegy1HsfsRzozCOPtD3RzzT1JouuaHobWyRfJzCBue/3jP7gECHt+kQyZUvwg/cYLWurNQ=="],
"@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/token-providers": "3.1026.0", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HWv4SEq3jZDYPlwryZVef97+U8CxxRos5mK8sgGO1dQaFZpV5giZLzqGE5hkDmh2csYcBO2uf5XHjPTpZcJlig=="],
"@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-PdMBza1WEKEUPFEmMGCfnU2RYCz9MskU2e8JxjyUOsMKku7j9YaDKvbDi2dzC0ihFoM6ods2SbhfAAro+Gwlew=="],
"@aws-sdk/middleware-bucket-endpoint": ["@aws-sdk/middleware-bucket-endpoint@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-arn-parser": "^3.972.3", "@smithy/node-config-provider": "^4.3.13", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-COToYKgquDyligbcAep7ygs48RK+mwe/IYprq4+TSrVFzNOYmzWvHf6werpnKV5VYpRiwdn+Wa5ZXkPqLVwcTg=="],
"@aws-sdk/middleware-expect-continue": ["@aws-sdk/middleware-expect-continue@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-V/FNCjFxnh4VGu+HdSiW4Yg5GELihA1MIDSAdsEPvuayXBVmr0Jaa6jdLAZLH38KYXl/vVjri9DQJWnTAujHEA=="],
"@aws-sdk/middleware-flexible-checksums": ["@aws-sdk/middleware-flexible-checksums@3.974.7", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@aws-crypto/crc32c": "5.2.0", "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/crc64-nvme": "^3.972.6", "@aws-sdk/types": "^3.973.7", "@smithy/is-array-buffer": "^4.2.2", "@smithy/node-config-provider": "^4.3.13", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-middleware": "^4.2.13", "@smithy/util-stream": "^4.5.22", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uU4/ch2CLHB8Phu1oTKnnQ4e8Ujqi49zEnQYBhWYT53zfFvtJCdGsaOoypBr8Fm/pmCBssRmGoIQ4sixgdLP9w=="],
"@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="],
"@aws-sdk/middleware-location-constraint": ["@aws-sdk/middleware-location-constraint@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-TyfOi2XNdOZpNKeTJwRUsVAGa+14nkyMb2VVGG+eDgcWG/ed6+NUo72N3hT6QJioxym80NSinErD+LBRF0Ir1w=="],
"@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="],
"@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="],
"@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.28", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-arn-parser": "^3.972.3", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-stream": "^4.5.22", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-qJHcJQH9UNPUrnPlRtCozKjtqAaypQ5IgQxTNoPsVYIQeuwNIA8Rwt3NvGij1vCDYDfCmZaPLpnJEHlZXeFqmg=="],
"@aws-sdk/middleware-ssec": ["@aws-sdk/middleware-ssec@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-wSA2BR7L0CyBNDJeSrleIIzC+DzL93YNTdfU0KPGLiocK6YsRv1nPAzPF+BFSdcs0Qa5ku5Kcf4KvQcWwKGenQ=="],
"@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="],
"@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="],
"@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="],
"@aws-sdk/s3-request-presigner": ["@aws-sdk/s3-request-presigner@3.1026.0", "", { "dependencies": { "@aws-sdk/signature-v4-multi-region": "^3.996.16", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-format-url": "^3.972.9", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-PBVt/zb4YsJMcyB/HbGmID4RP00dTkdQGkNQiw1i6oXQ/U8hnPEI8+IvTKR4+5YEQ8Cq4QmtIV0mzv070L+oOg=="],
"@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.16", "", { "dependencies": { "@aws-sdk/middleware-sdk-s3": "^3.972.28", "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-EMdXYB4r/k5RWq86fugjRhid5JA+Z6MpS7n4sij4u5/C+STrkvuf9aFu41rJA9MjUzxCLzv8U2XL8cH2GSRYpQ=="],
"@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1026.0", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-Ieq/HiRrbEtrYP387Nes0XlR7H1pJiJOZKv+QyQzMYpvTiDs0VKy2ZB3E2Zf+aFovWmeE7lRE4lXyF7dYM6GgA=="],
"@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="],
"@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.3", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-HzSD8PMFrvgi2Kserxuff5VitNq2sgf3w9qxmskKDiDTThWfVteJxuCS9JXiPIPtmCrp+7N9asfIaVhBFORllA=="],
"@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="],
"@aws-sdk/util-format-url": ["@aws-sdk/util-format-url@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/querystring-builder": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-fNJXHrs0ZT7Wx0KGIqKv7zLxlDXt2vqjx9z6oKUQFmpE5o4xxnSryvVHfHpIifYHWKz94hFccIldJ0YSZjlCBw=="],
"@aws-sdk/util-locate-window": ["@aws-sdk/util-locate-window@3.965.5", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ=="],
"@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="],
"@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="],
"@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="],
"@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.2.4", "", {}, "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ=="],
"@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.27.7", "", { "os": "android", "cpu": "arm" }, "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ=="],
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.7", "", { "os": "android", "cpu": "arm64" }, "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ=="],
"@esbuild/android-x64": ["@esbuild/android-x64@0.27.7", "", { "os": "android", "cpu": "x64" }, "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg=="],
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw=="],
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ=="],
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.7", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w=="],
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.7", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ=="],
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.7", "", { "os": "linux", "cpu": "arm" }, "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA=="],
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A=="],
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.7", "", { "os": "linux", "cpu": "ia32" }, "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg=="],
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q=="],
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw=="],
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.7", "", { "os": "linux", "cpu": "ppc64" }, "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ=="],
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ=="],
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.7", "", { "os": "linux", "cpu": "s390x" }, "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw=="],
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.7", "", { "os": "linux", "cpu": "x64" }, "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA=="],
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.7", "", { "os": "none", "cpu": "arm64" }, "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w=="],
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.7", "", { "os": "none", "cpu": "x64" }, "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw=="],
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.7", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A=="],
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.7", "", { "os": "openbsd", "cpu": "x64" }, "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg=="],
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.7", "", { "os": "none", "cpu": "arm64" }, "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw=="],
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.7", "", { "os": "sunos", "cpu": "x64" }, "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA=="],
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA=="],
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.7", "", { "os": "win32", "cpu": "ia32" }, "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw=="],
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.7", "", { "os": "win32", "cpu": "x64" }, "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg=="],
"@google/genai": ["@google/genai@1.50.1", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-YbkX7H9+1Pt8wOt7DDREy8XSoiL6fRDzZQRyaVBarFf8MR3zHGqVdvM4cLbDXqPhxqvegZShgfxb8kw9C7YhAQ=="],
"@napi-rs/canvas": ["@napi-rs/canvas@0.1.97", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "0.1.97", "@napi-rs/canvas-darwin-arm64": "0.1.97", "@napi-rs/canvas-darwin-x64": "0.1.97", "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.97", "@napi-rs/canvas-linux-arm64-gnu": "0.1.97", "@napi-rs/canvas-linux-arm64-musl": "0.1.97", "@napi-rs/canvas-linux-riscv64-gnu": "0.1.97", "@napi-rs/canvas-linux-x64-gnu": "0.1.97", "@napi-rs/canvas-linux-x64-musl": "0.1.97", "@napi-rs/canvas-win32-arm64-msvc": "0.1.97", "@napi-rs/canvas-win32-x64-msvc": "0.1.97" } }, "sha512-8cFniXvrIEnVwuNSRCW9wirRZbHvrD3JVujdS2P5n5xiJZNZMOZcfOvJ1pb66c7jXMKHHglJEDVJGbm8XWFcXQ=="],
"@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@0.1.97", "", { "os": "android", "cpu": "arm64" }, "sha512-V1c/WVw+NzH8vk7ZK/O8/nyBSCQimU8sfMsB/9qeSvdkGKNU7+mxy/bIF0gTgeBFmHpj30S4E9WHMSrxXGQuVQ=="],
"@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@0.1.97", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ok+SCEF4YejcxuJ9Rm+WWunHHpf2HmiPxfz6z1a/NFQECGXtsY7A4B8XocK1LmT1D7P174MzwPF9Wy3AUAwEPw=="],
"@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@0.1.97", "", { "os": "darwin", "cpu": "x64" }, "sha512-PUP6e6/UGlclUvAQNnuXCcnkpdUou6VYZfQOQxExLp86epOylmiwLkqXIvpFmjoTEDmPmXrI+coL/9EFU1gKPA=="],
"@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@0.1.97", "", { "os": "linux", "cpu": "arm" }, "sha512-XyXH2L/cic8eTNtbrXCcvqHtMX/nEOxN18+7rMrAM2XtLYC/EB5s0wnO1FsLMWmK+04ZSLN9FBGipo7kpIkcOw=="],
"@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@0.1.97", "", { "os": "linux", "cpu": "arm64" }, "sha512-Kuq/M3djq0K8ktgz6nPlK7Ne5d4uWeDxPpyKWOjWDK2RIOhHVtLtyLiJw2fuldw7Vn4mhw05EZXCEr4Q76rs9w=="],
"@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@0.1.97", "", { "os": "linux", "cpu": "arm64" }, "sha512-kKmSkQVnWeqg7qdsiXvYxKhAFuHz3tkBjW/zyQv5YKUPhotpaVhpBGv5LqCngzyuRV85SXoe+OFj+Tv0a0QXkQ=="],
"@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@0.1.97", "", { "os": "linux", "cpu": "none" }, "sha512-Jc7I3A51jnEOIAXeLsN/M/+Z28LUeakcsXs07FLq9prXc0eYOtVwsDEv913Gr+06IRo34gJJVgT0TXvmz+N2VA=="],
"@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@0.1.97", "", { "os": "linux", "cpu": "x64" }, "sha512-iDUBe7AilfuBSRbSa8/IGX38Mf+iCSBqoVKLSQ5XaY2JLOaqz1TVyPFEyIck7wT6mRQhQt5sN6ogfjIDfi74tg=="],
"@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@0.1.97", "", { "os": "linux", "cpu": "x64" }, "sha512-AKLFd/v0Z5fvgqBDqhvqtAdx+fHMJ5t9JcUNKq4FIZ5WH+iegGm8HPdj00NFlCSnm83Fp3Ln8I2f7uq1aIiWaA=="],
"@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/canvas-win32-arm64-msvc@0.1.97", "", { "os": "win32", "cpu": "arm64" }, "sha512-u883Yr6A6fO7Vpsy9YE4FVCIxzzo5sO+7pIUjjoDLjS3vQaNMkVzx5bdIpEL+ob+gU88WDK4VcxYMZ6nmnoX9A=="],
"@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@0.1.97", "", { "os": "win32", "cpu": "x64" }, "sha512-sWtD2EE3fV0IzN+iiQUqr/Q1SwqWhs2O1FKItFlxtdDkikpEj5g7DKQpY3x55H/MAOnL8iomnlk3mcEeGiUMoQ=="],
"@nodable/entities": ["@nodable/entities@2.1.0", "", {}, "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA=="],
"@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
"@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
"@protobufjs/codegen": ["@protobufjs/codegen@2.0.4", "", {}, "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg=="],
"@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.0", "", {}, "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q=="],
"@protobufjs/fetch": ["@protobufjs/fetch@1.1.0", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" } }, "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ=="],
"@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
"@protobufjs/inquire": ["@protobufjs/inquire@1.1.0", "", {}, "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q=="],
"@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
"@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
"@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="],
"@react-email/render": ["@react-email/render@1.1.2", "", { "dependencies": { "html-to-text": "^9.0.5", "prettier": "^3.5.3", "react-promise-suspense": "^0.3.4" }, "peerDependencies": { "react": "^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^18.0 || ^19.0 || ^19.0.0-rc" } }, "sha512-RnRehYN3v9gVlNMehHPHhyp2RQo7+pSkHDtXPvg3s0GbzM9SQMW4Qrf8GRNvtpLC4gsI+Wt0VatNRUFqjvevbw=="],
"@selderee/plugin-htmlparser2": ["@selderee/plugin-htmlparser2@0.11.0", "", { "dependencies": { "domhandler": "^5.0.3", "selderee": "^0.11.0" } }, "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ=="],
"@smithy/chunked-blob-reader": ["@smithy/chunked-blob-reader@5.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-St+kVicSyayWQca+I1rGitaOEH6uKgE8IUWoYnnEX26SWdWQcL6LvMSD19Lg+vYHKdT9B2Zuu7rd3i6Wnyb/iw=="],
"@smithy/chunked-blob-reader-native": ["@smithy/chunked-blob-reader-native@4.2.3", "", { "dependencies": { "@smithy/util-base64": "^4.3.2", "tslib": "^2.6.2" } }, "sha512-jA5k5Udn7Y5717L86h4EIv06wIr3xn8GM1qHRi/Nf31annXcXHJjBKvgztnbn2TxH3xWrPBfgwHsOwZf0UmQWw=="],
"@smithy/config-resolver": ["@smithy/config-resolver@4.4.14", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "tslib": "^2.6.2" } }, "sha512-N55f8mPEccpzKetUagdvmAy8oohf0J5cuj9jLI1TaSceRlq0pJsIZepY3kmAXAhyxqXPV6hDerDQhqQPKWgAoQ=="],
"@smithy/core": ["@smithy/core@3.23.14", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-stream": "^4.5.22", "@smithy/util-utf8": "^4.2.2", "@smithy/uuid": "^1.1.2", "tslib": "^2.6.2" } }, "sha512-vJ0IhpZxZAkFYOegMKSrxw7ujhhT2pass/1UEcZ4kfl5srTAqtPU5I7MdYQoreVas3204ykCiNhY1o7Xlz6Yyg=="],
"@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.2.13", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "tslib": "^2.6.2" } }, "sha512-wboCPijzf6RJKLOvnjDAiBxGSmSnGXj35o5ZAWKDaHa/cvQ5U3ZJ13D4tMCE8JG4dxVAZFy/P0x/V9CwwdfULQ=="],
"@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.2.13", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.14.0", "@smithy/util-hex-encoding": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-vYahwBAtRaAcFbOmE9aLr12z7RiHYDSLcnogSdxfm7kKfsNa3wH+NU5r7vTeB5rKvLsWyPjVX8iH94brP7umiQ=="],
"@smithy/eventstream-serde-browser": ["@smithy/eventstream-serde-browser@4.2.13", "", { "dependencies": { "@smithy/eventstream-serde-universal": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-wwybfcOX0tLqCcBP378TIU9IqrDuZq/tDV48LlZNydMpCnqnYr+hWBAYbRE+rFFf/p7IkDJySM3bgiMKP2ihPg=="],
"@smithy/eventstream-serde-config-resolver": ["@smithy/eventstream-serde-config-resolver@4.3.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-ied1lO559PtAsMJzg2TKRlctLnEi1PfkNeMMpdwXDImk1zV9uvS/Oxoy/vcy9uv1GKZAjDAB5xT6ziE9fzm5wA=="],
"@smithy/eventstream-serde-node": ["@smithy/eventstream-serde-node@4.2.13", "", { "dependencies": { "@smithy/eventstream-serde-universal": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-hFyK+ORJrxAN3RYoaD6+gsGDQjeix8HOEkosoajvXYZ4VeqonM3G4jd9IIRm/sWGXUKmudkY9KdYjzosUqdM8A=="],
"@smithy/eventstream-serde-universal": ["@smithy/eventstream-serde-universal@4.2.13", "", { "dependencies": { "@smithy/eventstream-codec": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-kRrq4EKLGeOxhC2CBEhRNcu1KSzNJzYY7RK3S7CxMPgB5dRrv55WqQOtRwQxQLC04xqORFLUgnDlc6xrNUULaA=="],
"@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.3.16", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/querystring-builder": "^4.2.13", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "tslib": "^2.6.2" } }, "sha512-nYDRUIvNd4mFmuXraRWt6w5UsZTNqtj4hXJA/iiOD4tuseIdLP9Lq38teH/SZTcIFCa2f+27o7hYpIsWktJKEQ=="],
"@smithy/hash-blob-browser": ["@smithy/hash-blob-browser@4.2.14", "", { "dependencies": { "@smithy/chunked-blob-reader": "^5.2.2", "@smithy/chunked-blob-reader-native": "^4.2.3", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-rtQ5es8r/5v4rav7q5QTsfx9CtCyzrz/g7ZZZBH2xtMmd6G/KQrLOWfSHTvFOUPlVy59RQvxeBYJaLRoybMEyA=="],
"@smithy/hash-node": ["@smithy/hash-node@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-buffer-from": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-4/oy9h0jjmY80a2gOIo75iLl8TOPhmtx4E2Hz+PfMjvx/vLtGY4TMU/35WRyH2JHPfT5CVB38u4JRow7gnmzJA=="],
"@smithy/hash-stream-node": ["@smithy/hash-stream-node@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-WdQ7HwUjINXETeh6dqUeob1UHIYx8kAn9PSp1HhM2WWegiZBYVy2WXIs1lB07SZLan/udys9SBnQGt9MQbDpdg=="],
"@smithy/invalid-dependency": ["@smithy/invalid-dependency@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-jvC0RB/8BLj2SMIkY0Npl425IdnxZJxInpZJbu563zIRnVjpDMXevU3VMCRSabaLB0kf/eFIOusdGstrLJ8IDg=="],
"@smithy/is-array-buffer": ["@smithy/is-array-buffer@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow=="],
"@smithy/md5-js": ["@smithy/md5-js@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-cNm7I9NXolFxtS20ojROddOEpSAeI1Obq6pd1Kj5HtHws3s9Fkk8DdHDfQSs5KuxCewZuVK6UqrJnfJmiMzDuQ=="],
"@smithy/middleware-content-length": ["@smithy/middleware-content-length@4.2.13", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-IPMLm/LE4AZwu6qiE8Rr8vJsWhs9AtOdySRXrOM7xnvclp77Tyh7hMs/FRrMf26kgIe67vFJXXOSmVxS7oKeig=="],
"@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.29", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/middleware-serde": "^4.2.17", "@smithy/node-config-provider": "^4.3.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-middleware": "^4.2.13", "tslib": "^2.6.2" } }, "sha512-R9Q/58U+qBiSARGWbAbFLczECg/RmysRksX6Q8BaQEpt75I7LI6WGDZnjuC9GXSGKljEbA7N118LhGaMbfrTXw=="],
"@smithy/middleware-retry": ["@smithy/middleware-retry@4.5.0", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/protocol-http": "^5.3.13", "@smithy/service-error-classification": "^4.2.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/uuid": "^1.1.2", "tslib": "^2.6.2" } }, "sha512-/NzISn4grj/BRFVua/xnQwF+7fakYZgimpw2dfmlPgcqecBMKxpB9g5mLYRrmBD5OrPoODokw4Vi1hrSR4zRyw=="],
"@smithy/middleware-serde": ["@smithy/middleware-serde@4.2.17", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-0T2mcaM6v9W1xku86Dk0bEW7aEseG6KenFkPK98XNw0ZhOqOiD1MrMsdnQw9QsL3/Oa85T53iSMlm0SZdSuIEQ=="],
"@smithy/middleware-stack": ["@smithy/middleware-stack@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-g72jN/sGDLyTanrCLH9fhg3oysO3f7tQa6eWWsMyn2BiYNCgjF24n4/I9wff/5XidFvjj9ilipAoQrurTUrLvw=="],
"@smithy/node-config-provider": ["@smithy/node-config-provider@4.3.13", "", { "dependencies": { "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-iGxQ04DsKXLckbgnX4ipElrOTk+IHgTyu0q0WssZfYhDm9CQWHmu6cOeI5wmWRxpXbBDhIIfXMWz5tPEtcVqbw=="],
"@smithy/node-http-handler": ["@smithy/node-http-handler@4.5.2", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/querystring-builder": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-/oD7u8M0oj2ZTFw7GkuuHWpIxtWdLlnyNkbrWcyVYhd5RJNDuczdkb0wfnQICyNFrVPlr8YHOhamjNy3zidhmA=="],
"@smithy/property-provider": ["@smithy/property-provider@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-bGzUCthxRmezuxkbu9wD33wWg9KX3hJpCXpQ93vVkPrHn9ZW6KNNdY5xAUWNuRCwQ+VyboFuWirG1lZhhkcyRQ=="],
"@smithy/protocol-http": ["@smithy/protocol-http@5.3.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-+HsmuJUF4u8POo6s8/a2Yb/AQ5t/YgLovCuHF9oxbocqv+SZ6gd8lC2duBFiCA/vFHoHQhoq7QjqJqZC6xOxxg=="],
"@smithy/querystring-builder": ["@smithy/querystring-builder@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-uri-escape": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-tG4aOYFCZdPMjbgfhnIQ322H//ojujldp1SrHPHpBSb3NqgUp3dwiUGRJzie87hS1DYwWGqDuPaowoDF+rYCbQ=="],
"@smithy/querystring-parser": ["@smithy/querystring-parser@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-hqW3Q4P+CDzUyQ87GrboGMeD7XYNMOF+CuTwu936UQRB/zeYn3jys8C3w+wMkDfY7CyyyVwZQ5cNFoG0x1pYmA=="],
"@smithy/service-error-classification": ["@smithy/service-error-classification@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0" } }, "sha512-a0s8XZMfOC/qpqq7RCPvJlk93rWFrElH6O++8WJKz0FqnA4Y7fkNi/0mnGgSH1C4x6MFsuBA8VKu4zxFrMe5Vw=="],
"@smithy/shared-ini-file-loader": ["@smithy/shared-ini-file-loader@4.4.8", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-VZCZx2bZasxdqxVgEAhREvDSlkatTPnkdWy1+Kiy8w7kYPBosW0V5IeDwzDUMvWBt56zpK658rx1cOBFOYaPaw=="],
"@smithy/signature-v4": ["@smithy/signature-v4@5.3.13", "", { "dependencies": { "@smithy/is-array-buffer": "^4.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-hex-encoding": "^4.2.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-uri-escape": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-YpYSyM0vMDwKbHD/JA7bVOF6kToVRpa+FM5ateEVRpsTNu564g1muBlkTubXhSKKYXInhpADF46FPyrZcTLpXg=="],
"@smithy/smithy-client": ["@smithy/smithy-client@4.12.9", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-stack": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-stream": "^4.5.22", "tslib": "^2.6.2" } }, "sha512-ovaLEcTU5olSeHcRXcxV6viaKtpkHZumn6Ps0yn7dRf2rRSfy794vpjOtrWDO0d1auDSvAqxO+lyhERSXQ03EQ=="],
"@smithy/types": ["@smithy/types@4.14.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-OWgntFLW88kx2qvf/c/67Vno1yuXm/f9M7QFAtVkkO29IJXGBIg0ycEaBTH0kvCtwmvZxRujrgP5a86RvsXJAQ=="],
"@smithy/url-parser": ["@smithy/url-parser@4.2.13", "", { "dependencies": { "@smithy/querystring-parser": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-2G03yoboIRZlZze2+PT4GZEjgwQsJjUgn6iTsvxA02bVceHR6vp4Cuk7TUnPFWKF+ffNUk3kj4COwkENS2K3vw=="],
"@smithy/util-base64": ["@smithy/util-base64@4.3.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-XRH6b0H/5A3SgblmMa5ErXQ2XKhfbQB+Fm/oyLZ2O2kCUrwgg55bU0RekmzAhuwOjA9qdN5VU2BprOvGGUkOOQ=="],
"@smithy/util-body-length-browser": ["@smithy/util-body-length-browser@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-JKCrLNOup3OOgmzeaKQwi4ZCTWlYR5H4Gm1r2uTMVBXoemo1UEghk5vtMi1xSu2ymgKVGW631e2fp9/R610ZjQ=="],
"@smithy/util-body-length-node": ["@smithy/util-body-length-node@4.2.3", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-ZkJGvqBzMHVHE7r/hcuCxlTY8pQr1kMtdsVPs7ex4mMU+EAbcXppfo5NmyxMYi2XU49eqaz56j2gsk4dHHPG/g=="],
"@smithy/util-buffer-from": ["@smithy/util-buffer-from@4.2.2", "", { "dependencies": { "@smithy/is-array-buffer": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-FDXD7cvUoFWwN6vtQfEta540Y/YBe5JneK3SoZg9bThSoOAC/eGeYEua6RkBgKjGa/sz6Y+DuBZj3+YEY21y4Q=="],
"@smithy/util-config-provider": ["@smithy/util-config-provider@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-dWU03V3XUprJwaUIFVv4iOnS1FC9HnMHDfUrlNDSh4315v0cWyaIErP8KiqGVbf5z+JupoVpNM7ZB3jFiTejvQ=="],
"@smithy/util-defaults-mode-browser": ["@smithy/util-defaults-mode-browser@4.3.45", "", { "dependencies": { "@smithy/property-provider": "^4.2.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-ag9sWc6/nWZAuK3Wm9KlFJUnRkXLrXn33RFjIAmCTFThqLHY+7wCst10BGq56FxslsDrjhSie46c8OULS+BiIw=="],
"@smithy/util-defaults-mode-node": ["@smithy/util-defaults-mode-node@4.2.49", "", { "dependencies": { "@smithy/config-resolver": "^4.4.14", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-jlN6vHwE8gY5AfiFBavtD3QtCX2f7lM3BKkz7nFKSNfFR5nXLXLg6sqXTJEEyDwtxbztIDBQCfjsGVXlIru2lQ=="],
"@smithy/util-endpoints": ["@smithy/util-endpoints@3.3.4", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-BKoR/ubPp9KNKFxPpg1J28N1+bgu8NGAtJblBP7yHy8yQPBWhIAv9+l92SlQLpolGm71CVO+btB60gTgzT0wog=="],
"@smithy/util-hex-encoding": ["@smithy/util-hex-encoding@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-Qcz3W5vuHK4sLQdyT93k/rfrUwdJ8/HZ+nMUOyGdpeGA1Wxt65zYwi3oEl9kOM+RswvYq90fzkNDahPS8K0OIg=="],
"@smithy/util-middleware": ["@smithy/util-middleware@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-GTooyrlmRTqvUen4eK7/K1p6kryF7bnDfq6XsAbIsf2mo51B/utaH+XThY6dKgNCWzMAaH/+OLmqaBuLhLWRow=="],
"@smithy/util-retry": ["@smithy/util-retry@4.3.0", "", { "dependencies": { "@smithy/service-error-classification": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-tSOPQNT/4KfbvqeMovWC3g23KSYy8czHd3tlN+tOYVNIDLSfxIsrPJihYi5TpNcoV789KWtgChUVedh2y6dDPg=="],
"@smithy/util-stream": ["@smithy/util-stream@4.5.22", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.16", "@smithy/node-http-handler": "^4.5.2", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-buffer-from": "^4.2.2", "@smithy/util-hex-encoding": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-3H8iq/0BfQjUs2/4fbHZ9aG9yNzcuZs24LPkcX1Q7Z+qpqaGM8+qbGmE8zo9m2nCRgamyvS98cHdcWvR6YUsew=="],
"@smithy/util-uri-escape": ["@smithy/util-uri-escape@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-2kAStBlvq+lTXHyAZYfJRb/DfS3rsinLiwb+69SstC9Vb0s9vNWkRwpnj918Pfi85mzi42sOqdV72OLxWAISnw=="],
"@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="],
"@smithy/util-waiter": ["@smithy/util-waiter@4.2.15", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-oUt9o7n8hBv3BL56sLSneL0XeigZSuem0Hr78JaoK33D9oKieyCvVP8eTSe3j7g2mm/S1DvzxKieG7JEWNJUNg=="],
"@smithy/uuid": ["@smithy/uuid@1.1.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-O/IEdcCUKkubz60tFbGA7ceITTAJsty+lBjNoorP4Z6XRqaFb/OjQjZODophEcuq68nKm6/0r+6/lLQ+XVpk8g=="],
"@supabase/auth-js": ["@supabase/auth-js@2.102.1", "", { "dependencies": { "tslib": "2.8.1" } }, "sha512-2uH2WB0H98TOGDtaFWhxIcR42Dro/VB7VDZanz/4bVJsqioIue1m3TUqu3xciDm2W9r+1LXQvYNsYbQfWmD+uQ=="],
"@supabase/functions-js": ["@supabase/functions-js@2.102.1", "", { "dependencies": { "tslib": "2.8.1" } }, "sha512-UcrcKTPnAIo+Yp9Jjq9XXwFbsmgRYY637mwka9ZjmTIWcX/xr1pote4OVvaGQycVY1KTiQgjMvpC0Q0yJhRq3w=="],
"@supabase/phoenix": ["@supabase/phoenix@0.4.0", "", {}, "sha512-RHSx8bHS02xwfHdAbX5Lpbo6PXbgyf7lTaXTlwtFDPwOIw64NnVRwFAXGojHhjtVYI+PEPNSWwkL90f4agN3bw=="],
"@supabase/postgrest-js": ["@supabase/postgrest-js@2.102.1", "", { "dependencies": { "tslib": "2.8.1" } }, "sha512-InLvXKAYf8BIqiv9jWOYudWB3rU8A9uMbcip5BQ5sLLNPrbO1Ekkr79OvlhZBgMNSppxVyC7wPPGzLxMcTZhlA=="],
"@supabase/realtime-js": ["@supabase/realtime-js@2.102.1", "", { "dependencies": { "@supabase/phoenix": "^0.4.0", "@types/ws": "^8.18.1", "tslib": "2.8.1", "ws": "^8.18.2" } }, "sha512-h2fCumib/v6u7XMwSPgxnpfimjX4xCEayUHrxWLC7UurfQjUZJ0pmJDgm6yj80DnUerxuulRghwm5zXYysFG/Q=="],
"@supabase/storage-js": ["@supabase/storage-js@2.102.1", "", { "dependencies": { "iceberg-js": "^0.8.1", "tslib": "2.8.1" } }, "sha512-eCL9T4Xpe40nmKlkUJ7Zq/hk34db1xPiT0WL3Iv5MbJqHuCAe5TxhV8Rjqd6DNZrzjtfYObZtYl9jKJaHrivqw=="],
"@supabase/supabase-js": ["@supabase/supabase-js@2.102.1", "", { "dependencies": { "@supabase/auth-js": "2.102.1", "@supabase/functions-js": "2.102.1", "@supabase/postgrest-js": "2.102.1", "@supabase/realtime-js": "2.102.1", "@supabase/storage-js": "2.102.1" } }, "sha512-bChxPVeLDnYN9M2d/u4fXsvylwSQG5grAl+HN8f+ZD9a9PuVU+Ru+xGmEsk+b9Iz3rJC9ZQnQUJYQ28fApdWYA=="],
"@types/body-parser": ["@types/body-parser@1.19.6", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="],
"@types/connect": ["@types/connect@3.4.38", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="],
"@types/cors": ["@types/cors@2.8.19", "", { "dependencies": { "@types/node": "*" } }, "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg=="],
"@types/express": ["@types/express@4.17.25", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^4.17.33", "@types/qs": "*", "@types/serve-static": "^1" } }, "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw=="],
"@types/express-serve-static-core": ["@types/express-serve-static-core@4.19.8", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA=="],
"@types/http-errors": ["@types/http-errors@2.0.5", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="],
"@types/mime": ["@types/mime@1.3.5", "", {}, "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w=="],
"@types/multer": ["@types/multer@1.4.13", "", { "dependencies": { "@types/express": "*" } }, "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw=="],
"@types/node": ["@types/node@22.19.17", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q=="],
"@types/qs": ["@types/qs@6.15.0", "", {}, "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow=="],
"@types/range-parser": ["@types/range-parser@1.2.7", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="],
"@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="],
"@types/send": ["@types/send@1.2.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ=="],
"@types/serve-static": ["@types/serve-static@1.15.10", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*", "@types/send": "<1" } }, "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@xmldom/xmldom": ["@xmldom/xmldom@0.8.12", "", {}, "sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg=="],
"accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="],
"agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
"append-field": ["append-field@1.0.0", "", {}, "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="],
"argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],
"array-flatten": ["array-flatten@1.1.1", "", {}, "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="],
"async": ["async@3.2.6", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
"bluebird": ["bluebird@3.4.7", "", {}, "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA=="],
"body-parser": ["body-parser@1.20.4", "", { "dependencies": { "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "~1.2.0", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", "qs": "~6.14.0", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" } }, "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA=="],
"bowser": ["bowser@2.14.1", "", {}, "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg=="],
"buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"busboy": ["busboy@1.6.0", "", { "dependencies": { "streamsearch": "^1.1.0" } }, "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"concat-stream": ["concat-stream@1.6.2", "", { "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^2.2.2", "typedarray": "^0.0.6" } }, "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw=="],
"content-disposition": ["content-disposition@0.5.4", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"cookie-signature": ["cookie-signature@1.0.7", "", {}, "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="],
"core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="],
"debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],
"deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"destroy": ["destroy@1.2.0", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="],
"dingbat-to-unicode": ["dingbat-to-unicode@1.0.1", "", {}, "sha512-98l0sW87ZT58pU4i61wa2OHwxbiYSbuxsCBozaVnYX2iCnr3bLM3fIes1/ej7h1YdOKuKt/MLs706TVnALA65w=="],
"docx": ["docx@9.6.1", "", { "dependencies": { "@types/node": "^25.2.3", "hash.js": "^1.1.7", "jszip": "^3.10.1", "nanoid": "^5.1.3", "xml": "^1.0.1", "xml-js": "^1.6.8" } }, "sha512-ZJja9/KBUuFC109sCMzovoq2GR2wCG/AuxivjA+OHj/q0TEgJIm3S7yrlUxIy3B+bV8YDj/BiHfWyrRFmyWpDQ=="],
"dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
"domelementtype": ["domelementtype@2.3.0", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="],
"domhandler": ["domhandler@5.0.3", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="],
"domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],
"dotenv": ["dotenv@17.4.1", "", {}, "sha512-k8DaKGP6r1G30Lx8V4+pCsLzKr8vLmV2paqEj1Y55GdAgJuIqpRp5FfajGF8KtwMxCz9qJc6wUIJnm053d/WCw=="],
"duck": ["duck@0.1.12", "", { "dependencies": { "underscore": "^1.13.1" } }, "sha512-wkctla1O6VfP89gQ+J/yDesM0S7B7XLXjKGzXxMDVFg7uEn706niAtyYovKbyq1oT9YwDcly721/iUWoc8MVRg=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
"esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": "bin/esbuild" }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"express": ["express@4.22.1", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "~1.20.3", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.3.1", "fresh": "~0.5.2", "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", "qs": "~6.14.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", "serve-static": "~1.16.2", "setprototypeof": "1.2.0", "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g=="],
"extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
"fast-deep-equal": ["fast-deep-equal@2.0.1", "", {}, "sha512-bCK/2Z4zLidyB4ReuIsvALH6w31YfAQDmXMqMx6FyfHqvBxtjC0eRumeSu4Bs3XtXwpyIywtSTrVT99BxY1f9w=="],
"fast-diff": ["fast-diff@1.3.0", "", {}, "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw=="],
"fast-xml-builder": ["fast-xml-builder@1.1.5", "", { "dependencies": { "path-expression-matcher": "^1.1.3" } }, "sha512-4TJn/8FKLeslLAH3dnohXqE3QSoxkhvaMzepOIZytwJXZO69Bfz0HBdDHzOTOon6G59Zrk6VQ2bEiv1t61rfkA=="],
"fast-xml-parser": ["fast-xml-parser@5.7.2", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.5", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-P7oW7tLbYnhOLQk/Gv7cZgzgMPP/XN03K02/Jy6Y/NHzyIAIpxuZIM/YqAkfiXFPxA2CTm7NtCijK9EDu09u2w=="],
"fetch-blob": ["fetch-blob@3.2.0", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="],
"finalhandler": ["finalhandler@1.3.2", "", { "dependencies": { "debug": "2.6.9", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "statuses": "~2.0.2", "unpipe": "~1.0.0" } }, "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg=="],
"formdata-polyfill": ["formdata-polyfill@4.0.10", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="],
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"fresh": ["fresh@0.5.2", "", {}, "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"gaxios": ["gaxios@7.1.4", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" } }, "sha512-bTIgTsM2bWn3XklZISBTQX7ZSddGW+IO3bMdGaemHZ3tbqExMENHLx6kKZ/KlejgrMtj8q7wBItt51yegqalrA=="],
"gcp-metadata": ["gcp-metadata@8.1.2", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"get-tsconfig": ["get-tsconfig@4.13.7", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q=="],
"google-auth-library": ["google-auth-library@10.6.2", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "8.1.2", "google-logging-utils": "1.1.3", "jws": "^4.0.0" } }, "sha512-e27Z6EThmVNNvtYASwQxose/G57rkRuaRbQyxM2bvYLLX/GqWZ5chWq2EBoUchJbCc57eC9ArzO5wMsEmWftCw=="],
"google-logging-utils": ["google-logging-utils@1.1.3", "", {}, "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hash.js": ["hash.js@1.1.7", "", { "dependencies": { "inherits": "^2.0.3", "minimalistic-assert": "^1.0.1" } }, "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA=="],
"hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
"html-to-text": ["html-to-text@9.0.5", "", { "dependencies": { "@selderee/plugin-htmlparser2": "^0.11.0", "deepmerge": "^4.3.1", "dom-serializer": "^2.0.0", "htmlparser2": "^8.0.2", "selderee": "^0.11.0" } }, "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg=="],
"htmlparser2": ["htmlparser2@8.0.2", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.0.1", "entities": "^4.4.0" } }, "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
"iceberg-js": ["iceberg-js@0.8.1", "", {}, "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA=="],
"iconv-lite": ["iconv-lite@0.4.24", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3" } }, "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA=="],
"immediate": ["immediate@3.0.6", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="],
"json-bigint": ["json-bigint@1.0.0", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],
"json-schema-to-ts": ["json-schema-to-ts@3.1.1", "", { "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" } }, "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g=="],
"jszip": ["jszip@3.10.1", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g=="],
"jwa": ["jwa@2.0.1", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],
"jws": ["jws@4.0.1", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
"leac": ["leac@0.6.0", "", {}, "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg=="],
"libreoffice-convert": ["libreoffice-convert@1.8.1", "", { "dependencies": { "async": "^3.2.3", "tmp": "^0.2.1" } }, "sha512-iZ1DD/EMTlPvol8G++QQ/0w4pVecSwRuhMLXRm7nRim/gcaSscSXuTO9Tgbkieyw5UdJg7UXD+lkFT8SCi51Dw=="],
"lie": ["lie@3.3.0", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="],
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
"lop": ["lop@0.4.2", "", { "dependencies": { "duck": "^0.1.12", "option": "~0.2.1", "underscore": "^1.13.1" } }, "sha512-RefILVDQ4DKoRZsJ4Pj22TxE3omDO47yFpkIBoDKzkqPRISs5U1cnAdg/5583YPkWPaLIYHOKRMQSvjFsO26cw=="],
"mammoth": ["mammoth@1.12.0", "", { "dependencies": { "@xmldom/xmldom": "^0.8.6", "argparse": "~1.0.3", "base64-js": "^1.5.1", "bluebird": "~3.4.0", "dingbat-to-unicode": "^1.0.1", "jszip": "^3.7.1", "lop": "^0.4.2", "path-is-absolute": "^1.0.0", "underscore": "^1.13.1", "xmlbuilder": "^10.0.0" }, "bin": "bin/mammoth" }, "sha512-cwnK1RIcRdDMi2HRx2EXGYlxqIEh0Oo3bLhorgnsVJi2UkbX1+jKxuBNR9PC5+JaX7EkmJxFPmo6mjLpqShI2w=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"media-typer": ["media-typer@0.3.0", "", {}, "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ=="],
"merge-descriptors": ["merge-descriptors@1.0.3", "", {}, "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ=="],
"methods": ["methods@1.1.2", "", {}, "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w=="],
"mime": ["mime@1.6.0", "", { "bin": "cli.js" }, "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="],
"mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
"mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="],
"minimalistic-assert": ["minimalistic-assert@1.0.1", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="],
"minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
"mkdirp": ["mkdirp@0.5.6", "", { "dependencies": { "minimist": "^1.2.6" }, "bin": "bin/cmd.js" }, "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw=="],
"ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="],
"multer": ["multer@1.4.5-lts.2", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.0.0", "concat-stream": "^1.5.2", "mkdirp": "^0.5.4", "object-assign": "^4.1.1", "type-is": "^1.6.4", "xtend": "^4.0.0" } }, "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A=="],
"nanoid": ["nanoid@5.1.7", "", { "bin": "bin/nanoid.js" }, "sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ=="],
"negotiator": ["negotiator@0.6.3", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],
"node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
"node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
"option": ["option@0.2.4", "", {}, "sha512-pkEqbDyl8ou5cpq+VsnQbe/WlEy5qS7xPzMS1U55OCG9KPvwFD46zDbxQIj3egJSFc3D+XhYOPUzz49zQAVy7A=="],
"p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="],
"pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
"parseley": ["parseley@0.12.1", "", { "dependencies": { "leac": "^0.6.0", "peberminta": "^0.9.0" } }, "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="],
"path-is-absolute": ["path-is-absolute@1.0.1", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
"path-to-regexp": ["path-to-regexp@0.1.13", "", {}, "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA=="],
"pdfjs-dist": ["pdfjs-dist@4.10.38", "", { "optionalDependencies": { "@napi-rs/canvas": "^0.1.65" } }, "sha512-/Y3fcFrXEAsMjJXeL9J8+ZG9U01LbuWaYypvDW2ycW1jL269L3js3DVBjDJ0Up9Np1uqDXsDrRihHANhZOlwdQ=="],
"peberminta": ["peberminta@0.9.0", "", {}, "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ=="],
"prettier": ["prettier@3.8.1", "", { "bin": "bin/prettier.cjs" }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
"protobufjs": ["protobufjs@7.5.5", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-3wY1AxV+VBNW8Yypfd1yQY9pXnqTAN+KwQxL8iYm3/BjKYMNg4i0owhEe26PWDOMaIrzeeF98Lqd5NGz4omiIg=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"qs": ["qs@6.14.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q=="],
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["raw-body@2.5.3", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "unpipe": "~1.0.0" } }, "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA=="],
"react": ["react@19.2.4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
"react-dom": ["react-dom@19.2.4", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
"react-promise-suspense": ["react-promise-suspense@0.3.4", "", { "dependencies": { "fast-deep-equal": "^2.0.1" } }, "sha512-I42jl7L3Ze6kZaq+7zXWSunBa3b1on5yfvUW6Eo/3fFOj6dZ5Bqmcd264nJbTK/gn1HjjILAjSwnZbV4RpSaNQ=="],
"readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"resend": ["resend@4.8.0", "", { "dependencies": { "@react-email/render": "1.1.2" } }, "sha512-R8eBOFQDO6dzRTDmaMEdpqrkmgSjPpVXt4nGfWsZdYOet0kqra0xgbvTES6HmCriZEXbmGk3e0DiGIaLFTFSHA=="],
"resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
"retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="],
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"sax": ["sax@1.6.0", "", {}, "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"selderee": ["selderee@0.11.0", "", { "dependencies": { "parseley": "^0.12.0" } }, "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA=="],
"send": ["send@0.19.2", "", { "dependencies": { "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "~0.5.2", "http-errors": "~2.0.1", "mime": "1.6.0", "ms": "2.1.3", "on-finished": "~2.4.1", "range-parser": "~1.2.1", "statuses": "~2.0.2" } }, "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg=="],
"serve-static": ["serve-static@1.16.3", "", { "dependencies": { "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", "send": "~0.19.1" } }, "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA=="],
"setimmediate": ["setimmediate@1.0.5", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
"side-channel-list": ["side-channel-list@1.0.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3" } }, "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA=="],
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
"sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"streamsearch": ["streamsearch@1.1.0", "", {}, "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg=="],
"string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="],
"tmp": ["tmp@0.2.5", "", {}, "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"ts-algebra": ["ts-algebra@2.0.0", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="],
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"tsx": ["tsx@4.21.0", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": "dist/cli.mjs" }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"type-is": ["type-is@1.6.18", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="],
"typedarray": ["typedarray@0.0.6", "", {}, "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"underscore": ["underscore@1.13.8", "", {}, "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"utils-merge": ["utils-merge@1.0.1", "", {}, "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],
"ws": ["ws@8.20.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
"xml": ["xml@1.0.1", "", {}, "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw=="],
"xml-js": ["xml-js@1.6.11", "", { "dependencies": { "sax": "^1.2.4" }, "bin": "bin/cli.js" }, "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g=="],
"xmlbuilder": ["xmlbuilder@10.1.1", "", {}, "sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg=="],
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
"@aws-crypto/sha1-browser/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],
"@aws-crypto/util/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],
"@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="],
"@types/serve-static/@types/send": ["@types/send@0.17.6", "", { "dependencies": { "@types/mime": "^1", "@types/node": "*" } }, "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og=="],
"docx/@types/node": ["@types/node@25.5.2", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg=="],
"https-proxy-agent/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"protobufjs/@types/node": ["@types/node@25.5.2", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg=="],
"readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
"send/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"string_decoder/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
"@aws-crypto/sha1-browser/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
"@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
"@aws-sdk/xml-builder/fast-xml-parser/fast-xml-builder": ["fast-xml-builder@1.1.4", "", { "dependencies": { "path-expression-matcher": "^1.1.3" } }, "sha512-f2jhpN4Eccy0/Uz9csxh3Nu6q4ErKxf0XIsasomfOihuSUa3/xw6w8dnOtCDgEItQFJG8KyXPzQXzcODDrrbOg=="],
"@aws-sdk/xml-builder/fast-xml-parser/path-expression-matcher": ["path-expression-matcher@1.4.0", "", {}, "sha512-s4DQMxIdhj3jLFWd9LxHOplj4p9yQ4ffMGowFf3cpEgrrJjEhN0V5nxw4Ye1EViAGDoL4/1AeO6qHpqYPOzE4Q=="],
"docx/@types/node/undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"https-proxy-agent/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"protobufjs/@types/node/undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"@aws-crypto/sha1-browser/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
}
}

View file

@ -0,0 +1,340 @@
-- Mike one-shot Supabase schema
-- Based on supabase-migration.sql plus the later backend/migrations/*.sql files.
-- Use this for a fresh Supabase database. Existing deployments should continue
-- to apply the incremental migration files instead.
create extension if not exists "pgcrypto";
-- ---------------------------------------------------------------------------
-- User profiles
-- ---------------------------------------------------------------------------
create table if not exists public.user_profiles (
id uuid primary key default gen_random_uuid(),
user_id uuid not null unique references auth.users(id) on delete cascade,
display_name text,
organisation text,
tier text not null default 'Free',
message_credits_used integer not null default 0,
credits_reset_date timestamptz not null default (now() + interval '30 days'),
tabular_model text not null default 'gemini-3-flash-preview',
claude_api_key text,
gemini_api_key text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists idx_user_profiles_user
on public.user_profiles(user_id);
alter table public.user_profiles enable row level security;
drop policy if exists "Users can view their own profile" on public.user_profiles;
create policy "Users can view their own profile"
on public.user_profiles for select
using (auth.uid() = user_id);
drop policy if exists "Users can update their own profile" on public.user_profiles;
create policy "Users can update their own profile"
on public.user_profiles for update
using (auth.uid() = user_id);
create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
insert into public.user_profiles (user_id)
values (new.id)
on conflict (user_id) do nothing;
return new;
exception when others then
-- Never block signup if the profile insert fails.
return new;
end;
$$;
drop trigger if exists on_auth_user_created on auth.users;
create trigger on_auth_user_created
after insert on auth.users
for each row execute procedure public.handle_new_user();
-- ---------------------------------------------------------------------------
-- Projects and documents
-- ---------------------------------------------------------------------------
create table if not exists public.projects (
id uuid primary key default gen_random_uuid(),
user_id text not null,
name text not null,
cm_number text,
visibility text not null default 'private',
shared_with jsonb not null default '[]'::jsonb,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists idx_projects_user
on public.projects(user_id);
create index if not exists projects_shared_with_idx
on public.projects using gin (shared_with);
create table if not exists public.project_subfolders (
id uuid primary key default gen_random_uuid(),
project_id uuid not null references public.projects(id) on delete cascade,
user_id text not null,
name text not null,
parent_folder_id uuid references public.project_subfolders(id) on delete cascade,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists idx_project_subfolders_project
on public.project_subfolders(project_id);
create table if not exists public.documents (
id uuid primary key default gen_random_uuid(),
project_id uuid references public.projects(id) on delete cascade,
user_id text not null,
filename text not null,
file_type text,
size_bytes integer not null default 0,
page_count integer,
structure_tree jsonb,
status text not null default 'pending',
folder_id uuid references public.project_subfolders(id) on delete set null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists idx_documents_user_project
on public.documents(user_id, project_id);
create index if not exists idx_documents_project_folder
on public.documents(project_id, folder_id);
create table if not exists public.document_versions (
id uuid primary key default gen_random_uuid(),
document_id uuid not null references public.documents(id) on delete cascade,
storage_path text not null,
pdf_storage_path text,
source text not null default 'upload',
version_number integer,
display_name text,
created_at timestamptz not null default now(),
constraint document_versions_source_check
check (source = any (array[
'upload'::text,
'user_upload'::text,
'assistant_edit'::text,
'user_accept'::text,
'user_reject'::text,
'generated'::text
]))
);
create index if not exists document_versions_document_id_idx
on public.document_versions(document_id, created_at desc);
create index if not exists document_versions_doc_vnum_idx
on public.document_versions(document_id, version_number);
alter table public.documents
add column if not exists current_version_id uuid
references public.document_versions(id) on delete set null;
create table if not exists public.document_edits (
id uuid primary key default gen_random_uuid(),
document_id uuid not null references public.documents(id) on delete cascade,
chat_message_id uuid,
version_id uuid not null references public.document_versions(id) on delete cascade,
change_id text not null,
del_w_id text,
ins_w_id text,
deleted_text text not null default '',
inserted_text text not null default '',
context_before text,
context_after text,
status text not null default 'pending'
check (status = any (array[
'pending'::text,
'accepted'::text,
'rejected'::text
])),
created_at timestamptz not null default now(),
resolved_at timestamptz
);
create index if not exists document_edits_document_id_idx
on public.document_edits(document_id, created_at desc);
create index if not exists document_edits_message_id_idx
on public.document_edits(chat_message_id);
create index if not exists document_edits_version_id_idx
on public.document_edits(version_id);
-- ---------------------------------------------------------------------------
-- Workflows
-- ---------------------------------------------------------------------------
create table if not exists public.workflows (
id uuid primary key default gen_random_uuid(),
user_id text,
title text not null,
type text not null,
prompt_md text,
columns_config jsonb,
practice text,
is_system boolean not null default false,
created_at timestamptz not null default now()
);
create index if not exists idx_workflows_user
on public.workflows(user_id);
create table if not exists public.hidden_workflows (
id uuid primary key default gen_random_uuid(),
user_id text not null,
workflow_id text not null,
created_at timestamptz not null default now(),
unique(user_id, workflow_id)
);
create index if not exists idx_hidden_workflows_user
on public.hidden_workflows(user_id);
create table if not exists public.workflow_shares (
id uuid primary key default gen_random_uuid(),
workflow_id uuid not null references public.workflows(id) on delete cascade,
shared_by_user_id text not null,
shared_with_email text not null,
allow_edit boolean not null default false,
created_at timestamptz not null default now(),
constraint workflow_shares_workflow_email_unique
unique(workflow_id, shared_with_email)
);
create index if not exists workflow_shares_workflow_id_idx
on public.workflow_shares(workflow_id);
create index if not exists workflow_shares_email_idx
on public.workflow_shares(shared_with_email);
-- ---------------------------------------------------------------------------
-- Assistant chats
-- ---------------------------------------------------------------------------
create table if not exists public.chats (
id uuid primary key default gen_random_uuid(),
project_id uuid references public.projects(id) on delete cascade,
user_id text not null,
title text,
created_at timestamptz not null default now()
);
create index if not exists idx_chats_user
on public.chats(user_id);
create index if not exists idx_chats_project
on public.chats(project_id);
create table if not exists public.chat_messages (
id uuid primary key default gen_random_uuid(),
chat_id uuid not null references public.chats(id) on delete cascade,
role text not null,
content jsonb,
files jsonb,
annotations jsonb,
created_at timestamptz not null default now()
);
create index if not exists idx_chat_messages_chat
on public.chat_messages(chat_id);
do $$
begin
if not exists (
select 1
from pg_constraint
where conname = 'document_edits_chat_message_id_fkey'
and conrelid = 'public.document_edits'::regclass
) then
alter table public.document_edits
add constraint document_edits_chat_message_id_fkey
foreign key (chat_message_id)
references public.chat_messages(id)
on delete set null;
end if;
end;
$$;
-- ---------------------------------------------------------------------------
-- Tabular reviews
-- ---------------------------------------------------------------------------
create table if not exists public.tabular_reviews (
id uuid primary key default gen_random_uuid(),
project_id uuid references public.projects(id) on delete cascade,
user_id text not null,
title text,
columns_config jsonb,
workflow_id uuid references public.workflows(id) on delete set null,
practice text,
shared_with jsonb not null default '[]'::jsonb,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists idx_tabular_reviews_user
on public.tabular_reviews(user_id);
create index if not exists idx_tabular_reviews_project
on public.tabular_reviews(project_id);
create index if not exists tabular_reviews_shared_with_idx
on public.tabular_reviews using gin (shared_with);
create table if not exists public.tabular_cells (
id uuid primary key default gen_random_uuid(),
review_id uuid not null references public.tabular_reviews(id) on delete cascade,
document_id uuid not null references public.documents(id) on delete cascade,
column_index integer not null,
content text,
citations jsonb,
status text not null default 'pending',
created_at timestamptz not null default now()
);
create index if not exists idx_tabular_cells_review
on public.tabular_cells(review_id, document_id, column_index);
create table if not exists public.tabular_review_chats (
id uuid primary key default gen_random_uuid(),
review_id uuid not null references public.tabular_reviews(id) on delete cascade,
user_id text not null,
title text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists tabular_review_chats_review_idx
on public.tabular_review_chats(review_id, updated_at desc);
create index if not exists tabular_review_chats_user_idx
on public.tabular_review_chats(user_id);
create table if not exists public.tabular_review_chat_messages (
id uuid primary key default gen_random_uuid(),
chat_id uuid not null references public.tabular_review_chats(id) on delete cascade,
role text not null,
content jsonb,
annotations jsonb,
created_at timestamptz not null default now()
);
create index if not exists tabular_review_chat_messages_chat_idx
on public.tabular_review_chat_messages(chat_id, created_at);

2
backend/nixpacks.toml Normal file
View file

@ -0,0 +1,2 @@
[phases.setup]
nixPkgs = ["libreoffice"]

4845
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

39
backend/package.json Normal file
View file

@ -0,0 +1,39 @@
{
"name": "mike-backend",
"version": "1.0.0",
"license": "AGPL-3.0-only",
"private": true,
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.90.0",
"@aws-sdk/client-s3": "^3.787.0",
"@aws-sdk/s3-request-presigner": "^3.787.0",
"@google/genai": "^1.50.1",
"@supabase/supabase-js": "^2.49.4",
"cors": "^2.8.5",
"docx": "^9.5.0",
"dotenv": "^17.4.1",
"express": "^4.21.2",
"fast-diff": "^1.3.0",
"fast-xml-parser": "^5.7.1",
"jszip": "^3.10.1",
"libreoffice-convert": "^1.6.0",
"mammoth": "^1.9.0",
"multer": "^1.4.5-lts.2",
"pdfjs-dist": "^4.10.38",
"resend": "^4.5.1"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/multer": "^1.4.12",
"@types/node": "^22.14.1",
"prettier": "^3.8.1",
"tsx": "^4.19.3",
"typescript": "^5.8.3"
}
}

39
backend/src/index.ts Normal file
View file

@ -0,0 +1,39 @@
import "dotenv/config";
import express from "express";
import cors from "cors";
import { chatRouter } from "./routes/chat";
import { projectsRouter } from "./routes/projects";
import { projectChatRouter } from "./routes/projectChat";
import { documentsRouter } from "./routes/documents";
import { tabularRouter } from "./routes/tabular";
import { workflowsRouter } from "./routes/workflows";
import { userRouter } from "./routes/user";
import { downloadsRouter } from "./routes/downloads";
const app = express();
const PORT = process.env.PORT ?? 3001;
app.use(
cors({
origin: process.env.FRONTEND_URL ?? "http://localhost:3000",
credentials: true,
}),
);
app.use(express.json({ limit: "50mb" }));
app.use("/chat", chatRouter);
app.use("/projects", projectsRouter);
app.use("/projects/:projectId/chat", projectChatRouter);
app.use("/single-documents", documentsRouter);
app.use("/tabular-review", tabularRouter);
app.use("/workflows", workflowsRouter);
app.use("/user", userRouter);
app.use("/users", userRouter);
app.use("/download", downloadsRouter);
app.get("/health", (_req, res) => res.json({ ok: true }));
app.listen(PORT, () => {
console.log(`Mike backend running on port ${PORT}`);
});

146
backend/src/lib/access.ts Normal file
View file

@ -0,0 +1,146 @@
/**
* Project / document access helpers.
*
* Sharing makes the previous "scope by user_id" pattern incorrect a doc
* can belong to user A's project that A has shared with B's email, and B
* must still be able to read/edit it. These helpers centralize the
* "owner OR shared project member" check so every route uses the same
* logic instead of re-implementing the join.
*
* Returned `isOwner` lets callers gate operations that should stay
* owner-only (delete, rename, member management).
*/
import type { createServerSupabase } from "./supabase";
type Db = ReturnType<typeof createServerSupabase>;
export type ProjectAccess =
| {
ok: true;
isOwner: boolean;
project: {
id: string;
user_id: string;
shared_with: string[] | null;
};
}
| { ok: false };
export async function checkProjectAccess(
projectId: string,
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<ProjectAccess> {
const { data: project } = await db
.from("projects")
.select("id, user_id, shared_with")
.eq("id", projectId)
.single();
if (!project) return { ok: false };
const proj = project as {
id: string;
user_id: string;
shared_with: string[] | null;
};
if (proj.user_id === userId) {
return { ok: true, isOwner: true, project: proj };
}
const sharedWith = Array.isArray(proj.shared_with) ? proj.shared_with : [];
const email = (userEmail ?? "").toLowerCase();
if (
email &&
sharedWith.some((e) => (e ?? "").toLowerCase() === email)
) {
return { ok: true, isOwner: false, project: proj };
}
return { ok: false };
}
/**
* Check whether the current user can access a document the caller has
* already loaded (saves a round-trip vs. having the helper re-fetch).
* Owner-of-doc passes immediately; otherwise we fall through to a
* project-membership check via `shared_with`.
*/
export async function ensureDocAccess(
doc: { user_id: string; project_id: string | null },
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<{ ok: true; isOwner: boolean } | { ok: false }> {
if (doc.user_id === userId) return { ok: true, isOwner: true };
if (!doc.project_id) return { ok: false };
const access = await checkProjectAccess(
doc.project_id,
userId,
userEmail,
db,
);
if (access.ok) return { ok: true, isOwner: false };
return { ok: false };
}
/**
* Same shape as `ensureDocAccess`, for tabular_reviews. A review can be
* shared in two ways:
* 1. Indirectly if `project_id` is set, everyone with project access
* can read/operate on it.
* 2. Directly `tabular_reviews.shared_with` is a per-review email list
* so standalone reviews (project_id null) can also be shared.
* The owner (review.user_id) always has access.
*/
export async function ensureReviewAccess(
review: {
user_id: string;
project_id: string | null;
shared_with?: string[] | null;
},
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<{ ok: true; isOwner: boolean } | { ok: false }> {
if (review.user_id === userId) return { ok: true, isOwner: true };
const email = (userEmail ?? "").toLowerCase();
if (email && Array.isArray(review.shared_with)) {
if (review.shared_with.some((e) => (e ?? "").toLowerCase() === email)) {
return { ok: true, isOwner: false };
}
}
if (!review.project_id) return { ok: false };
const access = await checkProjectAccess(
review.project_id,
userId,
userEmail,
db,
);
if (access.ok) return { ok: true, isOwner: false };
return { ok: false };
}
/**
* Returns the set of project IDs the user can access own projects plus
* any project where their email is in `shared_with`. Used to scope chat
* lists and similar collection queries.
*/
export async function listAccessibleProjectIds(
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<string[]> {
const [{ data: own }, { data: shared }] = await Promise.all([
db.from("projects").select("id").eq("user_id", userId),
userEmail
? db
.from("projects")
.select("id")
.contains("shared_with", [userEmail])
.neq("user_id", userId)
: Promise.resolve({ data: [] as { id: string }[] }),
]);
const ids = new Set<string>();
for (const p of (own ?? []) as { id: string }[]) ids.add(p.id);
for (const p of (shared ?? []) as { id: string }[]) ids.add(p.id);
return [...ids];
}

View file

@ -0,0 +1,76 @@
export const BUILTIN_WORKFLOWS: { id: string; title: string; prompt_md: string }[] = [
{
id: "builtin-cp-checklist",
title: "Generate CP Checklist",
prompt_md:
"## Generate Conditions Precedent Checklist\n\n" +
"Review the uploaded credit agreement or financing document and generate a comprehensive " +
"Conditions Precedent (CP) checklist.\n\n" +
"You MUST use the generate_docx tool to produce the checklist as a downloadable Word document. " +
"You MUST pass landscape: true to the generate_docx tool — the document must be in landscape orientation. " +
"Do not display the checklist inline — generate the .docx file and provide the download link.\n\n" +
"Structure the document as follows:\n" +
"- For each category of conditions (e.g. Corporate, Financial, Legal, Security), add a section with a heading\n" +
"- Under each category heading, include a table with exactly these four columns in this order:\n" +
" 1. Index — sequential number within the category (1, 2, 3…)\n" +
" 2. Clause Number — the clause or schedule reference from the agreement\n" +
" 3. Clause — a concise description of the condition precedent\n" +
" 4. Status — leave blank (empty string) for the user to fill in\n\n" +
"Use the table field in the section object (not content) for each category's rows.\n\n" +
"Before finalizing, double-check that every table is formatted correctly: each table must have exactly the four columns above in the same order, headers must match exactly (Index, Clause Number, Clause, Status), every row must have the same number of cells as the headers, the Index column must be sequential starting from 1 within each category, and no cells should contain stray markdown, newlines, or placeholder text (use an empty string for Status).",
},
{
id: "builtin-credit-summary",
title: "Credit Agreement Summary",
prompt_md:
"## Credit Agreement Summary\n\n" +
"Review the uploaded credit agreement and produce a comprehensive legal summary covering the following topics. " +
"For each section, identify the key provisions, quote the relevant clause or schedule references, and flag any unusual, onerous, or non-market terms.\n\n" +
"1. **Lenders** — All lenders or members of the lender syndicate, including their full legal name and role (e.g. mandated lead arranger, original lender, agent bank)\n" +
"2. **Borrowers** — All borrowers, including their full legal name and jurisdiction of incorporation\n" +
"3. **Guarantors** — All guarantors, including their full legal name and the scope of their guarantee obligation\n" +
"4. **Other Parties** — Any other material parties (e.g. facility agent, security agent, hedge counterparties, issuing bank) and their roles\n" +
"5. **Date of Agreement** — Date of the credit agreement\n" +
"6. **Facilities** — Each facility available (e.g. Revolving Credit Facility, Term Loan A, Term Loan B, Term Loan C), the facility type, tranche name, and any key structural features\n" +
"7. **Amount** — Total committed amount across all facilities, the currency, and breakdown by tranche if applicable\n" +
"8. **Purpose** — Stated purpose for which borrowings may be used and any restrictions on use of proceeds\n" +
"9. **Interest** — Applicable reference rate (e.g. SOFR, EURIBOR, base rate), the margin, any margin ratchet mechanism, and how interest periods are structured\n" +
"10. **Commitment Fee** — Commitment or utilisation fees, the applicable rate, how they are calculated, and the basis (e.g. undrawn commitment, average utilisation)\n" +
"11. **Repayment Schedule** — Repayment profile for each facility, whether by scheduled instalments or bullet repayment, and the repayment dates and amounts\n" +
"12. **Maturity** — Final maturity date for each facility\n" +
"13. **Security** — Each class of security granted or required (e.g. share pledges, fixed and floating charges, real estate mortgages, account pledges) and the assets or entities over which security is taken\n" +
"14. **Guarantees** — Guarantee obligations, the guarantors, the scope of the guarantee, and any limitations (e.g. up-stream guarantee limitations, guarantor coverage test)\n" +
"15. **Financial Covenants** — Each financial covenant, the metric (e.g. leverage ratio, interest cover, cashflow cover), the applicable test, testing frequency, and any equity cure rights\n" +
"16. **Events of Default** — Each event of default, noting any grace periods, materiality thresholds, or cross-default provisions\n" +
"17. **Assignment** — Restrictions or permissions on assignment or transfer (e.g. white/blacklists, borrower consent for lender transfers; restrictions on borrower assignment)\n" +
"18. **Change of Control** — What constitutes a change of control, what obligations it triggers (e.g. mandatory prepayment, cancellation, lender consent), and any cure period\n" +
"19. **Prepayment Fee** — Any prepayment fees, make-whole premiums, or soft-call protections, the applicable fee, the period during which it applies, and any exceptions (e.g. prepayment from insurance proceeds or asset disposals)\n" +
"20. **Governing Law** — Governing law of the agreement\n" +
"21. **Dispute Resolution** — Whether disputes go to litigation or arbitration, the chosen forum or seat, and any submission to jurisdiction provisions\n\n" +
"Deliver the summary inline in your chat response — do NOT call generate_docx. Only produce a downloadable Word document if the user explicitly asks for one.",
},
{
id: "builtin-sha-summary",
title: "Shareholder Agreement Summary",
prompt_md:
"## Shareholder Agreement Summary\n\n" +
"Review the uploaded shareholder agreement and produce a comprehensive legal summary covering the following topics. " +
"For each section, identify the key provisions, quote the relevant clause references, and flag any unusual, onerous, or market-standard deviations.\n\n" +
"1. **Parties & Shareholdings** — Full legal names, roles, share classes held, and percentage interests (on a fully diluted basis if stated)\n" +
"2. **Share Classes & Rights** — For each class: voting rights, dividend rights, liquidation preference, conversion or redemption features\n" +
"3. **Board Composition & Governance** — Board size, director appointment rights (and the shareholding thresholds required to maintain them), quorum, and casting vote\n" +
"4. **Reserved Matters** — Decisions requiring a special majority, unanimity, or a specific shareholder's consent; note the threshold and whose consent is required for each\n" +
"5. **Pre-emption on New Shares** — Who holds pre-emption rights, procedure, timeline, and any carve-outs (e.g. employee option schemes)\n" +
"6. **Transfer Restrictions** — Lock-up periods, prohibited transfers, permitted transfers (e.g. to affiliates), and any board or shareholder approval requirements\n" +
"7. **Right of First Refusal / Pre-emption on Transfer** — Trigger, procedure, pricing mechanics, and any exceptions\n" +
"8. **Drag-Along Rights** — Who holds the right, threshold to trigger, conditions (e.g. minimum price, independent valuation), and minority protections\n" +
"9. **Tag-Along Rights** — Who holds the right, triggering threshold, exercise procedure, and price terms\n" +
"10. **Anti-Dilution Protections** — Type (full ratchet, weighted average), trigger events, calculation mechanics, and exceptions\n" +
"11. **Dividend Policy** — Any obligation or target to pay dividends, preferential dividend rights, and restrictions on distributions\n" +
"12. **Exit & Liquidity** — Agreed exit routes (trade sale, IPO, drag sale), timelines, and liquidation preferences on exit\n" +
"13. **Deadlock** — Deadlock definition, escalation and resolution mechanisms (e.g. Russian roulette, put/call options), and consequences if unresolved\n" +
"14. **Non-Compete & Non-Solicitation** — Who is bound, scope of activities and geography, duration, and carve-outs\n" +
"15. **Governing Law & Dispute Resolution** — Applicable law, forum, arbitration or litigation, and any mandatory escalation steps\n\n" +
"Generate the summary as a downloadable Word document.",
},
];

2838
backend/src/lib/chatTools.ts Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,59 @@
import { promisify } from "util";
import JSZip from "jszip";
let _convert:
| ((buf: Buffer, ext: string, filter: undefined) => Promise<Buffer>)
| null = null;
async function getConvert() {
if (!_convert) {
const libre = await import("libreoffice-convert");
_convert = promisify(libre.default.convert.bind(libre.default));
}
return _convert;
}
/**
* Some older Windows/Word archives store .docx entries with backslash
* separators (e.g. `word\document.xml`). Mammoth and LibreOffice both look
* up entries by exact string and miss those files, producing empty output
* or conversion failures. Rewrite any such entries to the canonical
* forward-slash form before handing the buffer off.
*/
export async function normalizeDocxZipPaths(buffer: Buffer): Promise<Buffer> {
let zip: JSZip;
try {
zip = await JSZip.loadAsync(buffer);
} catch {
return buffer;
}
const renames: [string, string][] = [];
zip.forEach((relativePath) => {
if (relativePath.includes("\\")) {
renames.push([relativePath, relativePath.replace(/\\/g, "/")]);
}
});
if (renames.length === 0) return buffer;
for (const [oldPath, newPath] of renames) {
const entry = zip.file(oldPath);
if (!entry) continue;
const content = await entry.async("nodebuffer");
zip.remove(oldPath);
zip.file(newPath, content);
}
return zip.generateAsync({ type: "nodebuffer" });
}
/**
* Convert a DOCX/DOC buffer to PDF using LibreOffice.
* Throws if LibreOffice is not installed or conversion fails.
*/
export async function docxToPdf(buffer: Buffer): Promise<Buffer> {
const convert = await getConvert();
const normalized = await normalizeDocxZipPaths(buffer);
return convert(normalized, ".pdf", undefined);
}
export function convertedPdfKey(userId: string, docId: string): string {
return `converted-pdfs/${userId}/${docId}.pdf`;
}

View file

@ -0,0 +1,159 @@
import type { createServerSupabase } from "./supabase";
type Supa = ReturnType<typeof createServerSupabase>;
interface DocRow {
id: string;
latest_version_number?: number | null;
[k: string]: unknown;
}
interface VersionPathRow extends DocRow {
/** Set from document_versions.storage_path of the active version. */
storage_path?: string | null;
/** Set from document_versions.pdf_storage_path of the active version. */
pdf_storage_path?: string | null;
current_version_id?: string | null;
/** Set from document_versions.version_number of the active version. */
active_version_number?: number | null;
}
export interface ActiveVersion {
id: string;
storage_path: string;
pdf_storage_path: string | null;
version_number: number | null;
display_name: string | null;
source: string | null;
}
/**
* Resolve storage paths for a document. Prefers the version pointed to by
* `versionId` (if it belongs to this document); else falls back to
* `documents.current_version_id`. Returns null if no usable version exists.
*
* After the storage_path/pdf_storage_path columns moved off `documents`,
* every read-from-storage path goes through here.
*/
export async function loadActiveVersion(
documentId: string,
db: Supa,
versionId?: string | null,
): Promise<ActiveVersion | null> {
const { data: doc } = await db
.from("documents")
.select("current_version_id")
.eq("id", documentId)
.single();
const targetVersionId =
(typeof versionId === "string" && versionId) ||
(doc?.current_version_id as string | undefined) ||
null;
if (!targetVersionId) return null;
const { data: v } = await db
.from("document_versions")
.select(
"id, document_id, storage_path, pdf_storage_path, version_number, display_name, source",
)
.eq("id", targetVersionId)
.single();
if (!v || v.document_id !== documentId || !v.storage_path) return null;
return {
id: v.id as string,
storage_path: v.storage_path as string,
pdf_storage_path: (v.pdf_storage_path as string | null) ?? null,
version_number: (v.version_number as number | null) ?? null,
display_name: (v.display_name as string | null) ?? null,
source: (v.source as string | null) ?? null,
};
}
/**
* For a list of documents, look up the active version for each and merge
* `storage_path` + `pdf_storage_path` onto the row. One round-trip total
* regardless of list size. Documents with no current_version_id retain
* null paths.
*/
export async function attachActiveVersionPaths<T extends VersionPathRow>(
db: Supa,
docs: T[],
): Promise<T[]> {
if (docs.length === 0) return docs;
const versionIds = docs
.map((d) => d.current_version_id)
.filter((id): id is string => typeof id === "string");
if (versionIds.length === 0) {
for (const d of docs) {
d.storage_path = null;
d.pdf_storage_path = null;
}
return docs;
}
const { data: rows } = await db
.from("document_versions")
.select("id, storage_path, pdf_storage_path, version_number")
.in("id", versionIds);
const byId = new Map<
string,
{
storage_path: string | null;
pdf_storage_path: string | null;
version_number: number | null;
}
>();
for (const r of (rows ?? []) as {
id: string;
storage_path: string | null;
pdf_storage_path: string | null;
version_number: number | null;
}[]) {
byId.set(r.id, {
storage_path: r.storage_path ?? null,
pdf_storage_path: r.pdf_storage_path ?? null,
version_number: r.version_number ?? null,
});
}
for (const d of docs) {
const v = d.current_version_id ? byId.get(d.current_version_id) : null;
d.storage_path = v?.storage_path ?? null;
d.pdf_storage_path = v?.pdf_storage_path ?? null;
d.active_version_number = v?.version_number ?? null;
}
return docs;
}
/**
* Given a list of document rows, attach `latest_version_number` the
* max `version_number` across all assistant_edit rows for that doc, or
* null if none. Mutates rows in place and returns the same reference.
* One extra query regardless of list size.
*/
export async function attachLatestVersionNumbers<T extends DocRow>(
db: Supa,
docs: T[],
): Promise<T[]> {
if (docs.length === 0) return docs;
const ids = docs.map((d) => d.id);
const { data: rows } = await db
.from("document_versions")
.select("document_id, version_number")
.in("document_id", ids)
.eq("source", "assistant_edit")
.not("version_number", "is", null);
const latestByDoc = new Map<string, number>();
for (const r of (rows ?? []) as {
document_id: string;
version_number: number | null;
}[]) {
if (r.version_number == null) continue;
const prev = latestByDoc.get(r.document_id) ?? 0;
if (r.version_number > prev)
latestByDoc.set(r.document_id, r.version_number);
}
for (const d of docs) {
d.latest_version_number = latestByDoc.get(d.id) ?? null;
}
return docs;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,78 @@
import crypto from "crypto";
/**
* HMAC-signed, non-expiring download tokens.
*
* The token encodes the R2 storage path + filename; the backend route
* `/download/:token` validates the signature and streams the file. This
* gives persistent links safe to store in chat history without signed-URL
* expiry or R2 CORS headaches.
*/
function getSecret(): string {
return (
process.env.DOWNLOAD_SIGNING_SECRET ??
process.env.SUPABASE_SECRET_KEY ??
"dev-secret"
);
}
function b64urlEncode(buf: Buffer): string {
return buf
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/g, "");
}
function b64urlDecode(s: string): Buffer {
let t = s.replace(/-/g, "+").replace(/_/g, "/");
while (t.length % 4) t += "=";
return Buffer.from(t, "base64");
}
function timingSafeEqStr(a: string, b: string): boolean {
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
export function signDownload(path: string, filename: string): string {
const payload = JSON.stringify({ p: path, f: filename });
const enc = b64urlEncode(Buffer.from(payload, "utf8"));
const sig = crypto
.createHmac("sha256", getSecret())
.update(enc)
.digest();
return `${enc}.${b64urlEncode(sig)}`;
}
export function verifyDownload(
token: string,
): { path: string; filename: string } | null {
const parts = token.split(".");
if (parts.length !== 2) return null;
const [enc, sigEnc] = parts;
const expected = crypto
.createHmac("sha256", getSecret())
.update(enc)
.digest();
if (!timingSafeEqStr(sigEnc, b64urlEncode(expected))) return null;
try {
const parsed = JSON.parse(b64urlDecode(enc).toString("utf8")) as {
p: string;
f: string;
};
if (!parsed?.p || !parsed?.f) return null;
return { path: parsed.p, filename: parsed.f };
} catch {
return null;
}
}
/**
* Returns a relative download URL (e.g. "/download/abc.def"). The frontend
* prefixes it with NEXT_PUBLIC_API_BASE_URL when rendering `<a href=…>`.
*/
export function buildDownloadUrl(path: string, filename: string): string {
return `/download/${signDownload(path, filename)}`;
}

View file

@ -0,0 +1,172 @@
import Anthropic from "@anthropic-ai/sdk";
import type { Tool } from "@anthropic-ai/sdk/resources/messages/messages";
import * as fs from "fs";
import * as path from "path";
import type {
StreamChatParams,
StreamChatResult,
NormalizedToolCall,
NormalizedToolResult,
} from "./types";
import { toClaudeTools } from "./tools";
const RAW_STREAM_LOG_PATH = path.resolve(
process.cwd(),
"claude-raw-stream.log",
);
type ContentBlock =
| { type: "text"; text: string }
| { type: "tool_use"; id: string; name: string; input: unknown }
| { type: string; [key: string]: unknown };
type NativeMessage = {
role: "user" | "assistant";
content: string | ContentBlock[];
};
const MAX_TOKENS = 16384;
function client(override?: string | null): Anthropic {
const apiKey = override?.trim() || process.env.ANTHROPIC_API_KEY || "";
return new Anthropic({ apiKey });
}
function toNativeMessages(
messages: StreamChatParams["messages"],
): NativeMessage[] {
return messages.map((m) => ({ role: m.role, content: m.content }));
}
export async function streamClaude(
params: StreamChatParams,
): Promise<StreamChatResult> {
const {
model,
systemPrompt,
tools = [],
callbacks = {},
runTools,
apiKeys,
enableThinking,
} = params;
const maxIter = params.maxIterations ?? 10;
const anthropic = client(apiKeys?.claude);
const claudeTools = toClaudeTools(tools);
const messages: NativeMessage[] = toNativeMessages(params.messages);
let fullText = "";
for (let iter = 0; iter < maxIter; iter++) {
const stream = anthropic.messages.stream({
model,
system: systemPrompt,
messages: messages as Anthropic.MessageParam[],
tools: claudeTools.length
? (claudeTools as unknown as Tool[])
: undefined,
max_tokens: MAX_TOKENS,
// Claude 4.x models require `thinking.type: "adaptive"` and
// drive effort via `output_config.effort` rather than a fixed
// token budget. We only opt in when the caller requested it.
...(enableThinking
? ({
thinking: { type: "adaptive" },
output_config: { effort: "high" },
} as unknown as Record<string, unknown>)
: {}),
// Extended thinking requires temperature to be default (omitted).
});
let sawThinking = false;
stream.on("streamEvent", (event) => {
const line = JSON.stringify(event);
console.log("[claude raw stream]", line);
fs.appendFile(RAW_STREAM_LOG_PATH, line + "\n", () => {});
});
stream.on("text", (delta) => {
callbacks.onContentDelta?.(delta);
});
if (enableThinking) {
stream.on("thinking", (delta) => {
sawThinking = true;
callbacks.onReasoningDelta?.(delta);
});
}
const final = await stream.finalMessage();
if (sawThinking) callbacks.onReasoningBlockEnd?.();
const stopReason = final.stop_reason;
const assistantBlocks = final.content as ContentBlock[];
// Extract text content and tool_use calls from the final assistant
// message so we can accumulate text and drive the tool-call loop.
const toolCalls: NormalizedToolCall[] = [];
for (const block of assistantBlocks) {
if (block.type === "text") {
const txt = (block as { text: string }).text;
if (typeof txt === "string") fullText += txt;
} else if (block.type === "tool_use") {
const tu = block as {
id: string;
name: string;
input: unknown;
};
const call: NormalizedToolCall = {
id: tu.id,
name: tu.name,
input: (tu.input as Record<string, unknown>) ?? {},
};
callbacks.onToolCallStart?.(call);
toolCalls.push(call);
}
}
if (stopReason !== "tool_use" || !toolCalls.length || !runTools) {
break;
}
const results = await runTools(toolCalls);
// Record the assistant turn (preserving the original content blocks,
// which Claude requires on the follow-up) and the user turn that
// carries the tool_result blocks.
messages.push({ role: "assistant", content: assistantBlocks });
messages.push({
role: "user",
content: results.map((r) => ({
type: "tool_result",
tool_use_id: r.tool_use_id,
content: r.content,
})),
});
}
return { fullText };
}
export async function completeClaudeText(params: {
model: string;
systemPrompt?: string;
user: string;
maxTokens?: number;
apiKeys?: { claude?: string | null };
}): Promise<string> {
const anthropic = client(params.apiKeys?.claude);
const resp = await anthropic.messages.create({
model: params.model,
max_tokens: params.maxTokens ?? 512,
system: params.systemPrompt,
messages: [{ role: "user", content: params.user }],
});
const text = resp.content
.filter((b): b is Anthropic.TextBlock => b.type === "text")
.map((b) => b.text)
.join("");
return text;
}
// Helper re-export for callers wanting to hand normalized results back in.
export type { NormalizedToolResult };

View file

@ -0,0 +1,162 @@
import { GoogleGenAI } from "@google/genai";
import type {
StreamChatParams,
StreamChatResult,
NormalizedToolCall,
} from "./types";
import { toGeminiTools } from "./tools";
type GeminiPart = {
text?: string;
// Set by Gemini when the text content is a thought summary rather than
// final-answer prose. Requires `thinkingConfig.includeThoughts: true`.
thought?: boolean;
functionCall?: { id?: string; name: string; args?: Record<string, unknown> };
functionResponse?: {
id?: string;
name: string;
response: Record<string, unknown>;
};
// Gemini 3 returns a thoughtSignature on parts that contain reasoning or
// a functionCall. It must be echoed back verbatim on the same part when
// we replay the model's turn, or the API rejects the next call.
thoughtSignature?: string;
};
type GeminiContent = {
role: "user" | "model";
parts: GeminiPart[];
};
function client(override?: string | null): GoogleGenAI {
const apiKey = override?.trim() || process.env.GEMINI_API_KEY || "";
return new GoogleGenAI({ apiKey });
}
function toNativeContents(messages: StreamChatParams["messages"]): GeminiContent[] {
return messages.map((m) => ({
role: m.role === "assistant" ? "model" : "user",
parts: [{ text: m.content }],
}));
}
export async function streamGemini(
params: StreamChatParams,
): Promise<StreamChatResult> {
const { model, systemPrompt, tools = [], callbacks = {}, runTools, apiKeys, enableThinking } = params;
const maxIter = params.maxIterations ?? 10;
const ai = client(apiKeys?.gemini);
const functionDeclarations = toGeminiTools(tools);
const contents: GeminiContent[] = toNativeContents(params.messages);
let fullText = "";
for (let iter = 0; iter < maxIter; iter++) {
const stream = await ai.models.generateContentStream({
model,
contents: contents as never,
config: {
systemInstruction: systemPrompt,
tools: functionDeclarations.length
? [{ functionDeclarations } as never]
: undefined,
// When enabled, ask Gemini to surface thought summaries.
// When disabled, explicitly zero the thinking budget so the
// model skips thinking entirely (saves tokens and latency
// for bulk extraction jobs).
thinkingConfig: enableThinking
? { includeThoughts: true }
: { thinkingBudget: 0 },
},
});
// Per-iteration accumulators.
const textParts: string[] = [];
const callParts: GeminiPart[] = [];
const toolCalls: NormalizedToolCall[] = [];
let sawThinking = false;
for await (const chunk of stream) {
console.log("[gemini stream chunk]", JSON.stringify(chunk, null, 2));
const parts =
(chunk as { candidates?: { content?: { parts?: GeminiPart[] } }[] })
.candidates?.[0]?.content?.parts ?? [];
for (const part of parts) {
if (part.text) {
if (part.thought) {
sawThinking = true;
callbacks.onReasoningDelta?.(part.text);
} else {
textParts.push(part.text);
callbacks.onContentDelta?.(part.text);
}
}
if (part.functionCall) {
// Preserve the whole part (including thoughtSignature)
// so it can be echoed verbatim in the replay turn.
callParts.push(part);
const call: NormalizedToolCall = {
id: part.functionCall.id ?? `${part.functionCall.name}-${toolCalls.length}`,
name: part.functionCall.name,
input: part.functionCall.args ?? {},
};
callbacks.onToolCallStart?.(call);
toolCalls.push(call);
}
}
}
if (sawThinking) callbacks.onReasoningBlockEnd?.();
fullText += textParts.join("");
if (!toolCalls.length || !runTools) {
break;
}
const results = await runTools(toolCalls);
// Append the model's turn (text + functionCall parts, in that order)
// and the matching functionResponse turn.
const modelParts: GeminiPart[] = [];
if (textParts.length) modelParts.push({ text: textParts.join("") });
for (const cp of callParts) modelParts.push(cp);
contents.push({ role: "model", parts: modelParts });
contents.push({
role: "user",
parts: results.map((r) => {
const match = toolCalls.find((c) => c.id === r.tool_use_id);
return {
functionResponse: {
...(r.tool_use_id && !r.tool_use_id.startsWith(match?.name ?? "")
? { id: r.tool_use_id }
: {}),
name: match?.name ?? "tool",
response: { output: r.content },
},
};
}),
});
}
return { fullText };
}
export async function completeGeminiText(params: {
model: string;
systemPrompt?: string;
user: string;
apiKeys?: { gemini?: string | null };
}): Promise<string> {
const ai = client(params.apiKeys?.gemini);
const resp = await ai.models.generateContent({
model: params.model,
contents: [{ role: "user", parts: [{ text: params.user }] }],
config: params.systemPrompt
? { systemInstruction: params.systemPrompt }
: undefined,
});
return resp.text ?? "";
}

View file

@ -0,0 +1,27 @@
import { streamClaude, completeClaudeText } from "./claude";
import { streamGemini, completeGeminiText } from "./gemini";
import { providerForModel } from "./models";
import type { StreamChatParams, StreamChatResult, UserApiKeys } from "./types";
export * from "./types";
export * from "./models";
export async function streamChatWithTools(
params: StreamChatParams,
): Promise<StreamChatResult> {
const provider = providerForModel(params.model);
if (provider === "claude") return streamClaude(params);
return streamGemini(params);
}
export async function completeText(params: {
model: string;
systemPrompt?: string;
user: string;
maxTokens?: number;
apiKeys?: UserApiKeys;
}): Promise<string> {
const provider = providerForModel(params.model);
if (provider === "claude") return completeClaudeText(params);
return completeGeminiText(params);
}

View file

@ -0,0 +1,48 @@
import type { Provider } from "./types";
// ---------------------------------------------------------------------------
// Canonical model IDs
// ---------------------------------------------------------------------------
// Main-chat tier (top-end) — user picks one of these per message.
export const CLAUDE_MAIN_MODELS = ["claude-opus-4-7", "claude-sonnet-4-6"] as const;
export const GEMINI_MAIN_MODELS = [
"gemini-3.1-pro-preview",
"gemini-3-flash-preview",
] as const;
// Mid-tier (used for tabular review) — user picks one in account settings.
export const CLAUDE_MID_MODELS = ["claude-sonnet-4-6"] as const;
export const GEMINI_MID_MODELS = ["gemini-3-flash-preview"] as const;
// Low-tier (used for title generation, lightweight extractions) — user picks
// one in account settings.
export const CLAUDE_LOW_MODELS = ["claude-haiku-4-5"] as const;
export const GEMINI_LOW_MODELS = ["gemini-3.1-flash-lite-preview"] as const;
export const DEFAULT_MAIN_MODEL = "gemini-3-flash-preview";
export const DEFAULT_TITLE_MODEL = "gemini-3.1-flash-lite-preview";
export const DEFAULT_TABULAR_MODEL = "gemini-3-flash-preview";
const ALL_MODELS = new Set<string>([
...CLAUDE_MAIN_MODELS,
...GEMINI_MAIN_MODELS,
...CLAUDE_MID_MODELS,
...GEMINI_MID_MODELS,
...CLAUDE_LOW_MODELS,
...GEMINI_LOW_MODELS,
]);
// ---------------------------------------------------------------------------
// Provider inference
// ---------------------------------------------------------------------------
export function providerForModel(model: string): Provider {
if (model.startsWith("claude")) return "claude";
if (model.startsWith("gemini")) return "gemini";
throw new Error(`Unknown model id: ${model}`);
}
export function resolveModel(id: string | null | undefined, fallback: string): string {
if (id && ALL_MODELS.has(id)) return id;
return fallback;
}

View file

@ -0,0 +1,74 @@
import type { OpenAIToolSchema } from "./types";
// ---------------------------------------------------------------------------
// Tool-schema adapters
// ---------------------------------------------------------------------------
// Callers hand us OpenAI-style tool definitions. Provider-specific converters
// live here so the rest of the code never has to think about it.
export type ClaudeTool = {
name: string;
description: string;
input_schema: Record<string, unknown>;
};
export function toClaudeTools(tools: OpenAIToolSchema[]): ClaudeTool[] {
return tools.map((t) => ({
name: t.function.name,
description: t.function.description,
input_schema: normalizeSchema(t.function.parameters),
}));
}
export type GeminiFunctionDeclaration = {
name: string;
description: string;
parameters?: Record<string, unknown>;
};
export function toGeminiTools(tools: OpenAIToolSchema[]): GeminiFunctionDeclaration[] {
return tools.map((t) => {
const params = normalizeSchema(t.function.parameters);
// Gemini rejects `{ type: "object", properties: {} }` with no fields
// present; omit the parameters key entirely when empty.
const hasProps =
params &&
typeof params === "object" &&
Object.keys((params as { properties?: Record<string, unknown> }).properties ?? {}).length > 0;
return {
name: t.function.name,
description: t.function.description,
...(hasProps ? { parameters: params } : {}),
};
});
}
// ---------------------------------------------------------------------------
// Schema normalization
// ---------------------------------------------------------------------------
// The OpenAI tool schemas in the codebase already use plain JSON-Schema-lite
// shape. Both Claude and Gemini accept that shape. We only sanitise a couple
// of edge cases: `integer` is accepted by both, but we make sure arrays have
// `items` and objects have `properties` so Gemini doesn't error.
function normalizeSchema(schema: unknown): Record<string, unknown> {
if (!schema || typeof schema !== "object") {
return { type: "object", properties: {} };
}
const s = schema as Record<string, unknown>;
const type = s.type;
const out: Record<string, unknown> = { ...s };
if (type === "object") {
const props = (s.properties as Record<string, unknown>) ?? {};
const normProps: Record<string, unknown> = {};
for (const [k, v] of Object.entries(props)) {
normProps[k] = normalizeSchema(v);
}
out.properties = normProps;
}
if (type === "array" && s.items) {
out.items = normalizeSchema(s.items);
}
return out;
}

View file

@ -0,0 +1,64 @@
// Shared types for the LLM provider adapter.
// Callers always speak OpenAI-style tools + { role, content } messages; each
// provider translates internally.
export type Provider = "claude" | "gemini";
export type OpenAIToolSchema = {
type: "function";
function: {
name: string;
description: string;
parameters: Record<string, unknown>;
};
};
export type LlmMessage = {
role: "user" | "assistant";
content: string;
};
export type NormalizedToolCall = {
id: string;
name: string;
input: Record<string, unknown>;
};
export type NormalizedToolResult = {
tool_use_id: string;
content: string;
};
export type StreamCallbacks = {
onReasoningDelta?: (text: string) => void;
onReasoningBlockEnd?: () => void;
onContentDelta?: (text: string) => void;
onToolCallStart?: (call: NormalizedToolCall) => void;
};
export type UserApiKeys = {
claude?: string | null;
gemini?: string | null;
};
export type StreamChatParams = {
model: string;
systemPrompt: string;
messages: LlmMessage[];
tools?: OpenAIToolSchema[];
maxIterations?: number;
callbacks?: StreamCallbacks;
runTools?: (calls: NormalizedToolCall[]) => Promise<NormalizedToolResult[]>;
apiKeys?: UserApiKeys;
/**
* Enable provider-side reasoning/thinking. Off by default should only
* be turned on for interactive chat surfaces where the user actually
* benefits from seeing the thought stream. Bulk extraction jobs and
* one-shot completions should leave this off to save tokens and latency.
*/
enableThinking?: boolean;
};
export type StreamChatResult = {
fullText: string;
};

185
backend/src/lib/storage.ts Normal file
View file

@ -0,0 +1,185 @@
/**
* Cloudflare R2 storage utilities for Mike document management.
* R2 is S3-compatible uses @aws-sdk/client-s3.
*
* Required env vars:
* R2_ENDPOINT_URL https://<account-id>.r2.cloudflarestorage.com
* R2_ACCESS_KEY_ID R2 API token (Access Key ID)
* R2_SECRET_ACCESS_KEY R2 API token (Secret Access Key)
* R2_BUCKET_NAME bucket name (default: "mike")
*/
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
DeleteObjectCommand,
} from "@aws-sdk/client-s3";
import { getSignedUrl as awsGetSignedUrl } from "@aws-sdk/s3-request-presigner";
function getClient(): S3Client {
return new S3Client({
region: "auto",
endpoint: process.env.R2_ENDPOINT_URL!,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
},
});
}
const BUCKET = process.env.R2_BUCKET_NAME ?? "mike";
export const storageEnabled = Boolean(
process.env.R2_ENDPOINT_URL &&
process.env.R2_ACCESS_KEY_ID &&
process.env.R2_SECRET_ACCESS_KEY,
);
// ---------------------------------------------------------------------------
// Upload
// ---------------------------------------------------------------------------
export async function uploadFile(
key: string,
content: ArrayBuffer,
contentType: string,
): Promise<void> {
const client = getClient();
await client.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: Buffer.from(content),
ContentType: contentType,
}),
);
}
// ---------------------------------------------------------------------------
// Download
// ---------------------------------------------------------------------------
export async function downloadFile(key: string): Promise<ArrayBuffer | null> {
if (!storageEnabled) return null;
try {
const client = getClient();
const response = await client.send(
new GetObjectCommand({ Bucket: BUCKET, Key: key }),
);
if (!response.Body) return null;
const bytes = await response.Body.transformToByteArray();
return bytes.buffer as ArrayBuffer;
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// Delete
// ---------------------------------------------------------------------------
export async function deleteFile(key: string): Promise<void> {
if (!storageEnabled) return;
const client = getClient();
await client.send(new DeleteObjectCommand({ Bucket: BUCKET, Key: key }));
}
// ---------------------------------------------------------------------------
// Signed URL (pre-signed for temporary direct access)
// ---------------------------------------------------------------------------
export async function getSignedUrl(
key: string,
expiresIn = 3600,
downloadFilename?: string,
): Promise<string | null> {
if (!storageEnabled) return null;
try {
const client = getClient();
// Override the response Content-Disposition so the browser uses this
// filename on download, instead of the last path segment of the R2 key
// (which includes the document UUID). The `download` attribute on <a>
// is ignored for cross-origin URLs, so we have to set it server-side.
const responseContentDisposition = downloadFilename
? buildContentDisposition("attachment", downloadFilename)
: undefined;
const command = new GetObjectCommand({
Bucket: BUCKET,
Key: key,
ResponseContentDisposition: responseContentDisposition,
});
return await awsGetSignedUrl(client, command, { expiresIn });
} catch {
return null;
}
}
export function normalizeDownloadFilename(name: string): string {
const trimmed = name.trim();
const base = trimmed || "download";
return base.replace(/[\x00-\x1F\x7F]/g, "_").replace(/[\\/]/g, "_");
}
export function sanitizeDispositionFilename(name: string): string {
return normalizeDownloadFilename(name).replace(/["\\]/g, "_");
}
export function encodeRFC5987(str: string): string {
return encodeURIComponent(str).replace(
/['()*]/g,
(c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(),
);
}
export function buildContentDisposition(
kind: "inline" | "attachment",
filename: string,
): string {
const normalized = normalizeDownloadFilename(filename);
return `${kind}; filename="${sanitizeDispositionFilename(normalized)}"; filename*=UTF-8''${encodeRFC5987(normalized)}`;
}
// ---------------------------------------------------------------------------
// Storage key helpers
// ---------------------------------------------------------------------------
export function storageKey(
userId: string,
docId: string,
filename: string,
): string {
return `documents/${userId}/${docId}/source${storageExtension(filename, ".bin")}`;
}
export function pdfStorageKey(
userId: string,
docId: string,
stem: string,
): string {
return `documents/${userId}/${docId}/${stem}.pdf`;
}
export function generatedDocKey(
userId: string,
docId: string,
filename: string,
): string {
return `generated/${userId}/${docId}/generated${storageExtension(filename, ".docx")}`;
}
export function versionStorageKey(
userId: string,
docId: string,
versionSlug: string,
filename: string,
): string {
return `documents/${userId}/${docId}/versions/${versionSlug}${storageExtension(filename, ".bin")}`;
}
function storageExtension(filename: string, fallback: string): string {
const lastDot = filename.lastIndexOf(".");
if (lastDot < 0) return fallback;
const ext = filename.slice(lastDot).toLowerCase();
return /^\.[a-z0-9]{1,16}$/.test(ext) ? ext : fallback;
}

View file

@ -0,0 +1,41 @@
import { createClient } from "@supabase/supabase-js";
/**
* Server-side Supabase client using the service role key.
* Bypasses RLS only use in API routes after verifying the user.
*/
export function createServerSupabase() {
const url = process.env.SUPABASE_URL || "";
const key = process.env.SUPABASE_SECRET_KEY || "";
return createClient(url, key, { auth: { persistSession: false } });
}
/**
* Extract and verify the Supabase JWT from the Authorization header.
* Returns the user's UUID string, or throws a Response with 401.
*/
export async function getUserIdFromRequest(req: Request): Promise<string> {
const auth = req.headers.get("authorization") ?? "";
if (!auth.startsWith("Bearer ")) {
throw new Response("Missing or invalid Authorization header", {
status: 401,
});
}
const token = auth.slice(7).trim();
const supabaseUrl = process.env.SUPABASE_URL || "";
const serviceKey = process.env.SUPABASE_SECRET_KEY || "";
if (!supabaseUrl || !serviceKey) {
throw new Response("Server auth is not configured", { status: 500 });
}
const admin = createClient(supabaseUrl, serviceKey, {
auth: { persistSession: false },
});
const { data } = await admin.auth.getUser(token);
if (!data.user) {
throw new Response("Invalid or expired token", { status: 401 });
}
return data.user.id;
}

36
backend/src/lib/upload.ts Normal file
View file

@ -0,0 +1,36 @@
import type { RequestHandler } from "express";
import multer from "multer";
export const MAX_UPLOAD_SIZE_BYTES = 100 * 1024 * 1024;
export const MAX_UPLOAD_SIZE_MB = Math.round(
MAX_UPLOAD_SIZE_BYTES / (1024 * 1024),
);
const memoryUpload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: MAX_UPLOAD_SIZE_BYTES,
files: 1,
},
});
export function singleFileUpload(fieldName: string): RequestHandler {
return (req, res, next) => {
memoryUpload.single(fieldName)(req, res, (err) => {
if (!err) return next();
if (err instanceof multer.MulterError) {
if (err.code === "LIMIT_FILE_SIZE") {
return void res.status(413).json({
detail: `File too large. Maximum size is ${MAX_UPLOAD_SIZE_MB} MB.`,
});
}
return void res.status(400).json({
detail: `Upload failed: ${err.message}`,
});
}
return next(err);
});
};
}

View file

@ -0,0 +1,62 @@
import { createServerSupabase } from "./supabase";
import {
resolveModel,
DEFAULT_TITLE_MODEL,
DEFAULT_TABULAR_MODEL,
type UserApiKeys,
} from "./llm";
export type UserModelSettings = {
title_model: string;
tabular_model: string;
api_keys: UserApiKeys;
};
// Title generation is a lightweight task — always routed to the cheapest model
// of whichever provider the user has keys for: Gemini Flash Lite if Gemini is
// available, otherwise Claude Haiku. With no user keys set, defaults to Gemini
// (the dev-mode env fallback).
function resolveTitleModel(apiKeys: UserApiKeys): string {
if (apiKeys.gemini?.trim()) return DEFAULT_TITLE_MODEL;
if (apiKeys.claude?.trim()) return "claude-haiku-4-5";
return DEFAULT_TITLE_MODEL;
}
export async function getUserModelSettings(
userId: string,
db?: ReturnType<typeof createServerSupabase>,
): Promise<UserModelSettings> {
const client = db ?? createServerSupabase();
const { data } = await client
.from("user_profiles")
.select("tabular_model, claude_api_key, gemini_api_key")
.eq("user_id", userId)
.single();
const api_keys: UserApiKeys = {
claude: data?.claude_api_key ?? null,
gemini: data?.gemini_api_key ?? null,
};
return {
title_model: resolveTitleModel(api_keys),
tabular_model: resolveModel(data?.tabular_model, DEFAULT_TABULAR_MODEL),
api_keys,
};
}
export async function getUserApiKeys(
userId: string,
db?: ReturnType<typeof createServerSupabase>,
): Promise<UserApiKeys> {
const client = db ?? createServerSupabase();
const { data } = await client
.from("user_profiles")
.select("claude_api_key, gemini_api_key")
.eq("user_id", userId)
.single();
return {
claude: data?.claude_api_key ?? null,
gemini: data?.gemini_api_key ?? null,
};
}

View file

@ -0,0 +1,37 @@
import { Request, Response, NextFunction } from "express";
import { createClient } from "@supabase/supabase-js";
export async function requireAuth(
req: Request,
res: Response,
next: NextFunction,
): Promise<void> {
const auth = req.headers.authorization ?? "";
if (!auth.startsWith("Bearer ")) {
res.status(401).json({ detail: "Missing or invalid Authorization header" });
return;
}
const token = auth.slice(7).trim();
const supabaseUrl = process.env.SUPABASE_URL ?? "";
const serviceKey = process.env.SUPABASE_SECRET_KEY ?? "";
if (!supabaseUrl || !serviceKey) {
res.status(500).json({ detail: "Server auth is not configured" });
return;
}
const admin = createClient(supabaseUrl, serviceKey, {
auth: { persistSession: false },
});
const { data } = await admin.auth.getUser(token);
if (!data.user) {
res.status(401).json({ detail: "Invalid or expired token" });
return;
}
res.locals.userId = data.user.id;
res.locals.userEmail = data.user.email?.toLowerCase() ?? "";
res.locals.token = token;
next();
}

487
backend/src/routes/chat.ts Normal file
View file

@ -0,0 +1,487 @@
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
import {
buildDocContext,
buildMessages,
enrichWithPriorEvents,
buildWorkflowStore,
extractAnnotations,
runLLMStream,
type ChatMessage,
} from "../lib/chatTools";
import { completeText } from "../lib/llm";
import { getUserApiKeys, getUserModelSettings } from "../lib/userSettings";
import { checkProjectAccess } from "../lib/access";
export const chatRouter = Router();
// GET /chat
// Visible chats = the user's own chats + every chat under a project the
// user owns (so a project owner sees all collaborator chats in their
// own projects in the global recent-chats list). Chats in projects that
// are merely *shared with* the user are NOT included here — those are
// listed per-project via GET /projects/:projectId/chats.
chatRouter.get("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const db = createServerSupabase();
const { data: ownProjects, error: projErr } = await db
.from("projects")
.select("id")
.eq("user_id", userId);
if (projErr) return void res.status(500).json({ detail: projErr.message });
const ownProjectIds = ((ownProjects ?? []) as { id: string }[]).map(
(p) => p.id,
);
const filter =
ownProjectIds.length > 0
? `user_id.eq.${userId},project_id.in.(${ownProjectIds.join(",")})`
: `user_id.eq.${userId}`;
const { data, error } = await db
.from("chats")
.select("*")
.or(filter)
.order("created_at", { ascending: false });
if (error) return void res.status(500).json({ detail: error.message });
res.json(data ?? []);
});
// POST /chat/create
chatRouter.post("/create", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const projectId: string | null = req.body.project_id ?? null;
const db = createServerSupabase();
const { data, error } = await db
.from("chats")
.insert({ user_id: userId, project_id: projectId ?? undefined })
.select("id")
.single();
if (error) return void res.status(500).json({ detail: error.message });
res.json({ id: data.id });
});
// GET /chat/:chatId
chatRouter.get("/:chatId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { chatId } = req.params;
const db = createServerSupabase();
const { data: chat, error } = await db
.from("chats")
.select("*")
.eq("id", chatId)
.single();
if (error || !chat)
return void res.status(404).json({ detail: "Chat not found" });
// Owner of the chat OR a member of the chat's project can view it.
let canView = chat.user_id === userId;
if (!canView && chat.project_id) {
const access = await checkProjectAccess(
chat.project_id,
userId,
userEmail,
db,
);
canView = access.ok;
}
if (!canView)
return void res.status(404).json({ detail: "Chat not found" });
const { data: messages } = await db
.from("chat_messages")
.select("*")
.eq("chat_id", chatId)
.order("created_at", { ascending: true });
const hydrated = await hydrateEditStatuses(messages ?? [], db);
res.json({ chat, messages: hydrated });
});
// Stored message annotations/events capture the `status` at the time the
// assistant produced the edit (always "pending"). If the user later accepts
// or rejects, `document_edits.status` is updated but the stored message
// annotation is not. On chat load we merge the current DB status in so
// EditCards render with the real state.
async function hydrateEditStatuses(
messages: Record<string, unknown>[],
db: ReturnType<typeof createServerSupabase>,
): Promise<Record<string, unknown>[]> {
const editIds = new Set<string>();
const versionIds = new Set<string>();
const collectFromAnnList = (list: unknown) => {
if (!Array.isArray(list)) return;
for (const a of list as Record<string, unknown>[]) {
if (typeof a?.edit_id === "string") editIds.add(a.edit_id);
if (typeof a?.version_id === "string")
versionIds.add(a.version_id);
}
};
for (const m of messages) {
collectFromAnnList(m.annotations);
const content = m.content;
if (Array.isArray(content)) {
for (const ev of content as Record<string, unknown>[]) {
if (ev?.type === "doc_edited") {
collectFromAnnList(ev.annotations);
if (typeof ev.version_id === "string")
versionIds.add(ev.version_id);
}
}
}
}
if (editIds.size === 0 && versionIds.size === 0) return messages;
// Edit status patch.
const statusById = new Map<string, "pending" | "accepted" | "rejected">();
if (editIds.size > 0) {
const { data: rows } = await db
.from("document_edits")
.select("id, status")
.in("id", Array.from(editIds));
for (const r of (rows ?? []) as { id: string; status: string }[]) {
if (
r.status === "pending" ||
r.status === "accepted" ||
r.status === "rejected"
) {
statusById.set(r.id, r.status);
}
}
}
// Version-number patch — old stored events don't carry `version_number`
// because they predate the schema change. Look it up from
// document_versions so the UI can render "V3" chips + download filenames.
const versionNumberById = new Map<string, number | null>();
if (versionIds.size > 0) {
const { data: vrows } = await db
.from("document_versions")
.select("id, version_number")
.in("id", Array.from(versionIds));
for (const r of (vrows ?? []) as {
id: string;
version_number: number | null;
}[]) {
versionNumberById.set(r.id, r.version_number ?? null);
}
}
const patchAnnList = (list: unknown): unknown => {
if (!Array.isArray(list)) return list;
return (list as Record<string, unknown>[]).map((a) => {
let next = a;
if (typeof a?.edit_id === "string" && statusById.has(a.edit_id)) {
next = { ...next, status: statusById.get(a.edit_id) };
}
if (
typeof a?.version_id === "string" &&
versionNumberById.has(a.version_id)
) {
next = {
...next,
version_number: versionNumberById.get(a.version_id) ?? null,
};
}
return next;
});
};
return messages.map((m) => {
const next: Record<string, unknown> = { ...m };
next.annotations = patchAnnList(m.annotations);
if (Array.isArray(m.content)) {
next.content = (m.content as Record<string, unknown>[]).map(
(ev) => {
if (ev?.type !== "doc_edited") return ev;
let patched: Record<string, unknown> = {
...ev,
annotations: patchAnnList(ev.annotations),
};
if (
typeof ev.version_id === "string" &&
versionNumberById.has(ev.version_id)
) {
patched = {
...patched,
version_number:
versionNumberById.get(ev.version_id) ?? null,
};
}
return patched;
},
);
}
return next;
});
}
// PATCH /chat/:chatId
chatRouter.patch("/:chatId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { chatId } = req.params;
const title = (req.body.title ?? "").trim();
if (!title)
return void res.status(400).json({ detail: "title is required" });
const db = createServerSupabase();
const { data, error } = await db
.from("chats")
.update({ title })
.eq("id", chatId)
.eq("user_id", userId)
.select("id, title")
.single();
if (error || !data)
return void res.status(404).json({ detail: "Chat not found" });
res.json(data);
});
// DELETE /chat/:chatId
chatRouter.delete("/:chatId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { chatId } = req.params;
const db = createServerSupabase();
const { error } = await db
.from("chats")
.delete()
.eq("id", chatId)
.eq("user_id", userId);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// POST /chat/:chatId/generate-title
chatRouter.post("/:chatId/generate-title", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { chatId } = req.params;
const message: string = (req.body.message ?? "").trim();
if (!message)
return void res.status(400).json({ detail: "message is required" });
const db = createServerSupabase();
const { data: chat, error } = await db
.from("chats")
.select("id, user_id, project_id")
.eq("id", chatId)
.single();
if (error || !chat)
return void res.status(404).json({ detail: "Chat not found" });
let canTitle = chat.user_id === userId;
if (!canTitle && chat.project_id) {
const access = await checkProjectAccess(
chat.project_id,
userId,
userEmail,
db,
);
canTitle = access.ok;
}
if (!canTitle)
return void res.status(404).json({ detail: "Chat not found" });
try {
const { title_model, api_keys } = await getUserModelSettings(
userId,
db,
);
const titleText = await completeText({
model: title_model,
user: `Generate a concise title (36 words) for a chat in an AI Legal Platform that starts with this message. The title should describe the topic or document — do NOT include words like "Legal Assistant", "AI", "Chat", or any similar prefix. Return only the title, no quotes or punctuation.\n\nMessage: ${message.slice(0, 500)}`,
maxTokens: 64,
apiKeys: api_keys,
});
const title = titleText.trim() || message.slice(0, 60);
await db
.from("chats")
.update({ title })
.eq("id", chatId)
.eq("user_id", userId);
res.json({ title });
} catch (err) {
console.error("[generate-title]", err);
res.status(500).json({ detail: "Failed to generate title" });
}
});
// POST /chat — streaming
chatRouter.post("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { messages, chat_id, project_id, model } = req.body as {
messages: ChatMessage[];
chat_id?: string;
project_id?: string;
model?: string;
};
console.log("[chat/stream] incoming request", {
userId,
chat_id,
project_id,
model,
messageCount: messages?.length,
});
const userEmail = res.locals.userEmail as string | undefined;
const db = createServerSupabase();
let chatId = chat_id ?? null;
let chatTitle: string | null = null;
if (chatId) {
// Either chat owner OR a member of the chat's project can post.
const { data: existing } = await db
.from("chats")
.select("id, title, user_id, project_id")
.eq("id", chatId)
.single();
let canUse = !!existing && existing.user_id === userId;
if (!canUse && existing?.project_id) {
const access = await checkProjectAccess(
existing.project_id,
userId,
userEmail,
db,
);
canUse = access.ok;
}
if (!canUse || !existing) chatId = null;
else chatTitle = existing.title;
}
if (!chatId) {
// If creating a chat tied to a project, the user must have access
// to the project (own or shared).
if (project_id) {
const access = await checkProjectAccess(
project_id,
userId,
userEmail,
db,
);
if (!access.ok)
return void res
.status(404)
.json({ detail: "Project not found" });
}
const { data: newChat, error } = await db
.from("chats")
.insert({ user_id: userId, project_id: project_id ?? null })
.select("id, title")
.single();
if (error || !newChat) {
console.error("[chat/stream] failed to create chat", error);
return void res
.status(500)
.json({ detail: "Failed to create chat" });
}
chatId = newChat.id as string;
chatTitle = newChat.title;
}
console.log("[chat/stream] resolved chatId", chatId);
const lastUser = [...messages].reverse().find((m) => m.role === "user");
if (lastUser) {
await db.from("chat_messages").insert({
chat_id: chatId,
role: "user",
content: lastUser.content,
files: lastUser.files ?? null,
workflow: lastUser.workflow ?? null,
});
}
const { docIndex, docStore } = await buildDocContext(
messages,
userId,
db,
chatId,
);
const docAvailability = Object.entries(docIndex).map(([doc_id, info]) => ({
doc_id,
filename: info.filename,
}));
const enrichedMessages = await enrichWithPriorEvents(
messages,
chatId,
db,
docIndex,
);
const apiMessages = buildMessages(enrichedMessages, docAvailability);
const workflowStore = await buildWorkflowStore(userId, userEmail, db);
console.log("[chat/stream] starting LLM stream", {
apiMessageCount: apiMessages.length,
docCount: Object.keys(docIndex).length,
workflowCount: Object.keys(workflowStore).length,
});
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders();
const write = (line: string) => res.write(line);
const apiKeys = await getUserApiKeys(userId, db);
try {
write(`data: ${JSON.stringify({ type: "chat_id", chatId })}\n\n`);
const { fullText, events } = await runLLMStream({
apiMessages,
docStore,
docIndex,
userId,
db,
write,
workflowStore,
model,
apiKeys,
projectId: project_id ?? null,
});
console.log("[chat/stream] LLM stream finished", {
fullTextLen: fullText?.length ?? 0,
eventCount: events?.length ?? 0,
});
const annotations = extractAnnotations(fullText, docIndex, events);
await db.from("chat_messages").insert({
chat_id: chatId,
role: "assistant",
content: events.length ? events : null,
annotations: annotations.length ? annotations : null,
});
if (!chatTitle && lastUser?.content) {
await db
.from("chats")
.update({ title: lastUser.content.slice(0, 120) })
.eq("id", chatId);
}
} catch (err) {
console.error("[chat/stream] error:", err);
try {
write(
`data: ${JSON.stringify({ type: "error", message: "Stream error" })}\n\n`,
);
write("data: [DONE]\n\n");
} catch {
/* ignore */
}
} finally {
res.end();
}
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,70 @@
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
import { buildContentDisposition, downloadFile } from "../lib/storage";
import { verifyDownload } from "../lib/downloadTokens";
import { ensureDocAccess } from "../lib/access";
export const downloadsRouter = Router();
function contentTypeFor(filename: string): string {
const lower = filename.toLowerCase();
if (lower.endsWith(".docx"))
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
if (lower.endsWith(".pdf")) return "application/pdf";
if (lower.endsWith(".xlsx"))
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return "application/octet-stream";
}
// GET /download/:token
downloadsRouter.get("/:token", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const info = verifyDownload(req.params.token);
if (!info)
return void res.status(404).json({ detail: "Invalid link" });
const db = createServerSupabase();
let version:
| {
id: string;
document_id: string;
}
| null = null;
const { data: byStoragePath } = await db
.from("document_versions")
.select("id, document_id")
.eq("storage_path", info.path)
.maybeSingle();
if (byStoragePath) {
version = byStoragePath as { id: string; document_id: string };
}
if (!version)
return void res.status(404).json({ detail: "File not found" });
const { data: doc } = await db
.from("documents")
.select("id, user_id, project_id")
.eq("id", version.document_id)
.single();
if (!doc)
return void res.status(404).json({ detail: "File not found" });
const access = await ensureDocAccess(doc, userId, userEmail, db);
if (!access.ok)
return void res.status(404).json({ detail: "File not found" });
const raw = await downloadFile(info.path);
if (!raw)
return void res.status(404).json({ detail: "File not found" });
res.setHeader("Content-Type", contentTypeFor(info.filename));
res.setHeader(
"Content-Disposition",
buildContentDisposition("attachment", info.filename),
);
res.send(Buffer.from(raw));
});

View file

@ -0,0 +1,201 @@
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
import {
buildProjectDocContext,
buildMessages,
buildWorkflowStore,
enrichWithPriorEvents,
extractAnnotations,
runLLMStream,
PROJECT_EXTRA_TOOLS,
type ChatMessage,
} from "../lib/chatTools";
import { getUserApiKeys } from "../lib/userSettings";
import { checkProjectAccess } from "../lib/access";
const PROJECT_SYSTEM_PROMPT_EXTRA = `PROJECT CONTEXT:
You are operating within a project folder that contains a collection of legal documents the user has organised for a single matter. The user's questions will usually refer to one or more documents in this project your job is to find the relevant files to work on. Use list_documents to see what is available and fetch_documents / read_document to pull in any documents you need before answering.
A document may currently be displayed in the user's side panel; when provided, treat it as context for the user's likely focus, but do NOT assume it is the only or definitive document the user is asking about. If the request could apply to other files in the project, identify and read those as well. Prefer coverage across the relevant project documents over an over-narrow reading of only the displayed one.
REPLICATING A DOCUMENT:
When the user wants to use an existing project document as a starting point for a new file (e.g. "use this NDA as a template", "make me a copy of the SOW so I can edit it", "duplicate this and adapt it for company X"), call the replicate_document tool with the source doc_id. This creates a byte-for-byte copy as a new project document, returns a fresh doc_id slug, and shows a download/open card in the UI. Then call edit_document on the returned slug to make the user's requested changes — do NOT call generate_docx for cases where the user clearly wants the existing document's structure and formatting preserved.`;
export const projectChatRouter = Router({ mergeParams: true });
// POST /projects/:projectId/chat — streaming
projectChatRouter.post("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId } = req.params;
const { messages, chat_id, model, displayed_doc, attached_documents } =
req.body as {
messages: ChatMessage[];
chat_id?: string;
model?: string;
displayed_doc?: { filename: string; document_id: string };
attached_documents?: { filename: string; document_id: string }[];
};
const db = createServerSupabase();
// Verify the user has access to the project (owner or shared member).
const projectAccess = await checkProjectAccess(
projectId,
userId,
userEmail,
db,
);
if (!projectAccess.ok)
return void res.status(404).json({ detail: "Project not found" });
let chatId = chat_id ?? null;
let chatTitle: string | null = null;
if (chatId) {
const { data: existing } = await db
.from("chats")
.select("id, title, project_id")
.eq("id", chatId)
.single();
const canUse = !!existing && existing.project_id === projectId;
if (!canUse) chatId = null;
else chatTitle = existing!.title;
}
if (!chatId) {
const { data: newChat, error } = await db
.from("chats")
.insert({ user_id: userId, project_id: projectId })
.select("id, title")
.single();
if (error || !newChat)
return void res
.status(500)
.json({ detail: "Failed to create chat" });
chatId = newChat.id as string;
chatTitle = newChat.title;
}
const lastUser = [...messages].reverse().find((m) => m.role === "user");
if (lastUser) {
await db.from("chat_messages").insert({
chat_id: chatId,
role: "user",
content: lastUser.content,
files: lastUser.files ?? null,
workflow: lastUser.workflow ?? null,
});
}
const { docIndex, docStore, folderPaths } = await buildProjectDocContext(
projectId,
userId,
db,
);
const docAvailability = Object.entries(docIndex).map(([doc_id, info]) => ({
doc_id,
filename: info.filename,
folder_path: folderPaths.get(doc_id),
}));
const enrichedMessages = await enrichWithPriorEvents(
messages,
chatId,
db,
docIndex,
);
const messagesForLLM: ChatMessage[] = displayed_doc
? enrichedMessages.map((m, i) => {
if (i !== enrichedMessages.length - 1 || m.role !== "user")
return m;
return {
...m,
content: `${m.content}\n\ndisplayed_doc: ${displayed_doc.filename}, displayed_doc_id: ${displayed_doc.document_id}`,
};
})
: enrichedMessages;
// The user-attached docs for this turn (dragged into / picked from
// the chat input) come in as a request-level field. Surface them in
// the system prompt with the current-turn doc_id slugs so the model
// knows which docs the user is highlighting *now*, distinct from
// the broader project doc list.
let systemPromptExtra = PROJECT_SYSTEM_PROMPT_EXTRA;
if (attached_documents?.length) {
const slugByDocumentId = new Map<string, string>();
for (const [slug, info] of Object.entries(docIndex)) {
if (info.document_id)
slugByDocumentId.set(info.document_id, slug);
}
const lines = attached_documents.map((d) => {
const slug = slugByDocumentId.get(d.document_id);
return slug ? `- ${slug}: ${d.filename}` : `- ${d.filename}`;
});
systemPromptExtra += `\n\nUSER-ATTACHED DOCUMENTS FOR THIS TURN:\nThe user has attached the following document(s) directly to their latest message. Treat these as the primary focus of the request unless their message clearly says otherwise.\n${lines.join("\n")}`;
}
const apiMessages = buildMessages(
messagesForLLM,
docAvailability,
systemPromptExtra,
);
const workflowStore = await buildWorkflowStore(userId, userEmail, db);
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders();
const write = (line: string) => res.write(line);
const apiKeys = await getUserApiKeys(userId, db);
try {
write(`data: ${JSON.stringify({ type: "chat_id", chatId })}\n\n`);
const { fullText, events } = await runLLMStream({
apiMessages,
docStore,
docIndex,
userId,
db,
write,
extraTools: PROJECT_EXTRA_TOOLS,
workflowStore,
model,
apiKeys,
projectId,
});
const annotations = extractAnnotations(fullText, docIndex, events);
await db.from("chat_messages").insert({
chat_id: chatId,
role: "assistant",
content: events.length ? events : null,
annotations: annotations.length ? annotations : null,
});
if (!chatTitle && lastUser?.content) {
await db
.from("chats")
.update({ title: lastUser.content.slice(0, 120) })
.eq("id", chatId);
}
} catch (err) {
console.error("[project-chat/stream] error:", err);
try {
write(
`data: ${JSON.stringify({ type: "error", message: "Stream error" })}\n\n`,
);
write("data: [DONE]\n\n");
} catch {
/* ignore */
}
} finally {
res.end();
}
});

View file

@ -0,0 +1,801 @@
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
import { createClient } from "@supabase/supabase-js";
import {
attachActiveVersionPaths,
attachLatestVersionNumbers,
} from "../lib/documentVersions";
import { downloadFile, uploadFile, storageKey } from "../lib/storage";
import { docxToPdf, convertedPdfKey } from "../lib/convert";
import { checkProjectAccess } from "../lib/access";
import { singleFileUpload } from "../lib/upload";
export const projectsRouter = Router();
const ALLOWED_TYPES = new Set(["pdf", "docx", "doc"]);
// GET /projects
projectsRouter.get("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string;
const db = createServerSupabase();
const { data: ownProjects, error: ownError } = await db
.from("projects")
.select("*")
.eq("user_id", userId)
.order("created_at", { ascending: false });
if (ownError) return void res.status(500).json({ detail: ownError.message });
const { data: sharedProjects, error: sharedError } = userEmail
? await db
.from("projects")
.select("*")
.contains("shared_with", [userEmail])
.neq("user_id", userId)
.order("created_at", { ascending: false })
: { data: [], error: null };
if (sharedError)
return void res.status(500).json({ detail: sharedError.message });
const projects = [...(ownProjects ?? []), ...(sharedProjects ?? [])].sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
);
const result = await Promise.all(
projects.map(async (p) => {
const [docs, chats, reviews] = await Promise.all([
db
.from("documents")
.select("id", { count: "exact", head: true })
.eq("project_id", p.id),
db
.from("chats")
.select("id", { count: "exact", head: true })
.eq("project_id", p.id),
db
.from("tabular_reviews")
.select("id", { count: "exact", head: true })
.eq("project_id", p.id),
]);
return {
...p,
is_owner: p.user_id === userId,
document_count: docs.count ?? 0,
chat_count: chats.count ?? 0,
review_count: reviews.count ?? 0,
};
}),
);
res.json(result);
});
// POST /projects
projectsRouter.post("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { name, cm_number, shared_with } = req.body as {
name: string;
cm_number?: string;
shared_with?: string[];
};
if (!name?.trim())
return void res.status(400).json({ detail: "name is required" });
const db = createServerSupabase();
const { data, error } = await db
.from("projects")
.insert({
user_id: userId,
name: name.trim(),
cm_number: cm_number ?? null,
shared_with: shared_with ?? [],
})
.select("*")
.single();
if (error) return void res.status(500).json({ detail: error.message });
res.status(201).json({ ...data, documents: [] });
});
// GET /projects/:projectId
projectsRouter.get("/:projectId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string;
const { projectId } = req.params;
const db = createServerSupabase();
const { data: project, error } = await db
.from("projects")
.select("*")
.eq("id", projectId)
.single();
if (error || !project)
return void res.status(404).json({ detail: "Project not found" });
const canAccess =
project.user_id === userId ||
(userEmail &&
Array.isArray(project.shared_with) &&
project.shared_with.includes(userEmail));
if (!canAccess)
return void res.status(404).json({ detail: "Project not found" });
const [{ data: docs }, { data: folderData }] = await Promise.all([
db.from("documents").select("*").eq("project_id", projectId).order("created_at", { ascending: true }),
db.from("project_subfolders").select("*").eq("project_id", projectId).order("created_at", { ascending: true }),
]);
const docsTyped = (docs ?? []) as unknown as {
id: string;
current_version_id?: string | null;
}[];
await attachLatestVersionNumbers(db, docsTyped);
await attachActiveVersionPaths(db, docsTyped);
res.json({
...project,
is_owner: project.user_id === userId,
documents: docsTyped,
folders: folderData ?? [],
});
});
// GET /projects/:projectId/people
// Resolve the owner + every shared member to {email, display_name}. Used
// by the People modal so the UI can show display names where available
// and tag the current user as "You".
projectsRouter.get("/:projectId/people", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId } = req.params;
const db = createServerSupabase();
const { data: project } = await db
.from("projects")
.select("id, user_id, shared_with")
.eq("id", projectId)
.single();
if (!project)
return void res.status(404).json({ detail: "Project not found" });
const isOwner = project.user_id === userId;
const sharedWith = (Array.isArray(project.shared_with)
? (project.shared_with as string[])
: []
).map((e) => e.toLowerCase());
const isShared =
!!userEmail && sharedWith.includes(userEmail.toLowerCase());
if (!isOwner && !isShared)
return void res.status(404).json({ detail: "Project not found" });
// Pull every auth user (matching the lookup endpoint's pattern). For
// larger deployments this should page or be replaced with a bulk-by-id
// RPC, but it keeps things simple while user counts are modest.
const { data: usersData } = await db.auth.admin.listUsers({ perPage: 1000 });
const allUsers = usersData?.users ?? [];
const userByEmail = new Map<string, { id: string; email: string }>();
const userById = new Map<string, { id: string; email: string }>();
for (const u of allUsers) {
if (!u.email) continue;
const lower = u.email.toLowerCase();
userByEmail.set(lower, { id: u.id, email: u.email });
userById.set(u.id, { id: u.id, email: u.email });
}
const memberUserIds: string[] = [];
for (const email of sharedWith) {
const u = userByEmail.get(email);
if (u) memberUserIds.push(u.id);
}
const profileIds = [
project.user_id as string,
...memberUserIds,
].filter((x, i, arr) => arr.indexOf(x) === i);
const profileByUserId = new Map<
string,
{ display_name: string | null; organisation: string | null }
>();
if (profileIds.length > 0) {
const { data: profiles } = await db
.from("user_profiles")
.select("user_id, display_name, organisation")
.in("user_id", profileIds);
for (const p of profiles ?? []) {
profileByUserId.set(p.user_id as string, {
display_name: (p.display_name as string | null) ?? null,
organisation: (p.organisation as string | null) ?? null,
});
}
}
const ownerInfo = userById.get(project.user_id as string);
const owner = {
user_id: project.user_id,
email: ownerInfo?.email ?? null,
display_name:
profileByUserId.get(project.user_id as string)?.display_name ?? null,
};
const members = sharedWith.map((email) => {
const u = userByEmail.get(email);
const display_name = u
? profileByUserId.get(u.id)?.display_name ?? null
: null;
return { email, display_name };
});
res.json({ owner, members });
});
// PATCH /projects/:projectId
projectsRouter.patch("/:projectId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { projectId } = req.params;
const updates: Record<string, unknown> = {};
if (req.body.name != null) updates.name = req.body.name;
if (req.body.cm_number != null) updates.cm_number = req.body.cm_number;
if (Array.isArray(req.body.shared_with)) {
// Normalise: lowercase + dedupe + drop empties.
const seen = new Set<string>();
const cleaned: string[] = [];
for (const raw of req.body.shared_with) {
if (typeof raw !== "string") continue;
const e = raw.trim().toLowerCase();
if (!e || seen.has(e)) continue;
seen.add(e);
cleaned.push(e);
}
updates.shared_with = cleaned;
}
const db = createServerSupabase();
const { data, error } = await db
.from("projects")
.update({ ...updates, updated_at: new Date().toISOString() })
.eq("id", projectId)
.eq("user_id", userId)
.select("*")
.single();
if (error || !data)
return void res.status(404).json({ detail: "Project not found" });
const [{ data: docs }, { data: folderData }] = await Promise.all([
db.from("documents").select("*").eq("project_id", projectId).order("created_at", { ascending: true }),
db.from("project_subfolders").select("*").eq("project_id", projectId).order("created_at", { ascending: true }),
]);
const docsTyped = (docs ?? []) as unknown as {
id: string;
current_version_id?: string | null;
}[];
await attachActiveVersionPaths(db, docsTyped);
res.json({ ...data, documents: docsTyped, folders: folderData ?? [] });
});
// DELETE /projects/:projectId
projectsRouter.delete("/:projectId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { projectId } = req.params;
const db = createServerSupabase();
const { error } = await db
.from("projects")
.delete()
.eq("id", projectId)
.eq("user_id", userId);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// GET /projects/:projectId/documents
projectsRouter.get("/:projectId/documents", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId } = req.params;
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok)
return void res.status(404).json({ detail: "Project not found" });
const { data: docs } = await db
.from("documents")
.select("*")
.eq("project_id", projectId)
.order("created_at", { ascending: true });
const docsTyped = (docs ?? []) as unknown as {
id: string;
current_version_id?: string | null;
}[];
await attachActiveVersionPaths(db, docsTyped);
res.json(docsTyped);
});
// POST /projects/:projectId/documents/:documentId — assign or copy existing doc into project
projectsRouter.post(
"/:projectId/documents/:documentId",
requireAuth,
async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId, documentId } = req.params;
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok)
return void res.status(404).json({ detail: "Project not found" });
// Adding-by-id pulls a doc into the project — only the doc's owner
// is allowed to do that, so other people's standalone docs can't be
// siphoned into a project the requester happens to share.
const { data: doc } = await db
.from("documents")
.select("*")
.eq("id", documentId)
.eq("user_id", userId)
.single();
if (!doc)
return void res.status(404).json({ detail: "Document not found" });
// Already in this project — idempotent
if (doc.project_id === projectId) return void res.json(doc);
if (doc.project_id === null) {
// Standalone → assign project_id
const { data: updated, error } = await db
.from("documents")
.update({ project_id: projectId, updated_at: new Date().toISOString() })
.eq("id", documentId)
.select("*")
.single();
if (error || !updated)
return void res.status(500).json({ detail: "Failed to update document" });
return void res.json(updated);
} else {
// Belongs to another project → duplicate record AND copy the
// underlying storage objects so each project's copy is fully
// independent (edits/version bumps on one don't leak into the
// other).
const { data: copy, error } = await db
.from("documents")
.insert({
project_id: projectId,
user_id: userId,
filename: doc.filename,
file_type: doc.file_type,
size_bytes: doc.size_bytes,
page_count: doc.page_count,
structure_tree: doc.structure_tree,
status: doc.status,
})
.select("*")
.single();
if (error || !copy)
return void res.status(500).json({ detail: "Failed to copy document" });
let copyVersionRowId: string | null = null;
if (doc.current_version_id) {
const { data: srcV } = await db
.from("document_versions")
.select(
"storage_path, pdf_storage_path, version_number, display_name, source",
)
.eq("id", doc.current_version_id)
.single();
if (srcV?.storage_path) {
const srcBytes = await downloadFile(srcV.storage_path);
if (!srcBytes) {
return void res
.status(500)
.json({ detail: "Failed to read source document bytes" });
}
const newKey = storageKey(userId, copy.id as string, doc.filename);
const contentType =
doc.file_type === "pdf"
? "application/pdf"
: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
await uploadFile(newKey, srcBytes, contentType);
// PDFs share one object for source + display rendition. DOCX
// store the converted PDF at a separate `converted-pdfs/` key —
// copy that too if it exists so the copy renders without going
// back through libreoffice.
let newPdfPath: string | null = null;
if (srcV.pdf_storage_path) {
if (srcV.pdf_storage_path === srcV.storage_path) {
newPdfPath = newKey;
} else {
const pdfBytes = await downloadFile(srcV.pdf_storage_path);
if (pdfBytes) {
const newPdfKey = convertedPdfKey(userId, copy.id as string);
await uploadFile(newPdfKey, pdfBytes, "application/pdf");
newPdfPath = newPdfKey;
}
}
}
const { data: newV } = await db
.from("document_versions")
.insert({
document_id: copy.id,
storage_path: newKey,
pdf_storage_path: newPdfPath,
source: (srcV.source as string | null) ?? "upload",
version_number: srcV.version_number ?? 1,
display_name: srcV.display_name ?? doc.filename,
})
.select("id")
.single();
copyVersionRowId = (newV?.id as string | null) ?? null;
if (copyVersionRowId) {
await db
.from("documents")
.update({ current_version_id: copyVersionRowId })
.eq("id", copy.id);
}
}
}
return void res.status(201).json(copy);
}
},
);
// POST /projects/:projectId/documents
projectsRouter.post(
"/:projectId/documents",
requireAuth,
singleFileUpload("file"),
async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId } = req.params;
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok)
return void res.status(404).json({ detail: "Project not found" });
await handleDocumentUpload(req, res, userId, projectId, db);
},
);
// GET /projects/:projectId/chats — every assistant chat under this project
// (any author with project access). Used by the project page's chat tab so
// it doesn't have to filter the global GET /chat list — and so collaborators
// see each other's chats inside the project even though those don't appear
// in the global list.
projectsRouter.get("/:projectId/chats", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId } = req.params;
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok)
return void res.status(404).json({ detail: "Project not found" });
const { data, error } = await db
.from("chats")
.select("*")
.eq("project_id", projectId)
.order("created_at", { ascending: false });
if (error) return void res.status(500).json({ detail: error.message });
res.json(data ?? []);
});
// ── Folder routes ─────────────────────────────────────────────────────────────
// POST /projects/:projectId/folders
projectsRouter.post("/:projectId/folders", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId } = req.params;
const { name, parent_folder_id } = req.body as { name: string; parent_folder_id?: string | null };
if (!name?.trim()) return void res.status(400).json({ detail: "name is required" });
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok) return void res.status(404).json({ detail: "Project not found" });
// Verify parent folder belongs to this project
if (parent_folder_id) {
const { data: parent } = await db.from("project_subfolders").select("id").eq("id", parent_folder_id).eq("project_id", projectId).single();
if (!parent) return void res.status(404).json({ detail: "Parent folder not found" });
}
const { data, error } = await db.from("project_subfolders").insert({
project_id: projectId,
user_id: userId,
name: name.trim(),
parent_folder_id: parent_folder_id ?? null,
}).select("*").single();
if (error) return void res.status(500).json({ detail: error.message });
res.status(201).json(data);
});
// PATCH /projects/:projectId/folders/:folderId
projectsRouter.patch("/:projectId/folders/:folderId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId, folderId } = req.params;
const body = req.body as { name?: string; parent_folder_id?: string | null };
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok) return void res.status(404).json({ detail: "Project not found" });
const updates: Record<string, unknown> = { updated_at: new Date().toISOString() };
if (body.name != null) updates.name = body.name.trim();
if ("parent_folder_id" in body) {
// Cycle check: walk up the tree from the proposed parent to ensure folderId is not an ancestor
if (body.parent_folder_id) {
let cur: string | null = body.parent_folder_id;
while (cur) {
if (cur === folderId) return void res.status(400).json({ detail: "Cannot move a folder into itself or a descendant" });
const { data: p }: { data: { parent_folder_id: string | null } | null } =
await db.from("project_subfolders").select("parent_folder_id").eq("id", cur).single();
cur = p?.parent_folder_id ?? null;
}
}
updates.parent_folder_id = body.parent_folder_id ?? null;
}
const { data, error } = await db.from("project_subfolders")
.update(updates)
.eq("id", folderId).eq("project_id", projectId)
.select("*").single();
if (error || !data) return void res.status(404).json({ detail: "Folder not found" });
res.json(data);
});
// DELETE /projects/:projectId/folders/:folderId
projectsRouter.delete("/:projectId/folders/:folderId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId, folderId } = req.params;
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok) return void res.status(404).json({ detail: "Project not found" });
// Move direct documents to root before cascade-deleting subfolders
await db.from("documents").update({ folder_id: null }).eq("folder_id", folderId);
const { error } = await db.from("project_subfolders")
.delete().eq("id", folderId).eq("project_id", projectId);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// PATCH /projects/:projectId/documents/:documentId/folder — move doc to a folder
projectsRouter.patch("/:projectId/documents/:documentId/folder", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { projectId, documentId } = req.params;
const { folder_id } = req.body as { folder_id: string | null };
const db = createServerSupabase();
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok) return void res.status(404).json({ detail: "Project not found" });
const { data, error } = await db.from("documents")
.update({ folder_id: folder_id ?? null, updated_at: new Date().toISOString() })
.eq("id", documentId).eq("project_id", projectId)
.select("*").single();
if (error || !data) return void res.status(404).json({ detail: "Document not found" });
res.json(data);
});
export async function handleDocumentUpload(
req: import("express").Request,
res: import("express").Response,
userId: string,
projectId: string | null,
db: ReturnType<typeof createServerSupabase>,
) {
const file = req.file;
if (!file) return void res.status(400).json({ detail: "file is required" });
const filename = file.originalname;
const suffix = filename.includes(".")
? filename.split(".").pop()!.toLowerCase()
: "";
if (!ALLOWED_TYPES.has(suffix))
return void res
.status(400)
.json({
detail: `Unsupported file type: ${suffix}. Allowed: pdf, docx, doc`,
});
const content = file.buffer;
const { data: doc, error: insertErr } = await db
.from("documents")
.insert({
project_id: projectId,
user_id: userId,
filename,
file_type: suffix,
size_bytes: content.byteLength,
status: "processing",
})
.select("*")
.single();
if (insertErr || !doc)
return void res
.status(500)
.json({ detail: "Failed to create document record" });
try {
const docId = doc.id as string;
const key = storageKey(userId, docId, filename);
const contentType =
suffix === "pdf"
? "application/pdf"
: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
await uploadFile(
key,
content.buffer.slice(
content.byteOffset,
content.byteOffset + content.byteLength,
) as ArrayBuffer,
contentType,
);
const rawBuf = content.buffer.slice(
content.byteOffset,
content.byteOffset + content.byteLength,
) as ArrayBuffer;
const tree = await extractStructureTree(rawBuf, suffix, filename);
const pageCount = suffix === "pdf" ? await countPdfPages(rawBuf) : null;
// Convert DOCX/DOC → PDF for display. PDFs are their own rendition.
let pdfStoragePath: string | null = null;
if (suffix === "docx" || suffix === "doc") {
try {
const pdfBuf = await docxToPdf(content);
const pdfKey = convertedPdfKey(userId, docId);
await uploadFile(
pdfKey,
pdfBuf.buffer.slice(
pdfBuf.byteOffset,
pdfBuf.byteOffset + pdfBuf.byteLength,
) as ArrayBuffer,
"application/pdf",
);
pdfStoragePath = pdfKey;
} catch (err) {
console.error(
`[upload] DOCX→PDF conversion failed for ${filename}:`,
err,
);
}
} else if (suffix === "pdf") {
pdfStoragePath = key;
}
// Storage paths live on document_versions — create the V1 row and
// point documents.current_version_id at it.
const { data: versionRow, error: verErr } = await db
.from("document_versions")
.insert({
document_id: docId,
storage_path: key,
pdf_storage_path: pdfStoragePath,
source: "upload",
version_number: 1,
display_name: filename,
})
.select("id")
.single();
if (verErr || !versionRow) {
throw new Error(
`Failed to record upload version: ${verErr?.message ?? "unknown"}`,
);
}
await db
.from("documents")
.update({
current_version_id: versionRow.id,
size_bytes: content.byteLength,
page_count: pageCount,
structure_tree: tree ?? null,
status: "ready",
updated_at: new Date().toISOString(),
})
.eq("id", docId);
const { data: updated } = await db
.from("documents")
.select("*")
.eq("id", docId)
.single();
const responseDoc = updated
? {
...updated,
storage_path: key,
pdf_storage_path: pdfStoragePath,
}
: updated;
return void res.status(201).json(responseDoc);
} catch (e) {
await db.from("documents").update({ status: "error" }).eq("id", doc.id);
return void res
.status(500)
.json({ detail: `Document processing failed: ${String(e)}` });
}
}
async function countPdfPages(buf: ArrayBuffer): Promise<number | null> {
try {
const pdfjsLib = await import("pdfjs-dist/legacy/build/pdf.mjs" as string);
const pdf = await (
pdfjsLib as unknown as {
getDocument: (opts: unknown) => {
promise: Promise<{ numPages: number }>;
};
}
).getDocument({ data: new Uint8Array(buf) }).promise;
return pdf.numPages;
} catch {
return null;
}
}
async function extractStructureTree(
content: ArrayBuffer,
fileType: string,
filename: string,
): Promise<unknown[] | null> {
try {
if (fileType === "pdf") {
const pdfjsLib = await import(
"pdfjs-dist/legacy/build/pdf.mjs" as string
);
const pdf = await (
pdfjsLib as unknown as {
getDocument: (opts: unknown) => {
promise: Promise<{
numPages: number;
getOutline: () => Promise<{ title?: string }[]>;
}>;
};
}
).getDocument({ data: new Uint8Array(content) }).promise;
if (pdf.numPages <= 5) return null;
const outline = await pdf.getOutline();
if (outline?.length) {
return outline.map((item, i) => ({
id: `h1-${i}`,
title: item.title ?? `Item ${i + 1}`,
level: 1,
page_number: null,
children: [],
}));
}
return Array.from({ length: pdf.numPages }, (_, i) => ({
id: `page-${i + 1}`,
title: `Page ${i + 1}`,
level: 1,
page_number: i + 1,
children: [],
}));
} else {
const mammoth = await import("mammoth");
const result = await mammoth.extractRawText({
buffer: Buffer.from(content),
});
const lines = result.value.split("\n").filter((l) => l.trim());
const nodes = lines
.slice(0, 30)
.map((line, i) => ({
id: `h1-${i}`,
title: line.slice(0, 100),
level: 1,
page_number: null,
children: [],
}));
return nodes.length ? nodes : null;
}
} catch {
return null;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,28 @@
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
export const userRouter = Router();
// POST /user/profile
userRouter.post("/profile", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const db = createServerSupabase();
const { error } = await db
.from("user_profiles")
.upsert(
{ user_id: userId },
{ onConflict: "user_id", ignoreDuplicates: true },
);
if (error) return void res.status(500).json({ detail: error.message });
res.json({ ok: true });
});
// DELETE /user/account
userRouter.delete("/account", requireAuth, async (_req, res) => {
const userId = res.locals.userId as string;
const db = createServerSupabase();
const { error } = await db.auth.admin.deleteUser(userId);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});

View file

@ -0,0 +1,367 @@
import { Router } from "express";
import { createClient } from "@supabase/supabase-js";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
function getAdminClient() {
return createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL ?? "",
process.env.SUPABASE_SECRET_KEY ?? "",
{ auth: { autoRefreshToken: false, persistSession: false } },
);
}
export const workflowsRouter = Router();
type Db = ReturnType<typeof createServerSupabase>;
type WorkflowRecord = {
id: string;
user_id: string | null;
is_system: boolean;
[key: string]: unknown;
};
type WorkflowAccess =
| {
workflow: WorkflowRecord;
allowEdit: boolean;
isOwner: boolean;
}
| null;
function withWorkflowAccess<T extends Record<string, unknown>>(
workflow: T,
access: { allowEdit: boolean; isOwner: boolean; sharedByName?: string | null },
) {
return {
...workflow,
allow_edit: access.allowEdit,
is_owner: access.isOwner,
shared_by_name: access.sharedByName ?? null,
};
}
async function resolveWorkflowAccess(
workflowId: string,
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<WorkflowAccess> {
const { data: workflow } = await db
.from("workflows")
.select("*")
.eq("id", workflowId)
.single();
if (!workflow) return null;
const workflowRecord = workflow as WorkflowRecord;
if (workflowRecord.user_id === userId) {
return { workflow: workflowRecord, allowEdit: true, isOwner: true };
}
const normalizedUserEmail = (userEmail ?? "").trim().toLowerCase();
if (!normalizedUserEmail) return null;
const { data: share } = await db
.from("workflow_shares")
.select("allow_edit")
.eq("workflow_id", workflowId)
.eq("shared_with_email", normalizedUserEmail)
.maybeSingle();
if (!share) return null;
return { workflow: workflowRecord, allowEdit: !!share.allow_edit, isOwner: false };
}
// GET /workflows
workflowsRouter.get("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string;
const { type } = req.query as { type?: string };
const db = createServerSupabase();
// Own workflows
let ownQuery = db
.from("workflows")
.select("*")
.eq("user_id", userId)
.eq("is_system", false)
.order("created_at", { ascending: false });
if (type) ownQuery = ownQuery.eq("type", type);
const { data: own, error: ownErr } = await ownQuery;
if (ownErr) return void res.status(500).json({ detail: ownErr.message });
// Shared workflows (where the current user's email appears in workflow_shares)
const normalizedUserEmail = userEmail.trim().toLowerCase();
const { data: shares } = await db
.from("workflow_shares")
.select("workflow_id, shared_by_user_id, allow_edit")
.eq("shared_with_email", normalizedUserEmail);
let sharedWorkflows: Record<string, unknown>[] = [];
if (shares && shares.length > 0) {
const sharedIds = shares.map((s) => s.workflow_id);
let sharedQuery = db.from("workflows").select("*").in("id", sharedIds);
if (type) sharedQuery = sharedQuery.eq("type", type);
const { data: wfs } = await sharedQuery;
if (wfs && wfs.length > 0) {
// Fetch sharer profiles
const sharerIds = [...new Set(shares.map((s) => s.shared_by_user_id).filter(Boolean))];
const { data: profiles } = sharerIds.length > 0
? await db.from("user_profiles").select("user_id, display_name").in("user_id", sharerIds)
: { data: [] };
// Fetch sharer emails via admin client
const admin = getAdminClient();
const { data: authData } = await admin.auth.admin.listUsers({ perPage: 1000 });
const authUsers = authData?.users ?? [];
sharedWorkflows = wfs.map((wf) => {
const share = shares.find((s) => s.workflow_id === wf.id);
const sharerId = share?.shared_by_user_id;
const profile = profiles?.find((p) => p.user_id === sharerId);
const authUser = authUsers.find((u) => u.id === sharerId);
const shared_by_name = profile?.display_name || authUser?.email || null;
return withWorkflowAccess(wf, {
allowEdit: !!share?.allow_edit,
isOwner: false,
sharedByName: shared_by_name,
});
});
}
}
const ownWithFlag = (own ?? []).map((wf) =>
withWorkflowAccess(wf, { allowEdit: true, isOwner: true }),
);
res.json([...ownWithFlag, ...sharedWorkflows]);
});
// POST /workflows
workflowsRouter.post("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { title, type, prompt_md, columns_config, practice } = req.body as {
title: string;
type: string;
prompt_md?: string;
columns_config?: unknown;
practice?: string | null;
};
if (!title?.trim())
return void res.status(400).json({ detail: "title is required" });
if (!["assistant", "tabular"].includes(type))
return void res
.status(400)
.json({ detail: "type must be 'assistant' or 'tabular'" });
const db = createServerSupabase();
const { data, error } = await db
.from("workflows")
.insert({
user_id: userId,
title: title.trim(),
type,
prompt_md: prompt_md ?? null,
columns_config: columns_config ?? null,
practice: practice ?? null,
is_system: false,
})
.select("*")
.single();
if (error) return void res.status(500).json({ detail: error.message });
res.status(201).json(data);
});
async function handleWorkflowUpdate(req: import("express").Request, res: import("express").Response) {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { workflowId } = req.params;
const updates: Record<string, unknown> = {};
if (req.body.title != null) updates.title = req.body.title;
if (req.body.prompt_md != null) updates.prompt_md = req.body.prompt_md;
if (req.body.columns_config != null)
updates.columns_config = req.body.columns_config;
if ("practice" in req.body) updates.practice = req.body.practice ?? null;
const db = createServerSupabase();
const access = await resolveWorkflowAccess(workflowId, userId, userEmail, db);
if (!access || access.workflow.is_system || !access.allowEdit) {
return void res
.status(404)
.json({ detail: "Workflow not found or not editable" });
}
const { data, error } = await db
.from("workflows")
.update(updates)
.eq("id", workflowId)
.eq("is_system", false)
.select("*")
.single();
if (error || !data)
return void res
.status(404)
.json({ detail: "Workflow not found or not editable" });
res.json(
withWorkflowAccess(data, {
allowEdit: access.allowEdit,
isOwner: access.isOwner,
}),
);
}
// PUT /workflows/:workflowId
workflowsRouter.put("/:workflowId", requireAuth, handleWorkflowUpdate);
// PATCH /workflows/:workflowId
workflowsRouter.patch("/:workflowId", requireAuth, handleWorkflowUpdate);
// DELETE /workflows/:workflowId
workflowsRouter.delete("/:workflowId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { workflowId } = req.params;
const db = createServerSupabase();
const { error } = await db
.from("workflows")
.delete()
.eq("id", workflowId)
.eq("user_id", userId)
.eq("is_system", false);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// GET /workflows/hidden
workflowsRouter.get("/hidden", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const db = createServerSupabase();
const { data, error } = await db
.from("hidden_workflows")
.select("workflow_id")
.eq("user_id", userId);
if (error) return void res.status(500).json({ detail: error.message });
res.json((data ?? []).map((r) => r.workflow_id));
});
// POST /workflows/hidden
workflowsRouter.post("/hidden", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { workflow_id } = req.body as { workflow_id: string };
if (!workflow_id?.trim())
return void res.status(400).json({ detail: "workflow_id is required" });
const db = createServerSupabase();
const { error } = await db
.from("hidden_workflows")
.upsert({ user_id: userId, workflow_id }, { onConflict: "user_id,workflow_id" });
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// DELETE /workflows/hidden/:workflowId
workflowsRouter.delete("/hidden/:workflowId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { workflowId } = req.params;
const db = createServerSupabase();
const { error } = await db
.from("hidden_workflows")
.delete()
.eq("user_id", userId)
.eq("workflow_id", workflowId);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// GET /workflows/:workflowId
workflowsRouter.get("/:workflowId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { workflowId } = req.params;
const db = createServerSupabase();
const access = await resolveWorkflowAccess(workflowId, userId, userEmail, db);
if (!access)
return void res.status(404).json({ detail: "Workflow not found" });
res.json(
withWorkflowAccess(access.workflow, {
allowEdit: access.allowEdit,
isOwner: access.isOwner,
}),
);
});
// GET /workflows/:workflowId/shares
workflowsRouter.get("/:workflowId/shares", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { workflowId } = req.params;
const db = createServerSupabase();
const { data: wf } = await db
.from("workflows")
.select("id")
.eq("id", workflowId)
.eq("user_id", userId)
.eq("is_system", false)
.single();
if (!wf) return void res.status(404).json({ detail: "Workflow not found or not editable" });
const { data: shares, error } = await db
.from("workflow_shares")
.select("id, shared_with_email, allow_edit, created_at")
.eq("workflow_id", workflowId)
.order("created_at", { ascending: true });
if (error) return void res.status(500).json({ detail: error.message });
res.json(shares ?? []);
});
// DELETE /workflows/:workflowId/shares/:shareId
workflowsRouter.delete("/:workflowId/shares/:shareId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { workflowId, shareId } = req.params;
const db = createServerSupabase();
const { data: wf } = await db
.from("workflows")
.select("id")
.eq("id", workflowId)
.eq("user_id", userId)
.single();
if (!wf) return void res.status(404).json({ detail: "Workflow not found" });
await db.from("workflow_shares").delete().eq("id", shareId).eq("workflow_id", workflowId);
res.status(204).send();
});
// POST /workflows/:workflowId/share
workflowsRouter.post("/:workflowId/share", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { workflowId } = req.params;
const { emails, allow_edit } = req.body as { emails: string[]; allow_edit: boolean };
if (!emails?.length) return void res.status(400).json({ detail: "emails is required" });
const db = createServerSupabase();
// Verify ownership
const { data: wf } = await db
.from("workflows")
.select("id")
.eq("id", workflowId)
.eq("user_id", userId)
.eq("is_system", false)
.single();
if (!wf) return void res.status(404).json({ detail: "Workflow not found or not editable" });
const rows = emails.map((email: string) => ({
workflow_id: workflowId,
shared_by_user_id: userId,
shared_with_email: email.trim().toLowerCase(),
allow_edit: allow_edit ?? false,
}));
// Upsert on (workflow_id, shared_with_email) so re-sharing to the same
// person updates the existing row instead of stacking duplicates.
const { error } = await db
.from("workflow_shares")
.upsert(rows, { onConflict: "workflow_id,shared_with_email" });
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});

19
backend/tsconfig.json Normal file
View file

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"moduleResolution": "node",
"ignoreDeprecations": "5.0",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

View file

@ -0,0 +1,4 @@
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_DEFAULT_KEY=your-supabase-anon-key
SUPABASE_SECRET_KEY=your-supabase-service-role-key
NEXT_PUBLIC_API_BASE_URL=http://localhost:3001

4165
frontend/bun.lock Normal file

File diff suppressed because it is too large Load diff

22
frontend/components.json Normal file
View file

@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

View file

@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

21
frontend/next.config.ts Normal file
View file

@ -0,0 +1,21 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
reactCompiler: true,
async rewrites() {
return [
{
source: "/sitemap.xml",
destination: "/api/sitemap/sitemap.xml",
},
{
source: "/sitemap_:slug.xml",
destination: "/api/sitemap/sitemap_:slug.xml",
},
];
},
skipTrailingSlashRedirect: true,
};
export default nextConfig;

View file

@ -0,0 +1,3 @@
import { defineCloudflareConfig } from "@opennextjs/cloudflare";
export default defineCloudflareConfig();

17998
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

73
frontend/package.json Normal file
View file

@ -0,0 +1,73 @@
{
"name": "mike",
"version": "0.1.0",
"license": "AGPL-3.0-only",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
"deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
"upload": "opennextjs-cloudflare build && opennextjs-cloudflare upload",
"cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1025.0",
"@aws-sdk/s3-request-presigner": "^3.1025.0",
"@opennextjs/cloudflare": "^1.13.1",
"@openrouter/sdk": "^0.3.11",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-icons": "^1.3.2",
"@radix-ui/react-slot": "^1.2.4",
"@supabase/auth-helpers-nextjs": "^0.10.0",
"@supabase/auth-js": "^2.101.1",
"@supabase/supabase-js": "^2.81.1",
"@tiptap/pm": "^3.22.3",
"@tiptap/react": "^3.22.3",
"@tiptap/starter-kit": "^3.22.3",
"@types/jsdom": "^27.0.0",
"@uiw/react-md-editor": "^4.1.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"docx": "^9.6.1",
"docx-preview": "^0.3.7",
"exceljs": "^4.4.0",
"katex": "^0.16.27",
"lucide-react": "^0.553.0",
"mammoth": "^1.11.0",
"marked": "^17.0.1",
"next": "16.0.3",
"nextjs-toploader": "^3.9.17",
"pdfjs-dist": "4.10.38",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-markdown": "^10.1.0",
"recharts": "^3.7.0",
"rehype-katex": "^7.0.1",
"rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.1",
"remark-gfm-configurable": "^1.0.0",
"remark-math": "^6.0.0",
"resend": "^6.8.0",
"tailwind-merge": "^3.4.0",
"tiptap-markdown": "^0.9.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/marked": "^5.0.2",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/uuid": "^10.0.0",
"babel-plugin-react-compiler": "1.0.0",
"baseline-browser-mapping": "^2.9.11",
"eslint": "^9",
"eslint-config-next": "16.0.3",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5",
"wrangler": "^4.51.0"
}
}

View file

@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
frontend/public/file.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1 KiB

1
frontend/public/next.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View file

@ -0,0 +1,81 @@
"use client";
import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
interface TabDef {
id: string;
label: string;
href: string;
}
const TABS: TabDef[] = [
{ id: "general", label: "General", href: "/account" },
{ id: "models", label: "Models & API Keys", href: "/account/models" },
];
export default function AccountLayout({
children,
}: {
children: React.ReactNode;
}) {
const router = useRouter();
const pathname = usePathname();
const { isAuthenticated, authLoading } = useAuth();
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/");
}
}, [isAuthenticated, authLoading, router]);
if (authLoading) {
return (
<div className="h-dvh bg-white flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-blue-600" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<div className="flex flex-col h-full md:overflow-y-auto px-6 py-6 md:py-10">
<div className="max-w-5xl w-full mx-auto">
<h1 className="text-4xl font-medium mb-8 font-eb-garamond">
Settings
</h1>
<div className="flex flex-col md:flex-row gap-6 md:gap-10">
<nav
aria-label="Settings"
className="md:w-56 shrink-0 flex md:flex-col gap-1 overflow-x-auto"
>
{TABS.map((tab) => {
const active = pathname === tab.href;
return (
<button
key={tab.id}
onClick={() => router.push(tab.href)}
className={`text-left whitespace-nowrap px-3 py-2 rounded-md text-sm font-medium transition-colors ${
active
? "bg-gray-100 text-gray-900"
: "text-gray-500 hover:text-gray-900 hover:bg-gray-50"
}`}
>
{tab.label}
</button>
);
})}
</nav>
<div className="flex-1 min-w-0">{children}</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,263 @@
"use client";
import { useEffect, useState } from "react";
import { AlertCircle, Check, ChevronDown, Eye, EyeOff } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { MODELS } from "@/app/components/assistant/ModelToggle";
import {
isModelAvailable,
modelGroupToProvider,
} from "@/app/lib/modelAvailability";
export default function ModelsAndApiKeysPage() {
const { profile, updateModelPreference, updateApiKey } = useUserProfile();
return (
<div className="space-y-4">
{/* Model Preferences */}
<div className="pb-6">
<div className="flex items-center gap-2 mb-4">
<h2 className="text-2xl font-medium font-serif">
Model Preferences
</h2>
</div>
<div className="space-y-4 max-w-md">
<div>
<label className="text-sm text-gray-600 block mb-2">
Tabular review model
</label>
<TabularModelDropdown
value={
profile?.tabularModel ??
"gemini-3-flash-preview"
}
apiKeys={{
claudeApiKey: profile?.claudeApiKey ?? null,
geminiApiKey: profile?.geminiApiKey ?? null,
}}
onChange={(id) =>
updateModelPreference("tabularModel", id)
}
/>
</div>
</div>
</div>
{/* API Keys */}
<div className="py-6">
<div className="flex items-center gap-2 mb-2">
<h2 className="text-2xl font-medium font-serif">
API Keys
</h2>
</div>
<p className="text-sm text-gray-500 mb-4 max-w-xl">
You must provide your own API keys for the app to work or
add your API keys into the .env file if you are running your
own instance of Mike.
</p>
<p className="text-xs text-gray-400 mb-4 max-w-xl">
Title generation automatically routes to the cheapest model
of whichever provider you&rsquo;ve configured (Gemini Flash
Lite if a Gemini key is set, otherwise Claude Haiku).
</p>
<div className="space-y-4 max-w-xl">
<ApiKeyField
label="Anthropic (Claude) API Key"
placeholder="sk-ant-…"
initialValue={profile?.claudeApiKey ?? ""}
onSave={(value) =>
updateApiKey("claude", value.trim() || null)
}
/>
<ApiKeyField
label="Google (Gemini) API Key"
placeholder="AI…"
initialValue={profile?.geminiApiKey ?? ""}
onSave={(value) =>
updateApiKey("gemini", value.trim() || null)
}
/>
</div>
</div>
</div>
);
}
function TabularModelDropdown({
value,
onChange,
apiKeys,
}: {
value: string;
onChange: (id: string) => void;
apiKeys: { claudeApiKey: string | null; geminiApiKey: string | null };
}) {
const [isOpen, setIsOpen] = useState(false);
const selected = MODELS.find((m) => m.id === value);
const selectedAvailable = isModelAvailable(value, apiKeys);
const groups: ("Anthropic" | "Google")[] = ["Anthropic", "Google"];
return (
<DropdownMenu onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<button
type="button"
className="w-full h-9 rounded-md border border-gray-300 bg-white px-3 text-sm shadow-sm flex items-center justify-between gap-2 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-black/10"
>
<span className="flex items-center gap-2 min-w-0">
{!selectedAvailable && (
<AlertCircle className="h-3.5 w-3.5 shrink-0 text-red-500" />
)}
<span className="truncate text-gray-900">
{selected?.label ?? "Select a model"}
</span>
</span>
<ChevronDown
className={`h-3.5 w-3.5 shrink-0 text-gray-500 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
className="z-50"
style={{ width: "var(--radix-dropdown-menu-trigger-width)" }}
align="start"
>
{groups.map((group, gi) => {
const items = MODELS.filter((m) => m.group === group);
if (items.length === 0) return null;
return (
<div key={group}>
{gi > 0 && <DropdownMenuSeparator />}
<DropdownMenuLabel className="text-[10px] uppercase tracking-wider text-gray-400">
{group}
</DropdownMenuLabel>
{items.map((m) => {
const provider = modelGroupToProvider(m.group);
const available = isModelAvailable(
m.id,
apiKeys,
);
return (
<DropdownMenuItem
key={m.id}
className="cursor-pointer"
onSelect={() => onChange(m.id)}
title={
!available
? `Add a ${provider === "claude" ? "Claude" : "Gemini"} API key to use this model`
: undefined
}
>
<span
className={`flex-1 ${available ? "" : "text-gray-400"}`}
>
{m.label}
</span>
{!available && (
<AlertCircle className="h-3.5 w-3.5 text-red-500 ml-1" />
)}
{m.id === value && available && (
<Check className="h-3.5 w-3.5 text-gray-600 ml-1" />
)}
</DropdownMenuItem>
);
})}
</div>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}
function ApiKeyField({
label,
placeholder,
initialValue,
onSave,
}: {
label: string;
placeholder: string;
initialValue: string;
onSave: (value: string) => Promise<boolean>;
}) {
const [value, setValue] = useState(initialValue);
const [reveal, setReveal] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [saved, setSaved] = useState(false);
useEffect(() => {
setValue(initialValue);
}, [initialValue]);
const dirty = value !== initialValue;
const handleSave = async () => {
setIsSaving(true);
const ok = await onSave(value);
setIsSaving(false);
if (ok) {
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} else {
alert(`Failed to save ${label}.`);
}
};
return (
<div>
<label className="text-sm text-gray-600 block mb-2">{label}</label>
<div className="flex gap-2">
<div className="relative flex-1">
<Input
type={reveal ? "text" : "password"}
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={placeholder}
className="pr-10"
autoComplete="off"
spellCheck={false}
/>
<button
type="button"
onClick={() => setReveal((r) => !r)}
className="absolute inset-y-0 right-2 flex items-center text-gray-400 hover:text-gray-600"
aria-label={reveal ? "Hide key" : "Show key"}
>
{reveal ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
<Button
onClick={handleSave}
disabled={isSaving || !dirty || saved}
className="min-w-[80px] transition-all bg-black hover:bg-gray-900 text-white"
>
{isSaving ? (
"Saving..."
) : saved ? (
<>
<Check className="h-4 w-3" />
Saved
</>
) : (
"Save"
)}
</Button>
</div>
</div>
);
}

View file

@ -0,0 +1,240 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LogOut, Check } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { deleteAccount } from "@/app/lib/mikeApi";
export default function AccountPage() {
const router = useRouter();
const { user, signOut } = useAuth();
const { profile, updateDisplayName, updateOrganisation } = useUserProfile();
const [displayName, setDisplayName] = useState("");
const [isSavingName, setIsSavingName] = useState(false);
const [saved, setSaved] = useState(false);
const [organisation, setOrganisation] = useState("");
const [isSavingOrg, setIsSavingOrg] = useState(false);
const [orgSaved, setOrgSaved] = useState(false);
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => {
if (profile?.displayName) {
setDisplayName(profile.displayName);
}
if (profile?.organisation) {
setOrganisation(profile.organisation);
}
}, [profile]);
const handleLogout = async () => {
await signOut();
router.push("/");
};
const handleDeleteAccount = async () => {
setIsDeleting(true);
try {
await deleteAccount();
await signOut();
router.push("/");
} catch {
setIsDeleting(false);
setDeleteConfirm(false);
alert("Failed to delete account. Please try again.");
}
};
const handleSaveDisplayName = async () => {
setIsSavingName(true);
const success = await updateDisplayName(displayName.trim());
setIsSavingName(false);
if (success) {
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} else {
alert("Failed to update display name. Please try again.");
}
};
const handleSaveOrganisation = async () => {
setIsSavingOrg(true);
const success = await updateOrganisation(organisation.trim());
setIsSavingOrg(false);
if (success) {
setOrgSaved(true);
setTimeout(() => setOrgSaved(false), 2000);
} else {
alert("Failed to update organisation. Please try again.");
}
};
if (!user) return null;
return (
<div className="space-y-4">
{/* Profile Settings */}
<div className="pb-6">
<div className="flex items-center gap-2 mb-4">
<h2 className="text-2xl font-medium font-serif">Profile</h2>
</div>
<div className="space-y-4">
<div>
<label className="text-sm text-gray-600 block mb-2">
Display Name
</label>
<div className="flex gap-2">
<Input
type="text"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
placeholder="Enter your name"
className="flex-1"
/>
<Button
onClick={handleSaveDisplayName}
disabled={
isSavingName || !displayName.trim() || saved
}
className="min-w-[80px] transition-all bg-black hover:bg-gray-900 text-white"
>
{isSavingName ? (
"Saving..."
) : saved ? (
<>
<Check className="h-4 w-3" />
Saved
</>
) : (
"Save"
)}
</Button>
</div>
</div>
<div>
<label className="text-sm text-gray-600 block mb-2">
Organisation
</label>
<div className="flex gap-2">
<Input
type="text"
value={organisation}
onChange={(e) =>
setOrganisation(e.target.value)
}
placeholder="Enter your organisation"
className="flex-1"
/>
<Button
onClick={handleSaveOrganisation}
disabled={
isSavingOrg ||
organisation.trim() ===
(profile?.organisation ?? "") ||
orgSaved
}
className="min-w-[80px] transition-all bg-black hover:bg-gray-900 text-white"
>
{isSavingOrg ? (
"Saving..."
) : orgSaved ? (
<>
<Check className="h-4 w-3" />
Saved
</>
) : (
"Save"
)}
</Button>
</div>
</div>
<div>
<label className="text-sm text-gray-600 block mb-2">
Email
</label>
<p className="text-base">{user?.email}</p>
</div>
</div>
</div>
{/* Plan */}
<div className="py-6">
<div className="flex items-center gap-2 mb-4">
<h2 className="text-2xl font-medium font-serif">
Usage Plan
</h2>
</div>
<div>
<p className="text-base font-medium text-gray-500 capitalize">
{profile?.tier || "Free"}
</p>
</div>
</div>
{/* Actions */}
<div className="py-6">
<h2 className="text-2xl font-medium font-serif mb-4">
Actions
</h2>
<Button
variant="outline"
onClick={handleLogout}
className="w-full sm:w-auto"
>
<LogOut className="h-4 w-4 mr-2" />
Sign Out
</Button>
</div>
{/* Danger Zone */}
<div className="py-6">
<h2 className="text-2xl font-medium font-serif mb-1 text-red-600">
Danger Zone
</h2>
<p className="text-sm text-gray-500 mb-4">
Permanently delete your account and all associated data.
This action cannot be undone.
</p>
{deleteConfirm ? (
<div className="rounded-lg border border-red-200 bg-red-50 p-4 space-y-3 max-w-sm">
<p className="text-sm font-medium text-red-700">
Are you sure? This will permanently delete your
account.
</p>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => setDeleteConfirm(false)}
disabled={isDeleting}
className="text-sm"
>
Cancel
</Button>
<Button
onClick={handleDeleteAccount}
disabled={isDeleting}
className="text-sm bg-red-600 hover:bg-red-700 text-white"
>
{isDeleting ? "Deleting…" : "Delete Account"}
</Button>
</div>
</div>
) : (
<Button
variant="outline"
onClick={() => setDeleteConfirm(true)}
className="w-full sm:w-auto border-red-200 text-red-600 hover:bg-red-50 hover:text-red-700"
>
Delete Account
</Button>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,70 @@
"use client";
import { useEffect, useRef } from "react";
import { useParams, useRouter } from "next/navigation";
import { useAssistantChat } from "@/app/hooks/useAssistantChat";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { ChatView } from "@/app/components/assistant/ChatView";
import { getChat } from "@/app/lib/mikeApi";
export default function AssistantChatPage() {
const router = useRouter();
const params = useParams();
const id = params.id as string;
const { setCurrentChatId, newChatMessages, setNewChatMessages } =
useChatHistoryContext();
const initialMessages = newChatMessages ?? [];
const { messages, isResponseLoading, handleChat, setMessages, cancel } =
useAssistantChat({ initialMessages, chatId: id });
const hasAutoSent = useRef(false);
const hasLoaded = useRef(false);
useEffect(() => {
setCurrentChatId(id);
}, [id, setCurrentChatId]);
useEffect(() => {
if (initialMessages.length > 0) {
if (newChatMessages) setNewChatMessages(null);
return;
}
if (hasLoaded.current || messages.length > 0) return;
hasLoaded.current = true;
getChat(id)
.then(({ messages: loaded }) => {
if (loaded.length > 0) {
setMessages(loaded);
} else {
router.replace("/assistant");
}
})
.catch(() => router.replace("/assistant"));
}, [id]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (
newChatMessages &&
newChatMessages.length === 1 &&
newChatMessages[0].role === "user" &&
!hasAutoSent.current &&
!isResponseLoading &&
messages.length === 1
) {
hasAutoSent.current = true;
void handleChat(newChatMessages[0]);
}
}, [newChatMessages, messages.length, isResponseLoading]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<ChatView
messages={messages}
isResponseLoading={isResponseLoading}
handleChat={handleChat}
cancel={cancel}
/>
);
}

View file

@ -0,0 +1,35 @@
"use client";
import { useRouter } from "next/navigation";
import { useAssistantChat } from "@/app/hooks/useAssistantChat";
import { InitialView } from "@/app/components/assistant/InitialView";
import { ChatView } from "@/app/components/assistant/ChatView";
import type { MikeMessage } from "@/app/components/shared/types";
export default function AssistantPage() {
const router = useRouter();
const { messages, isResponseLoading, handleChat, handleNewChat, cancel } =
useAssistantChat();
async function handleInitialSubmit(message: MikeMessage) {
const chatId = await handleNewChat(message);
if (chatId) router.push(`/assistant/chat/${chatId}`);
}
if (messages.length === 0) {
return (
<InitialView
onSubmit={(message) => void handleInitialSubmit(message)}
/>
);
}
return (
<ChatView
messages={messages}
isResponseLoading={isResponseLoading}
handleChat={handleChat}
cancel={cancel}
/>
);
}

View file

@ -0,0 +1,107 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Menu } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { ChatHistoryProvider } from "@/app/contexts/ChatHistoryContext";
import { SidebarContext } from "@/app/contexts/SidebarContext";
import { AppSidebar } from "@/app/components/shared/AppSidebar";
export default function MikeLayout({
children,
}: {
children: React.ReactNode;
}) {
const { isAuthenticated, authLoading } = useAuth();
const router = useRouter();
const [isSidebarOpenDesktop, setIsSidebarOpenDesktop] = useState(() => {
if (typeof window !== "undefined") {
const saved = localStorage.getItem("sidebarOpen");
return saved !== null ? saved === "true" : true;
}
return true;
});
const [isSidebarOpen, setIsSidebarOpen] = useState(() => {
if (typeof window !== "undefined" && window.innerWidth < 768) {
return false;
}
return true;
});
useEffect(() => {
if (typeof window !== "undefined" && window.innerWidth >= 768) {
localStorage.setItem("sidebarOpen", isSidebarOpen.toString());
}
}, [isSidebarOpenDesktop]);
useEffect(() => {
if (typeof window === "undefined") return;
const handleResize = () => {
const isSmall = window.innerWidth < 768;
if (isSmall && isSidebarOpen) setIsSidebarOpen(false);
else if (!isSmall && !isSidebarOpen)
setIsSidebarOpen(isSidebarOpenDesktop);
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, [isSidebarOpen, isSidebarOpenDesktop]);
const handleSidebarToggle = () => {
if (window.innerWidth >= 768) {
setIsSidebarOpenDesktop(!isSidebarOpenDesktop);
setIsSidebarOpen(!isSidebarOpenDesktop);
} else {
setIsSidebarOpen(!isSidebarOpen);
}
};
useEffect(() => {
if (!authLoading && !isAuthenticated) {
router.push("/login");
}
}, [authLoading, isAuthenticated, router]);
if (authLoading) {
return (
<div className="flex h-screen items-center justify-center">
<div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-gray-700" />
</div>
);
}
if (!isAuthenticated) return null;
return (
<ChatHistoryProvider>
<SidebarContext.Provider
value={{ setSidebarOpen: (open) => { setIsSidebarOpen(open); setIsSidebarOpenDesktop(open); } }}
>
<div className="h-dvh bg-white flex flex-col">
<div className="flex-1 flex overflow-hidden">
<AppSidebar
isOpen={isSidebarOpen}
onToggle={handleSidebarToggle}
/>
<div className="flex-1 flex flex-col h-dvh md:overflow-hidden relative w-full">
{/* Mobile header */}
<div className="flex md:hidden items-center gap-3 px-4 py-3 border-b border-gray-100 shrink-0">
<button
onClick={handleSidebarToggle}
className="flex items-center justify-center w-8 h-8 rounded hover:bg-gray-100 text-gray-500 transition-colors"
>
<Menu className="h-5 w-5" />
</button>
</div>
<main className="flex-1 overflow-y-auto md:overflow-hidden w-full h-full">
{children}
</main>
</div>
</div>
</div>
</SidebarContext.Provider>
</ChatHistoryProvider>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
"use client";
import { use } from "react";
import { ProjectPage } from "@/app/components/projects/ProjectPage";
interface Props {
params: Promise<{ id: string }>;
}
export default function ProjectDetailPage({ params }: Props) {
const { id } = use(params);
return <ProjectPage projectId={id} />;
}

View file

@ -0,0 +1,13 @@
"use client";
import { use } from "react";
import { TRView } from "@/app/components/tabular/TabularReviewView";
interface Props {
params: Promise<{ id: string; reviewId: string }>;
}
export default function ProjectTabularReviewPage({ params }: Props) {
const { id, reviewId } = use(params);
return <TRView reviewId={reviewId} projectId={id} />;
}

View file

@ -0,0 +1,7 @@
"use client";
import { ProjectsOverview } from "@/app/components/projects/ProjectsOverview";
export default function ProjectsPage() {
return <ProjectsOverview />;
}

View file

@ -0,0 +1,13 @@
"use client";
import { use } from "react";
import { TRView } from "@/app/components/tabular/TabularReviewView";
interface Props {
params: Promise<{ id: string }>;
}
export default function TabularReviewPage({ params }: Props) {
const { id } = use(params);
return <TRView reviewId={id} />;
}

View file

@ -0,0 +1,539 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, Loader2, ChevronDown, Check, Table2 } from "lucide-react";
import { HeaderSearchBtn } from "@/app/components/shared/HeaderSearchBtn";
import { RowActions } from "@/app/components/shared/RowActions";
import {
deleteTabularReview,
listTabularReviews,
createTabularReview,
listProjects,
updateTabularReview,
} from "@/app/lib/mikeApi";
import type { TabularReview, MikeProject } from "@/app/components/shared/types";
import { ToolbarTabs } from "@/app/components/shared/ToolbarTabs";
import { AddNewTRModal } from "@/app/components/tabular/AddNewTRModal";
import { OwnerOnlyModal } from "@/app/components/shared/OwnerOnlyModal";
import { useAuth } from "@/contexts/AuthContext";
type Tab = "all" | "in-project" | "standalone";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
const TABS: { id: Tab; label: string }[] = [
{ id: "all", label: "All Reviews" },
{ id: "in-project", label: "In Project" },
{ id: "standalone", label: "Standalone" },
];
function formatDate(iso: string) {
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
export default function TabularReviewsPage() {
const [reviews, setReviews] = useState<TabularReview[]>([]);
const [projects, setProjects] = useState<MikeProject[]>([]);
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [newTROpen, setNewTROpen] = useState(false);
const [activeTab, setActiveTab] = useState<Tab>("all");
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [projectFilter, setProjectFilter] = useState<string | null>(null);
const [filterOpen, setFilterOpen] = useState(false);
const [search, setSearch] = useState("");
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [actionsOpen, setActionsOpen] = useState(false);
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const filterRef = useRef<HTMLDivElement>(null);
const actionsRef = useRef<HTMLDivElement>(null);
const router = useRouter();
const { user } = useAuth();
useEffect(() => {
Promise.all([
listTabularReviews().catch(() => []),
listProjects().catch(() => []),
])
.then(([r, p]) => {
setReviews(r);
setProjects(p);
})
.finally(() => setLoading(false));
}, []);
useEffect(() => {
setSelectedIds([]);
}, [activeTab, projectFilter]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (filterRef.current && !filterRef.current.contains(e.target as Node)) setFilterOpen(false);
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (
actionsRef.current &&
!actionsRef.current.contains(e.target as Node)
) {
setActionsOpen(false);
}
}
if (actionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [actionsOpen]);
const q = search.toLowerCase();
const filtered = reviews
.filter((r) => {
if (activeTab === "in-project") return !!r.project_id;
if (activeTab === "standalone") return !r.project_id;
return true;
})
.filter((r) => !projectFilter || r.project_id === projectFilter)
.filter((r) => !q || (r.title ?? "").toLowerCase().includes(q));
const allSelected =
filtered.length > 0 &&
filtered.every((r) => selectedIds.includes(r.id));
const someSelected =
!allSelected && filtered.some((r) => selectedIds.includes(r.id));
function toggleAll() {
if (allSelected) setSelectedIds([]);
else setSelectedIds(filtered.map((r) => r.id));
}
function toggleOne(id: string) {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
}
const selectedProject = projects.find((p) => p.id === projectFilter);
const handleNewReview = async (
title: string,
projectId?: string,
documentIds?: string[],
columnsConfig?:
| import("@/app/components/shared/types").ColumnConfig[]
| null,
) => {
setCreating(true);
try {
const review = await createTabularReview({
title,
document_ids: documentIds ?? [],
columns_config: columnsConfig ?? [],
...(projectId && { project_id: projectId }),
});
router.push(
projectId
? `/projects/${projectId}/tabular-reviews/${review.id}`
: `/tabular-reviews/${review.id}`,
);
} finally {
setCreating(false);
}
};
async function handleRenameSubmit(reviewId: string) {
const trimmed = renameValue.trim();
if (!trimmed) {
setRenamingId(null);
return;
}
const review = reviews.find((r) => r.id === reviewId);
if (review && user?.id && review.user_id !== user.id) {
setRenamingId(null);
setOwnerOnlyAction("rename this tabular review");
return;
}
setReviews((prev) =>
prev.map((r) => (r.id === reviewId ? { ...r, title: trimmed } : r)),
);
setRenamingId(null);
await updateTabularReview(reviewId, { title: trimmed });
}
async function handleDeleteSelected() {
const ids = [...selectedIds];
setActionsOpen(false);
const owned = ids.filter((id) => {
const r = reviews.find((rr) => rr.id === id);
return !r || !user?.id || r.user_id === user.id;
});
const blocked = ids.length - owned.length;
setSelectedIds([]);
await Promise.all(
owned.map((id) => deleteTabularReview(id).catch(() => {})),
);
setReviews((prev) => prev.filter((r) => !owned.includes(r.id)));
if (blocked > 0) {
setOwnerOnlyAction(
`delete ${blocked} of the selected reviews — only the review creator can delete a review`,
);
}
}
const projectFilterButton = (
<div className="relative" ref={filterRef}>
<button
onClick={() => setFilterOpen((o) => !o)}
className={`flex items-center gap-1 text-xs font-medium transition-colors ${
projectFilter
? "text-gray-700 hover:text-gray-900"
: "text-gray-500 hover:text-gray-700"
}`}
>
{selectedProject ? selectedProject.name : "Filter by project"}
<ChevronDown className="h-3 w-3" />
</button>
{filterOpen && (
<div className="absolute right-0 top-full mt-1.5 z-20 w-52 rounded-xl border border-gray-100 bg-white shadow-lg overflow-hidden">
<button
onClick={() => {
setProjectFilter(null);
setFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
All Projects
{!projectFilter && (
<Check className="h-3.5 w-3.5 text-gray-400" />
)}
</button>
{projects.length > 0 && (
<div className="border-t border-gray-100" />
)}
{projects.map((p) => (
<button
key={p.id}
onClick={() => {
setProjectFilter(p.id);
setFilterOpen(false);
}}
className="flex items-center justify-between w-full px-3 py-2 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<span className="truncate pr-2">{p.name}</span>
{projectFilter === p.id && (
<Check className="h-3.5 w-3.5 shrink-0 text-gray-400" />
)}
</button>
))}
</div>
)}
</div>
);
const toolbarActions = (
<div className="flex items-center gap-2">
{selectedIds.length > 0 && (
<div ref={actionsRef} className="relative">
<button
onClick={() => setActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{actionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={handleDeleteSelected}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
{projectFilterButton}
</div>
);
return (
<div className="flex-1 overflow-y-auto bg-white">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4">
<h1 className="text-2xl font-medium font-serif text-gray-900">
Tabular Reviews
</h1>
<div className="flex items-center gap-2">
<HeaderSearchBtn value={search} onChange={setSearch} placeholder="Search reviews…" />
<button
onClick={() => setNewTROpen(true)}
disabled={creating}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors disabled:opacity-40"
>
{creating ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Plus className="h-4 w-4" />
)}
</button>
</div>
</div>
<ToolbarTabs
tabs={TABS}
active={activeTab}
onChange={setActiveTab}
actions={toolbarActions}
/>
{/* Table */}
<div className="w-full overflow-x-auto">
<div className="min-w-max">
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{!loading && (
<input
type="checkbox"
checked={allSelected}
ref={(el) => {
if (el) el.indeterminate = someSelected;
}}
onChange={toggleAll}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Name
</div>
<div className="ml-auto w-24 shrink-0">Columns</div>
<div className="w-24 shrink-0">Documents</div>
<div className="w-40 shrink-0">Project</div>
<div className="w-32 shrink-0">Created</div>
<div className="w-8 shrink-0" />
</div>
{loading ? (
<div>
{[1, 2, 3].map((i) => (
<div
key={i}
className="flex items-center h-10 pr-8 border-b border-gray-50"
>
<div className="w-8 shrink-0" />
<div className="flex-1 min-w-0 pl-3 pr-4">
<div className="h-3.5 w-48 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-40 shrink-0">
<div className="h-3 w-24 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-32 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
{activeTab === "all" && !projectFilter ? (
<>
<Table2 className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Tabular Reviews
</p>
<p className="mt-1 text-xs text-gray-400 max-w-xs text-left">
Extract data from documents into tables
using AI.
</p>
<button
onClick={() => setNewTROpen(true)}
disabled={creating}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md disabled:opacity-40"
>
+ Create New
</button>
</>
) : (
<p className="text-sm text-gray-400">
No reviews found
</p>
)}
</div>
) : (
<div>
{filtered.map((review) => {
const project = projects.find(
(p) => p.id === review.project_id,
);
const rowBg = selectedIds.includes(review.id)
? "bg-gray-50"
: "bg-white";
return (
<div
key={review.id}
onClick={() => {
if (renamingId === review.id) return;
router.push(
review.project_id
? `/projects/${review.project_id}/tabular-reviews/${review.id}`
: `/tabular-reviews/${review.id}`,
);
}}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${rowBg} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={selectedIds.includes(
review.id,
)}
onChange={() =>
toggleOne(review.id)
}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${rowBg} group-hover:bg-gray-50`}>
{renamingId === review.id ? (
<input
autoFocus
value={renameValue}
onChange={(e) =>
setRenameValue(
e.target.value,
)
}
onKeyDown={(e) => {
if (e.key === "Enter")
handleRenameSubmit(
review.id,
);
if (e.key === "Escape")
setRenamingId(null);
}}
onBlur={() =>
handleRenameSubmit(
review.id,
)
}
onClick={(e) =>
e.stopPropagation()
}
className="w-full text-sm text-gray-800 bg-transparent outline-none"
/>
) : (
<span className="text-sm text-gray-800 truncate block">
{review.title ??
"Untitled Review"}
</span>
)}
</div>
<div className="ml-auto w-24 shrink-0 text-sm text-gray-500 truncate">
{review.columns_config?.length ?? 0}
</div>
<div className="w-24 shrink-0 text-sm text-gray-500 truncate">
{review.document_count ?? 0}
</div>
<div className="w-40 shrink-0 text-sm text-gray-500 truncate pr-2">
{project ? (
project.name
) : (
<span className="text-gray-300">
</span>
)}
</div>
<div className="w-32 shrink-0 text-sm text-gray-500 truncate">
{review.created_at ? (
formatDate(review.created_at)
) : (
<span className="text-gray-300">
</span>
)}
</div>
<div
className="w-8 shrink-0 flex justify-end"
onClick={(e) => e.stopPropagation()}
>
<RowActions
onRename={() => {
if (
user?.id &&
review.user_id !== user.id
) {
setOwnerOnlyAction(
"rename this tabular review",
);
return;
}
setRenameValue(
review.title ??
"Untitled Review",
);
setRenamingId(review.id);
}}
onDelete={async () => {
if (
user?.id &&
review.user_id !== user.id
) {
setOwnerOnlyAction(
"delete this tabular review",
);
return;
}
await deleteTabularReview(
review.id,
);
setReviews((prev) =>
prev.filter(
(r) =>
r.id !== review.id,
),
);
}}
/>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
<AddNewTRModal
open={newTROpen}
onClose={() => setNewTROpen(false)}
onAdd={handleNewReview}
projects={projects}
/>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>
);
}

View file

@ -0,0 +1,504 @@
"use client";
import { use, useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { ChevronDown, Plus, Users, X } from "lucide-react";
import { getWorkflow, updateWorkflow } from "@/app/lib/mikeApi";
import { ShareWorkflowModal } from "@/app/components/workflows/ShareWorkflowModal";
import { WFEditColumnModal } from "@/app/components/workflows/WFEditColumnModal";
import { WFColumnViewModal } from "@/app/components/workflows/WFColumnViewModal";
import { AddColumnModal } from "@/app/components/tabular/AddColumnModal";
import type { ColumnConfig, MikeWorkflow } from "@/app/components/shared/types";
import {
BUILT_IN_IDS,
BUILT_IN_WORKFLOWS,
} from "@/app/components/workflows/builtinWorkflows";
import { formatIcon, formatLabel } from "@/app/components/tabular/columnFormat";
import { RenameableTitle } from "@/app/components/shared/RenameableTitle";
// dynamic import keeps Tiptap (browser-only) out of the SSR bundle
const WorkflowPromptEditor = dynamic(
() =>
import("@/app/components/workflows/WorkflowPromptEditor").then(
(m) => ({ default: m.WorkflowPromptEditor }),
),
{ ssr: false },
);
interface Props {
params: Promise<{ id: string }>;
}
type SaveStatus = "idle" | "saving" | "saved";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------
export default function WorkflowDetailPage({ params }: Props) {
const { id } = use(params);
const router = useRouter();
const [workflow, setWorkflow] = useState<MikeWorkflow | null>(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
const isBuiltin = BUILT_IN_IDS.has(id);
const readOnly =
isBuiltin ||
(workflow?.is_system ?? false) ||
workflow?.allow_edit === false;
const canShare = !readOnly && (workflow?.is_owner ?? true);
// Editor state
const [promptMd, setPromptMd] = useState("");
const [columns, setColumns] = useState<ColumnConfig[]>([]);
// Save status
const [saveStatus, setSaveStatus] = useState<SaveStatus>("idle");
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Column selection
const [selectedColIndices, setSelectedColIndices] = useState<number[]>([]);
// Column modal
const [addColumnOpen, setAddColumnOpen] = useState(false);
const [editingColumn, setEditingColumn] = useState<ColumnConfig | null>(null);
const [viewingColumn, setViewingColumn] = useState<ColumnConfig | null>(null);
// Share popover
const [shareOpen, setShareOpen] = useState(false);
// Column actions dropdown
const [colActionsOpen, setColActionsOpen] = useState(false);
const colActionsRef = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (colActionsRef.current && !colActionsRef.current.contains(e.target as Node)) {
setColActionsOpen(false);
}
}
if (colActionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [colActionsOpen]);
// ---------------------------------------------------------------------------
// Load workflow
// ---------------------------------------------------------------------------
useEffect(() => {
if (isBuiltin) {
const wf = BUILT_IN_WORKFLOWS.find((w) => w.id === id) ?? null;
if (!wf) {
setNotFound(true);
} else {
setWorkflow(wf);
setPromptMd(wf.prompt_md ?? "");
setColumns(wf.columns_config ?? []);
}
setLoading(false);
return;
}
getWorkflow(id)
.then((wf) => {
setWorkflow(wf);
setPromptMd(wf.prompt_md ?? "");
setColumns(
(wf.columns_config ?? [])
.slice()
.sort((a, b) => a.index - b.index),
);
})
.catch(() => setNotFound(true))
.finally(() => setLoading(false));
}, [id, isBuiltin]);
// ---------------------------------------------------------------------------
// Debounced auto-save for prompt
// ---------------------------------------------------------------------------
const save = useCallback(
(newPromptMd: string) => {
if (readOnly) return;
if (debounceRef.current) clearTimeout(debounceRef.current);
setSaveStatus("saving");
debounceRef.current = setTimeout(async () => {
try {
await updateWorkflow(id, { prompt_md: newPromptMd });
setSaveStatus("saved");
setTimeout(() => setSaveStatus("idle"), 2000);
} catch {
setSaveStatus("idle");
}
}, 800);
},
[id, readOnly],
);
async function handleTitleCommit(newTitle: string) {
if (!newTitle || newTitle === workflow?.title) return;
const updated = await updateWorkflow(id, { title: newTitle });
setWorkflow(updated);
}
function handlePromptChange(val: string | undefined) {
const next = val ?? "";
setPromptMd(next);
save(next);
}
// ---------------------------------------------------------------------------
// Column save
// ---------------------------------------------------------------------------
async function saveColumns(next: ColumnConfig[]) {
if (readOnly) return;
setSaveStatus("saving");
try {
const updated = await updateWorkflow(id, { columns_config: next });
setWorkflow(updated);
setSaveStatus("saved");
setTimeout(() => setSaveStatus("idle"), 2000);
} catch {
setSaveStatus("idle");
}
}
function handleColumnsAdded(added: ColumnConfig[]) {
const next = [
...columns,
...added.map((c, i) => ({ ...c, index: columns.length + i })),
];
setColumns(next);
saveColumns(next);
setAddColumnOpen(false);
}
function handleColumnSaved(updated: ColumnConfig) {
const next = columns.map((c) =>
c.index === updated.index ? updated : c,
);
setColumns(next);
saveColumns(next);
setEditingColumn(null);
}
// ---------------------------------------------------------------------------
// Render
// ---------------------------------------------------------------------------
if (loading) {
return (
<div className="flex flex-col h-full">
{/* Header skeleton */}
<div className="flex items-center justify-between px-8 py-4 shrink-0">
<div className="flex items-center gap-1.5">
<div className="h-6 w-24 rounded bg-gray-100 animate-pulse" />
<span className="text-gray-300"></span>
<div className="h-6 w-40 rounded bg-gray-100 animate-pulse" />
</div>
</div>
{/* Toolbar skeleton */}
<div className="flex items-center px-8 h-10 border-b border-gray-200 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
{/* Table header skeleton */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 shrink-0">
<div className="w-8 shrink-0 border-r border-gray-100 self-stretch" />
<div className="flex-1 pl-3">
<div className="h-2.5 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-36 shrink-0">
<div className="h-2.5 w-14 rounded bg-gray-100 animate-pulse" />
</div>
<div className="flex-1">
<div className="h-2.5 w-12 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
{/* Row skeletons */}
<div className="flex-1 overflow-hidden">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-center h-10 pr-8 border-b border-gray-50">
<div className="w-8 shrink-0 border-r border-gray-100 self-stretch" />
<div className="flex-1 pl-3 pr-4">
<div className="h-3 rounded bg-gray-100 animate-pulse" style={{ width: `${40 + (i * 13) % 35}%` }} />
</div>
<div className="w-36 shrink-0">
<div className="h-3 w-16 rounded bg-gray-100 animate-pulse" />
</div>
<div className="flex-1 pr-4">
<div className="h-3 rounded bg-gray-100 animate-pulse" style={{ width: `${50 + (i * 17) % 35}%` }} />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
</div>
);
}
if (notFound || !workflow) {
return (
<div className="flex-1 flex items-center justify-center">
<p className="text-gray-400 font-serif">Workflow not found.</p>
</div>
);
}
return (
<div className="flex flex-col h-full">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4 shrink-0">
<div className="flex items-center gap-1.5 text-2xl font-medium font-serif">
<button
onClick={() => router.push("/workflows")}
className="text-gray-500 hover:text-gray-700 transition-colors"
>
Workflows
</button>
<span className="text-gray-300"></span>
{readOnly ? (
<span className="text-gray-900 truncate max-w-xs">{workflow.title}</span>
) : (
<RenameableTitle value={workflow.title} onCommit={handleTitleCommit} />
)}
</div>
<div className="flex items-center gap-3">
{/* Save status */}
<span className="text-xs text-gray-400">
{saveStatus === "saving"
? "Saving…"
: saveStatus === "saved"
? "Saved"
: ""}
</span>
{/* Share button (custom workflows only) */}
{canShare && (
<button
onClick={() => setShareOpen(true)}
aria-label="Open workflow people"
title="People"
className="flex items-center text-gray-500 hover:text-gray-900 transition-colors"
>
<Users className="h-4 w-4" />
</button>
)}
{shareOpen && (
<ShareWorkflowModal
workflowId={id}
workflowName={workflow.title}
onClose={() => setShareOpen(false)}
/>
)}
</div>
</div>
{/* Read-only badge for built-in workflows */}
{readOnly && (
<div className="flex items-center h-10 px-8 border-b border-gray-200">
<span className="text-xs text-gray-400">Read-only</span>
</div>
)}
{/* Body */}
<div className="flex-1 min-h-0 flex flex-col">
{workflow.type === "assistant" ? (
/* ── Assistant: WYSIWYG editor ── */
<div className="flex-1 min-h-0 p-6">
<WorkflowPromptEditor
value={promptMd}
onChange={readOnly ? undefined : handlePromptChange}
readOnly={readOnly}
/>
</div>
) : (
/* ── Tabular: Column table ── */
<div className="flex flex-col flex-1 min-h-0">
{/* Toolbar */}
{!readOnly && (
<div className="flex items-center justify-between px-8 h-10 border-b border-gray-200 shrink-0">
<button
onClick={() => setAddColumnOpen(true)}
className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-700 transition-colors"
>
<Plus className="h-3.5 w-3.5" />
Add Column
</button>
{selectedColIndices.length > 0 && (
<div ref={colActionsRef} className="relative">
<button
onClick={() => setColActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{colActionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={() => {
const next = columns
.filter((c) => !selectedColIndices.includes(c.index))
.map((c, i) => ({ ...c, index: i }));
setColumns(next);
saveColumns(next);
setSelectedColIndices([]);
setColActionsOpen(false);
}}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
</div>
)}
<div className="flex-1 min-h-0 overflow-auto">
<div className="min-w-max flex min-h-full flex-col">
{/* Table header */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium shrink-0 select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{columns.length > 0 && (
<input
type="checkbox"
checked={columns.length > 0 && selectedColIndices.length === columns.length}
ref={(el) => { if (el) el.indeterminate = selectedColIndices.length > 0 && selectedColIndices.length < columns.length; }}
onChange={() => setSelectedColIndices(selectedColIndices.length === columns.length ? [] : columns.map((c) => c.index))}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Column Title
</div>
<div className="ml-auto w-36 shrink-0">Format</div>
<div className="flex-1 min-w-0">Prompt</div>
{!readOnly && <div className="w-8 shrink-0" />}
</div>
{/* Rows */}
<div className="flex-1">
{columns.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
<Plus className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Columns
</p>
<p className="mt-1 text-xs text-gray-400 text-left">
Add columns to define what this tabular review workflow extracts from each document.
</p>
{!readOnly && (
<button
onClick={() => setAddColumnOpen(true)}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md"
>
+ Add Column
</button>
)}
</div>
) : (
columns.map((col) => {
const FormatIcon = formatIcon(col.format ?? "text");
const isChecked = selectedColIndices.includes(col.index);
return (
<div
key={col.index}
onClick={() => readOnly ? setViewingColumn(col) : setEditingColumn(col)}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${isChecked ? "bg-gray-50" : "bg-white"} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={isChecked}
onChange={() => setSelectedColIndices((prev) => prev.includes(col.index) ? prev.filter((i) => i !== col.index) : [...prev, col.index])}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${isChecked ? "bg-gray-50" : "bg-white"} group-hover:bg-gray-50`}>
<span className="text-sm text-gray-800 truncate block">
{col.name}
</span>
</div>
<div className="ml-auto w-36 shrink-0">
<span className="inline-flex items-center gap-1.5 text-xs text-gray-600">
<FormatIcon className="h-3.5 w-3.5 text-gray-400" />
{formatLabel(col.format ?? "text")}
</span>
</div>
<div className="flex-1 min-w-0 pr-4">
<span className="text-xs text-gray-500 truncate block">
{col.prompt}
</span>
</div>
{!readOnly && (
<div className="w-8 shrink-0 flex justify-end">
<button
onClick={(e) => {
e.stopPropagation();
const next = columns
.filter((c) => c.index !== col.index)
.map((c, i) => ({ ...c, index: i }));
setColumns(next);
saveColumns(next);
}}
className="p-1 text-gray-300 hover:text-red-500 transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)}
</div>
);
})
)}
</div>
</div>
</div>
</div>
)}
</div>
{/* Read-only column view modal */}
{viewingColumn && (
<WFColumnViewModal col={viewingColumn} onClose={() => setViewingColumn(null)} />
)}
{/* Add column modal */}
<AddColumnModal
open={addColumnOpen}
existingCount={columns.length}
onClose={() => setAddColumnOpen(false)}
onAdd={handleColumnsAdded}
/>
{/* Edit column modal */}
{editingColumn && (
<WFEditColumnModal
column={editingColumn}
onClose={() => setEditingColumn(null)}
onSave={handleColumnSaved}
onDelete={() => {
const next = columns
.filter((c) => c.index !== editingColumn.index)
.map((c, i) => ({ ...c, index: i }));
setColumns(next);
saveColumns(next);
setEditingColumn(null);
}}
/>
)}
</div>
);
}

View file

@ -0,0 +1,7 @@
"use client";
import { WorkflowList } from "@/app/components/workflows/WorkflowList";
export default function WorkflowsPage() {
return <WorkflowList />;
}

View file

@ -0,0 +1,110 @@
"use client";
import { useRef, useState } from "react";
import { PlusIcon, Upload, LayoutGridIcon, Loader2Icon } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { uploadStandaloneDocument } from "@/app/lib/mikeApi";
import type { MikeDocument } from "../shared/types";
interface Props {
onSelectDoc: (doc: MikeDocument) => void;
onBrowseAll: () => void;
selectedDocIds?: string[];
}
export function AddDocButton({ onSelectDoc, onBrowseAll, selectedDocIds = [] }: Props) {
const [isOpen, setIsOpen] = useState(false);
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) => uploadStandaloneDocument(f)),
);
uploaded.forEach((doc) => onSelectDoc(doc));
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
return (
<>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<DropdownMenu onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<button
className={`flex items-center gap-1 px-2 h-8 rounded-lg text-sm transition-colors cursor-pointer ${
selectedDocIds.length > 0
? "text-black hover:bg-gray-100"
: "text-gray-400 hover:text-gray-700 hover:bg-gray-100"
} ${isOpen ? "bg-gray-100" : ""}`}
title="Add documents"
aria-label="Add documents"
>
{selectedDocIds.length > 0 ? (
<span className="font-medium tabular-nums">{selectedDocIds.length}</span>
) : (
<PlusIcon
className={`h-4 w-4 shrink-0 transition-transform duration-300 ${isOpen ? "rotate-[135deg]" : ""}`}
/>
)}
<span className="hidden sm:inline">
{selectedDocIds.length === 1
? "Document"
: "Documents"}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-44 z-50"
side="bottom"
align="start"
>
<DropdownMenuItem
className="cursor-pointer"
disabled={uploading}
onSelect={(e) => {
e.preventDefault();
fileInputRef.current?.click();
}}
>
{uploading ? (
<Loader2Icon className="h-4 w-4 mr-2 animate-spin text-gray-400" />
) : (
<Upload className="h-4 w-4 mr-2 text-gray-500" />
)}
<span className="text-sm">
{uploading ? "Uploading…" : "Upload files"}
</span>
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer"
onClick={onBrowseAll}
>
<LayoutGridIcon className="h-4 w-4 mr-2 text-gray-500" />
<span className="text-sm">Browse all</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,274 @@
"use client";
import { useCallback, useRef, useState } from "react";
import { X } from "lucide-react";
import { DocPanel, type DocPanelMode } from "../shared/DocPanel";
import type {
MikeCitationAnnotation,
MikeEditAnnotation,
} from "../shared/types";
// ---------------------------------------------------------------------------
// Tab data
// ---------------------------------------------------------------------------
//
// Each tab represents ONE of:
// - a document view (no specific annotation),
// - a single citation quote,
// - a single tracked change.
// There is no selector UI inside the panel — the user picks what to view
// by clicking a different tab (or opening a new one from a citation pill,
// an EditCard's View button, or the download card).
type CommonTab = {
id: string;
documentId: string;
filename: string;
versionId: string | null;
versionNumber: number | null;
warning?: string | null;
initialScrollTop?: number | null;
};
export type DocumentTab = CommonTab & { kind: "document" };
export type CitationTab = CommonTab & {
kind: "citation";
citation: MikeCitationAnnotation;
};
export type EditTab = CommonTab & {
kind: "edit";
edit: MikeEditAnnotation;
};
export type AssistantSidePanelTab = DocumentTab | CitationTab | EditTab;
interface Props {
tabs: AssistantSidePanelTab[];
activeTabId: string | null;
onActivateTab: (id: string) => void;
onCloseTab: (id: string) => void;
onCloseAll: () => void;
/**
* Parent-driven reloading flag per document. Download buttons in
* DocPanel show a spinner iff this returns true for the tab's
* documentId. Used to signal "accept/reject in flight".
*/
isEditorReloading?: (documentId: string) => boolean;
/**
* True while an accept/reject for this exact edit is in flight.
* Disables the panel's Accept/Reject buttons for only the edit
* currently being resolved sibling edits stay clickable.
*/
isEditReloading?: (editId: string) => boolean;
onEditResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onEditResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
onEditError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
onWarningDismiss?: (tabId: string) => void;
onScrollChange?: (tabId: string, scrollTop: number) => void;
}
const MIN_WIDTH = 300;
const MAX_WIDTH_OFFSET = 56; // sidebar width
export function AssistantSidePanel({
tabs,
activeTabId,
onActivateTab,
onCloseTab,
onCloseAll,
isEditorReloading,
isEditReloading,
onEditResolveStart,
onEditResolved,
onEditError,
onWarningDismiss,
onScrollChange,
}: Props) {
const panelRef = useRef<HTMLDivElement>(null);
const [panelWidth, setPanelWidth] = useState(() =>
typeof window !== "undefined"
? Math.round((window.innerWidth - MAX_WIDTH_OFFSET) / 2)
: 600,
);
const dragStartX = useRef<number>(0);
const dragStartWidth = useRef<number>(0);
const onMouseDown = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
dragStartX.current = e.clientX;
dragStartWidth.current =
panelRef.current?.offsetWidth ?? panelWidth;
const onMouseMove = (ev: MouseEvent) => {
const delta = dragStartX.current - ev.clientX;
const maxWidth = window.innerWidth - MAX_WIDTH_OFFSET - 200;
setPanelWidth(
Math.min(
maxWidth,
Math.max(MIN_WIDTH, dragStartWidth.current + delta),
),
);
};
const onMouseUp = () => {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
},
[panelWidth],
);
const active = tabs.find((t) => t.id === activeTabId) ?? tabs[0] ?? null;
if (!active) return null;
return (
<div
ref={panelRef}
className="flex h-full shrink-0 flex-col bg-white relative border-l border-gray-200 shadow-[-4px_0_12px_rgba(0,0,0,0.02)]"
style={{ width: panelWidth }}
>
{/* Drag handle */}
<div
onMouseDown={onMouseDown}
className="absolute left-0 top-0 h-full w-1 cursor-col-resize hover:bg-blue-400 transition-colors z-10"
style={{ marginLeft: -2 }}
/>
{/* Tab strip (Chrome-style) */}
<div className="flex items-end gap-1 pr-2 pt-2 bg-gray-100">
<div className="flex-1 flex items-end gap-1 overflow-x-auto pl-2 pr-2">
{tabs.map((tab) => {
const isActive = tab.id === active.id;
const showVersionBadge =
typeof tab.versionNumber === "number" &&
Number.isFinite(tab.versionNumber) &&
tab.versionNumber > 1;
return (
<div
key={tab.id}
onClick={() => onActivateTab(tab.id)}
className={`group relative flex items-center gap-1.5 pl-3 pr-1.5 h-8 min-w-0 max-w-[220px] rounded-t-lg cursor-pointer select-none transition-colors ${
isActive
? "bg-white text-gray-800 before:content-[''] before:absolute before:bottom-0 before:-left-2 before:w-2 before:h-2 before:bg-[radial-gradient(circle_at_top_left,transparent_8px,white_9px)] after:content-[''] after:absolute after:bottom-0 after:-right-2 after:w-2 after:h-2 after:bg-[radial-gradient(circle_at_top_right,transparent_8px,white_9px)]"
: "bg-gray-200/70 text-gray-600 hover:bg-gray-200"
}`}
>
<span
className={`min-w-0 flex-1 truncate text-xs ${isActive ? "font-medium" : "font-normal"}`}
title={tab.filename}
>
{tab.filename}
</span>
{showVersionBadge && (
<span
className={`shrink-0 inline-flex items-center rounded border px-1 py-px text-[9px] font-medium ${
isActive
? "border-gray-200 bg-white text-gray-600"
: "border-gray-300 bg-white/70 text-gray-500"
}`}
>
V{tab.versionNumber}
</span>
)}
<button
onClick={(e) => {
e.stopPropagation();
onCloseTab(tab.id);
}}
className="shrink-0 rounded-full p-0.5 text-gray-400 hover:bg-gray-300 hover:text-gray-700"
>
<X className="h-3 w-3" />
</button>
</div>
);
})}
</div>
<button
onClick={onCloseAll}
className="shrink-0 mb-1 ml-1 rounded-lg p-1.5 text-gray-400 hover:bg-gray-200 hover:text-gray-700"
title="Close panel"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Tab bodies all mounted, inactive ones hidden. Each tab
preserves its state (scroll, docx-preview render, etc.)
when inactive. */}
<div className="flex-1 min-h-0 relative">
{tabs.map((tab) => {
const isActive = tab.id === active.id;
const mode: DocPanelMode =
tab.kind === "citation"
? {
kind: "citation",
citation: tab.citation,
}
: tab.kind === "edit"
? {
kind: "edit",
edit: tab.edit,
isEditReloading:
isEditReloading?.(tab.edit.edit_id) ??
false,
onResolveStart: onEditResolveStart,
onResolved: onEditResolved,
onError: onEditError,
}
: { kind: "document" };
return (
<div
key={tab.id}
className={`absolute inset-0 flex flex-col ${isActive ? "" : "invisible pointer-events-none"}`}
aria-hidden={!isActive}
>
<DocPanel
documentId={tab.documentId}
filename={tab.filename}
versionId={tab.versionId}
versionNumber={tab.versionNumber}
mode={mode}
isReloading={
isEditorReloading?.(tab.documentId) ?? false
}
warning={tab.warning ?? null}
onWarningDismiss={() =>
onWarningDismiss?.(tab.id)
}
initialScrollTop={tab.initialScrollTop ?? null}
onScrollChange={(scrollTop) =>
onScrollChange?.(tab.id, scrollTop)
}
/>
</div>
);
})}
</div>
</div>
);
}

View file

@ -0,0 +1,293 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, Search, X } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { MikeWorkflow } from "../shared/types";
import { listWorkflows } from "@/app/lib/mikeApi";
import { BUILT_IN_WORKFLOWS } from "../workflows/builtinWorkflows";
interface Props {
open: boolean;
onClose: () => void;
onSelect: (workflow: MikeWorkflow) => void;
projectName?: string;
projectCmNumber?: string | null;
initialWorkflowId?: string;
}
export function AssistantWorkflowModal({
open,
onClose,
onSelect,
projectName,
projectCmNumber,
initialWorkflowId,
}: Props) {
const [workflows, setWorkflows] = useState<MikeWorkflow[]>([]);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState<MikeWorkflow | null>(null);
const [search, setSearch] = useState("");
const [rightVisible, setRightVisible] = useState(false);
useEffect(() => {
if (!selected) {
setRightVisible(false);
return;
}
const frame = requestAnimationFrame(() => setRightVisible(true));
return () => cancelAnimationFrame(frame);
}, [selected]);
useEffect(() => {
if (!open) {
setSelected(null);
setSearch("");
return;
}
const builtins = BUILT_IN_WORKFLOWS.filter(
(w) => w.type === "assistant",
);
setWorkflows(builtins);
setLoading(true);
listWorkflows("assistant")
.then((custom) => {
const all = [...builtins, ...custom];
setWorkflows(all);
if (initialWorkflowId) {
const match = all.find((w) => w.id === initialWorkflowId);
if (match) setSelected(match);
}
})
.catch(() => {
if (initialWorkflowId) {
const match = builtins.find((w) => w.id === initialWorkflowId);
if (match) setSelected(match);
}
})
.finally(() => setLoading(false));
// Pre-select from builtins immediately if possible
if (initialWorkflowId) {
const match = builtins.find((w) => w.id === initialWorkflowId);
if (match) setSelected(match);
}
}, [open, initialWorkflowId]);
if (!open) return null;
const filteredWorkflows = search
? workflows.filter((w) => w.title.toLowerCase().includes(search.toLowerCase()))
: workflows;
function handleUse() {
if (!selected) return;
onSelect(selected);
onClose();
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div
className={`w-full rounded-2xl bg-white shadow-2xl flex flex-col h-[600px] ${selected ? "max-w-4xl" : "max-w-2xl"}`}
>
{/* Header */}
<div className="flex items-center justify-between px-4 py-4 shrink-0 border-b border-gray-100">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{projectName ? (
<>
<span>Projects</span>
<span></span>
<span>
{projectName}
{projectCmNumber
? ` (#${projectCmNumber})`
: ""}
</span>
<span></span>
<span>Assistant</span>
<span></span>
<span>Add workflow</span>
</>
) : (
<>
<span>Assistant</span>
<span></span>
<span>Add workflow</span>
</>
)}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Content */}
<div className="flex flex-row flex-1 min-h-0 overflow-hidden">
{/* Left panel — workflow list */}
<div
className={`overflow-y-auto ${selected ? "w-80 shrink-0" : "flex-1"}`}
>
{/* Search */}
<div className="px-4 pt-3 pb-2 shrink-0">
<div className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-gray-50 px-2.5 py-1">
<Search className="h-3 w-3 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search workflows…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 outline-none"
/>
{search && (
<button onClick={() => setSearch("")} className="text-gray-400 hover:text-gray-600">
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
{loading ? (
<div className="space-y-px px-4 pt-1">
{[60, 45, 75, 50, 65, 40, 55].map((w, i) => (
<div
key={i}
className="flex items-center justify-between gap-3 py-3 border-b border-gray-50"
>
<div
className="h-3 rounded bg-gray-100 animate-pulse"
style={{ width: `${w}%` }}
/>
<div className="h-3 w-10 rounded bg-gray-100 animate-pulse shrink-0" />
</div>
))}
</div>
) : filteredWorkflows.length === 0 ? (
<p className="px-4 py-8 text-sm text-center text-gray-400">
{search ? "No matches found" : "No assistant workflows found"}
</p>
) : (
filteredWorkflows.map((wf) => (
<button
key={wf.id}
type="button"
onClick={() =>
setSelected((prev) =>
prev?.id === wf.id ? null : wf,
)
}
className={`w-full flex items-center gap-3 px-4 py-3 text-xs text-left transition-colors border-b border-gray-50 ${
selected?.id === wf.id
? "bg-gray-50"
: "hover:bg-gray-50"
}`}
>
<span className="flex-1 truncate text-gray-800">
{wf.title}
</span>
<span className="shrink-0 text-xs text-gray-400">
{wf.is_system ? "Built-in" : "Custom"}
</span>
</button>
))
)}
</div>
{/* Right panel — prompt preview */}
{selected && (
<div className={`flex-1 border-l border-gray-100 flex flex-col overflow-hidden px-3 pb-3 transition-opacity duration-200 ${rightVisible ? "opacity-100" : "opacity-0"}`}>
<div className="flex items-center justify-between py-3 shrink-0">
<p className="text-xs font-medium text-gray-700">
Workflow Prompt
</p>
<button
onClick={() => setSelected(null)}
className="rounded-lg p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<ChevronLeft className="h-3.5 w-3.5" />
</button>
</div>
<div className="flex-1 overflow-y-auto px-4 py-3 text-sm border border-gray-200 rounded-md text-gray-600 leading-relaxed font-serif bg-gray-50">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
h1: ({ children }) => (
<h1 className="text-base font-semibold text-gray-900 mt-4 mb-1 first:mt-0">
{children}
</h1>
),
h2: ({ children }) => (
<h2 className="text-sm font-semibold text-gray-900 mt-3 mb-1 first:mt-0">
{children}
</h2>
),
h3: ({ children }) => (
<h3 className="text-xs font-semibold text-gray-900 mt-2 mb-0.5 first:mt-0">
{children}
</h3>
),
p: ({ children }) => (
<p className="mb-2 last:mb-0">
{children}
</p>
),
ul: ({ children }) => (
<ul className="list-disc pl-4 mb-2 space-y-0.5">
{children}
</ul>
),
ol: ({ children }) => (
<ol className="list-decimal pl-4 mb-2 space-y-0.5">
{children}
</ol>
),
li: ({ children }) => (
<li>{children}</li>
),
strong: ({ children }) => (
<strong className="font-semibold text-gray-800">
{children}
</strong>
),
em: ({ children }) => (
<em className="italic">
{children}
</em>
),
}}
>
{selected.prompt_md ??
"_No prompt defined._"}
</ReactMarkdown>
</div>
</div>
)}
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-end gap-2 shrink-0">
<button
type="button"
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="button"
onClick={handleUse}
disabled={!selected}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
Use
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,326 @@
"use client";
import {
useState,
useCallback,
useRef,
forwardRef,
useImperativeHandle,
} from "react";
import {
ArrowRight,
Check,
File,
FileText,
FolderOpen,
Library,
Square,
X,
} from "lucide-react";
import { AddDocButton } from "./AddDocButton";
import { AddDocumentsModal } from "../shared/AddDocumentsModal";
import { AssistantWorkflowModal } from "./AssistantWorkflowModal";
import { ApiKeyMissingModal } from "../shared/ApiKeyMissingModal";
import { ModelToggle } from "./ModelToggle";
import { useSelectedModel } from "@/app/hooks/useSelectedModel";
import { useUserProfile } from "@/contexts/UserProfileContext";
import {
getModelProvider,
isModelAvailable,
type ModelProvider,
} from "@/app/lib/modelAvailability";
import type { MikeDocument, MikeMessage } from "../shared/types";
export interface ChatInputHandle {
addDoc: (doc: MikeDocument) => void;
}
interface Props {
onSubmit: (message: MikeMessage) => void;
onCancel: () => void;
isLoading: boolean;
hideAddDocButton?: boolean;
hideWorkflowButton?: boolean;
onProjectsClick?: () => void;
projectName?: string;
projectCmNumber?: string | null;
}
export const ChatInput = forwardRef<ChatInputHandle, Props>(function ChatInput(
{
onSubmit,
onCancel,
isLoading,
hideAddDocButton,
hideWorkflowButton,
onProjectsClick,
projectName,
projectCmNumber,
}: Props,
ref,
) {
const [value, setValue] = useState("");
const [attachedDocs, setAttachedDocs] = useState<MikeDocument[]>([]);
const [selectedWorkflow, setSelectedWorkflow] = useState<{
id: string;
title: string;
} | null>(null);
const [model, setModel] = useSelectedModel();
const { profile } = useUserProfile();
const apiKeys = {
claudeApiKey: profile?.claudeApiKey ?? null,
geminiApiKey: profile?.geminiApiKey ?? null,
};
const textareaRef = useRef<HTMLTextAreaElement>(null);
const [docSelectorOpen, setDocSelectorOpen] = useState(false);
const [workflowModalOpen, setWorkflowModalOpen] = useState(false);
const [apiKeyModalProvider, setApiKeyModalProvider] =
useState<ModelProvider | null>(null);
useImperativeHandle(ref, () => ({
addDoc: (doc: MikeDocument) => {
setAttachedDocs((prev) => {
if (prev.some((d) => d.id === doc.id)) return prev;
return [...prev, doc];
});
},
}));
const handleAddDocFromProject = useCallback((doc: MikeDocument) => {
setAttachedDocs((prev) => {
if (prev.some((d) => d.id === doc.id)) return prev;
return [...prev, doc];
});
}, []);
const handleAddDocsFromSelector = useCallback(
(selectedDocs: MikeDocument[]) => {
setAttachedDocs((prev) => {
const existing = new Set(prev.map((d) => d.id));
return [
...prev,
...selectedDocs.filter((d) => !existing.has(d.id)),
];
});
},
[],
);
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setValue(e.target.value);
const el = e.target;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
};
const handleSubmit = () => {
const query = value.trim();
if (!query || isLoading) return;
if (!isModelAvailable(model, apiKeys)) {
setApiKeyModalProvider(getModelProvider(model));
return;
}
setValue("");
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
}
const files = attachedDocs.map((d) => ({
filename: d.filename,
document_id: d.id,
}));
setAttachedDocs([]);
const wf = selectedWorkflow;
setSelectedWorkflow(null);
onSubmit?.({
role: "user",
content: query,
files: files.length > 0 ? files : undefined,
workflow: wf ?? undefined,
model,
});
};
const handleActionClick = () => {
if (isLoading) {
onCancel();
} else {
handleSubmit();
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit();
}
};
return (
<>
<div className="w-full">
<div className="border border-gray-300 rounded-[16px] md:rounded-[20px] bg-white">
{/* Attached chips */}
{(selectedWorkflow || attachedDocs.length > 0) && (
<div className="flex flex-wrap gap-1.5 px-2 pt-2">
{selectedWorkflow && (
<div className="inline-flex items-center gap-1 pl-2.5 pr-1 py-0.5 rounded-full text-xs bg-blue-600 text-white border border-white/20 shadow backdrop-blur-sm">
<Library className="h-2.5 w-2.5 shrink-0" />
<span className="max-w-[140px] truncate">
{selectedWorkflow.title}
</span>
<button
type="button"
onClick={() =>
setSelectedWorkflow(null)
}
className="rounded-full p-0.5 ml-0.5 text-white/60 hover:text-white hover:bg-white/20 transition-colors"
>
<X className="h-2.5 w-2.5" />
</button>
</div>
)}
{attachedDocs.map((doc) => {
const ft = doc.file_type?.toLowerCase();
const isPdf = ft === "pdf";
return (
<div
key={doc.id}
className="inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded-full text-xs text-white shadow border border-white/20 bg-black backdrop-blur-sm"
>
{isPdf ? (
<FileText className="h-2.5 w-2.5 shrink-0 text-red-400" />
) : (
<File className="h-2.5 w-2.5 shrink-0 text-blue-400" />
)}
<span className="max-w-[140px] truncate">
{doc.filename}
</span>
<button
type="button"
onClick={() =>
setAttachedDocs((prev) =>
prev.filter(
(d) => d.id !== doc.id,
),
)
}
className="rounded-full p-0.5 ml-0.5 text-white/60 hover:text-white hover:bg-white/20 transition-colors"
>
<X className="h-2.5 w-2.5" />
</button>
</div>
);
})}
</div>
)}
{/* Input */}
<div className="px-4 pt-4">
<textarea
ref={textareaRef}
rows={1}
placeholder="Ask a question about your documents..."
value={value}
onChange={handleChange}
onKeyDown={handleKeyDown}
className="w-full resize-none text-sm overflow-hidden border-0 text-base p-0 bg-transparent outline-none placeholder:text-gray-400 leading-6 max-h-48"
/>
</div>
{/* Controls */}
<div className="flex items-center justify-between md:p-2.5 p-2">
<div className="flex items-center gap-1">
{!hideAddDocButton && (
<AddDocButton
onSelectDoc={handleAddDocFromProject}
onBrowseAll={() => setDocSelectorOpen(true)}
selectedDocIds={attachedDocs.map(
(d) => d.id,
)}
/>
)}
{onProjectsClick && (
<button
type="button"
onClick={onProjectsClick}
aria-label="Open projects"
className="flex items-center gap-1.5 rounded-lg px-2 h-8 text-sm text-gray-400 hover:bg-gray-100 hover:text-gray-700 transition-colors"
>
<FolderOpen className="h-3.5 w-3.5" />
<span className="hidden sm:inline">
Projects
</span>
</button>
)}
{!hideWorkflowButton && (
<button
type="button"
onClick={() => setWorkflowModalOpen(true)}
aria-label="Open workflows"
className={`flex items-center gap-1.5 rounded-lg px-2 h-8 text-sm transition-colors ${selectedWorkflow ? "text-blue-600 hover:bg-blue-50" : "text-gray-400 hover:bg-gray-100 hover:text-gray-700"}`}
>
{selectedWorkflow ? (
<Check className="h-3.5 w-3.5" />
) : (
<Library className="h-3.5 w-3.5" />
)}
<span className="hidden sm:inline">
Workflows
</span>
</button>
)}
</div>
<div className="flex items-center gap-1">
<ModelToggle
value={model}
onChange={setModel}
apiKeys={apiKeys}
/>
<button
type="button"
className="relative bg-gradient-to-b from-neutral-700 to-black text-white rounded-[10px] h-8 w-8 flex items-center justify-center cursor-pointer disabled:cursor-default disabled:from-neutral-600 disabled:to-black backdrop-blur-xl border border-white/30 active:enabled:scale-95 transition-all duration-150"
onClick={handleActionClick}
disabled={!isLoading && !value.trim()}
>
{isLoading ? (
<Square
className="h-4 w-4"
fill="currentColor"
strokeWidth={0}
/>
) : (
<ArrowRight className="h-4 w-4" />
)}
</button>
</div>
</div>
</div>
</div>
<AddDocumentsModal
open={docSelectorOpen}
onClose={() => setDocSelectorOpen(false)}
onSelect={handleAddDocsFromSelector}
breadcrumb={["Assistant", "Add Documents"]}
/>
<AssistantWorkflowModal
open={workflowModalOpen}
onClose={() => setWorkflowModalOpen(false)}
onSelect={(wf) => {
setSelectedWorkflow({ id: wf.id, title: wf.title });
setWorkflowModalOpen(false);
}}
projectName={projectName}
projectCmNumber={projectCmNumber}
/>
<ApiKeyMissingModal
open={apiKeyModalProvider !== null}
provider={apiKeyModalProvider}
onClose={() => setApiKeyModalProvider(null)}
/>
</>
);
});

View file

@ -0,0 +1,627 @@
"use client";
import { useCallback, useState, useRef, useEffect } from "react";
import { ArrowDown } from "lucide-react";
import { UserMessage } from "./UserMessage";
import { AssistantMessage } from "./AssistantMessage";
import { ChatInput } from "./ChatInput";
import {
AssistantSidePanel,
type AssistantSidePanelTab,
} from "./AssistantSidePanel";
import { AssistantWorkflowModal } from "./AssistantWorkflowModal";
import type {
MikeCitationAnnotation,
MikeEditAnnotation,
MikeMessage,
} from "../shared/types";
import { useSidebar } from "@/app/contexts/SidebarContext";
import { invalidateDocxBytes } from "@/app/hooks/useFetchDocxBytes";
interface Props {
messages: MikeMessage[];
isResponseLoading: boolean;
handleChat: (message: MikeMessage) => Promise<string | null>;
cancel: () => void;
}
export function ChatView({
messages,
isResponseLoading,
handleChat,
cancel,
}: Props) {
const [tabs, setTabs] = useState<AssistantSidePanelTab[]>([]);
const [activeTabId, setActiveTabId] = useState<string | null>(null);
const [panelMounted, setPanelMounted] = useState(false);
const [panelVisible, setPanelVisible] = useState(false);
const [workflowModalOpen, setWorkflowModalOpen] = useState(false);
const [workflowModalInitialId, setWorkflowModalInitialId] = useState<
string | undefined
>();
const [reloadingDocIds, setReloadingDocIds] = useState<Set<string>>(
() => new Set(),
);
// Per-edit in-flight set — disables Accept/Reject on only the one
// edit currently being resolved, so sibling edits in the same message
// (and their twins in DocPanel) stay clickable.
const [reloadingEditIds, setReloadingEditIds] = useState<Set<string>>(
() => new Set(),
);
const { setSidebarOpen } = useSidebar();
const showPanel = useCallback(() => {
setPanelMounted(true);
setSidebarOpen(false);
requestAnimationFrame(() =>
requestAnimationFrame(() => setPanelVisible(true)),
);
}, [setSidebarOpen]);
const closeAllTabs = useCallback(() => {
setPanelVisible(false);
setTimeout(() => {
setTabs([]);
setActiveTabId(null);
setPanelMounted(false);
setSidebarOpen(true);
}, 300);
}, [setSidebarOpen]);
const closeTab = useCallback(
(id: string) => {
setTabs((prev) => {
const next = prev.filter((t) => t.id !== id);
if (next.length === 0) {
setPanelVisible(false);
setTimeout(() => {
setActiveTabId(null);
setPanelMounted(false);
setSidebarOpen(true);
}, 300);
return next;
}
if (activeTabId === id) {
const idx = prev.findIndex((t) => t.id === id);
const neighbour = next[idx] ?? next[idx - 1] ?? next[0];
setActiveTabId(neighbour?.id ?? null);
}
return next;
});
},
[activeTabId, setSidebarOpen],
);
/**
* One tab per document. If a tab for `tab.documentId` already exists,
* the panel stays mounted and only the header-relevant fields swap
* (kind, citation/edit, version, filename). Per-tab UI state the
* dismissable warning and the saved scroll position is preserved
* so switching headers doesn't blow away viewer state. If no tab
* exists for the document, a new one is appended.
*/
const upsertTab = useCallback(
(tab: AssistantSidePanelTab) => {
setTabs((prev) => {
const idx = prev.findIndex(
(t) => t.documentId === tab.documentId,
);
if (idx >= 0) {
const existing = prev[idx];
const copy = prev.slice();
copy[idx] = {
...tab,
id: existing.id,
warning: existing.warning,
initialScrollTop: existing.initialScrollTop,
};
return copy;
}
return [...prev, tab];
});
setActiveTabId(tab.id);
showPanel();
},
[showPanel],
);
/**
* Open a tab showing a single citation quote. Called from
* AssistantMessage when the user clicks a numbered citation pill.
*/
const openCitation = useCallback(
(citation: MikeCitationAnnotation) => {
upsertTab({
kind: "citation",
id: citation.document_id,
documentId: citation.document_id,
filename: citation.filename,
versionId: citation.version_id ?? null,
versionNumber: citation.version_number ?? null,
citation,
});
},
[upsertTab],
);
/**
* Open a tab showing a single tracked change. Called from
* AssistantMessage when the user clicks an EditCard's View button.
*/
const openEditor = useCallback(
(ann: MikeEditAnnotation, filename: string) => {
upsertTab({
kind: "edit",
id: ann.document_id,
documentId: ann.document_id,
filename,
versionId: ann.version_id ?? null,
versionNumber: ann.version_number ?? null,
edit: ann,
});
},
[upsertTab],
);
/**
* Open a tab showing a document without targeting a specific
* citation/edit used by the download-card click.
*/
const openDocument = useCallback(
(args: {
documentId: string;
filename: string;
versionId: string | null;
versionNumber: number | null;
}) => {
upsertTab({
kind: "document",
id: args.documentId,
documentId: args.documentId,
filename: args.filename,
versionId: args.versionId,
versionNumber: args.versionNumber,
});
},
[upsertTab],
);
const [resolvedEditStatuses, setResolvedEditStatuses] = useState<
Record<string, "accepted" | "rejected">
>({});
const handleEditResolveStart = useCallback(
(args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => {
setReloadingDocIds((prev) => {
if (prev.has(args.documentId)) return prev;
const next = new Set(prev);
next.add(args.documentId);
return next;
});
setReloadingEditIds((prev) => {
if (prev.has(args.editId)) return prev;
const next = new Set(prev);
next.add(args.editId);
return next;
});
},
[],
);
const handleEditResolved = useCallback(
(args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => {
setResolvedEditStatuses((prev) => ({
...prev,
[args.editId]: args.status,
}));
setReloadingDocIds((prev) => {
if (!prev.has(args.documentId)) return prev;
const next = new Set(prev);
next.delete(args.documentId);
return next;
});
setReloadingEditIds((prev) => {
if (!prev.has(args.editId)) return prev;
const next = new Set(prev);
next.delete(args.editId);
return next;
});
// Propagate the new status onto any open edit-tab for this
// edit so DocPanel's Accept/Reject buttons flip and disable
// (their sync effect keys off edit.status). Without this, a
// resolve triggered from the inline EditCard or BulkEditActions
// leaves the panel buttons looking live.
setTabs((prev) =>
prev.map((t) =>
t.kind === "edit" && t.edit.edit_id === args.editId
? {
...t,
edit: { ...t.edit, status: args.status },
}
: t,
),
);
// Accept/reject mutates bytes for this document's current
// version; drop the cache so the next DocxView render (or an
// explicit re-open) fetches the fresh file.
invalidateDocxBytes(args.documentId);
},
[],
);
const patchTab = useCallback(
(
tabId: string,
patch: Partial<Pick<AssistantSidePanelTab, "warning" | "initialScrollTop">>,
) => {
setTabs((prev) => {
const idx = prev.findIndex((t) => t.id === tabId);
if (idx < 0) return prev;
const copy = prev.slice();
copy[idx] = { ...copy[idx], ...patch };
return copy;
});
},
[],
);
const handleEditError = useCallback(
(args: {
editId?: string;
documentId: string;
versionId?: string | null;
message: string;
}) => {
// Surface the warning on every tab tied to this document.
setTabs((prev) =>
prev.map((t) =>
t.documentId === args.documentId
? { ...t, warning: args.message }
: t,
),
);
setReloadingDocIds((prev) => {
if (!prev.has(args.documentId)) return prev;
const next = new Set(prev);
next.delete(args.documentId);
return next;
});
if (args.editId) {
setReloadingEditIds((prev) => {
if (!prev.has(args.editId!)) return prev;
const next = new Set(prev);
next.delete(args.editId!);
return next;
});
}
},
[],
);
const handleWarningDismiss = useCallback(
(tabId: string) => {
patchTab(tabId, { warning: null });
},
[patchTab],
);
const handleScrollChange = useCallback(
(tabId: string, scrollTop: number) => {
patchTab(tabId, { initialScrollTop: scrollTop });
},
[patchTab],
);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const latestUserMessageRef = useRef<HTMLDivElement>(null);
const chatInputRef = useRef<HTMLDivElement>(null);
const hasScrolledRef = useRef(false);
const [messagesVisible, setMessagesVisible] = useState(false);
const [showScrollButton, setShowScrollButton] = useState(false);
const [inputHeight, setInputHeight] = useState(0);
const [minHeight, setMinHeight] = useState("0px");
useEffect(() => {
const el = chatInputRef.current;
if (!el) return;
const observer = new ResizeObserver(() =>
setInputHeight(el.offsetHeight),
);
observer.observe(el);
setInputHeight(el.offsetHeight);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (latestUserMessageRef.current) {
const headerHeight = window.innerWidth < 768 ? 56 : 0;
const gap = window.innerWidth < 768 ? 16 : 24;
const paddingBottom = 128;
const marginBottom = 48;
const userMessageHeight = latestUserMessageRef.current.offsetHeight;
setMinHeight(
`calc(100dvh - ${headerHeight + gap + userMessageHeight + paddingBottom + marginBottom}px)`,
);
}
}, [messages.length, latestUserMessageRef.current]); // eslint-disable-line react-hooks/exhaustive-deps
const updateScrollButton = useCallback(() => {
const c = messagesContainerRef.current;
if (!c) return;
const isScrolledUp = c.scrollHeight - c.scrollTop - c.clientHeight > 10;
setShowScrollButton(isScrolledUp && c.scrollHeight > c.clientHeight);
}, []);
useEffect(() => {
const c = messagesContainerRef.current;
if (!c) return;
c.addEventListener("scroll", updateScrollButton);
updateScrollButton();
return () => c.removeEventListener("scroll", updateScrollButton);
}, [messages, updateScrollButton]);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
const scrollLatestUserToTop = useCallback(() => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const container = messagesContainerRef.current;
const element = latestUserMessageRef.current;
if (!container || !element) return;
container.scrollTo({
top: element.offsetTop - 24,
behavior: "smooth",
});
});
});
}, []);
useEffect(() => {
const last = messages[messages.length - 1];
if (last?.role === "user") scrollLatestUserToTop();
}, [messages, scrollLatestUserToTop]);
useEffect(() => {
if (isResponseLoading) scrollLatestUserToTop();
}, [isResponseLoading, scrollLatestUserToTop]);
useEffect(() => {
if (messages.length === 0) {
hasScrolledRef.current = false;
setMessagesVisible(false);
} else if (!hasScrolledRef.current) {
const userMsgCount = messages.filter(
(m) => m.role === "user",
).length;
if (
userMsgCount >= 2 &&
latestUserMessageRef.current &&
messagesContainerRef.current
) {
setTimeout(() => {
const container = messagesContainerRef.current;
const element = latestUserMessageRef.current;
if (container && element) {
container.scrollTo({
top: element.offsetTop - 24,
behavior: "instant",
});
}
hasScrolledRef.current = true;
setMessagesVisible(true);
}, 100);
} else {
hasScrolledRef.current = true;
setMessagesVisible(true);
}
}
}, [messages]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (panelMounted && window.innerWidth < 768) {
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "unset";
}
return () => {
document.body.style.overflow = "unset";
};
}, [panelMounted]);
return (
<div className="h-full w-full flex relative">
{/* Chat column */}
<div className="flex flex-col h-full flex-1 relative">
{/* Scrollable messages */}
<div
ref={messagesContainerRef}
className="flex-1 w-full overflow-y-auto"
style={{ scrollbarGutter: "stable both-edges" }}
>
<div className="w-full max-w-4xl mx-auto pb-32 px-6 md:px-8 pt-4 md:pt-6 min-h-full flex flex-col relative">
{!messagesVisible && (
<div className="space-y-6 w-full">
<div className="flex justify-end">
<div className="bg-gray-100 rounded-2xl p-4 w-2/5">
<div className="h-4 bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 bg-[length:200%_100%] animate-[shimmer_2s_ease-in-out_infinite] rounded w-full" />
</div>
</div>
<div className="space-y-3">
{[1, 2, 3, 4].map((i) => (
<div
key={i}
className={`h-4 bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 bg-[length:200%_100%] animate-[shimmer_2s_ease-in-out_infinite] rounded ${i === 3 ? "w-5/6" : i === 4 ? "w-4/6" : "w-full"}`}
/>
))}
</div>
</div>
)}
<div
className="space-y-6 transition-opacity duration-150"
style={{ opacity: messagesVisible ? 1 : 0 }}
>
{(() => {
const lastUserIndex = messages
.map((m) => m.role)
.lastIndexOf("user");
const lastAssistantIndex = messages
.map((m) => m.role)
.lastIndexOf("assistant");
return messages.map((msg, i) => (
<div
key={i}
ref={
i === lastUserIndex
? latestUserMessageRef
: null
}
>
{msg.role === "user" ? (
<UserMessage
content={msg.content ?? ""}
files={(msg as any).files}
workflow={(msg as any).workflow}
/>
) : (
<AssistantMessage
content={msg.content ?? ""}
events={msg.events}
isStreaming={
i === messages.length - 1 &&
isResponseLoading
}
isError={!!(msg as any).error}
errorMessage={
typeof (msg as any).error ===
"string"
? (msg as any).error
: undefined
}
annotations={msg.annotations}
onCitationClick={openCitation}
minHeight={
i === lastAssistantIndex
? minHeight
: "0px"
}
onWorkflowClick={(id) => {
setWorkflowModalInitialId(
id,
);
setWorkflowModalOpen(true);
}}
onEditViewClick={openEditor}
onOpenDocument={openDocument}
onEditResolveStart={
handleEditResolveStart
}
onEditResolved={
handleEditResolved
}
onEditError={handleEditError}
isDocReloading={(docId) =>
reloadingDocIds.has(docId)
}
isEditReloading={(editId) =>
reloadingEditIds.has(editId)
}
resolvedEditStatuses={
resolvedEditStatuses
}
/>
)}
</div>
));
})()}
<div ref={messagesEndRef} />
</div>
</div>
</div>
{/* Scroll to bottom button */}
{showScrollButton && (
<div
className="absolute left-1/2 -translate-x-1/2 z-19"
style={{ bottom: inputHeight + 12 }}
>
<button
onClick={scrollToBottom}
className="p-2 rounded-full bg-white/70 backdrop-blur-xs shadow-lg cursor-pointer border border-gray-300"
>
<ArrowDown className="h-6 w-6 text-gray-500" />
</button>
</div>
)}
{/* Chat input */}
<div
ref={chatInputRef}
className="absolute bottom-0 left-0 right-0 w-full z-30"
>
<div className="w-full max-w-4xl mx-auto px-4 md:px-6">
<div className="w-full rounded-t-[20px] bg-white">
<ChatInput
onSubmit={handleChat}
onCancel={cancel}
isLoading={isResponseLoading}
/>
<div className="py-3 text-center">
<p className="text-xs text-gray-500">
AI can make mistakes. Answers are not legal
advice.
</p>
</div>
</div>
</div>
</div>
</div>
<AssistantWorkflowModal
open={workflowModalOpen}
onClose={() => setWorkflowModalOpen(false)}
onSelect={() => setWorkflowModalOpen(false)}
initialWorkflowId={workflowModalInitialId}
/>
{panelMounted && (
<div
className={`fixed md:relative inset-0 md:inset-auto md:h-full md:flex-shrink-0 z-40 md:z-auto transition-transform duration-300 ease-in-out ${panelVisible ? "translate-x-0" : "translate-x-full"}`}
>
<AssistantSidePanel
tabs={tabs}
activeTabId={activeTabId}
onActivateTab={setActiveTabId}
onCloseTab={closeTab}
onCloseAll={closeAllTabs}
isEditorReloading={(documentId) =>
reloadingDocIds.has(documentId)
}
isEditReloading={(editId) =>
reloadingEditIds.has(editId)
}
onEditResolveStart={handleEditResolveStart}
onEditResolved={handleEditResolved}
onEditError={handleEditError}
onWarningDismiss={handleWarningDismiss}
onScrollChange={handleScrollChange}
/>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,348 @@
"use client";
import { useState } from "react";
import { supabase } from "@/lib/supabase";
import type { MikeEditAnnotation } from "../shared/types";
function normalizeText(s: string) {
return s.replace(/\s+/g, " ").trim();
}
function findMatch(
container: Element,
tag: "ins" | "del",
opts: { w_id?: string | null; text?: string },
): HTMLElement | null {
if (opts.w_id) {
// Values are numeric strings from our own backend — CSS.escape
// makes them hex-encoded which works but is harder to debug.
const byId = container.querySelector(
`${tag}[data-w-id="${opts.w_id}"]`,
) as HTMLElement | null;
console.log("[EditCard] findMatch by w_id", {
tag,
w_id: opts.w_id,
found: !!byId,
totalTagged: container.querySelectorAll(`${tag}[data-w-id]`).length,
totalAny: container.querySelectorAll(tag).length,
});
if (byId) return byId;
}
const text = opts.text ?? "";
const target = normalizeText(text);
if (!target) return null;
const candidates = Array.from(
container.querySelectorAll(tag),
) as HTMLElement[];
const byText =
candidates.find(
(el) => normalizeText(el.textContent ?? "") === target,
) ??
candidates.find((el) =>
normalizeText(el.textContent ?? "").includes(target),
) ??
null;
console.log("[EditCard] findMatch by text", {
tag,
target,
found: !!byText,
candidateCount: candidates.length,
});
return byText;
}
/**
* Ephemeral DOM mutation so the tracked change visually resolves the
* instant the user clicks Accept/Reject, instead of waiting for the
* backend round-trip + re-render. The real re-render from the new
* version supersedes this shortly after.
*/
/**
* Apply the optimistic DOM mutation for an accept/reject click. Returns
* a revert function that undoes every style + class the mutation added,
* so if the backend call later fails we can restore the original look.
*/
export function applyOptimisticResolution(
annotation: MikeEditAnnotation,
verb: "accept" | "reject",
): () => void {
const reverts: (() => void)[] = [];
if (typeof document === "undefined") return () => {};
const hide = (el: HTMLElement) => {
el.classList.add("docx-edit-hidden");
const prev = el.style.getPropertyValue("display");
const prevPriority = el.style.getPropertyPriority("display");
el.style.setProperty("display", "none", "important");
reverts.push(() => {
el.classList.remove("docx-edit-hidden");
if (prev) el.style.setProperty("display", prev, prevPriority);
else el.style.removeProperty("display");
});
};
const keep = (el: HTMLElement) => {
el.classList.add("docx-edit-kept");
const snapshot = {
color: [
el.style.getPropertyValue("color"),
el.style.getPropertyPriority("color"),
] as const,
bg: [
el.style.getPropertyValue("background-color"),
el.style.getPropertyPriority("background-color"),
] as const,
td: [
el.style.getPropertyValue("text-decoration"),
el.style.getPropertyPriority("text-decoration"),
] as const,
};
el.style.setProperty("color", "inherit", "important");
el.style.setProperty("background-color", "transparent", "important");
el.style.setProperty("text-decoration", "none", "important");
reverts.push(() => {
el.classList.remove("docx-edit-kept");
const restore = (
prop: "color" | "background-color" | "text-decoration",
[v, p]: readonly [string, string],
) => {
if (v) el.style.setProperty(prop, v, p);
else el.style.removeProperty(prop);
};
restore("color", snapshot.color);
restore("background-color", snapshot.bg);
restore("text-decoration", snapshot.td);
});
};
const scrolls = document.querySelectorAll(
`[data-document-id="${CSS.escape(annotation.document_id)}"]`,
);
console.log("[EditCard] optimistic scrolls found:", scrolls.length, {
document_id: annotation.document_id,
ins_w_id: annotation.ins_w_id,
del_w_id: annotation.del_w_id,
inserted_text: annotation.inserted_text?.slice(0, 40),
deleted_text: annotation.deleted_text?.slice(0, 40),
});
scrolls.forEach((scroll) => {
const container = scroll.querySelector(".docx-view-container");
if (!container) return;
const insEl = findMatch(container, "ins", {
w_id: annotation.ins_w_id,
text: annotation.inserted_text,
});
const delEl = findMatch(container, "del", {
w_id: annotation.del_w_id,
text: annotation.deleted_text,
});
if (verb === "accept") {
if (insEl) keep(insEl);
if (delEl) hide(delEl);
} else {
if (insEl) hide(insEl);
if (delEl) keep(delEl);
}
});
return () => reverts.forEach((fn) => fn());
}
interface Props {
annotation: MikeEditAnnotation;
/**
* External override for this edit's status. When set, takes
* precedence over the annotation's DB status and the card's own
* internal state used so bulk-resolved edits flip their per-card
* UI the moment the bulk handler calls onResolved.
*/
resolvedStatus?: "accepted" | "rejected";
/**
* True while an accept/reject request for any edit on this document
* is in flight (from here, DocPanel, or the bulk bar). When true the
* Accept/Reject buttons disable so the user can't race resolutions.
*/
isReloading?: boolean;
onViewClick?: (ann: MikeEditAnnotation) => void;
/**
* Fires immediately when the user clicks Accept or Reject, before the
* backend round-trip. Parents use this to show an in-progress spinner
* on download cards / editor panels tied to the same document while
* the version is being mutated.
*/
onResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
/**
* Fires when the backend accept/reject call fails. The optimistic
* DOM mutation has already been reverted. Parent should surface a
* warning (e.g. on the DocxView for this document + version) and
* clear the per-edit in-flight state keyed on `editId`.
*/
onError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
}
/**
* Renders a single tracked-change proposal as a card in the assistant
* message with Accept / Reject / View controls.
*/
export function EditCard({
annotation,
resolvedStatus,
isReloading,
onViewClick,
onResolveStart,
onResolved,
onError,
}: Props) {
const [busy, setBusy] = useState(false);
const [localStatus, setLocalStatus] = useState<
"pending" | "accepted" | "rejected"
>(annotation.status);
// External override (from a bulk resolve) takes precedence over the
// card's own click-driven state.
const status = resolvedStatus ?? localStatus;
const setStatus = setLocalStatus;
const resolved = status !== "pending";
// True while an accept/reject request for any edit on this card's
// document is in flight — triggered here, in DocPanel, or in the
// bulk bar. Disables the buttons so the user can't race resolutions.
const inFlight = busy || !!isReloading;
const handle = async (verb: "accept" | "reject") => {
if (busy || resolved) return;
setBusy(true);
onResolveStart?.({
editId: annotation.edit_id,
documentId: annotation.document_id,
verb,
});
let revert: (() => void) | null = null;
try {
revert = applyOptimisticResolution(annotation, verb);
} catch (e) {
console.error("[EditCard] optimistic update threw", e);
}
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const resp = await fetch(
`${apiBase}/single-documents/${annotation.document_id}/edits/${annotation.edit_id}/${verb}`,
{
method: "POST",
headers: token
? { Authorization: `Bearer ${token}` }
: undefined,
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = (await resp.json()) as {
ok: boolean;
already_resolved?: boolean;
status?: "accepted" | "rejected";
version_id: string | null;
download_url: string | null;
};
const nextStatus =
data.status ?? (verb === "accept" ? "accepted" : "rejected");
setStatus(nextStatus);
onResolved?.({
editId: annotation.edit_id,
documentId: annotation.document_id,
status: nextStatus,
versionId: data.version_id,
downloadUrl: data.download_url,
});
} catch (e) {
console.error("EditCard resolve failed", e);
try {
revert?.();
} catch (revertErr) {
console.error("[EditCard] revert threw", revertErr);
}
onError?.({
editId: annotation.edit_id,
documentId: annotation.document_id,
versionId: annotation.version_id ?? null,
message:
verb === "accept"
? "Couldn't save accept — reverted."
: "Couldn't save reject — reverted.",
});
} finally {
setBusy(false);
}
};
return (
<div className="border border-gray-200 rounded-lg p-3 bg-gray-50">
{annotation.reason && (
<p className="text-xs text-gray-500 mb-2">
{annotation.reason}
</p>
)}
<div className="text-sm leading-relaxed font-serif bg-white border border-gray-200 rounded-md px-2 py-2">
{annotation.inserted_text && (
<span className="text-green-700">
{annotation.inserted_text}
</span>
)}
{annotation.deleted_text && (
<span className="text-red-600 line-through">
{annotation.deleted_text}
</span>
)}
</div>
<div className="flex gap-2 mt-3">
<button
onClick={() => handle("accept")}
disabled={inFlight || resolved}
className="px-2 py-1 text-xs rounded border border-gray-900 bg-gray-900 text-white hover:bg-gray-800 disabled:opacity-50"
>
{status === "accepted" ? "Accepted" : "Accept"}
</button>
<button
onClick={() => handle("reject")}
disabled={inFlight || resolved}
className="px-2 py-1 text-xs rounded border border-gray-200 bg-white text-gray-700 hover:bg-gray-100 disabled:opacity-50"
>
{status === "rejected" ? "Rejected" : "Reject"}
</button>
{onViewClick && (
<button
onClick={() => onViewClick(annotation)}
disabled={resolved}
title={
resolved
? "This change has been resolved and is no longer in the document."
: undefined
}
className="ml-auto px-2 py-1 text-xs rounded border border-gray-200 bg-white text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-white"
>
View
</button>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,99 @@
"use client";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { MikeIcon } from "@/components/chat/mike-icon";
import { ChatInput } from "./ChatInput";
import { SelectAssistantProjectModal } from "./SelectAssistantProjectModal";
import type { MikeMessage } from "../shared/types";
interface InitialViewProps {
onSubmit: (message: MikeMessage) => void;
}
const ICON_SIZE = 35;
const GAP = 16; // gap-4 = 1rem = 16px
export function InitialView({ onSubmit }: InitialViewProps) {
const { user } = useAuth();
const { profile } = useUserProfile();
const [loaded, setLoaded] = useState(false);
const [projectModalOpen, setProjectModalOpen] = useState(false);
const [iconOffset, setIconOffset] = useState(0);
const [textOffset, setTextOffset] = useState(0);
const textRef = useRef<HTMLHeadingElement>(null);
const username =
profile?.displayName?.trim() || user?.email?.split("@")[0] || "there";
useLayoutEffect(() => {
if (!profile || !textRef.current) return;
const h1Width = textRef.current.offsetWidth;
setIconOffset((h1Width + GAP) / 2);
setTextOffset((ICON_SIZE + GAP) / 2);
}, [profile]);
useEffect(() => {
if (!iconOffset) return;
const t = setTimeout(() => setLoaded(true), 100);
return () => clearTimeout(t);
}, [iconOffset]);
return (
<div className="flex flex-col h-full w-full px-6">
<div className="flex-1 flex flex-col items-center justify-center">
<div className="flex-col items-center w-full max-w-4xl relative px-0 xl:px-8">
<div className="mb-10 relative flex items-center justify-center">
<div
className="absolute h-[35px]"
style={{
left: "50%",
transform: loaded
? `translateX(calc(-50% - ${iconOffset}px))`
: "translateX(-50%)",
transition:
"transform 900ms cubic-bezier(0.25, 0.46, 0.45, 0.94)",
}}
>
<MikeIcon size={ICON_SIZE} />
</div>
<h1
ref={textRef}
className="absolute text-4xl font-serif font-light text-gray-900 whitespace-nowrap"
style={{
left: "50%",
transform: loaded
? `translateX(calc(-50% + ${textOffset}px))`
: "translateX(-50%)",
opacity: loaded ? 1 : 0,
transition:
"transform 900ms cubic-bezier(0.25, 0.46, 0.45, 0.94), opacity 800ms ease-in-out 300ms",
}}
>
Hi, {username}
</h1>
</div>
<ChatInput
onSubmit={onSubmit}
onCancel={() => {}}
isLoading={false}
onProjectsClick={() => setProjectModalOpen(true)}
/>
<div className="text-center">
<p className="text-xs py-3 mb-3 text-gray-500">
AI can make mistakes. Answers are not legal advice.
</p>
</div>
</div>
</div>
<SelectAssistantProjectModal
open={projectModalOpen}
onClose={() => setProjectModalOpen(false)}
/>
</div>
);
}

View file

@ -0,0 +1,115 @@
"use client";
import { useState } from "react";
import { ChevronDown, Check, AlertCircle } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { isModelAvailable } from "@/app/lib/modelAvailability";
export interface ModelOption {
id: string;
label: string;
group: "Anthropic" | "Google";
}
export const MODELS: ModelOption[] = [
{ id: "claude-opus-4-7", label: "Claude Opus 4.7", group: "Anthropic" },
{ id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6", group: "Anthropic" },
{ id: "gemini-3.1-pro-preview", label: "Gemini 3.1 Pro", group: "Google" },
{ id: "gemini-3-flash-preview", label: "Gemini 3 Flash", group: "Google" },
];
export const DEFAULT_MODEL_ID = "gemini-3-flash-preview";
export const ALLOWED_MODEL_IDS = new Set(MODELS.map((m) => m.id));
const GROUP_ORDER: ModelOption["group"][] = ["Anthropic", "Google"];
interface Props {
value: string;
onChange: (id: string) => void;
apiKeys?: {
claudeApiKey: string | null;
geminiApiKey: string | null;
};
}
export function ModelToggle({ value, onChange, apiKeys }: Props) {
const [isOpen, setIsOpen] = useState(false);
const selected = MODELS.find((m) => m.id === value);
const selectedLabel = selected?.label ?? "Model";
const selectedAvailable = apiKeys
? isModelAvailable(value, apiKeys)
: true;
return (
<DropdownMenu onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
<button
type="button"
className={`flex items-center gap-1.5 rounded-lg px-2 h-8 text-sm transition-colors cursor-pointer text-gray-400 hover:bg-gray-100 hover:text-gray-700 ${isOpen ? "bg-gray-100 text-gray-700" : ""}`}
title={
!selectedAvailable
? "API key missing for selected model"
: "Choose model"
}
>
{!selectedAvailable && (
<AlertCircle className="h-3 w-3 shrink-0 text-red-500" />
)}
<span className="max-w-[140px] truncate">{selectedLabel}</span>
<ChevronDown
className={`h-3 w-3 shrink-0 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56 z-50" side="top" align="start">
{GROUP_ORDER.map((group, gi) => {
const items = MODELS.filter((m) => m.group === group);
if (items.length === 0) return null;
return (
<div key={group}>
{gi > 0 && <DropdownMenuSeparator />}
<DropdownMenuLabel className="text-[10px] uppercase tracking-wider text-gray-400">
{group}
</DropdownMenuLabel>
{items.map((m) => {
const available = apiKeys
? isModelAvailable(m.id, apiKeys)
: true;
return (
<DropdownMenuItem
key={m.id}
className="cursor-pointer"
onSelect={() => onChange(m.id)}
>
<span
className={`flex-1 ${available ? "" : "text-gray-400"}`}
>
{m.label}
</span>
{!available && (
<AlertCircle
className="h-3.5 w-3.5 text-red-500 ml-1"
aria-label="API key missing"
/>
)}
{m.id === value && available && (
<Check className="h-3.5 w-3.5 text-gray-600 ml-1" />
)}
</DropdownMenuItem>
);
})}
</div>
);
})}
</DropdownMenuContent>
</DropdownMenu>
);
}

View file

@ -0,0 +1,92 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { useDirectoryData } from "../shared/useDirectoryData";
import { ProjectPicker } from "../shared/ProjectPicker";
interface Props {
open: boolean;
onClose: () => void;
}
export function SelectAssistantProjectModal({ open, onClose }: Props) {
const [selectedId, setSelectedId] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
const router = useRouter();
const { saveChat } = useChatHistoryContext();
const { loading, projects } = useDirectoryData(open);
useEffect(() => {
if (!open) return;
setSelectedId(null);
}, [open]);
if (!open) return null;
async function handleContinue() {
if (!selectedId) return;
setCreating(true);
try {
const chatId = await saveChat(selectedId);
if (!chatId) return;
onClose();
router.push(`/projects/${selectedId}/assistant/chat/${chatId}`);
} finally {
setCreating(false);
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Assistant</span>
<span></span>
<span>Start Chat in a Project</span>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
<ProjectPicker
projects={projects}
loading={loading}
selectedId={selectedId}
onSelect={setSelectedId}
/>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-end gap-2">
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleContinue}
disabled={!selectedId || creating}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
{creating ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
"Continue"
)}
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,47 @@
"use client";
import { File, FileText, Library } from "lucide-react";
interface Props {
content: string;
files?: { filename: string; document_id?: string }[];
workflow?: { id: string; title: string };
}
export function UserMessage({ content, files, workflow }: Props) {
const hasFiles = files && files.length > 0;
return (
<div className="w-full flex justify-end">
<div className="max-w-[80%] bg-gray-100 rounded-xl px-4 py-3">
<p className="text-sm text-gray-900 whitespace-pre-wrap">{content}</p>
{(workflow || hasFiles) && (
<div className="flex flex-wrap justify-end gap-1.5 mt-3">
{workflow && (
<div className="inline-flex items-center gap-1 pl-2 pr-2.5 py-0.5 rounded-full text-xs bg-blue-600 text-white shadow border border-blue-600">
<Library className="h-2.5 w-2.5 shrink-0" />
<span className="max-w-[140px] truncate">{workflow.title}</span>
</div>
)}
{hasFiles && files.map((f, i) => {
const ext = f.filename.split(".").pop()?.toLowerCase();
const isPdf = ext === "pdf";
return (
<div
key={i}
className="inline-flex items-center gap-1 pl-2 pr-2.5 py-0.5 rounded-full text-xs text-white shadow border border-black bg-black"
>
{isPdf
? <FileText className="h-2.5 w-2.5 shrink-0 text-red-400" />
: <File className="h-2.5 w-2.5 shrink-0 text-blue-400" />
}
<span className="max-w-[140px] truncate">{f.filename}</span>
</div>
);
})}
</div>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,81 @@
import { X } from "lucide-react";
import { createPortal } from "react-dom";
interface CreditsExhaustedModalProps {
isOpen: boolean;
onClose: () => void;
resetDate: string;
}
export function CreditsExhaustedModal({
isOpen,
onClose,
resetDate,
}: CreditsExhaustedModalProps) {
if (!isOpen) return null;
// Format the reset date
const formatResetDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
});
};
return createPortal(
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 z-[200]"
onClick={onClose}
/>
{/* Modal */}
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[201] w-full max-w-md px-4">
<div className="relative bg-white rounded-2xl shadow-2xl p-6">
{/* Header */}
<div className="flex items-start justify-between mb-4">
<h2 className="text-3xl font-light font-eb-garamond text-gray-900">
Message Limit Reached
</h2>
</div>
{/* Content */}
<div className="space-y-4">
<p className="text-gray-600">
You've reached your monthly message limit of 100
messages.
</p>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<p className="text-sm text-blue-900 font-medium mb-1">
Your credits will reset on:
</p>
<p className="text-lg font-semibold text-blue-700">
{formatResetDate(resetDate)}
</p>
</div>
<p className="text-sm text-gray-500">
Your message credits automatically reset on the
first day of each month.
</p>
</div>
{/* Actions */}
<div className="mt-6 flex gap-3">
<button
onClick={onClose}
className="flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors"
>
Close
</button>
</div>
</div>
</div>
</>,
document.body,
);
}

View file

@ -0,0 +1,97 @@
"use client";
import { Button } from "@/components/ui/button";
import { X, Check } from "lucide-react";
interface DeleteChatsModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
chatCount: number;
isDeleting: boolean;
isSuccess?: boolean;
}
export function DeleteChatsModal({
isOpen,
onClose,
onConfirm,
chatCount,
isDeleting,
isSuccess = false,
}: DeleteChatsModalProps) {
if (!isOpen) return null;
return (
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 z-199"
onClick={isDeleting || isSuccess ? undefined : onClose}
/>
{/* Modal */}
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-200 w-full max-w-md">
<div className="bg-white rounded-2xl shadow-2xl p-8">
{isSuccess ? (
<>
{/* Success State */}
<div className="text-center">
<div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
<Check className="h-8 w-8 text-green-600" />
</div>
<h2 className="text-3xl font-light font-eb-garamond text-gray-900 mb-2">
All Chats Deleted
</h2>
<p className="text-gray-600 text-sm">
Your chat history has been successfully
deleted.
</p>
</div>
</>
) : (
<>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-4xl font-light font-eb-garamond text-red-700">
Delete All Chats
</h2>
</div>
{/* Content */}
<div className="space-y-4">
<p className="text-gray-600 text-sm leading-relaxed">
Are you sure you want to delete all{" "}
{chatCount} chat
{chatCount !== 1 ? "s" : ""}? This action is
permanent and cannot be undone.
</p>
<div className="space-y-3 pt-4">
<Button
onClick={onConfirm}
disabled={isDeleting}
variant="destructive"
className="w-full bg-red-600 hover:bg-red-700 text-white"
>
{isDeleting
? "Deleting..."
: "Delete All Chats"}
</Button>
<Button
onClick={onClose}
variant="outline"
disabled={isDeleting}
className="w-full border-gray-300 text-gray-700 hover:bg-gray-50"
>
Cancel
</Button>
</div>
</div>
</>
)}
</div>
</div>
</>
);
}

View file

@ -0,0 +1,90 @@
import { X, Link2, Check } from "lucide-react";
import { useState } from "react";
import { createPortal } from "react-dom";
interface SimpleLinkDialogProps {
isOpen: boolean;
onClose: () => void;
shareUrl: string | null;
}
export function SimpleLinkDialog({
isOpen,
onClose,
shareUrl,
}: SimpleLinkDialogProps) {
const [linkCopied, setLinkCopied] = useState(false);
if (!isOpen) return null;
const handleCopyLink = async () => {
if (!shareUrl) return;
try {
await navigator.clipboard.writeText(shareUrl);
setLinkCopied(true);
setTimeout(() => setLinkCopied(false), 2000);
} catch (err) {}
};
return createPortal(
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 z-[199]"
onClick={onClose}
/>
{/* Dialog */}
<div className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[200] w-full max-w-md px-4">
<div className="relative bg-white rounded-2xl shadow-2xl p-6">
{/* Close Button */}
<button
onClick={onClose}
className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 transition-colors"
>
<X className="h-5 w-5" />
</button>
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-3xl font-light font-eb-garamond text-gray-900">
Share Chat
</h2>
</div>
{/* Content */}
<div className="space-y-4">
{/* Link display */}
<div className="bg-gray-50 rounded-lg p-3 border border-gray-200">
<p className="text-sm text-gray-600 mb-2 font-medium">
Share Link
</p>
<p className="text-sm text-gray-800 break-all font-mono">
{shareUrl}
</p>
</div>
{/* Copy button */}
<button
onClick={handleCopyLink}
className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white py-2.5 px-4 rounded-lg transition-colors font-medium"
>
{linkCopied ? (
<>
<Check className="h-5 w-5" />
Copied!
</>
) : (
<>
<Link2 className="h-5 w-5" />
Copy Link
</>
)}
</button>
</div>
</div>
</div>
</>,
document.body,
);
}

View file

@ -0,0 +1,204 @@
"use client";
import { useRef, useState } from "react";
import { X, Users, Upload } from "lucide-react";
import {
addDocumentToProject,
createProject,
uploadProjectDocument,
} from "@/app/lib/mikeApi";
import { useDirectoryData } from "../shared/useDirectoryData";
import { FileDirectory } from "../shared/FileDirectory";
import { EmailPillInput } from "../shared/EmailPillInput";
import type { MikeProject } from "../shared/types";
interface Props {
open: boolean;
onClose: () => void;
onCreated: (project: MikeProject) => void;
}
export function NewProjectModal({ open, onClose, onCreated }: Props) {
const [name, setName] = useState("");
const [cmNumber, setCmNumber] = useState("");
const [sharedEmails, setSharedEmails] = useState<string[]>([]);
const [showMembers, setShowMembers] = useState(false);
const [selectedDocIds, setSelectedDocIds] = useState<Set<string>>(new Set());
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const fileInputRef = useRef<HTMLInputElement>(null);
const { loading: dirLoading, standaloneDocuments, projects: dirProjects } = useDirectoryData(open);
if (!open) return null;
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? []);
e.target.value = "";
if (!files.length) return;
setPendingFiles((prev) => [...prev, ...files.filter((f) => !prev.some((p) => p.name === f.name))]);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setLoading(true);
setError("");
try {
const project = await createProject(
name.trim(),
cmNumber.trim() || undefined,
sharedEmails,
);
await Promise.all([
...[...selectedDocIds].map((id) => addDocumentToProject(project.id, id).catch(() => {})),
...pendingFiles.map((f) => uploadProjectDocument(project.id, f).catch(() => {})),
]);
onCreated({ ...project, document_count: selectedDocIds.size + pendingFiles.length });
resetForm();
onClose();
} catch (err: unknown) {
setError((err as Error).message || "Failed to create project");
} finally {
setLoading(false);
}
}
function resetForm() {
setName("");
setCmNumber("");
setSharedEmails([]);
setShowMembers(false);
setSelectedDocIds(new Set());
setPendingFiles([]);
setError("");
}
function handleClose() {
resetForm();
onClose();
}
return (
<div className="fixed inset-0 z-101 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-6 pt-5 pb-2">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
<span>Projects</span>
<span></span>
<span>New project</span>
</div>
<button
onClick={handleClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
<form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
<div className="px-6 pt-3 pb-5 flex-1 overflow-y-auto">
{/* Title */}
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Project name"
className="w-full text-2xl font-serif text-gray-800 placeholder-gray-300 focus:outline-none bg-transparent"
autoFocus
/>
{/* CM Number */}
<input
type="text"
value={cmNumber}
onChange={(e) => setCmNumber(e.target.value)}
placeholder="Add a CM number..."
className="mt-1.5 w-full text-sm text-gray-500 placeholder-gray-300 focus:outline-none bg-transparent"
/>
{/* Attribute pills */}
<div className="mt-4 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setShowMembers((v) => !v)}
className="flex items-center gap-1.5 rounded-full border border-gray-200 px-3 py-1 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
>
<Users className="h-3 w-3 text-gray-400" />
Members{sharedEmails.length > 0 ? ` (${sharedEmails.length})` : ""}
</button>
</div>
{/* Members panel */}
{showMembers && (
<div className="mt-3">
<EmailPillInput
emails={sharedEmails}
onChange={setSharedEmails}
placeholder="Add colleagues by email…"
/>
</div>
)}
{/* Documents */}
<div className="mt-4 space-y-2">
<p className="text-xs font-medium text-gray-700">Select documents</p>
<FileDirectory
standaloneDocs={standaloneDocuments}
directoryProjects={dirProjects}
loading={dirLoading}
selectedIds={selectedDocIds}
onChange={setSelectedDocIds}
emptyMessage="No existing documents"
/>
</div>
{error && (
<p className="mt-3 text-sm text-red-500">{error}</p>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-gray-100 px-6 py-4 shrink-0">
<div className="flex items-center gap-2">
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={handleFileChange}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-50 transition-colors"
>
<Upload className="h-3.5 w-3.5" />
Upload files{pendingFiles.length > 0 ? ` (${pendingFiles.length})` : ""}
</button>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleClose}
className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={!name.trim() || loading}
className="rounded-lg bg-gray-900 px-5 py-2 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40 transition-colors"
>
{loading ? "Creating…" : "Create project"}
</button>
</div>
</div>
</form>
</div>
</div>
);
}

View file

@ -0,0 +1,425 @@
"use client";
import { useEffect, useRef, useState } from "react";
import {
FileText,
File,
Folder,
FolderOpen,
ChevronRight,
ChevronDown,
FolderPlus,
Trash2,
} from "lucide-react";
import type { MikeDocument, MikeFolder } from "@/app/components/shared/types";
import { VersionChip } from "@/app/components/shared/VersionChip";
interface Props {
projectName?: string | null;
documents: MikeDocument[];
folders?: MikeFolder[];
selectedDocId?: string | null;
onDocClick: (doc: MikeDocument) => void;
onCreateFolder?: (parentFolderId: string | null, name: string) => Promise<void>;
onRenameFolder?: (folderId: string, name: string) => Promise<void>;
onDeleteFolder?: (folderId: string) => Promise<void>;
onDeleteDoc?: (docId: string) => Promise<void>;
onMoveDoc?: (docId: string, targetFolderId: string | null) => Promise<void>;
onMoveFolder?: (folderId: string, targetFolderId: string | null) => Promise<void>;
}
function DocIcon({ fileType }: { fileType: string | null }) {
if (fileType === "pdf")
return <FileText className="h-3.5 w-3.5 text-red-500 shrink-0" />;
if (fileType === "docx" || fileType === "doc")
return <File className="h-3.5 w-3.5 text-blue-500 shrink-0" />;
return <File className="h-3.5 w-3.5 text-gray-400 shrink-0" />;
}
type ContextMenuState = {
x: number;
y: number;
parentId: string | null; // folder to create inside (null = root)
folderId?: string; // set if right-clicked on a specific folder
docId?: string; // set if right-clicked on a specific document
};
export function ProjectExplorer({
projectName,
documents,
folders = [],
selectedDocId,
onDocClick,
onCreateFolder,
onRenameFolder,
onDeleteFolder,
onDeleteDoc,
onMoveDoc,
onMoveFolder,
}: Props) {
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
const [creatingIn, setCreatingIn] = useState<string | null | undefined>(undefined);
const [newFolderName, setNewFolderName] = useState("");
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [dragOverFolderId, setDragOverFolderId] = useState<string | null>(null);
const [dragOverRoot, setDragOverRoot] = useState(false);
const newFolderInputRef = useRef<HTMLInputElement>(null);
const contextMenuRef = useRef<HTMLDivElement>(null);
// Close context menu on outside click
useEffect(() => {
if (!contextMenu) return;
function handle(e: MouseEvent) {
if (contextMenuRef.current && !contextMenuRef.current.contains(e.target as Node)) {
setContextMenu(null);
}
}
document.addEventListener("mousedown", handle);
return () => document.removeEventListener("mousedown", handle);
}, [contextMenu]);
// Clear all drag state when drag ends
useEffect(() => {
function handleDragEnd() {
setDragOverFolderId(null);
setDragOverRoot(false);
}
document.addEventListener("dragend", handleDragEnd);
return () => document.removeEventListener("dragend", handleDragEnd);
}, []);
function toggleFolder(id: string) {
setExpandedIds((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
}
async function commitNewFolder(parentId: string | null) {
const name = newFolderName.trim();
// Empty name → leave the input in place. Users dismiss with Escape.
// This guards against a React StrictMode race where the simulated
// unmount fires a blur that would otherwise immediately collapse
// the freshly-mounted input.
if (!name) return;
setCreatingIn(undefined);
setNewFolderName("");
if (!onCreateFolder) return;
await onCreateFolder(parentId, name);
if (parentId) setExpandedIds((prev) => new Set([...prev, parentId]));
}
async function commitRename(folderId: string) {
const name = renameValue.trim();
setRenamingId(null);
if (!name || !onRenameFolder) return;
await onRenameFolder(folderId, name);
}
function openContextMenu(
e: React.MouseEvent,
parentId: string | null,
folderId?: string,
docId?: string,
) {
e.preventDefault();
e.stopPropagation();
setContextMenu({ x: e.clientX, y: e.clientY, parentId, folderId, docId });
}
function wouldCreateCycle(movingId: string, targetId: string): boolean {
let cur: MikeFolder | undefined = folders.find((f) => f.id === targetId);
while (cur) {
if (cur.id === movingId) return true;
if (!cur.parent_folder_id) break;
cur = folders.find((f) => f.id === cur!.parent_folder_id);
}
return false;
}
async function handleDropOnTarget(targetFolderId: string | null, e: React.DragEvent) {
const docId = e.dataTransfer.getData("application/mike-doc");
const movingFolderId = e.dataTransfer.getData("application/mike-folder");
if (docId && onMoveDoc) {
const doc = documents.find((d) => d.id === docId);
if (!doc || (doc.folder_id ?? null) === targetFolderId) return;
await onMoveDoc(docId, targetFolderId);
} else if (movingFolderId && movingFolderId !== targetFolderId && onMoveFolder) {
if (targetFolderId !== null && wouldCreateCycle(movingFolderId, targetFolderId)) return;
const folder = folders.find((f) => f.id === movingFolderId);
if (!folder || (folder.parent_folder_id ?? null) === targetFolderId) return;
await onMoveFolder(movingFolderId, targetFolderId);
}
}
function isInternalDrag(e: React.DragEvent): boolean {
return (
Array.from(e.dataTransfer.types).includes("application/mike-doc") ||
Array.from(e.dataTransfer.types).includes("application/mike-folder")
);
}
function renderLevel(parentId: string | null, depth: number): React.ReactNode {
const basePadding = 28 + (depth - 1) * 16; // pl-7 at depth 1, +16px per level
const childFolders = folders
.filter((f) => f.parent_folder_id === parentId)
.sort((a, b) => a.name.localeCompare(b.name));
const childDocs = documents.filter((d) => (d.folder_id ?? null) === parentId);
return (
<>
{/* Inline new-folder input */}
{creatingIn === parentId && (
<li
className="flex items-center gap-1.5 py-1.5 pr-2 select-none"
style={{ paddingLeft: basePadding }}
>
<ChevronRight className="h-3 w-3 text-gray-300 shrink-0" />
<FolderPlus className="h-3.5 w-3.5 text-amber-400 shrink-0" />
<input
ref={newFolderInputRef}
autoFocus
className="flex-1 min-w-0 text-xs bg-transparent outline-none border-b border-gray-300 text-gray-800"
placeholder="Folder name"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void commitNewFolder(parentId);
if (e.key === "Escape") { setCreatingIn(undefined); setNewFolderName(""); }
}}
onBlur={() => void commitNewFolder(parentId)}
/>
</li>
)}
{/* Child folders */}
{childFolders.map((folder) => {
const isExpanded = expandedIds.has(folder.id);
const isRenaming = renamingId === folder.id;
const isDragTarget = dragOverFolderId === folder.id;
return (
<li key={`f-${folder.id}`}>
<div
draggable
onDragStart={(e) => {
e.dataTransfer.setData("application/mike-folder", folder.id);
e.dataTransfer.effectAllowed = "move";
e.stopPropagation();
}}
onDragOver={(e) => {
e.preventDefault();
e.stopPropagation();
setDragOverFolderId(folder.id);
setDragOverRoot(false);
}}
onDragLeave={(e) => {
e.stopPropagation();
setDragOverFolderId(null);
}}
onDrop={async (e) => {
e.preventDefault();
if (isInternalDrag(e)) {
e.stopPropagation();
setDragOverFolderId(null);
setDragOverRoot(false);
await handleDropOnTarget(folder.id, e);
}
}}
className={`flex items-center gap-1.5 py-1.5 pr-2 rounded-sm cursor-pointer select-none transition-colors group ${
isDragTarget
? "bg-blue-50 ring-1 ring-inset ring-blue-200"
: "hover:bg-gray-50"
}`}
style={{ paddingLeft: basePadding }}
onClick={() => toggleFolder(folder.id)}
onContextMenu={(e) =>
openContextMenu(e, folder.id, folder.id)
}
>
{isExpanded
? <ChevronDown className="h-3 w-3 text-gray-400 shrink-0" />
: <ChevronRight className="h-3 w-3 text-gray-400 shrink-0" />
}
{isExpanded
? <FolderOpen className="h-3.5 w-3.5 text-amber-500 shrink-0" />
: <Folder className="h-3.5 w-3.5 text-amber-500 shrink-0" />
}
{isRenaming ? (
<input
autoFocus
className="flex-1 min-w-0 text-xs bg-transparent outline-none border-b border-gray-300 text-gray-800"
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void commitRename(folder.id);
if (e.key === "Escape") setRenamingId(null);
}}
onBlur={() => void commitRename(folder.id)}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="text-xs text-gray-600 truncate">{folder.name}</span>
)}
</div>
{isExpanded && (
<ul>{renderLevel(folder.id, depth + 1)}</ul>
)}
</li>
);
})}
{/* Child documents */}
{childDocs.map((doc) => {
const isSelected = doc.id === selectedDocId;
return (
<li
key={`d-${doc.id}`}
draggable
onDragStart={(e) => {
e.dataTransfer.setData("application/mike-doc", doc.id);
e.dataTransfer.effectAllowed = "move";
}}
onDragOver={(e) => e.stopPropagation()} // don't let doc rows affect root drag state
onClick={() => onDocClick(doc)}
onContextMenu={(e) =>
openContextMenu(
e,
doc.folder_id ?? null,
undefined,
doc.id,
)
}
className={`flex items-center gap-2 py-1.5 pr-4 rounded-sm cursor-pointer select-none transition-colors ${
isSelected ? "bg-gray-100 text-gray-900" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
}`}
style={{ paddingLeft: basePadding }}
>
<DocIcon fileType={doc.file_type} />
<span className="text-xs truncate">{doc.filename}</span>
<VersionChip n={doc.latest_version_number} />
</li>
);
})}
</>
);
}
return (
<ul
className={`p-1 relative h-full ${dragOverRoot && dragOverFolderId === null ? "ring-2 ring-blue-400 ring-inset" : ""}`}
onContextMenu={(e) => {
// Only fires if not stopped by a child
openContextMenu(e, null);
}}
onDragOver={(e) => {
e.preventDefault();
setDragOverRoot(true);
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
setDragOverRoot(false);
}
}}
onDrop={async (e) => {
e.preventDefault();
if (isInternalDrag(e)) {
e.stopPropagation();
setDragOverRoot(false);
setDragOverFolderId(null);
await handleDropOnTarget(null, e);
}
// External file drops bubble up to the parent panel's onDrop (upload handler)
}}
>
{/* Project root row */}
{projectName && (
<li
className="flex items-center gap-2 px-2 py-1.5 select-none"
onContextMenu={(e) => { e.stopPropagation(); openContextMenu(e, null); }}
>
<FolderOpen className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<span className="text-xs text-gray-500 truncate">{projectName}</span>
</li>
)}
{/* Tree (depth 1 = direct children of root).
Root-level new-folder input is rendered here by renderLevel
when creatingIn === null no separate top-level block. */}
{renderLevel(null, 1)}
{/* Empty state */}
{documents.length === 0 && folders.length === 0 && creatingIn === undefined && (
<li className="px-4 py-2 text-xs text-gray-400">No documents in this project.</li>
)}
{/* Context menu */}
{contextMenu && (
<div
ref={contextMenuRef}
className="fixed z-50 w-44 rounded-lg border border-gray-100 bg-white shadow-lg overflow-hidden text-xs"
style={{ top: contextMenu.y, left: contextMenu.x }}
>
{onCreateFolder && (
<button
className="w-full px-3 py-1.5 text-left text-gray-700 hover:bg-gray-50 flex items-center gap-2"
onClick={() => {
setContextMenu(null);
if (contextMenu.parentId) {
setExpandedIds((prev) =>
new Set([...prev, contextMenu.parentId!]),
);
}
setCreatingIn(contextMenu.parentId);
setNewFolderName("");
}}
>
<FolderPlus className="h-3.5 w-3.5 text-gray-400" />
New subfolder
</button>
)}
{contextMenu.folderId && onRenameFolder && (
<button
className="w-full px-3 py-1.5 text-left text-gray-700 hover:bg-gray-50"
onClick={() => {
const f = folders.find((x) => x.id === contextMenu.folderId);
setRenameValue(f?.name ?? "");
setRenamingId(contextMenu.folderId!);
setContextMenu(null);
}}
>
Rename
</button>
)}
{contextMenu.folderId && onDeleteFolder && (
<button
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-red-600 hover:bg-red-50"
onClick={() => {
onDeleteFolder(contextMenu.folderId!);
setContextMenu(null);
}}
>
<Trash2 className="h-3.5 w-3.5 shrink-0" />
Delete folder
</button>
)}
{contextMenu.docId && onDeleteDoc && (
<button
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-red-600 hover:bg-red-50"
onClick={() => {
void onDeleteDoc(contextMenu.docId!);
setContextMenu(null);
}}
>
<Trash2 className="h-3.5 w-3.5 shrink-0" />
Delete file
</button>
)}
</div>
)}
</ul>
);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,448 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Plus, FolderOpen, ChevronDown } from "lucide-react";
import { HeaderSearchBtn } from "@/app/components/shared/HeaderSearchBtn";
import { listProjects, updateProject, deleteProject } from "@/app/lib/mikeApi";
import { OwnerOnlyModal } from "@/app/components/shared/OwnerOnlyModal";
import { useAuth } from "@/contexts/AuthContext";
import type { MikeProject } from "@/app/components/shared/types";
import { NewProjectModal } from "./NewProjectModal";
import { ToolbarTabs } from "@/app/components/shared/ToolbarTabs";
import { RowActions } from "@/app/components/shared/RowActions";
function formatDate(iso: string) {
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
type Tab = "all" | "mine" | "shared-with-me";
const CHECK_W = "w-8 shrink-0";
const NAME_COL_W = "w-[300px] shrink-0";
export function ProjectsOverview() {
const [projects, setProjects] = useState<MikeProject[]>([]);
const [loading, setLoading] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
const [activeTab, setActiveTab] = useState<Tab>("all");
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const [cmEditingId, setCmEditingId] = useState<string | null>(null);
const [cmValue, setCmValue] = useState("");
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [actionsOpen, setActionsOpen] = useState(false);
const [search, setSearch] = useState("");
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const actionsRef = useRef<HTMLDivElement>(null);
const router = useRouter();
const { user } = useAuth();
useEffect(() => {
listProjects()
.then(setProjects)
.catch(() => setProjects([]))
.finally(() => setLoading(false));
}, []);
useEffect(() => {
setSelectedIds([]);
}, [activeTab]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (
actionsRef.current &&
!actionsRef.current.contains(e.target as Node)
)
setActionsOpen(false);
}
if (actionsOpen) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [actionsOpen]);
const q = search.toLowerCase();
const filtered = (
activeTab === "all"
? projects
: activeTab === "mine"
? projects.filter((p) => p.is_owner ?? p.user_id === user?.id)
: projects.filter((p) => !(p.is_owner ?? p.user_id === user?.id))
).filter(
(p) =>
!q ||
p.name.toLowerCase().includes(q) ||
(p.cm_number ?? "").toLowerCase().includes(q),
);
const allSelected =
filtered.length > 0 &&
filtered.every((p) => selectedIds.includes(p.id));
const someSelected =
!allSelected && filtered.some((p) => selectedIds.includes(p.id));
function toggleAll() {
if (allSelected) {
setSelectedIds([]);
} else {
setSelectedIds(filtered.map((p) => p.id));
}
}
function toggleOne(id: string) {
setSelectedIds((prev) =>
prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
);
}
const tabs: { id: Tab; label: string }[] = [
{ id: "all", label: "All" },
{ id: "mine", label: "Mine" },
{ id: "shared-with-me", label: "Shared with me" },
];
async function handleRenameSubmit(projectId: string) {
const trimmed = renameValue.trim();
setRenamingId(null);
if (!trimmed) return;
setProjects((prev) =>
prev.map((p) => (p.id === projectId ? { ...p, name: trimmed } : p)),
);
await updateProject(projectId, { name: trimmed });
}
async function handleCmSubmit(projectId: string) {
const trimmed = cmValue.trim();
setCmEditingId(null);
setProjects((prev) =>
prev.map((p) =>
p.id === projectId ? { ...p, cm_number: trimmed || null } : p,
),
);
await updateProject(projectId, { cm_number: trimmed || undefined });
}
async function handleDeleteSelected() {
const ids = [...selectedIds];
setActionsOpen(false);
// Only the project owner can delete; the per-row delete is hidden
// for shared projects but the bulk action can still pick them up
// if a user toggled them across tabs. Filter and warn.
const owned = ids.filter((id) => {
const p = projects.find((pp) => pp.id === id);
return !p || (p.is_owner ?? p.user_id === user?.id);
});
const blocked = ids.length - owned.length;
setSelectedIds([]);
await Promise.all(owned.map((id) => deleteProject(id).catch(() => {})));
setProjects((prev) => prev.filter((p) => !owned.includes(p.id)));
if (blocked > 0) {
setOwnerOnlyAction(
`delete ${blocked} of the selected projects — only the project owner can delete a project`,
);
}
}
const toolbarActions = (
<div className="flex items-center gap-2">
{selectedIds.length > 0 && (
<div ref={actionsRef} className="relative">
<button
onClick={() => setActionsOpen((v) => !v)}
className="flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Actions
<ChevronDown className="h-3.5 w-3.5" />
</button>
{actionsOpen && (
<div className="absolute top-full right-0 mt-1 w-36 rounded-lg border border-gray-100 bg-white shadow-lg z-50 overflow-hidden">
<button
onClick={handleDeleteSelected}
className="w-full px-3 py-1.5 text-left text-xs text-red-600 hover:bg-red-50 transition-colors"
>
Delete
</button>
</div>
)}
</div>
)}
</div>
);
return (
<div className="flex-1 overflow-y-auto bg-white">
{/* Page header */}
<div className="flex items-center justify-between px-8 py-4">
<h1 className="text-2xl font-medium font-serif text-gray-900">
Projects
</h1>
<div className="flex items-center gap-2">
<HeaderSearchBtn
value={search}
onChange={setSearch}
placeholder="Search projects…"
/>
<button
onClick={() => setModalOpen(true)}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
<ToolbarTabs
tabs={tabs}
active={activeTab}
onChange={setActiveTab}
actions={toolbarActions}
/>
{/* Table */}
<div className="w-full overflow-x-auto">
<div className="min-w-max">
{/* Column headers */}
<div className="flex items-center h-8 pr-8 border-b border-gray-200 text-xs text-gray-500 font-medium select-none">
<div className={`sticky left-0 z-[60] ${CHECK_W} relative bg-white flex items-center justify-center self-stretch before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-white`}>
{!loading && (
<input
type="checkbox"
checked={allSelected}
ref={(el) => {
if (el) el.indeterminate = someSelected;
}}
onChange={toggleAll}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
)}
</div>
<div className={`sticky left-8 z-[60] ${NAME_COL_W} bg-white pl-2 text-left`}>
Name
</div>
<div className="ml-auto w-32 shrink-0 text-left">CM</div>
<div className="w-24 shrink-0 text-left">Files</div>
<div className="w-24 shrink-0 text-left">Chats</div>
<div className="w-36 shrink-0 text-left">
Tabular Reviews
</div>
<div className="w-32 shrink-0 text-left">Created</div>
<div className="w-8 shrink-0" />
</div>
{loading ? (
<div>
{[1, 2, 3].map((i) => (
<div
key={i}
className="flex items-center h-10 pr-8 border-b border-gray-50"
>
<div className="w-8 shrink-0" />
<div className="flex-1 min-w-0 pl-3 pr-4">
<div className="h-3.5 w-48 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-32 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-24 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-36 shrink-0">
<div className="h-3 w-8 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-32 shrink-0">
<div className="h-3 w-20 rounded bg-gray-100 animate-pulse" />
</div>
<div className="w-8 shrink-0" />
</div>
))}
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-start py-24 w-full max-w-xs mx-auto">
{activeTab === "all" || activeTab === "mine" ? (
<>
<FolderOpen className="h-8 w-8 text-gray-300 mb-4" />
<p className="text-2xl font-medium font-serif text-gray-900">
Projects
</p>
<p className="mt-1 text-xs text-gray-400 max-w-xs">
Upload documents into projects and to
commence chats and tabular reviews with
them.
</p>
<button
onClick={() => setModalOpen(true)}
className="mt-4 inline-flex items-center gap-1 rounded-full bg-gray-900 px-3 py-1 text-xs font-medium text-white hover:bg-gray-700 transition-colors shadow-md"
>
+ Create New
</button>
</>
) : (
<p className="text-sm text-gray-400">
No {activeTab} projects
</p>
)}
</div>
) : (
<div>
{filtered.map((project) => {
const rowBg = selectedIds.includes(project.id)
? "bg-gray-50"
: "bg-white";
return (
<div
key={project.id}
onClick={() => {
if (renamingId === project.id) return;
router.push(`/projects/${project.id}`);
}}
className="group flex items-center h-10 pr-8 border-b border-gray-50 hover:bg-gray-50 cursor-pointer transition-colors"
>
<div
className={`sticky left-0 z-[60] ${CHECK_W} p-2 flex items-center justify-center ${rowBg} group-hover:bg-gray-50`}
onClick={(e) => e.stopPropagation()}
>
<input
type="checkbox"
checked={selectedIds.includes(
project.id,
)}
onChange={() => toggleOne(project.id)}
className="h-2.5 w-2.5 rounded border-gray-200 cursor-pointer accent-black"
/>
</div>
{/* Project Name */}
<div className={`sticky left-8 z-[60] ${NAME_COL_W} p-2 ${rowBg} group-hover:bg-gray-50`}>
{renamingId === project.id ? (
<input
autoFocus
value={renameValue}
onChange={(e) =>
setRenameValue(e.target.value)
}
onKeyDown={(e) => {
if (e.key === "Enter")
handleRenameSubmit(
project.id,
);
if (e.key === "Escape")
setRenamingId(null);
}}
onBlur={() =>
handleRenameSubmit(project.id)
}
onClick={(e) => e.stopPropagation()}
className="w-full text-sm text-gray-800 bg-transparent outline-none"
/>
) : (
<span className="text-sm text-gray-800 truncate block">
{project.name}
</span>
)}
</div>
<div
className="ml-auto w-32 shrink-0 text-sm text-gray-500 truncate"
onClick={(e) => e.stopPropagation()}
>
{cmEditingId === project.id ? (
<input
autoFocus
value={cmValue}
onChange={(e) =>
setCmValue(e.target.value)
}
onKeyDown={(e) => {
if (e.key === "Enter")
handleCmSubmit(project.id);
if (e.key === "Escape")
setCmEditingId(null);
}}
onBlur={() =>
handleCmSubmit(project.id)
}
placeholder="CM #"
className="w-full text-sm text-gray-800 bg-transparent outline-none"
/>
) : (
(project.cm_number ?? (
<span className="text-gray-300">
</span>
))
)}
</div>
<div className="w-24 shrink-0 text-sm text-gray-500 truncate">
{project.document_count ?? 0}
</div>
<div className="w-24 shrink-0 text-sm text-gray-500 truncate">
{project.chat_count ?? 0}
</div>
<div className="w-36 shrink-0 text-sm text-gray-500 truncate">
{project.review_count ?? 0}
</div>
<div className="w-32 shrink-0 text-sm text-gray-500 truncate">
{formatDate(project.created_at)}
</div>
<div
className="w-8 shrink-0 flex justify-end"
onClick={(e) => e.stopPropagation()}
>
{(project.is_owner ??
project.user_id === user?.id) && (
<RowActions
onRename={() => {
setRenameValue(project.name);
setRenamingId(project.id);
}}
onUpdateCmNumber={() => {
setCmValue(
project.cm_number ?? "",
);
setCmEditingId(project.id);
}}
onDelete={async () => {
await deleteProject(project.id);
setProjects((prev) =>
prev.filter(
(p) =>
p.id !== project.id,
),
);
}}
/>
)}
</div>
</div>
);
})}
</div>
)}
</div>
</div>
<NewProjectModal
open={modalOpen}
onClose={() => setModalOpen(false)}
onCreated={(p) => {
setProjects((prev) => [p, ...prev]);
router.push(`/projects/${p.id}`);
}}
/>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>
);
}

View file

@ -0,0 +1,315 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { X, Upload, Search, Loader2 } from "lucide-react";
import {
uploadStandaloneDocument,
uploadProjectDocument,
addDocumentToProject,
deleteDocument,
} from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
import { FileDirectory } from "./FileDirectory";
import { useDirectoryData, invalidateDirectoryCache } from "./useDirectoryData";
import { OwnerOnlyModal } from "./OwnerOnlyModal";
import { useAuth } from "@/contexts/AuthContext";
export { invalidateDirectoryCache };
interface Props {
open: boolean;
onClose: () => void;
onSelect: (documents: MikeDocument[], projectId?: string) => void;
breadcrumb: string[];
allowMultiple?: boolean;
projectId?: string;
}
export function AddDocumentsModal({
open,
onClose,
onSelect,
breadcrumb,
allowMultiple = true,
projectId,
}: Props) {
const { loading, standaloneDocuments, projects } = useDirectoryData(open);
const { user } = useAuth();
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [uploading, setUploading] = useState(false);
const [search, setSearch] = useState("");
const [extraUploadedDocs, setExtraUploadedDocs] = useState<MikeDocument[]>([]);
// IDs deleted in this session — hidden locally since `useDirectoryData`'s
// cached state won't re-fetch until the modal reopens.
const [deletedIds, setDeletedIds] = useState<Set<string>>(new Set());
const [ownerOnlyAction, setOwnerOnlyAction] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) return;
setSearch("");
setSelectedIds(new Set());
setExtraUploadedDocs([]);
setDeletedIds(new Set());
}, [open]);
if (!open) return null;
const q = search.toLowerCase().trim();
const allStandalone = [
...extraUploadedDocs.filter(
(u) => !standaloneDocuments.some((d) => d.id === u.id),
),
...standaloneDocuments,
].filter((d) => !deletedIds.has(d.id));
const filteredStandalone = q
? allStandalone.filter((d) => d.filename.toLowerCase().includes(q))
: allStandalone;
const filteredProjects = projects
.filter((p) => p.id !== projectId)
.map((p) => ({
...p,
documents: (p.documents || []).filter(
(d) =>
!deletedIds.has(d.id) &&
(!q || d.filename.toLowerCase().includes(q)),
),
}))
.filter(
(p) =>
!q ||
p.name.toLowerCase().includes(q) ||
p.documents.length > 0,
);
const allDocs = [
...allStandalone,
...projects.flatMap((p) => p.documents || []),
];
async function handleConfirm() {
const selected = allDocs.filter((d) => selectedIds.has(d.id));
if (projectId) {
const toAssign = selected.filter((d) => d.project_id !== projectId);
const alreadyHere = selected.filter(
(d) => d.project_id === projectId,
);
if (toAssign.length > 0) {
setUploading(true);
try {
const assigned = await Promise.all(
toAssign.map((d) =>
addDocumentToProject(projectId, d.id),
),
);
onSelect([...alreadyHere, ...assigned], projectId);
} catch (err) {
console.error("Failed to assign documents:", err);
} finally {
setUploading(false);
}
} else {
onSelect(alreadyHere, projectId);
}
onClose();
return;
}
const projectIds = new Set(
selected.map((d) => d.project_id).filter(Boolean),
);
const singleProjectId =
projectIds.size === 1 ? [...projectIds][0]! : undefined;
onSelect(selected, singleProjectId);
onClose();
}
async function handleDelete(ids: string[]) {
// Server only allows the doc creator to delete. Filter to owned
// and warn for the rest.
const docsById = new Map<string, MikeDocument>();
for (const d of [
...standaloneDocuments,
...extraUploadedDocs,
...projects.flatMap((p) => p.documents ?? []),
]) {
docsById.set(d.id, d);
}
const owned = ids.filter((id) => {
const d = docsById.get(id);
return !d || !d.user_id || !user?.id || d.user_id === user.id;
});
const blocked = ids.length - owned.length;
if (owned.length === 0 && blocked > 0) {
setOwnerOnlyAction(
"delete these documents — only the document creator can delete a document",
);
return;
}
const idSet = new Set(owned);
try {
await Promise.all(owned.map((id) => deleteDocument(id)));
} catch (err) {
console.error("Delete failed:", err);
return;
}
invalidateDirectoryCache();
setExtraUploadedDocs((prev) => prev.filter((d) => !idSet.has(d.id)));
setDeletedIds((prev) => {
const next = new Set(prev);
owned.forEach((id) => next.add(id));
return next;
});
if (blocked > 0) {
setOwnerOnlyAction(
`delete ${blocked} of the selected documents — only the document creator can delete a document`,
);
}
}
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) =>
projectId
? uploadProjectDocument(projectId, f)
: uploadStandaloneDocument(f),
),
);
invalidateDirectoryCache();
setExtraUploadedDocs((prev) => [...uploaded, ...prev]);
uploaded.forEach((d) =>
setSelectedIds((prev) => new Set([...prev, d.id])),
);
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{breadcrumb.map((segment, i) => (
<span key={i} className="flex items-center gap-1.5">
{i > 0 && <span></span>}
{segment}
</span>
))}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Search bar */}
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
{search && (
<button
onClick={() => setSearch("")}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* File browser */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
<FileDirectory
standaloneDocs={filteredStandalone}
directoryProjects={filteredProjects}
loading={loading}
selectedIds={selectedIds}
onChange={setSelectedIds}
allowMultiple={allowMultiple}
forceExpanded={!!q}
emptyMessage={
q ? "No matches found" : "No documents yet"
}
onDelete={handleDelete}
/>
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-between gap-3">
<div>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 disabled:opacity-50"
>
{uploading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Upload className="h-3.5 w-3.5" />
)}
{uploading ? "Uploading…" : "Upload"}
</button>
</div>
<div className="flex items-center gap-2">
{selectedIds.size > 0 && (
<span className="text-xs text-gray-400">
{selectedIds.size} selected
</span>
)}
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleConfirm}
disabled={selectedIds.size === 0 || uploading}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
{uploading ? "Saving…" : "Confirm"}
</button>
</div>
</div>
</div>
<OwnerOnlyModal
open={!!ownerOnlyAction}
action={ownerOnlyAction ?? undefined}
onClose={() => setOwnerOnlyAction(null)}
/>
</div>,
document.body,
);
}

View file

@ -0,0 +1,299 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Check, Loader2, Search, Upload, X } from "lucide-react";
import { getProject, uploadProjectDocument } from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
import { DocFileIcon } from "./FileDirectory";
import { VersionChip } from "./VersionChip";
interface Props {
open: boolean;
onClose: () => void;
onSelect: (documents: MikeDocument[]) => void;
breadcrumb: string[];
projectId: string;
/** Docs already in the target list — rendered checked + disabled. */
excludeDocIds?: Set<string>;
allowMultiple?: boolean;
}
function formatDate(iso: string | null) {
if (!iso) return null;
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
export function AddProjectDocsModal({
open,
onClose,
onSelect,
breadcrumb,
projectId,
excludeDocIds,
allowMultiple = true,
}: Props) {
const [docs, setDocs] = useState<MikeDocument[]>([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState("");
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!open) return;
setSearch("");
setSelectedIds(new Set());
let cancelled = false;
setLoading(true);
getProject(projectId)
.then((p) => {
if (!cancelled) setDocs(p.documents ?? []);
})
.catch(() => {
if (!cancelled) setDocs([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, projectId]);
if (!open) return null;
const q = search.toLowerCase().trim();
const filtered = q
? docs.filter((d) => d.filename.toLowerCase().includes(q))
: docs;
const isExcluded = (id: string) => !!excludeDocIds?.has(id);
function toggle(id: string) {
if (isExcluded(id)) return;
if (!allowMultiple) {
setSelectedIds(new Set([id]));
return;
}
setSelectedIds((prev) => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
}
function handleConfirm() {
const selected = docs.filter((d) => selectedIds.has(d.id));
onSelect(selected);
onClose();
}
async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files || []);
if (!files.length) return;
setUploading(true);
try {
const uploaded = await Promise.all(
files.map((f) => uploadProjectDocument(projectId, f)),
);
setDocs((prev) => [...uploaded, ...prev]);
setSelectedIds((prev) => {
const next = new Set(prev);
uploaded.forEach((d) => next.add(d.id));
return next;
});
} catch (err) {
console.error("Upload failed:", err);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{breadcrumb.map((segment, i) => (
<span
key={i}
className="flex items-center gap-1.5"
>
{i > 0 && <span></span>}
{segment}
</span>
))}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Search */}
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
{search && (
<button
onClick={() => setSearch("")}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
{/* File list */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
{loading ? (
<div className="rounded-sm border border-gray-100 overflow-hidden">
{[60, 45, 75, 55, 40].map((w, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-2"
>
<div className="h-3.5 w-3.5 rounded border border-gray-200 shrink-0" />
<div className="h-3.5 w-3.5 rounded bg-gray-200 animate-pulse shrink-0" />
<div
className="h-3 rounded bg-gray-200 animate-pulse"
style={{ width: `${w}%` }}
/>
</div>
))}
</div>
) : filtered.length === 0 ? (
<p className="text-center text-sm text-gray-400 py-8">
{q ? "No matches found" : "No documents in this project"}
</p>
) : (
<div className="rounded-sm border border-gray-100 overflow-hidden">
{filtered.map((doc) => {
const excluded = isExcluded(doc.id);
const checked =
excluded || selectedIds.has(doc.id);
return (
<button
type="button"
key={doc.id}
disabled={excluded}
onClick={() => toggle(doc.id)}
className={`w-full flex items-center gap-2 px-2 py-2 text-xs text-left transition-colors ${
excluded
? "opacity-50 cursor-not-allowed"
: checked
? "bg-gray-100"
: "hover:bg-gray-50"
}`}
>
<span
className={`shrink-0 h-3.5 w-3.5 rounded border flex items-center justify-center ${
checked
? "bg-gray-900 border-gray-900"
: "border-gray-300"
}`}
>
{checked && (
<Check className="h-2.5 w-2.5 text-white" />
)}
</span>
<DocFileIcon
fileType={doc.file_type}
/>
<span
className={`flex-1 truncate ${
checked
? "text-gray-900"
: "text-gray-700"
}`}
>
{doc.filename}
</span>
{excluded && (
<span className="text-[10px] text-gray-400 shrink-0">
Already added
</span>
)}
<VersionChip
n={doc.latest_version_number}
/>
{doc.created_at && (
<span className="shrink-0 text-gray-300">
{formatDate(doc.created_at)}
</span>
)}
</button>
);
})}
</div>
)}
</div>
{/* Footer */}
<div className="border-t border-gray-100 px-4 py-3 flex items-center justify-between gap-3">
<div>
<input
ref={fileInputRef}
type="file"
accept=".pdf,.docx,.doc"
multiple
className="hidden"
onChange={handleUpload}
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 rounded-lg border border-gray-200 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50 disabled:opacity-50"
>
{uploading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Upload className="h-3.5 w-3.5" />
)}
{uploading ? "Uploading…" : "Upload"}
</button>
</div>
<div className="flex items-center gap-2">
{selectedIds.size > 0 && (
<span className="text-xs text-gray-400">
{selectedIds.size} selected
</span>
)}
<button
onClick={onClose}
className="rounded-lg px-3 py-1.5 text-sm text-gray-500 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleConfirm}
disabled={selectedIds.size === 0 || uploading}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700 disabled:opacity-40"
>
Confirm
</button>
</div>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,78 @@
"use client";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import { AlertTriangle, X } from "lucide-react";
import { providerLabel, type ModelProvider } from "@/app/lib/modelAvailability";
interface Props {
open: boolean;
onClose: () => void;
provider: ModelProvider | null;
/** Optional override for the body sentence. */
message?: string;
}
export function ApiKeyMissingModal({ open, onClose, provider, message }: Props) {
const router = useRouter();
if (!open) return null;
const providerName = provider ? providerLabel(provider) : "this provider";
const body =
message ??
`You haven't added a ${providerName} API key yet. Add one in your account settings to use this model.`;
const handleGoToAccount = () => {
onClose();
router.push("/account/models");
};
return createPortal(
<div
className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs"
onClick={onClose}
>
<div
className="w-full max-w-md rounded-2xl bg-white shadow-2xl flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-start justify-between gap-3 px-5 pt-5 pb-2">
<div className="flex items-center gap-2">
<AlertTriangle className="h-4 w-4 text-amber-600" />
<h2 className="text-base font-medium text-gray-900">
API key required
</h2>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="px-5 pb-2 pt-1">
<p className="text-sm text-gray-600 leading-relaxed">
{body}
</p>
</div>
<div className="flex justify-end gap-2 px-5 pb-5 pt-3">
<button
onClick={onClose}
className="rounded-lg px-4 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100"
>
Cancel
</button>
<button
onClick={handleGoToAccount}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700"
>
Go to account settings
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,311 @@
"use client";
import { useState, useEffect } from "react";
import {
PanelLeft,
MessageSquare,
FolderOpen,
Table2,
Library,
User,
ChevronsUpDown,
ChevronDown,
} from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { useChatHistoryContext } from "@/app/contexts/ChatHistoryContext";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { MikeIcon } from "@/components/chat/mike-icon";
import { SidebarChatItem } from "@/app/components/shared/SidebarChatItem";
import { listProjects } from "@/app/lib/mikeApi";
const NAV_ITEMS = [
{ href: "/assistant", label: "Assistant", icon: MessageSquare },
{ href: "/projects", label: "Projects", icon: FolderOpen },
{ href: "/tabular-reviews", label: "Tabular Review", icon: Table2 },
{ href: "/workflows", label: "Workflows", icon: Library },
];
interface AppSidebarProps {
isOpen: boolean;
onToggle: () => void;
}
export function AppSidebar({ isOpen, onToggle }: AppSidebarProps) {
const { user } = useAuth();
const { profile } = useUserProfile();
const { chats, currentChatId, setCurrentChatId } = useChatHistoryContext();
const router = useRouter();
const pathname = usePathname();
const [shouldAnimate, setShouldAnimate] = useState(false);
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [historyCollapsed, setHistoryCollapsed] = useState(false);
const [projectNames, setProjectNames] = useState<Record<string, string>>(
{},
);
useEffect(() => {
if (!user) return;
listProjects()
.then((projects) => {
const map: Record<string, string> = {};
for (const p of projects) map[p.id] = p.name;
setProjectNames(map);
})
.catch(() => {});
}, [user]);
useEffect(() => {
if (!isOpen) setShouldAnimate(true);
}, [isOpen]);
useEffect(() => {
const handleClickOutside = () => setIsDropdownOpen(false);
if (isDropdownOpen) {
document.addEventListener("click", handleClickOutside);
return () =>
document.removeEventListener("click", handleClickOutside);
}
}, [isDropdownOpen]);
useEffect(() => {
if (pathname.startsWith("/assistant/chat/")) {
const chatId = pathname.split("/").pop() ?? null;
setCurrentChatId(chatId);
return;
}
const projectChatMatch = pathname.match(
/^\/projects\/[^/]+\/assistant\/chat\/([^/]+)/,
);
if (projectChatMatch) {
setCurrentChatId(projectChatMatch[1]);
return;
}
if (pathname === "/assistant") {
setCurrentChatId(null);
}
}, [pathname, setCurrentChatId]);
const getUserInitials = (email: string) => {
if (profile?.displayName)
return profile.displayName.charAt(0).toUpperCase();
return email.charAt(0).toUpperCase();
};
const getDisplayName = () => {
if (!profile) return "";
return profile.displayName || user?.email?.split("@")[0] || "";
};
const getUserTier = () => {
if (!profile) return "";
return profile.tier || "Free";
};
if (!user) return null;
return (
<div
className={`${
isOpen
? "w-64 h-dvh bg-gray-50 border-r"
: "w-14 md:h-dvh md:bg-gray-50 md:border-r h-auto bg-transparent"
} border-gray-200 flex flex-col transition-all duration-300 absolute md:relative z-99 overflow-visible`}
>
{/* Toggle + Logo */}
<div
className={`mb-3 items-center justify-between px-2.5 py-2 ${
!isOpen ? "hidden md:flex" : "flex"
}`}
>
{isOpen && (
<div className="px-2.5">
<Link
href="/assistant"
className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
>
<MikeIcon size={22} />
<span
className={`text-2xl font-light font-serif ${
shouldAnimate ? "sidebar-fade-in" : ""
}`}
>
Mike
</span>
</Link>
</div>
)}
<button
onClick={onToggle}
className="h-9 w-9 p-2.5 items-center flex hover:bg-gray-100 rounded-md transition-colors"
title={isOpen ? "Close sidebar" : "Open sidebar"}
>
<PanelLeft className="h-4 w-4" />
</button>
</div>
{/* Nav items */}
{NAV_ITEMS.map(({ href, label, icon: Icon }) => {
const isActive =
pathname === href || pathname.startsWith(href + "/");
return (
<div key={href} className="py-1 px-2.5">
<button
onClick={() => router.push(href)}
title={!isOpen ? label : ""}
className={`w-full h-9 flex items-center gap-3 px-2.5 py-2 rounded-md transition-colors text-left ${
isActive
? "bg-gray-100 text-gray-900"
: "hover:bg-gray-100 text-gray-700"
} ${!isOpen ? "hidden md:flex" : "flex"}`}
>
<Icon
className={`h-4 w-4 flex-shrink-0 ${
isActive ? "text-gray-900" : "text-black"
}`}
/>
{isOpen && (
<span
className={`text-sm font-medium ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
{label}
</span>
)}
</button>
</div>
);
})}
{/* Assistant History */}
{isOpen && pathname.startsWith("/assistant") && (
<div className="mt-4 flex-1 min-h-0 flex flex-col">
<button
onClick={() => setHistoryCollapsed((v) => !v)}
className={`mb-2 px-5 flex items-center justify-between text-xs font-semibold text-gray-500 hover:text-gray-700 transition-colors ${
shouldAnimate ? "sidebar-fade-in" : ""
}`}
>
<span>Assistant History</span>
<ChevronDown
className={`h-3.5 w-3.5 transition-transform ${historyCollapsed ? "-rotate-90" : ""}`}
/>
</button>
<div
className={`overflow-y-auto flex-1 ${historyCollapsed ? "hidden" : ""}`}
>
{!chats ? (
<div className="space-y-1 px-2.5">
{[40, 60, 50, 70, 45].map((w, i) => (
<div
key={i}
className="h-9 flex items-center px-3 rounded-md"
>
<div
className="h-3 bg-gray-200 rounded animate-pulse"
style={{ width: `${w}%` }}
/>
</div>
))}
</div>
) : chats.length === 0 ? (
<div
className={`text-xs text-gray-500 py-2 px-5 ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
No chats yet
</div>
) : (
<div
className={`space-y-1 px-2.5 ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
{chats.map((chat) => (
<SidebarChatItem
key={chat.id}
chat={chat}
isActive={currentChatId === chat.id}
projectName={
chat.project_id
? projectNames[chat.project_id]
: undefined
}
onSelect={() => {
setCurrentChatId(chat.id);
router.push(
chat.project_id
? `/projects/${chat.project_id}/assistant/chat/${chat.id}`
: `/assistant/chat/${chat.id}`,
);
}}
/>
))}
</div>
)}
</div>
</div>
)}
{/* User Profile */}
<div className="mt-auto">
{user && (
<div className="relative">
<button
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
className={`flex items-center transition-colors w-full px-3.5 py-4 border-t border-gray-200 ${
!isOpen ? "hidden md:flex" : ""
} ${
pathname === "/account" || isDropdownOpen
? "bg-gray-100"
: "hover:bg-gray-100"
}`}
title={!isOpen ? user.email : undefined}
>
<div className="h-7 w-7 flex-shrink-0 rounded-full bg-gray-700 flex items-center justify-center text-white text-sm font-medium font-serif">
{getUserInitials(user.email)}
</div>
{isOpen && (
<div
className={`text-left flex-1 min-w-0 pl-3 flex items-center justify-between gap-2 ${
shouldAnimate ? "sidebar-fade-in-2" : ""
}`}
>
<div className="flex flex-col gap-0.5 min-w-0">
<div className="text-sm font-medium text-gray-900 leading-none">
{getDisplayName()}
</div>
<div className="text-[12px] text-gray-500 leading-none">
{getUserTier()}
</div>
</div>
<ChevronsUpDown className="h-4 w-4 flex-shrink-0 text-gray-400" />
</div>
)}
</button>
{isDropdownOpen && (
<div className="absolute bottom-full left-0 m-1 bg-white rounded-lg shadow-lg border border-gray-200 p-1 z-50 w-62 whitespace-nowrap">
<button
onClick={() => {
router.push("/account");
setIsDropdownOpen(false);
}}
className="w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 flex items-center gap-2 rounded-md"
>
<User className="h-4 w-4" />
Account Settings
</button>
</div>
)}
</div>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,505 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Download, Loader2 } from "lucide-react";
import { supabase } from "@/lib/supabase";
import { applyOptimisticResolution } from "../assistant/EditCard";
import { DocView } from "./DocView";
import { DocxView } from "./DocxView";
import {
displayCitationQuote,
expandCitationToEntries,
formatCitationPage,
} from "./types";
import type {
CitationQuote,
MikeCitationAnnotation,
MikeEditAnnotation,
} from "./types";
function isDocxFilename(name: string): boolean {
const ext = name.split(".").pop()?.toLowerCase();
return ext === "docx" || ext === "doc";
}
/**
* Discriminated-union describing what the panel is showing above the viewer.
* - "document": no header card, no label just the viewer.
* - "citation": "Citation Quote" card with the quoted text and page ref.
* - "edit": "Tracked Change" card with the diff + Accept/Reject.
*/
export type DocPanelMode =
| { kind: "document" }
| { kind: "citation"; citation: MikeCitationAnnotation }
| {
kind: "edit";
edit: MikeEditAnnotation;
/**
* True while an accept/reject request for this exact edit is in
* flight. Scoped per-edit (not per-document) so sibling edits on
* the same doc stay clickable.
*/
isEditReloading?: boolean;
onResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
onError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
};
interface Props {
documentId: string;
filename: string;
versionId: string | null;
versionNumber: number | null;
mode: DocPanelMode;
/** Spinner on the Download button while an accept/reject is in flight. */
isReloading?: boolean;
warning?: string | null;
onWarningDismiss?: () => void;
initialScrollTop?: number | null;
onScrollChange?: (scrollTop: number) => void;
}
/**
* Unified side-panel body for the assistant. Renders a single document
* with optionally a citation quote OR a tracked change highlighted above
* the viewer. No selector UI caller picks the one thing to show; if the
* user wants a different citation/edit, the panel gets a new tab.
*/
export function DocPanel({
documentId,
filename,
versionId,
versionNumber,
mode,
isReloading = false,
warning,
onWarningDismiss,
initialScrollTop,
onScrollChange,
}: Props) {
// Pick the viewer from the filename only, not from mode. Switching
// headers (citation ↔ edit ↔ document) for the same document must
// not unmount and remount the body — otherwise the user sees a full
// re-fetch every time they toggle. Tracked-change rendering still
// only lives in DocxView, which is fine because edits are DOCX-only.
const useDocxView = isDocxFilename(filename);
const quotes: CitationQuote[] | undefined = useMemo(() => {
if (mode.kind !== "citation") return undefined;
return expandCitationToEntries(mode.citation);
}, [mode]);
const highlightEdit = useMemo(() => {
if (mode.kind !== "edit") return null;
return {
key: `${mode.edit.edit_id}`,
inserted_text: mode.edit.inserted_text,
deleted_text: mode.edit.deleted_text,
ins_w_id: mode.edit.ins_w_id ?? null,
del_w_id: mode.edit.del_w_id ?? null,
};
}, [mode]);
return (
<div className="flex h-full flex-col px-3 pb-3">
{mode.kind === "citation" ? (
<CitationHeader
citation={mode.citation}
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
) : mode.kind === "edit" ? (
<TrackedChangeHeader
mode={mode}
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
) : (
<div className="flex items-center justify-end gap-2 py-2">
<div className="mr-auto flex min-w-0 items-center gap-2">
<span className="truncate text-sm text-gray-700">
{filename}
</span>
{versionNumber && versionNumber > 0 && (
<span className="shrink-0 inline-flex items-center rounded-md border border-gray-200 bg-white px-1.5 py-0.5 text-[10px] font-medium text-gray-600">
V{versionNumber}
</span>
)}
</div>
<DownloadButton
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
</div>
)}
{useDocxView ? (
<DocxView
documentId={documentId}
versionId={versionId ?? undefined}
quotes={quotes}
highlightEdit={highlightEdit}
warning={warning ?? null}
onWarningDismiss={onWarningDismiss}
initialScrollTop={initialScrollTop ?? null}
onScrollChange={onScrollChange}
/>
) : (
<DocView
doc={{
document_id: documentId,
version_id: versionId,
}}
quotes={quotes}
/>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Header variants
// ---------------------------------------------------------------------------
function SectionLabel({ children }: { children: React.ReactNode }) {
return <p className="text-xs font-medium text-gray-700">{children}</p>;
}
function CitationHeader({
citation,
documentId,
versionId,
filename,
isReloading,
}: {
citation: MikeCitationAnnotation;
documentId: string;
versionId: string | null;
filename: string;
isReloading: boolean;
}) {
const displayQuote = displayCitationQuote(citation);
const pagesLabel = formatCitationPage(citation);
return (
<div className="pt-2 pb-3">
<div className="flex items-center gap-2 mb-2">
<SectionLabel>Citation</SectionLabel>
<div className="ml-auto shrink-0">
<DownloadButton
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
</div>
</div>
<div className="w-full rounded-md bg-gray-50 border border-gray-200 px-2 py-2">
<p className="text-sm font-serif text-gray-600">
&ldquo;{displayQuote}&rdquo;
{pagesLabel && (
<span className="ml-1 text-gray-400">
({pagesLabel})
</span>
)}
</p>
</div>
</div>
);
}
function TrackedChangeHeader({
mode,
documentId,
versionId,
filename,
isReloading,
}: {
mode: Extract<DocPanelMode, { kind: "edit" }>;
documentId: string;
versionId: string | null;
filename: string;
isReloading: boolean;
}) {
const { edit, isEditReloading, onResolveStart, onResolved, onError } = mode;
return (
<div className="pt-2 pb-3">
<div className="flex items-center gap-2 mb-2">
<SectionLabel>Tracked Change</SectionLabel>
<div className="ml-auto flex items-center gap-2 shrink-0">
<EditResolveButtons
edit={edit}
isReloading={isEditReloading}
onResolveStart={onResolveStart}
onResolved={onResolved}
onError={onError}
/>
<DownloadButton
documentId={documentId}
versionId={versionId}
filename={filename}
isReloading={isReloading}
/>
</div>
</div>
{edit.reason && (
<p className="mb-2 text-xs text-gray-500">{edit.reason}</p>
)}
<div className="w-full rounded-md bg-gray-50 border border-gray-200 px-2 py-2">
<div className="text-sm leading-relaxed font-serif">
{edit.inserted_text && (
<span className="text-green-700">
{edit.inserted_text}
</span>
)}
{edit.deleted_text && (
<span className="text-red-600 line-through">
{edit.deleted_text}
</span>
)}
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Accept / Reject controls
// ---------------------------------------------------------------------------
function EditResolveButtons({
edit,
isReloading,
onResolveStart,
onResolved,
onError,
}: {
edit: MikeEditAnnotation;
/**
* True while an accept/reject for any edit on this document is in
* flight (triggered from here, the inline EditCard, the bulk bar, or
* elsewhere). Disables both buttons so the user can't double-submit
* while a resolution is racing to change the status.
*/
isReloading?: boolean;
onResolveStart?: (args: {
editId: string;
documentId: string;
verb: "accept" | "reject";
}) => void;
onResolved?: (args: {
editId: string;
documentId: string;
status: "accepted" | "rejected";
versionId: string | null;
downloadUrl: string | null;
}) => void;
onError?: (args: {
editId: string;
documentId: string;
versionId: string | null;
message: string;
}) => void;
}) {
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<"pending" | "accepted" | "rejected">(
edit.status,
);
// Sync with the prop when this edit is resolved elsewhere (bulk
// accept/reject, inline per-edit card, another open panel for the same
// edit). Skips while our own request is in flight so we don't flicker.
useEffect(() => {
if (busy) return;
setStatus(edit.status);
}, [edit.status, edit.edit_id, busy]);
const resolved = status !== "pending";
const handle = useCallback(
async (verb: "accept" | "reject") => {
if (busy || resolved) return;
setBusy(true);
onResolveStart?.({
editId: edit.edit_id,
documentId: edit.document_id,
verb,
});
// Optimistically mutate the DOM in the open viewer so the
// change reflects immediately. Revert if the backend errors.
let revert: (() => void) | null = null;
try {
revert = applyOptimisticResolution(edit, verb);
} catch (e) {
console.error(
"[DocPanel] optimistic update threw",
e,
);
}
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ??
"http://localhost:3001";
const resp = await fetch(
`${apiBase}/single-documents/${edit.document_id}/edits/${edit.edit_id}/${verb}`,
{
method: "POST",
headers: token
? { Authorization: `Bearer ${token}` }
: undefined,
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = (await resp.json()) as {
ok: boolean;
status?: "accepted" | "rejected";
version_id: string | null;
download_url: string | null;
};
const nextStatus =
data.status ??
(verb === "accept" ? "accepted" : "rejected");
setStatus(nextStatus);
onResolved?.({
editId: edit.edit_id,
documentId: edit.document_id,
status: nextStatus,
versionId: data.version_id,
downloadUrl: data.download_url,
});
} catch (e) {
console.error("[DocPanel] resolve failed", e);
try {
revert?.();
} catch (revertErr) {
console.error(
"[DocPanel] revert threw",
revertErr,
);
}
onError?.({
editId: edit.edit_id,
documentId: edit.document_id,
versionId: edit.version_id ?? null,
message:
verb === "accept"
? "Couldn't save accept — please retry."
: "Couldn't save reject — please retry.",
});
} finally {
setBusy(false);
}
},
[busy, resolved, edit, onResolveStart, onResolved, onError],
);
const inFlight = busy || !!isReloading;
return (
<div className="flex items-center gap-2">
<button
onClick={() => handle("accept")}
disabled={inFlight || resolved}
className="inline-flex items-center gap-1 rounded-lg border border-gray-900 bg-gray-900 px-2 py-1.5 text-xs font-medium text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
>
{status === "accepted" ? "Accepted" : "Accept"}
</button>
<button
onClick={() => handle("reject")}
disabled={inFlight || resolved}
className="inline-flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-2 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
>
{status === "rejected" ? "Rejected" : "Reject"}
</button>
</div>
);
}
// ---------------------------------------------------------------------------
// Download button
// ---------------------------------------------------------------------------
function DownloadButton({
documentId,
versionId,
filename,
isReloading,
}: {
documentId: string;
versionId: string | null;
filename: string;
isReloading?: boolean;
}) {
const [busy, setBusy] = useState(false);
const handleClick = async () => {
if (busy || isReloading) return;
setBusy(true);
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
const resp = await fetch(
`${apiBase}/single-documents/${documentId}/docx${qs}`,
{
headers: token ? { Authorization: `Bearer ${token}` } : {},
},
);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const blob = await resp.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = blobUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
} finally {
setBusy(false);
}
};
const spinning = busy || isReloading;
return (
<button
onClick={handleClick}
disabled={spinning}
className="inline-flex items-center gap-1 rounded-lg border border-gray-200 px-2 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-100 hover:text-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
>
{spinning ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Download className="h-3.5 w-3.5" />
)}
Download
</button>
);
}

View file

@ -0,0 +1,596 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ZoomIn, ZoomOut } from "lucide-react";
import { MikeIcon } from "@/components/chat/mike-icon";
import { useFetchSingleDoc } from "@/app/hooks/useFetchSingleDoc";
import { DocxView } from "./DocxView";
import type { CitationQuote } from "./types";
import {
clearHighlights,
getPdfJs,
highlightQuote,
STANDARD_FONT_DATA_URL,
} from "./highlightQuote";
interface Props {
doc: { document_id: string; version_id?: string | null } | null;
/** Preferred: one or more (page, quote) pairs to highlight. */
quotes?: CitationQuote[];
/** Back-compat single-quote API. Ignored if `quotes` is provided. */
quote?: string;
fallbackPage?: number;
rounded?: boolean;
bordered?: boolean;
}
type QuoteEntry = { page?: number; quote: string };
const SIDE_PADDING = 20;
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 3.0;
const ZOOM_STEP = 0.25;
type RenderedPage = {
page: import("pdfjs-dist").PDFPageProxy;
viewport: import("pdfjs-dist").PageViewport;
wrapper: HTMLDivElement;
canvas: HTMLCanvasElement;
textDivs: HTMLElement[];
};
export function DocView({
doc,
quotes,
quote,
fallbackPage,
rounded = true,
bordered = true,
}: Props) {
const containerRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const pdfDocRef = useRef<import("pdfjs-dist").PDFDocumentProxy | null>(
null,
);
const renderedPagesRef = useRef<RenderedPage[]>([]);
const quoteListRef = useRef<QuoteEntry[]>([]);
const zoomRef = useRef(1.0);
const currentPageRef = useRef(1);
const quoteList: QuoteEntry[] = useMemo(() => {
if (quotes?.length)
return quotes.map((q) => ({ page: q.page, quote: q.quote }));
if (quote) return [{ page: fallbackPage, quote }];
return [];
}, [quotes, quote, fallbackPage]);
// Stable string key so effects can depend on quote-list identity
const quoteKey = quoteList
.map((q) => `${q.page ?? ""}:${q.quote}`)
.join("|");
const [containerWidth, setContainerWidth] = useState(0);
const [zoom, setZoom] = useState(1.0);
const [currentPage, setCurrentPage] = useState(1);
const [numPages, setNumPages] = useState(0);
const { result, loading, error } = useFetchSingleDoc(
doc?.document_id ?? null,
doc?.version_id ?? null,
);
// /display returned DOCX bytes — the active version has no PDF
// rendition, so fall back to docx-preview (still applies citation
// highlighting via the same `quotes` API).
const fallbackToDocx = result?.type === "docx";
// Track container width via ResizeObserver so re-renders fire on resize
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) return;
const ro = new ResizeObserver((entries) => {
setContainerWidth(entries[0]?.contentRect.width ?? 0);
});
ro.observe(el);
return () => ro.disconnect();
}, []);
// Track current page via scroll position
useEffect(() => {
const scrollEl = scrollContainerRef.current;
if (!scrollEl) return;
const handleScroll = () => {
const pages = renderedPagesRef.current;
if (!pages.length) return;
const scrollCenter = scrollEl.scrollTop + scrollEl.clientHeight / 2;
let closest = 0;
let closestDist = Infinity;
pages.forEach((p, i) => {
const pageCenter =
p.wrapper.offsetTop + p.wrapper.clientHeight / 2;
const dist = Math.abs(pageCenter - scrollCenter);
if (dist < closestDist) {
closestDist = dist;
closest = i;
}
});
currentPageRef.current = closest + 1;
setCurrentPage(closest + 1);
};
scrollEl.addEventListener("scroll", handleScroll, { passive: true });
return () => scrollEl.removeEventListener("scroll", handleScroll);
}, []);
// Highlights all entries in `list` across the already-rendered pages.
// Returns the 1-based page number of the first successfully highlighted entry, or null.
const applyHighlights = useCallback(
async (list: QuoteEntry[]): Promise<number | null> => {
// Clear any prior highlights across all pages
for (const p of renderedPagesRef.current)
clearHighlights(p.textDivs);
let firstHitPage: number | null = null;
for (const entry of list) {
let hitPage: number | null = null;
if (entry.page) {
const target = renderedPagesRef.current[entry.page - 1];
if (target) {
const found = await highlightQuote(
target.textDivs,
entry.quote,
);
if (found) hitPage = entry.page;
}
}
// Fall back to scanning all pages for this quote
if (hitPage === null) {
console.warn(
`Quote not found on hinted page, scanning all pages: "${entry.quote.slice(0, 60)}..."`,
);
for (let i = 0; i < renderedPagesRef.current.length; i++) {
const p = renderedPagesRef.current[i];
const found = await highlightQuote(
p.textDivs,
entry.quote,
);
if (found) {
hitPage = i + 1;
break;
}
}
}
if (hitPage !== null && firstHitPage === null) {
firstHitPage = hitPage;
}
}
return firstHitPage;
},
[],
);
const renderPDF = useCallback(
async (
doc: import("pdfjs-dist").PDFDocumentProxy,
list: QuoteEntry[],
scrollToPage?: number,
) => {
if (!containerRef.current) return;
containerRef.current.innerHTML = "";
renderedPagesRef.current = [];
const lib = await getPdfJs();
lib.TextLayer.cleanup();
setNumPages(doc.numPages);
setCurrentPage(1);
currentPageRef.current = 1;
const hasCitation = list.length > 0;
if (hasCitation && scrollContainerRef.current) {
scrollContainerRef.current.style.opacity = "0";
}
const reveal = () => {
if (scrollContainerRef.current)
scrollContainerRef.current.style.opacity = "1";
};
const panelW = containerRef.current.clientWidth;
const firstPage = await doc.getPage(1);
const naturalWidth = firstPage.getViewport({ scale: 1 }).width;
const baseScale = Math.max(
0.5,
(panelW - SIDE_PADDING) / naturalWidth,
);
const scale = baseScale * zoomRef.current;
for (let pageNum = 1; pageNum <= doc.numPages; pageNum++) {
const page = await doc.getPage(pageNum);
const viewport = page.getViewport({ scale });
const wrapper = document.createElement("div");
wrapper.style.position = "relative";
wrapper.style.margin = "0 auto 8px";
wrapper.style.width = "fit-content";
wrapper.className = "shadow-md";
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
canvas.style.display = "block";
wrapper.appendChild(canvas);
containerRef.current?.appendChild(wrapper);
const ctx = canvas.getContext("2d");
if (!ctx) continue;
const task = page.render({ canvasContext: ctx, viewport });
try {
await task.promise;
} catch (e: unknown) {
if (
(e as { name?: string })?.name !==
"RenderingCancelledException"
) {
console.error("PDF render error", e);
}
continue;
}
const textLayerDiv = document.createElement("div");
textLayerDiv.className = "pdf-text-layer";
textLayerDiv.style.position = "absolute";
textLayerDiv.style.left = "0";
textLayerDiv.style.top = "0";
textLayerDiv.style.width = `${viewport.width}px`;
textLayerDiv.style.height = `${viewport.height}px`;
textLayerDiv.style.setProperty("--scale-factor", String(scale));
wrapper.appendChild(textLayerDiv);
const textLayer = new lib.TextLayer({
textContentSource: page.streamTextContent(),
container: textLayerDiv,
viewport,
});
await textLayer.render();
const textDivs = textLayer.textDivs;
renderedPagesRef.current.push({
page,
viewport,
wrapper,
canvas,
textDivs,
});
}
// Apply highlights across all entries, then scroll to the first hit.
let targetPage: number | null = null;
if (list.length) {
targetPage = await applyHighlights(list);
if (targetPage === null) {
// Fallback: scroll to the first entry's page hint, even without a highlight
const hint = list.find((e) => e.page)?.page ?? null;
targetPage = hint;
}
}
if (targetPage && targetPage >= 1) {
scrollToHighlightOnPage(targetPage);
} else if (!hasCitation && scrollToPage && scrollToPage > 1) {
// Restore scroll position after zoom re-render
const pageEntry = renderedPagesRef.current[scrollToPage - 1];
if (pageEntry)
pageEntry.wrapper.scrollIntoView({
behavior: "instant" as ScrollBehavior,
block: "start",
});
}
reveal();
},
[applyHighlights],
);
// Scroll so the first highlight on `pageNum` lands at the vertical center
// of the viewer. We compute the scroll position explicitly on the scroll
// container — calling `scrollIntoView` on a child of the absolutely-
// positioned text layer can scroll just the overlay while leaving the
// canvas untouched, which is why we don't use it here.
function scrollToHighlightOnPage(pageNum: number) {
const pageEntry = renderedPagesRef.current[pageNum - 1];
const scrollEl = scrollContainerRef.current;
if (!pageEntry || !scrollEl) return;
const highlightEl = pageEntry.wrapper.querySelector<HTMLElement>(
".pdf-text-highlight",
);
if (highlightEl) {
const containerRect = scrollEl.getBoundingClientRect();
const highlightRect = highlightEl.getBoundingClientRect();
const offsetWithinContainer = highlightRect.top - containerRect.top;
const targetTop =
scrollEl.scrollTop +
offsetWithinContainer -
scrollEl.clientHeight / 2 +
highlightRect.height / 2;
scrollEl.scrollTo({
top: Math.max(0, targetTop),
behavior: "instant" as ScrollBehavior,
});
} else {
const wrapperRect = pageEntry.wrapper.getBoundingClientRect();
const containerRect = scrollEl.getBoundingClientRect();
const targetTop =
scrollEl.scrollTop + (wrapperRect.top - containerRect.top);
scrollEl.scrollTo({
top: Math.max(0, targetTop),
behavior: "instant" as ScrollBehavior,
});
}
}
const rehighlightQuotes = useCallback(
async (list: QuoteEntry[]) => {
const targetPage = await applyHighlights(list);
const scrollPage =
targetPage ?? list.find((e) => e.page)?.page ?? null;
if (scrollPage && scrollPage >= 1) {
scrollToHighlightOnPage(scrollPage);
}
},
[applyHighlights],
);
// Trackpad pinch-to-zoom (wheel + ctrlKey)
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) return;
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
const handleWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return;
e.preventDefault();
const delta = e.deltaMode === 0 ? e.deltaY / 300 : e.deltaY * 0.1;
const next = Math.min(
ZOOM_MAX,
Math.max(
ZOOM_MIN,
Math.round(zoomRef.current * Math.exp(-delta) * 100) / 100,
),
);
if (next === zoomRef.current) return;
zoomRef.current = next;
setZoom(next);
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}, 150);
};
el.addEventListener("wheel", handleWheel, { passive: false });
return () => {
el.removeEventListener("wheel", handleWheel);
if (debounceTimer) clearTimeout(debounceTimer);
};
}, [renderPDF]);
// Touch pinch-to-zoom
useEffect(() => {
const el = scrollContainerRef.current;
if (!el) return;
let initialDist = 0;
let initialZoom = 1.0;
function getTouchDist(touches: TouchList) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;
return Math.hypot(dx, dy);
}
const handleTouchStart = (e: TouchEvent) => {
if (e.touches.length === 2) {
initialDist = getTouchDist(e.touches);
initialZoom = zoomRef.current;
}
};
const handleTouchMove = (e: TouchEvent) => {
if (e.touches.length !== 2 || initialDist === 0) return;
e.preventDefault();
const next = Math.min(
ZOOM_MAX,
Math.max(
ZOOM_MIN,
Math.round(
initialZoom *
(getTouchDist(e.touches) / initialDist) *
100,
) / 100,
),
);
zoomRef.current = next;
setZoom(next);
};
const handleTouchEnd = (e: TouchEvent) => {
if (e.touches.length < 2 && initialDist > 0) {
initialDist = 0;
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}
};
el.addEventListener("touchstart", handleTouchStart, { passive: true });
el.addEventListener("touchmove", handleTouchMove, { passive: false });
el.addEventListener("touchend", handleTouchEnd, { passive: true });
return () => {
el.removeEventListener("touchstart", handleTouchStart);
el.removeEventListener("touchmove", handleTouchMove);
el.removeEventListener("touchend", handleTouchEnd);
};
}, [renderPDF]);
// Clean up PDF.js static font-measurement canvases on unmount
useEffect(() => {
return () => {
getPdfJs().then((lib) => lib.TextLayer.cleanup());
};
}, []);
// Render PDF when fetch result arrives
useEffect(() => {
if (!result || result.type !== "pdf") return;
pdfDocRef.current = null;
renderedPagesRef.current = [];
quoteListRef.current = quoteList;
zoomRef.current = 1.0;
setZoom(1.0);
setNumPages(0);
const list = quoteList;
let cancelled = false;
(async () => {
const lib = await getPdfJs();
if (cancelled) return;
const pdfDoc = await lib.getDocument({
data: new Uint8Array(result.buffer),
standardFontDataUrl: STANDARD_FONT_DATA_URL,
}).promise;
if (cancelled) return;
pdfDocRef.current = pdfDoc;
await renderPDF(pdfDoc, list);
})();
return () => {
cancelled = true;
};
}, [result, renderPDF]); // eslint-disable-line react-hooks/exhaustive-deps
// Re-render at new scale when container is resized (debounced 150ms)
useEffect(() => {
if (!pdfDocRef.current) return;
const timer = setTimeout(() => {
if (pdfDocRef.current) {
renderPDF(pdfDocRef.current, quoteListRef.current);
}
}, 150);
return () => clearTimeout(timer);
}, [containerWidth, renderPDF]); // eslint-disable-line react-hooks/exhaustive-deps
// Re-highlight when quotes change without full re-render
useEffect(() => {
if (!pdfDocRef.current) return;
quoteListRef.current = quoteList;
if (quoteList.length === 0) return;
rehighlightQuotes(quoteList);
}, [quoteKey, rehighlightQuotes]); // eslint-disable-line react-hooks/exhaustive-deps
function handleZoomIn() {
const next = Math.min(
ZOOM_MAX,
Math.round((zoomRef.current + ZOOM_STEP) * 100) / 100,
);
zoomRef.current = next;
setZoom(next);
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}
function handleZoomOut() {
const next = Math.max(
ZOOM_MIN,
Math.round((zoomRef.current - ZOOM_STEP) * 100) / 100,
);
zoomRef.current = next;
setZoom(next);
if (pdfDocRef.current) {
renderPDF(
pdfDocRef.current,
quoteListRef.current,
currentPageRef.current,
);
}
}
if (fallbackToDocx && doc?.document_id) {
return (
<DocxView
documentId={doc.document_id}
quotes={quotes}
/>
);
}
return (
<div
className={`relative flex flex-col flex-1 overflow-hidden ${bordered ? "border border-gray-200" : ""} ${rounded ? "rounded-xl" : ""}`}
>
<div
ref={scrollContainerRef}
className="flex-1 overflow-auto bg-gray-100 px-3 pt-5 pb-3"
>
{loading && (
<div className="flex h-full items-center justify-center">
<MikeIcon spin mike size={28} />
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-red-500">{error}</p>
</div>
)}
<div ref={containerRef} />
</div>
{numPages > 0 && (
<>
{/* Page counter — bottom left */}
<div className="absolute bottom-4 left-4 pointer-events-none">
<span className="flex items-center px-3 py-1.5 rounded-full text-xs font-medium tabular-nums text-gray-700 bg-white/25 backdrop-blur-md border border-white/30 shadow-md">
{currentPage}/{numPages}
</span>
</div>
{/* Zoom controls — bottom right */}
<div className="absolute bottom-4 right-4 flex items-center gap-px rounded-full bg-white/25 backdrop-blur-md border border-white/30 shadow-md px-1 py-1">
<button
onClick={handleZoomOut}
disabled={zoom <= ZOOM_MIN}
className="flex items-center justify-center w-7 h-7 rounded-full text-gray-600 hover:bg-white/80 disabled:opacity-30 transition-colors"
>
<ZoomOut className="h-3.5 w-3.5" />
</button>
<span className="text-xs font-medium text-gray-600 tabular-nums w-9 text-center select-none">
{Math.round(zoom * 100)}%
</span>
<button
onClick={handleZoomIn}
disabled={zoom >= ZOOM_MAX}
className="flex items-center justify-center w-7 h-7 rounded-full text-gray-600 hover:bg-white/80 disabled:opacity-30 transition-colors"
>
<ZoomIn className="h-3.5 w-3.5" />
</button>
</div>
</>
)}
</div>
);
}

View file

@ -0,0 +1,101 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { Download, Trash2, X } from "lucide-react";
import { DocView } from "./DocView";
import { getDocumentUrl } from "@/app/lib/mikeApi";
import type { MikeDocument } from "./types";
interface Props {
doc: MikeDocument | null;
/** Optional specific version to display. Only honoured for DOCX. */
versionId?: string | null;
/** Optional label suffix for the header (e.g. "V3"). */
versionLabel?: string | null;
onClose: () => void;
onDelete?: (doc: MikeDocument) => void;
}
export function DocViewModal({
doc,
versionId,
versionLabel,
onClose,
onDelete,
}: Props) {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!doc || !mounted) return null;
async function handleDownload() {
if (!doc) return;
const { url, filename } = await getDocumentUrl(doc.id, versionId ?? null);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
return createPortal(
<div
className="fixed inset-0 z-100 flex items-center justify-center bg-black/40"
onClick={onClose}
>
<div
className="relative flex flex-col bg-white rounded-xl shadow-2xl w-[800px] max-w-[90vw] h-[90vh]"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-5 py-3 shrink-0">
<span className="text-base font-medium font-serif text-gray-800 truncate pr-4">
{doc.filename}
{versionLabel && (
<span className="ml-2 text-xs font-normal text-gray-500">
{versionLabel}
</span>
)}
</span>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={handleDownload}
className="flex items-center justify-center w-6 h-6 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors"
>
<Download className="h-4 w-4" />
</button>
{onDelete && (
<button
onClick={() => { onDelete(doc); onClose(); }}
className="flex items-center justify-center w-6 h-6 rounded hover:bg-red-50 text-gray-400 hover:text-red-500 transition-colors"
>
<Trash2 className="h-4 w-4" />
</button>
)}
<button
onClick={onClose}
className="flex items-center justify-center w-6 h-6 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-700 transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
{/* DocView serves PDF when available and falls back to
docx-preview internally if the active version has no
PDF rendition. Passing no versionId tells the backend
to resolve the latest tracked-changes version. */}
<div className="flex flex-col flex-1 overflow-hidden px-3 pb-3">
<DocView
key={versionId ?? "current"}
doc={{
document_id: doc.id,
version_id: versionId ?? null,
}}
/>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,86 @@
"use client";
import { FileText, File, X, AlertCircle, Loader2 } from "lucide-react";
import type { MikeDocument } from "./types";
interface Props {
document: MikeDocument;
onRemove?: (id: string) => void;
onClick?: (doc: MikeDocument) => void;
selected?: boolean;
}
function FileIcon({ fileType }: { fileType: string | null }) {
if (fileType === "pdf") {
return <FileText className="h-4 w-4 text-red-600 shrink-0" />;
}
if (fileType === "docx" || fileType === "doc") {
return <File className="h-4 w-4 text-blue-600 shrink-0" />;
}
return <File className="h-4 w-4 text-gray-500 shrink-0" />;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function DocumentCard({ document, onRemove, onClick, selected }: Props) {
const isError = document.status === "error";
const isProcessing = document.status === "pending" || document.status === "processing";
return (
<div
onClick={() => onClick?.(document)}
className={[
"flex items-center gap-2.5 rounded-lg border px-3 py-2.5 text-sm transition-colors",
onClick ? "cursor-pointer" : "",
selected
? "border-blue-500 bg-blue-50"
: isError
? "border-red-200 bg-red-50"
: "border-gray-200 bg-white hover:border-gray-300",
].join(" ")}
>
{isProcessing ? (
<Loader2 className="h-4 w-4 animate-spin text-gray-400 shrink-0" />
) : isError ? (
<AlertCircle className="h-4 w-4 text-red-500 shrink-0" />
) : (
<FileIcon fileType={document.file_type} />
)}
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-gray-800" title={document.filename}>
{document.filename}
</p>
<p className="text-xs text-gray-400">
{isProcessing
? "Processing…"
: isError
? "Upload failed"
: [
document.size_bytes != null ? formatBytes(document.size_bytes) : null,
document.page_count ? `${document.page_count}p` : null,
]
.filter(Boolean)
.join(" · ")}
</p>
</div>
{onRemove && !isProcessing && (
<button
onClick={(e) => {
e.stopPropagation();
onRemove(document.id);
}}
className="shrink-0 rounded p-0.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
aria-label="Remove document"
>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
);
}

View file

@ -0,0 +1,509 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
import { MikeIcon } from "@/components/chat/mike-icon";
import { useFetchDocxBytes } from "@/app/hooks/useFetchDocxBytes";
import { supabase } from "@/lib/supabase";
import {
clearDocxQuoteHighlights,
highlightDocxQuote,
} from "./highlightDocxQuote";
import type { CitationQuote } from "./types";
interface Props {
documentId: string;
versionId?: string | null;
/**
* Called once the document has been rendered to the DOM. Handy for
* scrolling to a particular tracked change after a re-render.
*/
onReady?: () => void;
/**
* Tracked-change to scroll to + briefly flash after each render. The
* `key` is used to re-trigger scrolling when the same edit is clicked
* twice in a row.
*/
highlightEdit?: {
key: string;
inserted_text?: string;
deleted_text?: string;
/**
* Numeric w:id values of the <w:ins>/<w:del> wrappers in
* document.xml. Preferred over text matching uniquely identifies
* the right DOM element even when multiple edits share identical
* inserted/deleted text. `docx-preview` drops these during parsing,
* so we re-tag each rendered <ins>/<del> with data-w-id after load.
*/
ins_w_id?: string | null;
del_w_id?: string | null;
} | null;
/**
* Forces a byte re-fetch when it changes, even if documentId/versionId
* are stable. Used after accept/reject: the backend overwrites bytes at
* the same storage path (no new version row), so the hook has no other
* signal that the file changed.
*/
refetchKey?: number;
/**
* Citation quotes to highlight in the rendered output. The first match
* is scrolled into view. Page numbers are ignored DOCX has no explicit
* pagination the renderer can match against.
*/
quotes?: CitationQuote[];
/**
* Warning banner copy rendered in the top-left of the viewer. Used
* for non-blocking errors (e.g. "Accept failed — reverted").
*/
warning?: string | null;
/**
* Called when the user dismisses the warning banner.
*/
onWarningDismiss?: () => void;
/**
* Scroll position to restore after the first render used by parents
* that track per-tab scroll and want to re-enter at the same spot.
* Null/undefined means "no override" (preserve the pre-render scroll).
*/
initialScrollTop?: number | null;
/**
* Fires on scroll (throttled by rAF) so the parent can persist the
* current scrollTop against its tab state.
*/
onScrollChange?: (scrollTop: number) => void;
rounded?: boolean;
bordered?: boolean;
}
function findEditElement(
root: HTMLElement,
tag: "ins" | "del",
opts: { w_id?: string | null; text?: string },
): HTMLElement | null {
if (opts.w_id) {
const byId = root.querySelector(
`${tag}[data-w-id="${CSS.escape(opts.w_id)}"]`,
) as HTMLElement | null;
if (byId) return byId;
}
const text = opts.text ?? "";
const normalize = (s: string) => s.replace(/\s+/g, " ").trim();
const target = normalize(text);
if (!target) return null;
const candidates = Array.from(root.querySelectorAll(tag)) as HTMLElement[];
return (
candidates.find((el) => normalize(el.textContent ?? "") === target) ??
candidates.find((el) =>
normalize(el.textContent ?? "").includes(target),
) ??
null
);
}
function scrollToHighlight(
container: HTMLElement,
scrollEl: HTMLElement,
edit: {
inserted_text?: string;
deleted_text?: string;
ins_w_id?: string | null;
del_w_id?: string | null;
},
) {
const insEl = findEditElement(container, "ins", {
w_id: edit.ins_w_id,
text: edit.inserted_text,
});
const delEl = findEditElement(container, "del", {
w_id: edit.del_w_id,
text: edit.deleted_text,
});
const anchor = insEl ?? delEl;
if (!anchor) return;
const scrollRect = scrollEl.getBoundingClientRect();
const targetRect = anchor.getBoundingClientRect();
const offset = targetRect.top - scrollRect.top + scrollEl.scrollTop - 80;
scrollEl.scrollTo({ top: Math.max(0, offset), behavior: "smooth" });
const flashed = [insEl, delEl].filter((el): el is HTMLElement => !!el);
flashed.forEach((el) => el.classList.add("docx-edit-flash"));
window.setTimeout(() => {
flashed.forEach((el) => el.classList.remove("docx-edit-flash"));
}, 2000);
}
/**
* Fetch the ordered list of w:ids for every w:ins/w:del in the current
* version and tag each rendered <ins>/<del> with data-w-id. The backend
* returns ids in document order, and docx-preview emits <ins>/<del>
* in the same order, so we can align by index.
*/
async function tagWIdsOnRenderedDom(
container: HTMLElement,
documentId: string,
versionId: string | null | undefined,
): Promise<void> {
try {
const {
data: { session },
} = await supabase.auth.getSession();
const token = session?.access_token;
const apiBase =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3001";
const qs = versionId
? `?version_id=${encodeURIComponent(versionId)}`
: "";
const resp = await fetch(
`${apiBase}/single-documents/${documentId}/tracked-change-ids${qs}`,
{ headers: token ? { Authorization: `Bearer ${token}` } : {} },
);
if (!resp.ok) {
console.warn(
"[DocxView] tracked-change-ids fetch failed",
resp.status,
);
return;
}
const data = (await resp.json()) as {
ids: { kind: "ins" | "del"; w_id: string }[];
};
const domEls = Array.from(
container.querySelectorAll("ins, del"),
) as HTMLElement[];
const ids = data.ids ?? [];
let tagged = 0;
let mismatched = 0;
for (let i = 0; i < Math.min(domEls.length, ids.length); i++) {
const el = domEls[i];
const info = ids[i];
if (el.tagName.toLowerCase() !== info.kind) {
mismatched++;
continue;
}
el.setAttribute("data-w-id", info.w_id);
tagged++;
}
} catch (e) {
console.warn("[DocxView] tagWIdsOnRenderedDom failed", e);
}
}
/**
* Renders a .docx in the browser using `docx-preview`. Tracked changes
* (`w:ins` / `w:del`) show up automatically with coloured strike/underline
* styling. Scroll position is preserved across re-renders so Accept/Reject
* doesn't jump the user back to the top.
*/
export function DocxView({
documentId,
versionId,
onReady,
highlightEdit,
refetchKey,
quotes,
warning,
onWarningDismiss,
initialScrollTop,
onScrollChange,
rounded = true,
bordered = true,
}: Props) {
const scrollRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const lastScrollTopRef = useRef(0);
const renderKeyRef = useRef(0);
// Ref-stabilize onReady and highlightEdit so the render effect only
// re-fires when `bytes` actually change. Without this, any parent
// re-render (e.g. clicking a new highlight) creates a new onReady
// identity, triggers a full re-render, and snaps scroll back to top.
const onReadyRef = useRef(onReady);
onReadyRef.current = onReady;
const highlightEditRef = useRef(highlightEdit);
highlightEditRef.current = highlightEdit;
const quotesRef = useRef(quotes);
quotesRef.current = quotes;
const initialScrollTopRef = useRef(initialScrollTop ?? null);
initialScrollTopRef.current = initialScrollTop ?? null;
const onScrollChangeRef = useRef(onScrollChange);
onScrollChangeRef.current = onScrollChange;
// Stable key for the quote list so the re-highlight effect re-fires
// only when the actual text/order of quotes changes.
const quoteKey = useMemo(
() => (quotes ?? []).map((q) => q.quote).join("||"),
[quotes],
);
const { bytes, loading, error } = useFetchDocxBytes(
documentId,
versionId,
refetchKey,
);
/**
* Highlight every quote in `list` inside the rendered DOM and scroll
* the first match into view. Returns true if any match was found.
*/
const applyQuoteHighlights = (
containerEl: HTMLElement,
scrollEl: HTMLElement,
list: CitationQuote[] | undefined,
): boolean => {
clearDocxQuoteHighlights(containerEl);
if (!list || list.length === 0) return false;
let firstMatch: HTMLElement | null = null;
for (const q of list) {
const match = highlightDocxQuote(containerEl, q.quote);
if (match && !firstMatch) firstMatch = match;
}
if (!firstMatch) return false;
const scrollRect = scrollEl.getBoundingClientRect();
const targetRect = firstMatch.getBoundingClientRect();
const offset =
targetRect.top -
scrollRect.top +
scrollEl.scrollTop -
scrollEl.clientHeight / 2 +
targetRect.height / 2;
scrollEl.scrollTo({
top: Math.max(0, offset),
behavior: "instant" as ScrollBehavior,
});
return true;
};
/**
* docx-preview renders pages at their natural Word page width (e.g.
* ~816px for US Letter). When the side-panel is narrower than that,
* the page overflows horizontally. Apply CSS `zoom` on each
* section.docx so the document shrinks to fit `zoom` (unlike
* `transform: scale`) also shrinks the layout box, so the scroll
* container's scrollHeight adapts. We zoom each page rather than the
* wrapper because docx-preview injects flex styles on `.docx-wrapper`
* that can interfere with wrapper-level zoom.
*/
const applyDocxScale = () => {
const containerEl = containerRef.current;
const scrollEl = scrollRef.current;
if (!containerEl || !scrollEl) return;
const wrapper = containerEl.querySelector<HTMLElement>(".docx-wrapper");
if (!wrapper) return;
const sections = Array.from(
wrapper.querySelectorAll<HTMLElement>("section.docx"),
);
if (sections.length === 0) return;
// Reset zoom on every page before measuring so offsetWidth reports
// each page's natural width (pages can have different widths — e.g.
// mixed portrait/landscape sections).
sections.forEach((s) => {
s.style.zoom = "1";
});
// Use the scroll container's content box (clientWidth - padding)
// as the available width.
const styles = window.getComputedStyle(scrollEl);
const padX =
(parseFloat(styles.paddingLeft) || 0) +
(parseFloat(styles.paddingRight) || 0);
const available = scrollEl.clientWidth - padX;
if (available <= 0) return;
// Scale each page independently against its own natural width so
// landscape/custom-size pages still fit without distorting the
// page dividers.
sections.forEach((s) => {
const w = s.offsetWidth;
if (!w) return;
const scale = Math.min(1, available / w);
s.style.zoom = String(scale);
});
};
// Observe the scroll container (which tracks the side panel's width)
// and re-scale whenever it resizes. Also observe the docx container so
// we re-scale once docx-preview finishes inserting pages.
useEffect(() => {
const scrollEl = scrollRef.current;
const containerEl = containerRef.current;
if (!scrollEl || !containerEl) return;
let raf = 0;
const schedule = () => {
if (raf) cancelAnimationFrame(raf);
raf = requestAnimationFrame(() => applyDocxScale());
};
const ro = new ResizeObserver(schedule);
ro.observe(scrollEl);
ro.observe(containerEl);
return () => {
if (raf) cancelAnimationFrame(raf);
ro.disconnect();
};
}, []);
useEffect(() => {
let cancelled = false;
if (!bytes || !containerRef.current || !scrollRef.current) return;
const scrollEl = scrollRef.current;
const containerEl = containerRef.current;
console.log("[DocxView] render effect fired", {
documentId,
versionId,
refetchKey,
bytesLen: bytes.byteLength,
});
// Remember scroll position across re-renders so Accept/Reject stays put.
lastScrollTopRef.current = scrollEl.scrollTop;
const thisRender = ++renderKeyRef.current;
(async () => {
try {
const { renderAsync } = await import("docx-preview");
if (cancelled) return;
containerEl.innerHTML = "";
await renderAsync(bytes, containerEl, undefined, {
inWrapper: true,
ignoreWidth: false,
ignoreHeight: false,
renderChanges: true,
experimental: true,
});
if (cancelled) return;
await tagWIdsOnRenderedDom(
containerEl,
documentId,
versionId ?? null,
);
if (cancelled) return;
// Scale to fit before scrolling so offsets are computed
// against the post-zoom layout.
applyDocxScale();
requestAnimationFrame(() => {
if (
!scrollRef.current ||
thisRender !== renderKeyRef.current
)
return;
const pendingHighlight = highlightEditRef.current;
const pendingQuotes = quotesRef.current;
const pendingInitialScroll = initialScrollTopRef.current;
if (pendingHighlight) {
scrollToHighlight(
containerEl,
scrollRef.current,
pendingHighlight,
);
// Highlight quotes too, but don't override the edit scroll
if (pendingQuotes?.length) {
for (const q of pendingQuotes)
highlightDocxQuote(containerEl, q.quote);
}
} else if (
pendingQuotes &&
applyQuoteHighlights(
containerEl,
scrollRef.current,
pendingQuotes,
)
) {
// scrolled inside applyQuoteHighlights
} else if (typeof pendingInitialScroll === "number") {
scrollRef.current.scrollTop = pendingInitialScroll;
} else {
scrollRef.current.scrollTop = lastScrollTopRef.current;
}
onReadyRef.current?.();
});
} catch (e) {
console.error("docx-preview render failed", e);
}
})();
return () => {
cancelled = true;
};
}, [bytes]);
// Re-scroll/highlight if the target edit changes without a re-render
// (e.g. same doc, different edit clicked).
useEffect(() => {
if (!highlightEdit || !containerRef.current || !scrollRef.current)
return;
scrollToHighlight(
containerRef.current,
scrollRef.current,
highlightEdit,
);
}, [highlightEdit?.key]); // eslint-disable-line react-hooks/exhaustive-deps
// Re-apply quote highlights when the quote list changes without a full
// re-render (e.g. clicking a different citation on the same doc).
useEffect(() => {
if (!containerRef.current || !scrollRef.current) return;
applyQuoteHighlights(
containerRef.current,
scrollRef.current,
quotesRef.current,
);
}, [quoteKey]); // eslint-disable-line react-hooks/exhaustive-deps
// Fire onScrollChange (rAF-throttled) so parents can persist scroll
// per-tab. We still maintain lastScrollTopRef locally for same-mount
// re-renders (Accept/Reject preserving scroll within one view).
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
let scheduled = false;
const onScroll = () => {
lastScrollTopRef.current = el.scrollTop;
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
onScrollChangeRef.current?.(el.scrollTop);
});
};
el.addEventListener("scroll", onScroll, { passive: true });
return () => el.removeEventListener("scroll", onScroll);
}, []);
return (
<div
className={`relative flex flex-col flex-1 overflow-hidden ${bordered ? "border border-gray-200" : ""} ${rounded ? "rounded-xl" : ""}`}
>
{warning && (
<div className="absolute top-2 left-2 z-10 flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-800 shadow-sm">
<span>{warning}</span>
<button
type="button"
onClick={() => onWarningDismiss?.()}
className="text-amber-600 hover:text-amber-900"
aria-label="Dismiss warning"
>
×
</button>
</div>
)}
<div
ref={scrollRef}
className="flex-1 overflow-auto bg-gray-100 px-5 pt-5 pb-3 docx-view-scroll"
data-document-id={documentId}
data-version-id={versionId ?? ""}
>
{loading && !bytes && (
<div className="flex h-full items-center justify-center">
<MikeIcon spin mike size={28} />
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-red-500">{error}</p>
</div>
)}
<div ref={containerRef} className="docx-view-container" />
</div>
</div>
);
}

View file

@ -0,0 +1,117 @@
"use client";
import { useState } from "react";
import { X } from "lucide-react";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
interface Props {
emails: string[];
onChange: (emails: string[]) => void;
validate?: (email: string) => Promise<string | null>;
onValidatingChange?: (validating: boolean) => void;
placeholder?: string;
autoFocus?: boolean;
}
export function EmailPillInput({
emails,
onChange,
validate,
onValidatingChange,
placeholder = "Add by email…",
autoFocus = false,
}: Props) {
const [input, setInput] = useState("");
const [validating, setValidating] = useState(false);
const [error, setError] = useState<string | null>(null);
function setValidatingState(v: boolean) {
setValidating(v);
onValidatingChange?.(v);
}
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
addEmail();
} else if (e.key === "Backspace" && !input && emails.length > 0) {
onChange(emails.slice(0, -1));
}
}
async function addEmail() {
const email = input.trim().toLowerCase();
if (!email) return;
if (emails.includes(email)) {
setInput("");
return;
}
if (!EMAIL_RE.test(email)) {
setError("Enter a valid email address.");
return;
}
if (validate) {
setValidatingState(true);
setError(null);
try {
const err = await validate(email);
if (err) {
setError(err);
return;
}
} catch {
setError("Could not verify email. Try again.");
return;
} finally {
setValidatingState(false);
}
}
onChange([...emails, email]);
setInput("");
setError(null);
}
return (
<div>
<div
className={`flex flex-wrap gap-1.5 rounded-lg border bg-gray-50 px-3 py-2 min-h-[40px] transition-colors ${
error
? "border-red-300 focus-within:border-red-400"
: "border-gray-200 focus-within:border-gray-400"
}`}
>
{emails.map((email) => (
<span
key={email}
className="inline-flex items-center gap-1 rounded-full bg-gray-200 px-2.5 py-0.5 text-xs text-gray-700"
>
{email}
<button
type="button"
onClick={() => onChange(emails.filter((e) => e !== email))}
className="text-gray-400 hover:text-gray-700 transition-colors"
>
<X className="h-3 w-3" />
</button>
</span>
))}
<input
type="email"
value={input}
onChange={(e) => {
setInput(e.target.value);
setError(null);
}}
onKeyDown={handleKeyDown}
onBlur={addEmail}
placeholder={emails.length === 0 ? placeholder : ""}
className="flex-1 min-w-[160px] bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus={autoFocus}
/>
</div>
{error && <p className="mt-1.5 text-xs text-red-500">{error}</p>}
{validating && <p className="mt-1.5 text-xs text-gray-400">Checking</p>}
</div>
);
}

View file

@ -0,0 +1,334 @@
"use client";
import { useState } from "react";
import {
Check,
ChevronDown,
ChevronRight,
File,
FileText,
Folder,
Trash2,
} from "lucide-react";
import type { MikeDocument, MikeProject } from "./types";
import { VersionChip } from "./VersionChip";
function formatDate(iso: string | null) {
if (!iso) return null;
return new Date(iso).toLocaleDateString(undefined, {
day: "numeric",
month: "short",
year: "numeric",
});
}
export function DocFileIcon({ fileType }: { fileType: string | null }) {
if (fileType === "pdf")
return <FileText className="h-3.5 w-3.5 text-red-500 shrink-0" />;
return <File className="h-3.5 w-3.5 text-blue-500 shrink-0" />;
}
interface FileDirectoryProps {
standaloneDocs: MikeDocument[];
directoryProjects: MikeProject[];
loading: boolean;
selectedIds: Set<string>;
onChange: (ids: Set<string>) => void;
allowMultiple?: boolean;
forceExpanded?: boolean;
emptyMessage?: string;
heading?: string;
onDelete?: (ids: string[]) => void | Promise<void>;
}
export function FileDirectory({
standaloneDocs,
directoryProjects,
loading,
selectedIds,
onChange,
allowMultiple = true,
forceExpanded = false,
emptyMessage = "No documents yet",
heading = "Documents",
onDelete,
}: FileDirectoryProps) {
const [expandedProjects, setExpandedProjects] = useState<Set<string>>(
new Set(),
);
const [deleting, setDeleting] = useState(false);
const selectedCount = selectedIds.size;
async function handleDelete() {
if (!onDelete || selectedCount === 0 || deleting) return;
const ids = Array.from(selectedIds);
setDeleting(true);
try {
await onDelete(ids);
const next = new Set(selectedIds);
ids.forEach((id) => next.delete(id));
onChange(next);
} finally {
setDeleting(false);
}
}
const allDocs = [
...standaloneDocs,
...directoryProjects.flatMap((p) => p.documents ?? []),
];
const allStandaloneSelected =
standaloneDocs.length > 0 &&
standaloneDocs.every((d) => selectedIds.has(d.id));
function toggle(docId: string) {
if (!allowMultiple) {
onChange(new Set([docId]));
return;
}
const next = new Set(selectedIds);
next.has(docId) ? next.delete(docId) : next.add(docId);
onChange(next);
}
function toggleAll() {
if (allStandaloneSelected) {
const next = new Set(selectedIds);
standaloneDocs.forEach((d) => next.delete(d.id));
onChange(next);
} else {
const next = new Set(selectedIds);
standaloneDocs.forEach((d) => next.add(d.id));
onChange(next);
}
}
function toggleFolder(projectId: string) {
if (forceExpanded) return;
setExpandedProjects((prev) => {
const next = new Set(prev);
next.has(projectId) ? next.delete(projectId) : next.add(projectId);
return next;
});
}
if (loading) {
return (
<div className="rounded-sm border border-gray-100 overflow-hidden">
{/* Documents header skeleton */}
<div className="flex items-center justify-between px-2 py-2">
<div className="h-3 w-20 rounded bg-gray-200 animate-pulse" />
<div className="h-3 w-12 rounded bg-gray-200 animate-pulse" />
</div>
{/* File rows skeleton */}
<div>
{[60, 45, 75, 55, 40].map((w, i) => (
<div
key={i}
className="flex items-center gap-2 px-2 py-2"
>
<div className="h-3.5 w-3.5 rounded border border-gray-200 shrink-0" />
<div className="h-3.5 w-3.5 rounded bg-gray-200 animate-pulse shrink-0" />
<div
className="h-3 rounded bg-gray-200 animate-pulse"
style={{ width: `${w}%` }}
/>
</div>
))}
</div>
</div>
);
}
if (allDocs.length === 0 && directoryProjects.length === 0) {
return (
<p className="text-center text-sm text-gray-400 py-8">
{emptyMessage}
</p>
);
}
return (
<div className="rounded-sm border border-gray-100 overflow-hidden">
<div>
{(standaloneDocs.length > 0 ||
(onDelete && selectedCount > 0)) && (
<div className="flex items-center justify-between px-2 py-2">
<p className="text-xs font-medium text-gray-400">
{heading}
</p>
<div className="flex items-center gap-3">
{onDelete && selectedCount > 0 && (
<button
type="button"
onClick={handleDelete}
disabled={deleting}
className="inline-flex items-center gap-1 text-xs text-red-500 hover:text-red-700 transition-colors disabled:opacity-50"
>
<Trash2 className="h-3 w-3" />
Delete
</button>
)}
{standaloneDocs.length > 0 && (
<button
type="button"
onClick={toggleAll}
className="text-xs text-gray-400 hover:text-gray-600 transition-colors"
>
{allStandaloneSelected
? "Deselect all"
: "Select all"}
</button>
)}
</div>
</div>
)}
{standaloneDocs.map((doc) => {
const selected = selectedIds.has(doc.id);
return (
<button
type="button"
key={doc.id}
onClick={() => toggle(doc.id)}
className={`w-full flex items-center gap-2 px-2 py-2 text-xs transition-colors text-left ${
selected ? "bg-gray-100" : "hover:bg-gray-50"
}`}
>
<span
className={`shrink-0 h-3.5 w-3.5 rounded border flex items-center justify-center ${
selected
? "bg-gray-900 border-gray-900"
: "border-gray-300"
}`}
>
{selected && (
<Check className="h-2.5 w-2.5 text-white" />
)}
</span>
<DocFileIcon fileType={doc.file_type} />
<span
className={`flex-1 truncate ${
selected ? "text-gray-900" : "text-gray-700"
}`}
>
{doc.filename}
</span>
<VersionChip n={doc.latest_version_number} />
{doc.created_at && (
<span className="shrink-0 text-gray-300">
{formatDate(doc.created_at)}
</span>
)}
</button>
);
})}
{standaloneDocs.length > 0 && directoryProjects.length > 0 && (
<div className="border-t border-gray-100 py-2 px-2">
<p className="text-xs font-medium text-gray-400">
Projects
</p>
</div>
)}
{directoryProjects.map((project) => {
const isExpanded =
forceExpanded || expandedProjects.has(project.id);
const docs = project.documents ?? [];
return (
<div key={project.id}>
<button
type="button"
onClick={() => toggleFolder(project.id)}
className="w-full flex items-center gap-2 px-2 py-2 text-xs hover:bg-gray-50 transition-colors text-left"
>
{isExpanded ? (
<ChevronDown className="h-3 w-3 text-gray-400 shrink-0" />
) : (
<ChevronRight className="h-3 w-3 text-gray-400 shrink-0" />
)}
<Folder className="h-3.5 w-3.5 shrink-0 text-gray-400" />
<span className="flex-1 truncate font-medium text-gray-700">
{project.name}
{project.cm_number && (
<span className="ml-1 font-normal text-gray-400">
(#{project.cm_number})
</span>
)}
</span>
<span className="text-xs text-gray-400 shrink-0">
{docs.length}
</span>
</button>
{isExpanded && (
<div>
{docs.length === 0 ? (
<p className="pl-7 py-1 text-xs text-gray-400">
Empty
</p>
) : (
docs.map((doc) => {
const selected = selectedIds.has(
doc.id,
);
return (
<button
type="button"
key={doc.id}
onClick={() =>
toggle(doc.id)
}
className={`w-full flex items-center gap-2 pl-7 pr-2 py-2 text-xs transition-colors text-left ${
selected
? "bg-gray-100"
: "hover:bg-gray-50"
}`}
>
<span
className={`shrink-0 h-3.5 w-3.5 rounded border flex items-center justify-center ${
selected
? "bg-gray-900 border-gray-900"
: "border-gray-300"
}`}
>
{selected && (
<Check className="h-2.5 w-2.5 text-white" />
)}
</span>
<DocFileIcon
fileType={doc.file_type}
/>
<span
className={`flex-1 truncate min-w-0 ${
selected
? "text-gray-900 font-medium"
: "text-gray-700"
}`}
>
{doc.filename}
</span>
<VersionChip
n={doc.latest_version_number}
/>
{doc.created_at && (
<span className="shrink-0 text-gray-300">
{formatDate(
doc.created_at,
)}
</span>
)}
</button>
);
})
)}
</div>
)}
</div>
);
})}
</div>
</div>
);
}

View file

@ -0,0 +1,57 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Search, X } from "lucide-react";
interface Props {
value: string;
onChange: (v: string) => void;
placeholder?: string;
}
export function HeaderSearchBtn({ value, onChange, placeholder = "Search…" }: Props) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
onChange("");
}
}
if (open) document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, [open, onChange]);
return (
<div ref={ref} className="relative flex items-center">
{open ? (
<div className="absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-2 bg-white border border-gray-200 rounded-lg px-3 py-1.5 shadow-sm z-10 w-72">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
autoFocus
type="text"
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
className="flex-1 text-sm text-gray-700 placeholder:text-gray-400 outline-none bg-transparent"
/>
<button
onClick={() => { setOpen(false); onChange(""); }}
className="text-gray-400 hover:text-gray-600"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
) : (
<button
onClick={() => setOpen(true)}
className="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 transition-colors"
>
<Search className="h-4 w-4" />
</button>
)}
</div>
);
}

View file

@ -0,0 +1,93 @@
"use client";
import { createPortal } from "react-dom";
import { Lock, X } from "lucide-react";
interface Props {
open: boolean;
onClose: () => void;
/** Short headline above the body, e.g. "Owner-only action". */
title?: string;
/** Sentence describing what the user tried to do. */
action?: string;
/** Email of the project/resource owner, shown so the user knows who to ask. */
ownerEmail?: string | null;
/** Override the default message entirely. */
message?: string;
}
/**
* Lightweight "you don't have permission" modal shown when a non-owner
* attempts an owner-only action (manage people, rename, delete, ) on a
* shared project. Replaces the silent 404 the backend would otherwise
* return so the user understands why the action didn't go through.
*/
export function OwnerOnlyModal({
open,
onClose,
title = "Owner-only action",
action,
ownerEmail,
message,
}: Props) {
if (!open) return null;
const body =
message ??
(action
? `Only the project owner can ${action}.`
: "Only the project owner can perform this action.");
return createPortal(
<div
className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs"
onClick={onClose}
>
<div
className="w-full max-w-md rounded-2xl bg-white shadow-2xl flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-start justify-between gap-3 px-5 pt-5 pb-2">
<div className="flex items-center gap-2">
<Lock className="h-4 w-4 text-amber-600" />
<h2 className="text-base font-medium text-gray-900">
{title}
</h2>
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Body */}
<div className="px-5 pb-2 pt-1">
<p className="text-sm text-gray-600 leading-relaxed">
{body}
</p>
{ownerEmail && (
<p className="mt-2 text-xs text-gray-400">
Ask{" "}
<span className="text-gray-600">{ownerEmail}</span>{" "}
if you need access.
</p>
)}
</div>
{/* Footer */}
<div className="flex justify-end gap-2 px-5 pb-5 pt-3">
<button
onClick={onClose}
className="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-gray-700"
>
OK
</button>
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,364 @@
"use client";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X, User, UserPlus, Loader2, Plus } from "lucide-react";
import type { ProjectPeople } from "@/app/lib/mikeApi";
/**
* Any resource the modal can manage members for projects today, tabular
* reviews now, anything else with a `shared_with` email list later.
*/
export interface SharedResource {
id: string;
shared_with?: string[] | null;
}
interface Props {
open: boolean;
onClose: () => void;
/** The thing being shared (project, review, …). */
resource: SharedResource | null;
/**
* Resolve the owner + members roster for the given resource. Different
* resource types hit different endpoints (`/projects/:id/people`,
* `/tabular-review/:id/people`, ) so the caller passes the appropriate
* fetcher.
*/
fetchPeople: (id: string) => Promise<ProjectPeople>;
/** Currently signed-in user's email — gets the "You" tag if it matches. */
currentUserEmail?: string | null;
breadcrumb: string[];
/**
* Persist a new shared_with list. Parent should PATCH the resource and
* sync its local state on success. Throw to surface an error inline.
*/
onSharedWithChange?: (sharedWith: string[]) => Promise<void> | void;
}
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
type RosterRow = {
email: string;
display_name: string | null;
role: "owner" | "member";
};
/**
* Roster of every Mike member with access to the project, with controls to
* add/remove members. Mirrors AddDocumentsModal's frame.
*/
export function PeopleModal({
open,
onClose,
resource,
fetchPeople,
currentUserEmail,
breadcrumb,
onSharedWithChange,
}: Props) {
const [newEmail, setNewEmail] = useState("");
const [busy, setBusy] = useState<"add" | "remove" | null>(null);
const [removingEmail, setRemovingEmail] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
// Server-resolved roster: owner email/display_name + members'
// display_names. We keep `resource.shared_with` as the source of truth
// for membership and just merge display_names from this fetch.
const [people, setPeople] = useState<ProjectPeople | null>(null);
const [peopleLoading, setPeopleLoading] = useState(false);
const resourceId = resource?.id ?? null;
const sharedWith: string[] = Array.isArray(resource?.shared_with)
? (resource!.shared_with as string[])
: [];
useEffect(() => {
if (!open) return;
setNewEmail("");
setError(null);
setBusy(null);
setRemovingEmail(null);
}, [open]);
// Re-fetch roster whenever the modal opens or membership changes —
// keyed by the joined shared_with list so add/remove triggers a refresh.
const sharedKey = sharedWith
.map((e) => e.toLowerCase())
.sort()
.join(",");
useEffect(() => {
if (!open || !resourceId) return;
let cancelled = false;
setPeopleLoading(true);
fetchPeople(resourceId)
.then((data) => {
if (cancelled) return;
setPeople(data);
})
.catch(() => {
/* keep stale data; modal still works on emails alone */
})
.finally(() => {
if (!cancelled) setPeopleLoading(false);
});
return () => {
cancelled = true;
};
}, [open, resourceId, sharedKey, fetchPeople]);
if (!open || !resource) return null;
const memberDisplayByEmail = new Map<string, string | null>();
for (const m of people?.members ?? []) {
memberDisplayByEmail.set(m.email.toLowerCase(), m.display_name);
}
const ownerEmail = people?.owner.email ?? null;
const ownerDisplayName = people?.owner.display_name ?? null;
const roster: RosterRow[] = [];
if (ownerEmail) {
roster.push({
email: ownerEmail,
display_name: ownerDisplayName,
role: "owner",
});
}
for (const email of sharedWith) {
const lower = email.toLowerCase();
if (ownerEmail && lower === ownerEmail.toLowerCase()) continue;
roster.push({
email,
display_name: memberDisplayByEmail.get(lower) ?? null,
role: "member",
});
}
const trimmedNewEmail = newEmail.trim().toLowerCase();
const isValidEmail = EMAIL_RE.test(trimmedNewEmail);
const sharedLower = sharedWith.map((e) => e.toLowerCase());
const alreadyShared = sharedLower.includes(trimmedNewEmail);
const isOwnerEmail =
!!ownerEmail && trimmedNewEmail === ownerEmail.toLowerCase();
const canAdd =
isValidEmail && !alreadyShared && !isOwnerEmail && busy === null;
async function handleAdd() {
if (!canAdd || !onSharedWithChange) return;
setBusy("add");
setError(null);
try {
const next = [...sharedWith, trimmedNewEmail];
await onSharedWithChange(next);
setNewEmail("");
} catch (e) {
setError(
e instanceof Error
? e.message
: "Couldn't add the member. Try again.",
);
} finally {
setBusy(null);
}
}
async function handleRemove(email: string) {
if (!onSharedWithChange || busy !== null) return;
setBusy("remove");
setRemovingEmail(email);
setError(null);
try {
const next = sharedWith.filter(
(e) => e.toLowerCase() !== email.toLowerCase(),
);
await onSharedWithChange(next);
} catch (e) {
setError(
e instanceof Error
? e.message
: "Couldn't remove the member. Try again.",
);
} finally {
setBusy(null);
setRemovingEmail(null);
}
}
return createPortal(
<div className="fixed inset-0 z-[200] flex items-center justify-center bg-black/10 backdrop-blur-xs">
<div className="w-full max-w-2xl rounded-2xl bg-white shadow-2xl flex flex-col h-[600px]">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-1.5 text-xs text-gray-400">
{breadcrumb.map((segment, i) => (
<span key={i} className="flex items-center gap-1.5">
{i > 0 && <span></span>}
{segment}
</span>
))}
</div>
<button
onClick={onClose}
className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
>
<X className="h-4 w-4" />
</button>
</div>
{/* Add-member row */}
{onSharedWithChange && (
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2">
<div className="flex flex-1 items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<UserPlus className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="email"
placeholder="Add by email…"
value={newEmail}
onChange={(e) =>
setNewEmail(e.target.value)
}
onKeyDown={(e) => {
if (e.key === "Enter") void handleAdd();
}}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
</div>
<button
onClick={() => void handleAdd()}
disabled={!canAdd}
title="Add member"
className="inline-flex items-center justify-center rounded-lg border border-gray-900 bg-gray-900 p-2 text-white hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
>
{busy === "add" ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Plus className="h-3.5 w-3.5" />
)}
</button>
</div>
{alreadyShared && trimmedNewEmail && (
<p className="mt-1.5 text-xs text-gray-400">
{trimmedNewEmail} already has access.
</p>
)}
{isOwnerEmail && trimmedNewEmail && (
<p className="mt-1.5 text-xs text-gray-400">
{trimmedNewEmail} is the owner.
</p>
)}
{trimmedNewEmail &&
!isValidEmail &&
!alreadyShared &&
!isOwnerEmail && (
<p className="mt-1.5 text-xs text-gray-400">
Enter a valid email.
</p>
)}
{error && (
<p className="mt-1.5 text-xs text-red-500">
{error}
</p>
)}
</div>
)}
{/* Section heading */}
<div className="px-4 pt-3 pb-1 flex items-center gap-2">
<h3 className="text-xs font-medium text-gray-500">
People with Access
</h3>
{peopleLoading && (
<Loader2 className="h-3 w-3 animate-spin text-gray-400" />
)}
</div>
{/* Member list */}
<div className="flex-1 overflow-y-auto px-4 pb-2">
{roster.length === 0 ? (
<div className="flex h-full items-center justify-center text-sm text-gray-400">
No one has access yet.
</div>
) : (
<ul className="divide-y divide-gray-100 [&>li:nth-child(2)]:border-t-0">
{roster.map((entry) => {
const isYou =
!!currentUserEmail &&
entry.email.toLowerCase() ===
currentUserEmail.toLowerCase();
const isRemoving =
busy === "remove" &&
removingEmail === entry.email;
const primary =
entry.display_name?.trim() || entry.email;
const showSecondary =
!!entry.display_name?.trim() &&
primary !== entry.email;
return (
<li
key={`${entry.role}-${entry.email}`}
className="flex items-center gap-3 py-3"
>
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gray-900 text-white">
<User className="h-3 w-3" />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm text-gray-800">
{primary}
{isYou && (
<span className="ml-1.5 text-xs text-gray-400">
(You)
</span>
)}
{entry.role === "owner" && (
<span className="ml-1.5 text-[10px] text-gray-400">
Owner
</span>
)}
</p>
{showSecondary && (
<p className="truncate text-xs text-gray-400">
{entry.email}
</p>
)}
</div>
{entry.role === "member" &&
onSharedWithChange && (
<button
onClick={() =>
void handleRemove(
entry.email,
)
}
disabled={busy !== null}
title="Remove access"
className="self-center inline-flex items-center gap-1 rounded px-2 py-1 text-xs text-gray-500 hover:bg-red-50 hover:text-red-600 disabled:opacity-50"
>
{isRemoving && (
<Loader2 className="h-3 w-3 animate-spin" />
)}
Remove
</button>
)}
</li>
);
})}
</ul>
)}
</div>
{/* Footer */}
<div className="px-5 py-3 text-[11px] text-gray-400">
{roster.length === 0
? "No one has access yet."
: `${roster.length} ${
roster.length === 1 ? "person" : "people"
} with access.`}
</div>
</div>
</div>,
document.body,
);
}

View file

@ -0,0 +1,74 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { ChevronDown } from "lucide-react";
export function PreResponseWrapper({
children,
stepCount,
shouldMinimize,
isStreaming,
compact = false,
}: {
children: React.ReactNode;
stepCount: number;
shouldMinimize: boolean;
isStreaming: boolean;
/** Tighter typography + child gap for narrow side panels (e.g. TR chat). */
compact?: boolean;
}) {
const [userToggled, setUserToggled] = useState(false);
const [isOpen, setIsOpen] = useState(!shouldMinimize);
// Once content has streamed in (shouldMinimize=true even once), stay
// minimized even if a later render briefly evaluates shouldMinimize=false.
// Without this latch, the wrapper visibly pops open when isStreaming
// flips off at the end of the response.
const hasMinimizedRef = useRef(shouldMinimize);
useEffect(() => {
if (shouldMinimize) hasMinimizedRef.current = true;
if (userToggled) return;
setIsOpen(!shouldMinimize && !hasMinimizedRef.current);
}, [shouldMinimize, userToggled]);
const stepWord = `step${stepCount === 1 ? "" : "s"}`;
const label = isStreaming
? "Working"
: `Completed in ${stepCount} ${stepWord}`;
const buttonTextClass = compact ? "text-xs" : "text-sm";
const childrenGapClass = compact ? "gap-2.5" : "gap-4";
return (
<div className="border border-gray-200 rounded-lg px-3 py-2">
<button
type="button"
onClick={() => {
setUserToggled(true);
setIsOpen((v) => !v);
}}
className={`w-full flex items-center justify-between font-serif text-gray-500 hover:text-gray-700 transition-colors ${buttonTextClass}`}
>
<span className="flex items-baseline min-w-0">
<span className="truncate">{label}</span>
{isStreaming && (
<span className="inline-flex ml-1 shrink-0 items-baseline">
<span className="w-0.5 h-0.5 rounded-full bg-gray-400 mr-0.5 animate-[bounce_1.4s_infinite_0s]" />
<span className="w-0.5 h-0.5 rounded-full bg-gray-400 mr-0.5 animate-[bounce_1.4s_infinite_0.2s]" />
<span className="w-0.5 h-0.5 rounded-full bg-gray-400 animate-[bounce_1.4s_infinite_0.4s]" />
</span>
)}
</span>
<ChevronDown
size={12}
className={`shrink-0 ml-2 transition-transform duration-200 ${isOpen ? "" : "-rotate-90"}`}
/>
</button>
{isOpen && (
<div className={`mt-3 flex flex-col ${childrenGapClass}`}>
{children}
</div>
)}
</div>
);
}

View file

@ -0,0 +1,91 @@
"use client";
import { useState } from "react";
import { Folder, Search, X } from "lucide-react";
import type { MikeProject } from "./types";
interface Props {
projects: MikeProject[];
loading: boolean;
selectedId: string | null;
onSelect: (id: string | null) => void;
}
export function ProjectPicker({ projects, loading, selectedId, onSelect }: Props) {
const [search, setSearch] = useState("");
const q = search.toLowerCase().trim();
const filtered = q ? projects.filter((p) => p.name.toLowerCase().includes(q)) : projects;
return (
<>
<div className="px-4 pt-1 pb-2">
<div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2">
<Search className="h-3.5 w-3.5 text-gray-400 shrink-0" />
<input
type="text"
placeholder="Search projects…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="flex-1 bg-transparent text-sm text-gray-700 placeholder:text-gray-400 outline-none"
autoFocus
/>
{search && (
<button onClick={() => setSearch("")} className="text-gray-400 hover:text-gray-600">
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto px-4 pb-2">
{loading ? (
<div className="rounded-sm border border-gray-100 overflow-hidden">
<div className="flex items-center px-2 py-2">
<div className="h-3 w-14 rounded bg-gray-200 animate-pulse" />
</div>
{[65, 45, 80, 55, 70].map((w, i) => (
<div key={i} className="flex items-center gap-2 px-2 py-2">
<div className="h-3.5 w-3.5 rounded-full border border-gray-200 shrink-0" />
<div className="h-3.5 w-3.5 rounded bg-gray-200 animate-pulse shrink-0" />
<div className="h-3 rounded bg-gray-200 animate-pulse" style={{ width: `${w}%` }} />
</div>
))}
</div>
) : filtered.length === 0 ? (
<p className="text-center text-sm text-gray-400 py-8">
{q ? "No matches found" : "No projects yet"}
</p>
) : (
<div className="rounded-sm border border-gray-100 overflow-hidden">
<div className="flex items-center justify-between px-2 py-2">
<p className="text-xs font-medium text-gray-400">Projects</p>
</div>
<div className="space-y-px">
{filtered.map((project) => {
const isSelected = selectedId === project.id;
return (
<button
key={project.id}
onClick={() => onSelect(isSelected ? null : project.id)}
className={`w-full flex items-center gap-2 px-2 py-2 text-xs transition-colors text-left ${isSelected ? "bg-gray-100" : "hover:bg-gray-50"}`}
>
<span className={`shrink-0 h-3.5 w-3.5 rounded-full border flex items-center justify-center ${isSelected ? "bg-gray-900 border-gray-900" : "border-gray-300"}`}>
{isSelected && <span className="h-1.5 w-1.5 rounded-full bg-white" />}
</span>
<Folder className="h-3.5 w-3.5 shrink-0 text-gray-400" />
<span className={`flex-1 truncate ${isSelected ? "text-gray-900 font-medium" : "text-gray-700"}`}>
{project.name}
{project.cm_number && (
<span className="ml-1 font-normal text-gray-400">(#{project.cm_number})</span>
)}
</span>
<span className="shrink-0 text-gray-400">{project.document_count ?? 0}</span>
</button>
);
})}
</div>
</div>
)}
</div>
</>
);
}

Some files were not shown because too many files have changed in this diff Show more